Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code refactoring: from $ to [[

Tags:

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:

  • R language aware code reformatting/refactoring tools?
  • Tips for refactoring repetitive code in R
like image 902
Bobby Avatar asked Oct 20 '16 10:10

Bobby


1 Answers

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"))
like image 191
Steven Beaupré Avatar answered Sep 24 '22 14:09

Steven Beaupré