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

Fab*_*rea 5 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)
Run Code Online (Sandbox Code Playgroud)

该代码工作正常,但它在 RStudio 中生成两组图形,而不是一组。

如何避免这种行为?

Ron*_*hah 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
Run Code Online (Sandbox Code Playgroud)

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

?lapply

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

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

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