Applying a simple function over a vector using vapply

This question is somewhat twofold. First, I'm trying to find a better way to achieve a simple implementation of a function on a vector. Secondly, I am trying to understand the meaning of FUN.VALUE in vapply.

I defined a simple half-wave rectification function:

Fun = function(x) x[x<0]=0

Then I define a vector:

A = -10:10

I want to apply this function to a vector. I tried several approaches, but cannot figure out how to do this easily.

I could always

A[A<0]=0

but it defeats the purpose of using the function.

I tried to define the function so that it applies to every element of the vector, and not to the vector as a whole:

Fun = function(x) {if (x<0) {x=0} }

I cannot use apply, since apply only works when the object to which this function is applied has dimensions, and for some reason the vector has no sizes in R.

lapply, NULL 0 , , .

vapply FUN.VALUE

:

FUN.VALUE
a () ; FUN. . "".

:

vapply , FUN.VALUE. (FUN.VALUE) == 1, , X, , . FUN.VALUE , (FUN.VALUE) (X), a dim (a) == c (dim (FUN.VALUE), ()).

. A - 20 , , 20 . , 20 ? 20, 1?

. , , , , - .

+4
1

.

Fun = function(x) x[x<0]=0

:

correct_fun = function(x){
  x[x<0]=0
  return(x)
}

, . x, , . correct_fun on A :

[1]  0  0  0  0  0  0  0  0  0  0  0  1  2  3  4  5  6  7  8  9 10
+4

All Articles