如何给R中组的最后一行赋值?

问题描述 投票:0回答:1

这个问题类似,我想选择每组的最后一行并为其赋值。

 a <- data.frame("ID" = c("A", "A", "B", "B", "C", "C"),
                 "NUM" = c(1, 2, 4, 3, 6, 9),
                 "VAL" = c(1, 0, 1, 0, 1, 0))
 
 ID NUM VAL
  A   1   1
  A   2   0
  B   4   1
  B   3   0
  C   6   1
  C   9   0

我想要的输出:

 ID NUM VAL end.spell
  A   1   1         0
  A   2   0         1
  B   4   1         0
  B   3   0         1
  C   6   1         0
  C   9   0         1

我该怎么做?如有任何帮助,我们将不胜感激。

r variables dplyr tidyverse data-cleaning
1个回答
0
投票

使用

group_by()
中的
dplyr
,您可以识别行号与该组的行数相同的情况,并为该观察给出 1,否则为 0。

library(dplyr)
a <- data.frame("ID" = c("A", "A", "B", "B", "C", "C"),
                "NUM" = c(1, 2, 4, 3, 6, 9),
                "VAL" = c(1, 0, 1, 0, 1, 0))


a %>% 
  group_by(ID) %>% 
  mutate(end.spell = ifelse(row_number() == n(), 1,0))
#> # A tibble: 6 × 4
#> # Groups:   ID [3]
#>   ID      NUM   VAL end.spell
#>   <chr> <dbl> <dbl>     <dbl>
#> 1 A         1     1         0
#> 2 A         2     0         1
#> 3 B         4     1         0
#> 4 B         3     0         1
#> 5 C         6     1         0
#> 6 C         9     0         1

创建于 2024-01-22,使用 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.