I'm having trouble rearranging the following data frame with tidyr
package:
data <- data.frame(
name = rep(c("John", "Mary", "Peter", "Sarah"), each=2),
firm = c("a", "b", "c", "d", "a", "b", "c", "d"),
rank = rep(1:2, 4),
value = rnorm(8)
)
I want to reshape it so that each unique "name" variable is a rowname, with the "values" as observations along that row and the "rank" as colnames followed by the "firm" name. Sort of like this:
name 1 firm_1 2 firm_2
John 0.3407997 a -0.3795377 b
Mary -0.8981073 c -0.5013782 d
Peter 0.3407997 a -0.3795377 b
Sarah -0.8981073 c -0.5013782 d
library(data.table);dcast(setDT(data), name ~ rank, value.var = c("firm", "value"))
– akrun[,c(1,4,2,5,3)]
behind akrun's solution to sort it like yours. – Andre Elrico