Transpose in dplyr

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 this in dplyr without using t ()? I tried

 df %>% tidyr::spread(HEADER , price) 

but it does not give a flat structure, but instead does it:

 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 file should look 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")) 
+5
source share
1 answer

I think you want tidyr , not 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 groups - and you can add to select(-group) to remove them later.

+12
source

Source: https://habr.com/ru/post/1237115/


All Articles