這是 R 中一個很重要的概念。 為了幫助理解各種可能性,不妨想想各個函式輸入與輸出的維度。
我們已經看過一些接收向量、並回傳單一純量值的函式:
> v <- 1:5
> length(v)
#> [1] 5
> sum(v)
#> [1] 15
許多統計函式也屬於這一類,例如mean()。
對於邏輯向量,則有all()和any()。
R 中許多函式會直接對整個向量運算,輸出通常也是向量。 大多數數學函式都屬於這類:
> sq <- c(4, 9, 16, 25)
> sqrt(sq) # square root
#> [1] 2 3 4 5
這麼做不僅簡潔方便,還能省去其他語言常見的迴圈、串列推導或遞迴。 在 R 裡,向量函式的執行速度往往比這些技巧快得多。
若要排序向量,可以用sort()回傳值,用order()回傳索引:
> v <- c("I", "am", "not", "in", "order")
> sort(v)
#> [1] "am" "I" "in" "not" "order"
> order(v)
#> [1] 2 1 4 3 5
預設是由小到大排序。
需要的話可以指定decreasing = TRUE,或使用rev()反轉現有的向量。
v <- c("I", "am", "not", "in", "order")
sort(v, decreasing = TRUE)
#> [1] "order" "not" "in" "I" "am"
rev(1:4)
#> [1] 4 3 2 1
此外,也有函式能產生累積的向量輸出,由左至右處理輸入向量:
> cumsum(1:5)
#> [1] 1 3 6 10 15 # sums
> cumprod(1:5)
#> [1] 1 2 6 24 120 # equivalent to factorials
這個概念延伸出去,也能用來比較向量。
例如,看看成對取最大值的函式pmax():
> v
#> [1] 2 7 9
> w
#> [1] 3 1 5
> pmax(v, w)
#> [1] 3 7 9 # max of each pairwise comparison
你是個熱衷的賞鳥者,會記錄過去 7 天內有多少鳥造訪你的花園。
你有 6 個任務,全都和造訪你花園的鳥的數量有關。
實作today()函式,回傳今天有多少鳥造訪你的花園。鳥的數量依日期排序,第一個元素是最早那天的數量,最後一個元素則是今天的數量。
birds_per_day <- c(2, 5, 0, 7, 4, 1)
today(birds_per_day)
# => 1
實作increment_todays_count()函式,把今天的數量加一:
birds_per_day <- c(2, 5, 0, 7, 4, 1)
increment_todays_count(birds_per_day)
# => c(2, 5, 0, 7, 4, 2)
實作has_day_without_birds()函式,如果有一天沒有任何鳥造訪花園,就回傳TRUE;否則回傳FALSE:
birds_per_day <- c(2, 5, 0, 7, 4, 1)
has_day_without_birds(birds_per_day)
# => true
實作count_for_first_days()函式,回傳從本週第一天起造訪你花園的鳥的數量,但只計算從本週第一天起算的指定天數。
birds_per_day <- c(2, 5, 0, 7, 4, 1)
count_for_first_days(birds_per_day, 4)
# => 14
有些日子比其他日子更忙碌。只要一天有 5 隻以上的鳥造訪你的花園,就算是忙碌的一天。
實作busy_days()函式,回傳忙碌的日子有幾天:
birds_per_day <- c(2, 5, 0, 7, 4, 1)
busy_days(birds_per_day)
# => 2
你很好奇這週到目前為止總共有多少鳥造訪。 請計算每一天的累計總和。
running_total(c(7, 6, 5, 4, 3, 2, 1))
#> [1] 7 13 18 22 25 27 28
你懷疑鳥的造訪受到附近道路交通型態的影響,所以週末和平日有所不同。
請依造訪鳥數的_遞減_順序,排序這些星期的縮寫。
day_names <- c("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
birds_per_day <- c(5, 2, 4, 6, 0, 9, 8)
busy_days_of_week(birds_per_day, day_names)
#> [1] "Sat" "Sun" "Thu" "Mon" "Wed" "Tue" "Fri"