R - 在重复的系列中找到缺少的元素

问题描述 投票:0回答:1

您如何找到应该(可预测地)存在于数据帧中但不存在的条目?我可能微不足道的问题类似于this question,但是有一两个额外的层 - 我尝试过的每一个解决方案都不能解决集合中的重复和不规则问题。

# Over some years, with a few skipped...
yrs <- 1985:2018 
yrs <- yrs[-sample(1:length(yrs),5)]
# at a number of plots, replicated over two transects...
pts <- letters[1:10]
lns <- c('N','S')
# a study was done (data fields omitted):
yrsr <- rep(yrs, each= length(lns)*length(pts))
lnsr <- rep(rep(lns, each=length(pts)), times=length(yrs))
ptsr <- rep(rep(pts, times=length(lns)), times=length(yrs))
study <- data.frame(YEAR=yrsr, LINE=lnsr, PLOT=ptsr)
## But for random reasons certain plots got left out.
studym <- study[-sample(1:nrow(study), 23),]
# NB: The number of entries per plot varies:
studym$SPEC <- sample(c(1,1,1,1,1,2,2,2,3), nrow(studym), replace=TRUE)
studyAll <- studym[rep(row.names(studym), studym$SPEC),]

错过的地块可能是合法的零或数据输入错误或其他;他们需要被追踪并作为NA进行纠正或插入。因此,要在原始数据表中找到它们,我需要一个列表... studyAll中不存在的所有元素...从我在这里运行的那将是类似的

# 1985 N d
# 1985 N g
# ...
# 2017 S g

但由于它们不存在,我无法确定要求的内容,以及从哪里来。我无法找出任何联接来做我想做的事情。我得到了一个诱人的总结:

studyAll %>% group_by(YEAR, LINE) %>% count(PLOT) %>% apply(2, table)

但这只是告诉我每个问题有多少,而不是在哪里找到它。

(额外费用问题:有没有办法更直接地从studyyrspts构建lns,没有那三行rep()?我认为必须有某种方式来生成这样的简单层次结构,但找不到它。 )

r missing-data
1个回答
1
投票

在因子设计中找到缺失数据的一种方法是从studyAll生成YEAR,LINE和PLOT的所有组合,然后通过anti_join找到所有组合与记录的观察结果之间的差异。

library("tidyr")
library("dplyr")

 studyMissing <- studyAll %>%
   expand(YEAR, LINE, PLOT) %>%
   anti_join(studyAll, by = c("YEAR", "LINE", "PLOT"))

# Giving
# A tibble: 23 x 3 
#    YEAR LINE  PLOT 
#   <int> <fct> <fct>
# 1  1985 N     f    
# 2  1986 N     h    
# 3  1986 S     g    
# 4  1992 N     h    
# 5  1996 S     g    
# 6  2001 N     e    
# 7  2001 N     i    
# 8  2002 N     c    
# 9  2002 S     g    
#10  2003 N     h    
## ... with 13 more rows
© www.soinside.com 2019 - 2024. All rights reserved.