R Script is not running in Power BI - r

I have seen similar problems to this one but I have not found a solution for this specific case.
Context:
I have some excel files imported into Power BI and I need to do some analysis.
Goal:
I want to run the following code: head(my_df,3)
To achieve that I do the following:
Home -> Transform Data -> Power Query Editor opens -> Click on "my_df" -> "Run R script" -> "output <- head(my_df,3)
This results in the following error message:
DataSource.Error: ADO.NET: R script error. Error in head(raw_booking,
3) : object 'raw_booking' not found Execution halted
Details:
DataSourceKind=R
DataSourcePath=R
Message=R script error. Error in head(raw_booking, 3) : object 'raw_booking' not found Execution halted
I tried head(iris,3) and it worked!!!
What am I missing?

"Run R script" takes the input data from the last applied step in the query and stores it as dataset in the script window.
Therefore, try:
output <- head(dataset, 3)

Related

Problems exporting Power BI with R Script

can you help me?
DataSource.Error: ADO.NET: A problem occurred while processing your R script.
Here are the technical details: Information about a data source is required.
Details:
DataSourceKind = R
DataSourcePath = R
Message = A problem occurred while processing your R script.
Here are the technical details: Information about a data source is required.
ErrorCode = -2147467259
ExceptionType = Microsoft.PowerBI.Scripting.R.Exceptions.RUnexpectedException
This error comes up when I try to export my table using an R script
write.csv2(dataset, file = paste0("C:/Users/Acer/OneDrive/ALLPARTS/ALLPARTSNET_", format(Sys.time(), "%Y%m%d"), ".csv"), row.names=F)
Already tried:
reinstall R, R Studio and Power BI
Is there a solution?
LINK POWER BI FILE
https://1drv.ms/u/s!AnziDWh5m2I1gplLfe9FM2M0EFqDyw
Click on File > Options & settings > Options.
Inside the Options window, you can change the Privacy in the Global or in the Current File section. Click on Privacy.
Select “Ignore the Privacy Levels and potentially improve performance”.
RUN SCRIPT AGAIN!
Power BI often changes the data type upon importing data into Power BI, and this conflicts with how R interprets that data. In my specific case, the error I was getting was the exact same as yours
I fixed this by removing the Applied Step where Power BI changed the data type of all of my columns. It instantly fixed my issue.

Is there a function in R to check if there is an error in r script or in a log?

I'm trying to create an if statement to check whether there is any errors in my R script (or error displayed on the console) and also log files if there are to have "error" in a variable and if there isn't to have "no error" in the same variable.
I looked at is.error() however I want to check if an error is shown on the console or log file.
There is no single-stop solution to the best of my knowledge. There are several things you can try:
1) Incorporate your script into your code and use tryCatch or try to catch any errors. More information on error catching and debugging in R can be found here.
2) Execute your script in the system shell via the system command and inspect output caught by setting intern=TRUE.
You can source the script in a new environment :
testscript <- function(scriptpath) {
tryCatch({
# Tests is the script runs without error
source(scriptpath, local = new.env())
message("Script OK")
},
error = function(cond){
message('Script not OK')
message(cond)
})}
for example, content of script.R :
x <- 1
y <- 2
x + z
testscript('script.R')
Script not OK
object 'z' not found

error using write_csv within R Markdown dowcument

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")

Error when running (working) R script from command prompt

I am trying to run an R script from the Windows command prompt (the reason is that later on I would like to run the script by using VBA).
After having set up the R environment variable (see the end of the post), the following lines of code saved in R_code.R work perfectly:
library('xlsx')
x <- cbind(rnorm(10),rnorm(10))
write.xlsx(x, 'C:/Temp/output.xlsx')
(in order to run the script and get the resulting xlsx output, I simply type the following command in the Windows command prompt: Rscript C:\Temp\R_code.R).
Now, given that this "toy example" is working as expected, I tried to move to my main goal, which is indeed very similar (to run a simple R script from the command line), but for some reason I cannot succeed.
Again I have to use a specific R package (-copula-, used to sample some correlated random variables) and export the R output into a csv file.
The following script (R_code2.R) works perfectly in R:
library('copula')
par_1 <- list(mean=0, sd=1)
par_2 <- list(mean=0, sd=1)
myCop.norm <- ellipCopula(family='normal', dim=2, dispstr='un', param=c(0.2))
myMvd <- mvdc(myCop.norm,margins=c('norm','norm'),paramMargins=list(par_1,par_2))
x <- rMvdc(10, myMvd)
write.table(x, 'C:/Temp/R_output.csv', row.names=FALSE, col.names=FALSE, sep=',')
Unfortunately, when I try to run the same script from the command prompt as before (Rscript C:\Temp\R_code2.R) I get the following error:
Error in FUN(c("norm", "norm"))[[1L]], ...) :
cannot find the function "existsFunction"
Calls: mvdc -> mvdcCheckM -> mvd.has.marF -> vapply -> FUN
Do you have any idea idea on how to proceed to fix the problem?
Any help is highly appreciated, S.
Setting up the R environment variable (Windows)
For those of you that want to replicate the code, in order to set up the environment variable you have to:
Right click on Computer -> Properties -> Advanced System Settings -> Environment variables
Double click on 'PATH' and add ; followed by the path to your Rscript.exe folder. In my case it is ;C:\Program Files\R\R-3.1.1\bin\x64.
This is a tricky one that has bitten me before. According to the documentation (?Rscript),
Rscript omits the methods package as it takes about 60% of the startup time.
So your better solution IMHO is to add library(methods) near the top of your script.
For those interested, I solved the problem by simply typing the following in the command prompt:
R CMD BATCH C:\Temp\R_code2.R
It is still not clear to me why the previous command does not work. Anyway, once again searching into the R documentation (see here) proves to be an excellent choice!

Group_by function not working with R markdown

I'm trying to create a pdf from an R markdown script which says this:
test <- group_by(trials, SubjID)
number <- summarise(test, nsubj=n())
sum(number$nsubj != 12)
but when I click on Knitpdf I get the following error:
error in eval(expr,envir,enclos): could not find function "group_by" Calls:
<Anonymous>...handle->withCallingHandlers->withVisible->eval->eval Execution halted
I have dplyr installed and it works when I send the information to the console but not when I press knitPDF.
You need to add below library import at top in R markdown-
library(dplyr)

Resources