0

I want to create create an extra column with positions in a data frame. My plan was to use the start and end column as the input of seq command and expected with as.list to get a nested data entry which I can afterwards just unnest. But this is giving me an error. So as n example:

tibble(
  start=c(1,7),
  end=c(3,10),
  total=15,
  value=c(100,200)
)

My expected result would be something like this:

tibble(
  start=c(1,1,1,7,7,7,7),
  end=c(3,3,3,10,10,10,10),
  total=15,
  value=c(100,100,100,200,200,200,200),
  position=c(1,2,3,7,8,9,10)
)

I tried something like

tibble(
  start=c(1,7),
  end=c(3,10),
  total=15,
  value=c(100,200)
) %>% 
  mutate(position=as.list(seq(start,end))) %>% 
  unnest(position)

What am I doing wrong?

drmariod
  • 11,106
  • 16
  • 64
  • 110
  • 1
    Related: [Expand ranges defined by "from" and "to" columns](https://stackoverflow.com/questions/11494511/expand-ranges-defined-by-from-and-to-columns) – Henrik Jan 04 '23 at 14:11

1 Answers1

2

The error comes from seq. You must apply your function row-wise, since the call is interpreting seq(c(1, 7), c(3, 10)) by default.

To do that, you can use mapply, pmap, or rowwise.

tbl %>% 
  mutate(position = mapply(seq, start, end))
tbl %>% 
  rowwise() %>% 
  mutate(position = list(seq(start, end)))
Maël
  • 45,206
  • 3
  • 29
  • 67
  • 1
    Just for completeness, could you provide a solution using `rowwise` – drmariod Jan 04 '23 at 14:06
  • 1
    Thanks! Just figured out, that in the rowwise solution I have to wrap in list... The rowwise solution is more intuitive I think. Thanks, that did the trick! – drmariod Jan 04 '23 at 14:09