Passing all variables in a dataframe to expand()

Hello,

I want to be able to pass all variables into the second argument of expand() without writing all of the variables out. I was hoping I could do something like a full stop or !! but I am not exactly finding the right way to pass it on.

library(tidyverse)

df_initial <- data_frame(V1 = c(0,1),
                      V2 = c(0,1),
                      V3 = c(0,1),
                      V4 = c(0,1),
                      V5 = c(0,1),
                      V6 = c(0,1),
                      V7 = c(0,1),
                      V8 = c(0,1),
                      V9 = c(0,1)
)

df_all_combinations <- tidyr::expand(df_initial,V1,V2,V3,V4,V5,V6,V7,V8,V9)

Hi @GreyMerchant,

Are you trying to get all possible combinations for all variables? The function expand.grid() should help with this.

expand.grid(df_initial)

You can also use the purrr function cross_df()

purrr::cross_df(df_initial)
1 Like

Thanks! This does work as I wanted it to. I would still like to know how to pass the dataframe while getting it to "read" the variables instead if that is at all possible.

Could you clarify what you mean by "I would still like to know how to pass the dataframe while getting it to "read" the variables instead"? I am not sure what exactly this means.

Is there a way within expand() to only pass in the dataframe while getting it evaluated as all variables within the dataframe without writing each variable explicitly out?

I know that expand.grid() deals with this problem directly but I was wondering if there is some standard evaluation way of passing a dataframe while only evaluating the variables in that specific object.

No, currently you are not able to do this. In fact, I submitted an issue to the tidyr GitHub several months ago requesting this very feature. See here for more details.

1 Like

Thanks for sharing! I look forward to this addition.

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