1

I've transitioned into writing some user-defined functions in R, but I'm hung up on whether it's best to use a dollar sign or bracket when indexing several data_frame columns. My function is like this, for a conditional value replace:

replacer <- function(df_col1,df_col2 i, k) {
  df_col1[df_col2 %in% i] <-k
}

Is there a better way to write this, one that has fewer arguments? With four arguments my way isn't very practical.

elliot
  • 1,844
  • 16
  • 45
  • Base R has a replace function, it would look something like `replace(df_col1, df_col2 %in% i, k)` for your example. – lmo Nov 11 '17 at 20:32
  • 2
    It's best to use brackets if you're passing names. – Rich Scriven Nov 11 '17 at 20:33
  • @RichScriven, how so? Thanks. – elliot Nov 11 '17 at 20:34
  • @elliot see [this post](https://stackoverflow.com/questions/2329036/how-to-reference-columns-of-a-data-frame-within-a-data-frame) and [this one](https://stackoverflow.com/questions/18222286/dynamically-select-data-frame-columns-using-and-a-vector-of-column-names) for some ideas. Most likely better SO posts exist as this is a fairly common question. – lmo Nov 11 '17 at 20:52
  • You are missing a comma after `df_col2` in `function(df_col1,df_col2 i, k)`. – Rui Barradas Nov 11 '17 at 21:56

0 Answers0