1

I have a data set that looks like the below with many more grouping variables. What I would like to do is expand this data set so that each Score1 is associated with its corresponding Score2 running from the Min to the Max.

data = data.frame(
  Score1 = c(286, 287, 288, 289, 290, 291),
  Score2_Min = c(108, 112, 112, 112, 112, 112),
  Score2_Max = c(111, 113, 113, 113, 113, 113)

  Score1 Score2_Min Score2_Max
1    286        108        111
2    287        112        113
3    288        112        113
4    289        112        113
5    290        112        113
6    291        112        113
)

So the final dataset should look like this:

   Score1 Score2
1     286    108
2     286    109
3     286    110
4     286    111
5     287    112
6     287    113
7     288    112
8     288    113
9     289    112
10    289    113
11    290    112
12    290    113
13    291    112
14    291    113
)
Kate N
  • 423
  • 3
  • 14

2 Answers2

2

We can get the rowwise sequence from 'Score2_Min' to 'Score2_Max' with map2 in a list column and then unnest the list column

library(dplyr)
library(tidyr)
library(purrr)
data %>% 
    transmute(Score1, Score2 = map2(Score2_Min, Score2_Max, `:`)) %>%
    unnest(Score2)
# A tibble: 14 x 2
#   Score1 Score2
#    <dbl>  <int>
# 1    286    108
# 2    286    109
# 3    286    110
# 4    286    111
# 5    287    112
# 6    287    113
# 7    288    112
# 8    288    113
# 9    289    112
#10    289    113
#11    290    112
#12    290    113
#13    291    112
#14    291    113
akrun
  • 874,273
  • 37
  • 540
  • 662
1
library(data.table)
setDT(data)
data[,.(Score2 = Score2_Min:Score2_Max), Score1]
pseudospin
  • 2,737
  • 1
  • 4
  • 19