R语言 如何解析一个数字范围?

jjjwad0x  于 2023-06-19  发布在  其他
关注(0)|答案(2)|浏览(159)

我有一些数据看起来像这样:

> dput(range)
structure(list(Range = c("0T-1T", "2T-5T")), class = "data.frame", row.names = c(NA, 
-2L))

基本上,我想知道是否有可能解析出这些值,以便最终的dataframe看起来像这样:

> dput(range2)
structure(list(Range = c("0T", "1T", "2T", "3T", "4T", "5T")), class = "data.frame", row.names = c(NA, 
-6L))
wrrgggsh

wrrgggsh1#

tidyverse解决方案,其中tidyr::separate_longer_delim() + tidyr::full_seq()

library(tidyverse)

range %>%
  group_by(grp = Range) %>%
  separate_longer_delim(Range, '-') %>%
  reframe(Range = paste0(full_seq(parse_number(Range), 1), 'T')) %>%
  select(-grp)

# # A tibble: 6 × 1
#   Range
#   <chr>
# 1 0T
# 2 1T   
# 3 2T
# 4 3T
# 5 4T
# 6 5T
c2e8gylq

c2e8gylq2#

可能有更简单的方法,但这里有一个方法:

library(dplyr, warn.conflicts = F)
library(stringr)
library(tidyr)
library(purrr)
structure(list(Range = c("0T-1T", "2T-5T")), class = "data.frame", row.names = c(NA, 
                                                                                 -2L)) %>% 
    mutate(
        Range = str_split(Range, '-'),
        Range = map(Range, str_remove, 'T'),
        Range = map(Range, as.integer),
        Range = map(Range, ~ paste0('T', seq(.x[1], .x[2], 1)))
    ) %>% 
    unnest(Range)
#> # A tibble: 6 × 1
#>   Range
#>   <chr>
#> 1 T0   
#> 2 T1   
#> 3 T2   
#> 4 T3   
#> 5 T4   
#> 6 T5

创建于2023-06-08使用reprex v2.0.2
假设只在每个“XT-YT”对内扩展,而不是整个范围(这肯定会更容易)。

相关问题