The following problem can be seen as a "two-column reshape to wide", and there are several methods available to solve it the classical way, from base::reshape
(horror) to reshape2
. For the two-group case, a simple subgroup join works best.
Can I reformulate the join within the piping framework of dplyr
? The example below is a bit silly, but I needed the join in a longer pipe-chain which I do not want to break.
library(dplyr)
d = data.frame(subject= rep(1:5,each=2),treatment=letters[1:2],bp = rnorm(10))
d %>%
# Assume piped manipulations here
# Make wide
# Assume additional piped manipulations here
# Make wide (old style)
with(d,left_join(d[treatment=="a",],
d[treatment=="b",],by="subject" ))
How about
You could continue the pipe right after the left join.
Or if you don't require the separate treatment columns, you could use tidyr to do:
(which is the same as using
d %>% dcast(subject ~ treatment, value.var = "bp")
fromreshape2
package as noted by Henrik in the comments)