user10011859
user10011859

Reputation:

Using loops or lapply to read and name files

I am a beginner to R, so my question may be very basic. I have searched for the answer to this question to the best of my ability, but I could not find what I need.

I have several files containing data collected from each state. I currently have the files titled things such as "ALTable.csv", "DETable.csv", etc.

I want to read these files into a program and save the contents in a named data frame. I then want to go on to perform operations on these data frames, and to use them to construct new data frames filled by computations with the old data frames.

I currently have many lines of code such as

AL <- read.csv("ALTable.csv")
DE <- read.csv("DETable.csv")

I am trying to avoid having to do this command individually for each state. I was able to find out how to tell R to make a list of the relevant files and how to load them, but I do not know how to tell R to make a list of these files, read them, and saved them as a named data frame.

Similarly, after I have these data frames, I am performing computations with these frames and creating new data frames filled with these computations. I have lines such as

MuAL <- AL$prop/AL$pop
MuDE <- DE$prop/DE$pop

I would like to perform these computations and save the results with the given names without having to do it for each individual state.

Ideally, I could simply make a single list of all abbreviations and in each line of code where an individual state occurs, insert placeholders where the state abbreviation goes and create a for loop which goes over my list and inserts the abbreviations for the placeholders. However, I have no idea how to do this other than the most naive way, which did not work.

Upvotes: 0

Views: 557

Answers (2)

Simon C.
Simon C.

Reputation: 1077

if you have a list of your abrevations and all the csv file are indeed named the same way, you could generate a list of dataframe using lapply.

Something like:

abbr<- c("AL","DE")
name(abbr)<-abbr
listofDF <- lapply(abbr,function(ab)read.csv(paste0(ab,"Table.csv"))

and then you should be able to do muAL <- listofDF$AL$prop/listofDF$AL$pop or even if you want to do that for all abbrevation:

mu <- lapply(litofDF,function(i)i$prop/i$pop)

And here mu$AL will store the equivalent of your MuAL.

Maybe if you could give some sample of your data that may help to find a good solution.

Upvotes: 0

Paweł Chabros
Paweł Chabros

Reputation: 2399

First put all .csv files that you want to load in some folder (let's name folder data for this example). Then your's working directory must be set up to the parent directory of this folder. Then you can load all files from this directory as following:

for (file in dir('data/')) {
  assign(substr(file, 1, 2), read.csv(paste0('data/', file)))
}

Upvotes: 0

Related Questions