0

有没有一种简单的方法来重塑这个

id  date
A   Jan 2012
B   Jan 2012
C   Jan 2012
A   Feb 2012
B   Feb 2012
A   Mar 2012
B   MAr 2012

id  Jan 2012    Feb 2012    Mar 2012
A   T           T           T
B   T           T           T
C   T           F           F

dcast并且reshape需要一个我认为不需要的聚合函数(?)

4

2 回答 2

3

按照你的建议使用dcast...

#  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

或者就像table@AnandaMahto建议的那样......

table(dt) > 0
#   date
#id  February January March
#  A     TRUE    TRUE  TRUE
#  B    FALSE   FALSE  TRUE
#  C     TRUE    TRUE FALSE

哪个在语法上更容易!

于 2013-08-16T16:43:53.163 回答
2

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
于 2013-08-16T16:57:07.690 回答