write.table to new directory - r

Is there any way to use write() and write.table() so that the output file is in a different directory than the working directory? It tried setting the path to the output file before the filename, and just get an error message.

If you're using windows, R will know to go outside the current directory if it sees C:/ first (presumably other mounted drives too). With Macs it will go outside the current wd if it sees /. So:
Mac OS X:
write.table(foo, file="/users/name/folder/filename.ext")
Windows
write.table(foo, file="C:/users/name/folder/filename.ext")
Always test to make sure you have the path right first!
list.files("C:/...")
list.files("/....") #Give errors if path doesn't exist as typed
So if you're in /users/parent/subdir and you want to reference something in parent, you must type out the full path - write.table(foo, "parent/name.ext") will tell R to make a file: /users/parent/subdir/parent/name.ext.

Sure:
write.table(foo,file="../bar/baz.txt")
Or you can use absolute paths - nomenclature will depend on your operating system.

Related

Read a file in R without changing the working directory

How can others who run my R program read a file(eg: csv) used in my R code without having to change the working directory in setwd()?
I will suggest you use the here() function in the here package in your code like this:
library(here)
Data1 <- read_csv(here("test_data.csv"))
read.csv has a file argument and if I were to quote from the inbuilt R help about file:
If it does not contain an absolute path, the file name is relative to
the current working directory, getwd().
So, providing the absolute path of the file inside the file argument solves this problem.
In Windows
Suppose your file name is test.csv and it's located in D:\files\test_folder (you can get the location of any file from its properties in Windows)
For reading this file you run:
df<-read.csv('D:\\files\\test_folder\\test.csv')
or
df<-read.csv('D:/files/test_folder/test.csv')
Suggested reading: Why \\ instead of \ and Paths in programming languages
Haven't used R in Linux but maybe Getting a file path in Linux might help
Read from web
Just type in the web address of the dataset in the file attribute. Try:
df<-read.csv('https://raw.githubusercontent.com/AdiPersonalWorks/Random/master/student_scores%20-%20student_scores.csv')
Note: This link contains a list of 25 students with their study hours and marks. I myself used this dataset for one of my earlier tasks and its perfectly safe

"../" relative path directory not working R

I often have to work with shared data/code from Dropbox, and all of the files are usually loaded in as df <- import("../data/branch/file_name.csv")
However, this never loads on my computer, so I always have to type in my full directory as df <- import("C:/Users/Name/Dropbox/Folder1/Folder2/data/branch/file_name.csv")
Which makes it difficult for others to reproduce the code. Is there any way to fix this so that R can read the "../" part properly? I always get this error: Error: path does not exist: ../data/branch/file_name.csv
(I used the import function as an example but this problem occurs with other packages or loading functions as well)
I've also tried using "~/" but the problem persists. The shared code I work with always uses "../" though so I'd prefer a solution that gets that to work instead so that I don't have to change the original script each time I need to use it.
Thank you very much.
Edit: Despite the conversation below, I am still having trouble with this. I tried setting the working directory and then using "../" and it sometimes works for read_xls() (it was working a few hours ago, not anymore, depsite doing the exact same thing and setting the same working directory) but not for rio::import() or other reading functions. I've even tried setting my working directory to the exact same folder and using "./" but no luck. Errors now say "Cannot open the connection" or "No such file"
You can try setting your working directory(wd) to the current folder first, then use read.csv to import the data.
To set the working directory, first obtain the current directory using rstudioapi::getActiveDocumentContext()$path then use setwd() to set the wd to this path.
Then use whatever function to import your data.
For example, let's say your R code is saved in the "branch" folder, then the following code should work just fine:
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
mydata <- read.csv("./file_name.csv")
head(mydata)
Otherwise, if your R code was saved in a subfolder under Folder2 called code such that your R script's directory is: "C:/Users/Name/Dropbox/Folder1/Folder2/code/mycode.R", then the following should work:
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
mydata <- read.csv("../data/branch/file_name.csv")
head(mydata)
It looks like the person you are collaborating with has their working directory set to a separate folder within Folder2 (perhaps a folder with all the .R code?). The .. means that the relative path is referencing the next folder up from the working directory (the next folder up is presumably Folder2).
To solve your problem, every time you start working you need to set your working directory to the same folder that your collaborator is using for their working directory. For example, this may be something like setwd("C:/Users/Name/Dropbox/Folder1/Folder2/RCode"). Unfortunately you will have to do that every time you open up the script, but if you do it at the very beginning, then the rest of the code should work.
Working directories can be hard to manage, especially when collaborating. A better solution to the working directory problem is to create a project in R Studio and collaborate on that project using GitHub. If you don't have experience with GitHub, these videos are an approachable resource for helping you get started.

R: importing data impossible (windows)

