逗号为小数点分隔符的数据框 [英] data frame with commas as decimal separator

查看:139
本文介绍了逗号为小数点分隔符的数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将数据帧作为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文件时,可以根据文件类型指定sepdec参数:

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.

这篇关于逗号为小数点分隔符的数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