将行插入数据框,增量为r

时间:2014-03-09 04:39:59

标签: r dataframe rep

我有一个名为data的数据框,如下所示:

No. count   gender
23  2   Male
52  4   Female
75  3   Female

我想插入增加No.的行,如下所示:

No. count   gender
23  2   Male
24  2   Male
52  4   Female
53  4   Female
54  4   Female
55  4   Female
56  4   Female
75  3   Female
76  3   Female
77  3   Female

我试过这个z <- data[rep(seq(nrow(data)), data[,2]), ] 但这只是应对它。如何将带增量的行插入数据框?

由于

1 个答案:

答案 0 :(得分:1)

再添加一个步骤来增加“否”柱:

z <- data[rep(seq(nrow(data)), data[,2]), ]
z$No. <- z$No. + sequence(data[, 2]) - 1
z
#     No. count gender
# 1    23     2   Male
# 1.1  24     2   Male
# 2    52     4 Female
# 2.1  53     4 Female
# 2.2  54     4 Female
# 2.3  55     4 Female
# 3    75     3 Female
# 3.1  76     3 Female
# 3.2  77     3 Female