[R] Unique lists from a list

Adaikalavan Ramasamy ramasamy at cancer.org.uk
Wed Sep 1 17:05:53 CEST 2004


name <- c("a", "b", "a", "c", "d", "a", "b")
addr <- c(10, 20, 10, 30, 40, 10, 20)

duplicated(name)
[1] FALSE FALSE  TRUE FALSE FALSE  TRUE  TRUE

which(duplicated(name))
[1] 3 6 7

addr[ -which(duplicated(name)) ]
[1] 10 20 30 40

cbind( name, addr) [ -which(duplicated(name)),  ]
     name addr
[1,] "a"  "10"
[2,] "b"  "20"
[3,] "c"  "30"
[4,] "d"  "40"

Make sure that person named "a" always lives in address "10" (i.e.
one-to-one mapping). 


If it is possible for person "a" to have two addresses (e.g. house and
office) "10" and "11", then it might be better to collect both address.
In this case, you can try :

addr2  <- c(10, 20, 11, 30, 40, 12, 21)
tapply(addr2, as.factor(name), function(x) paste(x, collapse=", ") )
           a            b            c            d
"10, 11, 12"     "20, 21"         "30"         "40"

To convert this into a list, use sapply(a, strsplit, split=", ").



On Wed, 2004-09-01 at 15:31, michael watson (IAH-C) wrote:
> Hi
> 
> I have a list.  Two of the elements of this list are "Name" and
> "Address", both of which are character vectors.  Name and Address are
> linked, so that the same "Name" always associates with the same
> "Address".
> 
> What I want to do is pull out the unique values, as a new list of the
> same format (ie two elements of character vectors).  Now I've worked out
> that unique(list$Name) will give me a list of the unique names, but how
> do I then go and link those to the correct (unique) addresses so I end
> up with a new list which is the same format as the rest, but now unique?
> 
> Cheers
> Mick
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>




More information about the R-help mailing list