我使用了回答我之前问题的用户的 R 代码(请参阅此处: Split values of a column in a data frame by specific tag and add them as extra row)来实现以下目标:
df <- data.frame(var1 = c("A", "B", "C", "D", "E"),
var2 = c("test", "5 | 6", "X & Y", "M | N | O", "none"))
> df
var1 var2
1 A test
2 B 5 | 6
3 C X & Y
4 D M | N | O
5 E none
t1 <- c("", "|")[df$var1 %in% df$var1[grep("\\|", df$var2)]+1]
t2 <- c("", "&")[df$var1 %in% df$var1[grep("&", df$var2)]+1]
t1[which(t2 == "&")] <- "&"
df$var3 <- t1
> df
var1 var2 var3
1 A test
2 B 5 | 6 |
3 C X & Y &
4 D M | N | O |
5 E none
我只是想知道是否有更好的方法,因为我真的想改进我的 R 编码方式。对我来说,这并不是一项简单的任务,但我愿意学习 :-)