[Rd] merge.list proposal

From: Eric Lecoutre <lecoutre_at_stat.ucl.ac.be>
Date: Wed 24 Nov 2004 - 01:31:46 EST

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?

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)

}

$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@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

______________________________________________
R-devel@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel
Received on Wed Nov 24 02:17:35 2004

This archive was generated by hypermail 2.1.8 : Wed 24 Nov 2004 - 03:12:37 EST