4

I'm experimenting with plot in R and I'm trying to understand why it has the following behaviour.

I send a table into the plot function and it gives me a very nice variwidth graph which is quite insightful. However, after I reorder the columns of the table and send it to plot again, I get an odd scatter plot. What has happened in the re-ordering and how can I avoid this?

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
4

2 回答 2

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*.

于 2013-04-13T17:28:09.650 回答
4

当您对列重新排序时,您将“烟雾”类从“表”更改为“矩阵”,因此根据输入返回不同默认结果的绘图返回了不同的绘图。

尝试:

plot(as.table(smoke))
于 2013-04-13T17:21:06.903 回答