Giuseppe Petri
Giuseppe Petri

Reputation: 640

How to make a sequence of values in a factorial dataframe?

I am trying to get a 3 column data frame for a combination of two factors (gen and treat) and x values from a sequence spanning from min and max values. Why am I getting a 6 column table instead?

I have a dataframe with max and min values observed for each combination of gen and treat. Create an empty dataframe to be populated with the loop. Get a sequence of 100 from the min and max values. And then tried to paste all and store back in the empty dataframe.

Here is my reproducible example"

gen <- c("gen1", "gen2" , "gen3")
trt <- c("treat1", "treat2")
t1 <- expand.grid(gen, trt)
max.vals <- c(0.005570975, 0.006843775, 0.006046788, 0.005808882, 0.005091197, 0.007763680)
min.vals <- c(-0.002843542 -0.002425798 -0.002187437 -0.002872362 -0.004089794 -0.003156588)
t2 <- data.frame(t1, min.vals, max.vals)
colnames(t2) <- c("gen", "trt", "min.vals", "max.vals")


x.values <- as.data.frame(matrix(nrow = 600, ncol = 3)) #empty dataframe
for (i in 1:6) {
        x.vals <- seq(t2$min.vals[i], t2$max.vals[i], length.out = 100) 
        gen.tret <- paste(t2$gen[i], t2$trt[i], x.vals)
        x.values[i] <- gen.tret
        }

I expected a 3 column (gen, rep, and x.vals from the sequence), but I am having a 6 column dataframe.

Upvotes: 1

Views: 247

Answers (1)

akrun
akrun

Reputation: 887511

Here is an option with tidyverse. Grouped by 'gen', 'trt' get the complete sequence between each element of 'min.vals', 'max.vals'

library(tidyverse)
t2 %>% 
   group_by(gen, trt) %>%
   complete(min.vals =  seq(min.vals, max.vals, length.out = 100)) %>%
   select(gen, trt, x.vals = min.vals)

Or with map2

t2 %>%
  transmute(gen, trt, x.vals = map2(min.vals, max.vals, seq, length.out = 100)) %>%
  unnest

Upvotes: 1

Related Questions