使用带有k-means的`purrr :: map`

时间:2017-10-19 19:40:10

标签: 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'

但第二个不起作用。如何将kmeanspurrr::map()结合使用?

1 个答案:

答案 0 :(得分:2)

matrix本身就是一个带有暗淡属性的vector。因此,当我们直接在map上应用matrix时,它会遍历每个元素。而是将其放在list

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

请注意,对于单个matrix,我们不需要map

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

当我们有list matric es

时,它会变得有用
list(matrix(1:50, 5), matrix(51:100, 5)) %>% 
            map( ~kmeans(x = .x, centers = 2, iter.max = 10))