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.
Why not just do this: first convert
f(which could be numeric or factor) to character, then to numeric: