[SOLVED] How function(x) works in R?

Issue

data =data.frame(sapply(data,function(x) ifelse((x==999),NA,x)))

Could you explain how function(x)….,x works? I know what input and output of this function are, it just replaces 999 values with NAs in dataframe, but I want to know how this function(x) works in General.

Solution

This is your function with the name my_func: It takes a value x checks if it is 999, if not it gives back the value of x, if yes it gives back 999:

my_func <- function(x) {
  ifelse(x==999, NA, x)
}

You now can use this function as follows:

  1. named function standalone:
my_func(mtcars$mpg)
  1. As named function with lapply or sapply

Basically sapply function in R does the same job as lapply() function but returns a vector:

  • lapply(X, FUN)
    Arguments:
    X: A vector or an object
    FUN: Function applied to each element of x
lapply(mtcars$mpg, my_func)
  • sapply(X, FUN)
    Arguments:
    -X: A vector or an object
    -FUN: Function applied to each element of x
sapply(mtcars$mpg, my_func)

Now your question:

You can use a function in this case my_func directly without defining or naming first as an anonymous function (means the function has not a name) like:

lapply(mtcars$mpg, function(x) ifelse(x==999, NA, x))

Note: essentially after function(x) it is the body part of your named function my_func.

Answered By – TarJae

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published.