0

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?

D3SL
  • 117
  • 8

1 Answers1

2

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)

DaveArmstrong
  • 18,377
  • 2
  • 13
  • 25
  • Looks like no matter what I need to construct the entire function in at least a two-step process, there's no one-step solution where I just drop something into the back half of the ```print()``` function. ```do.call()``` is probably more R-esque way to code this than treating things as strings. Like Lumley's fortune said: "If the answer is parse you should rethink the question". – D3SL Jan 11 '23 at 07:40
  • I think that's right. I have also been a user of `parse()`, but I'm trying to kick the habit. – DaveArmstrong Jan 11 '23 at 11:11