Home > Software design >  Pivoting with no pivot column
Pivoting with no pivot column

Time:04-17

I have a dataframe like so:

avg_cost avg_assets avg_liabilities avg_income
100432   203998      76020          89021

I want to transpose the dataframe like so in R

type              stat
avg_cost          100432
avg_assets        203998
avg_liabilities   76020
avg_income        89021

I've tried using pivot_longer but I don't have a column to pivot on. I just want to transpose the whole dataframe. How can I do this?

CodePudding user response:

If it is a single row dataset, use data.frame

data.frame(type = names(df1), stat = unlist(df1, use.names = FALSE))
             type   stat
1        avg_cost 100432
2      avg_assets 203998
3 avg_liabilities  76020
4      avg_income  89021

CodePudding user response:

If only one Row the the following are sufficient. If not use pivot/reshape/melt

in Base R:

setNames(rev(stack(df1)), c('stat', 'type'))
             stat   type
1        avg_cost 100432
2      avg_assets 203998
3 avg_liabilities  76020
4      avg_income  89021

in tidyverse:

enframe(unlist(df1), 'stat', 'type')
# A tibble: 4 x 2
  stat              type
  <chr>            <int>
1 avg_cost        100432
2 avg_assets      203998
3 avg_liabilities  76020
4 avg_income       89021

in datatable:

data.table::transpose(df1, keep.names = 'stat')
             stat     V1
1        avg_cost 100432
2      avg_assets 203998
3 avg_liabilities  76020
4      avg_income  89021

CodePudding user response:

data.frame(type = t(df1))

#                 type
# avg_cost        100432
# avg_assets      203998
# avg_liabilities  76020
# avg_income       89021

or if you have multiple rows:

df1.pivot <- as.data.frame(t(df1))

names(df1.pivot) <- c("type", ...)

Data:

df1 <- structure(list(avg_cost = 100432, avg_assets = 203998, avg_liabilities = 76020, 
                        avg_income = 89021), 
                 row.names = c(NA, -1L), class = "data.frame")

CodePudding user response:

Something like this I suppose? You'll want to use purrr::tranpose for this kind of situation.

library(tidyverse)

df1 <- tribble(~avg_cost, ~avg_assets, ~avg_liabilities, ~avg_income,
        100432,   203998,     76020,         89021)

df2 <- tibble(stat = df1 %>%  purrr::transpose()) %>%
  unnest(c(stat)) %>%
  mutate(type = names(stat), .before = 1) %>%
  unnest(c(stat)); df2
#> # A tibble: 4 × 2
#>   type              stat
#>   <chr>            <dbl>
#> 1 avg_cost        100432
#> 2 avg_assets      203998
#> 3 avg_liabilities  76020
#> 4 avg_income       89021

Created on 2022-04-15 by the reprex package (v2.0.1)

  • Related