R:确定组内某些子组的最大值和最小值之间的差异

标签 r dplyr grouping tidyverse difference

下面的示例数据字段

Event        Ethnicity        Score
50 yd dash    Asian             7
50 yd dash    Afr. Am           8
50 yd dash    White             5
Hurdle        Asian             6
Hurdle        Afr. Am           8
Hurdle        White             9

我正在尝试确定每个事件中某些种族之间的差异,希望使用 dplyr 或 tidyverse 中的某些东西,但会接受任何答案/帮助。比如亚组和白组在各个项目中的区别,

例如,亚洲人 (7) - 白人 (5) = 差异 (2),

导致类似于下面的输出:

Event          Difference
50 yd dash         2
Hurdle            -3

最佳答案

使用以下内容应该可以帮助您:

library(tidyverse)

df %>%
    spread(Ethnicity, Score) %>%
    mutate("Difference" = Asian - White) %>%
    select(-Asian, -White, -`Afr. Am`)
#       Event Difference
#1 50 yd dash          2
#2     Hurdle         -3

数据。

df <-
structure(list(Event = structure(c(1L, 1L, 1L, 2L, 2L, 2L), .Label = c("50 yd dash", 
"Hurdle"), class = "factor"), Ethnicity = structure(c(2L, 1L, 
3L, 2L, 1L, 3L), .Label = c("Afr. Am", "Asian", "White"), class = "factor"), 
    Score = c(7L, 8L, 5L, 6L, 8L, 9L)), class = "data.frame", row.names = c(NA, 
-6L))

@AntoniosK 已经发布了一种读取 OP 发布的数据的 read.table 方法,但我的方法有点不同。我没有从列的值中删除空格,而是将它们放在单引号之间。 (它必须是引号,因为指令将参数text的值放在引号之间。)

df <- read.table(text = "
Event        Ethnicity        Score
'50 yd dash'    Asian             7
'50 yd dash'    'Afr. Am'           8
'50 yd dash'    White             5
Hurdle        Asian             6
Hurdle        'Afr. Am'           8
Hurdle        White             9
", header = TRUE)

关于R:确定组内某些子组的最大值和最小值之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51955425/

相关文章:

javascript - 如何按对象的子对象对对象列表进行最佳分组?

python - SQLite 还是纯文本文件?

regex - 在第一个遇到的数字上通过 dplyr 使用单独的 (tidyr) 分隔列

在 R 中重新编码除一个变量之外的所有变量

javascript - 对象数组到按属性分组的对象数组

MySQL join查询结果按标签过滤

r - 如何确保 RStudio 包含在 .bashrc 中所做的更改

r - 绘制 grobs 列表

r - 用日期的最大值在 dplyr 中汇总 - R

r - 在 R 中按分组复制过滤数据帧