我使用R代表我的问题:
假设我跟随数据帧:
dates <- c("2010-01-01","2010-02-01","2010-03-01","2010-04-01",
"2010-02-01","2010-03-01","2010-04-01","2010-05-01",
"2010-03-01","2010-04-01","2010-05-01","2010-06-01")
data.frame(A=c(1,1,1,1,2,2,2,2,3,3,3,3),B=dates,C=c(21:32))
R为这个例子提供了数据:
A B C
1 1 2010-01-01 21
2 1 2010-02-01 22
3 1 2010-03-01 23
4 1 2010-04-01 24
5 2 2010-02-01 25
6 2 2010-03-01 26
7 2 2010-04-01 27
8 2 2010-05-01 28
9 3 2010-03-01 29
10 3 2010-04-01 30
11 3 2010-05-01 31
12 3 2010-06-01 32
我需要在以下结构中转换此日期框架:
"2010-01-01" "2010-02-01" "2010-03-01" "2010-04-01" "2010-05-01" "2010-06-01"
1 21 22 23 24 na na
2 na 25 26 27 28 na
3 na na 29 30 30 31
有什么建议吗? (我是新用的R并试图解决它几个小时;))
答案 0 :(得分:4)
您可以使用reshape2
包和dcast
功能:
library(reshape2)
dcast(dat, A ~ B, value.var='C')
# A 2010-01-01 2010-02-01 2010-03-01 2010-04-01 2010-05-01 2010-06-01
# 1 1 21 22 23 24 NA NA
# 2 2 NA 25 26 27 28 NA
# 3 3 NA NA 29 30 31 32
您也可以使用基本R函数reshape
执行此操作,但我发现其语法最多会让人感到困惑!