release code error but not in debug or on source - r

My code runs fine but fails in a package
I boiled it down to
wtf<-function(r)
{
require(raster)
stopifnot(class(r) == "RasterLayer")
return(as.matrix(r))
}
When sourced, everything works fine. When the function is part of a package, it fails. It nicely runs in debug mode though, step by step.
library(mypackage)
r <- raster(ncol=6, nrow=6)
r[] <- runif(ncell(r),0,1)
extent(r) <- matrix(c(0, 0, 6, 6), nrow=2)
wtf(r)
# Error in as.vector(data) :
# no method for coercing this S4 class to a vector
# Traceback
# 5 as.vector(data)
# 4 array(x, c(length(x), 1L), if (!is.null(names(x))) list(names(x),
# NULL) else NULL)
# 3 as.matrix.default(r)
# 2 as.matrix(r) at terrain.R#7
# 1 wtf(s)
I'm a bit puzzeled as to why this happens and to how proceed.
The build went fine, the check went clean, so what is going on?
What would be the next question to ask and explore in order to solve the problem?
R version 3.1.1 (2014-07-10)
Platform: x86_64-apple-darwin10.8.0 (64-bit)
locale:
[1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] raster_2.3-0 spdep_0.5-77 Matrix_1.1-4 minerva_1.4.1 gdata_2.13.3 rgdal_0.9-1 sp_1.0-15
loaded via a namespace (and not attached):
[1] boot_1.3-11 coda_0.16-1 deldir_0.1-5 grid_3.1.1 gtools_3.4.1 lattice_0.20-29 LearnBayes_2.15 MASS_7.3-33 nlme_3.1-118 parallel_3.1.1 splines_3.1.1 tools_3.1.1

The traceback shows that the default as.matrix is used, rather than the raster variant. I believe this problem goes away if you add this line to your Namespace file:
import(raster)
Or when you are explicit about which as.matrix you want:
wtf <- function(r) {
stopifnot(inherits(r, "RasterLayer"))
raster::as.matrix(r)
}
Rather than 'manually' testing for class membership, you might consider a more formal (S4) approach:
if (!isGeneric("wtf")) {
setGeneric("wtf", function(x, ...)
standardGeneric("wtf"))
}
setMethod("wtf", signature(x='RasterLayer'),
function(x, ...) {
raster::as.matrix(x)
}
)

Related

Mysterious misspelt R error in assign 'argumemt is not a character' after updating shiny

I am running a shiny app that basically generates SQL code for word-searches within a column 'WordText'.
While the code is working fine for other users running R 3.1.1, it has started throwing errors after I updated shiny. Please note that I was running R 3.2.3 prior to updating shiny and the shiny app worked fine.
ERROR MESSAGE:
Warning: Error in FUN: argumemt is not a character vector
Stack trace (innermost first):
74: lapply
73: paste8
72: HTML
71: assign
70: renderUI [U:\00 R\Shiny - Coursera\08 Tech05/server.R#174]
69: func
68: output$key1A_main
1: runApp
Also this is the first time I'm getting a stack trace! Not sure what triggered these.
The code snippet in question:
########### GENERATING MULTIPLE OUTPUTS ################
#### MULTIPLE KEYWORD DEPENDENCIES !!!
lapply(1:5, function(x){
## Defining as many functions as the number of times displayed - Word Search Generator, (Complaints and Monthly Trends TAB ) X2 - SS + TD
output[[sprintf("key%dA_main",x)]] <- output[[sprintf("key%dA_main_SS_1",x)]] <- output[[sprintf("key%dA_main_SS_2",x)]] <-
output[[sprintf("key%dA_main_TD_1",x)]] <- output[[sprintf("key%dA_main_TD_2",x)]] <- renderUI({
## Main Keyword Case Summary LIKE Statement
assign(sprintf("key%dA_start",x),
if(input[[sprintf("key%dA",x)]]=="") {""}
else {HTML(paste0("(",br(),"WordText like '%",input[[sprintf("key%dA",x)]],"%'",br(),em(sprintf("/* Main Keyword %d */",x)),br()))}
)
## 'AND' and Starting Parenthesis if any dependent keywords
assign(sprintf("key%dA_start_OR",x),
if(nchar(input[[sprintf("key%d_temp_1",x)]],allowNA = TRUE)==0) {" "} else {paste0("AND",br()," (",br()) }
)
## 1st Dependent Keyword Case Summary LIKE Statment
assign(sprintf("key%dA_first",x),
if(nchar(input[[sprintf("key%d_temp_1",x)]],allowNA = TRUE)==0) {" "} else {paste0("WordText like '%", input[[sprintf("key%d_temp_1",x)]], "%'", br())}
)
## All other Dependent Keywords Case Summary LIKE Statments
assign(sprintf("key%dA_other",x),HTML(
lapply(2:10, function(i) {
xy <- input[[sprintf("key%d_temp_%d",x, i)]]
if (nchar(xy,allowNA = TRUE)>0) paste0("OR WordText like '%", xy, "%'", br())
else " "
})#END lapply
))
## Ending Parenthesis if any dependent keywords
assign(sprintf("key%dA_end_OR",x),
if(nchar(input[[sprintf("key%d_temp_1",x)]],allowNA = TRUE)==0) {" "} else {paste0(")",br(),em(sprintf("/* Dependent Keyword(s) for Keyword %d */",x))) }
)
## Ending Parenthesis for entire criteria (Main Keyword + dependent keywords)
assign(sprintf("key%dA_end",x),
if(input[[sprintf("key%dA",x)]]=="") {" "} else {HTML(paste0(br(),")")) }
)
## Collating outputs
HTML(paste0( get(sprintf("key%dA_start",x))
, get(sprintf("key%dA_start_OR",x))
, get(sprintf("key%dA_first",x))
, get(sprintf("key%dA_other",x))
, get(sprintf("key%dA_end_OR",x))
, get(sprintf("key%dA_end",x))) )
})#END renderUI
})#END LAPPLY
The session info is as below:
sessionInfo()
R version 3.2.3 (2015-12-10)
Platform: i386-w64-mingw32/i386 (32-bit)
Running under: Windows >= 8 x64 (build 9200)
locale:
[1] LC_COLLATE=English_Australia.1252 LC_CTYPE=English_Australia.1252 LC_MONETARY=English_Australia.1252 LC_NUMERIC=C LC_TIME=English_Australia.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] scales_0.3.0 ggplot2_2.0.0 RODBC_1.3-12 shinythemes_1.0.1 DT_0.1 shiny_0.13.0
loaded via a namespace (and not attached):
[1] Rcpp_0.12.3 digest_0.6.9 mime_0.4 plyr_1.8.3 grid_3.2.3 R6_2.1.1 jsonlite_0.9.19 xtable_1.8-0 gtable_0.1.2 magrittr_1.5 tools_3.2.3
[12] htmlwidgets_0.5 munsell_0.4.2 httpuv_1.3.3 colorspace_1.2-6 htmltools_0.3

