r - 从特定列中选择值并跳过 R 中的 NA 值

标签 r na col

我正在处理癌症登记数据。在以下数据示例 (ex_data) 中,变量 id 和 diagnostic_yr 分别代表癌症诊断时的 ID 和年份。 x_2005 到 x_2010 和 y_2005 到 y_2010 列分别代表每年(2005 年到 2010 年)的 x 和 y 状态。在我的实际工作数据中,我有很多年(2005-2020 年)的列。我想通过排除 NAs 从最早的可用年份、最晚的可用年份和诊断年份(即“通缉”中的 x_earliest, y_latest,x_at_diagnosis,y_at_diagnosis 变量)中提取 x 和 y 值。例如,对于 id 1,我想通过跳过 NA 从最早的一年中提取 x 值和从最近一年中提取 y 值。对于诊断年份的 x 和 y 值,如果诊断年份有 NA,我想跳过 NA 并提取前一年的可用数据。我如何实现以在 R 中获取想要的变量?

library(tidyverse)

#example data
ex_data <- tribble(
~id,~diagnosis_yr,~x_2005,~x_2006,~x_2007,~x_2008,~x_2009,~x_2010,~y_2005,~y_2006,~y_2007,~y_2008,~y_2009,~y_2010,
1,  2007,   NA, NA, 1,  2,  2,  3,  "a",    "b",    "c",    "d",    "e",    NA, 
2,  2008,   1,  3,  1,  NA, 1,  2,   NA,    "b",    "b",    "e",    "d", "d",
3,  2010,   NA, 2,  2,  2,  3,  NA, "a",    "b",    "c",     NA,     NA,    NA,
4,  2009, 1,    3,  1,  NA, 1,  2,   NA,     NA,     NA,     NA,     NA,    NA,
5,  2005, NA,   1,  1,  2,  2,  3,  "a",    "b",    "c",    "d",    "e",    "e"
)

#wanted variables
wanted <- tribble(
  ~id,~diagnosis_yr,~x_earliest,~y_latest,~x_at_diagnosis,~y_at_diagnosis,
  1,    2007,   1,  "e",    1,  "c",
  2,    2008,   1,  "d",    1,  "e",
  3,    2010,   2,  "c",    3,  "c",
  4,  2009, 1,   NA,  1,  NA,
  5,  2005, 1,  "e", NA,  "a"
)

最佳答案

我不完全确定,如果这是正确的:

library(dplyr)
library(tidyr)

ex_data %>% 
  pivot_longer(-c(id, diagnosis_yr), 
               names_to = c(".value", "year"),
               names_pattern = "(.*)_(\\d+)") %>% 
  group_by(id) %>% 
  mutate(x_earliest     = first(na.omit(x)),
         x_at_diagnosis = last(na.omit(x[diagnosis_yr >= year])),
         y_latest       = last(na.omit(y)),
         y_at_diagnosis = last(na.omit(y[diagnosis_yr >= year]))) %>% 
  select(id, diagnosis_yr, x_earliest, y_latest, x_at_diagnosis, y_at_diagnosis) %>% 
  distinct() %>% 
  ungroup()
这返回
# A tibble: 3 x 6
     id diagnosis_yr x_earliest y_latest x_at_diagnosis y_at_diagnosis
  <dbl>        <dbl>      <dbl> <chr>             <dbl> <chr>         
1     1         2007          1 e                     1 c             
2     2         2008          1 d                     1 e             
3     3         2010          2 c                     3 c    

关于r - 从特定列中选择值并跳过 R 中的 NA 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68913278/

相关文章:

javascript - 将鼠标事件添加到 colgroup 或 col

r - 在 CMD 检查期间找不到函数 "%>%"

xml - 返回 R 网页中的链接列表

r - if 语句中的逻辑 (0)

r - 是否有 R 函数仅从具有许多 NA 值的逗号分隔字符串中提取数字以创建仅包含数字的列?

layout - Bootstrap 4.0 网格系统布局不起作用

jquery - 响应表 : show thead elements' content in corresponding tds

r - 为负值和正值定义颜色渐变 scale_fill_gradientn()

r - 如何格式化 tableHTML 包中的 colnames 文本?

r - 是否可以在 "NA"中区分 NA_character_ 和 `switch` ?