5

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 [[:

References about refactoring in R:

3
  • Honestly, I wouldn't worry too much about refactoring your code. You're probably going to introduce more errors in refactoring than you are likely to experience by leaving it. I just spent 20 minutes trying to get a start and the best I can come up with comes no where near functioning on all of the common cases, let alone the edge cases. 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")
    – Benjamin
    Commented Oct 20, 2016 at 11:20
  • 1
    I second @Benjamin's comment. Fix only important things in existing code and use your newfound fav idiom moving forward. Your $-filled code is not wrong and not broken. Spend your limited resource of time on new and important things.
    – hrbrmstr
    Commented Oct 20, 2016 at 14:48
  • Thanks @Benjamin and @hrbmstr, I appreciate your comments. Here, the purpose of refactoring is only part of the story and not only for code readability. Actually I prefer $ 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.
    – Bobby
    Commented Oct 21, 2016 at 8:43

1 Answer 1

4

You could try:

v <- c("l$`__a`$`__ID`")

library(stringi)
stri_replace_all_fixed(v, c('$`', '`'), c('[["', '"]]'), vectorize_all = FALSE)

Which gives:

#[1] "l[[\"__a\"]][[\"__ID\"]]"

Note: You see the \" in the output because print() escapes the quotes when diplaying them. You can wrap the above in noquote() to see the output without the \"

noquote(
  stri_replace_all_fixed(v, c('$`', '`'), c('[["', '"]]'), vectorize_all = FALSE)
)

Which gives:

#[1] l[["__a"]][["__ID"]]

Should you want to apply this on an entire file, you could try:

writeLines(stri_replace_all_fixed(readLines("script.R"), 
                                  c('$`', '`'), c('[["', '"]]'), vectorize_all = FALSE),
           file("new_script.R"))
4
  • This looks very encouraging. Do you know how to apply it to an entire .r file?
    – Bobby
    Commented Oct 20, 2016 at 12:09
  • @Bobby Maybe stri_replace_all_fixed(readLines("script.R"), c('$', ''), c("[['", "']]"), vectorize_all = FALSE) ? Commented Oct 20, 2016 at 12:18
  • I still think this is a fantastic answer for the specific part of my question. For the general part, I'm not yet sure. How can I make sure that I don't have backtick symbols which should not be replaced?
    – Bobby
    Commented Oct 20, 2016 at 17:16
  • @Bobby I'm thinking we could use a more robust approach with a regex to make sure we only change the backtick if there were a $backtick before. Commented Oct 20, 2016 at 17:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.