Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are these sequences reversed when generated with the colon operator?

Tags:

r

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 to seq(from, to), and generates a sequence from from to to 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)?

like image 576
Rich Scriven Avatar asked Jan 10 '23 10:01

Rich Scriven


1 Answers

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.

like image 77
MrFlick Avatar answered Jan 11 '23 23:01

MrFlick