我正在使用 Sleuth2 库中的 ex0622 数据
library(Sleuth2)
library(lattice)
attach(ex0622)
#Using the 'rep()' function to create a vector for the sexual preference variable ('Hetero' or 'Homo')
sex.pref=as.factor(c(rep("Hetero", 16), rep("Homo", 19), rep("Hetero", 6)))
#Using the 'rep()' function to create a vector for the Type of Death variable ('AIDS' or 'Non-AIDS')
death.type=c(rep("Aids",6), rep("Non-Aids",10), rep("Aids", 19), "Aids", rep("Non-Aids", 5))
#creating a vector of gender variable
gender=(c(rep("Male", 35), rep("Female", 6)))
length(death.type)
ex0622_alt=as.data.frame(cbind(ex0622, gender, sex.pref, death.type))
ex0622_alt
我运行前面的代码以向数据集添加一些因素。然后我想用lattice包显示某些变量组合
histogram(~Volume[sex.pref=="Hetero"]|gender, data=ex0622_alt, main="Heterosexuals")
dotplot(Volume[sex.pref=="Hetero"]~gender, col=1)
这两种尝试都会产生性别和性别.pref因素的空组合,而它们不应该产生这种组合。我不知道发生了什么事。
如有任何帮助,我们将不胜感激!
谢谢!
最佳答案
您的问题出在 histogram
调用中:在 ex0622_alt
数据框中,您将 Volume
变量子集为 sex.pref == "Hetero"
,但您根本没有对 gender
变量进行子集化,因此 Volume
子向量并且 gender
变量的长度不同,因此结果会很奇怪。如果您这样做,它就会起作用:
histogram(~Volume[sex.pref=="Hetero"] |
gender[sex.pref=='Hetero'], data=ex0622_alt, main="Heterosexuals")
或者您可以只使用subset
arg,这会更自然:
histogram(~Volume | gender,
data = ex0622_alt, subset = sex.pref == 'Hetero', main="Heterosexuals")
相同的注释(和修复)适用于 dotplot
命令。
关于R问题。绘制响应时出现无法解释的空因子组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5053941/