R軟體 -- 變數與運算式

# 基本型態

``````> x <- 1
> mode(x)
[1] "numeric"
> length(x)
[1] 1
> A <- "abc"; cp <- TRUE; z<- 3+2i
> mode(A); mode(cp); mode(z)
[1] "character"
[1] "logical"
[1] "complex"
> N <- 3.2e15
> N
[1] 3.2e+15
> x <- 3/0
> x
[1] Inf
> exp(x)
[1] Inf
> exp(-x)
[1] 0
> x - x
[1] NaN
> x <- "abc\"def"
> x
[1] "abc\"def"
> cat(x)
abc"def
>
> n <- 5
> 3 -> m
> k = 8
> n; m; k
[1] 5
[1] 3
[1] 8
> x <- 2 + rnorm(1)
> x
[1] 1.948103
> ls()
[1] "k" "m" "n" "x"
> ls.str()
k :  num 8
m :  num 3
n :  num 5
x :  num 1.95
> ls(pat="m")
[1] "m"
> ls(pat="m").str()

> ls.str(pat="m")
m :  num 3
>```
```

# 基本運算

``````2.1    基本運算
> 2+3
[1] 5
> 3*5+8
[1] 23
> 3/7
[1] 0.4285714
> 1%2

> 1%%2
[1] 1
> 10%%3
[1] 1
> 10%/%3
[1] 3
> cos(pi/2)
[1] 6.123032e-17
> cos(pi/3)
[1] 0.5
> sin(pi/3)
[1] 0.8660254
> tan(pi/3)
[1] 1.732051
> sec(pi/3)

> ?tan
> atan(pi/3)
[1] 0.8084488
> asin(1/3)
[1] 0.3398369
> acos(1/3)
[1] 1.230959
> x=1.2e10 / 100
> x
[1] 1.2e+08
> x=c(3,4,5,6,7)
> x > 5
[1] FALSE FALSE FALSE  TRUE  TRUE
> x[x>5]
[1] 6 7
>```
```

# 向量

``````> x = c(1,2,3,4,5)
> print(x)
[1] 1 2 3 4 5
> x
[1] 1 2 3 4 5
> x1 <- c(1,2,3)
> x1
[1] 1 2 3
> x2 <- 1:5
> x2
[1] 1 2 3 4 5
> x3 = seq(1,5,1)
> x3
[1] 1 2 3 4 5
> x4 = seq(1,10,2)
> x4
[1] 1 3 5 7 9
> y = 6:10
> x
[1] 1 2 3 4 5
> z = c(x,y)
> z
[1]  1  2  3  4  5  6  7  8  9 10
>
> x
[1] 1 2 3 4 5
> x+1
[1] 2 3 4 5 6
> x*2
[1]  2  4  6  8 10
> x/2
[1] 0.5 1.0 1.5 2.0 2.5
> x+y
[1]  7  9 11 13 15
> length(x)
[1] 5
> x - y
[1] -5 -5 -5 -5 -5
> x*y
[1]  6 14 24 36 50
> x/y
[1] 0.1666667 0.2857143 0.3750000 0.4444444 0.5000000
> log(x)
[1] 0.0000000 0.6931472 1.0986123 1.3862944 1.6094379
> ?log
starting httpd help server ... done
> sqrt(x)
[1] 1.000000 1.414214 1.732051 2.000000 2.236068
> exp(x)
[1]   2.718282   7.389056  20.085537  54.598150 148.413159
>```
```

page revision: 6, last edited: 26 Oct 2011 00:33