Shreta Ghimire
Shreta Ghimire

Reputation: 1029

R - Read multiple Variable/Objects in a loop

Is it possible to read multiple user-defined objects/variable in a loop in R? I have more than 50 variables and i have to write same code over and over again to execute all the variables.

If it is possible to use the loop to read the objects, it would help me a lot.

Thank you in advance. Any suggestions are welcome.

Upvotes: 0

Views: 418

Answers (1)

Adam Quek
Adam Quek

Reputation: 7153

Assume I have 10 iris data sets named as a.01 to a.10:

for(i in 1:10) assign(sprintf("a.%02d", i), iris)

(i) create list of objects:

list_of_objects <- grep("a[.]", ls(), value=T)

(ii) calculate colSums for each:

lapply(list_of_objects, function(x) colSums(get(x)[-5])) # remove column 5 since iris[,5] == iris$Species (non-numeric)

Upvotes: 2

Related Questions