Tapan
Tapan

Reputation: 1

Operation on data frame in loop with changing dataframe names

I have six data frames , z1, z2, ...z6. (read from six different sheets of a single excel file).

I need to do subsetting on these data frames and build some models. The process is identical for each of them. I was hoping to do it in a loop but not able to find the right syntax. (I am trying to use paste and assign functions but it does not help). For example I want

for (i in 1:6){
Z=subset(Zi,Zi$var1==1)
}

Zi should be Z1, Z2, Z3 exactly which are already defined. I can generate a variable through paste function which is Z1, Z2 in each iteration like

temp=paste('Z',i,sep='') but I cannot use 'temp' in place of Zi in the above code.

There is some discussion on other threads on similar problem but I am not able to find anything directly related there. If I am missing something, please point me to the right thread.

Upvotes: 0

Views: 122

Answers (2)

bramtayl
bramtayl

Reputation: 4024

Is are the column names of the data similar? If so, you might want to do this:

library(dplyr)

"Z" %>% 
  paste0(1:6) %>% 
  mget %>% 
  bind_rows(.id = "source") %>%
  filter(var1 == 1)

Upvotes: 0

akrun
akrun

Reputation: 887311

We get the 'values' in a list using mget, loop over the list (lapply(..)) and subset` the rows based on the 'var1' column.

lapply(mget(paste0('Z', 1:6)), subset, subset=var1==1)

Upvotes: 1

Related Questions