Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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
)
like image 597
Username Avatar asked Mar 20 '17 02:03

Username


1 Answers

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)
like image 76
akrun Avatar answered Oct 10 '22 14:10

akrun