0

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?

vrajs5
  • 4,066
  • 1
  • 27
  • 44
Kuber
  • 1,023
  • 12
  • 21

1 Answers1

2

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.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • Great.. So my mistake was not adding parenthesis after return.. return(d) worked just fine. – Kuber Jun 09 '14 at 03:42