2010-01-08 12 views
0

我以前也問過這個問題,並獲得瞭解決方案,但我的問題是從原來的解釋內排序爲R - 一旦被數字然後通過阿爾法(V2)

我有一個數據幀,這樣有點不同的:

nums<-c(5,7,8,9,10,3,2,1) 
text<-c("Company a","Company b","Company c","Company d","Company a 09","Company b 09","Company c 09","Company d 09") 
this <- data.frame() 
this <- cbind(text,nums) 

「公司一個:d」 =數據從2010年,「公司一個09:09:d」我想從= 2009年數據它首先由數字列從最大到最小進行排序然後通過字符串列。唯一美中不足的是,該字符串列有顯示2010年的數據下的09' 的數據,這樣的:

"Company d" 9 
"Company d 09" 1 
"Company c" 8 
"Company c 09" 2 
"Company b" 7 
"Company b 09" 3 
"Company a" 5 
"Company a 09" 10 

還有的是從this question一些建議,但我不能複製它這個,有點多複雜的例子。

我已經上傳了一些test data

+0

爲什麼09數據與其他數據有不同的'nums'值,爲什麼選擇按「」元素排序而不是每個組中的「09」元素? –

+0

另一個問題是:你能有「10」而不是「」嗎? – Shane

+0

@Alex,@Shane,需要顯示。以這種方式組織數據允許我複製/粘貼,而不是手動排序大列表。 –

回答

2

這個怎麼樣?

## Read in the data 
foo <- read.csv("testdata.csv") 
## Normalize names so that things work later. 
foo$Company <- toupper(gsub(" *$", "", foo$Company)) 

## Split the data into 09 and not 09. 
not.09 <- subset(foo, !grepl("09$", Company)) 
is.09 <- subset(foo, grepl("09$", Company)) 

## Figure out where the not09 should go (even indices) 
not.09$Index <- 2 * order(not.09$Score, decreasing=TRUE) 

## Find out where the 09s should go (odd indices) 
is.09$Index <- not.09[match(is.09$Company, paste(not.09$Company, "09")),]$Index + 1 

## Combine and sort 
combined <- rbind(is.09, not.09) 
combined <- combined[order(combined$Index),-4] 
+0

這一個工程!感謝您的詳細評論! –

相關問題