Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.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_R Factor - Fatal编程技术网

R 在没有数据帧的情况下跟踪因子水平

R 在没有数据帧的情况下跟踪因子水平,r,r-factor,R,R Factor,免责声明:这个项目是从别人的代码开始的,我肯定会有一些非最佳设计决策,但我的手比我自己的项目更紧 我有一个机器学习算法,它使用经过训练的模型对象和一组评分数据来创建评分数据的数据框架。模型对象是一个包含公式和数据框的列表 模型数据框架的作用之一是确保评分数据框架具有与模型预期相同的列,并且这些列的因子水平相同。为了实现这一点,我们在模型$df(数据帧)中存储一行任意的训练数据,因为没有行的数据帧被强制没有因子级别。然后我们使用有点笨拙的线条 scoring.set$df <- rbind(

免责声明:这个项目是从别人的代码开始的,我肯定会有一些非最佳设计决策,但我的手比我自己的项目更紧

我有一个机器学习算法,它使用经过训练的模型对象和一组评分数据来创建评分数据的数据框架。模型对象是一个包含公式和数据框的列表

模型数据框架的作用之一是确保评分数据框架具有与模型预期相同的列,并且这些列的因子水平相同。为了实现这一点,我们在
模型$df
(数据帧)中存储一行任意的训练数据,因为没有行的数据帧被强制没有因子级别。然后我们使用有点笨拙的线条

scoring.set$df <- rbind(model$df, scoring.set$df)[-1, ]
评分。设置$df创建样本数据集

set.seed(23452)

##create 5 variables with 15 levels and 5 variables with 20 levels
nrowd <- 100
full <- data.frame(
    replicate(5,letters[sample(sample(1:24,15),nrowd,replace=TRUE) ]),
    replicate(5,LETTERS[sample(sample(1:24,20),nrowd,replace=TRUE) ])
)

###the following code represents a process that creates a dataframe with variables 
###that have no more levels than full but may have fewer levels
scoring.set <- data.frame(sapply(full[sample(1:nrow(full),10),],as.character))

#factor levels are not the same
identical(sapply(full,levels),sapply(scoring.set,levels))

引入非因子变量会使事情复杂化,但总体思路是通过
factor.vars将因子变量子集为仅因子变量。我的想法是,有某种方法可以存储具有所需因子级别的变量列表,但是我还没能想出它。这行代码并没有让我觉得特别笨拙——特别是在代码行方面,它是有效的。你可以将这些级别保留为向量列表-这样会更好吗?好的,谢谢!我猜这不是线本身,而是数据帧的存储,只是为了它的因子级别。无法决定是否需要重新构造代码。您的第一个测试看起来是重复的。如果您的意思是:
相同(as.character(完整)、as.character(scoring.set2))
。。。。它返回FALSE。
##make it so the levels of scoring.set variables have the levels of full
scoring.set2 <- data.frame(
    mapply(scoring.set,lapply(full,levels), SIMPLIFY=FALSE,
       FUN=function(scoring.var, full.level){     
        factor(scoring.var, levels=union(full.level,levels(scoring.var))) 
     }) 
)
all(
    mapply(scoring.set,scoring.set2, FUN=function(x,y){
        identical(as.character(x),as.character(y))
    })
)

    identical(sapply(full,levels),sapply(scoring.set2,levels))