我想根据周数分配月份。我试过了:
full = data.frame(group = c('a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'c', 'c'), week = c(1, 2, 3, 4, 5, 1, 2, 3, 1, 2))
full %>% group_by(group) %>% mutate(month = rep(1, 4, each = length(group) / 4))
输出为:
group week month
1 a 1 1
2 a 2 1
3 a 3 1
4 a 4 1
5 a 5 2
6 b 1 1
7 b 2 1
8 b 3 1
9 c 1 1
10 c 2 1
但是,上面的代码返回错误
mutate_impl(.data,dots)中的错误: 列
month
必须是长度5(组大小)或1,而不是4
无论如何重复某些部分长度的时间:rep(1:2, each = 1.5
)为1, 1, 2
,而不是1, 2
?
答案 0 :(得分:1)
您可以将周视为日期并使用lubridate
library(lubridate)
library(dplyr)
full %>%
group_by(group) %>%
mutate(month = lubridate::month(origin + lubridate::weeks(x=week)))
输出
# A tibble: 10 x 3
# Groups: group [3]
group week month
<fctr> <dbl> <dbl>
1 a 1 1
2 a 2 1
3 a 3 1
4 a 4 1
5 a 5 2
6 b 1 1
7 b 2 1
8 b 3 1
9 c 1 1
10 c 2 1
答案 1 :(得分:0)
也许您可以使用floor
代替:
full %>% group_by(group) %>% mutate(month = floor((1:length(group) + 3)/4))