简体   繁体   中英

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.

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) ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM