I have the following data.frame
df = structure(list(HEADER = c("HOME_TRPM", "AWAY_TRPM", "HOME_TEAM","AWAY_TEAM"), price = c("0.863104076023855", "-0.845186446996287","CHA", "NOP")), .Names = c("HEADER", "price"), row.names = c(NA, 4L), class = "data.frame") df #> HEADER price #> 1 HOME_TRPM 0.863104076023855 #> 2 AWAY_TRPM -0.845186446996287 #> 3 HOME_TEAM CHA #> 4 AWAY_TEAM NOP
which I want to transpose. How can I do it in dplyr without using t()? I tried
df %>% tidyr::spread(HEADER , price)
but it doesn't give a flat structure but instead does this:
structure(list(AWAY_TEAM = c(NA, NA, NA, "NOP"), AWAY_TRPM = c(NA, "-0.845186446996287", NA, NA), HOME_TEAM = c(NA, NA, "CHA", NA), HOME_TRPM = c("0.863104076023855", NA, NA, NA)), .Names = c("AWAY_TEAM", "AWAY_TRPM", "HOME_TEAM", "HOME_TRPM"), class = "data.frame", row.names = c(NA, 4L))
The resulting data.frame should be like this:
structure(list(HOME_TRPM = "0.863104076023855", AWAY_TRPM = "-0.845186446996287", HOME_TEAM = "CHA", AWAY_TEAM = "NOP"), .Names = c("HOME_TRPM", "AWAY_TRPM", "HOME_TEAM", "AWAY_TEAM"), row.names = c(NA, -1L), class = "data.frame"))
Transpose of a matrix is an operation in which we convert the rows of the matrix in column and column of the matrix in rows. The general equation for performing the transpose of a matrix is as follows.
To interchange rows with columns, you can use the t() function. For example, if you have the matrix (or dataframe) mat you can transpose it by typing t(mat) . This will, as previously hinted, result in a new matrix that is obtained by exchanging the rows and columns.
I think you want tidyr
rather than dplyr
:
library(tidyr) library(dplyr) df %>% mutate(group = 1) %>% spread(HEADER, price) group AWAY_TEAM AWAY_TRPM HOME_TEAM HOME_TRPM 1 1 NOP -0.845186446996287 CHA 0.863104076023855
Using this, you can specify your groupings - and you can add on select(-group)
to remove them later.
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