Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Problems creating nested data or better solution in R

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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)))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading