Reputation: 1107
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?
Upvotes: 1
Views: 73
Reputation: 35649
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
Upvotes: 2
Reputation: 73802
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)
Upvotes: 0
Reputation: 33743
Why not?
names(a) <- tolower(names(a))
names(b) <- tolower(names(b))
Upvotes: 2