我想通过保留所有列中都有数字的行来获取数据框的子集,因此
>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))),]
给出:
这是做什么的:
sapply(small, as.numeric)
可以将所有列都强制为数字。结果将非数字值转换为NA
-values。 NA
计数rowSums(is.na(sapply(small, as.numeric)))
-values的数量,这会给您返回数字 vector [1] 1 0 1 0
,并按行显示非数字值的数量。 !
取反可为您提供行的逻辑 vector ,其中所有列均具有数值。 使用的数据:
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))))),]
这使:
额外说明:
as.numeric(as.character(x))
。如果您不这样做,则as.numeric
与一起返回因子水平的数字。 testdata[-1]
是因为我认为您不想在检查数值时包括第一列。 关于r - 数据框的子集行,在所有列中都包含数字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44972786/