Home > Software engineering >  Convert dataframe column names to cell values of a new variable
Convert dataframe column names to cell values of a new variable

Time:04-06

I have the dataframe below

d<-structure(list(WaterYear = c(2014, 2015), Discharge = c(1783.939638, 
1970.891674), EnvWater = c(6, 1)), row.names = c(NA, -2L), class = c("tbl_df", 
"tbl", "data.frame"))

and I want to convert it in a way that will have 3 columns. The WaterYear as it is, the Category which will include Discharge and EnvWater and the Value with thei relative values. Normally I want to apply it to more than 2 columns.

CodePudding user response:

We can reshape to 'long' with pivot_longer to create the required data

library(tidyr)
pivot_longer(d, cols = -WaterYear, names_to = 'Category', values_to = 'Value')
  •  Tags:  
  • r
  • Related