r - Rename portions of named list of lists without for loop
问题描述
I have a list of lists like this
list1 <- list(a = 1, error = 2)
list2 <- list(a = 1, error = 3)
mylist <- list(list1, list2)
I'd like to rename all the elements currently named "a"
to the names in new_names
new_names <- c("new_1", "new_2")
I can do this with a for
loop like so
for(i in seq_along(mylist)) {
names(mylist[[i]])[names(mylist[[i]]) == "a"] <- new_names[i]}
and get my desired result:
mylist
[[1]]
[[1]]$new_1
[1] 1
[[1]]$error
[1] 2
[[2]]
[[2]]$new_2
[1] 3
[[2]]$error
[1] 4
I'd like to do this without the for
loop. Something like this map
function perhaps, which doesn't work because it replaces all names, not just those that are "a"
.
library(purrr)
mylist_2 <- map(mylist, ~{names(.)[names(.) == "a"] <- new_names})
解决方案
You can use Map
from baseR
f <- function(x, y) {
names(x)[names(x) == "a"] <- y
x
}
Map(f, x = mylist, y = new_names)
#[[1]]
#[[1]]$new_1
#[1] 1
#
#[[1]]$error
#[1] 2
#
#
#[[2]]
#[[2]]$new_2
#[1] 1
#
#[[2]]$error
#[1] 3
Using purrr
it would be map2
purrr::map2(mylist, new_names, f)
推荐阅读
- javascript - 将基于 javascript 的待办事项列表中的 localStorage 数据推送到 mysql 数据库
- node.js - 在新域上使用 Let's Encrypt with Nginx 和 Node.js 时出现 502 Bad Gateway
- java - Android 资源链接失败(在 Google 上找不到任何专门解决此问题的内容)
- php - PHP curl post/put中的编码
- python - 将多行for循环更改为单行for循环
- svn - 如何使用 SharpSVN 获取每个版本的文件列表
- javascript - 为什么我的书没有排列在正确的书架上(React-Redux)?
- reactjs - 为什么我会得到“预期减速器是一个函数。”?
- c++ - 对对象使用 shared_ptr
- python-3.x - redshift 中的 python udf - 支持嵌套的 udf