我希望通过保留所有列中包含数字的行来获取我的数据框的子集
>small
0 16h 24h 48h
ID1 1 0 0
ID2 453 254 21 12
ID3 true 3 2 1
ID4 65 23 12 12
Run Code Online (Sandbox Code Playgroud)
将会
>small_numeric
0 16h 24h 48h
ID2 453 254 21 12
ID4 65 23 12 1
Run Code Online (Sandbox Code Playgroud)
我试过了
sapply(small, is.numeric)
Run Code Online (Sandbox Code Playgroud)
但得到了这个
0 16h 24h 48h
FALSE FALSE FALSE FALSE
Run Code Online (Sandbox Code Playgroud)
使用:
small[!rowSums(is.na(sapply(small, as.numeric))),]
Run Code Online (Sandbox Code Playgroud)
得到:
Run Code Online (Sandbox Code Playgroud)0 16h 24h 48h ID2 453 254 21 12 ID4 65 23 12 12
这是做什么的:
sapply(small, as.numeric)你强迫所有列数字.因此,非数字值将转换为NA-values.NA有-值rowSums(is.na(sapply(small, as.numeric))),让你回一个数字载体,[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)
Run Code Online (Sandbox Code Playgroud)
对于更新的示例数据,问题是具有非数字值的列是因子而不是字符.在那里你必须调整上面的代码如下:
testdata[!rowSums(is.na(sapply(testdata[-1], function(x) as.numeric(as.character(x))))),]
Run Code Online (Sandbox Code Playgroud)
这使:
Run Code Online (Sandbox Code Playgroud)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返回因子级别的数字.testdata[-1]因为我认为你不想在检查数字值中包含第一列.