The numbers include a comma - how can I make these numbers?

I have a whole column of numbers that includes comma separators on thousands. When I try to create a numeric column from them, anything over 999 becomes NA.

I used cbind:

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

and ended 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 break commas or tell as.numeric how to handle them?

+6
source share
2 answers

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

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

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

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

+2
source

All Articles