R将行值转置到列



data %>% select(Year, Type) %>% table()的输出给我:

Year  Type Freq
2001    A     5
2002    A     2
2003    A     9
...    ...  ...
2001    B    21   
2002    B    22
2003    B    19

我想要我的数据:

Year  A   B   C   D   E  
2001  5  21   ..  ..  ..
2002  2  22   ..  ..  .. 
2003  9  19   ..  ..  ..
...

我怎样才能做到这一点?我找到的例子似乎不符合我的情况

使用reshape的base R选项

reshape(
df,
direction = "wide",
idvar = "Year",
timevar = "Type"
)

Year Freq.A Freq.B
1 2001      5     21
2 2002      2     22
3 2003      9     19

data.table选项

dcast(setDT(df), Year ~ Type)

Year A  B
1: 2001 5 21
2: 2002 2 22
3: 2003 9 19

一个dplyr选项

df %>%
pivot_wider(names_from = Type, values_from = Freq)

# A tibble: 3 x 3
Year     A     B
<int> <int> <int>
1  2001     5    21
2  2002     2    22
3  2003     9    19

> dput(df)
structure(list(Year = c(2001L, 2002L, 2003L, 2001L, 2002L, 2003L
), Type = c("A", "A", "A", "B", "B", "B"), Freq = c(5L, 2L, 9L,
21L, 22L, 19L)), class = "data.frame", row.names = c(NA, -6L))

base R使用xtabs的选项

xtabs(Freq ~ Year + Type, df)

相关内容

  • 没有找到相关文章

最新更新