简体   繁体   中英

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

> 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" . 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 . 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.

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).

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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