简体   繁体   中英

Transpose columns to rows in R dataframe

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"))

?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM