简体   繁体   中英

Creating sequence of numbers inside a string R

I want to create a sequence of numbers as a string. I have columns "start" and "end" indicating the start and end of the sequence. The desired output is a string with a sequence by 1. See the example below.

df <- data.frame(ID=seq(1:5), 
                 start=seq(2,10,by=2),
                 end=seq(5,13,by=2),
                 desired_output_aschar= c("2,3,4,5", "4,5,6,7", "6,7,8,9", "8,9,10,11", "10,11,12,13"))

View(df)

Thank you in advance...

The following solution needs only one *apply loop.

mapply(function(x, y) paste(x:y, collapse = ","), df$start, df$end)
#[1] "2,3,4,5"     "4,5,6,7"     "6,7,8,9"     "8,9,10,11"   "10,11,12,13"

With the new lambdas, same output.

mapply(\(x, y) paste(x:y, collapse = ","), df$start, df$end)

Mapply to call the different seq function, sapply to call the columns

sapply(
  data.frame(mapply(seq,df$start,df$end)),
  paste0,
  collapse=","
)

           X1            X2            X3            X4            X5 
    "2,3,4,5"     "4,5,6,7"     "6,7,8,9"   "8,9,10,11" "10,11,12,13" 

Using dplyr -

library(dplyr)

df %>%
  rowwise() %>%
  mutate(output = toString(start:end)) %>%
  ungroup

#     ID start   end output        
#  <int> <dbl> <dbl> <chr>         
#1     1     2     5 2, 3, 4, 5    
#2     2     4     7 4, 5, 6, 7    
#3     3     6     9 6, 7, 8, 9    
#4     4     8    11 8, 9, 10, 11  
#5     5    10    13 10, 11, 12, 13

We could use map2 from purrr

library(dplyr)
library(purrr)
df %>% 
   mutate(output = map2_chr(start, end,  ~ toString(.x:.y)))
  ID start end desired_output_aschar         output
1  1     2   5               2,3,4,5     2, 3, 4, 5
2  2     4   7               4,5,6,7     4, 5, 6, 7
3  3     6   9               6,7,8,9     6, 7, 8, 9
4  4     8  11             8,9,10,11   8, 9, 10, 11
5  5    10  13           10,11,12,13 10, 11, 12, 13

A data.table option

> setDT(df)[, out := toString(seq(start, end)), ID][]
   ID start end desired_output_aschar            out
1:  1     2   5               2,3,4,5     2, 3, 4, 5
2:  2     4   7               4,5,6,7     4, 5, 6, 7
3:  3     6   9               6,7,8,9     6, 7, 8, 9
4:  4     8  11             8,9,10,11   8, 9, 10, 11
5:  5    10  13           10,11,12,13 10, 11, 12, 13

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM