Home > other >  Transposing Dataframes in R
Transposing Dataframes in R

Time:07-06

I'm attempting to Transpose a data frame in a R Shiny App using Tidyr/Dplyr techniques and can't seem to get a result that is desired. For example, I have the below table

Original Table

I'd like to transpose it to the following data frame.

Desired Table

library(stringr)
library(tidyr)
library(dplyr)

dates <- c('2022-06-01','2022-06-02','2022-06-03','2022-06-04','2022-06-05')
price <- c(11,18,15,10,15)
Quantity <- c(20,19,14,19,17)
Tax <- c(2,4,4,1,5)

df <- data.frame(dates,price,Quantity, Tax)

df <-  df %>% 
  mutate(dates = str_replace(str_sub(dates, start= -5), "-", "/")) %>%  
  pivot_wider(names_from= dates, values_from= c(price, Quantity, Tax))

df

CodePudding user response:

This is just transposing the data. In base R:

setNames(data.frame(t(df[-1])), df$dates)

         2022-06-01 2022-06-02 2022-06-03 2022-06-04 2022-06-05
price            11         18         15         10         15
Quantity         20         19         14         19         17
Tax               2          4          4          1          5

Using data.table:

 data.table::transpose(df, make.names = 'dates', keep.names = 'rn')

        rn 2022-06-01 2022-06-02 2022-06-03 2022-06-04 2022-06-05
1    price         11         18         15         10         15
2 Quantity         20         19         14         19         17
3      Tax          2          4          4          1          5

CodePudding user response:

The other method using dplyr and tidyr:

require(dplyr)
require(tidyr)
require(tibble)

df %>%
  pivot_longer(, cols = -dates) %>%
  pivot_wider(, names_from = dates) %>%
  rename("dates" = 1) %>%
  as.data.frame()
     dates 2022-06-01 2022-06-02 2022-06-03 2022-06-04 2022-06-05
1    price         11         18         15         10         15
2 Quantity         20         19         14         19         17
3      Tax          2          4          4          1          5

CodePudding user response:

We can use rotate_df from sjmisc:

library(sjmisc)

df %>% 
  rotate_df(cn = TRUE)

Output

         2022-06-01 2022-06-02 2022-06-03 2022-06-04 2022-06-05
price            11         18         15         10         15
Quantity         20         19         14         19         17
Tax               2          4          4          1          5
  • Related