Hiding output from console - r

My code contains a command which is essential for it to run, however it ends up showing the result of this command in the console, i have tried to use suppressWarnings(), suppressMessages(), invisible() and sink() but all of these still show the result.
Here is an example data set and where the problem originates from:
M<-c(1111,1222,1333,1444,1555,1666,1777,2223,6654,9867,1123,1456,2436,6875)
fstAdi <- ets(ts(rep(M,length = length(M)), deltat= 1/4, start = c(8,1)), model = "AAA", damped = FALSE, opt.crit = "mae", ic="aic", lower = c(0, 0, 0, 0), upper = c(0.999, 0.999, 0.999, 0.999), bounds = "admissible", restrict = FALSE)
mae11Ad<-summary(fstAdi)[,"MAE"]
The last line of the code above always shows the summary in the console, which when automating this for a report causing problems. Does anyone know of a command which can stop this happening?
Thankyou
I have found a way to hide it while automating the report, but if anyone knows how to hide it while just running the code to make the process quicker then that would be really helpful anyway :)

The summary method for ets objects is a bit verbose:
> forecast:::summary.ets
function (object, ...)
{
print(object)
cat("\nTraining set error measures:\n")
print(accuracy(object))
}
<bytecode: 0x161d31c8>
<environment: namespace:forecast>
This is pretty bad style, summary methods should return an object with a class and the print method for that class should produce the output.
So you could just call the accuracy method on your object:
> accuracy(fstAdi)[,"MAE"]
[1] 1971.468
which has the advantage of not needing any diversion of output and is more readable.

sink does work, how exactly are you using it? Try for example
M<-c(1111,1222,1333,1444,1555,1666,1777,2223,6654,9867,1123,1456,2436,6875)
fstAdi <- ets(ts(rep(M,length = length(M)), deltat= 1/4, start = c(8,1)), model = "AAA", damped = FALSE, opt.crit = "mae", ic="aic", lower = c(0, 0, 0, 0), upper = c(0.999, 0.999, 0.999, 0.999), bounds = "admissible", restrict = FALSE)
sink(tempfile())
mae11Ad<-summary(fstAdi)[,"MAE"]
sink()

I know that probably looks like a bad-style approach, but this seems to work
sink( tempfile() )
mae11Ad<-summary(fstAdi)[,"MAE"]

Related

R error "attempt to select less than one element in get1index"

