的R - 对包含数千数字列读取CSV分离器
问题描述:
我想读的CSV文件完全相同的格式如下:的R - 对包含数千数字列读取CSV分离器
Date,x,y
"2015/08/01","71,131","20,390"
"2015/08/02","81,599","23,273"
"2015/08/03","79,435","21,654"
"2015/08/04","80,733","20,924"
的分隔符是逗号,但每个值也被封入因为报价用作千位分隔符的逗号。我尝试了{readr}中的read.csv
,read_csv
和{data.table}中的fread
,我能做的最好的是读取所有值为字符串,然后使用as.numeric
和gsub
的组合将它们转换为数字。
我也发现这个:Most elegant way to load csv with point as thousands separator in R这是非常有用的,但我的数据有很多列(不是所有的数字),我宁可不指定列类型。
任何想法或我应该开始gsub ing?在有趣的一面,Excel读取文件就好:)
答
你应该可以通过read.csv
读取数据。下面的例子
#write data
write('Date,x,y\n"2015/08/01","71,131","20,390"\n"2015/08/02","81,599","23,273"\n"2015/08/03","79,435","21,654"\n"2015/08/04","80,733","20,924"',"test.csv")
#use "text" rather than "file" in read.csv
#perform regex substitution before using read.csv
#the outer gsub with '(?<=\\d),(\\d{3})(?!\\d)' performs the thousands separator substitution
#the inner gsub replaces all \" with '
read.csv(text=gsub('(?<=\\d),(\\d{3})(?!\\d)',
'\\1',
gsub("\\\"",
"'",
paste0(readLines("test.csv"),collapse="\n")),
perl=TRUE),
header=TRUE,
quote="'",
stringsAsFactors=FALSE)
结果
# Date x y
#1 2015/08/01 71131 20390
#2 2015/08/02 81599 23273
#3 2015/08/03 79435 21654
#4 2015/08/04 80733 20924
答
随着data.table
包,你可以做到这一点,如下所示:
1:创建COLUMNNAMES的载体进行改造。在这种情况下,Date
必须被排除。
cols <- setdiff(names(dt),"Date")
2:应用转换功能,其余列:
library(data.table)
dt[, (cols) := lapply(.SD, function(x) as.numeric(gsub(",", "", x))), .SDcols = cols]
这导致:
> dt
Date x y
1: 2015/08/01 71131 20390
2: 2015/08/02 81599 23273
3: 2015/08/03 79435 21654
4: 2015/08/04 80733 20924
使用的数据:
dt <- fread('Date,x,y
"2015/08/01","71,131","20,390"
"2015/08/02","81,599","23,273"
"2015/08/03","79,435","21,654"
"2015/08/04","80,733","20,924"')
答
最好的解决方案是在导出之前从Excel工作表中删除所有这些格式。
做不到这一点,只需使用lapply
每一列转换:
df[c("x", "y")] <- lapply(df[c("x", "y")], function(x) as.numeric(gsub(",", "", x)))
你知道哪些列已进行改造? – Jaap
@Jaap我想,但至少它会正确读取它。刚才看到他们已经试过了。 nvm –
David - 我不确定那会完成什么。无论如何,我得到这个错误:'期望的sep(''),但新行,EOF(或其他非打印字符)结束字段4时检测类型(第一):输入新的日期:(mm-dd-yy)' – BogdanC