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.
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.
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.
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.
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)).
As Sotos has mentioned it, you just need to re-declare your matrix as a tibble:
as_tibble(cbind(nms = names(df), t(df)))
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With