1

I have a column with values as follows and I want to take 1 random value between "+or_"20% of the same value of each row and assign it to another column.

sample_data

    benchmark
1   100
2   200   
3   250
4   400
5   150
6   1000

Now I want to create a variable called value in the same data by adding 1 random number between +or- 20% of the benchmark value for each row.

Expected output:

    benchmark   value
 1  100         87 
 2  200         213
 3  250         255
 4  400         320
 5  150         180
 6  1000        900  

The snippet below illustrates my attempt to achieve that; it works as expected, but takes too much time to get executed:

for (i in 1:nrow(sample_data)){
    sample_data$value[i] = sample_data$benchmark[i] + runif(1,min = -0.2*sample_data$benchmark[i], max = 0.2*sample_data$benchmark[i])
}

How can I improve upon the performance of my code?

2 Answers 2

5

How about:

sample_data$value <- runif(length(sample_data$benchmark), 
                            min = 0.8 * sample_data$benchmark, 
                            max = 1.2 * sample_data$benchmark)
Sign up to request clarification or add additional context in comments.

2 Comments

please try to understand the question.... the code u suggested me will generate n row of samples.... which is of no use... any how thanks
The code will generate 1 random value between 80% and 120% of the benchmark value in the same row. I believe it gives exactly what you have asked for.
1
library(dplyr)
sample_data %>% mutate(value = benckmark + (benckmark * runif(1, -0.20, 0.20)))

Tested on

sample_data <- tribble(~Benckmark, 100, 200, 250)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.