0

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...

massisenergy
  • 1,764
  • 3
  • 14
  • 25
hartono -
  • 41
  • 6

1 Answers1

2

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
akrun
  • 874,273
  • 37
  • 540
  • 662
  • thank you, it works.. but i wanna replace it with list(date=exactly date in the rows, sales=0) sorry im new in R – hartono - Aug 11 '19 at 13:22
  • @hartono- According to the question, you want to replace with 0, right? – akrun Aug 11 '19 at 13:22
  • @hartono- Sorry, I am not following your comments about what the replacement would be – akrun Aug 11 '19 at 13:30
  • @hartono- Did you meant the dates in 'test" If it is of length n, then would be there be 'n' dates and also should the sales be 0 of length n? – akrun Aug 11 '19 at 13:32
  • @hartono- I updatd the post. Can you please check – akrun Aug 11 '19 at 13:42