基于文件名的子目录中的rbind文件

时间:2017-09-06 00:40:07

标签: r

我在多个子目录中有一个名称相同的目录。我试图将名称相似的CSV组合成1个数据框,并将子目录名称添加为列。通过下面的示例,我将有一个名为'data'的数据框和一个名为'name'的数据框,其中包含Run 1和Run 2的观察结果,并在每个数据框中添加一个名为Run的列。如果解决方案与CSV的名称无关,那将是理想的,但任何解决方案都会非常有用。

在这个问题中,这个人有同样的问题,但我需要一个R解决方案:Combining files with same name in r and writing them into different files in R

 dir <- getwd()

subDir <- 'temp'

dir.create(subDir)

setwd(file.path(dir, subDir))

dir.create('Run1')
dir.create('Run2')

employeeID <- c('123','456','789')
salary <- c(21000, 23400, 26800)
startdate <- as.Date(c('2010-11-1','2008-3-25','2007-3-14'))

employeeID <- c('123','456','789')
first <- c('John','Jane','Tom')
last <- c('Doe','Smith','Franks')

data <- data.frame(employeeID,salary,startdate)
name <- data.frame(employeeID,first,last)

write.csv(data, file = "Run1/data.csv",row.names=FALSE, na="")
write.csv(name, file = "Run1/name.csv",row.names=FALSE, na="")

employeeID <- c('465','798','132')
salary <- c(100000, 500000, 300000)
startdate <- as.Date(c('2000-11-1','2001-3-25','2003-3-14'))

employeeID <- c('465','798','132')
first <- c('Jay','Susan','Tina')
last <- c('Jones','Smith','Thompson')

data <- data.frame(employeeID,salary,startdate)
name <- data.frame(employeeID,first,last)

write.csv(data, file = "Run2/data.csv",row.names=FALSE, na="")
write.csv(name, file = "Run2/name.csv",row.names=FALSE, na="")

# list files in all directories to read
files <- list.files(recursive = TRUE)

# Read csvs into a list
list <- lapply(files, read.csv)

# Name each dataframe with the run and filename
names <- sub("\\..*$", "", files)
names(list) <- sub("\\..*$", "", files)

# And add .id = 'run' so that the run number is one of the columns
# This would work if all of the files were the same, but I don't know how to subset the dataframes based on name. 
all_dat <- list %>%
bind_rows(.id = 'run')

1 个答案:

答案 0 :(得分:1)

files_to_df <- function(pattern){ 

  # pattern <- "data"
  filenames <- list.files(recursive = TRUE, pattern = pattern) 

  df_list <- lapply(filenames, read.csv, header = TRUE)

  # Name each dataframe with the run and filename
  names(df_list) <- str_sub(filenames, 1, 4)

  # Create combined dataframe  
  df <- df_list %>%
    bind_rows(.id = 'run')

  # Assign dataframe to the name of the pattern  
  assign(pattern, df)

  # Return the dataframe  
  return(data.frame(df))
}

name_df <- files_to_df('name')