将范围(低,高)扩展为带索引的值

时间:2016-08-16 17:08:02

标签: r dplyr tidyr

我的数据如下:

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

1 个答案:

答案 0 :(得分:3)

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
相关问题