我正在比较针对两种不同偏头痛症状的两项不同调查。因为我想在表和图中呈现每个症状的相关性,所以我使用 cor.test() 检索表的值,并使用 ggplot() 和 sm_statCorr() 创建绘图。然而,计算 Spearman rho 的两个函数给出的结果略有不同。我怀疑这与我的数据转换有关,但我一直无法弄清楚其中的原因。
这是一个可重现的示例:
install.packages("pacman")
pacman::p_load(stats, dplyr, ggplot2, smplot2)
# Import and transform data
data <- matrix(c(1, "headache", 1, NA, 1, "aura", 0, 0, 2, "headache", 1, 1, 2, "aura", 0, 0,
3, "headache", -1, -1, 3, "aura", 0, 1, 4, "headache", 1, 2, 4, "aura", -2, -2,
5, "headache", 0, 1, 5, "aura", 1, 1, 6, "headache", 2, 2, 6, "aura", 0, 0,
7, "headache", 0, 0, 7, "aura", 0, 0, 8, "headache", 1, 1, 8, "aura", 0, 0,
9, "headache", 1, 0, 9, "aura", 0, 0, 10, "headache", 1, -1, 10, "aura", 0, 0,
11, "headache", 0, 1, 11, "aura", 0, 0, 12, "headache", 0, 0, 12, "aura", 0, 0),
nrow = 24, ncol = 4, byrow = T)
colnames(data) = c("id", "symptom", "survey_1", "survey_2")
data <- as.matrix(data)
data <- as.data.frame(data)
data$id <- as.numeric(data$id)
data$survey_1 <- as.numeric(data$survey_1)
data$survey_2 <- as.numeric(data$survey_2)
data$symptom = factor(data$symptom, levels=c("headache", "aura"))
# Create plot with sm_statCorr
data_n <- data %>% group_by(symptom, survey_1, survey_2) %>% tally() %>% ungroup()
data_n <- data_n[,c("symptom", "survey_1", "survey_2", "n")]
ggplot(data_n, aes(x = survey_1, y = survey_2)) +
geom_point(aes(size = n)) +
sm_statCorr(data = data, aes(x = survey_1, y = survey_2), corr_method = "spearman") +
facet_wrap(. ~ symptom)
# Perform cor.test
cor.test(data[(data$symptom == "headache"), ]$survey_1,
data[(data$symptom == "headache"), ]$survey_2,
method = "spearman")
cor.test(data_aura <- data[(data$symptom == "aura"), ]$survey_1,
data_aura <- data[(data$symptom == "aura"), ]$survey_2,
method = "spearman")
cor.test() 为我提供了 Spearman 头痛的 rho 0.5028556 和先兆的 rho 0.8174239。 然而,在图中,相同的值分别为 0.55 和 0.83:
这些方法之间统计数据的差异是由于它们是使用不同的数据计算的。通过该图,由
sm_statCorr
生成的统计数据按 symptom
数据框中的 data_n
列进行分组,而不是对 data
使用 cor.test
。
发生这种情况是因为
facet
调用在顶层 facet
调用的数据中查找 ggplot
ting 变量,在问题中是 data_n
。
您可以通过交换顶层使用的数据来获得相同的分组:
ggplot(data=data, aes(x = survey_1, y =survey_2)) +
geom_point(data=data_n, aes(x = survey_1, y = survey_2, size = n)) +
sm_statCorr(corr_method = "spearman") +
facet_wrap(. ~ symptom) # this now uses `symptom` from data`