如何在R数据帧中用零替换NA值?

本文介绍了在R中如何将数据框中的NA值替换为零,包括使用`ifelse`函数、在导出时替换、利用dplyr包的`mutate_each`函数,以及定义自定义函数等不同方法。
摘要由CSDN通过智能技术生成

本文翻译自:How do I replace NA values with zeros in an R dataframe?

I have a data frame and some columns have NA values. 我有一个数据框,有些列有NA值。

How do I replace these NA values with zeroes? 如何用零代替这些NA值?


#1楼

参考:https://stackoom.com/question/YFGW/如何在R数据帧中用零替换NA值


#2楼

You can use replace() 您可以使用replace()

For example: 例如:

> x <- c(-1,0,1,0,NA,0,1,1)
> x1 <- replace(x,5,1)
> x1
[1] -1  0  1  0  1  0  1  1

> x1 <- replace(x,5,mean(x,na.rm=T))
> x1
[1] -1.00  0.00  1.00  0.00  0.29  0.00 1.00  1.00

#3楼

如果我们在导出时尝试替换NA ,例如在写入csv时,则可以使用:

  write.csv(data, "data.csv", na = "0")

#4楼

dplyr example: dplyr示例:

library(dplyr)

df1 <- df1 %>%
    mutate(myCol1 = if_else(is.na(myCol1), 0, myCol1))

Note: This works per selected column, if we need to do this for all column, see @reidjax 's answer using mutate_each . 注意:这适用于每个选定的列,如果我们需要对所有列执行此操作,请参阅@reidjax使用mutate_each的答案。


#5楼

I know the question is already answered, but doing it this way might be more useful to some: 我知道这个问题已经回答了,但是这样做对某些人可能更有用:

Define this function: 定义此功能:

na.zero <- function (x) {
    x[is.na(x)] <- 0
    return(x)
}

Now whenever you need to convert NA's in a vector to zero's you can do: 现在,每当需要将向量中的NA转换为零时,都可以执行以下操作:

na.zero(some.vector)

#6楼

More general approach of using replace() in matrix or vector to replace NA to 0 在矩阵或向量中使用replace()NA替换为0更通用方法

For example: 例如:

> x <- c(1,2,NA,NA,1,1)
> x1 <- replace(x,is.na(x),0)
> x1
[1] 1 2 0 0 1 1

This is also an alternative to using ifelse() in dplyr 这也是在dplyr使用ifelse()dplyr

df = data.frame(col = c(1,2,NA,NA,1,1))
df <- df %>%
   mutate(col = replace(col,is.na(col),0))
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值