在R中破解replace_na_if的最佳方法

时间:2017-06-26 16:25:20

标签: r dplyr

缺少replace_na_if动词,系统地替换具有相同值的所有字符/数字/逻辑/等...列中的NA的最佳方法是什么?这就是我现在所做的事情。

starwars %>% 
  # islolate the columns for the post
  select_if(is.numeric) %>%
  filter(!complete.cases(.))

# A tibble: 51 x 3
   height  mass birth_year
    <int> <dbl>      <dbl>
 1     97    32         NA
 2    180    NA         64
 3    180   110         NA
 4    150    NA         48
 5     NA    NA         NA
 6    160    68         NA
 7    191    90         NA
 8    170    NA         91
 9    224    82         NA
10    206    NA         NA
# ... with 41 more rows

starwars %>% 
  # isolate the columns for the post
  select_if(is.numeric) %>%
  filter(!complete.cases(.)) %>% 
  replace_na(as.list(
    setNames(rep(0, sum(map_chr(., class) == "numeric")),
             colnames(.)[map_chr(., class) == "numeric"])))

# A tibble: 51 x 3
   height  mass birth_year
    <int> <dbl>      <dbl>
 1     97    32          0
 2    180     0         64
 3    180   110          0
 4    150     0         48
 5     NA     0          0
 6    160    68          0
 7    191    90          0
 8    170     0         91
 9    224    82          0
10    206     0          0
# ... with 41 more rows

2 个答案:

答案 0 :(得分:1)

您可以合并mutate_ififelse来实现此目标:

library(dplyr)
starwars %>% mutate_if(is.numeric, funs(ifelse(is.na(.), 0, .)))

您也可以使用tidyr :: replace_na,但您需要提供列列表及其填充值:

library(tidyr)
replace_ls <- starwars %>% 
  select_if(is.numeric) %>% names() %>% 
  sapply( function(x) 0, USE.NAMES=TRUE) %>% 
  as.list()

replace_na(starwars, replace_ls)

答案 1 :(得分:0)

因为is.na有一个data.frame方法,所以它就像

一样简单
starwars[is.na(starwars)] <- 0