I have a dataframe like this:
df = data.frame(time=c(2010:2015,2010:2015),
variable=c(rep("a",6),rep("b",6)),
value=c(rnorm(6),rnorm(6,mean=10)))
or:
time variable value
1 2010 a -0.5472416
...
6 2015 a -0.2433123
7 2010 b 9.8617777
...
12 2015 b 7.7674609
I need to create a new variable 'c=a-b'. The best solution I've found is to use packages 'dplyr' and 'tidyr':
df <- spread(df,variable,value) %>%
mutate(c=b-a) %>%
gather(variable,value,a:c) %>%
filter(variable=="c")
which gives the requested outcome:
time variable value
1 2010 c 10.444794
2 2011 c 8.121627
...
6 2015 c 10.589378
Is there a more direct way to obtain the same result, which does not require first to "spread" and then to "gather" the dataframe?