如何填充数据直到最后一个非缺失值?

我有一些数据按let分组:

events <- structure(list(let = c("A","A","B","B"),age = c(0L,4L,16L,0L,8L,7L),value = c(61L,60L,13L,29L,56L,99L)),class = "data.frame",row.names = c("1","2","3","4","5","6"))

  let age value
1   A   0    61
2   A   4    60
3   A  16    13
4   B   0    29
5   B   8    56
6   B   7    99

如何投射数据框,以便:

  1. 年龄是分为几周的多列。因此,对于每一列,取小于或等于0、7、14等天的最大年龄的值
  2. 在年龄之前填写let,直到最后一个非缺失值。

最终结果如下:

    events.cast <- data.frame(
 let = LETTERS[1:2],T0_value = c(61,29),T1_value = c(60,99),T2_value = c(60,56),T3_value = c(13,56))

 let T0_value T1_value T2_value T3_value
1   A       61       60       60       13
2   B       29       99       56       NA

请注意,这来自我问的previous question

jishuailove 回答:如何填充数据直到最后一个非缺失值?

我们可以在complete之前创建一个'actuals'列,并根据'actuals'中NA的出现使用它来在'value'列中创建NA

library(dplyr)
library(tidyr)
library(stringr)
events %>% 
    group_by(grp = cut(age,breaks = c(-Inf,7,14,21),labels = str_c("T",0:3,"_value")),let) %>% 
    slice(which.max(value)) %>%
    ungroup %>%
    select(-age) %>% 
    mutate(actuals = TRUE) %>%  
    group_by(let) %>% 
    complete(grp = unique(.$grp)) %>% 
    fill(value) %>%
    ungroup %>%
    mutate(i1 = cumsum(is.na(actuals)),value = replace(value,i1 == max(i1),NA)) %>%
    select(-i1,-actuals) %>%
    pivot_wider(names_from = grp,values_from = value)
# A tibble: 2 x 5
#  let   T0_value T1_value T2_value T3_value
#  <chr>    <int>    <int>    <int>    <int>
#1 A           61       60       60       13
#2 B           29       99       56       NA
本文链接:https://www.f2er.com/2883918.html

大家都在问