首页 > 解决方案 > 在 R 中,按顺序对列表的每个元素进行排序,并使用该顺序对列表中的数据进行采样

问题描述

嗨,我有几个数据框,每个数据框代表接受一种处理的样本,我将它们组合成一个列表,我的想法是我想在列表中的每个元素/数据框上测试 Kmeans 聚类方法,然后使用 KNN 找到最接近的数据中的数据点进行子样本。

说我有这两个数据框,我绑定到一个列表中。以下是示例数据https://drive.google.com/drive/folders/1B8JQY94Z-BHTZEKlV4dvUDocmiyppBDa?usp=sharing

每个数据框具有相同的结构:多行样本和 107 列变量,但第 1 和第 2 列只是数据标签,例如实际药物治疗。

所以我试图对列表中的每个元素(数据帧)执行 Kmeans 聚类,从 kmeans 聚类的输出中,我取了与每个数据帧匹配的“中心”,并将所有中心绑定到另一个列表中。

接下来,我要做的是使用函数 get.knnx(),这样我就可以使用 kmeans 聚类生成的每个中心,然后返回到原始数据帧,对离中心最近的 500 个数据点进行采样, 以实现对数据的良好二次抽样。

library(tidyverse)
library(purr)

#take data into list
mylist <- list(df1,df2)

#perform Kmeans cluster
#scale datainput and drop the data label column
Kmeans.list <- map(.x = mylist,
                   .f = ~kmeans(scale(.x[,-c(1:2)]),
                        centers =15,
                        nstart=50,
                        iter.max = 100)) %>% 
  purrr::set_names(c("df1", "df2"))


#Isolate the Centers info to another list
Kmeans_centers <- map(Kmeans.list, ~.x$centers)

#trying to use map2
y <- map2(.x = mylist,.y=Kmeans_centers,
          .f=~get.knnx(scale(.x[,-c(1:2)]),.y, 500)) %>% 
    purrr::set_names(c("df1","df2"))

get.knnx 的输出在输出列表中每个元素有 2 个组件,一个是 nn.index,另一个是 nn.dist。nn.index 表示数据的实际行索引位置,因此我想使用此索引返回原始数据(df1,df2)以找到这些数据点,并将这些数据点用作数据的最佳代表.

我不太清楚如何只使用列表 y 的 nn.index 部分,所以我想首先我可以取出 nn.index 并将它们设为列表

#bind all the centers into a list for mapping
y.nnindex <- map(y, ~.x$nn.index)%>% 
  purrr::set_names(c("df1", "df2"))

df1 或 df2 对应的每个索引应该是 15 X 500,从 Kmean 中选择 15 个中心,KNN 选择 500 个点。

这是我卡住的部分,我想订购 nnindex,然后用它来子集原始数据。我想我可以建立一个采样数据列表,然后将它们绑定到一个数据帧中。我收到错误消息说 Mylist[i][idx, ] 中的错误:维数不正确。我认为我在如何访问列表中每个数据框的 nnindex 以及如何从列表的元素中对事物进行子集化方面是错误的。一直卡在这类问题上。一些指示和解释将不胜感激

cl.list <- list()

for (i in 1:2) {
  idx <- sort(y.nnindex[[i]])
  cl.list[[i]] <- as.data.frame(cbind(idx, mylist[i][idx,]))
}

标签: rlistk-meansknn

解决方案


推荐阅读