问题描述
我将数据帧作为csv文件,数字用逗号分隔作为小数点分隔符,我设法使用read.csv2
导入并在R中读取了它.但是现在数字被视为characters
.
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
.
我想要做的是用点替换逗号并使用numeric
值.
What I want to do is to replace commas with dots and have a numeric
value.
我的df看起来像这样:
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
推荐答案
当您读取.csv文件时,可以根据文件类型指定sep
和dec
参数:
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.
这篇关于逗号为小数点分隔符的数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!