我之前已经问过这个问题并收到了解决方案,但我的问题与原来的解释有所不同
我有一个数据框,如下所示:
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)
“公司a:d”=来自2010年的数据,“公司a 09:d:09”=来自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 :(得分: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]