Home > Net >  Loading files and applying function to specific components in the code
Loading files and applying function to specific components in the code

Time:03-07

I have a number of external files that I would like to load in that can be applied to my list l1 based on the name of the list and the names of the files.

For example: If I have 3 .csv files "2008.csv", "2009.csv", "2010.csv", and the data from these .csv files would be loaded in as a data frame. I would like to load in these data frames into the list as follows:

"2008.csv" into the first element in l1 (i.e., 2008 in the list)

"2009.csv" into the second element in l1 (2009 in the list)

"2010.csv" into the third element in l1 (2010 in the list).

In this case, the .csv files are targeting specific elements of a list (i.e., "2009.csv" is not going into either 2008 and 2010.

Is there a way to tell R to look at the names of the files and load them into specific components of a list?

l1 <- list(NULL, NULL, NULL)
names(l1) <- c("2008", "2009", "2010")

CodePudding user response:

A simple solution using lapply based on a user-supplied list of names:

lapply(c("2008", "2009", "2010"), function(thisfile) read.csv(paste0(thisfile, ".csv")))

(This is less sophisticated than akrun's suggestion in the comment, which searches over files and extracts the filename.)

CodePudding user response:

You can do this as follows :

l1 <- list()
list.names <- c("2008", "2009", "2010")
for(i in list.names){
  l1[[i]] <- read.csv2("file.csv", header=T)
}
  • Related