What is the best way to do the same action across multiple lines of code in the RStudio source editor?
Example 1
Let's say that I copy a list from a text file and paste it into R (like the list below). Then, I want to add quotation marks around each word and add a comma to each line, so that I can make a vector.
Krista Hicks
Miriam Cummings
Ralph Lamb
Jaylene Gilbert
Jordon Sparks
Kenna Melton
Expected Output
"Krista Hicks",
"Miriam Cummings",
"Ralph Lamb",
"Jaylene Gilbert",
"Jordon Sparks",
"Kenna Melton"
Example 2
How can I add missing parentheses on multiple lines. For example, if I have an if
statement, then how can I add the missing opening parentheses for names
on line 1 and line 4.
if (!is.null(names pattern))) {
vec <- FALSE
replacement <- unname(pattern)
pattern[] <- names pattern)
}
Expected Output
if (!is.null(names(pattern))) {
vec <- FALSE
replacement <- unname(pattern)
pattern[] <- names(pattern)
}
*Note: These names are just from a random name generator.
RStudio has support for multiple cursors, which allows you to write and edit multiple lines at the same time.
Example 1
You can simply click Alt on Windows/Linux (or option on Mac) and drag your mouse to make your selection, or you can use Alt+Shift to create a rectangular selection from the current location of the cursor to a clicked position.
Example 2
Another multiple cursor option is for selecting all matching instances of a term. So, you can select names
and press Ctrl+Alt+Shift+M. Then, you can use the arrow keys to move the cursors to delete the space and add in the parentheses.