将长度不等的向量合并到数据帧中并进行堆叠

时间:2018-10-04 00:19:59

标签: r dataframe

我试图将长度不等的向量合并到一个数据帧中,然后将它们堆叠起来,以便可以对其进行ANOVA测试。我的载体是:

Age_0_11 <- c(17.2, 18.4, 17.9, 16.6, 19.0, 18.3, 13.6, 13.5, 18.5, 19.1, 19.1, 13.4)
Age_12_24 <- c(14.8, 17.6, 18.3, 17.2, 10.0, 11.3, 10.2, 17.0, 18.9, 19.2)
Age_25_45 <- c(18.4, 13.0, 14.8, 18.4, 12.8, 17.6, 18.8, 17.9, 18.5, 17.5, 18.3, 15.2, 10.8, 19.8, 17.3, 19.2, 15.4, 13.2)
Age_45plus <- c(15.5, 18.2, 12.7, 15.1, 18.2, 18.0, 14.4, 10.2, 16.7)

我希望他们看起来像:

   Ratio         Age
1   17.2        0-11
2   18.4        0-11
          ...
    19.2       12-24
    18.4       25-45
          ...

我知道我可以将向量合并到一个数据帧中,但是所有多余的值都将填充

1 个答案:

答案 0 :(得分:4)

R的基本选项是将向量存储在list中,然后使用stack

lst <- list(
    Age_0_11 = Age_0_11,
    Age_12_24 = Age_12_24,
    Age_25_45 = Age_25_45,
    Age_45plus = Age_45plus)
setNames(stack(lst), c("Ratio", "Age"))
#   Ratio        Age
#1   17.2   Age_0_11
#2   18.4   Age_0_11
#3   17.9   Age_0_11
#4   16.6   Age_0_11
#5   19.0   Age_0_11
#6   18.3   Age_0_11
#7   13.6   Age_0_11
#8   13.5   Age_0_11
#9   18.5   Age_0_11
#...