[英]How to loop subset of lists in R?
我有一個9個列表的列表,請參見以下代碼,在這里我只想循環三個列表p
, r
和t
用於Pearson,Spearson和Kendall相關,而不是全部9個列表。 當前偽代碼如下,其中測試函數為corrplot(M.cor, ...)
,請參見下面的完整偽代碼
for (i in p.mat.all) {
...
}
使用mtcars
測試數據進行編碼
library("psych")
library("corrplot")
M <- mtcars
M.cor <- cor(M)
p.mat.all <- psych::corr.test(M.cor, method = c("pearson", "kendall", "spearman"),
adjust = "none", ci = F)
str(p.mat.all)
str(p.mat.all$r)
str(p.mat.all$t)
str(p.mat.all$p)
輸出有關9個列表的列表
List of 9
$ r : num [1:11, 1:11] 1 -0.991 -0.993 -0.956 0.939 ...
..- attr(*, "dimnames")=List of 2
.. ..$ : chr [1:11] "mpg" "cyl" "disp" "hp" ...
.. ..$ : chr [1:11] "mpg" "cyl" "disp" "hp" ...
$ n : num 11
$ t : num [1:11, 1:11] Inf -21.92 -25.4 -9.78 8.22 ...
..- attr(*, "dimnames")=List of 2
.. ..$ : chr [1:11] "mpg" "cyl" "disp" "hp" ...
.. ..$ : chr [1:11] "mpg" "cyl" "disp" "hp" ...
$ p : num [1:11, 1:11] 0.00 4.04e-09 1.09e-09 4.32e-06 1.78e-05 ...
..- attr(*, "dimnames")=List of 2
.. ..$ : chr [1:11] "mpg" "cyl" "disp" "hp" ...
.. ..$ : chr [1:11] "mpg" "cyl" "disp" "hp" ...
$ se : num [1:11, 1:11] 0 0.0452 0.0391 0.0978 0.1143 ...
..- attr(*, "dimnames")=List of 2
.. ..$ : chr [1:11] "mpg" "cyl" "disp" "hp" ...
.. ..$ : chr [1:11] "mpg" "cyl" "disp" "hp" ...
$ adjust: chr "none"
$ sym : logi TRUE
$ ci : NULL
$ Call : language psych::corr.test(x = M.cor, method = c("pearson", "kendall", "spearman"), adjust = "none", ci = F)
- attr(*, "class")= chr [1:2] "psych" "corr.test"
num [1:11, 1:11] 1 -0.991 -0.993 -0.956 0.939 ...
- attr(*, "dimnames")=List of 2
..$ : chr [1:11] "mpg" "cyl" "disp" "hp" ...
..$ : chr [1:11] "mpg" "cyl" "disp" "hp" ...
num [1:11, 1:11] Inf -21.92 -25.4 -9.78 8.22 ...
- attr(*, "dimnames")=List of 2
..$ : chr [1:11] "mpg" "cyl" "disp" "hp" ...
..$ : chr [1:11] "mpg" "cyl" "disp" "hp" ...
num [1:11, 1:11] 0.00 4.04e-09 1.09e-09 4.32e-06 1.78e-05 ...
- attr(*, "dimnames")=List of 2
..$ : chr [1:11] "mpg" "cyl" "disp" "hp" ...
..$ : chr [1:11] "mpg" "cyl" "disp" "hp" ...
我關於用測試函數corrplot
循環所有三個相關性的偽代碼,但由於它遍歷了所有9個列表,因此無法正常工作
for (i in p.mat.all) {
p.mat <- i
print("p.mat ===========")
print(i)
alpha <- 0.05
corrplot( M.cor,
method="color",
type="upper",
addCoefasPercent = TRUE,
tl.col = "black",
tl.pos = "td",
p.mat = p.mat, sig.level = alpha, insig = "blank",
order = "original"
)
}
預期的輸出:僅循環t
, p
和r
列表,以便可以將它們傳遞到測試函數corrplot
R:3.3.1
操作系統:Debian 8.5
或帶有* apply函數:
lapply(p.mat.all[c("r","p","t")], function(x) {
# x takes now first p.mat.all$r, then p.mat.all$p, etc
print("p.mat ===========")
print(x)
alpha <- 0.05
corrplot( M.cor,
method="color",
type="upper",
addCoefasPercent = TRUE,
tl.col = "black",
tl.pos = "td",
p.mat = x, sig.level = alpha, insig = "blank",
order = "original"
)
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.