这是我的问题。
我有8*3张数据。8.在2005年至2012年期间,我每年都有三个与生态、花卉分布和地点相对应的数据框架。csv文件的名称基于相同的类型(flowerdistrib_2005.csv,ecology_2005.csv,.)
我想为每年建立一个数据框架,其中包含所有列的“花卉分发”文件和部分“生态”和“地点”文件。
由于这个脚本,我导入了所有这些代码:
listflower = list.files(path = "C:/Directory/.../", pattern = "flowerdistrib_")
for (i in listflower) {
filepath1 <- file.path("C:/Directory/.../",paste(i))
assign(i,read.csv(filepath1, sep=";", dec=",", header=TRUE))
}生态和地理位置也一样。
然后,我想为每年做一个vlookup,其中包含一些特定列的三个文件。每年,csv文件的生态、位置和花卉分布都有一个名为"idp“的列。
我知道怎么做一年。我使用以下脚本:
2005年示例,提取文件location_2005.csv中存在的名为“location_2005.csv”的列:
flowerdistrib_2005[, "xl93"] = location_2005$"xl93"[match(flowerdistrib_2005$"idp", location_2005$"idp")]但我不知道这些年该怎么做一次。我正在考虑使用一个for循环,并结合lapply函数,但我没有很好地处理它,因为我是一个R初学者。
我会感谢所有的帮助。
非常感谢。
PS:我不是英语本地人,对可能的误解和可能的语言错误表示歉意。
发布于 2014-03-20 18:28:14
这是对您的read.csv过程的重新组织,但是您可以使用下面的脚本来完成您需要做的事情。它将创建一个列表data,其中包含指定年份的所有数据。如果输入表都具有完全相同的结构,您还可以将所有这些数据帧组合成一个。
希望这有帮助,不确定下面的代码是否有效,如果您复制粘贴它并更新路径,但是非常类似的东西可能对您有帮助。
# Prepare empty list
data <- list()
# Loop through all years
for(year in 2005:2012){
# Load data for this year
flowers <- read.csv(paste('C:/Directory/.../a/flowerdistrib_', year, '.csv', sep=''), sep=";", dec=",", header=TRUE)
ecology <- read.csv(paste('C:/Directory/.../a/ecology_', year, '.csv', sep=''), sep=";", dec=",", header=TRUE)
location <- read.csv(paste('C:/Directory/.../a/location_', year, '.csv', sep=''), sep=";", dec=",", header=TRUE)
# Merge data for this specific year, using idp as identifier
all <- merge(flowers, ecology, by = "idp", all = TRUE)
all <- merge(all, location, by = "idp", all = TRUE)
# Add a year column with constant year value to data
all$year <- year
# Drop unused columns
dropnames = c('column_x', 'column_y')
all <- all[,!(names(all) %in% dropnames)]
# Or alternatively, only keep wanted columns
keepnames = c('idp', 'year', 'column_z', 'column_v')
all <- all[keepnames]
# Append data to list
data[[as.character(year)]] <- all
}
# At this point, data should be a list of dataframes with all data for each year
# so this should print the summary of the data for 2007
summary(data[['2007']])
# If all years have the very same column structure,
# you can use use rbind to combine all years into one big dataframe
data <- do.call(rbind, data)
# This would summarize the data frame with all data combined
summary(data)发布于 2014-03-20 18:56:27
下面是使用一些函数式编程概念的较短版本。首先,我们编写了一个函数read_and_merge,它接受一个年份作为参数,为该年构造一个文件列表,并将它们读入由三个文件组成的data_中。最后一个窍门是使用Reduce函数,它递归地合并三个数据帧。我假设唯一常见的列是idp。
read_and_merge <- function(year, mydir = "C:/Directory/.../a/"){
files_ = list.files(mydir, pattern = paste("*_", year, ".csv"))
data_ = lapply(files_, read.csv, sep = ";", dec = ",", header = TRUE)
Reduce('merge', data_)
}第二步是创建年份列表,并使用lapply为每年创建数据集。
mydata = lapply(2005:2012, read_and_merge)https://stackoverflow.com/questions/22541064
复制相似问题