只需使用table() 函数。
我。所有数字列
mtcars 数据集中的第 3 行。检查第 3 行中有多少列值大于 10。
第 3 行值 > 10
table(mtcars[3,] > 10)
# FALSE TRUE
# 7 4
在 11 个数字列中,其中 4 个列的值大于 10,7 个列的值小于 10。
要知道第 3 行中哪些值大于 10
mtcars[3,][which(mtcars[3,] >10)]
# mpg disp hp qsec
# Datsun 710 22.8 108 93 18.61
检查第 3 行中有多少列值大于 10 且小于 20
第 3 行值 > 10 &
table(mtcars[3,] > 10 & mtcars[3,] < 20)
# FALSE TRUE
# 10 1
要知道第 3 行中大于 10 且小于 20 的值有哪些
mtcars[3,][which(mtcars[3,] >10 & mtcars[3,] < 20)]
# qsec
# Datsun 710 18.61
二。数据中的任何因素列
如果数据中有任何因素或字符列或非数字,table( ) 将抛出警告消息。但它会给你计数我们想要的数字列。
例如,在 iris 数据集中,我们将第 5 列作为Species 因子列。
鸢尾花数据集一瞥
head(iris, n = 4)
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1 5.1 3.5 1.4 0.2 setosa
# 2 4.9 3.0 1.4 0.2 setosa
# 3 4.7 3.2 1.3 0.2 setosa
# 4 4.6 3.1 1.5 0.2 setosa
虹膜第 3 行值 > 4
如下所示,只计算了 4 列,其中只有一列的值大于 4。由于 iris 数据集中的第 5 列是一个因素,它会抛出警告消息,我们无法检查 Species水平是否大于 4。
table(iris[3,] > 4)
# FALSE TRUE
# 3 1
# Warning message:
# In Ops.factor(left, right) : ‘>’ not meaningful for factors
iris数据集第3行哪一列值大于4
iris[3,][which(iris[3,] > 4)]
# Sepal.Length
# 3 4.7
# Warning message:
# In Ops.factor(left, right) : ‘>’ not meaningful for factors