In R, how can I make a function with dynamic column assignments? I want to replace a row values in a column whose name I pass to the f'n
===

In dataframe `df` and column `a`, I would like to replace all `is.na` and all `a=2` `<- 0` for all rows.

This has been achieved simply with the following: `df[is.na(df$a) | df$a==2, "a"] <- 0`

I will be doing this over and over again over different columns (`b`, `c`, `d`, etc) so I just wanted to see if I could build a function. I will simply use the function over and over again. That way, if I need to change which values or which output, it will be a simple task.

Here is a small example. First the dataframe:

    df<-data.frame(
      a=sample(c(0,1,2), 10, replace=TRUE)
      )

Now some missing values:

    df[sample(nrow(df), 3, FALSE), "a"] <- NA

Finally, the action to replace [which I already mentioned]:

    df[is.na(df$a) | df$a==2, "a"] <- 0

I have tried the following function:

    f.na<-function(df,col) df[is.na(df[,col]) | df[,col]==2, col]<-0
    f.na(df, "a")

I feel like it should work but I cannot figure out why it doesn't. I get:

> Error in `[.data.frame`(df, , col) : undefined columns selected

I know that I cannot use the `$` sign so I tried using this `[]` format after reading some things online. I had used an `apply` type of function but then later I could not use the results in a dataframe. So I resorted to this way. I guess I can just iterate over and over for each column I need to modify but I thought the function solution would be nice.

Can you suggest anything I should try?