【问题标题】:Use `purrr::map` with k-means将 `purrr::map` 与 k-means 一起使用
【发布时间】:2017-10-19 19:40:10
【问题描述】:

我以为是这个

 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() 结合使用?

【问题讨论】:

  • 这里为什么需要mapmatrix(1:50, 5) %>% kmeans(., centers = 2, iter.max = 10)matrix 是具有暗淡属性的 vector。当您执行map 时,它会遍历每个单独的观察结果。
  • @akrun 因为在我原来的例子中我有几个矩阵(缩放,有/没有某些变量等),我想比较聚类的结果。
  • 不确定我明白了。如果list中有多个矩阵,则可以应用map
  • 如果您的方法在 listlist(matrix(1:50, 5), matrix(51:100, 5)) %>% map( ~kmeans(x = .x, centers = 2, iter.max = 10)) 中,您的方法将有效

标签: r purrr


【解决方案1】:

matrix 本身就是一个带有暗属性的vector。因此,当我们直接在matrix 上应用map 时,它会遍历每个单独的元素。而是将其放在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)

当我们有 listmatrices 时,它变得有用

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-25
    • 2017-11-07
    • 1970-01-01
    • 1970-01-01
    • 2012-07-22
    • 1970-01-01
    • 2017-04-27
    相关资源
    最近更新 更多