简体   繁体   中英

Use a string as a function argument in R

For a given n I would like to enumerate all 2^( n ) - 1 possible subsets (excluding the null set).

So for n = 3 items (A, B, C) I have 8 - 1 combinations: {A}, {B}, {C}, {A, B}, {A, C}, {B, C}, and {A, B, C}.

To enumerate these subsets I would like to define a binary grid. For n = 3:

> expand.grid(0:1, 0:1, 0:1)[ -1, ]

  Var1 Var2 Var3
2    1    0    0
3    0    1    0
4    1    1    0
5    0    0    1
6    1    0    1
7    0    1    1
8    1    1    1

However, n is itself a random variable that changes from one simulation to the next.

It is easy to programmatically generate the string I need to pass to the function call. For instance, for n = 7, I can run:

> gsub(", $", "", paste(rep("0:1, ", 7), collapse = ""))

[1] "0:1, 0:1, 0:1, 0:1, 0:1, 0:1, 0:1"

But when I try to pass this string to expand.grid() I get an error. Surely there is a function that can coerce this string to a usable expression?

Running string as code is not recommended and should be avoided in general.

In this case, you can use replicate to repeat a vector n times and then use expand.grid with do.call .

n <- 3
do.call(expand.grid, replicate(n, list(0:1)))

#  Var1 Var2 Var3
#1    0    0    0
#2    1    0    0
#3    0    1    0
#4    1    1    0
#5    0    0    1
#6    1    0    1
#7    0    1    1
#8    1    1    1

We can use crossing

library(dplyr)
library(tidyr)
library(stringr)
library(purrr)
n <- 3
replicate(n, list(0:1)) %>%
    set_names(str_c('Var', seq_along(.))) %>% 
    invoke(crossing, .)
# A tibble: 8 x 3
#   Var1  Var2  Var3
#  <int> <int> <int>
#1     0     0     0
#2     0     0     1
#3     0     1     0
#4     0     1     1
#5     1     0     0
#6     1     0     1
#7     1     1     0
#8     1     1     1
    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM