R: How to generate a noisy sine function

Arne picture Arne · Aug 20, 2015 · Viewed 10.3k times · Source

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

Answer

Marc in the box picture Marc in the box · Aug 20, 2015

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