purrr语法和map_depth

问题描述 投票:1回答:2

我正在尝试使用不带管道的purrr来保持语法的一致性。但是我遇到了以下相同深度的麻烦提取列表元素

## 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

但是,以下引发错误

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

我应该只使用管道,还是缺少明显的语法错误?

r purrr sapply
2个回答
1
投票

您没有指定需要应用的功能,即

purrr::map(Henry_VIII$marriages, `[[`, 4)
#Similar to
#purrr::map(Henry_VIII$marriages, ~.x[[4]])

#[[1]]
#[1] "annulled"

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

或者也许在这种情况下map_chr会更好?

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

0
投票

我们可以使用lapply中的base R

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

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

或者如果我们需要向量

sapply(Henry_VIII$marriages, `[[`, 4)
© www.soinside.com 2019 - 2024. All rights reserved.