按组获取基于日期列的最新非NA值

3
我有一个数据框,其中包含“country_name”、“date”和几个列: “column_1”、“column_2”和“column_3”。我正在尝试基于日期跨多个列提取最新记录。
数据框如下所示:
| country_name | date        | column_1| column_2| column_3|
| US           | 2016-11-02  | 7.5     | NA      | NA      |
| US           | 2017-09-12  | NA      | NA      | 9       |
| US           | 2017-09-19  | NA      | 8       | 10      |
| US           | 2020-02-10  | 10      | NA      | NA      |
| US           | 2021-03-10  | NA      | NA      | 7.3     |
| US           | 2021-05-02  | NA      | 3       | NA      |
| UK           | 2016-11-02  | NA      | 2       | NA      |
| UK           | 2017-09-12  | 0.5     | 3       | NA      |
 .
 .

对于美国,期望的输出为:

| country_name | column_1| column_2| column_3|
| US           | 10      | 3       | 7.3     |
column_1的最新日期的值为10(日期:2020年2月10日), column_2的最新日期值为3(日期:2021年5月2日), column_3的最新日期值为7.3(日期:2021年3月10日)。 我的目标是将此逻辑应用于多个国家。我该如何实现?
5个回答

4
library(dplyr)
library(tidyr)

df1 %>% 
  mutate(date = as.Date(date)) %>% 
  group_by(country_name) %>%
  arrange(date) %>%
  select(-date) %>% 
  fill(everything()) %>% 
  slice(n())

#> # A tibble: 2 x 4
#> # Groups:   country_name [2]
#>   country_name column_1 column_2 column_3
#>   <chr>           <dbl>    <int>    <dbl>
#> 1 UK                0.5        3     NA  
#> 2 US               10          3      7.3

数据:

read.table(text = "country_name  date         column_1 column_2 column_3
                   US            2016-11-02   7.5      NA       NA      
                   US            2017-09-12   NA       NA       9       
                   US            2017-09-19   NA       8        10      
                   US            2020-02-10   10       NA       NA      
                   US            2021-03-10   NA       NA       7.3     
                   US            2021-05-02   NA       3        NA      
                   UK            2016-11-02   NA       2        NA      
                   UK            2017-09-12   0.5      3        NA", 
           header = T, stringsAsFactors = F) -> df1

1

更新:

感谢 @Darren Tsai 处理警告:

Warning: Problem while computing `..1 = across(-country_name, ~parse_number(.)).
i 1 parsing failure. row col expected actual 1 -- a number NA NA

添加这行代码:

 mutate(across(-country_name, ~str_trim(str_replace_all(., 'NA', ''))))

library(tidyverse)
library(lubridate)

df1 %>% 
  mutate(date = ymd(date)) %>% 
  group_by(country_name) %>%
  arrange(date, .by_group = TRUE) %>% 
  summarise(across(starts_with("column"), ~paste(rev(.), collapse = ' '))) %>% 
  mutate(across(-country_name, ~str_trim(str_replace_all(., 'NA', '')))) %>% 
  mutate(across(-country_name, ~parse_number(.)))

  country_name column_1 column_2 column_3
  <chr>           <dbl>    <dbl>    <dbl>
1 UK                0.5        3     NA  
2 US               10          3      7.3

第一个答案:

以下是我们可以实现它的方法:

  1. 如果必要,使用lubridate库中的ymd()函数将date列转换为日期类型。
  2. country_name分组。
  3. 现在来介绍一下我们使用across对col1 col2等进行操作,并使用paste(rev(.)....对其进行倒序合并,以使最后一个值移到第一个位置。这对于下一步非常重要。
  4. 使用readr包中的parse_number()函数提取第一个数字!
library(dplyr)
library(lubridate)
library(readr)

df %>% 
  mutate(date = ymd(date)) %>% 
  group_by(country_name) %>%
  arrange(date, .by_group = TRUE) %>% 
  summarise(across(starts_with("column"), ~paste(rev(.), collapse = ' '))) %>% 
  mutate(across(-country_name, parse_number))


 country_name column_1 column_2 column_3
  <chr>           <dbl>    <dbl>    <dbl>
1 UK                0.5        3     NA  
2 US               10          3      7.3

好的,我明白了,谢谢。我会去检查它。 - TarJae

1

你可以使用na.omitrev函数来清除空值并反转每一列,并获取第一个元素。然后使用rbind函数进行合并。注意正确的顺序以及是否为as.Date格式。

by(transform(dat, date=as.Date(date)), dat$country_name, \(x) {
  cbind(x[1, 1, drop=FALSE], 
        lapply(x[order(x$date), 3:5], \(z) {
          z <- el(rev(na.omit(z)))
          ifelse(length(z) == 1, z, NA_real_)
        }))
}) |> c(make.row.names=FALSE) |> do.call(what=rbind)
#   country_name column_1 column_2 column_3
# 1           UK      0.5        3       NA
# 2           US     10.0        3      7.3

数据:

dat <- structure(list(country_name = c("US", "US", "US", "US", "US", 
"US", "UK", "UK"), date = c("2016-11-02", "2017-09-12", "2017-09-19", 
"2020-02-10", "2021-03-10", "2021-05-02", "2016-11-02", "2017-09-12"
), column_1 = c(7.5, NA, NA, 10, NA, NA, NA, 0.5), column_2 = c(NA, 
NA, 8L, NA, NA, 3L, 2L, 3L), column_3 = c(NA, 9, 10, NA, 7.3, 
NA, NA, NA)), class = "data.frame", row.names = c(NA, -8L))

0
这里是一个基于R的解决方案。它使用了两个sapply调用:一个用于国家,一个用于列。
foo <- structure(list(country_name = c("US", "US", "US", "US", "US", 
"US", "UK", "UK"), date = c("2016-11-02", "2017-09-12", "2017-09-19", 
"2020-02-10", "2021-03-10", "2021-05-02", "2016-11-02", "2017-09-12"
), column_1 = c(7.5, NA, NA, 10, NA, NA, NA, 0.5), column_2 = c(NA, 
NA, 8L, NA, NA, 3L, 2L, 3L), column_3 = c(NA, 9, 10, NA, 7.3, 
NA, NA, NA)), class = "data.frame", row.names = c(NA, -8L))


split(foo, foo$country_name)|>
  sapply( function(s) {
    s = s[order(s$date),]
    sapply(s[,3:5], function(x) {
       y = na.omit(x)
       ifelse(length(y)> 0, y[length(y)], NA) })}) |>
  t()

#   column_1 column_2 column_3
#UK      0.5        3       NA
#US     10.0        3      7.3

0

您可以使用 across() 在多列中对每个国家进行汇总。最新的非 NA 值可以通过 .x[date == max(date[!is.na(.x)])] 进行子集化。

library(dplyr)

df %>%
  group_by(country_name) %>%
  summarise(across(starts_with("column"),
                   ~ if(all(is.na(.x))) NA else .x[date == max(date[!is.na(.x)])])) %>%
  ungroup()

# # A tibble: 2 × 4
#   country_name column_1 column_2 column_3
#   <chr>           <dbl>    <int>    <dbl>
# 1 UK                0.5        3     NA  
# 2 US               10          3      7.3

另一个想法:

df %>% 
  group_by(country_name) %>%
  arrange(desc(date), .by_group = TRUE) %>% 
  summarise(across(starts_with("column"), ~ .x[!is.na(.x)][1])) %>% 
  ungroup()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接