-2

I would like to add observation based on certain criteria.

For example:

SN     Species       Habitat        X_Cor   Y_cor     Total 
1      monkey        grassland      4444    6666      6
2      porcupine     agri_Land      6666    5555      20

I would like to add observation up to 60 times. In above, the first observation is to be repeated 54 times (60-5), with value in "Total" 0. The second observation is to be repeated 40 times (60-20).

Furthermore,

I want to repeate first observation six times (because there is 6 in "Total").

I have 590 such observation. I would like to know how to code it in R.

Blaszard
  • 30,954
  • 51
  • 153
  • 233
  • Your question is rather cryptic, could you show some of what you've done so we can tease out the problem? – Badger Jun 20 '16 at 01:47
  • 1
    Upvoted the answer but downvoted the question because no response after 3 hours. – IRTFM Jun 20 '16 at 05:10

1 Answers1

1

If the criteria is to replicate the rows based on the values in 'Total', use rep to replicate the sequence of rows.

df1[rep(1:nrow(df1), df1$Total),]

or if we need a wrapper

library(splitstackshape)
expandRows(df1, "Total")

The part of the description add observation upto 60 times. In above, the first observation is to be repeated 54 times (60-5) is not clear from the example showed. If we need to replicate based on the description

df1[rep(1:nrow(df1), c(54, 40)),]
akrun
  • 874,273
  • 37
  • 540
  • 662