Reputation: 11
I have this data set:
Now I want to add rows, which contain all the ages that between minimum and maximum of each id, like this dataset:
Could someone give me some tips? Thanks in advance.
Upvotes: 0
Views: 62
Reputation: 887223
Here is an option with tidyverse
. We get the sequence of 'min_age', 'max_age' with map2
within transmute
and then unnest
the list
column to get the expected output
library(tidyverse)
DF %>%
transmute(id = id, age = map2(min_age, max_age, `:`)) %>%
unnest
# id age
#1 1 60
#2 1 61
#3 1 62
#4 1 63
#5 1 64
#6 1 65
#7 2 55
#8 2 56
#9 2 57
#10 3 72
#11 4 67
#12 4 68
#13 4 69
#14 5 58
#15 5 59
#16 5 60
#17 5 61
Or using base R
with Map
stack(setNames(do.call(Map, c(f = `:`, DF[-1])), DF$id))[2:1]
DF <- structure(list(id = 1:5, min_age = c(60, 55, 72, 67, 58), max_age = c(65,
57, 72, 69, 61)), class = "data.frame", row.names = c(NA, -5L
))
Upvotes: 0
Reputation: 26343
This can be done with data.table
DF <- data.frame(id = 1:5,
min_age = c(60, 55, 72, 67, 58),
max_age = c(65, 57, 72, 69, 61))
library(data.table)
setDT(DF)[, .(age = seq(min_age, max_age)), by = id]
# id age
# 1: 1 60
# 2: 1 61
# 3: 1 62
# 4: 1 63
# 5: 1 64
# 6: 1 65
# 7: 2 55
# 8: 2 56
# 9: 2 57
#10: 3 72
#11: 4 67
#12: 4 68
#13: 4 69
#14: 5 58
#15: 5 59
#16: 5 60
#17: 5 61
Upvotes: 1