[英]Why are these sequences reversed when generated with the colon operator?
I've noticed that when I try to generate a list of sequences with the :
operator (without an anonymous function), the sequences are always reversed. 我注意到当我尝试使用:
运算符(没有匿名函数)生成序列列表时,序列总是反转的。 Take the following example. 以下面的例子为例。
x <- c(4, 6, 3)
lapply(x, ":", from = 1)
# [[1]]
# [1] 4 3 2 1
#
# [[2]]
# [1] 6 5 4 3 2 1
#
# [[3]]
# [1] 3 2 1
But when I use seq
, everything is fine. 但是当我使用seq
,一切都很好。
lapply(x, seq, from = 1)
# [[1]]
# [1] 1 2 3 4
#
# [[2]]
# [1] 1 2 3 4 5 6
#
# [[3]]
# [1] 1 2 3
And from help(":")
it is stated that 从help(":")
可以看出
For other arguments
from:to
is equivalent toseq(from, to)
, and generates a sequence fromfrom
toto
in steps of 1 or -1. 对于from:to
其他参数from:to
等于seq(from, to)
,并to
1或-1to
步长生成从from
到to
的序列。
Why is the first list of sequences reversed? 为什么第一个序列列表被反转?
Can I generated forward sequences this way with the colon operator with lapply
? 我能否产生正向序列这样用冒号运算lapply
?
Or do I always have to use lapply(x, function(y) 1:y)
? 或者我总是必须使用lapply(x, function(y) 1:y)
?
The ":" operator is implemented as the primitive do_colon function in C. This primitive function does not have named arguments. “:”运算符被实现为C中的原始do_colon函数。该原始函数没有命名参数。 It simply takes the first parameter as the "from" and the second as the "to" ignorning any parameter names. 它只是将第一个参数作为“from”,将第二个参数作为“to”来取消任何参数名称。 See 看到
`:`(to=10, from=5)
# [1] 10 9 8 7 6 5
Additionally the lapply
function only passes it's values as a leading unnamed parameter in the function call. 此外, lapply
函数仅将其值作为函数调用中的前导未命名参数传递。 You cannot pass values to primitive functions via lapply
as the second positional argument. 您不能通过lapply
将值传递给基本函数作为第二个位置参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.