R语言,如何检测数字序列中的间隔是随机的还是连续的?

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

我有许多数字数据向量,其中一些包含间隙。我必须检测这些间隙是否在每个向量内是连续的或几乎随机分布的。类似的示例在这里:

# Let's create a couple of data vectors
x <- runif(1000)
y <- runif(1000)

# Let's add some NAs at random to x
x[sample(c(1:1000), 100, replace = F)] <- NA
# Let's add some continuous NAs to y
y[c(251:350)] <- NA

# And get the respective summaries
summary(x)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
0.00294 0.24446 0.51441 0.50535 0.76200 0.99850     100 
summary(y)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
0.00325 0.22178 0.47765 0.48207 0.73380 0.99969     100

也就是说,x和y具有相同数量的间隙,但是在x中,它们沿着矢量随机分布,而在y中,它们被聚合。我必须发现这个,有什么主意吗?

r vector random gaps-and-islands
2个回答
2
投票

将其变成小标题,然后查看NA的行号的标准偏差。

library(tidyverse)
myt <- tibble(X = x, Y = y) %>%  
  rowid_to_column("LINE") 

myt %>% 
  filter(is.na(X)) %>% 
  pull(LINE) %>% 
  sd()
# [1] 300.2694
myt %>% 
  filter(is.na(Y)) %>% 
  pull(LINE) %>% 
  sd()
# [1] 29.01149


1
投票

连续或分布式的定义在帖子中并不清楚。

这里是一个函数,如果至少有一系列TRUE值大于NA的长度,则返回n。>

is_contiguous <- function(vec, n) with(rle(is.na(vec)), any(lengths[values] > n))

is_contiguous(x, 30)
#[1] FALSE

is_contiguous(y, 30)
#[1] TRUE
© www.soinside.com 2019 - 2024. All rights reserved.