2017-10-19 69 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))