假设有一个数据框 df 和一个列表 list:
df <- data.frame(ID = c(1:6), Value = c(5, 8, 3, 2, 6, 7))
list <- c(1, 3, 9)
想要将 list 中存在于 df 中的数值和不存在于 df 中的数值分别放入两个向量中。
首先,我们可以使用 %in% 运算符来检查 df 中是否存在 list 中的数值:
exist <- df$ID[df$ID %in% list]
not_exist <- setdiff(list, df$ID)
其中,exist 表示在 df 中存在的数值,not_exist 表示在 list 中存在但不在 df 中的数值。
代码示例输出:
> exist
[1] 1 3
> not_exist
[1] 9
上一篇:比较数据框的每一行中的两个列。