从字符串和数字中删除逗号

时间:2018-02-05 03:06:57

标签: r comma string-substitution

使用R,如果它是一个数字,如何删除逗号,如果是一个字母,请用空格替换逗号?:

  Company        | Sales   |
  -------------------------
  go, go, llc    |2,550.40 |
  tires & more   |  500    |
  l-m tech       |1,000.67 |

示例数据:

data = matrix(c('go, go,llc', 'tires & more', 'l-m technology',
 formatC(2550.40, format="f", big.mark=",", digits=2), 500, 
 formatC(1000.67, format="f", big.mark=",", digits=2)), 
 nrow=3, 
 ncol=2)

预期产出:

  Company      | Sales  |
  -----------------------
  go go llc    |2550.40 |
  tires & more |  500   |
  l-m tech     |1000.67 |

我尝试了什么:

data <- sapply(data, function(x){
           if (grepl("[[:punct:]]",x)){
              if (grepl("[[:digit:]]",x)){
                 x <- gsub(",","",x)
              }
              else{
                 x <- gsub(","," ",x)
              }
           }
        })

print(nrow(data)) # returns NULL

1 个答案:

答案 0 :(得分:5)

您可以使用嵌套的gsub

轻松完成此操作
gsub(",", "", gsub("([a-zA-Z]),", "\\1 ", input)

内部模式匹配一​​个字母后跟一个逗号,并将其替换为字母。外部gsub用空格替换任何剩余的逗号。

将其应用于矩阵:

    apply(data, 2, function(x) gsub(",", "", gsub("([a-zA-Z]),", "\\1 ", x)))
    #      [,1]             [,2]     
    # [1,] "go  go llc"     "2550.40"
    # [2,] "tires & more"   "500"    
    # [3,] "l-m technology" "1000.67"
相关问题