data frame with commas as decimal separator

。_饼干妹妹 提交于 2020-08-06 05:04:48

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!