Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R:在数据框中定义因子的级别_R_Dataframe_Apply_R Factor - Fatal编程技术网

R:在数据框中定义因子的级别

R:在数据框中定义因子的级别,r,dataframe,apply,r-factor,R,Dataframe,Apply,R Factor,假设您有一个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) 目标是使V3和V4兼容,以便操作有效。

假设您有一个
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)
目标是使V3和V4兼容,以便操作有效。一种选择是:

dat$V3<-factor(dat$V3,levels=c('1','2','3','4','5','9')

试试这个来协调水平

#  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 
#获取data.frame中显示的所有级别的向量

levs+1是一个可复制的例子,也是你尝试过的。我完全同意+谢谢,非常感谢,伙计们!谢谢我发现关键在于使用
lappy
而不是
apply
,因为
data.frame
是一个
列表
。答案不错,复制粘贴到我的一小堆有用的代码片段中+1.@tomka完全正确!很高兴我能帮忙。
dat[,3:4]<-apply(dat[,3:4],2,factor,levels=c('1','2','3','4','5','9'))
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