【发布时间】:2014-07-22 14:54:26
【问题描述】:
我有一系列具有相同列标题和不同行数的 csv 文件(每年一个)。最初我正在阅读它们并像这样合并它们;
setwd <- ("N:/Ring data by cruise/Shetland")
LengthHeight2013 <- read.csv("N:/Ring data by cruise/Shetland/R_0113A_S2013_WD.csv",sep=",",header=TRUE)
LengthHeight2012 <- read.csv("N:/Ring data by cruise/Shetland/R_0212A_S2012_WD.csv",sep=",",header=TRUE)
LengthHeight2011 <- read.csv("N:/Ring data by cruise/Shetland/R_0211A_S2011_WOD.csv",sep=",",header=TRUE)
LengthHeight2010 <- read.csv("N:/Ring data by cruise/Shetland/R_0310A_S2010_WOD.csv",sep=",",header=TRUE)
LengthHeight2009 <- read.csv("N:/Ring data by cruise/Shetland/R_0309A_S2009_WOD.csv",sep=",",header=TRUE)
LengthHeight <- merge(LengthHeight2013,LengthHeight2012,all=TRUE)
LengthHeight <- merge(LengthHeight,LengthHeight2011,all=TRUE)
LengthHeight <- merge(LengthHeight,LengthHeight2010,all=TRUE)
LengthHeight <- merge(LengthHeight,LengthHeight2009,all=TRUE)
我想知道是否有更短/更整洁的方法来执行此操作,同时考虑到每次运行脚本时我可能想查看不同的年份范围。
我还发现了 Tony Cookson 的这段代码,看起来它可以满足我的需求,但是它为我生成的数据帧只有正确的标题,但没有数据行。
multmerge = function(mypath){
filenames=list.files(path=mypath, full.names=TRUE)
datalist = lapply(filenames, function(x){read.csv(file=x,header=T)})
Reduce(function(x,y) {merge(x,y)}, datalist)
mymergeddata = multmerge("C://R//mergeme")
【问题讨论】:
-
你真的需要合并吗? do.call(rbind, datalist) 呢?
-
sep=",",header=TRUE是read.csv()的默认值。
标签: r csv data-binding merge dataframe