lundi 11 janvier 2021

Alternate for FOR loop in RStudio

I have 2 dataframes below,

col1_x <- c(0123,123,234,4567,77789,4578,45588,669887,7887,5547)
col2_x <- c('X1','X8','X2','X55','C12','B11','Z1','SS12','D9','F55')
a    <- c(10,9,8,7,6,5,4,3,2,1)
DF1 <- cbind(col1_x,col2_x,a)
DF1 <- as.data.frame(DF1, stringsAsFactors = F)

col1_y <- c(012,123,56,55,78,5547)
col2_y <- c('X1','X8','S2','ER4','KL1','F55')
b    <- c(111,222,NA,NA,555,666)
DF2 <- cbind(col1_y,col2_y,b)
DF2 <- as.data.frame(DF2, stringsAsFactors = F)

Below are the codes which I am trying to execute.

# code1
for (i in 1:nrow(DF2)) { 
  if(is.na(DF2$b[i])) {} else {
    DF1 <-mutate(DF1, 
                 a = ifelse(col1_x == DF2$col1_y[i] & col2_x == DF2$col2_y[i],
                            DF2$b[i],a) )
  }
}

# code2
if(is.na(DF2$b)) {} else {
  DF1$a <- ifelse(DF1$col1_x == DF2$col1_y & DF1$col2_x == DF2$col2_y, DF2$b, DF1$a)
}

I am getting warnings when I run code2,

Warning messages:
1: In if (is.na(Y$b)) { :
  the condition has length > 1 and only the first element will be used
2: In X$col1 == Y$col1 :
  longer object length is not a multiple of shorter object length
3: In X$col2 == Y$col2 :
  longer object length is not a multiple of shorter object length

Kindly help me how can I fix this without using FOR loop as it takes a lot of time for iterations.

Note: code1 satisfies my requirement

Aucun commentaire:

Enregistrer un commentaire