2017-10-14 35 views
1

我在將某些數據重構爲更易消化的格式方面遇到了一些麻煩。我有這樣的數據框(但有更多的行和列)。該行是鳥類中,列有森林類型:從每列中提取最高值以及ID

Species Decid Hemlock Mixed Pine Spruce Total 
ACFL  0  2  0 2  0  4 
AMCR  0  2  0 0  5  7 
AMRE 74  18 51 40  43 226 
AMRO  3  0  0 3  0  6 
BAWW 16  32 27 29  22 126 
BBCU  5  2  1 4  5 17 

我想要做的是寫R中的一些代碼,會返回一個數據幀只顯示5種發生在每一森林類型最。換句話說,遍歷每一列,找到5個最高值,然後將它們與「Species」列中的相關值一起放入一個新的數據框中。我嘗試了幾種方法,包括使用head(),sort()等我想我可以做一個循環,但我不知道如何得到它。更具體地說,我試圖讓循環遍歷每列,但不知道如何。我現在知道df $ i不正確,df [[i]]也不起作用。我是新來的循環,所以也許我一切都錯了。

我相信我能得到我通過一些過於令人費解的方法想要的結果,但如果任何人任何更快的方法知道我是非常讚賞。

+0

你想同時'Species'和每列的值? –

回答

1

你可以用dplyrtidyr這樣做。輸出是與頂部5種用於每個森林和它們相應的值a「長格式」的數據幀(請注意,可以存在多於五個條目如果出現平局)。

library(dplyr) 
library(tidyr) 
df %>% gather(key=Forest,value=value,-Species) %>% #convert to long format 
     group_by(Forest) %>% #group by forest type 
     top_n(5,value) %>% #select the top five for each group 
     arrange(Forest,-value) #sort by forest type and descending value 

    Species Forest value 
    <chr> <chr> <int> 
1 AMRE Decid 74 
2 BAWW Decid 16 
3 BBCU Decid  5 
4 AMRO Decid  3 
5 ACFL Decid  0 
6 AMCR Decid  0 
7 BAWW Hemlock 32 
8 AMRE Hemlock 18 
9 ACFL Hemlock  2 
10 AMCR Hemlock  2 
# ... with 23 more rows 
1

繼回報包含包含每個森林頂部種兩列的數據空間項目的列表。您可以使用top_n改變物種上面的數字 - 我用3在這裏,而不是5

top_n <- 3 
lapply(2 : 6, function(i) x[order(x[, i], decreasing=T)[1 : top_n], c(1, i)]) 
+0

修正了它。謝謝。 – Suren

0

這裏有一個版本也採用tidyverse但使用通過arrange()功能分類,然後用slice()

抓住了前5項
library(tidyverse) 

df %>% 
    gather(forest, value, Decid:Total) %>% 
    group_by(forest) %>% 
    arrange(forest, desc(value)) %>% 
    slice(1:5)