In R: remove commas from a field AND have the modified field remain part of the dataframe

怎甘沉沦 提交于 2019-11-30 07:34:06

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

The result is still a data.frame:

> class(df)
[1] "data.frame"
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!