Professional Documents
Culture Documents
R Tutorial: SEC 1 (Semester III)
R Tutorial: SEC 1 (Semester III)
• > sqrt(-17+0i)
[1] 0+4.123106i
• > sqrt(as.complex(−1))
[1] 0+1i
sqrt(as.complex(-17))
[1] 0+4.123106i
sqrt(as.complex(17))
[1] 4.123106+0i
• A complex value in R is defined via the pure
imaginary value i.
y <- c(x, 0, x)
Y
• would create a vector y with 11 entries consisting
of two copies of x with a zero in the middle-place.
x<-6
y<-4
z<-x+y
> z # OUTPUT OF z
[1] 10
• At any time you can list the objects which have been
created:
• ls()
[1] "x" "y" "z“
Useful when one has to recall all the variables which have
been defined.
rm(x,y) # Removes the variables x and y
x<-6
y<-4
a<-2
rm(x,y)
>x
Error: object 'x' not found
>a
[1] 2
> data1<- c(3, 5, 7, 5, 3, 2, 6, 8, 5, 6, 9)
> data1
[1] 3 5 7 5 3 2 6 8 5 6 9
> rep(1:3,rep(6,3))
[1] 1 1 1 1 1 1 2 2 2 2 2 2 3 3 3 3 3 3
> s5 <- rep(x, times=5)
> s5
[1] 10.4 5.6 3.1 6.4 21.7 10.4 5.6 3.1 6.4 21.7
10.4 5.6 3.1 6.4 21.7
[16] 10.4 5.6 3.1 6.4 21.7 10.4 5.6 3.1 6.4
21.7
[[2]]
[1] "aa" "bb" "cc" "dd" "ee"
[[3]]
[1] TRUE FALSE TRUE FALSE FALSE
[[4]]
[1] 3
List Slicing
• We retrieve a list slice with the single square
bracket "[]" operator. The following is a slice
containing the second member of x, which is a
copy of s.
• x[2]
[[1]]
[1] "aa" "bb" "cc" "dd" "ee"
• With an index vector, we can retrieve a slice
with multiple members. Here a slice
containing the second and fourth members
of x.
x[c(2, 4)]
[[1]]
[1] "aa" "bb" "cc" "dd" "ee"
[[2]]
[1] 3
Member Reference
• In order to reference a list member directly,
we have to use the double square
bracket "[[]]" operator. The following
object x[[2]] is the second member of x. In
other words, x[[2]] is a copy of s, but is not a
slice containing s or its copy.
x[[2]]
[1] "aa" "bb" "cc" "dd" "ee"
We can modify its content directly.
> x[[2]][1]
[1] "aa"
> x[[2]]
[1] “aa" "bb" "cc" "dd" "ee"
>s
[1] "aa" "bb" "cc" "dd" "ee" # s is unaffected
Interestingly,
x[2][1]
[[1]]
[1] "aa" "bb" "cc" "dd" "ee“
> length(a)
[1] 3
> t(a) # Row vector
[,1] [,2] [,3]
[1,] 6 8 9
> t(a)%*%b
[,1]
[1,] 58
Matrix as product of two vectors
> a%*%t(b)
[,1] [,2] [,3]
[1,] 6 12 24
[2,] 8 16 32
[3,] 9 18 36
Excersise