Loop "for" with multiple data frames in different lengths

Hello,

I need to use a package that depend on multiple data frames to run (climate, parameters, site conditions and species), I created 4 data frames, each one contains 15 different characteristics of those varibles. I need to run 15 times, so I implemented a loop "for", but didn't work, seem like it keeps using the same climate data.
ps: After I eliminated the colun that contains the subset code, because the package doens't work if I keep it.

Can anybody help, please?!!
thanks

for(i in 1:N) {

dados_ic <- subset(d_climate, d_climate$pesquisa == pesquisa[i])
dados_ip <- subset(d_parameters, d_parameters$pesquisa == pesquisa[i])
dados_is <- subset(d_site, d_site$pesquisa == pesquisa[i])
dados_isp <- subset(d_species, d_species$pesquisa == pesquisa[i])

dados_ic <- dados_ic[,-1]
dados_ip <- dados_ip[,-1]
dados_is <- dados_is[,-1]
dados_isp <- dados_isp[,-1]

out_i <- run_3PG(
site = dados_is,
species = dados_isp,
climate = dados_ic,
thinning = NULL,
parameters = dados_ip,
size_dist = NULL,
check_input = TRUE, df_out = TRUE)

}

The immediate problem is that every iteration overwrites the previous result
successively. You can confirm this by checking that the output data corresponds to what you would expect for N.

The larger problem is conceptual. R can be made to work like other scripting languages, but that's not its strength. Rather, R excels at functional, not procedural, orientation. Every problem in R can be thought of with advantage as an exercise in school algebra, f(x) = y. The three objects, x, y and f (in R everything is an object) are

x what is at hand
y what is desired
f converts x to y

In this case x is 4 data frames. For simplicity, I assume they have identical structures.

y is the return value of your package's function on each element of x.

Thus, we can think of f as a composite function f(g(), where g is the package function and f is the function that feeds g.

So, what's an appropriate x? A list is simple.

What function will take a list as an argument and apply g to each. For that, you can look to purrr:map or base::lapply.

Without a reprex, I can't offer a concrete example.

1 Like

That's ok, as long as they have identical types and number of columns.

1 Like

It worked!!!!!!!!!! =D
I used the lists, and the loop "for" to access the elements inside the lists!

Thank you!!

1 Like

Hi!

To help us help you, could you please prepare a reproducible example (reprex) illustrating your issue? Please have a look at this guide, to see how to create one:

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.

Thank you for the explanation!!
I forget to tell that my data frames does not have the same length.

1 Like