[R] how to create a pivot table in r?
peter dalgaard
pd@|gd @end|ng |rom gm@||@com
Thu Feb 6 11:02:43 CET 2020
There is also
> with(daT, tapply(as.character(ObsDate), list(id, ObsSite), function(x)format(list(x))))
site1 site4 site5 site7
id1 NA NA NA "06/13/13"
id2 NA NA NA "07/03/14, 05/17/14"
id4 NA "05/08/14" NA NA
id5 NA NA "06/13/14" NA
id6 "05/30/14, 06/28/13" NA NA NA
id7 NA NA "06/25/13" NA
...with the added bonus that if you leave out the format() business, you get a data structure that doesn't print as nicely, but can be used for further computations:
> with(daT, tapply(as.character(ObsDate), list(id, ObsSite), list, simplify=FALSE))
site1 site4 site5 site7
id1 NULL NULL NULL List,1
id2 NULL NULL NULL List,1
id4 NULL List,1 NULL NULL
id5 NULL NULL List,1 NULL
id6 List,1 NULL NULL NULL
id7 NULL NULL List,1 NULL
> M <- with(daT, tapply(as.character(ObsDate), list(id, ObsSite), list, simplify=FALSE))
> M[["id2", "site7"]]
[[1]]
[1] "07/03/14" "05/17/14"
-pd
> On 6 Feb 2020, at 01:37 , Marna Wagley <marna.wagley using gmail.com> wrote:
>
> daT<-structure(list(id = structure(c(1L, 2L, 2L, 3L, 4L, 5L, 5L, 6L
> ), .Label = c("id1", "id2", "id4", "id5", "id6", "id7"), class = "factor"),
> ObsSite = structure(c(4L, 4L, 4L, 2L, 3L, 1L, 1L, 3L), .Label =
> c("site1",
> "site4", "site5", "site7"), class = "factor"), ObsDate =
> structure(c(4L,
> 8L, 2L, 1L, 5L, 3L, 7L, 6L), .Label = c("05/08/14", "05/17/14",
> "05/30/14", "06/13/13", "06/13/14", "06/25/13", "06/28/13",
> "07/03/14"), class = "factor")), .Names = c("id", "ObsSite",
> "ObsDate"), class = "data.frame", row.names = c(NA, -8L))
> daT
> daT$date <- mdy(daT$ObsDate)
--
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Office: A 4.23
Email: pd.mes using cbs.dk Priv: PDalgd using gmail.com
More information about the R-help
mailing list