Skip to content

Instantly share code, notes, and snippets.

@chenpanliao
Created October 9, 2015 07:10
Show Gist options
  • Save chenpanliao/98b9d1ddb9ae46122f3e to your computer and use it in GitHub Desktop.
Save chenpanliao/98b9d1ddb9ae46122f3e to your computer and use it in GitHub Desktop.
R long table wide table convertion
#### long data to wide data
long.data <- read.csv(textConnection("ID,Month,Sale
1,1,100
1,2,123
1,3,456
1,4,45
1,5,486
2,1,200
2,2,131
2,3,423
2,4,486
2,5,1
3,1,300
3,2,123
3,3,456
3,4,864
3,5,486
4,1,300
4,2,123
4,3,45
4,4,48
4,5,90
5,1,300
5,2,5563
5,3,1
5,4,53
5,5,15"))
# optional
long.data$Month <- factor(long.data$Month, labels=c("M1", "M2", "M3", "M4", "M5"))
## using reshape2::dcast()
library(reshape2)
dcast(long.data, ID ~ Month, value.var = "Sale")
## using tidyr::spread()
library(tidyr)
spread(long.data, Month, Sale
#### wide data to long data
wide.data <- read.csv(textConnection("ID,Month1,Month2,Month3,Month4,Month5
1,100,123,456,45,486
2,200,131,423,486,1
3,300,123,456,864,486
4,300,123,45,48,90
5,300,5563,1,53,15"))
## using reshape2::melt()
melt(wide.data, id.vars = c("ID"))
## using tidyr::gather()
gather(wide.data, Month, Sale, Month1:Month5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment