如何简化识别哪些下限和上限不为 0?

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

我需要在下面的图表中包含置信区间不包括 0 的区域。目前,我正在以一种非常冗长的方式做这件事。

例如

#first identify regions above 0 or below 0

sig1 <- with(df, lower > 0 & upper > 0 )
sig2 <- with(df, lower < 0 & upper < 0)

#then make new sig3, which includes the true from both sig1 and sig2 columns and use this for plot

df_new$sig3 <- df_new$sig1

positions <- which(df_new$sig2 == "TRUE")

df_new[positions, 9] <- "TRUE"

任何能让这更快一点的指示将不胜感激。

r ggplot2
1个回答
0
投票

尝试类似下面注释行之间的代码。创建一个列来指示置信区间 does 是否包含零(

include
列),然后对其求反(对于
exclude
列)似乎更简单。也许只需要
include
列就足以满足您想要做的事情?

library(dplyr)
library(ggplot2)

N <- 50

df <- data.frame(
  mean = rnorm(N)
) %>% mutate(
  lower = mean - 1,
  upper = mean + 1,
  t = row_number()
)

# =============================================================================

# Add columns that indicate whether the confidence intervals includes or
# excludes zero.

df <- df %>% mutate(
  include = lower < 0 & upper > 0,
  exclude = !include
)

# =============================================================================

ggplot(df, aes(x = t, y = mean)) +
  geom_ribbon(aes(ymin = lower, ymax = upper), fill = "lightgrey") +
  geom_point(aes(col = exclude))

我的情节不如你的漂亮,但我认为它展示了原理。

© www.soinside.com 2019 - 2024. All rights reserved.