2017-06-20 42 views
2

看來,如果名單有標題或不是,嗚呼功能評估不同,但爲什麼?這只是「其中的一件事」嗎?嗚嗚聲清單評價奇怪

實施例:

func_b <- function(x,y,z) paste(x,y,z) 

## Works as expected 
pmap(list(iris$Sepal.Length, iris$Sepal.Width, iris$Petal.Length), func_b) %>% head(2) 

[[1]] [1] 「5.1 3.5 1.4」

[[2] [1] 「4.9 3 1.4」

## Doesn't work 
pmap(map(iris[,1:3],list),func_b) 

錯誤.f(Sepal.Length = .l [[c(1L,1L)]],Sepal.Width = .l [[c(2L,1L)]],:未使用的參數(Sepal .L ength = .l [[c(1,1)]],Sepal.Width = .l [[c(2,1)]],Petal.Length = .l [[c(3,1)]])

但唯一的區別似乎是其中一個列表保留其標題,而另一個不是?

list(iris$Sepal.Length, iris$Sepal.Width, iris$Petal.Length) %>% map(head) 

[[1]] [1] 5.1 4.9 4.7 4.6 5.0 5.4

[[2] [1] 3.5 3.0 3.2 3.1 3.6 3.9

[[3]] [1] 1.4 1.4 1.3 1.5 1.4 1.7

as.list(iris[,1:3]) %>% map(head) 

$ Sepal.Length [1] 5.1 4.9 4.7 4.6 5.0 5.4

$ Sepal.Width [1] 3.5 3.0 3.2 3.1 3.6 3.9

$ Petal.Length [1] 1.4 1.4 1.3 1.5 1.4 1.7

class(list(iris$Sepal.Length, iris$Sepal.Width, iris$Petal.Length)) == class(as.list(iris[,1:3])) 

[1] TRUE

str(list(iris$Sepal.Length, iris$Sepal.Width, iris$Petal.Length)); str(as.list(iris[,1:3])) 

List of 3 
$ : num [1:150] 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ... 
$ : num [1:150] 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ... 
$ : num [1:150] 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ... 
List of 3 
$ Sepal.Length: num [1:150] 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ... 
$ Sepal.Width : num [1:150] 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ... 
$ Petal.Length: num [1:150] 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ... 

如果我們剛剛擺脫的第二列表的名稱,它不工作 一個問題。

aa <- as.list(iris[,1:3]) 
names(aa) <- NULL  
pmap(aa,func_b) %>% head(2) 

[[1]] [1] 「5.1 3.5 1.4」

[[2]] [1] 「4.9 3 1.4」

所以我的特定問題:爲什麼標題會影響評估方法?有什麼方法可以在不破壞dplyr管道的情況下轉換東西來消除名稱?

+2

未命名列表被分配給位置的功能參數,稱爲按名稱列出。這意味着'purrr'試圖做'func_b(Sepal.Length = .....等)'。如有必要,您可以隨時輸入「unname」。 – Axeman

+0

不錯,這個unname很漂亮:'map(iris [,1:3],list)%>%unname()%>%pmap(func_b)%>%map(head)' –

回答

4

斧頭兵通過點上,但你可以戍周圍&動態程序:

library(purrr) 

func_b <- function(...) { 
    args <- list(...) 
    paste(args[[1]], args[[2]], args[[3]]) 
} 

list(iris$Sepal.Length, iris$Sepal.Width, iris$Petal.Length) %>% 
    pmap(func_b) %>% 
    head(2) 
## [[1]] 
## [1] "5.1 3.5 1.4" 
## 
## [[2]] 
## [1] "4.9 3 1.4" 

iris[,1:3] %>% pmap(func_b) %>% head(3) 
## [[1]] 
## [1] "5.1 3.5 1.4" 
## 
## [[2]] 
## [1] "4.9 3 1.4" 
## 
## [[3]] 
## [1] "4.7 3.2 1.3" 

func_c <- function(...) { 
    args <- list(...) 
    paste0(args, collapse = " ") 
} 

list(iris$Sepal.Length, iris$Sepal.Width, iris$Petal.Length) %>% 
    pmap(func_c) %>% 
    head(2) 
## [[1]] 
## [1] "5.1 3.5 1.4" 
## 
## [[2]] 
## [1] "4.9 3 1.4" 

iris[,1:3] %>% pmap(func_c) %>% head(3) 
## [[1]] 
## [1] "5.1 3.5 1.4" 
## 
## [[2]] 
## [1] "4.9 3 1.4" 
## 
## [[3]] 
## [1] "4.7 3.2 1.3" 

iris[,1:2] %>% pmap(func_c) %>% head(3) 
## [[1]] 
## [1] "5.1 3.5" 
## 
## [[2]] 
## [1] "4.9 3" 
## 
## [[3]] 
## [1] "4.7 3.2" 
+0

所以你基本上明確地做了在函數本身中未命名的列表,它可以保護您免於發送什麼列表類型,這是正確的嗎? –

+1

。正確。並試圖使其對任何'pmap()'調用都是通用的 – hrbrmstr