構建數據集有兩個步驟:
-
選擇一種數據結構來儲存數據
-
將數據導入數據結構
#構建vector
numeric.vector <- c(1, 10, 49)
character.vector <- c("a", "b", "c")
boolean.vector <- c(TRUE, FALSE, TRUE)
numeric.vector
character.vector
boolean.vector
> numeric.vector
[1] 1 10 49
> character.vector
[1] "a" "b" "c"
> boolean.vector
[1] TRUE FALSE TRUE
Poker和Roulette在拉斯維加斯進行了一週的賭博
# Poker winnings from Monday to Friday:
poker.vector <- c(140, -50, 20, -120, 240)
# Roulette winnings form Monday to Friday:
roulette.vector <- c(-24, -50, 100, -350, 10)
#給vector命名
names(poker.vector) <- names(roulette.vector) <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
# Print the named vectors
poker.vector
roulette.vector
> poker.vector
Monday Tuesday Wednesday Thursday
Friday
140 -50 20 -120 240
> roulette.vector
Monday Tuesday Wednesday Thursday
Friday
-24 -50 100 -350 10
total.daily <- poker.vector + roulette.vector
# Show me:
total.daily
> total.daily
Monday Tuesday Wednesday Thursday
Friday
116 -100 120 -470 250
#計算vector的和
total.poker <- sum(poker.vector)
total.roulette <- sum(roulette.vector)
total.week <- total.roulette + total.poker
total.week
> total.week
[1] -84
#
poker.wednesday <- poker.vector[3]
poker.midweek <- poker.vector[c(2, 3, 4)]
poker.midweek
> poker.midweek
Tuesday Wednesday Thursday
-50 20 -120
roulette.selection.vector <- roulette.vector[2:5]
roulette.selection.vector
> roulette.selection.vector
Tuesday Wednesday Thursday Friday
-50 100 -350 10
selection.vector <- poker.vector > 0
selection.vector
> selection.vector
Monday Tuesday Wednesday Thursday
Friday
TRUE FALSE TRUE FALSE TRUE
poker.winning.days <- poker.vector[selection.vector]
poker.winning.days
> poker.winning.days
Monday Wednesday Friday
140 20 240