0

I've got the following data frame:

country v1 v2 v3 v4
Ethiopia 35 2 1 1
Lithuania 41 1 1 1
Fiji 50 2 1 3
Haiti 33 1 2 3
France 40 1 1 2
UAE 41 2 1 1
Sint Maarten 44 1 1 1
Denmark 39 2 1 3
UK 52 1 2 3
US 39 1 1 2

I would like to pivot it to the following format:

variables Ethiopia Lithuania Fiji Haiti France UAE Sint Maarten Denmark UK US
v1 35 41 50 33 40 41 44 39 52 39
v2 2 1 2 1 1 2 1 2 1 1
v3 1 1 1 2 1 1 1 1 2 1
v4 1 1 3 3 2 1 1 3 3 2

I came up with the following solution that works but seems overly complicated:

new_df <- df %>%
  pivot_longer(cols = -country,
               names_to = "type",
               values_to = "value") %>%
  pivot_wider(id_cols = type,
              names_from = country,
              values_from = value)

QUESTION: Is there a more elegant way to accomplish this?

MWE:

set.seed(2)

df <- data.frame(country = c("Ethiopia", 
                             "Lithuania", 
                             "Fiji", 
                             "Haiti", 
                             "France", 
                             "UAE", 
                             "Sint Maarten", 
                             "Denmark", 
                             "UK", 
                             "US"),   
                 v1 = round(rnorm(10, 40, 6),0),
                 v2 = sample(c(1:2),5,replace = T),
                 v3 = sample(c(1:2),5,replace = T),
                 v4 = sample(c(1:3),5,replace = T))
jono3030
  • 412
  • 5
  • 14
  • Nothing's really changed since the duplicate. `tidyr` doesn't have a single function for transposing a tibble. But `data.table` does: `data.table::transpose(df, keep.names="variables", make.names="country")` – MrFlick Mar 06 '22 at 00:59
  • Thank you for your comment @MrFlick and for marking the question as a duplicate! I should have been more precise with my phrasing as I realize now that my question implies a solution with `tidyr` when I was actually looking for any alternative way of doing this in one line regardless of the technique/package used. I missed the question that is linked above when I was looking for a solution and before posting here, but your `data.table` solution is exactly what I was looking for! – jono3030 Mar 06 '22 at 03:56

0 Answers0