1

I have data frame as csv file, numbers are separated with commas as decimal separators, I managed to import and read it in R using read.csv2. But now numbers are seen as characters.

What I want to do is to replace commas with dots and have a numeric value.

My df looks like this:

var1 <- c("50,0", "72,0", "960,0", "1.920,0", "50,0", "50,0", "960,0")
var2 <- c("40,0", "742,0", "9460,0", "1.920,0", "50,0", "50,0", "960,0")
var3<- c("40,0", "72,0", "90,0", "1,30", "50,0", "50,0", "960,0")
df <- data.frame(cbind(var1, var2, var3))

However in this case numbers are seen as factors and not as characters

TheMaster
  • 45,448
  • 6
  • 62
  • 85
Al14
  • 1,734
  • 6
  • 32
  • 55
  • 1
    `as.numeric(sub(',', '.', your_var, fixed = TRUE))` – Sotos Jan 11 '18 at 14:55
  • I think this is a duplicate, but: `as.numeric(gsub(",",".",var))`? A reproducible example would be very useful. – Ben Bolker Jan 11 '18 at 14:55
  • @ Sotos, can my variable be a subset of my data frame or do Ì need to replace for each column – Al14 Jan 11 '18 at 14:57
  • 2
    you can apply, for example `df[c(1, 4, 5)] <- lapply(df[c(1, 4, 5)], function(i) as.numeric(sub(',', '.', i, fixed = TRUE)))` will apply the `sub` to columns 1, 4 and 5. For any further help please post a reproducible example – Sotos Jan 11 '18 at 14:59
  • @Sotos worked pretty well! – Al14 Jan 11 '18 at 16:33
  • Also [as.numeric with comma decimal separators?](/q/15236440/15497888) if wanting to post process rather than directly from CSV – Henry Ecker Jun 07 '22 at 19:15

1 Answers1

4

When you read in the .csv file, you can specify the sep and dec parameters based on the file-type:

# assuming file uses ; for separating columns and , for decimal point
# Using base functions 
read.csv(filename, sep = ";", dec = ",")

# Using data.table
library(data.table)
fread(filename, sep = ";", dec = ",")

You should attempt to address the source of the issue first, regular expressions and other work-arounds should be used only if that fails to get the desired result.

Gautam
  • 2,597
  • 1
  • 28
  • 51