I used to work with R on my mac and never had any problems.
Now I would like to use it on my work computer (windows). The problem is I can't import any files to start working with them. I tried several options:
mydata<-read.table("c:/temp/myfile.csv",header=TRUE)
mydata<-read.csv("myfile.csv",header=TRUE)
mydata<-read.table("c:/myfile.csv",header=TRUE)
mydata<-read.table("Desktop/myfile.csv",header=TRUE)
I also tried to change / into \ in all variants above.
Nothing seems to work. R displays the command in red, sometimes with a comment "connection can't be opened" or "no such file or directory" (my translation from German).
I tried copying the file I want to open to a different location (desktop, c:, temp), but alas, nothing helps.
Do you have any ideas why I have this problem and how I can solve it? Thanks in advance.
There is a safer way to work with paths; just using file.path().
So, if you're trying to get a file in C:/temp/turtles.csv, then you'd use:
targetFile <- file.path('C:/', 'temp', 'turtles.csv')
read.csv( targetFile, header=TRUE )
Minor point since it showed up on Twitter; DO NOT USE PATHS THAT EXIST ONLY IN YOUR ENVIRONMENT.
Try to keep the data in a path either in or directly under where the script is.
You have three ways to do this with read.csv() function
To avoid inserting actual path you can do it simply nesting function
read.csv(file.choose(),header=TRUE)
it will open pop up for selecting your file just select file from directory
where you have saved it.
Now if you have to insert a path then just get actual location of your file
by
read.csv("C:\path\to\your\file\filename.csv",header=TRUE)
for Example
read.csv("C:\Users\Amway\Desktop\resources.csv",header=TRUE)
Best way is to have your own work space directory
so create a directory by your preferred name and just set that directory as a
R session work space by
setwd("C:\path\to\your\workspace directory\")
check your current directory by
getwd()
now if you want to read a file into R session just copy your file to work
space and just write
read.csv("resources.csv",header=TRUE)
So, it should be like this.
setwd("c:/mydir") # note / instead of \ in windows
Also.
MyData <- read.csv(file="c:/mydir/TheDataIWantToReadIn.csv", header=TRUE, sep=",")
Windows uses the other backslash.
https://www.howtogeek.com/181774/why-windows-uses-backslashes-and-everything-else-uses-forward-slashes/

Calling Skim from inside R

I'm making a simple line in r to automatically open my generated plots.
I output the plots to a file called "plots.pdf" in the same directory as my r file, and at the end i use this two lines to try to open it:
dir <- paste("/Applications/Skim.app/Contents/MacOS/Skim ",getwd(),"/plots.pdf",sep="")
system(dir)
Basically, dir concatenates the full path of the skim app and the full path of the generated plot.
If i run the string stored at dir in a shell it works perfect, it opens the pdf file in Skim, but when i run it with system() from inside R it doesn't work (Skim says 'The document “plots.pdf” could not be opened.').
I believe this is a very little mistake somewhere in the syntax regarding the absolute/relative paths, but haven't managed to find it... Any advice is welcome! (Or a better way to achieve the same)
I found a way to bypass that problem, i just changed the path to Skim for the 'open' command and i let the system to assign the default app for pdf viewing. So:
dir <- paste("open ",getwd(),"/plots.pdf",sep="")
And it works.

How to supply file names with paths to R's read.table function?

What is the correct method for enter data(d=read.table("WHAT GOES HERE IF YOU HAVE A MACBOOK ") if you have a mac computer?
Also what does the error code list below mean:
d=read.table(“Firststatex.notepad”,header=T)
Error: unexpected input in "d=read.table(‚"
Two usage errors:
You don't use data() to read in to R datasets held in external files. data() is an R function to load datasets that are built in to R and R packages. read.table("foo.txt") will return a data frame object from the file "foo.txt", which you can assign to an object within R using the assignment operator <-, e.g.
DF <- read.table("foo.txt")
As for "what goes here...", you need to supply a file system path from the current directory to the directory holding the file you want to read in. If the file "foo.txt" is in the current working directory, you can just provide the file name with extension as I did above. If the file is in another directory you need to supply the path to the file name and the file name, for example if the file "foo.txt" is located in the directory above the current directory, you would supply "../foo.txt". If it were in a directory myData located in the directory above the current directory you could us "../myData/foo.txt". So paths can be relative to the current directory. You can also use the fully qualified path on your file system hierarchy.
An alternative is to use the file.choose() function in place of the file name string. This will allow you to navigate to the file you wish to load interactively using a native file selection dialogue. This is what happens on Windows and I suspect also on Mac; not much different happens on Linux. For example:
DF <- read.table(file.choose())
You should probably look for specific help for your operating system if you are not familiar with how to specify file names and paths.
I get the same error when copying and pasting in the code you provide. The problem comes from the fact that you are using fancy, curly quotes “Firststatex.notepad” rather than one of the three sets of accepted quote marks: ` , ", and '; each of these is acceptable, i) "Firststatex.notepad", ii) 'Firststatex.notepad', and iii) `Firststatex.notepad` Just because the quotes you used look like quotes to you or I, these aren't quotes as far as most computer programs recognise. MS Word often inserts these quotes when you enter " for example, as do many other applications.

Resources