繁体   English   中英

使用lapply从数据表创建多个格子图

[英]Create multiple lattice plots from a data table using lapply

我试图为每个变量(种类)按组生成平均值,然后分别绘制每个变量。 我尝试过列表和数据表格式。 基本绘图功能在for循环中工作:

library(data.table)

      for (i in 3:5) {
      # generate a list of mean value for the species in column number i
      temp <- v2[, lapply(.SD, mean), by="Season", .SDcols=i]
      # plot each col of the list as a scatterplot with main title = header of 2nd col
      plot(temp[[2]]~temp[[1]], main = colnames(temp)[[2]])
    }

但是当我尝试创建晶格图时,最后一个变量仅生成一个图:

library(data.table)
library(lattice)

for (i in 3:5) {
  # generate a list of mean value by season for the species in column number i
  temp <- v2[, lapply(.SD, mean), by=c("Season", "Location"), .SDcols=i]
  # Each group in a separate mini plot
  xyplot(temp[[3]]~temp[[1]] | temp[[2]], main = colnames(temp)[3])
}

尝试保存或打印每个格子图,这是正确的想法吗? 也许我完全是用错误的方式来解决这个问题?

这是我的数据的一小部分样本:

    structure(list(Location = structure(c(1L, 1L, 1L, 1L, 4L, 4L, 
4L, 6L, 6L, 1L), .Label = c("BN", "BS", "GN", "GS", "SB", "SL"
), class = "factor"), Season = c(1981L, 1981L, 1981L, 1981L, 
1995L, 1995L, 1995L, 1997L, 1997L, 2000L), Agrostis.magellanica = c(0.3, 
0.3, 0.3, 0.01, 0.6, 0.3, 0.3, 0.3, 0.6, 0.05), Festuca.contracta = c(0.6, 
0.05, 0.3, 0.01, 0.01, 0, 0, 0, 0.01, 0.05), Poa.annua = c(0.01, 
0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.05, 0.01, 0.01)), .Names = c("Location", 
"Season", "Agrostis.magellanica", "Festuca.contracta", "Poa.annua"
), class = c("data.table", "data.frame"), row.names = c(NA, -10L
)

这在R-FAQ中。 在函数内部使用时,需要围绕网格图形(格子或ggplot)的print语句,而for循环是一个函数:

# Needed
require(data.table)  # before defining the object.

pdf()  # pdf is a multipage device.
for (i in 3:5) {
  # generate a list of mean value by season for the species in column number i
  temp <- v2[, lapply(.SD, mean), by=c("Season", "Location"), .SDcols=i]
  # Each group in a separate mini plot
  print( xyplot(temp[[3]]~temp[[1]] | temp[[2]], main = colnames(temp)[3]) )
}
dev.off()  # Failing to properly close a file graphics device is common error.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM