使用 purrr 包中的 lapply() 或 map() 来提取列表元素的名称
use of lapply() or map() from purrr package to extract names of list elements
我正在尝试使用 purrr
中的 lapply
或 map
从列表中检索名称,作为我正在构建的更大函数的一部分,但我不断收到意想不到的结果。例如:
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
。我想自己提取名称,作为列表中的元素或作为字符向量。为什么会这样?我该如何完成?
不幸的是,无法使用 map
或 lapply
获取元素名称。当我在 map
或 lapply
中使用需要元素名称的自定义函数时,我将 map
覆盖 m 个元素名称的向量,然后使用它从列表中提取数据。这是一个例子:
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
我正在尝试使用 purrr
中的 lapply
或 map
从列表中检索名称,作为我正在构建的更大函数的一部分,但我不断收到意想不到的结果。例如:
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
。我想自己提取名称,作为列表中的元素或作为字符向量。为什么会这样?我该如何完成?
不幸的是,无法使用 map
或 lapply
获取元素名称。当我在 map
或 lapply
中使用需要元素名称的自定义函数时,我将 map
覆盖 m 个元素名称的向量,然后使用它从列表中提取数据。这是一个例子:
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