如何在 R 数据框的俩列中比较两个完全匹配的值?
有时分析要求用户检查 R 数据框两列中的值是否完全相同,如果我们怀疑两列中的比较值,则这有助于分析非常大的数据框。这可以通过 ifelse 函数轻松完成。
示例
考虑以下数据框−
x1<-sample(c("Spring","Winter","Autumn","Summer"),20,replace=TRUE) y1<-sample(c("Spring","Winter","Autumn","Summer"),20,replace=TRUE) df1<-data.frame(x1,y1) df1
输出
x1 y1 1 Spring Autumn 2 Winter Winter 3 Summer Summer 4 Autumn Autumn 5 Summer Autumn 6 Autumn Autumn 7 Summer Winter 8 Spring Spring 9 Summer Spring 10 Winter Winter 11 Autumn Summer 12 Autumn Summer 13 Spring Winter 14 Spring Winter 15 Spring Spring 16 Summer Autumn 17 Spring Winter 18 Winter Summer 19 Summer Spring 20 Spring Autumn
确定 x1 和 y1 中的每个值是否相同−
示例
ifelse(df1$x1==df1$y1,"Yes","No")
输出
[1] "No" "Yes" "Yes" "Yes" "No" "Yes" "No" "Yes" "No" "Yes" "No" "No" [13] "No" "No" "Yes" "No" "No" "No" "No" "No"
示例
x2<-sample(c("Male","Female"),20,replace=TRUE) y2<-sample(c("Male","Female"),20,replace=TRUE) df2<-data.frame(x2,y2) df2
输出
x2 y2 1 Male Female 2 Female Male 3 Female Female 4 Male Male 5 Female Female 6 Male Female 7 Female Female 8 Male Male 9 Male Female 10 Female Female 11 Female Female 12 Male Female 13 Male Male 14 Female Male 15 Male Male 16 Female Female 17 Male Male 18 Female Female 19 Male Female 20 Male Female
确定 x2 和 y2 中的每个值是否相同−
示例
> ifelse(df2$x2==df2$y2,"Yes","No")
输出
[1] "No" "No" "Yes" "Yes" "Yes" "No" "Yes" "Yes" "No" "Yes" "Yes" "No" [13] "Yes" "No" "Yes" "Yes" "Yes" "Yes" "No" "No"
广告