var1 var2 var3
1 2 3
1 2 3
1 2 3
I want to stack var2 and var3 underneath var1 to get:
var1
1
1
1
2
2
2
3
3
3
I tried:
data$var <- append(data$var1,data$var2)
Then I get an error that my replacement has more rows. How do I solve this?
You may want to try
unlist
:Stack seems like the obvious answer here, but
melt
in the reshape package does works in an equivalent fashion and MAY offer some flexibility for other more complicated situations. Assuming you are working with an object named dat:If you need to preserve one of the columns as an ID variable:
I'm guessing you're getting this error because each column/variable in a dataframe needs to be the same length. You could make a new longer variable and join it with the old dataframe but it is going to repeat the data in the other variables.
Your output has a different number of rows to your input, so trying to turn the latter into the former is going to cause problems. Just make a new data frame:
You can also get fancy with
do.call
, taking advantage of the fact that a data frame is a list under the hood: