我有一个类似于内置 InsectSprays 的数据框(带有因子和数字数据),但它包含 10+ 数字和 20+ 因子向量,NA 很少。当我使用 boxplot(numeric ~ factor) 时,我注意到某些级别很突出,我希望能够将它们与其他级别进行比较。
例如:InsectSprays 包含一个名为 count (0:26) 的数字向量,以及一个名为 Sprays 的因子向量,级别为:A、B、C、D、E 和 F。在 InsectSprays 中,C 最低,所以我想 cbe能够将 C 与所有其他 C 进行比较。
我为这样的数字向量写了一个函数:
num_interlevel <- function(df, variable, category){
#find the levels of the categorizing parameter
level.list <- levels(category)
#build enough columns in the plot area
par(mfrow=c(1,length(level.list)))
for(i in 1:length(level.list)){
#subset the df containing only the level in question
variable.df <- na.omit(df[which(category == level.list[i]),])
#subset the df containing all other levels
category.df <- na.omit(df[which(category != level.list[i]),])
boxplot(variable.df[, variable], category.df[, variable])
p <- t.test(variable.df[, variable], category.df[, variable])$p.value
title(paste(level.list[i], "=", p))
}
}
并num_interlevel(InsectSprays, "count", InsectSprays$spray)
给我想要的结果。
但是在比较因子向量时(我为此使用了表格),它不起作用,仅仅是因为数据框的大小不同,更重要的是,因为这是一种错误的方式。
然后我认为可能有一个现有的功能,但找不到任何功能。谁能建议一种方法/功能来创建一个包含一个级别的子集和另一个包含所有其他级别的子集?
#dput:
structure(list(Yas = c(27, 18, 17, 18, 18), Cinsiyet = structure(c(2L,
2L, 2L, 1L, 1L), .Label = c("Erkek", "Kadın"), class = "factor"),
Ikamet = structure(c(5L, 4L, 3L, 3L, 5L), .Label = c("Aileyle",
"Akrabayla", "Arkadaşla", "Devlet yurdu", "Diğer", "Özel yurt",
"Tek başına"), class = "factor"), Aile_birey = c(13, 9, 6,
10, 6), Aile_gelir = c(700, 1000, 1500, 600, 800)), .Names = c("Yas",
"Cinsiyet", "Ikamet", "Aile_birey", "Aile_gelir"), row.names = c(NA,
5L), class = "data.frame")
编辑
在詹姆斯的回答之后,我改革了我的职能。这当然不是一个优雅的解决方案,但我把它放在这里以供将来参考:
n.compare <- function(df, variable, category){
level.list <- levels(df[,category])
par(mfrow=c(1,length(level.list)))
for(i in 1:length(level.list)){
boxplot(df[,variable] ~ (df[,category] == level.list[i]))
p <- t.test(df[,variable] ~ (df[,category] == level.list[i]))$p.value
title(paste(level.list[i], "=", p))
}
}
f.compare <- function(df, variable, category){
level.list <- levels(df[,category])
par(mfrow=c(1,length(level.list)))
for(i in 1:length(level.list)){
print(paste(level.list[i]))
print(table((df[,category] == level.list[i]), df[,variable]))
writeLines("\n")
}
}