[英]Correlation in R - missing values
我想在以下數據集上運行相關性。 我想要所有之間的關聯(V1與V2,V3,V4,V5; V2與V1,V3,V4,V5等等)。 我想要相關系數和p值。
mydataset
Group V1 V2 V3 V4 V5
OH 0.3 5 -3.09 2.5 NA
OH 0.5 1 NA 1.8 2.5
ON 2 2.5 NA -3.11 -7.5
OH 1.5 -3.35 -0.82 NA -2.5
ON 6.5 -2.85 2.5 NA NA
OH 3 0.5 1.8 -2.85 NA
我運行了這段代碼
correlations <- corr.test (mydataset, use = "pairwise").
我也跑了:
correlations <- cor(mydataset, use = "complete.obs", method = "pearson")
我不知道如何處理缺失的價值觀。 而且我沒有任何輸出。 我不斷收到此錯誤:
Error in cor(x, use = use, method = method) : 'x' must be numeric
關於什么可行的任何建議?
謝謝!
問題不在於NA,而在於變量Group
不是數字。 所以嘗試
cor(mydataset[sapply(mydataset, is.numeric)], use='pairwise')
這只會選擇數字變量,而排除NA。
V1 V2 V3 V4 V5
V1 1.0000000 -0.5917056 0.8907941 -0.9355822 -0.9819805
V2 -0.5917056 1.0000000 -0.6376181 0.4894776 -0.2468321
V3 0.8907941 -0.6376181 1.0000000 -1.0000000 NA
V4 -0.9355822 0.4894776 -1.0000000 1.0000000 1.0000000
V5 -0.9819805 -0.2468321 NA 1.0000000 1.0000000
在相關矩陣中,我們看到獲得V3
和V5
之間的相關性的NA,但這是因為V3
和V5
並非僅在一次觀察中同時具有NA,並且不能僅在一對點上獲得相關性。
corr.test(test[2:6], use = 'pairwise')
是您想要的。 您必須排除第一列,它是一個字符向量。 下面是帶有輸出的代表。 您將獲得系數和p值。
library('tidyverse')
#> ── Attaching packages ─────────────────────────────────────────────────────────────────────────── tidyverse 1.2.1 ──
#> ✔ ggplot2 2.2.1 ✔ purrr 0.2.4
#> ✔ tibble 1.3.4 ✔ dplyr 0.7.4
#> ✔ tidyr 0.7.2 ✔ stringr 1.2.0
#> ✔ readr 1.1.1 ✔ forcats 0.2.0
#> ── Conflicts ────────────────────────────────────────────────────────────────────────────── tidyverse_conflicts() ──
#> ✖ dplyr::filter() masks stats::filter()
#> ✖ dplyr::lag() masks stats::lag()
library('psych')
#>
#> Attaching package: 'psych'
#> The following objects are masked from 'package:ggplot2':
#>
#> %+%, alpha
test = tibble::tribble(
~Group, ~V1, ~V2, ~V3, ~V4, ~V5,
'OH', 0.3, 5, -3.09, 2.5, NA,
'OH', 0.5, 1, NA, 1.8, 2.5,
'ON', 2 , 2.5, NA, -3.11, -7.5,
'OH', 1.5, -3.35, -0.82, NA, -2.5,
'ON', 6.5, -2.85, 2.5, NA, NA,
'OH', 3, 0.5, 1.8, -2.85, NA
)
corr.test(test[2:6], use = 'pairwise')
#> Warning in sqrt(n - 2): NaNs produced
#> Warning in corr.test(test[2:6], use = "pairwise"): Number of subjects must
#> be greater than 3 to find confidence intervals.
#> Warning in sqrt(n[lower.tri(n)] - 3): NaNs produced
#> Call:corr.test(x = test[2:6], use = "pairwise")
#> Correlation matrix
#> V1 V2 V3 V4 V5
#> V1 1.00 -0.59 0.89 -0.94 -0.98
#> V2 -0.59 1.00 -0.64 0.49 -0.25
#> V3 0.89 -0.64 1.00 -1.00 NA
#> V4 -0.94 0.49 -1.00 1.00 1.00
#> V5 -0.98 -0.25 NA 1.00 1.00
#> Sample Size
#> V1 V2 V3 V4 V5
#> V1 6 6 4 4 3
#> V2 6 6 4 4 3
#> V3 4 4 4 2 1
#> V4 4 4 2 4 2
#> V5 3 3 1 2 3
#> Probability values (Entries above the diagonal are adjusted for multiple tests.)
#> V1 V2 V3 V4 V5
#> V1 0.00 0.86 0.66 0.45 0.66
#> V2 0.22 0.00 1.00 1.00 1.00
#> V3 0.11 0.36 0.00 NaN NA
#> V4 0.06 0.51 NaN 0.00 NaN
#> V5 0.12 0.84 NA NaN 0.00
#>
#> To see confidence intervals of the correlations, print with the short=FALSE option
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.