如果实际上您希望创建一个新的数据框,将多个学生聚合(或在dplyr 中汇总)到每个学生的一行中,其中您指定的分类列将包含最常见的值,您可以使用 @来自DescTools 库的987654322@ 函数,以及summarise 和dplyr。您应该注意,当您没有最常见的值或多个值(多模式)时,您可能会遇到麻烦,例如在您的示例数据中。你需要决定做什么。
这可以让你开始:
install.packages("dplyr")
library(dplyr)
install.packages("DescTools")
library(DescTools)
#create sample data tibble (similar to data frame)
data <- data.frame(student=c('a', 'a', 'a', 'b', 'c', 'c'),
subject=c('aze','sdf','hjk','uio','okn','uhv'),
class=c('h','h','f','l','h','l'),
num=c(2,2,3,5,2,6))
# returns a single mode. Will return NA if multimodal by default.
# To return the first mode if multimodal, add "FALSE" to the second condition
get_mode = function(x, multimodal.na="TRUE"){
modes <- Mode(x)
if (multimodal.na=="FALSE" | length(modes)==1) {
return(modes[1])
} else {
return(modes[length(modes)+1])
}
}
# tests
data_mode <- data %>% group_by(student) %>% summarise(md_subject = get_mode(subject, multimodal.na = "FALSE"),
md_class = get_mode(class, multimodal.na = "FALSE"),
md_num = get_mode(num, multimodal.na = "FALSE"))
data_mode2 <- data %>% group_by(student) %>% summarise(md_subject = get_mode(subject),
md_class = get_mode(class),
md_num = get_mode(num))
现在让我们查看上面的两个数据:
> data_mode
# A tibble: 3 x 4
student md_subject md_class md_num
<fct> <chr> <chr> <dbl>
1 a aze h 2
2 b uio l 5
3 c okn h 2
> data_mode2
# A tibble: 3 x 4
student md_subject md_class md_num
<fct> <chr> <chr> <dbl>
1 a NA h 2
2 b uio l 5
3 c NA NA NA