I am trying to find a way to access named nested list elements by passing their names as a string (or list of strings). Something like you can do with attr(the_thing, "the_attr") but I want to do attr(the_thing, "$attr1$attr2$attr3"). Seems like this should be possible but I'm at a loss.
For example, I'm writing some code to consume responses from the Github API. There are a bunch of functions like (these are very simplified just for example's sake):
get_milestone <- function(org, repo) {
response <- graphql_query(org = org, repo = repo)
return(response$repository$milestone$issues)
}
get_pull_request <- function(org, repo) {
response <- graphql_query(org = org, repo = repo)
return(response$repository$pull_request$issues)
}
get_issues <- function(org, repo) {
response <- graphql_query(org = org, repo = repo)
return(response$repository$issues)
}
and you'll notice the only difference is what attributes you pull out of the response.
I'd like to make simple helper function like
get_something <- function(org, repo, attr_to_get) {
response <- graphql_query(org = org, repo = repo)
return(attr(response, attr_to_get))
}
and then call it each time like
get_something(org, repo, attr_to_get="$repository$milestone$issues")
get_something(org, repo, attr_to_get="$repository$pull_request$issues")
get_something(org, repo, attr_to_get="$repository$issues")
but that syntax doesn't work.
Is there any way to pass a string to specify nested attributes to extract from an object? I feel like rlang or something like that may be relevant, but I can't seem to figure it out.
My initial idea was just to do something like this
param_list <- unlist(strsplit(attr_to_get, "\\$"))
for (p in param_list) {
if (p != "") {
response <- response[[p]]
}
}
But that feels very ugly and silly to me. Like, there must be a one-liner way of doing this without manually iterating. But maybe I should just do it that way? Any help is much appreciated.
For reproducibility you can replace the response <- graphql_query(org = org, repo = repo) line in my function with something like response <- list(repository = list(milestone = list(issues=c("issue1", "issue2", "issue3")))) and then attempt to extract "$repository$milestone$issues" from the response.
Thanks!
$repository$milestone$issuesis not an attribute. it is just a nested list. Are you dealing with nested lists or withattributes??response[[c("repository","milestone","issues")]]purrr:pluckfunction is also very helpful for extracting elements from nested lists.