user2472273
user2472273

Reputation: 125

For loop problems in R

I have a 365x1 vector called dv (day value). I am applying a function to generate some hourly values, hv. My codes are as follows:

sigma<-0.246*dv
stime<-function(x,y,z){(exp(-(x-12)^2/(2*y^2))+cos(pi*(x-12)/(z-1)))/(2*y*sqrt(2*pi))}
t<-1:24
hv<-NULL
for (i in seq(along=t)){hv<-c(hv,mapply(stime,t[i],sigma,dv))}

I want to the first 24 values using t[1],t[2],...t[24] with z=dv[1] and the next 24 values to use z=dv[2] etc. But what this code does is to have first 365 values dv[1],dv[2]...dv[365] to take t[1] then the next 365 values to take t[2]...I am not sure if I explain this clearly. I really appreciate your help.

Upvotes: 1

Views: 105

Answers (2)

IRTFM
IRTFM

Reputation: 263301

Maybe:

hv <- stime( x =rep(dv, each= 24), y=rep(1:24, each=365), z=x)

Upvotes: 1

Simon O&#39;Hanlon
Simon O&#39;Hanlon

Reputation: 59970

R is vectorised for exp, cos, sqrt and all arithmetic operators so all you really need to do is loop along your dv values.

Here is an example using your function with sapply, and only the first 3 t values for brevity...

dv <- 1:5
sapply( dv , function(i) stime( x = t[1:3] , y = 0.246*i , z = i ) )

     [,1]       [,2]          [,3]       [,4]          [,5]
[1,]  NaN -0.4054291 -6.621773e-16  0.1013573 -1.146727e-01
[2,]  NaN  0.4054291 -2.702861e-01 -0.1013573  7.689812e-16
[3,]  NaN -0.4054291  1.489523e-16 -0.2027146  1.146727e-01

So there is one value for z (which is the current dv value), one value for y which is 0.246 * current dv value, and the 3 values of t for x. Output is 3 values, one for each t, the sigma and dv values are recycled and reused each time.

The NaNs in the first column are caused by the fact that in this example the first value of t and also dv are 1, which leads to

cos(pi * (1 - 12)/(1 - 1))

Which simplifies to;

cos(-Inf)
NaN

So the result must be NaN in this example (hopefully this is not the case in your real data).

Upvotes: 1

Related Questions