2017-08-30 37 views
0

我正在使用以下設置來創建圖表的列表。在marrange之後無法使用ggsaveGrob

這工作得很好:

library(grid) 
library(gridExtra) 
library(ggplot2) 

mycols <- c('year','displ') 

mylist <- list() 
for(item in mycols){ 

    p <- ggplot(mpg, aes_string(x = 'hwy', y = item)) + 
    geom_point() 
    mylist[[(length(mylist) +1)]] <- p 
} 

ml = marrangeGrob(grob = mylist, nrow=2, ncol=1) 
ggsave("P://multipage.pdf", ml, width =10, height = 5) 

然而,在循環中,替換:

錯誤$<-.data.frame*tmp* 「wrapvp」,值=列表(x = 0.5,Y = 0.5,:更換有17行,數據具有234

什麼是這裏的問題?個別地,列表中的所有圖表看起來都很好。

謝謝!

+0

嘿@MrFlick謝謝。我現在正在更新。我發現了一個有趣的bug –

+0

是的,這是真的。讓我試試通常的玩具例子 –

+0

@MrFlick精彩編輯你不覺得? :) –

回答

2

這真的和marrangeGrob無關,並且與您建立清單的方式有關。比較這些方法的輸出結構

out1 <- list() 
out1[[length(out1)+1]]<-list(a=1, b=2) 
out1[[length(out1)+1]]<-list(a=2, b=2) 
str(out1) 
# List of 2 
# $ :List of 2 
# ..$ a: num 1 
# ..$ b: num 2 
# $ :List of 2 
# ..$ a: num 2 
# ..$ b: num 2 

out2 <- list() 
out2 <- append(out2, list(a=1, b=2)) 
out2 <- append(out2, list(a=2, b=2)) 
str(out2) 
# List of 4 
# $ a: num 1 
# $ b: num 2 
# $ a: num 2 
# $ b: num 2 

請注意,它們會產生不同的結構。 append()將元素添加到「根」列表中,而不是將列表嵌套到列表中。你可以明確地做自己與和額外list()

out3 <- list() 
out3 <- append(out3, list(list(a=1, b=2))) 
out3 <- append(out3, list(list(a=2, b=2))) 
str(out3) 
# List of 2 
# $ :List of 2 
# ..$ a: num 1 
# ..$ b: num 2 
# $ :List of 2 
# ..$ a: num 2 
# ..$ b: num 2 

但R中環這樣搞亂很少是必要的。最好使用內置迭代器,如lapply()Map()。例如

mylist <- lapply(mycols, function(item) { 
    ggplot(mpg, aes_string(x = 'hwy', y = item)) + 
    geom_point() 
}) 
+0

非常明確和有趣。謝謝!一個嵌套和unnested循環的令人討厭的例子 –

相關問題