使用map作为参数值的迭代

时间:2018-01-08 23:25:03

标签: r functional-programming purrr

说我有一个简单的功效分析:

> power.t.test(power = .90, delta = 1)

我想对具有幂和delta值的两个向量的值的所有排列设置此函数:

> power_vector <- c(0.85, 0.90, 0.95)
> delta_vector <- c(0.5, 1, 1.5)

这样第一个函数将使用0.85的幂和0.5的delta,第二个函数使用0.85的幂和delta的1,......直到所有的排列都用完为止。

这可以通过purrr:map()purrr:map2()完成吗?

2 个答案:

答案 0 :(得分:2)

您可以使用purrr::cross2进行交叉(笛卡儿)联接以在单个列表中获取组合,然后使用map进行迭代:

library(purrr)

power_vector <- c(0.85, 0.90, 0.95)
delta_vector <- c(0.5, 1, 1.5)

tests1 <- cross2(power_vector, delta_vector) %>% 
    map(~power.t.test(power = .x[[1]], delta = .x[[2]]))

tests1[[1]]
#> 
#>      Two-sample t test power calculation 
#> 
#>               n = 72.80053
#>           delta = 0.5
#>              sd = 1
#>       sig.level = 0.05
#>           power = 0.85
#>     alternative = two.sided
#> 
#> NOTE: n is number in *each* group

另一种方法是创建一个命名的向量列表,在其上调用cross,然后在结果上迭代lift(power.t.test),其中lift修改函数以获取列表参数作为输入(如果愿意,可以向后do.callpurrr::invoke):

tests3 <- list(power = power_vector, 
               delta = delta_vector) %>% 
    cross() %>% 
    map(lift(power.t.test))

tests3[[3]]
#> 
#>      Two-sample t test power calculation 
#> 
#>               n = 104.928
#>           delta = 0.5
#>              sd = 1
#>       sig.level = 0.05
#>           power = 0.95
#>     alternative = two.sided
#> 
#> NOTE: n is number in *each* group

在基地R,

tests2 <- do.call(Map, 
                  c(power.t.test, 
                    expand.grid(power = power_vector, 
                                delta = delta_vector)))

tests2[[2]]
#> 
#>      Two-sample t test power calculation 
#> 
#>               n = 85.03129
#>           delta = 0.5
#>              sd = 1
#>       sig.level = 0.05
#>           power = 0.9
#>     alternative = two.sided
#> 
#> NOTE: n is number in *each* group

答案 1 :(得分:1)

对组合使用expand.grid并传递给func compare(date thisDate: Date, aheadOf aheadOfDate: Date, before beforeDate: Date) -> Bool { return (thisDate > aheadOfDate) && (thisDate < beforeDate) } func fromToday(days: Double) -> Date { let today = Date() return Date(timeIntervalSince1970: today.timeIntervalSince1970 + (days * 86400.0)) //Todays date in seconds + seconds in a day times desired number of days } let today = Date() let fiveDaysAgo = fromToday(days: -5) let oneDayFromToday = fromToday(days: 1) print(compare(date: oneDayFromToday, aheadOf: fiveDaysAgo, before: today)) ,因为pmap会引发错误:

map

因为它产生一个列表,你可能只是期望一个向量:

df_map <- expand.grid(power=power_vector, delta=delta_vector)
purrr::pmap(df_map, power.t.test)