在R中:从字段中删除逗号,并使修改后的字段仍然是数据框的一部分 [英] In R: remove commas from a field AND have the modified field remain part of the dataframe
问题描述
我需要从R数据框中的字段中删除逗号。从技术上讲,我已经做到了这一点,但是结果似乎既不是向量也不是矩阵,而且我无法以可用格式将其返回到数据帧中。因此,有一种方法可以删除字段中的逗号,并使该字段保留在数据帧中。
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.
这里是需要删除逗号的字段示例,其结果由我的代码生成:
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)
推荐答案
gsub()
将返回字符向量,而不是数字向量(这听起来像您想要的)。 as.numeric()
会将字符向量转换回数字向量:
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:
> 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
结果仍然是 data.frame
:
> class(df)
[1] "data.frame"
这篇关于在R中:从字段中删除逗号,并使修改后的字段仍然是数据框的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!