Eisen
Eisen

Reputation: 1897

Transforming dataframe to make some columns to rows in dplyr

how can i transform this data frame

Input:

sex     avg_height avg_weight avg_pay
female  61         128        70000
male    69         161        89000

to look like this in dplyr

Expected Output:

            male   female
avg_height  69     61
avg_weight  161    128
avg_pay     89000  70000

Can I use pivot_longer() here?

Upvotes: 0

Views: 81

Answers (1)

akrun
akrun

Reputation: 887901

We may transpose and set the names from 'sex' column in base R

setNames(as.data.frame(t(df1[-1])), df1$sex)
             female  male
avg_height     61    69
avg_weight    128   161
avg_pay     70000 89000

Or may use data.table::transpose

data.table::transpose(df1, make.names = 'sex', keep.names = 'new')

Or with tidyverse

library(dplyr)
library(tidyr)
library(tibble)
df1 %>%
    pivot_longer(cols = -sex) %>%
    pivot_wider(names_from = sex, values_from = value) %>% 
    column_to_rownames('name')
           female  male
avg_height     61    69
avg_weight    128   161
avg_pay     70000 89000

data

df1 <- structure(list(sex = c("female", "male"), avg_height = c(61L, 
69L), avg_weight = c(128L, 161L), avg_pay = c(70000L, 89000L)), 
class = "data.frame", row.names = c(NA, 
-2L))

Upvotes: 1

Related Questions