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))