The dollar sign is convenient to write, but allows for partial matching, which we don't often want. This function takes a file and changes all dollar signs to double brackets with names in quotations instead. Note that this function will incorrectly convert text enclosed in backticks that includes a dollar sign.

rm_dollar_sign(file, out_file = file, allow_recursive = TRUE, max_loops = 5)

Arguments

file

Filename either with full path or relative to working directory.

out_file

The name or path of a new file to write to. This is by default the same as the original file. Set to NULL to avoid writing a new file.

allow_recursive

Should dollar sign references of list in list be replaced? If this is FALSE, then only the first reference will be replaced. For example, F$first$second would become F[["first"]]$second when allow_recursive is FALSE, but would become F[["first"]][["second"]] if TRUE.

max_loops

How many times should dollar signs be looked for recursively, if allow_recursive is TRUE? Defaults to 5. This is meant to prevent an infinite loop in case the function does not work properly.

Value

A character vector of the modified text. As a side effect, produces a text file (name specified in out_file) written out from R using writeLines().

Author

Kathryn Doering

Examples

test_text <- c(
  "x$my_name <- y$test",
  "x[['my_name']]",
  "no_replace_here <- 44",
  "x$names<-new_assign;x$`22`",
  "x$names <- new_assign; x$`22`",
  "x$`$$weirdcharacters`<-222",
  "x$`nameinbacktick`",
  "x$mylist$my_col$YetAnotherCol",
  "x$mylist$my_col$`1_somename`"
)
writeLines(test_text, "test_rm_dollar_sign.txt")
new_text <- rm_dollar_sign(
  file = "test_rm_dollar_sign.txt",
  out_file = NULL
)
new_text
#> [1] "x[[\"my_name\"]] <- y[[\"test\"]]"                 
#> [2] "x[['my_name']]"                                    
#> [3] "no_replace_here <- 44"                             
#> [4] "x[[\"names\"]]<-new_assign;x[[\"22\"]]"            
#> [5] "x[[\"names\"]] <- new_assign; x[[\"22\"]]"         
#> [6] "x[[\"$$weirdcharacters\"]]<-222"                   
#> [7] "x[[\"nameinbacktick\"]]"                           
#> [8] "x[[\"mylist\"]][[\"my_col\"]][[\"YetAnotherCol\"]]"
#> [9] "x[[\"mylist\"]][[\"my_col\"]][[\"1_somename\"]]"   
file.remove("test_rm_dollar_sign.txt")
#> [1] TRUE