你有一个数据框。如何最好地检查特定列的值的所有组合是否经常发生?
(当处理来自具有因子设计的实验的数据文件时,有时需要这样做。每列是一个独立变量,我们想要检查所有独立变量的组合是否经常出现。)
答案 0 :(得分:1)
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
从?replications
我们有一个平衡测试:
!is.list(replications(~ supp + dose, data = tmp))
> !is.list(replications(~ supp + dose, data = tmp))
[1] TRUE
来自replications()
的输出并不是您所期望的,但使用它的测试会给出您想要的答案。
答案 1 :(得分: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
答案 2 :(得分: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
是否相等或者您喜欢的其他内容。