Data
require(tidyverse)
d <- tibble(group = c("HRT", "Placebo"),
MeanHDL = c(8, 2),
sdHDL = c(10, 4))
d
## # A tibble: 2 x 3
## group MeanHDL sdHDL
## <chr> <dbl> <dbl>
## 1 HRT 8 10
## 2 Placebo 2 4
map function, 5 ways
With Just function name
d %>%
mutate(logldl = map(MeanHDL, log)) %>%
unnest()
## # A tibble: 2 x 4
## group MeanHDL sdHDL logldl
## <chr> <dbl> <dbl> <dbl>
## 1 HRT 8 10 2.08
## 2 Placebo 2 4 0.693
With mentioning additional parameters
d %>%
mutate(logldl = map(MeanHDL, log, base = 2)) %>%
unnest()
## # A tibble: 2 x 4
## group MeanHDL sdHDL logldl
## <chr> <dbl> <dbl> <dbl>
## 1 HRT 8 10 3
## 2 Placebo 2 4 1
With a ~ sign, bracket and .x
d %>%
mutate(logldl = map(MeanHDL, ~log(.x))) %>%
unnest()
## # A tibble: 2 x 4
## group MeanHDL sdHDL logldl
## <chr> <dbl> <dbl> <dbl>
## 1 HRT 8 10 2.08
## 2 Placebo 2 4 0.693
With ~, bracket, .x and additional parameter
d %>%
mutate(logldl = map(MeanHDL, ~log(.x, base = 2))) %>%
unnest()
## # A tibble: 2 x 4
## group MeanHDL sdHDL logldl
## <chr> <dbl> <dbl> <dbl>
## 1 HRT 8 10 3
## 2 Placebo 2 4 1
With ..1 to mention the first variable as first argument
d %>%
mutate(logldl = map(MeanHDL, ~log(..1))) %>%
unnest()
## # A tibble: 2 x 4
## group MeanHDL sdHDL logldl
## <chr> <dbl> <dbl> <dbl>
## 1 HRT 8 10 2.08
## 2 Placebo 2 4 0.693
map2 function, 4 ways
With Just function name and argument
d %>%
mutate(simldl = map2(MeanHDL, sdHDL, rnorm, n = 1000)) %>%
unnest() %>%
group_by(group) %>%
summarise(mean(simldl), sd(simldl))
## # A tibble: 2 x 3
## group `mean(simldl)` `sd(simldl)`
## <chr> <dbl> <dbl>
## 1 HRT 8.19 10.2
## 2 Placebo 1.78 3.86
With ~ sign, bracket and .x , .y
d %>%
mutate(simldl = map2(MeanHDL, sdHDL, ~rnorm(1000, .x, .y))) %>%
unnest() %>%
group_by(group) %>%
summarise(mean(simldl), sd(simldl))
## # A tibble: 2 x 3
## group `mean(simldl)` `sd(simldl)`
## <chr> <dbl> <dbl>
## 1 HRT 8.24 9.97
## 2 Placebo 2.08 4.01
With ..1 to mention the first variable as first argument, and second variable as second argument
d %>%
mutate(simldl = map2(MeanHDL, sdHDL, ~rnorm(1000, ..1, ..2))) %>%
unnest() %>%
group_by(group) %>%
summarise(mean(simldl), sd(simldl))
## # A tibble: 2 x 3
## group `mean(simldl)` `sd(simldl)`
## <chr> <dbl> <dbl>
## 1 HRT 8.08 10.2
## 2 Placebo 1.97 3.83
Rotating the arguments list will result in different result
d %>%
mutate(simldl = map2(MeanHDL, sdHDL, ~rnorm(1000, ..2, ..1))) %>%
unnest() %>%
group_by(group) %>%
summarise(mean(simldl), sd(simldl))
## # A tibble: 2 x 3
## group `mean(simldl)` `sd(simldl)`
## <chr> <dbl> <dbl>
## 1 HRT 9.96 8.04
## 2 Placebo 4.01 2.06