这可能是PICNIC,但是在尝试构建函数时,我得到的行为比我在控制台中执行操作时的行为要简单。
我正在尝试使用cut2生成一组间隔,并将它们分配给变量以供以后重用。函数外部的使用产生适当的向量,但在函数内部,赋值是以不同的方式强制执行的。我试着在它周围包装as.vector,但这产生了一个char [210]。
谁能告诉我我做错了什么?
谢谢, 斯蒂芬 PS全局分配是这样的,可以修改间隔,并在以后重复使用
设置
library("Hmisc")
library("caret")
# functions in use ----------------------------------------------------------------
# functions for splitting data according to Max Kuhn's preferences in caret vignette, code condensed to save space
splitDataset<-function(dataset=rawdata, nPrimaryKeyCol=1, nOutcomeCol=1) {
end<-as.numeric(ncol(dataset))
stopifnot(is.numeric(nPrimaryKeyCol),nPrimaryKeyCol<=end,is.numeric(nOutcomeCol),nOutcomeCol<=end,(nPrimaryKeyCol+nOutcomeCol)<=end)
predstart<-nPrimaryKeyCol+1
predend<-ncol(dataset)-nOutcomeCol
assign(x="keys",value=dataset[, 0:nPrimaryKeyCol],envir = parent.frame())
assign(x="outcomes",value=dataset[,(predend+1):end],envir = parent.frame())
assign(x="predictors",value=dataset[,predstart:predend], envir = parent.frame())
}
partitionDataset<-function(proportion=0.7){
require("caret")
assign(x="inTrain", value=createDataPartition(outcomes,p=proportion, list=FALSE), envir = parent.frame())
assign(x="trainKeys", value=keys[inTrain], envir = parent.frame())
assign(x="trainPredictors",value=predictors[inTrain,],envir = parent.frame())
assign(x="trainOutcomes", value=outcomes[inTrain],envir = parent.frame())
assign(x="testKeys",value=keys[-inTrain],envir = parent.frame())
assign(x="testPredictors", value=predictors[-inTrain,], envir = parent.frame())
assign(x="testOutcomes",value=outcomes[-inTrain], envir = parent.frame())
assign(x="trainPredictors.Bad", value=subset(trainPredictors,trainOutcomes=="bad"), envir = parent.frame())
}
# this is the problem function
equalFreqBins.derive<-function(characteristic,deriveDataset,g=20){
stopifnot(is.numeric(deriveDataset[,characteristic]),is.numeric(g))
dnam<-paste0("interval.",characteristic)
# this is the assignment
intervals<-cut2(deriveDataset[,characteristic],g,onlycuts=TRUE)
assign(
x=dnam,
value=intervals,
envir=as.environment(".GlobalEnv")
)
# return to make it easier to look at variable
return(str(intervals))
}
# data loadup----------------------------------------------------------------
data(GermanCredit)
GermanCredit$outcome<-GermanCredit$Class
GermanCredit$Class<-NULL
levels(GermanCredit$outcome)<-c("bad","good")
basedata<-GermanCredit
splitDataset(basedata,nPrimaryKeyCol=0,nOutcomeCol=1)
partitionDataset(proportion=0.7)
问题再现
# this is outputting a factor of 210
equalFreqBins.derive(characteristic="Age",deriveDataset=trainPredictors.Bad,g=20)
# this is outputting a num [1:20]
intervals<-cut2(trainPredictors.Bad[,"Age"],g=20,onlycuts=TRUE)
str(intervals)
答案 0 :(得分:1)
cut2
的概要是
cut2(x, cuts, m, g, levels.mean, digits, minmax=TRUE, oneval=TRUE, onlycuts=FALSE)
所以当你打电话时
intervals <- cut2(deriveDataset[,characteristic], g, onlycuts = TRUE)
作为第二个未命名参数的g
变量被视为cuts
参数。解决方案:使用命名参数调用函数:
intervals <- cut2(deriveDataset[,characteristic], g = g, onlycuts = TRUE)