如何使用tidyverse筛选出两列取值不同的数据行?
基于tidyverse的解决方案
可以使用tidyverse中的dplyr包实现需求,核心通过filter()函数筛选出两列取值不同的行,具体代码如下:
library(tidyverse) # 模拟数据 df <- data.frame(Col1=c("cat","dog","man","man","cat","cat"), Col2=c("cat","dog","dog","dog","dog","cat")) # 筛选两列取值不同的行 filtered_df <- df %>% filter(Col1 != Col2) # 输出结果 filtered_df
运行代码后得到的结果与期望一致:
Col1 Col2 1 man dog 2 man dog 3 cat dog
代码说明
- 加载
tidyverse包,它包含dplyr等数据处理核心工具; - 用管道符
%>%将数据框传递给filter()函数; - 条件
Col1 != Col2会保留所有两列取值不相等的行,自动过滤掉取值相同的行。
内容的提问来源于stack exchange,提问作者Ginko-Mitten
相关产品推荐
相关产品推荐

