Skip to content

Instantly share code, notes, and snippets.

@nstrayer
Last active March 12, 2021 21:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nstrayer/e8b951549caea967cd48e268852a465f to your computer and use it in GitHub Desktop.
Save nstrayer/e8b951549caea967cd48e268852a465f to your computer and use it in GitHub Desktop.
Experiments with the function rapply in R's base library
library(magrittr)
str_replace_all <- function(text, pattern, replacement){
gsub(pattern = pattern, replacement = replacement, x = text, perl = TRUE)
}
str_remove_all <- function(text, pattern){
str_replace_all(text, pattern = pattern, replacement = "")
}
pretty_str <- function(x){
capture.output(str(x)) %>%
str_replace_all("\\$ :", "~") %>%
str_replace_all("\\.\\.", " ") %>%
str_replace_all("([[:alpha:]]+)\\s*:\\s*(.+)", "\\1: \\2") %>%
str_replace_all("List of [1-9]+", "List:") %>%
str_remove_all(" chr|num ") %>%
str_remove_all("\\$") %>%
paste(collapse = "\n") %>%
cat()
}
my_list <- list(
list(id = "a",
val = 2),
list(id = "b",
val = 1,
children = list(
list(id = "b1",
val = 2.5),
list(id = "b2",
val = 8))))
# Double all numbers
my_list %>%
rapply(function(x) x*2, classes = "numeric", how = "replace") %>%
pretty_str()
#> List:
#> ~List:
#> id: "a"
#> val: 4
#> ~List:
#> id: "b"
#> val: 2
#> children: List:
#> ~List:
#> id: "b1"
#> val: 5
#> ~List:
#> id: "b2"
#> val: 16
# Get all characters out and squash to flat list
rapply(my_list, I, classes = "character", how = "unlist")
#> id id children.id children.id
#> "a" "b" "b1" "b2"
my_list <- list(
list(id = "hi",
attribs = list(
class = "a")),
list(id = "there",
attribs = list(
class = "b"))
)
extract_chr <- function(x, ...){
path_to_query <- paste(list(...), collapse = ".")
flattened <- rapply(x, I, classes = "character", how = "unlist")
flattened[names(flattened) == path_to_query]
}
extract_chr(my_list, "id")
#> id id
#> "hi" "there"
extract_chr(my_list, "attribs", "class")
#> attribs.class attribs.class
#> "a" "b"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment