gpt4 book ai didi

读取并绑定(bind)多个 csv 文件

转载 作者:行者123 更新时间:2023-12-04 11:40:05 25 4
gpt4 key购买 nike

我有一系列具有相同列标题和不同行数的 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")

最佳答案

您可以像这样整洁地尝试它:

   files <- list.files('the path of you files', 
pattern = ".csv$", recursive = TRUE, full.names = TRUE)

myMergedData <- read_csv(files) %>% bind_rows()

关于读取并绑定(bind)多个 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23995384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com