Using seq vectorwise

86 Views Asked by At

I would like to create a column with lists of all integers from a starting vector to an endvector in a datatable.

Is there a way to use seq vectorwise? Something like:

 library(data.table)
 Startpoints <- seq(1,11,5)
 Endpoints <- seq(5,15,5)
 DT <- data.table(Startpoints, Endpoints)
 DT[, sequences := seq(Startpoints, Endpoints, 1)]

which would idealy give me a column like that within DT (not considering list-wrap ups so far):

sequences
1 2 3 4 5
6  7  8  9 10
11 12 13 14 15

More generally asked: I suppose that there is no easy way to transform a function into a vectorized version of it? I still don't fully understand when a (vector)variable represents a single value from one row and when it stands for its complete vector when used as function-argument.

2

There are 2 best solutions below

0
On BEST ANSWER

You could simply use Map:

DT[,sequences := Map(":", Startpoints, Endpoints)]
#   Startpoints Endpoints      sequences
#1:           1         5      1,2,3,4,5
#2:           6        10  6, 7, 8, 9,10
#3:          11        15 11,12,13,14,15

It comes in handy when you are trying to apply a function to corresponding elements of multiple vectors, or in your case columns.

1
On
DT[, .(seq = paste0(Startpoints:Endpoints, collapse = ",")), 
      by = c("Startpoints", "Endpoints")]
#   Startpoints Endpoints            seq
#1:           1         5      1,2,3,4,5
#2:           6        10     6,7,8,9,10
#3:          11        15 11,12,13,14,15

library(dplyr)
 DT %>% group_by(Startpoints, Endpoints) %>% mutate(seq = paste0(Startpoints:Endpoints, collapse = ","))

#  Startpoints Endpoints            seq
#1           1         5      1,2,3,4,5
#2           6        10     6,7,8,9,10
#3          11        15 11,12,13,14,15