Question

I am have a dataframe called data like this:

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

I want to insert rows with increasing No. as shown below:

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

I tried this z <- data[rep(seq(nrow(data)), data[,2]), ] but this is simply coping it. How I can I insert rows with increment to a dataframe?

Thanks

Was it helpful?

Solution

Just add one more step to increment the "No." column:

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top