luciano
luciano

Reputation: 13792

Add rows to dataframe based on criteria

I have this dataframe:

percentDf <- data.frame(category=c("a", "a", "b", "c", "c", "d"), 
                        percent=c(50, 50, 100, 30, 70, 100))

percentDf
  category percent
1        a      50
2        a      50
3        b     100
4        c      30
5        c      70
6        d     100

In rows where the value in percent is 100, I need to replicate that row, and add it underneath. This should be the dataframe outputted:

percentDfComplete <- data.frame(category=c("a", "a", "b", "b", "c", "c", "d", "d"), 
                                percent=c(50, 50, 100, 100, 30, 70, 100, 100))

percentDfComplete
  category percent
1        a      50
2        a      50
3        b     100
4        b     100
5        c      30
6        c      70
7        d     100
8        d     100

What is the best way to do this?

Upvotes: 1

Views: 3221

Answers (1)

Arun
Arun

Reputation: 118799

I'd just pick them up first and then rbind them and them order them.

out <- rbind(percentDf, percentDf[percentDf$percent == 100, ])
out[order(out$category), ]

Alternatively, you can first find which rows have percent = 100 and append and sort and index your data.frame.

percentDf[sort(c(seq_len(nrow(percentDf)), which(percentDf$percent == 100))), ]

Note: If you have in your original data.frame two rows with b 100 then you'll get each of the rows duplicated here.

Upvotes: 4

Related Questions