How do I transpose a tibble() in R [duplicate]

限于喜欢 提交于 2019-11-29 04:07:47

As Sotos has mentioned it, you just need to re-declare your matrix as a tible:

as_tibble(cbind(nms = names(df), t(df)))
Rahul

Solution here: https://stackoverflow.com/a/28917212/3880322

library(dplyr)
library(tidyr)
df %>%
    gather(key = var_name, value = value, 2:ncol(df)) %>% 
    spread_(key = names(df)[1],value = 'value')

I was faced with the same problem and tried all the above-mentioned solutions and realized that none of them actually preserve the names of the columns.

Here is, in my opinion, a better way to do the same:

# attaching needed libraries
library(dplyr)
library(data.table)
library(tibble)

# defining the dataframe
df <- cbind.data.frame(x = rnorm(10), y = rnorm(10))

# custom function to transpose while preserving names
transpose_df <- function(df) {
  t_df <- data.table::transpose(df)
  colnames(t_df) <- rownames(df)
  rownames(t_df) <- colnames(df)
  t_df <- t_df %>%
    tibble::rownames_to_column(.data = .) %>%
    tibble::as_tibble(.)
  return(t_df)
}

# using the function
transpose_df(df)
#> # A tibble: 2 x 11
#>   rowname    `1`   `2`     `3`    `4`      `5`   `6`    `7`    `8`    `9`
#>   <chr>    <dbl> <dbl>   <dbl>  <dbl>    <dbl> <dbl>  <dbl>  <dbl>  <dbl>
#> 1 x       -1.38  0.752  1.22    0.296 -0.00298 1.50  -0.719 -0.503 -0.114
#> 2 y        0.618 0.304 -0.0559 -1.27   0.0806  0.156  0.522  0.677  0.532
#> # ... with 1 more variable: `10` <dbl>

Created on 2018-02-17 by the reprex package (v0.2.0).

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