如何使用lapply()函数将NA更改为0?

5

我有一个数据集列表。

dfList <- list(df1,df2,df3)

每个数据集看起来都像这样。
apples, oranges
1,      2
NA,     4

我希望以编程方式将每个数据框中的NA更改为0。我该如何实现?
到目前为止,我的代码是...
lapply(
  X = dfList,
  FUN = cbind,
  is.na = FALSE
)

2
从你过去的两个问题来看,阅读help(lapply)可能对你有所帮助。 - Rich Scriven
1个回答

6
我们可以使用replace
dfList1 <- lapply(dfList, function(x) replace(x, is.na(x), 0))
dfList1
#[[1]]
#  apples oranges
#1      1       2
#2      0       4

#[[2]]
#  apples oranges
#1      1       2
#2      0       4

#[[3]]
#  apples oranges
#1      1       2
#2      0       4

数据

df2 <- df1
df3 <- df1
dfList1 <- list(df1, df2, df3)

1
@Sathish 我必须为x提供一个返回语句。 - akrun

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接