Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transposing in dplyr

Tags:

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")) 
like image 533
geodex Avatar asked Nov 30 '15 17:11

geodex


People also ask

What is transposing in R?

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.

How do I transpose rows to columns in R?

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.


1 Answers

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.

like image 152
jeremycg Avatar answered Sep 24 '22 08:09

jeremycg