r-从purrr软件包中使用lapply()或map()来提取列表元素的名称



我正在尝试使用 lapplymappurrr中从列表中检索名称,这是我正在构建的较大函数的一部分,但是我一直会得到意外的结果。例如:

MyList=list(x=1:5, y=6:10)
> MyList
$x
[1] 1 2 3 4 5
$y
[1]  6  7  8  9 10
names(MyList)
[1] "x" "y"
### seems OK
map(MyList,names)
$x
NULL
$y
NULL
map_chr(MyList,names)
Error: Result 1 is not a length 1 atomic vector

lapply()给出与map()相同的结果。我回来的对象是list,其元素具有我想要的名称,但是每个元素的内容是NULL。我想自己提取名称本身,要么作为列表中的元素或角色向量。为什么会发生这种情况?我应该如何完成此操作?

不幸的是,没有办法使用 maplapply获取元素名称。当我在maplapply中使用自定义函数时,它需要元素名称,我将在m元素名称的向量上 map,然后使用该元素名称从列表中删除数据。这是一个例子:

library(dplyr) 
library(purrr)
MyList = list(Normal = rnorm(1000), 
              Gamma = rgamma(1000, shape = 4), 
              Weibull = rweibull(1000, shape = 1))
ListNames <- names(MyList)
ListNames %>% 
  walk(function(x) { # walk is another version of map
    data <- MyList[[x]]
    cat("nMean of ", x, "is ", mean(data))
    cat("nMedian of ", x, "is ", median(data))
  })

给出:

Mean of  Normal is  0.03043051
Median of  Normal is  0.01864171
Mean of  Gamma is  3.884722
Median of  Gamma is  3.500294
Mean of  Weibull is  0.9854814
Median of  Weibull is  0.6707907