我有一个5个值的向量,包含不同的月份,如下所示:
app.get('/update', function acceptReq(req, res) {
db.getDB().collection(collection).findOneAndUpdate({
_id: ObjectId("5c94f444dab6e423a488d2ae")
}, {
$set: {
requested: false,
requests: {
user: undefined,
time: undefined
},
Booked: true
}
}, {
returnOriginal: false
}, (err, result) => {
if (err)
console.log(err);
else {
req.flash(
'success_msg',
'Request Accepted!'
);
res.redirect('/dashboard/requests')
}
});
});
如何将它们转换成如下所示的矩阵形式。
[July August September October November]
此外,我还有一个向量要附加在末尾,这样输出将如下所示。
[July August September October November]
[1, 0, 0, 0, 0 ]
[0, 1, 0, 0, 0 ]
[0, 0, 1, 0, 0 ]
[0, 0, 0, 1, 0 ]
[0, 0, 0, 0, 1 ]
答案 0 :(得分:1)
我们可以将task = SomeTask()
try:
task.start()
except KeyboardInterruptException:
print("Keyboard interrupted")
except Exception as e:
print_exception(e) # To show what happened
finally:
task.store_results() # If Control-C is pressed here, data gets corrupted
与向量的序列以及向量本身一起使用。如果需要保持月份名称的顺序,则将其转换为table
并使用factor
,其中levels
由vector的intersect
个元素的unique
和month.name
指定
tbl <- table(seq_along(v1), v2, dnn = NULL)
tbl
# July August September October November
#1 1 0 0 0 0
#2 0 1 0 0 0
#3 0 0 1 0 0
#4 0 0 0 1 0
#5 0 0 0 0 1
现在,我们可以附加第二个vector
cbind(tbl, Other)
或使用model.matrix
model.matrix(~ v2 - 1, data = data.frame(v2))
或使用mtabulate
中的qdapTools
library(qdapTools)
mtabulate(v2)
v1 <- c("July", "August", "September", "October", "November")
v2 <- factor(v1, levels = intersect(month.name, unique(v1)))
答案 1 :(得分:1)
sapply(v1, function(x) as.numeric(v1 == x))
# July August September October November
#[1,] 1 0 0 0 0
#[2,] 0 1 0 0 0
#[3,] 0 0 1 0 0
#[4,] 0 0 0 1 0
#[5,] 0 0 0 0 1
答案 2 :(得分:0)
您也可以使用model.matrix
或dummyVars
v1 <- c("July", "August", "September", "October", "November")
v1 <- as.data.frame(v1)
v2 <- data.frame(v1 = v1)
as.data.frame(model.matrix(~.-1, v1))
v1August v1July v1November v1October v1September
1 0 1 0 0 0
2 1 0 0 0 0
3 0 0 0 0 1
4 0 0 0 1 0
5 0 0 1 0 0
library(caret)
m1 <- dummyVars(" ~ .", data = v1)
data.frame(predict(m1, newdata = v1))
v1.August v1.July v1.November v1.October v1.September
1 0 1 0 0 0
2 1 0 0 0 0
3 0 0 0 0 1
4 0 0 0 1 0
5 0 0 1 0 0