r - Subset panel data by group -


i subset unbalanced panel data set group. each group, keep 2 observations in first , last years.

how best in r? example:

dt <- data.frame(name= rep(c("a", "b", "c"), c(3,2,3)),                   year=c(2001:2003,2000,2002,2000:2001,2003))  > dt   name year 1    2001 2    2002 3    2003 4    b 2000 5    b 2002 6    c 2000 7    c 2001 8    c 2003 

what have:

  name year 1    2001 3    2003 4    b 2000 5    b 2002 6    c 2000 8    c 2003 

here's quick possible data.table solution

library(data.table) setdt(dt)[, .sd[c(1l, .n)], = name] #    name year # 1:    2001 # 2:    2003 # 3:    b 2000 # 4:    b 2002 # 5:    c 2000 # 6:    c 2003 

or if have 2 columns

dt[, year[c(1l, .n)], = name] 

Comments

Popular posts from this blog

cakephp - simple blog with croogo -

How to group boxplot outliers in gnuplot -

bash - Performing variable substitution in a string -