Of course R is more than a simple calculator. The great benefit of using such a language is being able to store the results of an operation into a variable (or an object) that can be used later in some subsequent operation or passed as an argument in a function. In R you can do that using either “<-” (which passes the value from the right to the left; shortcut: Alt + -) or the “=”. They have the same effect, but keeping the usage of “=” for operations or passing a value as an argument and “<-” for storing values in an object is usually better seen. Whatever you choose to use, keep it consistent.
An object in R is stored in the environment and can be accessed by just typing its name. An object can store anything, a number, a character string, a vector or list, a matrix or data frame, even functions. Keep in mind that R is case-sensitive! The class of an object can be checked using the class() function.
Y =2y =1Y == y
[1] FALSE
class(y)
[1] "numeric"
answer ="Y is not the same as y"answer
[1] "Y is not the same as y"
class(answer)
[1] "character"
sequence <-1:10sequence
[1] 1 2 3 4 5 6 7 8 9 10
class(sequence)
[1] "integer"
class(class)
[1] "function"
Operations can be done with objects instead of numbers (such as Y == y above). You can also combine objects into different objects. For example, to create a matrix (2-dimensions object), you can combine two vectors (1D objects) using functions like rbind or cbind (check their Help pages using ?rbind. Check also the function c()).
vec.1<-c(2, 4, 6)vec.2<-c(3, 5, 7)matrix.1<-cbind(vec.1, vec.2) ## binds by columnmatrix.1
vec.1 vec.2
[1,] 2 3
[2,] 4 5
[3,] 6 7
matrix.2<-rbind(vec.1, vec.2) ## binds by rowmatrix.2
[,1] [,2] [,3]
vec.1 2 4 6
vec.2 3 5 7
vec.1+ vec.2
[1] 5 9 13
vec.1>4
[1] FALSE FALSE TRUE
There is another class of objects in R called data frames that are used a lot by many functions due to its capacity of storing different data types and to have your dimensions changed after creation. For example, you cannot have one column with character strings and another with numbers in a matrix (it will convert the columns to the same type), but you can have that with a data frame. You can access single columns, rows or cells by using the row and/or column number between square brackets.