creating one column from severla column names

I have a dtaframe where it has several numbers for years as columns . I want to create a column with year numbers
Data

structure(list(Cause = c("Ischaemic Heart Disease", "Pneumonia", 
"Spontenuos ICH", "Cirrhosis of the liver", "Malignancy", "Sepsis", 
"Others", "Hanging", "Poisoning", "Drowning", "Others", "Motor vehicle -RTA", 
"Drowning", "Food Aspiration", "Fallen from height", "Electrocution", 
"Others", "Sharp weapon injuries", "Blunt weapon injuries", "Fire arm injuries", 
"Strangulation", "Others", "Drowning", "Others"), `2017` = c(203, 
58, 22, 27, 15, 35, 40, 51, 29, 11, 1, 49, 11, 1, 4, 2, 10, 2, 
5, 1, 1, 1, 1, 8), `2018` = c(206, 33, 21, 27, 9, 53, 30, 38, 
20, 15, 4, 47, 14, 2, 3, 6, 6, 7, 2, 2, 0, 1, 0, 1), `2020` = c(219, 
27, 23, 23, 25, 47, 59, 28, 24, 4, 5, 37, 24, 0, 11, 7, 12, 4, 
4, 1, 0, 2, 0, 2)), row.names = c(NA, -24L), class = c("tbl_df", 
"tbl", "data.frame"))

I want a column name called year

You could use pivot_longer().

library(tidyverse)
data %>% 
  pivot_longer(-Cause, names_to = "year", values_to = "value")

# A tibble: 72 x 3
   Cause                   year  value
   <chr>                   <chr> <dbl>
 1 Ischaemic Heart Disease 2017    203
 2 Ischaemic Heart Disease 2018    206
 3 Ischaemic Heart Disease 2020    219
 4 Pneumonia               2017     58
 5 Pneumonia               2018     33
 6 Pneumonia               2020     27
 7 Spontenuos ICH          2017     22
 8 Spontenuos ICH          2018     21
 9 Spontenuos ICH          2020     23
10 Cirrhosis of the liver  2017     27
# ... with 62 more rows

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.