Question

I have nested lists of strings:

mylist1 <- list(
   list(c("banana"),c("banana","tomato"))
 , list(c("", "nut"), c("nut", "orange"))
   )

mylist2 <- list(
   list(c("orange","nut"), c("nut", ""))
 , list(c("tomato","banana"),c("banana"))
)

mylist3 <- list(
   list(c("orange","nut"), c("nut"))
 , list(c("tomato","banana"),c("banana"))
)

Note: In the above example mylist1and mylist2 would be equal. But mylist3 is different from mylist1 and mylist2, as the sublist with the empty string and "nut" is missing c("nut", "")

The order of the elements in the lists are not important. I want a function that compares two such lists and returns a boolean, if they are equal when disregarding the order of elements.

Essentially my nested lists of type string represent mathematical sets. I want to compare two such nested lists, but as they represent sets the order is not important. I want to get a boolean (true/false) value back.

Était-ce utile?

La solution

If you dont have duplicated items in your lists, you can use Set and Set Operations. So it would be something like:

(set1 <-c(mylist1, NA))
(set2 <-c(mylist2, NA))
setequal(set1, set2)

Autres conseils

You can always compare each element of list 1 to second list's elements, but that would take a long time and can be impossible (On^2) (it is going to be a nested loop) The other option that comes to my mind is to sort both lists and then do a comparison between them, since they are both sorted you only have to check an element in list 1 to the same order element in list 2. The second option is theoretically going to be faster: (assuming sorting the lists take nLog(n)) it is going to be 2*nLog(n) + n (number of times you check the elements of both sorted lists) which is OnLog(n)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top