Number values include comma — how do I make these numeric? [duplicate]

余生颓废 提交于 2019-12-01 00:15:34

问题


I have a whole column of numbers that include comma separators at the thousands. When I try to create a numeric column out of them, anything over 999 becomes NA.

I used cbind:

df <- cbind(df, var2 = as.numeric(as.character(df$var1)))

and wound up with:

        var1  var2
1   2,518.50    NA
2   2,518.50    NA
3   5,018.50    NA
4   4,018.50    NA
5  10,018.50    NA
6     318.50 318.5
7   2,518.50    NA
8   3,518.50    NA
9   7,518.50    NA
10  1,018.50    NA

Is there a way to strip the commas or tell as.numeric how to handle them?


回答1:


If you are trying to add a new column var2 to df, you can use the following

  df$var2 <- as.numeric(gsub(",", "", as.character(df$var1)))



回答2:


Use as.numeric(gsub(",", "", df$var1)).

You want to use gsub as sub will only replace the first comma.



来源:https://stackoverflow.com/questions/13594223/number-values-include-comma-how-do-i-make-these-numeric

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