This tutorial explains how to convert data from wide to long format with R programming.
Note : Before running the code below, Install reshape2 package if not installed already.
R Code
The following program would create a sample data for demonstration.
Explanation :
Note : If you do not want to remove NA values, make na.rm = TRUE to na.rm = FALSE.
Tutorial : Convert data from long to wide format
R Code : Convert Data from Wide to Long |
R Code
The following program would create a sample data for demonstration.
df = read.table(text= "ID Product1 Product2 Product3 Product4The following code would turn our data from wide to long format.
1 1 NA 1 1
2 1 1 NA 1
3 1 1 NA NA
4 1 1 1 1", header=TRUE)
library(reshape2)
x = colnames(df[,-1])
t2 <- melt(df,id.vars = "ID",measure.vars = x , variable.name="Product", value.name="value",na.rm = TRUE)
t2 = t2[order(t2$ID),]
Explanation :
- id.vars - additional variables to keep in the output.
- measure.vars - variables to be reshaped
- variable.name - name of variable used to store measured variable names
- value.name - name of variable used to store values
Note : If you do not want to remove NA values, make na.rm = TRUE to na.rm = FALSE.
Tutorial : Convert data from long to wide format
I would use tidyr for a nice clean data conversion
ReplyDelete#sample data
ReplyDeletehousehold <- data.frame(county = c("Nairobi",
"Kiambu",
"Laikipia",
"Murang'a"),
subCounty = c("Dagoretti",
"Lari",
"L.North",
"Kigumo"),
Name_p1 = c("Tiana",
"Joseph",
"Ochweri",
"Maina"),
Age_p1 = c(25, 16, 15, 45),
Name_p2 = c(NA,
"Mary",
NA,
"Susan"),
Age_p2 = c(NA, 34, NA, 16))
##How would you convert this to long format?