dplyr mutate:使用第一次出现的另一列创建列

时间:2019-12-05 16:13:49

标签: r dplyr

我想知道是否有一种更优雅的方式来获取数据帧,按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")

2 个答案:

答案 0 :(得分:4)

按'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

答案 1 :(得分: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