# How to add a noise term in a formula

I am trying to add a noise term in my formula, but I do not know how to make it happen.

For example, I have a function:

``````function_1 <- function(var1, var2, var3) {
output <- (2*var1) + (-1*var2) + (3*var3)
return(output)
}
``````

But, I want to add a noise term in my formula like the following:

``````function_2 <- function(var1, var2, var3) {
output <- (2*var1) + (-1*var2) + (3*var3) + noise
return(output)
}
``````

How could I make "function_2" in R properly? If any of you have any idea? I wanted to use the jitter function, but I am not sure if this may work or not.

``````function_2 <- function(var1, var2, var3) {
output <- jitter((2*var1) + (-1*var2) + (3*var3))
return(output)
}
``````

Please let me know what do you guys think.

This package may be overkill for your purposes, but it's worth checking:

If you're happy with random noise (i.e. random normals) you could use `rnorm()`:

``````function_2 <- function(var1, var2, var3) {
output <- (2*var1) + (-1*var2) + (3*var3) + rnorm(1, mean = 0, sd = 1)
return(output)
}
``````

You could use a different distribution to get random noise from if you wanted to, using the appropriate `r[distribution-shorthand]()` function instead of `rnorm()`, or change the `mean` and `sd` arguments to be something else, or control them with arguments to your function, too.

This is also assuming your `var` values are all length 1 (as opposed to vectors), if you're working with vectors you could add the normals afterwards, using the length of output to add a different amount of noise to each value:

``````function_2 <- function(var1, var2, var3) {
output <- (2 * var1) + (-1 * var2) + (3 * var3)
output + rnorm(length(output), mean = 0, sd = 1)
}
``````

Or add the same amount of noise to each one, using the first example I gave above.

(Note that I didn't use `return()`, by default a function in R will return the last expression it evaluates).

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.