如何根据其他变量非NA值替换tibble中dispone变量的NA值?
问题:替换tibble中dispone变量的NA值
我有一个字符类型的tibble数据,其中dispone变量存在多个NA值。需要根据comp至comp_reu变量中是否存在非NA的"Sí"或"No"值,将dispone的NA值替换为"Sí"。以下是我尝试的几种dplyr写法及报错:
尝试1:错误的mutate格式
trans <- trans %>% mutate(dispone, ~ case_when("Sí" %in% c(across(comp:comp_reu)) ~ "Sí", "No" %in% c(across(comp:comp_reu)) ~ "Sí", TRUE ~ .))
报错信息:
x `..2` must be a vector, not a `formula` object.
尝试2:使用rowwise但条件分支错误
trans <- trans %>% rowwise() %>% mutate(dispone = case_when("Sí" %in% c(across(comp:comp_reu)) ~ "Sí", "No" %in% c(across(comp:comp_reu)) ~ "Sí",TRUE ~ .))
报错信息:
Error in `mutate()`:! Problem while computing `dispone = case_when(...)`. i The error occurred in row 1. Caused by error in `` names(message) <- `*vtmp*` ``: ! 'names' attribute [1] must be the same length as the vector [0] Run `rlang::last_error()` to see where the error occurred.
尝试3:使用c_across但分支逻辑错误
trans <- trans %>% rowwise() %>% mutate(dispone = case_when("Sí" %in% c_across(comp:comp_reu) ~ "Sí", "No" %in% c_across(comp:comp_reu) ~ "Sí", TRUE ~ .))
报错信息:
Error in `mutate()`: ! Problem while computing `dispone = case_when(...)`. i The error occurred in row 1. Caused by error in `` names(message) <- `*vtmp*` ``: ! 'names' attribute [1] must be the same length as the vector [0] Run `rlang::last_error()` to see where the error occurred.
尝试4:错误的列范围使用方式
trans <- trans %>% mutate(dispone = case_when(!is.na(comp:comp_reu) ~ "Sí", TRUE ~ .))
报错信息:
Error in `mutate()`: ! Problem while computing `dispone = case_when(!is.na(comp:comp_reu) ~ "Sí", TRUE ~ .)`. Caused by error in `comp:comp_reu`: ! NA/NaN argument Run `rlang::last_error()` to see where the error occurred. Warning messages: 1: Problem while computing `dispone = case_when(!is.na(comp:comp_reu) ~ "Sí", TRUE ~ .)`. i numerical expression has 968 elements: only the first used
尝试5:错误的非NA检测写法
trans<- trans %>% rowwise() %>% mutate(dispone = case_when(!is.na %in% c_across(comp:comp_reu) ~ "Sí", TRUE ~ .))
正确解法
方法1:使用rowwise + c_across(适合小数据集)
trans <- trans %>% rowwise() %>% mutate( dispone = case_when( # 仅当dispone为NA,且目标列存在非NA的"Sí"或"No"时替换 is.na(dispone) & any(c_across(comp:comp_reu) %in% c("Sí", "No"), na.rm = TRUE) ~ "Sí", # 其他情况保持原变量值 TRUE ~ dispone ) ) %>% ungroup() # 取消行分组,避免后续操作性能下降
方法2:使用if_any(无需rowwise,性能更优,推荐)
trans <- trans %>% mutate( dispone = case_when( is.na(dispone) & if_any(comp:comp_reu, ~ .x %in% c("Sí", "No"), na.rm = TRUE) ~ "Sí", TRUE ~ dispone ) )
内容的提问来源于stack exchange,提问作者FrancoBattiato
相关产品推荐
相关产品推荐

