【问题标题】:Generate several multiplots using two dataframes with the same column names in R使用 R 中具有相同列名的两个数据框生成多个多图
【发布时间】:2015-01-22 10:31:10
【问题描述】:

我有两个具有相同列名的数据框(data1 和 data2),分别称为 A、B、C、D、G、F、G、H、...。 我想通过组合不同的列来创建几个图,其中包含 data1 和 data2 的图。这样我就可以将函数称为:

getPlot(data1, data2, A, B, C, D)
getPlot(data1, data2, B, F, G, H)
getPlot(data1, data2, A, C, F, B)

...

以及任何列组合。

我这样写函数:

getPlot = function(df1, df2, M1, M2, M3, M4){
   png(file=paste("",M1,"",M2,"vs",M3,"",M4,"_plot.png", sep=""), width=800, height=800 )

   plot(df1$M1-df1$M2, df1$M3-df1$M4, xlab = M1-M2, ylab = M3-M4, type="p", pch=20, cex=0.5, col="red")

   points(df2$M1-df2$M2, df2$M3-df2$M4, type="p", pch=20, cex=0.5, col="red")

   dev.off()
}

但问题是我使用列名调用函数

 getPlot(data1, data2, A, B, C, D)

因此,由于它们不是现有变量,getPlot 无法理解我想要得到什么......因此,例如,df1$M1 对他来说没有任何意义......

我怎样才能获得具有不同列组合的不同图?

【问题讨论】:

标签: r


【解决方案1】:

使用此功能:

getPlot = function(df1, df2, M1, M2, M3, M4)
{
png(file=paste("",M1,"",M2,"vs",M3,"",M4,"_plot.png", sep=""), width=800, height=800 )

plot(df1[[M1]]-df1[[M2]], df1[[M3]]-df1[[M4]], xlab = paste0(M1,"-",M2), ylab = paste0(M3,"-",M4), type="p", pch=20, cex=0.5, col="red")

points(df2[[M1]]-df2[[M2]], df2[[M3]]-df2[[M4]], type="p", pch=20, cex=0.5, col="red")
dev.off()
} 

然后这样称呼它:

getPlot(data1, data2, "A", "B", "C", "D")

这里,M1M2 是字符串,我们使用以下事实:

 data1$A

data1[["A"]]

是访问Adata1 列的两种方式。

【讨论】:

  • 谢谢,这行得通!但是在您的函数中,您必须在 ylab 表达式的末尾添加一个“)”:ylab = paste0(M3, "-", M4)。由于 M1、M2、M3、M4 它们已经是字符串,在函数中我们必须将列称为:df1[[M1]] 没有“”。如果您在帖子中更正此问题,我将选择它作为正确答案。再次感谢!
  • 非常感谢!是的,我错过了那些。我已经更正了。
猜你喜欢
  • 2023-03-25
  • 1970-01-01
  • 2013-12-08
  • 2021-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-26
  • 1970-01-01
相关资源
最近更新 更多