1

I'm trying to create a number sequence from a single row when I know the maximum number.

I've actually done this successfully using a loop but want to know how to do this using the apply family of functions and so reduce the number of steps and intermediate objects created.

I've tried combinations of apply, lapply and mapply to no avail.

Here's the data:

df <- structure(list(location = c("doncaster", "dover", "dundee", "eastbourne"), num.pages = c(6, 3, 3, 4)), row.names = c(NA, -4L), class = c("tbl_df", "tbl", "data.frame"))

Here's the loop:

for(i in seq_along(df$location)) {
  assign(
    paste0("loc_seq_", df$location[[i]]),
    seq(from = 1, to = df$num.pages[[i]]) %>%
      enframe(name    = NULL, value = 'page.seq') %>%
      mutate(location = df$location[[i]])
  )
}

I then use:

location_sequence <- bind_rows(mget(ls(pattern = "loc_seq_*")))

... to produce the correct result.

How can I use the apply family to get the same result from my df starting point above please?

nycrefugee
  • 1,629
  • 1
  • 10
  • 23

1 Answers1

2

One dplyr option could be:

df %>%
 uncount(num.pages) %>%
 group_by(location) %>%
 mutate(page.seq = 1:n())

  location   page.seq
   <chr>         <int>
 1 doncaster         1
 2 doncaster         2
 3 doncaster         3
 4 doncaster         4
 5 doncaster         5
 6 doncaster         6
 7 dover             1
 8 dover             2
 9 dover             3
10 dundee            1
11 dundee            2
12 dundee            3
13 eastbourne        1
14 eastbourne        2
15 eastbourne        3
16 eastbourne        4
tmfmnk
  • 38,881
  • 4
  • 47
  • 67