R - how to add cases of one variable to other vari

2019-08-08 02:40发布

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?

标签: r stack rbind
5条回答
在下西门庆
2楼-- · 2019-08-08 03:26

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楼-- · 2019-08-08 03:30

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
查看更多
Viruses.
4楼-- · 2019-08-08 03:37

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楼-- · 2019-08-08 03:39
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
查看更多
仙女界的扛把子
6楼-- · 2019-08-08 03:41

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))
查看更多
登录 后发表回答