R: How to generate a noisy sine function
Asked Answered
B

2

9

I am still pretty new to the whole R-thing.

I have the following aim; I have a sine function that describes a calcium particle number over time: something like y = a * sin (b*t) + c

Since in reality the generation and removal of calcium is described in stochastic events, I would like to add a random noise term to my function (preferably scalable in average noise amplitude).

Something like z = y + random*Amplitude

can you help me out?

Best

Blighter answered 20/8, 2015 at 7:23 Comment(0)
H
17

Here's an approach I would use - I provided two options on how your error might be generated (uniform distribution vs Gaussian distribution):

### Equation: y=a*sin(b*t)+c.unif*amp
# variables
n <- 100 # number of data points
t <- seq(0,4*pi,,100)
a <- 3
b <- 2
c.unif <- runif(n)
c.norm <- rnorm(n)
amp <- 2

# generate data and calculate "y"
set.seed(1)
y1 <- a*sin(b*t)+c.unif*amp # uniform error
y2 <- a*sin(b*t)+c.norm*amp # Gaussian/normal error

# plot results
plot(t, y1, t="l", ylim=range(y1,y2)*c(1,1.2))
lines(t, y2, col=2)
legend("top", legend=c("y1", "y2"), col=1:2, lty=1, ncol=2, bty="n")

enter image description here

Howe answered 20/8, 2015 at 7:56 Comment(0)
D
2

y <- jitter(a*sin(b*t) + c) using the jitter() function will add random noise to your function. you can specify the "amount" parameter inside jitter() to control the amplitude.

Deicer answered 20/8, 2015 at 7:29 Comment(4)
Isn't jitter() intended to small noise just for the purpose of visualization (avoiding repeated datapoints to obscure each other)?Socrates
not familiar with jitter but it is not working as shown above in any case giving Error in a * b + c : non-numeric argument to binary operatorKeitt
You don't need the +c part any more, ie just jitter(asin(bt)) - if you remove that @javadba it will work.Testudo
Thx @NickCotterKeitt

© 2022 - 2024 — McMap. All rights reserved.