Home > Back-end >  How to multiply a value by a random range of values in R
How to multiply a value by a random range of values in R

Time:04-10

Suppose i have some values, there it dat$x1=c(23L, 45L). How to multiply each of these values by randomly on any value that is in the range from -2 to 2? For example 23*1,5 or 23*-0,2 and so on. What easy way to do it? Thanks.

CodePudding user response:

We can use

s1 <- sample(seq(-2, 2, by = 0.1), nrow(dat), replace = FALSE)
dat$x1 * s1

CodePudding user response:

We can also use

dat$x1 * runif(nrow(dat), -2, 2)
  •  Tags:  
  • r
  • Related