绘制列表包含许多带有R的列表

时间:2016-09-10 13:21:01

标签: r list plot

我有一个这样的列表,$ 1081786081以上的数字是用户ID,我想根据时间绘制day_count。

如果它是数据框,那么很容易做到这一点

plot(list4$day_count)

但我不知道如何为每个名单做这件事。我应该使用lapply吗?

$`1081786081`
         time day_count
1  2016-01-13         2
2  2016-01-20         2
3  2016-02-06         2
4  2016-02-23         2
5  2016-03-14         2
6  2016-03-24         2
7  2016-04-06         2
8  2016-04-11         2
9  2016-05-04         2
10 2016-06-06         2
11 2016-06-26         2
12 2016-07-01         2

$`1087949661`
         time day_count
1  2016-01-02         4
2  2016-01-11         2
3  2016-01-20         2
4  2016-01-21         6
5  2016-01-22         2
6  2016-01-27         4
7  2016-01-30         4
8  2016-02-02         2
9  2016-02-05         2

1 个答案:

答案 0 :(得分:1)

如果我们需要在单个list中为data.frame pdf绘制每个绘图的单独页面,在设置输出.pdf之后,我们将遍历'list4'和plot

pdf("yourplot.pdf")
invisible(lapply(list4, function(x) with(x, plot(time, day_count))))
dev.off()

我们还可以通过循环plot元素的names来为每个list创建一些标识符

pdf("yourplot.pdf")
invisible(lapply(names(list4), function(nm) with(list4[[nm]],
             plot(time, day_count, main = paste("plot of", nm)))))
dev.off()

如果我们需要包含一行的单个图,我们可以rbind list元素,然后执行plot ting。

library(dplyr)
library(ggplot2)
bind_rows(list4, .id = "grp") %>%
       ggplot(., aes(x=time, y = day_count, colour = grp)) + 
       geom_line() +
       geom_point()

数据

list4 <- structure(list(`1081786081` = structure(list(time = structure(c(16813, 
16820, 16837, 16854, 16874, 16884, 16897, 16902, 16925, 16958, 
16978, 16983), class = "Date"), day_count = c(2L, 2L, 2L, 2L, 
 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L)), .Names = c("time", "day_count"
), row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", 
"10", "11", "12"), class = "data.frame"), `1087949661` = structure(list(
time = structure(c(16802, 16811, 16820, 16821, 16822, 16827, 
16830, 16833, 16836), class = "Date"), day_count = c(4L, 
2L, 2L, 6L, 2L, 4L, 4L, 2L, 2L)), .Names = c("time", "day_count"
), row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9"), 
class = "data.frame")), .Names = c("1081786081", 
"1087949661"))