将'purrr::map'与k-means连用

将'purrr::map'与k-means连用,r,purrr,R,Purrr,我想这个 kmeans(x = matrix(1:50, 5), centers = 2, iter.max = 10) 可以写成: matrix(1:50, 5) %>% map( ~kmeans(x = .x, centers = 2, iter.max = 10)) Error in sample.int(m, k) : cannot take a sample larger than the population when 'replace = FALSE' 但第二

我想这个

 kmeans(x = matrix(1:50, 5), centers = 2, iter.max = 10)
可以写成:

matrix(1:50, 5) %>% 
map( ~kmeans(x = .x, centers = 2, iter.max = 10))

Error in sample.int(m, k) : 
  cannot take a sample larger than the population when 'replace = FALSE'

但第二种方法不起作用。如何将
kmeans
purrr::map()
结合使用?

矩阵本身就是一个具有暗淡属性的
向量。因此,当我们直接在
矩阵
上应用
映射
时,它会遍历每个单独的元素。相反,将其放在
列表中

list(matrix(1:50, 5) ) %>% 
         map( ~kmeans(x = .x, centers = 2, iter.max = 10))
请注意,对于单个
矩阵
,我们不需要
映射

 matrix(1:50, 5) %>% 
      kmeans(., centers = 2, iter.max = 10)
当我们有一个
矩阵的
列表时,它就变得很有用了

list(matrix(1:50, 5), matrix(51:100, 5)) %>% 
            map( ~kmeans(x = .x, centers = 2, iter.max = 10))

为什么您需要
地图
<代码>矩阵(1:50,5)%>%kmeans(,中心=2,iter.max=10)
矩阵
是具有dim属性的
向量
。当你做
map
时,它会遍历每一个观察结果。@akrun,因为在我最初的例子中,我有几个矩阵(缩放、有/没有某些变量等),我想将聚类结果相互比较。我不确定我是否得到了它。如果在
列表中有多个矩阵
,则可以应用
映射
如果在
列表中,即
列表(矩阵(1:50,5),矩阵(51:100,5))%%>%map(~kmeans(x=.x,centers=2,iter.max=10))