我以为这个
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()
结合使用?
答案 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))