gpt4 book ai didi

r - 在 R : remove commas from a field AND have the modified field remain part of the dataframe

转载 作者:行者123 更新时间:2023-12-04 05:49:11 25 4
gpt4 key购买 nike

我需要从 R 数据框中的字段中删除逗号。从技术上讲,我设法做到了这一点,但结果似乎既不是向量也不是矩阵,而且我无法将其以可用格式返回到数据帧中。那么有没有办法从字段中删除逗号,并使该字段保留为数据帧的一部分。

这是需要删除逗号的字段示例,以及我的代码生成的结果:

> 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\...)"

所需的结果是一个数字字段:
       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() 会将字符向量转换回数值向量:

> 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 - 在 R : remove commas from a field AND have the modified field remain part of the dataframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28129554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com