Reputation: 85
Suppose I have:
x <- c(1, 2, 3, 4, 5)
y <- c(2, 3, 6, 8, 10)
my.list <- list(start = x, end = y) %>% as.data.frame()
I need to define a new variable that contains seq(start,end) or start:end stored in that variable, I want the sequence of numbers across the rows, for example, 1 2 for the first row and 3 4 5 6 for the third row.
Many thanks
Upvotes: 3
Views: 845
Reputation: 887951
We can use map2
to get the seq
uence of corresponding values of 'start', 'end' to create a list
of vector
s
library(dplyr)
library(purrr)
my.list %>%
mutate(new = map2(start, end, `:`))
# start end new
#1 1 2 1, 2
#2 2 3 2, 3
#3 3 6 3, 4, 5, 6
#4 4 8 4, 5, 6, 7, 8
#5 5 10 5, 6, 7, 8, 9, 10
Another option is rowwise
my.list %>%
rowwise %>%
mutate(new = list(start:end))
# A tibble: 5 x 3
# Rowwise:
# start end new
# <dbl> <dbl> <list>
#1 1 2 <int [2]>
#2 2 3 <int [2]>
#3 3 6 <int [4]>
#4 4 8 <int [5]>
#5 5 10 <int [6]>
Or with data.table
as @markus mentioned in comments
library(data.table)
setDT(my.list)[, V3 := Map(`:`, start, end)]
Or with Map
from base R
Map(`:`, my.list$start, my.list$end)
Upvotes: 5