Username
Username

Reputation: 3663

How do I change NA to 0 with lapply()?

I have a list of datasets.

dfList <- list(df1,df2,df3)

Each dataset looks like this.

apples, oranges
1,      2
NA,     4

I want to programatically change each dataframe's NAs to 0s. How do I do this?

My code so far...

lapply(
  X = dfList,
  FUN = cbind,
  is.na = FALSE
)

Upvotes: 5

Views: 1452

Answers (1)

akrun
akrun

Reputation: 887961

We can use 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

data

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

Upvotes: 6

Related Questions