【问题标题】:Replace NULL value from list in dataframe R替换数据框R中列表中的NULL值
【发布时间】:2019-08-11 12:52:28
【问题描述】:

我有一个dataframe,字段为list(),但有时它有空值,我在查询中尝试了replace(is.null(.), 0),但什么也没发生。

我想:

  • list(date=exactly date in the rows, sales=0)替换火车
  • 显示 train.sales

这是我的数据框: https://pasteboard.co/IsclvYT.png

数据框内的内容: https://pasteboard.co/IscmiwV.png

谢谢...

【问题讨论】:

    标签: r dataframe data-manipulation forecastr


    【解决方案1】:

    由于“火车”是list,我们可以循环遍历list 并将NULL 元素替换为0

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

    根据 cmets,OP 想用“test”中的相应“date”替换 NULL 元素

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

    或使用base R

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

    【讨论】:

    • 谢谢,它有效.. 但我想用列表替换它(日期=行中的确切日期,销售额=0)对不起,我是 R 中的新手
    • @hartono- 根据问题,你想用0替换,对吧?
    • @hartono- 抱歉,我没有关注你的 cmets 的替换内容
    • @hartono- 你的意思是'test'中的日期如果它的长度为n,那么会有'n'个日期并且销售额也应该是长度为n的0吗?
    • @hartono- 我更新了帖子。你能检查一下吗
    猜你喜欢
    • 2022-01-14
    • 1970-01-01
    • 2018-02-11
    • 2017-08-06
    • 1970-01-01
    • 2014-12-15
    • 1970-01-01
    • 2016-02-10
    • 1970-01-01
    相关资源
    最近更新 更多