与R中的情节不一致的结果

时间:2013-04-13 17:15:40

标签: r charts plot

我正在试验R中的情节,我试图理解为什么它有以下行为。

我将一个表发送到绘图函数中,它给了我一个非常好的变量图,非常有见地。但是,在我重新排序表的列并将其再次发送到绘图后,我得到一个奇怪的散点图。在重新排序中发生了什么,我该如何避免这种情况?

smoke <- matrix(c(51,43,22,92,28,21,68,22,9),ncol=3,byrow=TRUE)
colnames(smoke) <- c("High","Low","Middle")
rownames(smoke) <- c("current","former","never")
smoke <- as.table(smoke)
plot(smoke)  # This gives me a variwidth plot
smoke = smoke[,c("Low", "Middle", "High")] # I reorder the columns
plot(smoke)  # This gives me a weird scatter plot

2 个答案:

答案 0 :(得分:5)

调查此问题的方法是对两个“smoke”实例执行str():

> str(smoke)
 table [1:3, 1:3] 51 92 68 43 28 22 22 21 9
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:3] "current" "former" "never"
  ..$ : chr [1:3] "High" "Low" "Middle"

> str( smoke[,c("Low", "Middle", "High")] )
 num [1:3, 1:3] 43 28 22 22 21 9 51 92 68
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:3] "current" "former" "never"
  ..$ : chr [1:3] "Low" "Middle" "High"

第一个是表对象,而第二个是矩阵。您也可以在两者上完成class()并获得更紧凑的答案。要了解为什么这很重要,请查看

methods(plot) 

....并且看到有plot.table*方法。 '*'表示它不是“可见的”,您需要查看需要使用的代码:

getAnywhere(plot.table)

正如Ananda所示,您可以将表类恢复为该烟雾对象,然后让调度系统将对象发送到plot.table*

答案 1 :(得分:4)

当您重新排序列时,您将“smoke”类从“table”更改为“matrix”,因此plot会根据其输入返回不同的默认结果,返回不同的图。

尝试:

plot(as.table(smoke))
相关问题