I am trying to learn how to use function and apply. So first I wanted to understand how both works.
Here is a basic example. I am creating a function that, depending in the value of a column, use one algorith or another:
datos = data.frame(replicate(5,sample(0:10,10,rep=TRUE)))
calculo <- function(variable) {
aa = variable * 2
if (variable < 5) {
aa = 0
}
return(aa)
}
datos$Y1 = apply(datos, 1, FUN=function(x) calculo(datos$X1))
My simple idea in this example is that:
- If the value of X1 is < 5, then value is 0.
- If >= 5, then multiply by 2.
When I apply it, I think that the condition is applied to all the values in datos$X1 at the same time, instead of going row by row. So it isn´t working in the way I thought.
Is there a way to apply the condition row by row?
Thanks