我一直在努力解决这个问题,并决定在一些失败后寻求帮助。
这是我的问题,我想根据日期划分这两个向量,例如 2012-12-11 将是 3/17,2012-12-12 应该是 0/7。但是我似乎无法弄清楚如何做到这一点..
> ili
2012-12-11 2012-12-13 2012-12-14 2012-12-17
3 6 7 1
> no.ili
2012-12-11 2012-12-12 2012-12-13 2012-12-14 2012-12-15 2012-12-16 2012-12-17
17 7 232 322 38 21 36
最后一次尝试是遍历两个向量并将值或零添加到新向量中,但是当我使用
%in%
时它没有按顺序排列值(显然)但如果我使用 ==
它也不起作用.. days.ili <- unique(one.three$timestamp)
days <- unique(one.week$timestamp)
ili.vec <- rep(0, length(days))
for (i in 1:length(days)) {
if (days.ili[i] %in% days) {
ili.vec[i] <- ili[i]
} else {
ili.vec[i] <- 0
}
}
我一定是忘记了一些事情,因为我无法看透这个问题.. 任何人都可以告诉我在 R 中实现这一目标的最佳方法吗?
也许一个选项会使用
merge
..
最佳答案
像这样的东西:
res <- rep(0, length(no.ili))
where <- match( names(ili), names(no.ili) )
res[ where ] <- ili / no.ili[where]
names(res) <- names(no.ili)
res
# 2012-12-11 2012-12-12 2012-12-13 2012-12-14 2012-12-15 2012-12-16 2012-12-17
# 0.17647059 0.00000000 0.02586207 0.02173913 0.00000000 0.00000000 0.02777778
关于r - 比较 R 中不同长度的两个向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14121273/