如何将因子的一个级别与R中的所有剩余级别进行比较
我有一个数据帧,类似于内置的INSTETSPRAYS(带有因子和数值数据),但它包含10+数值和20+因子向量,很少有NAs。当我使用箱线图(数值~因子)时,我注意到一些级别非常突出,我希望能够将它们与其他级别进行比较 例如:InsectSprays包含一个名为count(0:26)的数字向量,以及一个名为sprays的因子向量,其级别为:a、B、C、D、E和F。在InsectSprays中,C是最低的,因此我希望cbe能够将C与所有其他变量进行比较 我为这些数字向量编写了一个函数:如何将因子的一个级别与R中的所有剩余级别进行比较,r,subset,levels,R,Subset,Levels,我有一个数据帧,类似于内置的INSTETSPRAYS(带有因子和数值数据),但它包含10+数值和20+因子向量,很少有NAs。当我使用箱线图(数值~因子)时,我注意到一些级别非常突出,我希望能够将它们与其他级别进行比较 例如:InsectSprays包含一个名为count(0:26)的数字向量,以及一个名为sprays的因子向量,其级别为:a、B、C、D、E和F。在InsectSprays中,C是最低的,因此我希望cbe能够将C与所有其他变量进行比较 我为这些数字向量编写了一个函数: num_i
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))
}
}
编辑
在詹姆斯的回答之后,我改革了我的功能。这当然不是一个优雅的解决方案,但我把它放在这里供将来参考:
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")
}
}
n.compare要拆分数据帧,请使用split
:
lapply(split(InsectSprays,InsectSprays$spray=="A"),summary)
$`FALSE`
count spray
Min. : 0.00 A: 0
1st Qu.: 3.00 B:12
Median : 5.00 C:12
Mean : 8.50 D:12
3rd Qu.:13.25 E:12
Max. :26.00 F:12
$`TRUE`
count spray
Min. : 7.00 A:12
1st Qu.:11.50 B: 0
Median :14.00 C: 0
Mean :14.50 D: 0
3rd Qu.:17.75 E: 0
Max. :23.00 F: 0
也考虑如下:
boxplot(count~(spray=="A"),InsectSprays)
请使用dput
函数在问题中包含您的数据的一个小示例。您能否详细说明“相互比较因子向量”的含义?例如,鉴于上述数据,您希望结果是什么?@Victor K.很抱歉下面的最后一条评论。我发现表函数已经在一个地方通过比例提供了我所需要的一切。老实说,你的箱线图解决方案至少比我的更优雅。然而,尽管有这样的见解,我仍然在努力比较因子向量。问题可能源于我对R还不太熟悉(甚至不知道split)。那么,该表还有其他提示吗?@barerd用于比较平均值,例如:sapply(levels(InsectSprays$spray)、函数(x)lappy(split(InsectSprays,InsectSprays$spray==x)、函数(y)mean(y$count))
boxplot(count~(spray=="A"),InsectSprays)