How to define a vectorized function in R

前端 未结 2 1588
迷失自我
迷失自我 2020-12-13 09:24

As the title, I\'d like to know how to define a vectorized function in R.

  • Is it just by using a loop in the function?
  • Is this method efficient?
  • <
2条回答
  •  眼角桃花
    2020-12-13 09:58

    A vectorized function will return a vector of the same length as one of its arguments. Generally one can get such a function by using combinations of built-in functions like "+", cos or exp that are vectorized as well.

    vecexpcos <- function(x) exp(cos(x))
    vecexpcos( (1:10)*pi )
    >    vecexpcos( (1:10)*pi )
    # [1] 0.3678794 2.7182818 0.3678794 2.7182818 0.3678794 2.7182818 0.3678794 2.7182818 0.3678794 2.7182818
    

    If you need to use a non-vectorized function like sum, you may need to invoke mapply or Vectorize in order to get the desired behavior.

提交回复
热议问题