0 votes
1 view
in R Programming by (5.3k points)

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

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

    A   B

1      12

2  xyz    

3  jkl 100

Expected result:

    A   B

1  NA   12

2  xyz  NA  

3  jkl  100

1 Answer

0 votes
by (25.3k points)

To replace all empty values in a data frame with NA, you can do the following:

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

df

    A   B

1      12

2 xyz    

3 jkl 100

Empty values to NA:

df[df==""]<-NA

> df

     A    B

1 <NA>   12

2  xyz <NA>

3  jkl  100

To replace values in a factor column:

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

To convert a factor column to a character to replace values:

df$A <- as.character(df$A)

df[df=="xyz"] <- "abc"

df[df==""]<-NA

df$A <- as.factor(df$A)

str(df)

'data.frame': 3 obs. of  2 variables:

 $ A: Factor w/ 2 levels "abc","jkl": NA 1 2

 $ B: Factor w/ 3 levels "","100","12": 3 NA 2

df

     A    B

1 <NA>   12

2  abc <NA>

3  jkl  100

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...