从 R 中的三列数据框创建矩阵

creating matrix from three column data frame in R

我有一个包含三列的数据框,其中每一行都是唯一的:

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

我想创建一个矩阵,其中行的状态名称和列的季节名称 val_1 作为值。我以前用过:

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

并且它创建了所需的矩阵,每个状态名称出现一次,但由于某种原因,当我最近使用 acastdcast 时,它会自动默认为长度函数并给出 1's价值。谁能推荐一个解决方案?

数据

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)

您可以定义 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

这也有效

library(reshape2)

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)

dcast(df1, state~season, value.var = 'val_1')
#>   state spring summer winter
#> 1   BOS     26     19     14
#> 2    NY     10     24      3
#> 3  WASH     66     42     99

reprex package (v2.0.1)

于 2022-04-08 创建