ggplot2在lapply()循环中时打印两次

时间:2019-02-05 01:29:06

标签: r ggplot2 rstudio

创建两个图形集时,在lapply循环内打印将在RStudio绘图面板中打印两次。

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)

该代码可以正常运行,但是它在RStudio中生成了两组图形,而不是一组图形。

如何避免这种行为?

1 个答案:

答案 0 :(得分:2)

该对象被打印两次是因为一个输出来自lapply,另一输出来自print。检查

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

这里1-5的第一部分来自print,而列表中1-5的下一部分则来自lapply

来自?lapply

  

lapply返回一个与X长度相同的列表,其中每个元素都是对X的对应元素应用FUN的结果。

因此,当您应用lapply时,它会返回显示的同一对象,并且由于FUN参数是print,因此它将对该函数应用到lapply中的每个对象打印两次。

@www建议的解决方法是在控制台中使用print(collect.graph)或仅使用collect.graph仅打印一次。