Home > Mobile >  Transpose columns to rows in R dataframe
Transpose columns to rows in R dataframe

Time:04-29

Transforming dataframes in R keeps challenging for me. How can I change my dataframe from:

df <- data.frame(level1 = c("A", "B","C"), cheese1.kg = c("58","63","33"), cheese2.kg = c("11","22","20"), column.other = c("yes","yes","yes"))

To:

desired.output <- data.frame(level1 = c("A","A","B","B","C","C"), 
                             product = c("cheese1","cheese2","cheese1","cheese2","cheese1","cheese2"), 
                             kg = c("58","11","63","22","33","20"), 
                             column.other= c("yes","yes","yes","yes","yes","yes"))

?

CodePudding user response:

We may use pivot_longer

library(tidyr)
pivot_longer(df, cols = starts_with('cheese'), 
   names_to = c("product", ".value"), names_sep = "\\.", 
     values_transform = list(kg = as.integer))

-output

# A tibble: 6 × 4
  level1 column.other product    kg
  <chr>  <chr>        <chr>   <int>
1 A      yes          cheese1    58
2 A      yes          cheese2    11
3 B      yes          cheese1    63
4 B      yes          cheese2    22
5 C      yes          cheese1    33
6 C      yes          cheese2    20
  • Related