Replace NULL value from list in dataframe R

1k views Asked by At

i have a dataframe with field as list(), but sometimes it have null values, i've tried replace(is.null(.), 0) in my query but nothing happened.

i want to :

  • replace train with list(date=exactly date in the rows, sales=0)
  • displaying train.sales

here is my dataframe : https://pasteboard.co/IsclvYT.png

content inside dataframe : https://pasteboard.co/IscmiwV.png

Thanks...

1

There are 1 answers

5
akrun On

As the 'train' is a list, we can loop through the list and replace the NULL elements with 0

library(tidyverse)
df1 %>%
    mutate(train = map(train, ~ replace(.x, is.null(.x), 0)))

Based on the comments, the OP wanted to replace the NULL elements with the corresponding 'date' from 'test'

df1 %>%
   mutate(train = map2(train, test, ~ if(is.null(.x)) list(date = .y$date, sales = rep(0, length(.y$sales))) else .x))

Or using base R

i1 <- sapply(df1$train, is.null)
df1$train[i1] <- 0