Home > Software design >  R: Trying to replace values in one column with values in another column based on some conditions
R: Trying to replace values in one column with values in another column based on some conditions

Time:09-19

So I have a a dataframe,df: df = data.frame(c("",1,1),c(1,"",1),c(1,1,""))

I want to loop through the dataframe and replace the values in the first and second column, if they are empty, with the value in the third column if it has a value in it:

n = nrow(df)
    for(i in 1:n)df[i,] <-{
    if(df[i,1] == "" & df[i,2] == "" & df[i,3] != ""){
    df[i,1] = df[i,3]
    df[i,2] = df[i,3]
    }
}

However, I get the following error:

error in x[[jj]][iseq] <- vjj : replacement has length zero. I've been trying for quite some time, but can't figure our what I'm doing wrong. Any help would be much appreciated.

CodePudding user response:

Since R is vectorized you do not need a loop:

df <- structure(list(A = c("1", "1", "1"), B = c("1", "1", "1"), C = c("1", 
"1", "")), row.names = c(NA, -3L), class = "data.frame")

Note your data are character vectors as in your example data. The answer will differ slightly if they are numeric.

df$A[df$A==""] <- df$C[df$A==""]
df$B[df$B==""] <- df$C[df$B==""]
df
#   A B C
# 1 1 1 1
# 2 1 1 1
# 3 1 1  
  • Related