0

I'm working on a loop where my input is a big data frame and my output would be multiples dataframes. In my loop there is a nested loop, where I use assign(paste0('small_df', x, y,sep = ''),big_df) to create multiple df who I can work with. And it works ! But later I'm trying to do the same (exactly) but with my new df, and it doesn't really work, I only have one df at the end, and I don't have any error message.

i've checked, but I don't have NA or zero in any of my df and it's the same code line. I don't understand where the error is coming from... Do you have any idea why it doesn't work ?

so this is my code:

for (x in 1:ncol(xdata)) { 
      for (y in 1:ncol(ydata)) {  
        df<- data.frame(iso3c = c(data$iso3c),
                           date= c(data$date),
                           x= c(xdata[,x]),
                           y= (ydata[,y]))         
        df<- df[!is.na(df$x),]
        df<- df[!is.na(df$y),]                    
        assign(paste0('all_df', x, y,sep = ''),prems)  
        all_df <- lapply(ls(pattern="all_df"), function(x) get(x))
        for (i in length(all_df)) {
          datyr<-filter(all_df[[i]],date == yr)       
          data2<-data.frame(datyr)       
          sumyr<- lm(data2[ ,4]~log(data2[ ,3]), data2)
          assign(paste0('final_year', -x, -y,sep = ''),final_year)
        }
      }
}

Thank you.

Limey
  • 10,234
  • 2
  • 12
  • 32
marine
  • 1
  • 3
  • 3
    I would strongly advice you to store the data frames in a list, and don't use ``assign``. It's much more efficient to work with data frames in lists and much preferable to clogging up your namespace with lots of different dfs. Please also provide a reproducible example. – user438383 May 04 '22 at 08:31
  • Welcome to SO! We need more code and a sample o the data to see why it doesn't work. See [here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). However, it sounds like what is happening is that you are overwriting the same variable every iteration of the loop, either because `x` and `y` do not change value or your `assign` statement is not in the correct place. I would question writing code this way though. It is almost always better to store variables from a loop in a big list, rather than creating lots of new variables in the global environment. – SamR May 04 '22 at 08:31
  • thanks for the answer ! I'm sure it could be written better, but I'm new to R, so if you have any suggestions of how i sould write it i'm open to any new idea :) – marine May 04 '22 at 09:45
  • We can suggest improvements to your code if you provide us with test input data and the corresponding expected output. – Limey May 04 '22 at 09:47
  • I think wrapping with get() should set you: assign( get (paste0('final_year', -x, -y,sep = '')),final_year) – Zahiro Mor May 04 '22 at 09:53

0 Answers0