我有一個自定義類對象(元組列表)。 我也已經定義了<.myclass
>.myclass
和==.myclass
。R中自定義類的元素列表的排序列表?
現在我有一個
a <- obj1 # of myclass
b <- obj2 # of myclass
c <- obj3 # of myclass
L <- list(list(a,12,1),list(b,215,23),list(c,21,9))
我要排序L,對指數1即我已經b < c < a
然後,我要排序L的這種形式list(list(b,215,23),list(c,21,9),list(a,12,1))
如何實現這一目標?
在我的搜索,我發現如何排序的特定索引,並使用我寫了下面的功能
magic_sort <- function(lst, sortind, dec = T) {
return(lst[order(sapply(lst,'[[',sortind), decreasing = dec)])
}
但是,當我給指數1到它,排序OBJ1,它失敗
> magic_sort(L,1)
Error in order(sapply(lst, "[[", sortind), decreasing = dec) :
unimplemented type 'list' in 'orderVector1'
有沒有解決這個問題?一般來說,根據比較運算符的自定義定義,我是否可以擁有排序,最小等功能?
編輯:繼或許有助於瞭解結構更好:http://pastebin.com/0M7JRLTu
編輯2:
library("sets")
a <- list()
class(a) <- "dfsc"
a[[1]] <- tuple(1L, 2L, "C", "a", "B")
b <- list()
class(b) <- "dfsc"
b[[1]] <- tuple(1L, 2L, "A", "b", "B")
c <- list()
class(c) <- "dfsc"
c[[1]] <- tuple(1L, 2L, "A", "a", "B")
L <- list()
L[[1]] <- list(a, 12, 132)
L[[2]] <- list(b, 21, 21)
L[[3]] <- list(c, 32, 123)
`<.dfsc` <- function(c1, c2) {
return(lt_list(toList(c1),toList(c2)))
}
`==.dfsc` <- function(c1, c2) {
return(toString(c1) == toString(c2))
}
`>.dfsc` <- function(c1, c2) {
return(!((c1 < c2) || (c1 == c2)))
}
lt_list <- function(l1, l2) {
n1 <- length(l1)
n2 <- length(l2)
j = 1
while(j <= n1 && j <= n2) {
if (l1[[j]] != l2[[j]]) {
return (l1[[j]] < l2[[j]])
}
j = j + 1
}
return(n1 < n2)
}
toString.dfsc <- function(x) {
code_string <- ""
#for(ii in x[[1]]) {
for(ii in x) {
code_string <- paste(code_string,"(",ii[[1]],",",ii[[2]],",",ii[[3]],",",ii[[4]],",",ii[[5]],")", sep = "")
}
return(code_string)
}
現在我想所需的L
是list(list(c,_,_),list(b,_,_),list(a,_,_))
「我想在obj1上排序L」。這意味着什麼含糊不清。請提供可重複的示例並顯示預期輸出。 – Roland
我澄清了一下。我希望它不再含糊不清。基本上我想排序第一個索引,(這是對我的類的對象),爲此我有一個比較運算符實現。 – Hrishikesh
請通過提供一個可重現的例子*來澄清。 – Roland