Cannot get verbose=FALSE working for "joinCountryData2Map" - r

I am using 'R Presentation' from R Studio to create a slide show for my project. I am using the below code and whatever I do I am not able to get rid of the output message from the code. I do not want the progress message to be included in my presentation slide.
I have the below portion of code in a different chunk , but that did not help me either. I cleared cache and tried all stuffs, but could not get rid of the progress message.
Any idea how to get rid of the output message ?
sPDF <- joinCountryData2Map(subset(world_all, year==year.list[i]),joinCode = "ISO3 ,nameJoinColumn = "country_code" , mapResolution = "coarse",verbose=FALSE)
it generates below output message , which I do not want to show in my presentation slide
154 codes from your data successfully matched countries in the map 0
codes from your data failed to match with a country code in the map 90
codes from the map weren't represented in your data

That did not work either.
Then I went to the source code of that function and found that a "cat" command is being used to print the messages. So, I muted the cat command output using the below method , and it worked !!
capture.output( 'the whole function' , file='NUL' )

Yes; verbose=BOOL controls whether or not the progress messages are printed, not the final message. I'd suggest experimenting with wrapping the call in a call to suppressMessages, and seeing what happens.

Related

RStudio not showing output in Console when using a variable?

Currently learning RStudio but for some reason my Console isn't outputting my code? Not sure if there was a setting I may have toggled but it seems to only affect me when I have a variable in my code?
For example:
when working the ToothGrowth dataset
data("ToothGrowth")
View(ToothGrowth)
This executes and I can view the table of the data in a separate tab.
However, when I try to filter it
data("ToothGrowth")
View(ToothGrowth)
filtered_tg = filter(ToothGrowth, dose=0.5)
View(filtered_tg)
Nothing Returns, a formatted table doesn't open and an empty line is returned in the console window.
This is just one example, even when i try something as simple as
number = 10
number
I would expect, in return;
[1] 10
But console is empty.
Looking for solutions online, I've seen maybe i didn't close a bracket or parenthesis and to include CloseAllConnections() if there was a '+' showing in the console (which there isn't).
Working on rstudio cloud so is there a reset somewhere that I could possibly try?
Thanks for any and all help!
I changed the function as follows:
filtered_tg = filter(ToothGrowth, dose=="0.5")
View(filtered_tg)
After running these commands it was viewed as the table of the data in a separate tab 👇
Output

.Rprofile's search path is not the same as the default one

Consider the two lines below:
Sys.setenv(R_IMPORT_PATH = "/path/to/my/r_import")
foo <- modules::import("foo")
If I execute this code from within an already-established interactive R session, it works fine.
But if I put the same two lines in my .Rprofile and start a new interactive R session, the modules::import line fails with
Error in module_init_files(module, module_path) :
could not find function "setNames"
If I then attempt the following fix/hack
Sys.setenv(R_IMPORT_PATH = "/path/to/my/r_import")
library(stats)
foo <- modules::import("foo")
...then the modules::import line still fails, but with the following
Error in lapply(x, f) : could not find function "lsf.str"
So the idea of patching the missing names seems like it will be an unmaintainable nightmare...
The crucial issue is this: It appears that the search path right after an interactive search session starts is different from the one that an .Rprofile script sees.
Q1: Is there a way that I can tell R to make the search path exactly as it will be when the first > prompt appears in the interactive session?
Q2: Alternatively, is there a way for the .Rprofile to schedule some code to run after the session's default search path is in place?
NB: Solutions like the following:
Sys.setenv(R_IMPORT_PATH = "/path/to/my/r_import")
library(stats)
library(utils)
foo <- modules::import("foo")
...are liable to break every time that the (third-party) modules package is modified.

read_html() induces fatal error in R session

I'm trying to scrape a set of news articles using rvest and boilerpipeR. The code works fine for most of time, however, it crashes for some specific values. I searched online high and low and could not find anyone with anything similar.
require(rvest)
require(stringr)
require(boilerpipeR)
# this is a problematic URL, its duplicates also generate fatal errors
url = "http://viagem.estadao.com.br/noticias/geral,museu-da-mafia-ganha-exposicao-permanente-da-serie-the-breaking-bad,10000018395"
content_html = getURLContent(url) # HTML source code in character type
article_text = ArticleExtractor(content_html) # returns 'NA'
# next line induces fatal error
encoded_exit = read_html(content_html ,encoding = "UTF-8")
paragraph = html_nodes(encoded_exit,"p")
article_text = html_text(paragraph)
article_text = iconv(article_text,from="UTF-8", to="latin1")
This is not the only news piece that ArticleExtractor() returns 'NA' to, and the code was built to handle it as a viable result. This whole snippet is inside a tryCatch(), so regular errors should not be able to stop execution.
The main issue is that the entire R session just crashes and has to be reloaded, which prevents me from grabbing data and debugging it.
What could be causing this issue?
And how can I stop it from crashing the entire R session?
I had the same problem.
RScript crashes without any error message (session aborted), no matter if I use 32bit or 64bit.
The solution for me was to look at the URL I was scraping.
If the URL has some severe mistakes in the HTML-Code-syntax, RScript will crash. It's reproducable. Check the page with https://validator.w3.org.
In your case:
"Error: Start tag body seen but an element of the same type was
already open."
From line 107, column 1; to line 107, column 25
crashed it. So your document had two <body><body> opening Tags. A quick&dirty solution for me was to check first, if read_html gets valid HTML content:
url = "http://www.blah.de"
page = read_html(url, encoding = "UTF-8")
# check HTML-validity first to prevent fatal crash
if (!grepl("<html.*<body.*</body>.*</html>", toString(page), ignore.case=T)) {
print("Skip this Site")
}
# proceed with html_nodes(..) etc
rrscriptrvestsession-abortedweb-scraping

How to display data frame contents inside a function

I want to see the contents of a dataframe that is created inside a function after the dataframe gets created.
Let's say the dataframe is called df in the function. If I just include a line of code like this:
df
I don't get any display to the console. I would get the dump of the dataframe contents outside a function.
Thanks
In an interactive session, when you type the name of an object, like df, R implicitly prints() the object using an appropriate method. It is as if you'd typed print(df), without you actually having to type all those extra characters.
However, there are a few places that this automatic printing is not active
As you found out, this is not active within functions,
Within loops, such a for, while etc.,
When you source a script.
In such cases, you need to explicitly print() an object.
This often catches people out with lattice and ggplot2 plots, which need to be print()ed to get them drawn on the device. but in general use, the user never has to explicitly print() these plots to get something drawn.
You're expecting it to print out because when you type the name of an object into R's shell, you have the representation of the object helpfully echoed back to you. Inside a function, this doesn't happen unless you explicitly tell R to print the information.
If print(df) doesn't work, look for buffered output and be sure it's turned off.
When you type a variable name in the console and hit enter, R silently passes that variable to print. In order to get the same effect from inside a function, you need to explicitly print. In your case:
print(df)
df <- data.frame(x = rpois(100,80))
print_me <- function(x){
print(x)
}
print_me(df)

R - How to create array from console input

Hi all and thanks in advance for all your help.
In R, I'm sending a command to an external Windows program using system(command), which in turn outputs lines (with multiple values per line) that I see directly on the R console. They look something like this:
a,b,c,d,e,f,g,h
1,2,3,4,5,6,7,8
3,4,5,7,1,3,4,9
7,5,3,1,8,1,5,7
What I would like to do is create an array that has the top row as column names and each subsequent row from the input should be the values that go into these columns. Any and all help in making this work would be very appreciated.
This is my first foray into this territory so I'm quite stuck as to how to do it. I've meddled with scan(), pipe() and readLines() but haven't been able to succeed. I have no particular attachment to system(command), any function that will run the executable that will give me the output I need is fine by me if it helps achieve what I want.
The comment made by user1935457 did the trick.
read.table(text = system(command, intern=TRUE), sep = ",", header=TRUE)

Resources