user3070455
user3070455

Reputation: 21

Replace blank values in one row with text

I need to replace blank values in the second row of my data set with text ("dummy" in this example), without overwriting blank values in the remainder of the dataset.

For example, if you start with a dataframe

df <- data.frame(x1=c("X","Y",""),x2=c("Z","",""),x3=c("A","B","C"),x4=c("E","",""))

I would like a line of code to convert it to:

df <- data.frame(x1=c("X","Y",""),x2=c("Z","dummy",""),x3=c("A","B","C"),x4=c("E","dummy",""))

I have tried:

df[df == ""] <- "dummy"

however this replaces all blank values, instead of only those in the second row. I have also tried combining this with df[2,] in various ways with no success.

Any suggestions greatly appreciated.

Upvotes: 2

Views: 1811

Answers (1)

user1317221_G
user1317221_G

Reputation: 15441

Perhaps its easier to make things not factors in the first place:

df <- data.frame(x1=c("X","Y",""),x2=c("Z","",""), 
                 x3=c("A","B","C"),x4=c("E","",""), 
                 stringsAsFactors = FALSE)

df[df == ""] <- "YO"
#df
#  x1 x2 x3 x4
#1  X  Z  A  E
#2  Y YO  B YO
#3 YO YO  C YO

If you want everything to be a factor once your done you could try:

df <- data.frame(x1=c("X","Y",""), x2=c("Z","",""), 
                 x3=c("A","B","C"), x4=c("E","",""))

new <- as.data.frame( sapply(df, function(x){ w <- as.character(x)
                                              w[w == ""] <- "DUMMY"
                                              return(w) } ))

str(new)
#'data.frame':   3 obs. of  4 variables:
# $ x1: Factor w/ 3 levels "DUMMY","X","Y": 2 3 1
# $ x2: Factor w/ 2 levels "DUMMY","Z": 2 1 1
# $ x3: Factor w/ 3 levels "A","B","C": 1 2 3
# $ x4: Factor w/ 2 levels "DUMMY","E": 2 1 1

EDIT as per your comment:

# you still need to set things to characters first
df <- data.frame(x1=c("X","Y",""),x2=c("Z","",""), 
                 x3=c("A","B","C"),x4=c("E","",""), 
                 stringsAsFactors = FALSE)

# then
df[2,][df[2,] == ""] <- "DUMMY"

df
#  x1    x2 x3    x4
#1  X     Z  A     E
#2  Y DUMMY  B DUMMY
#3           C   

Upvotes: 1

Related Questions