问题
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?
回答1:
df <- data.frame(var1=1:3,var2=4:6,var3=7:9)
df2 <- stack(df)
print(df2)
values ind
1 1 var1
2 2 var1
3 3 var1
4 4 var2
5 5 var2
6 6 var2
7 7 var3
8 8 var3
9 9 var3
回答2:
You may want to try unlist
:
dtf <- data.frame(a = 1:3, b = 1:3, c = 1:3)
unlist(dtf)
a1 a2 a3 b1 b2 b3 c1 c2 c3
1 2 3 1 2 3 1 2 3
回答3:
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:
df <- data.frame(x = c(df$var1, df$var2, df$var3)
You can also get fancy with do.call
, taking advantage of the fact that a data frame is a list under the hood:
df <- data.frame(x = do.call("c", df))
回答4:
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.
> df <- data.frame(var1=1:3,var2=4:6,var3=7:9)
> df
var1 var2 var3
1 1 4 7
2 2 5 8
3 3 6 9
# join combination of var1/var2 and 'df' dataframe
> data.frame(newvar=c(df$var1,df$var2),df)
newvar var1 var2 var3
1 1 1 4 7
2 2 2 5 8
3 3 3 6 9
4 4 1 4 7
5 5 2 5 8
6 6 3 6 9
回答5:
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:
library(reshape)
melt(dat)
variable value
1 var1 1
2 var1 1
3 var1 1
4 var2 2
5 var2 2
6 var2 2
7 var3 3
8 var3 3
9 var3 3
If you need to preserve one of the columns as an ID variable:
> melt(dat, id.vars = "var1")
var1 variable value
1 1 var2 2
2 1 var2 2
3 1 var2 2
4 1 var3 3
5 1 var3 3
6 1 var3 3
来源:https://stackoverflow.com/questions/5482249/r-how-to-add-cases-of-one-variable-to-other-variable-stack-variables