I have a lot of code which uses the $
operator rather than [[
. I've read about many advantages of [[
and would like to refactor all of the code.
Would there be any problems with the following method? And how could I best do the search and replace with RStudio or TextWrangler on a Mac?
l <- list()
l$`__a` <- data.frame(`__ID` = stringi::stri_rand_strings(10, 1), col = stringi::stri_rand_strings(10, 1), check.names = F )
The code looks like this now:
l$`__a`$`__ID`
And I would like to refactor it to:
l[["__a"]][["__ID"]]
To achieve this, are the following replacements sufficient?
$` to [["
` to "]]
I've found one area in my code where this method would not work, and now I've also found a workaround for how to avoid the issue: Avoiding backtick characters with dplyr
df <- dat[["__Table"]] %>% select(`__ID` ) %>% mutate(fk_table = "__Table", val = 1)
Before doing the replacements above, I would need to change the select
function to this to avoid making false replacements of the backtick character:
select_(as.name("__ID"))
Unfortunately, the __
in column names cannot be avoided since the data is downloaded from a relational database (FileMaker) and needs to be written back to the database while preserving the column names.
References about [[
:
- Code autocompletion with lists in RStudio
- Is it possible to index an R list using a character variable and the '$' operator?
- The difference between [] and [[]] notations for accessing the elements of a list or dataframe
References about refactoring in R:
library(stringr) test <- c("x <- df$var_name\n", "x <- df$var_name", "x <- df$var_name ") str_replace(test, pattern = "([$])(.+)(\n|[!\"#$%&()*+,-./:;<=>?@^`{|}~])", replace = "[[\"\\2\"]]\\3")
$
-filled code is not wrong and not broken. Spend your limited resource of time on new and important things.$
for readability even though it has the backtick symbols. My main goals is to allow for passing column names as variables (even when they start with_
and that is easier with standard strings that don't contain backtick symbols.) Does that make sense? Now the parts that have backticks are hard coded and I will move towards calculating them dynamically.