因子、水平和原始值
我想将变量 f
写入现有矩阵 m
的某些元素(index
)。让我们假设 f
是一个因素:
f <- factor(c(3,3,0,3,0))
m <- matrix(NA, 10, 1)
index <- c(1,4,5,8,9)
Using
m[index] <- f
不会给出所需的结果,因为它将标签('1' 和 '2')放入 m
中,而不是原始值( “0”和“3”)。所以我就用
m[index] <- as.numeric(levels(f))[f]
它来代替,效果很好。
但在我的情况下, f
并不总是一个因素,但也可以是数字,例如
f <- c(3.43, 4.29, 5.39, 7.01, 7.15)
我是否必须检查它
if ( is.factor(f) ) {
m[index] <- as.numeric(levels(f))[f]
} else {
m[index] <- f
}
,或者是否有一种“通用”方法来放置 的“真实”值f
转换为矩阵 m
,与 f
的类型无关?
提前致谢!
PS:背景是f
是f <-predict(mymodel, Xnew)
的结果,其中model
是由以下方法训练的SVM模型model <- svm(Xtrain, Ytrain)
可以是分类模型(然后 f
是因子)或回归模型(然后 f
code> 是数字)。我确实知道模型的类型,但上面的 if 子句对我来说似乎有点不方便。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么不这样做:首先将
f
(可以是数字或因子)转换为字符,然后转换为数字:Why not just do this: first convert
f
(which could be numeric or factor) to character, then to numeric:矩阵的类型不能是“因子”:您必须单独处理因子。
最简单的可能是将它们转换为字符串。
The type of a matrix cannot be "factor": you will have to treat factors separately.
The easiest may be to convert them to strings.