0

this is surely a basic question but couldn't find a way to solve.

I need to create a sequence of values for a minimum (dds_min) to maximum (dds_max) per group (fs). This is my data:

fs <- c("early", "late")
dds_min <-as.numeric(c("47.2", "40"))
dds_max <-as.numeric(c("122", "105"))
dds_min.max <-as.data.frame(cbind(fs,dds_min, dds_max))

And this is what I did....

dss_levels <-dds_min.max %>% 
                group_by(fs) %>% 
                mutate(dds=seq(dds_min,dds_max,length.out=100))

I intended to create a new variable (dds), that has to be 100 length and start and end at different values depending on "fs". My expectation was to end with another dataframe (dss_levels) with two columns (fs and dds), 200 values on it.

But I am getting this error.

Error: Column `dds` must be length 1 (the group size), not 100
In addition: Warning messages:
1: In Ops.factor(to, from) : ‘-’ not meaningful for factors
2: In Ops.factor(from, seq_len(length.out - 2L) * by) :
  ‘+’ not meaningful for factors

Any help would be really appreciated.

Thanks!

Giuseppe Petri
  • 604
  • 4
  • 14
  • 2
    Don't use `as.data.frame(cbind(fs,dds_min, dds_max))`. `cbind()` makes everything a matrix, which turns everything into `character` before converting to to data frame. If you use `data.frame(fs,dds_min, dds_max)` directly, there are no problems. – Gregor Thomas Dec 19 '19 at 22:16
  • Possible duplicate /Related : https://stackoverflow.com/questions/11494511/expand-ranges-defined-by-from-and-to-columns – Ronak Shah Dec 20 '19 at 00:30

1 Answers1

3

I make the sequence length 5 for illustrative purposes, you can change it to 100.

library(purrr)
library(tidyr)
dds_min.max %>%
  mutate(dds= map2(dds_min, dds_max, seq, length.out = 5)) %>%
  unnest(cols = dds)
# # A tibble: 10 x 4
#    fs    dds_min dds_max   dds
#    <fct>   <dbl>   <dbl> <dbl>
#  1 early    47.2     122  47.2
#  2 early    47.2     122  65.9
#  3 early    47.2     122  84.6
#  4 early    47.2     122 103. 
#  5 early    47.2     122 122  
#  6 late     40       105  40  
#  7 late     40       105  56.2
#  8 late     40       105  72.5
#  9 late     40       105  88.8
# 10 late     40       105 105  

Using this data (make sure your numeric columns are numeric! Don't use cbind!)

fs <- c("early", "late")
dds_min <-c(47.2, 40)
dds_max <-c(122, 105)
dds_min.max <-data.frame(fs,dds_min, dds_max)
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
  • Thanks so much @Gregor! Super useful answer. Never used `map2` or `unnest` before... need to explore a bit what those functions do. – Giuseppe Petri Dec 19 '19 at 22:49