所以,我已经断断续续地使用 R 两年了,并一直试图获得矢量化的整个概念。由于我经常处理来自调查的多个响应集中的虚拟变量,因此我认为学习这个案例会很有趣。
这个想法来自 多个回复 至 虚拟变量 (并返回),例如:“在这 8 种不同的巧克力中,您最喜欢哪一种(最多选择 3 种)?”
有时我们将其编码为虚拟变量( 1 表示喜欢“Cote d'Or”的人, 0 表示不喜欢的人),每个选项有 1 个变量,有时作为分类( 1 表示喜欢“Cote d'Or”的人, 2 表示喜欢“Lindt”的人,等等),有 3 个变量用于 3 个选择。
所以,基本上我可以得到一个矩阵,线条就像
1,0,0,1,0,0,1,0
或者像这样的线的矩阵
1,4,7
如前所述,这个想法是从一个到另一个。到目前为止,我得到了每个案例的循环解决方案和从虚拟到分类的矢量化解决方案。我将不胜感激对此问题的进一步深入了解,并为分类到虚拟步骤提供矢量化解决方案。
假到不假
vecOrig<-matrix(0,nrow=18,ncol=8) # From this one
vecDest<-matrix(0,nrow=18,ncol=3) # To this one
# Populating the original matrix.
# I'm pretty sure this could have been added to the definition of the matrix,
# but I kept getting repeated numbers.
# How would you vectorize this?
for (i in 1:length(vecOrig[,1])){
vecOrig[i,]<-sample(vec)
}
# Now, how would you vectorize this following step...
for(i in 1:length(vecOrig[,1])){
vecDest[i,]<-grep(1,vecOrig[i,])
}
# Vectorized solution, I had to transpose it for some reason.
vecDest2<-t(apply(vecOrig,1,function(x) grep(1,x)))
不是假人对假人
matOrig<-matrix(0,nrow=18,ncol=3) # From this one
matDest<-matrix(0,nrow=18,ncol=8) # To this one.
# We populate the origin matrix. Same thing as the other case.
for (i in 1:length(matOrig[,1])){
matOrig[i,]<-sample(1:8,3,FALSE)
}
# this works, but how to make it vectorized?
for(i in 1:length(matOrig[,1])){
for(j in matOrig[i,]){
matDest[i,j]<-1
}
}
# Not a clue of how to vectorize this one.
# The 'model.matrix' solution doesn't look neat.
最佳答案
矢量化解决方案:
假到不假
vecDest <- t(apply(vecOrig == 1, 1, which))
非虚拟对虚拟 (回到原来的)
nCol <- 8
vecOrig <- t(apply(vecDest, 1, replace, x = rep(0, nCol), values = 1))
关于r - 来回到 R 中的虚拟变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13935831/