【问题标题】:R, extrapolate from one data pointR,从一个数据点推断
【发布时间】:2015-03-17 09:32:24
【问题描述】:

我希望从一个只有一个非缺失数据点的数组中进行推断。解决方案是使所有值与该非缺失数据点相同。

library(zoo)

datax <- data.frame(id = c(1:6),variable = c(NA,NA,0,NA,NA,NA))

#Both na.fill, and na.approx require at least two data points in the vector, 
#in the case of interpolation naturally for a good reason.
datax$variable <- na.fill(na.approx(datax$variable, na.rm = FALSE), "extend")

我可以编写以下 hack,但我想知道是否有更好更通用的函数。

if(length(which(!is.na(as.numeric(unlist(datax$variable))))) == 1) +
    {datax$variable <- datax[which(!is.na(as.numeric(unlist(datax$variable))))]}

有人有想法吗?谢谢!

【问题讨论】:

    标签: r zoo missing-data interpolation


    【解决方案1】:

    试试这个:

    library(zoo) 
    library(dplyr)
    
    # From zoo::na.locf() description: 
    # Generic function for replacing each NA with the most recent non-NA prior to it.
    

    动物园

    datax$new_variable <- 
      na.locf(na.locf(datax$variable, na.rm = FALSE),  fromLast = TRUE)
    

    动物园和dplyr

    datax  %>% 
      mutate(new_variable = na.locf(na.locf(variable, na.rm = FALSE), fromLast = TRUE))
    

    结果

      id variable new_variable
    1  1       NA            0
    2  2       NA            0
    3  3        0            0
    4  4       NA            0
    5  5       NA            0
    6  6       NA            0
    

    【讨论】:

    • 不应该加datax$variable &lt;- na.locf(zoo(datax$variable), na.rm = FALSE, fromLast = TRUE)吗?
    • @G.Grothendieck 已更正。
    • hm...这不是来自基础datax$new_variable...添加列...我想我应该删除基础。
    猜你喜欢
    • 2023-03-12
    • 2020-09-24
    • 2022-10-24
    • 1970-01-01
    • 2013-03-10
    • 1970-01-01
    • 1970-01-01
    • 2015-03-11
    • 1970-01-01
    相关资源
    最近更新 更多