library(reshape2)
id<-c(1,2,3,4)
time<-c(1,2,1,2)
x1<-c(5,3,6,2)
x2<-c(2,4,6,8)
data.frame(id,time,x1,x2)
## id time x1 x2
## 1 1 1 5 2
## 2 2 2 3 4
## 3 3 1 6 6
## 4 4 2 2 8
data<-data.frame(id,time,x1,x2)
reshape2 package
melt function
melt(data,id.vars = c("id"))
## id variable value
## 1 1 time 1
## 2 2 time 2
## 3 3 time 1
## 4 4 time 2
## 5 1 x1 5
## 6 2 x1 3
## 7 3 x1 6
## 8 4 x1 2
## 9 1 x2 2
## 10 2 x2 4
## 11 3 x2 6
## 12 4 x2 8
melt(data,id.vars = c("id","time"),variable.name = "x1&x2")
## id time x1&x2 value
## 1 1 1 x1 5
## 2 2 2 x1 3
## 3 3 1 x1 6
## 4 4 2 x1 2
## 5 1 1 x2 2
## 6 2 2 x2 4
## 7 3 1 x2 6
## 8 4 2 x2 8
dcast function
z <- data.frame(
item=letters[rep(24:26,2)],
freq=c(4,3,2,4,4,1),
id=rep(1:2,each=3)
)
z
## item freq id
## 1 x 4 1
## 2 y 3 1
## 3 z 2 1
## 4 x 4 2
## 5 y 4 2
## 6 z 1 2
dcast(z, id ~ item, value.var="freq")
## id x y z
## 1 1 4 3 2
## 2 2 4 4 1
acast(z, id ~ item, value.var="freq")
## x y z
## 1 4 3 2
## 2 4 4 1
tidyr package
library(tidyr)
##
## Attaching package: 'tidyr'
## The following object is masked from 'package:reshape2':
##
## smiths
data%>%
gather("new column",count,x1:x2)
## id time new column count
## 1 1 1 x1 5
## 2 2 2 x1 3
## 3 3 1 x1 6
## 4 4 2 x1 2
## 5 1 1 x2 2
## 6 2 2 x2 4
## 7 3 1 x2 6
## 8 4 2 x2 8