Pieter
Pieter

Reputation: 657

In R, how can I replace items in a text string with other items?

I'm a beginner to R.

I often switch working directory using setwd(). I'm on Windows where addresses have backslashes like so: C:\Users\myname\Documents, but R uses forward slashes like this:

> getwd()
[1] "C:/Users/myname/Documents"

Often when changing directories using setwd() I find myself manually copy-pasting the address of the directory from Windows Explorer, pasting it into the setwd() command and manually changing the backslashes into forward slashes.

Is there a command that I can use that will replace the backslashes in a text string into forward slashes?

Thank you!

Upvotes: 3

Views: 219

Answers (2)

Tyler Rinker
Tyler Rinker

Reputation: 109874

Not built in but I too was annoyed by Windows paths:

## Frist Install this
library(devtools)
install_github('slidify', 'ramnathv', ref = 'dev')
install_github('slidifyLibraries', 'ramnathv', ref = 'dev')
install_github("reports", "trinker")

## Then use this:
library(reports)
WP()

This stands for Windows path and can read from the clipboard and correct the slashes. It copies the correct version back to the clipboard. Eventually this version of reports will go to CRAN once slidify goes to CRAN.

Upvotes: 3

mnel
mnel

Reputation: 115392

You can use the fact that if you scan the text "C:\mydir" it is read in as "C:\\mydir".

You can access what is held in the clipboard by using file('clipboard').

# something like the following will work
scan(file('clipboard'), what = 'character')

# and a function that will read and coerce the clipboard
scanclip <- function(){
  scan(file('clipboard'), what = 'character', quiet= TRUE)}
# so you can use
setwd(scanclip())

Upvotes: 3

Related Questions