将R中的所选列中的所有NA替换为FALSE [英] Replace all NA with FALSE in selected columns in R

查看:538
本文介绍了将R中的所选列中的所有NA替换为FALSE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似于这一个的问题,但我的数据集有点大:50列,1列为UID,其他列为 TRUE NA ,我想将所有 NA 更改为 FALSE ,但我不想使用显式循环。

I have a question similar to this one, but my dataset is a bit bigger: 50 columns with 1 column as UID and other columns carrying either TRUE or NA, I want to change all the NA to FALSE, but I don't want to use explicit loop.

可以 plyr 做窍门吗?谢谢。

感谢您的快速回复,但如果我的数据集如下所示: / p>

Thanks for quick reply, but what if my dataset is like below:

df <- data.frame(
  id = c(rep(1:19),NA),
  x1 = sample(c(NA,TRUE), 20, replace = TRUE),
  x2 = sample(c(NA,TRUE), 20, replace = TRUE)
)

我只想要 X1 X2 要处理,怎么办?

I only want X1 and X2 to be processed, how can this be done?

推荐答案

如果你想做更换对于变量的一个子集,您仍然可以使用 is.na(*)< - 技巧,如下所示:

If you want to do the replacement for a subset of variables, you can still use the is.na(*) <- trick, as follows:

df[c("x1", "x2")][is.na(df[c("x1", "x2")])] <- FALSE

使用临时变量的IMO使逻辑更容易遵循:

IMO using temporary variables makes the logic easier to follow:

vars.to.replace <- c("x1", "x2")
df2 <- df[vars.to.replace]
df2[is.na(df2)] <- FALSE
df[vars.to.replace] <- df2

这篇关于将R中的所选列中的所有NA替换为FALSE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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