chew
chew

Reputation: 21

Apply functions in different csv files in R with

Already made some research about loops in R and found that most of them focus only on how to change file or variable name with loops like Change variable name in for loop using R could find a good solution from other articles of bloggers....

The following is what I want to do with my original data(s1P...s9P) to get new data(s1Pm...s9Pm) by calculate their means according to the Datum column in (s1P...s9P).

Running the following lines one by one is okay, however, it seems like there should be a possibility to use loops to make it tidy.

Any suggestions would be appreciated. Have a nice weekend!

s1Pm = aggregate(s1P, list(s1P$Datum), mean)
s2Pm = aggregate(s2P, list(s2P$Datum), mean)
s3Pm = aggregate(s3P, list(s3P$Datum), mean)
s4Pm = aggregate(s4P, list(s4P$Datum), mean)
s5Pm = aggregate(s5P, list(s5P$Datum), mean)
s6Pm = aggregate(s6P, list(s6P$Datum), mean)
s7Pm = aggregate(s7P, list(s7P$Datum), mean)
s8Pm = aggregate(s8P, list(s8P$Datum), mean)
s9Pm = aggregate(s9P, list(s9P$Datum), mean)

Upvotes: 2

Views: 60

Answers (1)

akrun
akrun

Reputation: 886938

We can load all the objects in a list with mget and then apply the aggregate by looping through the list

outLst <- lapply(mget(paste0("s", 1:9, "P")), 
             function(x) aggregate(x, list(x$Datum), mean))
names(outLst) <- paste0(names(outLst), "m")

It is better to keep the output in a list rather than creating multiple objects. But, it can be done as well

list2env(outLst, envir = .GlobalEnv)

though not recommended

Upvotes: 2

Related Questions