| x <- 1 y <- 2 x + y |
| [1] 3 |
Vector
(1-dimension)
| v1 <- c(2,4,6) v1 |
| [1] 2 4 6 |
| v1[3] |
| [1] 6 |
| v2 <- c("a","b","c") v2 |
| [1] "a" "b" "c" |
| v2[3] |
| [1] "c" |
| # One vector cannot contain both numbers and characters. When they're mixed, then all is regarded as characters. v3 <- c(1,"b","c") v3 |
| [1] "1" "b" "c" |
| v3[1] |
| [1] "1" |
| v3[3] |
| [1] "c" |
Matrix
(2-dimension)
| # default: column 1 first matCol1 <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3) matCol1 |
| [,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6 |
| # byrow = TRUE: row 1 first matRow1 <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3, byrow = TRUE) matRow1 |
| [,1] [,2] [,3] [1,] 1 2 3 [2,] 4 5 6 |
Data Frame
(2-dimension; mixed structure of numbers and characters)
| df <- data.frame(symbol = c("AAPL", "GOOG", "GS"), action = c("Buy", "Buy", "Sell"), price = c(127.17, 532.33, 213.06), shares = c(500,100,500)) df |
| symbol action price shares 1 AAPL Buy 127.17 500 2 GOOG Buy 532.33 100 3 GS Sell 213.06 500 |
| df[2,3] |
| [1] 532.33 |
List
("A matrix which can contain any form of data like number, vector, matrix, and even a data frame.")
| l <- list(a = c(1, 2), b = matrix(1:6, nrow = 2, ncol = 3), c = data.frame(symbol = c("AAPL", "GOOG", "GS"), action = c("Buy", "Buy", "Sell"), price = c(127.17, 532.33, 213.06), shares = c(500,100,500))) l |
$a [1] 1 2 $b [,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6 $c symbol action price shares 1 AAPL Buy 127.17 500 2 GOOG Buy 532.33 100 3 GS Sell 213.06 500 |
| # The same result above. l2 <- list(a = c(1, 2), b = matrix(1:6, nrow = 2, ncol = 3), c = df) l2 |
No comments:
Post a Comment