【问题标题】:Performing operations on dplyr summaries对 dplyr 摘要执行操作
【发布时间】:2021-09-01 11:38:54
【问题描述】:

假设我们有一些随机数据:

data <- data.frame(ID = rep(seq(1:3),3),
                   Var = sample(1:9, 9))

我们可以使用dplyr 计算汇总操作,如下所示:

library(dplyr)
data%>%
  group_by(ID)%>%
  summarize(count = n_distinct(Var))

在 r 降价块下方给出如下所示的输出:

ID count
1   3           
2   3           
3   3   

我想知道我们如何在此dplyr 输出中对单个数据点执行操作,而不将输出保存在单独的对象中。

例如在summarise 的输出中,假设我们想从ID == 1ID == 2 的输出值之和中减去ID == 3 的输出值,并保留@987654330 的输出值@ 和 ID == 2 就像他们一样。我知道这样做的唯一方法是将摘要输出保存在另一个对象中并对该对象执行操作,如下所示:

a<-
  data%>%
  group_by(ID)%>%
  summarize(count = n_distinct(Var))
a
#now perform the operation on a
a[3,2] <- a[2,1]+a[2,2]-1
a

a 现在看起来像这样:

ID count
1   3           
2   3           
3   4

有没有办法在dplyr 输出中做到这一点而无需创建新对象?我们能不能像这样直接在输出上使用mutate

【问题讨论】:

  • a[2,1]+a[2,2]-1 对我来说没有意义:为什么要将 ID 添加到 count?为什么要使用矩阵索引而不是帧索引(即按名称)?
  • 我也回应了 r2evans 的评论。首先我想,除了最后一行之外,它会是所有行。但是,那么你的输出会有所不同
  • 你是对的,我的例子没有逻辑意义,起初它实际上是一个错字,但它仍然是我关于如何在输出中的各个位置执行操作的问题的一个有效例子,因此我选择保持原样

标签: r dplyr summarize


【解决方案1】:

按您说的做(“sum others”)而不是您演示的替代方案。

data %>%
  group_by(ID) %>%
  summarize(count = n_distinct(Var)) %>%
  mutate(count = if_else(ID == 3L, sum(count) - count, count))
# # A tibble: 3 x 2
#      ID count
#   <int> <int>
# 1     1     3
# 2     2     3
# 3     3     6

或者,如果还有其他不应包含在总和中的IDs,则

data %>%
  group_by(ID) %>%
  summarize(count = n_distinct(Var)) %>%
  mutate(count = if_else(ID == 3L, sum(count[ID %in% 1:2]), count))

【讨论】:

    【解决方案2】:

    我们可以在summarise后面加上mutatereplace来修改list中指定的位置

    library(dplyr)
    data%>%
       group_by(ID)%>%
       summarize(count = n_distinct(Var)) %>% 
       mutate(count = replace(count, n(), count[2] + ID[2] - 1))
    

    -输出

    # A tibble: 3 x 2
         ID count
      <int> <dbl>
    1     1     3
    2     2     3
    3     3     4
    

    或者如果多于两列,在sliced 行使用sum

    data%>%
       group_by(ID)%>%
       summarize(count = n_distinct(Var)) %>% 
       mutate(count = replace(count, n(), sum(cur_data() %>% 
              slice(2)) - 1))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-26
      • 2018-12-03
      • 1970-01-01
      • 2017-12-22
      • 1970-01-01
      相关资源
      最近更新 更多