有时分析需要用户检查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"