I need to estimate some parameters in gp model so I install "kergp" package in R to generate a customized kernel. When I use "mle" function to estimate parameters, I get the error as below:
Error in fitList[[bestIndex]] : attempt to select less than one element in get1index
Here is the code:(where initial_data is a dataframe.)
q4<-q1CompSymm(af, input = "af", cov = "corr", intAsChar = TRUE)
quan<-covTP(k1Fun1 = k1Fun1PowExp,d = 4,cov = "homo",
iso1 = 0,parLower = c(rep(0,9)), parUpper = c(2,2,2,2,Inf,Inf,Inf,Inf,Inf))
inputNames(quan)<-c("hl","hn1","hn2","hn3")
kernel<-covComp(formula = ~quan()*q4())
mle(kernel,
parCovIni = c(rep(0.5,10)),
initial_data$y,select(initial_data,-c('index','y','iw','rts')), F = NULL,
parCovLower = c(rep(0,10)),
parCovUpper = c(2,2,2,2,Inf,Inf,Inf,Inf,Inf,1),
noise = TRUE, varNoiseIni = var(initial_data$y) / 10,
optimFun = "stats::optim",
optimMethod = "BFGS")
I had seen the related document from github(https://github.com/cran/kergp/blob/master/R/methodMLE.R) but still couldn't figure out how this situation happen...
Besides, this error occurred after some iterations if there are any help. Any help would be appreciated. Thanks

Error calling rCBA::fpgrowth: method fpgrowth with signature (DDI)[[Ljava/lang/String; not found

I wrote the R code below to mine with the FP-Growth algorithm:
fpgabdata <- read.csv('../Agen Biasa.csv', header = FALSE)
train <- sapply(fpgabdata, as.factor)
train <- data.frame(train, check.names = TRUE)
txns <- as(train,"transactions")
abrulesfpg = rCBA::fpgrowth(txns, support = 0.25, confidence = 0.5, maxLength = 10, consequent = NULL, verbose = TRUE, parallel = TRUE)
But I get the following error:
Error in .jcall(jPruning, "[[Ljava/lang/String;", "fpgrowth", support, :
method fpgrowth with signature (DDI)[[Ljava/lang/String; not found
These are my data:
The reason you are seeing this error is that the current implementation of the FP-growth algorithm in rCBA requires that you specify a value for the consequent (right hand side).
For example, the following should work, assuming you have sensible thresholds for support and confidence:
abrulesfpg = rCBA::fpgrowth(
txns,
support = 0.25,
confidence = 0.5,
maxLength = 10,
consequent = "SPIRULINA",
verbose = TRUE,
parallel = TRUE
)
I know the OP is likely to have discovered this by now, but I've answered this just in case anyone else encounters the same error.

optim is giving errors from par input where fn = dlogis

I don't know if this should be a new item or not.
I modified the code to be:
library(Rcpp)
rm(list = ls())
datafile <- data.frame(
N = c(1.5, 2.6, 0.555555555555556, 0.535714285714286, 0.418604651162791, 0.557377049180328, 0.463157894736842, 0.762589928057554, 0.583673469387755, 0.528350515463918, 0.649241146711636, 0.534764826175869, 0.556295802798135, 0.250856164383562, 0.202258726899384, 0.351266723598064, 0.226669475458184, 0.1275974583548, 0.0906183368869936, 0.123027510124284, 0.119124595871674)
)
View(datafile)
datafile$a<-dlogis(datafile$N, location = 0, scale = 1, log = FALSE)
datafile does not become 2 columns N rows. It becomes 1 column N+1 rows where the datafile$a becomes one more entry.
I am wondering if anyone would know whether this is the problem my code with dlogis or with optim.
1) Console says I am running dlogis correct.
Console at the same time says I am not running it correctly when I call optim with dlogis. What is the correct way to call optim with the below code?
2) Also, when I call dlogis, I want to find the parameters location and scale so that the errors with the data I feed in can be minimized. Are there other things I should pay attention?
Thank you
library(Rcpp)
rm(list = ls())
datafile <- data.frame(
N = c(1.5, 2.6, 0.555555555555556, 0.535714285714286, 0.418604651162791, 0.557377049180328, 0.463157894736842, 0.762589928057554, 0.583673469387755, 0.528350515463918, 0.649241146711636, 0.534764826175869, 0.556295802798135, 0.250856164383562, 0.202258726899384, 0.351266723598064, 0.226669475458184, 0.1275974583548, 0.0906183368869936, 0.123027510124284, 0.119124595871674)
)
View(datafile)
datafile$a<-dlogis(datafile$N, location = 0, scale = 1, log = FALSE)
View(datafile)
optim(c(datafile$N, 0.5, 0.1), dlogis)
Console gives me this error msg:
> optim(c(datafile$N, 0.5, 0.1), dlogis)
Error in optim(c(datafile$N, 0.5, 0.1), dlogis) :
objective function in optim evaluates to length 23 not 1

theta.sparse error with lorDIF

I was wondering whether anyone can help me out.
I am trying to run a dif analysis on my data but keep getting a theta.sparse error, which I am unsure of how to fix. I would really appreciate any that you can give me.
library(lordif)
dat<- read.csv2("OPSO.csv",header=TRUE)
datgender <- read.csv2("DATA.csv",header=TRUE)
group<-datgender$Gender
sink("outputDIFopso.txt")
gender.difopso <- lordif(dat, group, selection = NULL,
criterion = c("Chisqr", "R2", "Beta"),
pseudo.R2 = c("McFadden", "Nagelkerke", "CoxSnell"), alpha = 0.01,
beta.change = 0.1, R2.change = 0.02, maxIter = 10, minCell = 5,
minTheta = -4, maxTheta = 4, inc = 0.1, control = list(), model = "GRM",
anchor = NULL, MonteCarlo = FALSE, nr = 100)
print(gender.difopso)
summary(gender.difopso)
sink()
pdf("graphtestop.pdf")
plot(gender.difopso)
dev.off()
dev.off()
Error in lordif(dat, group, selection = NULL, criterion = c("Chisqr", :
object 'theta.sparse' not found
Thank you :)
You should check the error line before then. The output will probably say you have no items flagged for DIF. When that's the case you should just run the mirt function and extract theta and ipar objects as necessary.
The author could add some case handling for when compare(flags, flags.matrix) is true. At the very least, it seems a warning is omitted when there are no items with DIF the same way it says
if (ndif == ni) {
warning("all items got flagged for DIF - stopping\n")
}
and there is no case handling when (ndif == 0) although compare(flags, flag.matrix) evaluates to TRUE.
The implications when all or none of the items have DIF is that you would get the same results (generating the same ICC plots, same inference etc) by fitting mirt in the combined sample (no DIF) or two or more mirt models for each group (all DIF). So it's a correct time saving procedure to just bypass when all that breaks down.

R 'fdrtool' package: how to use t statistic

Can one use t statistics from a Student's t-test directly in the fdrtool() function of fdrtool package (ver. 1.2.12)? The paper (Strimmer-K BMC Bioinfo. 2008, 9:303) mentions this but as far as I can see the parameters only recognize "normal", "correlation" and "pvalue". Is there a workaround for a non-statistician ?
I think it's a typo.
I took a look at the source for the fdrtool function and found that the statistic argument first gets passed through match.arg and then to fdrtool:::get.nullmodel.
Then, lo and behold:
args(fdrtool:::get.nullmodel)
# function (statistic = c("normal", "correlation", "pvalue", "studentt"))
# NULL
and indeed there is a fully-implemented case in that function for the student t:
if (statistic == "studentt") {
f0 = function(x, param, log = FALSE) {
return(dt(x, df = param, log = log))
}
F0 = function(x, param) {
return(pt(x, df = param))
}
iqr = function(param) {
return(qt(0.75, df = param) - qt(0.25, df = param))
}
get.support = function() return(c(1, 1000))
}
Now, before I tell you how to access this option, I want to warn you that it's very possible it was disabled on purpose. I can't imagine why, because at first glance it seems like it should work fine. But if you're planning to use this in a research result you ought to document the fact that this was essentially a "hidden" option and that you had to do some hacking to access it. Moreover, I haven't actually tested this on my computer, so beware of typos.
Now, as for that hacking, the easiest way to get this to work would be to first simply type fdrtool into the R console. Then, copy and paste the output to a new R script (or use sink if you're fancy like that). The first few lines should look like:
function (x, statistic = c("normal", "correlation", "pvalue"),
plot = TRUE, color.figure = TRUE, verbose = TRUE, cutoff.method = c("fndr",
"pct0", "locfdr"), pct0 = 0.75)
{
statistic = match.arg(statistic)
...
Then all you have to do is change c("normal", "correlation", "pvalue") to c("normal", "correlation", "pvalue", "studentt"). That is, the first few lines should now look like
function (x, statistic = c("normal", "correlation", "pvalue", "studentt"),
plot = TRUE, color.figure = TRUE, verbose = TRUE, cutoff.method = c("fndr",
"pct0", "locfdr"), pct0 = 0.75)
{
statistic = match.arg(statistic)
...
Finally, reassign this function to fdrtool (don't worry, this won't break the underlying package, it will just act like a "mask" until you remove it with rm):
fdrtool <- function (x, statistic = c("normal", "correlation", "pvalue", "studentt"),
plot = TRUE, color.figure = TRUE, verbose = TRUE, cutoff.method = c("fndr",
"pct0", "locfdr"), pct0 = 0.75)
{
statistic = match.arg(statistic)
...
And run the whole thing or source the script. Then you should be good to go.
Turns out that the maintainer of the package, Korbinian Strimmer, disabled the t-score based function on purpose. The reason for that is that it has been used incorrectly too often.
Prof. Strimmer is a nice guy and responded to my help request quickly and very comprehensively. This is what he suggests: T-scores in practice often do not follow a t-distribution but show rather an over- or underdispersion, which is why you should better use the normal option.
Before that, however, you will have to center your data
z.centered = z-median(z)
fdrtool(z.centered, statistic="normal")

Resources