library(tidyverse)
I'm attempting to use tidyverse tools to selectively bind a list of dataframes using dplyr::bind_rows(). I'll split the mtcars dataset to create a basic reproduction of my real data.
Df<-mtcars%>%
split(.$carb)%>%
head()
I can bind it together with bind_rows()...
Df<-Df%>%
bind_rows()
But how do I selectively bind elements of the list. What I want to do is create two lists - the first binds list elements 1,3,6 while the second binds 2,4,8. I'm thinking something like...
Df<-Df%>%map(~bind_rows(.x,list(.$`1`,.$`3`,.$`6`),list(.$`2`,.$`4`,.$`8`)))
But this code is obviously not correct so I would appreciate some suggestions.
Ok, So I realised that OP has given this as just an example and originally, the starting point is from
The original solution would still work, if we do
But is there a way we can bind them according to
lst
directly ?I am not an expert in
tidyverse
but after going through through the documentation , I found a functioninvoke_map
which can give what we want here.gives us the expected output. There could be better ways to optimize this, I am not sure.
Original Answer :
Why not change your
split
step? Get the output without usingbind_rows()
.This could be another way. I tried to reflect your
map()
theme here. I usedMap()
in base R. If you want to use thepurrr
package, I think you can trymap2()
.An easy approach is to just map with one fixed argument in an implicit function.
which based on the other answers is I think what you want now:
Note: I originally was very confused by whether you wanted what I call
picker
to be indices of the list or you wanted to names of the list. This confusion was just an artifact of the waysplit()
names lists and probably doesn't apply to your real data.