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.
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
For other arguments
from:to
is equivalent toseq(from, to)
, and generates a sequence fromfrom
toto
in steps of 1 or -1.
Why is the first list of sequences reversed?
Can I generated forward sequences this way with the colon operator with lapply
?
Or do I always have to use 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. It simply takes the first parameter as the "from" and the second as the "to" ignorning any parameter names. 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. You cannot pass values to primitive functions via lapply
as the second positional argument.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With