0

I was not able to find the solution to this easy question in R. How to apply a "user defined" function to each element (cell) of a dataframe with out looping?

    func <- function(cell){
        if (cell==1) return("hello")
        else return ("bye")
    }

Please do not try to say you can replace 1 with "hello" in your dataframe. It is just an example of user-defined function on a scalar but we can apply it to each element. The function might be a few hundred lines of code. I tried to mapply and sapply but did not work. Apparently, I am missing something. Thank you in advance.

Ali Khosro
  • 1,580
  • 18
  • 25
  • 2
    `apply(df, 1:2, func)` – Sotos Apr 08 '16 at 06:21
  • You should also have a look at [this link](http://stackoverflow.com/questions/3505701/r-grouping-functions-sapply-vs-lapply-vs-apply-vs-tapply-vs-by-vs-aggrega?rq=1). It is very helpful. – Sotos Apr 08 '16 at 06:24
  • OMG. Thank you. Worked! I feel relieved but stupid at the same time, which is a good feeling by the way. :) – Ali Khosro Apr 08 '16 at 06:27

1 Answers1

1

You need apply

see :

func <- function(cell){
  if (cell==1) return("hello")
  else return ("bye")
}

df=data.frame(x=1:5,y=-2:2)
apply(df,c(1,2),func)

     x       y      
[1,] "hello" "bye"  
[2,] "bye"   "bye"  
[3,] "bye"   "bye"  
[4,] "bye"   "hello"
[5,] "bye"   "bye"  
Batanichek
  • 7,761
  • 31
  • 49