It seems that the natural depth of the map function in R is not what one would expect.
Reprex:
data = list(
a =list(
'1' <- c(1, 2),
'2' <- c(3,4)
),
b = list(
'3' <- c(5,6),
'4' <- c(7,8)
)
)
I want to uppercase the names of the list and print them out, but this doesn't work.
map(data, ~str_to_upper(names(.x)))
Instead I have to do this:
map_depth(data,.depth = 0, ~str_to_upper(names(.x)))
Thanks in advance for the help.
The input to map
is the underlying list which for first iteration is
data[[1]]
#[[1]]
#[1] 1 2
#[[2]]
#[1] 3 4
This has no names in it hence it fails.
When you pass
map_depth(data,.depth = 0, ~str_to_upper(names(.x)))
The input for first iteration is
data[1]
#$a
#$a[[1]]
#[1] 1 2
#$a[[2]]
#[1] 3 4
which has names and hence it prints them.
You can directly use
stringr::str_to_upper(names(data))
#[1] "A" "B"
Or in base R
toupper(names(data))
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.