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:
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With