Search code examples
rpurrrsapply

purrr syntax and map_depth


I'm trying to use purrr without piping for some consistency in syntax. But I'm running into the following trouble extract list elements at the same depth

## Example of a list

Henry_VIII <- 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(name="Catherine of Aragon", marriage_date=1509, end_date=1533, end_cause="annulled")
Anne_Boleyn <- list(name="Anne Boleyn", marriage_date=1533, end_date=1536, end_cause="executed")

Henry_VIII <- 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", marriages=list(Catherine_of_Aragon,Anne_Boleyn))  


sapply(1:length(Henry_VIII$marriages), function(x) Henry_VIII$marriages[[x]]$end_cause) ##works fine

Henry_VIII$marriages %>% map_depth(1,4) ## also works fine

But, the following throws an error

purrr::map(Henry_VIII$marriages, c(1,4))

Should I just use piping, or is there an obvious syntax error I'm missing?


Solution

  • You didn't specify the function you need to apply i.e

    purrr::map(Henry_VIII$marriages, `[[`, 4)
    #Similar to
    #purrr::map(Henry_VIII$marriages, ~.x[[4]])
    
    #[[1]]
    #[1] "annulled"
    
    #[[2]]
    #[1] "executed"
    

    Or perhaps, in this case map_chr would be better?

    purrr::map_chr(Henry_VIII$marriages, `[[`, 4)
    #[1] "annulled" "executed"