将许多.csv文件导入到一个数据框中,并根据名称添加列

时间:2016-11-30 03:53:05

标签: r

我有>我的计算机上的文件夹中有50个.csv文件。这些文件都包含相同的列标题/格式。

我有代码导入所有.csv文件并对其进行适当命名:

path <- "~/My folder Location/"
files <- list.files(path=path, pattern="*.csv")
for(file in files)
{
  perpos <- which(strsplit(file, "")[[1]]==".")
  assign(
    gsub(" ","",substr(file, 1, perpos-1)), 
    read.csv(paste(path,file,sep="")))
}

我现在有很多.csv文件,在我看来,在环境中命名。但是,我现在希望根据data.frame名称的一部分在每个data.frame中创建两列,然后创建一个大数据。框架

例如,如果其中一个data.frames是:

LeftArm_Beatrice

我希望包括:

LeftArm_Beatrice$BodyPart <- c("LeftArm")
LeftArm_Beatrice$Name <- c("Beatrice")

另一个例子,如果其中一个data.frames是:

RightLeg_Sally

我希望包括:

RightLeg_Sally$BodyPart <- c("RightLeg")
RightLeg_Sally$Name <- c("Sally")

然后我想将所有这50多个data.frames合并为一个。如果这些步骤可以包含在我的导入代码中,那就太棒了。

谢谢!

1 个答案:

答案 0 :(得分:1)

这可能有用!实际上,我需要对数据和要命名的命名进行更多说明。如果您有任何问题,请告诉我

path = "D:/pathname/"
l = list.files(path, pattern = ".csv")
# below func does importing and creation of new columns
func <- function(i){
  df <- read.csv(paste0(path,l[i]))
  names <- unlist(strsplit(l[i], "_"))
  df["BodyPart"] <- names[1]
  df["Name"] <- names[2]
  return(df)
}
# l1 shall have each of the dataframes individually with new columns attached
l1 = lapply(1:length(l), func)
# here we combine all dataframes together
l2 <- as.data.frame(l1)