链接seq和sort会产生意想不到的结果

时间:2021-08-04 07:43:17

I am trying to understand the (to me) unexpected behavior of chaining seq and sort:

我试图理解(对我来说)链接seq和sort的意外行为:

> seq(sort(c(5,1)))
[1] 1 2
> sort(c(5,1))
[1] 1 5
> seq(1,5)
[1] 1 2 3 4 5
> seq(c(sort(c(5,1))))
[1] 1 2

I would expect, that the first line yielded a sequence from 1 to 5, as this is what I would like to get, but I cannot make R do this just by chaining these to functions. Why?

我期望,第一行产生了一个从1到5的序列,因为这是我想要的,但是我不能让R仅仅通过把它们链接到函数来实现。为什么?

1 个解决方案

#1


0  

If you are trying to pass arguments to a function as a vector , you can use do.call(). It allows you to execute a function call with a function name and a list of its arguments.

如果要将参数作为向量传递给函数,可以使用do.call()。它允许使用函数名和参数列表执行函数调用。

do.call(seq, as.list(sort(c(5,1)))) # vector needs to be converted to a list
#[1] 1 2 3 4 5

Your example returns [1] 1 2, because whenever we pass seq a vector of length > 1, it will act as seq_along. In other words, a sequence will be created with a length equal to the count of elements in the vector.

您的示例返回[1]122,因为每当我们传递一个长度为> 1的向量seq时,它将作为seq_along。换句话说,将创建一个长度等于向量中元素个数的序列。

#1


0  

If you are trying to pass arguments to a function as a vector , you can use do.call(). It allows you to execute a function call with a function name and a list of its arguments.

如果要将参数作为向量传递给函数,可以使用do.call()。它允许使用函数名和参数列表执行函数调用。

do.call(seq, as.list(sort(c(5,1)))) # vector needs to be converted to a list
#[1] 1 2 3 4 5

Your example returns [1] 1 2, because whenever we pass seq a vector of length > 1, it will act as seq_along. In other words, a sequence will be created with a length equal to the count of elements in the vector.

您的示例返回[1]122,因为每当我们传递一个长度为> 1的向量seq时,它将作为seq_along。换句话说,将创建一个长度等于向量中元素个数的序列。