Erratic behaviour of traceback() with Rstudio: different output every time - r

I use RStudio; I have script1 importing script2 with source ; a function in script2 causes an error. The first time it happens, Rstudio tells me that script 1 at row x caused an error in script2 at row y. If I rerun it, it only tells me about the error in script2. Why? This can make debugging much more painful than it needs to be.
More in detail:
I have a myfun.R file which contains this function (of course this is just a toy example):
sum_2_nums <- function(x,y) {
out <- x + y
return(out)
}
I then import the function into another file using source:
source("myfun.R")
mysum <- sum_2_nums(3,"hello")
RStudio is set to debug -> on error -> error inspector. When I run the code above, I see:
which tells me that an error in myfun.R, row 12 was caused by try_traceback.R, row 13. Great.
However, if I run the script again, I get:
i.e. the error no longer gets traced back to try_traceback.R. I need to type traceback() in the console to see that. Why? The different behaviour the second time really puzzles me. This makes debug needlessly more painful than it needs to be! Is there a way to avoid it?
Note this questions is not a duplicate of this: they may look similar but the answer given there of using echo=TRUE or verbose=TRUE does not address my point about tracing the error to the first .R file.
I saw the same question here, but it remains unanswered.
Edit
To clarify, in answer to some comments:
like I said, if I click on Debug -> on Error -> I see that "error inspector" is ticked.
if I type options(error=function()traceback(1)) in the console, nothing happens on screen, but "error inspector" becomes deselected
I do not have anything else in my code. It is a toy example with only the lines I have shown, and nothing else. I do not know what else I can clarify - any guidance would be most appreciated.
I am very new to R. I use Python for data analysis but am curious to understand about R. I had heard that debugging was much more cumbersome in R and wanted to try for myself. Let's say I am not going to invest a lot of my time learning R if even only tracing back such a banal error is so problematic, so I'd like to understand if I am doing something wrong, or debugging and tracing back are always like this in R
when I say "run" I mean I click the "source" button in RStudio (the button next to "run"
sessionInfo() shows:
sessionInfo() R version 3.5.3 (2019-03-11) Platform:
x86_64-w64-mingw32/x64 (64-bit) Running under: Windows >= 8 x64 (build 9200)
Matrix products: default
locale: [1] LC_COLLATE=English_United Kingdom.1252 LC_CTYPE=English_United Kingdom.1252
[3] LC_MONETARY=English_United Kingdom.1252 LC_NUMERIC=C
[5] LC_TIME=English_United Kingdom.1252
attached base packages: [1] stats graphics grDevices utils datasets methods base
loaded via a namespace (and not attached):
[1] compiler_3.5.3 tools_3.5.3 yaml_2.2.0
Edit #2 (in reply to duckmayr's answer)
Let's maybe take a step back. In Python I am used to always seeing a rather detailed traceback of what called what when there is an error. E.g. when I see something like this, I find it very helpful:
The first screenshot I posted of R studio is quite similar, and similarly helpful. So my expected output would be to get the full traceback every single time the error occurs.
Why? Because that's most helpful to me; what would possibly be the advantages of NOT showing it every time? I don't get it.
Are you instead saying that it is by design that the full traceback is not listed every time? If so:
Why? Is there a fundamental reason I am missing? Is there any scenario where this makes more sense than what I am used to with Python?
Is this documented anywhere? I couldn't find it.
Is there a way to get the full traceback every single time? A setting to change? Would exiting and reopening RStudio do?
Yes, I understand I can always type traceback(), but Python's behaviour of showing the full traceback every single time is much more convenient - I genuinely fail to see what the upside of showing the traceback only the first time would be.

I find it somewhat difficult to get precisely what behavior you are wanting RStudio to give you, but it may help you if I post some information about what is expected.
The full traceback is not listed every time: In my experience, RStudio only automatically prints the full traceback the first time a function is executed in its current form. If you change your code, then the very next call should also automatically print the full traceback. This behavior may or may not be automatically configurable. However, more importantly:
The R functions traceback() and debug() are always available to you, regardless of RStudio's settings! So, the first time I source your script, I see:
Then if I source your script with nothing else changed, I get:
> source('~/try_traceback.R')
Error in x + y : non-numeric argument to binary operator
But, this is no problem; I can just run:
> traceback()
5: sum_2_nums(3, "hello") at try_traceback.R#2
4: eval(ei, envir)
3: eval(ei, envir)
2: withVisible(eval(ei, envir))
1: source("~/try_traceback.R")
I could also use debug(sum_2_nums) to re-run the function with debug.
Additionally, if I change sum_2_nums() in myfun.R to the following:
sum_2_nums <- function(x,y) {
cat("")
out <- x + y
return(out)
}
I again see
when I try to source your script.
So you may disagree, but I do not find debugging to be difficult in R, just remember the functions traceback() and debug() and you'll be alright.

Related

Error with a "Selection: " prompt

I have a weird recurring error and I am hoping to get some help here. The issue is that R would break into an error prompt (see below) whenever I refer to a nonexistent function the moment I type ( following the incorrect function name (and before I even hit enter):
> asdf(
Selection:
The word Selection would be in purple (prompt color, as set in R preferences). At this point I have to enter 0 to go back to the regular prompt. Entering other numbers does not give any useful information as in traceback.
There are various ways that can lead to this. However, I have not been successful in replicating this from a --vanilla launch (while this suggests it's something with my profile, I haven't been able to isolate the cause). And even if I launch with my usual profile I would not see it when I first launch R, and it would take some time before this happens.
Once I see this error happens once, I would be able to consistent reproduce it until I restart R.
I can also trigger the error by selecting characters.
> xx <- 1
> xx
(right now the cursor is right behind the last x in xx) So far so good, but now if I try to select the last x (either by using the trackpad, or by pressing shift-left-arrow key) R would break into the same error.
In the status bar at the bottom of the R console window I would see
executing: try(gsub('\\s+','',paste(capture.output(print(args(x))),collapse='')),silent=TRUE)
I have R 3.2.2 on Mac OS X (10.11), but I have seen this error for a long time (I think more than a year).
While the error does not lead to any serious problems, it is very annoying. Anyone can give me some idea on how to fix this?

R could not find function "col2rgb"

When I started R it came with the following Error
Error in alpha(fill, alpha) : could not find function "col2rgb"
when I try to compile PDF in knitr I get the same error:
Error in alpha(fill, alpha) : could not find function "col2rgb"
Calls: .First ... grob -> gpar -> validGP -> numnotnull -> match -> alpha
Execution halted
I don't know how to isolate this problem, since it last I used R and no when I start it produces the error. From what I can gather the col2rgb should be in the base package {grDevices}
library(grDevices)
grDevices::col2rgb("white")
[,1]
red 255
green 255
blue 255
Which seems to work fine.
The error is independent of knitr
Anyone know a fix, or can give any suggestion as to how to isolate the problem?
Best Regards
You must have saved your workspace. Almost all experienced R users never do this.... so don't do that in the future.
For now, you'd find an .Rdata or .RData or similar in your working directory/folder and rename it (so if it contains important stuff you can still load(.) it manually afterward.
After that, starting R should not give your message anymore
(the grDevices package is one of the packages that are always loaded in R ((unless you specifically disable that; which may even be difficult in RStudio))).
Found it!
It was due to a source("") of some often used functions that was sourced at startup via the .Rprofile. when i moved the sourcing to after Rstudio had fully started it works - even knitr.

RStudio does not display any output in console after entering code

The problem is that when I run the code, there's no return in the console; I mean it does run the code, but does not return any output.
For example, if I write
v <- c(1, 2, 3, 4, 5)
v
I would expect in return
[1] 1 2 3 4 5
But it's not working.
I have version RStudio Version 0.98.1079 and R Version 3.1.1
Possibility 1 (until the + sign was mentioned): I was wondering if you had been doing a tutorial where they were demonstrating the sink function and you hadn't gotten to the point where it was reversed.
> sink('out.txt') # diverts all output to a disk file
> v <- c(1,2)
> v # output went to file
> sink() # sets the output back to the console
> v
[1] 1 2
Another way would be to call closeAllConnections:
> sink('out.txt')
> v
> v
> closeAllConnections()
> v
[1] 1 2
Possibility 2: To address the lack of response with a "+" showing at the Rstudio console ... that is a sign that the R parser "thinks" the entered text has not completed a full R command. It may indicate that you haven't typed a closing bracket or parenthesis. If typing one or two of those is unsuccessful and you keep getting mor +'s then you may be successful with typing the [esc]-key. If it is showing up immediately after a restart then you should check your code for correctness and make sure that the .Rdata file is deleted from your working directory. If you don't know what that means then you may need to search for the methods appropriate to your operating system. You could also have an error in the code of one of your .rprofile files.
In any case these two possibilities have nothing to do with Rstudio per se and everything to to with the typical behavior of an R console session in pretty much any IDE.
Do the lines still start with a "+"? It is also possible you forgot to close the brackets of a function. Try "}".
I had the same issue and none of the tips mentioned here were working.
Session > Restart R did the trick for me, possibly suggesting that I had a similar problem as andrewH but was not patient enough to wait for R to behave again.
This is a very old question, but I just had the same problem with a different cause, so I thought I would describe it here case it should be useful to someone else. I was getting the regular command prompt, with nothing more, no matter what I typed at the command line. I tried multiple returns, escape, sink, traceback, closeAllConnections (which did give me a response, "error: unexpected ) in (), but then went back to the command prompt and ignored a second traceback).
Anyway after half an hour or so of pulling my hair out, up pops "View(Mid2)". Mid2 is a tibble with 8.5 million observations of 88 numeric variables. I must have tapped it in the environment pane accidentally. I suppose it just took that long for the viewer to render it. I assume that all the other things I did hit at once, because RStudio crashed immediately thereafter.
The interesting thing about this particular version of the problem is what didn't happen. The red stop sign in the upper right of the console window, that lights when R is busy, didn't light. That is unfortunate -- but understandable, if the RStudio viewer is a different process. But also, when my computer is working hard on a really big computation or IO task, the fan usually starts, but it didn't. Don't know why. . I took its absence, incorrectly, to mean no such computation was underway.
If the lines in console are starting with "+".
Save your work and close the 'RStudio' or other tool which you are using and Start it again, it worked for me.
If you are using R Studio Cloud, refresh or re-opening won't work.
Only clue from the above posts or answers is your console will always start with '+'
In my case I tried all possibilities of closing braces.
And ")" worked for me when I typed that into the console and press enter.
sink() function did nothing in R Studio Cloud
A simple mistake might have also caused this problem:
A rather lengthy command left abandoned in the console is blocking the appearance of the result line.
Thus, the console only shows that line, but the result from any code run from the source, will not appear.
To solve this, just switch to the console, remove any remaining command and try again.
Experiencing something like that explained here as an unresponsive console to the R-Code running was just devastating for me when I experienced it. But luckly although I tried every trick explained in this page, it did not work for me. At last I clicked on the "To console" option available just below the Environment, History, Connections, Tutorial Tab on the R Studio. It solved the puzzle for me just now.
The best solution I've found is closeAllConnections and/or sink which almost always work
But as a stop gap measure, View()'ing always works. It's sort of a pain but whatever you wanted to print out, surround by View and you can see it

Non-english special characters in knitr

I am using knitr 1.1. in R 3.0.0 and within WinEdt (RWinEdt 2.0). I am having problems with knitr recognizing Swedish characters (ä, ö, å). This is not an issue with R; those characters are even recognized in file names, directory names, objects, etc. In Sweave it was not a problem either.
I already have \usepackage[utf8]{inputenc} in my document, but knitr does not seem able to handle the special characters. After running knitr, I get the following message:
Warning in remind_sweave(if (in.file) input) :
It seems you are using the Sweave-specific syntax; you may need Sweave2knitr("deskriptiv 130409.Rnw") to convert it to knitr
processing file: deskriptiv 130409.Rnw
(*) NOTE: I saw chunk options "label=läser_in_data"
please go to http://yihui.name/knitr/options (it is likely that you forgot to
quote "character" options)
Error in parse(text = str_c("alist(", quote_label(params), ")"), srcfile = NULL) :
1:15: unexpected input
1: alist(label=lä
^
Calls: knit ... parse_params -> withCallingHandlers -> eval -> parse
Execution halted
The particular label it complains about is label=läser. Changing the label is not enough, since knitr even complains if R objects use äåö.
I used Sweave2knitr() since the file originally was created for Sweave, but the result was not better: now all äåö have been transformed to äpåö, both in the R chunks and in the latex text, and knitr still gives an error message.
Session info:
R version 3.0.0 (2013-04-03)
Platform: i386-w64-mingw32/i386 (32-bit)
locale:
[1] LC_COLLATE=Swedish_Sweden.1252 LC_CTYPE=Swedish_Sweden.1252 LC_MONETARY=Swedish_Sweden.1252
[4] LC_NUMERIC=C LC_TIME=Swedish_Sweden.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] knitr_1.1
loaded via a namespace (and not attached):
[1] digest_0.6.3 evaluate_0.4.3 formatR_0.7 stringr_0.6.2 tools_3.0.0
As I mentioned there are file names and objects with Swedish characters (since that has not been a problem before), and also the text needs to be in Swedish.
Thank you for any help in getting knitr to work outside of English.
I think you have to contact the maintainer of the R-Sweave mode in WinEdt if you are using this mode to call knitr. The issue is WinEdt has to pass the encoding of the file to knit() if you are not using the native encoding of your OS. You mentioned UTF-8 but that is not the native encoding for Windows, so you must not use \usepackage[utf8]{inputenc} unless you are sure your file is UTF8-encoded.
There are several problems mixed up here, and it is unlikely to solve them all with a single answer.
The first problem is label=läser, which really should be label='läser', i.e. you must quote all the chunk labels (check other labels in the document as well); knitr tries to automatically quote your labels when you write <<foo>>= (it is turned to <<'foo'>>=), but this does not work when you use <<label=foo>>= (you have to write <<label='foo'>>= explicitly). But this problem is perhaps not essential here.
I think the real problem here is the file encoding (which is nasty under Windows). You seem to be using UTF-8 under a system that does not respect UTF-8 by default. In this case you have call knit('yourfile.Rnw', encoding = 'UTF-8'), i.e. pass the encoding to knit(). I do not use WinEdt, so I have no idea how to do that. You can hard-code the encoding in the configurations, but that is not recommended.
Two suggestions:
do not use UTF-8 under Windows; use your system native encoding (Windows-1252, I guess) instead;
or use RStudio instead of WinEdt, which can pass the encoding to knitr;
BTW, since Sweave2knitr() was popped up, there must be other problems in your Rnw document. To diagnose the problem, there are two ways to go:
if you use UTF-8, run Sweave2knitr('deskriptiv 130409.Rnw', encoding = 'UTF-8')
if you use the native encoding of your OS, just run Sweave2knitr('deskriptiv 130409.Rnw')
Please read the documentation if you have questions about the diagnostic information printed out by Sweave2knitr().
R-Sweave invokes knitr through the knitr.edt macro, which itself uses the code in knitrSweave.R to launch knit. The knitcommand in this later script is near the top and reads res <- knit(filename).
Following Yihui's suggestion, you can try to replace this command with
res <- knit(filename, encoding = 'UTF-8')
The knitr.edt and knitrSweave.R files should be in your %b\Contrib\R-Sweave folder, where %b is your winEdt user folder (something like "C:\Users\userA\AppData\Roaming\WinEdt Team\WinEdt 7" under Win 7).
Currently, I do not know how we could pass the encoding as an argument to avoid this hard coding solution.
I would suggest to avoid extended characters in file names which can only be sources of problems. Personally, I never use such names.

Input Chinese characters not correctly echoed in ESS

I had this weird encoding issue for my Emacs and R environment. Display of Chinese characters are all good with my .Rprofile setting Sys.setlocale("LC_ALL","zh_CN.utf-8"); except the echo of input ones.
> linkTexts[5]
font
"使用帮助"
> functionNotExist()
错误: 没有"functionNotExist"这个函数
> fire <- "你好"
> fire
[1] " "
As we can see, Chinese characters contained in the vector linkTexts, Chinese error messages, and input Chinese characters all can be perfectly shown, yet the echo of input characters were only shown as blank placeholders.
sessionInfo() is here, which is as expected given the Sys.setlocale("LC_ALL","zh_CN.utf-8"); setting:
> sessionInfo()
R version 2.15.2 (2012-10-26)
Platform: i386-apple-darwin9.8.0/i386 (32-bit)
locale:
[1] zh_CN.utf-8/zh_CN.utf-8/zh_CN.utf-8/C/zh_CN.utf-8/C
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] XML_3.96-1.1
loaded via a namespace (and not attached):
[1] compiler_2.15.2 tools_2.15.2
And I have no locale settings in the .Emacs file.
To me, this seems to be an Emacs encoding issue, but I just don't know how to correct it. Any idea or suggestion? Thanks.
Your examples work for me out of the box. You can set emacs process decoding/encoding with M-x set-buffer-process-coding-system. Once you figure out what encoding works (if any) you can make the change permanent with:
(add-hook 'ess-R-post-run-hook
(lambda () (set-buffer-process-coding-system
'utf-8-unix 'utf-8-unix)))
Replace utf-8-unix with your chosen encoding.
I am not very convinced that the above will help. LinkText in your example displays well, but fire does not, doesn't look like an emacs/ESS issue.
VitoshKa has made the perfectly correct suggestion. I just wanna add more of own findings here, as people may meet different but similar special character problems. Yet they can be solved in the same way.
The root cause is the input encoding setting to the current buffer process. As shown by the M-x describe-current-coding-system command, default buffer process encoding setting was good for output (utf-8-unix) but deteriorated for input:
Coding systems for process I/O:
encoding input to the process: 1 -- iso-latin-1-unix (alias: iso-8859-1-unix latin-1-unix)
decoding output from the process: U -- utf-8-unix (alias: mule-utf-8-unix)
Changing the coding system for input into utf-8-unix, either by 'M-x set-buffer-process-coding-system' or adding the ess-post-run-hook into .emacs like suggested by VitoshKa, would suffice for solving the Chinese character display problem.
The other problem people may meet due to this setting is special character in ESS. When trying to input special characters, you may get the error message, 错误: 句法分析器%d行里不能有多字节字符
, or invalid multibyte character in parser at line %d in English.
> x <- data.frame(part = c("målløs", "ny"))
错误: 句法分析器1行里不能有多字节字符
And with the correct utf-8-unix setting for input coding system of buffer process, the above error for special characters disappears.

Resources