【发布时间】:2018-05-13 09:01:54
【问题描述】:
我的问题是当我出于某种奇怪的原因计算运行相关性时,对于相同的估计/相关值,我没有得到相同的 p 值。
我的目标是计算同一 data.frame 中两个向量(下例中的 subject1 和 subject2)的运行 Spearman 相关性。此外,我的窗口(向量的长度)和步幅(每个窗口之间的跳跃/步长)是恒定的。因此,当查看下面的公式(来自wiki)时,我应该得到相同的临界 t,因此对于相同的 Spearman 相关性,相同的 p 值。这是因为n 声明相同(窗口大小相同)并且r 相同。但是,我的最终 p 值不同。
#Needed pkgs
require(tidyverse)
require(pspearman)
require(gtools)
#Sample data
set.seed(528)
subject1 <- rnorm(40, mean = 85, sd = 5)
set.seed(528)
subject2 <- c(
lag(subject1[1:21]) - 10,
rnorm(n = 6, mean = 85, sd = 5),
lag(subject1[length(subject1):28]) - 10)
df <- data.frame(subject1 = subject1,
subject2 = subject2) %>%
rowid_to_column(var = "Time")
df[is.na(df)] <- subject1[1] - 10
rm(subject1, subject2)
#Function for Spearman
psSpearman <- function(x, y)
{
out <- pspearman::spearman.test(x, y,
alternative = "two.sided",
approximation = "t-distribution") %>%
broom::tidy()
return(data.frame(estimate = out$estimate,
statistic = out$statistic,
p.value = out$p.value )
}
#Running correlation along the subjects
dfRunningCor <- running(df$subject1, df$subject2,
fun = psSpearman,
width = 20,
allow.fewer = FALSE,
by = 1,
pad = FALSE,
align = "right") %>%
t() %>%
as.data.frame()
#Arranging the Results into easy to handle data.frame
Results <- do.call(rbind.data.frame, dfRunningCor) %>%
t() %>%
as.data.frame() %>%
rownames_to_column(var = "Win") %>%
gather(CorValue, Value, -Win) %>%
separate(Win, c("fromIndex", "toIndex")) %>%
mutate(fromIndex = as.numeric(substring(fromIndex, 2)),
toIndex = as.numeric(toIndex, 2)) %>%
spread(CorValue, Value) %>%
arrange(fromIndex) %>%
select(fromIndex, toIndex, estimate, statistic, p.value)
我的问题是当我用估计值 (Spearman rho;estimate)、窗口号 (fromIndex) 绘制 Results 并为 p 值着色时,我应该得到像同一区域内相同颜色的“隧道”/“路径” - 我没有。
例如,在下图中,红色圆圈中相同高度的点应该具有相同的颜色 - 但不是。
图表代码:
Results %>%
ggplot(aes(fromIndex, estimate, color = p.value)) +
geom_line()
到目前为止我发现可能是由于:
1. 像Hmisc::rcorr() 这样的函数在小样本或很多关系中往往不会给出相同的 p.value。这就是我使用pspearman::spearman.test 的原因,从我在这里读到的内容假设它可以解决这个问题。
2. 样本量小 - 我尝试使用更大的样本量。我仍然遇到同样的问题。
3. 我尝试四舍五入我的 p 值 - 我仍然遇到同样的问题。
感谢您的帮助!
编辑。
可能是 ggplot 的“伪”着色吗?难道ggplot 只是插入“最后一个”颜色直到下一点?这就是为什么我从第 5 点到第 6 点得到“浅蓝色”,而从第 7 点到第 8 点得到“深蓝色”?
【问题讨论】:
-
为什么
estimate应该和p.value一样? -
对于每个估计,我应该得到相同的 p.value。例如,对于估计 0.3,我应该总是得到相同的 p.value。
-
我收到一个语法错误:(psSpearman 的定义中缺少括号)。还缺少一个库调用来加载任何可能有
running的包 -
对不起。请看我的编辑。我添加了所需的 pkgs。
-
感谢您的评论。我做了检查。我实际上使用了几个包并从头开始计算(并得到了相同的结果)。我总是首先假设错误在我身上;)
标签: r ggplot2 graph correlation hmisc