firmo23
firmo23

Reputation: 8454

Convert dataframe column names to cell values of a new variable

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.

Upvotes: 1

Views: 109

Answers (1)

akrun
akrun

Reputation: 887951

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

Upvotes: 1

Related Questions