I would like to know how I could use ddply in combination with an ifelse condition, as in the example bellow, where I attempt to add y_added to y after a certain week. I want that this is separately done for each subject and year, therefore I thought ddply might be a good option, but if another function works better, I would be happy to know about that. I have seen a similar question has already been answered but I cannot figure out how to do it in this case
library(plyr); library(dplyr)
# Example data
year <- c(rep(2000, 20), rep(2001, 20))
week <- c(1:10, 1:10, 1:10, 1:10)
subject <- c(rep("A",10), rep("B", 10), rep("A",10), rep("B", 10))
y <- c(1:10, 21:30, 11:20, 18:27)
d1 <- data.frame(year, week, subject, y)
d_addition <- data.frame(subject = c("A","B", "A"), y_added = c(5, 12, 7),
week_added = c(5, 7, 8), year = c(2000, 2000, 2001))
d2 = full_join(d1, d_addition)
# Attempt to add y_added to y after the week the addition occured
d3 = ddply(d2,c("year", "subject"),transform,
y2 <- ifelse(week >= y_added, y + y_added,y))
Aucun commentaire:
Enregistrer un commentaire