【问题标题】:using gsub to remove strings but not numeric使用 gsub 删除字符串但不是数字
【发布时间】:2018-10-01 01:20:25
【问题描述】:

我有一个看起来像这样的数据框

 id   col1
  1     4
  2     -
  3     +
  4     _
  5     N
  6     text-abc
  7     50

我的目标是拥有一个如下所示的数据框:

 id   col1
  1     4
  2     0
  3     0
  4     0
  5     0
  6     0
  7     50

我想保持数值不变,并将“-”、“+”、“_”、“N”和“text-abc”转换为零。也就是说,我只希望数值出现在此列中,将文本和其他字符串转换为零并保持数值不变。这是一个很长的列(即数千行),可能包含其他不必要的文本。

为了修复,我尝试使用以下方法手动完成:

  df$col1 <- gsub("text-abc", 0, df$col1)
  df$col1 <- gsub("+", 0, df$col1)
  df$col1 <- gsub("-", 0, df$col1)
  df$col1 <- gsub("_", 0, df$col1)
  df$col1 <- gsub("N", 0, df$col1)

但是,如前所述,这对于大量数据集是不切实际的。因此,我尝试了以下方法:

  df$col1 <- gsub("[^[[:alnum:]]", 0, df$col1)

但它只是将“text-abc”更改为“text0abc”,而不是将整个内容变为 0。理想情况下,我希望该列仅包含数值。

任何帮助将不胜感激。非常感谢您抽出宝贵时间!

【问题讨论】:

  • 愚蠢的我。非常感谢罗纳克!

标签: r gsub


【解决方案1】:

我们可以使用as.numeric 将非数字列更改为NAs,然后将这些NA 转换为0,而不是逐个转换列。

df$col1 <- as.numeric(df$col1)

#Use this if `col1` is factor
#df$col1 <- as.numeric(as.character(df$col1))

df$col1[is.na(df$col1)] <- 0

df

#  id col1
#1  1    4
#2  2    0
#3  3    0
#4  4    0
#5  5    0
#6  6    0
#7  7   50

【讨论】:

    【解决方案2】:

    我们可以使用正则表达式来做到这一点

    df$col1[!grepl('^[0-9]+$', df$col1)] <- 0
    df$col1 <- as.numeric(df$col1)
    df
    #  id col1
    #1  1    4
    #2  2    0
    #3  3    0
    #4  4    0
    #5  5    0
    #6  6    0
    #7  7   50
    

    数据

    df <- structure(list(id = 1:7, col1 = c("4", "-", "+", "_", "N", "text-abc", 
       "50")), class = "data.frame", row.names = c(NA, -7L))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-01
      • 1970-01-01
      • 2012-07-31
      • 1970-01-01
      • 2019-06-16
      • 2019-03-14
      • 2021-01-28
      • 1970-01-01
      相关资源
      最近更新 更多