【问题标题】:R remove groups with only NAsR 删除只有 NA 的组
【发布时间】:2016-06-09 19:28:47
【问题描述】:

我有一个类似于以下结构生成的数据框:

library(dplyr)

df1 <- expand.grid(region   = c("USA", "EUR", "World"),
                  time     = c(2000, 2005, 2010, 2015, 2020),
                  scenario = c("policy1", "policy2"),
                  variable = c("foo", "bar"))

df2 <- expand.grid(region   = c("USA", "EUR", "World"),
                  time     = seq(2000, 2020, 1),
                  scenario = c("policy1", "policy2"),
                  variable = c("foo", "bar"))

df2 <- filter(df2, !(time %in% c(2000, 2005, 2010, 2015, 2020)))

df1$value <- rnorm(dim(df1)[1], 1.5, 1)
df1[df1 < 0] <- NA
df2$value <- NA

df1[df1$region == "World" & df1$variable == "foo", "value"] <- NA

df <- rbind(df1, df2)

rm(df1, df2)

df <- arrange(df, region, scenario, variable, time)

df 包含两种“类型”的 NA。对于区域和变量(World/foo)的一种组合,根本没有数据。对于所有其他组合,我们有除 2000、2005、2010、2015、2020 年以外的所有年份的 NA。

我需要一个过滤器来删除仅包含 NA 的区域和变量的组合,但保留那些仅包含几个 NA 的组合。背景是我想应用线性插值来计算后者的缺失值,方法是将dplyrzoo-package 中的功能(用于插值)结合使用,如下所示:

df <- group_by(df, region, scenario, variable, time) %>%
      mutate(value = zoo::na.approx(value)) %>% ungroup()

仅包含 NA 的组会导致 na.approx 返回错误,因为它不能仅与 NA 一起使用。

【问题讨论】:

    标签: r dataframe dplyr zoo


    【解决方案1】:

    要仅保留 regionvariablevalue 中至少有 1 个非 NA 条目的组合,您可以使用:

    df %>% group_by(region, variable) %>% filter(any(!is.na(value)))
    

    或等价:

    df %>% group_by(region, variable) %>% filter(!all(is.na(value)))
    

    你可以使用 data.table:

    library(data.table)
    setDT(df)[, if(any(!is.na(value))) .SD, by = .(region, variable)]
    

    base R 中的一种方法可能是:

    df_split <- split(df, interaction(df$region, df$scenario, df$variable))
    do.call(rbind.data.frame, df_split[sapply(df_split, function(x) any(!is.na(x$value)))])
    

    【讨论】:

    • 谢谢,这指向了我:df &lt;- group_by(df, region, scenario, variable) %&gt;% filter(!all(is.na(value))) 成功了。按场景进行的额外分组很重要,否则World 的所有值都将被删除。
    • 另一个基本类比:with(df, df[ !ave(value, region, scenario, variable, FUN = function(x) all(is.na(x))), ])
    猜你喜欢
    • 1970-01-01
    • 2020-05-12
    • 2020-10-01
    • 2017-06-12
    • 2013-11-25
    • 2017-02-28
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多