0

I have a dataframe (data) in R and I have created a function that does the following:

If data contains zero values, then replace data with data +2 and then return datanew <- data + data^2. If data does not contains zeros then do datanew <- data + data^2.

I manage to do that as follows:

set.seed(123)
data <- as.data.frame(matrix(rbinom(10 * 5, 1, 0.5), ncol = 5, nrow = 10))

Myfunction <- function(data) {
  if (any(data == 0, na.rm = TRUE)) {
    data <- data + 2
  } # 2 is the a value that i want to add in all elements
  datanew <- data + data ^ 2
  print(datanew)
}

Myfunction(data = data)

However, I want to define in the function the element a (function(data, a)) and if omitted then the default value will be 2, otherwise the value that has be given by the user. How can i do that R??

Parfait
  • 104,375
  • 17
  • 94
  • 125
nickolakis
  • 621
  • 3
  • 7
  • 6
    Try with `Myfunction <- function(data, a = 2)` – stefan Jan 14 '23 at 16:29
  • That seems to work, however is there anyway to make it looks like an optional argument like other functions do? Meaning when function is defined, if a is missing to put a=2, otherwise the specified value without seeing when typing `Myfunction(data=, a=2)`. – nickolakis Jan 14 '23 at 16:39
  • 5
    This is a pretty basic R question. Look up *default argument* in function. This [Hadley tutorial](http://adv-r.had.co.nz/Functions.html) gives a nice primer on functions. Be sure to [research](https://meta.stackoverflow.com/q/261592/1422451) before posting. Cheers! – Parfait Jan 14 '23 at 16:39
  • 2
    Regarding follow-up question, see https://stackoverflow.com/q/28370249/1422451 – Parfait Jan 14 '23 at 16:41

0 Answers0