Read line causing a wait for input R - r

I'm a total noob at R and I may have bitten off a little more than I can chew but if you can help me I will appreciate it.
So what i'm trying to do is retrieve the top trending from twitter (working) and then use them as part of a URL to try pull back their definitions. My issue is the readline function seems to wait for me to hit return before it attempts the URL and i'm looking for a way to make it do the rest automagically, please find my code below
definitions <- ""
lapply(X=hashtags,FUN=function(X){
tagdef <- c(tagdefurl,X[[dfPointer]])
tagdef<- paste(tagdef,collapse=" ")
tagdef <- stringr::str_replace(string=tagdef,pattern=" ", replacement="")
definitions <- tryCatch(readline(tagdef),silent=F)
})
tagdef is defined as is supposed to be the list to store the returned definitions in
I've checked all my OAuth nonsense and everything on that side is fine, i'm getting the trends back without issue. Can anyone give me some pointers?

Unfortunately, you might have just stumbled on a case of "user error due to similarly named functions". In R, there is both readline (which reads a line from the terminal (in interactive use)) and readLines (which is used to *read some or all text lines from a connection).
The former expects user input, and the first argument is "prompt", hence the waiting for input.
Remember also that cApItaLiZation matters in R.

Related

Asking for an input and printing in a C interface for R

I'm trying to modify a CRAN package. From what I understand, they use a C interface using .Call().
So I made changes in the C code (can't do it anywhere else since it's in a loop) but I need to ask the user to input an integer.
I read the "Writing R extension" doc and found out that you need to use specific functions as Rprintf() instead of printf().
But I can't seem to find a way to replace scanf() so how can we ask for an input?
And finally is Rprintf() supposed to print in the R console because it is what I'd want but I can't find where it is printed?
Edit:
I'm unable to try it right now but it may seem that using capture_output() may work to get the Rprintf() output. Therefore the only remaining issue would be the scanf() :)
Thanks a lot!

R: Why does fs::dir_copy fail some of the time?

During a process, I need to copy a directory using fs::dir_copy(currentPath, newPath). Some of the time, I get the following error message:
Error in link_copy(links, path(new_path[[i]], path_rel(links, path[[i]])), :
all(is_link(path)) is not TRUE
This only happens some of the time, not always. What's more, if I replace my directory with a manual copy of itself (i.e. manually copy directory, delete original, rename the copy), then my code will work.
Could someone please explain why this could be happening? Is there a way I can sidestep that error once and for all?
This does not answer your question but may help you to further analyse what is going on. One of the great things of R is that you can easily inspect source code. Especially in a situation where unusual things appear to happen, looking at the code may be useful.
In your case, we can inspect the source code of fs::dir_copy and trace back to which code generates the error message. If you type fs::dir_copy (no parenthesis) into the console, R will print the R code of the function (if the function is not primitive). Doing that here will show you that the fs:dir_copy function calls the fs::link_copyfunction. Makes sense, as the error message comes from this function.
We can now print this function with fs::link_copy
This function generates the error message in this line:
stopifnot(all(is_link(path)))
From the error message we know that all(is_link(path)) returns FALSE. Next step is to have a look at the fs::is_link function. Here we see that the error may come from the call to the setNames function, which depends on the fs::file_info function: res <- file_info(path)
Here we see that setNames is called with a condition depending on what the file_infofunction returned:
setNames(!is.na(res$type) & res$type == "symlink", res$path)
This looks unusual as setNames takes an object and a character vector as formals. But then, I am not the developer of these functions ;-)
Perhaps there are issues with the file type on your machine and fs::file_info(path) returns something unexpected under some conditions.

Saving R history from a particular session

I'm an instructor, and my students have expressed interest in a record of the code I run in class. Since this is often off-the-cuff, I would like to have an easy function I could run at the end of class which would save everything I had run in the session. I know savehistory() will save my entire history, but that is not what I'm looking for.
Similar to this question, except I believe I have a pedagogically sound reason for wanting the history, and I'm looking to limit what gets saved on a per-session basis, rather than on the basis of the number of lines.
I think if you invoke R with --no-restore-history (so that history from previous sessions isn't appended to the record for this one) and add
.Last <- function() {
if(interactive())
try(savehistory(paste0("~/.Rhistory_", sys.time())))
}
to your Rprofile, you should get self-contained, and timestamped history files every time R closes naturally.
The .Last function, when defined in the global environment, is called directly before normal close. See ?.Last
NB: this won't preserve your history in the case of a fatal error (crash) in R itself, though that shouldn't come up much in a teaching context.
NB2: the above code will have generated file names with spaces in them. Depending on your OS, this could range from no big deal to hairpulling nightmarescape. If it's a problem, wrap sys.time() with your favorite datetime formatting code, e.g. format(sys.time(), "<format string>") or something from lubridate (probably, I don't actually know as I don't use it myself).
In the development version of rite on GitHub (>= v0.3.6), you can use the sinkstart() function to dump all of your code, all of your results, or both to a little interactive Tcl/tk widget, from which you could then just copy or save the output.
To make it work you can do this:
devtools::install_github("leeper/rite")
library("rite")
sinkstart(print.eval = FALSE, prompt.echo = "", split = TRUE)
## any code here
sinkstop() # stop printing to the widget
That will look something like:
You can dynamically change what is printed in the widget from the context (right-click) menu on the widget. You can also dynamically switch between sinkstart() and sinkstop() if you only want some code and/or results output to there.
Full Disclosure: This is a package I developed.

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

Suppressing some messages in R but leaving others?

I'm an R newbie using RScaLAPACK and every time I spawn a new process grid I get a message.
> sla.gridInit(2)
[1] "RScaLAPACK:Process Grid Initialized "
I'm going to put this line in a function and I don't want my function to be spitting out this message. However- I don't want to just sink("/dev/null") the call because for all I know, something somewhere could go wrong and then I'd be suppressing useful output. Basically, I want it to be silent when it succeeds and loud if it fails. What is the best way to accomplish this?
Any thoughts, including design considerations, are welcome.
edit:
sla.gridInit() isn't returning anything. The code for sla.gridInit just calls print().
edit:
I suppose capturing output is best like in suppress messages displayed by "print" instead of "message" or "warning" in R . At least I will have the output if I want to do something with it.
You can wrap this function in one of the suppress* functions, suppressMessages, suppressWarnings or suppressPackageStartupMessages. See the help pages of those functions for more details.

Resources