[R] Adding elements to existing lists

David Winsemius dwinsemius at comcast.net
Sat Feb 16 18:38:10 CET 2008


"Mag. Ferri Leberl" <ferri.leberl at gmx.at> wrote in
news:1203175203.27666.2.camel at localhost: 

> Dear everybody!
> Is there a command to add elements to an existing list, at best
> excluding the addition of already included ones?
> Thank you in advance.
> Yours,
> Mag. Ferri Leberl

Don't know of one, but it's not that hard to make one.

lone <- c( "r","is", "great")
ltwo <- "great"
lthree <- "but sometimes puzzling"

add.unique<-function(ls1,ls2) {
            ifelse (ls2 %in% ls1, return(ls1) , return(c(ls1,ls2)) )
              }

> add.unique(lone,ltwo)
[1] "r"     "is"    "great"

> add.unique(lone,lthree)
[1] "r"                       "is"                     
[3] "great"                   "but sometimes puzzling"

# my puzzlement: until using return(<list argument>),
# only got the first element, "r",  back
# I thought ifelse( (.), ls1, .) would evaluate to all of ls1

Technically these are character vectors. If you wanted a more LISP-like 
list then you may need to use list() rather than c(). Or you could use 
a construction like:

 lone[[length(lone)+1]]<-new.element

You really should include example data that lets the reader tell what 
structure you are working with and what you expect the function(s) to 
return.

-- 
David Winsemius



More information about the R-help mailing list