![](/img/trans.png)
[英]How do you rename the elements of a list when they are nested within another list using R's purrr package?
[英]Rename list elements which has names starting with specified characters using purrr package
我有一個包含元素名稱的列表,例如x.height, x.weight, y.height, y.length, z.weight, z.price
我想提取名稱以"x."
並通過刪除它們的前綴"x."
. 這可以分兩步完成:
list.new <- list.old %>% keep(str_detect(names(.), "^x."))
names(list.new) <- str_replace(names(list.new), "x", "")
我的第一個問題:如何在管道中結合這兩個步驟?
最后,我想處理所有不同前綴"y.", "z."
的列表。 使用重命名的子列表獲取新列表,例如:
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
是否可以使用單個管道來執行此操作?
您可以通過以下方式實現您想要的。 請注意,這要求您擁有最新版本的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
您可以簡單地使用setNames()
或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
要應用於許多前綴,請使用前面的代碼作為 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.