R - repetition with dplyr -
in order transform "long compact" format data wide format need use rep
function.
i can not figure out how integrate dplyr
flow.
this repetition need use
dta1 = as.data.frame(cbind(rep(dta$id, dta$duration), rep(dta$act, dta$duration) ) ) colnames(dta1) <- c('id', 'act')
here dplyr
code.
dta1 %>% group_by(id) %>% mutate( time = 1:n() ) %>% spread(time, act)
do have idea how put these 2 codes ?
the data
dta = structure(list(id = c("b10001n1", "b10001n1", "b10001n1", "b10001n1", "b10001n1", "b10001n1", "b10001n1", "b10001n1", "b10001n1", "b10001n1", "b10001n1", "b10001n1", "b10001n1", "b10001n1", "b10001n1", "b10001n1", "b10001n2", "b10001n2", "b10001n2", "b10001n2", "b10001n2", "b10001n2", "b10001n2", "b10001n2", "b10001n2", "b10001n2", "b10001n2", "b10001n2", "b10001n2", "b10001n3", "b10001n3", "b10001n3", "b10001n3", "b10001n3", "b10001n3", "b10001n3", "b10001n3", "b10001n3", "b10001n3", "b10001n3", "b10001n3", "b10001n3", "b10001n4", "b10001n4", "b10001n4", "b10001n4", "b10001n4", "b10001n4", "b10001n4", "b10001n4", "b10001n4", "b10001n4", "b10001n4", "b10001n4", "b10001n4"), act = c("-11", "1704", "1302", "1301", "1507", "603", "1301", "101", "502", "1704", "1507", "1404", "8888", "603", "1507", "101", "-11", "1302", "1301", "1507", "704", "101", "1704", "1704", "3102", "1002", "1704", "3101", "101", "-11", "1704", "1302", "1302", "1507", "603", "2902", "3201", "812", "1704", "1704", "3701", "101", "-11", "1302", "1301", "3101", "1001", "1507", "1006", "2101", "2902", "1704", "8888", "1704", "1302"), duration = c(30, 570, 5, 30, 25, 3, 12, 165, 30, 10, 5, 20, 70, 45, 180, 240, 570, 30, 30, 20, 25, 95, 70, 20, 20, 20, 60, 45, 435, 30, 30, 570, 90, 30, 15, 5, 40, 60, 240, 60, 30, 240, 600, 15, 45, 15, 75, 30, 150, 60, 30, 60, 210, 60, 90)), row.names = c(na, 55l), class = "data.frame", .names = c("id", "act", "duration"))
try
library(dplyr) library(tidyr) dta[rep(1:nrow(dta), dta$duration), -3] %>% group_by(id) %>% mutate( time = 1:n() ) %>% spread(time, act)
Comments
Post a Comment