【问题标题】:How to create and add a new variable based on the sum of values of a group如何根据组值的总和创建和添加新变量
【发布时间】:2019-09-28 12:46:13
【问题描述】:

我有一个名为 test 的数据集,每个参与者有多个观察结果。每个参与者都有一个唯一的 ID,但有几个观察值(数据中的 1 行 = 1 个观察值)。我必须将数据集减少到每个参与者 1 行,并添加两个新变量,它们是 no 的总和。每个参与者的观察次数和他或她每次观察获得的分数总和。

我已经得到了这个值,但是如何根据这个代码创建这两个变量并将其添加到我的数据集中?

test %>%
  group_by(id) %>%
  summarize(sum_communities = sum(id/id, na.rm = TRUE))
test %>%
  group_by(id) %>%
  summarize(sum_points = sum(points, na.rm = TRUE))

【问题讨论】:

  • 我不对名称进行任何赋值。即使在 tidyverse 中,你仍然需要这样做。
  • 欢迎来到 StackOverflow!请阅读有关how to ask a good question 的信息以及如何提供reproducible example。这将使其他人更容易帮助您。

标签: r dplyr


【解决方案1】:

我在测试表中创建了一个演示数据。 test_reduced 表具有所需的输出。

library(dplyr)
test = data.frame("Participent" =c("A","A","A","B","B","C","C","C", "C"), 
       "Observation" = c(4,5,6,4,7,4,6,6,3))
test_reduced = test %>% group_by(Participent) %>% 
                summarise(count = n(), sum = sum(Observation))

输出:

 # A tibble: 3 x 3
  Participent count   sum
  <fct>       <int> <dbl>
 1 A               3    15
 2 B               2    11
 3 C               4    19

【讨论】:

    猜你喜欢
    • 2016-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-02
    • 1970-01-01
    相关资源
    最近更新 更多