2013-03-12 71 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))