Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

numeric

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?

like image 542
Amanda Avatar asked Nov 27 '12 22:11

Amanda


People also ask

How do you split numbers with commas?

In English, we use commas to separate numbers greater than 999. We use a comma every third digit from the right.

How do I separate data from a comma in Excel?

Type the formula =CONCATENATE(TRANSPOSE(A1:A7)&",") in a blank cell adjacent to the list's initial data, for example, cell C1. (The column A1:A7 will be converted to a comma-serrated list, and the separator "," will be used to separate the list.)

How do you convert a number into a comma with a number?

To convert a comma-separated number to an integer:Use the str. replace() method to remove the commas from the string. Use the int() class to convert the string to an integer.


1 Answers

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)))
like image 179
Ricardo Saporta Avatar answered Sep 29 '22 11:09

Ricardo Saporta