如何在复杂的行操作中使用逐行变异?

如何使用mutate实现以下目标?

bd_diag_date <- df %>%
  apply(1, function(dates) last(na.omit(dates))) %>%
  as.data.frame() %>%
  `colnames<-`("diag_date")

I tried this below but didn't work. I can't find out why and it says Error: Column 'diagnosis_date' is of unsupported type symbol. Should I assume mutate takes any function operation that can apply to a vector? If not, then what kind of operation does it accept?

bd_diag_date <- df %>%
  rowwise() %>%
  {mutate(., diag_date=last(na.omit(all_vars(.))))}

我还有一个更一般的问题。那是我该如何调试呢?每次遇到此问题时,我都必须使用Google Stack进行交换,但是我觉得这不是提高我的dplyr技能的正确方法。

评论
  • xiebruce
    xiebruce 回复

    我们可以用

    library(dplyr)
    df %>%
          rowwise %>%
          mutate(diag_date = last(na.omit(.)))
    

    or using pmap

    library(purrr)
    df %>%
       mutate(diag_date = pmap(., ~ last(na.omit(c(...)))))