【问题标题】:Using purrr functions to replace NAs with is.na使用 purrr 函数将 NA 替换为 is.na
【发布时间】:2017-05-11 22:21:24
【问题描述】:

我正在寻找一种使用 R 中的 purrr::map() 函数套件替换各种列表项中的 NA 的方法。看起来这应该是一项简单的任务,但我无法让它工作。

以下作品:

 vec1 <- c(3,6,7,NaN)
 vec1[is.na(vec1)] <- 0

但是当我尝试使用 map() 对向量列表执行此操作时,它不起作用:

 library(purrr)

 vec1 <- c(3,6,7,NaN)
 vec2 <- c(2,3,4)
 vec3 <- c(1,6,NaN,NaN,1)

 veclist <- list(a = vec1,
                 b = vec2,
                 c = vec3)

 veclistnew <- map(veclist, function(vec){vec[is.na(vec)] <- 0})

想法?我希望输出是原始向量的列表,其中 NA 被 0 替换。

【问题讨论】:

    标签: r purrr


    【解决方案1】:

    您可以执行以下操作:

    na_to_y <- function(x, y){
      x[is.na(x)] <- y
      x # you need to return the vector after replacement
    }
    
    map(veclist, na_to_y, 0)
    

    【讨论】:

      【解决方案2】:

      另一个选项是replace

      library(purrr)
      veclist %>% 
          map(~replace(., is.nan(.), 0))
      #$a
      #[1] 3 6 7 0
      
      #$b
      #[1] 2 3 4
      
      #$c
      #[1] 1 6 0 0 1
      

      【讨论】:

        【解决方案3】:

        你也可以从dplyr使用coalesce

        library(dplyr)
        veclistnew <- map(veclist, ~coalesce(., 0))
        
        > veclistnew
        $a
        [1] 3 6 7 0
        
        $b
        [1] 2 3 4
        
        $c
        [1] 1 6 0 0 1
        

        【讨论】:

          猜你喜欢
          • 2019-07-22
          • 1970-01-01
          • 2020-09-20
          • 2017-11-27
          • 2019-11-14
          • 2022-01-24
          • 1970-01-01
          • 2019-05-20
          • 2020-10-28
          相关资源
          最近更新 更多