R语言 获取每组的最后n个

ars1skjm  于 2023-04-03  发布在  其他
关注(0)|答案(1)|浏览(165)

假设我有这样的数据:

df <- tibble(id = c(1, 1, 1, 2, 2, 2, 2),
              value = c(1, 2, 3, 1, 5, 4, 1))

我想重塑数据,以便考虑最后4个出现的值。即:

A tibble: 2 × 5
     id  last last2 last3 last4
  <dbl> <dbl> <dbl> <dbl> <dbl>
1     1     3     2     1    NA
2     2     1     4     5     1

到目前为止,我实现了用

df %>% group_by(id) %>% summarise(last = dplyr::last(value))

有什么想法吗?

mftmpeh8

mftmpeh81#

尝试使用pivot_wider

library(dplyr) # version >= 1.1.0
library(tidyr)
library(data.table)
df %>% 
 slice_tail(n = 4, by = id) %>%
 mutate(value = rev(value), .by = id) %>%
 mutate(rn = rowid(id)) %>%
 pivot_wider(names_from = rn, values_from = value, names_prefix = 'last')
  • 输出
# A tibble: 2 × 5
     id last1 last2 last3 last4
  <dbl> <dbl> <dbl> <dbl> <dbl>
1     1     3     2     1    NA
2     2     1     4     5     1

或使用unnest

df %>% 
  reframe(last = list(rev(tail(value, 4))), .by = id) %>% 
  unnest_wider(last, names_sep = "")
  • 输出
# A tibble: 2 × 5
     id last1 last2 last3 last4
  <dbl> <dbl> <dbl> <dbl> <dbl>
1     1     3     2     1    NA
2     2     1     4     5     1

相关问题