1

你有一个数据框。如何最好地检查特定列的值的所有组合是否同样频繁地出现?

(在使用因子设计处理来自实验的数据文件时,有时需要这样做。每一列都是一个自变量,我们要检查自变量的所有组合是否同样频繁地出现)。

4

3 回答 3

1

What about replications()?

tmp <- transform(ToothGrowth, dose = factor(dose))

replications( ~ supp + dose, data = tmp)
replications( ~ supp * dose, data = tmp)

> replications( ~ supp + dose, data = tmp)
supp dose 
  30   20 
> replications( ~ supp * dose, data = tmp)
     supp      dose supp:dose 
       30        20        10

And from ?replications we have a test for balance:

!is.list(replications(~ supp + dose, data = tmp))

> !is.list(replications(~ supp + dose, data = tmp))
[1] TRUE

The output from replications() isn't quite what you might expect, but the test shown using it gives the answer you want.

于 2013-06-19T22:35:23.743 回答
0
checkAllCombosOccurEquallyOften<- function(df,colNames,dropZeros=FALSE) {
    #in data.frame df, check whether the factors in the list colNames reflect full factorial design (all combinations of levels occur equally often)
    #
    #dropZeros is useful if one of the factors nested in the others. E.g. testing different speeds for each level of    
    # something else, then a lot of the combos will occur 0 times because that speed not exist for that level.
    #but it's dangerous to dropZeros because it won't pick up on 0's that occur for the wrong reason- not fully crossed
    #
    #Returns:
    # true/false, and prints informational message
    #
    listOfCols <- as.list( df[colNames] )
    t<- table(listOfCols)

    if (dropZeros) {  
        t<- t[t!=0]   
    }           
    colNamesStr <- paste(colNames,collapse=",")
    if ( length(unique(t)) == 1 ) { #if fully crossed, all entries in table should be identical (all combinations occur equally often)
          print(paste(colNamesStr,"fully crossed- each combination occurred",unique(t)[1],'times'))
          ans <- TRUE
      } else {
          print(paste(colNamesStr,"NOT fully crossed,",length(unique(t)),'distinct repetition numbers.'  ))
          ans <- FALSE
      } 
    return(ans)
}

加载数据集并调用上述函数

library(datasets)
checkAllCombosOccurEquallyOften(ToothGrowth,c("supp","dose")) #specify dataframe and columns

输出提供了完全交叉的答案:

[1] "supp,dose fully crossed- each combination occurred 10 times"
[1] TRUE
于 2013-06-19T07:56:14.607 回答
0

使用相同的ToothGrowth数据:

library(datasets)
library(data.table)

dt = data.table(ToothGrowth)

setkey(dt, supp, dose)
dt[CJ(unique(supp), unique(dose)), .N] # note: using hidden by-without-by
#   supp dose  N
#1:   OJ  0.5 10
#2:   OJ  1.0 10
#3:   OJ  2.0 10
#4:   VC  0.5 10
#5:   VC  1.0 10
#6:   VC  2.0 10

然后,您可以检查所有N' 是否相等或您喜欢的任何其他内容。

于 2013-06-19T15:18:04.663 回答