6

The similar questions on this topic all used spread() and gather() which are retired Tidyverse functions. Let's say I have a tibble as such:

people   1      2     3.    4     5
person1 27000 30000 40000 50000 60000
person2 27000 30000 40000 50000 60000
person3 27000 30000 40000 50000 60000
person4 27000 30000 40000 50000 60000

And I want to transpose this as such

People Person1 Person2 Person3 Person4 Person5
1.      270000  270000  270000. 270000. 270000
2.      30000.  30000. 30000  30000. 30000
3
4
5.     60000.   60000.  60000 60000 60000

(Didn't fill the third and fourth columns just to save myself time, but they should have been filled.

Steveman30290
  • 511
  • 7
  • 17

1 Answers1

8

It is easier with data.table::transpose

library(data.table)
data.table::transpose(setDT(df1), make.names = 'people')[, People := .I][]

or with tidyverse, the transpose can be done in two steps, 1), reshape to long format with pivot_longer, 2) reshape back to wide with a different column with pivot_wider

library(dplyr)
library(tidyr)
df1 %>%
   pivot_longer(cols = -people, names_to = 'People') %>% 
   pivot_wider(names_from = people, values_from = value)
# A tibble: 5 x 5
#  People person1 person2 person3 person4
#  <chr>    <int>   <int>   <int>   <int>
#1 1        27000   27000   27000   27000
#2 2        30000   30000   30000   30000
#3 3        40000   40000   40000   40000
#4 4        50000   50000   50000   50000
#5 5        60000   60000   60000   60000

data

df1 <- structure(list(people = c("person1", "person2", "person3", "person4"
), `1` = c(27000L, 27000L, 27000L, 27000L), `2` = c(30000L, 30000L, 
30000L, 30000L), `3` = c(40000L, 40000L, 40000L, 40000L), `4` = c(50000L, 
50000L, 50000L, 50000L), `5` = c(60000L, 60000L, 60000L, 60000L
)), class = "data.frame", row.names = c(NA, -4L))
akrun
  • 874,273
  • 37
  • 540
  • 662