R中是否有一种方法可以根据另一个df在df上计算新列?

是否可以在R中执行类似的操作(假设df1和df2的行数相同?

if (df1$var1 = 8) df2$var1 = 1.
if (df1$var2 = 9) df2$var2 = 1.
评论
吟唱怕寂寞
吟唱怕寂寞

Here is one simple option in base R, where we replicate the values 8, 9 to make the lengths same and compare with the subset of columns of 'df1', resulting in a logical matrix. Subset the 'df2' and assign those columns to 1

nm1 <- c('var1', 'var2')
df2[nm1][df1[nm1] == c(8, 9)[col(df1[nm1])]] <- 1
df2
#  var1 var2 var3
#1    5    1    1
#2    3    1    2
#3    1    3    3
#4    1    4    4
#5    4    2    5

或者这可以分两步完成

df2$var1[df1$var1 == 8] <- 1
df2$var2[df1$var2 == 9] <- 1

Or using Map

df2[nm1] <- Map(function(x, y, z) replace(x, y == z, 1),
            df2[nm1], df1[nm1], c(8, 9))

The if/else loop can be also done, but it is not vectorized i.e. it expects input to be of length 1. If we do a loop, then it can be done (but would be inefficient in R)

vals <- c(8, 9)
for(i in seq_len(nrow(df1))) {
     for(j in seq_along(nm1)) {
        if(df1[[nm1[j]]][i] == vals[j]) df2[[nm1[j]]][i] <- 1
      }
   }

数据

df1 <- data.frame(var1 = c(1, 3, 8, 5, 2), var2 = c(9, 3, 1, 8, 4),
          var3 = 1:5)
df2 <- data.frame(var1 = c(5, 3, 2, 1,  4), var2 = c(3, 1, 3,  4, 2),
        var3 = 1:5)
点赞
评论
d小调
d小调

可以使用Base R ifelse语句完成一个简单的两行代码

df1 <- data.frame(var1 = c(1:10), var2 = c(1:10))
df2 <- data.frame(var1 = c(1:10), var2 = c(1:10))

df2$var1  <- ifelse(df1$var1 == 8, 1,df2$var1)
df2$var2  <- ifelse(df1$var2 == 9, 1,df2$var2)
点赞
评论