I have simple data frame, let say:
dd <- data.frame(id = letters[1:4], v1 = c(0.3,0.1,0.7,1.3))
dd
id v1
1 a 0.3
2 b 0.1
3 c 0.7
4 d 1.3
For every row of this data frame, I want to "explode" it by adding a new variable which gives a sequence of numbers. I succeeded doing this, but it's my code is not ideal and hardly expendable:
dd %>%
mutate("0"=0,"5"=5,"10"=10) %>%
reshape2::melt(id.vars=c("id", "v1")) %>%
select(-variable)
id v1 value
1 a 0.3 0
2 b 0.1 0
3 c 0.7 0
4 d 1.3 0
5 a 0.3 5
6 b 0.1 5
7 c 0.7 5
8 d 1.3 5
9 a 0.3 10
10 b 0.1 10
11 c 0.7 10
12 d 1.3 10
So, in this example, for every row, I add a column called value
which have all three values within c(0,5,10)
This code is not ideal because the actual sequence I want is pretty much 1:70
and I don't want to write all 70 new variables in my mutate
manually. There sure is a better way of doing this, can you help me?
I don't have to stay in dplyr
but I want ot be able to pipe my code.
Thanks
library(tidyr)
dd %>% crossing(value = c(0, 5, 10))
id v1 value
1 a 0.3 0
2 a 0.3 5
3 a 0.3 10
4 b 0.1 0
5 b 0.1 5
6 b 0.1 10
7 c 0.7 0
8 c 0.7 5
9 c 0.7 10
10 d 1.3 0
11 d 1.3 5
12 d 1.3 10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With