Filling out data.frame from another date.frame

Asked

Viewed 1,126 times

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 fill the date.frame "df" with its values, IE, at 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. Starting only from data.frame "a" ??

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

1 answer

4


What you want to do is actually move the data frame to the format wide ("pivotear"). You can do this with the function dcast package reshape2:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.