通过数据框子集

时间:2015-07-31 16:34:05

标签: r

我有一个27,538乘29的数据框(NBA_Data)。其中一列称为“月”,有八个月(10月:6月)。我想编写一个函数,按月自动子化该数据框,然后在ggplot2中创建8个绘图对象。我已经离开了我的深度,但我想这些将被存储在一个列表中(“我的情节”)。

我计划为每个绘图对象使用geom_plot来绘制针对Minutes.Played的点数。我不熟悉grid.arrange,但我猜测一旦我有了“我的情节”,我就可以使用它(以某种形式)作为grid.arrange的参数。

我试过了:

empty_list <- list()
    for (cat in unique(NBA_Data$month)){
      d <- subset(NBA_Data, month == cat)
    empty_list <- c(empty_list, d) 
    }

这给出了一个不间断的列表,每个月重复所有29列,长度为261.不太理想,但可行。然后我尝试使用lapply来分割列表,但我搞砸了。

lapply(empty_list, split(empty_list, empty_list$month))

Error in match.fun(FUN) : 
'split(x = empty_list, f = empty_list$month)' is not a function, character or symbol
In addition: Warning message:
In split.default(x = empty_list, f = empty_list$month) :
data length is not a multiple of split variable

有什么建议吗? 谢谢。

1 个答案:

答案 0 :(得分:2)

您可以使用split将数据集分块到列表中:

list <- split(data, data$month)

如果您使用ggplot,也可以使用facet_wrap在一个页面上使用相同的数据制作多个绘图。

library(ggplot2)
ggplot(data, aes(x = PlayerName, y = PPG)) + geom_point() + facet_wrap(~month)
相关问题