R - how to add cases of one variable to other variable (stack variables)

﹥>﹥吖頭↗ 提交于 2019-12-11 12:59:35

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!