如何将一个因子水平与R中的所有剩余水平进行比较

时间:2013-05-16 16:03:06

标签: r subset levels

我有一个类似于内置InsectSprays的数据框(包含因子和数字数据),但它包含10个数字和20+因子矢量,几乎没有NA。当我的boxplot(数字〜因子)时,我注意到某些级别突出,我希望能够将它们与其余级别进行比较。

作为示例:InsectSprays包含一个名为count(0:26)的数字向量,以及一个名为Sprays的因子向量,其级别为:A,B,C,D,E和F.在InsectSprays中,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)给了我想要的结果。

但是当涉及到将因子向量相互比较时(我使用表格),它不起作用,仅仅因为数据帧的大小不同,更重要的是,因为这是一种错误的方式。 / p>

然后我认为可能有一个现有的功能,但找不到任何功能。 任何人都可以建议一种方法/功能来创建一个只包含一个级别的子集和另一个包含所有其他级别的子集吗?

#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")
  }
}

1 个答案:

答案 0 :(得分:2)

要拆分data.frame,请使用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)