Output of saved .R files in r - r

I want to save my code in R. I did:
save(Data,file="Code_Data.R")
When I open the file in R again, the code looks like hieroglyphics.
How can I save the code in a way, that I can read the code in an editor or RStudio again?

save outputs a binary copy of the objects you tell it to save, not R code. Because you are naming this file with a ".R" extension, RStudio is blindly trying to open this binary file as R code, and you are seeing the results of that mess.
Technically, the R language doesn't care what the extension of the file is. As long as you know that the file contains, you can load it back in with the command load("Code_Data.R"). However, if you want to get RStudio to recognize that this is actually a file containing binary data and not R code, try saving the file with the canonical ".RData" extension:
save(Data, file="Code_Data.RData")
Using the ".RData" extension will also help you and other programmers who look at your code avoid this confusion in the future.

Related

"The system cannot find the file specified whenever I knit"

Whenever I knit to a PDF in RStudio, the error "The system cannot find the file specified."
Here is the code that I'm using:
##importing data
library(readr)
Quiz1data_2 <- read_csv("C:/Users/erinp/Downloads/Quiz1data-2.csv")
I have restarted RStudio multiple times and I have copied and pasted the exact link that my file is saved to and it's still not working.
What am I not seeing or what am I not thinking?
Some suggestions/questions:
Without knitting, when you run the line reading in the csv, does it work?
Also, are you sure that the error is referring to the data csv? Could it be referring to the (I'm assuming) markdown file you are writing your code in? Have you moved that file since you started working in it?
Are you able to knit other documents to pdf? You need MiKTeX on a windows machine. Does knitting to html work?
I've found R to be a little tricky reading in files. I usually use the base function like this:go to the environment tab>import dataset>from text(base)> (select the file you want, hit open)>(select settings so that the dataframe preview looks right>import. Code that does this will run in the console, and I copy it into my markdown file so that every time it knits, it replicates that successful process.
I figured it out. It's because I forgot to assign a value to an object so it wouldn't knit into a PDF. I made a comment earlier, but it's small so I thought I would add this to the answer section.

Understanding R console vs writing R code in text file

What is the difference between using R console vs writing R code in a text file? I wrote this question on Kaggle but there were no previous questions on this matter.
When you supply code via text file (.R file) you "run the file with R" without visualizing it and it can stop somewhere due to error i.e. (which can be handled, etc.). Also running an .R file with R (for example via .bat file) generates a .Rout file, which is basically a print out of the console and some aditional info like runtime, etc.
If you feed the code in the console, each line is treated independently: even if there is an error you can process an aditional line (if it depends on the failed comand then it will fail also though) and you get to see each result as soon as the comand is run. In comparision to the .R file you will have no copy of the code other than that stored in the session - meaning you will end up needing to save to disk the code you have written if you want it to persist between session. Now you can choose to use whatever text format you like for this task from simple .txt to .docx BUT if you use .R format you can manipulate with notepad++ or the notepad editor and still run/complipe the file with R (via .bat file for example). In case of opting against .R file to store the written code, you will have to feed it to the console again to run.
In R Studio you can open .R files and manage (extend, correct) your code and feed it comand per comand or as a block to the console. So one could say you use .R files to manage you code, having the possiblity to compile/run these .R files directly with R to execute on a button click or repeatedly for example.
Not sure if that is what you are looking for?

Can you save R code files with .RData objects for version control?

There is no version control at my work (we have an outdated, centralized system with sensitive patient information, so we can't save things outside of it). When I save a .RData file from a script, I would like to be able to save the exact version of that .R file with it at that time. Is there a way to do this?
E.g. if I have an R script "run_analysis.R" that has the line
save(data,file='foo.RData')
Is there a way I can do something like
save(data,run_analysis.R,file='foo.RData')
so that if I pull up the data file a year later I'll know exactly what code was used to create it?
you could zip the foo.RData file together with the run_analysis.R file and store the zipped file.
the CRAN package [zip] (https://cran.r-project.org/web/packages/zip/zip.pdf) can be used to create the zip file from within r.

Importing to R an Excel file saved as web-page

I would like to open an Excel file saved as webpage using R and I keep getting error messages.
The desired steps are:
1) Upload the file into RStudio
2) Change the format into a data frame / tibble
3) Save the file as an xls
The message I get when I open the file in Excel is that the file format (excel webpage format) and extension format (xls) differ. I have tried the steps in this answer, but to no avail. I would be grateful for any help!
I don't expect anybody will be able to give you a definitive answer without a link to the actual file. The complication is that many services will write files as .xls or .xlsx without them being valid Excel format. This is done because Excel is so common and some non-technical people feel more confident working with Excel files than a csv file. Now, the files will have been stored in a format that Excel can deal with (hence your warning message), but R's libraries are more strict and don't see the actual file type they were expecting, so they fail.
That said, the below steps worked for me when I last encountered this problem. A service was outputting .xls files which were actually just HTML tables saved with an .xls file extension.
1) Download the file to work with it locally. You can script this of course, e.g. with download.file(), but this step helps eliminate other errors involved in working directly with a webpage or connection.
2) Load the full file with readHTMLTable() from the XML package
library(XML)
dTemp = readHTMLTable([filename], stringsAsFactors = FALSE)
This will return a list of dataframes. Your result set will quite likely be the second element or later (see ?readHTMLTable for an example with explanation). You will probably need to experiment here and explore the list structure as it may have nested lists.
3) Extract the relevant list element, e.g.
df = dTemp[2]
You also mention writing out the final data frame as an xls file which suggests you want the old-style format. I would suggest the package WriteXLS for this purpose.
I seriously doubt Excel is 'saved as a web page'. I'm pretty sure the file just sits on a server and all you have to do is go fetch it. Some kind of files (In particular Excel and h5) are binary rather than text files. This needs an added setting to warn R that it is a binary file and should be handled appropriately.
myurl <- "http://127.0.0.1/imaginary/file.xlsx"
download.file(url=myurl, destfile="localcopy.xlsx", mode="wb")
or, for use downloader, and ty something like this.
myurl <- "http://127.0.0.1/imaginary/file.xlsx"
download(myurl, destfile="localcopy.csv", mode="wb")

Opening an .R files EDIT: gzip files saved with .R extension. Is there any other way to access them?

I have a number of R files with an .R extension. I've tried various ways to see what is inside these file, including Xcode, vim, etc.
What I find is utterly indecipherable. For example, it looks like this Lçæ§o‡dµ’Ò6ÇìùëfiFŒÀ±y2Â8á∫˝É, but pages of it.
Is it safe to say that these files are fundamentally corrupt? Or should I be using R to open these files to see what's actually in them?
EDIT: I've never worked with a file like this. After using load() in R, how would I read the data? I have used
> data <- load("~/filename.RData")
> data
The output is [1] "filename".
EDIT2: It appears these are gzip files saved with an .R extension. I can using load() to read the data into R. Is there any other way I can access these data files?
"filename" is now loaded and it is stored in an object of the same name. You should be able to see what it is inside by running:
filename

Resources