Create a new variable based on two other variables.

I have a data set with three variables; country, year and UHCindex.
It has only two years 2017 and 2015.
Each country has its UHCindex for 2017 and 2015 hence observations for each country are two.

I would like to transform it so that there is are two new variables UHCindex2015 and UHCindex2017 so that we have one observation per country.

Help will be appretiated.

I have tried mutate function in vain.

Here is a solution using pivot_wider() from the tidyr package.

DF <- data.frame(Country = c("A", "A", "B", "B", "C", "C"),
                  Year = rep(c(2015, 2017), 3),
                  UHCindex = c(10, 9, 12, 14, 8, 18))
DF
  Country Year UHCindex
1       A 2015       10
2       A 2017        9
3       B 2015       12
4       B 2017       14
5       C 2015        8
6       C 2017       18
library(tidyr)
pivot_wider(DF, names_from = Year, values_from = UHCindex, 
             names_prefix = "UHCindex")
# A tibble: 3 x 3
  Country UHCindex2015 UHCindex2017
  <chr>          <dbl>        <dbl>
1 A                 10            9
2 B                 12           14
3 C                  8           18

This worked. Thank you so much

This topic was automatically closed 21 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.