Filling in data.frame from another data.frame

4

I have two data.frames: "a" and "df"

a <- data.frame(x=seq(13,37,1),rep(c(1,2,3,4,5),each=5),seq(21,105,21))
colnames(a)<-c("values","date","term")

b<-data.frame(x,21,42,63,84,105)
colnames(b)<-c("date","term21","term42","term63","term84","term105")
m <- as.matrix(b)
m[m>20] <- 0
df <- as.data.frame(m)


head(a)

  values date term
1     13    1   21
2     14    1   42
3     15    1   63
4     16    1   84
5     17    1  105
6     18    2   21

head(df)

  date term21 term42 term63 term84 term105
1    1      0      0      0      0       0
2    2      0      0      0      0       0
3    3      0      0      0      0       0
4    4      0      0      0      0       0
5    5      0      0      0      0       0

What I did was transpose the data frame "a" and delete the repeated "date" lines.

Now, I want to populate the "df" data.frame with its values, ie in the end I have to have:

date  term21  term42  term63  term84  term105
    1   13      14      15      16       17
    2   18      19      20      21       22 
    3   23      24      25      26       27 
    4   28      29      30      31       32
    5   33      34      35      36       37

There is some more functional way to do this. Just starting from the data.frame "a" ??

Because my original "a" data.frame is gigantic.

    
asked by anonymous 27.01.2016 / 19:14

1 answer

3

What you really want to do is pass the date frame to the wide ("pivot") format. You can do this with the dcast function of the reshape2 package:

library(reshape2)
dcast(a, date~term, value.var = "values")
  date 21 42 63 84 105
1    1 13 14 15 16  17
2    2 18 19 20 21  22
3    3 23 24 25 26  27
4    4 28 29 30 31  32
5    5 33 34 35 36  37

You can also do with tidyr :

library(tidyr)
a %>% spread(term, values)
  date 21 42 63 84 105
1    1 13 14 15 16  17
2    2 18 19 20 21  22
3    3 23 24 25 26  27
4    4 28 29 30 31  32
5    5 33 34 35 36  37
    
27.01.2016 / 22:48