2013-03-12 92 views
0

重新排序列表我以前問過這個問題:」重新排序數據,使r中

我如何重新排列在r多個物種數據幀每一個物種都有一個不同的若干意見,我需要。最後一個數據幀按降序排列,首先列出大多數觀測值,在這個例子中,最後的數據幀應該先看列表B,然後是物種C,最後是物種A.

colA= c("C","C","C","B","B","B","B","A","A") 
colB= c(1.1,2.1,3.1,4.1,5.1,6.1,7.1,8.1,9.1) 
colC= c(-1.2,-2.1,-3.1,-4.1,-5.1,-6.1,-7.1,-8.1,-9.1) 
df= data.frame (spp=colA, latitude=colB, longitude=colC) 
df 

我收到其正常工作的偉大答案:

# add a column counting the number of rows in each species 
df <- transform(df, n = ave(latitude ,spp, FUN = length)) 
# order by this new column 
dfordered <- df[order(df$n),decreasing = TRUE] 

但現在我在做這在它的有序物種名稱的對象「種」又卡住了。 現在我有:

species <- levels(df$spp) 

此命令使一切恢復按字母順序排列,但我需要的對象由「N」(記錄數)進行排序。有什麼建議麼。提前致謝!

乾杯, 以色列

回答

1

這是因爲使用unique一樣簡單。我強制要求character以免混淆級別和實際值。

unique(as.character(dfordered$spp)) 

從原始數據到這裏,用table

table(df$spp) 

## A B C 
## 2 4 3 

如果你是在相對丰度主要感興趣的您可以按這個

sppCount <- table(df$spp) 

names(sort(sppCount, decreasing = TRUE)) 

# [1] "B" "C" "A" 
1

,你可能還需要您的spp因素按頻率排序。在這種情況下,請使用reorder()根據需要安排其級別,然後對數據幀進行排序,以便觀測數據最多的物種最先出現。

df <- transform(df, spp = reorder(spp, spp, length)) 
df[order(df$spp, decreasing=TRUE),] 
# spp latitude longitude 
# 4 B  4.1  -4.1 
# 5 B  5.1  -5.1 
# 6 B  6.1  -6.1 
# 7 B  7.1  -7.1 
# 1 C  1.1  -1.2 
# 2 C  2.1  -2.1 
# 3 C  3.1  -3.1 
# 8 A  8.1  -8.1 
# 9 A  9.1  -9.1 

## To see one advantage of reordering the factor levels 
barplot(table(df$spp))