Reputation: 49
I have a list with element names like x.height, x.weight, y.height, y.length, z.weight, z.price
I would like to extract the elements which names start with "x."
and rename these element by removing their prefix "x."
. This can be done in two steps:
list.new <- list.old %>% keep(str_detect(names(.), "^x."))
names(list.new) <- str_replace(names(list.new), "x", "")
My first question: how to combine these two steps in a pipeline?
At the end, I would like to process the list for all of the different prefixes "y.", "z."
to get a new list with the renamed sublists like:
List of 3
$ x:List of 2
..$ height: num 100
..$ weight: num 200
$ y:List of 2
..$ height: num 300
..$ length: num 400
$ z:List of 2
..$ weight: num 500
..$ price: num 600
Is it possible to do this using a single pipeline?
Upvotes: 0
Views: 890
Reputation: 3134
You can simply use setNames()
or set_names()
:
list.old <- list(
x.height=1, x.weight=2, y.height=3, y.length=4, z.weight=5, z.price=6
)
list.old %>%
keep(startsWith(names(.), prefix)) %>%
set_names(str_replace(names(.), prefix, ""))
# $height
# [1] 1
#
# $weight
# [1] 2
And to apply to many prefixes, use the previous code as a function:
prefix_list <- c("x","y","z")
map(prefix_list,
function(prefix) list.old %>%
keep(startsWith(names(.), prefix)) %>%
set_names(str_replace(names(.), prefix, ""))
) %>%
set_names(prefix_list)
# $x
# $x$.height
# [1] 1
#
# $x$.weight
# [1] 2
#
#
# $y
# $y$.height
# [1] 3
#
# $y$.length
# [1] 4
#
#
# $z
# $z$.weight
# [1] 5
#
# $z$.price
# [1] 6
Upvotes: 1
Reputation: 3334
You can achieve what you want the following way. Note that this requires that you have a recent version of the dplyr
package (>= 1.0.0).
library(dplyr)
library(stringr)
library(purrr)
list.old <- list(
x = list(x.height = 100, x.weight = 200),
y = list(y.height = 300, y.length = 400),
z = list(z.weight = 500, z.price = 600)
)
list.new <- list.old %>%
map(as_tibble) %>%
map(~ rename_with(.x, ~ str_remove(.x, "^[xyz]\\."))) %>%
map(as.list)
str(list.new)
List of 3
$ x:List of 2
..$ height: num 100
..$ weight: num 200
$ y:List of 2
..$ height: num 300
..$ length: num 400
$ z:List of 2
..$ weight: num 500
..$ price : num 600
Upvotes: 0