2017-10-19 51 views
1

我认为这使用`purrr :: map`与k均值

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' 

但第二不起作用。我如何结合purrr::map()使用kmeans

+1

为什么你需要'map'在这里? '矩阵(1:50,5)%>%kmeans(。,center = 2,iter.max = 10)'。 “矩阵”是具有暗淡属性的“矢量”。当你做“地图”时,它会经历每一次观察。 – akrun

+0

@akrun,因为在我的原始示例中,我有几个矩阵(缩放,带/不带某些变量等),我想比较彼此的聚类结果。 – Dambo

+1

不知道我明白了。如果你在'list'中有几个矩阵,那么'map'可以应用 – akrun

回答

2

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) 

它变成有用的,当我们有matriclist ES

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