I want to add a vector of variables in a dataframe, repeating within a given group of variables. There should be an easy way to do this in dplyr notation (I would prefer not to execute the match () statement)
Data:
library(dplyr); library(lubridate)
data <- data.frame(
date = seq(as.Date('2014-11-01'), length = 30, by = '1 day'))
data$day <- weekdays(as.Date(data$date))
data$week <- week(as.Date(data$date))
Now, for each weekly breakthrough, I want to add a number from a predefined vector (I'm trying to split the month into weekly percentages, the sum of which is 1):
weekly_vector <- c(0.1, 0.2, 0.4, 0.2, 0.1)
The idea is that I want the first element of this vector --0.1-- to be added to Week 44, the second element to Week 45, etc.
but something like:
data <- data %>% group_by(week) %>% mutate(perc = weekly_vector)
does not work: Error: unable to replicate a vector of size 5
How would I replicate vector elements with a weekly breakthrough?
source
share