0

I used the pivot_wider function to transpose a dataframe from:

metric    shop1     shop2    shop3    shop4
sales     10        12       14       16
county    orange    sperling wood     riverside

Using this code:

df_new <- pivot_wider(df, 
                      cols = c("shop1", "shop2", 
                      "shop3", "shop4"),
                      cols = shop)

I got the following:

measure  name      value
sales    shop1     10
sales    shop2     12
sales    shop3     14
sales    shop4     16
county   shop1     orange
county   shop2     sperling 
county   shop3     wood
county   shop4     riverside

I was hoping to have separate columns for sales, county, and shop. How do I do that?

  • Congratulations on your first post! It's generally helpful if you can include a line that allows any potential answerers to create your dataframe, as well as include a code snippet of your desired end result. – Serenthia Jul 21 '21 at 14:54
  • Does this answer your question? [Reshaping data.frame from wide to long format](https://stackoverflow.com/questions/2185252/reshaping-data-frame-from-wide-to-long-format) – Serenthia Jul 21 '21 at 14:57
  • 1
    Why are you setting cols twice? – camille Jul 21 '21 at 20:19

2 Answers2

0

You can transpose the dataframe instead of pivot_wider.

library(dplyr)
library(tibble)

df %>%
  column_to_rownames('metric') %>%
  t %>%
  as.data.frame() %>%
  type.convert(as.is = TRUE) %>%
  rownames_to_column('shop') -> res

res

#   shop sales    county
#1 shop1    10    orange
#2 shop2    12  sperling
#3 shop3    14      wood
#4 shop4    16 riverside

data

df <- structure(list(metric = c("sales", "county"), shop1 = c("10", 
"orange"), shop2 = c("12", "sperling"), shop3 = c("14", "wood"
), shop4 = c("16", "riverside")), class = "data.frame", row.names = c(NA, -2L))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

From your current dataset, you should consider doing:

data.table::transpose(df, make.names = TRUE,keep.names = 'shop')

   shop sales    county
1 shop1    10    orange
2 shop2    12  sperling
3 shop3    14      wood
4 shop4    16 riverside
Onyambu
  • 67,392
  • 3
  • 24
  • 53