Professional Documents
Culture Documents
Objects in R
Variable
Is an object with a single value. It is the simplest object in R
Can be assigned an expression involving other variables
Examples: x = 3, or x = b + c where b = 2 and c = 6
Vector
Is a collection of elements of the same data type
Examples: {1, 2, 3}, {“Amar”, “Akbar”, “Anthony”}, {10.4, 7.8,
9.1}
Sequence
Is a vector made of numbers
Have a fixed pattern
Examples: {1, 4, 7}, {5.1, 6.2, 7.3}, {1 + 2i, 2 + 3i, 3 + 4i}
Objects in R
Array
Matrix
Factor
It is like a vector
Data Frame
Examples:
>x<-c(1,3,4,6)
> x
[1] 1 3 4 6
> x<-c("Amar","Akbar","Anthony")
> x
Examples:
> x<-c(1,3,5)
> rep(x,2)
[1] 1 3 5 1 3 5
> rep(x,each=2,times=3)
[1] 1 1 3 3 5 5 1 1 3 3 5 5 1 1 3 3 5 5
> rep(x,c(2,4,3))
[1] 1 1 3 3 3 3 5 5 5
Sorting
Examples:
> x<-c(1,3,5,2,1,3,7,3,2)
> sort(x)
[1] 1 1 2 2 3 3 3 5 7
> sort(x,decreasing = True)
Error in sort(x, decreasing = True) : object
'True' not found
> sort(x,decreasing = TRUE)
[1] 7 5 3 3 3 2 2 1 1
[
Concatenation
Function paste() can be used to concatenate
two or more vectors
Examples:
> x<-c(1,2,3)
> y<-c("A","B","C")
> paste(x,y)
[1] "1 A" "2 B" "3 C" > x<-3
> paste("The value of x is", x)
> paste(x,y,sep="&") [1] "The value of x is 3"
Examples:
Creating an Array
(Method 2)
Examples:
Retrieving Elements and
Subsections
Elements of an array can be retrieved by
referencing its position, or the index
Exercises
1. Creating Vectors
1.a) Create a numeric vector: x={20,30,40}. Test if it is a vector using
is.vector function. Check its type and mode.
➡ i Two times
➡ Both i and ii
➡ Repeating the first number 5 times and the third number twice
2.d) The sequence 3.5, 5.5, 7.5, 9.5 [Hint: use c()]:
3. Creating Arrays