Is there a simple way to reshape this
id date
A Jan 2012
B Jan 2012
C Jan 2012
A Feb 2012
B Feb 2012
A Mar 2012
B MAr 2012
in
id Jan 2012 Feb 2012 Mar 2012
A T T T
B T T T
C T F F
dcast
and reshape
requires a aggregate function that I don't think I need (?)
Using dcast
as you suggest...
# Please provide reproducible data next time!
set.seed(123)
dt <- data.frame( id = rep(c("A","B","C"),3 ), date = sample( month.name[1:3] , 9 , repl = TRUE ) , stringsAsFactors = FALSE )
# id date
#1 A January
#2 B March
#3 C February
#4 A March
#5 B March
#6 C January
#7 A February
#8 B March
#9 C February
require( reshape2 )
dcast( dt , id ~ date , fun = function(x) length(x) > 0 , fill = FALSE )
# id February January March
#1 A TRUE TRUE TRUE
#2 B FALSE FALSE TRUE
#3 C TRUE TRUE FALSE
Or just table
as @AnandaMahto suggets...
table(dt) > 0
# date
#id February January March
# A TRUE TRUE TRUE
# B FALSE FALSE TRUE
# C TRUE TRUE FALSE
Which is certianly syntactically easier!!
I think this would work great for what you are looking for:
library(zoo)
df <- data.frame(id = c("A", "B", "C", "A", "B", "A", "B"), date = c("2012-01", "2012-01", "2012-01", "2012-02", "2012-02", "2012-03", "2012-03"))
df$date <- as.yearmon(df$date)
result <- with(df, tapply(date, list(id, date), length))
result[is.na(result)] <- 0
result <- (result == 1)
You get:
Jan 2012 Feb 2012 Mar 2012
A TRUE TRUE TRUE
B TRUE TRUE TRUE
C TRUE FALSE FALSE
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.