how to apply long only add.distribution parameterset in quantStrat - simpleError in param.combo[[param.label]]

I am applying similar add.distribution rule as in the luxor-demo while my strategy has only a long position.
The whole strategy works, but when applying a parameterset I get following error:
TakeProfitLONG 47 0.047
TakeProfitLONG 47 0.047 result of evaluating expression:
simpleError in param.combo[[param.label]]: subscript out of bounds
got results for task 47 numValues: 47, numResults: 47, stopped: FALSE
returning status FALSE evaluation # 48: $param.combo
I am trying to run a distribution on a simple takeProfit rule (get same result from stopLoss or trailingStop):
.use.takeProfit = TRUE
.takeprofit <- 2.0/100 # actual
.TakeProfit = seq(0.1, 4.8, length.out=48)/100 # parameter set for optimization
## take-profit
add.rule(strategy.st, name = 'ruleSignal',
arguments=list(sigcol='signal.gt.zero' , sigval=TRUE,
replace=FALSE,
orderside='long',
ordertype='limit',
tmult=TRUE,
threshold=quote(.takeprofit),
TxnFees=.txnfees,
orderqty='all',
orderset='ocolong'
),
type='chain',
parent='EnterLONG',
label='TakeProfitLONG',
enabled=.use.takeProfit
)
I am adding the distribution as follows:
add.distribution(strategy.st,
paramset.label = 'TakeProfit',
component.type = 'chain',
component.label = 'TakeProfitLONG',
variable = list(threshold = .TakeProfit),
label = 'TakeProfitLONG'
)
and apply the set:
results <- apply.paramset(strategy.st, paramset.label='TakeProfit', portfolio.st=portfolio.st, account.st=account.st, nsamples=.nsamples, verbose=TRUE)
From my limited debugging it seems that the parameterset is a simple vector whereas in the apply.paramset following function fails:
results <- fe %dopar% { ... }
Here I am too new to R as i am only 4 weeks looking into this, but possibly a call to:
install.param.combo <- function(strategy, param.combo, paramset.label)
might cause the error?
Have to apologize as I am to new, but did anyone encounter this or could help how to apply a distribution to only one item in a long only strategy?
Many thanks in advance!
EDIT 1: SessionInfo()
R version 3.1.2 (2014-10-31)
Platform: i486-pc-linux-gnu (32-bit)
locale:
[1] C
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] lattice_0.20-29 iterators_1.0.7 downloader_0.3
[4] quantstrat_0.9.1665 foreach_1.4.2 blotter_0.9.1644
[7] PerformanceAnalytics_1.4.3574 FinancialInstrument_1.2.0 quantmod_0.4-3
[11] TTR_0.22-0.1 xts_0.9-7 zoo_1.7-12
loaded via a namespace (and not attached):
[1] codetools_0.2-9 compiler_3.1.2 digest_0.6.7 grid_3.1.2 tools_3.1.2
This is the same bug as # 5776. It was fixed for "signal" component types, but not for "chain". It should now be fixed as of revision 1669 on R-Forge.

