Factor, levels, and original values

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-25 07:49:33

问题


I would like to write variable f into certain elements (index) of an existing matrix m. Let's assume f is a factor:

f <- factor(c(3,3,0,3,0))
m <- matrix(NA, 10, 1)
index <- c(1,4,5,8,9)

Using

m[index] <- f

does not give the desired result as it puts the labels ('1' and '2') into m but not the original values ('0' and '3'). Therefore, I used

m[index] <- as.numeric(levels(f))[f]

instead, which works well.

But in my situation, f is not always a factor but can also be numeric like

f <- c(3.43, 4.29, 5.39, 7.01, 7.15)

Do I have to check it like

if ( is.factor(f) ) {
    m[index] <- as.numeric(levels(f))[f]
} else {
    m[index] <- f
}

or is there a "universal" way of putting the "true" values of f into matrix m, independent of the type of f?

Thanks in advance!

P.S.: The background is that f is the result of f <- predict(mymodel, Xnew) where model is a SVM model trained by model <- svm(Xtrain, Ytrain) and can be either be a classfication model (then f is factor) or a regression model (then f is numeric). I do know the type of the model, but the above if clause seems somewhat unhandy to me.


回答1:


Why not just do this: first convert f (which could be numeric or factor) to character, then to numeric:

m[ index ] <- as.numeric( as.character(f) )



回答2:


The type of a matrix cannot be "factor": you will have to treat factors separately. The easiest may be to convert them to strings.

if(is.factor(f)) {
  m[index] <- as.character(f)
} else {
  m[index] <- f
}


来源:https://stackoverflow.com/questions/8800569/factor-levels-and-original-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!