boshek
boshek

Reputation: 4416

Using purrr::map2 when one variable is not part of the function

If I had a function like this:

foo <- function(var) {
  if(length(var) > 5) stop("can't be greater than 5")

  data.frame(var = var)
}

Where this worked:

df <- 1:20

foo(var = df[1:5])

But this didn't:

foo(var = df)

The desired output is:

   var
1    1
2    2
3    3
4    4
5    5
6    6
7    7
8    8
9    9
10  10
11  11
12  12
13  13
14  14
15  15
16  16
17  17
18  18
19  19
20  20

If I know that I can only run this function in chunk of 5 rows, what would be the best approach if I wanted to evaluate all 20 rows? Can I use purrr::map() for this? Assume that the 5 row constraint is rigid.

Thanks in advance.

Upvotes: 0

Views: 103

Answers (2)

moodymudskipper
moodymudskipper

Reputation: 47330

You can use dplyr::group_by or tapply :

data.frame(df) %>%
  mutate(grp = (row_number()-1) %/% 5) %>%
  group_by(grp) %>%
  mutate(var = foo(df)$var) %>%
  ungroup %>%
  select(var)

# # A tibble: 20 x 1
#     var
# <int>
# 1     1
# 2     2
# 3     3
# 4     4
# 5     5
# 6     6
# 7     7
# 8     8
# 9     9
# 10    10
# 11    11
# 12    12
# 13    13
# 14    14
# 15    15
# 16    16
# 17    17
# 18    18
# 19    19
# 20    20

data.frame(var=unlist(tapply(df,(df-1) %/% 5,foo)))
#    var
# 01   1
# 02   2
# 03   3
# 04   4
# 05   5
# 11   6
# 12   7
# 13   8
# 14   9
# 15  10
# 21  11
# 22  12
# 23  13
# 24  14
# 25  15
# 31  16
# 32  17
# 33  18
# 34  19
# 35  20

Upvotes: 0

Tung
Tung

Reputation: 28391

We split df in chunks of 5 each then use purrr::map_dfr to apply foo function on them then bind everything together by rows

library(tidyverse)

foo <- function(var) {
  if(length(var) > 5) stop("can't be greater than 5")

  data.frame(var = var)
}

df <- 1:20
df_split <- split(df, (seq(length(df))-1) %/% 5)
df_split

map_dfr(df_split, ~ foo(.x))

   var
1    1
2    2
3    3
4    4
5    5
6    6
7    7
8    8
9    9
10  10
11  11
12  12
13  13
14  14
15  15
16  16
17  17
18  18
19  19
20  20

Upvotes: 1

Related Questions