计算大型df(12k+列,3.5k行)的Moran'sI并将结果存储在单独的df中
我想在具有 12044 列(和 3400 行)的数据框上运行 Moran's I test 并将结果存储在 df 或排序列表中。前三列分别是 ID、Lat 和 Long。其余的是我感兴趣的变量。
我知道这lapply是为了做我想做的事,但我不太擅长将结果存储在单独的 df 中。测试结果有四个变量:observed、expected、sd和p.value。
这是 df 和函数本身的示例。
set.seed(1)
df <- data.frame(
ID = 1:15,
LATITUDE = c(42.6, 42.5, 42.3, 42.8, 42.4, 42.4, 42.4, 42.3, 42.4, 42.4, 41.4, 41.6, 41.8, 43.7, 47.3),
LONGITUDE = c(-71.5, -71.6, -71.9, -71.0, -71.1, -71.1, -71.1, -71.1, -71.2, -71.2, -70.5, -70.3, -71.2, -70.3, -68.3),
x1 = runif(15, min=0, max=1000),
x2 = runif(15, min=0, max=1000),
x3 = runif(15, min=0, max=1000),
x4 = runif(15, min=0, max=1000),
x5 = runif(15, min=0, max=1000),
x6 = runif(15, min=0, max=1000),
x7 = runif(15, min=0, max=1000),
x8 = runif(15, min=0, max=1000) )
require(ape)
dists <- as.matrix(dist(cbind(df$LONGITUDE, df$LATITUDE)))
dists.inv <- 1/dists
diag(dists.inv) <- 0
#check
dists.inv[1:5, 1:5]
#deal with the infinite values in the matrix
dists.inv[is.infinite(dists.inv)] <- 0
#calculate Moran's I
Moran.I(df$x1, dists.inv)
谢谢你们
回答
考虑使用tidyverse. 仅选择starts_with'x' 或matches("^xd+$") 的列map,使用循环遍历这些列,应用Moran.I已经创建的 'dists.inv' 和循环列,并按行返回绑定列表元素 ( _dfr)
library(purrr)
library(dplyr)
df %>%
select(starts_with('x')) %>%
map_dfr(~ ape::Moran.I(.x, dists.inv))
-输出
# A tibble: 8 x 4
observed expected sd p.value
<dbl> <dbl> <dbl> <dbl>
1 -0.0305 -0.0714 0.0745 0.583
2 -0.0854 -0.0714 0.0739 0.850
3 -0.185 -0.0714 0.0712 0.111
4 -0.237 -0.0714 0.0737 0.0250
5 -0.109 -0.0714 0.0736 0.612
6 -0.0280 -0.0714 0.0749 0.562
7 0.00361 -0.0714 0.0731 0.305
8 -0.177 -0.0714 0.0737 0.152
THE END
二维码