为了语法上的一致性,我尝试使用不带管道的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))我应该只使用管道,还是我遗漏了一个明显的语法错误?
发布于 2020-01-26 23:58:51
您没有指定需要应用的函数,即
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"发布于 2020-01-27 02:05:52
我们可以从base R使用lapply
lapply(Henry_VIII$marriages, `[[`, 4)
#[[1]]
#[1] "annulled"
#[[2]]
#[1] "executed"或者如果我们需要一个向量
sapply(Henry_VIII$marriages, `[[`, 4)https://stackoverflow.com/questions/59920038
复制相似问题