string - how to summary the historical data based on the same ID in R -


i have data:

id |result -------- 1  | ------- 1  | b ------- 1  | c ------- 2  | e ------- 2  | f ------- 2  | g 

the dataframe want listed below:

id |result|history ------------------- 1  |    |  ------------------- 1  | b    | ------------------ 1  | c    | a,b ------------------ 2  | e    | ------------------ 2  | f    | e ----------------- 2  | g    | e,f 

i tried use lag in r. however, doesn't work one. can help?

df$history = unlist(tapply(x = df$result, index = df$id, function(a)     c("", reduce(function(x, y) {paste(x, y, sep = ", ")},                 head(a, -1),                  accumulate = true)))) df #  id result history #1  1              #2  1      b       #3  1      c    a, b #4  2      e         #5  2      f       e #6  2      g    e, f 

data

df = structure(list(id = c(1l, 1l, 1l, 2l, 2l, 2l), result = c("a",          "b", "c", "e", "f", "g")), .names = c("id", "result"),         class = "data.frame", row.names = c(na, -6l)) 

Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -