R 将列表中的数据帧发送到绘图函数
我正在尝试从多个数据帧生成多个ggplot图表。我已经开发了下面的代码,但是最终的循环不起作用R 将列表中的数据帧发送到绘图函数,r,list,for-loop,ggplot2,R,List,For Loop,Ggplot2,我正在尝试从多个数据帧生成多个ggplot图表。我已经开发了下面的代码,但是最终的循环不起作用 df1 <- tibble( a = rnorm(10), b = rnorm(10) ) df2 <- tibble( a = rnorm(20), b = rnorm(20) ) chart_it <- function(x) { x %>% ggplot() + geom_line(mapping = aes(y=a,x=b)) +
df1 <- tibble(
a = rnorm(10),
b = rnorm(10)
)
df2 <- tibble(
a = rnorm(20),
b = rnorm(20)
)
chart_it <- function(x) {
x %>% ggplot() +
geom_line(mapping = aes(y=a,x=b)) +
ggsave(paste0(substitute(x),".png"))
}
ll <- list(df1,df2)
for (i in seq_along(ll)) {
chart_it(ll[[i]])
}
但我不明白为什么,因为当我把它放在控制台中时,它给出了我想要的数据帧。还有,有没有一种方法可以用map函数代替for循环的tidyverse方法来实现这一点?问题在于
图表中的it
函数。它不会返回ggplot
。尝试将管道的结果保存到一个变量中并return()
该变量(或将其作为函数中的最后一条语句)
类似于
chart_it <- function(x) {
chart <- x %>% ggplot() +
geom_line(mapping = aes(y=a,x=b))
ggsave(paste0(substitute(x),".png")) # this will save the last ggplot figure
return(chart)
}
chart\u it问题出在chart\u it
函数中。它不会返回ggplot
。尝试将管道的结果保存到一个变量中并return()
该变量(或将其作为函数中的最后一条语句)
类似于
chart_it <- function(x) {
chart <- x %>% ggplot() +
geom_line(mapping = aes(y=a,x=b))
ggsave(paste0(substitute(x),".png")) # this will save the last ggplot figure
return(chart)
}
chart\u it我假设您希望在末尾看到两个名为df1.png
和df2.png
的文件
您需要以某种方式将数据帧的名称传递给函数。一种方法是通过命名列表,将名称与列表元素的内容一起传递
library(ggplot2)
library(purrr)
df1 <- tibble(
a = rnorm(10),
b = rnorm(10)
)
df2 <- tibble(
a = rnorm(20),
b = rnorm(20)
)
chart_it <- function(x, nm) {
p <- x %>% ggplot() +
geom_line(mapping = aes(y=a,x=b))
ggsave(paste0(nm,".png"), p, device = "png")
}
ll <- list(df1=df1,df2=df2)
for (i in seq_along(ll)) {
chart_it(ll[[i]], names(ll[i]))
}
或者干脆
purrr::iwalk(ll, chart_it)
还有imap
和lmap
,但它们会在控制台中留下一些输出,我想这不是您想要做的。我假设您希望在最后看到两个名为df1.png
和df2.png
的文件
您需要以某种方式将数据帧的名称传递给函数。一种方法是通过命名列表,将名称与列表元素的内容一起传递
library(ggplot2)
library(purrr)
df1 <- tibble(
a = rnorm(10),
b = rnorm(10)
)
df2 <- tibble(
a = rnorm(20),
b = rnorm(20)
)
chart_it <- function(x, nm) {
p <- x %>% ggplot() +
geom_line(mapping = aes(y=a,x=b))
ggsave(paste0(nm,".png"), p, device = "png")
}
ll <- list(df1=df1,df2=df2)
for (i in seq_along(ll)) {
chart_it(ll[[i]], names(ll[i]))
}
或者干脆
purrr::iwalk(ll, chart_it)
还有imap
和lmap
,但它们会在控制台中留下一些输出,我想这不是您想要做的。谢谢您的回复。如果我运行chart_it(df1)
它会保存绘图,那么这不意味着我的函数正常吗?尝试了以下chart_it%ggplot()+geom_line(mapping=aes(y=a,x=b))+ggsave(paste0(替换(x),“.png”)->图表返回(chart)}
我得到“错误:device
必须为NULL,字符串或函数。”感谢您的回复。如果我运行chart\u it(df1)
它会保存绘图,那么这不意味着我的函数正常吗?尝试了以下chart\u it%ggplot()+geom\u line(mapping=aes(y=a,x=b))+ggsave(paste0(替换(x),“.png”)->图表返回(chart)}
我得到“错误:设备
必须为NULL,字符串或函数。”这很完美。非常感谢:)这很完美。非常感谢:)