Code refactoring: from $ to [

I have a lot of code that uses the $ operator, not [[ . I read about the many benefits [[ and would like to reorganize all the code.

Were there any problems with the following method? And what is the best way for me to search and replace 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 ) 

Now the code is as follows:

 l$`__a`$`__ID` 

And I would like to reorganize it into:

 l[["__a"]][["__ID"]] 

To achieve this, are the following replacements sufficient?

 $` to [[" ` to "]] 

I found one area in my code where this method did not work, and now I also found a workaround to avoid the problem: Avoid inverse characters with dplyr

 df <- dat[["__Table"]] %>% select(`__ID` ) %>% mutate(fk_table = "__Table", val = 1) 

Before performing the replacements described above, I will need to change the select function to this to avoid false substitution of the return line character:

 select_(as.name("__ID")) 

Unfortunately, the __ name in column names cannot be avoided because the data is loaded from a relational database (FileMaker) and must be written back to the database when saving the column names.

Links about [[ :

Refactoring links in R:

+5
source share
1 answer

You can try:

 v <- c("l$`__a`$`__ID`") library(stringi) stri_replace_all_fixed(v, c('$`', '`'), c('[["', '"]]'), vectorize_all = FALSE) 

What gives:

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

Note: You see \" in the output, because print() avoids quotation marks when propagating them. You can wrap above in noquote() to see the result without \"

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

What gives:

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

If you want to apply this to the whole file, you can try:

 writeLines(stri_replace_all_fixed(readLines("script.R"), c('$`', '`'), c('[["', '"]]'), vectorize_all = FALSE), file("new_script.R")) 
+4
source

Source: https://habr.com/ru/post/1258523/


All Articles