如何将变量的行转换为出现和 grouped_by 的列?
How to turn rows of a variable into columns with occurrence and grouped_by?
我有一个看起来像这样的数据集
Group| School
11-12 Middle School
8-10 Elementary
5-8 Elementary
5-8 Elementary
8-10 Elementary
14-16 High School
11-13 Middle School
如何把它变成
Group|Elementary|Middle School|High School
5-8 2 0 0
8-10 2 0 0
11-12 0 1 0
11-13 0 1 0
14-16 0 0 1
我们可以使用 base R
中的 table
,它给出 matrix/table
class
中的频率 table
table(df1)
或者如果我们需要一个 tidyverse 选项
library(dplyr)
library(tidyr)
df1 %>%
pivot_wider(names_from = 'School',
values_from = 'School', values_fn = length, values_fill = 0)
或 dcast
来自 data.table
library(data.table)
dcast(setDT(df1), Group ~ School, fun.aggregate = length, fill = 0)
我有一个看起来像这样的数据集
Group| School
11-12 Middle School
8-10 Elementary
5-8 Elementary
5-8 Elementary
8-10 Elementary
14-16 High School
11-13 Middle School
如何把它变成
Group|Elementary|Middle School|High School
5-8 2 0 0
8-10 2 0 0
11-12 0 1 0
11-13 0 1 0
14-16 0 0 1
我们可以使用 base R
中的 table
,它给出 matrix/table
class
table(df1)
或者如果我们需要一个 tidyverse 选项
library(dplyr)
library(tidyr)
df1 %>%
pivot_wider(names_from = 'School',
values_from = 'School', values_fn = length, values_fill = 0)
或 dcast
来自 data.table
library(data.table)
dcast(setDT(df1), Group ~ School, fun.aggregate = length, fill = 0)