gpt4 book ai didi

r - 数据框的所有列中包含数字的子集行

转载 作者:行者123 更新时间:2023-12-02 09:18:13 25 4
gpt4 key购买 nike

我想通过保留所有列中包含数字的行来获取数据框的子集

>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 -结果值。
  • 接下来数一下 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)

对于更新的示例数据,问题在于具有非数字值的列是因子而不是字符。您必须按如下方式调整上述代码:

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返回因子水平的数量。
  • 我用过testdata[-1]因为我认为您不想在检查数值时包含第一列。

关于r - 数据框的所有列中包含数字的子集行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44972786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com