【问题标题】:R, mapply , ggplot : EXPR must be a length 1 vectorR, mapply , ggplot : EXPR 必须是长度为 1 的向量
【发布时间】:2015-03-09 18:36:01
【问题描述】:

我正在尝试使用 ggplot 和 gridExtra 绘制表格的子集。 但是我遇到了以下错误 EXPR must be a length 1 vector.

我可以想出任何辅助步骤。任何帮助都会很有用。

这是我正在尝试执行的一个小例子:

# the table
dt1 <- data.table(parkName=rep(c("Zone A","Zone B", "Zone C" ,
"Zone D"),5), boundary=rep(0:1,10),v=1:20, w=rnorm(20))[]

# criteria for subsetting the table
dt2 <- data.table(zone1 = c("Zone A","Zone B"), zone2 =c("Zone B","Zone C"))

# function for subsetting the table and plotting
p <- function(sd1,sd2){
dlist <- dt1[parkName==sd1 | parkName==sd2]    

b <- dt1[parkName %in% dlist]
a <- ggplot(
       b,
       aes(v,w)) + geom_line()
return(a)
}

mplot <- mapply(p,dt2[,zone1],dt2[,zone2])
cairo_pdf("myplot1.pdf")
do.call(marrangeGrob, c(mplot, list(nrow=2, ncol=2)))
dev.off()

# results
Error in switch(ct, ggplot = ggplotGrob(grobs[[ii.table]]), trellis =
 latticeGrob(grobs[[ii.table]]),  : EXPR must be a length 1 vector

【问题讨论】:

  • 没有运行您的代码,但 dt1[parkName==sd1 &amp; parkName==sd2] 看起来有点可疑,因为您要求 parkName 是 sd1 sd2 - 也许你的意思是 或我> 而不是?然后你可以使用dt1[parkName %in% c(sd1, sd2)]
  • 我的错误谢谢。我的意思是dt1[parkName==sd1 | parkName==sd2]

标签: r ggplot2 gridextra mapply


【解决方案1】:

改变

mplot <- mapply(p,dt2[,zone1],dt2[,zone2])

mplot <- mapply(p,dt2[,zone1],dt2[,zone2], SIMPLIFY=FALSE)

mplot <- Map(p,dt2[,zone1],dt2[,zone2])

mapply() 如果返回对象的尺寸匹配,将尝试将其结果强制转换为矩阵,但是,在这种情况下,您将始终需要一个列表。您可以将SIMPLIFY= 参数设置为false,或者使用始终返回列表的Map()

【讨论】:

  • 谢谢,我会记住的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-08
  • 2021-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多