【问题标题】:Select rows of a data.frame that contain only numbers in a certain column选择仅包含特定列中数字的 data.frame 行
【发布时间】:2014-04-12 16:17:16
【问题描述】:

如何仅选择列 b 中包含数字的行。

a <- c(1,5,3,1,-8,6,-1)
b <- c(4,-2,1,0,"c",2,"DX")

df <- data.frame(a,b)
df

#    a  b
# 1  1  4
# 2  5 -2
# 3  3  1
# 4  1  0
# 5 -8  c
# 6  6  2
# 7 -1  DX

输出应如下所示:

#    a  b
# 1  1  4
# 2  5 -2
# 3  3  1
# 4  1  0
# 5  6  2

【问题讨论】:

    标签: r dataframe subset numeric


    【解决方案1】:

    这应该更快(它不使用正则表达式)

    df[!is.na(as.numeric(df$b)), ]
    

    【讨论】:

    • 你是对的,你的解决方案更快,但它会产生警告:as.numeric("a") 并且当列包含factor as.numeric(factor("a")) 时不起作用(如本例中,因为stringsAsFactors=FALSE不见了)。
    【解决方案2】:

    你可以使用grep:

    df[grep("[[:digit:]]", df$b), ]
    #  a  b
    #1 1  4
    #2 5 -2
    #3 3  1
    #4 1  0
    #6 6  2
    

    【讨论】:

      猜你喜欢
      • 2012-03-10
      • 1970-01-01
      • 2018-06-28
      • 2021-12-13
      • 2015-08-16
      • 1970-01-01
      • 2015-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多