如何检查变量是否在R数据帧中包含大于1的数字?
R数据帧中的变量称为数据帧的列。有时我们为特定列设置了阈值,我们需要检查该列中的所有值是否大于或小于阈值。为此,我们可以使用ifelse函数,如以下示例所示。
例1
考虑以下数据帧-
set.seed(24) x<−rnorm(20,1,0.25) df1<−data.frame(x) df1输出结果
x 1 0.8635298 2 1.1341463 3 1.1049058 4 0.8540932 5 1.2118650 6 1.0665055 7 1.1111463 8 0.8833762 9 0.7879075 10 1.0005780 11 0.6707730 12 1.1495673 13 0.8094464 14 0.6427274 15 1.0830611 16 0.8827348 17 0.9162533 18 1.3840630 19 1.1524986 20 1.1290839
检查x列中的值是否大于1-
ifelse(df1$x> 1,"Yes","No")
例2
y<−rpois(20,1) df2<−data.frame(y) df2输出结果
y 1 1 2 0 3 0 4 0 5 1 6 0 7 3 8 3 9 2 10 1 11 0 12 0 13 0 14 4 15 1 16 0 17 1 18 2 19 0 20 1
检查y列中的值是否大于1-
示例
ifelse(df2$y>1,"Yes","No")输出结果
[1] "No" "No" "No" "No" "No" "No" "Yes" "Yes" "Yes" "No" "No" "No" [13] "No" "Yes" "No" "No" "No" "Yes" "No" "No"
范例3
z<−sample(0:5,20,replace=TRUE) df3<−data.frame(z) df3输出结果
z 1 4 2 2 3 0 4 1 5 1 6 0 7 3 8 4 9 2 10 3 11 1 12 1 13 1 14 0 15 5 16 3 17 4 18 0 19 0 20 2
检查z列中的值是否大于1-
示例
ifelse(df3$z>1,"Yes","No")输出结果
[1] "Yes" "Yes" "No" "No" "No" "No" "Yes" "Yes" "Yes" "Yes" "No" "No" [13] "No" "No" "Yes" "Yes" "Yes" "No" "No" "Yes"