Fix column name and row name

Dear all,

I would like to transpose my data like the picture below.
I used this code
tdf <- data.frame(t(df)
My problem is that I can not fix the column name and row name.
I would like to ask for help. Thank you so much.

df<-data.frame(wgi = as.factor(c("voice","stability", "government","regulatory","rule")),
X2016 = c(-1.37, 0.23, 0.02, -0.45, 0.08),
X2017 = c(-1.4, 0.29, 0.01, -0.4, 0.07),
X2018 = c(-1.44, 0.11, 0, -0.35, 0),
X2019 = c(-1.38, 0.13, 0.04, -0.26, -0.02))

Code:

library(tidyverse)

df %>% 
  pivot_longer(-wgi, names_to = "names", values_to = "values") %>% 
  mutate(names = parse_number(names)) %>% 
  pivot_wider(names_from = wgi, values_from = values) %>% 
  rename(wgi = names)

Which is:

# A tibble: 4 x 6
    wgi voice stability government regulatory  rule
  <dbl> <dbl>     <dbl>      <dbl>      <dbl> <dbl>
1  2016 -1.37     0.23        0.02      -0.45  0.08
2  2017 -1.4      0.290       0.01      -0.4   0.07
3  2018 -1.44     0.11        0         -0.35  0   
4  2019 -1.38     0.13        0.04      -0.26 -0.02
1 Like

Thank you so much for you quick reply.
Best regards,

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.