如何使用R计算范围?

问题描述

我有以下数据集并试图计算男孩和女孩的外观范围。

我正在尝试使用函数范围,但如何将 Boy 或 Girl 传递给 Gender?诸如 Gender='Boy' 或 Gender = 'Girl' 之类的东西?

> range(~Looks,~Gender,data = PopularKids)
 Boy1  Boy2 Girl1 Girl2 
 1     4     1     4  

   Age Gender GradeLevel School Location    Goal Grades Sports Looks Money
1  11    Boy          5    Elm    Rural  Sports      1      2     4     3
2  10    Boy          5    Elm    Rural Popular      2      1     4     3
3  11   Girl          5    Elm    Rural Popular      4      3     1     2
4  11   Girl          5    Elm    Rural Popular      2      3     4     1
5  10   Girl          5    Elm    Rural Popular      4      2     1     3
6  11   Girl          5    Elm    Rural Popular      4      2     1     3

解决方法

我们可以使用

library(dplyr)
PopularKids %>%
    group_by(Gender) %>%
    summarise(Min = min(Looks),Max = max(Looks))
,

使用data.table

library(data.table)

df <- structure(list(Age = c(11L,10L,11L,11L),Gender = c("Boy","Boy","Girl","Girl"),GradeLevel = c(5L,5L,5L),School = c("Elm","Elm","Elm"),Location = c("Rural","Rural","Rural"),Goal = c("Sports","Popular","Popular"),Grades = c(1L,2L,4L,4L),Sports = c(2L,1L,3L,2L),Looks = c(4L,1L),Money = c(3L,3L)),class = c("data.frame"),row.names = c(NA,-6L))

setDT(df)
df[,.(range=list(range(Looks))),by=.(Gender)]
#>    Gender range
#> 1:    Boy   4,4
#> 2:   Girl   1,4