I've got a table like this:

country    continent      date         n_case         Ex         TD         TC
--------------------------------------------------------------------------------
 Italy      Europe      2022-02-24        6           NA          2          90
 Italy      Europe      2022-01-17        12          87          2          86
 USA        America     2022-02-23        NA          NA          3          65
 USA        America     2022-01-08        6           NA          5          67
 USA        America     2022-01-04        6           7           7          87
etc etc...

What I wish is a new data frame with one row per country that for each country will store as columns the country name (column = country) and continent (column = continent), and also the latest date reported for each value in the column(date, n_case, Ex, TD, TC):

the desirable data frame:

country    continent      date         n_case         Ex         TD         TC
--------------------------------------------------------------------------------
 Italy      Europe      2022-02-24        6           87          2          90
 USA        America     2022-02-23        6           7           3          65
 etc etc..

values to ignore are either NA or " " (blank)

thank you!

推荐答案

With dplyr, you can sort the data by dates decreasingly and then select the first non-NA value in each column.

library(dplyr)

df %>%
  group_by(country, continent) %>%
  arrange(desc(date), .by_group = TRUE) %>% 
  summarise(across(everything(), ~ .x[!is.na(.x)][1])) %>%
  ungroup()

# # A tibble: 2 × 7
#   country continent date       n_case    Ex    TD    TC
#   <chr>   <chr>     <date>      <int> <int> <int> <int>
# 1 Italy   Europe    2022-02-24      6    87     2    90
# 2 USA     America   2022-02-23      6     7     3    65

Data
df <- structure(list(country = c("Italy", "Italy", "USA", "USA", "USA"),
continent = c("Europe", "Europe", "America", "America", "America"),
date = structure(c(19047, 19009, 19046, 19000, 18996), class = "Date"), 
n_case = c(6L, 12L, NA, 6L, 6L), Ex = c(NA, 87L, NA, NA, 7L),
TD = c(2L, 2L, 3L, 5L, 7L), TC = c(90L, 86L, 65L, 67L, 87L)),
row.names = c(NA, -5L), class = "data.frame")

R相关问答推荐

在R中为马赛克图中的每个字段着色

如果某些列全部为NA,则更改列

在ggplot中为不同几何体使用不同的 colored颜色 比例

从所有项的 struct 相同的两级列表中,将该第二级中的所有同名项绑定在一起

在ggplot2的框图中绘制所有级别的系数

如何使用For-R循环在向量中找到一系列数字

按组内中位数分类

以任意顺序提取具有多个可能匹配项的组匹配项

R-如何在ggplot2中显示具有不同x轴值(日期)的多行?

每行不同列上的行求和

具有自定义仓位限制和计数的GGPLATE直方图

条形图中的条形图没有try 赋予它们的 colored颜色

如何从矩阵绘制环弦图

用逗号拆分字符串,并删除一些字符

使用另一列中的增长率外推R(使用dplyr)

使用条件格式R替换字符串中的字符

如何在分子和分母垂直对齐并由水平线分隔的情况下为除法添加批注

将3个连续公式的函数应用于具有相同变量的稳健数据框

如何反转R中数据表的排序操作?

使用增量时隙数据帧使用R创建房间