使用 summarize_all AND 格式输出提取第一个和最后一个非 na 值的索引和日期

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

我有一个带有各种时间序列的 tibble df(列变量,各种日期的行观察值),日期列在名为 Date 的第一列中。我想为每一列提取索引和第一个和最后一个非 na 观察的相应日期,然后将它们保存到一个新的数据框中,每个时间序列都有一个列,索引和日期在四行中。

我走到这一步:

df %>% summarise_all(.funs = list(first.idx = ~min(which(!is.na(.))), last.idx = ~max(which(!is.na(.)))) )

但这只适用于索引,我为每个时间序列和函数得到两列,所以一行。如何进行?提前致谢

r dplyr na summarize
1个回答
1
投票

我们可以这样做:

library(dplyr)
library(tidyr)

 df %>% 
   mutate(across(-Date, list(first.idx = ~as.character(min(which(!is.na(.)))),
                               last.idx = ~as.character(max(which(!is.na(.))))))) %>% 
   mutate(across(contains("_"), ~ifelse(. == row_number(), as.character(Date), NA), .names = "date_{.col}")) %>% 
   fill(starts_with("date"), .direction = "updown") %>% 
   slice(1) %>% 
   select(-c(Date, A, B)) %>% 
   pivot_longer(everything())
  name             value     
  <chr>            <chr>     
1 A_first.idx      1         
2 A_last.idx       9         
3 B_first.idx      4         
4 B_last.idx       9         
5 date_A_first.idx 2022-01-01
6 date_A_last.idx  2022-01-09
7 date_B_first.idx 2022-01-04
8 date_B_last.idx  2022-01-09
© www.soinside.com 2019 - 2024. All rights reserved.