Search code examples
rlistsapply

Replace NULL is list with NA


I'm trying to extract elements from a list, replacing NULL's with NA's. My simple ifelse and is.null statement seems to truncate sub-lists to the first element. What's going on?

Henry_VIII.list <- list(name="Henry Tudor",DOB=as.Date("28 June 1491", format=("%d %B %Y")),place_of_birth="Palace of Placentia, Greenwich, Kent",
                        DOD=as.Date("28 January 1547", format=("%d %B %Y")),place_of_death="Palace of Whitehall, London")

Catherine_of_Aragon.list <- list(name="Catherine of Aragon",DOB=as.Date("16 December 1485", format=("%d %B %Y")),place_of_birth="Archiepiscopal Palace of Alcalá de Henares, Alcalá de Henares, Castile", DOD=as.Date("7 January 1536", format=("%d %B %Y")),place_of_death="Kimbolton Castle, England")
Anne_Boleyn.list <- list(name="Anne Boleyn", DOB="?? July 1501", place_of_birth="Blickling Hall, Norfolk or Hever Castle, Kent", DOD=as.Date("19 May 1536", format=("%d %B %Y")),place_of_death="Tower of London, London")

Henry_VIII.list$spouse <- list(Catherine_of_Aragon.list,Anne_Boleyn.list)
Emily_Dickinson.list <- list(name="Emily Dickinson",DOB=as.Date("10 December 1830", format=("%d %B %Y")),place_of_birth="Amherst, Massachusetts, US",
                             DOD=as.Date("15 May 1886", format=("%d %B %Y")),place_of_death="Amherst, Massachusetts, US")

biography.list <- list(Henry_VIII.list,Emily_Dickinson.list)
sapply(1:2, function(x) biography.list[[x]]$spouse) ## gets correct results
sapply(1:2, function(x) ifelse(is.null(biography.list[[x]]), NA, biography.list[[x]])) ## kills Anne Boleyn

Solution

  • We can also do an assignment

    biography.list <- lapply(biography.list, function(x) 
              {x$spouse[is.null(x$spouse)] <- NA;x})