简体   繁体   中英

reading mutilple csv files in R using loops

I have multiple csv files to read into R and I want to do it in the following way:

read data into R, using read_csv(), starting with list_files() creating a vector with full names of files, then set a tibble to NULL & loop over the entries in the vector I created using list_files, each time reading a file and attaching, with bind_rows(), the resulting tibble to the tibble set to NULL containing the data already read.

set the tibble to NULL before starting the loop, so that it can be added to each tibble that is read wihtin the loop.

I need to do this using this exact method, not a quicker way even if there is one

A solution where we replace for loops and lapply with purrr map_df.

library(dplyr)
library(purrr)
all_data <- list.files( "some/Where", full.names=TRUE pattern="\\.csv$" ) %>% 
  purrr::map_df(read.csv)

If you insist on rbind'ing stepwise to a variable that you initialize to NULL, then see below:


library(dplyr)

all.data <- NULL

my.files <- list.files( "some/Where", full.names=TRUE pattern="\\.csv$" )

for( csv.file in my.files ) {
    this.data <- read.csv( csv.file )
    all.data <- rbind( all.data, this.data )
}

There goes. I shudder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM