Replace NA in all data tables in the list

I have a list containing many data tables. For each of these tables, I would like to replace NA with 0.

I know how to change the NA for each data table separately, but is there a way to put this in one command, for example using lapply?

For example: li is a list containing two data tables: dt1 and dt2.

li <- list(dt1 = data.table(name = c(4,5), age = c(12, NA)), dt2= data.table(name = c(43,245,243), age = c(354,NA,NA)));

Changing NA to 0 in a single .table data file works like a charm:

d <- "dt1";
li[[d]][is.na(li[[d]])]<-0;

Results in:

> li
$dt1
  name age
1:    4  12
2:    5   0
$dt2
name age
1:   43 354
2:  245  NA
3:  243  NA

But when I try:

test <- lapply(names(li), function(d) li[[d]][is.na(li[[d]])]<-0)

I get:

> test
[[1]]
[1] 0
[[2]]
[1] 0

Is there a way to do this without using a loop for all the data tables in my list?

+4
source share
3 answers

You just need to return the list item

lapply(names(li), function(d) { li[[d]][is.na(li[[d]])] <-0; li[[d]] })
#[[1]]
#   name age
#1:    4  12
#2:    5   0

#[[2]]
#   name age
#1:   43 354
#2:  245   0
#3:  243   0

You can also use:

lapply(li, function(d) { d[is.na(d)] <- 0; d })
+8
source

Another option:

library(dplyr)
lapply(li, function(x) { mutate_each(x, funs(replace(., is.na(.), 0))) })
+5

NA . replace_na tidyr

library(tidyr)
lapply(li,function(df){replace_na(df,list(name=0,age=0))})

This replace_narequires a list of notes per column, which is useful when you want to replace the NA in each column with the same value.

Hope this works.

+3
source

Source: https://habr.com/ru/post/1606942/


All Articles