R问题。绘制响应时出现无法解释的空因子组合

标签 r histogram lattice

我正在使用 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/

相关文章:

r - x 轴为周数,次要 x 轴为日期

r - 仅将括号与 R 中的文本和数字匹配

Python Matplotlib 直方图 bin 移位

numpy - numpy中对数对数直方图的线性回归

R格子: Change panel title layout

r - 线框图(格子包)中的负长度向量意味着什么?

rbind 多个数据集

r - 基于更平等条件的不精确连接数据

math - 直方图匹配-图像处理-c/c++

r - 如何将绘图保存为磁盘上的图像?