string 在 R 中:从字段中删除逗号并使修改后的字段保留为数据帧的一部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28129554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In R: remove commas from a field AND have the modified field remain part of the dataframe
提问by mark stevenson
I need to remove commas from a field in an R dataframe. Technically I have managed to do this, but the result seems to be neither a vector nor a matrix, and I cannot get it back into the dataframe in a usable format. So is there a way to remove the commas from a field, AND have that field remain part of the dataframe.
我需要从 R 数据框中的字段中删除逗号。从技术上讲,我设法做到了这一点,但结果似乎既不是向量也不是矩阵,而且我无法将其以可用格式返回到数据帧中。那么有没有办法从字段中删除逗号,并使该字段保留为数据帧的一部分。
Here is a sample of the field that needs commas removed, and the results generated by my code:
这是需要删除逗号的字段示例,以及我的代码生成的结果:
> print(x['TOT_EMP'])
TOT_EMP
1 132,588,810
2 6,542,950
3 2,278,260
4 248,760
> y
[1] "c(\"132588810\" \"6542950\" \"2278260\" \"248760\...)"
The desired result is a numeric field:
所需的结果是一个数字字段:
TOT_EMP
1 132588810
2 6542950
3 2278260
4 248760
x<-read.csv("/home/mark/Desktop/national_M2013_dl.csv",header=TRUE,colClasses="character")
y=(gsub(",","",x['TOT_EMP']))
print(y)
回答by Richard Border
gsub()
will return a character vector, not a numeric vector (which is it sounds like you want). as.numeric()
will convert the character vector back into a numeric vector:
gsub()
将返回一个字符向量,而不是一个数字向量(这听起来像你想要的)。as.numeric()
将字符向量转换回数值向量:
> df <- data.frame(numbers = c("123,456,789", "1,234,567", "1,234", "1"))
> df
numbers
1 123,456,789
2 1,234,567
3 1,234
4 1
> df$numbers <- as.numeric(gsub(",","",df$numbers))
> df
numbers
1 123456789
2 1234567
3 1234
4 1
The result is still a data.frame
:
结果仍然是data.frame
:
> class(df)
[1] "data.frame"