bind_rows multiple objects

Hello,
I need to perform some simple task.
I just generate three objects. From res1 to res3.

library(tidyverse)

datox=datasets::iris
datox


res1=datox %>% 
  group_by(Species) %>% 
  summarise(expansion=Sepal.Width+1)

res2=datox %>% 
  group_by(Species) %>% 
  summarise(expansion=Sepal.Width+2)

res3=datox %>% 
  group_by(Species) %>% 
  summarise(expansion=Sepal.Width+3)

bind_rows(res1,res2,res3)

Then I used the command bind_rows to join them.
But now I just want to generate the list that contains every object.
I tried doing It with paste0.
But when I use that list, I received an error:

list_res=paste0("res",1:3,"")
bind_rows(list_res)
Error: Argument 1 must have names.
Run `rlang::last_error()` to see where the error occurred.

I pretend to repeat this tak with 100 object, so that's why I need to generate the list declaring all the objects for joining.

Thanks for your time and interest, community.
Have a nice weekend.

I'm not sure if this is the best way to do it, but this might be a solution?

do.call(bind_rows, sapply(list_res, as.name))

# A tibble: 450 × 2
# Groups:   Species [3]
   Species expansion
   <fct>       <dbl>
 1 setosa        4.5
 2 setosa        4  
 3 setosa        4.2
 4 setosa        4.1
 5 setosa        4.6
 6 setosa        4.9
 7 setosa        4.4
 8 setosa        4.4
 9 setosa        3.9
10 setosa        4.1
# … with 440 more rows

sapply calls as.name on each string and returns a list of symbols (the variables res1-3).
do.call calls bind_rows and, importantly, expands the list into individual arguments for bind_rows. This is like manually calling

bind_rows(res1, res2, res3, ...)

Hope that's what you were looking for.

1 Like
lista=paste("res",1:3, sep="")
lista

res0=res1

zzz=res1

for (i in lista) {
  
  texto=paste("zzz=bind_rows(zzz,",i,")",sep="")
  print(texto)
  eval(parse(text=texto))
  
  
}
zzz

It worked. Not the nicest code, but It does the job.
It's a shame I can't use purrr or across and num_range from tidyverse

Why this code doesn't work?
This is the reason I wrote eval and parse...

listax=as.list(paste("res",1:5, sep=""))

listax
for (i in 1:3) { 
  
res1=res1 %>% bind_rows(listax[i])  
  
}
res1
(listax <- paste("res",1:3, sep=""))
bind_rows(mget(listax))
1 Like

Thanks, nirgrahamuk
This solved my issue

This topic was automatically closed 7 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.