假设您有一个data.frame
具有多个因素的因素,这些因素具有不同级别的数量:
V1<-factor(sample(c(1:5,9),100,TRUE))
V2<-factor(sample(c(1:5,9),100,TRUE))
V3<-factor(sample(c(1:5),100,TRUE))
V4<-factor(sample(c(1:5),100,TRUE))
dat<-data.frame(V1,V2,V3,V4)
目的是估计两个因素在电平频率上的差异。但是,由于级别数不同,基于V1 / V2和V3 / V4的两个表中的数组不一致,例如:
table(dat$V1)-table(dat$V3)
Error in table(dat$V1) - table(dat$V3) : non-conformable arrays
目的是使V3和V4兼容,以便该操作有效。一种选择是:
dat$V3<-factor(dat$V3,levels=c('1','2','3','4','5','9')
但是,这需要为每个变量设置因子水平,这对于许多变量V5,...,Vn来说是不切实际的。我想
dat[,3:4]<-apply(dat[,3:4],2,factor,levels=c('1','2','3','4','5','9'))
可能以更笼统的方式工作,但is.factor(dat$V3)
那时为假。
编辑:此功能可能会完成SimonO101的答案:
correct_factors<-function(df_object,range){
if(is.data.frame(df_object)==FALSE){stop('Requires data.frame object')}
levs <- unique( unlist( lapply( df_object[,range[1]:range[2]] , levels ) ) )
df_object[,range[1]:range[2]] <-
data.frame( lapply( df_object[,range[1]:range[2]] , factor , levels = levs ) )
return(df_object)
}
试试这个来协调水平...
# Get vector of all levels that appear in the data.frame
levs <- unique( unlist( lapply( dat , levels ) ) )
# Set these as the levels for each column
dat2 <- data.frame( lapply( dat , factor , levels = levs ) )
table(dat2$V1)-table(dat2$V3)
# 1 2 3 4 5 9
#-15 -5 4 7 -5 14
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句