使用starts_with()将NA替换为0 [英] replace NA with 0 using starts_with()

查看:90
本文介绍了使用starts_with()将NA替换为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用tibble中的一组特定列替换NA值.这些列都以相同的前缀开头,所以我想知道是否有一种简洁的方法可以利用dplyr包中的starts_with()函数,使我能够做到这一点.

I am trying to replace NA values for a specific set of columns in my tibble. The columns all start with the same prefix so I am wanting to know if there is a concise way to make use of the starts_with() function from the dplyr package that would allow me to do this.

我还看到了关于SO的其他几个问题,但是它们都需要使用特定的列名或位置.我真的想变得懒惰,不想定义所有列,只是前缀.

I have seen several other questions on SO, however they all require the use of specific column names or locations. I'm really trying to be lazy and not wanting to define ALL columns, just the prefix.

我已经尝试过tidyr包中的replace_na()函数,但无济于事.我知道我的代码对于作业是错误的,但是我的词汇量不够大,无法知道在哪里查找.

I've tried the replace_na() function from the tidyr package to no avail. I know the code I have is wrong for the assignment, but my vocabulary isn't large enough to know where to look.

代表:

library(tidyverse)

tbl1 <- tibble(
 id = c(1, 2, 3),
 num_a = c(1, NA, 4),
 num_b = c(NA, 99, 100),
 col_c = c("d", "e", NA)
)

replace_na(tbl1, list(starts_with("num_") = 0)))

推荐答案

mutate_atif_else(或case_when)一起使用怎么样?如果您要将感兴趣的列中的所有NA都替换为0,则此方法有效.

How about using mutate_at with if_else (or case_when)? This works if you want to replace all NA in the columns of interest with 0.

mutate_at(tbl1, vars( starts_with("num_") ), 
          funs( if_else( is.na(.), 0, .) ) )

# A tibble: 3 x 4
     id num_a num_b col_c
  <dbl> <dbl> <dbl> <chr>
1     1     1     0     d
2     2     0    99     e
3     3     4   100  <NA>

请注意,starts_with和其他选择助手会返回给出匹配变量位置的整数向量.在我通常无法使用的情况下尝试使用它们时,我始终必须牢记这一点.使用它们.

Note that starts_with and other select helpers return An integer vector giving the position of the matched variables. I always have to keep this in mind when trying to use them in situations outside how I normally use them..

在较新版本的 dplyr 中,将list()与波浪号一起使用,而不是funs():

In newer versions of dplyr, use list() with a tilde instead of funs():

list( ~if_else( is.na(.), 0, .) )

这篇关于使用starts_with()将NA替换为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