Clinician's
corner

Back to main page

Programmer's
corner
So, you use WinBUGS a lot? Want more?
Patrick Blisle
Division of Clinical Epidemiology
McGill University Health Center
Montreal, Quebec CANADA
patrick.belisle@rimuhc.ca

Last modification: 17 aug 2017















Version 1.0 (August 2017)
combine.lists
[R] Combining two lists
[ combine.lists is an R function developped combine/append two lists, with special attention to dimensions present in both. ]


combine.lists(list1, list2) returns a list consisting in the elements found in either list1 or list2, giving precedence to values found in list2 for dimensions found in both lists.

Menu



Top
Syntax

combine.lists(list1, list2)


Top
combine.lists arguments

Argument Value
list1, list2 Two lists to be combined.


Top
Example

The code below reproduces the input and output of a call to combine.lists.

> source('c:/users/patrick/R/fcts/combineLists.R') # load file where combine.lists R function is defined
> list1 <- list(a=rnorm(4), b=seq(3), c=c(10, 11))
> list1

$a
[1] -1.2065101 -0.1044239 0.5002407 -1.3123974

$b
[1] 1 2 3

$c
[1] 10 11

> list2 <- list(b=-seq(2), d=0.24)
> list2

$b
[1] -1 -2

$d
[1] 0.24

> new <- combine.lists(list1, list2)
> new

$a
[1] -1.2065101 -0.1044239 0.5002407 -1.3123974

$b
[1] -1 -2

$c
[1] 10 11

$d
[1] 0.24

Note that the first line of code in the block above reads in the combine.lists function code, if it was previously saved to the file referenced by that command. Alternatively, you can cut and paste the function (see code in section below) directly into R. Of course, if you save your session, this step needs to be done only the first time you use combine.lists.

Also note that the dimension $b — present in both list1 and list2 — in the resulting object new shows the same values as in list2.

Top
Code
combine.lists <- function(list1, list2)
{
   # Combine lists 'list1' and 'list2', giving precedence to elements found in 'list2':
   # that is, if $something is found in both 'list1' and 'list2',
   # the new (output) list will have the same values as 'list2' in $something

   # Version 1.0 (August 2017)
   #
   # Function developed by
   # Patrick Belisle
   # Division of Clinical Epidemiology
   # McGill University Hospital Center
   # Montreal, Qc, Can
   #
   # patrick.belisle@rimuhc.ca
   # http://www.medicine.mcgill.ca/epidemiology/Joseph/PBelisle/BetaParmsFromQuantiles.html


   list1.names <- names(list1)
   list2.names <- names(list2)

   new.list <- list1


   tmp <- match(list2.names, list1.names)
   w <- which(!is.na(tmp))

   if (length(w) > 0)
   {
     # take values from list2 in matching dimension names
     tmp <- tmp[!is.na(tmp)]
     new.list[[tmp]] <- list2[[w]]

     # append elements of 'list2' with unmatched names
     new.list <- c(new.list, list2[-w])
   }
   else
   {
     new.list <- c(new.list, list2)
   }

   new.list
} # end of combine.lists


Top
Download

combine.lists is a free R function. Download version 1.0 now.