R is a language used for statistical computing and graphics. It can be used to efficiently produce well-designed plots that include mathematical symbols and formulas.
A variable is a container that can take any value. This value can be changed as the program progresses.
There are five different data types in R:
A sequence of elements of the same basic data types, namely:
If the data types are not the same, an undesirable outcome is received.
The following code shows how each of these basic data types can be declared:
A = c(TRUE, FALSE) #LogicalB = c(5L, 19L) #IntegerC = c(1.1, 1.22) #NumericD = c(1+2i) #ComplexE = c("A", "B") #Character#To check the data type of a variableclass(B)
Note: To declare integer values, L should be written next to the value.
It can be used to declare elements in two-dimensional objects. Matrices are declared in the following syntax:
matrix (data, nrow, ncol, byrow, dimnames)
data
- Input vector that become data elements of the matrixnrow
- Number of rowsncol
- Number of columnsbyrow
- If true, the elements are arranged by rowdimnames
- Names assigned to rows and columnsThe following example shows how to store numbers 1-29 in a matrix:
m = matrix(c(1:30), 5, 5, 1)m
Notice how setting the byrow parameter changes the data entry.
They are used to store data elements in more than two dimensions. You can store multiple matrices in an array. Arrays are declared using the following syntax:
array(data, dim, dimnames)
data
- Input vector that becomes the data elements of the arraydim
- Dimensions of the arraydimnames
- Names assigned to rows and columnsThe following example declares an array that stores four 3x3 matrices in an array of 2x2:
Arr = array( c(1:9) , dim = c(3,3,2,2))Arr
They are used to store multiple values of different data types. Vectors change the values of data types to ensure that they all belong to the same data type, lists do not.
They are declared using the following syntax:
list (data)
data
- Vectors that become data elements of a list
The following code shows how to declare a list:
l = list("Apple", 1.1, TRUE)l
Notice how the values are not converted to match a single data type.
These are similar to the data frames used in Python. Columns are used to store the value of the same data types with each row corresponding to a single set of values.
The following code presents how to create a data frame of fruits along with their price:
Serial_no = c(1:5)Fruits = c("Apple ", "Banana", "Orange", "Mango ", "Kiwi ")Price = c(1.1, 2.3, 1, 5.5, 8.9)df = data.frame(Serial_no, Fruits, Price)df
Free Resources