Core Data Types and Structures in R
- Using RStudio
ggplot2
The ggplot2 package providse powerful data visualization. To install it, run the following in the RStudio console:
install.packages("ggplot2")
Once installed, load the package in each script with:
library(ggplot2)
Note that in RStudio’s Source pane, pressing Ctrl+Enter (or clicking Run) executes only the current line. Code runs line by line.
- R Language Basics
Data Types
Basic Types
In R, variables are assigned without explicit type declarations. For example, value <- 123 stores 123 in value. The same variable can later hold a different type.
R has six atomic data types, summarized below. Use print(class(x)) to check the type of x.
| Data Type | Examples |
|---|---|
| Raw | See explanation |
| Logical | TRUE, FALSE |
| Integer | 2L, 0L |
| Numeric | 12.3, 123 |
| Complex | 3 + 2i |
| Character | 'a', "good", "TRUE", '23.4' |
The Raw type holds bytes. For instance:
rawData <- charToRaw("Hi")
stores "Hi" as the raw bytes 48 69.
Complex numbers must include the imaginary unit i explicitly, e.g., 3+1i. Omitting the numeric coefficient (3+i) causes an error.
Vectors
Combine multiple values into a vector with c():
vec <- c(3L, 5+2i, TRUE, "hello", 2.5)
print(vec)
Output:
[1] "3" "5+2i" "TRUE" "hello" "2.5"
All elements are coerced to the same type. When mixed, the priority order is Raw < Logical < Integer < Numeric < Complex < Character. Thus class(vec) returns "character".
Lists
A list can contain elements of any type, including other lists.
baseList <- list(10, 20, 30)
combinedList <- list(c(7, 8, 9), 3.14, sqrt, baseList, list(100, 200))
print(combinedList)
[[2]] [1] 3.14
[[3]] function (x) .Primitive("sqrt")
[[4]] [[4]][[1]] [1] 10
[[4]][[2]] [1] 20
[[4]][[3]] [1] 30
[[5]] [[5]][[1]] [1] 100
[[5]][[2]] [1] 200
</details>Lists can be nested self-referentially, but they capture the state at assignment time:
<details> <summary>Click to view code</summary> ```
> myList <- list(5)
> myList <- list(10, myList)
> print(myList)
[[1]]
[1] 10
[[2]]
[[2]][[1]]
[1] 5
> myList <- list(10, myList)
> print(myList)
[[1]]
[1] 10
[[2]]
[[2]][[1]]
[1] 10
[[2]][[2]]
[[2]][[2]][[1]]
[1] 5
Use the matrix() function to create a matrix:
mat <- matrix(1:6, nrow = 2, ncol = 3, byrow = TRUE)
print(mat)
The resulting 2×3 matrix is filled by row with 1,2,3 in the first row and 4,5,6 in the second.