2017-09-06 48 views
1

我有一個在多個子目錄中具有相同名稱CSV的目錄。我試圖將類似命名的CSV合併到1個數據框中,並將子目錄名稱添加爲列。在下面的示例中,我將有一個名爲'data'的數據框和一個名爲'name'的數據框,其中包含來自Run 1和Run 2的觀察結果,並將名爲Run的列添加到每個數據框。如果解決方案不知道CSV的名稱,這將是理想的解決方案,但任何解決方案都將非常有幫助。基於文件名的子目錄中的rbind文件

在這個問題上的人有同樣的問題,但我需要的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
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') 
相關問題