[Rd] merge.list proposal

Eric Lecoutre lecoutre at stat.ucl.ac.be
Tue Nov 23 15:31:46 CET 2004


Hi R-devel,

Today I was needing a way to "merge" two different lists (see the example 
for my definition of merge). I didn't find anything relevant using 
different search methods.
So, here is my proposal to add a list method for "merge".

Best wishes,

Eric

PS: AFAIK, there still is no place for code snipplets. I am not sure this 
mail doesn't suite R-devel. If not, what place could there be for 
discussions/proposal on such code snipplets?

-- CODE

merge.list=function(x,y,only.new.y=FALSE,append=FALSE,...)
{
     out=x

      ystructure = names(c(y,recursive=TRUE))
      xstructure = names(c(x,recursive=TRUE))
      yunique = ystructure[! ystructure %in% xstructure]

      ystructure = sapply(ystructure,FUN=function(element) 
strsplit(element,"\\."))
      xstructure = sapply(xstructure,FUN=function(element) 
strsplit(element,"\\."))
      yunique = sapply(yunique,FUN=function(element) strsplit(element,"\\."))

     if (only.new.y) lapply(yunique, FUN=function(index) 
out[[index]]<<-y[[index]])
     else
     {
       if (!append){
             lapply(ystructure, FUN=function(index) out[[index]]<<-y[[index]])
       }
       else lapply(ystructure, FUN=function(index) 
out[[index]]<<-c(out[[index]],y[[index]]))
     }
     return(out)
}

-- SAMPLE
 > (l1=list(a=list(a1=1,a2=2),b=list(b1=1)))
$a
$a$a1
[1] 1

$a$a2
[1] 2


$b
$b$b1
[1] 1


 > (l2=list(a=list(a1=-1,a3=3),c=pi))
$a
$a$a1
[1] -1

$a$a3
[1] 3


$c
[1] 3.141593

 > merge(l1,l2)
$a
$a$a1
[1] -1

$a$a2
[1] 2

$a$a3
[1] 3


$b
$b$b1
[1] 1


$c
[1] 3.141593

 > merge(l1,l2,append=TRUE)
$a
$a$a1
[1]  1 -1

$a$a2
[1] 2

$a$a3
[1] 3


$b
$b$b1
[1] 1


$c
[1] 3.141593

 > merge(l1,l2,only.new.y=TRUE)
$a
$a$a1
[1] 1

$a$a2
[1] 2

$a$a3
[1] 3


$b
$b$b1
[1] 1


$c
[1] 3.141593

 >

--
Eric Lecoutre
UCL /  Institut de Statistique
Voie du Roman Pays, 20
1348 Louvain-la-Neuve
Belgium

tel: (+32)(0)10473050
lecoutre at stat.ucl.ac.be
http://www.stat.ucl.ac.be/ISpersonnel/lecoutre

If the statistics are boring, then you've got the wrong numbers. -Edward 
Tufte



More information about the R-devel mailing list