Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

In R the t() function is really meant for matrices. When I try to transpose my tibble with t() I end up with a matrix. A matrix can't be made into a tibble with tibble(). I end up spending time storing column names as variables and attaching them as I try to re-make a transposed version of my tibble.

Question: What is the simplest way to transpose a tibble where the first column should become the column names of the new tibble and the old column names become the first column of my new tibble.

like image 598
Alex Avatar asked Mar 14 '17 15:03

Alex


People also ask

How do I transpose a function in R?

Rotating or transposing R objects You can rotate the data. frame so that the rows become the columns and the columns become the rows. That is, you transpose the rows and columns. You simply use the t() command.

How do I transpose data frame 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.

What is the difference between a Tibble and a Dataframe in R?

Tibbles vs data frames There are two main differences in the usage of a data frame vs a tibble: printing, and subsetting. Tibbles have a refined print method that shows only the first 10 rows, and all the columns that fit on screen. This makes it much easier to work with large data.

How do I flip a column into a row in R?

Thus, to convert columns of an R data frame into rows we can use transpose function t. For example, if we have a data frame df with five columns and five rows then we can convert the columns of the df into rows by using as. data. frame(t(df)).


2 Answers

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

as_tibble(cbind(nms = names(df), t(df))) 
like image 167
Laurent Avatar answered Jan 21 '23 01:01

Laurent


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') 
like image 21
Rahul Avatar answered Jan 20 '23 23:01

Rahul