简体   繁体   English

立即更改列表名称

[英]Change names of lists at once

I have lists and I want their names to be in lower letters.我有列表,我希望他们的名字用小写字母。 I don't want to use a for-loop, I want to use a function of purrr我不想使用for循环,我想使用purrr的函数

> library(purrr)
> a <- list(Header = 1, Body = 1)
> b <- list(Header = 3, Body = 2)
> list(a, b) %>%
+   walk(~ {names(.x) <<- str_to_lower(names(.x))})
> a
$Header
[1] 1

$Body
[1] 1

> b
$Header
[1] 3

$Body
[1] 2

The names should be "header" and "body" .名称应该是"header""body" Why does this not work?为什么这不起作用? I explicitly used <<- and not <- but the names don't change.我明确使用了<<-而不是<-但名称没有改变。 What can I do?我能做什么?

library(purrr)
a <- list(Header = 1, Body = 1)
b <- list(Header = 3, Body = 2)

I guess you intend to change global variables by purrr::walk .我猜您打算通过purrr::walk更改全局变量。 Here is a choice to make the symbol "<<-" work:这是使符号"<<-"起作用的选择:

c("a", "b") %>%
  walk(~ eval(parse(text = paste0("names(", ., ")<<-tolower(names(", ., "))"))))

In addition, you can use assign(..., pos = 1) to change global variables.此外,您可以使用assign(..., pos = 1)来更改全局变量。

list(a = a, b = b) %>%
  iwalk(~ assign(.y, set_names(.x, tolower(names(.x))), pos = 1))

Check查看

a

# $header
# [1] 1
# 
# $body
# [1] 1

b

# $header
# [1] 3
# 
# $body
# [1] 2

Why not?为什么不?

names(a) <- tolower(names(a))
names(b) <- tolower(names(b))

If I understand you right you want a global assignment to lower case names.如果我理解正确,您希望对小写名称进行全局分配。 To do this for all selected objects c("a", "b") at once, in a function you may get them from global environment, lower the names, and assign the transformed objects to the old ones (overwrite).要一次对所有选定的对象c("a", "b")执行此操作,您可以在函数中从全局环境中get它们,降低名称,并将转换后的对象assign旧对象(覆盖)。

lapply(c("a", "b"), function(x) {
  d <- get(x, envir=.GlobalEnv)
  names(d) <- tolower(names(d))
  assign(x, d, envir=.GlobalEnv)
})

names(a)
# [1] "header" "body"  
names(b)
# [1] "header" "body"  

Data数据

a <- list(Header = 1, Body = 1)
b <- list(Header = 3, Body = 2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM