1

I previously posted a question about how to randomly remove 20 consecutive values from a dataframe. I received an answer as follows:

df[-c(seq(sample(nrow(df) - 19, 1), length.out = 20)), ]

What I would now like to do however is to replace the randomly selected 20 consecutive values with NA, whilst retaining the same order of values in the dataframe.

Many thanks in advance.

Drew
  • 131
  • 8
  • 1
    Please, provide a reproducible example and a link to the other post. It's difficult to help you out with such few information. – Francesco Grossetti Apr 01 '20 at 12:27
  • Does this answer your question? [Replace all 0 values to NA](https://stackoverflow.com/questions/11036989/replace-all-0-values-to-na) – caldwellst Apr 01 '20 at 12:28

1 Answers1

1

Given values in v, you can do it like below (similar to yours)

v[seq(sample(length(v)-19,1),length.out = 20)]<- NA

or

v <- replace(v,seq(sample(length(v)-19,1),length.out = 20),NA)
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
  • Hi Thomas would you know how to code a function to repeat this 100 times, to produce a dataframe. I was using the following code: sapply(1:100, function(i){v[seq(sample(length(v)-19,1),length.out = 20)]<- NA}) ; however using this code I get a dataframe full of NAs – Drew Apr 01 '20 at 14:31
  • 1
    @Drew you can try `df <- data.frame(t(replicate(100, replace(v,seq(sample(length(v)-19,1),length.out = 20),NA)))) ` – ThomasIsCoding Apr 01 '20 at 14:53