Passing and returning functions in R

I want to create a function in R, which take data as a function, do some operation on it(add some columns/Rows etc) and return it. I found usually I can not do so.

f <- function(d = cars){
    d$new = ifelse(d$dist > rep(10, nrow(d)), 1, 0)
    return d 
}

Error: unexpected symbol in:
"d$new= ifelse(d$dist>rep(10,nrow(d)),1,0)
return d"

If I remove return d, I get only the vector, not whole data frame. Any suggestion?

Answers


Functions in R return the value from the last statement executed. When you do an assignment, the value from the left side of the assignment is the (invisibly) returned result. For exampel

d <- cars
a <- (d$new <- ifelse(d$dist>10, 1, 0))
a

#  [1] 0 0 0 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
# [40] 1 1 1 1 1 1 1 1 1 1 1

So in your example you're merely returning the vector you just created. R doesn't know that you want to return the whole d data.frame. If you put the return(d), it will know that's what you want. You can even just put d on the last line by itself to return that value.


Need Your Help