I am quite new to writing functions and am working a generic function that is to be applied to several, but not all, rows in a data frame. The function is supposed to conditionally transform the values of these specified rows.
Example data:
df <- data.frame("Var1" = c(0:5), "Var2" = c(-5:0), "Var3" = c(0,0,0,0,0,0)
> df
Var1 Var2 Var3
1 0 -5 0
2 1 -4 0
3 2 -3 0
4 3 -2 0
5 4 -1 0
6 5 0 0
Example function:
myFun <- function(x, na_value){
x[x == na_value] <- NA
x
}
Given that I want 0's to transform to NA for Var1 and Var 2 - but NOT Var3, I have written df$Var1 <- myFun(df$Var1, 0) and df$Var2 <- myFun(df$Var2, 0) - but there has got to be a simpler way of doing this?
What I evision is something like myFun(Var1, Var2, 0) that transforms the 0's in Var1 and Var2 to NA without having to repeat the code for both variables. The function is to be applied for multiple data frames with different variable names and different na_values which is why I have written it in the first place, and it works fine, but I would like to simplify even more.
df[, c("Var1", "Var2")][df[, c("Var1", "Var2")] == 0] <- NA