R lapply 将 NA 转换为 0 [英] R lapply convert NA's to 0

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

问题描述

我正在尝试使用以下代码将列的子集从 NA 转换为 0.不幸的是,它会将所有单元格变为 0.

I'm trying to convert a subset of columns from NA's to 0's using the following code. Unfortunately it turns all the cells to 0's.

df1 <- data.frame(id = 1:20, col1 = runif(20), col2 = runif(20), col3 = runif(20))

df1[sample(1:20,5),'col1'] <- NA
df1[sample(1:20,5),'col2'] <- NA
df1[sample(1:20,5),'col3'] <- NA

subset1 <- c('col1','col2','col3')

df1[,subset1] <- as.data.frame(lapply(df1[,subset1], function(x) x[is.na(x)] <- 0))

有什么建议吗?

推荐答案

试试这个简单的方法

df1[is.na(df1),] <- 0

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

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