简体   繁体   English

R中的地图调用深度似乎不太直观

[英]The depth of a map call in R seems unintuitive

It seems that the natural depth of the map function in R is not what one would expect. 似乎R中的map函数的自然深度不是人们所期望的。

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 map的输入是基础列表,对于第一次迭代是

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 或以R为底

toupper(names(data))

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

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