将范围(低、高)扩展到具有索引的值

Expand range (low, high) to values with index

我的数据是这样的:

df <- data.frame(
    index = c(1, 2, 3),
    lo = c(1, 3, 6),
    hi = c(2, 5, 10)
)

#   index lo hi
# 1     1  1  2
# 2     2  3  5
# 3     3  6 10

我想整理低 - 高范围以扩展值:

df_new <- data.frame(
    index = c(1, 1, 2, 2, 2, 3, 3, 3, 3, 3),
    value = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
)

#    index value
# 1      1     1
# 2      1     2
# 3      2     3
# 4      2     4
# 5      2     5
# 6      3     6
# 7      3     7
# 8      3     8
# 9      3     9
# 10     3    10

两个选项 dplyrtidyr,第二种方法适用于数据框中没有重复索引的情况:

library(dplyr); library(tidyr)
df %>% rowwise() %>% summarise(index = index, value = list(lo:hi)) %>% unnest()

# Source: local data frame [10 x 2]

#    index value
#    <dbl> <int>
# 1      1     1
# 2      1     2
# 3      2     3
# 4      2     4
# 5      2     5
# 6      3     6
# 7      3     7
# 8      3     8
# 9      3     9
# 10     3    10


df %>% group_by(index) %>% summarise(value = list(lo:hi)) %>% unnest()

# Source: local data frame [10 x 2]

#    index value
#    <dbl> <int>
# 1      1     1
# 2      1     2
# 3      2     3
# 4      2     4
# 5      2     5
# 6      3     6
# 7      3     7
# 8      3     8
# 9      3     9
# 10     3    10