数字值包括逗号 - 如何制作这些数字? [重复]

时间:2023-01-13 15:55:06

This question already has an answer here:

这个问题在这里已有答案:

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.

我有一整列数字,包括成千上万的逗号分隔符。当我尝试用它们创建一个数字列时,超过999的任何东西都变成了NA。

I used cbind:

我用过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?

有没有办法去除逗号或告诉as.numeric如何处理它们?

2 个解决方案

#1


11  

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

如果您尝试将新列var2添加到df,则可以使用以下命令

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

#2


2  

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

使用as.numeric(gsub(“,”,“”,df $ var1))。

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

你想使用gsub作为sub只会替换第一个逗号。

#1


11  

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

如果您尝试将新列var2添加到df,则可以使用以下命令

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

#2


2  

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

使用as.numeric(gsub(“,”,“”,df $ var1))。

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

你想使用gsub作为sub只会替换第一个逗号。