EZ Study

Actuarial Biology Chemistry Economics Calculators Confucius Engineer
Physics
C.S.

R Coding Tutorial: Coding Tips-2

```
> if ( a & b) {
>     cat("TRUE", "\n")
> } else {
>     cat("FALSE", "\n")
> }
```
else must be on the same line, otherwise: unexpected 'else' error.

Some sample to compute KDJ value, notice the usage of eval() function, otherwise there might be some mistakes.
```Id = which(data3g[,2] == '2014-12-01' )
data3h=transform(data3g,D=K)
Id1 = c(0,Id)
Id1

for(i in 2:length(Id1) ) {
for(j in eval(Id1[i]-1):eval(Id1[eval(i-1)]+1) ) {
data3h[j,4] = data3h[j+1,4]*2/3+data3h[j,3]/3
}
}

for(i in 2:length(Id1) ) {
for(j in eval(Id1[i]-1):eval(Id1[eval(i-1)]+1) ) {
data3h[j,6] = data3h[j+1,6]*2/3+data3h[j,4]/3
}
}

attach(data3h)
data3i= transform(data3h, J=3*D-2*K,
K_last1=Next(K, 1),
K_last2=Next(K, 2),
D_last1=Next(D, 1),
D_last2=Next(D, 2)
)
detach(data3h)
```
```> getwd()
[1] "/home/black/public_html/tutorial/R/rst/source/R"
> dir()

> x = 1.0
> if ( x < 0.2)
{
x <- x + 1
cat("increment that number!\n")
} else if ( x < 2.0)
{
x <- 2.0*x
cat("not big enough!\n")
} else
{
x <- x - 1
cat("nah, make it smaller.\n");
}
not big enough!
> x
[1] 2

> for (lupe in seq(0,1,by=0.3))
{
cat(lupe,"\n");
}
0
0.3
0.6
0.9
>
> x <- c(1,2,4,8,16)
> for (loop in x)
{
cat("value of loop: ",loop,"\n");
}
value of loop:  1
value of loop:  2
value of loop:  4
value of loop:  8
value of loop:  16

>  repeat
{
x <- rnorm(1)
if(x < -2.0) break
}
> x
[1] -2.300532

```