We wish to transpose a data frame so (1) its columns become its rows (2) the column names are converted to a column and (3) the values of a particular column are used as the new column names.
df_2 = df %>%
pivot_longer(!a, names_to = "A", values_to = "val") %>%
pivot_wider(names_from = "a", values_from = "val")
Here is how this works:
pivot_longer()
function from tidyr
package to convert the data frame from wide to
long format, creating a new data frame with three columns: "a", "A", and "val".!a
argument means to pivot all columns except for the column named "a". The names_to
argument specifies the name of the column that will contain the old column names (in this case, "
A"), and the values_to
argument specifies the name of the column that will contain the old
values (in this case, "val").
See Pivot Longer.pivot_wider()
function to convert the data frame back from long to
wide format, but this time with "a" as the column names and "val" as the values. The names_from
argument specifies the column to use for the new column names, and the values_from
argument
specifies the column to use for the new values.df_2
is the transposed version of df_1
. i.e. The first column in df_1
is the column names in df_2
, and the columns names in df_1
are now the values if the first
column indf_2
.Alternative: via Matrix Transpose
df_2 = df %>%
select(b, c, d) %>%
t() %>%
as_tibble(.name_repair = ~df %>% pull(a),
rownames = "A")
Here is how this works:
select()
function from dplyr
to select the columns named "b", "c", and "d" from the
data frame df
.t()
function to transpose the selected columns. This turns the columns into rows and
the rows into columns.t()
function into a tibble using as_tibble()
. We pass the
values of column "a" as the name_repair
argument. We use the pull()
function from dplyr
to
get the values of the "a" column from the original data frame.rownames
argument specifies the name of the column that contains the original row names,
which in this case is "A".Extension: Data Frame has Row Names
In some cases, the data frame rows have names, and we wish to transpose row names into columns and columns into row names
df_2 = df %>%
t() %>%
as_tibble(rownames = 'A')
Here is how this works:
t()
function to transpose the selected columns. This turns the columns into rows and
the rows into columns.t()
to a data frame using as_tibble()
function, and we set the
rownames
argument to "A".