使用 gsub 删除字符串但不删除数字

using gsub to remove strings but not numeric

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

 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。理想情况下,我希望该列仅包含数值。

如有任何帮助,我们将不胜感激。非常感谢您的宝贵时间!

我们可以使用 as.numeric 将非数字列更改为 NA,然后将那些 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

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

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))