r - Applying the minimum date to the rest of a set of observations -
i have dataframe:
zz <- "id created status snap zx1 2012-09-07 2013-01-01 zx1 2012-09-07 b 2013-01-02 zx1 2012-10-11 b 2013-01-03 zx1 2012-12-03 b 2013-01-04 zy2 2014-01-04 2013-01-01 zy2 2014-01-04 2013-01-04 zz3 2014-08-06 2013-01-01 zz3 2014-05-06 b 2013-01-03 zz3 2014-07-15 c 2013-01-04" df <- read.table(text=zz, header=t)
where need pick , apply minimum created date each id
.
output:
id created status snap zx1 2012-09-07 2013-01-01 zx1 2012-09-07 b 2013-01-02 zx1 2012-09-07 b 2013-01-03 zx1 2012-09-07 b 2013-01-04 zy2 2014-01-04 2013-01-01 zy2 2014-01-04 2013-01-04 zz3 2014-05-06 2013-01-01 zz3 2014-05-06 b 2013-01-03 zz3 2014-05-06 c 2013-01-04
example: zx1
"created" should 2012-09-07
observations.
try
library(dplyr) df %>% group_by(id) %>% mutate(created=min(as.date(created))) # id created status snap #1 zx1 2012-09-07 2013-01-01 #2 zx1 2012-09-07 b 2013-01-02 #3 zx1 2012-09-07 b 2013-01-03 #4 zx1 2012-09-07 b 2013-01-04 #5 zy2 2014-01-04 2013-01-01 #6 zy2 2014-01-04 2013-01-04 #7 zz3 2014-05-06 2013-01-01 #8 zz3 2014-05-06 b 2013-01-03 #9 zz3 2014-05-06 c 2013-01-04
or using data.table
library(data.table) setdt(df)[, created1 := min(as.date(created)), by=id][]
Comments
Post a Comment