R pass a vector in crossing function

I'm trying to pass a vector in the tidyr 'crossing' function, but I don't see how to do it. Here's what I want to do: I want to crossproduct the objects michel, anita, robert to obtain the dataframe everybody as follow:

# objects to combine

michel <- c("Berlin","Tokyo","Amsterdam")
anita <- c("London","Montreal")
robert <- "Moscow"

# combination

library(tidyr)

everybody <- crossing(michel,anita,robert)

Thing is, I want to pick the list michel, anita, robert from a dataframe (or vector), then pass that vector to the crossing function (so that everybody2 is the same as everybody):

# vector with names:

vector1 <- as.data.frame(c("michel","anita","robert"))

# how to pass 'vector1' into crossing?

everybody2 <- crossing(vector1)

I don't see how I can make it work... any advice?

Thank you in advance!

1 answer

  • answered 2020-07-05 02:44 akrun

    We can use mget to return the values of the string objects

    everybody2 <- crossing(!!! mget(vector1[[1]]))
    identical(everybody, everybody2)
    #[1] TRUE
    

    Or another option is do.call

    do.call(crossing, mget(vector1[[1]]))
    

    Here, the 'vector1' is a data.frame with single column of strings. We extract the first column with [[1]], get the value of string objects with mget into a list, splice the list (!!!) in crossing

    NOTE: We used R 4.0 and the default option in data.frame or as.data.frame is stringsAsFactors = FALSE. If the R version is < 4.0, then convert the factor class to character with as.character or specify stringsAsFactors = FALSE in as.data.frame

    crossing(!!! mget(as.character(vector1[[1]])))
    

    Or using base R with expand.grid

    expand.grid(mget(vector1[[1]]))