How to transpose a dataframe in tidyverse?

扶醉桌前 提交于 2020-02-17 06:50:41

问题


Using basic R, I can transpose a dataframe, say mtcars, which has all columns of the same class:

as.data.frame(t(mtcars))

Or with pipes:

library(magrittr)
mtcars %>% t %>% as.data.frame

How to accomplish the same within tidyr or tidyverse packages?

My attempt below gives:

Error: Duplicate identifiers for rows

library(tidyverse)
mtcars %>% gather(var, value, everything()) %>% spread(var, value)

回答1:


Try with add_rownames

add_rownames(mtcars) %>% 
         gather(var, value, -rowname) %>% 
         spread(rowname, value) 

In the newer version, rownames_to_column replaces add_rownames

mtcars %>%
   rownames_to_column %>% 
   gather(var, value, -rowname) %>% 
   spread(rowname, value) 


来源:https://stackoverflow.com/questions/40306280/how-to-transpose-a-dataframe-in-tidyverse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!