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
Related
I believe a switch to OneDrive is causing some issues in various packages in R due to spaces being incorporated into the file path name. One shown below is the readxl package. Is there a way to get the package to read the spaces in the file path names? Or is it something other than the spaces that I might have overlooked?
Installation and the loading of the library work fine. However, when trying to import an excel file, it only works if I put the file in a location without spaces in the file path. I need the file to be in OneDrive so that it will be backed up.
install.packages("readxl")
library("readxl")
TRENDS_2020 <- read_excel("C:\\Users\\name03\\OneDrive - Specific Details Here (ABC)\\Backup_12_22_2020\\WQ_ALL_FINAL_WEBSITE_PIVOT_TRENDS_2020.xlsx")
I get the following error when running that:
Error in utils::unzip(zip_path, list = TRUE) :
zip file 'C:\Users\name03\OneDrive - Specific Details Here (ABC)\Backup_12_22_2020\TRENDS_2020.xlsx' cannot be opened
The following does work for the same file that I copy and pasted into my C drive:
TRENDS_2020 <-read_excel("C:\\TRENDS_2020.xlsx")
Zip {utils}
treated as if passed to system, if the filepaths contain spaces they must be quoted e.g. by shQuote.
Statistical Data Analysis ETH Zurich
I'm trying to load and plot a picture from that path :
C:\Users\Rayane_2\Desktop\Data\PCB-DATASET-master\PCB-DATASET-master\01_missing_hole_01.jpeg
I tried :
library(imager)
file <- system.file('C:\Users\Rayane_2\Desktop\Data\PCB-DATASET-master\PCB-DATASET-master\01_missing_hole_01.jpeg',package='imager')
im <- load.image(file)
im # file not found
Example of correct run provided by the package :
library(imager)
file <- system.file('extdata/parrots.png',package='imager')
#system.file gives the full path for a file that ships with a R package
#if you already have the full path to the file you want to load just run:
#im <- load.image("/somedirectory/myfile.png")
im <- load.image(file)
plot(im) #Parrots!
Thank you for your help !
Backslashes as directory delimiters must be escaped, you should have seen the error
Error: '\U' used without hex digits in character string starting ""C:\U"
Escape it with another backslash, as in
'C:\\Users\\Rayane_2\\Desktop\\Data\\PCB-DATASET-master\\PCB-DATASET-master\\01_missing_hole_01.jpeg'
Even on windows, though, one can use forward-slashes, so this also works:
'C:/Users/Rayane_2/Desktop/Data/PCB-DATASET-master/PCB-DATASET-master/01_missing_hole_01.jpeg'
system.file only finds files within packages. From ?system.file:
Description
Finds the full file names of files in packages etc.
Arguments
...: character vectors, specifying subdirectory and file(s) within
some package. The default, none, returns the root of the
package. Wildcards are not supported.
This means that all paths provided in the ... arguments need to be relative. One such example is what you put in your question,
system.file('extdata/parrots.png',package='imager')
If you look at the file structure of the installed package (perhaps C:/Users/Rayane_2/R/win_library/4.1/imager), you'll see directories named Meta, R, data, doc, help, html, and (not found in every package) extdata. In that directory must be parrots.png. If a file is found within the specified package's installation directory, then the full (absolute) path of the file you seek is returned.
The value of system.file is that you may not know the full path. This is a good method when (1) doing something programmatically where other users will be using your code; (2) you have multiple library paths in .libPaths() and don't know which one contains the package, and you don't want to check all of them yourself; or (3) you want shorter and more self-documenting code.
If you already know the full path of a file, then system.file doesn't help.
Bottom line, system.file is the wrong function for this.
Just load the file directly.
library(imager)
im <- load.image('C:/Users/Rayane_2/Desktop/Data/PCB-DATASET-master/PCB-DATASET-master/01_missing_hole_01.jpeg')
Use one of these.
For more info see ?Quotes, ?file.path, ?Sys.getenv, ?path.expand. The path.expand example will depend on how your home directory is set but typically it has been set to C:\Users\yourname\Documents .
file.path("C:", "Users", "Rayane_2", "Desktop", "Data", "PCB-DATASET-master",
"PCB-DATASET-master", "01_missing_hole_01.jpeg")
file.path(Sys.getenv("USERPROFILE"), "Desktop", "Data", "PCB-DATASET-master",
"PCB-DATASET-master", "01_missing_hole_01.jpeg")
r"{C:\Users\Rayane_2\Desktop\Data\PCB-DATASET-master\PCB-DATASET-master\01_missing_hole_01.jpeg}"
"C:\\Users\\Rayane_2\\Desktop\\Data\\PCB-DATASET-master\\PCB-DATASET-master\\01_missing_hole_01.jpeg"
# this depends on how your home variable has been set but the
# setting is often such that this works
path.expand("~\\..\\Desktop\\Data\\PCB-DATASET-master\\PCB-DATASET-master\\01_missing_hole_01.jpeg")
"C:/Users/Rayane_2/Desktop/Data/PCB-DATASET-master/PCB-DATASET-master/01_missing_hole_01.jpeg"
# after entering this navigate to file. This will display the path
# to the file and you can then copy and paste it from the
# R console into your code.
file.choose()
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/
I have a collection of functions in a file called some_functions.R and saved in a SVN directory in C:\blah1\blah2\Rcodes\some_functions.R . I have several Rprojects which uses this code file. Say a R project is available in the directory C:\blah1\blah2\Rprojects\project1. I can use hard coded path to refer the file and it works.
source("C:/blah1/blah2/Rcodes/some_functions.R")'
But I would like to set the path as environmental variable.
Looking at How to unfold user and environment variable in R language? and setting the home directory in windows R I add the following line in the RProfile.site file
Sys.setenv(R_CODE_PATH = "C:/blah1/blah2/Rcodes")
and in the project1.Rnw file
source("R_CODE_PATH/some_functions.R")
But the project file can not read the some_functions.R file. I tried with %R_CODE_PATH% without any luck.
Not sure what I'm missing here. Any help is much appreciated.
You retrieve environment variables using Sys.getenv(). Try:
r_code_path <- Sys.getenv("R_CODE_PATH")
Then, for example:
source(paste(r_code_path, "some_functions.R", sep = "/"))
I would use the .Renviron config file to define environment variables. Put it in whatever directory the R command Sys.getenv("HOME") returns and include lines like this:
R_CODE_PATH=C:/blah1/blah2/Rcodes
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.