丢失数据时插入NA行

时间:2017-08-14 15:51:45

标签: r na

我有一个数据集,序列中有一些缺失值:

Seq<-c(1,2,3,4,6,7,10,11,12,18,19,20)
Data<-c(3,4,5,4,3,2,1,2,3,5,4,3)
DF<-data.frame(Seq, Data)

我想在此数据集中添加行,近似于我缺少值的位置,并使用NA填充数据。因此,每当我有一个大于2的间隙时,我会添加一个NA行(如果间隙很大,则添加多行)。结果看起来像这样:

NewSeq<-c(1,2,3,4,6,7,8.5,10,11,12,14,16,18,19,20)
NewData<-c(3,4,5,4,3,2,NA,1,2,3,NA,NA,18,19,20)
NewDF<-data.frame(NewSeq,NewData)

所以我忽略了差距只是&lt; 2,但是每当有间隙时我都会添加NA行&gt; 2.如果还有一个&gt;添加NA行后2个间隙,我添加另一个,直到填补了间隙。

2 个答案:

答案 0 :(得分:1)

不是很优雅,但我会这样做:

Seq<-c(1,2,3,4,6,7,10,11,12,18,19,20)
Data<-c(3,4,5,4,3,2,1,2,3,5,4,3)
DF<-data.frame(Seq, Data)

first <- DF$Seq
second <- DF$Data

for(i in length(first):2) {
  gap <- first[i] - first[i - 1]
  if(gap > 2) {
    steps <- ifelse(gap %% 2 == 1, gap %/% 2, (gap %/% 2) -1)
    new_values_gap <- gap / (steps + 1)
    new_values <- vector('numeric')
    for(j in 1:steps) {
      new_values <- c(new_values, first[i - 1] + j * new_values_gap)
    }
    first <- c(first[1:i - 1], new_values, first[i:length(first)])
    second <- c(second[1:i - 1], rep(NA, length(new_values)), second[i:length(second)])
  }
}

NewDF <- data.frame(NewSeq = first, NewData = second)

> NewDF

##    NewSeq NewData
## 1     1.0       3
## 2     2.0       4
## 3     3.0       5
## 4     4.0       4
## 5     6.0       3
## 6     7.0       2
## 7     8.5      NA
## 8    10.0       1
## 9    11.0       2
## 10   12.0       3
## 11   14.0      NA
## 12   16.0      NA
## 13   18.0       5
## 14   19.0       4
## 15   20.0       3

答案 1 :(得分:1)

似乎适用于您的示例,但不确定它将如何对我尚未见过的数据执行。您需要根据您想要考虑不同差异区间的方式来调整ifelse语句中的区间。

Seq<-c(1,2,3,4,6,7,10,11,12,18,19,20)
Data<-c(3,4,5,4,3,2,1,2,3,5,4,3)
DF<-data.frame(Seq, Data)


diffs <- diff(Seq)
inds <- which(diffs > 2)
new.vals <- sapply(inds, function(x) 
  if(diffs[x] %% 2 != 0){
    seq(Seq[x]+1.5, Seq[x+1]-1.5,1.5)
    }else{
      seq(Seq[x]+2, Seq[x+1]-2,2)
    })

add.length <- unlist(lapply(new.vals, function(x) length(x)))
Seq.new <- c(Seq, unlist(new.vals))
id <- c(seq_along(Seq),
rep(inds+0.5,add.length))
Seq.new <- Seq.new[order(id)]
Data.new <- c(Data, rep(NA, sum(add.length)))
id <- c(seq_along(Seq),
        rep(inds+0.5,add.length))
Data.new <- Data.new[order(id)]
NewDF <- data.frame(Seq.new, Data.new)