[英]Select rows of a data.frame that contain only numbers in a certain column
[英]Subset rows of a data frame that contain numbers in all of the column
我想通过保留所有列中都有数字的行来获取数据框的子集,因此
>small
0 16h 24h 48h
ID1 1 0 0
ID2 453 254 21 12
ID3 true 3 2 1
ID4 65 23 12 12
将会
>small_numeric
0 16h 24h 48h
ID2 453 254 21 12
ID4 65 23 12 1
我试过了
sapply(small, is.numeric)
但是得到这个
0 16h 24h 48h
FALSE FALSE FALSE FALSE
使用:
small[!rowSums(is.na(sapply(small, as.numeric))),]
得到:
0 16h 24h 48h ID2 453 254 21 12 ID4 65 23 12 12
这是做什么的:
sapply(small, as.numeric)
您可以将所有列强制为数字。 结果将非数字值转换为NA
值。 rowSums(is.na(sapply(small, as.numeric)))
计算NA
的数量,这将为您返回一个数值矢量[1] 1 0 1 0
,其中包含非数值的数量按行。 !
为您提供行的逻辑矢量,其中所有列均具有数值。 使用的数据:
small <- read.table(text=" 0 16h 24h 48h
ID1 1 0 0
ID2 453 254 21 12
ID3 true 3 2 1
ID4 65 23 12 12", header=TRUE, stringsAsFactors = FALSE, fill = TRUE, check.names = FALSE)
对于更新后的示例数据,问题在于具有非数字值的列是因子而不是字符。 您必须在其中修改上面的代码,如下所示:
testdata[!rowSums(is.na(sapply(testdata[-1], function(x) as.numeric(as.character(x))))),]
这使:
0 16h 24h 48h NA ID2 ID2 46 23 23 48 ID3 ID3 44 10 14 22 ID4 ID4 17 11 4 24 ID5 ID5 13 5 3 18 ID7 ID7 4387 4216 2992 3744
额外说明:
as.numeric(as.character(x))
。 如果您不这样做,则as.numeric
with会返回因子水平的数字。 testdata[-1]
因为我想您不想在检查数值时包括第一列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.