I have a data frame as follows:
id day count
1 mon 3
1 tues 4
1 wed 8
2 mon 6
2 tues 3
and I would like to transform it to look something like this:
id mon tues wed
1 3 4 8
2 6 3 NA
Any ideas? Thanks!
Using the data shown reproducibly in the Note at the end here are a few ways. No packages are used.
# 1
xtabs(count ~., DF)
## day
## id mon tues wed
## 1 3 4 8
## 2 6 3 0
# 2
tapply(DF[[3]], DF[-3], c, default = 0)
## day
## id mon tues wed
## 1 3 4 8
## 2 6 3 0
# 3
r <- reshape(DF, dir = "wide", timevar = "day")
r[is.na(r)] <- 0
r
## id count.mon count.tues count.wed
## 1 1 3 4 8
## 4 2 6 3 0
Lines <- "id day count
1 mon 3
1 tues 4
1 wed 8
2 mon 6
2 tues 3"
DF <- read.table(text = Lines, header = TRUE)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments