【问题标题】:dplyr mutate: create column using first occurrence of another columndplyr mutate:使用第一次出现的另一列创建列
【发布时间】:2019-12-05 16:13:49
【问题描述】:

我想知道是否有更优雅的方式来获取数据帧,按x 分组以查看数据集中出现了多少 x,然后变异以查找每个 x 的第一次出现 (y)

test <- data.frame(x = c("a", "b", "c", "d", 
                         "c", "b", "e", "f", "g"),
                   y = c(1,1,1,1,2,2,2,2,2)) 
  x y
1 a 1
2 b 1
3 c 1
4 d 1
5 c 2
6 b 2
7 e 2
8 f 2
9 g 2

电流输出

output <- test %>% 
  group_by(x) %>%
  summarise(count = n())
  x     count
  <fct> <int>
1 a         1
2 b         2
3 c         2
4 d         1
5 e         1
6 f         1
7 g         1

期望的输出

  x     count first_seen
  <fct> <int> <dbl>
1 a         1     1
2 b         2     1
3 c         2     1
4 d         1     1
5 e         1     2
6 f         1     2
7 g         1     2

我可以过滤test 数据框以查找第一次出现,然后使用left_join,但希望使用mutate 有更优雅的解决方案?

# filter for first occurrences of y
right <- test %>% 
  group_by(x) %>% 
  filter(y == min(y)) %>% 
  slice(1) %>%
  ungroup()

# bind to the output dataframe
left_join(output, right, by = "x")

【问题讨论】:

  • 您只需将该列添加到您的摘要中,将其设为summarise(count = n(), first_seen = first(y)) 即可获得该输出。

标签: r dplyr


【解决方案1】:

我们可以在按'x'分组后使用first创建一个新列,在group_by中也使用它并通过n()获取计数

library(dplyr)
test %>% 
   group_by(x) %>%
   group_by(first_seen = first(y), add = TRUE) %>% 
   summarise(count = n())
# A tibble: 7 x 3
# Groups:   x [7]
#  x     first_seen count
#  <fct>      <dbl> <int>
#1 a              1     1
#2 b              1     2
#3 c              1     2
#4 d              1     1
#5 e              2     1
#6 f              2     1
#7 g              2     1

【讨论】:

    【解决方案2】:

    我有一个问题。为什么不保持简单?例如

    test %>% 
      group_by(x) %>% 
      summarise(
        count = n(), 
        first_seen = first(y)
        )
    #> # A tibble: 7 x 3
    #>   x     count first_seen
    #>   <chr> <int>      <dbl>
    #> 1 a         1          1
    #> 2 b         2          1
    #> 3 c         2          1
    #> 4 d         1          1
    #> 5 e         1          2
    #> 6 f         1          2
    #> 7 g         1          2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-12
      • 2017-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多