【问题标题】:R: Remove Counties with >3 NA's in Yield column , and use na.spline for counties with < 3 NA'sR:删除产量列中 >3 NA 的县,并对 < 3 NA 的县使用 na.spline
【发布时间】:2015-09-23 05:39:51
【问题描述】:

我有一个包含 5 列的 data.frame “df”:“year”、“state”、“county”、“fips”(州-县标识符)、“yield”。

许多县包含NA 以表示产量。我最初通过代码消除了具有任何NA 值的县:

Data <- df %>% group_by(fips) %>% filter(!any(is.na(Yield)))

我现在只需要消除那些包含超过 3 个 NA 的县。因此,NA>3

对于NA =spline 函数:

v <- na.spline(df$Yield)
df$Yield <- v

到目前为止,我有以下内容用于删除所有带有NA>3 的县,并使用样条填充剩余郡的NA

if(length(df$Yield[is.na(df$Yield))<3){
na.spline(df$Yield)
}
}else{
df %>% group_by(fips) %>% filter(!any(is.na(Yield)))
}

这显然行不通。任何见解将不胜感激。

【问题讨论】:

  • 请考虑根据该示例提供一个带有预期输出的小型示例数据集
  • 类似这样的:df %&gt;% group_by(country) %&gt;% mutate(is3NA=ifelse(sum(is.na(Yield))&gt;3,"Include","Exclude")) %&gt;% filter(is3NA=="Incude") 请提供示例数据和预期输出。

标签: r if-statement na spline subset


【解决方案1】:

使用dplyr

library(dplyr)
library(zoo) 
df %>% 
   group_by(fips) %>%
   filter(sum(is.na(Yield))<3) %>% 
   mutate(Yield=na.spline(Yield))

使用data.table

library(data.table)#v1.9.5+
setDT(df)[, .SD[sum(is.na(Yield))<=3] , fips][,Yield:= na.spline(Yield) ,fips][]

或使用base R

transform(subset(df, ave(is.na(Yield), fips, FUN=sum)<3), Yield=na.spline(Yield))

数据

set.seed(29)
df <- data.frame(fips= sample(LETTERS[1:4], 30, replace=TRUE), 
     Yield= as.numeric(sample(c(NA,0:3), 30, replace=TRUE)), 
         stringsAsFactors=FALSE) 

【讨论】:

    猜你喜欢
    • 2017-08-09
    • 1970-01-01
    • 2015-02-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-11
    • 2015-07-16
    • 2017-01-17
    • 2019-09-13
    相关资源
    最近更新 更多