问题描述
我试图用 lattice
绘制一个图,其中点颜色和形状都根据数据中的变量而变化。当我自己设置 col
和 pch
值并且不要将 panel.xyplot
放在 ifelse
语句中时,这很好用:
#Setup
library(cluster)
library(lattice)
xyplot(V8 ~ V7,data = flower,V8_var = flower$V8,panel = function(x,y,...,V8_var,subscripts) {
col <- ifelse(V8_var[subscripts] < 50,'blue','orange')
pch <- ifelse(V8_var[subscripts] < 50,2,6)
panel.xyplot(x,type='p',col = col,pch = pch)
})
但是,当我在 panel.xyplot
或 ifelse
循环中使用 if
时,这不起作用:
xyplot(V8 ~ V7,'orange')
ifelse(
V8_var[subscripts] < 50,panel.xyplot(x,pch = 2),pch = 6)
)
})
xyplot(V8 ~ V7,'orange')
if(V8_var[subscripts] < 50){
panel.xyplot(x,pch = 2)
} else {
panel.xyplot(x,pch = 6)
}
})
使用 if
语句也会给出警告:
Warning message:
In if (V8_var[subscripts] < 50) { :
the condition has length > 1 and only the first element will be used
解决这个问题的方法是通过 if
或 ifelse
语句获取变量值,然后将它们插入任何 panel.xyplot
语句之外的 if
,但我这样做不明白当 ifelse
在其中时,为什么 panel.xyplot
语句不能像我预期的那样工作?
会话信息:
R version 4.0.2 (2020-06-22)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Mojave 10.14.6
Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRlapack.dylib
locale:
[1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] lattice_0.20-41 cluster_2.1.0
loaded via a namespace (and not attached):
[1] compiler_4.0.2 tools_4.0.2 grid_4.0.2
解决方法
panel.xyplot 不能是 ifelse 的参数。以与代码计算col相同的方式计算pch:
library(cluster)
library(lattice)
xyplot(V8 ~ V7,data = flower,V8_var = flower$V8,panel = function(x,y,...,V8_var,subscripts) {
col <- ifelse(V8_var[subscripts] < 50,'blue','orange')
pch <- ifelse(V8_var[subscripts] < 50,2,6)
panel.xyplot(x,type='p',col = col,pch = pch)
})
尽管在这种情况下您甚至不需要面板功能:
xyplot(V8 ~ V7,col = ifelse(flower$V8 < 50,"blue","orange"),pch = ifelse(flower$V8 < 50,6))