Marna Wagley
2021-Apr-02 14:14 UTC
[R] extraction of last observation date from many observations in each row/column
Dear R-Users, I have a dataset containing more than two observation dates in some of the columns and sites but I wanted to extract only the last date of the observation. Is there any easiest way to get that last observation in each column/row? Here is the example data: daT<-structure(list(ID = c("M3", "M5", "M1"), Site1 c("12/20/2018,12/28/2018", "12/17/18", ""), Site2 = c("", "", "1/19/2019"), Site3 = c("9/25/2019", "", "1/10/2019, 1/11/2019, 1/17/2019")), class = "data.frame", row.names c(NA,-3L)) #I wanted to make the table like this: output<-structure(list(ID = c("M3", "M5", "M1"), Site1 = c("12/28/2018", "12/7/2018", ""), Site2 = c("", "", "1/19/2019"), Site3 = c("9/25/2019", "", "1/17/2019")), class = "data.frame", row.names = c(NA, -3L)) Thank you for your help. Sincerely, MW [[alternative HTML version deleted]]
Sarah Goslee
2021-Apr-02 14:31 UTC
[R] extraction of last observation date from many observations in each row/column
Hi Marna, This very short function deletes everything before the last , if there is a comma. Some of your entries have comma-space and some just have comma, so it deletes the optional space as well. lastdate <- function(x) { sub("^.*, *", "", x) } data.frame(apply(daT, 2, lastdate)) Sarah On Fri, Apr 2, 2021 at 10:15 AM Marna Wagley <marna.wagley at gmail.com> wrote:> > Dear R-Users, > I have a dataset containing more than two observation dates in some of the > columns and sites but I wanted to extract only the last date of the > observation. > Is there any easiest way to get that last observation in each column/row? > > Here is the example data: > daT<-structure(list(ID = c("M3", "M5", "M1"), Site1 > c("12/20/2018,12/28/2018", > "12/17/18", ""), Site2 = c("", "", "1/19/2019"), Site3 = c("9/25/2019", "", > "1/10/2019, 1/11/2019, 1/17/2019")), class = "data.frame", row.names > c(NA,-3L)) > > #I wanted to make the table like this: > output<-structure(list(ID = c("M3", "M5", "M1"), Site1 = c("12/28/2018", > "12/7/2018", ""), Site2 = c("", "", "1/19/2019"), Site3 = c("9/25/2019", > "", "1/17/2019")), class = "data.frame", row.names = c(NA, -3L)) > > Thank you for your help. > Sincerely, > MW > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code.-- Sarah Goslee (she/her) http://www.numberwright.com