这是 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"