使用dplyr,计算每个类中的非数字等级
给定下面的输入和代码,使用dplyr和groups,如何生成输出中显示的结果?我知道如何使用dplyr对组中的列求和,但在本例中,我需要计算每个类中出现的每个非数字等级的数量使用dplyr,计算每个类中的非数字等级,r,group-by,dplyr,R,Group By,Dplyr,给定下面的输入和代码,使用dplyr和groups,如何生成输出中显示的结果?我知道如何使用dplyr对组中的列求和,但在本例中,我需要计算每个类中出现的每个非数字等级的数量 **INPUT** Class Student Grade 1 Jack C 1 Mary B 1 Mo B 1 Jane A 1 Tom C 2 Don C 2 Betsy B 2
**INPUT**
Class Student Grade
1 Jack C
1 Mary B
1 Mo B
1 Jane A
1 Tom C
2 Don C
2 Betsy B
2 Sue C
2 Tayna B
2 Kim C
我们可以使用
count
获得频率计数,然后使用pivot\u wide
将“长”格式更改为“宽”格式
library(dplyr)
library(tidyr)
library(stringr)
StudentGrades %>%
count(Class, Grade = str_c('Grade_', Grade)) %>%
pivot_wider(names_from = Grade, values_from = n, values_fill = list(n = 0))
# A tibble: 2 x 4
# Class Grade_A Grade_B Grade_C
# <dbl> <int> <int> <int>
#1 1 1 2 2
#2 2 0 2 3
我们可以使用
count
获得频率计数,然后使用pivot\u wide
将“长”格式更改为“宽”格式
library(dplyr)
library(tidyr)
library(stringr)
StudentGrades %>%
count(Class, Grade = str_c('Grade_', Grade)) %>%
pivot_wider(names_from = Grade, values_from = n, values_fill = list(n = 0))
# A tibble: 2 x 4
# Class Grade_A Grade_B Grade_C
# <dbl> <int> <int> <int>
#1 1 1 2 2
#2 2 0 2 3
这是一个基本的R解决方案,其中使用了
table()
+split()
dfout <- do.call(rbind,lapply(split(StudentGrades,StudentGrades$Class),
function(v) c(unique(v[1]),table(v$Grade))))
这是一个基本的R解决方案,其中使用了
table()
+split()
dfout <- do.call(rbind,lapply(split(StudentGrades,StudentGrades$Class),
function(v) c(unique(v[1]),table(v$Grade))))
dfout <- do.call(rbind,lapply(split(StudentGrades,StudentGrades$Class),
function(v) c(unique(v[1]),table(v$Grade))))
> dfout
Class A B C
1 1 1 2 2
2 2 0 2 3