Post hoc tests with ezANOVA output

I tried to use TukeyHSD(my_anova$aov) but it gives an error:
Error in UseMethod("TukeyHSD") :
no applicable method for 'TukeyHSD' applied to an object of class "c('aovlist', 'listof')"
Google says that there is no way to post hoc with 'aovlist'. But maybe you have any idea about post hoc with ezANOVA output.
Example:
require(ez)
data(ANT)
rt_anova = ezANOVA(data = ANT[ANT$error==0,], dv = rt, wid = subnum, within = cue,return_aov = TRUE)
Try to use multcomp:
require(multcomp)
glht(my_anova$aov, linfct = mcp(cue = "Tukey"))
Error in model.matrix.aovlist(model) :
‘glht’ does not support objects of class ‘aovlist’
Error in factor_contrasts(model) :
no ‘model.matrix’ method for ‘model’ found!
Try to use lme:
require(nlme)
lme_velocity = lme(rt ~ cue, data=ANT[ANT$error==0,], random = ~1|subnum)
Error in .Call("La_chol", as.matrix(x), PACKAGE = "base") :
Incorrect number of arguments (1), expecting 2 for 'La_chol'
> sessionInfo()
R version 2.15.2 (2012-10-26)
Platform: i386-w64-mingw32/i386 (32-bit)
locale:
[1] LC_COLLATE=Russian_Russia.1251 LC_CTYPE=Russian_Russia.1251 LC_MONETARY=Russian_Russia.1251 LC_NUMERIC=C LC_TIME=Russian_Russia.1251
attached base packages:
[1] splines stats graphics grDevices utils datasets methods base
other attached packages:
[1] nlme_3.1-108 multcomp_1.2-15 survival_2.37-2 mvtnorm_0.9-9994 ez_4.1-1 stringr_0.6.2 scales_0.2.3 reshape2_1.2.2 plyr_1.8 memoise_0.1
[11] mgcv_1.7-22 lme4_0.999999-0 Matrix_1.0-10 lattice_0.20-13 ggplot2_0.9.3 car_2.0-15 nnet_7.3-5 MASS_7.3-23
loaded via a namespace (and not attached):
[1] colorspace_1.2-1 dichromat_2.0-0 digest_0.6.2 grid_2.15.0 gtable_0.1.2 labeling_0.1 munsell_0.4 proto_0.3-10 RColorBrewer_1.0-5
[10] stats4_2.15.0 tools_2.15.0
It's not that it's ezANOVA output but that it's a repeated measures ANOVA. The class 'aovlist' is typically for that. TukeyHSD is for independent designs. See this question and related links there.
You don't give any reproducible code, but my guess is that you need to use the package multcomp:
require(multcomp)
glht(my_anova$aov, linfct = mcp(cue= "Tukey"))
(does not work with repeated measures aov, see #John's answer why)
===Update===
Your code works for me (R 2.15.2, nlme 3.1-105, multcomp 1.2-15):
> data(ANT)
> lme_velocity = lme(rt ~ cue, data=ANT[ANT$error==0,], random = ~1|subnum)
> glht(lme_velocity, linfct = mcp(cue= "Tukey"))
General Linear Hypotheses
Multiple Comparisons of Means: Tukey Contrasts
Linear Hypotheses:
Estimate
Center - None == 0 -41.872
Double - None == 0 -47.897
Spatial - None == 0 -86.040
Double - Center == 0 -6.026
Spatial - Center == 0 -44.169
Spatial - Double == 0 -38.143

dataframe does not work inside of a function

When trying to generate a data.frame inside of a function, found that when calling the function, despite everything apparently worked well outside of the function, the data.frame was not generated.
Anybody could tell me how is this possible?
Species=c("a","b","c")
data=data.frame(Species)
df=data.frame(matrix(nrow=length(levels(data$Species)),ncol=43))
rm(df)
f<-function(data)
{
df=data.frame(matrix(nrow=length(levels(data$Species)),ncol=43))
}
f(data)
In my Rstudio no data.frame is generated when calling the function f!
> sessionInfo()
R version 2.14.1 (2011-12-22)
Platform: x86_64-pc-mingw32/x64 (64-bit)
locale:
[1] LC_COLLATE=English_Australia.1252
LC_CTYPE=English_Australia.1252
LC_MONETARY=English_Australia.1252
[4] LC_NUMERIC=C LC_TIME=English_Australia.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] plyr_1.7.1 maptools_0.8-14 lattice_0.20-0 foreign_0.8-48
geosphere_1.2-26
[6] rgdal_0.7-8 outliers_0.14 XML_3.9-4.1 PBSmapping_2.62.34
dismo_0.7-14
[11] raster_1.9-58 sp_0.9-93
loaded via a namespace (and not attached):
[1] grid_2.14.1 tools_2.14.1
This should not be surprising. You haven't specified anywhere in the function what the function should return. This can be done the same way you display an object that you have created at the command prompt in R: type the name of the object. Alternatively, you can use return().
In other words, modify your function as follows (I've changed "df" to "mydf" and "data" to "mydata" to avoid any potential conflicts with base R functions):
f <- function(mydata)
{
mydf = data.frame(matrix(nrow=length(levels(data$Species)), ncol=43))
mydf
## Or, more explicitly
## return(mydf)
}
You can now run it using f(data). However, note that this will just display the output, not assign it to an object. If you wanted it assigned to an object ("mydf", for example) you need to use mydf <- f(data).
There is another option, use <<- in your function.
f <- function(mydata)
{
mydf <<- data.frame(matrix(nrow=length(levels(data$Species)), ncol=43))
## uncomment the next line if you want to *display* the output too
## mydf
}
> rm(mydf)
> ls(pattern = "mydf")
character(0)
> f(data) ## No ouput is displayed when you run the function
> ls(pattern = "mydf")
[1] "mydf"

F-test with plm-model

I want to make a f-test to a plm-model and test for
model <- plm(y ~ a + b)
if
# a = b
and
# a = 0 and b = 0
I tried linearHypothesis like this
linearHypothesis(ur.model, c("a", "b")) to test for a = 0 and b = 0
but got the error
Error in constants(lhs, cnames_symb) :
The hypothesis "sgp1" is not well formed: contains bad coefficient/variable names.
Calls: linearHypothesis ... makeHypothesis -> rbind -> Recall -> makeHypothesis -> constants
In addition: Warning message:
In constants(lhs, cnames_symb) : NAs introduced by coercion
Execution halted
My example above is with code that is a little simplified if the problem is easy. If the problems is in the details is the actual code here.
model3 <- formula(balance.agr ~ sgp1 + sgp2 + cp + eu + election + gdpchange.imf + ue.ameco)
ur.model<-plm(model3, data=panel.l.fullsample, index=c("country","year"), model="within", effect="twoways")
linearHypothesis(ur.model, c("sgp1", "sgp2"), vcov.=vcovHC(plmmodel1, method="arellano", type = "HC1", clustering="group"))
I can't reproduce your error with one of the inbuilt data sets, even after quite a bit of fiddling.
Does this work for you?
require(plm)
require(car)
data(Grunfeld)
form <- formula(inv ~ value + capital)
re <- plm(form, data = Grunfeld, model = "within", effect = "twoways")
linearHypothesis(re, c("value", "capital"),
vcov. = vcovHC(re, method="arellano", type = "HC1"))
Note also, that you seem to have an error in the more complex code you showed. You are using linearHypothesis() on the object ur.model, yet call vcovHC() on object plmmodel1. Not sure if that is the problem or not, but check that in case.
Is it possible to provide the data? Finally, edit your Question to include output from sessionInfo(). Mine is (from quite a busy R instance):
> sessionInfo()
R version 2.11.1 Patched (2010-08-25 r52803)
Platform: x86_64-unknown-linux-gnu (64-bit)
locale:
[1] LC_CTYPE=en_GB.utf8 LC_NUMERIC=C
[3] LC_TIME=en_GB.utf8 LC_COLLATE=en_GB.utf8
[5] LC_MONETARY=C LC_MESSAGES=en_GB.utf8
[7] LC_PAPER=en_GB.utf8 LC_NAME=C
[9] LC_ADDRESS=C LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_GB.utf8 LC_IDENTIFICATION=C
attached base packages:
[1] splines grid stats graphics grDevices utils datasets
[8] methods base
other attached packages:
[1] car_2.0-2 nnet_7.3-1 plm_1.2-6 Formula_1.0-0
[5] kinship_1.1.0-23 lattice_0.19-11 nlme_3.1-96 survival_2.35-8
[9] mgcv_1.6-2 chron_2.3-37 MASS_7.3-7 vegan_1.17-4
[13] lmtest_0.9-27 sandwich_2.2-6 zoo_1.6-4 moments_0.11
[17] ggplot2_0.8.8 proto_0.3-8 reshape_0.8.3 plyr_1.2.1
loaded via a namespace (and not attached):
[1] Matrix_0.999375-44 tools_2.11.1
Could it be because you are "mixing" models? You have a variance specification that starts out:
, ...vcov.=vcovHC(plmmodel1,
... and yet you are working with ur.model.

Resources