如何置换 R 中嵌套列表中的函数?

How to permute a function in nested list in R?

我正在尝试计算与以下子集嵌套的列表子集的 gower::gower_dist() 索引。

即,我有一个嵌套列表,每个子集中有十行。

我愿意:

一个可重现的例子:

list_to_split <- data.frame(rnorm(100), rnorm(100), rnorm(100))
names(list_to_split) <- c("var_1", "var_2", "var_3")

n <- 10
nr <- nrow(list_to_split)

nested_list<-split(list_to_split[,c(1:3)], rep(1:ceiling(nr/n), each=n, length.out=nr))

下面是我打算做的一部分微积分:

dt_1 <- list_to_split[c(1:10),]
dt_2 <- list_to_split[c(11:20),]

gower_test <- gower::gower_dist(dt_1,  dt_2)

mean(gower_test[[1]])

> gower::gower_dist(dt_1,  dt_2)
 [1] 0.45988316 0.04906887 0.31952329 0.54794324 0.23139261 0.26743197 0.27649944 0.35229745 0.19163644 0.20118909

> mean(gower_test[[1]])
[1] 0.4598832

以上例子只针对第一个和第二个。我想为整个列表执行并测试所有组合

library(tidyr)
library(purrr)
library(dplyr)

# create a nested data frame where we have created 10 lists
# for rows 1..10, 11..20, etc
df <- list_to_split %>% 
    mutate(row_id = (row_number()-1) %/% 10 + 1) %>% 
    group_by(row_id) %>% 
    nest()

# create cartesian product
crossing(a = df, b = df) %>% 
    
    # compute gdist for each combo
    mutate(gdist = map2(a$data, b$data, gower::gower_dist)) %>% 
    
    # compute avg value for each
    mutate(gavg = map_dbl(gdist, mean)) %>% 
    
    # order
    arrange(-gavg)