用比較來選取 - 步驟 2
善用比較可以讓你的資料分析工作更輕鬆。與其像先前一樣自己挑出要觀察的幾天,你可以直接請 R 回傳那些你在撲克牌有正報酬的日子。
在前面的練習中,你使用 selection_vector <- poker_vector > 0 找出你在撲克牌有正報酬的日子。現在,你不只想知道哪些天有贏,還想知道那些天各贏了多少。
你可以把 selection_vector 放在 poker_vector 後面的中括號裡,來選出想要的元素:
poker_vector[selection_vector]
當你在中括號中傳入邏輯向量時,R 知道該怎麼做:它只會選取 selection_vector 中對應為 TRUE 的元素。
本練習屬於課程
R 入門
練習說明
在中括號中使用 selection_vector,把你在獲利日子贏得的金額指派給變數 poker_winning_days。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Poker and roulette winnings from Monday to Friday:
poker_vector <- c(140, -50, 20, -120, 240)
roulette_vector <- c(-24, -50, 100, -350, 10)
days_vector <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
names(poker_vector) <- days_vector
names(roulette_vector) <- days_vector
# Which days did you make money on poker?
selection_vector <- poker_vector > 0
# Select from poker_vector these days
poker_winning_days <-