Getting rid of an extra "Null" in an R Function - r

I've written a simple function in R (see below) which works well. But, I get an unwanted word: "Null" at the end of the output when I execute the code.
I was wondering how I could modify my current code to remove the the unwanted, extra word "Null" that appears at the end of the output given by this function?
Here is my R code:
postsigma <- function(n,sigma2,b2,mu,mean){
SigPost <- (1/((n/sigma2)+(1/b2)))
MuPost <- ((SigPost/b2)*mu)+((SigPost/(sigma2/n))*mean)
curve(dnorm(x,MuPost,sqrt(SigPost)),xlim=c(0,MuPost+4),ylim=c(0,dnorm(MuPost,MuPost,sqrt(SigPost))+.02),ylab="Density",main=expression("Posterior of "(mu)))
D <- cat("\t","Mu of Posterior:","\t",MuPost,"\n","\t","Sigma of Posterior:",SigPost)
return(D)}
postsigma(200,15,5,2,5)

The NULL is the value of D. R will print this out. Just remove the statement return(D) and it will get rid of the NULL. You might also want to add a linefeed \n to your cat statement
Also there is no reason to save the result of the cat in D. You can leave off D <- as well.

Related

Getting an error writing R function with gsub

Tried copying an old working code which substituted 2 values instead of 3. This isn't working though. Here it is:
Names <- c("Robert", "Mandy", "Mordecai")
Search <-function(find,relace,type){
gsub("find","relace",type)
}
Search("o","ooo", Names) #getting Names vector but no replacements
You need to remove the "'s from the line with the gsub call. Try:
gsub(find,relace,type)

How can I keep toJSON from quoting my JSON string in R?

