在 dataframe 列中查找间隔的边缘并将它们用于 ggplot 中的 geom_rect xmin-xmax

Find edges of intervals in dataframe column and use them for geom_rect xmin-xmax in ggplot

我有一个由两列组成的数据框

positionx <- c(1:10)
pvalue <- c(0.1, 0.04, 0.03, 0.02, 0.001, 0.2, 0.5, 0.6, 0.001, 0.002)
df <- data.frame(cbind(positionx, pvalue))
df
positionx pvalue
1          1  0.100
2          2  0.040
3          3  0.030
4          4  0.020
5          5  0.001
6          6  0.200
7          7  0.500
8          8  0.600
9          9  0.001
10        10  0.002

我想找出我的 pvalue 在某个阈值以下的 positionx 值区间,比方说 0.05。 使用 'which' 我可以找到行的索引,并且可以返回到 positionx 的值。

which(df[,2]<0.05)
[1]  2  3  4  5  9 10

但是我想要的是间隔的边缘,我的意思是这样的结果:2-5、9-10

我也试过使用下面的 findInterval 函数

int <- c(-10, 0.05, 10)
separation <- findInterval(pvalue,int)
separation
[1] 2 1 1 1 1 2 2 2 1 1

df_sep <- data.frame(cbind(df, separation))
df_sep

   positionx pvalue separation
1          1  0.100          2
2          2  0.040          1
3          3  0.030          1
4          4  0.020          1
5          5  0.001          1
6          6  0.200          2
7          7  0.500          2
8          8  0.600          2
9          9  0.001          1
10        10  0.002          1

然而,我再次被一列数字困住了,而我想要在分隔列中包含 1 的间隔的边缘。 有办法吗?

这是一个简化的例子,实际上我有很多图,每个图都有一个这种类型的数据框(只是更长,而且 pvalues 不容易一目了然)。 我认为我需要间隔边缘信息的原因是我想根据 pvalue 为 ggplot 的背景着色。我知道我可以使用 geom_rect,但我想我需要间隔的边缘来构建彩色矩形。

有没有办法以自动方式而不是手动方式执行此操作?

这似乎是 run length encoding 的一个很好的用例。

示例如下:

library(ggplot2)

# Data from question
positionx <- c(1:10)
pvalue <- c(0.1, 0.04, 0.03, 0.02, 0.001, 0.2, 0.5, 0.6, 0.001, 0.002)
df <- data.frame(cbind(positionx, pvalue))

# Sort data (just to be sure)
df <- df[order(df$positionx),]

# Do run length encoding magic
threshold <- 0.05
rle <- rle(df$pvalue < threshold)
starts <- {ends <- cumsum(rle$lengths)} - rle$lengths + 1

df2 <- data.frame(
  xmin = df$positionx[starts],
  xmax = df$positionx[ends],
  type = rle$values
)

# Filter on type
df2 <- df2[df2$type == TRUE, ] # Satisfied threshold criterium

ggplot(df2, aes(xmin = xmin, xmax = xmax, ymin = 0, ymax = 1)) +
  geom_rect()

reprex package (v0.3.0)

于 2020-05-22 创建