purrr 语法和 map_depth
purrr syntax and map_depth
我正在尝试使用不带管道的 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))
我应该只使用管道,还是我遗漏了明显的语法错误?
您没有指定需要应用的函数,即
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"
我们可以使用 base R
中的 lapply
lapply(Henry_VIII$marriages, `[[`, 4)
#[[1]]
#[1] "annulled"
#[[2]]
#[1] "executed"
或者如果我们需要一个向量
sapply(Henry_VIII$marriages, `[[`, 4)
我正在尝试使用不带管道的 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))
我应该只使用管道,还是我遗漏了明显的语法错误?
您没有指定需要应用的函数,即
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"
我们可以使用 base R
lapply
lapply(Henry_VIII$marriages, `[[`, 4)
#[[1]]
#[1] "annulled"
#[[2]]
#[1] "executed"
或者如果我们需要一个向量
sapply(Henry_VIII$marriages, `[[`, 4)