Sunday, August 7, 2016

R programming brief note

What is R?
R is a dialect of S.

What is S?
S is a language that was developed by John Chambers and others at the old Bell Telephone
Laboratories, originally part of AT&T Corp. S was initiated in 1976 as an internal statistical analysis environment—originally implemented as Fortran libraries. Early versions of the language did not even contain functions for statistical modeling.

R Objects
R has five basic or “atomic” classes of objects:
• character ("This is a text")
• numeric (real numbers) (2, 5, 10)
• integer (2, 3, 10)
• complex (2i, 4i)
• logical (True/False)

Assignment Operator
"<-" is an assignment operator in R

Declare a variable
x <- 5 #This is a comment in R like other programming language, note that number 5 is assigned to variable x

Attributes
R objects can have attributes, which are like metadata for the object.
Some examples of R object attributes are
• names, dimnames
• dimensions (e.g. matrices, arrays)
• class (e.g. integer, numeric)
• length
• other user-defined attributes/metadata

Creating Vectors
The c() function can be used to create vectors of objects by concatenating things together.
> x <- c(0.5, 0.6) ## numeric
> x <- c(TRUE, FALSE) ## logical
> x <- c(T, F) ## logical
> x <- c("a", "b", "c") ## character
> x <- 9:29 ## integer
> x <- c(1+0i, 2+4i) ## complex

or

x <- vector("list", length = 5)

Matrices
Matrices are vectors with a dimension attribute. The dimension attribute is itself an integer vector of length 2 (number of rows, number of columns)
> m <- matrix(1:6, nrow = 2, ncol = 3)
> m
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6

List
Lists are a special type of vector that can contain elements of different classes. Lists are a very important data type in R and you should get to know them well. Lists, in combination with the various “apply” functions discussed later, make for a powerful combination.
Lists can be explicitly created using the list() function, which takes an arbitrary number of
arguments.
> x <- list(1, "a", TRUE, 1 + 4i)
> x
[[1]]
[1] 1
[[2]]
[1] "a"
[[3]]
[1] TRUE
[[4]]
[1] 1 + 4i

Factors
Factors are used to represent categorical data and can be unordered or ordered.
> x <- factor(c("yes", "yes", "no", "yes", "no"))
> x
[1] yes yes no yes no
Levels: no yes

Data Frames
Data frames are used to store tabular data in R.
> x <- data.frame(foo = 1:4, bar = c(T, T, F, F))
> x
foo bar
1 1 TRUE
2 2 TRUE
3 3 FALSE
4 4 FALSE
> nrow(x)
[1] 4
> ncol(x)
[1] 2

Names
R objects can have names, which is very useful for writing readable code and self-describing objects.
Here is an example of assigning names to an integer vector.
> x <- 1:3
> names(x)
NULL
> names(x) <- c("New York", "Seattle", "Los Angeles")
> x
New York Seattle Los Angeles
1 2 3
> names(x)
[1] "New York" "Seattle" "Los Angeles"

Subsetting R Objects
There are three operators that can be used to extract subsets of R objects.
• The [ operator always returns an object of the same class as the original. It can be used to
select multiple elements of an object
• The [[ operator is used to extract elements of a list or a data frame. It can only be used to
extract a single element and the class of the returned object will not necessarily be a list or
data frame.
• The $ operator is used to extract elements of a list or data frame by literal name. Its semantics are similar to that of [[.

x <- c("a", "b", "c", "c", "d", "a")
x[1]
x[1:4]
x[c(1,2,4)]

u <- x > "a"
u

x[x > "a"]

Subsetting Matrix

x <- matrix(1:6, 2, 3)
x[1,2]

> x[1, ] ## Extract the first row
[1] 1 3 5
> x[, 2] ## Extract the second column
[1] 3 4

Subsetting Lists
> x <- list(foo = 1:4, bar = 0.6)
> x
$foo
[1] 1 2 3 4
$bar
[1] 0.6

x[[1]]
x[["bar"]]
x$foo

> x <- list(a = list(10, 12, 14), b = c(3.14, 2.81))
>
> ## Get the 3rd element of the 1st element
> x[[c(1, 3)]]
[1] 14
>
> ## Same as above
> x[[1]][[3]]
[1] 14
>
> ## 1st element of the 2nd element
> x[[c(2, 1)]]
[1] 3.14

> x <- list(foo = 1:4, bar = 0.6, baz = "hello")
> x[c(1, 3)]
$foo
[1] 1 2 3 4
$baz
[1] "hello"

Date Time:
datestring <- c("January 10, 2012 10:40", "December 9, 2011 9:10")
x <- strptime(datestring, "%B %d, %Y %H:%M")

x <- as.Date("2012-03-01")
y <- as.Date("2012-02-28")
x-y

Control Structures
Commonly used control structures are
if and else: testing a condition and acting on it
for: execute a loop a fixed number of times
while: execute a loop while a condition is true
repeat: execute an infinite loop (must break out of it to stop)
break: break the execution of a loop
next: skip an interation of a loop

> if(a==4){
+ print(a)
+ }
[1] 4
>

> for(i in 1:10){
+ print(i)
+ }
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10
>

> x <- c("a", "b", "c", "d")
>
> for(i in 1:4) {
+ ## Print out each element of 'x'
+ print(x[i])
+ }
[1] "a"
[1] "b"
[1] "c"
[1] "d"

> x <- c(1,3,4,5,6,7)
> for(i in 1:3) print(x[i])
[1] 1
[1] 3
[1] 4
>

Nested for loops
x <- matrix(1:6, 2, 3)
for(i in seq_len(nrow(x))) {
for(j in seq_len(ncol(x))) {
print(x[i, j])
}
}

next and break:

for(i in 1:100){
  if(i<=20){
    next
  }
  print(i)
 
  if(i>=50){
    break
  }
}

Function

> f <- function() {
+ ## This is an empty function
+ }
> ## Functions have their own class
> class(f)
[1] "function"
> ## Execute this function
> f()
NULL

f <- function(a, b){
a^2 #now b no use
}
f(2) #result 4 and no error

f <- function(a,b){
print(a)
print(b)
}
f(1) #result 1 and return error because no b

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.