i trying add variable data frame indicates observation of factor last. essentially, i'd create indicated lastobs variable below.
id date val obsnum lastobs 1999-01-05 5 1 0 1999-01-05 9 2 0 1999-02-14 4 3 1 b 1999-03-19 7 1 1 c 1999-02-14 10 1 1 any appreciated.
library(dplyr) df %>% group_by(id) %>% mutate(lastobs = +(row_number() == n())) # source: local data frame [5 x 5] # groups: id # # id date val obsnum lastobs # 1 1999-01-05 5 1 0 # 2 1999-01-05 9 2 0 # 3 1999-02-14 4 3 1 # 4 b 1999-03-19 7 1 1 # 5 c 1999-02-14 10 1 1 explanation
dplyr useful package familiar new user. simplify , speed tasks you. symbol %>% called pipe , creates sentence format each statement linked together. first input name of data frame using df, variable group results id. create new column called lastobs consists of matching command checks if each observation last observation. plus sign on outside turns true , false results 1's , 0's.
with base r:
df$lastobs <- unlist(with(df, tapply(val, id, fun= function(x) (seq_along(x) == length(x))+0l))) with data.table package (credit: @akrun):
setdt(df)[, lastobs := +(1:.n==.n), id] data
df <- read.table(text=' id date val obsnum lastobs 1999-01-05 5 1 0 1999-01-05 9 2 0 1999-02-14 4 3 1 b 1999-03-19 7 1 1 c 1999-02-14 10 1 1', header=t) df <- df[,-5]
Comments
Post a Comment