Reputation: 1867
I have a dataset with multiple columns:
Value1 Value3 Annotation Value4 Value2
1 4 s 9 4
2 5 t 0 4
3 6 q 4 4
The order of the values and the position of Annotation
is unknown.
Now I'm trying to append multiple columns and try to keep the Annotation
correct. The result should be a 2 column matrix
eg. when I try to append Value1
and Value3
:
Annotation Valuelist
s 1
t 2
q 3
s 4
t 5
q 6
I found the method append()
but I can't figure out how to make sure the annotation is correct.
Upvotes: 0
Views: 3032
Reputation: 193527
The stack
function might come in handy for what you want to do in base R:
cbind(mydf["Annotation"], stack(mydf[c("Value1", "Value3")])["values"])
# Annotation values
# 1 s 1
# 2 t 2
# 3 q 3
# 4 s 4
# 5 t 5
# 6 q 6
stack
normally creates two columns, "values" and "ind" (in that order), so we select just the first to match what you describe.
A similar approach can be taken with melt
from "reshape2":
library(reshape2)
melt(mydf, id.vars="Annotation",
measure.vars=c("Value1", "Value3"))[c("Annotation", "value")]
# Annotation value
# 1 s 1
# 2 t 2
# 3 q 3
# 4 s 4
# 5 t 5
# 6 q 6
Upvotes: 2
Reputation: 44330
You could construct this with something like:
columns <- c("Value1", "Value3")
data.frame(Annotation=rep(dat$Annotation, length(columns)),
Valuelist=as.vector(as.matrix(dat[columns])))
# Annotation Valuelist
# 1 s 1
# 2 t 2
# 3 q 3
# 4 s 4
# 5 t 5
# 6 q 6
Upvotes: 1