Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For i loop, calling different dataframes

Tags:

for-loop

r

I'm new to loops and I have a problem with calling variable from i'th data frame.

I'm able to call each data frame correctly, but when I should call a specified variable inside each data frame problems come:

Example:

for (i in 1:15) {
    assign(
      paste("model", i, sep = ""), 
    (lm(response ~ variable, data = eval(parse(text = paste("data", i, sep = "")))))
    )
    plot(data[i]$response, predict.lm(eval(parse(text = paste("model", i, sep = ""))))) #plot obs vs preds
}

Here I'm doing a simple one variable linear model 15 times, which works just fine. Problems come when I try to plot the results. How should I call data[i] response?

like image 398
reima Avatar asked May 06 '26 12:05

reima


1 Answers

Let's say there are multiple dataframes with names: data1 ...data15 and that there are no other data-objects that begin with the letters: d,a,t,a. Lets also assume that in each of those dataframes are columns named 'response' and 'variable'. The this would gather the dataframes into a list and draw separate plots for the linear regression lines.

dlist <- lapply ( ls(patt='^data'), get)
lapply(dlist, function(df) 
                 plot(NA, xlim=range(df$variable), ylim=range(df$response)
                 abline( coef( lm(response ~ variable, data=df) ) )
         )

If you wanted to name the dataframes in that list, you could use your paste code to supply names:

names(dlist) <- paste("data", i, sep = "")

There are many other assignments you could make in the context of this loop, but you would need to describe the desired results better than with failed efforts.

like image 157
IRTFM Avatar answered May 08 '26 18:05

IRTFM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!