Sunday, June 14, 2015

[3] Data Types

Number

sample code(s)
x <- 1
y <- 2
x + y
[1] 3


Vector
(1-dimension)

sample code(s)
v1 <- c(2,4,6)
v1
[1] 2 4 6

sample code(s)
v1[3]
[1] 6

sample code(s)
v2 <- c("a","b","c")
v2
[1] "a" "b" "c"

sample code(s)
v2[3]
[1] "c"

sample code(s)
# 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"

sample code(s)
v3[1]
[1] "1"

sample code(s)
v3[3]
[1] "c"

Matrix
(2-dimension)

sample code(s)
# 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

sample code(s)
# 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)

sample code(s)
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

sample code(s)
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.")


sample code(s)
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

sample code(s)
# 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