Reputation: 163
i've following issue using R for my:
Let's say i've following dataframe:
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 delivers for this exmaple-data:
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
I need to transform this dateframe in the following structure:
"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
Any suggestions? (I'm new using R and tried to solve it for a couple of hours ;))
Upvotes: 0
Views: 69
Reputation: 43245
you can use the reshape2
package and the dcast
function:
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
You can also do this with the base R function reshape
, but I find its syntax confusing at best!
Upvotes: 4