简体   繁体   English

gppplot2在lapply()循环内打印两次

[英]ggplot2 prints twice when inside lapply() loop

When creating a set of two graphs, then printing inside a lapply loop will print twice in RStudio Plots Panel. 创建一组两个图形时,在lapply循环内打印将在RStudio Plots Panel中打印两次。

x=1:7
y=1:7
df1 = data.frame(x=x,y=y)
x=10:70
y=10:70
df2 = data.frame(x=x,y=y)
db <- list(df1, df2)

# Given a data frame, the function below creates a graph
create.graph <- function (df){
  p <- ggplot(df,aes(x,y))+geom_point()
  # here goes other stuff, such as ggsave()
  return (p)
}

# collect.graph is a list of generated graphs
collect.graph <- lapply(db,create.graph)

# Finally, lapply prints the list of collected graphs
lapply(collect.graph,print)

The code works ok, but it generates two sets of graphs in RStudio instead of only one. 代码工作正常,但它在RStudio中生成两组图形而不是一组。

How to avoid this behavior? 如何避免这种行为?

The object gets printed twice is because one output is from lapply and the other one is from print . 对象被打印两次是因为一个输出来自lapply而另一个来自print Check 校验

lapply(1:5, print)

#[1] 1
#[1] 2
#[1] 3
#[1] 4
#[1] 5
#[[1]]
#[1] 1

#[[2]]
#[1] 2

#[[3]]
#[1] 3

#[[4]]
#[1] 4

#[[5]]
#[1] 5

Here, the first part of 1-5 is coming from print whereas the next part of 1-5 which is in a list is returned from lapply . 这里,1-5的第一部分来自print而列表中的1-5的下一部分是从lapply返回的。

From ?lapply 来自?lapply

lapply returns a list of the same length as X, each element of which is the result of applying FUN to the corresponding element of X. lapply返回与X相同长度的列表,其中每个元素都是将FUN应用于X的相应元素的结果。

So when you apply lapply it returns the same object back which gets displayed and since the FUN argument is print it applies that function to every object in lapply thus printing it twice. 因此,当你应用lapply它返回显示的同一个对象,因为FUN参数是print它将该函数应用于lapply每个对象,从而将其打印两次。

The workaround as suggested by @www is use print(collect.graph) or just collect.graph in the console to print it only once. @www建议的解决方法是使用print(collect.graph)或只在控制台中的collect.graph打印一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM