我正在试验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
Run Code Online (Sandbox Code Playgroud)
调查这个的方法是对两个"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"
Run Code Online (Sandbox Code Playgroud)
第一个是表对象,而第二个是矩阵.您也可以在两者上完成class()并获得更紧凑的答案.要理解为什么这很重要也要看
methods(plot)
Run Code Online (Sandbox Code Playgroud)
....并且看到有一种plot.table*方法.'*'表示它不是"可见的",您需要查看需要使用的代码:
getAnywhere(plot.table)
Run Code Online (Sandbox Code Playgroud)
正如Ananda所示,您可以将表类还原到该smoke对象,然后让调度系统将对象发送到plot.table*.