Monday, November 2, 2015

R Basics 1 - Brief Introduction to Language Elements and Control Structures in R

1 Determine the nature of an object

> library(MASS)
> x=rnorm(1000)

# the R type of x
> typeof(x)
[1] "double"

# the data mode of x
> mode(x)
[1] "numeric"

# the storage mode of x
> storage.mode(x)
[1] "double"

# the class of x
> class(x)
[1] "numeric"

# the attributes of x
> attributes(x)
NULL

# print a summary structure of x
> str(x)
 num [1:1000] 0.248 1.893 -0.36 0.921 -0.721 ...

# print full text R code for x
> dput(x)
c(0.248081640772571, 1.89344072095915, -0.360359279529437, 0.921223527734382,
-0.721062915381023, -0.564184655238014, ...

2 NULL vs NA
# NULL is an object, typically used to mean the variable contains no object.
> x <- NULL
> is.null(x)
[1] TRUE
> length(NULL)
[1] 0

# NA is a value that means missing data item here
> y <- NA
> is.na(y)
[1] TRUE
> length(NA)
[1] 1

> # Other non-number numbers
> 1/0
[1] Inf
> 0/0
[1] NaN

3 Flow Control Structure
> #if
> if (checkNum == 0) stop("Count is 0 in lh_DevUserFactMembership")

> #if() else
> x <- 0
> if (x < 0) {
+   print("Negative number")
+ } else if (x > 0) {
+   print("Positive number")
+ } else
+   print("Zero")
[1] "Zero"

> #for ()
> str=""
> for (i in 1 : 10) {
+   str <- paste(str, LETTERS[i], sep = ",")
+   print(str)
+ }
[1] ",A"
[1] ",A,B"
[1] ",A,B,C"
[1] ",A,B,C,D"
[1] ",A,B,C,D,E"
[1] ",A,B,C,D,E,F"
[1] ",A,B,C,D,E,F,G"
[1] ",A,B,C,D,E,F,G,H"
[1] ",A,B,C,D,E,F,G,H,I"
[1] ",A,B,C,D,E,F,G,H,I,J"

> #while () expr
> i <- 1
> while (i < 6) {
+   print(i)
+   i = i+1
+ }
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

> #repeat
> x <- 1
> repeat {
+   print(x)
+   x = x+1
+   if (x == 6){
+     break
+   }
+ }
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

4 Flow Control Function
> #result <- ifelse()
> a = c(5,7,2,9)
> ifelse(a %% 2 == 0,"even","odd")
[1] "odd"  "odd"  "even" "odd"

> #switch()
> switch(2,"red","green","blue")
[1] "green"

No comments:

Post a Comment

Blog Archive