简体   繁体   中英

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?

You didn't specify the function you need to apply ie

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"

We can use lapply from base R

lapply(Henry_VIII$marriages, `[[`, 4)
#[[1]]
#[1] "annulled"

#[[2]]
#[1] "executed"

Or if we need a vector

sapply(Henry_VIII$marriages, `[[`, 4)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM