Question

I have generate following set. How can i get the elements for further usage?
Plus, how can i delete {}?

> library(sets)
> A<-set("item1","item2","item3")
> A
{"item1", "item2", "item3"}
> A[1]
{}        #i would like to have {}
> A[2]
{}        #i would like to have "item1"
> A[3]    
{}        #i would like to have "item2"

Additional question is that:

> A1<-set(paste("item",1:3,sep=""))
> A1
{<<character(3)>>}    # how can i generate the same result as A?

Thanks for your gentle reply!

Was it helpful?

Solution

For sets as mathematical objects, element order (as well as possible repetition) makes no difference. It "doesn't make sense" to talk about a set's "first" or "second" or "third", so the sets package's authors have not supplied a subsetting method that would allow you to retrieve indexed elements of "set"-class objects.

To get a sense of why that's a good design decision that directly follows from the objects' faithful representation of sets' important mathematical structure, examine the following:

library(sets)
a <- set("item3", "item3", "item2", "item1")
b <- set("item1", "item2", "item3")
identical(a,b)
# [1] TRUE

If you insist on extracting set elements with a numeric index, you can always do something like this:

set(as.character(a)[1])
# {"item1"}

As for your second question, the outcome you're after can be got by using the enormously useful function do.call():

do.call(set, as.list(paste("item",1:3,sep="")))
# {"item1", "item2", "item3"}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top