【问题标题】:Count numer of independent observations in group with repeated meassures用重复测量计算组中独立观察的数量
【发布时间】:2019-05-29 21:54:07
【问题描述】:

我想计算具有重复测量的组中每组独立观察的数量。

这里有一些玩具数据

library(dplyr)
df <- bind_rows(mtcars, mtcars, mtcars) %>%
 mutate(id=rep(row.names(mtcars),3)) 

在这个数据中,

df %>% group_by(cyl, id) %>% count()

显示

# A tibble: 32 x 3
# Groups:   cyl, id [32]
     cyl id                 n
   <dbl> <chr>          <int>
 1     4 Datsun 710         3
 2     4 Fiat 128           3
 3     4 Fiat X1-9          3
 4     4 Honda Civic        3
 5     4 Lotus Europa       3
 6     4 Merc 230           3
 7     4 Merc 240D          3
 8     4 Porsche 914-2      3
 9     4 Toyota Corolla     3
10     4 Toyota Corona      3
# … with 22 more rows

这是每个人(也就是每辆车)的观察次数。要获得每组独立观察的数量(每个cyl 有多少辆车),我可以这样做。

df %>% group_by(cyl,id) %>% count() %>% ungroup() %>% group_by(cyl) %>% count()
# A tibble: 3 x 2
# Groups:   cyl [3]
    cyl     n
  <dbl> <int>
1     4    11
2     6     7
3     8    14

给出正确的结果(检查mtcars %&gt;% group_by(cyl) %&gt;% count()

group_by(...) %&gt;% count() %&gt;% ungroup() %&gt;% group_by() %&gt;% count() 对我来说并不直观。

我错过了什么?有没有更好的方法来做到这一点?

相关问题,有没有办法将计数输入原始 df 或者您需要一个新对象和left_join(...)

【问题讨论】:

  • 比你的方法短一点是df %&gt;% count(cyl,id) %&gt;% count(cyl)

标签: r dplyr


【解决方案1】:

你需要n_distinct() -

df %>% group_by(cyl) %>% summarize(n = n_distinct(id))

# A tibble: 3 x 2
    cyl     n
  <dbl> <int>
1     4    11
2     6     7
3     8    14

对于您的相关问题,您可以这样做-

df %>% 
  group_by(cyl) %>% 
  mutate(n = n_distinct(id)) %>% 
  ungroup()

【讨论】:

  • 太棒了,看起来像 n_distinct() 的行为有点像我们对 unique(df$id) 的期望,但由于 group_by() 嵌套在组中。
  • 是的,您可以将其视为每个组内的length(unique(df$id))
猜你喜欢
  • 1970-01-01
  • 2020-12-05
  • 2021-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-02
  • 1970-01-01
  • 2022-11-16
相关资源
最近更新 更多