Replace all specific values ​​in a data frame

Having a data frame, how do I go about replacing all the specific values ​​for all rows and columns. Say, for example, I want to replace all empty records with NA (without entering positions):

 df <- data.frame(list(A=c("", "xyz", "jkl"), B=c(12, "", 100))) AB 1 12 2 xyz 3 jkl 100 

Expected Result:

  AB 1 NA 12 2 xyz NA 3 jkl 100 
+42
replace r dataframe
Oct 21 '13 at 19:41
source share
4 answers

Like this:

 > df[df==""]<-NA > df AB 1 <NA> 12 2 xyz <NA> 3 jkl 100 
+65
Oct 21 '13 at 19:44
source share

Since PikkuKatja and glallen have asked for a more general solution, and I still can not comment, I will write an answer. You can combine statements as in:

 > df[df=="" | df==12] <- NA > df AB 1 <NA> <NA> 2 xyz <NA> 3 jkl 100 

For factors, the zxzak code already gives factors:

 > df <- data.frame(list(A=c("","xyz","jkl"), B=c(12,"",100))) > str(df) 'data.frame': 3 obs. of 2 variables: $ A: Factor w/ 3 levels "","jkl","xyz": 1 3 2 $ B: Factor w/ 3 levels "","100","12": 3 1 2 

If in trouble I suggest temporarily abandoning the factors.

 df[] <- lapply(df, as.character) 
+18
Dec 08 '15 at 1:12
source share

We can use data.table to get it quickly. First create df without factors

 df <- data.frame(list(A=c("","xyz","jkl"), B=c(12,"",100)), stringsAsFactors=F) 

Now you can use

 setDT(df) for (jj in 1:ncol(df)) set(df, i = which(df[[jj]]==""), j = jj, v = NA) 

and you can convert it back to data.frame file

 setDF(df) 

If you want to use data.frame and hold on to factors, it’s more complicated, you need to work with

 levels(df$value)[levels(df$value)==""] <- NA 

where value is the name of each column. You need to insert it into the loop.

+1
Nov 28 '16 at 19:28
source share

If you want to replace multiple values ​​in a data frame, you may need to loop through all the columns.

Suppose you want to replace "" and 100 :

 na_codes <- c(100, "") for (i in seq_along(df)) { df[[i]][df[[i]] %in% na_codes] <- NA } 
-one
Apr 07 '17 at 2:11 on
source share



All Articles