替换R中的逗号和点 [英] Replacing commas and dots in R

查看:89
本文介绍了替换R中的逗号和点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一整列数字,其中包含千位分隔符和逗号而不是点作为暗淡的分隔符.当我尝试用它们创建一个数字列时,我丢失了所有数据.

I have a whole column of numbers that include dot separators at the thousands and comma instead of dot as an dismal separator. When I try to create a numeric column out of them, I lose all data.

var1 <- c("50,0", "72,0", "960,0", "1.920,0", "50,0", "50,0", "960,0")
df <- cbind(var1, var2 = as.numeric(gsub(".", "", as.character(var1))))

最后是:

 var1      var2
[1,] "50,0"    NA  
[2,] "72,0"    NA  
[3,] "960,0"   NA  
[4,] "1.920,0" NA  
[5,] "50,0"    NA  
[6,] "50,0"    NA  
[7,] "960,0"   NA 

我做错了什么?

推荐答案

您需要对正则表达式中的 "." 进行转义,并且需要将逗号替换为 "." 在您可以转换为数字之前.

You need to escape the "." in your regular expression, and you need to replace the commas with a "." before you can convert to numeric.

> as.numeric(gsub(",", ".", gsub("\\.", "", var1)))
[1]   50   72  960 1920   50   50  960

这篇关于替换R中的逗号和点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