I am using OpenCPU and R to create a web API that takes in some inputs and returns a topoJSON file from a database, as well as some other information. OpenCPU automatically pushes the output through toJSON, which results in JSON output that has quoted JSON in it (i.e., the topoJSON). This is obviously not ideal--especially since it then gets incredibly cluttered with backticked quotes (\"). I tried using fromJSON to convert it to an R object, which could then be converted back (which is incredibly inefficient), but it returns a slightly different syntax and the result is that it doesn't work.
I feel like there should be some way to convert the string to some other type of object that results in toJSON calling a different handler that tells it to just leave it alone, but I can't figure out how to do that.
> s <- '{"type":"Topology","objects":{"map": "0"}}'
> fromJSON(s)
$type
[1] "Topology"
$objects
$objects$map
[1] "0"
> toJSON(fromJSON(s))
{"type":["Topology"],"objects":{"map":["0"]}}
That's just the beginning of the file (I replaced the actual map with "0"), and as you can see, brackets appeared around "Topology" and "0". Alternately, if I just keep it as a string, I end up with this mess:
> toJSON(s)
["{\"type\":\"Topology\",\"objects\":{\"0000595ab81ec4f34__csv\": \"0\"}}"]
Is there any way to fix this so that I just get the verbatim string but without quotes and backticks?
EDIT: Note that because I'm using OpenCPU, the output needs to come from toJSON (so no other function can be used, unfortunately), and I can't do any post-processing.
To it seems you just want the values rather than vectors. Set auto_unbox=TRUE to turn length-one vectors into scalar values
toJSON(fromJSON(s), auto_unbox = TRUE)
# {"type":"Topology","objects":{"map":"0"}}
That does print without escaping for me (using jsonlite_1.5). Maybe you are using an older version of jsonlite. You can also get around that by using cat() to print the result. You won't see the slashes when you do that.
cat(toJSON(fromJSON(s), auto_unbox = TRUE))
You can manually unbox the relevant entries:
library(jsonlite)
s <- '{"type":"Topology","objects":{"map": "0"}}'
j <- fromJSON(s)
j$type <- unbox(j$type)
j$objects$map <- unbox(j$objects$map)
toJSON(j)
# {"type":"Topology","objects":{"map":"0"}}

readChar from stdin

I would like to read in one character at a time and convert it to a string command to execute once a space is entered.
I tried
con <- file("stdin")
open(con, blocking=TRUE)
while(q!=" "){
#q=scan("",what="", nmax=1)
q=readChar(con,1)
cmd[i]=q;i=i+1
}
eval(cmd)
but I seem to not understand readChar() correctly.
Interesting question, but with a few flaws:
you use q, cmd and i and never assign them which leads to immediate error and program abort on undefined symbols being used in tests or assignments
you test for q at the top of your while loop but never give it a value (related to previous point)
you assign in the vector with i but never set to 1 first
you misunderstand how string concatenation works
you misunderstand how input from the console works, it is fundamentally by line and not by character so your approach has a deadly design issue (and blocking makes no difference)
you terminate the wrong way; your sentinel value of '' still gets assigned.
you open a console and never close it (though that may be ok with stdin)
you grow the result var the wrong way, but that doesn't matter here compared to all the other issues
If we repair the code a little, and use better style with whitespaces, no semicolons and an <- for assignment (all personal / common preferences) we get
con <- file("stdin")
open(con, blocking=TRUE)
cmd <- q <- ""
i <- 1
while (q != " ") {
q <- readChar(con,1)
cmd[i] <- q
i <- i+1
}
print(cmd) # for exposition only
close(con)
and note the final print rather than eval, we get this (and I typed the ls command letters followed by whitespace)
$ Rscript /tmp/marcusloecher.R
ls
[1] "l" "s" " "
$
I suggest you look into readLines() instead.
And now that I checked, I see that apparently you also never accept an answer to questions you asked. That is an ... interesting outcome for someone from our field which sometimes defines itself as being all about incentives...

R split call to funciton over several lines

I wonder if there is a way to split a call to a function in R over several lines, other then using commas or '+' which is not always applicable.
I am basically looking like Python's '\' escape.
For example, I want to display this line:
PromoterIslands$illumina_probes[bins_with_probes]-tapply(CGIP_to_Probe$subjectHits,CGIP_to_Probe$subjectHits,function(x) length(x))
as:
PromoterIslands$illumina_probes[bins_with_probes]
<-tapply(CGIP_to_Probe$subjectHits,CGIP_to_Probe$subjectHits,
function(x) length(x))]
Is there any way to do this?
Thanks in advance
You can just split commands on various lines, no special sign needed.
The command you wrote is almost OK, you just need to put the <- operator on the first line.
So for instance, this is valid R code, and will assign 13 to a
a <-
5 +
8
But this is not
a
<- 5 +
8
Note, however, that this is valid code
a <-
5
+ 8
But would assign 5 to a and print 8.
Assuming you're talking about source (as opposed to desiring to get something to print a particular way), you can break R code in any place that doesn't produce a syntactically complete statement. There is no special character that tells R that the statement isn't complete. In your case, one option is:
PromoterIslands$illumina_probes[bins_with_probes] <-
tapply(
CGIP_to_Probe$subjectHits,
CGIP_to_Probe$subjectHits,
function(x) length(x)
)
You have to leave the <- at the end of the first line, otherwise PromoterIslands$illumina_probes[bins_with_probes] is a syntactically complete statement that would get evaluated. Similarly, on the next line, you have to leave the ( on the same line as tapply otherwise tapply is a syntactically complete statement (returns the contents of the tapply function).
While this doesn't quite answer your question, hopefully you will find there are enough places you can break a line in R that the lack of the special command you are looking for isn't a problem.

Difference between paste and print (affecting result of function)

To start off, I'm not really sure what the difference between paste and print is. But I am using "print" to spit out generic statements and "paste" to spit out statements that use/ reference specific variables.
My issue is that when using paste within a function, I am losing my pasted output if there is anything included in the function following the "paste" statement.
Please see the following three functions:
TS<-5
Example 1- everything works fine
T<-function(){
if(exists("TS"))
{paste("TS= ", TS, sep=" ")}
else
if(!exists("TS"))
{print.noquote("No TS Values")}
}
Example 2- My Problem. When I add anything (in this case another print command) following my "if" statement I will lose my pasted output
T<-function(){
if(exists("TS"))
{paste("TS= ", TS, sep=" ")}
else
if(!exists("TS"))
{print.noquote("No TS Values")}
print("my exsistance removes paste output")
}
Example 3- The same statement placed before the "if" has no negative effect
T<-function(){
print("my exsistance does not remove paste output")
if(exists("TS"))
{paste("TS= ", TS, sep=" ")}
else
if(!exists("TS"))
{print.noquote("No TS Values")}
}
Can someone explain where the conflict is within this function. And better yet how can I work around it so that I can have a paste statement followed by other actions within a function
basically how can I get example #2 to work.
Brownie points- (for sake of visual consistency) when using "print.noquote", is there such a thing as a paste.noquote?
paste concatenates (pastes) strings and returns a character vector, so you can do thing like
paste('a','b', sep = '-')
## [1] "a-b"
print prints values. From ?print
print prints its argument and returns it invisibly (via invisible(x)). It is a generic function which means that new printing methods can be easily added for new classes.
Most classes will have a defined print method (or will use print.default)
You can see the available print methods by typing
methods('print')
In your case
paste("TS= ", TS, sep=" ") returns a character vector, so when this is the result of the function, print.character is used to display the results
In fact, I think you want message not print or print.noquote.
T <- function() {
if (exists("TS"))
{
message(paste("TS= ", TS, sep=" "))
} else if (!exists("TS")) {
message("No TS Values")
}
message("my exsistance removes paste output")
}
paste returns the input concatenated together. When a function returns it calls print on whatever was returned if it isn't stored into a variable. Functions return the last top level call if there is no explicit 'return' or 'invisible' statement.
All of these things add up to what you end up seeing. If paste is the last function called it ends up returning the input concatenated together - which ends up being returned by the function - which ends up being printed since you don't save it into a variable. If you explicitly want something printed it is best to use print or message or cat - they each serve slightly different purposes.

Resources