【发布时间】:2021-10-07 08:40:34
【问题描述】:
我有一个这样的 df
df <- data.frame (id = c(123,123,456), w1= c("abc","fgh","kit"), w2 = c("eat","drink","ty"))
id w1 w2
1 123 abc eat
2 123 fgh drink
3 456 kit ty
和一个向量
vec <- c('value1', 'value2').
当有精确的对应关系时,我想将这些值添加到 df 中。我想获得的最终df是这样的:
id w1 w2 new_col
1 123 abc eat value1
2 123 abc eat value2
3 123 fgh drink no correspondance
4 456 kit ty no correspondance
我试过这段代码
for (i in 1:length(df$id)) { ## for iterating each row
if (df$w2[i] == 'eat') {
df$new_col[i] <- vec ### how to? Here I need to replace both 'value1' and 'value2' copying the row
}
}
有人可以给我一些建议吗?提前致谢!
【问题讨论】:
-
when there is a precise correspondance需要详细说明吗?