dplyr mutate:使用另一列的第一个匹配项创建列

dplyr mutate:使用另一列的第一个匹配项创建列,r,dplyr,R,Dplyr,我想知道是否有一种更优雅的方法来获取数据帧,通过x分组以查看数据集中出现了多少个x,然后变异以找到每个x的第一个出现(y) 电流输出 在按“x”分组后,我们可以先使用来创建一个新列,也可以在groupby中使用该列,并使用n()获取计数 库(dplyr) 测试%>% 分组依据(x)%>% 分组依据(第一次查看=第一次(y),添加=真实)%>% 总结(计数=n() #一个tibble:7x3 #组别:x[7] #x第一次看到的计数 # #一一一一 #2b12 #3 c 1 2 #

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

电流输出
在按“x”分组后,我们可以先使用
来创建一个新列,也可以在
groupby
中使用该列,并使用
n()获取计数

库(dplyr)
测试%>%
分组依据(x)%>%
分组依据(第一次查看=第一次(y),添加=真实)%>%
总结(计数=n()
#一个tibble:7x3
#组别:x[7]
#x第一次看到的计数
#         
#一一一一
#2b12
#3 c 1 2
#4 d 1 1
#5 e 2 1
#6F21
#7 g 2 1

我有个问题。为什么不保持简单呢?比如说

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
测试%>%
分组依据(x)%>%
总结(
计数=n(),
第一次看到=第一次(y)
)
#>#tibble:7 x 3
#>第一次看到的x计数
#>          
#>一一一一
#>2B21
#>3 c 2 1
#>4 d 1 1
#>5 e 1 2
#>6 f 1 2
#>7 g 1 2

您只需将该列添加到摘要中,使其成为摘要(count=n(),first_seen=first(y))
即可获得该输出。
  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
# 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")
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
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