2017-04-18 30 views
1

我試圖使用lapplymappurrr從列表中檢索名稱作爲我正在構建的更大功能的一部分,但我一直得到意想不到的結果。例如:從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。我想自己提取名稱,或者作爲列表中的元素或者作爲字符向量。這是爲什麼發生?我應該如何做到這一點?

+4

'名(MYLIST)'?它是具有名稱的「MyList」。 「MyList」,「MyList $ x」和「MyList $ y」的內容沒有名稱。 – BrodieG

+0

@BrodieG謝謝 - 我是一個白癡。 –

回答

1

不幸的是,沒有辦法使用maplapply獲取元素名稱。當我在maplapply中使用自定義函數時,需要元素名稱我將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 
相關問題