error using write_csv within R Markdown dowcument - r

When inputting
write_csv(MyComplicationData,"Data/MyComplicationData.csv")
as part of a .Rmd file, I get the following error when trying to knit the document:
Error in open.connection(path, "wb") : cannot open the connection
Calls: ... write_delim -> stream_delim -> open.connection
Execution halted
When I input the same command from the console, it works without a problem.
MyComplicationData is a tibble with 4812 observations of 7 variables.

You can use the getwd() command that return your working directory if the directory in which you want to save it is inside, otherwise you should give the entire path.
It would give something like this :
write_csv(MyComplicationData,paste(getwd(),"/Data/MyComplicationData.csv", sep = "")
or
paste0(getwd(),"/Data/MyComplicationData.csv")

Related

RStudio knit button error for download multiple files in RMarkdown file

download.file function for multiple files works fine in console. It will return error when I click knit in RStudio to compile the code as a chunk of rmarkdown file.
Here is an example Rmd file and the code is
options(timeout=600)
# Download demo data from figshare
name <- c('1.mzML','2.mzML')
url <- c("https://ndownloader.figshare.com/files/25521071","https://ndownloader.figshare.com/files/25521074")
download.file(url, name)
The code works fine in the console and will download two files. However, it will generate error in Rmd files when click knit in RStudio and the error is:
Quitting from lines 10-15 (download.Rmd)
Error in download.file(url, name) :
'url' must be a length-one character vector
Calls: <Anonymous> ... withCallingHandlers -> withVisible -> eval -> eval -> download.file
Execution halted
A temporary solution is using for loop:
options(timeout=600)
# Download demo data from figshare
name <- c('1.mzML','2.mzML')
url <- c("https://ndownloader.figshare.com/files/25521071","https://ndownloader.figshare.com/files/25521074")
for(i in c(1:2)){
download.file(url[i], name[i])
}
I am sure it's not an issue from knitr package because the following code will work:
knitr::knit('download.Rmd')
However, I wonder why download.file doesn't work for multiple files in RStudio by clicking knit button?

Code runs fine in R but Knit shows an error

I'm having a problem with the following code in an Rmd file, the problem is that if I run the commands in the console, the code runs perfectly fine, and also there is no mistakes in the syntax, I have change several styles but I'm still receiving the same error when I knit the file.
Raw_Data96_11$EVTYPE <- as.character(Raw_Data96_11$EVTYPE)
List_Events <- count(Raw_Data96_11, vars = "EVTYPE")
List_Events <- arrange(List_Events,desc(n))
List_Events <- mutate(List_Events, percentage = trunc((100*(n/653530))))
Top_10_Events <- List_Events[1:10,2:3]
I had to change the syntax for count, when I run the command in the console, I did not had to use vars, but now I cannot run the command arrange, this is the error :
Quitting from lines 98-117 (PA_2_Reproducible_Research.Rmd)
Error in order(List_Events$n) : argument 1 is not a vector
Calls: ... withVisible -> eval -> eval -> arrange -> eval -> eval -> order
Execution halted
I have included the libraries in that chunk but I'm still receiving an error, does anyone know what is going, is it the syntax or what else do I need to do?

Saving text file in the data folder of an R package

I am trying to save a text file in the data folder of a private package I am developing.
I tried the following:
my_text <- “Some text string”
save.RDS(my_text, file = “C/…./package_name/data/mytext.rda”)
When I try to build the document, I get the error:
Error in FUN(X[[i]], ...) :
bad restore file magic number (file may be corrupted) -- no data loaded
Calls: suppressPackageStartupMessages ... <Anonymous> -> load_all -> load_data -> unlist -> lapply -> FUN
In addition: Warning message:
file mytext.rda' has magic number 'X'
Use of save versions prior to 2 is deprecated
Execution halted
Exited with status 1.
What could I do to save the text?
Library(readr)
write_rds(x = my_text, path = "C/…./package_name/data/mytext.rda")
try this.
Best way is using devtools::use_data(my_text, internal = TRUE) as mentioned by #PoGibas.

Knitting returns parse error

In attempting to knit a PDF. I'm calling a script that should return two ggplots by calling the chunk:
```{r, echo=FALSE}
read_chunk('Script.R')
```r
But receive the error
processing file: Preview-24a46368403c.Rmd
Quitting from lines 9-12 (Preview-24a46368403c.Rmd) Error in
parse(text = x, srcfile = src) : attempt to use zero-length
variable name Calls: <Anonymous> ... <Anonymous> -> parse_all ->
parse_all.character -> parse Execution halted
The script on its own runs and returns the two plots, but won't return them when knitted.
Similarly attempted to use source()
But got a similar error
Quitting from lines 7-10 (Preview-24a459ca4c1.Rmd) Error in
file(filename, "r", encoding = encoding) : cannot open the
connection Calls: <Anonymous> ... withCallingHandlers -> withVisible
-> eval -> eval -> source -> file Execution halted
While this does not appear to be a solution for you, this exact same error message appears if the chunk is not ended properly.
I experienced this error and traced it to ending chunk with `` instead of ```. Correcting the syntax of the chunk solved the problem I experienced with the same error message as you.
Are you sure that knitr is running from the directory you think it is? It appears that it is failing to find the file.
use an absolute path, if that fixes it, you've found your problem
once you've done that, you can use opts_knit$set(root.dir = "...") -- don't use setwd(.) if you want it (the cwd) to be maintained.
Knitr's default is the directory of the .Rmd file itself.
It may have to do with the "r" at the end of the triple backquotes demarcating your code chunk. There should be nothing after the triple backquotes, but I think the problem is specifically that the letter is "r".
The issue stems from the fact that R markdown processes backquoted statements starting with r as inline code, meaning it actually runs whatever is between the backquotes.
I had similar issues writing a problem set in an Rmd with this statement, which had backquoted text intended to be monospace but not run as inline code:
Use sapply or map to calculate the probability of a failure rate over r <- seq(.05, .5, .025).
When I knit the document, I got opaque error messages saying I had an improper assignment using <-. It was because instead of just displaying the backquoted statement in monospace, r <- seq(.05, .5, .025) was actually processed as R inline code of <- seq(.05, .5, .025)...thus the improper assignment error. I fixed my error by changing the variable name from r to rate.
The actual text of the error message in your question might refer to whatever follows your code chunk, as the knitting process is probably trying to run that as code. In this case, just removing that stray r at the end of the code chunk should fix the error.
You should use the following similar syntax, I had the same exact issue but got it fixed:
```{r views}
bank.df <- read.csv("C:/Users/User/Desktop/Banks.csv", header = TRUE) #load data
dim(bank.df) # to find dimension of data frame
head(bank.df) # show first six rows
```
the ``` has to be in the end of the line.
In my case was that I finished the code with four comas, not three . Check this and If you finished with four comas too, try to delete one of them.

Error in R. Error in gsub("(?<=\n)(?=.|\n)", continue, x, perl = TRUE) :

I am encountering an error in R that I cannot seem to figure out. I am creating an R markdown document where I read in an a csv table using this code.
iati <- read.csv(file="/filepath/IATI_NGOS.csv",head=TRUE,sep=",")
and then using ggplot2 I create a plot using the following code.
figure_one <- ggplot(iati, aes(iati$reporting.org))+
geom_bar(fill="blue")+
ylab("Total Activities")+
xlab("NGO Reporting Organizations in IATI")+
ggtitle("Total Number of Activities compared to each NGO Reporting Organization in IATI")+
coord_flip()
When I try to call figure_one in the R markdown I get the following error:
Quitting from lines 44-55 (NGO_IATI.Rmd)
Error in gsub("(?<=\n)(?=.|\n)", continue, x, perl = TRUE) :
input string 1 is invalid UTF-8
Calls: <Anonymous> ... paste -> comment_out -> line_prompt -> paste -> gsub
In addition: Warning message:
In grep("\n", message) : input string 1 is invalid in this locale
Execution halted
When I run this code in a regular R script I have absolutely no issues. I have search for some answers but can't figure it out.
Thanks!
I ended solving my issue by just doing a fresh install of R and Rstudio on my local machine. I think the recent update to Yosemite on my local environment created a lot of issues with the TeX plugin I had installed for R markdown.
I get the same question when I knit my rmarkdown document and find **encoding is the cause.
When you use functions like read.csv, fread or read_csv, you will read the column name.
If column names are in other languages, like Chinese, the problem will easily happen.
Or you rmarkdown works on Windows, but the encoding bug happens on Mac, a different environment.
The temporal solution is to rename the column name in English and resave the data files.
Here is the pseudocode in R to show my idea.
library(data.table)
library(tidyverse)
fread('yourfile.csv',encoding = 'UTF-8') %>%
purrr::set_names(c('x1','x2','x3')) %>%
write_excel_csv('yourfile_2.csv')
Here the new file yourfile_2.csv is fine to rmarkdown knit without encoding problems happening.

Resources