I have an issue of expanding rows of my data frame. I tried expand
from tidyr
inside of a dplyr
chain. The point is that it seems that this function is expanding the data but by changing the order of expand element which is not desired. I want to keep order of sp
column after expand.
Here is my attempt
df <- data.frame(label1=letters[1:6],label2=letters[7:12])
sp <- c(-1,0,seq(0.1,0.5,0.1),seq(-2,-2.5,-0.1),seq(0.1,0.5,0.1))
sp
# [1] -1.0 0.0 0.1 0.2 0.3 0.4 0.5 -2.0 -2.1 -2.2 -2.3 -2.4 -2.5 0.1 0.2 0.3 0.4 0.5
library(dplyr)
library(tidyr)
expanded <- df%>%
expand(df,sp)
> head(expanded)
label1 label2 sp
1 a g -2.5
2 a g -2.4
3 a g -2.3
4 a g -2.2
5 a g -2.1
6 a g -2.0
I want to expand df
based on sp
order. how can we do that?
expected output
label1 label2 sp
1 a g -1.0
2 a g 0.0
3 a g 0.1
4 a g 0.2
5 a g 0.3
6 a g 0.4
7 a g 0.5
8 a g -2
9 a g -2.1
10 a g -2.2
11 a g -2.3
12 a g -2.4
13 a g -2.5
14 b h -1.0
15 b h 0.0
16 b h 0.1
and so on
We can
match
the column 'sp' with the vectorsp
in the global environment to do the orderingUpdate
If there are duplicates in the 'sp'
vector
and we want toexpand
on all the values, one option is to do the expansion on the sequence of thevector
and later change the values