rreshapedcast

creating matrix from three column data frame in R


I have a data frame with three columns where each row is unique:

df1
#   state val_1 season
# 1    NY     3 winter
# 2    NY    10 spring
# 3    NY    24 summer
# 4   BOS    14 winter
# 5   BOS    26 spring
# 6   BOS    19 summer
# 7  WASH    99 winter
# 8  WASH    66 spring
# 9  WASH    42 summer

I want to create a matrix with the state names for rows and the seasons for columns with val_1 as the values. I have previously used:

library(reshape2)
df <- acast(df1, state ~ season, value.var='val_1')

And it has created the desired matrix with each state name appearing once but for some reason when I have been using acast or dcast recently it automatically defaults to the length function and gives 1's for the values. Can anyone recommend a solution?

data

state <- c('NY', 'NY', 'NY', 'BOS', 'BOS', 'BOS', 'WASH', 'WASH', 'WASH')
val_1 <- c(3, 10, 24, 14, 26, 19, 99, 66, 42)
season <- c('winter', 'spring', 'summer', 'winter', 'spring', 'summer',
           'winter', 'spring', 'summer')
df1 <- data.frame(state, val_1, season)

Solution

  • You may define the fun.aggregate=.

    library(reshape2)
    acast(df1, state~season, value.var = 'val_1', fun.aggregate=sum)
    #      spring summer winter
    # BOS      26     19     14
    # NY       10     24      3
    # WASH     66     42     99