我有一個向量v
和矩陣m
並使用適用於從cor.test
函數(相關性v
和m
列之間)提取的結果的子集。控制嵌套列表的結構時適用FUN返回列表或NA
set.seed(1)
m <- matrix(runif(12), nrow = 3)
v <- 3:1
res <- apply(m, 2, function(x) {
cor.test(x, v, method = 'spearman', exact = F)[c(1,3,4)]
})
這與長度等於列的數目的列表中m
嵌套列表 - 和在結構我想作爲輸出(2級表)。
> str(res)
List of 4
$ :List of 3
..$ statistic: Named num 8
.. ..- attr(*, "names")= chr "S"
..$ p.value : num 0
..$ estimate : Named num -1
.. ..- attr(*, "names")= chr "rho"
$ :List of 3
..$ statistic: Named num 2
.. ..- attr(*, "names")= chr "S"
..$ p.value : num 0.667
..$ estimate : Named num 0.5
.. ..- attr(*, "names")= chr "rho"
$ :List of 3
..$ statistic: Named num 0
.. ..- attr(*, "names")= chr "S"
..$ p.value : num 0
..$ estimate : Named num 1
.. ..- attr(*, "names")= chr "rho"
$ :List of 3
..$ statistic: Named num 6
.. ..- attr(*, "names")= chr "S"
..$ p.value : num 0.667
..$ estimate : Named num -0.5
.. ..- attr(*, "names")= chr "rho"
我要篩選的每種cor.test
結果,說p.value,內環路申請並返回NA指示過濾的結果(保留結果的長度,這裏四個)。
res <- apply(m, 2, function(x) {
tmp <- cor.test(x, v, method = 'spearman', exact = F)[c(1,3,4)]
ifelse(tmp$p.value < 0.1, list(tmp), NA)
})
我的問題是,我們現在得到一個3級列表結構
res2 <- apply(m, 2, function(x) {
tmp <- cor.test(x, v, method = 'spearman', exact = F)[c(1,3,4)]
ifelse(tmp$p.value < 0.1, list(tmp), NA)
})
> str(res2)
List of 4
$ :List of 1
..$ :List of 3
.. ..$ statistic: Named num 8
.. .. ..- attr(*, "names")= chr "S"
.. ..$ p.value : num 0
.. ..$ estimate : Named num -1
.. .. ..- attr(*, "names")= chr "rho"
$ : logi NA
$ :List of 1
..$ :List of 3
.. ..$ statistic: Named num 0
.. .. ..- attr(*, "names")= chr "S"
.. ..$ p.value : num 0
.. ..$ estimate : Named num 1
.. .. ..- attr(*, "names")= chr "rho"
$ : logi NA
只有從apply
的第一個結果是NA結果的結構非常像期望的,顯然因爲apply
則可以容納未過濾導致結構。
res3 <- apply(m, 2, function(x) {
tmp <- cor.test(x, v, method = 'spearman', exact = F)[c(1,3,4)]
ifelse(tmp$p.value > 0.1, list(tmp), NA) #'invert' the test
})
>res3
List of 4
$ : logi NA
$ :List of 3
..$ statistic: Named num 2
.. ..- attr(*, "names")= chr "S"
..$ p.value : num 0.667
..$ estimate : Named num 0.5
.. ..- attr(*, "names")= chr "rho"
$ : logi NA
$ :List of 3
..$ statistic: Named num 6
.. ..- attr(*, "names")= chr "S"
..$ p.value : num 0.667
..$ estimate : Named num -0.5
.. ..- attr(*, "names")= chr "rho"
我試圖徒然返回ifelse(tmp$p.value < 0.1, tmp, NA)
和ifelse(tmp$p.value < 0.1, list(tmp), list(NA))
。
我發現的唯一的解決辦法是分配NA
的apply
外:
res4 <- apply(m, 2, function(x) {
cor.test(x, v, method = 'spearman', exact = F)[c(1,3,4)]
})
res4[sapply(res4, "[[", 2) > 0.1] <- NA
很顯然,我錯過了什麼關於適用的內部運作。
我會強烈建議在看「掃帚」包在提取之前將結果簡化成一個整齊的數據幀。 –