使用 mutate() 和 case_when() 操作 NA 时出错

Error when manipulating NAs with mutate() and case_when()

我有一个数据集,其中包含许多死亡年份的缺失值。我想用出生年份 + 79 替换那些 NA,这对应于美国的预期寿命。

num_df = num_df %>%
  mutate(
    gdc_cases.demographic.year_of_death = 
      case_when( 
         is.na(gdc_cases.demographic.year_of_death) ~ round(gdc_cases.demographic.year_of_birth + 79), 
        TRUE ~ gdc_cases.demographic.year_of_death)
    )

但是,我收到一条消息错误,我不确定如何修复它:

Error in mutate(., gdc_cases.demographic.year_of_death = case_when(is.na(gdc_cases.demographic.year_of_death) ~ : 

Caused by error in `` names(message) <- `*vtmp*` ``:
! 'names' attribute [1] must be the same length as the vector [0]

提前致谢!

数据

RData file available here

rse_gene
counts = assay(rse_gene)
genes = rowData(rse_gene)
sample = as.data.frame(colData(rse_gene))
num_df= sample %>% 
  dplyr::select(where(~!all(is.na(.x)))) %>%
  dplyr::select(where(is.numeric)) 

此处的错误消息不是很清楚,但是 case_when 的 RHS 元素都必须是同一类型。目前你有一个 numeric (第一种情况)和一个 integer (第二种情况)。

选择您想要的一个并强制另一个匹配 - 考虑到您使用的是年份,整数似乎更有意义:

num_df = num_df %>%
  mutate(
    gdc_cases.demographic.year_of_death = 
      case_when( 
        is.na(gdc_cases.demographic.year_of_death) ~ as.integer(round(gdc_cases.demographic.year_of_birth + 79)), 
        TRUE ~ gdc_cases.demographic.year_of_death)
  )