2

Here is my data:

For each x1 level, I am trying to duplicate a number of rows equal to number.class and I would like for each row the length class to goes from the Lmin..cm. to Lmax..cm. increasing by 1 for each row.I came up with this code:

test<-A.M %>% filter(x1=="Crenimugil crenilabis")
for (i in 1:test$number.class){test<-test %>%  add_row()}
for (i in 1:nrow(test)){test[i,]=test[1,]}
  for (i in 1:nrow(test)){test$length.class[i]<-print(i+test$Lmin..cm.)}
  test$length.class<-test$length.class-1

which basically works and gives me the expected results: 2

However, this script does not allow me to run this for every species.

Thank you.

Sebastien
  • 25
  • 3

1 Answers1

2

Here, we could use uncount from tidyr to replicate the rows, do a group by 'x1' and mutate the 'Lmin..cm' by adding the row_number()

library(dplyr)
library(tidyr)
A.M %>%
    uncount(number.class) %>%
    group_by(x1) %>%
    mutate(`Lmin..cm.` = `Lmin..cm.` + row_number())

If we need to create a sequence from Lmin..cm to Lmax..cm, then instead of uncount, we could use map2 to create the sequence and then unnest

library(purrr)
A.M %>%
     mutate(new = map2(`Lmin..cm.`, `Lmax..cm`, ~ seq(.x, .y, by = 1)) %>%
    unnest(c(new))
akrun
  • 874,273
  • 37
  • 540
  • 662