I have some data in a data frame in the following form:
A B C V1 V2 V3
1 1 1 x y z
1 1 2 a b c
...
Where A,B,C are factors, and the combination A,B,C is unique for each row.
I need to convert some of the columns into factors, to achieve a form like:
A B C V val
1 1 1 V1 x
1 1 1 V2 y
1 1 1 V3 z
1 1 2 V1 a
1 1 2 V2 b
1 1 2 V2 c
...
This seems to relate to both stack and the inverse of xtabs, but I don't see how to specify that only certain columns should be "stacked".
And before @AnandaMahto gets here and offers his base
reshape
solution, here's my attempt:Using
reshape2
packagestack
You are right that
stack
is a possibility, but you perhaps missed a key line in the documentation forstack
:So, how do we proceed?
Here's your data:
Here, we convert the factors to
as.character
:Here's how we specify which columns to
stack
:But, we still need to "expand" your rows for columns 1-3. See here for how to do that.
With this information, we can use
cbind
to get the desired result.xtabs
You are also right that
xtabs
seems like it could be a likely possibility, butxtabs
actually expects the opposite of what you've provided. That is to say, when you specify a formula, it expects the items on the left hand side to be numbers, and the items on the right hand side to be factors. Thus, is your data were swapped, you could certainly usextabs
.Here's a demonstration (which only works because you are using a simple example where we can easily
match
"letters" to "numbers").In other words, your choice of tools could potentially be right, but your data needs to also be in the form that the tools expect.
But, I'm not sure why you'd want to do all the work I've shown when better solutions exist with
reshape
and friends ;)Very late update...
You can also look at
merged.stack
from my "splitstackshape" package:Or
gather
from "tidyr":