Reputation: 33
I would like to gather the rows for each pair of comparison. In other words, go from:
x=data.frame(id="Study1",
t1=1,
t2=2,
t3=3,
y2=0.1,
y3=0.2,
se2=0.5,
se3=0.7)
to:
y=data.frame(id=c("Study1", "Study1"),
t1=c(1,1),
t2=c(2,3),
y2=c(0.1,0.2),
se2=c(0.5,0.7))
Upvotes: 0
Views: 48
Reputation: 20085
An option is to use grouped
measure variables of data.table::melt
as:
library(data.table)
melt(setDT(x), id=1:2, measure=list(c("t2","t3"), c("y2","y3"), c("se2","se3")),
value.name=c("t2", "y2", "se2"))
#Or in short form
melt(setDT(x), id=1:2, measure=patterns("^t[2-3]", "^y", "^se"),
value.name=c("t2", "y2", "se2"))
# id t1 variable t2 y2 se2
# 1: Study1 1 1 2 0.1 0.5
# 2: Study1 1 2 3 0.2 0.7
Upvotes: 0
Reputation: 79208
You can use reshape
n=length(grep("y",names(x)))
reshape(x,t(matrix(3:ncol(x),n)),idvar="id",dir="long")
id t1 time t2 y2 se2
Study1.1 Study1 1 1 2 0.1 0.5
Study1.2 Study1 1 2 3 0.2 0.7
or you can use:
library(data.table)
cbind(melt(setDT(x),"id",data.frame(matrix(3:ncol(x),2)),t1=x$t1)
id variable value1 value2 value3 t1
1: Study1 1 2 0.1 0.5 1
2: Study1 2 3 0.2 0.7 1
reshape(x,data.frame(matrix(3:ncol(x),2)),idvar="id",dir="long")
id t1 time t2 y2 se2
1 Study1 1 1 2 0.1 0.5
2 Study1 1 2 3 0.2 0.7
Upvotes: 1