问题
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
回答1:
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.
来源:https://stackoverflow.com/questions/48209897/data-frame-with-commas-as-decimal-separator