rrlangdata.tree

Use variable in place of sequential arguments in a function


I'm working with the data.trees package and the syntax to work with multiple attributes is to input them in quotes as arguments to a function, like here with print(): print(tree,"item1","item2","item99"). I want to be able to replace that sequence of quoted arguments with a variable so I can deal with it programmatically.

The only method I've found so far is to construct the entire function call as a string using something like str_glue() then feed it to str2lang() and eval():

data(acme) #comes with data.trees
foo<-print(acme$IT$Outsource ,"attributes")[[2]]
foo<-gsub('(\\w+)', '"\\1"', foo)

##str2lang also works
str_glue("print(acme$IT$Outsource,{foo})") %>%
str2lang()%>%eval()

Is there as less involved way of doing this?


Solution

  • How about something like this:

    library(data.tree)
    data(acme) #comes with data.trees
    library(stringr)
    foo<-print(acme$IT$Outsource ,"attributes")[[2]]
    #>   levelName attributes
    #> 1 Outsource    cost, p
    foo <- str_split(foo, ", ", simplify = TRUE) %>% trimws()
    
    l <- c(list(acme$IT$Outsource), as.list(foo))
    
    do.call(print, l)
    #>   levelName  cost   p
    #> 1 Outsource 4e+05 0.2
    

    Created on 2023-01-09 by the reprex package (v2.0.1)

    You could even write a little function that would automate all this:

    library(data.tree)
    data(acme)
    my_print <- function(x){
      require(dplyr, quietly = TRUE)
      require(stringr, quietly = TRUE)
      sink(tempfile())
      foo <- print(x, "attributes")[[2]]
      sink()
      foo <- str_split(foo, ", ", simplify = TRUE) %>% trimws()
      
      l <- c(list(x), as.list(foo))
      do.call(print, l)
    }
    x <- my_print(acme$IT$Outsource)
    #>   levelName  cost   p
    #> 1 Outsource 4e+05 0.2
    

    Created on 2023-01-09 by the reprex package (v2.0.1)