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?
CodePudding user response:
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)))