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??