R dplyr with seq()

Viewed 100

I need to mutate a column in a dataframe, with the seq of another column. For example with iris, I would like to add a new column for each Species, with seq(min(Sepal.Length),max(Sepal.Length),length=100)

I tried (with no success):

 iris %>% 
     group_by(Species) %>% 
     mutate(seqq = seq(min(Sepal.Length),max(Sepal.Length),  100))

Any ideas?

thank you!

1 Answers

mutate needs to return the same number of rows as the original data or the ones in the group_by. We may use summarise

library(dplyr)
iris %>% 
     group_by(Species) %>% 
     summarise(seq = seq(min(Sepal.Length),max(Sepal.Length), 
         length = 100), .groups = 'drop')

-output

# A tibble: 300 x 2
# Groups:   Species [3]
   Species   seq
   <fct>   <dbl>
 1 setosa   4.3 
 2 setosa   4.32
 3 setosa   4.33
 4 setosa   4.35
 5 setosa   4.36
 6 setosa   4.38
 7 setosa   4.39
 8 setosa   4.41
 9 setosa   4.42
10 setosa   4.44
# … with 290 more rows
Related