code
stringlengths
1
13.8M
library(DendSer) if (!("Iyer517" %in% rownames(installed.packages()))) install.packages("Iyer517") library(Iyer517) data(Iyer517) fib <- log(exprs(Iyer517)[,1:12],2) colnames(fib) <- c("0","15m","30m","1hr","2hr","3hr","4hr","8hr","12hr","16hr","20hr","24hr") dm <- 1- cor(t(fib)) d <- as.dist(dm) h <- hclust(d,method="ward") ob <- dser(h,dm,cost=costBAR) ob<-rev(ob) od <- dser(h, ser_weight=rowMeans(fib),cost=costLS) od<-rev(od) mcol <-sequential_hcl(50) dev.new(height=3, width=3);par(mar=c(1,1,1,1)) plotAsColor(dm,ann=F,order=od,useRaster=T,col=mcol) dev.new(height=3, width=3);par(mar=c(1,1,1,1)) plotAsColor(dm,ann=F,order=ob,useRaster=T,col=mcol) breaks <- c(min(fib)-1,seq(-3,3,length.out=30),max(fib)+1) hcol <-diverge_hcl(length(breaks)-1) dev.new(width=2.35) par(mar=c(3,1,1,1)) plotAsColor(fib[ob,],col=hcol,breaks=breaks,useRaster=T) axis(1, at=c(1:12), las=2, labels=colnames(fib)) nc<-10 ccols <- rainbow(nc) clush <- cutree(h, nc) names(clush)<-NULL zz<- tapply(1:nrow(fib),clush[ob],min ) clus<- rank(zz)[clush] dev.new(width=.5) par(mar=c(3,1,1,.5)) plotAsColor(as.matrix(clus),order.row=ob,col=ccols[1:nc],useRaster=T) clusname<-LETTERS[1:nc] z <- nrow(fib) -tapply(order(ob),clus,mean) axis(2,at=z,labels=clusname,las=2,tick=F,line=-.6,cex.axis=.7) dev.new(width=.5) par(mar=c(3,1,1,.5)) plotAsColor(as.matrix(clus),order.row=od,col=ccols[1:nc],useRaster=T) clusname<-LETTERS[1:nc] z <- nrow(fib) -tapply(order(od),clus,mean) axis(2,at=z,labels=clusname,las=2,tick=F,line=-.6,cex.axis=.7) fibm<-aggregate(fib, list(clus),mean) dev.new(width=3.5) m<- rbind(matrix(1:10, 5, 2, byrow = F),c(11,12)) layout(m,widths = c(1,1),heights=c(1,1,1,1,1,.2)) par(mar=c(1,3,0,.3)) par(mgp=c(3, 1, 0)) for (i in 1:nc) { plot(1:12,fibm[i,-1], col=ccols[i],ylim=c(-1.5,2.1),axes=F,pch=20,ann=F) lines(1:12,fibm[i,-1], col=ccols[i]) axis(2, at=c(-1.5,1.5),las=2,cex.axis=.7) mtext(clusname[i],2,line=.75,las=2,cex=.7) abline(h=0,col="grey50") } plot(1:12,fibm[i,-1], col=ccols[i],ylim=c(-1.5,2.1),axes=F,main="",type="n",ann=F) par("mgp" = c(3,-.5,1),"tcl"= .2) axis(3,at=1:12,labels=colnames(fib),las=2,cex.axis=.7) plot(1:12,fibm[i,-1], col=ccols[i],ylim=c(-1.5,2.1),axes=F,main="",type="n",ann=F) par("mgp" = c(3,-.5,1),"tcl"= .2) axis(3,at=1:12,labels=colnames(fib),las=2,cex.axis=.7) mds2 <- cmdscale(d, k=2) dev.new() plot(mds2, pch=clusname[clus], col=ccols[clus], asp=1, main="2-D Classical MDS solution", xlab="Dimension 1", ylab="Dimension 2")
AbForests_CompareForests<-function(list1,list2,DAG,clonal_frequency,scaleByClonalFreq,weight,tie_flag,opt){ metrics_list1<-AbForests_ForestMetrics(list1,DAG,clonal_frequency,scaleByClonalFreq,weight,tie_flag,opt) metrics_list2<-AbForests_ForestMetrics(list2,DAG,clonal_frequency,scaleByClonalFreq,weight,tie_flag,opt) df1<-.CREATE_DF(list1,metrics_list1,1) df2<-.CREATE_DF(list2,metrics_list2,2) df_total<-rbind(df1, df2) iso_info_list1<-sapply(metrics_list1,function(x) x[16]) res_list1 <- lapply(iso_info_list1, function(x) x %>% dplyr::group_by(x$Parent,x$Child) %>% dplyr::slice(which.max(x$Freq))) merged.data.frame_list1 <- Reduce(function(...) merge(..., all=T), res_list1) merged.data.frame_list1<-unique(merged.data.frame_list1[ , -which(names(merged.data.frame_list1) %in% c('Freq'))]) row.names(merged.data.frame_list1) <- NULL merged.data.frame_list1<-merged.data.frame_list1[1:2] iso_info_lis2<-sapply(metrics_list2,function(x) x[16]) res_list2 <- lapply(iso_info_lis2, function(x) x %>% dplyr::group_by(x$Parent, x$Child) %>% dplyr::slice(which.max(x$Freq))) merged.data.frame_list2 <- Reduce(function(...) merge(..., all=T), res_list2) merged.data.frame_list2<-unique(merged.data.frame_list2[ , -which(names(merged.data.frame_list2) %in% c('Freq'))]) row.names(merged.data.frame_list2) <- NULL merged.data.frame_list2<-merged.data.frame_list2[1:2] return(list(combined_df=df_total,isotype_info_rep1=merged.data.frame_list1,isotype_info_rep2=merged.data.frame_list2)) }
"clindata_miss"
circa_single_mixed <- function (x, col_time, col_outcome, col_id, randomeffects = c("k", "alpha", "phi"), period = 24, alpha_threshold = 0.05, nlme_control = list(), nlme_method = "ML", verbose = FALSE, timeout_n = 10000, return_figure = TRUE, control = list()){ if(!requireNamespace("ggplot2", quietly = TRUE) & return_figure){ return(message("Please install 'ggplot2'")) } controlVals <- circa_single_mixed_control() controlVals[names(control)] <- control if(controlVals$period_param){ controlVals$main_params <- c(controlVals$main_params, "tau") } if("tau" %in% controlVals$main_params){ controlVals$period_param=TRUE } randomeffects <- unique(c(randomeffects, controlVals$random_params)) x <- x[c(col_time, col_outcome, col_id)] colnames(x) <- c("time", "measure", "id") if(length(controlVals$decay_params)>0){ p <- append(controlVals$main_params, paste0(controlVals$decay_params, "_decay")) }else{ p <- controlVals$main_params } if(length(setdiff(randomeffects, p)) != 0){ return(message('"randomeffects" should only include the names of parameters\nthat represent rhythmic characteristics in the model.\nThey should be a subset of, or equal to c("k", "alpha", "phi")')) } if(length(randomeffects) == 0){ return(message("If you do not want to include any random effects, than you ought to use 'circa_single' rather than 'circa_single_mixed'")) } if (!class(x$time) %in% c("numeric", "integer")) { return(message(paste("The time variable which you gave was a '", class(x$time), "' \nThis function expects time to be given as hours and be of class 'integer' or 'numeric'.", "\nPlease convert the time variable in your dataframe to be of one of these classes", sep = ""))) } if (!class(x$measure) %in% c("numeric", "integer")) { return(message(paste("The measure variable which you gave was a '", class(x$measure), "' \nThis function expects measure to be number and be of class 'integer' or 'numeric'.", "\nPlease convert the measure variable in your dataframe to be of one of these classes", sep = ""))) } if(!class(period) %in% c("numeric", "integer") & !controlVals$period_param){ return(message(paste0("The period argument must be a number representing the period of the rhythm in hours\n", "If you would like the period to be estimated as part of the model, use:\ncontrol=list(period_param=TRUE)"))) } if(controlVals$period_param & !is.na(period)){ message(paste0("control$period_param is TRUE\n'period=", period, "' is being ignored.\nSet 'period=NA' to avoid this message")) } x$time_r <- x$time*2*pi if(!controlVals$period_param){ x$period <- period }else{ if(is.null(controlVals$period_min) | is.null(controlVals$period_min)){ message(paste0("If you want the model to estimate the period using a parameter,", "you may get faster convergence if you provide an approximate range using 'period_min' and 'period_max' in control()", "\nCurrently assuming period is between: period_min=", controlVals$period_min, "and period_max=", controlVals$period_max)) } } success <- FALSE n <- 0 form <- create_formula(main_params = controlVals$main_params, decay_params=controlVals$decay_params)$formula fixedeffects_formula <- stats::formula(paste(paste0(p, collapse="+"), "~ 1")) randomeffects_formula <- stats::formula(paste(paste0(randomeffects, collapse="+"), "~ 1 | id")) while(!success){ fit.nlme <- try({nlme::nlme(model = form, random = randomeffects_formula, fixed = fixedeffects_formula, data = x, start = unlist(start_list(outcome=x$measure, controlVals=controlVals)), control = nlme_control, method = nlme_method, verbose = verbose)}, silent = ifelse(verbose, FALSE, TRUE) ) if ("try-error" %in% class(fit.nlme)) { n <- n + 1 } else { nlme_coefs <- extract_model_coefs(fit.nlme) V <- nlme_coefs[, 'estimate'] success <- assess_model_estimates(param_estimates=V) n <- n + 1 } if (n >= timeout_n) { return(message("Failed to converge data prior to timeout. \nYou may try to increase the allowed attempts before timeout by increasing the value of the 'timeout_n' argument or setting a new seed before this function.\nIf you have repeated difficulties, please contact me (via github) or Oliver Rawashdeh (contact details in manuscript).")) } } data_rhythmic <- nlme_coefs['alpha', 'p_value'] < alpha_threshold if(!controlVals$period_param){V['tau'] <- period} eq_expression <- create_formula(main_params = controlVals$main_params, decay_params=controlVals$decay_params)$f_equation eval(parse(text=eq_expression)) if(return_figure){ if(data_rhythmic){ fig_out <- ggplot2::ggplot(x, ggplot2::aes(time, measure)) + ggplot2::stat_function(fun = eq, size = 1) + ggplot2::geom_point() + ggplot2::xlim(min(floor(x$time/period) * period), max(ceiling(x$time/period) * period)) + ggplot2::labs(subtitle = "Data is rhythmic", x = "time (hours)") }else{ fig_out <- ggplot2::ggplot(x, ggplot2::aes(time, measure)) + ggplot2::geom_point() + ggplot2::xlim(min(floor(x$time/period) * period), max(ceiling(x$time/period) * period)) + ggplot2::labs(subtitle = "Data is arrhythmic", x = "time (hours)") } } output_parms <- circa_summary(model=fit.nlme, period=period, control=controlVals) if(return_figure){ return(list(fit=fit.nlme, summary=output_parms, plot=fig_out)) }else{ return(list(fit=fit.nlme, summary=output_parms)) } } circa_single_mixed_control <- function(period_param=F, period_min=20, period_max=28, main_params=c("k", "alpha", "phi"), decay_params=c(), random_params=c("k")){ list(period_param=period_param, period_min=period_min, period_max=period_max, main_params=main_params, decay_params=decay_params, random_params=random_params) }
jnt <- function (xj, unique = FALSE, sep) { ifelse(missing(sep) == TRUE, sep <- ", ", NA) if (isTRUE(length(xj) != 0) == TRUE) { if (isTRUE(is.list(xj)) == TRUE) { Xj <- list() jt <- list() length(Xj) <- length(jt) <- length(xj) for (i in seq_len(length(xj))) { if (isTRUE(length(xj[[i]]) != 0) == TRUE) { tmpj <- as.list(xj[[i]]) for (j in seq_len(length(xj[[i]]))) { ifelse(isTRUE("." %in% strsplit(sep, "")[[1]]) == TRUE, Xj[[i]] <- append(Xj[[i]], tmpj[[j]]), Xj[[i]] <- append(Xj[[i]], strsplit(tmpj[[j]], sep)[[1]])) } rm(j, tmpj) Xj[[i]] <- unique(Xj[[i]]) if (length(Xj[[i]]) == 1) jt[[i]] <- Xj[[i]] if (length(Xj[[i]]) > 1) jt[[i]] <- paste(Xj[[i]][1], Xj[[i]][2], sep = sep) if (length(Xj[[i]]) > 2) { for (j in 3:length(Xj[[i]])) jt[[i]] <- paste(jt[[i]], Xj[[i]][j], sep = sep) rm(j) } } else { NA } } rm(i) } else if (isTRUE(is.vector(xj)) == TRUE) { vec <- vector() for (i in seq_len(length(xj))) { ifelse(is.numeric(xj) == TRUE, vec <- append(vec, strsplit(as.character(xj)[i], sep)[[1]]), vec <- append(vec, strsplit(xj[i], sep)[[1]])) } rm(i) if (isTRUE(unique == TRUE) == TRUE) { vec <- unique(vec) } else { vec <- levels(factor(vec)) } if (length(vec) == 1) jt <- vec if (length(vec) > 1) jt <- paste(vec[1], vec[2], sep = sep) if (length(vec) > 2) { for (i in 3:length(vec)) jt <- paste(jt, vec[i], sep = sep) rm(i) } } else { xj } ifelse(isTRUE(is.list(xj)) == TRUE && is.null(attr(xj, "names")) == FALSE, attr(jt, "names") <- attr(xj, "names"), NA) return(jt) } else { xj } }
read.landmarks.amira<-function(file, CoordinatesOnly=TRUE, Verbose=FALSE){ r=read.amiramesh(file, header=TRUE, simplify=FALSE, Verbose=Verbose) headerLines=attr(r,"header") dataDef=attr(r,"dataDef") NumSetLine=grep("NumSets\\s+[0-9]{1,}",headerLines,value=TRUE) if(length(NumSetLine)==0) stop(paste("Unable to establish number of amira landmarks sets in",file)) nSets=as.numeric(sub(".*NumSets\\s+([0-9]{1,}).*","\\1",NumSetLine)) nDataSections=nrow(dataDef) nSectionsPerSet=nDataSections/nSets if(round(nSectionsPerSet)!=nSectionsPerSet) stop(paste("Unable to parse amira landmarks sets",file,":too many data sections!")) if(CoordinatesOnly){ chosenSections=seq(from=1,by=nSectionsPerSet,length=nSets) r=r[chosenSections] } if(length(r)==1) r[[1]] else r } write.landmarks.amira<-function(x, file){ if(is.list(x) && !is.data.frame(x)) l=x else l=list(x) nSets=length(l) nummarkers=sapply(l,nrow) if(length(unique(nummarkers))!=1) stop("Must have just an equal number of markers in paired landmark sets") nummarkers=nummarkers[1] cat(" for(i in 1:nSets){ coordsuffix=ifelse(i==1,"",i) cat("Markers { float[3] Coordinates",coordsuffix," } @",i,sep="","\n",file=file,append=T) } for(i in 1:nSets){ cat("@",i,sep="","\n",file=file,append=T) write.table(l[[i]],col.names=F,row.names=F,file=file,append=TRUE) cat("\n",file=file,append=T) } } read.landmarks<-function(f, ...) { if(grepl("^http[s]{0,1}://", f)) { url=f f=file.path(tempdir(), basename(f)) on.exit(unlink(f)) filecontents=httr::GET(url) writeBin(httr::content(filecontents,type = 'raw'), con = f) } ffs=getformatreader(f, class = 'landmarks') if(is.null(ffs)) stop("Unable to identify file type of:", f) l=match.fun(ffs$read)(f, ...) class(l)=c('landmarks', class(l)) l } write.landmarks<-function(x, file, format='amiralandmarks', ext=NULL, Force=FALSE, MakeDir=TRUE, ...) { fw=getformatwriter(format=format, file=file, ext=ext, class='landmarks') file=fw$file if(!Force && file.exists(file)){ warning(file," already exists; use Force=T to overwrite") return(NA_character_) } if(!file.exists(dirname(file))){ if(MakeDir){ if(!dir.create(dirname(file))) stop("Unable to create ",dirname(file)) } else { stop(dirname(file)," does not exist; use MakeDir=T to overwrite") } } match.fun(fw$write)(x, file=file, ...) invisible(file) }
phyl.pca<-function(tree,Y,method="BM",mode="cov",...){ if(hasArg(opt)) opt<-list(...)$opt else opt<-"ML" if(!inherits(tree,"phylo")) stop("tree should be an object of class \"phylo\".") if(length(strsplit(mode,split="")[[1]])<=2){ message(paste("mode = \"",mode, "\" not a valid option; setting mode = \"cov\"",sep="")) mode<-"cov" } if(all(strsplit(mode,split="")[[1]]==strsplit("correlation", split="")[[1]][1:length(strsplit(mode,split="")[[1]])])) mode<-"corr" else if(all(strsplit(mode,split="")[[1]]==strsplit("covariance", split="")[[1]][1:length(strsplit(mode,split="")[[1]])])) mode<-"cov" else { message(paste("mode = \"",mode, "\" not a valid option; setting mode = \"cov\"",sep="")) mode="cov" } n<-nrow(Y) m<-ncol(Y) if(n>Ntip(tree)) stop("number of rows in Y cannot be greater than number of taxa in your tree") Y<-as.matrix(Y) if(is.null(rownames(Y))){ if(nrow(Y)==n){ print("Y has no names. function will assume that the row order of Y matches tree$tip.label") rownames(Y)<-tree$tip.label } else stop("Y has no names and does not have the same number of rows as tips in tree") } else if(length(setdiff(rownames(Y),tree$tip.label))!=0) stop("Y has rownames, but some rownames of Y not found in tree") C<-vcv.phylo(tree)[rownames(Y),rownames(Y)] if(method=="BM"){ temp<-phyl.vcv(Y,C,1.0) V<-temp$R a<-t(temp$alpha) C<-temp$C } else if(method=="lambda"){ if(opt=="ML") temp<-optimize(f=likMlambda,interval=c(0,maxLambda(tree)),X=Y, C=C,maximum=TRUE) else if(opt=="REML") temp<-optimize(f=remlMlambda,interval=c(0,maxLambda(tree)), tree=tree,X=Y,maximum=TRUE) else if(opt=="fixed"){ if(hasArg(lambda)) lambda<-list(...)$lambda else { cat(" opt=\"fixed\" requires the user to specify lambda.\n") cat(" setting lambda to 1.0.\n") lambda<-1.0 } temp<-list(maximum=lambda,objective=likMlambda(lambda,X=Y,C=C)) } lambda<-temp$maximum logL<-as.numeric(temp$objective) temp<-phyl.vcv(Y,C,lambda) V<-temp$R a<-t(temp$alpha) C<-temp$C } invC<-solve(C) if(mode=="corr"){ Y=Y/matrix(rep(sqrt(diag(V)),n),n,m,byrow=T) V=V/(sqrt(diag(V))%*%t(sqrt(diag(V)))) a<-matrix(colSums(invC%*%Y)/sum(invC),m,1) } es=eigen(V) obj<-list() obj$Eval<-diag(es$values[1:min(n-1,m)]) obj$Evec<-es$vectors[,1:min(n-1,m)] dimnames(obj$Eval)<-list(paste("PC",1:min(n-1,m),sep=""), paste("PC",1:min(n-1,m),sep="")) dimnames(obj$Evec)<-list(colnames(Y),paste("PC",1:min(n-1,m),sep="")) A<-matrix(rep(a,n),n,m,byrow=T) obj$S<-(Y-A)%*%obj$Evec Ccv<-t(Y-A)%*%invC%*%obj$S/(n-1) obj$L<-matrix(,m,min(n-1,m),dimnames=list(colnames(Y),paste("PC",1:min(n-1,m),sep=""))) for(i in 1:m) for(j in 1:min(n-1,m)) obj$L[i,j]<-Ccv[i,j]/sqrt(V[i,i]*obj$Eval[j,j]) if(method=="lambda"){ obj$lambda<-lambda obj$logL.lambda<-logL } obj$V<-temp$R obj$a<-a obj$mode<-mode class(obj)<-"phyl.pca" obj } print.phyl.pca<-function(x, ...){ cat("Phylogenetic pca\n") cat("Standard deviations:\n") print(sqrt(diag(x$Eval))) cat("Loads:\n") print(x$L) if("lambda" %in% names(x)){ cat("lambda:\n") print(x$lambda) } } summary.phyl.pca<-function(object, ...){ cat("Importance of components:\n") sd<-sqrt(diag(object$Eval)) varProp<- diag(object$Eval)/sum(object$Eval) impp<-rbind("Standard deviation"=sd,"Proportion of Variance"=varProp, "Cumulative Proportion"=cumsum(varProp)) print(impp) xx<-list(sdev=sd,importance=impp) class(xx)<-"summary.phyl.pca" invisible(xx) } biplot.phyl.pca<-function(x,...){ to.do<-list(...) if(hasArg(choices)){ choices<-list(...)$choices to.do$choices<-NULL } else choices<-c(1,2) to.do$x<-x$S[,choices] to.do$y<-x$Evec[,choices] do.call(biplot,to.do) } lambdaTree<-function(tree,lambda){ n<-length(tree$tip.label) h1<-nodeHeights(tree) ii<-which(tree$edge[,2]>n) tree$edge.length[ii]<-lambda*tree$edge.length[ii] h2<-nodeHeights(tree) tree$edge.length[-ii]<-tree$edge.length[-ii]+h1[-ii,2]-h2[-ii,2] tree } remlMlambda<-function(lambda,tree,X){ tt<-lambdaTree(tree,lambda) Y<-apply(X,2,pic,phy=tt) V<-t(Y)%*%Y/nrow(Y) logL<-sum(dmnorm(Y,mean=rep(0,ncol(Y)),varcov=V,log=TRUE)) print(c(lambda,logL)) logL } plot.phyl.pca<- function(x,...){ if(hasArg(main)) main<-list(...)$main else main="screeplot" x$sdev<-sqrt(diag(x$Eval)) screeplot(x,main=main) } scores<-function(object,...) UseMethod("scores") scores.default<-function(object,...){ warning(paste( "scores does not know how to handle objects of class ", class(object),".")) } scores.phyl.pca<-function(object,...){ if(hasArg(newdata))newdata<-list(...)$newdata else newdata<-NULL if(!is.null(newdata)){ if(!is.matrix(newdata)) newdata<-as.matrix(newdata) if(ncol(newdata)!=nrow(object$Evec)) stop("Dimensions of newdata incorrect.") n<-nrow(newdata) m<-ncol(newdata) A<-matrix(rep(object$a,n),n,m,byrow=TRUE) V<-object$V if(object$mode=="corr"){ Y<-newdata/matrix(rep(sqrt(diag(V)),n),n,m,byrow=TRUE)-A } else Y<-newdata-A Scores<-Y%*%object$Evec } else { Scores<-object$S } Scores }
context("test_SER_posterior_e_loglik.R") test_that("SER_posterior_e_loglik agrees with version 0.3", with(simulate(sparse=T), { original.res = readRDS('SER_original_res.rds') Eb = rep(1, p) Eb2 = rep(1, p) s2 = s$sigma2 scaledX = set_X_attributes(X) scaledX.sparse = set_X_attributes(X.sparse) dense.res = SER_posterior_e_loglik(scaledX,y,s2,Eb,Eb2) sparse.res = SER_posterior_e_loglik(scaledX.sparse,y,s2,Eb,Eb2) expect_equal(dense.res, original.res) expect_equal(sparse.res, original.res) }))
evaluation.criteria=function(Ypred,Yobs,draw.plot=FALSE){ warning("this function is depreciated, please use now goodness.of.fit") select=!is.na(Ypred)&!is.na(Yobs) Ypred=Ypred[select] Yobs=Yobs[select] Nobs<-length(Yobs) N<-length(Ypred) mean.Yobs<-mean(Yobs,na.rm=TRUE) mean.Ypred<-mean(Ypred,na.rm=TRUE) bias<-mean.Ypred-mean.Yobs var.Yobs<- var(Yobs)*(Nobs-1)/Nobs std.Yobs<-var.Yobs^0.5 std.Yobs var.Ypred<- var(Ypred)*(N-1)/N std.Ypred<-var.Ypred^0.5 std.Ypred SSE<- sum((Yobs-Ypred)^2) SSE MSE<- SSE/Nobs MSE RMSE=MSE^0.5 RMSE bias.Squared<-bias^2 bias.Squared SDSD<-(std.Yobs-std.Ypred)^2 SDSD covBYobs<-cov(Ypred,Yobs)*(Nobs-1)/Nobs r<-covBYobs/(var.Yobs^0.5*var.Ypred^0.5) r LCS<-2*var.Yobs^0.5*var.Ypred^0.5*(1-r) LCS MSE==bias.Squared+SDSD+LCS if( draw.plot){ par(mfrow=c(3,1), cex=1, mar=c(4.5, 4.2, 0.5, 1.2), cex.main=0.75 ) plot(Ypred,Yobs, xlim=range(c(Ypred,Yobs)),ylim=range(c(Ypred,Yobs))) abline(b=1,a=0) plot(Ypred,Yobs-Ypred) abline(a=0,b=0) barplot(c("MSE"=MSE,"Bias^2"=bias.Squared,"SDSD"=SDSD,"LCS"=LCS),main="decomposition of MSE", ylab="unit^2") } EF<- 1 - sum((Yobs-Ypred)^2)/sum((Yobs-mean.Yobs)^2) EF return(data.frame(Nobs=Nobs,mean.Yobs=mean.Yobs,mean.Ypred=mean.Ypred,std.Yobs=std.Yobs,std.Ypred=std.Ypred,SSE=SSE,MSE=MSE,RMSE=RMSE,r=r,bias.Squared=bias.Squared,SDSD=SDSD,LCS=LCS,EF=EF)) }
setMethod("simulate", "yuima.Hawkes", function(object, nsim=1, seed=NULL, xinit, true.parameter, space.discretized=FALSE, increment.W=NULL, increment.L=NULL, method="euler", hurst, methodfGn="WoodChan", sampling, subsampling, ...){ res <- aux.simulatHawkes(object, nsim = nsim, seed = seed, xinit = xinit, true.parameter = true.parameter, space.discretized = space.discretized, increment.W = increment.W, increment.L = increment.L, method = method, hurst = hurst, methodfGn = methodfGn, sampling = sampling, subsampling = subsampling) return(res) } ) aux.simulatHawkes<- function(object, nsim, seed, xinit, true.parameter, space.discretized, increment.W, increment.L, method, hurst, methodfGn, sampling, subsampling){ res <- aux.simulatPPR(object, nsim = nsim, seed = seed, xinit = xinit, true.parameter = true.parameter, space.discretized = space.discretized, increment.W = increment.W, increment.L = increment.L, method = method, hurst = hurst, methodfGn = methodfGn, sampling = sampling, subsampling = subsampling) return(res) } setMethod("simulate", "yuima.PPR", function(object, nsim=1, seed=NULL, xinit, true.parameter, space.discretized=FALSE, increment.W=NULL, increment.L=NULL, method="euler", hurst, methodfGn="WoodChan", sampling, subsampling, ...){ res <- aux.simulatPPR(object, nsim = nsim, seed = seed, xinit = xinit, true.parameter = true.parameter, space.discretized = space.discretized, increment.W = increment.W, increment.L = increment.L, method = method, hurst = hurst, methodfGn = methodfGn, sampling = sampling, subsampling = subsampling) return(res) } ) constHazIntPr <- function(g.Fun , Kern.Fun, covariates, counting.var,statevar=NULL){ numb.Int <- length(g.Fun) Int.Intens <- list() dum.g <- character(length=numb.Int) for(i in c(1:numb.Int)){ dum.g0 <- as.character(g.Fun[i]) dum.g0 <- gsub("(", "( ", fixed=TRUE,x = dum.g0) dum.g0 <- gsub(")", " )", fixed=TRUE,x = dum.g0) if(length(counting.var)>0){ for(j in c(1:length(counting.var))){ my.countOld <- paste0(counting.var[j] ," ") my.countNew <- paste0("(", counting.var[j] ,")") dum.g0 <- gsub(my.countOld, my.countNew, x = dum.g0, fixed=TRUE) my.countOld <- paste0(counting.var[j] ,"[",[email protected]@upper.var,"]") my.countNew <- paste0("(", counting.var[j] ,")") dum.g0 <- gsub(my.countOld, my.countNew, x = dum.g0, fixed=TRUE) } } if(length(covariates)>0){ for(j in c(1:length(covariates))){ my.covarOld <- paste0(covariates[j] ," ") my.covarNew <- covariates[j] dum.g0 <- gsub(my.covarOld, my.covarNew, x = dum.g0, fixed=TRUE) my.covarOld <- paste0(covariates[j] ,"[",[email protected]@upper.var,"]") my.covarNew <- covariates[j] dum.g0 <- gsub(my.covarOld, my.covarNew, x = dum.g0, fixed=TRUE) } } dum.g[i] <- paste("tail(",dum.g0,", n=1L)") } dum.Ker <- as.character(unlist(Kern.Fun@Integrand@IntegrandList)) dum.Ker <- gsub("(", "( ", fixed=TRUE,x = dum.Ker) dum.Ker <- gsub(")", " )", fixed=TRUE,x = dum.Ker) dimKernel<-length(dum.Ker) condIntInKer <- FALSE for(i in c(1:dimKernel)){ if(!condIntInKer) condIntInKer <- statevar%in%all.vars(parse(text=dum.Ker[i])) } if(condIntInKer){ for(i in c(1:length(statevar))){ my.countOld <- paste0(statevar[i] ," ") my.countNew <- paste0( statevar[i] , "ForKernel[CondJumpGrid]") dum.Ker <- gsub(my.countOld, my.countNew, x = dum.Ker, fixed=TRUE) my.countOld <- paste0(statevar[i] ,"[",[email protected]@upper.var,"]") my.countNew <- paste0( "tail(",statevar[i] ,"ForKernel ,n=1L) ") dum.Ker <- gsub(my.countOld, my.countNew, x = dum.Ker, fixed=TRUE) my.countOld <- paste0(statevar[i] ,"[",[email protected]@var.time,"]") my.countNew <- paste0(statevar[i] , "ForKernel[CondJumpGrid]") dum.Ker <- gsub(my.countOld, my.countNew, x = dum.Ker, fixed=TRUE) } } if(length(counting.var)>0){ for(i in c(1:length(counting.var))){ my.countOld <- paste0(counting.var[i] ," ") my.countNew <- paste0( counting.var[i] , "[CondJumpGrid]") dum.Ker <- gsub(my.countOld, my.countNew, x = dum.Ker, fixed=TRUE) my.countOld <- paste0(counting.var[i] ,"[",[email protected]@upper.var,"]") my.countNew <- paste0( "tail(",counting.var[i] ,",n=1L) ") dum.Ker <- gsub(my.countOld, my.countNew, x = dum.Ker, fixed=TRUE) my.countOld <- paste0(counting.var[i] ,"[",[email protected]@var.time,"]") my.countNew <- paste0(counting.var[i] , "[CondJumpGrid]") dum.Ker <- gsub(my.countOld, my.countNew, x = dum.Ker, fixed=TRUE) } } if(length(covariates)>0){ for(i in c(1:length(covariates))){ my.countOld <- paste0(covariates[i] ," ") my.countNew <- paste0( covariates[i] , "[CondJumpGrid]") dum.Ker <- gsub(my.countOld, my.countNew, x = dum.Ker, fixed=TRUE) my.countOld <- paste0(covariates[i] ,"[",[email protected]@upper.var,"]") my.countNew <- paste0("tail(", covariates[i] , ", n=1L ) ") dum.Ker <- gsub(my.countOld, my.countNew, x = dum.Ker, fixed=TRUE) my.countOld <- paste0(covariates[i] ,"[",[email protected]@var.time,"]") my.countNew <- paste0( covariates[i] , "[CondJumpGrid]") dum.Ker <- gsub(my.countOld, my.countNew, x = dum.Ker, fixed=TRUE) } } dif.dx <- paste("d",[email protected]@var.dx, sep="") if(Kern.Fun@Integrand@dimIntegrand[1]==1){ dum.Ker <- paste(dum.Ker,dif.dx, sep = "*") }else{ dum.Ker <- matrix(dum.Ker,Kern.Fun@Integrand@dimIntegrand[1], Kern.Fun@Integrand@dimIntegrand[2], byrow=T) dum.Ker <- paste(dum.Ker,dif.dx, sep = "*") dum.Ker <- matrix(dum.Ker,Kern.Fun@Integrand@dimIntegrand[1], Kern.Fun@Integrand@dimIntegrand[2], byrow=T) } cond.Sup <- paste([email protected]@var.time, "<", [email protected]@upper.var) dum.Ker <- paste("(",dum.Ker, ") * (", cond.Sup, ")") dum.Ker <- paste0("sum(",dum.Ker,")") if(Kern.Fun@Integrand@dimIntegrand[2]>1 & Kern.Fun@Integrand@dimIntegrand[1]==1){ dum.Ker <- paste(dum.Ker,collapse = " + ") } if(Kern.Fun@Integrand@dimIntegrand[1]>1){ mydum <- matrix(dum.Ker,Kern.Fun@Integrand@dimIntegrand[1], Kern.Fun@Integrand@dimIntegrand[2]) dum.Ker <- character(length = Kern.Fun@Integrand@dimIntegrand[1]) for (i in c(1:Kern.Fun@Integrand@dimIntegrand[1])){ dum.Ker[i] <- paste(mydum[i,],collapse = " + ") } } for(i in c(1:numb.Int)){ Int.Intens[[i]] <- parse(text = paste(dum.g[i], dum.Ker[i], sep = " + ")) } res <- list(Intens = Int.Intens) } aux.simulatPPR<- function(object, nsim = nsim, seed = seed, xinit = xinit, true.parameter = true.parameter, space.discretized = space.discretized, increment.W = increment.W, increment.L = increment.L, method = method, hurst = hurst, methodfGn = methodfGn, sampling = sampling, subsampling = subsampling){ ROLDVER<-!(is(object@model@measure$df,"yuima.law")) if(ROLDVER){ object <- aux.simulatPPRROldVersion(object, nsim = nsim, seed = seed, xinit = xinit, true.parameter = true.parameter, space.discretized = space.discretized, increment.W = increment.W, increment.L = increment.L, method = method, hurst = hurst, methodfGn = methodfGn, sampling = sampling, subsampling = subsampling) }else{ if(object@PPR@RegressWithCount){ object <-aux.simulatPPRWithCount(object, nsim = nsim, seed = seed, xinit = xinit, true.parameter = true.parameter, space.discretized = space.discretized, increment.W = increment.W, increment.L = increment.L, method = method, hurst = hurst, methodfGn = methodfGn, sampling = sampling, subsampling = subsampling) }else{ posLambda <- object@[email protected] %in% object@[email protected] condInteFeedbackCov <- any(posLambda) if(condInteFeedbackCov){ object <- aux.simulatPPRWithIntesFeedBack(object, nsim = nsim, seed = seed, xinit = xinit, true.parameter = true.parameter, space.discretized = space.discretized, increment.W = increment.W, increment.L = increment.L, method = method, hurst = hurst, methodfGn = methodfGn, sampling = sampling, subsampling = subsampling, posLambda=posLambda) }else{ object <- aux.simulatPPRROldNew(object, nsim = nsim, seed = seed, xinit = xinit, true.parameter = true.parameter, space.discretized = space.discretized, increment.W = increment.W, increment.L = increment.L, method = method, hurst = hurst, methodfGn = methodfGn, sampling = sampling, subsampling = subsampling) } } } return(object) } eulerPPR<-function(xinit,yuima,Initial,Terminal, dW, n, env){ sdeModel<-yuima@model modelstate <- [email protected] modeltime <- [email protected] V0 <- sdeModel@drift V <- sdeModel@diffusion r.size <- [email protected] d.size <- [email protected] dL <- env$dL if(length(unique(as.character(xinit)))==1 && is.numeric(tryCatch(eval(xinit[1],env),error=function(...) FALSE))){ dX_dummy<-xinit[1] dummy.val<-eval(dX_dummy, env) if(length(dummy.val)==1){dummy.val<-rep(dummy.val,length(xinit))} for(i in 1:length(modelstate)){ assign(modelstate[i],dummy.val[i] ,env) } dX<-vector(mode="numeric",length(dX_dummy)) for(i in 1:length(xinit)){ dX[i] <- dummy.val[i] } }else{ dX_dummy <- xinit if(length(modelstate)==length(dX_dummy)){ for(i in 1:length(modelstate)) { if(is.numeric(tryCatch(eval(dX_dummy[i],env),error=function(...) FALSE))){ assign(modelstate[i], eval(dX_dummy[i], env),env) }else{ assign(modelstate[i], 0, env) } } }else{ yuima.warn("the number of model states do not match the number of initial conditions") return(NULL) } dX<-vector(mode="numeric",length(dX_dummy)) for(i in 1:length(dX_dummy)){ dX[i] <- eval(dX_dummy[i], env) } } delta <- yuima@sampling@delta if(!length([email protected])){ b <- parse(text=paste("c(",paste(as.character(V0),collapse=","),")")) vecV <- parse(text=paste("c(",paste(as.character(unlist(V)),collapse=","),")")) X_mat <- .Call("euler", dX, Initial, as.integer(r.size), rep(1, n) * delta, dW, modeltime, modelstate, quote(eval(b, env)), quote(eval(vecV, env)), env, new.env()) tsX <- ts(data=t(X_mat), deltat=delta , start = Initial) }else{ has.drift <- sum(as.character(sdeModel@drift) != "(0)") var.in.diff <- is.logical(any(match(unlist(lapply(sdeModel@diffusion, all.vars)), [email protected]))) p.b <- function(t, X=numeric(d.size)){ for(i in 1:length(modelstate)){ assign(modelstate[i], X[i], env) } assign(modeltime, t, env) if(has.drift){ tmp <- matrix(0, d.size, r.size+1) for(i in 1:d.size){ tmp[i,1] <- eval(V0[i], env) for(j in 1:r.size){ tmp[i,j+1] <- eval(V[[i]][j],env) } } } else { tmp <- matrix(0, d.size, r.size) if(!is.Poisson(sdeModel)){ for(i in 1:d.size){ for(j in 1:r.size){ tmp[i,j] <- eval(V[[i]][j],env) } } } } return(tmp) } X_mat <- matrix(0, d.size, (n+1)) X_mat[,1] <- dX if(has.drift){ dW <- rbind( rep(1, n)*delta , dW) } JP <- [email protected] mu.size <- length(JP) p.b.j <- function(t, X=numeric(d.size)){ for(i in 1:length(modelstate)){ assign(modelstate[i], X[i], env) } assign(modeltime, t, env) j.size <- length(JP[[1]]) tmp <- matrix(0, mu.size, j.size) for(i in 1:mu.size){ for(j in 1:j.size){ tmp[i,j] <- eval(JP[[i]][j],env) } } return(tmp) } dZ <- dL if(is.null(dim(dZ))) dZ <- matrix(dZ,nrow=1) for(i in 1:n){ assign([email protected], dZ[,i], env) if([email protected]){ dZ[,i] <- 1 } tmp.j <- p.b.j(t=Initial+(i - 1)*delta, X=dX) if(sum(dim(tmp.j))==2) tmp.j <- as.numeric(tmp.j) dX <- dX + p.b(t=Initial+(i - 1)*delta, X=dX) %*% dW[, i] +tmp.j %*% dZ[,i] X_mat[, i+1] <- dX } } return(X_mat) } eulerPPRwithInt<-function(xinit,yuima,Initial,Terminal, dW, dL, n, env){ sdeModel<-yuima@model modelstate <- [email protected] modeltime <- [email protected] V0 <- sdeModel@drift V <- sdeModel@diffusion r.size <- [email protected] d.size <- [email protected] if(length(unique(as.character(xinit)))==1 && is.numeric(tryCatch(eval(xinit[1],env),error=function(...) FALSE))){ dX_dummy<-xinit[1] dummy.val<-eval(dX_dummy, env) if(length(dummy.val)==1){dummy.val<-rep(dummy.val,length(xinit))} for(i in 1:length(modelstate)){ assign(modelstate[i],dummy.val[i] ,env) } dX<-vector(mode="numeric",length(dX_dummy)) for(i in 1:length(xinit)){ dX[i] <- dummy.val[i] } }else{ dX_dummy <- xinit if(length(modelstate)==length(dX_dummy)){ for(i in 1:length(modelstate)) { if(is.numeric(tryCatch(eval(dX_dummy[i],env),error=function(...) FALSE))){ assign(modelstate[i], eval(dX_dummy[i], env),env) }else{ assign(modelstate[i], 0, env) } } }else{ yuima.warn("the number of model states do not match the number of initial conditions") dX_dummy <- c(dX_dummy,env[[yuima@[email protected]]]) for(i in 1:length(modelstate)){ if(is.numeric(tryCatch(eval(dX_dummy[i],env),error=function(...) FALSE))){ assign(modelstate[i], eval(dX_dummy[i], env),env) }else{ assign(modelstate[i], 0, env) } } } dX<-vector(mode="numeric",length(dX_dummy)) for(i in 1:length(dX_dummy)){ dX[i] <- eval(dX_dummy[i], env) } } delta <- yuima@sampling@delta if(!length([email protected])){ b <- parse(text=paste("c(",paste(as.character(V0),collapse=","),")")) vecV <- parse(text=paste("c(",paste(as.character(unlist(V)),collapse=","),")")) X_mat <- .Call("euler", dX, Initial, as.integer(r.size), rep(1, n) * delta, dW, modeltime, modelstate, quote(eval(b, env)), quote(eval(vecV, env)), env, new.env()) tsX <- ts(data=t(X_mat), deltat=delta , start = Initial) }else{ has.drift <- sum(as.character(sdeModel@drift) != "(0)") var.in.diff <- is.logical(any(match(unlist(lapply(sdeModel@diffusion, all.vars)), [email protected]))) p.b <- function(t, X=numeric(d.size)){ for(i in 1:length(modelstate)){ assign(modelstate[i], X[i], env) } assign(modeltime, t, env) if(has.drift){ tmp <- matrix(0, d.size, r.size+1) for(i in 1:d.size){ tmp[i,1] <- eval(V0[i], env) for(j in 1:r.size){ tmp[i,j+1] <- eval(V[[i]][j],env) } } } else { tmp <- matrix(0, d.size, r.size) if(!is.Poisson(sdeModel)){ for(i in 1:d.size){ for(j in 1:r.size){ tmp[i,j] <- eval(V[[i]][j],env) } } } } return(tmp) } X_mat <- matrix(0, d.size, (n+1)) X_mat[,1] <- dX if(has.drift){ dW <- rbind( rep(1, n)*delta , dW) } JP <- [email protected] mu.size <- length(JP) p.b.j <- function(t, X=numeric(d.size)){ for(i in 1:length(modelstate)){ assign(modelstate[i], X[i], env) } assign(modeltime, t, env) j.size <- length(JP[[1]]) tmp <- matrix(0, mu.size, j.size) for(i in 1:mu.size){ for(j in 1:j.size){ tmp[i,j] <- eval(JP[[i]][j],env) } } return(tmp) } dZ <- dL if(is.null(dim(dZ))) dZ <- matrix(dZ,nrow=1) for(i in 1:n){ assign([email protected], dZ[,i], env) if([email protected]){ dZ[,i] <- 1 } tmp.j <- p.b.j(t=Initial+(i - 1)*delta, X=dX) if(sum(dim(tmp.j))==2) tmp.j <- as.numeric(tmp.j) dX <- dX + p.b(t=Initial+(i - 1)*delta, X=dX) %*% dW[, i] +tmp.j %*% dZ[,i] X_mat[, i+1] <- dX } } return(X_mat) } aux.simulatPPRWithCount<-function(object, nsim = nsim, seed = seed, xinit = xinit, true.parameter = true.parameter, space.discretized = space.discretized, increment.W = increment.W, increment.L = increment.L, method = method, hurst = 0.5, methodfGn = methodfGn, sampling = sampling, subsampling = subsampling){ samp <- sampling Model <- object@model gFun <- object@gFun Kern <- object@Kernel object@sampling <- samp randomGenerator<-object@model@measure$df if(missing(increment.W) | is.null(increment.W)){ if( Model@hurst!=0.5 ){ grid<-sampling2grid(object@sampling) isregular<-object@sampling@regular if((!isregular) || (methodfGn=="Cholesky")){ dW<-CholeskyfGn(grid, Model@hurst,[email protected]) yuima.warn("Cholesky method for simulating fGn has been used.") } else { dW<-WoodChanfGn(grid, Model@hurst,[email protected]) } } else { delta <- samp@delta if(!is.Poisson(Model)){ dW <- rnorm(samp@n * [email protected], 0, sqrt(delta)) dW <- matrix(dW, ncol=samp@n, [email protected],byrow=TRUE) } else { dW <- matrix(0,ncol=samp@n,nrow=1) } } } else { dW <- increment.W } if(missing(xinit)){ if(length(object@model@xinit)!=0){ xinit<-numeric(length=length(object@model@xinit)) for(i in c(1:object@[email protected])) xinit[i] <- eval(object@model@xinit[i]) }else{ xinit <- rep(0,object@[email protected]) object@model@xinit<-xinit } } if(missing(hurst)){ hurst<-0.5 } if(samp@regular){ tForMeas<-samp@delta NumbIncr<-samp@n if(missing(true.parameter)){ eval(parse(text= paste0("measureparam$", object@[email protected]," <- tForMeas",collapse=""))) }else{ measureparam<-true.parameter[object@model@parameter@measure] eval(parse(text= paste0("measureparam$", object@[email protected]," <- tForMeas",collapse=""))) } Noise.L <- t(rand(object = randomGenerator, n=NumbIncr, param=measureparam)) rownames(Noise.L)<[email protected] Noise.count <- Noise.L[object@[email protected],] Noise.Laux <- Noise.L for(i in c(1:length(object@[email protected]))){ Noise.Laux[object@[email protected][i],]<-0 } } myenv<-new.env() par.len <- length(object@PPR@allparam) if(par.len>0){ for(i in 1:par.len){ pars <- object@PPR@allparam[i] for(j in 1:length(true.parameter)){ if( is.na(match(pars, names(true.parameter)[j]))!=TRUE){ assign(object@PPR@allparam[i], true.parameter[[j]],myenv) } } } } assign("dL",Noise.Laux,myenv) condMatrdW <- is.matrix(dW) if(condMatrdW){ dimdW <- dim(dW)[2] }else{ dimdW <- length(dW) } CovariateSim<- eulerPPR(xinit=xinit,yuima=object,dW=dW, Initial=samp@Initial,Terminal=samp@Terminal,n=samp@n, env=myenv) rownames(CovariateSim)<- [email protected] assign("info.PPR", object@PPR, myenv) dimCov <- length(object@PPR@covariates) if (dimCov>0){ for(j in c(1:dimCov)){ assign(object@PPR@covariates[j], as.numeric(CovariateSim[object@PPR@covariates[j],1]), envir = myenv) } } dimNoise<-dim(Noise.Laux) dimCovariateSim <- dim(CovariateSim) ExprHaz <- constHazIntPr(g.Fun = object@gFun@formula, Kern.Fun = object@Kernel, covariates = object@PPR@covariates, counting.var = object@[email protected], statevar = object@[email protected])$Intens compErrHazR4 <- function(samp, Kern, capitalTime, Model, my.env, ExprHaz, Time, dN, Index, pos){ assign([email protected]@var.time, Time, envir = my.env) assign([email protected], capitalTime, envir = my.env) l <- 1 for(i in c(1:length([email protected]@var.dx)) ){ if(any([email protected]@var.dx[i][email protected])){ assign(paste0("d",[email protected]@var.dx[i]), dN[l,], envir =my.env) l <- l + 1 } if([email protected]@var.dx[i]%in%my.env$info.PPR@covariates){ assign(paste0("d",[email protected]@var.dx[i]), diff(c(0,my.env[[[email protected]@var.dx[i]]])) , envir =my.env) } } condPointIngrid <- samp@grid[[1]]<=my.env$t PointIngridInt <- samp@grid[[1]][condPointIngrid] CondJumpGrid <- PointIngridInt %in% my.env$s assign("CondJumpGrid", CondJumpGrid, envir = my.env) Lambda <- NULL Lambda <- eval(ExprHaz[[pos]], envir = my.env) return(Lambda) } dN <- matrix(0,object@gFun@dimension[1],object@gFun@dimension[2]) grid <- samp@grid[[1]] const <- -log(runif(gFun@dimension[1])) condMyTR <- const<delta while(any(condMyTR)){ if(sum(condMyTR)==0){ const <- -log(runif(length(condMyTR))) condMyTR <- const<delta }else{ const[condMyTR] <- -log(runif(sum(condMyTR))) condMyTR <- const<delta } } jumpT<-NULL i <- 1 dimGrid <-length(grid) cond <- const Index <- gFun@dimension[1] inter_i <- rep(i,Index) noExit<-rep(T,Index) while(any(noExit)){ for(j in c(1:Index)){ HazardRate<-0 while(cond[j]>0 && noExit[j]){ lambda<-compErrHazR4(samp, Kern, capitalTime=samp@grid[[1]][inter_i[j]], Model, myenv, ExprHaz, Time=jumpT, dN, Index, j) incrlambda <- lambda*delta HazardRate <- HazardRate+incrlambda cond[j] <- const[j]-HazardRate inter_i[j]<-inter_i[j]+1 if(inter_i[j]>=(dimGrid-1)){ noExit[j] <- FALSE } if(inter_i[j]<dim(CovariateSim)[2]){ dimCov <- length(object@PPR@covariates) if (dimCov>0){ for(j in c(1:dimCov)){ assign(object@PPR@covariates[j], as.numeric(CovariateSim[object@PPR@covariates[j],1:inter_i[j]]), envir = myenv) } } } } } i <- min(inter_i) if(any(noExit)){ if(i<dim(CovariateSim)[2]){ jumpT<-c(jumpT,grid[i]) if(dim(dN)[2]==1 & all(dN[,1]==0)){ dN[i==inter_i,1] <- Noise.count[i-1] Noise.Laux[object@[email protected],i-1]<-Noise.count[i-1] dumdN <- dN }else{ dumdN <- rep(0,Index) dumdN[i==inter_i] <- Noise.count[i-1] Noise.Laux[object@[email protected],i-1] <- dumdN[i==inter_i] dN <- cbind(dN,dumdN) } assign("dL",Noise.Laux[,c((i-1):dimNoise[2])],myenv) xinit <- CovariateSim[,i-1] if(condMatrdW){ CovariateSim[,(i-1):dimCovariateSim[2]] <- eulerPPR(xinit=xinit, yuima=object,dW=dW[,(i-1):dimdW], Initial=samp@grid[[1]][i-1],Terminal=samp@Terminal,n=(samp@n-(i-1)+1), env=myenv) }else{ CovariateSim[,(i-1):dimCovariateSim[2]] <- eulerPPR(xinit=xinit, yuima=object, dW=dW[(i-1):dimdW], Initial=samp@grid[[1]][i-1],Terminal=samp@Terminal,n=(samp@n-(i-1)+1), env=myenv) } rownames(CovariateSim)<- [email protected] const <- -log(runif(object@gFun@dimension[1])) condMyTR <- const<delta while(any(condMyTR)){ if(sum(condMyTR)==0){ const <- -log(runif(length(condMyTR))) condMyTR <- const<delta }else{ const[condMyTR] <- -log(runif(sum(condMyTR))) condMyTR <- const<delta } } cond <- const if(all(noExit)){ inter_i <- rep(i, Index) }else{ if(any(noExit)){ inter_i[noExit] <- i inter_i[!noExit] <- samp@n+1 } } } } } tsX <- ts(data=t(CovariateSim), deltat=delta, start=object@sampling@Initial) object@data <- setData(original.data=tsX) for(i in 1:length(object@[email protected])) index(object@[email protected][[i]]) <- object@sampling@grid[[1]] if(missing(subsampling)) return(object) subsampling(object, subsampling) } aux.simulatPPRWithIntesFeedBack<-function(object, nsim = nsim, seed = seed, xinit = xinit, true.parameter = true.parameter, space.discretized = space.discretized, increment.W = increment.W, increment.L = increment.L, method = method, hurst = hurst, methodfGn = methodfGn, sampling = sampling, subsampling = subsampling, posLambda=posLambda){ samp <- sampling Model <- object@model gFun <- object@gFun Kern <- object@Kernel object@sampling <- samp randomGenerator<-object@model@measure$df nameIntensityProc <- object@[email protected] if(missing(increment.W) | is.null(increment.W)){ if( Model@hurst!=0.5 ){ grid<-sampling2grid(object@sampling) isregular<-object@sampling@regular if((!isregular) || (methodfGn=="Cholesky")){ dW<-CholeskyfGn(grid, Model@hurst,[email protected]) yuima.warn("Cholesky method for simulating fGn has been used.") } else { dW<-WoodChanfGn(grid, Model@hurst,[email protected]) } } else { delta <- samp@delta if(!is.Poisson(Model)){ dW <- rnorm(samp@n * [email protected], 0, sqrt(delta)) dW <- matrix(dW, ncol=samp@n, [email protected],byrow=TRUE) } else { dW <- matrix(0,ncol=samp@n,nrow=1) } } } else { dW <- increment.W } if(missing(xinit)){ if(length(object@model@xinit)!=0){ xinit<-numeric(length=length(object@model@xinit)) for(i in c(1:object@[email protected])) xinit[i] <- eval(object@model@xinit[i]) }else{ xinit <- rep(0,object@[email protected]) object@model@xinit<-xinit } } if(missing(hurst)){ hurst<-0.5 } if(samp@regular){ tForMeas<-samp@delta NumbIncr<-samp@n if(missing(true.parameter)){ eval(parse(text= paste0("measureparam$", object@[email protected]," <- tForMeas",collapse=""))) }else{ measureparam<-true.parameter[object@model@parameter@measure] eval(parse(text= paste0("measureparam$", object@[email protected]," <- tForMeas",collapse=""))) } Noise.L <- t(rand(object = randomGenerator, n=NumbIncr, param=measureparam)) rownames(Noise.L)<[email protected] Noise.count <- Noise.L[object@[email protected],] Noise.Laux <- Noise.L for(i in c(1:length(object@[email protected]))){ Noise.Laux[object@[email protected][i],]<-0 } } myenv<-new.env() par.len <- length(object@PPR@allparam) if(par.len>0){ for(i in 1:par.len){ pars <- object@PPR@allparam[i] for(j in 1:length(true.parameter)){ if( is.na(match(pars, names(true.parameter)[j]))!=TRUE){ assign(object@PPR@allparam[i], true.parameter[[j]],myenv) } } } } assign("dL",Noise.Laux,myenv) condMatrdW <- is.matrix(dW) if(condMatrdW){ dimdW <- dim(dW)[2] }else{ dimdW <- length(dW) } assign("info.PPR", object@PPR, myenv) dimCov <- length(object@PPR@covariates) dimNoise<-dim(Noise.Laux) compErrHazR4 <- function(samp, Kern, capitalTime, Model, my.env, ExprHaz, Time, dN, Index, pos){ assign([email protected]@var.time, Time, envir = my.env) assign([email protected], capitalTime, envir = my.env) l <- 1 for(i in c(1:length([email protected]@var.dx)) ){ if(any([email protected]@var.dx[i][email protected])){ assign(paste0("d",[email protected]@var.dx[i]), dN[l,], envir =my.env) l <- l + 1 } if([email protected]@var.dx[i]%in%my.env$info.PPR@covariates){ assign(paste0("d",[email protected]@var.dx[i]), diff(c(0,my.env[[[email protected]@var.dx[i]]])) , envir =my.env) } } condPointIngrid <- samp@grid[[1]]<=my.env$t PointIngridInt <- samp@grid[[1]][condPointIngrid] CondJumpGrid <- PointIngridInt %in% my.env$s assign("CondJumpGrid", CondJumpGrid, envir = my.env) Lambda <- NULL Lambda <- eval(ExprHaz[[pos]], envir = my.env) return(Lambda) } if (dimCov>0){ for(j in c(1:dimCov)){ assign(object@PPR@covariates[j], as.numeric(xinit[j]), envir = myenv) } } CovariateSim <-matrix(0,[email protected],(samp@n+1)) ExprHaz <- constHazIntPr(g.Fun = object@gFun@formula, Kern.Fun = object@Kernel, covariates = object@PPR@covariates, counting.var = object@[email protected], statevar=nameIntensityProc)$Intens IntensityProcInter <- as.matrix(tryCatch(eval(object@gFun@formula,envir=myenv),error =function(){1})) dN <- matrix(0,object@gFun@dimension[1],object@gFun@dimension[2]) rownames(CovariateSim)<- [email protected] assign(object@[email protected],CovariateSim[object@[email protected],1],envir=myenv) grid <- samp@grid[[1]] const <- -log(runif(gFun@dimension[1])) condMyTR <- const<delta AllnameIntensityProc <- paste0(nameIntensityProc,"ForKernel") assign(AllnameIntensityProc,IntensityProcInter,envir=myenv) while(any(condMyTR)){ if(sum(condMyTR)==0){ const <- -log(runif(length(condMyTR))) condMyTR <- const<delta }else{ const[condMyTR] <- -log(runif(sum(condMyTR))) condMyTR <- const<delta } } jumpT<-NULL i <- 1 Initial_i <- i-1 dimGrid <-length(grid) cond <- const Index <- gFun@dimension[1] inter_i <- rep(i,Index) noExit<-rep(T,Index) while(any(noExit)){ for(j in c(1:Index)){ HazardRate<-0 while(cond[j]>0 && noExit[j]){ lambda<-compErrHazR4(samp, Kern, capitalTime=samp@grid[[1]][inter_i[j]], Model, myenv, ExprHaz, Time=jumpT, dN, Index, j) if(is.matrix(posLambda)){}else{ assign(nameIntensityProc,lambda[j], envir = myenv) assign(AllnameIntensityProc, cbind(t(myenv[[AllnameIntensityProc]][j,]), lambda[j]), envir=myenv) } incrlambda <- lambda*delta HazardRate <- HazardRate+incrlambda cond[j] <- const[j]-HazardRate inter_i[j]<-inter_i[j]+1 if(inter_i[j]-1==1){ CovariateSim[,c((inter_i[j]-1):inter_i[j])]<- eulerPPRwithInt(xinit=xinit,yuima=object,dW=dW[,(inter_i[j]-1)], dL=as.matrix(myenv$dL[,c(i-Initial_i)]),Initial=samp@Initial,Terminal=samp@grid[[1]][inter_i[j]],n=1, env=myenv) rownames(CovariateSim)<- [email protected] }else{ CovariateSim[,inter_i[j]]<- eulerPPRwithInt(xinit=CovariateSim[,(inter_i[j]-1)], yuima=object,dW=dW[,(inter_i[j]-1)], dL=as.matrix(myenv$dL[,c(inter_i[j]-1-Initial_i)]), Initial=samp@grid[[1]][(inter_i[j]-1)], Terminal=samp@grid[[1]][inter_i[j]],n=1, env=myenv)[,-1] } if(inter_i[j]>=(dimGrid)){ noExit[j] <- FALSE } if(inter_i[j]<=dimGrid){ assign(object@[email protected],CovariateSim[object@[email protected][j],1:inter_i[j]],envir=myenv) dimCov <- length(object@PPR@covariates) if (dimCov>0){ for(jj in c(1:dimCov)){ assign(object@PPR@covariates[jj], as.numeric(CovariateSim[object@PPR@covariates[jj],1:inter_i[j]]), envir = myenv) } } } } } i <- min(inter_i) Initial_i <- i-1 if(any(noExit)){ if(i<dim(CovariateSim)[2]){ jumpT<-c(jumpT,grid[i]) if(dim(dN)[2]==1 & all(dN[,1]==0)){ dN[i==inter_i,1] <- Noise.count[i-1] Noise.Laux[object@[email protected],i-1]<-Noise.count[i-1] dumdN <- dN }else{ dumdN <- rep(0,Index) dumdN[i==inter_i] <- Noise.count[i-1] Noise.Laux[object@[email protected],i-1] <- dumdN[i==inter_i] dN <- cbind(dN,dumdN) } assign("dL",Noise.Laux[,c((i-1):dimNoise[2])],myenv) xinit <- CovariateSim[,i-1] const <- -log(runif(object@gFun@dimension[1])) condMyTR <- const<delta while(any(condMyTR)){ if(sum(condMyTR)==0){ const <- -log(runif(length(condMyTR))) condMyTR <- const<delta }else{ const[condMyTR] <- -log(runif(sum(condMyTR))) condMyTR <- const<delta } } cond <- const if(all(noExit)){ inter_i <- rep(i, Index) }else{ if(any(noExit)){ inter_i[noExit] <- i inter_i[!noExit] <- samp@n+1 } } } } } tsX <- ts(data=t(CovariateSim), deltat=delta, start=object@sampling@Initial) object@data <- setData(original.data=tsX) for(i in 1:length(object@[email protected])) index(object@[email protected][[i]]) <- object@sampling@grid[[1]] if(missing(subsampling)) return(object) subsampling(object, subsampling) } aux.simulatPPRROldNew<-function(object, nsim = nsim, seed = seed, xinit = xinit, true.parameter = true.parameter, space.discretized = space.discretized, increment.W = increment.W, increment.L = increment.L, method = method, hurst = 0.5, methodfGn = methodfGn, sampling = sampling, subsampling = subsampling){ myhawkesP <- function(simMod, Kern, samp, Model, my.env, ExprHaz, Time, dN){ noExit<-TRUE const <- -log(runif(1)) delta <- samp@delta grid <- samp@grid[[1]] while(const<delta){ const <- -log(runif(1)) } jumpT<-NULL i <- 1 dimGrid <-length(grid) cond <- const allconst <- NULL allcond <- NULL allhaz <- NULL while(noExit){ HazardRate<-0 while(cond>0 && noExit){ lambda<-compErrHazR2(simMod, Kern, capitalTime=samp@grid[[1]][i], Model, my.env, ExprHaz, Time=jumpT, dN) incrlambda <- lambda*delta HazardRate <- HazardRate+incrlambda cond <- const-HazardRate i<-i+1 if(i>=(dimGrid-1)){ noExit <- FALSE } if(i<dim(simMod@[email protected])[1]){ dimCov <- length(object@PPR@covariates) if (dimCov>0){ for(j in c(1:dimCov)){ assign(object@PPR@covariates[j], as.numeric(simMod@[email protected][1:i,object@PPR@covariates[j]]), envir = my.env) } } } } if(i<dim(simMod@[email protected])[1]){ jumpT<-c(jumpT,grid[i]) if(dN[1]==0){ dN <- simMod@[email protected][i,object@[email protected]]-simMod@[email protected][i-1,object@[email protected]] }else{ dN <- c(dN, simMod@[email protected][i,object@[email protected]]-simMod@[email protected][i-1,object@[email protected]]) } allhaz <- c(allhaz,HazardRate) allcond <- c(allcond,cond) cond <- const allconst <- c(allconst, const) const <- -log(runif(1)) while(const<delta){ const <- -log(runif(1)) } } } return(list(jumpT=jumpT,allcond=allcond,allconst=allconst, allhaz=allhaz)) } myhawkesPMulti <- function(simMod, Kern, samp, Model, my.env, ExprHaz, Time, dN, Index){ delta <- samp@delta grid <- samp@grid[[1]] const <- -log(runif(object@gFun@dimension[1])) condMyTR <- const<delta while(any(condMyTR)){ if(sum(condMyTR)==0){ const <- -log(runif(length(condMyTR))) condMyTR <- const<delta }else{ const[condMyTR] <- -log(runif(sum(condMyTR))) condMyTR <- const<delta } } jumpT<-NULL i <- 1 dimGrid <-length(grid) cond <- const inter_i <- rep(i,Index) noExit<-rep(T,Index) while(any(noExit)){ for(j in c(1:Index)){ HazardRate<-0 while(cond[j]>0 && noExit[j]){ lambda<-compErrHazR3(simMod, Kern, capitalTime=samp@grid[[1]][inter_i[j]], Model, my.env, ExprHaz, Time=jumpT, dN, Index, j) incrlambda <- lambda*delta HazardRate <- HazardRate+incrlambda cond[j] <- const[j]-HazardRate inter_i[j]<-inter_i[j]+1 if(inter_i[j]>=(dimGrid-1)){ noExit[j] <- FALSE } if(inter_i[j]<dim(simMod@[email protected])[1]){ dimCov <- length(object@PPR@covariates) if (dimCov>0){ for(jj in c(1:dimCov)){ assign(object@PPR@covariates[jj], as.numeric(simMod@[email protected][1:inter_i[j],object@PPR@covariates[jj]]), envir = my.env) } } } } } i <- min(inter_i) if(any(noExit)){ if(i<dim(simMod@[email protected])[1]){ jumpT<-c(jumpT,grid[i]) if(dim(dN)[2]==1 & all(dN[,1]==0)){ dN[i==inter_i,1] <- 1 dumdN <- dN }else{ dumdN <- rep(0,Index) dumdN[i==inter_i] <- 1 dN <- cbind(dN,dumdN) } const <- -log(runif(object@gFun@dimension[1])) condMyTR <- const<delta while(any(condMyTR)){ if(sum(condMyTR)==0){ const <- -log(runif(length(condMyTR))) condMyTR <- const<delta }else{ const[condMyTR] <- -log(runif(sum(condMyTR))) condMyTR <- const<delta } } cond <- const if(all(noExit)){ inter_i <- rep(i, Index) }else{ if(any(noExit)){ inter_i[noExit] <- i inter_i[!noExit] <- samp@n+1 } } } } } return(list(jumpT=jumpT,dN = dN)) } compErrHazR2 <- function(simMod, Kern, capitalTime, Model, my.env, ExprHaz, Time, dN){ if(length([email protected]@var.dx)==1){ assign([email protected]@var.time, Time, envir = my.env) assign([email protected], capitalTime, envir = my.env) assign(paste0("d",[email protected]@var.dx), dN, envir =my.env) condPointIngrid <- simMod@sampling@grid[[1]]<=my.env$t PointIngridInt <- simMod@sampling@grid[[1]][condPointIngrid] CondJumpGrid <- PointIngridInt %in% my.env$s assign("CondJumpGrid", CondJumpGrid, envir = my.env) Lambda <- eval(ExprHaz[[1]], envir=my.env) return(Lambda) }else{ if(Kern@Integrand@dimIntegrand[1]==1){ assign([email protected]@var.time, Time, envir = my.env) assign([email protected], capitalTime, envir = my.env) for(i in c(1:length([email protected]@var.dx)) ){ if([email protected]@var.dx[i][email protected]){ assign(paste0("d",[email protected]@var.dx[i]), dN, envir =my.env) } if([email protected]@var.dx[i]%in%my.env$info.PPR@covariates){ assign(paste0("d",[email protected]@var.dx[i]), diff(c(0,my.env[[[email protected]@var.dx[i]]])) , envir =my.env) } if([email protected]@var.dx[i]%in%[email protected]){ assign(paste0("d",[email protected]@var.dx[i]), diff(c(0,my.env[[[email protected]@var.dx[i]]])) , envir =my.env) } } condPointIngrid <- simMod@sampling@grid[[1]]<=my.env$t PointIngridInt <- simMod@sampling@grid[[1]][condPointIngrid] CondJumpGrid <- PointIngridInt %in% my.env$s assign("CondJumpGrid", CondJumpGrid, envir = my.env) Lambda <- eval(ExprHaz[[1]], envir=my.env) return(Lambda) } } } compErrHazR3 <- function(simMod, Kern, capitalTime, Model, my.env, ExprHaz, Time, dN, Index, pos){ assign([email protected]@var.time, Time, envir = my.env) assign([email protected], capitalTime, envir = my.env) l <- 1 for(i in c(1:length([email protected]@var.dx)) ){ if(any([email protected]@var.dx[i][email protected])){ assign(paste0("d",[email protected]@var.dx[i]), dN[l,], envir =my.env) l <- l + 1 } if([email protected]@var.dx[i]%in%my.env$info.PPR@covariates){ assign(paste0("d",[email protected]@var.dx[i]), diff(c(0,my.env[[[email protected]@var.dx[i]]])) , envir =my.env) } } condPointIngrid <- simMod@sampling@grid[[1]]<=my.env$t PointIngridInt <- simMod@sampling@grid[[1]][condPointIngrid] CondJumpGrid <- PointIngridInt %in% my.env$s assign("CondJumpGrid", CondJumpGrid, envir = my.env) Lambda <- NULL Lambda <- eval(ExprHaz[[pos]], envir = my.env) return(Lambda) } if(missing(hurst)){ hurst<-0.5 } samp <- sampling Model <- object@model gFun <- object@gFun Kern <- object@Kernel if(missing(xinit)){ if(object@PPR@RegressWithCount){ yuima.warn("Counting Variables are also covariates. In this case, the algorthim will be implemented as soon as possible.") return(NULL) } }else{ if(object@PPR@RegressWithCount){ yuima.warn("Counting Variables are also covariates. In this case, the algorthim will be implemented as soon as possible.") return(NULL) } } if(!object@PPR@RegressWithCount && !object@PPR@IntensWithCount){ auxg <- setMap(func = gFun@formula, yuima =Model) dummyKernIntgrand <- Kern@Integrand@IntegrandList dummyUpperTime<- paste0([email protected]@upper.var, [email protected]@upper.var, collapse = "") dummyTime <[email protected] for(i in c(1:length(dummyKernIntgrand))){ if([email protected]@upper.var %in% all.vars(dummyKernIntgrand[[i]])){ dumExpr <- paste0("substitute(expression(", dummyKernIntgrand[[i]],"), list(", [email protected]@upper.var, " = as.symbol(dummyUpperTime), ", [email protected]@var.time, " = as.symbol([email protected])))") dummyKernIntgrand[[i]] <- eval(parse(text=dumExpr)) } } auxIntMy <- unlist(lapply(dummyKernIntgrand, FUN = function(X){as.character(X)[2]})) auxIntMy <- matrix(auxIntMy, Kern@Integrand@dimIntegrand[1], Kern@Integrand@dimIntegrand[2], byrow=T) if(object@[email protected]@var.dx==object@[email protected]@var.time){ auxInt <- setIntegral(yuima = Model, integrand = auxIntMy, var.dx = [email protected], upper.var = dummyUpperTime, lower.var = [email protected]@lower.var) }else{ auxInt <- setIntegral(yuima = Model, integrand = auxIntMy, var.dx =object@[email protected]@var.dx , upper.var = dummyUpperTime, lower.var = [email protected]@lower.var) } randomGenerator<-object@model@measure$df if(samp@regular){ tForMeas<-samp@delta NumbIncr<-samp@n if(missing(true.parameter)){ eval(parse(text= paste0("measureparam$", object@[email protected]," <- tForMeas",collapse=""))) }else{ measureparam<-true.parameter[object@model@parameter@measure] eval(parse(text= paste0("measureparam$", object@[email protected]," <- tForMeas",collapse=""))) } Noise.L <- t(rand(object = randomGenerator, n=NumbIncr, param=measureparam)) Noise.W <- t(rnorm(NumbIncr, 0,tForMeas)) if(length(object@model@diffusion[[1]])>1){ for(i in c(2:length(object@model@diffusion[[1]]))){ Noise.W <- rbind(Noise.W, rnorm(NumbIncr, 0,tForMeas)) } } if(missing(xinit)){ simg <- simulate(object = auxg, true.parameter = true.parameter[auxg@Output@param@allparam], sampling = samp, hurst = hurst, increment.W = Noise.W, increment.L = Noise.L) simK <- simulate(object = auxInt, true.parameter = true.parameter[auxInt@[email protected]@allparam], sampling = samp, hurst = hurst, increment.W = Noise.W, increment.L = Noise.L) Lambda.data <- simg@[email protected]+simK@[email protected] Pos<-0 globPos<-Pos condWhile <- TRUE while(condWhile){ Hazard<--cumsum(as.numeric(Lambda.data)[c(Pos:(samp@n+1))])*samp@delta U<-runif(1) CondPos <- log(U)<=Hazard Pos <- Pos+sum(CondPos) if(Pos > (samp@n+1)){ condWhile <- FALSE }else{ globPos <- c(globPos,Pos) } } globPos <- unique(globPos) globPos <- globPos[(globPos<=samp@n)] NewNoise.L <- Noise.L cod <[email protected]%in%object@[email protected] NeWNoise.W<-Noise.W NeWNoise.W[cod,] <- 0 NewNoise.L[cod,] <- 0 NewNoise.L[cod,globPos[-1]] <- Noise.L[cod,globPos[-1]] simM <- simulate(object = Model, true.parameter = true.parameter[Model@parameter@all], sampling = samp, hurst = hurst, increment.W = NeWNoise.W, increment.L = NewNoise.L) object@data <- simM@data object@sampling <- samp return(object) }else{ simg <- simulate(object = auxg, xinit=xinit, sampling = samp) } } }else{ if(!object@PPR@RegressWithCount && object@PPR@IntensWithCount){ DummyT <- c(true.parameter[Model@parameter@measure], samp@delta) names(DummyT) <- c(names(true.parameter[Model@parameter@measure]), [email protected]) increment.L <- rand(object = Model@measure$df, n = samp@n , param = DummyT) if(!is.matrix(increment.L)){ increment.L <- matrix(increment.L,ncol = 1) } if(missing(xinit)){ simMod <- simulate(object = Model, hurst = hurst, sampling = samp, true.parameter = true.parameter[Model@parameter@all], increment.L = t(increment.L)) }else{ simMod <- simulate(object = Model, hurst = hurst, sampling = samp, xinit =xinit, true.parameter = true.parameter[Model@parameter@all], increment.L = t(increment.L)) } colnames(simMod@[email protected]) <- [email protected] Data.tot <- as.matrix(simMod@[email protected]) ExprHaz <- constHazIntPr(g.Fun = object@gFun@formula, Kern.Fun = object@Kernel, covariates = object@PPR@covariates, counting.var = object@[email protected], statevar = object@[email protected])$Intens if(length(ExprHaz)>=1){ Time <- samp@Initial my.env <- new.env() assign("info.PPR", object@PPR, my.env) for(i in c(1:length(object@PPR@allparam))){ assign(object@PPR@allparam[i], as.numeric(true.parameter[object@PPR@allparam[i]]), envir = my.env) } dimCov <- length(object@PPR@covariates) if (dimCov>0){ for(j in c(1:dimCov)){ assign(object@PPR@covariates[j], as.numeric(simMod@[email protected][1,object@PPR@covariates[j]]), envir = my.env) } } if(object@gFun@dimension[1]==1){ IntensityProc <- 0 dN <- 0 prova1 <- myhawkesP(simMod, Kern, samp, Model, my.env, ExprHaz, Time, dN) }else{ CPP<-FALSE IntensityProc <- matrix(0,object@gFun@dimension[1],object@gFun@dimension[2]) dN <- matrix(0,object@gFun@dimension[1],object@gFun@dimension[2]) prova1 <- myhawkesPMulti(simMod, Kern, samp, Model, my.env, ExprHaz, Time, dN, Index = object@gFun@dimension[1]) Time<-unique(prova1$jumpT) dN <- prova1$dN[,1:length(Time)] cond <- samp@grid[[1]][-1] %in% Time countVar <- [email protected] %in% object@[email protected] increment.L[!cond, countVar]<-0 increment.L[cond, countVar]<-t(dN) if(missing(xinit)){ simModNew <- simulate(object = Model, hurst = hurst, sampling = samp, true.parameter = true.parameter[Model@parameter@all], increment.L = t(increment.L)) }else{ simModNew <- simulate(object = Model, hurst = hurst, sampling = samp, xinit =xinit, true.parameter = true.parameter[Model@parameter@all], increment.L = t(increment.L)) } object@data<-simModNew@data object@sampling<-simModNew@sampling return(object) } Time<-prova1$jumpT cond <- samp@grid[[1]][-1] %in% Time countVar <- [email protected] %in% object@[email protected] increment.L[!cond, countVar]<-0 if(missing(xinit)){ simModNew <- simulate(object = Model, hurst = hurst, sampling = samp, true.parameter = true.parameter[Model@parameter@all], increment.L = t(increment.L)) }else{ simModNew <- simulate(object = Model, hurst = hurst, sampling = samp, xinit =xinit, true.parameter = true.parameter[Model@parameter@all], increment.L = t(increment.L)) } object@data<-simModNew@data object@sampling<-simModNew@sampling return(object) }else{ my.env <- new.env() assign("info.PPR", object@PPR, my.env) for(i in c(1:length(object@PPR@allparam))){ assign(object@PPR@allparam[i], as.numeric(true.parameter[object@PPR@allparam[i]]), envir = my.env) } dimCov <- length(object@PPR@covariates) if (dimCov>0){ for(j in c(1:dimCov)){ assign(object@PPR@covariates[j], as.numeric(simMod@[email protected][1,object@PPR@covariates[j]]), envir = my.env) } } CPP<-FALSE IntensityProc <- matrix(0,object@gFun@dimension[1],object@gFun@dimension[2]) dN <- NULL CondGlobal <- TRUE CondWhile <- TRUE u_bar <- samp@Initial u_old <- samp@Initial jumpT<-NULL posInitial <- 1 while(CondGlobal){ CondWhile <- TRUE const <- log(runif(object@gFun@dimension[1])) delta <- samp@delta grid <- samp@grid[[1]] condMyTR <- -const<delta while(any(condMyTR)){ if(sum(condMyTR)==0){ const <- log(runif(length(condMyTR))) condMyTR <- -const<delta }else{ const[condMyTR] <- log(runif(sum(condMyTR))) condMyTR <- -const<delta } } posfin <- sum(samp@grid[[1]]<=u_bar) dimGrid <-length(grid) cond <- const allconst <- NULL allcond <- NULL allhaz <- NULL checkFunDum_old <- const checkFunDum <- const count <- 0 while(CondWhile & count<20){ HowManylambda <- posfin-posInitial+1 lambda <- matrix(NA,object@gFun@dimension[1],HowManylambda) for(hh in c(1:HowManylambda)){ lambda[,hh] <- compErrHazR3(simMod, Kern, capitalTime=samp@grid[[1]][hh+(posInitial-1)], Model, my.env, ExprHaz, Time=jumpT, dN, object@gFun@dimension[1]) } u_next_comp <- numeric(length = object@gFun@dimension[1]) FunDum <- numeric(length=object@gFun@dimension[1]) for(l in c(1:object@gFun@dimension[1])){ FunDum[l] <- const[l] + sum(lambda[l, ]*delta) denomi <- lambda[l,HowManylambda] u_next_comp[l] <- u_bar-FunDum[l]/denomi } u_next <- min(u_next_comp) if(abs(tail(grid[grid<=u_next],1L) - tail(grid[grid<=u_bar],1L))<delta/2){ CondWhile<-FALSE } condpos <- u_next_comp %in% u_next checkFunDumAll <- FunDum[condpos] checkFunDum <- checkFunDumAll if(u_next > u_old){ if(checkFunDum_old<=0){ if(checkFunDum <= 0){ u_old<-u_bar checkFunDum_old <- checkFunDum }else{ checkFunDum_old <- checkFunDum } } u_bar <- u_next }else{ if(CondWhile){ u_bar <- (u_bar + u_old)/2 }else{ u_bar <- u_next } } posfin <- sum(samp@grid[[1]]<=u_bar) count <- count+1 } next_jump <- tail(grid[grid<=u_next],1L) dummydN <- rep(0,object@gFun@dimension[1]) for(hhh in c(1:object@gFun@dimension[1])){ condJumpComp <- u_next == u_next_comp[hhh] if(condJumpComp) dummydN[hhh] <- 1 } dN <- cbind(dN,dummydN) if(length(jumpT)>0){ if(tail(jumpT, 1L)+delta >= next_jump){ next_jump <- next_jump+delta } }else{ if(next_jump < delta){ next_jump <- next_jump+delta } } jumpT<-c(jumpT,next_jump) u_bar <- tail(jumpT,1L) posInitial<- sum(grid<=next_jump) posfin <- posInitial u_old <- next_jump if((next_jump+delta)>=samp@Terminal-delta){ CondGlobal <- FALSE } } Time<-jumpT cond <- samp@grid[[1]][-1] %in% Time countVar <- [email protected] %in% object@[email protected] increment.L[!cond, countVar]<-0 if(missing(xinit)){ simModNew <- simulate(object = Model, hurst = hurst, sampling = samp, true.parameter = true.parameter[Model@parameter@all], increment.L = t(increment.L)) }else{ simModNew <- simulate(object = Model, hurst = hurst, sampling = samp, xinit =xinit, true.parameter = true.parameter[Model@parameter@all], increment.L = t(increment.L)) } object@data<-simModNew@data object@sampling<-simModNew@sampling return(object) } } } return(NULL) } aux.simulatPPRROldVersion <- function(object, nsim = nsim, seed = seed, xinit = xinit, true.parameter = true.parameter, space.discretized = space.discretized, increment.W = increment.W, increment.L = increment.L, method = method, hurst = hurst, methodfGn = methodfGn, sampling = sampling, subsampling = subsampling){ Time <- sampling@Terminal numbVardx <- length(object@[email protected]) numbCountVar <- length(object@[email protected]) U <- runif(numbCountVar) my.env<- new.env() true.parameter <- unlist(true.parameter) if(!all(names(true.parameter)==object@PPR@allparam)){ yuima.stop("true.parameters mismatch the model parameters") } for(i in c(1:length(object@PPR@allparam))){ assign(object@PPR@allparam[i],true.parameter[object@PPR@allparam[i]], envir = my.env) } assign("t",object@gFun@[email protected], envir = my.env) nameu <- object@gFun@[email protected] assign("dt",sampling@delta, envir = my.env) if(is.null(increment.W)){ dimW <- length(object@model@diffusion[[1]]) W <- matrix(rnorm(dimW*sampling@n,mean=0,sd= sqrt(sampling@delta)),nrow=dimW,ncol=sampling@n) } Condcovariate <- TRUE if(is.null(increment.L)){ dimL <- length(object@[email protected][[1]]) L <- matrix(0,nrow=dimL,ncol=sampling@n) Condcovariate <- FALSE cond <- !(object@[email protected] %in% object@[email protected]) if(any(cond)){ Condcovariate <- TRUE } dimMd <- length(object@[email protected]) dumMod <- setModel(drift = rep("0",dimMd), diffusion = matrix("0",dimMd,1), jump.coeff = diag("1",dimMd,dimMd), measure = object@[email protected]$measure, measure.type = object@[email protected]$type, solve.variable = object@[email protected]) if(length(object@model@parameter@measure)!=0){ simMod <- simulate(object = dumMod, true.parameter = true.parameter[object@model@parameter@measure], sampling = sampling) }else{ simMod <- simulate(object = dumMod, sampling = sampling) } L <- t(diff(simMod@[email protected])) } assign("Condcovariate",Condcovariate, envir = my.env) assign("W", W, envir = my.env) rownames(L)<- object@[email protected] assign("L", L, envir = my.env) assign("All.labKern",object@[email protected],envir = my.env) assign("All.labgFun",object@gFun@param,envir = my.env) Fun1 <- function(u,env){ part <- seq(0,u,by=env$dt) env$t<-part[-length(part)] if(Condcovariate){ yuima<- object@model for(i in c(1:length(object@PPR@covariates))){ assign(object@PPR@covariates[i], eval(yuima@xinit[[email protected]==object@PPR@covariates[i]], envir = env), envir = env) } if(u!=0){ Linc <- env$L[,c(1:(length(part)-1))] Linc[[email protected]!=object@PPR@covariates,] <- 0 DumUnderlMod <- simulate(yuima, true.parameter = true.parameter, increment.L = env$L[,c(1:(length(part)-1))], sampling = setSampling(Terminal = u, n= (length(part)-1))) for(i in c(1:length(object@PPR@covariates))){ VariableDum <- DumUnderlMod@[email protected][,[email protected]==object@PPR@covariates[i]] assign(object@PPR@covariates[i], as.numeric(VariableDum), envir = env) } } } (log(env$U)+sum(eval(env$gFun,envir = env)*env$dt))^2 } Fun2 <- function(u,env){ u <- max(env$old_u,u) dumpart <- seq(0,env$old_u, by=env$dt) part <- seq(env$old_u,u,by=env$dt) t_k <- env$t env$t<-part[-length(part)] if(u>=sampling@Terminal){ my.env$utrue<-u return(0) } if(Condcovariate){ LevIncr <- env$L[, length(dumpart)+c(1:(length(env$t)))] LevIncr[object@[email protected],]<-0 yuima<- object@model xinit<- numeric(length(object@PPR@covariates)) names(xinit)<- object@PPR@covariates for(i in c(1:length(object@PPR@covariates))){ xinit[i] <- env[[object@PPR@covariates[i]]] } xinitCount <- numeric(length(object@[email protected])) names(xinitCount) <- object@[email protected] for(i in c(1:length(xinitCount))){ xinitCount[i] <- tail(env[[object@[email protected][i]]],n = 1) } xinit <- c(xinit,xinitCount) if(part[length(part)]-part[1]!=0){ DumVarCov <- simulate(yuima, true.parameter = true.parameter, increment.L = LevIncr, sampling = setSampling(Terminal = (part[length(part)]-part[1]), n = dim(LevIncr)[2]), xinit=xinit[[email protected]]) for(i in c(1:length(object@PPR@covariates))){ VariableDum <- DumVarCov@[email protected][,[email protected]==object@PPR@covariates[i]] assign(object@PPR@covariates[i], as.numeric(VariableDum), envir = env) } }else{ for(i in c(1:length(object@PPR@covariates))){ VariableDum <- xinit[[email protected]==object@PPR@covariates[i]] assign(object@PPR@covariates[i], as.numeric(VariableDum), envir = env) } } } integG <-sum(eval(env$gFun,envir = env)*env$dt) env$s <- unique(c(env$s,t_k))[-length(env$s)] dumt <- env$t num <- length(env$Kern) integKer <- 0 for(j in c(1:length(dumt))){ env$t <- dumt[j] dumKernInt <- 0 for(i in c(1:num)){ lab.dx <- [email protected][i] dumKernInt <- dumKernInt+sum(eval(env$Kern,envir=env)*diff(eval(env[[lab.dx]]))) } integKer <- integKer + dumKernInt } NewTerm <- 0 if(env$Condcovariate){ } my.env$utrue<-u (log(env$U)+ integG + integKer+NewTerm)^2 } u <- numeric(length = numbCountVar) names(u) <- object@[email protected] for(i in c(1:numbCountVar)){ assign("gFun", object@gFun@formula[[i]], envir=my.env) assign("U",runif(1),envir = my.env) u[i]<- as.numeric(optim(0,Fun1,env=my.env)$par) } t_1 <- min(u) if(t_1>Time){ yuima.stop("No jump occurs in the considered time interval. Increasing Terminal in setSampling is suggested") } condt1<- u%in%t_1 namesContVarJump <- names(u[condt1]) JUMP <- matrix(0,nrow=numbCountVar,ncol=sampling@n) rownames(JUMP)<- object@[email protected] pos<-sum(sampling@grid[[1]][-1]<=t_1) t_1 <- sampling@grid[[1]][-1][pos] recordTime<-c(0,t_1) pos0<-0 JUMP[namesContVarJump, pos] <- L[namesContVarJump, pos] ntot <- sampling@n dL <- L dL[object@[email protected],c((pos0+1):pos)]<-JUMP[object@[email protected],c((pos0+1):pos)] X_mat <- matrix(0, length(object@[email protected]), ntot) rownames(X_mat) <- object@[email protected] dummyX <- simulate(object@model, true.parameter = true.parameter, increment.W = if(is.matrix(W[,1:pos])){W[,1:pos]}else{t(as.matrix(W[,1:pos]))}, increment.L = if(is.matrix(dL[,1:pos])){dL[,1:pos]}else{t(as.matrix(dL[,1:pos]))}, sampling = setSampling(Terminal = t_1, n = t_1/sampling@delta)) X_mat[,1:pos] <- t(dummyX@[email protected])[,-1] t_jump <- t_1 if(length(object@[email protected]@var.dx)==1){ Comulat.dx <- apply(t(X_mat[object@[email protected]@var.dx, c((pos0+1):pos)]), 1, diff) }else{ Comulat.dx <- apply(t(X_mat[object@[email protected]@var.dx, c((pos0+1):pos)]), 2, diff) } Index <- matrix(c(1:prod(object@Kernel@Integrand@dimIntegrand)), nrow = object@Kernel@Integrand@dimIntegrand[1], ncol = object@Kernel@Integrand@dimIntegrand[2]) assign(object@[email protected]@var.time, sampling@grid[[1]][c((pos0+1):(pos))], envir = my.env) assign(object@gFun@[email protected], t_1, envir = my.env) for(i in c(1:object@Kernel@Integrand@dimIntegrand[2])){ assign(object@[email protected]@var.dx[i], as.numeric(Comulat.dx[,i]), envir = my.env) } KernDum <- list() for(i in c(1:object@Kernel@Integrand@dimIntegrand[1])){ dumKern <- expression() for(j in c(1:object@Kernel@Integrand@dimIntegrand[2])){ id <- as.numeric(Index[i,j]) dumKern <- c(dumKern,object@Kernel@Integrand@IntegrandList[[id]]) } KernDum[[i]] <- dumKern } udumm <- numeric(length = numbCountVar) names(udumm) <- object@[email protected]@var.dx assign("L",dL,envir = my.env) pos0 <- pos assign("pos0", pos, envir = my.env) assign("old_u",t_1, envir = my.env) while(t_jump<Time){ oldt_1<-t_1 for(i in c(1:numbCountVar)){ assign("gFun", object@gFun@formula[[i]], envir=my.env) assign("Kern", KernDum[[i]], envir=my.env) my.env$utrue<-0 while(my.env$utrue<oldt_1){ assign("U",runif(1),envir = my.env) optim((t_1+2*my.env$dt),Fun2,method = "Nelder-Mead", env=my.env)$par u[i] <- as.numeric(my.env$utrue) } } t_1 <- min(u) condt1<- u%in%t_1 namesContVarJump <- names(u[condt1]) mypos<-sum(sampling@grid[[1]][-1]<=t_1) if((pos0+1)<mypos){ pos<-sum(sampling@grid[[1]][-1]<=t_1) t_jump<- t_1 t_1 <- sampling@grid[[1]][-1][pos] recordTime<-c(recordTime,t_1) pos <- min(pos,dim(L)[2]) JUMP[namesContVarJump, pos] <- L[namesContVarJump, pos] dL[object@[email protected],c((pos0+1):pos)]<-JUMP[object@[email protected],c((pos0+1):pos)] aa<-setSampling(Terminal = (t_1-my.env$old_u), n = length((pos0+1):pos)) dummyX <- simulate(object@model, true.parameter = true.parameter, increment.W = if(is.matrix(W[,(pos0+1):pos])){W[,(pos0+1):pos]}else{t(as.matrix(W[,(pos0+1):pos]))}, increment.L = if(is.matrix(dL[,(pos0+1):pos])){dL[,(pos0+1):pos]}else{t(as.matrix(dL[,(pos0+1):pos]))}, sampling = aa, xinit=X_mat[,(pos0)]) X_mat[,(pos0+1):pos] <- t(dummyX@[email protected])[,-1] if(length(object@[email protected]@var.dx)==1){ Comulat.dx <- apply(t(X_mat[object@[email protected]@var.dx, c((pos0+1):pos)]), 1, diff) }else{ Comulat.dx <- apply(t(X_mat[object@[email protected]@var.dx, c((pos0+1):pos)]), 2, diff) } if(!is.matrix(Comulat.dx)){ Comulat.dx <-t(as.matrix(Comulat.dx)) } Index <- matrix(c(1:prod(object@Kernel@Integrand@dimIntegrand)), nrow = object@Kernel@Integrand@dimIntegrand[1], ncol = object@Kernel@Integrand@dimIntegrand[2]) assign(object@[email protected]@var.time, sampling@grid[[1]][c((pos0+1):(pos))], envir = my.env) assign(object@gFun@[email protected], t_1, envir = my.env) for(i in c(1:object@Kernel@Integrand@dimIntegrand[2])){ assign(object@[email protected]@var.dx[i], as.numeric(Comulat.dx[,i]), envir = my.env) } pos0<-pos assign("pos0", pos, envir = my.env) assign("old_u",t_1, envir = my.env) } assign("L",dL,envir = my.env) } X_mat[namesContVarJump,pos]<-X_mat[namesContVarJump,pos] res.dum <- list(X_mat=X_mat,timeJump = recordTime, grid=sampling) solve.variable <-unique(c(object@[email protected])) N.VarPPR<-length(solve.variable) dummy.mod <- setModel(drift=rep("0",N.VarPPR), diffusion = NULL, jump.coeff = diag(rep("1",N.VarPPR)), measure = object@[email protected]$measure, measure.type = object@[email protected]$type, solve.variable = solve.variable, xinit=c(object@model@xinit)) mynewincr <- if(is.matrix(res.dum$X_mat)){t(as.matrix(apply(cbind(0,res.dum$X_mat),1,diff)))}else{apply(cbind(0,res.dum$X_mat),1,diff)} interResMod <- simulate(object = dummy.mod, true.parameter = true.parameter, sampling = sampling, increment.L = mynewincr) resGfun<-new("yuima.Map", Output = object@gFun, yuima=setYuima(model=dummy.mod,sampling = sampling)) interResGfun <- simulate(object = resGfun, true.parameter = true.parameter, sampling = sampling, increment.L = mynewincr) dummyObject <- object@Kernel [email protected]@out.var <-object@[email protected] resInt <- new("yuima.Integral", Integral = dummyObject, yuima = setYuima(model=dummy.mod,sampling = sampling)) interResInt <- simulate(object = resInt, true.parameter = true.parameter, sampling = sampling, increment.L = mynewincr) DataIntensity <- interResGfun@[email protected] + interResInt@[email protected] InterMDia<-zoo(interResMod@[email protected], order.by = index(DataIntensity)) Alldata <-merge(InterMDia,DataIntensity) colnames(Alldata)<-c(solve.variable,object@[email protected]) object@data<-setData(Alldata) return(object) }
context("Check point_extraction...") testthat::test_that("Checking point_extraction..", { point_extraction_tester_func <- function(object,...) { testthat::with_mock( `metaDigitise::MB_extract` = function(...) 1, `metaDigitise::group_scatter_extract` = function(...) 2, `metaDigitise::histogram_extract` = function(...) 3, point_extraction (object) ) } testthat::expect_equal( point_extraction_tester_func(object=list(plot_type="mean_error")), 1, info = "point_extraction failed") testthat::expect_equal( point_extraction_tester_func(object=list(plot_type="scatterplot")), 2, info = "point_extraction failed") testthat::expect_equal( point_extraction_tester_func(object=list(plot_type="histogram")), 3, info = "point_extraction failed") })
effecush <-function(paravec,esternocush,shelter,m){ ordinal<-esternocush[,1] ncovar<-ncol(esternocush) X<-esternocush[,3:ncovar] return(-loglikcushcov(m,ordinal,X,paravec,shelter)) }
splits_reform <- function(df){ df <- df %>% dplyr::filter(DQ != 1, stringr::str_detect(Event, "Diving") == FALSE, stringr::str_detect(Event, "\\s50\\s|\\s50m\\s") == FALSE) %>% dplyr::mutate(F_sec = sec_format(Finals_Time)) %>% dplyr::mutate(dplyr::across(dplyr::starts_with("Split"), ~ sec_format(.x))) %>% dplyr::rowwise() %>% dplyr::mutate(total = sum(dplyr::c_across(Split_50:length(df)), na.rm = TRUE)) %>% dplyr::mutate(not_matching = dplyr::case_when(round(F_sec - total, 2) == 0 ~ FALSE, round(F_sec - total, 2) != 0 ~ TRUE)) return(df) }
EMSRb_internal = function (Fare = Fare, Mean = Mean, Var = Var, p_up = numeric(length(Fare)), cap = cap) { N_FProd <- length(Fare) tmp <- sort.int(Fare, decreasing=T, method = "sh", index.return=TRUE) Fare <- tmp$x ind <- tmp$ix Mean <- Mean[ind] Var <- Var[ind] p_up <- p_up[ind] p <- vector(mode="numeric", length(Fare)) for (i in 1:(length(Fare)-1)) { wr <- sum(Fare[1:i]*Mean[1:i])/sum(Mean[1:i]) X <- sum(Mean[1:i]) Sigma <- sqrt(sum(Var[1:i])) p[i] <- qnorm((1 / (1 - p_up[i+1])) * (1 - Fare[i+1]/wr), mean=X, sd=Sigma) } p[length(Fare)] <- cap p <- ceiling(p) p <- p * (p < cap) + cap * (p >= cap) names(p) <- as.character(Fare) return(p) }
sd.start <- function(...){ cat("\n","\n") cat("Welcome to the Scenario Discovery toolkit","\n","\n") cat("Copyright (C) 2009 Evolving Logic","\n") nicecat("This program comes with ABSOLUTELY NO WARRANTY; for details type 'sdwarranty()' when you are back at the R command prompt. This is free software, and you are welcome to redistribute it under certain conditions; when you are not in this dialogue, type 'RShowDoc('COPYING')' for the complete GNU General Public License, which states these conditions.") cat("\n") cat("Note, unless you are asked specifically, you do not need to include quotes","\n", "around your responses to dialogues, including filenames and directories.", "\n", "(Nor do you need them when the dialogue uses single quotes to tell you possible responses - as in 'y' or 'n')","\n","\n", "However, directory specifications should use forward slashes or double", "\n", "backslashes, and all dialogues require you to press ENTER to end the dialogue.","\n") cat("\n","\n") cat("====== SETTING THE WORKING DIRECTORY ======","\n") cat("The current working directory is:", "\n") cat(getwd()) cat("\n","\n") dirnotset <- TRUE while(dirnotset){ wkdir <- readline(cat("Please enter the directory for you analysis, or enter 'a' to accept","\n","the current directory.","\n")) cat("\n") if (wkdir != "a"){ tryout <- try(setwd(wkdir)) if(class(tryout)=="try-error"){ cat("Sorry, can't seem to change to the directory you entered. Please try again.") cat("\n") cat("\n") } else { dirnotset <- FALSE cat("Working directory changed to","\n",getwd(),"\n","\n") } } else { dirnotset <- FALSE cat("Directory remains the same as above.","\n","\n") } } cat("If you ever need to change the directory later, the R command is:","\n", "setwd(\"the new path\") (using quotes around the path)","\n","\n") cat("====== READING IN YOUR DATA ======","\n") nicecat("Future versions will give a choice between csv, rda files and mySQL databases.") cat("\n") nicecat("mySQL is not yet implemented, so for now, please enter the name of the csv or rda file containing your data (no quotes, but include the .csv or .rda extension).") cat("\n") filename <- readline(nicecat("Note, it is assumed that your csv file begins with a row of column names. If that is not the case, enter 'doh' instead of the filename.")) if(filename!="doh"){ nc <- nchar(filename) lastthree <- substr(filename,(nc-2),nc) if(lastthree=="rda"){ gotloaded <- load(filename) mydata <- get(gotloaded) rm(list=gotloaded) } else if(lastthree=="csv"){ mydata <- read.csv(filename) } } else if (filename=="doh"){ cat("\n") cat("If your csv file does not start with a row of column names, you can accept","\n", "'bland' names from R (such as 'V1', 'V2', 'V3', etc, or you can exit this","\n", "program and modify your input file to include column names, or you can","\n", "specify them by hand inside this program.","\n") howtofix <- readline(cat("Which would you like to do? Enter 'bland', 'exit', or 'specify'.","\n")) if (howtofix=="exit"){ stop("You chose to exit and fix your column names. Rerun this program when done.") } else if (howtofix=="bland"){ filename <- readline(cat("You chose to accept bland names given by R. Please enter your csv filename:","\n")) mydata <- read.csv(filename,header=FALSE) } else if(howtofix=="specify"){ filename <- readline(cat("You chose to specify your column names. Please enter your csv filename first:","\n")) mydata <- read.csv(filename,header=FALSE) satisfied <- FALSE while(!satisfied){ vars <- readline(cat("Your data appears to contain",ncol(mydata),"variables (columns).","\n", "Please enter that many variable names separated by commas. For example:","\n", "Myvar1,Coolvar2,spiffy3,regret ","\n")) tcnames <- strsplit(vars,",")[[1]] ok <- readline(cat("You entered the following column names:","\n",tcnames,"\n","Is this ok? ('y' or 'n')","\n")) if(ok=='n'){ cat("You're not satisfied, try re-entering again.","\n") satisfied <- FALSE } if(ok=='y'){ cat("Great. Let's move on.","\n") satisfied <- TRUE } } } } cat("\n") cat("You chose the following file:","\n") cat(getwd(),"/",filename,sep="","\n","\n") cat("As read in by R, your data has",nrow(mydata),"rows (cases) and",ncol(mydata),"columns (variables).") cat("\n") cat("\n") nas <- is.na(mydata) nans <- apply(mydata,2,is.nan) infs <- apply(mydata,2,is.infinite) chars <- any(apply(mydata,2,is.character)) if(chars){ stop(cat("ERROR! You have character values in your input file, which at present are too difficult for R and this program to fix or handle appropriately. This program will now exit so you can inspect your data and translate or remove character values. If they are character representations of binary or ORDINAL variables (eg \"win\" and \"lose\" or \"low\", \"med\",\"high\"), this program should handle them appropriately provided they are converted to numbers prior to reading them in. If they represent unordered categorical variables, this program is not yet capable of handling that. If you need to rely heavily on true categorical variables, please consider using the SuperGEM implementation of PRIM (available free online).","\n")) } if(any(c(nas,nans,infs))){ cat("WARNING: The data contains non-finite values, specifically some mix of","\n", " 'NA', 'NaN', or +/- 'Inf'.","\n","These could quite likely break the algorithms.","\n") inspect <- readline(cat("To find out more, enter 'inspect', otherwise enter 'fine' to take your chances","\n")) cat("\n") if(inspect=="inspect"){ if(any(nas)){ cat("There are",sum(nas),"'NA' values (including 'NaN'), distributed throughout the following columns:",c(1:ncol(mydata))[apply(nas,2,any)]) cat("\n") } if(any(nans)){ cat("There are",sum(nans),"'NaN' values, distributed throughout the following columns:",c(1:ncol(mydata))[apply(nans,2,any)]) cat("\n") } if(any(infs)){ cat("There are",sum(infs),"infinite values, distributed throughout the following columns:",c(1:ncol(mydata))[apply(infs,2,any)]) cat("\n") } cat("\n") cat("Chances are these values will mess up the scenario discovery tools, ","\n", "but you have three options: Ignore them and see what happens, drop rows containing weird values from the dataset and see what happens, drop variables (columns) containing weird values, or exit this program and fix your data however you choose.","\n","\n") whattodo <- readline(cat("Which would you like? Enter 'ignore', 'droprows', 'dropvars', or 'fix'.","\n")) anybad <- !((!nas)*(!infs)) if(whattodo=="fix"){ stop("You chose to fix it. Restart this program when you are done.") } else if(whattodo=="droprows"){ cat("You chose to drop records that have weird data.","\n") badrows <- apply(anybad,1,any) dropok <- readline(cat("This will drop",sum(badrows),"out of",nrow(mydata),"rows. Is that ok? (Enter 'y' or 'n')","\n")) if(dropok=='y'){ mydata <- mydata[!badrows,] } else if(dropok=='n'){ cat("\n") stop(cat("You have bad data and you said dropping that data was not ok. Please rerun this program after you fixed your data.")) } } else if(whattodo=="dropvars"){ badcols <- apply(anybad,2,any) cat("You chose to drop variables containing weird entries.","\n") dropok <- readline(cat("This will drop the following columns out of",ncol(mydata),"columns total:", c(1:ncol(mydata))[badcols],"\n", "Is that ok? (Enter 'y' or 'n')","\n")) if(dropok=='y'){ mydata <- mydata[,!badcols] } else if(dropok=='n'){ stop(cat("You have bad data and you said dropping that data was not ok. Please rerun this program after you fixed your data.")) } } else if(whattodo=="ignore"){ cat("You chose to keep the data as is and see what happens.") } cat("\n") cat("After making any modifications describe above, your data now contains",nrow(mydata),"rows and",ncol(mydata),"columns.") cat("\n") cat("\n") } } cat("The variable names (and column number) are as follows:","\n") print(matrix(colnames(mydata),ncol=1, dimnames=list(c(1:ncol(mydata))," name"))) cat("\n") datagood <- readline(cat("Are the size and variables as expected? If so enter 'y', if not enter 'n'. (Note that you will be able to specify a subset of variables you'd like to use in the analysis later.)","\n")) if(datagood=="n"){cat("\n","If the data does not look as you expected it to, there are a few possible causes, though 'NA' related causes should have been taken care of above. If you have one fewer row than expected, you maybe lied when you implied that your data had column names in the first row. Inspect your csv file to see if that is the case. If so, either name your columns and start this program over, or keep them unnamed and start the program over and enter 'doh' at the appropriate place in dialogue, and R will give your data bland names (like \"V1\",\"V2\",\"V10\").") keepgoing <- readline(cat("To continue anyway, enter 'y', to stop enter 'n'.","\n")) if(keepgoing=="n"){ stop("Alright, see you next time.") } } x <- mydata xfull <- x repcols <- logical(length=ncol(x)) for (i in 1:ncol(x)){ if (isTRUE(all.equal(xfull[,i],rep(x[1,i],nrow(x))))){repcols[i] <- TRUE} } if(any(repcols)){ cat("\n") cat("==== WARNING ====","\n") cat("The following columns were identified as containing entirely single values:","\n") for(i in which(repcols)){ cat("Column", i, "corresponding to the variable", colnames(x)[i],"\n") } cat("\n") cat("Because they show no variation, it is impossible for these variables to play a role in the box definition, and they will be removed and/or ignored to avoid fouling up the algorithms.") mydata <- x[,!repcols] } else{ cat("\n","Checked for columns with all identical entries - none found.") } cat("\n") cat("\n") dupout <- dupcolchecker(mydata) if(length(dupout)==1){ if(dupout=="nodups"){ } } else if (is.vector(dupout)){ nicecat("Here's the vector of columns that should be deleted. These remain in the dataset for now and may cause problems.") print(dupout) } else { mydata <- dupout } mydata <- as.matrix(mydata) varsatisfied <- FALSE while(!varsatisfied){ cat("====== SELECTING VARIABLES FOR ANALYSIS ======","\n","\n") satisfied <- FALSE while(!satisfied){ cat("To remind you, your data has the following variables:","\n") cat("\n") print(matrix(colnames(mydata),ncol=1, dimnames=list(c(1:ncol(mydata))," name"))) cat("\n") sensicalinput <- FALSE while(!sensicalinput){ sensicalinput <- TRUE nicecat("Please specify which variables you would like to have the algorithms consider as input variables. If you would like to specify all variables from column number X to column Y, you can enter 'X:Y'. If you only want specific variables, you can enter them separated by commas, for example: '1,2,3,6,7' (You can also mix, like '1,3,5:7'.)") cat("\n") inputvars <- readline(nicecat("Also, note that if you modified columns above, you will need to specify the new column numbers since they may have changed from the original dataset.")) cat("\n") tinputvars <- as.vector(strsplit(inputvars,",")[[1]]) hascolon <- grep(":",tinputvars) inputvars <- c() for (i in 1:length(tinputvars)){ if(i %in% hascolon){ cols <- as.numeric(as.vector(strsplit(tinputvars[i],":")[[1]])) inputvars <- c(inputvars,c(cols[1]:cols[2])) } else { inputvars <- c(inputvars,as.numeric(tinputvars[i])) } } if(length(inputvars)==1){ cat("\n","You selected only one input variable, which doesn't make sense for using PRIM.","\n", "Try again.","\n") sensicalinput <- FALSE } } cat("You selected the following input variables:,","\n") cat("\n") print(matrix(colnames(mydata),ncol=1, dimnames=list(c(1:ncol(mydata)),"name"))[inputvars,]) cat("\n") good <- readline(cat("Is this correct? Enter 'y' to accept or 'n' to try again.","\n")) if (good=='y'){ satisfied <- TRUE } } satisfied <- FALSE while(!satisfied){ cat("Here are the remaining variables (those not already designated as input variables:","\n") cat("\n") coln <- 1:ncol(mydata) print(matrix(matrix(colnames(mydata),ncol=1, dimnames=list(c(1:ncol(mydata)),"name"))[-inputvars,],ncol=1,dimnames=list(coln[-inputvars],"name"))) cat("\n") outputvars <- readline(cat("Please specify which variables you would like to have the algorithms consider as OUTPUT variables, using the same format as for input variables.","\n")) cat("\n") toutputvars <- as.vector(strsplit(outputvars,",")[[1]]) hascolon <- grep(":",toutputvars) outputvars <- c() for (i in 1:length(toutputvars)){ if(i %in% hascolon){ cols <- as.numeric(as.vector(strsplit(toutputvars[i],":")[[1]])) outputvars <- c(outputvars,c(cols[1]:cols[2])) } else { outputvars <- c(outputvars,as.numeric(toutputvars[i])) } } cat("You selected the following output variables:","\n") print(matrix(colnames(mydata),ncol=1, dimnames=list(c(1:ncol(mydata))," name"))[outputvars,]) cat("\n") good <- readline(cat("Is this correct? Enter 'y' to accept or 'n' to try again.","\n")) if (good=='y'){ satisfied <- TRUE } } cat("\n") cat("====== PLOTTING HISTOGRAMS AND CDFs ======","\n") cat("There should now be one or more graphics windows open displaying useful","\n") cat("histograms and cdfs to help you choose a threshold for your data.","\n", "reactivate this window to continue the dialogue.") oldpar <- par(no.readonly = TRUE) graphics.off() for (i in 1:length(outputvars)){ xname = colnames(mydata)[outputvars[i]] options("device")$device(width=14) par(mfcol=c(1,2)) hist(mydata[,outputvars[i]],xlab=xname,main = paste("Histogram of",xname),breaks=10) plot.ecdf(mydata[,outputvars[i]],xlab=xname, main = paste("Empirical CDF of",xname), ylab=paste("Fn(",xname,")",sep=""), verticals=TRUE) } par(oldpar) cat("\n") cat("\n") cat("====== CHOOSING THRESHOLDS ======") threshvals <- vector(length=length(outputvars)) threshhighlow <- vector(length=length(outputvars)) for (i in 1:length(outputvars)){ threshsatisfied <- FALSE while(!threshsatisfied){ cat("\n") uplownone <- readline(cat("For variable",colnames(mydata)[outputvars[i]],"would you like to define a: 1. Upper Threshold (values above are 1, values below are 0) 2. Lower Threshold (values below are 1, values above are 0) 3. No Threshold (Enter '1', '2' or '3')","\n")) if(!(uplownone=="1" | uplownone=="2" | uplownone=="3")){ cat("Invalid entry, please try again.","\n") } else { if(uplownone=="3"){ cat("You chose not to define a threshold. Moving on...","\n") threshhighlow[i] <- "3" threshsatisfied <- TRUE } else { if(uplownone=="1"){ ulnchar <- "upper" upthresh <- readline(cat("You chose to define an upper threshold. Please enter it now:","\n")) upthresh <- as.numeric(upthresh) at <- sum(mydata[,outputvars[i]]>upthresh) tot <- nrow(mydata) cat("Using",upthresh,"as a threshold, you will have:","\n", at,"out of",tot,"above the threshold (",100*at/tot,"percent)","\n", (tot-at),"out of",tot,"below the threshold (",100*(1-at/tot),"percent)","\n") cat("\n") } if(uplownone=="2"){ ulnchar <- "lower" lthresh <- readline(cat("You chose to define a lower threshold. Please enter it now:","\n")) lthresh <- as.numeric(lthresh) at <- sum(mydata[,outputvars[i]]<lthresh) tot <- nrow(mydata) cat("Using",lthresh,"as a lower threshold, you will have:","\n", at,"out of",tot,"below the threshold (",100*at/tot,"percent becoming '1's)","\n", (tot-at),"out of",tot,"above the threshold (",100*(1-at/tot),"percent becoming '0's)","\n") cat("\n") } cat("Are you satisfied with this threshold for this variable?","\n") keeporno <- readline(cat("Enter 'y' or 'n'","\n")) if(keeporno=="y"){ if(uplownone=="1"){ threshvals[i] <- upthresh threshhighlow[i] <- uplownone } else{ threshvals[i] <- lthresh threshhighlow[i] <- uplownone } threshsatisfied <- TRUE } else{ cat("\n") nicecat("You said you were unsatisfied - try again, or move on by selecting option 3 below.") } } } } } infinalq <- TRUE while(infinalq){ cat("\n") cat("Would you like to: 1) save your cleaned data so you can call sdprim directly in the future 2) begin the PRIM analysis using 'sdprim', calling it from this program? 3) redefine variables? 4) start over from the very beginning, possibly with a new dataset? 5) exit this dialogue, and possibly begin the PRIM analysis on your own using the 'sdprim' command? (Recommended if you wish to change some parameters from their defaults.) ","\n") whattodo <- readline(cat("(Enter '1', '2','3','4' or '5')","\n")) cat("\n") infinalq <- FALSE varsatisfied <- TRUE if (whattodo =="1"){ inputneeded <- TRUE infinalq <- TRUE while(inputneeded){ nicecat("If your dataset was modified above, you might like to save a copy of the modified version so that in the future you can run sdprim directly, without needing to 'fix' your data. If you would like to save a copy, either a csv or rda file, then enter the filename you would like to save it as, including the extension, and it will automatically save in appropriate format. Otherwise enter 'n'.") cat("\n") savetype <- readline(nicecat("(Note that this will not save the thresholded data as an addition to your dataset - rather, it will simply save the original dataset, but without the rows and columns and entries that caused problems.)")) nc <- nchar(savetype) if(nc > 4){ ext <- substr(savetype, nc-3,nc) if(ext==".csv" | ext==".rda"){ if(ext==".csv"){ write.csv(mydata, file=savetype, row.names=FALSE) } else { save(mydata, file=savetype) } inputneeded <- FALSE cat("\n") cat("Modified data saved as file", savetype,"\n") cat("\n") } else { nicecat("Sorry, you input a filename that is either missing an extension, or does not have an extension that matches the currently allowed forms of either rda or csv. You will now be returned to the start of the data-saving dialogue.") cat("\n") cat("\n") } } else { inputneeded <- FALSE nicecat("You decided not to save.") } } } else if (whattodo =="2"){ cat("\n") cat("\n") cat(" ====== Running PRIM Analysis ====== ","\n") if(length(outputvars)!=1){ cat("\n") cat("Which output variable would you like?","\n") cat("(If you defined a threshold it will be used, if not the output variable should already be binary.)","\n") coln <- 1:ncol(mydata) print(matrix(matrix(colnames(mydata),ncol=1, dimnames=list(c(1:ncol(mydata)),"name"))[outputvars,],ncol=1,dimnames=list(coln[outputvars],"name"))) cat("\n") outputvar <- as.numeric(readline(cat("Enter the number next to the variable you would like to use","\n"))) }else{ cat("You chose to run PRIM and you only had only identified one output variable:","\n") print(colnames(mydata)[outputvars]) cat("\n") outputvar <- outputvars } vec <- mydata[,outputvar] looksbinary <- all(vec==0 | vec==1) theind <- which(outputvars==outputvar) if(!(threshhighlow[theind]=="1" | threshhighlow[theind]=="2") & !looksbinary){ cat("You did not previously select a threshold for this variable.","\n") cat("Also it does not appear to be binary. Thus you will need to start over,","\n", "at the variable selection phase, which you will be returned to now.") infinalq <- FALSE varsatisfied <- FALSE } else { if(threshhighlow[theind]=="3"){ cat("You did not previously select a threshold for this variable.","\n") cat("Fortunately, it appears to already be binary, so it will get used as is.","\n") yvec <- mydata[,outputvar] } else if(threshhighlow[theind]=="1"){ cat("Earlier, you defined an upper threshold of",threshvals[theind],"\n", "This will be used for the PRIM analysis.","\n") yvec <- 1*mydata[,outputvar]>threshvals[theind] } else if(threshhighlow[theind]=="2"){ cat("Earlier, you defined a lower threshold of",threshvals[theind],"\n", "This will be used for the PRIM analysis.","\n") yvec <- 1*mydata[,outputvar]<threshvals[theind] } cat("\n") cat("\n") cat("PRIM will be using the following input variables:","\n") cat("\n") print(matrix(colnames(mydata),ncol=1, dimnames=list(c(1:ncol(mydata)),"name"))[inputvars,]) cat("\n") cat("And the following output variable: ") print(colnames(mydata)[outputvar]) cat("\n") cat("\n") cat("The default arguments for sdprim are listed below:","\n") c("\n") sdpformals <- formals(sdprim) for (i in 3:length(sdpformals)){ if(!identical(sdpformals[[i]],"")){ if(is.character(sdpformals[[i]])){ cat(" ",names(sdpformals)[i],"=");cat(c(),sdpformals[[i]],c(),sep="\"","\n") } else if(is.null(sdpformals[[i]])){ cat(" ",names(sdpformals)[i],"=","NULL","\n") } else if(sdpformals[[i]]==""){ } else{ cat(" ",names(sdpformals)[i],"=",sdpformals[[i]],"\n") } } } cat("\n") sdscall <- match.call() if(length(match.call())>1){ cat("Based on the arguments passed to sd.start, these will be modified as follows:") cat("\n") for (i in 2:length(sdscall)){ cat(" ",names(sdscall)[i],"=",sdscall[[i]],"\n") } } cat("\n") mod <- readline(cat("Would you like to modify them further? (enter 'y' or 'n')","\n")) if(mod=="y"){ nicecat("Please enter the arguments you would like to change, specifying the argument name followed by an = sign, followed by the value of the argument, with each argument separated by a comma.") cat("For example, you might enter:","\n") cat("peel.alpha=.2, outfile=\"somethingnew.txt\"","\n") newargs <- readline() eacharg <- strsplit(newargs,",") argvals <- strsplit(eacharg[[1]],"=") backtogether <- argvals for (i in 1:length(argvals)){ for (j in 1:length(argvals[[i]])){ allchars <- strsplit(argvals[[i]][j],"")[[1]] notspaces <- which(allchars!=" " & allchars!="\"") backtogether[[i]][j] <- paste(allchars[notspaces],collapse="") } currwarn <- getOption("warn") options(warn=-1) assig <- backtogether[[i]][2] if(!is.na(as.logical(assig))){ sdscall[[backtogether[[i]][1]]] <- as.logical(assig) } else if (!is.na(as.numeric(assig))){ sdscall[[backtogether[[i]][1]]] <- as.numeric(assig) } options(warn=currwarn) } } cat("\n") cat("\n") cat("\n") cat("====== NOW ENTERING SDPRIM FUNCTION ======","\n") cat("\n") flush.console() sdscall$x <- mydata[,inputvars] sdscall$y <- yvec sdscall[[1]] <- sdprim sdprimresults <- eval(sdscall) return(sdprimresults) } } else if (whattodo=="3"){ infinalq <- FALSE varsatisfied <- FALSE cat("\n") cat("You chose to redefine variables.","\n") } else if (whattodo=="4"){ cat("\n") cat("You chose to start over from the beginning.","\n") cat("For now, please implement that yourself after this program exits by typing 'sd.start()' at the command line you are about to see. Thanks.") cat("\n") infinalq <- FALSE } else if (whattodo=="5"){ cat("\n") cat("Have fun.","\n") cat("\n") infinalq <- FALSE } else {cat("\n") cat("Didn't recognize what you entered - please try again.","\n") infinalq <- TRUE } } } }
rdplot = function(y, x, c=0, p=4, nbins = NULL, binselect = "esmv", scale = NULL, kernel = "uni", weights = NULL, h = NULL, covs = NULL, covs_eval = "mean", covs_drop = TRUE, ginv.tol = 1e-20, support = NULL, subset = NULL, masspoints = "adjust", hide = FALSE, ci = NULL, shade = FALSE, title = NULL, x.label = NULL, y.label = NULL, x.lim = NULL, y.lim = NULL, col.dots = NULL, col.lines = NULL) { if (!is.null(subset)) { x <- x[subset] y <- y[subset] } na.ok <- complete.cases(x) & complete.cases(y) if (!is.null(covs)){ if (!is.null(subset)) covs <- subset(covs,subset) na.ok <- na.ok & complete.cases(covs) } if (!is.null(weights)){ if (!is.null(subset)) weights <- weights[subset] na.ok <- na.ok & complete.cases(weights) & weights>=0 } x <- x[na.ok] y <- y[na.ok] if (!is.null(covs)) covs = as.matrix(covs)[na.ok, , drop = FALSE] if (!is.null(weights)) weights = as.matrix(weights[na.ok]) x_min = min(x); x_max = max(x) x_l = x[x<c]; x_r = x[x>=c] y_l = y[x<c]; y_r = y[x>=c] if (!is.null(support)) { support_l = support[1] support_r = support[2] if (support_l<x_min) x_min = support_l if (support_r>x_max) x_max = support_r } range_l = c - x_min range_r = x_max - c n_l = length(x_l) n_r = length(x_r) n = n_l + n_r meth="es" if (is.null(scale)) { scale = scale_l = scale_r = 1 } else{ if (length(scale)==1) scale_l = scale_r = scale if (length(scale)==2) { scale_l = scale[1] scale_r = scale[2] } } if (!is.null(nbins)) { if (length(nbins)==1) nbins_l = nbins_r = nbins if (length(nbins)==2) { nbins_l = nbins[1] nbins_r = nbins[2] } } if (is.null(h)) { h_l = range_l h_r = range_r } else{ if (length(h)==1) h_l = h_r = h if (length(h)==2) { h_l = h[1] h_r = h[2] } } flag_no_ci <- FALSE if (is.null(ci)) { ci<- 95 flag_no_ci <- TRUE } kernel_type = "Uniform" if (kernel=="epanechnikov" | kernel=="epa") kernel_type = "Epanechnikov" if (kernel=="triangular" | kernel=="tri") kernel_type = "Triangular" if (is.null(masspoints)) masspoints=FALSE mN = n M_l = n_l M_r = n_r if (masspoints=="check" | masspoints=="adjust") { X_uniq_l = sort(unique(x_l), decreasing=TRUE) X_uniq_r = unique(x_r) M_l = length(X_uniq_l) M_r = length(X_uniq_r) M = M_l + M_r mass_l = 1-M_l/n_l mass_r = 1-M_r/n_r if (mass_l>=0.2 | mass_r>=0.2){ print("Mass points detected in the running variable.") if (masspoints=="check") print("Try using option masspoints=adjust.") if (masspoints=="adjust") { if (binselect=="es") binselect="espr" if (binselect=="esmv") binselect="esmvpr" if (binselect=="qs") binselect="qspr" if (binselect=="qsmv") binselect="qsmvpr" } } } covs_drop_coll=dZ=0 if (covs_drop == TRUE) covs_drop_coll = 1 if (!is.null(covs)) { covs.names = colnames(covs) if (is.null(covs.names)) { covs.names = paste("z",1:ncol(covs),sep="") colnames(covs) = covs.names } covs = covs[,order(nchar(covs.names))] covs = as.matrix(covs) dZ = length(covs.names) covs.check = covs_drop_fun(covs) if (covs.check$ncovs < dZ & covs_drop==FALSE) { print("Multicollinearity issue detected in covs. Please rescale and/or remove redundant covariates, or use covs_drop option.") } if (covs.check$ncovs < dZ & isTRUE(covs_drop)) { covs <- as.matrix(covs.check$covs) dZ <- covs.check$ncovs } } exit=0 if (c<=x_min | c>=x_max){ print("c should be set within the range of x") exit = 1 } if (kernel!="uni" & kernel!="uniform" & kernel!="tri" & kernel!="triangular" & kernel!="epa" & kernel!="epanechnikov" & kernel!="" ){ print("kernel incorrectly specified") exit = 1 } if (p<0 ){ print("p should be a positive number") exit = 1 } if (scale<=0 |scale_l<=0 |scale_r<=0){ print("scale should be a positive number") exit = 1 } p_ceiling = ceiling(p)/p if (p_ceiling!=1 & p>0) { print("p should be an integer number") exit = 1 } if (n<20){ print("Not enough observations to perform bin calculations") exit = 1 } if (exit>0) stop() R_p_l = matrix(NA,n_l,p+1); R_p_r = matrix(NA,n_r,p+1) for (j in 1:(p+1)) { R_p_l[,j] = (x_l-c)^(j-1) R_p_r[,j] = (x_r-c)^(j-1) } W_h_l = rdrobust_kweight(x_l,c,h_l,kernel) W_h_r = rdrobust_kweight(x_r,c,h_r,kernel) n_h_l = sum(W_h_l>0) n_h_r = sum(W_h_r>0) if (!is.null(weights)) { fw_l=weights[x<c]; fw_r=weights[x>=c] W_h_l = fw_l*W_h_l; W_h_r = fw_r*W_h_r } invG_p_l = qrXXinv((sqrt(W_h_l)*R_p_l)); invG_p_r = qrXXinv((sqrt(W_h_r)*R_p_r)) if (is.null(covs)) { gamma_p1_l = invG_p_l%*%crossprod(R_p_l*W_h_l, y_l) gamma_p1_r = invG_p_r%*%crossprod(R_p_r*W_h_r, y_r) } else { z_l = covs[x<c,]; z_r = covs[x>=c,] D_l = cbind(y_l,z_l); D_r = cbind(y_r,z_r) U_p_l = crossprod(R_p_l*W_h_l,D_l); U_p_r = crossprod(R_p_r*W_h_r,D_r) beta_p_l = invG_p_l%*%crossprod(R_p_l*W_h_l,D_l); beta_p_r = invG_p_r%*%crossprod(R_p_r*W_h_r,D_r); ZWD_p_l = crossprod(z_l*W_h_l,D_l) ZWD_p_r = crossprod(z_r*W_h_r,D_r) colsZ = 2:max(c(2+dZ-1,2)) UiGU_p_l = crossprod(U_p_l[,colsZ],invG_p_l%*%U_p_l) UiGU_p_r = crossprod(U_p_r[,colsZ],invG_p_r%*%U_p_r) ZWZ_p_l = ZWD_p_l[,colsZ] - UiGU_p_l[,colsZ] ZWZ_p_r = ZWD_p_r[,colsZ] - UiGU_p_r[,colsZ] ZWY_p_l = ZWD_p_l[,1] - UiGU_p_l[,1] ZWY_p_r = ZWD_p_r[,1] - UiGU_p_r[,1] ZWZ_p = ZWZ_p_r + ZWZ_p_l ZWY_p = ZWY_p_r + ZWY_p_l if (covs_drop_coll == 0) gamma_p = chol2inv(chol(ZWZ_p))%*%ZWY_p if (covs_drop_coll == 1) gamma_p = ginv(ZWZ_p, tol = ginv.tol)%*%ZWY_p s_Y = c(1 , -gamma_p[,1]) gamma_p1_l = t(s_Y%*%t(beta_p_l)) gamma_p1_r = t(s_Y%*%t(beta_p_r)) } nplot = 500 x_plot_l = seq(c-h_l, c, length.out =nplot) x_plot_r = seq(c, c+h_r, length.out =nplot) rplot_l = matrix(NA,nplot,p+1); rplot_r = matrix(NA,nplot,p+1) for (j in 1:(p+1)) { rplot_l[,j] = (x_plot_l-c)^(j-1) rplot_r[,j] = (x_plot_r-c)^(j-1) } y_hat_l = rplot_l%*%gamma_p1_l y_hat_r = rplot_r%*%gamma_p1_r if (!is.null(covs) & covs_eval=="mean" ) { gammaZ = colMeans(covs)%*%gamma_p y_hat_l = rplot_l%*%gamma_p1_l + c(gammaZ) y_hat_r = rplot_r%*%gamma_p1_r + c(gammaZ) } k=4 rk_l = matrix(NA,n_l,(k+1)) rk_r = matrix(NA,n_r,(k+1)) for (j in 1:(k+1)) { rk_l[,j] = x_l^(j-1) rk_r[,j] = x_r^(j-1) } invG_k_l = try(qrXXinv(rk_l),silent=TRUE) invG_k_r = try(qrXXinv(rk_r),silent=TRUE) if (class(invG_k_l)[1] == "try-error" | class(invG_k_r)[1] == "try-error") { k = 3 rk_l = matrix(NA,n_l,(k+1)) rk_r = matrix(NA,n_r,(k+1)) for (j in 1:(k+1)) { rk_l[,j] = x_l^(j-1) rk_r[,j] = x_r^(j-1) } invG_k_l = try(qrXXinv(rk_l),silent=TRUE) invG_k_r = try(qrXXinv(rk_r),silent=TRUE) } if (class(invG_k_l)[1] == "try-error" | class(invG_k_r)[1] == "try-error") { k = 2 rk_l = matrix(NA,n_l,(k+1)) rk_r = matrix(NA,n_r,(k+1)) for (j in 1:(k+1)) { rk_l[,j] = x_l^(j-1) rk_r[,j] = x_r^(j-1) } invG_k_l = qrXXinv(rk_l) invG_k_r = qrXXinv(rk_r) } gamma_k1_l = invG_k_l%*%crossprod(rk_l, y_l) gamma_k2_l = invG_k_l%*%crossprod(rk_l, y_l^2) gamma_k1_r = invG_k_r%*%crossprod(rk_r, y_r) gamma_k2_r = invG_k_r%*%crossprod(rk_r, y_r^2) mu0_k1_l = rk_l%*%gamma_k1_l mu0_k1_r = rk_r%*%gamma_k1_r mu0_k2_l = rk_l%*%gamma_k2_l mu0_k2_r = rk_r%*%gamma_k2_r drk_l = matrix(NA,n_l,k) drk_r = matrix(NA,n_r,k) for (j in 1:k) { drk_l[,j] = j*x_l^(j-1) drk_r[,j] = j*x_r^(j-1) } ind_l = order(x_l); ind_r = order(x_r) x_i_l = x_l[ind_l]; y_i_l = y_l[ind_l] x_i_r = x_r[ind_r]; y_i_r = y_r[ind_r] dxi_l=(x_i_l[2:length(x_i_l)]-x_i_l[1:(length(x_i_l)-1)]) dxi_r=(x_i_r[2:length(x_i_r)]-x_i_r[1:(length(x_i_r)-1)]) dyi_l=(y_i_l[2:length(y_i_l)]-y_i_l[1:(length(y_i_l)-1)]) dyi_r=(y_i_r[2:length(y_i_r)]-y_i_r[1:(length(y_i_r)-1)]) x_bar_i_l = (x_i_l[2:length(x_i_l)]+x_i_l[1:(length(x_i_l)-1)])/2 x_bar_i_r = (x_i_r[2:length(x_i_r)]+x_i_r[1:(length(x_i_r)-1)])/2 drk_i_l = matrix(NA,n_l-1,k); rk_i_l = matrix(NA,n_l-1,(k+1)) drk_i_r = matrix(NA,n_r-1,k); rk_i_r = matrix(NA,n_r-1,(k+1)) for (j in 1:(k+1)) { rk_i_l[,j] = x_bar_i_l^(j-1) rk_i_r[,j] = x_bar_i_r^(j-1) } for (j in 1:k) { drk_i_l[,j] = j*x_bar_i_l^(j-1) drk_i_r[,j] = j*x_bar_i_r^(j-1) } mu1_i_hat_l = drk_i_l%*%(gamma_k1_l[2:(k+1)]) mu1_i_hat_r = drk_i_r%*%(gamma_k1_r[2:(k+1)]) mu0_i_hat_l = rk_i_l%*%gamma_k1_l mu0_i_hat_r = rk_i_r%*%gamma_k1_r mu2_i_hat_l = rk_i_l%*%gamma_k2_l mu2_i_hat_r = rk_i_r%*%gamma_k2_r mu0_hat_l = rk_l%*%gamma_k1_l mu0_hat_r = rk_r%*%gamma_k1_r mu2_hat_l = rk_l%*%gamma_k2_l mu2_hat_r = rk_r%*%gamma_k2_r mu1_hat_l = drk_l%*%(gamma_k1_l[2:(k+1)]) mu1_hat_r = drk_r%*%(gamma_k1_r[2:(k+1)]) mu1_i_hat_l = drk_i_l%*%(gamma_k1_l[2:(k+1)]) mu1_i_hat_r = drk_i_r%*%(gamma_k1_r[2:(k+1)]) var_y_l = var(y_l) var_y_r = var(y_r) sigma2_hat_l_bar = mu2_i_hat_l - mu0_i_hat_l^2 sigma2_hat_r_bar = mu2_i_hat_r - mu0_i_hat_r^2 ind_s2_l = sigma2_hat_l_bar<0 ind_s2_r = sigma2_hat_r_bar<0 sigma2_hat_l_bar[ind_s2_l] = var_y_l sigma2_hat_r_bar[ind_s2_r] = var_y_r sigma2_hat_l = mu2_hat_l - mu0_hat_l^2 sigma2_hat_r = mu2_hat_r - mu0_hat_r^2 ind_s2_l = sigma2_hat_l<0 ind_s2_r = sigma2_hat_r<0 sigma2_hat_l[ind_s2_l] = var_y_l sigma2_hat_r[ind_s2_r] = var_y_r J.fun = function(B,V) {ceiling((((2*B)/V)*n)^(1/3))} B_es_hat_dw = c( ((c-x_min)^2/(12*n))*sum(mu1_hat_l^2),((x_max-c)^2/(12*n))*sum(mu1_hat_r^2)) V_es_hat_dw = c((0.5/(c-x_min))*sum(dxi_l*dyi_l^2),(0.5/(x_max-c))*sum(dxi_r*dyi_r^2)) V_es_chk_dw = c((1/(c-x_min))*sum(dxi_l*sigma2_hat_l_bar),(1/(x_max-c))*sum(dxi_r*sigma2_hat_r_bar)) J_es_hat_dw = J.fun(B_es_hat_dw, V_es_hat_dw) J_es_chk_dw = J.fun(B_es_hat_dw, V_es_chk_dw) B_qs_hat_dw = c((n_l^2/(24*n))*sum(dxi_l^2*mu1_i_hat_l^2), (n_r^2/(24*n))*sum(dxi_r^2*mu1_i_hat_r^2)) V_qs_hat_dw = c((1/(2*n_l))*sum(dyi_l^2),(1/(2*n_r))*sum(dyi_r^2)) V_qs_chk_dw = c((1/n_l)*sum(sigma2_hat_l), (1/n_r)*sum(sigma2_hat_r)) J_qs_hat_dw = J.fun(B_qs_hat_dw, V_qs_hat_dw) J_qs_chk_dw = J.fun(B_qs_hat_dw, V_qs_chk_dw) J_es_hat_mv = c(ceiling((var_y_l/V_es_hat_dw[1])*(n/log(n)^2)), ceiling((var_y_r/V_es_hat_dw[2])*(n/log(n)^2))) J_es_chk_mv = c(ceiling((var_y_l/V_es_chk_dw[1])*(n/log(n)^2)), ceiling((var_y_r/V_es_chk_dw[2])*(n/log(n)^2))) J_qs_hat_mv = c(ceiling((var_y_l/V_qs_hat_dw[1])*(n/log(n)^2)), ceiling((var_y_r/V_qs_hat_dw[2])*(n/log(n)^2))) J_qs_chk_mv = c(ceiling((var_y_l/V_qs_chk_dw[1])*(n/log(n)^2)), ceiling((var_y_r/V_qs_chk_dw[2])*(n/log(n)^2))) if (binselect=="es") { J_star_orig = J_es_hat_dw meth="es" binselect_type="IMSE-optimal evenly-spaced method using spacings estimators" J_IMSE = J_es_hat_dw J_MV = J_es_hat_mv } if (binselect=="espr") { J_star_orig = J_es_chk_dw meth="es" binselect_type="IMSE-optimal evenly-spaced method using polynomial regression" J_IMSE = J_es_chk_dw J_MV = J_es_chk_mv } if (binselect=="esmv" ) { J_star_orig = J_es_hat_mv meth="es" binselect_type="mimicking variance evenly-spaced method using spacings estimators" J_IMSE = J_es_hat_dw J_MV = J_es_hat_mv } if (binselect=="esmvpr" ) { J_star_orig = J_es_chk_mv meth="es" binselect_type="mimicking variance evenly-spaced method using polynomial regression" J_IMSE = J_es_chk_dw J_MV = J_es_chk_mv } if (binselect=="qs" ) { J_star_orig = J_qs_hat_dw meth="qs" binselect_type="IMSE-optimal quantile-spaced method using spacings estimators" J_IMSE = J_qs_hat_dw J_MV = J_qs_hat_mv } if (binselect=="qspr" ) { J_star_orig = J_qs_chk_dw meth="qs" binselect_type="IMSE-optimal quantile-spaced method using polynomial regression" J_IMSE = J_qs_chk_dw J_MV = J_qs_chk_mv } if (binselect=="qsmv" ) { J_star_orig = J_qs_hat_mv meth="qs" binselect_type="mimicking variance quantile-spaced method using spacings estimators" J_IMSE = J_qs_hat_dw J_MV = J_qs_hat_mv } if (binselect=="qsmvpr" ) { J_star_orig = J_qs_chk_mv meth="qs" binselect_type="mimicking variance quantile-spaced method using polynomial regression" J_IMSE = J_qs_chk_dw J_MV = J_qs_chk_mv } J_star_l = scale_l*J_star_orig[1] J_star_r = scale_r*J_star_orig[2] if (!is.null(nbins)) { J_star_l = nbins_l J_star_r = nbins_r binselect_type="manually evenly spaced" } if (var_y_l==0) { J_star_l = J_star_l_orig = 1 print("Warning: not enough variability in the outcome variable below the threshold") } if (var_y_r==0) { J_star_r = J_star_r_orig = 1 print("Warning: not enough variability in the outcome variable above the threshold") } rscale_l = J_star_l / J_IMSE[1] rscale_r = J_star_r / J_IMSE[2] bin_x_l = rep(0,length(x_l)); bin_x_r = rep(0,length(x_r)) jump_l = range_l/J_star_l;jump_r = range_r/J_star_r; if (meth=="es") { jumps_l=seq(x_min,c,jump_l) jumps_r=seq(c,x_max,jump_r) } else if (meth=="qs") { jumps_l=quantile(x_l,probs=seq(0,1,1/J_star_l)) jumps_r=quantile(x_r,probs=seq(0,1,1/J_star_r)) } for (k in 1:(J_star_l-1)) bin_x_l[x_l>=jumps_l[k] & x_l<jumps_l[k+1]] = -J_star_l+k-1 bin_x_l[x_l>=jumps_l[(J_star_l)]] = -1 for (k in 1:(J_star_r-1)) bin_x_r[x_r>=jumps_r[k] & x_r<jumps_r[k+1]] = k bin_x_r[x_r>=jumps_r[(J_star_r)]] = J_star_r rdplot_mean_bin_l=rdplot_mean_x_l=rdplot_mean_y_l=rep(0,J_star_l) rdplot_mean_bin_r=rdplot_mean_x_r=rdplot_mean_y_r=rep(0,J_star_r) if (!is.null(covs) & covs_eval=="mean") { covs_model_l = lm(y_l~ z_l + factor(bin_x_l)) covs_model_r = lm(y_r~ z_r + factor(bin_x_r)) yhatZ_l = predict(covs_model_l) yhatZ_r = predict(covs_model_r) } for (k in 1:(J_star_l)) { rdplot_mean_bin_l[k] = mean(c(jumps_l[k],jumps_l[k+1])) rdplot_mean_x_l[k] = mean(x_l[bin_x_l==-k]) rdplot_mean_y_l[k] = mean(y_l[bin_x_l==-k]) if (!is.null(covs) & covs_eval=="mean") rdplot_mean_y_l[k] = mean(yhatZ_l[bin_x_l==-k]) } rdplot_mean_y_l = rev(rdplot_mean_y_l) rdplot_mean_x_l = rev(rdplot_mean_x_l) for (k in 1:(J_star_r)) { rdplot_mean_bin_r[k] = mean(c(jumps_r[k],jumps_r[k+1])) rdplot_mean_x_r[k] = mean(x_r[bin_x_r==k]) rdplot_mean_y_r[k] = mean(y_r[bin_x_r==k]) if (!is.null(covs) & covs_eval=="mean") rdplot_mean_y_r[k] = mean(yhatZ_r[bin_x_r==k]) } rdplot_mean_bin_l[J_star_l]=mean(c(jumps_l[J_star_l],c)) rdplot_mean_bin_r[J_star_r]=mean(c(jumps_r[J_star_r],x_max)) bin_x = c(bin_x_l,bin_x_r) rdplot_mean_bin = c(rdplot_mean_bin_l, rdplot_mean_bin_r) rdplot_mean_x = c(rdplot_mean_x_l, rdplot_mean_x_r) rdplot_mean_y = c(rdplot_mean_y_l, rdplot_mean_y_r) rdplot_sd_y_l=rdplot_N_l=rdplot_sd_y_r=rdplot_N_r=0 for (j in 1:(J_star_l)) { rdplot_sd_y_l[j] = sd(y_l[bin_x_l==-j]) rdplot_N_l[j] = length(y_l[bin_x_l==-j]) } for (j in 1:(J_star_r)) { rdplot_sd_y_r[j] = sd(y_r[bin_x_r==j]) rdplot_N_r[j] = length(y_r[bin_x_r==j]) } rdplot_sd_y_l[is.na(rdplot_sd_y_l)]=0 rdplot_sd_y_r[is.na(rdplot_sd_y_r)]=0 rdplot_sd_y=c(rev(rdplot_sd_y_l),rdplot_sd_y_r) rdplot_N=c(rev(rdplot_N_l),rdplot_N_r) quant = -qt((1-(ci/100))/2,pmax(rdplot_N-1,1)) rdplot_se_y <- rdplot_sd_y/sqrt(rdplot_N) rdplot_cil_bin = rdplot_mean_y - quant*rdplot_se_y rdplot_cir_bin = rdplot_mean_y + quant*rdplot_se_y temp_plot =NULL if (hide=="FALSE") { if (is.null(col.lines)) col.lines = "red" if (is.null(col.dots)) col.dots = "darkblue" if (is.null(title)) title="RD Plot" if (is.null(x.label)) x.label="X axis" if (is.null(y.label)) y.label="Y axis" data_bins <- data.frame(rdplot_mean_bin, rdplot_mean_y, rdplot_cil_bin, rdplot_cir_bin) data_poly <- data.frame(x_plot_l, y_hat_l, x_plot_r, y_hat_r) temp_plot <- ggplot() + theme_bw() + geom_point(data=data_bins, aes(x=rdplot_mean_bin, y=rdplot_mean_y), col=col.dots, na.rm=TRUE) + geom_line( data=data_poly, aes(x=x_plot_l, y=y_hat_l), col=col.lines, na.rm=TRUE) + geom_line( data=data_poly, aes(x=x_plot_r, y=y_hat_r), col=col.lines, na.rm=TRUE) if (flag_no_ci==FALSE) temp_plot <- temp_plot + geom_errorbar(data=data_bins, aes(x=rdplot_mean_bin, ymin=rdplot_cil_bin, ymax=rdplot_cir_bin), linetype = 1) if (shade==TRUE){ temp_plot <- temp_plot + geom_ribbon(data=data_bins, aes(x=rdplot_mean_bin, ymin=rdplot_cil_bin, ymax=rdplot_cir_bin)) } temp_plot <- temp_plot + labs(x = x.label, y = y.label) + ggtitle(title)+ coord_cartesian(xlim = x.lim, ylim = y.lim) + theme(legend.position = "None") + geom_vline(xintercept = c, size = 0.5) print(temp_plot) } cutoffs = c(jumps_l,jumps_r[2:length(jumps_r)]) rdplot_min_bin = cutoffs[1:(length(cutoffs)-1)] rdplot_max_bin = cutoffs[2:length(cutoffs)] bin_length = rdplot_max_bin-rdplot_min_bin bin_avg_l = mean(bin_length[1:J_star_l]) bin_med_l = median(bin_length[1:J_star_l]) bin_avg_r = mean(bin_length[(J_star_l+1):length(bin_length)]) bin_med_r = median(bin_length[(J_star_l+1):length(bin_length)]) vars_bins = data.frame("rdplot_mean_bin"=rdplot_mean_bin,"rdplot_mean_x"=rdplot_mean_x, "rdplot_mean_y"=rdplot_mean_y, "rdplot_min_bin"=rdplot_min_bin, "rdplot_max_bin"=rdplot_max_bin, "rdplot_se_y"=rdplot_se_y, "rdplot_N"=rdplot_N, "rdplot_ci_l"=rdplot_cil_bin, "rdplot_ci_r"=rdplot_cir_bin) vars_poly = data.frame("rdplot_x"= c(x_plot_l, x_plot_r), "rdplot_y"= c(y_hat_l, y_hat_r)) coef = cbind(gamma_p1_l,gamma_p1_r) colnames(coef)=c("Left","Right") out=list(coef=coef, rdplot=temp_plot, vars_bins=vars_bins, vars_poly=vars_poly, J=c(J_star_l,J_star_r), J_IMSE=J_IMSE, J_MV=J_MV, scale=c(scale_l,scale_r), rscale=c(rscale_l,rscale_r), bin_avg=c(bin_avg_l,bin_avg_r), bin_med=c(bin_med_l,bin_med_r), p=p, c=c, h=c(h_l,h_r), N=c(n_l,n_r), N_h=c(n_h_l,n_h_r), binselect=binselect_type, kernel=kernel_type) out$call <- match.call() class(out) <- "rdplot" return(invisible(out)) } print.rdplot <- function(x,...){ cat("Call: rdplot\n\n") cat(paste("Number of Obs. ", format(x$N[1]+x$N[2], width=10, justify="right"),"\n", sep="")) cat(paste("Kernel ", format(x$kernel, width=10, justify="right"),"\n", sep="")) cat("\n") cat(paste("Number of Obs. ", format(x$N[1], width=10, justify="right"), " ", format(x$N[2], width=10, justify="right"), "\n", sep="")) cat(paste("Eff. Number of Obs. ", format(x$N_h[1], width=10, justify="right"), " ", format(x$N_h[2], width=10, justify="right"), "\n", sep="")) cat(paste("Order poly. fit (p) ", format(x$p, width=10, justify="right"), " ", format(x$p, width=10, justify="right"), "\n", sep="")) cat(paste("BW poly. fit (h) ", format(sprintf("%10.3f",x$h[1])), " ", format(sprintf("%10.3f",x$h[2])), "\n", sep="")) cat(paste("Number of bins scale ", format(sprintf("%10.3f",x$scale[1])), " ", format(sprintf("%10.3f",x$scale[2])), "\n", sep="")) cat("\n") } summary.rdplot <- function(object,...) { x <- object args <- list(...) cat("Call: rdplot\n\n") cat(paste("Number of Obs. ", format(x$N[1]+x$N[2], width=10, justify="right"),"\n", sep="")) cat(paste("Kernel ", format(x$kernel, width=10, justify="right"),"\n", sep="")) cat("\n") cat(paste("Number of Obs. ", format(x$N[1], width=10, justify="right"), " ", format(x$N[2], width=10, justify="right"), "\n", sep="")) cat(paste("Eff. Number of Obs. ", format(x$N_h[1], width=10, justify="right"), " ", format(x$N_h[2], width=10, justify="right"), "\n", sep="")) cat(paste("Order poly. fit (p) ", format(x$p, width=10, justify="right"), " ", format(x$p, width=10, justify="right"), "\n", sep="")) cat(paste("BW poly. fit (h) ", format(sprintf("%10.3f",x$h[1])), " ", format(sprintf("%10.3f",x$h[2])), "\n", sep="")) cat(paste("Number of bins scale ", format(sprintf("%10.0f",x$scale[1])), " ", format(sprintf("%10.0f",x$scale[2])), "\n", sep="")) cat("\n") cat(paste("Bins Selected ", format(x$J[1], width=10, justify="right"), " ", format(x$J[2], width=10, justify="right"), "\n", sep="")) cat(paste("Average Bin Length ", format(sprintf("%10.3f",x$bin_avg[1])), " ", format(sprintf("%10.3f",x$bin_avg[2])), "\n", sep="")) cat(paste("Median Bin Length ", format(sprintf("%10.3f",x$bin_med[1])), " ", format(sprintf("%10.3f",x$bin_med[2])), "\n", sep="")) cat("\n") cat(paste("IMSE-optimal bins ", format(x$J_IMSE[1], width=10, justify="right"), " ", format(x$J_IMSE[2], width=10, justify="right"), "\n", sep="")) cat(paste("Mimicking Variance bins ", format(x$J_MV[1], width=10, justify="right"), " ", format(x$J_MV[2], width=10, justify="right"), "\n", sep="")) cat("\n") cat(paste("Relative to IMSE-optimal:", "\n", sep="")) cat(paste("Implied scale ", format(sprintf("%10.3f",x$rscale[1])), " ", format(sprintf("%10.3f",x$rscale[2])), "\n", sep="")) cat(paste("WIMSE variance weight ", format(sprintf("%10.3f",1/(1+x$rscale[1]^3))), " ", format(sprintf("%10.3f",1/(1+x$rscale[2]^3))), "\n", sep="")) cat(paste("WIMSE bias weight ", format(sprintf("%10.3f",x$rscale[1]^3/(1+x$rscale[1]^3))), " ", format(sprintf("%10.3f",x$rscale[2]^3/(1+x$rscale[2]^3))), "\n", sep="")) cat("\n") }
vec_ptype_full <- function(x, ...) { if (!missing(...)) { ellipsis::check_dots_empty() } UseMethod("vec_ptype_full") } vec_ptype_abbr <- function(x, ..., prefix_named = FALSE, suffix_shape = TRUE) { if (!missing(...)) { ellipsis::check_dots_empty() } abbr <- vec_ptype_abbr_dispatch(x) return(paste0( if ((prefix_named || is_bare_list(x)) && !is.null(vec_names(x))) "named ", abbr, if (suffix_shape) vec_ptype_shape(x) )) UseMethod("vec_ptype_abbr") } vec_ptype_abbr_dispatch <- function(x, ...) { UseMethod("vec_ptype_abbr") } vec_ptype_full.NULL <- function(x, ...) "NULL" vec_ptype_abbr.NULL <- function(x, ...) "NULL" vec_ptype_full.default <- function(x, ...) { if (is.object(x)) { class(x)[[1]] } else if (is_vector(x)) { paste0(typeof(x), vec_ptype_shape(x)) } else { abort("Not a vector.") } } vec_ptype_abbr.default <- function(x, ...) { if (is.object(x)) { unname(abbreviate(vec_ptype_full(x), 8)) } else if (is_vector(x)) { switch(typeof(x), list = "list", logical = "lgl", integer = "int", double = "dbl", character = "chr", complex = "cpl", list = "list", expression = "expr", raw = "raw", abbreviate(typeof(x)) ) } else { abort("Not a vector.") } } vec_ptype_shape <- function(x) { dim <- dim2(x) if (length(dim) == 1) { "" } else { paste0("[,", paste(dim[-1], collapse = ","), "]") } }
context("hash-corpus construction") train_ind = 1:1000 txt = movie_review[['review']][train_ind] tokens = tolower(txt) tokens = word_tokenizer(tokens) it = itoken(tokens, progressbar = FALSE) test_that("Unigram Hash Corpus construction", { h_size = 2 ^ 14; vectorizer = hash_vectorizer(hash_size = h_size) m = create_dtm(it, vectorizer) expect_equal( dim(m)[[1]], length(train_ind)) expect_equal( dim(m)[[2]], h_size) expect_equal( length(m@x), 140615L) }) test_that("trigram hash-corpus construction", { h_size = 2 ^ 18; vectorizer = hash_vectorizer(hash_size = h_size, ngram = c(1L, 3L)) m = create_dtm(it, vectorizer) expect_equal( dim(m)[[1]], length(train_ind)) expect_equal( dim(m)[[2]], h_size) expect_equal( length(m@x), 591549L) })
context("ple_lma_Independence") library(pleLMA) test_that("output from fitting independence is correct", { data(dass) inData <- dass[1:250,c("d1", "d2", "d3", "a1","a2","a3","s1","s2","s3")] model <- ple.lma(inData, model.type="independence") expect_equal(model$npersons, 250) expect_equal(model$nitems, 9) expect_equal(model$ncat, 4) expect_equal(model$nless, 3) expect_equal(nrow(model$estimates), 9) expect_equal(ncol(model$estimates), 4) expect_is(model, "list") expect_is(model$phi.mlogit, "mlogit") expect_is(model$mlpl.phi, "numeric") shows_message("No errors detected in the input") })
"glaciers"
dslindley <- function(x, theta, alpha, log = FALSE) { stopifnot(theta > 0, alpha > -theta) if(log) { t1 <- log(theta) t4 <- log(theta + alpha) t7 <- log1p(alpha * x) -theta * x + 2 * t1 - t4 + t7 } else { t1 <- theta ^ 2 t8 <- exp(-theta * x) t1 / (theta + alpha) * (alpha * x + 1) * t8 } } pslindley <- function(q, theta, alpha, lower.tail = TRUE, log.p = FALSE) { stopifnot(theta > 0, alpha > -theta) if(lower.tail) { t8 <- exp(-theta * q) cdf<- 0.1e1 - (alpha * theta * q + alpha + theta) / (theta + alpha) * t8 } else { t8 <- exp(-theta * q) cdf<- (alpha * theta * q + alpha + theta) / (theta + alpha) * t8 } if(log.p) return(log(cdf)) else return(cdf) } qslindley <- function(p, theta, alpha, lower.tail = TRUE, log.p = FALSE) { stopifnot(theta > 0, alpha > -theta) if(lower.tail) { t2 <- theta + alpha t4 <- 0.1e1 / alpha t6 <- exp(-t2 * t4) t9 <- lambertWm1((p - 1) * t2 * t4 * t6) qtf <- -(alpha * t9 + alpha + theta) / theta * t4 } else { t1 <- theta + alpha t2 <- 0.1e1 / alpha t4 <- exp(-t1 * t2) t8 <- lambertWm1(-t1 * t4 * p * t2) qtf <- -(alpha * t8 + alpha + theta) / theta * t2 } if(log.p) return(log(qtf)) else return(qtf) } rslindley <- function(n, theta, alpha, mixture = TRUE) { stopifnot(theta > 0, alpha > -theta) if(mixture) { p <- rbinom(n, size = 1, prob = theta / (theta + alpha)) p * rgamma(n, shape = 1, rate = theta) + (1 - p) * rgamma(n, shape = 2, rate = theta) } else { qslindley(p = runif(n), theta, alpha, lower.tail = TRUE, log.p = FALSE) } } hslindley <- function(x, theta, alpha, log = FALSE) { stopifnot(theta > 0, alpha > -theta) if(log) { t1 <- log(theta) t5 <- log1p(alpha * x) t9 <- log(alpha * theta * x + alpha + theta) 0.2e1 * t1 + t5 - t9 } else { t1 <- theta ^ 2 t1 * (alpha * x + 1) / (alpha * theta * x + alpha + theta) } }
setMethodS3("drawLevels", "DNAcopy", function(fit, field=c("seg.mean", "tcn.mean", "dh.mean"), xScale=1, col="red", lwd=3, ...) { field <- match.arg(field) segments <- fit$output[,c("loc.start", "loc.end", field)] apply(segments, MARGIN=1, FUN=function(seg) { x <- c(seg[["loc.start"]], seg[["loc.end"]]) y <- rep(seg[[field]], times=2) lines(x=xScale*x, y=y, col=col, lwd=lwd, ...) }) })
ibdhap.reduce.states <- function(qibd.filename, dat.filename, output.filename){ par.file<-read.table(dat.filename, fill =TRUE, colClasses = "numeric") n.snps<- par.file[3,1] n.sets<-par.file[2,1] temp<-FALSE for( iset in 1:n.sets){ line1<-scan(qibd.filename, skip=((n.snps+2)*(iset-1)), nlines=1, what='raw') write(line1, file=output.filename, ncolumns=length(line1), append=temp) temp<-TRUE line2<-scan(qibd.filename, skip=((n.snps+2)*(iset-1)+1), nlines=1, what='raw') write(line2, file=output.filename, ncolumns=length(line2), append=TRUE) rm(line1,line2) ibd.dat<-scan(qibd.filename,what = "numeric",skip = (2*(iset)+(n.snps)*(iset-1)), nlines = n.snps) ibd.dat<-t(matrix(as.numeric(unlist(ibd.dat)), nrow=17)) reduced.dat <- t( apply(ibd.dat,1,sumcol) ) reduced.dat <- cbind( ibd.dat[,1:2], reduced.dat) write.table( reduced.dat,file=output.filename, append = TRUE, col.names=FALSE, row.names=FALSE) } return(paste("file", output.filename, "written in", getwd()) ) }
calc_k <- function(N = Inf, R = Inf, H_0 = 0.5, C = 1) { K <- H_0 * C * 2 * N * R / (2 * N * C + R) if (is.infinite(N)) { K <- H_0 * R } if (is.infinite(R)) { K <- H_0 * C * 2 * N } if (is.infinite(N) && is.infinite(R)) { K <- Inf } return(K) }
`[.id_tbl` <- function(x, ...) wrap_ptype(as_ptype(x), NextMethod()) `[<-.id_tbl` <- function(x, ..., value) wrap_ptype(as_ptype(x), NextMethod()) `[[<-.id_tbl` <- function(x, ..., value) wrap_ptype(as_ptype(x), NextMethod()) `$<-.id_tbl` <- function(x, ..., value) wrap_ptype(as_ptype(x), NextMethod()) wrap_ptype <- function(ptyp, res) { ptyp <- force(ptyp) if (is_dt(res)) { reclass_tbl(res, ptyp, FALSE) } else { res } } row.names.id_tbl <- function(x) NULL `row.names<-.id_tbl` <- function(x, value) { warn_arg("value") x } `names<-.id_tbl` <- function(x, value) rename_cols(x, value) `dimnames<-.id_tbl` <- function(x, value) { assert_that(length(value) == 2L) if (not_null(value[[1L]])) { warn_arg("value[[1]]") } rename_cols(x, value[[2L]]) } print.id_tbl <- function(x, ..., n = NULL, width = NULL, n_extra = NULL) { cat_line(format(x, ..., n = n, width = width, n_extra = n_extra)) invisible(x) } format.id_tbl <- function(x, ..., n = NULL, width = NULL, n_extra = NULL) { format(prt::trunc_dt(x, n = n, width = width, n_extra = n_extra)) } tbl_sum.win_tbl <- function(x) { c(NextMethod(), `Duration var` = quote_bt(dur_var(x))) } tbl_sum.ts_tbl <- function(x) { idx <- paste0(quote_bt(index_var(x)), " (", format(interval(x)), ")") c(NextMethod(), `Index var` = idx) } tbl_sum.id_tbl <- function(x) { get_unit <- function(x) { if (inherits(x, "difftime")) "" else if (inherits(x, "units")) units::deparse_unit(x) else if (has_attr(x, "units")) attr(x, "units") else "" } ids <- id_vars(x) cls <- class(x)[1L] cls <- paste0(approx_art(cls), " `", cls, "`") res <- setNames( c(dim_desc(x), concat(quote_bt(ids))), c(cls, paste0("Id var", if (length(ids) > 1L) "s")) ) unt <- chr_ply(x, get_unit, use_names = TRUE) unt <- unt[nzchar(unt)] if (has_length(unt)) { res <- c(res, Units = concat("`", names(unt), "` [", unt, "]")) } res } approx_art <- function(x) { if (substr(x, 1L, 1L) %in% c("a", "e", "i", "o", "u")) "An" else "A" } str.id_tbl <- function(object, ...) invisible(prt::str_dt(object, ...)) cbind_id_tbl <- function(..., keep.rownames = FALSE, check.names = FALSE, key = NULL, stringsAsFactors = FALSE) { lst <- list(...) check <- lgl_ply(lst, is_id_tbl) if (sum(check) == 1L) { hit <- which(check) lst <- c(lst[hit], lst[-hit]) ptyp <- as_ptype(lst[[hit]]) } else { ptyp <- NULL } res <- do.call(data.table::data.table, c(lst, list(keep.rownames = keep.rownames, check.names = check.names, key = key, stringsAsFactors = stringsAsFactors)) ) reclass_tbl(res, ptyp) } rbind_id_tbl <- function(..., use.names = TRUE, fill = FALSE, idcol = NULL) { rbind_lst(list(...), use.names = use.names, fill = fill, idcol = idcol) } cbind.id_tbl <- cbind_id_tbl rbind.id_tbl <- rbind_id_tbl merge.id_tbl <- function(x, y, by = NULL, by.x = NULL, by.y = NULL, ...) { targ <- NULL if (xor(is_win_tbl(x), is_win_tbl(y)) && xor(!is_win_tbl(x) && is_ts_tbl(x), !is_win_tbl(y) && is_ts_tbl(y))) { stop_ricu("`win_tbl` objects should be converted to `ts_tbl` objects using `expand()` before merging with `ts_tbl` objects", class = "merge_win_tbl") } if (is_id_tbl(y)) { if (is_ts_tbl(x) && is_ts_tbl(y)) { assert_that(same_time(interval(x), interval(y))) if (is_win_tbl(x)) { assert_that(identical(dur_unit(x), dur_unit(y))) } if (setequal(meta_vars(x), meta_vars(y))) { if (is.null(by)) by <- meta_vars(x) } else { if (is.null(by.x)) by.x <- meta_vars(x) if (is.null(by.y)) by.y <- meta_vars(y) } targ <- as_ptype(x) } else { if (setequal(id_vars(x), id_vars(y))) { if (is.null(by)) by <- id_vars(x) } else { if (is.null(by.x)) by.x <- id_vars(x) if (is.null(by.y)) by.y <- id_vars(y) } if (is_ts_tbl(y)) { targ <- as_ptype(y) targ <- rename_cols(targ, id_vars(x), id_vars(targ)) } else { targ <- as_ptype(x) } } } else { if (has_cols(y, meta_vars(x)) && is.null(by)) { by <- meta_vars(x) } targ <- as_ptype(x) } if (is.null(by)) { if (is.null(by.x) && is.null(by.y)) { res <- data.table::merge.data.table(x, y, ...) } else if (is.null(by.x)) { res <- data.table::merge.data.table(x, y, by.y = by.y, ...) } else { res <- data.table::merge.data.table(x, y, by.x = by.x, by.y = by.y, ...) } } else { res <- data.table::merge.data.table(x, y, by, ...) } res <- reclass_tbl(res, targ) sort(res, by_ref = TRUE) } split.id_tbl <- function(x, ...) lapply(NextMethod(), try_reclass, x) rbind_lst <- function(x, ...) { cond_as <- function(x) if (is.list(x)) x else as.data.table(x) dt_rbl <- function(x, ...) rbindlist(lapply(x, cond_as), ...) do_rename <- function(x, new) { fun <- if (is_ts_tbl(x) && is_ts_tbl(new)) meta_vars else id_vars rename_cols(x, fun(new), fun(x), by_ref = TRUE) } if (length(x) == 0L) { return(data.table()) } rows <- int_ply(x, nrow) if (all(rows == 0L)) { return(x[[1L]]) } x <- x[rows > 0L] if (length(x) == 1L) { return(x[[1L]]) } win_tbl <- lgl_ply(x, is_win_tbl) id_tbl <- lgl_ply(x, is_id_tbl) ts_tbl <- lgl_ply(x, is_ts_tbl) & !win_tbl id_tbl <- id_tbl & !ts_tbl if (any(id_tbl)) { ptyp <- as_ptype(x[[which(id_tbl)[1L]]]) } else if (any(ts_tbl)) { ptyp <- as_ptype(x[[which(ts_tbl)[1L]]]) assert_that( all_fun(lapply(x[ts_tbl], interval), all_equal, interval(ptyp)), msg = "cannot mix interval lengths when row-binding" ) } else { ptyp <- NULL } if (sum(win_tbl) >= 2L) { units <- chr_ply(x[win_tbl], dur_unit) targ <- min_time_unit(units) todo <- rep_along(FALSE, x) todo[win_tbl] <- units != targ if (any(todo)) { x[todo] <- lapply(x[todo], change_dur_unit, targ) } } if (not_null(ptyp)) { id_tbls <- lgl_ply(x, is_id_tbl) old_ptp <- lapply(x[id_tbls], as_ptype) x[id_tbls] <- lapply(x[id_tbls], do_rename, ptyp) on.exit(Map(do_rename, x[id_tbls], old_ptp)) } res <- reclass_tbl(dt_rbl(x, ...), ptyp) if (is_id_tbl(res)) { res <- sort(res, by_ref = TRUE) } res } merge_lst <- function(x) { assert_that(is.list(x), all_fun(x, is_id_tbl)) ts <- lgl_ply(x, is_ts_tbl) id <- c(which(ts), which(!ts)) ft <- unlist(lapply(x, data_vars)) x <- reduce(merge, x[id], all = TRUE) x <- setcolorder(x, c(meta_vars(x), ft)) x } unmerge <- function(x, col_groups = as.list(data_vars(x)), by = meta_vars(x), na_rm = TRUE) { name_has <- function(name, x) has_name(x, name) assert_that(has_name(x, by), all_fun(col_groups, name_has, x), is.flag(na_rm)) extract_col <- function(col, x) { y <- x[, c(by, col), with = FALSE] if (na_rm) { y <- rm_na(y, col) } y } lapply(col_groups, extract_col, x) }
ibd.terms=function(y,subject.ids,l1,l2,pim) { n=length(y) if(!is.factor(y)) stop("y should be of type factor") paires.i.i.boo=apply(cbind(l1,l2),1,function(x) x[1]==x[2]) l1=l1[!paires.i.i.boo] l2=l2[!paires.i.i.boo] pim=array(pim[!paires.i.i.boo,],c(sum(!paires.i.i.boo),ncol(pim))) l1=c(subject.ids,l1) l2=c(subject.ids,l2) pim=rbind(array(1,c(n,ncol(pim))),pim) pairs.table=as.matrix(table(factor(l1,levels=subject.ids),factor(l2,levels=subject.ids))) if(any(((pairs.table+t(pairs.table))[lower.tri(pairs.table)])>1)) stop("all pairs of subjects must be present only once in the ibd file") for(j in 1:ncol(pim)) { pi.tmp=pim[,j] paires.pi.NA=is.na(pi.tmp) if(sum(paires.pi.NA)>0) { l1.pi.NA=l1[paires.pi.NA] l2.pi.NA=l2[paires.pi.NA] pi.tmp[paires.pi.NA]=0 pim[,j]=pi.tmp missing.pairs=paste(l1.pi.NA,l2.pi.NA) cat("IBD data missing for column",j,"of pim, for the following pairs of subjects \n",paste(missing.pairs,"\n")) cat("Posterior probabilities of IBD P1 and P2 have been set to 0 for these pairs ! \n \n") } } pairs.table.mod=pairs.table+t(pairs.table) pairs.table.mod[lower.tri(pairs.table)]=1 which.missing=which(pairs.table.mod==0,arr.ind=TRUE) if(nrow(which.missing)!=0) { missing1=subject.ids[which.missing[,1]] missing2=subject.ids[which.missing[,2]] missing.pairs=paste(missing1,missing2) l1=c(missing1,l1) l2=c(missing2,l2) pim=rbind(array(0,c(length(missing1),ncol(pim))),pim) cat("IBD data missing, from all of the IBD files, for the following",length(missing.pairs),"pairs of subjects (out of",n*(n-1)/2,"possible pairs): \n",paste(missing.pairs,"\n")) cat("Posterior probabilities of IBD P1 and P2 have been set to 0 for these pairs ! \n") } liste.par.cat=tapply(1:n,y,function (vec) subject.ids[vec],simplify=FALSE) ny=table(y) n.levels=nlevels(y) res=array(NA,c(ncol(pim),n.levels-1,n.levels-1)) l1.double=c(l1,l2[l1!=l2]) l2.double=c(l2,l1[l1!=l2]) pim=rbind(pim,array(pim[l1!=l2,],c(sum(l1!=l2),ncol(pim)))) for (k in 1:(n.levels-1)) { if (length(liste.par.cat[[k]])>0) { dims=c(sum(l1.double %in% liste.par.cat[[k]] & l2.double %in% liste.par.cat[[k]]),ncol(pim)) term1=((n-ny[k])^2)*apply(array(pim[l1.double %in% liste.par.cat[[k]] & l2.double %in% liste.par.cat[[k]],],dims),2,sum) dims=c(sum(!(l1.double %in% liste.par.cat[[k]]) & !(l2.double %in% liste.par.cat[[k]])),ncol(pim)) term2=(ny[k]^2)*apply(array(pim[!(l1.double %in% liste.par.cat[[k]]) & !(l2.double %in% liste.par.cat[[k]]),],dims),2,sum) dims=c(sum(l1.double %in% liste.par.cat[[k]] & !(l2.double %in% liste.par.cat[[k]])),ncol(pim)) term3=2*ny[k]*(n-ny[k])*apply(array(pim[l1.double %in% liste.par.cat[[k]] & !(l2.double %in% liste.par.cat[[k]]),],dims),2,sum) res[,k,k]=(term1+term2-term3)/(n^2) } } if(n.levels>2) { for (k in 2:(n.levels-1)) { for (l in 1:(k-1)) { if (length(liste.par.cat[[k]])>0 & length(liste.par.cat[[l]])>0) { dims=c(sum(l1.double %in% liste.par.cat[[k]] & l2.double %in% liste.par.cat[[l]]),ncol(pim)) term1=(n-ny[k])*(n-ny[l])*apply(array(pim[l1.double %in% liste.par.cat[[k]] & l2.double %in% liste.par.cat[[l]],],dims),2,sum) dims=c(sum(!(l1.double %in% liste.par.cat[[k]]) & !(l2.double %in% liste.par.cat[[l]])),ncol(pim)) term2=ny[k]*ny[l]*apply(array(pim[!(l1.double %in% liste.par.cat[[k]]) & !(l2.double %in% liste.par.cat[[l]]),],dims),2,sum) dims=c(sum(l1.double %in% liste.par.cat[[k]] & !(l2.double %in% liste.par.cat[[l]])),ncol(pim)) term3=ny[l]*(n-ny[k])*apply(array(pim[l1.double %in% liste.par.cat[[k]] & !(l2.double %in% liste.par.cat[[l]]),],dims),2,sum) dims=c(sum(!(l1.double %in% liste.par.cat[[k]]) & l2.double %in% liste.par.cat[[l]]),ncol(pim)) term4=ny[k]*(n-ny[l])*apply(array(pim[!(l1.double %in% liste.par.cat[[k]]) & l2.double %in% liste.par.cat[[l]],],dims),2,sum) res[,k,l]=res[,l,k]=(term1+term2-term3-term4)/(n^2) } } } } res }
new_ORRRR <- function(x = list()){ stopifnot(is.list(x)) stopifnot(all(c("method","SAAmethod","spec","history", "mu", "A", "B", "D", "Sigma", "obj") %in% names(x))) structure(x, class = c("ORRRR", "RRRR","RRR")) } print.ORRRR <- function(x, digits = max(3L, getOption("digits") - 2L), ...){ cat("Online Robust Reduced-Rank Regression") cat("\n------\n") switch(x$method, "SMM" = cat("Stochastic Majorisation-Minimisation"), "SAA" = cat("Sample Average Approximation")) if(x$method == "SAA"){ cat("\nSub solver: ") switch(x$SAAmethod, "optim" = cat("stats::optim"), "MM" = cat("Majorisation Minimisation")) } cat("\n------------\n") cat("Specifications:\n") print(do.call(base::c, x$spec)) cat("\nCoefficients:\n") print(coef(x), digits = digits) }
setOldClass <- function(Classes, prototype = NULL, where = topenv(parent.frame()), test = FALSE, S4Class) { simpleCase <- is.null(prototype) mainClass <- Classes[[1L]] prevDef <- getClassDef(mainClass, where, inherits = FALSE) if(!missing(S4Class)) { if(test) stop("not allowed to have test==TRUE and an S4Class definition") if(!is(S4Class, "classRepresentation")) { if(is.character(S4Class)) { clName <- S4Class S4Class <- getClass(S4Class) if(.identC(clName, Classes[[1L]])) removeClass(clName, where = where) } else stop(gettextf("argument 'S4Class' must be a class definition: got an object of class %s", dQuote(class(S4Class))), domain = NA) } if(!is.null(prototype)) { S4prototype <- S4Class@prototype S4Class@prototype <- .mergeAttrs(prototype, S4prototype) } Recall(Classes, where = where) return(.S4OldClass(Classes[[1L]], if(length(Classes) > 1) Classes[[2L]] else "oldClass", S4Class, where, prevDef)) } if(test) return(.setOldIs(Classes, where)) if(!is.null(prevDef)) { on.exit(.restoreClass(prevDef, where)) removeClass(mainClass, where = where) } prevClass <- "oldClass" S3Class <- character() if(is.null(S3table <- where$.S3MethodsClasses)) { S3table <- new.env() assign(".S3MethodsClasses", S3table, envir = where) } dataPartClass <- NULL for(cl in rev(Classes)) { S3Class <- c(cl, S3Class) if(isClass(cl, where)) { def <- getClass(cl, where) if(!extends(def, prevClass)) { cl1 <- .validDataPartClass(cl, where, dataPartClass) if(is.null(cl1)) stop(gettextf("inconsistent old-style class information for %s; the class is defined but does not extend %s and is not valid as the data part", dQuote(cl), dQuote(prevClass)), domain = NA) else dataPartClass <- cl1 } else { prevP <- def@prototype if(missing(prototype)) prototype <- prevP prevS3Class <- attr(prevP, ".S3Class") if(length(prevS3Class) > length(S3Class)) S3Class <- prevS3Class } } else { useP <- TRUE if(cl != mainClass || simpleCase) { setClass(cl, contains = c(prevClass, "VIRTUAL"), where = where) } else if(isClass(class(prototype))) setClass(cl, contains = prevClass, prototype = prototype, where = where) else { if(.class1(prototype) != mainClass) stop(gettextf('the S3 class of the prototype, "%s", is undefined; only allowed when this is the S3 class being registered ("%s")', .class1(prototype), mainClass), domain = NA) setClass(cl, contains = prevClass, where = where) useP <- FALSE } def <- getClassDef(cl, where) if(useP) clp <- def@prototype else clp <- prototype attr(clp, ".S3Class") <- S3Class def@prototype <- .notS4(clp) assignClassDef(cl, def, where = where) assign(cl, def, envir= S3table) } prevClass <- cl } if(!is.null(prevDef)) on.exit() } .restoreClass <- function(def, where) { cl <- def@className message(gettextf("restoring definition of class %s", dQuote(cl)), domain = NA) if(isClass(cl, where = where)) removeClass(cl, where = where) assignClassDef(cl, def, where = where) } .S4OldClass <- function(Class, prevClass, def,where, prevDef) { curDef <- getClassDef(Class, where) if(!is.null(prevDef)) { on.exit(.restoreClass(prevDef, where)) removeClass(Class, where = where) } if(!identical(def@className, curDef@className)) def <- .renameClassDef(def, curDef@className) .validS3Extends(def, curDef) def@slots[names(curDef@slots)] <- curDef@slots ext <- c(def@contains, curDef@contains) distOrder <- sort.list(vapply(ext, function(x) x@distance, 1)) ext <- ext[distOrder] if(anyDuplicated(names(ext))) ext <- .resolveSuperclasses(def, ext, where) def@contains <- ext oldSupers <- setdiff(names(def@contains), names(curDef@contains)) addSubclass <- function(super) { superDef <- getClassDef(super, where) superWhere <- .findOrCopyClass(super, superDef, where, "subclass") superDef@subclasses[[Class]] <- def@contains[[super]] assignClassDef(super, superDef, superWhere, TRUE) } lapply(oldSupers, addSubclass) subcls <- curDef@subclasses if(length(subcls) > 0) { def@subclasses[names(subcls)] <- subcls } proto <- def@prototype if(is.null(attr(proto, ".S3Class"))) { attr(proto, ".S3Class") <- if(.identC(prevClass, "oldClass")) Class else S3Class(curDef@prototype) def@prototype <- proto } assignClassDef(Class, def, where = where) if(!extends(def, prevClass, maybe = FALSE)) setIs(Class, prevClass, classDef = def, where = where) slotsMethod <- function(object) NULL body(slotsMethod) <- substitute({LIST}, list(LIST = def@slots)) setMethod("slotsFromS3", Class, slotsMethod, where = where) if(!is.null(prevDef)) on.exit() } .validS3Extends <- function(classDef1, classDef2) { slots2 <- classDef2@slots if(length(slots2) > 0) { n2 <- names(slots2) slots1 <- classDef1@slots n1 <- names(slots1) bad <- character() for(what in n2[match(n2, n1, 0) > 0]) if(!extends(slots1[[what]], slots2[[what]])) { message(gettextf("slot %s: class %s should extend class %s", sQuote(what), dQuote(slots1[[what]]), dQuote(slots2[[what]])), domain = NA) bad <- c(bad, what) } if(length(bad)>0) stop( gettextf("invalid S4 class corresponding to S3 class: slots in S4 version must extend corresponding slots in S3 version: fails for %s", paste0('"', bad, '"', collapse = ", ")), domain = NA) } TRUE } slotsFromS3 <- function(object) { list() } utils::globalVariables("CLASS") .oldTestFun <- function(object) CLASS %in% attr(object, "class") .oldCoerceFun <- function(from, strict = TRUE) { if(strict) stop(gettextf("explicit coercion of old-style class (%s) is not defined", paste(class(from), collapse = ", ")), domain = NA) from } .oldReplaceFun <- function(from, to, value) stop(gettextf("explicit replacement not defined for as(x, \"%s\") <- value for old-style class %s", to, dQuote(class(from)[1L])), domain = NA) .setOldIs <- function(Classes, where) { if(length(Classes) != 2) stop(gettextf("argument 'Classes' must be a vector of two classes; got an argument of length %d", length(Classes)), domain = NA) for(cl in Classes) { if(isClass(cl, where)) { if(!extends(cl, "oldClass")) warning(gettextf("inconsistent old-style class information for %s (maybe mixing old and new classes?)", dQuote(cl)), domain = NA) } else setClass(cl, representation("oldClass", "VIRTUAL"), where = where) } Class1 <- Classes[[1L]] for(cl in Classes[-1L]) { tfun <- .oldTestFun body(tfun, envir = environment(tfun)) <- substitute(inherits(object, CLASS), list(CLASS = cl)) setIs(Class1, cl, test = tfun, coerce = .oldCoerceFun, replace = .oldReplaceFun, where = where) } NULL } isXS3Class <- function(classDef) { ".S3Class" %in% names(classDef@slots) } S3Class <- function(object) { value <- attr(object, ".S3Class") if(is.null(value)) { if(isS4(object)) { if(is.na(match(".Data", names(getClass(class(object))@slots)))) stop(gettextf("'S3Class' only defined for extensions of %s or classes with a data part: not true of class %s", dQuote("oldClass"), dQuote(class(object))), domain = NA) class(getDataPart(object)) } else class(object) } else value } .S3Class <- S3Class .addS3Class <- function(class, prototype, contains, where) { for(what in contains) { whatDef <- getClassDef(what@superClass, package=packageSlot(what)) if(isXS3Class(whatDef)) class <- c(class, attr(whatDef@prototype, ".S3Class")) } attr(prototype, ".S3Class") <- unique(class) prototype } "S3Class<-" <- function(object, value) { if(isS4(object)) { current <- attr(object, ".S3Class") if(is.null(current)) { if(is.na(match(value, .BasicClasses))) stop(gettextf("'S3Class' can only assign to S4 objects that extend \"oldClass\"; not true of class %s", dQuote(class(object))), domain = NA) mode(object) <- value } else slot(object, ".S3Class") <- value } else class(object) <- value object } .renameClassDef <- function(def, className) { validObject(def) def@className <- className comp <- def@contains for(i in seq_along(comp)) comp[[i]]@subClass <- className def@contains <- comp comp <- def@subclasses for(i in seq_along(comp)) comp[[i]]@superClass <- className def@subclasses <- comp def } ..extendsForS3 <- function(Class) extends(Class, maybe = FALSE) .extendsForS3 <- function(Class) extends(Class)
m <- crosstalk::SharedData$new(mtcars, ~vs) p <- plot_ly(m, x = ~wt, y = ~mpg) %>% add_markers() test_that("SharedData produces key/set in plot_ly", { tr <- plotly_build(p)$x$data[[1]] expect_true(all(tr$key == m$key())) expect_identical(tr$set, m$groupName()) expect_false(tr$`_isNestedKey` %||% FALSE) expect_false(tr$`_isSimpleKey` %||% FALSE) }) test_that("Warning is thrown when clickmode='select' is used with crosstalk", { expect_warning( plotly_build(layout(p, clickmode = "select")), "not designed to work well" ) }) test_that("SharedData produces key/set in ggplotly", { p <- ggplot(m, aes(x = wt, y = mpg)) + geom_point() tr <- plotly_build(p)$x$data[[1]] expect_true(all(tr$key == m$key())) expect_type(tr$set, "character") expect_length(tr$set, 1) expect_false(tr$`_isNestedKey` %||% FALSE) expect_false(tr$`_isSimpleKey` %||% FALSE) }) test_that("crosstalk keys are inherited in a layer with inherit = FALSE", { p <- txhousing %>% group_by(city) %>% crosstalk::SharedData$new(~city, "Select a city") %>% plot_ly(x = ~date, y = ~median) %>% add_lines(alpha = 0.2) %>% add_ribbons( x = c(2016, 2017), ymin = c(150000, 160000), ymax = c(200000, 190000), inherit = FALSE ) b <- plotly_build(p) expect_null(b$x$data[[2]][["key"]]) expect_null(b$x$data[[2]][["set"]]) k <- unique(b$x$data[[1]]$key) expect_equal(sort(k[!is.na(k)]), sort(unique(txhousing$city))) expect_true(b$x$data[[1]][["set"]] == "Select a city") }) test_that("Simple scatterplot brushing with plot_ly() and subplot()", { p <- mtcars %>% crosstalk::SharedData$new(group = "testing") %>% plot_ly(x = ~mpg, y = ~wt) b <- subplot(p, p) %>% highlight("plotly_selected") %>% plotly_build() expect_true(all(b$x$data[[1]]$key == row.names(mtcars))) expect_true(all(b$x$data[[2]]$key == row.names(mtcars))) expect_true(b$x$data[[1]]$set == "testing") expect_true(b$x$layout$dragmode == "select") }) test_that("group_by.plotly() retains crosstalk set", { b <- mtcars %>% crosstalk::SharedData$new(group = "foo") %>% plot_ly(x = ~mpg, y = ~hp) %>% group_by(am) %>% add_markers() %>% plotly_build() expect_equal(b$x$data[[1]]$set, "foo") expect_true(all(b$x$data[[1]]$key == row.names(mtcars))) }) test_that("When key is equivalent to group, produce simple keys", { gg <- ggplot(m, aes(wt, mpg, color = factor(vs))) + geom_point() + geom_smooth(se = FALSE) l <- plotly_build(gg)$x for (i in seq_along(l$data)) { tr <- l$data[[i]] expect_false(tr$`_isNestedKey` %||% FALSE) if (tr$mode == "markers") { expect_true(tr$key == tr$name) expect_true(tr$`_isSimpleKey`) } else { expect_true(tr$name %in% tr$key) expect_true(tr$`_isSimpleKey`) } } }) m2 <- crosstalk::SharedData$new(mtcars) test_that("When key is nested within group, produce simple key", { gg <- ggplot(m2, aes(wt, mpg, color = factor(vs))) + geom_point() + geom_smooth(se = FALSE) l <- plotly_build(gg)$x for (i in seq_along(l$data)) { tr <- l$data[[i]] key <- m2$key()[mtcars$vs == tr$name] expect_true(all(tr$key == key)) if (tr$mode == "markers") { expect_false(tr$`_isSimpleKey` %||% FALSE) expect_false(tr$`_isNestedKey` %||% FALSE) } else { expect_true(tr$`_isSimpleKey`) expect_false(tr$`_isNestedKey` %||% FALSE) } } }) test_that("Key structure is passed along to frame data", { p <- ggplot(m2, aes(wt, mpg, color = factor(vs), frame = am)) + geom_point() + geom_smooth(se = FALSE) l <- suppressWarnings(plotly_build(p)$x) for (i in seq_along(l$data)) { tr <- l$data[[i]] key <- m2$key()[mtcars$vs == tr$name & mtcars$am == tr$frame] expect_true(all(tr$key == key)) } for (i in seq_along(l$frames)) { fr <- l$frames[[i]] for (j in seq_along(fr$data)) { tr <- fr$data[[j]] if (tr$mode != "lines") next expect_true(tr$`_isSimpleKey`) } } }) test_that("can handle inconsistent d <- data.frame( y = rnorm(20), score = c(1,1,1,1,2,2,2,2,3,3,3,3,1,1,1,1,2,2,2,2), population = c(rep(1, 12), rep(2, 8)) ) p <- plot_ly(d, y = ~y, split = ~as.factor(score), frame = ~population) %>% add_boxplot() l <- plotly_build(p)$x expect_length(l$data, 3) cols <- sapply(l$data, function(x) x$line$color) defaultCols <- toRGB(colorway()[1:3]) expect_equivalent(cols, defaultCols) nms <- sapply(l$data, "[[", "name") expect_equivalent(nms, levels(as.factor(d$score))) expect_length(l$frames, 2) expect_length(l$frames[[1]]$data, 3) expect_length(l$frames[[2]]$data, 3) expect_equivalent(l$frames[[1]]$traces, 0:2) expect_equivalent(l$frames[[2]]$traces, 0:2) expect_true( unique(sapply(l$frames[[1]]$data, "[[", "visible")) ) expect_identical( sapply(l$frames[[2]]$data, "[[", "visible"), c(TRUE, TRUE, FALSE) ) cols <- sapply(l$frames[[1]]$data, function(x) x$line$color) expect_equivalent(cols, defaultCols) cols <- sapply(l$frames[[2]]$data, function(x) x$line$color) expect_equivalent(cols, defaultCols) buttonArgs <- l$layout$updatemenus[[1]]$buttons[[1]]$args[[2]] defaults <- animation_opts_defaults() expect_identical( buttonArgs[names(defaults)], defaults ) steps <- l$layout$sliders[[1]]$steps expect_equivalent( unlist(lapply(steps, function(s) s$args[[1]])), c("1", "2") ) res <- lapply(steps, function(s) { expect_identical(s$args[[2]], defaults) }) }) test_that("can change animation defaults", { data(mtcars) p <- plot_ly(mtcars, x = ~wt, y = ~mpg, frame = ~cyl) %>% animation_opts(frame = 1200, transition = 1000, easing = "elastic") %>% animation_button( x = 1, xanchor = "right", y = 0, yanchor = "bottom" ) %>% animation_slider( currentvalue = list(prefix = "YEAR ", font = list(color="red")) ) l <- plotly_build(p)$x expect_length(l$data, 1) expect_length(l$frames, 3) cyl <- as.character(unique(sort(mtcars$cyl))) for (i in seq_along(l$frames)) { f <- l$frames[[i]] expect_equivalent(f$name, cyl[[i]]) expect_length(f$data, 1) } aniOpts <- modify_list( rapply(animation_opts_defaults(), unclass, how = "list"), list( frame = list(duration = 1200), transition = list(duration = 1000, easing = "elastic") ) ) buttonArgs <- l$layout$updatemenus[[1]]$buttons[[1]]$args[[2]] expect_equivalent( buttonArgs[names(aniOpts)], aniOpts ) steps <- l$layout$sliders[[1]]$steps expect_equivalent( unlist(lapply(steps, function(s) s$args[[1]])), cyl ) res <- lapply(steps, function(s) { expect_identical( s$args[[2]], aniOpts ) }) }) test_that("simple animation targeting works", { df <- data.frame( x = c(1, 2, 2, 1, 1, 2), y = c(1, 2, 2, 1, 1, 2), z = c(1, 1, 2, 2, 3, 3) ) p <- plot_ly(df) %>% add_markers(x = 1.5, y = 1.5) %>% add_markers(x = ~x, y = ~y, frame = ~z) l <- plotly_build(p)$x expect_length(l$data, 2) for (i in seq_along(l$data)) { tr <- l$data[[i]] expect_equivalent(tr$name %||% "no-name", "no-name") expect_true(tr$marker$color == toRGB(colorway()[[i]])) } expect_length(l$frames, 3) for (i in seq_along(l$frames)) { f <- l$frames[[i]] for (j in seq_along(f$data)) { tr <- f$data[[j]] expect_equivalent(tr$name %||% "no-name", "no-name") expect_true(tr$marker$color == toRGB(colorway()[[2]])) } } buttonArgs <- l$layout$updatemenus[[1]]$buttons[[1]]$args expect_false(buttonArgs[[2]]$frame$redraw) steps <- l$layout$sliders[[1]]$steps res <- lapply(steps, function(s) { expect_false(s$args[[2]]$frame$redraw) }) }) test_that("animation frames are boxed up correctly", { dallas <- subset(txhousing, city == "Dallas" & month == 1) p <- ggplot(dallas, aes(x = volume, y = sales, frame = year)) + geom_point() l <- plotly_build(p)$x for (i in seq_along(l$frames)) { traces <- l$frames[[i]]$data for (j in seq_along(traces)) { x <- traces[[j]]$x y <- traces[[j]]$y expect_true(length(x) > 1 || inherits(x, "AsIs")) expect_true(length(y) > 1 || inherits(y, "AsIs")) } } }) test_that("animation button can be customized", { p <- plot_ly(mtcars, x = ~mpg, y = ~wt, frame = ~vs) %>% animation_button(label = "Custom", bgcolor = "red", font = list(color = "white")) f <- plotly_build(p)$x menu <- f$layout$updatemenus[[1]] expect_true(menu$bgcolor == "red") expect_true(menu$font$color == "white") expect_true(menu$buttons[[1]]$label == "Custom") }) test_that("sf works with crosstalk", { skip_if_not_installed("sf") skip_if_not_installed("s2") nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE) ncsd <- crosstalk::SharedData$new(nc) p <- ggplot(ncsd) + geom_sf(aes(fill = AREA, text = paste0(NAME, "\n", "FIPS: ", FIPS))) + ggthemes::theme_map() gg <- ggplotly(p, tooltip = "text") d <- gg$x$data for (i in seq_along(d)) { if (!isTRUE(d[["_isGraticule"]])) next expect_false(is.null(d[[i]]$key)) expect_false(is.null(d[[i]]$set)) } })
"trajdyn" <- function(x, burst = attr(x[[1]],"burst"), hscale=1, vscale=1, recycle = TRUE, display = c("guess", "windows", "tk"), ...) { if (!inherits(x, "ltraj")) stop("x should be of class 'ltraj'") e1 <- new.env(parent = baseenv()) typeII <- attr(x,"typeII") x <- lapply(x, function(i) { jj <- i[!is.na(i$x),] attr(jj, "id") <- attr(i,"id") attr(jj, "burst") <- attr(i,"burst") return(jj) }) class(x) <- c("ltraj","list") attr(x, "typeII") <- typeII attr(x, "regular") <- is.regular(x) u <- x assign("x", x[burst = burst], envir=e1) assign("v", x[burst = burst], envir=e1) assign("ajouli", FALSE, envir=e1) assign("ajoupo", FALSE, envir=e1) assign("ajoubu", FALSE, envir=e1) assign("addpoints", TRUE, envir=e1) assign("addlines", TRUE, envir=e1) assign("lim", TRUE, envir=e1) assign("buadd", burst, envir=e1) assign("K",1, envir=e1) assign("N",nrow(get("x", envir=e1)[[1]]), envir=e1) assign("cusr", rep(0 + NA, 4), envir=e1) assign("cplt", rep(0 + NA, 4), envir=e1) opt <- options(warn=-1) on.exit(options(opt)) dsp <- substring(match.arg(display), 1, 1) if (dsp == "g") dsp <- switch(.Platform$OS.type, windows = "w", "t") if (dsp == "t" && !requireNamespace("tkrplot", quietly = TRUE)) stop("'tkrplot' package needed\n") if (dsp == "t") assign("hoho", 1, envir=e1) replot <- function() { opar <- par(mar=c(0,0,0,0), bg="white") tmptmp <- get("x", envir=e1) attr(tmptmp[[1]], "id") <- " " assign("x", tmptmp, envir=e1) if (get("lim", envir=e1)) { assign("xlim", range(get("x", envir=e1)[[1]]$x), envir=e1) assign("ylim", range(get("x", envir=e1)[[1]]$y), envir=e1) } plot(get("x", envir=e1), id = attr(get("x", envir=e1)[[1]],"id"), addlines=FALSE, addp=FALSE, final=FALSE, xlim = get("xlim", envir=e1), ylim = get("ylim", envir=e1), ...) assign("cusr", par("usr"), envir=e1) assign("cplt", par("plt"), envir=e1) scatterutil.sub(as.character(get("x", envir=e1)[[1]]$date[get("K", envir=e1)]), 1, "topleft") if (get("ajoubu", envir=e1)) { lapply(u[burst=get("buadd", envir=e1)], function(zz) { if (get("addpoints", envir=e1)) points(zz[,c("x","y")], pch=16, col="grey") if (get("addlines", envir=e1)) lines(zz[,c("x","y")], pch=16, col="grey")}) } if (get("addpoints", envir=e1)) points(get("x", envir=e1)[[1]][1:get("K", envir=e1),c("x","y")], pch=16) if (get("addlines", envir=e1)) if (get("K", envir=e1)>1) lines(get("x", envir=e1)[[1]][1:get("K", envir=e1),c("x","y")], lwd=2) if (get("ajouli", envir=e1)) lines(c(get("a1", envir=e1)[1], get("a2", envir=e1)[1]),c(get("a1", envir=e1)[2], get("a2", envir=e1)[2]), lwd=2, col="red") if (get("ajoupo", envir=e1)) points(get("a5", envir=e1)[1], get("a5", envir=e1)[2], pch=16, col="red", cex=1.7) iti <- unlist(get("x", envir=e1)[[1]][get("K", envir=e1),c("x","y")]) points(iti[1],iti[2], col="blue", pch=16, cex=1.4) par(opar) } help.txt <- paste("\n-------- to obtain this help, type 'h' ------------------", "n/p -- Next/Previous relocation", "a -- show all relocations", "g -- Go to...", "0-9 -- show a given part of the path", "b -- change Burst", "i -- add/remove other bursts on the graph", "z/o -- Zoom in/Out", "Left-Click -- measure the distance between two points", "Right-Click -- identify a relocation", "r/l -- add or remove points/Lines", "q -- Quit", "---------------------------------------------------------", "\n", sep = "\n") assign("D",0, envir=e1) assign("a1", 0, envir=e1) assign("a2", 0, envir=e1) if (dsp == "t") { tt <- tcltk::tktoplevel() tcltk::tkwm.title(tt, "Exploration of Animal Movements") img <- tkrplot::tkrplot(tt, replot, hscale = hscale, vscale = vscale) txt <- tcltk::tktext(tt, bg = "white", font = "courier 10") scr <- tcltk::tkscrollbar(tt, repeatinterval = 5, command = function(...) tcltk::tkyview(txt, ...)) tcltk::tkconfigure(txt, yscrollcommand = function(...) tcltk::tkset(scr, ...)) tcltk::tkpack(img, side = "top") tcltk::tkpack(txt, side = "left", fill = "both", expand = TRUE) tcltk::tkpack(scr, side = "right", fill = "y") iw <- as.numeric(tcltk::tcl("image", "width", tcltk::tkcget(img, "-image"))) ih <- as.numeric(tcltk::tcl("image", "height", tcltk::tkcget(img, "-image"))) } showz <- function() switch(dsp, w = replot(), t = {tkrplot::tkrreplot(img)}) type <- function(s) switch(dsp, w = cat(s), t = { tcltk::tkinsert(txt, "end", s) tcltk::tksee(txt, "end") }) type(help.txt) cc <- function(x, y) { if (dsp == "t") { x <- (as.double(x) - 1)/iw y <- 1 - (as.double(y) - 1)/ih } px <- (x - get("cplt", envir=e1)[1])/(get("cplt", envir=e1)[2] - get("cplt", envir=e1)[1]) py <- (y - get("cplt", envir=e1)[3])/(get("cplt", envir=e1)[4] - get("cplt", envir=e1)[3]) ux <- px * (get("cusr", envir=e1)[2] - get("cusr", envir=e1)[1]) + get("cusr", envir=e1)[1] uy <- py * (get("cusr", envir=e1)[4] - get("cusr", envir=e1)[3]) + get("cusr", envir=e1)[3] c(ux,uy) } mm.w <- function(buttons, x, y) { if (buttons == 0) { i<-get("D", envir=e1) if (i == 0) { assign("a1", cc(x,y), envir=e1) assign("D", 1, envir=e1) } if (i == 1) { assign("a2", cc(x,y), envir=e1) assign("D", 0, envir=e1) di <- sqrt(sum((get("a2", envir=e1)-get("a1", envir=e1))^2)) cat(paste("distance:",round(di,6),"\n")) lines(c(get("a1", envir=e1)[1],get("a2", envir=e1)[1]),c(get("a1", envir=e1)[2],get("a2", envir=e1)[2]), lwd=2, col="red") } return() } if (buttons == 2) { w <- get("v",envir=e1)[[1]][1:get("K", envir=e1),] assign("a3", cc(x,y), envir=e1) di <- sqrt((w$x-get("a3", envir=e1)[1])^2 + (w$y-get("a3", envir=e1)[2])^2) print(w[which.min(di),]) cat("\n") points(w[which.min(di),c("x","y")], pch=16, col="red", cex=1.7) return() } } mm.t <- function(x, y) { i<-get("D", envir=e1) if (i == 0) { assign("a1", cc(x,y), envir=e1) assign("D", 1, envir=e1) } if (i == 1) { assign("a2", cc(x,y), envir=e1) assign("D", 0, envir=e1) di <- sqrt(sum((get("a2", envir=e1)-get("a1", envir=e1))^2)) type(paste("distance:",di,"\n")) assign("ajouli", TRUE, envir=e1) showz() assign("ajouli", FALSE, envir=e1) } return() } mm.t2 <- function(x, y) { w <- get("v",envir=e1)[[1]][1:get("K", envir=e1),] assign("a3", cc(x,y), envir=e1) di <- sqrt((w$x-get("a3", envir=e1)[1])^2 + (w$y-get("a3", envir=e1)[2])^2) assign("a5", unlist(w[which.min(di),c("x","y")]), envir=e1) assign("ajoupo", TRUE, envir=e1) showz() assign("ajoupo", FALSE, envir=e1) tmp <- w[which.min(di),] se <-unlist(lapply((max(nchar(names(tmp))+ nchar(sapply(tmp,as.character))+1) - nchar(names(tmp))-nchar(sapply(tmp, as.character))), function(zz) paste(rep(" ",zz), collapse=""))) so<-unlist(lapply(1:length(tmp), function(i) paste(paste(names(tmp)[i], as.character(tmp[1,i]), sep = se[i]),"\n"))) type(paste("Relocation",row.names(w)[which.min(di)],":\n")) sapply(so,type) type("\n") return() } mm.mouse <- function(buttons, x, y) { assign("a8", cc(x,y), envir=e1) return() } mm.mouset <- function(x, y) { assign("a8", cc(x,y), envir=e1) return() } kb <- function(A) { key <- tolower(A) if (key == "q") { if (dsp=="t") tcltk::tkdestroy(tt) return("OK - Finished") } if (key %in% c(0:9)) { if (key > 0) assign("K", round(seq(1,get("N", envir=e1),length=11))[as.numeric(key)+1], envir=e1) if (key == 0) assign("K", 1, envir=e1) showz() } if (key == "z") { assign("tmppx", (get("cusr", envir=e1)[1:2]- get("cusr", envir=e1)[1])/2, envir=e1) assign("xlim", c((get("a8", envir=e1)[1] - (get("tmppx", envir=e1)[2] - get("tmppx", envir=e1)[1])/2), (get("a8", envir=e1)[1] + (get("tmppx", envir=e1)[2] - get("tmppx", envir=e1)[1])/2)), envir=e1) assign("tmppy", (get("cusr", envir=e1)[3:4]-get("cusr", envir=e1)[3])/2, envir=e1) assign("ylim", c((get("a8", envir=e1)[2] - (get("tmppy",envir=e1)[2] - get("tmppy",envir=e1)[1])/2), (get("a8", envir=e1)[2] + (get("tmppy",envir=e1)[2] - get("tmppy",envir=e1)[1])/2)), envir=e1) assign("lim", FALSE, envir=e1) showz() } if (key == "o") { assign("lim", TRUE, envir=e1) showz() } if (key == "n") { if (get("K", envir=e1)<=get("N", envir=e1)) assign("K", get("K", envir=e1)+1, envir=e1) if (get("K", envir=e1)>get("N", envir=e1)) { if (recycle) assign("K", 1, envir=e1) if (!recycle) { assign("K", get("N", envir=e1), envir=e1) cat("End of burst !\n") } } showz() } if (key == "l") { assign("addlines", !get("addlines", envir=e1), envir=e1) showz() } if (key == "g") { if (dsp == "w") { recom <- TRUE while (recom) { rr <- readline("Enter a relocation number: ") recom <- FALSE if (!(rr%in%row.names(get("x", envir=e1)[[1]]))) { cat("invalid number\n") recom <- TRUE } } assign("K", which(row.names(get("x", envir=e1)[[1]])==as.numeric(rr)), envir=e1) showz() } if (dsp == "t") { lv <- tcltk::tclVar(row.names(get("x", envir=e1)[[1]])[1]) tu <- tcltk::tktoplevel(tt, width=500, height=50) tcltk::tkwm.title(tu, "Enter a relocation number") tcltk::tkwm.resizable(tu, 0, 0) en <- tcltk::tkentry(tu, textvariable=lv, width=50) submit.but <- tcltk::tkbutton(tu, text=" OK ", command=function() { rr <- tcltk::tclvalue(lv) if (!(rr%in%row.names(get("x", envir=e1)[[1]]))) { tcltk::tkmessageBox(message="invalid number", type="ok") } else { assign("K", which(row.names(get("x", envir=e1)[[1]])==as.numeric(rr)), envir=e1) showz() tcltk::tkdestroy(tu)}}) tcltk::tkpack(en, side = "top", fill = "both") tcltk::tkpack(submit.but, side = "bottom") tcltk::tkwait.window(tu) } } if (key == "r") { assign("addpoints", !get("addpoints", envir=e1), envir=e1) showz() } if (key == "b") { assign("K", 1, envir=e1) if (dsp == "w") { assign("hoho", select.list(unlist(lapply(u, function(y) attr(y, "burst")))), envir=e1) type(paste("Choice of the burst:", get("hoho", envir=e1),"\n\n")) assign("x",u[burst=get("hoho", envir=e1)], envir=e1) assign("v",u[burst=get("hoho", envir=e1)], envir=e1) assign("N", nrow(get("x", envir=e1)[[1]]), envir=e1) showz() } if (dsp == "t") { lv <- tcltk::tclVar(unlist(lapply(u, function(y) attr(y, "burst")))) bubu <- unlist(lapply(u, function(y) attr(y, "burst"))) tu <- tcltk::tktoplevel(tt) tcltk::tkwm.title(tu, "Choose a burst of relocations") tcltk::tkwm.resizable(tu, 0, 0) tfr <- tcltk::tkframe(tu) tli <- tcltk::tklistbox(tfr, bg = "white", font = "courier 12", listvariable = lv) scr2 <- tcltk::tkscrollbar(tfr, repeatinterval = 5, command = function(...) tcltk::tkyview(tli, ...)) tcltk::tkconfigure(tli, yscrollcommand = function(...) tcltk::tkset(scr2, ...)) submit.but <- tcltk::tkbutton(tu, text=" OK ", command=function() { assign("hoho", ifelse(nchar(tcltk::tclvalue(tcltk::tkcurselection(tli)))==0, 1, as.numeric(tcltk::tclvalue(tcltk::tkcurselection(tli)))+1), envir=e1) type(paste("Choice of the burst:", bubu[get("hoho", envir=e1)],"\n\n")) tcltk::tkdestroy(tu)}) tcltk::tkpack(tli, side = "left", fill = "both", expand = TRUE) tcltk::tkpack(scr2, side = "right", fill = "y") tcltk::tkpack(tfr, side = "right", fill = "y") tcltk::tkpack(submit.but, side = "bottom") tcltk::tkwait.window(tu) assign("x",u[burst=bubu[get("hoho", envir=e1)]], envir=e1) assign("v",u[burst=bubu[get("hoho", envir=e1)]], envir=e1) assign("N", nrow(get("x", envir=e1)[[1]]), envir=e1) showz() } } if (key == "i") { if (get("ajoubu", envir=e1)) { assign("ajoubu", FALSE, envir=e1) showz() } else { if (dsp == "w") { assign("buadd", select.list(unlist(lapply(u, function(y) attr(y, "burst"))), multiple=TRUE), envir=e1) if (length(get("buadd", envir=e1)>0)) { type(paste("show bursts:", paste(get("buadd", envir=e1), collapse=" "),"\n\n")) assign("ajoubu", TRUE, envir=e1) showz() } } if (dsp == "t") { lv <- tcltk::tclVar(unlist(lapply(u, function(y) attr(y, "burst")))) bubu <- unlist(lapply(u, function(y) attr(y, "burst"))) tu <- tcltk::tktoplevel(tt) tcltk::tkwm.title(tu, "Choose one or several bursts") tcltk::tkwm.resizable(tu, 0, 0) tfr <- tcltk::tkframe(tu) tli <- tcltk::tklistbox(tfr, bg = "white", font = "courier 12", listvariable = lv, selectmode="multiple") scr2 <- tcltk::tkscrollbar(tfr, repeatinterval = 5, command = function(...) tcltk::tkyview(tli, ...)) tcltk::tkconfigure(tli, yscrollcommand = function(...) tcltk::tkset(scr2, ...)) submit.but <- tcltk::tkbutton(tu, text=" OK ", command=function() { argg <- ifelse(nchar(tcltk::tclvalue(tcltk::tkcurselection(tli)))==0, 1,0) if (argg==0) { assign("ajoubu", TRUE, envir=e1) assign("buadd", bubu[as.numeric(unlist(strsplit(tcltk::tclvalue(tcltk::tkcurselection(tli)), " ")))+1], envir=e1) type(paste("show bursts:", paste(get("buadd", envir=e1), collapse=" "),"\n\n")) showz() tcltk::tkdestroy(tu)}}) tcltk::tkpack(tli, side = "left", fill = "both", expand = TRUE) tcltk::tkpack(scr2, side = "right", fill = "y") tcltk::tkpack(tfr, side = "right", fill = "y") tcltk::tkpack(submit.but, side = "bottom") tcltk::tkwait.window(tu) assign("x", u[burst=bubu[get("hoho", envir=e1)]], envir=e1) assign("v", u[burst=bubu[get("hoho", envir=e1)]], envir=e1) assign("N", nrow(get("x", envir=e1)[[1]]), envir=e1) showz() } } } if (key == "p") { if (get("K", envir=e1)>1) assign("K", get("K", envir=e1)-1, envir=e1) if (get("K", envir=e1)==1) { if (recycle) assign("K", get("N", envir=e1), envir=e1) if (!recycle) { assign("K", 1, envir=e1) cat("Beginning of burst!\n") } } showz() } if (key == "a") { assign("K", get("N", envir=e1), envir=e1) showz() } if (key == "h") type(help.txt) return() } showz() toto <- switch(dsp, w = getGraphicsEvent("", onKeybd = kb, onMouseDown = mm.w, onMouseMove = mm.mouse), t ={tcltk::tkbind(tt, "<Key>", kb) tcltk::tkbind(img, "<Button-1>", mm.t) tcltk::tkbind(img, "<Motion>", mm.mouset) tcltk::tkbind(img, "<Button-3>", mm.t2) tcltk::tkwait.window(tt)}) }
normalize_pcl <- function(df) { sum.dee <- NULL lidar.pulse <- NULL can.hits <- NULL df <- normalize_pcl_one(df) df <- normalize_pcl_two(df) df <- normalize_pcl_three(df) return(df) } normalize_pcl_one <- function(df) { sum.dee <- NULL lidar.pulses <- NULL can.hits <- NULL df <- df[with(df, order(xbin, zbin)), ] df$hit.count <- 0 df.list <- split(df, df$xbin) df.list <- lapply(df.list, function(x){ for (i in 1:nrow(x)) { x.counter = 1 for(j in 2:nrow(x)){ x$hit.count[j] = x$hit.count[j-1] + x$bin.hits[j] } return(x) } }) df <- plyr::ldply(df.list, data.frame) df <- df[-1] return(df) } normalize_pcl_two <- function(df) { sum.dee <- NULL lidar.pulses <- NULL can.hits <- NULL eq1 = ((df$can.hits + 1) - df$hit.count) / (df$can.hits + 1) eq2 = (df$can.hits - df$hit.count) / df$can.hits df <- transform(df, phi = ifelse(lidar.pulses == can.hits, eq1, eq2)) df <- replace(df, is.na(df), 0) } normalize_pcl_three <- function(df) { sum.dee <- NULL df$dee <- 0 df.list <- split(df, df$xbin) df.list <- lapply(df.list, function(x){ for(i in 1:nrow(x)) { x.counter = 1 for(j in 2:nrow(x)){ x.counter = 1 if(x$phi[j-1] > 0 && x$phi[j] > 0){ x$dee[j] = log(x$phi[j-1] / x$phi[j]) x$x.counter = x.counter }else { x$dee[j] = 0 x$x.counter = x.counter } } x.counter = x.counter + 1 return(x) } }) df2 <- plyr::ldply(df.list, data.frame) q <- stats::setNames(stats::aggregate(dee ~ xbin, data = df2, FUN = sum), c("xbin", "sum.dee")) df2$sum.dee <- q$sum.dee[match(df2$xbin, q$xbin)] eq.fee = df2$dee / df2$sum.dee df2 <- transform(df2, fee = ifelse(sum.dee > 0, eq.fee, 0)) return(df2) }
plot.sgSEMp1 <- function(x, ..., cutoff = 0.2, width = NULL, height = NULL, filename = NULL){ rtp1 <- x$table rtp1[, -c(1:3)] <- round(rtp1[, -c(1:3)], 2) rtp1.a <- rtp1[rtp1[, "adj-R-Sqr"] < cutoff, ] rtp1.b <- rtp1[rtp1[, "adj-R-Sqr"] >= cutoff, ] if(dim(rtp1.a)[1] > 0) { conp1.a <- sapply(1 :nrow(rtp1.a), function(i){ paste0(rtp1.a[i,2], "(", rtp1.a[i,2], ")", "-.->|", paste0(colnames(rtp1.a[,3:5]), ":", rtp1.a[i,3:5], collapse="<br/>"), "|", rtp1.a[i,1], "(", rtp1.a[i,1], ")") } ) } if(dim(rtp1.b)[1] > 0) { conp1.b <- sapply(1:nrow(rtp1.b), function(i){ paste0(rtp1.b[i,2], "(", rtp1.b[i,2], ")", "==>|", paste0(colnames(rtp1.b[,3:5]), ":", rtp1.b[i,3:5], collapse="<br/>"), "|", rtp1.b[i,1], "(", rtp1.b[i,1], ")") } ) } if(exists("conp1.a") == TRUE & exists("conp1.b") == TRUE) { conp1.plot <- paste0( "graph LR;", "\n", paste(conp1.a, collapse = "\n"), "\n", paste(conp1.b, collapse="\n"), "\n", "classDef default fill: } if(exists("conp1.a") == FALSE) { conp1.plot <- paste0( "graph LR;", "\n", paste(conp1.b, collapse="\n"), "\n", "classDef default fill: cat("The cutoff value is lower than all of the adjusted R-sqr values: Only solid lines") } if(exists("conp1.b") == FALSE) { conp1.plot <- paste0( "graph LR;", "\n", paste(conp1.a, collapse="\n"), "\n", "classDef default fill: cat("The cutoff value is higher than all of the adjusted R-sqr values: Only dotted lines\n") } p1 <- DiagrammeR::mermaid(conp1.plot, width=width, height=height) if(!is.null(filename)) saveWidget(p1, file = filename, selfcontained = TRUE) return(p1) }
tabPanel('Model Building', value = 'tab_model_home', fluidPage( fluidRow( br(), column(12, align = 'center', h3('What do you want to do?') ), br(), br() ), fluidRow( column(12), br(), column(3), column(4, align = 'left', h5('Bivariate Analysis') ), column(2, align = 'left', actionButton( inputId = 'model_bivar_click', label = 'Click Here', width = '120px' ) ), column(3), br(), br(), br(), column(3), column(4, align = 'left', h5('Regression') ), column(2, align = 'left', actionButton( inputId = 'model_regress_click', label = 'Click Here', width = '120px' ) ), column(3), br(), br(), br(), column(3), column(4, align = 'left', h5('Model Fit Statistics') ), column(2, align = 'left', actionButton( inputId = 'model_fitstat_click', label = 'Click Here', width = '120px' ) ), column(3), br(), br(), br(), column(3), column(4, align = 'left', h5('Variable Selection') ), column(2, align = 'left', actionButton( inputId = 'model_varsel_click', label = 'Click Here', width = '120px' ) ), column(3), br(), br(), br(), column(3), column(4, align = 'left', h5('Model Validation') ), column(2, align = 'left', actionButton( inputId = 'model_validation_click', label = 'Click Here', width = '120px' ) ), column(3), br(), br(), br(), column(3), column(4, align = 'left', h5('Residual Diagnostics') ), column(2, align = 'left', actionButton( inputId = 'model_resdiag_click', label = 'Click Here', width = '120px' ) ), column(3) ) ) )
"bike_sharing_demand"
insertPed<-function(ped, founders=NULL){ ped[,1]<-as.character(ped[,1]) ped[,2]<-as.character(ped[,2]) ped[,3]<-as.character(ped[,3]) mmothers<-na.omit(ped[,2][which(ped[,2]%in%ped[,1]==FALSE)]) mfathers<-na.omit(ped[,3][which(ped[,3]%in%ped[,1]==FALSE)]) if(is.null(founders)==FALSE){ founders<-na.omit(founders[which(founders%in%ped[,1]==FALSE)]) } mparents<-unique(c(mmothers, mfathers, founders)) nped<-ped[rep(1,length(mparents)),] nped[,1]<-mparents nped[,2]<-NA nped[,3]<-NA nped<-rbind(nped,ped) colnames(nped)<-colnames(ped) nped }
predict.epx <- function(object, newdata, classifier.args = list(), ...) { FUNS <- .getBaseClassifier(classifier = (object$BASE.CLASSIFIER.ARGS)[[1]], classifier.args) BC <- FUNS[[1]] BC.predict <- FUNS[[2]] classifier.args <- FUNS[[3]] message("Base classifier:", (object$BASE.CLASSIFIER.ARGS)[[1]], "\n") epx.classifier.args <- (object$BASE.CLASSIFIER.ARGS)[[2]] message("Base classifier arguments specified in phalanx-formation:") if (length(epx.classifier.args) == 0) { message(" none", "\n") } else { message("\n") print(epx.classifier.args) } message("Base classifier arguments specified in prediction:") if (length(classifier.args) == 0) { message(" none", "\n") } else { message("\n") print(classifier.args) } if (missing(newdata) && length(classifier.args) == 0) { return(object$ENSEMBLED.FITS) } if (missing(newdata) && length(classifier.args) > 0) { newdata <- object$X } if (ncol(newdata) != ncol(object$X)) { stop("Given newdata with incorrect number of columns.") } if (!all(colnames(newdata) %in% colnames(object$X)) || !all(colnames(object$X) %in% colnames(newdata))) { stop("Given newdata with incorrect variable names.") } groups <- (object$PHALANXES)[[4]] var.names <- colnames(object$X) data <- cbind(object$X, y = object$Y) sort.unique.groups <- 1:max(groups) predictions <- NULL for (j in sort.unique.groups) { namef <- NULL namef <- var.names[groups == j] classifier.j <- BC(.ClassifierFormula(namef), dat = data) preds1 <- BC.predict(model = classifier.j, newdata = newdata) predictions <- cbind(predictions, preds1) } colnames(predictions) <- sort.unique.groups predicted.values <- as.numeric(apply(predictions, 1, mean)) return(predicted.values) }
listAllMeasures = function() { return(measureList) }
"pneumo" <- structure(list(exposure.time = c(5.8, 15, 21.5, 27.5, 33.5, 39.5, 46, 51.5), normal = c(98, 51, 34, 35, 32, 23, 12, 4), mild = c(0, 2, 6, 5, 10, 7, 6, 2), severe = c(0, 1, 3, 8, 9, 8, 10, 5)), .Names = c("exposure.time", "normal", "mild", "severe"), class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6", "7", "8"))
context("Test ari_stitch()") if (ffmpeg_version_sufficient()) { res = ffmpeg_audio_codecs() if (is.null(res)) { fdk_enabled = FALSE } else { fdk_enabled = grepl("fdk", res[ res$codec == "aac", "codec_name"]) } } else { fdk_enabled = FALSE } if (fdk_enabled) { audio_codec = "libfdk_aac" } else { audio_codec = "ac3" } test_that("ari_stitch() can combine audio and images into a video", { skip_on_cran() temp_dir <- tempdir() for (i in 1:3) { jpeg(file.path(temp_dir, paste0("plot", i, ".jpg"))) plot(1:5 * i, 1:5, main = i) dev.off() } sound <- replicate( 3, tuneR::Wave(round(rnorm(88200, 127, 20)), samp.rate = 44100, bit = 16)) graphs <- file.path(temp_dir, paste0("plot", 1:3, ".jpg")) video <- file.path(temp_dir, "output.mp4") on.exit(walk(c(graphs, video), unlink, force = TRUE), add = TRUE) ari_stitch(graphs, sound, output = video, audio_codec = audio_codec, verbose = 2) expect_true(file.size(video) > 50000) })
`coef.ppar` <- function(object, extrapolated = TRUE, ...) { x <- object$theta.table[,1] if(!extrapolated) x[object$theta.table[,3]] <- NA names(x) <- rownames(object$theta.table) x }
set.seed(1234) expand.grid(run = paste("run", 1:6), rep = 1:10000) %>% mutate(x = rcauchy(6 * 10000)) %>% group_by(run) %>% arrange(rep) %>% mutate(runningMean = cumsum(x) / 1:length(x)) %>% gf_line(runningMean ~ rep | run) %>% gf_hline(yintercept = 0, color = "red", alpha = 0.5) %>% gf_lims(y = c(-20, 20)) %>% gf_labs(y = "running mean", x = "")
stat_fit_residuals <- function(mapping = NULL, data = NULL, geom = "point", method = "lm", method.args = list(), formula = NULL, resid.type = NULL, weighted = FALSE, position = "identity", na.rm = FALSE, orientation = NA, show.legend = FALSE, inherit.aes = TRUE, ...) { ggplot2::layer( stat = StatFitResiduals, data = data, mapping = mapping, geom = geom, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(method = method, method.args = method.args, formula = formula, resid.type = resid.type, weighted = weighted, na.rm = na.rm, orientation = orientation, ...) ) } residuals_compute_group_fun <- function(data, scales, method, method.args, formula, resid.type, weighted, orientation) { stopifnot(!any(c("formula", "data") %in% names(method.args))) if (is.null(data$weight)) { data$weight <- 1 } if (is.null(formula)) { if (is.na(orientation) || orientation == "x") { formula = y ~ x } else if (orientation == "y") { formula = x ~ y } } if (is.na(orientation)) { orientation <- unname(c(x = "y", y = "x")[as.character(formula)[2]]) } if (is.function(method)) { fun <- method } else if (is.character(method)) { if (method == "rq" && length(method.args) == 0) { method.args <- list(tau = 0.5) } fun <- switch(method, lm = stats::lm, rlm = MASS::rlm, rq = quantreg::rq, stop("Method '", method, "' not yet implemented.") ) } else { stop("Method '", method, "' not yet implemented.") } mf <- do.call(fun, args = c(list(formula = formula, data = data, weights = quote(weight)), method.args)) if (!is.null(resid.type)) { if (weighted) { if (resid.type != "deviance") { warning("Ignoring supplied 'resid.type' as 'weighted = TRUE'") } resid.args <- list(obj = mf, drop0 = TRUE) } else { resid.args <- list(object = mf, type = resid.type) } } else { if (weighted) { resid.args <- list(obj = mf, drop0 = TRUE) } else { resid.args <- list(object = mf) } } if (weighted) { fit.residuals <- do.call(stats::weighted.residuals, args = resid.args) } else { fit.residuals <- do.call(stats::residuals, args = resid.args) } if (exists("w", mf)) { weight.vals <- mf[["w"]] } else { weight.vals <- stats::weights(mf) weight.vals <- ifelse(length(weight.vals) == length(fit.residuals), weight.vals, rep_len(NA_real_, length(fit.residuals))) } if (orientation == "y") { data.frame(y = data$y, x = fit.residuals, x.resid = fit.residuals, y.resid = NA_real_, weights = weight.vals) } else { data.frame(x = data$x, y = fit.residuals, y.resid = fit.residuals, x.resid = NA_real_, weights = weight.vals) } } StatFitResiduals <- ggplot2::ggproto("StatFitResiduals", ggplot2::Stat, compute_group = residuals_compute_group_fun, required_aes = c("x", "y") )
getStatuses <- function(ids=NULL, filename, oauth_folder, verbose=TRUE, sleep=1){ require(rjson); require(ROAuth) creds <- list.files(oauth_folder, full.names=T) cr <- sample(creds, 1) if (verbose) {cat(cr, "\n")} load(cr) limit <- getLimitStatuses(my_oauth) if (verbose) {cat(limit, " API calls left\n")} while (limit==0){ cr <- sample(creds, 1) if (verbose){cat(cr, "\n")} load(cr) Sys.sleep(sleep) rate.limit <- getLimitRate(my_oauth) if (rate.limit<100){ Sys.sleep(300) } limit <- getLimitStatuses(my_oauth) if (verbose){cat(limit, " API calls left\n")} } url <- "https://api.twitter.com/1.1/statuses/lookup.json" ids.left <- ids while (length(ids.left)>0){ params <- list(id = paste(ids.left[1:100], collapse=",")) url.data <- my_oauth$OAuthRequest(URL=url, params=params, method="GET", cainfo=system.file("CurlSSL", "cacert.pem", package = "RCurl")) Sys.sleep(sleep) limit <- limit - 1 json.data <- RJSONIO::fromJSON(url.data) if (length(json.data$error)!=0){ cat(url.data) stop("error downloading IDs! First ID not downloaded", ids[1]) } conn <- file(filename, "a") invisible(lapply(json.data, function(x) writeLines(rjson::toJSON(x), con=conn))) close(conn) ids.left <- ids.left[-(1:100)] if (verbose){cat(limit, " API calls left\n")} while (limit==0){ cr <- sample(creds, 1) if (verbose){cat(cr, "\n")} load(cr) Sys.sleep(sleep) rate.limit <- getLimitRate(my_oauth) if (rate.limit<100){ Sys.sleep(300) } limit <- getLimitStatuses(my_oauth) if (verbose){cat(limit, " API calls left\n")} } } } getLimitRate <- function(my_oauth){ require(rjson); require(ROAuth) url <- "https://api.twitter.com/1.1/application/rate_limit_status.json" params <- list(resources = "followers,application") response <- my_oauth$OAuthRequest(URL=url, params=params, method="GET", cainfo=system.file("CurlSSL", "cacert.pem", package = "RCurl")) return(unlist(fromJSON(response)$resources$application$`/application/rate_limit_status`[['remaining']])) } getLimitStatuses <- function(my_oauth){ require(rjson); require(ROAuth) url <- "https://api.twitter.com/1.1/application/rate_limit_status.json" params <- list(resources = "statuses,application") response <- my_oauth$OAuthRequest(URL=url, params=params, method="GET", cainfo=system.file("CurlSSL", "cacert.pem", package = "RCurl")) return(unlist(rjson::fromJSON(response)$resources$statuses$`/statuses/lookup`[['remaining']])) } ids <- scan("data/romney-tweets.txt", n=100, what="character") getStatuses(ids=ids, filename='romney-tweets.json', oauth_folder = "~/credentials/twitter") library(streamR) tweets <- parseTweets("romney-tweets.json")
row1 = c(91,90,51) row2 = c(150,200,155) row3 = c(109,198,172) data.table = rbind(row1,row2,row3) data.table chisq.test(data.table) UCBAdmissions ftable(UCBAdmissions, row.vars=c("Admit")) str(UCBAdmissions) deptB = UCBAdmissions[,,2] deptB chisq.test(deptB) chisq.test(deptB)$expected chisq.test(deptB)$resid chisq.test(deptB)$statistic data(survey, package="MASS") str(survey) table(survey$Sex, survey$Fold) (ct3 = chisq.test(x=survey$Sex, y=survey$Fold)) ct3$observed; ct3$expected rbind(ct3$observed, ct3$expected) ct3$residuals (result = matrix(c(200,150,50,250,300,50), byrow=T, ncol=3)) dimnames(result) = list(gender=c('male','female'), party=c('bjp','cong','aap') ) result (ct4 = chisq.test(x=result)) ct4$observed; ct4$expected ct4$statistic ct4$p.value qchisq(1-.05,df=(2-1)*(3-1)) ct4$residuals
YPmodel.setParameter <- function(startPoint=c(0,0), nm=log(100), maxIter1=50, maxIter2=20, ...) { Parameters <- list(GroupNum=2, startPoint=startPoint, nm=nm, maxIter1=maxIter1, maxIter2=maxIter2) return(Parameters) }
coxseiest <- function(dat,par.init,m=2, mit=1000,tr=TRUE,method="L-BFGS-B", lower=c(rep(-Inf,ncol(dat)-3),-Inf,0), upper=rep(Inf,ncol(dat)-3 + 2), gfun=function(x,pa){ ifelse(x <= 0, rep(0,length(x)), pa[1]*exp(-pa[2]*x)) }){ ids <- unique(dat$id) ng <- length(ids) gs <- as.numeric(table(dat$id)) gofst <- cumsum(gs)-gs C <- dat$Y[!dat$delta] Z <- as.matrix(dat[,setdiff(colnames(dat),c("Y","delta","id"))], nrow=nrow(dat)) Zs <- array(0,dim=c(dim(Z),ng)) for(l in 1:ng){ for(i in 1:ng){ for(j in 1:NCOL(Z)){ Zs[dat$id==ids[i],j,l] <- if(diff(range(Z[dat$id==ids[l],j]))==0){ Z[dat$id==ids[l],j][1] }else{ approxfun(dat$Y[dat$id==ids[l]], Z[dat$id==ids[l],j],method="constant", f=1,rule=2)(dat$Y[dat$id==ids[i]]) } } } } loglik <- function(param){ np <- length(param); par <- param[1:(np-2)]; parg <- param[np- 1:0]; ll <- function(i){ if(gs[i]==1)return(0); res <- 0; for(j in 1:(gs[i]-1)){ posij <- gofst[i]+j res <- res+ Z[posij,] %*% par + sum(gfun(dat$Y[posij]- tail(dat$Y[dat$id==ids[i]][(1:gs[i])<j],m), parg)) tmp <- 0 for(l in (1:ng)[dat$Y[posij]<=C]) tmp <- tmp+exp(Zs[posij,,l]%*%par + sum(gfun(dat$Y[posij]- tail((yl <- dat$Y[dat$id==l])[yl<dat$Y[posij]],m), parg))) res <- res-log(tmp) } res } -sum(sapply((1:ng)[gs>1],ll)) } ret <- optim(par.init,loglik,control=list(trace=tr,maxit=mit), hessian=TRUE,method=method,lower=lower,upper=upper) ret }
mitmlComplete <- function(x, print = "all", force.list = FALSE){ if(sum(print <= 0) > 1) stop("Only one negative or zero value is allowed in 'print'.") dat <- x$data srt <- order( attr(x$data, "sort") ) labs <- attr(x$data, "labels") method <- class(x)[2] m <- x$iter$m ind <- x$index.mat rpm <- x$replacement.mat if(is.numeric(print)){ if(length(print) == 1){ if(print > 0){ com <- .completeOne(dat, print, ind, rpm, method) out <- com[srt,] }else{ out <- .stripDataAttributes(dat[srt,]) } if(force.list) out <- list(out) }else{ out <- list() for(ii in print){ if(ii > 0){ com <- .completeOne(dat, ii, ind, rpm, method) out <- c(out, list(com[srt,])) }else{ out <- c(out, list(.stripDataAttributes(dat[srt,]))) } } } }else{ if(!print %in% c("list", "all")) stop("Invalid 'print' argument.") out <- list() for(ii in 1:m){ com <- .completeOne(dat, ii, ind, rpm, method) out <- c(out, list(com[srt,])) } } if(is.list(out) && !is.data.frame(out)) class(out) <- c("mitml.list", "list") return(out) } .completeOne <- function(x, i, ind, rpm, method){ if(method == "jomo"){ fac <- which(colnames(x) %in% names(attr(x, "labels"))) nofac <- !(ind[,2] %in% fac) if(any(nofac)) x[ ind[nofac, ,drop = F] ] <- rpm[nofac, i, drop = F] for(ff in fac){ fi <- which(ind[,2] == ff) lev <- attr(x, "labels")[[colnames(x)[ff]]] if(length(fi)>0) x[ ind[fi, ,drop = F] ] <- lev[rpm[fi, i]] } }else{ x[ind] <- rpm[,i] } .stripDataAttributes(x) } .stripDataAttributes <- function(x){ attr(x, "sort") <- NULL attr(x, "group") <- NULL attr(x, "levels") <- NULL attr(x, "labels") <- NULL x }
require(Rmosek) n <- 100 r <- 10 m <- 2*r + 1 theta <- rep(c(.2,.3),n/2) y <- rnorm(n*m, mean = 0, sd = rep(theta, each = m)) id <- rep(1:n,each = m) x <- tapply(y, id, var) m <- tapply(y, id, length) f <- GVmix(x,m, verb = 0) g <- GVmix(x,m, rtol = 1e-10, verb = 0) plot(g,xlab = expression(sigma^2), main = "Estimated Mixing Density") lines(g, col = 4) abline(v = .04, col = "red") abline(v = .09, col = "red")
model_get_xlevels <- function(model) { UseMethod("model_get_xlevels") } model_get_xlevels.default <- function(model) { xlevels <- tryCatch( model %>% purrr::chuck("xlevels"), error = function(e) { NULL } ) xlevels %>% .add_xlevels_for_logical_variables(model) } .add_xlevels_for_logical_variables <- function(xlevels, model) { log_vars <- model %>% model_list_variables() %>% dplyr::filter(.data$var_class == "logical") %>% purrr::pluck("variable") for (v in setdiff(log_vars, names(xlevels))) xlevels[[v]] <- c("FALSE", "TRUE") xlevels } model_get_xlevels.lmerMod <- function(model) { stats::model.frame(model) %>% lapply(levels) %>% purrr::compact() %>% .add_xlevels_for_logical_variables(model) } model_get_xlevels.glmerMod <- model_get_xlevels.lmerMod model_get_xlevels.felm <- model_get_xlevels.lmerMod model_get_xlevels.brmsfit <- model_get_xlevels.lmerMod model_get_xlevels.glmmTMB <- model_get_xlevels.lmerMod model_get_xlevels.plm <- model_get_xlevels.lmerMod
test_that("hrank works", { s1 <- 1:4 s2 <- 4:7 s3 <- c(5,6,8) s4 <- c(1,4,7) h1 <- hypergraph_from_edgelist(list(s1,s2,s3,s4)) h2 <- hypergraph_from_edgelist(list(s1,s2)) expect_equal(hrank(h1),length(s1)) expect_equal(hcorank(h1),length(s3)) expect_equal(hrank(h2),length(s1)) expect_equal(hcorank(h2),length(s1)) })
LSCV.risk <- function(f, g = NULL, hlim = NULL, hseq = NULL, type = c("fixed", "adaptive"), method = c("kelsall-diggle", "hazelton", "davies"), resolution = 64, edge = TRUE, hp = NULL, pilot.symmetry = c("none","f","g","pooled"), auto.optim = TRUE, seqres = 30, parallelise = NA, verbose = TRUE, ...){ if(!inherits(f,"ppp")) stop("'f' must be an object of class \"ppp\"") if(is.null(g)){ fm <- marks(f) if(!is.factor(fm)) marks(f) <- fm <- factor(fm) if(nlevels(fm)!=2) stop("'f' marks must be dichotomous if 'g' unsupplied") fs <- split(f) f <- fs[[1]] g <- fs[[2]] } if(!inherits(g,"ppp")) stop("'g' must be an object of class \"ppp\"") W <- Window(f) if(!identical_windows(W,Window(g))) stop("study windows for 'f' and 'g' must be identical") if(!is.null(hlim)){ if(hlim[1]>=hlim[2]) stop("invalid 'hlim'") } else { md <- min(c(nndist(unique(f)),nndist(unique(g)))) hlim <- c(md,max(md*50,min(diff(W$xrange),diff(W$yrange))/6)) } meth <- method[1] typ <- type[1] if(meth=="davies"&&typ=="adaptive") stop("method = \"davies\" not possible for type = \"adaptive\"") if(typ=="fixed"){ if(auto.optim){ if(meth=="kelsall-diggle"){ if(verbose) cat("Searching for optimal Kelsall-Diggle h in [",round(hlim[1],3),",",round(hlim[2],3),"]...",sep="") result <- optimise(LSCV.risk.single,interval=hlim,cases=f,controls=g,res=resolution,edge=edge,hazey=FALSE)$minimum } else if(meth=="hazelton"){ if(verbose) cat("Searching for optimal Hazelton h in [",round(hlim[1],3),",",round(hlim[2],3),"]...",sep="") result <- optimise(LSCV.risk.single,interval=hlim,cases=f,controls=g,res=resolution,edge=edge,hazey=TRUE)$minimum } else if(meth=="davies"){ if(verbose) cat("Searching for optimal Davies h in [",round(hlim[1],3),",",round(hlim[2],3),"]\n -initialisation...",sep="") marks(f) <- NULL marks(g) <- NULL pooled <- suppressWarnings(superimpose(f,g)) lambda <- LSCV.density(pooled,verbose=FALSE) bp <- BAMprep(f,g,lambda,3,resolution) if(verbose) cat("Done.\n -optimisation...") result <- optimise(BAM.single,interval=hlim,edge=edge,BP=bp)$minimum } else { stop("invalid 'method'") } if(verbose) cat("Done.\n") } else { if(is.null(hseq)) hseq <- seq(hlim[1],hlim[2],length=seqres) hn <- length(hseq) if(meth=="kelsall-diggle"){ if(is.na(parallelise)){ lscv.vec <- rep(NA,hn) if(verbose) pb <- txtProgressBar(1,hn) for(i in 1:hn){ lscv.vec[i] <- LSCV.risk.single(hseq[i],cases=f,controls=g,res=resolution,edge=edge,hazey=FALSE) if(verbose) setTxtProgressBar(pb,i) } if(verbose) close(pb) } else { ncores <- detectCores() if(verbose) cat(paste("Evaluating criterion on",parallelise,"/",ncores,"cores...")) if(parallelise>ncores) stop("cores requested exceeds available count") registerDoParallel(cores=parallelise) lscv.vec <- foreach(i=1:hn,.packages="spatstat",.combine=c) %dopar% { return(LSCV.risk.single(hseq[i],cases=f,controls=g,res=resolution,edge=edge,hazey=FALSE)) } if(verbose) cat("Done.\n") } } else if(meth=="hazelton"){ if(is.na(parallelise)){ lscv.vec <- rep(NA,hn) if(verbose) pb <- txtProgressBar(1,hn) for(i in 1:hn){ lscv.vec[i] <- LSCV.risk.single(hseq[i],cases=f,controls=g,res=resolution,edge=edge,hazey=TRUE) if(verbose) setTxtProgressBar(pb,i) } if(verbose) close(pb) } else { ncores <- detectCores() if(verbose) cat(paste("Evaluating criterion on",parallelise,"/",ncores,"cores...")) if(parallelise>ncores) stop("cores requested exceeds available count") registerDoParallel(cores=parallelise) lscv.vec <- foreach(i=1:hn,.packages="spatstat",.combine=c) %dopar% { return(LSCV.risk.single(hseq[i],cases=f,controls=g,res=resolution,edge=edge,hazey=TRUE)) } if(verbose) cat("Done.\n") } } else if(meth=="davies"){ marks(f) <- NULL marks(g) <- NULL pooled <- suppressWarnings(superimpose(f,g)) lambda <- LSCV.density(pooled,verbose=FALSE) bp <- BAMprep(f,g,lambda,3,resolution) if(is.na(parallelise)){ lscv.vec <- rep(NA,hn) if(verbose) pb <- txtProgressBar(1,hn) for(i in 1:hn){ lscv.vec[i] <- BAM.single(hseq[i],edge=edge,BP=bp) if(verbose) setTxtProgressBar(pb,i) } if(verbose) close(pb) } else { ncores <- detectCores() if(verbose) cat(paste("Evaluating criterion on",parallelise,"/",ncores,"cores...")) if(parallelise>ncores) stop("cores requested exceeds available count") registerDoParallel(cores=parallelise) lscv.vec <- foreach(i=1:hn,.packages="spatstat",.combine=c) %dopar% { return(BAM.single(hseq[i],edge=edge,BP=bp)) } if(verbose) cat("Done.\n") } } else { stop("invalid 'method'") } result <- cbind(hseq,lscv.vec) dimnames(result)[[2]] <- c("h","CV") } return(result) } else if(typ=="adaptive"){ pilot.symmetry <- pilot.symmetry[1] pdat <- list() if(pilot.symmetry=="none"){ pdat[[1]] <- f pdat[[2]] <- g } else if(pilot.symmetry=="f"){ pdat[[1]] <- pdat[[2]] <- f } else if(pilot.symmetry=="g"){ pdat[[1]] <- pdat[[2]] <- g } else if(pilot.symmetry=="pooled"){ marks(f) <- NULL marks(g) <- NULL pooled <- suppressWarnings(superimpose(f,g)) pdat[[1]] <- pdat[[2]] <- pooled } else { stop("invalid 'pilot.symmetry' argument") } if(!is.null(hp)){ if(length(hp)>1){ fp <- hp[1] gp <- hp[2] } else { fp <- gp <- hp[1] } } else { if(verbose) cat("Selecting pilot bandwidth(s)...") if(pilot.symmetry=="none"){ if(verbose) cat("\n --f--\n") fp <- LSCV.density(f,verbose=FALSE) if(verbose) cat(" --g--\n") gp <- LSCV.density(g,verbose=FALSE) } else { fp <- gp <- LSCV.density(pdat[[1]],verbose=FALSE) } if(verbose) cat(paste("Done.\n [ Using hp(f) =",fp,"\b; hp(g) =",gp,"]\n")) } hhash <- mean(hlim) if(verbose) cat("Computing multi-scale estimates...\n --f--\n") fms <- multiscale.density(f,h0=hhash,hp=fp,h0fac=hlim/hhash,edge=ifelse(edge,"uniform","none"),resolution=resolution,intensity=FALSE,pilot.density=pdat[[1]],verbose=FALSE,...) if(verbose) cat(" --g--\n") gms <- multiscale.density(g,h0=hhash,hp=gp,h0fac=hlim/hhash,edge=ifelse(edge,"uniform","none"),resolution=resolution,intensity=FALSE,pilot.density=pdat[[2]],verbose=FALSE,...) if(verbose) cat("Done.\n") h0range <- fms$h0range if(meth=="kelsall-diggle"){ if(auto.optim){ if(verbose) cat("Searching for optimal h0 in ",prange(h0range),"...",sep="") h0opt <- optimise(ms.loo.risk,interval=h0range,fob=fms,gob=gms,hazey=FALSE)$minimum if(verbose) cat("Done.\n") return(h0opt) } else { if(is.null(hseq)) hseq <- seq(h0range[1],h0range[2],length=seqres) hn <- length(hseq) if(is.na(parallelise)){ lscv.vec <- rep(NA,hn) if(verbose) pb <- txtProgressBar(1,hn) for(i in 1:hn){ lscv.vec[i] <- suppressWarnings(ms.loo.risk(hseq[i],fob=fms,gob=gms,hazey=FALSE)) if(verbose) setTxtProgressBar(pb,i) } if(verbose) close(pb) } else { ncores <- detectCores() if(verbose) cat(paste("Evaluating criterion on",parallelise,"/",ncores,"cores...")) if(parallelise>ncores) stop("cores requested exceeds available count") registerDoParallel(cores=parallelise) lscv.vec <- foreach(i=1:hn,.combine=c) %dopar% { return(suppressWarnings(ms.loo.risk(hseq[i],fob=fms,gob=gms,hazey=FALSE))) } if(verbose) cat("Done.\n") } } } else if(meth=="hazelton"){ if(auto.optim){ if(verbose) cat("Searching for optimal h0 in ",prange(h0range),"...",sep="") h0opt <- optimise(ms.loo.risk,interval=h0range,fob=fms,gob=gms,hazey=TRUE)$minimum if(verbose) cat("Done.\n") return(h0opt) } else { if(is.null(hseq)) hseq <- seq(h0range[1],h0range[2],length=seqres) hn <- length(hseq) if(is.na(parallelise)){ lscv.vec <- rep(NA,hn) if(verbose) pb <- txtProgressBar(1,hn) for(i in 1:hn){ lscv.vec[i] <- suppressWarnings(ms.loo.risk(hseq[i],fob=fms,gob=gms,hazey=TRUE)) if(verbose) setTxtProgressBar(pb,i) } if(verbose) close(pb) } else { ncores <- detectCores() if(verbose) cat(paste("Evaluating criterion on",parallelise,"/",ncores,"cores...")) if(parallelise>ncores) stop("cores requested exceeds available count") registerDoParallel(cores=parallelise) lscv.vec <- foreach(i=1:hn,.combine=c) %dopar% { return(suppressWarnings(ms.loo.risk(hseq[i],fob=fms,gob=gms,hazey=TRUE))) } if(verbose) cat("Done.\n") } } } else { stop("invalid 'method'") } result <- cbind(hseq,lscv.vec) dimnames(result)[[2]] <- c("h","CV") return(result) } else { stop("invalid 'type'") } }
nns_ratio <- function(x, N = 10, numerator = NULL, candidates = character(0), pre_trained, verbose = TRUE){ if(nrow(x)!=2) stop('nns_ratio can only be applied to a pair of embeddings i.e. nrow(x) must equal 2') if(!is.null(numerator) && rownames(x)[1]!=numerator) x <- x[c(rownames(x)[2],rownames(x)[1]),] if(length(candidates) > 0) candidates <- intersect(candidates, rownames(pre_trained)) nnsdf1 <- nns(x = x[1,], N = Inf, candidates = candidates, pre_trained = pre_trained, as_list = FALSE) nnsdf2 <- nns(x = x[2,], N = Inf, candidates = candidates, pre_trained = pre_trained, as_list = FALSE) if(is.null(N)){union_nns <- union(nnsdf1$feature, nnsdf2$feature)}else{union_nns <- union(nnsdf1$feature[1:N], nnsdf2$feature[1:N])} nnsdf1 <- nnsdf1 %>% dplyr::filter(feature %in% union_nns) %>% dplyr::arrange(feature) nnsdf2 <- nnsdf2 %>% dplyr::filter(feature %in% union_nns) %>% dplyr::arrange(feature) result <- data.frame(feature = nnsdf1$feature, value = nnsdf1$value/nnsdf2$value) %>% dplyr::arrange(-value) attr(result, "numerator") <- rownames(x)[1] if(verbose) cat("NOTE: values refer to the ratio", paste0(rownames(x)[1], "/", rownames(x)[2], ".")) return(result) }
upgrade_beast2 <- function( folder_name = rappdirs::user_data_dir(), os = rappdirs::app_dir()$os ) { stop( "'beastier::upgrade_beast2' is deprecated, \n", "as it violated CRAN policy. \n", " \n", "To upgrade BEAST2 from R, do: \n", " \n", "remotes::install_github(\"richelbilderbeek/beastierinstall\") \n", "beastierinstall::upgrade_beast2() \n" ) }
translate_full = function(x) { keyfrom = "JustForTestYouDao" key = "498375134" result = list() for (i in 1:length(x)) { x[i] = gsub( pattern = " ", replacement = "+", x = x[i] ) url = paste0( "http://fanyi.youdao.com/openapi.do?", "keyfrom=", keyfrom, "&key=", key, "&type=data&doctype=json&version=1.2&q=", x[i] ) url = utils::URLencode(iconv(url, to = 'UTF-8')) initial = RCurl::getURL(url) obj = rjson::fromJSON(initial) value = list( phonetic = ifelse( is.null(obj$basic$`us-phonetic`) == FALSE, obj$basic$`us-phonetic`, ifelse( is.null(obj$basic$`phonetic`) == FALSE, obj$basic$`phonetic`, "") ), explains = obj$basic$explains, web = obj$web[[1]]$value ) result[[i]] = value } return( purrr::flatten(result) ) }
knitr::opts_chunk$set( collapse = TRUE, comment = " eval = TRUE, echo = TRUE, message = TRUE, warning = TRUE, fig.width = 8, fig.height = 6, dpi = 200, fig.align = "center" ) knitr::opts_chunk$set() library(DataFakeR) set.seed(123) options(tibble.width = Inf) default_faker_opts$opt_pull_character default_faker_opts$opt_pull_integer
rppa2boxplot<-function (x, param , control=NULL, orderGrp=NULL, file = "boxplot_groups.pdf") { data <- select.measurements(x) groups <- unique(setdiff(data[[4]][, param],NA)) if(!is.null(control)){ groups.i <- as.character(groups[-which(groups==control)]) l.pvals <- vector("list",ncol(data[[1]])) for ( i in 1:ncol(data[[1]])){ pvals <- c(NULL) for (j in 1:length(groups.i)){ p <- wilcox.test(data[[1]][which(data[[4]][,param]==control),i], data[[1]][which(data[[4]][,param]==groups.i[j]),i]) pvals <- c(pvals,p$p.value) } adjustedvals <- signif(p.adjust(pvals,method="BH"),digits=3) l.pvals[[i]] <- adjustedvals } names(l.pvals) <- data[[3]]["target",] pdf(file=sub("_groups","_groups_wilcox",file)) groupx <- c(control,groups.i) for ( i in 1:ncol(data[[1]])){ grouplist <- vector("list",length(groupx)) if(is.null(orderGrp)){ for (j in seq(along=groupx)){ grouplist[[j]] <- data[[1]][which(data[[4]][,param]==groupx[j]),i] } names(grouplist) <- groupx par(lwd=2,bty="n") par(mar = c(6.5, 6.5, 3, 1), mgp = c(5, 1, 0)) boxplot(grouplist,main=c("target: ",data[[3]]["target",i]),bty="n", ylab="signal intensity [a.u.]",xlab="sample groups", ylim=c(c(min(unlist(grouplist))),c(max(unlist(grouplist)))*1.1), las=2) stripchart(grouplist,add=T,vertical=T,method="jitter",jitter=0.3,col="red") text( c(1:length(groups)),c(max(unlist(grouplist)))*1.1,c("control",l.pvals[[i]]), col="green") }else{ match.g<-match(orderGrp,groupx) for (j in 1:length(match.g)){ grouplist[[j]] <- data[[1]][which(data[[4]][,param]==groupx[match.g][j]),i] } names(grouplist) <- groupx[match.g] par(lwd=2,bty="n") par(mar = c(6.5, 6.5, 3, 1), mgp = c(5, 1, 0)) boxplot(grouplist,main=c("target: ",data[[3]]["target",i]),bty="n", ylab="signal intensity [a.u.]",xlab="sample groups", ylim=c(c(min(unlist(grouplist))),c(max(unlist(grouplist)))*1.1), las=2) stripchart(grouplist,add=T,vertical=T,method="jitter",jitter=0.3,col="red") text( c(1:length(groups)),c(max(unlist(grouplist)))*1.1,c("control",l.pvals[[i]])[match.g], col="green") } } dev.off() }else{ groups.i <- as.character(groups) l.pvals <- vector("list",ncol(data[[1]])) for ( i in 1:ncol(data[[1]])){ p <- kruskal.test(x=data[[1]][which(data[[4]][,param]%in%groups.i),i], g=factor(data[[4]][,param][which(data[[4]][,param]%in%groups.i)])) l.pvals[[i]] <- signif(p$p.value,digits=3) } names(l.pvals) <- data[[3]]["target",] pdf(file=sub("_groups","_groups_kruskal",file)) groupx <- groups.i for ( i in 1:ncol(data[[1]])){ grouplist <- vector("list",length(groupx)) if(is.null(orderGrp)){ for (j in seq(along=groupx)){ grouplist[[j]] <- data[[1]][which(data[[4]][,param]==groupx[j]),i] } names(grouplist) <- groupx par(lwd=2,bty="n") par(mar = c(6.5, 6.5, 3, 1), mgp = c(5, 1, 0)) boxplot(grouplist,main=c("target: ",data[[3]]["target",i]),bty="n", ylab="signal intensity [a.u.]",xlab="sample groups", ylim=c(c(min(unlist(grouplist))),c(max(unlist(grouplist)))*1.1), las=2) stripchart(grouplist,add=T,vertical=T,method="jitter",jitter=0.3,col="red") text( ifelse(length(groups)%%2==0, (length(groups))/2 + 0.5, (length(groups))/2), c(max(unlist(grouplist)))*1.1, l.pvals[[i]], col="green") }else{ match.g<-match(orderGrp,groupx) for (j in 1:length(match.g)){ grouplist[[j]] <- data[[1]][which(data[[4]][,param]==groupx[match.g][j]),i] } names(grouplist) <- groupx[match.g] par(lwd=2,bty="n") par(mar = c(6.5, 6.5, 3, 1), mgp = c(5, 1, 0)) boxplot(grouplist,main=c("target: ",data[[3]]["target",i]),bty="n", ylab="signal intensity [a.u.]",xlab="sample groups", ylim=c(c(min(unlist(grouplist))),c(max(unlist(grouplist)))*1.1), las=2) stripchart(grouplist,add=T,vertical=T,method="jitter",jitter=0.3,col="red") text(ifelse(length(groups)%%2==0, (length(groups))/2 + 0.5, (length(groups))/2), c(max(unlist(grouplist)))*1.1,l.pvals[[i]], col="green") } } dev.off() } }
getsetattr <- function(x, which, value) { ret <- copy_vector(attr(x, which)) .Call(C_R_bit_set_attr, x, which, value) ret } setattr <- function(x, which, value) { .Call(C_R_bit_set_attr, x, which, value) invisible() } setattributes <- function(x, attributes) { nam <- names(attributes) for (i in seq_len(length(attributes))){ .Call(C_R_bit_set_attr, x, nam[[i]], attributes[[i]]) } invisible() } unattr <- function(x){ attributes(x) <- NULL x }
get_match_summary <- function(match_url) { get_each_match_summary <- function(match_url) { pb$tick() each_game_page <- tryCatch(xml2::read_html(match_url), error = function(e) NA) if(!is.na(each_game_page)) { match_report <- .get_match_report_page(match_page = each_game_page) Home_Team <- tryCatch(each_game_page %>% rvest::html_nodes("div:nth-child(1) div strong a") %>% rvest::html_text() %>% .[1], error = function(e) NA) Away_Team <- tryCatch(each_game_page %>% rvest::html_nodes("div:nth-child(1) div strong a") %>% rvest::html_text() %>% .[2], error = function(e) NA) events <- each_game_page %>% rvest::html_nodes(" events_home <- events %>% rvest::html_nodes(".a") %>% rvest::html_text() %>% stringr::str_squish() events_away <- events %>% rvest::html_nodes(".b") %>% rvest::html_text() %>% stringr::str_squish() home_events <- tryCatch(data.frame(Team=Home_Team, Home_Away="Home", events_string=events_home), error = function(e) data.frame()) away_events <- tryCatch(data.frame(Team=Away_Team, Home_Away="Away", events_string=events_away), error = function(e) data.frame()) events_df <- dplyr::bind_rows(home_events, away_events) if(nrow(events_df) > 0) { events_df <- events_df %>% dplyr::mutate(Event_Time = gsub("&rsquor.*", "", .data$events_string)) %>% dplyr::mutate(Is_Pens = stringr::str_detect(.data$Event_Time, "[A-Z]")) suppressWarnings( events_df <- events_df %>% dplyr::mutate(Event_Half = dplyr::case_when( !.data$Is_Pens & as.numeric(gsub("\\+.*", "", .data$Event_Time)) <= 45 ~ 1, !.data$Is_Pens & dplyr::between(as.numeric(gsub("\\+.*", "", .data$Event_Time)), 46, 90) ~ 2, !.data$Is_Pens & dplyr::between(as.numeric(gsub("\\+.*", "", .data$Event_Time)), 91, 105) ~ 3, !.data$Is_Pens & dplyr::between(as.numeric(gsub("\\+.*", "", .data$Event_Time)), 106, 120) ~ 4, TRUE ~ 5 )) ) events_df <- events_df %>% dplyr::mutate(Event_Time = gsub("&rsquor.*", "", .data$events_string) %>% ifelse(stringr::str_detect(., "\\+"), (as.numeric(gsub("\\+.*", "", .)) + as.numeric(gsub(".*\\+", "", .))), .), Event_Time = ifelse(.data$Is_Pens, 121, .data$Event_Time), Event_Time = as.numeric(.data$Event_Time), Event_Type = ifelse(stringr::str_detect(tolower(.data$events_string), "penalty"), "Penalty", ifelse(stringr::str_detect(tolower(.data$events_string), "own goal"), "Own Goal", gsub(".* [^\x20-\x7E] ", "", .data$events_string) %>% gsub("[[:digit:]]:[[:digit:]]", "", .))) %>% stringr::str_squish(), Event_Players = gsub(".*\\;", "", .data$events_string) %>% gsub(" [^\x20-\x7E] .*", "", .), Score_Progression = stringr::str_extract(.data$Event_Players, "[[:digit:]]:[[:digit:]]"), Event_Players = gsub("[[:digit:]]:[[:digit:]]", "", .data$Event_Players) %>% stringr::str_squish(), Penalty_Number = dplyr::case_when( .data$Is_Pens ~ gsub("([0-9]+).*$", "\\1", .data$Event_Players), TRUE ~ NA_character_ ), Penalty_Number = as.numeric(.data$Penalty_Number), Event_Players = gsub("[[:digit:]]+\\s", "", .data$Event_Players), Event_Type = ifelse(.data$Is_Pens, "Penalty Shootout", .data$Event_Type)) %>% dplyr::select(-.data$events_string) %>% dplyr::arrange(.data$Event_Half, .data$Event_Time) events_df <- cbind(match_report, events_df) } else { events_df <- data.frame() } } else { print(glue::glue("Match Summary not available for {match_url}")) events_df <- data.frame() } return(events_df) } pb <- progress::progress_bar$new(total = length(match_url)) all_events_df <- match_url %>% purrr::map_df(get_each_match_summary) seasons <- read.csv("https://raw.githubusercontent.com/JaseZiv/worldfootballR_data/master/raw-data/all_leages_and_cups/all_competitions.csv", stringsAsFactors = F) seasons <- seasons %>% dplyr::filter(.data$seasons_urls %in% all_events_df$League_URL) %>% dplyr::select(League=.data$competition_name, Gender=.data$gender, Country=.data$country, Season=.data$seasons, League_URL=.data$seasons_urls) all_events_df <- seasons %>% dplyr::left_join(all_events_df, by = "League_URL") %>% dplyr::select(-.data$League_URL) %>% dplyr::distinct(.keep_all = T) return(all_events_df) }
expected <- eval(parse(text="FALSE")); test(id=0, code={ argv <- eval(parse(text="list(structure(c(NA, 1, 1, 2), .Names = c(\"<none>\", \"M.user\", \"Temp\", \"Soft\")))")); do.call(`is.list`, argv); }, o=expected);
fs_search <- function(query, author = NA, title = NA, description = NA, tag = NA, category = NA, from_date = NA, to_date = NA, mine = FALSE, public_only = FALSE, private_only = FALSE, drafts_only = FALSE, session = fs_get_auth(), base = "http://api.figshare.com/v1", debug = FALSE) { the_title <- title method <- "articles" if(mine) method <- "my_data/articles" if(public_only) method <- paste(method, "/public", sep="") if(private_only) method <- paste(method, "/private", sep="") if(drafts_only) method <- paste(method, "/drafts", sep="") if(!is.na(query)) method <- paste(method, "/search?search_for=", query, sep="") if(!is.na(author)){ method <- paste(method, "&has_author=", author, sep="") } if(!is.na(the_title)) method <- paste(method, "&has_title=", the_title, sep="") if(!is.na(description)) method <- paste(method, "&has_description=", description, sep="") if(!is.na(tag)) method <- paste(method, "&has_tag=", tag, sep="") if(!is.na(category)){ method <- paste(method, "&has_category=", category, sep="") } if(!is.na(from_date)) method <- paste(method, "&from_date=", from_date, sep="") if(!is.na(to_date)) method <- paste(method, "&to_date=", to_date, sep="") request <- paste(base, method, sep="/") request <- build_url(parse_url(request)) out <- GET(request, config(token = session)) if(debug | out$status_code != 200) out else { parsed <- fromJSON(content(out, "text")) if(is.null(parsed$count)) parsed$count <- parsed$items_found if(is.null(parsed$count)) parsed$count <- length(parsed$items) out <- parsed$items if(parsed$count > 10) { total_pages <- ceiling(parsed$count / 10) all <- lapply(1:total_pages, function(i){ method_ <- paste(method, "&page=", i, sep="") request = paste(base, method_, sep="/") request <- build_url(parse_url(request)) out <- GET(request, config(token = session)) parsed <- fromJSON(content(out, as = "text")) parsed$items }) out <- unlist(all, recursive = FALSE) } out } }
Gscores <- function(IATlong) { Gaussianranks <- function(x) { y <- x[!is.na(x)] N <- length(y) Fr <- rank(y)/N Fr <- Fr - 1/(2*N) Gr <- scale(Fr) attr(Gr, "scaled:center") <- NULL attr(Gr, "scaled:scale") <- NULL x[!is.na(x)] <- Gr x } Mranks <- filter(IATlong, variable != "pxxxx") %>% group_by(subject, variable) %>% mutate(Gr = Gaussianranks(RT)) %>% group_by(subject, variable, blockcode) %>% summarize(Mean = mean(Gr, na.rm = TRUE)) Mranks <- dcast(Mranks, subject*variable ~ blockcode, value.var = "Mean") Mranks <- mutate(Mranks, Gscore = pair2 - pair1) Gsc <- dcast(Mranks, subject ~ variable, value.var = "Gscore") names(Gsc) <- str_replace(names(Gsc), "xx", "2x") Gsc }
setMethodS3("plotCovariateEffects", "GcContentNormalization2", function(this, arrays=NULL, units=NULL, ref="zero", ..., pch=".", lwd=2, xlim=NULL, ylim="auto", xlab="GC fraction", ylab="auto", verbose=FALSE) { dataSet <- getInputDataSet(this) if (!is.null(arrays)) { arrays <- Arguments$getIndices(arrays, max=length(dataSet)) } if (is.null(ref)) { } else if (is.character(ref)) { } else if (inherits(ref, "SnpChipEffectFile")) { } else { throw("Unknown value of argument 'ref': ", class(ref)[1]) } unf <- getUnitNamesFile(dataSet) if (is.null(units)) { units <- seq_len(nbrOfUnits(unf)) } else { units <- Arguments$getIndices(units, max=nbrOfUnits(unf)) } verbose <- Arguments$getVerbose(verbose) if (verbose) { pushState(verbose) on.exit(popState(verbose)) } verbose && enter(verbose, "Plotting signals as a function of covariate(s)") verbose & cat(verbose, "Arrays:") verbose & str(verbose, arrays) X <- getCovariates(this, units=units, verbose=less(verbose,5)) verbose & cat(verbose, "Covariates:") verbose & str(verbose, X) X <- X[,1] keep <- is.finite(X) X <- X[keep] units <- units[keep] keep <- NULL stopifnot(length(units) == length(X)) yR <- NULL if (is.character(ref)) { if (ref == "median") { verbose && enter(verbose, "Calculating reference (average) file") ref <- getAverageFile(dataSet, verbose=less(verbose,10)) verbose && exit(verbose) if (is.null(ylim)) { ylim <- c(-1,1)*3 } } else if (ref == "zero") { if (is.null(ylim)) { ylim <- c(0,16) } } } if (inherits(ref, "SnpChipEffectFile")) { verbose && enter(verbose, "Extracting reference signals") yR <- extractTotalAndFreqB(ref, units=units, drop=TRUE, verbose=less(verbose,50))[,"total"] yR <- log2(yR) verbose && str(verbose, yR) verbose && exit(verbose) } if (!is.null(arrays)) { dataSet <- extract(dataSet, arrays, onDuplicates="error") } if (is.null(xlim)) { xlim <- range(X, na.rm=TRUE) } if (identical(ylim, "auto")) { if (is.null(yR)) { ylim <- c(0,16) } else { ylim <- c(-3,3) } } if (identical(ylab, "auto")) { if (is.null(yR)) { ylab <- expression(log[2](theta)) } else { ylab <- expression(log[2](theta/theta[R])) } } verbose && enter(verbose, "Plotting") nbrOfArrays <- length(dataSet) subplots(nbrOfArrays) par(mar=c(4,3,1,0.5)+0.1, mgp=c(2.0, 0.8, 0)) for (cc in seq_len(nbrOfArrays)) { ce <- dataSet[[cc]] name <- getFullName(ce) name <- gsub(",chipEffects", "", name) verbose && enter(verbose, sprintf("Array x <- X verbose && enter(verbose, "Extracting total signals") y <- extractTotalAndFreqB(ce, units=units, drop=TRUE, verbose=less(verbose,50))[,"total"] y <- log2(y) if (!is.null(yR)) { y <- y - yR } verbose && exit(verbose) verbose && cat(verbose, "(x,y):") verbose && str(verbose, x) verbose && str(verbose, y) ok <- (is.finite(x) & is.finite(y)) x <- x[ok] y <- y[ok] ok <- NULL verbose && enter(verbose, "smoothScatter(x,y, ...):") verbose && str(verbose, x) verbose && str(verbose, y) smoothScatter(x, y, pch=pch, xlab=xlab, ylab=ylab, xlim=xlim, ylim=ylim) verbose && exit(verbose) stext(side=3, pos=1, name) if (!is.null(yR)) { abline(h=0, col=" } fit <- smooth.spline(x,y) lines(fit, col="red", lwd=lwd) x <- y <- NULL verbose && exit(verbose) } verbose && exit(verbose) yR <- NULL verbose && exit(verbose) })
Task <- R6::R6Class("Task", private = list( process = NULL, target = NULL, args = NULL, callback = NULL, error = NULL, should_release = FALSE ), public = list( time = NULL, delay = NULL, initialize = function(target, args, callback = NULL, error = NULL, delay = 0) { private$target <- target private$args <- args private$callback <- callback private$error <- error self$time <- Sys.time() self$delay <- delay }, start = function(session) { if (is.null(session)) { private$should_release <- FALSE private$process <- callr::r_bg( private$target, private$args, system_profile = TRUE, user_profile = TRUE ) } else { private$should_release <- TRUE private$process <- session private$process$start(private$target, private$args) } }, check = function() { if (is.null(private$process)) { FALSE } else if (private$process$is_alive()) { FALSE } else { result <- NULL if (private$should_release) { result <- private$process$get_result() private$process$release() } else { result <- tryCatch(private$process$get_result(), error = function(e) e) } if (!is.null(private$callback)) { if (inherits(result, "error")) { if (!is.null(private$error)) { private$error(result) } } else { private$callback(result) } } TRUE } }, kill = function() { private$process$kill() } ) ) TaskManager <- R6::R6Class("TaskManager", private = list( cpus = NULL, pending_tasks = NULL, running_tasks = NULL, session_pool = NULL, name = NULL, use_session = FALSE ), public = list( initialize = function(name, session_pool = NULL) { private$cpus <- parallel::detectCores() private$pending_tasks <- collections::ordered_dict() private$running_tasks <- collections::ordered_dict() private$session_pool <- session_pool private$use_session <- !is.null(session_pool) private$name <- name }, add_task = function(id, task) { private$pending_tasks$set(id, task) }, run_tasks = function(cpu_load = 0.5) { n <- 0 if (private$use_session) { n <- private$session_pool$get_idle_size() } else { n <- max(max(private$cpus * cpu_load, 1) - private$running_tasks$size(), 0) } ids <- private$pending_tasks$keys() if (length(ids) > n) { ids <- ids[seq_len(n)] } for (id in ids) { task <- private$pending_tasks$get(id) if (Sys.time() - task$time >= task$delay) { session <- NULL if (private$use_session) { session <- private$session_pool$acquire() if (is.null(session)) { next } } if (private$running_tasks$has(id)) { task <- private$running_tasks$pop(id) task$kill() } task <- private$pending_tasks$pop(id) private$running_tasks$set(id, task) task$start(session) } } }, check_tasks = function() { running_tasks <- private$running_tasks keys <- private$running_tasks$keys() pending_tasks <- private$pending_tasks for (key in keys) { task <- running_tasks$get(key) if (task$check()) { logger$info(private$name, "task timing:", Sys.time() - task$time, " ", key) running_tasks$remove(key) } } } ) ) package_call <- function(target) { func <- call(":::", as.name("languageserver"), substitute(target)) target <- eval(substitute(function(...) func(...), list(func = func))) target } create_task <- function(target, args, callback = NULL, error = NULL, delay = 0) { Task$new( target = target, args = args, callback = callback, error = error, delay = delay ) }
ce.simnormal.Init.MeanVar.AIC <- function(N, init.locs, data, h, L0, L, M, Melite, eps, a, b, var.init){ new_para <- rbind(init.locs, rep(var.init, N)) k<-0 repeat { k<-k+1 ch<-array(0,dim=c(M,N+2)) ch[,1]<-c(1) ch[,N+2]<-c(L+1) ch[,(2:(N+1))]<-apply(new_para,2,normrand,L0,L,M) ch<-t(apply(ch,1,sort)) LL.full <- apply(ch, 1, llhood.MeanVarNormal, data, h) AIC.val <- apply(as.data.frame(LL.full), 1, AIC.MeanVarNormal, N, L) ch <- cbind(ch, LL.full, AIC.val) ch <- ch[order(ch[, (N + 4)], decreasing = FALSE), ] melitesmpl<-ch[1:Melite,] new_par_n<-array(0,dim=c(2,N)) new_par_n[1,]<-apply(as.matrix(melitesmpl[,(2:(N+1))]),2,mean) new_par_n[2,]<-apply(as.matrix(melitesmpl[,(2:(N+1))]),2,sd) new_para[1,] <- a*new_par_n[1,] + (1-a)*new_para[1,] new_para[2,] <- b*new_par_n[2,] + (1-b)*new_para[2,] mad<-apply(as.matrix(melitesmpl[,(2:(N+1))]),2,mad) if(max(mad)<=eps){break} } return(list(loci=ch[1,(1:(N+2))], AIC.Val = melitesmpl[1, (N + 4)][[1]], LogLike = melitesmpl[1, (N + 3)][[1]])) }
warningf = function(..., immediate = TRUE, warning.length = 8170L) { msg = sprintf(...) if (immediate) { old = getOption("warn") if (old <= 0L) { on.exit(options(warn = old)) options(warn = 1L) } } obj = simpleWarning(msg, call = sys.call(sys.parent())) warning(obj) }
sits_timeline <- function(data) { .check_set_caller("sits_timeline") data <- .config_data_meta_type(data) UseMethod("sits_timeline", data) } sits_timeline.sits <- function(data) { return(data$time_series[[1]]$Index) } sits_timeline.sits_model <- function(data) { return(environment(data)$data$time_series[[1]]$Index) } sits_timeline.raster_cube <- function(data) { timelines.lst <- slider::slide(data, function(tile) { timeline_tile <- .file_info_timeline(tile) return(timeline_tile) }) names(timelines.lst) <- data$tile timeline_unique <- unname(unique(timelines.lst)) if (length(timeline_unique) == 1) return(timeline_unique[[1]]) else { warning("Cube is not regular. Returning all timelines") return(timelines.lst) } } sits_timeline.satveg_cube <- function(data) { ts <- .sits_satveg_ts_from_txt(longitude = -55.50563, latitude = -11.71557, data) return(as.Date(ts$Index)) } sits_timeline.wtss_cube <- function(data) { return(.file_info_timeline_wtss(data)) } sits_timeline.probs_cube <- function(data) { start_date <- .file_info_start_date(data) end_date <- .file_info_end_date(data) timeline_probs <- c(start_date, end_date) return(timeline_probs) } sits_timeline.uncertainty_cube <- function(data) { start_date <- .file_info_start_date(data) end_date <- .file_info_end_date(data) timeline_uncert <- c(start_date, end_date) return(timeline_uncert) } sits_timeline.classified_image <- function(data) { start_date <- .file_info_start_date(data) end_date <- .file_info_end_date(data) timeline_class <- c(start_date, end_date) return(timeline_class) } .sits_timeline_check_cube <- function(cube, start_date, end_date) { .check_set_caller(".sits_timeline_check_cube") timeline <- sits_timeline(cube) if (purrr::is_null(start_date)) { start_date <- lubridate::as_date(timeline[1]) } else { .check_that( x = start_date >= timeline[1], msg = paste("start_date is not inside the cube timeline") ) } if (purrr::is_null(end_date)) { end_date <- lubridate::as_date(timeline[length(timeline)]) } else { .check_that( x = end_date <= timeline[length(timeline)], msg = paste("end_date is not inside the cube timeline") ) } start_end <- c(lubridate::as_date(start_date), lubridate::as_date(end_date)) names(start_end) <- c("start_date", "end_date") return(start_end) } .sits_timeline_class_info <- function(data, samples) { timeline <- sits_timeline(data) .check_length( x = timeline, len_min = 1, msg = "sits_timeline_class_info: invalid timeline" ) .sits_tibble_test(samples) labels <- sits_labels(samples) bands <- sits_bands(samples) ref_start_date <- lubridate::as_date(samples[1, ]$start_date) ref_end_date <- lubridate::as_date(samples[1, ]$end_date) num_samples <- nrow(samples[1, ]$time_series[[1]]) ref_dates <- .sits_timeline_match(timeline, ref_start_date, ref_end_date, num_samples) dates_index <- .sits_timeline_match_indexes(timeline, ref_dates) nsamples <- dates_index[[1]][2] - dates_index[[1]][1] + 1 class_info <- tibble::tibble( bands = list(bands), labels = list(labels), timeline = list(timeline), num_samples = nsamples, ref_dates = list(ref_dates), dates_index = list(dates_index) ) return(class_info) } .sits_timeline_valid_date <- function(date, timeline) { if (date %within% lubridate::interval(timeline[1], timeline[length(timeline)])) return(TRUE) timeline_diff <- as.integer(timeline[2] - timeline[1]) if (abs(as.integer(date - timeline[1])) <= timeline_diff) { return(TRUE) } timeline_diff <- as.integer(timeline[length(timeline)] - timeline[length(timeline) - 1]) if (abs(as.integer(date - timeline[length(timeline)])) <= timeline_diff) { return(TRUE) } return(FALSE) } .sits_timeline_match <- function(timeline, ref_start_date, ref_end_date, num_samples) { .check_set_caller(".sits_timeline_match") timeline <- lubridate::as_date(timeline) input_start_date <- timeline[1] ref_st_mday <- as.character(lubridate::mday(ref_start_date)) ref_st_month <- as.character(lubridate::month(ref_start_date)) year_st_date <- as.character(lubridate::year(input_start_date)) est_start_date <- lubridate::as_date(paste0(year_st_date, "-", ref_st_month, "-", ref_st_mday) ) idx_start_date <- which.min(abs(est_start_date - timeline)) start_date <- timeline[idx_start_date] .check_that( x = .sits_timeline_valid_date(start_date, timeline), msg = "start date in not inside timeline" ) subset_dates <- list() idx_end_date <- idx_start_date + (num_samples - 1) end_date <- timeline[idx_end_date] .check_that( x = !(is.na(end_date)), msg = paste("start and end date do not match timeline/n", "Please compare your timeline with your samples") ) while (!is.na(end_date)) { subset_dates[[length(subset_dates) + 1]] <- c(start_date, end_date) idx_start_date <- idx_end_date + 1 start_date <- timeline[idx_start_date] idx_end_date <- idx_start_date + num_samples - 1 end_date <- timeline[idx_end_date] } end_date <- subset_dates[[length(subset_dates)]][2] .check_that( x = .sits_timeline_valid_date(end_date, timeline), msg = "end_date not inside timeline" ) return(subset_dates) } .sits_timeline_match_indexes <- function(timeline, ref_dates) { dates_index <- ref_dates %>% purrr::map(function(date_pair) { start_index <- which(timeline == date_pair[1]) end_index <- which(timeline == date_pair[2]) dates_index <- c(start_index, end_index) return(dates_index) }) return(dates_index) } .sits_timeline_dist_indexes <- function(class_info, ntimes) { .check_set_caller(".sits_timeline_dist_indexes") dates_index <- class_info$dates_index[[1]] timeline <- class_info$timeline[[1]] bands <- class_info$bands[[1]] n_bands <- length(bands) .check_that( x = n_bands > 0, msg = "no bands in cube" ) time_index <- .sits_timeline_idx_from_dates(dates_index, timeline, bands) size_lst <- n_bands * ntimes + 2 dist_indexes <- purrr::map(time_index, function(idx) { dist_idx <- logical(length = size_lst) dist_idx[1:2] <- TRUE for (b in seq_len(n_bands)) { i1 <- idx[[(2 * b - 1)]] + 2 i2 <- idx[[2 * b]] + 2 dist_idx[i1:i2] <- TRUE } return(dist_idx) }) return(dist_indexes) } .sits_timeline_idx_from_dates <- function(dates_index, timeline, bands) { n_bands <- length(bands) time_index <- dates_index %>% purrr::map(function(idx) { idx_lst <- seq_len(n_bands) %>% purrr::map(function(b) { idx1 <- idx[1] + (b - 1) * length(timeline) idx2 <- idx[2] + (b - 1) * length(timeline) return(c(idx1, idx2)) }) index_ts <- unlist(idx_lst) return(index_ts) }) return(time_index) } .sits_timeline_during <- function(timeline, start_date = NULL, end_date = NULL) { .check_set_caller(".sits_timeline_during") if (purrr::is_null(start_date)) { start_date <- timeline[1] } if (purrr::is_null(end_date)) { end_date <- timeline[length(timeline)] } valid <- timeline >= lubridate::as_date(start_date) & timeline <= lubridate::as_date(end_date) .check_that( x = any(valid), msg = paste("no valid data between ", as.Date(start_date), " and ", as.Date(end_date)) ) return(timeline[valid]) } .sits_timeline_date_format <- function(date) { .check_set_caller(".sits_timeline_date_format") .check_length( x = date, len_min = 1, msg = "invalid date parameter") converted_date <- purrr::map_dbl(date, function(dt) { if (length(strsplit(dt, "-")[[1]]) == 1) converted_date <- lubridate::fast_strptime(dt, "%Y") else if (length(strsplit(dt, "-")[[1]]) == 2) converted_date <- lubridate::fast_strptime(dt, "%Y-%m") else converted_date <- lubridate::fast_strptime(dt, "%Y-%m-%d") converted_date <- lubridate::as_date(converted_date) .check_that( x = !is.na(converted_date), msg = paste0("invalid date format '", dt, "' in file name") ) return(converted_date) }) converted_date <- lubridate::as_date(converted_date) .check_length( x = converted_date, len_min = length(date), len_max = length(date), msg = "invalid date values" ) return(converted_date) } .sits_timeline_check <- function(data) { .sits_tibble_test(data) if (length(unique(lapply(data$time_series, nrow))) == 1) return(TRUE) else return(FALSE) }
dbColumnInfo_MariaDBResult <- function(res, ...) { df <- result_column_info(res@ptr) df$name <- tidy_names(df$name) df } setMethod("dbColumnInfo", "MariaDBResult", dbColumnInfo_MariaDBResult)
get_slicingDistance <- function(slicingDistance = NULL, data, d = ncol(data)) { if(is.null(slicingDistance)) { halfRange <- max(sqrt(rowSums(tourr::center(data)^2))) vRel <- (halfRange^(d - 2))/10 slicingDistance <- vRel^(1/(d - 2)) } slicingDistance } get_slicingIn <- function(proj, data, slicingDistance) { orthogonalDistance <- anchored_orthogonal_distance(proj, data) orthogonalDistance[,1] < slicingDistance } anchored_orthogonal_distance <- function (plane, data, anchor = NULL) { n <- ncol(data) if (is.null(anchor)) { anchor <- matrix(colMeans(data), ncol = n) } else { anchor <- matrix(anchor, ncol = n) } alpha_sq <- sum(anchor^2) - sum((anchor %*% plane)^2) full_norm_sq <- apply(data, 1, function(x) sum(x^2)) subtr <- lapply(seq(ncol(plane)), function(i) { as.matrix(data) %*% plane[, i] }) dist_sq <- full_norm_sq - Reduce("+", lapply(subtr, function(x) x^2)) subtr_drop <- lapply(seq(ncol(plane)), function(i) { subtr[[i]] * drop(anchor %*% plane[, i]) }) xterm <- 2 * (as.matrix(data) %*% t(anchor) - Reduce("+", subtr_drop)) sqrt(dist_sq + alpha_sq - xterm) }
kAAComposition<-function(seqs,rng=3,upto=FALSE,normalized=TRUE,label=c()){ if(length(seqs)==1&&file.exists(seqs)){ seqs<-fa.read(seqs,alphabet="aa") seqs_Lab<-alphabetCheck(seqs,alphabet = "aa",label) seqs<-seqs_Lab[[1]] label<-seqs_Lab[[2]] } else if(is.vector(seqs)){ seqs<-sapply(seqs,toupper) seqs_Lab<-alphabetCheck(seqs,alphabet = "aa",label) seqs<-seqs_Lab[[1]] label<-seqs_Lab[[2]] } else { stop("ERROR: Input sequence is not in the correct format. It should be a FASTA file or a string vector.") } if(upto==TRUE && length(rng)==1){ l<-length(rng) l<-rng[l] rng<-1:l } rng <- sort(rng) rng <- unique(rng) len<-length(rng) dict<-list("A"=1,"C"=2,"D"=3,"E"=4,"F"=5,"G"=6,"H"=7,"I"=8,"K"=9,"L"=10,"M"=11,"N"=12,"P"=13,"Q"=14,"R"=15,"S"=16,"T"=17,"V"=18,"W"=19,"Y"=20) mergedMatrix<-vector(mode = "numeric") numSeqs<-length(seqs) for(l in rng){ featureMatrix<-matrix(0,ncol = (20^l),nrow = numSeqs) namesKmer<-nameKmer(l,type = "aa") colnames(featureMatrix)<-namesKmer for(n in 1:numSeqs){ seq<-seqs[n] seqChars<-unlist(strsplit(seq,split = "")) lenSeq<-length(seqChars) kmers<-"" for (i in 0:(l-1)){ temp<-seqChars[(1+i):(lenSeq-(l-1-i))] kmers<-paste(kmers,temp,sep = "") } tabKmers<-table(kmers) tabNames<-names(tabKmers) for(i in 1:length(tabKmers)) { temp<-unlist(strsplit(tabNames[i],split = "")) num=0 for(j in 1:l){ pow<-20^(l-j) num<-num+(((as.numeric(dict[temp[j]]))-1)*pow) } num<-num+1 featureMatrix[n,num]<-tabKmers[i] } } mergedMatrix<-cbind(mergedMatrix,featureMatrix) } if(normalized==TRUE){ seqLen<-sapply(seqs, nchar) mergedMatrix<-mergedMatrix/seqLen } if(length(label)==numSeqs){ mergedMatrix<-as.data.frame(mergedMatrix) mergedMatrix<-cbind(mergedMatrix,label) } row.names(mergedMatrix)<-names(seqs) return(mergedMatrix) }
[ { "title": "Inaccurate results from microbenchmark", "href": "https://radfordneal.wordpress.com/2014/02/02/inaccurate-results-from-microbenchmark/" }, { "title": "Using R to visually compare the volume of different information sources", "href": "https://web.archive.org/web/http://somelab.ischool.uw.edu/2013/01/using-r-to-visually-compare-the-volume-of-different-information-sources/" }, { "title": "JAGS model Fe concentration in rainwater including values below detection level", "href": "http://wiekvoet.blogspot.com/2013/12/jags-model-fe-concentration-in.html" }, { "title": "Tutorials freely available of course I taught: including ggplot2, dplyr and shiny", "href": "http://www.numbertheory.nl/2015/09/05/tutorials-freely-available-form-course-i-taught-including-ggplot2-dplyr-and-shiny/" }, { "title": "how to create a variable with r", "href": "http://www.twotorials.com/2012/03/how-to-create-variable-with-r.html" }, { "title": "R Tagosphere!", "href": "http://amitkohli.com/r-tagosphere/" }, { "title": "Feller’s shoes and Rasmus’ socks [well, Karl’s actually…]", "href": "https://xianblog.wordpress.com/2014/10/24/fellers-shoes-and-rasmus-socks-well-karls-actually/" }, { "title": "A list of R packages, by popularity", "href": "http://blog.revolutionanalytics.com/2013/06/a-list-of-r-packages-by-popularity.html" }, { "title": "Efficiency Balanced Information Criterion for Item Selection", "href": "http://www.econometricsbysimulation.com/2013/11/efficiency-balanced-information.html" }, { "title": "Slide: one function for lag/lead variables in data frames, including time-series cross-sectional data", "href": "http://christophergandrud.blogspot.com/2013/05/slide-one-function-for-laglead.html" }, { "title": "Changes to FSA — Size Structure", "href": "https://web.archive.org/web/https://fishr.wordpress.com/2014/09/16/changes-to-fsa-size-structure/" }, { "title": "partools: a Sensible R Package for Large Data Sets", "href": "https://matloff.wordpress.com/2015/08/05/partools-a-sensible-r-package-for-large-data-sets/" }, { "title": "Bottom-up creation of data-driven capabilities: show don’t tell", "href": "http://ww7.housesofstones.com/" }, { "title": "xkcd: A webcomic of the internet, small talk, meta discussions, and whimsical phantasmagoria", "href": "http://www.hotdamndata.com/2013/10/xkcd-webcomic-of-internet-small-talk.html" }, { "title": "The Shape of Floating Point Random Numbers", "href": "http://www.johnmyleswhite.com/notebook/2012/10/15/the-shape-of-floating-point-random-numbers/" }, { "title": "A Tale of Two Charting Paradigms: Vega-Lite vs R+ggplot2", "href": "http://rud.is/b/2016/02/28/a-tale-of-two-charting-paradigms-vega-lite-vs-rggplot2/" }, { "title": "Expected overestimation of Cohen’s d under publication bias", "href": "http://rpsychologist.com/expected-overestimation-of-cohens-d-under-publication-bias" }, { "title": "Data Science with R", "href": "http://www.dataperspective.info/2015/12/datasciencewithR.html" }, { "title": "An Analysis of Traffic Violation Data with SQL Server and R", "href": "http://blog.revolutionanalytics.com/2016/04/an-analysis-of-traffic-violation-data-with-sql-server-and-r.html" }, { "title": "An obscure integral", "href": "https://xianblog.wordpress.com/2010/04/08/an-obscure-integral/" }, { "title": "In case you missed it: September 2012 Roundup", "href": "http://blog.revolutionanalytics.com/2012/10/in-case-you-missed-it-september-2012-roundup.html" }, { "title": "Fun with geocoding and mapping in JGR", "href": "https://nerdsrule.co/2012/07/31/fun-with-geocoding-and-mapping-with-r-and-jgr/" }, { "title": "Shiny module design patterns: Pass module inputs to other modules", "href": "https://itsalocke.com/shiny-module-design-patterns-pass-module-input-to-other-modules/" }, { "title": "R User Groups Highlight R Creativity", "href": "http://blog.revolutionanalytics.com/2015/10/r-user-groups-highlight-r-creativity.html" }, { "title": "Credit Scoring in R 101", "href": "https://web.archive.org/web/http://jkunst.com/post/credit-scoring-r-101/" }, { "title": "Repeated Measures ANOVA using R", "href": "https://web.archive.org/web/http://blog.gribblelab.org/2009/03/09/repeated-measures-anova-using-r/" }, { "title": "TripleR/ BlockR: Working on mixed effect models …", "href": "https://gsoc2010r.wordpress.com/2010/07/09/tripler-blockr-working-on-mixed-effect-models/" }, { "title": "How NOAA uses R to forecast river flooding", "href": "http://blog.revolutionanalytics.com/2012/04/noaa-r-river-flooding.html" }, { "title": "Runing R in the Command Mode in the Window system", "href": "http://yusung.blogspot.com/2009/01/runing-r-in-command-mode-in-window.html" }, { "title": "Dump R datasets into a single file", "href": "https://danganothererror.wordpress.com/2010/08/22/dump-r-datasets-into-a-single-file/" }, { "title": "Seasonal adjusment on the fly with X-13ARIMA-SEATS, seasonal and ggplot2", "href": "http://ellisp.github.io/blog/2015/10/10/X13ARIMA-SEATS" }, { "title": "Quandl.com for Time Series Datasets", "href": "http://r-datameister.blogspot.com/2013/07/quandlcom-for-time-series-datasets.html" }, { "title": "Webinar Nov 17: What’s new in Revolution R Enterprise 5.0", "href": "http://blog.revolutionanalytics.com/2011/11/webinar-nov-17-whats-new-in-revolution-r-enterprise-50.html" }, { "title": "Export R data to tex code", "href": "https://binfalse.de/2010/10/12/export-r-data-to-tex-code/" }, { "title": "Presidential Debates 2012", "href": "https://trinkerrstuff.wordpress.com/2012/10/23/presidential-debates-2012/" }, { "title": "Cluster Portfolio Allocation", "href": "https://systematicinvestor.wordpress.com/2013/02/12/cluster-portfolio-allocation/" }, { "title": "An OpenBLAS-based Rblas for Windows 64", "href": "http://www.avrahamadler.com/2013/10/22/an-openblas-based-rblas-for-windows-64/" }, { "title": "A Warning About warning()", "href": "http://blog.obeautifulcode.com/R/A-Warning-About-Warning/" }, { "title": "Example 8.8: more Hosmer and Lemeshow", "href": "https://feedproxy.google.com/~r/SASandR/~3/OIM0_nermng/example-88-more-hosmer-and-lemeshow.html" }, { "title": "Introduction to Fractals", "href": "http://www.exegetic.biz/blog/2013/11/introduction-to-fractals/" }, { "title": "Winning a Marathon", "href": "http://www.moreorlessnumbers.com/2014/12/winning-marathon.html" }, { "title": "A very short and unoriginal introduction to snow", "href": "http://leftcensored.skepsi.net/2011/04/02/a-very-short-and-unoriginal-introduction-to-snow/" }, { "title": "Let’s go! (and Disclaimer)", "href": "http://rcrastinate.blogspot.com/2012/09/lets-go.html" }, { "title": "Morning coffee: scripting language", "href": "https://martinsbioblogg.wordpress.com/2014/03/13/morning-coffee-scripting-languages/" }, { "title": "Introducing V8: An Embedded JavaScript Engine for R", "href": "https://www.opencpu.org/posts/v8-release-0-2/" }, { "title": "Progress bar in R", "href": "http://zvfak.blogspot.com/2013/02/progress-bar-in-r.html" }, { "title": "Measuring persistence in a time series : Application of rolling window regression", "href": "http://programming-r-pro-bro.blogspot.com/2012/07/measuring-persistence-in-time-series.html" }, { "title": "Scripts and Functions: Using R to Implement the Golden Section Search Method for Numerical Optimization", "href": "https://chemicalstatistician.wordpress.com/2013/04/22/using-r-to-implement-the-golden-bisection-method/" }, { "title": "A wordcloud comparison of the 2011 and 2012 "href": "http://simplystatistics.tumblr.com/post/16448577464/a-wordcloud-comparison-of-the-2011-and-2012-sotu" }, { "title": "Data Manipulation with R – Spector (2008)", "href": "https://feedproxy.google.com/~r/ProgrammingR/~3/eCC9duZ522A/" } ]
message(" if (interactive()) { pkgload::load_all(".") source(file.path( devtools::as.package(".")["path"], "inst", "runit_tests", "setup.R" )) } message(" suppressWarnings(rm("s1", "s2", "s12")) data("zberg", package = "forestinventory") set.seed(1234) zberg[["weights"]] <- sample(c(rep(1, 5), 0.2), nrow(zberg), replace = TRUE) s1 <- zberg[zberg[["phase_id_2p"]] == 1, ] s2 <- zberg[zberg[["phase_id_2p"]] == 2, ] s12 <- rbind(s1, s2) s12[["s1"]] <- s12[["phase_id_2p"]] %in% c(1, 2) s12[["s2"]] <- s12[["phase_id_2p"]] == 2 test_unclustered_unweighted <- function() { fi <- forestinventory::twophase( formula = basal ~ stade + couver + melange, data = zberg, phase_id = list(phase.col = "phase_id_2p", terrgrid.id = 2), small_area = list( sa.col = "ismallold", areas = c("1"), unbiased = TRUE ) )$estimation object <- maSAE::saObj( data = s12, f = basal ~ stade + couver + melange | ismallold, s2 = "s2" ) ma <- maSAE::predict(object) RUnit::checkEquals(ma[2, c(2, 3)], fi[c(2, 4)], check.attributes = FALSE) } if (interactive()) test_unclustered_unweighted() test_unclustered_weighted <- function() { fi <- forestinventory::twophase( formula = basal ~ stade + couver + melange, data = zberg, phase_id = list(phase.col = "phase_id_2p", terrgrid.id = 2), boundary_weights = "weights", small_area = list( sa.col = "ismallold", areas = c("1"), unbiased = TRUE ) )$estimation object <- saObj( data = s12, f = basal ~ stade + couver + melange | ismallold, auxiliaryWeights = "weights", s2 = "s2" ) ma <- maSAE::predict(object) RUnit::checkEquals(ma[2, c(2, 3)], fi[c(2, 4)], check.attributes = FALSE) } if (interactive()) test_unclustered_weighted()
structure(list(url = "/api/datasets/5b6c9f/batches/", status_code = 202L, headers = structure(list(date = "Thu, 25 Mar 2021 15:18:28 GMT", `content-type` = "application/json;charset=utf-8", `content-length` = "179", location = "/api/datasets/5b6c9f/batches/import_batch%3A5b6c9f%24c6f12343-98a7-414c-b850-f4bc7ab927e2/", server = "nginx", `content-encoding` = "gzip", vary = "Cookie, Accept-Encoding", allow = "GET, HEAD, OPTIONS, POST", `x-timing` = "", `x-xss-protection` = "1; mode=block", `strict-transport-security` = "max-age=31536000; includeSubDomains", `x-content-type-options` = "nosniff"), class = c("insensitive", "list")), all_headers = list(list(status = 202L, version = "HTTP/2", headers = structure(list(date = "Thu, 25 Mar 2021 15:18:28 GMT", `content-type` = "application/json;charset=utf-8", `content-length` = "179", location = "/api/datasets/5b6c9f/batches/import_batch%3A5b6c9f%24c6f12343-98a7-414c-b850-f4bc7ab927e2/", server = "nginx", `content-encoding` = "gzip", vary = "Cookie, Accept-Encoding", allow = "GET, HEAD, OPTIONS, POST", `x-timing` = "", `x-xss-protection` = "1; mode=block", `strict-transport-security` = "max-age=31536000; includeSubDomains", `x-content-type-options` = "nosniff"), class = c("insensitive", "list")))), cookies = structure(list(domain = logical(0), flag = logical(0), path = logical(0), secure = logical(0), expiration = structure(numeric(0), class = c("POSIXct", "POSIXt")), name = logical(0), value = logical(0)), row.names = integer(0), class = "data.frame"), content = charToRaw("{\"element\": \"shoji:view\", \"self\": \"/api/datasets/5b6c9f/batches/\", \"value\": \"/api/progress/\"}"), date = structure(1616685508, class = c("POSIXct", "POSIXt" ), tzone = "GMT"), times = c(redirect = 0, namelookup = 2.8e-05, connect = 2.9e-05, pretransfer = 8.5e-05, starttransfer = 9e-05, total = 0.1917)), class = "response")
is.corranalysis <- function(x) { inherits(x, "corranalysis") }
readDataSetFacto <- function() { initializeDialog(title=.Facto_gettext("Read Text Data From File, Clipboard, or URL")) optionsFrame <- tkframe(top) dsname <- tclVar(.Facto_gettext("Dataset")) entryDsname <- ttkentry(optionsFrame, width="20", textvariable=dsname) radioButtons(optionsFrame, "location", buttons=c("local", "clipboard", "url"), labels=.Facto_gettext(c("Local file system", "Clipboard", "Internet URL")), title=.Facto_gettext("Location of Data File")) headerVariable <- tclVar("1") nameRows <- tclVar("0") headerCheckBox <- tkcheckbutton(optionsFrame, variable=headerVariable) rowCheckBox <- tkcheckbutton(optionsFrame, variable=nameRows) radioButtons(optionsFrame, "delimiter", buttons=c("whitespace", "commas", "tabs"), labels=.Facto_gettext(c("White space", "Commas", "Tabs")), title=.Facto_gettext("Field Separator")) otherButton <- ttkradiobutton(delimiterFrame, variable=delimiterVariable, value="other") otherVariable <- tclVar("") otherEntry <- ttkentry(delimiterFrame, width="4", textvariable=otherVariable) radioButtons(optionsFrame, "decimal", buttons=c("period", "comma"), labels=.Facto_gettext(c("Period [.]", "Comma [,]")), title=.Facto_gettext("Decimal-Point Character")) missingVariable <- tclVar("NA") missingEntry <- ttkentry(optionsFrame, width="8", textvariable=missingVariable) onOK <- function(){ closeDialog() dsnameValue <- trim.blanks(tclvalue(dsname)) if (dsnameValue == ""){ errorCondition(recall=readDataSet, message=.Facto_gettext("You must enter a name for the data set.")) return() } if (!is.valid.name(dsnameValue)){ errorCondition(recall=readDataSet, message=paste('"', dsnameValue, '" ', .Facto_gettext("is not a valid name."), sep="")) return() } if (is.element(dsnameValue, listDataSets())) { if ("no" == tclvalue(checkReplace(dsnameValue, .Facto_gettext("Data set")))){ readDataSet() return() } } location <- tclvalue(locationVariable) file <- if (location == "clipboard") "clipboard" else if (location == "local") tclvalue(tkgetOpenFile(filetypes= .Facto_gettext('{"Text Files" {".txt" ".TXT" ".dat" ".DAT" ".csv" ".CSV"}} {"All Files" {"*"}}'))) else { initializeDialog(subdialog, title=.Facto_gettext("Internet URL")) onOKsub <- function(){ closeDialog(subdialog) } urlFrame <- tkframe(subdialog) urlVar <- tclVar("") url <- ttkentry(urlFrame, font=getRcmdr("logFont"), width="30", textvariable=urlVar) urlXscroll <- ttkscrollbar(urlFrame, orient="horizontal", command=function(...) tkxview(url, ...)) tkconfigure(url, xscrollcommand=function(...) tkset(urlXscroll, ...)) subOKCancelHelp() tkgrid(url, sticky="w") tkgrid(urlXscroll, sticky="ew") tkgrid(urlFrame, sticky="nw") tkgrid(subButtonsFrame, sticky="w") dialogSuffix(subdialog, rows=2, columns=1, focus=url, onOK=onOKsub) tclvalue(urlVar) } if (file == "") { if (getRcmdr("grab.focus")) tkgrab.release(top) tkdestroy(top) return() } head <- tclvalue(headerVariable) == "1" row <- tclvalue(nameRows) == "1" delimiter <- tclvalue(delimiterVariable) del <- if (delimiter == "whitespace") "" else if (delimiter == "commas") "," else if (delimiter == "tabs") "\\t" else tclvalue(otherVariable) miss <- tclvalue(missingVariable) dec <- if (tclvalue(decimalVariable) == "period") "." else "," if (row) command <- paste('read.table("', file,'", header=', head, ', sep="', del, '", na.strings="', miss, '", dec="', dec, '", row.names=1, strip.white=TRUE)', sep="") else command <- paste('read.table("', file,'", header=', head, ', sep="', del, '", na.strings="', miss, '", dec="', dec, '", strip.white=TRUE)', sep="") logger(paste(dsnameValue, " <- ", command, sep="")) result <- justDoIt(command) if (class(result)[1] != "try-error"){ gassign(dsnameValue, result) activeDataSet(dsnameValue) } tkfocus(CommanderWindow()) } OKCancelHelp(helpSubject="read.table") tkgrid(labelRcmdr(optionsFrame, text=.Facto_gettext("Enter name for data set:")), entryDsname, sticky="w") tkgrid(labelRcmdr(optionsFrame, text=.Facto_gettext("Variable names in file:")), headerCheckBox, sticky="w") tkgrid(labelRcmdr(optionsFrame, text=.Facto_gettext("Row names in the first columns:")), rowCheckBox, sticky="w") tkgrid(labelRcmdr(optionsFrame, text=.Facto_gettext("Missing data indicator:")), missingEntry, sticky="w") tkgrid(locationFrame, sticky="w") tkgrid(labelRcmdr(delimiterFrame, text=.Facto_gettext("Other")), otherButton, labelRcmdr(delimiterFrame, text=paste(" ",.Facto_gettext("Specify:"))), otherEntry, sticky="w") tkgrid(delimiterFrame, sticky="w", columnspan=2) tkgrid(decimalFrame, sticky="w") tkgrid(optionsFrame, sticky="w") tkgrid(buttonsFrame, sticky="w") dialogSuffix(rows=5, columns=1) }
.onAttach <- function(libname, pkgname){ if (!interactive()) return() Rcmdr <- options()$Rcmdr plugins <- Rcmdr$plugins if (!pkgname %in% plugins) { Rcmdr$plugins <- c(plugins, pkgname) options(Rcmdr=Rcmdr) if("package:Rcmdr" %in% search()) { if(!getRcmdr("autoRestart")) { closeCommander(ask=FALSE, ask.save=TRUE) Commander() } } else { Commander() } } } if (getRversion() >= '2.15.1') globalVariables(c('dataTab', 'optionsTab', 'tkselect', 'notebook', 'echocodigoVariable', 'creahtmlVariable', 'alternativaVariable', 'pruebaVariable', 'UMW', 'statisticsTab', 'alternativaFrame', 'pruebaFrame', 'opsFrame', 'descripVariable', 'graficoVariable', 'SCuadradosVariable', '.prueba.avarMR', '.baseDatosActiva', 'SCuadradosFrame', 'statsFrame', 'tablaVariable', 'subsetVariable', 'subsetFrame', 'tablaFrame', 'statistics2Tab', 'porcentajesVariable', 'frecEspVariable', 'jicuadradoVariable', 'jiComponentesVariable', 'phiPearsonVariable', 'contingPearsonVariable', 'sakodaVariable', 'chuprovVariable', 'VCramerVariable', 'yuleVariable', 'lambdaVariable', 'tauVariable', 'theilVariable', '.indices.bc', 'porcentajesFrame', 'esperadasFrame', 'errorpredFrame', 'CovVariable', 'pearsonVariable', 'spearmanVariable', 'kendallVariable', 'determVariable', '.indices.bn', 'cond1', 'cond2', 'cond3', 'cond4', 'gammaVariable', 'sommersVariable', 'wilsonVariable', '.indices.bo', 'dtm', 'identificaVariable', 'cajaFrame', 'cond', 'variable', 'escalaVariable', 'normalsupVariable', 'escalaFrame', 'histogramaFrame', 'oddsVariable', 'modaVariable', 'RVVariable', 'blauVariable', 'IVQVariable', 'teachmanVariable', '.indices.cat', 'numcatFrame', 'pruebaZ.apuntamiento', 'pruebaZ.forma', 'TW', 'adVariable', 'ksVariable', 'shapiroVariable', 'graficosVariable', '.groups', 'tab', '.norm.test', 'groupsFrame', '.TablaResumen', 'selectodasVariable', 'mediaVariable', 'medianaVariable', 'mediageomVariable', 'trimediaVariable', 'promcuarVariable', 'midRVariable', 'medrecVariable', 'varianciaVariable', 'dtVariable', 'CVVariable', 'dtgeomVariable', 'desvmedVariable', 'rangoVariable', 'IQRVariable', 'desvcuarVariable', 'madVariable', 'CVRVariable', 'ACentVariable', 'minVariable', 'maxVariable', 'Q1Variable', 'Q2Variable', 'Q3Variable', 'percentVariable', 'H1Variable', 'H3Variable', 'K2Variable', 'K3Variable', 'beta1Variable', 'gamma1Variable', 'beta2Variable', 'gamma2Variable', '.indices.num', 'tcFrame', 'tcRFrame', 'dispFrame', 'dispRFrame', 'statistics3Tab', 'posicFrame', 'posicRFrame', 'statistics4Tab', 'formaFrame', 'formaRFrame', '.indices.ord', 'ywttest')) catResumen <- function(x){ ni <- table(x,useNA='always') fi <- ni/sum(ni) Ni <- cumsum(ni) Fi <- cumsum(fi) res <- as.data.frame(matrix(round(cbind(ni,Ni,fi,Fi),2),nrow=nrow(ni), byrow=FALSE, dimnames=list(c(levels(x),'NAs'),c('ni','Ni','fi','Fi')))) res } resumen.categoricas <- function(){ defecto <- list(x.inicial=NULL,echo.inicial="0",creahtml.inicial="0", tab.inicial=0) dialog.valores <- getDialog("resumen.categoricas",defecto) initializeDialog(title=gettextRcmdr("Resumen distribucion de frecuencias"),use.tabs=TRUE) listaVar <- variableListBox(dataTab, Factors(), selectmode="multiple", title=gettextRcmdr("Variables (escoja una o mas)"), initialSelection=varPosn(dialog.valores$x.inicial,"factor")) checkBoxes(optionsTab,frame="opsFrame",boxes=c("echocodigo","creahtml"), initialValues=c(dialog.valores$echo.inicial,dialog.valores$creahtml.inicial), labels=gettextRcmdr(c("Mostrar en pantalla el codigo de R ejecutado ","Generar informe de resultados ")), title = gettextRcmdr("Opciones")) onOK <- function() { tab <- if(as.character(tkselect(notebook)) == dataTab$ID) 0 else 1 x <- getSelection(listaVar) .BaseDatosActiva <- ActiveDataSet() echocodigo <- tclvalue(echocodigoVariable) creahtml <- tclvalue(creahtmlVariable) putDialog("resumen.categoricas",list(x.inicial=x,echo.inicial=echocodigo,creahtml.inicial=creahtml,tab.inicial=tab)) if (length(x) == 0){ errorCondition(recall=resumen.categoricas, message=gettextRcmdr("Debe escoger una variable.")) return() } if (creahtml == 1) { if (!file.exists("Informe de Resultados.html")) .archivo <- HTMLInitFile(file.path(getwd()), "Informe de Resultados", BackGroundColor=" else .archivo <- file.path(getwd(), "Informe de Resultados.html") } for (variable in x) { instruccion1 <- paste(".TablaResumen <- catResumen(", .BaseDatosActiva, "$", variable, ")", sep="") if (echocodigo == 1) { logger(instruccion1) } justDoIt(instruccion1) doItAndPrint(paste(".TablaResumen if (creahtml == 1) { titulo <- paste("Distribucion frecuencias para variable ", variable,sep="") HTML(as.title(titulo),file=.archivo) HTML(.TablaResumen, file=.archivo) HTMLhr(file = .archivo) } } closeDialog() if (echocodigo == 1) logger("remove('.TablaResumen')") remove(.TablaResumen, envir=.GlobalEnv) tkfocus(CommanderWindow()) } OKCancelHelp(helpSubject="table",reset="resumen.categoricas",apply="resumen.categoricas") tkgrid(getFrame(listaVar), sticky="nw") tkgrid(opsFrame, sticky="w") dialogSuffix(use.tabs=TRUE,grid.buttons=TRUE,tab.names=c("Datos","Opciones")) } catindices <- function(vars,statistics,kVariable=NULL){ vars <- as.data.frame(vars) variables <- names(vars) .ni <- lapply(vars,table) odds <- function(x){ res <- round(x/(sum(x,na.rm=TRUE)-x), 2) res } moda <- function(vars){ .ni <- table(vars) if (is.numeric(vars)) res <- as.numeric(names(.ni[which(.ni==max(.ni,na.rm=TRUE))])) else res <- names(.ni)[which(.ni==max(.ni))] res } RV <- function(x){ res <- round(1 - max(x,na.rm=TRUE)/sum(x,na.rm=TRUE),2) res } blau <- function(x){ res <- round(1-sum(prop.table(x)^2),2) res } IVQ <- function(x,kval){ .ni <- lapply(x,table) res <- array() for (i in 1:length(x)){ resi <- round((1-sum(prop.table(.ni[[i]])^2))/((kval[i]-1)/kval[i]),2) res[i] <- resi } res } teachman <- function(x){ res <- round(-sum(prop.table(x)[prop.table(x)!=0]*log(prop.table(x)[prop.table(x)!=0])),2) res } res <- list() res[[1]] <- variables res[[2]] <- statistics i <- 2 if ("Odds" %in% statistics) { .odds <- lapply(.ni,odds) i <- i + 1 res[[i]] <- .odds } if ("Moda" %in% statistics) { .moda <- lapply(vars,moda) i <- i + 1 res[[i]] <- .moda } numfilas <- length(vars) numcolumnas <- sum(c("RV","Blau","IVQ","Teachman") %in% statistics) .tablaRes <- as.data.frame(matrix(nrow=numfilas,ncol=numcolumnas)) j <- 0 if ("RV" %in% statistics) { .RV <- unlist(lapply(.ni,RV),use.names=T) j <- j + 1 .tablaRes[,j]<-.RV } if ("Blau" %in% statistics) { .blau <- unlist(lapply(.ni,blau),use.names=T) j <- j + 1 .tablaRes[,j]<-.blau } if ("IVQ" %in% statistics) { if (length(kVariable)==1) { if (kVariable == "<auto>") kVariable <- unlist(lapply(.ni,length),use.names=F)} if (length(kVariable) > 1) { for (k in 1:length(vars)){ if (kVariable[k] < length(.ni[[k]])) kVariable[k] <- length(.ni[[k]]) if (is.na(kVariable[k]) | kVariable[k] < 1) kVariable[k] <- length(.ni[[k]]) if (kVariable[k] == "<auto>") kVariable[k] <- length(.ni[[i]]) } } .IVQ <- IVQ(vars,kVariable) j <- j + 1 .tablaRes[,j]<-.IVQ } if ("Teachman" %in% statistics) { .teachman <- unlist(lapply(.ni,teachman),use.names=T) j <- j + 1 .tablaRes[j]<-.teachman } if (numcolumnas > 0){ i <- i + 1 res[[i]] <- .tablaRes } class(res) <- "catindices" res } print.catindices <- function(x,...){ j<-3 if ("Odds" %in% x[[2]]) { for (i in 1:length(x[[1]])) {cat(paste(" names(x[[j]][i]) <- NULL print(x[[j]][i]) cat("\n\n") } j <- j + 1 } if ("Moda" %in% x[[2]]) { for (i in 1:length(x[[1]])) {cat(paste(" names(x[[j]][[i]]) <- NULL print(x[[j]][[i]]) cat("\n\n") } j <- j + 1 } if (sum(c("RV","Blau","IVQ","Teachman") %in% x[[2]]) > 0){ names(x[[j]]) <- NULL .tablaResultados <- as.data.frame(x[[j]]) rownames(.tablaResultados) <- x[[1]] colnames(.tablaResultados) <- c("RV","Blau","IVQ","Teachman")[c("RV","Blau","IVQ","Teachman") %in% x[[2]]] cat(" print(.tablaResultados) cat("\n\n") } invisible(x) } indices.categoricas <- function(){ defecto <- list(x.inicial=NULL,odds.inicial="0",moda.inicial="0",RV.inicial="0", blau.inicial="0",IVQ.inicial="0",teachman.inicial="0",k.inicial="<auto>", echo.inicial="0",creahtml.inicial="0",tab.inicial=0) dialog.valores <- getDialog("indices.categoricas",defecto) initializeDialog(title=gettextRcmdr("Otros indices para variables categoricas"),use.tabs=TRUE, tabs=c('dataTab','statisticsTab','optionsTab')) listaVar <- variableListBox(dataTab, Factors(), selectmode="multiple", title=gettextRcmdr("Variables (escoja una o mas)"), initialSelection=varPosn(dialog.valores$x.inicial,"factor")) onOK <- function(){ tab <- if(as.character(tkselect(notebook)) == dataTab$ID) 0 else 1 x <- getSelection(listaVar) if (length(x) == 0){ errorCondition(recall=indices.categoricas, message=gettextRcmdr("Debes escoger una variable.")) return() } .BaseDatosActiva <- ActiveDataSet() echocodigo <- tclvalue(echocodigoVariable) oddsval <- tclvalue(oddsVariable) modaval <- tclvalue(modaVariable) RVval <- tclvalue(RVVariable) blauval <- tclvalue(blauVariable) IVQval <- tclvalue(IVQVariable) teachmanval <- tclvalue(teachmanVariable) creahtml <- tclvalue(creahtmlVariable) selec <- as.numeric(modaval) + as.numeric(oddsval) + as.numeric(RVval) + as.numeric(blauval) + as.numeric(IVQval) + as.numeric(teachmanval) if (selec == 0){ errorCondition(recall=indices.categoricas, message=gettextRcmdr("Debe escoger algun indicador.")) return() } putDialog("indices.categoricas",list(x.inicial=x,odds.inicial=oddsval,moda.inicial=modaval, RV.inicial=RVval,blau.inicial=blauval,IVQ.inicial=IVQval, k.inicial=tclvalue(kVariable),teachman.inicial=teachmanval, echo.inicial=echocodigo,creahtml.inicial=creahtml,tab.inicial=tab)) if (IVQval == 1) { kval <- vector() opts <- options(warn=-1) options(opts) if (tclvalue(kVariable) != gettextRcmdr("<auto>")) { k <- c(gsub(" ", ",",gsub(", ", ",",tclvalue(kVariable)))) k <- unlist(strsplit(k,",")) if (length(k) < length(x)) { tclvalue(kVariable) <- gettextRcmdr("<auto>") kval <- as.character(tclvalue(kVariable)) Message(message=gettextRcmdr("Vector de categorias, invalido se utilizara '<auto>'."), type="warning") } else { j <- 0 for (variable in x){ j <- j + 1 kval[j] <- as.numeric(k[j]) if (is.na(kval[j]) || kval[j] < 1) { errorCondition(recall=indices.categoricas, message=gettextRcmdr ("El numero de categorias k debe ser un numero positivo")) return() } } kval <- paste("c(",paste(kval,collapse=",",sep=''),")",sep='') } } else kval <- tclvalue(kVariable) } vars <- if (length(x) == 1) paste('"', x, '"', sep="") else paste("c(", paste('"', x, '"', collapse=", ", sep=""), ")", sep="") if (length(x) == 1) variables <- paste(.BaseDatosActiva, "[", vars, "]", sep="") else variables <- paste(.BaseDatosActiva, "[,", vars, "]", sep="") stats <- paste("c(", paste(c('"Odds"', '"Moda"', '"RV"', '"Blau"', '"IVQ"', '"Teachman"') [c(oddsval, modaval, RVval, blauval, IVQval , teachmanval) == 1], collapse=", "), ")", sep="") if (IVQval == 1) { if (kval!="<auto>") instruccion1 <- paste(".indices.cat <- catindices(vars=",variables, ", statistics=", stats,", kVariable=", kval, ")", sep="") else instruccion1 <- paste(".indices.cat <- catindices(vars=",variables, ", statistics=", stats,", kVariable='", kval, "')", sep="") } else instruccion1 <- paste(".indices.cat <- catindices(vars=",variables, ", statistics=", stats,")", sep="") justDoIt(instruccion1) if (echocodigo == 1) { logger(instruccion1) } doItAndPrint(".indices.cat if (creahtml == 1) { if (!file.exists("Informe de Resultados.html")) .archivo <- HTMLInitFile(file.path(getwd()), "Informe de Resultados", BackGroundColor=" else .archivo <- file.path(getwd(), "Informe de Resultados.html") titulo <- "Descriptivos para variables categoricas" HTML(as.title(titulo),file=.archivo) i <- 1 while (i <= length(x)){ j <- 3 if (oddsval ==1){ HTML(paste("Odds para:",.indices.cat[[1]][i]), file=.archivo) .odds <- as.data.frame(.indices.cat[[j]][i])[2] colnames(.odds) <- 'Odds' rownames(.odds) <- unlist(as.data.frame(.indices.cat[[j]][i])[1],use.names=F) HTML(.odds, file=.archivo) j <- j + 1 } if (modaval ==1){ HTML(paste("Moda para:",.indices.cat[[1]][i]), file=.archivo) .moda <- as.data.frame(.indices.cat[[j]][i])[1] colnames(.moda) <- 'Moda' rownames(.moda) <- NULL HTML(.moda, file=.archivo) j <- j + 1 } i <- i +1 } selec <- sum(as.numeric(RVval) + as.numeric(blauval) + as.numeric(IVQval) + as.numeric(teachmanval)) if ( selec>0 ){ .TablaRes <- as.data.frame(.indices.cat[[5]]) rownames(.TablaRes) <- .indices.cat[[1]] colnames(.TablaRes) <- c("RV","Blau","IVQ","Teachman")[c("RV","Blau","IVQ","Teachman") %in% .indices.cat[[2]]] HTML("Otros indicadores: ", file=.archivo) HTML(.TablaRes, file=.archivo) HTMLhr(file = .archivo) } } remove(.indices.cat, envir=.GlobalEnv) closeDialog() if (echocodigo == 1) logger("remove(.indices.cat)") tkfocus(CommanderWindow()) } OKCancelHelp(helpSubject="RcmdrPlugin.EACSPIR",reset="indices.categoricas",apply="indices.categoricas") checkBoxes(statisticsTab,frame="numcatFrame",boxes=c("odds","moda","RV","blau","IVQ","teachman"), initialValues=c(dialog.valores$odds.inicial,dialog.valores$moda.inicial, dialog.valores$RV.inicial,dialog.valores$blau.inicial, dialog.valores$IVQ.inicial,dialog.valores$teachman.inicial), labels=gettextRcmdr(c("Odds ","Moda ","Razon de Variacion ","Indice de Diversidad de Blau ", "Indice de Variacion Cualitativa","Indice de Diversidad de Teachman ")), title = gettextRcmdr("Indices")) checkBoxes(optionsTab,frame="opsFrame",boxes=c("echocodigo","creahtml"), initialValues=c(dialog.valores$echo.inicial,dialog.valores$creahtml.inicial), labels=gettextRcmdr(c("Mostrar en pantalla el codigo de R ejecutado ","Generar informe de resultados ")), title = gettextRcmdr("Opciones")) rightFrame <- tkframe(statisticsTab) kVariable <- tclVar(dialog.valores$k.inicial) kField <- ttkentry(rightFrame, width="8", textvariable=kVariable) tkgrid(getFrame(listaVar), sticky="nw") tkgrid(labelRcmdr(rightFrame,text=" ")) tkgrid(labelRcmdr(rightFrame,text=" ")) tkgrid(labelRcmdr(rightFrame,text=" ")) tkgrid(labelRcmdr(rightFrame,text=" ")) tkgrid(labelRcmdr(rightFrame,text=" ")) tkgrid(labelRcmdr(rightFrame,text=gettextRcmdr("Categorias: k ="),fg=getRcmdr("title.color"),font="RcmdrTitleFont"), kField,sticky="w") tkgrid(numcatFrame, labelRcmdr(statisticsTab,text=" "), rightFrame, sticky="nw") tkgrid(opsFrame, sticky="w") dialogSuffix(use.tabs=TRUE,grid.buttons=TRUE,tabs=c('dataTab','statisticsTab','optionsTab'), tab.names=c("Datos","Estadisticos","Opciones")) } pareto <- function(x,tablaVar){ x <- as.data.frame(x) variable <- names(x) if (tablaVar == "ni") .tabla <- table(x) else .tabla <- table(x)/sum(table(x)) .tabla <- .tabla[order(-.tabla)] titulo <- paste('Diagrama de Pareto para ', variable, sep="") tituloy <- if (tablaVar == "ni") "Frecuencias Absolutas" else "Frecuencias Relativas" par(mar=c(5,4,4,4)) .x <- barplot(.tabla, main=titulo,ylab=tituloy, ylim=c(0,sum(.tabla)*1.05),col=heat.colors(length(.tabla))) lines(.x[1:length(.tabla)],cumsum(.tabla),type='b') box() axis(4,at=seq(0,max(cumsum(.tabla)),length=5), labels=paste(seq(0,1,length=5)*100,'%',sep='')) mtext('Porcentaje Acumulado', 4, line=2.5, las=3) } grafico.Pareto <- function(){ defecto <- list(x.inicial=NULL,tabla.inicial="ni",echo.inicial="0",creahtml.inicial="0",tab.inicial=0) dialog.valores <- getDialog("grafico.Pareto",defecto) initializeDialog(title=gettextRcmdr("Diagrama de Pareto"),use.tabs=TRUE) listaVar <- variableListBox(dataTab, Factors(), title=gettextRcmdr("Variables (escoja una)"), initialSelection=varPosn(dialog.valores$x.inicial,"factor")) checkBoxes(optionsTab,frame="opsFrame",boxes=c("echocodigo","creahtml"), initialValues=c(dialog.valores$echo.inicial,dialog.valores$creahtml.inicial), labels=gettextRcmdr(c("Mostrar en pantalla el codigo de R ejecutado ","Generar informe de resultados ")), title = gettextRcmdr("Opciones")) onOK <- function() { tab <- if(as.character(tkselect(notebook)) == dataTab$ID) 0 else 1 x <- getSelection(listaVar) .BaseDatosActiva <- ActiveDataSet() echocodigo <- tclvalue(echocodigoVariable) creahtml <- tclvalue(creahtmlVariable) tabVariable <- as.character(tclvalue(tablaVariable)) putDialog("grafico.Pareto",list(x.inicial=x,tabla.inicial=tabVariable, echo.inicial=echocodigo,creahtml.inicial=creahtml,tab.inicial=tab)) if (length(x) == 0){ errorCondition(recall=grafico.Pareto, message=gettextRcmdr("Debe escoger una variable.")) return() } vars <- paste('"', x, '"', sep="") variables <- paste(.BaseDatosActiva, "[,", vars, "]", sep="") instruccion1 <- paste("pareto(x=", .BaseDatosActiva, "[", vars,"], tablaVar='",tabVariable, "')", sep="") if (echocodigo == 1) { logger(instruccion1) } justDoIt(instruccion1) if (creahtml == 1) { if (!file.exists("Informe de Resultados.html")) .archivo <- HTMLInitFile(file.path(getwd()), "Informe de Resultados", BackGroundColor=" else .archivo <- file.path(getwd(), "Informe de Resultados.html") titulo <- paste("Diagrama de Pareto para variable ",variable,sep="") HTML(as.title(titulo),file=.archivo) nombre.archivo <- paste("ParetoR",gsub(":","",substr(Sys.time(),12,19)), ".jpg",sep="") dev.print(jpeg, filename=paste(getwd(),"/",nombre.archivo,sep=""), width=500, height=500) HTMLInsertGraph(nombre.archivo,file=.archivo,append=TRUE) HTMLhr(file = .archivo) } closeDialog() tkfocus(CommanderWindow()) } OKCancelHelp(helpSubject="table",reset="grafico.Pareto",apply="grafico.Pareto") tkgrid(getFrame(listaVar), sticky="nw") radioButtons(dataTab,name = "tabla", buttons = c("niButton","fiButton"), values = c("ni","fi"), labels = gettextRcmdr(c("Frecuencias Absolutas", "Frecuencias Relativas")), initialValue = dialog.valores$tabla.inicial, title = gettextRcmdr("Tablas basadas en:")) tkgrid(tablaFrame, sticky="w") tkgrid(opsFrame, sticky="w") dialogSuffix(use.tabs=TRUE,grid.buttons=TRUE,tab.names=c("Datos","Opciones")) } ordindices <- function(vars,statistics,rec=NULL,propdat=NULL,percentil=NULL){ vars <- as.data.frame(vars) variables <- names(vars) mediana <- function(x){ res <- median(as.numeric(x),na.rm=TRUE) res } moda <- function(x){ .ni <- table(x) if (is.numeric(x)) res <- as.numeric(names(.ni[which(.ni==max(.ni,na.rm=TRUE))])) else res <- names(.ni)[which(.ni==max(.ni))] res } trimedia <- function(x){ .Finf <- fivenum(as.numeric(x))[2] .Md <- fivenum(as.numeric(x))[3] .Fsup <- fivenum(as.numeric(x))[4] res <- round((.Finf+2*.Md+.Fsup)/4,2) res } promcuar <- function(x){ .Q1 <- quantile(as.numeric(x),na.rm=TRUE)[2] .Q3 <- quantile(as.numeric(x),na.rm=TRUE)[4] res <- round((.Q1+.Q3)/2,2) names(res) <- NULL res } midR <- function(x){ .min <- quantile(as.numeric(x),na.rm=TRUE)[1] .max <- quantile(as.numeric(x),na.rm=TRUE)[5] res <- round((.min+.max)/2,2) names(res) <- NULL res } medrec <- function(x,rec){ res <- round(mean(as.numeric(x),trim=rec,na.rm=TRUE),2) res } rango <- function(x){ .min <- quantile(as.numeric(x),na.rm=TRUE)[1] .max <- quantile(as.numeric(x),na.rm=TRUE)[5] res <- round(.max-.min,2) names(res) <- NULL res } iqr <- function(x){ .Q1 <- quantile(as.numeric(x),na.rm=TRUE)[2] .Q3 <- quantile(as.numeric(x),na.rm=TRUE)[4] res <- round(.Q3-.Q1,2) names(res) <- NULL res } mad <- function(x){ .mediana <- median(as.numeric(x),na.rm=TRUE) res <- round(median(abs(as.numeric(x)-.mediana),na.rm=TRUE),2) res } cvr <- function(x){ .Finf <- fivenum(as.numeric(x))[2] .Fsup <- fivenum(as.numeric(x))[4] res <- round((.Fsup-.Finf)/(.Finf+.Fsup), 2) res } desvcuar <- function(x){ .Q1 <- quantile(as.numeric(x),na.rm=TRUE)[2] .Q3 <- quantile(as.numeric(x),na.rm=TRUE)[4] res <- round((.Q3-.Q1)/2,2) names(res) <- NULL res } acent <- function(x,propdat){ .ACinf <- quantile(as.numeric(x),probs=(1-propdat)/2,na.rm=TRUE) .ACsup <- quantile(as.numeric(x),probs=1-(1-propdat)/2,na.rm=TRUE) res <- round(.ACsup-.ACinf,2) names(res) <- NULL res } q1 <- function(x){ res <- round(quantile(as.numeric(x),na.rm=TRUE)[2],2) names(res) <- NULL res } q2 <- function(x){ res <- round(quantile(as.numeric(x),na.rm=TRUE)[3],2) names(res) <- NULL res } q3 <- function(x){ res <- round(quantile(as.numeric(x),na.rm=TRUE)[4],2) names(res) <- NULL res } pct <- function(x,percentil){ res <- round(quantile(as.numeric(x),probs=percentil,na.rm=TRUE),2) names(res) <- NULL res } h1 <- function(x) { .Finf <- fivenum(as.numeric(x))[2] .Md <- fivenum(as.numeric(x))[3] .Fsup <- fivenum(as.numeric(x))[4] res <- round((.Finf+.Fsup-2*.Md)/(2*.Md),2) res } h3 <- function(x) { .AC90 <- quantile(as.numeric(x),probs=0.9,na.rm=TRUE) .AC10 <- quantile(as.numeric(x),probs=0.1,na.rm=TRUE) .Md <- fivenum(as.numeric(x))[3] res <- round((.AC90+.AC10-2*.Md)/(2*.Md),2) names(res) <- NULL res } k2 <- function(x){ .AC90 <- quantile(as.numeric(x),probs=0.9,na.rm=TRUE) .AC10 <- quantile(as.numeric(x),probs=0.1,na.rm=TRUE) .Q1 <- quantile(as.numeric(x),na.rm=TRUE)[2] .Q3 <- quantile(as.numeric(x),na.rm=TRUE)[4] res <- round((.AC90-.AC10)/(1.9*(.Q3-.Q1)),2) names(res) <- NULL res } k3 <- function(x){ .Einf <- quantile(as.numeric(x),probs=0.125,na.rm=TRUE) .Esup <- quantile(as.numeric(x),probs=0.875,na.rm=TRUE) .Finf <- fivenum(as.numeric(x))[2] .Fsup <- fivenum(as.numeric(x))[4] res <- round((.Esup-.Einf)/(1.7*(.Fsup-.Finf)),2) names(res) <- NULL res } res <- list() res[[1]] <- variables res[[2]] <- statistics res[[3]] <- rec res[[4]] <- propdat res[[5]] <- percentil i <- 5 numfilas <- length(vars) TCcol <- sum(c("Mediana","Moda","Trimedia","PromCuar","midR","MediaRec") %in% statistics) dispcol <- sum(c("Rango", "IQR", "DesvCuar", "MAD", "CVR", "ACent") %in% statistics) posiccol <- sum(c("Min", "Max", "Q1", "Q2", "Q3") %in% statistics) + ("Pct" %in% statistics)*length(percentil) formacol <- sum(c("H1", "H3", "K2", "K3") %in% statistics) .tablaTC <- as.data.frame(matrix(nrow=numfilas,ncol=TCcol)) .tabladisp <- as.data.frame(matrix(nrow=numfilas,ncol=dispcol)) .tablaposic <- as.data.frame(matrix(nrow=numfilas,ncol=posiccol)) .tablaforma <- as.data.frame(matrix(nrow=numfilas,ncol=formacol)) if (TCcol > 0){ j <- 0 if ("Mediana" %in% statistics) { .mediana <- unlist(lapply(vars,mediana),use.names=F) j <- j + 1 .tablaTC[,j]<-.mediana } if ("Moda" %in% statistics) { .moda <- lapply(vars,moda) for (variable in length(.moda)) { if (length(.moda[[variable]]) > 1) { Message(message=gettextRcmdr(paste("Variable ",variables[variable]," tiene mas de una moda: ", "En documento HTML se muestra un solo valor.", sep="")), type="warning") } } if (length(.moda[which(lapply(.moda,length)>1,useNames=FALSE)])>0) .moda[which(lapply(.moda,length)>1,useNames=FALSE)]<-.moda[[which(lapply(.moda,length)>1,useNames=FALSE)]][1] .moda <- unlist(.moda,use.names=F) j <- j + 1 .tablaTC[,j] <- .moda } if ("Trimedia" %in% statistics) { .trimedia <- unlist(lapply(vars,trimedia),use.names=F) j <- j + 1 .tablaTC[,j]<-.trimedia } if ("PromCuar" %in% statistics) { .promcuar <- unlist(lapply(vars,promcuar),use.names=F) j <- j + 1 .tablaTC[,j]<-.promcuar } if ("midR" %in% statistics) { .midr <- unlist(lapply(vars,midR),use.names=F) j <- j + 1 .tablaTC[,j]<-.midr } if ("MediaRec" %in% statistics) { .mediarec <- unlist(lapply(vars,medrec,rec),use.names=F) j <- j + 1 .tablaTC[,j]<-.mediarec } i <- i + 1 res[[i]] <- .tablaTC } if (dispcol > 0){ j <- 0 if ("Rango" %in% statistics) { .rango <- unlist(lapply(vars,rango),use.names=F) j <- j + 1 .tabladisp[,j]<-.rango } if ("IQR" %in% statistics) { .iqr <- unlist(lapply(vars,iqr),use.names=F) j <- j + 1 .tabladisp[,j]<-.iqr } if ("DesvCuar" %in% statistics) { .dq <- unlist(lapply(vars,desvcuar),use.names=F) j <- j + 1 .tabladisp[,j]<-.dq } if ("MAD" %in% statistics) { .mad <- unlist(lapply(vars,mad),use.names=F) j <- j + 1 .tabladisp[,j]<-.mad } if ("CVR" %in% statistics) { .cvr <- unlist(lapply(vars,cvr),use.names=F) j <- j + 1 .tabladisp[,j]<-.cvr } if ("ACent" %in% statistics) { .acent <- unlist(lapply(vars,acent,propdat),use.names=F) j <- j + 1 .tabladisp[,j]<-.acent } i <- i + 1 res[[i]] <- .tabladisp } if (posiccol > 0){ j <- 0 if ("Min" %in% statistics) { .min <- unlist(lapply(lapply(vars,as.numeric),min,na.rm=TRUE),use.names=F) j <- j + 1 .tablaposic[,j]<-.min } if ("Max" %in% statistics) { .max <- unlist(lapply(lapply(vars,as.numeric),max,na.rm=TRUE),use.names=F) j <- j + 1 .tablaposic[,j]<-.max } if ("Q1" %in% statistics) { .q1 <- unlist(lapply(vars,q1),use.names=F) j <- j + 1 .tablaposic[,j]<-.q1 } if ("Q2" %in% statistics) { .q2 <- unlist(lapply(vars,q2),use.names=F) j <- j + 1 .tablaposic[,j]<-.q2 } if ("Q3" %in% statistics) { .q3 <- unlist(lapply(vars,q3),use.names=F) j <- j + 1 .tablaposic[,j]<-.q3 } if ("Pct" %in% statistics) { .pct <- matrix(unlist(lapply(vars,pct,percentil),use.names=F), nrow=numfilas,ncol=length(percentil),byrow=T) .tablaposic[,(j+1):(j+length(percentil))]<-.pct } i <- i + 1 res[[i]] <- .tablaposic } if (formacol > 0){ j <- 0 if ("H1" %in% statistics) { .h1 <- unlist(lapply(vars,h1),use.names=F) j <- j + 1 .tablaforma[,j]<-.h1 } if ("H3" %in% statistics) { .h3 <- unlist(lapply(vars,h3),use.names=F) j <- j + 1 .tablaforma[,j]<-.h3 } if ("K2" %in% statistics) { .k2 <- unlist(lapply(vars,k2),use.names=F) j <- j + 1 .tablaforma[,j]<-.k2 } if ("K3" %in% statistics) { .k3 <- unlist(lapply(vars,k3),use.names=F) j <- j + 1 .tablaforma[,j]<-.k3 } i <- i + 1 res[[i]] <- .tablaforma } class(res) <- "ordindices" res } print.ordindices <- function(x,...){ j<-6 if (sum(c("Mediana","Moda","Trimedia","PromCuar","midR","MediaRec") %in% x[[2]]) > 0){ .tablaTC <- as.data.frame(x[[j]]) rownames(.tablaTC) <- x[[1]] colnames(.tablaTC) <- c("Mediana","Moda","Trimedia","PromCuar","midR", paste("MediaRec(",x[[3]]*100,"%)",sep=''))[c("Mediana", "Moda","Trimedia","PromCuar","midR","MediaRec") %in% x[[2]]] cat(" print(.tablaTC) cat("\n\n") j <- j+1 } if (sum(c("Rango", "IQR", "DesvCuar", "MAD", "CVR", "ACent") %in% x[[2]]) > 0){ .tabladisp <- as.data.frame(x[[j]]) rownames(.tabladisp) <- x[[1]] colnames(.tabladisp) <- c("Rango", "IQR", "DesvCuar", "MAD", "CVR", paste("ACent(",x[[4]]*100,"%)",sep=''))[c("Rango", "IQR","DesvCuar", "MAD", "CVR", "ACent") %in% x[[2]]] cat(" print(.tabladisp) cat("\n\n") j <- j+1 } if (sum(c("Min", "Max", "Q1", "Q2", "Q3") %in% x[[2]]) + ("Pct" %in% x[[2]])*length(x[[5]]) > 0){ .tablaposic <- as.data.frame(x[[j]]) rownames(.tablaposic) <- x[[1]] colnames(.tablaposic) <- c("Min", "Max", "Q1", "Q2", "Q3", paste(if (!is.null(x[[5]])) x[[5]]*100 else "Pct",'%',sep=''))[c("Min", "Max", "Q1", "Q2", "Q3",rep("Pct",if (!is.null(x[[5]])) length(x[[5]]) else 1)) %in% x[[2]]] cat(" print(.tablaposic) cat("\n\n") j <- j+1 } if (sum(c("H1", "H3", "K2", "K3") %in% x[[2]]) > 0){ .tablaforma <- as.data.frame(x[[j]]) rownames(.tablaforma) <- x[[1]] colnames(.tablaforma) <- c("H1", "H3", "K2", "K3")[c("H1", "H3", "K2", "K3") %in% x[[2]]] cat(" print(.tablaforma) cat("\n\n") j <- j+1 } invisible(x) } resumen.ordinales <- function(){ defecto <- list(x.inicial=NULL,mediana.inicial="0",moda.inicial="0",trimedia.inicial="0", promcuar.inicial="0",midR.inicial="0",medrec.inicial="0",trim.inicial="0.05", rango.inicial="0",IQR.inicial="0",desvcuar.inicial="0",mad.inicial="0", CVR.inicial="0",ACent.inicial="0",AC.inicial="0.9",min.inicial="0", max.inicial="0",Q1.inicial="0",Q2.inicial="0",Q3.inicial="0", percent.inicial="0",percentil.inicial="0, .25, .5, .75, 1", H1.inicial="0",H3.inicial="0",K2.inicial="0",K3.inicial="0", echo.inicial="0",creahtml.inicial="0",selectodas.inicial="0",tab.inicial=0) dialog.valores <- getDialog("resumen.ordinales",defecto) initializeDialog(title=gettextRcmdr("Indices para variables ordinales"),use.tabs=TRUE, tabs=c('dataTab','statisticsTab','statistics2Tab','statistics3Tab','statistics4Tab','optionsTab')) listaVar <- variableListBox(dataTab, Factors(), selectmode="multiple", title=gettextRcmdr("Variables (escoja una o mas)"), initialSelection=varPosn(dialog.valores$x.inicial,"factor")) onOK <- function(){ tab <- if(as.character(tkselect(notebook)) == dataTab$ID) 0 else 1 x <- getSelection(listaVar) if (length(x) == 0){ errorCondition(recall=resumen.ordinales, message=gettextRcmdr("Debes escoger una variable.")) return() } for (variable in x) { justDoIt(paste("cond <- !is.ordered(",paste(ActiveDataSet(),"$",variable,sep=""),")",sep="")) if (cond){ errorCondition(recall=resumen.ordinales, message=gettextRcmdr(paste("Variable ",variable, " no es ordinal.",sep=''))) return() } remove("cond", envir=.GlobalEnv) } .BaseDatosActiva <- ActiveDataSet() echocodigo <- tclvalue(echocodigoVariable) creahtml <- tclvalue(creahtmlVariable) selectodas <- tclvalue(selectodasVariable) if (selectodas == 1) { medianaval = modaval = trimediaval = promcuarval = midRval = medrecval = rangoval = IQRval = desvcuarval = madval = CVRval = ACentval = minval = maxval = Q1val = Q2val = Q3val = percentval = H1val = H3val = K2val = K3val = TRUE } else { medianaval <- tclvalue(medianaVariable) modaval <- tclvalue(modaVariable) trimediaval <- tclvalue(trimediaVariable) promcuarval <- tclvalue(promcuarVariable) midRval <- tclvalue(midRVariable) medrecval <- tclvalue(medrecVariable) rangoval <- tclvalue(rangoVariable) IQRval <- tclvalue(IQRVariable) desvcuarval <- tclvalue(desvcuarVariable) madval <- tclvalue(madVariable) CVRval <- tclvalue(CVRVariable) ACentval <- tclvalue(ACentVariable) minval <- tclvalue(minVariable) maxval <- tclvalue(maxVariable) Q1val <- tclvalue(Q1Variable) Q2val <- tclvalue(Q2Variable) Q3val <- tclvalue(Q3Variable) percentval <- tclvalue(percentVariable) H1val <- tclvalue(H1Variable) H3val <- tclvalue(H3Variable) K2val <- tclvalue(K2Variable) K3val <- tclvalue(K3Variable) } selec <- as.numeric(medianaval) + as.numeric(modaval) + as.numeric(trimediaval) + as.numeric(promcuarval) + as.numeric(midRval) + as.numeric(medrecval) selec2 <- as.numeric(rangoval) + as.numeric(IQRval) + as.numeric(desvcuarval) + as.numeric(madval) + as.numeric(CVRval) + as.numeric(ACentval) selec3 <- as.numeric(minval) + as.numeric(maxval) + as.numeric(Q1val) + as.numeric(Q2val) + as.numeric(Q3val) + as.numeric(percentval) selec4 <- as.numeric(H1val) + as.numeric(H3val) + as.numeric(K2val) + as.numeric(K3val) seleccion <- selec + selec2 + selec3 + selec4 if (seleccion == 0){ errorCondition(recall=resumen.ordinales, message=gettextRcmdr("Debes escoger algun indicador.")) return() } putDialog("resumen.ordinales",list(x.inicial=x,mediana.inicial=medianaval,moda.inicial=modaval, trimedia.inicial=trimediaval,promcuar.inicial=promcuarval,midR.inicial=midRval, medrec.inicial=medrecval,trim.inicial=tclvalue(trimVariable), rango.inicial=rangoval,IQR.inicial=IQRval,desvcuar.inicial=desvcuarval, mad.inicial=madval,CVR.inicial=CVRval,ACent.inicial=ACentval, AC.inicial=tclvalue(ACVariable),min.inicial=minval,max.inicial=maxval, Q1.inicial=Q1val,Q2.inicial=Q2val,Q3.inicial=Q3val,percent.inicial=percentval, percentil.inicial=tclvalue(percentilVariable),H1.inicial=H1val, H3.inicial=H3val,K2.inicial=K2val,K3.inicial=K3val, selectodas.inicial=selectodas,echo.inicial=echocodigo, creahtml.inicial=creahtml,tab.inicial=tab)) if (percentval == 1) { pct <- c(gsub(" ", ",",gsub(", ", ",",tclvalue(percentilVariable)))) pct1 <- as.numeric(unlist(strsplit(pct,","))) if ( is.na(pct1) || (sum(pct1<0.0)>0) || (sum(pct1>1.0)>0) || (sum(!is.numeric(pct1))>0) ) { pct <- paste(seq(0.,1.,.25),collapse=",") Message(message=gettextRcmdr("Vector de percentiles invalido. Se utilizara vector por defecto."), type="warning") } } else pct <- NULL if (medrecval == 1) { rec <- as.numeric(tclvalue(trimVariable)) if ( rec < .0 || rec > .5 || !is.numeric(rec) ) { rec <- 0.05 Message(message=gettextRcmdr("Proporcion de recorte invalida se utilizara valor por defecto."), type="warning") } } else rec <- NULL if (ACentval == 1) { propdat <- as.numeric(tclvalue(ACVariable)) if ( propdat < .0 || propdat > 1. || !is.numeric(propdat) ) { prop.dat <- 0.9 Message(message=gettextRcmdr("Proporcion de datos invalida se utilizara valor por defecto."), type="warning") } } else propdat <- NULL vars <- if (length(x) == 1) paste('"', x, '"', sep="") else paste("c(", paste('"', x, '"', collapse=", ", sep=""), ")", sep="") if (length(x) == 1) variables <- paste(.BaseDatosActiva, "[", vars, "]", sep="") else variables <- paste(.BaseDatosActiva, "[,", vars, "]", sep="") stats <- paste("c(", paste(c('"Mediana"', '"Moda"', '"Trimedia"', '"PromCuar"', '"midR"', '"MediaRec"', '"Rango"', '"IQR"', '"DesvCuar"', '"MAD"', '"CVR"', '"ACent"', '"Min"', '"Max"', '"Q1"', '"Q2"', '"Q3"', '"Pct"', '"H1"', '"H3"', '"K2"', '"K3"') [c(medianaval, modaval, trimediaval, promcuarval, midRval, medrecval, rangoval, IQRval, desvcuarval, madval, CVRval, ACentval, minval, maxval, Q1val, Q2val, Q3val, percentval, H1val, H3val, K2val, K3val) == 1], collapse=", "), ")", sep="") if (percentval ==1) instruccion1 <- paste(".indices.ord <- ordindices(vars=",variables, ", statistics=", stats, if (!is.null(rec)){paste(",rec=",rec)}, if(!is.null(propdat)){paste(",propdat=",propdat)},",percentil=c(",pct,")",")", sep="") else instruccion1 <- paste(".indices.ord <- ordindices(vars=",variables, ", statistics=", stats, if (!is.null(rec)){paste(",rec=",rec)}, if(!is.null(propdat)){paste(",propdat=",propdat)},")", sep="") justDoIt(instruccion1) if (echocodigo == 1) { logger(instruccion1) } doItAndPrint(".indices.ord if (creahtml == 1) { if (!file.exists("Informe de Resultados.html")) .archivo <- HTMLInitFile(file.path(getwd()), "Informe de Resultados", BackGroundColor=" else .archivo <- file.path(getwd(), "Informe de Resultados.html") titulo <- "Indicadores descriptivos para variables ordinales" HTML(as.title(titulo),file=.archivo) j <- 6 if ( selec>0 ){ .TablaRes <- as.data.frame(.indices.ord[[j]]) rownames(.TablaRes) <- .indices.ord[[1]] colnames(.TablaRes) <- c("Mediana","Moda","Trimedia","PromCuar","midR", paste("MediaRec(",.indices.ord[[3]]*100,"%)",sep=''))[c("Mediana", "Moda", "Trimedia", "PromCuar", "midR", "MediaRec") %in% .indices.ord[[2]]] HTML("Indicadores de tendencia central: ", file=.archivo) HTML(.TablaRes, file=.archivo) HTMLhr(file = .archivo) j <- j+1 } if ( selec2>0 ){ .TablaRes <- as.data.frame(.indices.ord[[j]]) rownames(.TablaRes) <- .indices.ord[[1]] colnames(.TablaRes) <- c("Rango", "IQR", "DesvCuar", "MAD", "CVR", paste("ACent(",.indices.ord[[4]]*100,"%)",sep=''))[c("Rango", "IQR", "DesvCuar", "MAD", "CVR", "ACent") %in% .indices.ord[[2]]] HTML("Indicadores de dispersion: ", file=.archivo) HTML(.TablaRes, file=.archivo) HTMLhr(file = .archivo) j <- j+1 } if ( selec3>0 ){ .TablaRes <- as.data.frame(.indices.ord[[j]]) rownames(.TablaRes) <- .indices.ord[[1]] colnames(.TablaRes) <- c("Min", "Max", "Q1", "Q2", "Q3", paste(.indices.ord[[5]]*100,'%',sep=''))[c("Min", "Max", "Q1", "Q2", "Q3",rep("Pct",length(.indices.ord[[5]]))) %in% .indices.ord[[2]]] HTML("Indicadores de posicion: ", file=.archivo) HTML(.TablaRes, file=.archivo) HTMLhr(file = .archivo) j <- j+1 } if ( selec4>0 ){ .TablaRes <- as.data.frame(.indices.ord[[j]]) rownames(.TablaRes) <- .indices.ord[[1]] colnames(.TablaRes) <- c("H1", "H3", "K2", "K3")[c("H1", "H3", "K2", "K3") %in% .indices.ord[[2]]] HTML("Indicadores de forma: ", file=.archivo) HTML(.TablaRes, file=.archivo) HTMLhr(file = .archivo) j <- j+1 } } remove(.indices.ord, envir=.GlobalEnv) closeDialog() if (echocodigo == 1) logger("remove(.indices.ord)") tkfocus(CommanderWindow()) } OKCancelHelp(helpSubject="RcmdrPlugin.EACSPIR",reset="resumen.ordinales",apply="resumen.ordinales") tkgrid(getFrame(listaVar), sticky="nw") checkBoxes(statisticsTab,frame="tcFrame",boxes=c("mediana","moda","trimedia"), initialValues=c(dialog.valores$mediana.inicial,dialog.valores$moda.inicial, dialog.valores$trimedia.inicial), labels=gettextRcmdr(c("Mediana ","Moda ","Trimedia ")), title = gettextRcmdr("Indices de tendencia central")) checkBoxes(statisticsTab,frame="tcRFrame",boxes=c("promcuar","midR","medrec"), initialValues=c(dialog.valores$promcuar.inicial, dialog.valores$midR.inicial,dialog.valores$medrec.inicial), labels=gettextRcmdr(c("Promedio de cuartiles ","Rango medio ","Media Recortada ")), title = gettextRcmdr(" ")) trimFrame <- tkframe(statisticsTab) trimVariable <- tclVar(dialog.valores$trim.inicial) trimField <- ttkentry(trimFrame, width="8", textvariable=trimVariable) tkgrid(labelRcmdr(trimFrame,text=" ")) tkgrid(labelRcmdr(trimFrame,text=" ")) tkgrid(labelRcmdr(trimFrame,text=" ")) tkgrid(labelRcmdr(trimFrame,text=gettextRcmdr("Proporcion datos recortados = "), fg=getRcmdr("title.color"),font="RcmdrTitleFont"), trimField,sticky="w") tkgrid(tcFrame, labelRcmdr(statisticsTab,text=" "),tcRFrame, labelRcmdr(statisticsTab,text=" "), trimFrame, sticky="nw") checkBoxes(statistics2Tab,frame="dispFrame",boxes=c("rango","IQR","desvcuar"), initialValues=c(dialog.valores$rango.inicial,dialog.valores$IQR.inicial, dialog.valores$desvcuar.inicial), labels=gettextRcmdr(c("Amplitud ","Amplitud intercuartil (IQR) ","Desviacion Cuartil")), title = gettextRcmdr("Indices de dispersion")) checkBoxes(statistics2Tab,frame="dispRFrame",boxes=c("mad","CVR","ACent"), initialValues=c(dialog.valores$mad.inicial, dialog.valores$CVR.inicial,dialog.valores$ACent.inicial), labels=gettextRcmdr(c("Mediana Desviaciones Absolutas (MAD) ","Coeficiente Variacion Robusto ", "Desviacion centilica ")), title = gettextRcmdr(" ")) ACFrame <- tkframe(statistics2Tab) ACVariable <- tclVar(dialog.valores$AC.inicial) ACField <- ttkentry(ACFrame, width="4", textvariable=ACVariable) tkgrid(labelRcmdr(ACFrame,text=" ")) tkgrid(labelRcmdr(ACFrame,text=" ")) tkgrid(labelRcmdr(ACFrame,text=" ")) tkgrid(labelRcmdr(ACFrame,text=gettextRcmdr("Proporcion datos utilizados = "), fg=getRcmdr("title.color"),font="RcmdrTitleFont"), ACField,sticky="w") tkgrid(dispFrame, labelRcmdr(statistics2Tab,text=" "), dispRFrame, labelRcmdr(statistics2Tab,text=" "), ACFrame, sticky="nw") checkBoxes(statistics3Tab,frame="posicFrame",boxes=c("Q1","Q2","Q3"), initialValues=c(dialog.valores$Q1.inicial,dialog.valores$Q2.inicial, dialog.valores$Q3.inicial), labels=gettextRcmdr(c("Primer Cuartil", "Segundo Cuartil ","Tercer Cuartil ")), title = gettextRcmdr("Indices de posicion")) checkBoxes(statistics3Tab,frame="posicRFrame",boxes=c("min","max","percent"), initialValues=c(dialog.valores$min.inicial,dialog.valores$max.inicial, dialog.valores$percent.inicial), labels=gettextRcmdr(c("Minimo","Maximo","Cuantilas")), title = gettextRcmdr(" ")) percentFrame <- tkframe(statistics3Tab) percentilVariable <- tclVar(dialog.valores$percentil.inicial) percentField <- ttkentry(percentFrame, width="15", textvariable=percentilVariable) tkgrid(labelRcmdr(percentFrame,text=" ")) tkgrid(labelRcmdr(percentFrame,text=" ")) tkgrid(labelRcmdr(percentFrame,text=" ")) tkgrid(labelRcmdr(percentFrame,text=gettextRcmdr("Seleccione cuantilas = "), fg=getRcmdr("title.color"),font="RcmdrTitleFont"), percentField,sticky="w") tkgrid(posicFrame, labelRcmdr(statistics3Tab,text=" "), posicRFrame, labelRcmdr(statistics3Tab,text=" "), percentFrame, sticky="nw") checkBoxes(statistics4Tab,frame="formaFrame",boxes=c("H1","H3"), initialValues=c(dialog.valores$H1.inicial,dialog.valores$H3.inicial), labels=gettextRcmdr(c("Coef. Asimetria H1 ","Coef. Asimetria H3 ")), title = gettextRcmdr("Indices de forma")) checkBoxes(statistics4Tab,frame="formaRFrame",boxes=c("K2","K3"), initialValues=c(dialog.valores$K2.inicial,dialog.valores$K3.inicial), labels=gettextRcmdr(c("Coef. Apuntamiento K2 ","Coef. Apuntamiento K3 ")), title = gettextRcmdr(" ")) tkgrid(formaFrame, labelRcmdr(statistics4Tab,text=" "), formaRFrame, sticky="w") checkBoxes(optionsTab,frame="opsFrame",boxes=c("echocodigo","creahtml","selectodas"), initialValues=c(dialog.valores$echo.inicial,dialog.valores$creahtml.inicial, dialog.valores$selectodas.inicial), labels=gettextRcmdr(c("Mostrar en pantalla el codigo de R ejecutado ","Generar informe de resultados ", "Calcular todos los indices ")), title = gettextRcmdr("Opciones")) tkgrid(opsFrame, sticky="w") dialogSuffix(use.tabs=TRUE,grid.buttons=TRUE,tabs=c('dataTab','statisticsTab','statistics2Tab', 'statistics3Tab','statistics4Tab','optionsTab'), tab.names=c("Datos","Tend. Central","Dispersion","Posicion","Forma","Opciones")) } numindices <- function(vars,statistics,rec=NULL,propdat=NULL,percentil=NULL){ vars <- as.data.frame(vars) variables <- names(vars) media <- function(x){ res <- round(mean(x,na.rm=TRUE),2) res } mediana <- function(x){ res <- round(median(x,na.rm=TRUE),2) res } moda <- function(x){ .ni <- table(x) res <- as.numeric(names(.ni[which(.ni==max(.ni,na.rm=TRUE))])) if (length(res) > 1) res <- res[[1]] res } moda2 <- function(x){ .ni <- table(x) res <- as.numeric(names(.ni[which(.ni==max(.ni,na.rm=TRUE))])) res } mediageom <- function(x){ res <- round(mean(log(x)[x!=0],na.rm=TRUE),2) res } trimedia <- function(x){ .Finf <- fivenum(x)[2] .Md <- fivenum(x)[3] .Fsup <- fivenum(x)[4] res <- round((.Finf+2*.Md+.Fsup)/4,2) res } promcuar <- function(x){ .Q1 <- quantile(x,na.rm=TRUE)[2] .Q3 <- quantile(x,na.rm=TRUE)[4] res <- round((.Q1+.Q3)/2,2) names(res) <- NULL res } midR <- function(x){ .min <- quantile(x,na.rm=TRUE)[1] .max <- quantile(x,na.rm=TRUE)[5] res <- round((.min+.max)/2,2) names(res) <- NULL res } medrec <- function(x,rec){ res <- round(mean(x,trim=rec,na.rm=TRUE),2) res } variancia <- function(x){ res <- round(var(x,na.rm=TRUE),2) res } dt <- function(x){ res <- round(sd(x,na.rm=TRUE),2) res } dtgeom <- function(x){ res <- round(sd(log(x)[x!=0],na.rm=TRUE),2) res } desvmed <- function(x){ .media <- mean(x,na.rm=TRUE) res <- round(sum(abs(x - .media),na.rm=TRUE)/length(na.omit(x)),2) res } CV <- function(x){ .media <- mean(x,na.rm=TRUE) .dt <- sd(x,na.rm=TRUE) res <- round(.dt/.media,2) res } rango <- function(x){ .min <- quantile(x,na.rm=TRUE)[1] .max <- quantile(x,na.rm=TRUE)[5] res <- round(.max-.min,2) names(res) <- NULL res } iqr <- function(x){ .Q1 <- quantile(x,na.rm=TRUE)[2] .Q3 <- quantile(x,na.rm=TRUE)[4] res <- round(.Q3-.Q1,2) names(res) <- NULL res } mad <- function(x){ .mediana <- median(x,na.rm=TRUE) res <- round(median(abs(x-.mediana),na.rm=TRUE),2) res } cvr <- function(x){ .Finf <- fivenum(x)[2] .Fsup <- fivenum(x)[4] res <- round((.Fsup-.Finf)/(.Finf+.Fsup), 2) res } desvcuar <- function(x){ .Q1 <- quantile(x,na.rm=TRUE)[2] .Q3 <- quantile(x,na.rm=TRUE)[4] res <- round((.Q3-.Q1)/2,2) names(res) <- NULL res } acent <- function(x,propdat){ .ACinf <- quantile(x,probs=(1-propdat)/2,na.rm=TRUE) .ACsup <- quantile(x,probs=1-(1-propdat)/2,na.rm=TRUE) res <- round(.ACsup-.ACinf,2) names(res) <- NULL res } q1 <- function(x){ res <- round(quantile(x,na.rm=TRUE)[2],2) names(res) <- NULL res } q2 <- function(x){ res <- round(quantile(x,na.rm=TRUE)[3],2) names(res) <- NULL res } q3 <- function(x){ res <- round(quantile(x,na.rm=TRUE)[4],2) names(res) <- NULL res } pct <- function(x,percentil){ res <- round(quantile(x,probs=percentil,na.rm=TRUE),2) names(res) <- NULL res } h1 <- function(x) { .Finf <- fivenum(x)[2] .Md <- fivenum(x)[3] .Fsup <- fivenum(x)[4] res <- round((.Finf+.Fsup-2*.Md)/(2*.Md),2) res } h3 <- function(x) { .AC90 <- quantile(x,probs=0.9,na.rm=TRUE) .AC10 <- quantile(x,probs=0.1,na.rm=TRUE) .Md <- fivenum(x)[3] res <- round((.AC90+.AC10-2*.Md)/(2*.Md),2) names(res) <- NULL res } k2 <- function(x){ .AC90 <- quantile(x,probs=0.9,na.rm=TRUE) .AC10 <- quantile(x,probs=0.1,na.rm=TRUE) .Q1 <- quantile(x,na.rm=TRUE)[2] .Q3 <- quantile(x,na.rm=TRUE)[4] res <- round((.AC90-.AC10)/(1.9*(.Q3-.Q1)),2) names(res) <- NULL res } k3 <- function(x){ .Einf <- quantile(x,probs=0.125,na.rm=TRUE) .Esup <- quantile(x,probs=0.875,na.rm=TRUE) .Finf <- fivenum(x)[2] .Fsup <- fivenum(x)[4] res <- round((.Esup-.Einf)/(1.7*(.Fsup-.Finf)),2) names(res) <- NULL res } beta1 <- function(x){ .media <- mean(x,na.rm=TRUE) .n <- length(na.omit(x)) res <- round((sum((x-.media)^3,na.rm=TRUE)/.n)^2/(sum((x-.media)^2,na.rm=TRUE)/.n)^3,2) res } gamma1 <- function(x){ .media <- mean(x,na.rm=TRUE) .dt <- sd(x,na.rm=TRUE) .n <- length(na.omit(x)) res <- round(.n*sum((x-.media)^3,na.rm=TRUE)/((.n-1)*(.n-2))/(.dt^3),2) res } beta2 <- function(x){ .media <- mean(x,na.rm=TRUE) .n <- length(na.omit(x)) res <- round(sum((x-.media)^4,na.rm=TRUE)/.n/(sum((x-.media)^2,na.rm=TRUE)/.n)^2,2) res } gamma2 <- function(x){ .media <- mean(x,na.rm=TRUE) .dt <- sd(x,na.rm=TRUE) .n <- length(na.omit(x)) res <- round((.n*(.n+1)*sum((x-.media)^4,na.rm=TRUE)/((.n-1)*(.n-2)*(.n-3))-3* sum((x-.media)^2,na.rm=TRUE)^2/((.n-2)*(.n-3)))/(.dt^4),2) res } res <- list() res[[1]] <- variables res[[2]] <- statistics res[[3]] <- rec res[[4]] <- propdat res[[5]] <- percentil i <- 5 numfilas <- length(vars) TCcol <- sum(c("Media", "Mediana", "Moda", "MediaGeom", "Trimedia", "PromCuar", "midR", "MediaRec") %in% statistics) dispcol <- sum(c("Variancia", "DT", "DTGeom", "DesvMed", "CV", "Rango", "IQR", "DesvCuar", "MAD", "CVR", "ACent") %in% statistics) posiccol <- sum(c("Min", "Max", "Q1", "Q2", "Q3") %in% statistics) + ("Pct" %in% statistics)*length(percentil) formacol <- sum(c("H1", "H3", "K2", "K3", "beta1", "gamma1", "beta2", "gamma2") %in% statistics) .tablaTC <- as.data.frame(matrix(nrow=numfilas,ncol=TCcol)) .tabladisp <- as.data.frame(matrix(nrow=numfilas,ncol=dispcol)) .tablaposic <- as.data.frame(matrix(nrow=numfilas,ncol=posiccol)) .tablaforma <- as.data.frame(matrix(nrow=numfilas,ncol=formacol)) if (TCcol > 0){ j <- 0 if ("Media" %in% statistics) { .media <- unlist(lapply(vars,media),use.names=F) j <- j + 1 .tablaTC[,j]<-.media } if ("Mediana" %in% statistics) { .mediana <- unlist(lapply(vars,mediana),use.names=F) j <- j + 1 .tablaTC[,j]<-.mediana } if ("Moda" %in% statistics) { .moda <- unlist(lapply(vars,moda),use.names=F) .moda2 <- lapply(vars,moda2) for (k in length(.moda2)) { if (length(.moda2[[k]]) > 1) { Message(message=gettextRcmdr(paste("Variable ",variables[k]," tiene mas de una moda: ", "En documento HTML se muestra un solo valor.", sep="")), type="warning") } } j <- j + 1 .tablaTC[,j]<-.moda } if ("MediaGeom" %in% statistics) { .mediageom <- unlist(lapply(vars,mediageom),use.names=F) j <- j + 1 .tablaTC[,j]<-.mediageom } if ("Trimedia" %in% statistics) { .trimedia <- unlist(lapply(vars,trimedia),use.names=F) j <- j + 1 .tablaTC[,j]<-.trimedia } if ("PromCuar" %in% statistics) { .promcuar <- unlist(lapply(vars,promcuar),use.names=F) j <- j + 1 .tablaTC[,j]<-.promcuar } if ("midR" %in% statistics) { .midr <- unlist(lapply(vars,midR),use.names=F) j <- j + 1 .tablaTC[,j]<-.midr } if ("MediaRec" %in% statistics) { .mediarec <- unlist(lapply(vars,medrec,rec),use.names=F) j <- j + 1 .tablaTC[,j]<-.mediarec } i <- i + 1 res[[i]] <- .tablaTC } if (dispcol > 0){ j <- 0 if ("Variancia" %in% statistics) { .var <- unlist(lapply(vars,variancia),use.names=F) j <- j + 1 .tabladisp[,j]<-.var } if ("DT" %in% statistics) { .dt <- unlist(lapply(vars,dt),use.names=F) j <- j + 1 .tabladisp[,j]<-.dt } if ("DTGeom" %in% statistics) { .dtgeom <- unlist(lapply(vars,dtgeom),use.names=F) j <- j + 1 .tabladisp[,j]<-.dtgeom } if ("DesvMed" %in% statistics) { .desvmed <- unlist(lapply(vars,desvmed),use.names=F) j <- j + 1 .tabladisp[,j]<-.desvmed } if ("CV" %in% statistics) { .cv <- unlist(lapply(vars,CV),use.names=F) j <- j + 1 .tabladisp[,j]<-.cv } if ("Rango" %in% statistics) { .rango <- unlist(lapply(vars,rango),use.names=F) j <- j + 1 .tabladisp[,j]<-.rango } if ("IQR" %in% statistics) { .iqr <- unlist(lapply(vars,iqr),use.names=F) j <- j + 1 .tabladisp[,j]<-.iqr } if ("DesvCuar" %in% statistics) { .dq <- unlist(lapply(vars,desvcuar),use.names=F) j <- j + 1 .tabladisp[,j]<-.dq } if ("MAD" %in% statistics) { .mad <- unlist(lapply(vars,mad),use.names=F) j <- j + 1 .tabladisp[,j]<-.mad } if ("CVR" %in% statistics) { .cvr <- unlist(lapply(vars,cvr),use.names=F) j <- j + 1 .tabladisp[,j]<-.cvr } if ("ACent" %in% statistics) { .acent <- unlist(lapply(vars,acent,propdat),use.names=F) j <- j + 1 .tabladisp[,j]<-.acent } i <- i + 1 res[[i]] <- .tabladisp } if (posiccol > 0){ j <- 0 if ("Min" %in% statistics) { .min <- unlist(lapply(lapply(vars,as.numeric),min,na.rm=TRUE),use.names=F) j <- j + 1 .tablaposic[,j]<-.min } if ("Max" %in% statistics) { .max <- unlist(lapply(lapply(vars,as.numeric),max,na.rm=TRUE),use.names=F) j <- j + 1 .tablaposic[,j]<-.max } if ("Q1" %in% statistics) { .q1 <- unlist(lapply(vars,q1),use.names=F) j <- j + 1 .tablaposic[,j]<-.q1 } if ("Q2" %in% statistics) { .q2 <- unlist(lapply(vars,q2),use.names=F) j <- j + 1 .tablaposic[,j]<-.q2 } if ("Q3" %in% statistics) { .q3 <- unlist(lapply(vars,q3),use.names=F) j <- j + 1 .tablaposic[,j]<-.q3 } if ("Pct" %in% statistics) { .pct <- matrix(unlist(lapply(vars,pct,percentil),use.names=F), nrow=numfilas,ncol=length(percentil),byrow=T) .tablaposic[,(j+1):(j+length(percentil))]<-.pct } i <- i + 1 res[[i]] <- .tablaposic } if (formacol > 0){ j <- 0 if ("H1" %in% statistics) { .h1 <- unlist(lapply(vars,h1),use.names=F) j <- j + 1 .tablaforma[,j]<-.h1 } if ("H3" %in% statistics) { .h3 <- unlist(lapply(vars,h3),use.names=F) j <- j + 1 .tablaforma[,j]<-.h3 } if ("K2" %in% statistics) { .k2 <- unlist(lapply(vars,k2),use.names=F) j <- j + 1 .tablaforma[,j]<-.k2 } if ("K3" %in% statistics) { .k3 <- unlist(lapply(vars,k3),use.names=F) j <- j + 1 .tablaforma[,j]<-.k3 } if ("beta1" %in% statistics) { .beta1 <- unlist(lapply(vars,beta1),use.names=F) j <- j + 1 .tablaforma[,j]<-.beta1 } if ("gamma1" %in% statistics) { .gamma1 <- unlist(lapply(vars,gamma1),use.names=F) j <- j + 1 .tablaforma[,j]<-.gamma1 } if ("beta2" %in% statistics) { .beta2 <- unlist(lapply(vars,beta2),use.names=F) j <- j + 1 .tablaforma[,j]<-.beta2 } if ("gamma2" %in% statistics) { .gamma2 <- unlist(lapply(vars,gamma2),use.names=F) j <- j + 1 .tablaforma[,j]<-.gamma2 } i <- i + 1 res[[i]] <- .tablaforma } class(res) <- "numindices" res } print.numindices <- function(x,...){ j<-6 if (sum(c("Media", "Mediana", "Moda", "MediaGeom", "Trimedia", "PromCuar", "midR", "MediaRec") %in% x[[2]]) > 0){ .tablaTC <- as.data.frame(x[[j]]) rownames(.tablaTC) <- x[[1]] colnames(.tablaTC) <- c("Media", "Mediana", "Moda", "MediaGeom", "Trimedia", "PromCuar", "midR", paste("MediaRec(",x[[3]]*100,"%)",sep=''))[c("Media", "Mediana", "Moda", "MediaGeom", "Trimedia", "PromCuar", "midR", "MediaRec") %in% x[[2]]] cat(" print(.tablaTC) cat("\n\n") j <- j+1 } if (sum(c("Variancia", "DT", "DTGeom", "DesvMed", "CV", "Rango", "IQR", "DesvCuar", "MAD", "CVR", "ACent") %in% x[[2]]) > 0){ .tabladisp <- as.data.frame(x[[j]]) rownames(.tabladisp) <- x[[1]] colnames(.tabladisp) <- c("Variancia", "DT", "DTGeom", "DesvMed", "CV", "Rango", "IQR", "DesvCuar", "MAD", "CVR", paste("ACent(",x[[4]]*100,"%)",sep=''))[c("Variancia", "DT", "DTGeom", "DesvMed", "CV", "Rango", "IQR", "DesvCuar", "MAD", "CVR", "ACent") %in% x[[2]]] cat(" print(.tabladisp) cat("\n\n") j <- j+1 } if (sum(c("Min", "Max", "Q1", "Q2", "Q3") %in% x[[2]]) + ("Pct" %in% x[[2]])*length(x[[5]]) > 0){ .tablaposic <- as.data.frame(x[[j]]) rownames(.tablaposic) <- x[[1]] colnames(.tablaposic) <- c("Min", "Max", "Q1", "Q2", "Q3", paste(if (!is.null(x[[5]])) x[[5]]*100 else "Pct",'%',sep=''))[c("Min", "Max", "Q1", "Q2", "Q3",rep("Pct",if (!is.null(x[[5]])) length(x[[5]]) else 1)) %in% x[[2]]] cat(" print(.tablaposic) cat("\n\n") j <- j+1 } if (sum(c("H1", "H3", "K2", "K3", "beta1", "gamma1", "beta2", "gamma2") %in% x[[2]]) > 0){ .tablaforma <- as.data.frame(x[[j]]) rownames(.tablaforma) <- x[[1]] colnames(.tablaforma) <- c("H1", "H3", "K2", "K3", "beta1", "gamma1", "beta2", "gamma2")[c("H1", "H3", "K2", "K3", "beta1", "gamma1", "beta2", "gamma2") %in% x[[2]]] cat(" print(.tablaforma) cat("\n\n") } invisible(x) } resumen.numericas <- function(){ defecto <- list(x.inicial=NULL,media.inicial="0",mediana.inicial="0",moda.inicial="0", mediageom.inicial="0",trimedia.inicial="0",promcuar.inicial="0", midR.inicial="0",medrec.inicial="0",trim.inicial="0.05",variancia.inicial="0", dt.inicial="0",dtgeom.inicial="0",desvmed.inicial="0",CV.inicial="0", rango.inicial="0",IQR.inicial="0",desvcuar.inicial="0",mad.inicial="0", CVR.inicial="0",ACent.inicial="0",AC.inicial="0.9",min.inicial="0", max.inicial="0",Q1.inicial="0",Q2.inicial="0",Q3.inicial="0", percent.inicial="0",percentil.inicial="0, .25, .5, .75, 1", H1.inicial="0",H3.inicial="0",K2.inicial="0",K3.inicial="0", beta1.inicial="0",gamma1.inicial="0",beta2.inicial="0",gamma2.inicial="0", echo.inicial="0",creahtml.inicial="0",selectodas.inicial="0",tab.inicial=0) dialog.valores <- getDialog("resumen.numericas",defecto) initializeDialog(title=gettextRcmdr("Indices para variables cuantitativas"),use.tabs=TRUE, tabs=c('dataTab','statisticsTab','statistics2Tab','statistics3Tab','statistics4Tab','optionsTab')) listaVar <- variableListBox(dataTab, Numeric(), selectmode="multiple", title=gettextRcmdr("Variables (escoja una o mas)"), initialSelection=varPosn(dialog.valores$x.inicial,"numeric")) onOK <- function(){ tab <- if(as.character(tkselect(notebook)) == dataTab$ID) 0 else 1 x <- getSelection(listaVar) if (length(x) == 0){ errorCondition(recall=resumen.ordinales, message=gettextRcmdr("Debes escoger una variable.")) return() } .BaseDatosActiva <- ActiveDataSet() echocodigo <- tclvalue(echocodigoVariable) creahtml <- tclvalue(creahtmlVariable) selectodas <- tclvalue(selectodasVariable) if (selectodas == 1) { mediaval = medianaval = modaval = mediageomval = trimediaval = promcuarval = midRval = medrecval = varianciaval = dtval = CVval = dtgeomval = desvmedval = rangoval = IQRval = desvcuarval = madval = CVRval = ACentval = minval = maxval = Q1val = Q2val = Q3val = percentval = H1val = H3val = K2val = K3val = beta1val = gamma1val = beta2val = gamma2val = TRUE } else { mediaval <- tclvalue(mediaVariable) medianaval <- tclvalue(medianaVariable) modaval <- tclvalue(modaVariable) mediageomval <- tclvalue(mediageomVariable) trimediaval <- tclvalue(trimediaVariable) promcuarval <- tclvalue(promcuarVariable) midRval <- tclvalue(midRVariable) medrecval <- tclvalue(medrecVariable) varianciaval <- tclvalue(varianciaVariable) dtval <- tclvalue(dtVariable) CVval <- tclvalue(CVVariable) dtgeomval <- tclvalue(dtgeomVariable) desvmedval <- tclvalue(desvmedVariable) rangoval <- tclvalue(rangoVariable) IQRval <- tclvalue(IQRVariable) desvcuarval <- tclvalue(desvcuarVariable) madval <- tclvalue(madVariable) CVRval <- tclvalue(CVRVariable) ACentval <- tclvalue(ACentVariable) minval <- tclvalue(minVariable) maxval <- tclvalue(maxVariable) Q1val <- tclvalue(Q1Variable) Q2val <- tclvalue(Q2Variable) Q3val <- tclvalue(Q3Variable) percentval <- tclvalue(percentVariable) H1val <- tclvalue(H1Variable) H3val <- tclvalue(H3Variable) K2val <- tclvalue(K2Variable) K3val <- tclvalue(K3Variable) beta1val <- tclvalue(beta1Variable) gamma1val <- tclvalue(gamma1Variable) beta2val <- tclvalue(beta2Variable) gamma2val <- tclvalue(gamma2Variable) } selec <- as.numeric(mediaval) + as.numeric(medianaval) + as.numeric(modaval) + as.numeric(mediageomval) + as.numeric(trimediaval) + as.numeric(promcuarval) + as.numeric(midRval) + as.numeric(medrecval) selec2 <- as.numeric(varianciaval) + as.numeric(dtval) + as.numeric(CVval) + as.numeric(dtgeomval) + as.numeric(desvmedval) + as.numeric(rangoval) + as.numeric(IQRval) + as.numeric(desvcuarval) + as.numeric(madval) + as.numeric(CVRval) + as.numeric(ACentval) selec3 <- as.numeric(minval) + as.numeric(maxval) + as.numeric(Q1val) + as.numeric(Q2val) + as.numeric(Q3val) + as.numeric(percentval) selec4 <- as.numeric(H1val) + as.numeric(H3val) + as.numeric(K2val) + as.numeric(K3val) + as.numeric(beta1val) + as.numeric(gamma1val) + as.numeric(beta2val) + as.numeric(gamma2val) seleccion <- selec + selec2 + selec3 + selec4 if (seleccion == 0){ errorCondition(recall=resumen.numericas, message=gettextRcmdr("Debes escoger algun indicador.")) return() } putDialog("resumen.numericas",list(x.inicial=x,media.inicial=mediaval,mediana.inicial=medianaval, moda.inicial=modaval,mediageom.inicial=mediageomval, trimedia.inicial=trimediaval,promcuar.inicial=promcuarval, midR.inicial=midRval,medrec.inicial=medrecval, trim.inicial=tclvalue(trimVariable),variancia.inicial=varianciaval, dt.inicial=dtval,dtgeom.inicial=dtgeomval,desvmed.inicial=desvmedval, CV.inicial=CVval,rango.inicial=rangoval,IQR.inicial=IQRval, desvcuar.inicial=desvcuarval,mad.inicial=madval,CVR.inicial=CVRval, ACent.inicial=ACentval,AC.inicial=tclvalue(ACVariable),min.inicial=minval, max.inicial=maxval,Q1.inicial=Q1val,Q2.inicial=Q2val,Q3.inicial=Q3val, percent.inicial=percentval,percentil.inicial=tclvalue(percentilVariable), H1.inicial=H1val,H3.inicial=H3val,K2.inicial=K2val,K3.inicial=K3val, beta1.inicial=beta1val,gamma1.inicial=gamma1val,beta2.inicial=beta2val, gamma2.inicial=gamma2val,selectodas.inicial=selectodas, echo.inicial=echocodigo,creahtml.inicial=creahtml,tab.inicial=tab)) if (percentval == 1) { pct <- c(gsub(" ", ",",gsub(", ", ",",tclvalue(percentilVariable)))) pct1 <- as.numeric(unlist(strsplit(pct,","))) if ( is.na(pct1) || (sum(pct1<0.0)>0) || (sum(pct1>1.0)>0) || (sum(!is.numeric(pct1))>0) ) { pct <- paste(seq(0.,1.,.25),collapse=",") Message(message=gettextRcmdr("Vector de percentiles invalido. Se utilizara vector por defecto."), type="warning") } } else pct <- NULL if (medrecval == 1) { rec <- as.numeric(tclvalue(trimVariable)) if ( rec < .0 || rec > .5 || !is.numeric(rec) ) { rec <- 0.05 Message(message=gettextRcmdr("Proporcion de recorte invalida se utilizara valor por defecto."), type="warning") } } else rec <- NULL if (ACentval == 1) { propdat <- as.numeric(tclvalue(ACVariable)) if ( propdat < .0 || propdat > 1. || !is.numeric(propdat) ) { prop.dat <- 0.9 Message(message=gettextRcmdr("Proporcion de datos invalida se utilizara valor por defecto."), type="warning") } } else propdat <- NULL vars <- if (length(x) == 1) paste('"', x, '"', sep="") else paste("c(", paste('"', x, '"', collapse=", ", sep=""), ")", sep="") if (length(x) == 1) variables <- paste(.BaseDatosActiva, "[", vars, "]", sep="") else variables <- paste(.BaseDatosActiva, "[,", vars, "]", sep="") stats <- paste("c(", paste(c('"Media"', '"Mediana"', '"Moda"', '"MediaGeom"', '"Trimedia"', '"PromCuar"', '"midR"', '"MediaRec"', '"Variancia"', '"DT"', '"DTGeom"', '"DesvMed"', '"CV"', '"Rango"', '"IQR"', '"DesvCuar"', '"MAD"', '"CVR"', '"ACent"', '"Min"', '"Max"', '"Q1"', '"Q2"', '"Q3"', '"Pct"', '"H1"', '"H3"', '"K2"', '"K3"', '"beta1"', '"gamma1"', '"beta2"', '"gamma2"') [c(mediaval, medianaval, modaval, mediageomval, trimediaval, promcuarval, midRval, medrecval, varianciaval, dtval, dtgeomval, desvmedval, CVval, rangoval, IQRval, desvcuarval, madval, CVRval, ACentval, minval, maxval, Q1val, Q2val, Q3val, percentval, H1val, H3val, K2val, K3val, beta1val, gamma1val, beta2val, gamma2val) == 1], collapse=", "), ")", sep="") if (percentval ==1) instruccion1 <- paste(".indices.num <- numindices(vars=",variables, ", statistics=", stats, if (!is.null(rec)){paste(",rec=",rec)}, if(!is.null(propdat)){paste(",propdat=",propdat)},",percentil=c(",pct,")",")", sep="") else instruccion1 <- paste(".indices.num <- numindices(vars=",variables, ", statistics=", stats, if (!is.null(rec)){paste(",rec=",rec)}, if(!is.null(propdat)){paste(",propdat=",propdat)},")", sep="") justDoIt(instruccion1) if (echocodigo == 1) { logger(instruccion1) } doItAndPrint(".indices.num if (creahtml == 1) { if (!file.exists("Informe de Resultados.html")) .archivo <- HTMLInitFile(file.path(getwd()), "Informe de Resultados", BackGroundColor=" else .archivo <- file.path(getwd(), "Informe de Resultados.html") titulo <- "Indicadores descriptivos para variables cuantitativas" HTML(as.title(titulo),file=.archivo) j <- 6 if ( selec>0 ){ .TablaRes <- as.data.frame(.indices.num[[j]]) rownames(.TablaRes) <- .indices.num[[1]] colnames(.TablaRes) <- c("Media","Mediana","Moda", "MediaGeom", "Trimedia","PromCuar","midR", paste("MediaRec(",.indices.num[[3]]*100,"%)",sep=''))[c("Media","Mediana","Moda", "MediaGeom", "Trimedia","PromCuar","midR", "MediaRec") %in% .indices.num[[2]]] HTML("Indicadores de tendencia central: ", file=.archivo) HTML(.TablaRes, file=.archivo) HTMLhr(file = .archivo) j <- j+1 } if ( selec2>0 ){ .TablaRes <- as.data.frame(.indices.num[[j]]) rownames(.TablaRes) <- .indices.num[[1]] colnames(.TablaRes) <- c("Variancia", "DT", "DTGeom", "DesvMed", "CV","Rango", "IQR", "DesvCuar", "MAD", "CVR",paste("ACent(",.indices.num[[4]]*100,"%)",sep=''))[c("Variancia", "DT", "DTGeom", "DesvMed", "CV","Rango", "IQR", "DesvCuar", "MAD", "CVR", "ACent") %in% .indices.num[[2]]] HTML("Indicadores de dispersion: ", file=.archivo) HTML(.TablaRes, file=.archivo) HTMLhr(file = .archivo) j <- j+1 } if ( selec3>0 ){ .TablaRes <- as.data.frame(.indices.num[[j]]) rownames(.TablaRes) <- .indices.num[[1]] colnames(.TablaRes) <- c("Min", "Max", "Q1", "Q2", "Q3", paste(.indices.num[[5]]*100,'%',sep=''))[c("Min", "Max", "Q1", "Q2", "Q3",rep("Pct",length(.indices.num[[5]]))) %in% .indices.num[[2]]] HTML("Indicadores de posicion: ", file=.archivo) HTML(.TablaRes, file=.archivo) HTMLhr(file = .archivo) j <- j+1 } if ( selec4>0 ){ .TablaRes <- as.data.frame(.indices.num[[j]]) rownames(.TablaRes) <- .indices.num[[1]] colnames(.TablaRes) <- c("H1", "H3", "K2", "K3","beta1", "gamma1", "beta2", "gamma2")[c("H1", "H3", "K2", "K3","beta1", "gamma1", "beta2", "gamma2") %in% .indices.num[[2]]] HTML("Indicadores de forma: ", file=.archivo) HTML(.TablaRes, file=.archivo) HTMLhr(file = .archivo) j <- j+1 } } remove(.indices.num, envir=.GlobalEnv) closeDialog() if (echocodigo == 1) logger("remove(.indices.num)") tkfocus(CommanderWindow()) } OKCancelHelp(helpSubject="RcmdrPlugin.EACSPIR",reset="resumen.numericas",apply="resumen.numericas") tkgrid(getFrame(listaVar), sticky="nw") checkBoxes(statisticsTab,frame="tcFrame",boxes=c("media","mediana","mediageom","moda"), initialValues=c(dialog.valores$media.inicial,dialog.valores$mediana.inicial, dialog.valores$mediageom.inicial,dialog.valores$moda.inicial), labels=gettextRcmdr(c("Media ","Mediana ","Media Geometrica ","Moda ")), title = gettextRcmdr("Indices de tendencia central")) checkBoxes(statisticsTab,frame="tcRFrame",boxes=c("trimedia","promcuar","midR","medrec"), initialValues=c(dialog.valores$trimedia.inicial,dialog.valores$promcuar.inicial, dialog.valores$midR.inicial,dialog.valores$medrec.inicial), labels=gettextRcmdr(c("Trimedia ","Promedio de cuartiles ","Rango medio ","Media Recortada ")), title = gettextRcmdr(" ")) trimFrame <- tkframe(statisticsTab) trimVariable <- tclVar(dialog.valores$trim.inicial) trimField <- ttkentry(trimFrame, width="8", textvariable=trimVariable) tkgrid(labelRcmdr(trimFrame,text=" ")) tkgrid(labelRcmdr(trimFrame,text=" ")) tkgrid(labelRcmdr(trimFrame,text=" ")) tkgrid(labelRcmdr(trimFrame,text=" ")) tkgrid(labelRcmdr(trimFrame,text=gettextRcmdr("Proporcion datos recortados = "), fg=getRcmdr("title.color"),font="RcmdrTitleFont"), trimField,sticky="w") tkgrid(tcFrame, labelRcmdr(statisticsTab,text=" "),tcRFrame, labelRcmdr(statisticsTab,text=" "), trimFrame, sticky="nw") checkBoxes(statistics2Tab,frame="dispFrame",boxes=c("variancia","dt","dtgeom","desvmed","rango","IQR"), initialValues=c(dialog.valores$variancia.inicial,dialog.valores$dt.inicial, dialog.valores$dtgeom.inicial,dialog.valores$desvmed.inicial, dialog.valores$rango.inicial,dialog.valores$IQR.inicial), labels=gettextRcmdr(c("Variancia ", "Desv. Tipica ", "Desviacion Geometrica ", "Desv. Media ", "Amplitud ", "Amplitud intercuartil (IQR) ")), title = gettextRcmdr("Indices de dispersion")) checkBoxes(statistics2Tab,frame="dispRFrame",boxes=c("CV","desvcuar","mad","CVR","ACent"), initialValues=c(dialog.valores$CV.inicial,dialog.valores$desvcuar.inicial, dialog.valores$mad.inicial,dialog.valores$CVR.inicial, dialog.valores$ACent.inicial), labels=gettextRcmdr(c("Coeficiente Variacion ","Desviacion Cuartil ", "Mediana Desviaciones Absolutas (MAD) ","Coeficiente Variacion Robusto ", "Desviacion centilica ")), title = gettextRcmdr(" ")) ACFrame <- tkframe(statistics2Tab) ACVariable <- tclVar(dialog.valores$AC.inicial) ACField <- ttkentry(ACFrame, width="4", textvariable=ACVariable) tkgrid(labelRcmdr(ACFrame,text=" ")) tkgrid(labelRcmdr(ACFrame,text=" ")) tkgrid(labelRcmdr(ACFrame,text=" ")) tkgrid(labelRcmdr(ACFrame,text=" ")) tkgrid(labelRcmdr(ACFrame,text=" ")) tkgrid(labelRcmdr(ACFrame,text=gettextRcmdr("Proporcion datos utilizados = "), fg=getRcmdr("title.color"),font="RcmdrTitleFont"), ACField,sticky="w") tkgrid(dispFrame, labelRcmdr(statistics2Tab,text=" "), dispRFrame, labelRcmdr(statistics2Tab,text=" "), ACFrame, sticky="nw") checkBoxes(statistics3Tab,frame="posicFrame",boxes=c("Q1","Q2","Q3"), initialValues=c(dialog.valores$Q1.inicial,dialog.valores$Q2.inicial, dialog.valores$Q3.inicial), labels=gettextRcmdr(c("Primer Cuartil", "Segundo Cuartil ","Tercer Cuartil ")), title = gettextRcmdr("Indices de posicion")) checkBoxes(statistics3Tab,frame="posicRFrame",boxes=c("min","max","percent"), initialValues=c(dialog.valores$min.inicial,dialog.valores$max.inicial, dialog.valores$percent.inicial), labels=gettextRcmdr(c("Minimo ","Maximo ","Cuantilas ")), title = gettextRcmdr(" ")) percentFrame <- tkframe(statistics3Tab) percentilVariable <- tclVar(dialog.valores$percentil.inicial) percentField <- ttkentry(percentFrame, width="15", textvariable=percentilVariable) tkgrid(labelRcmdr(percentFrame,text=" ")) tkgrid(labelRcmdr(percentFrame,text=" ")) tkgrid(labelRcmdr(percentFrame,text=" ")) tkgrid(labelRcmdr(percentFrame,text=gettextRcmdr("Seleccione cuantilas = "), fg=getRcmdr("title.color"),font="RcmdrTitleFont"), percentField,sticky="w") tkgrid(posicFrame, labelRcmdr(statistics3Tab,text=" "), posicRFrame, labelRcmdr(statistics3Tab,text=" "), percentFrame, sticky="nw") checkBoxes(statistics4Tab,frame="formaFrame",boxes=c("H1","H3","beta1","gamma1"), initialValues=c(dialog.valores$H1.inicial,dialog.valores$H3.inicial, dialog.valores$beta1.inicial,dialog.valores$gamma1.inicial), labels=gettextRcmdr(c("Coef. Asimetria H1 ","Coef. Asimetria H3 ", "Coef. Asimetria Pearson ","Coef. Asimetria Fisher ")), title = gettextRcmdr("Indices de forma")) checkBoxes(statistics4Tab,frame="formaRFrame",boxes=c("K2","K3","beta2","gamma2"), initialValues=c(dialog.valores$K2.inicial,dialog.valores$K3.inicial, dialog.valores$beta2.inicial,dialog.valores$gamma2.inicial), labels=gettextRcmdr(c("Coef. Apuntamiento K2 ","Coef. Apuntamiento K3 ", "Coef. Apuntamiento Pearson ","Coef. Apuntamiento Fisher ")), title = gettextRcmdr(" ")) tkgrid(formaFrame, labelRcmdr(statistics4Tab,text=" "), formaRFrame, sticky="w") checkBoxes(optionsTab,frame="opsFrame",boxes=c("echocodigo","creahtml","selectodas"), initialValues=c(dialog.valores$echo.inicial,dialog.valores$creahtml.inicial, dialog.valores$selectodas.inicial), labels=gettextRcmdr(c("Mostrar en pantalla el codigo de R ejecutado ","Generar informe de resultados ", "Calcular todos los indices ")), title = gettextRcmdr("Opciones")) tkgrid(opsFrame, sticky="w") dialogSuffix(use.tabs=TRUE,grid.buttons=TRUE,tabs=c('dataTab','statisticsTab','statistics2Tab', 'statistics3Tab','statistics4Tab','optionsTab'), tab.names=c("Datos","Tend. Central","Dispersion","Posicion","Forma","Opciones")) } histfun <- function(data,tscale,nsup,interval){ variable <- unlist(strsplit(deparse(substitute(data)), "[$]"))[2] titulop <- paste("Histograma para ",variable, sep="") if (tscale == "frequency") { tituloy <- "Frecuencias absolutas" frecuencia <- TRUE } if (tscale == "density") { tituloy <- "Densidades" frecuencia <- FALSE } titulox <- "Intervalos" if (nsup == TRUE) { .xfit <- seq(min(data,na.rm=TRUE),max(data,na.rm=TRUE),length=1000) .yfit <- dnorm(x=.xfit,mean=mean(data,na.rm=TRUE),sd=sd(data,na.rm=TRUE)) .h <- hist(data,breaks=interval,plot=FALSE) if (frecuencia==TRUE) .yfit <- .yfit*diff(.h$mids[1:2])*length(na.omit(data)) if (frecuencia==TRUE) maxlim <- max(max(.h$counts),max(.yfit)) else maxlim <- max(max(.h$density),max(.yfit)) .h <- hist(data,freq=frecuencia,breaks=interval,main=titulop,ylab=tituloy,xlab=titulox,col='red', ylim=c(0,maxlim)) lines(.xfit,.yfit,col='blue',lwd=2) } else .h <- hist(data,freq=frecuencia,breaks=interval,main=titulop,ylab=tituloy,xlab=titulox,col='red') box() } histograma <- function(){ defecto <- list(x.inicial=NULL,escala.inicial="frequency",intervalos.inicial="<auto>", normalsup.inicial="0",echo.inicial="0",creahtml.inicial="0",tab.inicial=0) dialog.valores <- getDialog("histograma",defecto) initializeDialog(title=gettextRcmdr("Histograma"),use.tabs=TRUE, tabs=c('dataTab','statisticsTab','optionsTab')) onOK <- function(){ tab <- if(as.character(tkselect(notebook)) == dataTab$ID) 0 else 1 x <- getSelection(listaVar) .BaseDatosActiva <- ActiveDataSet() interv <- tclvalue(intervalosVariable) echocodigo <- tclvalue(echocodigoVariable) creahtml <- tclvalue(creahtmlVariable) escala <- tclvalue(escalaVariable) normalsup <- tclvalue(normalsupVariable) echocodigo <- tclvalue(echocodigoVariable) creahtml <- tclvalue(creahtmlVariable) if (length(x) == 0){ errorCondition(recall=histograma, message=gettextRcmdr("Debe escoger una variable.")) return() } putDialog("histograma",list(x.inicial=x,escala.inicial=escala,intervalos.inicial=interv, normalsup.inicial=normalsup,echo.inicial=echocodigo, creahtml.inicial=creahtml,tab.inicial=tab)) opts <- options(warn=-1) interv <- if (interv == gettextRcmdr("<auto>")) '"Sturges"' else as.numeric(interv) vars <- x bd <- paste(.BaseDatosActiva, "$", vars, sep="") normalsup <- as.logical(as.numeric(normalsup)) options(opts) instruccion1 <- paste("histfun(data=",bd, ", tscale='", escala, "', nsup=", normalsup,", interval=", interv, ")", sep="") if (echocodigo == 1) { logger(instruccion1) } justDoIt(instruccion1) if (creahtml == 1) { if (!file.exists("Informe de Resultados.html")) .archivo <- HTMLInitFile(file.path(getwd()), "Informe de Resultados", BackGroundColor=" else .archivo <- file.path(getwd(), "Informe de Resultados.html") titulo <- paste("Histograma para variable ",x,sep="") HTML(as.title(titulo),file=.archivo) nombre.archivo <- paste("HistogramaR",gsub(":","",substr(Sys.time(),12,19)), ".jpg",sep="") dev.print(jpeg, filename=paste(getwd(),"/",nombre.archivo,sep=""), width=500, height=500) HTMLInsertGraph(nombre.archivo,file=.archivo,append=TRUE) HTMLhr(file = .archivo) } closeDialog() tkfocus(CommanderWindow()) } OKCancelHelp(helpSubject="hist",reset="histograma",apply="histograma") listaVar <- variableListBox(dataTab, Numeric(), title=gettextRcmdr("Variables (escoja una)"), initialSelection=varPosn(dialog.valores$x.inicial,"numeric")) radioButtons(statisticsTab,name = "escala", buttons = c("frequency","density"), values = c("frequency","density"), labels = gettextRcmdr(c("Frecuencias Absolutas","Densidades")), title = gettextRcmdr("Escala eje ordenadas"), initialValue = dialog.valores$escala.inicial) checkBoxes(statisticsTab,frame="histogramaFrame",boxes=c("normalsup"), initialValues=c(dialog.valores$normalsup.inicial), labels=gettextRcmdr(c("Superponer curva normal ")), title = gettextRcmdr("Configuracion del histograma")) checkBoxes(optionsTab,frame="opsFrame",boxes=c("echocodigo","creahtml"), initialValues=c(dialog.valores$echo.inicial,dialog.valores$creahtml.inicial), labels=gettextRcmdr(c("Mostrar en pantalla el codigo de R ejecutado ","Generar informe de resultados ")), title = gettextRcmdr("Opciones")) intervalosFrame <- tkframe(statisticsTab) intervalosVariable <- tclVar(dialog.valores$intervalos.inicial) intervalosField <- ttkentry(intervalosFrame, width="8", textvariable=intervalosVariable) tkgrid(getFrame(listaVar), sticky="nw") tkgrid(escalaFrame, sticky="w") tkgrid(histogramaFrame, sticky="w") tkgrid(labelRcmdr(intervalosFrame, text = gettextRcmdr("Numero de intervalos: ")), intervalosField, sticky = "w") tkgrid(intervalosFrame, sticky = "w") tkgrid.configure(intervalosField, sticky = "e") tkgrid(opsFrame, sticky="w") dialogSuffix(use.tabs=TRUE,grid.buttons=TRUE,tabs=c('dataTab','statisticsTab','optionsTab'), tab.names=c("Datos","Estadisticos","Opciones")) } bpfun <- function(data, intervinf, intervsup, ident){ variable <- unlist(strsplit(deparse(substitute(data)), "[$]"))[2] titulop <- paste("Diagrama de caja para ",variable, sep="") .bxp1 <- boxplot.stats(as.numeric(data),coef=intervinf) .bxp2 <- boxplot.stats(as.numeric(data),coef=intervsup) boxplot(as.numeric(data),main=titulop,col='red',outpch=NA) .selec <- .bxp1$out %in% .bxp2$out .anom <- .bxp1$out .anom[.selec] <- NA points(rep(1, length(.anom)), .anom, pch = 1, col = 'blue') .extrem <- .bxp2$out points(rep(1, length(.extrem)), .extrem, pch = 8, col = 'red') if (ident == TRUE) { identify(rep(1,length(data)),as.numeric(data),rownames(data.frame(data))) } } diagrama.caja.ord <- function (){ defecto <- list(x.inicial=NULL,intervinf.inicial="1.5",intervsup.inicial="3.0", identifica.inicial="0",echo.inicial="0",creahtml.inicial="0",tab.inicial=0) dialog.valores <- getDialog("diagrama.caja.ord",defecto) initializeDialog(title=gettextRcmdr("Diagrama de Caja"),use.tabs=TRUE, tabs=c('dataTab','statisticsTab','optionsTab')) listaVar <- variableListBox(dataTab, Factors(), title=gettextRcmdr("Variables (escoja una)"), initialSelection=varPosn(dialog.valores$x.inicial,"factor")) checkBoxes(statisticsTab,frame="cajaFrame",boxes=c("identifica"), initialValues=c(dialog.valores$identifica.inicial), labels=gettextRcmdr(c("Identificar sujetos (por numero de fila ocupado) ")), title = gettextRcmdr("Configuracion del grafico")) checkBoxes(optionsTab,frame="opsFrame",boxes=c("echocodigo","creahtml"), initialValues=c(dialog.valores$echo.inicial,dialog.valores$creahtml.inicial), labels=gettextRcmdr(c("Mostrar en pantalla el codigo de R ejecutado ","Generar informe de resultados ")), title = gettextRcmdr("Opciones")) intervalosFrame <- tkframe(statisticsTab) intervinfVariable <- tclVar(dialog.valores$intervinf.inicial) intervinfField <- ttkentry(intervalosFrame, width="6", textvariable=intervinfVariable) intervsupVariable <- tclVar(dialog.valores$intervsup.inicial) intervsupField <- ttkentry(intervalosFrame, width="6", textvariable=intervsupVariable) onOK <- function(){ tab <- if(as.character(tkselect(notebook)) == dataTab$ID) 0 else 1 x <- getSelection(listaVar) .BaseDatosActiva <- ActiveDataSet() intervinf <- as.numeric(tclvalue(intervinfVariable)) intervsup <- as.numeric(tclvalue(intervsupVariable)) if ( is.na(intervinf) || (intervinf<0) || (!is.numeric(intervinf)) || is.na(intervsup) || (intervsup<0) || (!is.numeric(intervsup)) || (intervsup < intervinf) ) { intervinf <- 1.5 intervsup <- 3.0 Message(message=gettextRcmdr("Coeficientes inferior y superior no validos. Se utilizara valores por defecto."), type="warning") } opts <- options(warn=-1) echocodigo <- tclvalue(echocodigoVariable) creahtml <- tclvalue(creahtmlVariable) identif <- as.logical(as.numeric(tclvalue(identificaVariable))) putDialog("diagrama.caja.ord",list(x.inicial=x,intervinf.inicial=intervinf,intervsup.inicial=intervsup, identifica.inicial=identif,echo.inicial=echocodigo, creahtml.inicial=creahtml,tab.inicial=tab)) if (length(x) == 0){ errorCondition(recall=diagrama.caja.ord, message=gettextRcmdr("Debe escoger una variable.")) return() } bd <- paste(.BaseDatosActiva, "$", x, sep="") options(opts) justDoIt(paste("cond <- !is.ordered(",paste(.BaseDatosActiva,"$",x,sep=""),")",sep="")) if (cond){ errorCondition(recall=diagrama.caja.ord, message=gettextRcmdr(paste("Variable ",x, " no es ordinal.",sep=''))) return() } remove("cond", envir=.GlobalEnv) instruccion1 <- paste("bpfun(data=",bd, ", intervinf=", intervinf, ", intervsup=", intervsup, ", ident=", identif, ")", sep="") if (echocodigo == 1) { logger(instruccion1) } justDoIt(instruccion1) if (creahtml == 1) { if (!file.exists("Informe de Resultados.html")) .archivo <- HTMLInitFile(file.path(getwd()), "Informe de Resultados", BackGroundColor=" else .archivo <- file.path(getwd(), "Informe de Resultados.html") titulo <- paste("Diagrama de caja para variable ",x,sep="") HTML(as.title(titulo),file=.archivo) nombre.archivo <- paste("DiagramaCajaR",gsub(":","",substr(Sys.time(),12,19)), ".jpg",sep="") dev.print(jpeg, filename=paste(getwd(),"/",nombre.archivo,sep=""), width=500, height=500) HTMLInsertGraph(nombre.archivo,file=.archivo,append=TRUE) HTMLhr(file = .archivo) } closeDialog() tkfocus(CommanderWindow()) } OKCancelHelp(helpSubject="boxplot",reset="diagrama.caja.ord",apply="diagrama.caja.ord") tkgrid(getFrame(listaVar), sticky="nw") tkgrid(cajaFrame, sticky="w") tkgrid(labelRcmdr(intervalosFrame, text = gettextRcmdr("Coeficiente Limite inferior: ")), intervinfField, sticky = "w") tkgrid(labelRcmdr(intervalosFrame, text = gettextRcmdr("Coeficiente Limite superior: ")), intervsupField, sticky = "w") tkgrid(intervalosFrame, sticky = "w") tkgrid.configure(intervinfField, sticky = "e") tkgrid.configure(intervsupField, sticky = "e") tkgrid(opsFrame, sticky="w") dialogSuffix(use.tabs=TRUE,grid.buttons=TRUE,tabs=c('dataTab','statisticsTab','optionsTab'), tab.names=c("Datos","Estadisticos","Opciones")) } diagrama.caja <- function (){ defecto <- list(x.inicial=NULL,intervinf.inicial="1.5",intervsup.inicial="3.0", identifica.inicial="0",echo.inicial="0",creahtml.inicial="0",tab.inicial=0) dialog.valores <- getDialog("diagrama.caja",defecto) initializeDialog(title=gettextRcmdr("Diagrama de Caja"),use.tabs=TRUE, tabs=c('dataTab','statisticsTab','optionsTab')) listaVar <- variableListBox(dataTab, Numeric(), title=gettextRcmdr("Variables (escoja una)"), initialSelection=varPosn(dialog.valores$x.inicial,"numeric")) checkBoxes(statisticsTab,frame="cajaFrame",boxes=c("identifica"), initialValues=c(dialog.valores$identifica.inicial), labels=gettextRcmdr(c("Identificar sujetos (por numero de fila ocupado) ")), title = gettextRcmdr("Configuracion del grafico")) checkBoxes(optionsTab,frame="opsFrame",boxes=c("echocodigo","creahtml"), initialValues=c(dialog.valores$echo.inicial,dialog.valores$creahtml.inicial), labels=gettextRcmdr(c("Mostrar en pantalla el codigo de R ejecutado ","Generar informe de resultados ")), title = gettextRcmdr("Opciones")) intervalosFrame <- tkframe(statisticsTab) intervinfVariable <- tclVar(dialog.valores$intervinf.inicial) intervinfField <- ttkentry(intervalosFrame, width="6", textvariable=intervinfVariable) intervsupVariable <- tclVar(dialog.valores$intervsup.inicial) intervsupField <- ttkentry(intervalosFrame, width="6", textvariable=intervsupVariable) onOK <- function(){ tab <- if(as.character(tkselect(notebook)) == dataTab$ID) 0 else 1 x <- getSelection(listaVar) .BaseDatosActiva <- ActiveDataSet() intervinf <- as.numeric(tclvalue(intervinfVariable)) intervsup <- as.numeric(tclvalue(intervsupVariable)) if ( is.na(intervinf) || (intervinf<0) || (!is.numeric(intervinf)) || is.na(intervsup) || (intervsup<0) || (!is.numeric(intervsup)) || (intervsup < intervinf) ) { intervinf <- 1.5 intervsup <- 3.0 Message(message=gettextRcmdr("Coeficientes inferior y superior no validos. Se utilizara valores por defecto."), type="warning") } opts <- options(warn=-1) echocodigo <- tclvalue(echocodigoVariable) creahtml <- tclvalue(creahtmlVariable) identif <- as.logical(as.numeric(tclvalue(identificaVariable))) putDialog("diagrama.caja",list(x.inicial=x,intervinf.inicial=intervinf,intervsup.inicial=intervsup, identifica.inicial=identif,echo.inicial=echocodigo, creahtml.inicial=creahtml,tab.inicial=tab)) if (length(x) == 0){ errorCondition(recall=diagrama.caja, message=gettextRcmdr("Debe escoger una variable.")) return() } bd <- paste(.BaseDatosActiva, "$", x, sep="") options(opts) instruccion1 <- paste("bpfun(data=",bd, ", intervinf=", intervinf, ", intervsup=", intervsup, ", ident=", identif, ")", sep="") if (echocodigo == 1) { logger(instruccion1) } justDoIt(instruccion1) if (creahtml == 1) { if (!file.exists("Informe de Resultados.html")) .archivo <- HTMLInitFile(file.path(getwd()), "Informe de Resultados", BackGroundColor=" else .archivo <- file.path(getwd(), "Informe de Resultados.html") titulo <- paste("Diagrama de caja para variable ",x,sep="") HTML(as.title(titulo),file=.archivo) nombre.archivo <- paste("DiagramaCajaR",gsub(":","",substr(Sys.time(),12,19)), ".jpg",sep="") dev.print(jpeg, filename=paste(getwd(),"/",nombre.archivo,sep=""), width=500, height=500) HTMLInsertGraph(nombre.archivo,file=.archivo,append=TRUE) HTMLhr(file = .archivo) } closeDialog() tkfocus(CommanderWindow()) } OKCancelHelp(helpSubject="boxplot",reset="diagrama.caja",apply="diagrama.caja") tkgrid(getFrame(listaVar), sticky="nw") tkgrid(cajaFrame, sticky="w") tkgrid(labelRcmdr(intervalosFrame, text = gettextRcmdr("Coeficiente Limite inferior: ")), intervinfField, sticky = "w") tkgrid(labelRcmdr(intervalosFrame, text = gettextRcmdr("Coeficiente Limite superior: ")), intervsupField, sticky = "w") tkgrid(intervalosFrame, sticky = "w") tkgrid.configure(intervinfField, sticky = "e") tkgrid.configure(intervsupField, sticky = "e") tkgrid(opsFrame, sticky="w") dialogSuffix(use.tabs=TRUE,grid.buttons=TRUE,tabs=c('dataTab','statisticsTab','optionsTab'), tab.names=c("Datos","Estadisticos","Opciones")) } bivcat <- function(rowvar,colvar,statistics=NULL,tables=NULL,subset=NULL,pcttable=NULL,data){ res <- list() res[[1]] <- rowvar res[[2]] <- colvar res[[3]] <- statistics res[[4]] <- tables res[[5]] <- pcttable i <- 6 .Tabla <- eval(parse(text=paste('xtabs(~',rowvar,'+',colvar, if (!is.null(subset)) {paste(',subset=',subset,'')}, ',data=',data,')'))) res[[i]] <- .Tabla MArow <- sum(c("JiCuadrado", "Phi", "CoefCont", "Sakoda", "Chuprov", "VCramer") %in% statistics) + + ("Yule" %in% statistics)*3 MEProw <- sum(c("Lambda","Theil") %in% statistics)*3 + ("Tau" %in% statistics)*2 .tablaMA <- array(dim=c(MArow,1)) .tablaMEP <- array(dim=c(MEProw,1)) if ("Porcentajes" %in% tables){ if (pcttable == "fila") { .porcentajes <- rowPercents(.Tabla) } if (pcttable == "columna") { .porcentajes <- colPercents(.Tabla) } if (pcttable == "total") { .porcentajes <- totPercents(.Tabla) } i <- i + 1 res[[i]] <- round(.porcentajes,2) } if ("FrecEsperadas" %in% tables) { .esperadas <- chisq.test(.Tabla, correct=FALSE)$expected mensAviso <- NULL if (0 < (emq1 <- sum(.esperadas < 1))) mensAviso <- paste(emq1, gettextRcmdr("frecuencias esperadas menores que 1")) if (0 < (emq5 <- sum(.esperadas < 5))) mensAviso <- paste(mensAviso, "\n", emq5, gettextRcmdr(" frecuencias esperadas menores que 5"), sep="") if (!is.null(mensAviso)) Message(message=mensAviso, type="warning") i <- i + 1 res[[i]] <- round(.esperadas,2) } if ("JiComponentes" %in% tables) { .Componentes <- round(chisq.test(.Tabla, correct=FALSE)$residuals^2,2) i <- i + 1 res[[i]] <- round(.Componentes,2) } if (MArow > 0){ j <- 0 if ( (sum(c("JiCuadrado", "Phi", "CoefCont", "Sakoda", "Chuprov", "VCramer") %in% statistics) + "JiComponentes" %in% tables) > 0 ) { .Jicuadrado <- chisq.test(.Tabla, correct=FALSE)$statistic names(.Jicuadrado)<-NULL } if ("JiCuadrado" %in% statistics) { j <- j + 1 .tablaMA[j] <- .Jicuadrado } if ("Phi" %in% statistics) { .phi <- sqrt(.Jicuadrado/sum(.Tabla)) j <- j + 1 .tablaMA[j] <- .phi } if ("CoefCont" %in% statistics) { .Coef.Contingencia <- sqrt(.Jicuadrado/(sum(.Tabla)+.Jicuadrado)) j <- j + 1 .tablaMA[j] <- .Coef.Contingencia } if ("Sakoda" %in% statistics) { .sakoda<- sqrt(min(dim(.Tabla))*.Jicuadrado/((min(dim(.Tabla))-1)*(sum(.Tabla)+.Jicuadrado))) j <- j + 1 .tablaMA[j]<-.sakoda } if ("Chuprov" %in% statistics) { .chuprov <- sqrt(.Jicuadrado/(sum(.Tabla)*(dim(.Tabla)[1]-1)*(dim(.Tabla)[2]-1))) j <- j + 1 .tablaMA[j]<-.chuprov } if ("VCramer" %in% statistics) { .VCramer <- sqrt(.Jicuadrado/((min(dim(.Tabla))-1)*sum(.Tabla))) j <- j + 1 .tablaMA[j]<-.VCramer } if ("Yule" %in% statistics) { if ( dim(.Tabla)[1] != 2 || dim(.Tabla)[2] != 2){ Message(message=gettextRcmdr("La tabla de contingencia no es de tamano 2x2: \n Indices de Yule no se calcularan"), type="warning") return() } .a <- .Tabla[1,1] .b <- .Tabla[1,2] .c <- .Tabla[2,1] .d <- .Tabla[2,2] .Q <- (.a*.d-.b*.c)/(.a*.d+.b*.c) .Y <- (sqrt(.a*.d)-sqrt(.b*.c))/(sqrt(.a*.d)+sqrt(.b*.c)) .V <- (.a*.d-.b*.c)/((.a+.b)*(.a+.c)*(.b+.d)*(.c+.d)) j <- j + 1 .tablaMA[j:(j+2)] <- c(.Q,.Y,.V) } i <- i + 1 res[[i]] <- round(.tablaMA,2) } if (MEProw > 0){ j <- 0 if ("Lambda" %in% statistics) { lambda.a.b <- (sum(apply(.Tabla,2,max)/sum(.Tabla)) - max(rowSums(.Tabla))/sum(.Tabla))/(1 - max(rowSums(.Tabla))/sum(.Tabla)) lambda.b.a <- (sum(apply(.Tabla,1,max)/sum(.Tabla)) - max(colSums(.Tabla))/sum(.Tabla))/(1 - max(colSums(.Tabla))/sum(.Tabla)) .lambda <- (lambda.a.b + lambda.b.a)/2 j <- j + 1 .tablaMEP[j:(j+2)] <- c(lambda.a.b,lambda.b.a,.lambda) j <- j+2 } if ("Tau" %in% statistics) { tau.a.b <- (sum((.Tabla/sum(.Tabla))^2/matrix(colSums(.Tabla)[col(.Tabla)]/sum(.Tabla), nrow=nrow(.Tabla)))-sum((rowSums(.Tabla)/sum(.Tabla))^2))/(1-sum((rowSums(.Tabla)/sum(.Tabla))^2)) tau.b.a <- (sum((.Tabla/sum(.Tabla))^2/matrix(rowSums(.Tabla)[row(.Tabla)]/sum(.Tabla), nrow=nrow(.Tabla)))-sum((colSums(.Tabla)/sum(.Tabla))^2))/(1-sum((colSums(.Tabla)/sum(.Tabla))^2)) j <- j+1 .tablaMEP[j:(j+1)] <- c(tau.a.b,tau.b.a) j <- j+1 } if ("Theil" %in% statistics) { H.a.b <- -sum(.Tabla/sum(.Tabla)*log(.Tabla/sum(.Tabla)),na.rm=TRUE) H.a <- -sum(rowSums(.Tabla)/sum(.Tabla)*log(rowSums(.Tabla)/sum(.Tabla)),na.rm=TRUE) H.b <- -sum(colSums(.Tabla)/sum(.Tabla)*log(colSums(.Tabla)/sum(.Tabla)),na.rm=TRUE) theil.a.b <- (H.a + H.b - H.a.b)/H.a theil.b.a <- (H.a + H.b - H.a.b)/H.b .theil <- 2*(H.a + H.b - H.a.b)/(H.a+H.b) j <- j+1 .tablaMEP[j:(j+2)] <- c(theil.a.b,theil.b.a,.theil) } i <- i + 1 res[[i]] <- round(.tablaMEP,2) } class(res) <- "bivcat" res } print.bivcat <- function(x,...){ cat("Tabla de contingencia para ",x[[1]], " y ",x[[2]],": \n\n",sep='') print(x[[6]]) cat("\n\n") j<-7 if ("Porcentajes" %in% x[[4]]){ msg <- switch(x[[5]], 'total'='Tabla porcentajes respecto al total: ', 'fila'='Tabla porcentajes respecto a marginales fila: ', 'columna'='Tabla porcentajes respecto a marginales columna: ') cat(paste(msg,"\n\n")) print(x[[j]]) cat("\n\n") j <- j + 1 } if ("FrecEsperadas" %in% x[[4]]){ cat(paste("Frecuencias Esperadas: \n\n")) print(x[[j]]) cat("\n\n") j <- j + 1 } if ("JiComponentes" %in% x[[4]]){ cat(paste("Descomposicion del estadistico Ji cuadrado: \n\n")) print(x[[j]]) cat("\n\n") j <- j + 1 } if (sum(c("JiCuadrado", "Phi", "CoefCont", "Sakoda", "Chuprov", "VCramer", "Yule") %in% x[[3]]) > 0){ .tablaMA <- as.data.frame(x[[j]]) rownames(.tablaMA) <- c("Ji Cuadrado", "Phi de Pearson", "Coef. Contingencia de Pearson", "Transf. Sakoda", "Coef. Chuprov", "V de Cramer",c("Q de Yule","Y de Yule","V de Yule"))[ c("JiCuadrado", "Phi", "CoefCont", "Sakoda", "Chuprov", "VCramer",rep("Yule",3)) %in% x[[3]]] colnames(.tablaMA) <- "Valores" cat("Coeficientes de asociacion: \n\n") print(.tablaMA) cat("\n\n") j <- j+1 } if (sum(c("Lambda", "Tau", "Theil") %in% x[[3]]) > 0){ .tablaMEP <- as.data.frame(x[[j]]) rownames(.tablaMEP) <- c(c("Lambda A/B", "Lambda B/A","Lambda (simetrica)"), c("Tau A/B", "Tau B/A"), c("Theil A/B","Theil B/A","Theil (simetrica)"))[ c(rep("Lambda",3), rep("Tau",2), rep("Theil",3)) %in% x[[3]]] colnames(.tablaMEP) <- "Valores" cat("Medidas del error de prediccion: \n\n") print(.tablaMEP) cat("\n\n") j <- j+1 } invisible(x) } bivariante.categoricas <- function(){ defecto <- list(fila.inicial=NULL,columna.inicial=NULL,porcentajes.inicial="ninguno", frecEsp.inicial="0",jicuadrado.inicial="0", phiPearson.inicial="0",sakoda.inicial="0",VCramer.inicial="0", jicomponentes.inicial="0",contingPearson.inicial="0",chuprov.inicial="0", yule.inicial="0",lambda.inicial="0",tau.inicial="0",theil.inicial="0", subconjunto.inicial=gettextRcmdr("<all valid cases>"), echo.inicial="0",creahtml.inicial="0",tab.inicial=0) dialog.valores <- getDialog("bivariante.categoricas",defecto) initializeDialog(title=gettextRcmdr("Descripcion tablas de contingencia"),use.tabs=TRUE, tabs=c('dataTab','statisticsTab','statistics2Tab','optionsTab')) variablesFrame <- tkframe(dataTab) filaVar <- variableListBox(variablesFrame, Factors(), title=gettextRcmdr("Variables (escoja una)"), initialSelection=varPosn(dialog.valores$fila.inicial,"factor")) columnaVar <- variableListBox(variablesFrame, Factors(), title=gettextRcmdr("Variables (escoja una)"), initialSelection=varPosn(dialog.valores$columna.inicial,"factor")) subsetBox(dataTab, subset.expression=dialog.valores$subconjunto.inicial) radioButtons(statisticsTab,name = "porcentajes", buttons = c("fila","columna", "total", "ninguno"), values = c("fila", "columna","total", "ninguno"), labels = gettextRcmdr(c("Porcentajes respecto a marginales fila", "Porcentajes respecto a marginales columna","Porcentajes respecto al total", "Ningun porcentaje")), title = gettextRcmdr("Calcular Porcentajes"), initialValue = dialog.valores$porcentajes.inicial) checkBoxes(statistics2Tab,frame="esperadasFrame",boxes=c("frecEsp"), initialValues=c(dialog.valores$frecEsp.inicial), labels=gettextRcmdr(c("Calcular frecuencias esperadas ")), title = gettextRcmdr("Frecuencias Esperadas")) checkBoxes(statistics2Tab,frame="statsFrame",boxes=c("jicuadrado","phiPearson","sakoda","VCramer"), initialValues=c(dialog.valores$jicuadrado.inicial,dialog.valores$phiPearson.inicial, dialog.valores$sakoda.inicial,dialog.valores$VCramer.inicial), labels=gettextRcmdr(c("Ji Cuadrado ","Phi de Pearson ","Transformacion de Sakoda ", "Coef. Contingencia Cramer ")), title = gettextRcmdr("Coeficientes de Asociacion")) rightFrame <- tkframe(statistics2Tab) checkBoxes(statistics2Tab,frame="rightFrame",boxes=c("jiComponentes","contingPearson","chuprov","yule"), initialValues=c(dialog.valores$jicomponentes.inicial,dialog.valores$contingPearson.inicial, dialog.valores$chuprov.inicial,dialog.valores$yule.inicial), labels=gettextRcmdr(c("Descomposicion Ji cuadrado de Pearson ","Coef. Contingencia Pearson ", "Coef. Contingencia Chuprov ","Coeficientes Yule (Tablas 2x2) ")), title = gettextRcmdr(" ")) checkBoxes(statistics2Tab,frame="errorpredFrame",boxes=c("lambda","tau","theil"), initialValues=c(dialog.valores$lambda.inicial,dialog.valores$tau.inicial, dialog.valores$theil.inicial), labels=gettextRcmdr(c("Lambda Goodman-Kruskal ","Tau Goodman-Kruskal ", "Coef. Incertidumbre Theil ")), title = gettextRcmdr("Medidas Error de Prediccion")) checkBoxes(optionsTab,frame="opsFrame",boxes=c("echocodigo","creahtml"), initialValues=c(dialog.valores$echo.inicial,dialog.valores$creahtml.inicial), labels=gettextRcmdr(c("Mostrar en pantalla el codigo de R ejecutado ","Generar informe de resultados ")), title = gettextRcmdr("Opciones")) onOK <- function(){ tab <- if(as.character(tkselect(notebook)) == dataTab$ID) 0 else 1 fila <- getSelection(filaVar) columna <- getSelection(columnaVar) if (length(fila) == 0 || length(columna) == 0){ errorCondition(recall=bivariante.categoricas, message=gettextRcmdr("Debe seleccionar dos variables.")) return() } if (fila == columna) { errorCondition(recall=bivariante.categoricas, message=gettextRcmdr("Debe seleccionar dos variables distintas.")) return() } porcentajes <- as.character(tclvalue(porcentajesVariable)) esperadas <- tclvalue(frecEspVariable) jicuadrado <- tclvalue(jicuadradoVariable) jicomponentes <- tclvalue(jiComponentesVariable) phival <- tclvalue(phiPearsonVariable) contingval <- tclvalue(contingPearsonVariable) sakodaval <- tclvalue(sakodaVariable) chuprovval <- tclvalue(chuprovVariable) VCramerval <- tclvalue(VCramerVariable) yuleval <- tclvalue(yuleVariable) lambdaval <- tclvalue(lambdaVariable) tauval <- tclvalue(tauVariable) theilval <- tclvalue(theilVariable) subconjunto <- tclvalue(subsetVariable) echocodigo <- tclvalue(echocodigoVariable) creahtml <- tclvalue(creahtmlVariable) putDialog("bivariante.categoricas",list(fila.inicial=fila,columna.inicial=columna, porcentajes.inicial=porcentajes,frecEsp.inicial=esperadas, jicuadrado.inicial=jicuadrado,jicomponentes.inicial=jicomponentes, phiPearson.inicial=phival,contingPearson.inicial=contingval, sakoda.inicial=sakodaval,chuprov.inicial=chuprovval, VCramer.inicial=VCramerval,yule.inicial=yuleval,lambda.inicial=lambdaval, tau.inicial=tauval, theil.inicial=theilval,subconjunto.inicial=subconjunto, echo.inicial=echocodigo,creahtml.inicial=creahtml,tab.inicial=tab)) selec <- as.numeric(jicuadrado) + as.numeric(phival) + as.numeric(contingval) + as.numeric(sakodaval) + as.numeric(chuprovval) + as.numeric(VCramerval) + as.numeric(yuleval)*3 selec2 <- as.numeric(lambdaval)*3 + as.numeric(tauval)*2 + as.numeric(theilval)*3 if (selec+selec2 >0) stats <- paste("c(", paste(c('"JiCuadrado"', '"Phi"', '"CoefCont"', '"Sakoda"', '"Chuprov"', '"VCramer"', '"Yule"', '"Lambda"', '"Tau"', '"Theil"') [c(jicuadrado,phival,contingval,sakodaval,chuprovval,VCramerval,yuleval, lambdaval,tauval,theilval) == 1], collapse=", "), ")", sep="") else stats <- 'NULL' if ((porcentajes!='ninguno') || (as.numeric(esperadas)+as.numeric(jicomponentes))>0) tabs <- paste("c(", paste(c('"Porcentajes"', '"FrecEsperadas"', '"JiComponentes"') [c((porcentajes!="ninguno"),c(esperadas,jicomponentes) == 1)], collapse=", "), ")", sep="") else tabs <- 'NULL' if (trim.blanks(subconjunto) == gettextRcmdr("<all valid cases>")) instruccion1 <- paste(".indices.bc <- bivcat(rowvar='",fila, "', colvar='",columna, "', statistics=", stats, ", tables=",tabs, if(porcentajes!="ninguno"){paste(", pcttable='",porcentajes,"'",sep='')}, ", data='",ActiveDataSet(),"')", sep="") else { instruccion1 <- paste(".indices.bc <- bivcat(rowvar='",fila, "', colvar='",columna, "', statistics=", stats, ", tables=",tabs, if(porcentajes!="ninguno"){paste(", pcttable='",porcentajes,"'",sep='')}, ", subset='",subconjunto, "', data='",ActiveDataSet(),"')", sep="") } justDoIt(instruccion1) if (echocodigo == 1) { logger(instruccion1) } doItAndPrint(paste(".indices.bc " y ", columna, sep="")) if (creahtml == 1) { if (!file.exists("Informe de Resultados.html")) .archivo <- HTMLInitFile(file.path(getwd()), "Informe de Resultados", BackGroundColor=" else .archivo <- file.path(getwd(), "Informe de Resultados.html") titulo <- paste("Descripcion bivariante de datos categoricos: ",fila, " y ", columna, sep="") HTML(as.title(titulo),file=.archivo) HTML('Tabla de contigencia: ', file=.archivo) HTML(.indices.bc[[6]], file=.archivo) j <- 7 if ("Porcentajes" %in% .indices.bc[[4]]){ msg <- switch(.indices.bc[[5]], 'total'='Tabla porcentajes respecto al total: ', 'fila'='Tabla porcentajes respecto a marginales fila: ', 'columna'='Tabla porcentajes respecto a marginales columna: ') HTML(msg, file=.archivo) HTML(.indices.bc[[j]], file=.archivo) j <- j + 1 } if ("FrecEsperadas" %in% .indices.bc[[4]]){ msg <- 'Frecuencias esperadas:' HTML(msg, file=.archivo) HTML(.indices.bc[[j]], file=.archivo) j <- j + 1 } if ("JiComponentes" %in% .indices.bc[[4]]){ msg <- 'Descomposicion del estadistico Ji cuadrado::' HTML(msg, file=.archivo) HTML(.indices.bc[[j]], file=.archivo) j <- j + 1 } if ( selec>0 ){ .TablaRes <- as.data.frame(.indices.bc[[j]]) rownames(.TablaRes) <- c("Ji Cuadrado", "Phi de Pearson", "Coef. Contingencia de Pearson", "Transf. Sakoda", "Coef. Chuprov", "V de Cramer",c("Q de Yule","Y de Yule","V de Yule"))[ c("JiCuadrado", "Phi", "CoefCont", "Sakoda", "Chuprov", "VCramer",rep("Yule",3)) %in% .indices.bc[[3]]] colnames(.TablaRes) <- "Valores" HTML("Coeficientes de asociacion: ", file=.archivo) HTML(.TablaRes, file=.archivo) HTMLhr(file = .archivo) j <- j+1 } if ( selec2>0 ){ .TablaRes <- as.data.frame(.indices.bc[[j]]) rownames(.TablaRes) <- c(c("Lambda A/B", "Lambda B/A","Lambda (simetrica)"), c("Tau A/B", "Tau B/A"), c("Theil A/B","Theil B/A","Theil (simetrica)"))[ c(rep("Lambda",3), rep("Tau",2), rep("Theil",3)) %in% .indices.bc[[3]]] colnames(.TablaRes) <- "Valores" HTML("Medidas del error de prediccion: ", file=.archivo) HTML(.TablaRes, file=.archivo) HTMLhr(file = .archivo) j <- j+1 } } remove(.indices.bc, envir=.GlobalEnv) closeDialog() tkfocus(CommanderWindow()) } OKCancelHelp(helpSubject="xtabs",reset="bivariante.categoricas",apply="bivariante.categoricas") tkgrid(getFrame(filaVar), labelRcmdr(variablesFrame, text=" "), getFrame(columnaVar), sticky="nw") tkgrid(variablesFrame, sticky="w") tkgrid(subsetFrame, sticky="w") tkgrid(porcentajesFrame, sticky="w") tkgrid(esperadasFrame, sticky="w") tkgrid(statsFrame, rightFrame, sticky="w") tkgrid(errorpredFrame, sticky="w") tkgrid(opsFrame, sticky="w") dialogSuffix(use.tabs=TRUE,grid.buttons=TRUE,tabs=c('dataTab','statisticsTab', 'statistics2Tab','optionsTab'), tab.names=c("Datos","Tablas","Estadisticos","Opciones")) } barragfun <- function(rowvar,colvar,tabVariable='ni',subset=NULL,data){ .Tabla <- eval(parse(text=paste('xtabs(~',rowvar,'+',colvar, if (!is.null(subset)) {paste(',subset=',subset,'')}, ',data=',data,')'))) .Tabla <- eval(parse(text=paste('xtabs(~',rowvar,'+',colvar, if (!is.null(subset)) {paste(',subset=',subset,'')}, ',data=',data,')'))) if (tabVariable == "fi") { .Tabla <- .Tabla/sum(.Tabla) } titulo <- paste("Barras agrupadas para ",rowvar," y ",colvar, sep="") tituloy <- if (tabVariable == "ni") "Frecuencias Absolutas" else "Frecuencias Relativas" eval(parse(text=paste('barplot(.Tabla,beside=TRUE,main=titulo,ylab=tituloy,xlab="',colvar, '",ylim=c(0,max(.Tabla)*1.05),col=heat.colors(length(levels(',data,'$',rowvar, '))),legend.text=TRUE,args.legend=list(x="topright",title="',rowvar,'")',')',sep=''))) box() } barras.agrupadas <- function(){ defecto <- list(fila.inicial=NULL,columna.inicial=NULL,tabla.inicial="ni", subconjunto.inicial=gettextRcmdr("<all valid cases>"), echo.inicial="0",creahtml.inicial="0",tab.inicial=0) dialog.valores <- getDialog("barras.agrupadas",defecto) initializeDialog(title=gettextRcmdr("Diagrama de barras agrupadas"),use.tabs=TRUE, tabs=c('dataTab','statisticsTab','optionsTab')) variablesFrame <- tkframe(dataTab) filaVar <- variableListBox(variablesFrame, Factors(), title=gettextRcmdr("Variables (escoja una)"), initialSelection=varPosn(dialog.valores$fila.inicial,"factor")) columnaVar <- variableListBox(variablesFrame, Factors(), title=gettextRcmdr("Variables (escoja una)"), initialSelection=varPosn(dialog.valores$columna.inicial,"factor")) subsetBox(dataTab, subset.expression=dialog.valores$subconjunto.inicial) radioButtons(statisticsTab,name = "tabla", buttons = c("niBoton","fiBoton"), values = c("ni","fi"), labels = gettextRcmdr(c("Frecuencias Absolutas", "Frecuencias Relativas")), title = gettextRcmdr("Tabla basada en:"), initialValue = dialog.valores$tabla.inicial) checkBoxes(optionsTab,frame="opsFrame",boxes=c("echocodigo","creahtml"), initialValues=c(dialog.valores$echo.inicial,dialog.valores$creahtml.inicial), labels=gettextRcmdr(c("Mostrar en pantalla el codigo de R ejecutado ","Generar informe de resultados ")), title = gettextRcmdr("Opciones")) onOK <- function(){ tab <- if(as.character(tkselect(notebook)) == dataTab$ID) 0 else 1 fila <- getSelection(filaVar) columna <- getSelection(columnaVar) if (length(fila) == 0 || length(columna) == 0){ errorCondition(recall=barras.agrupadas, message=gettextRcmdr("Debe seleccionar dos variables.")) return() } if (fila == columna) { errorCondition(recall=barras.agrupadas, message=gettextRcmdr("Debe seleccionar dos variables distintas.")) return() } tabla <- as.character(tclvalue(tablaVariable)) subconjunto <- tclvalue(subsetVariable) echocodigo <- tclvalue(echocodigoVariable) creahtml <- tclvalue(creahtmlVariable) putDialog("barras.agrupadas",list(fila.inicial=fila,columna.inicial=columna, tabla.inicial=tabla,subconjunto.inicial=subconjunto, echo.inicial=echocodigo,creahtml.inicial=creahtml,tab.inicial=tab)) if (trim.blanks(subconjunto) == gettextRcmdr("<all valid cases>")) instruccion1 <- paste("barragfun(rowvar='",fila, "', colvar='",columna, "', tabVariable='", tabla, "', data='",ActiveDataSet(),"')", sep="") else { instruccion1 <- paste("barragfun(rowvar='",fila, "', colvar='",columna, "', tabVariable='", tabla, "', subset='",subconjunto, "', data='",ActiveDataSet(),"')", sep="") } justDoIt(instruccion1) if (echocodigo == 1) { logger(instruccion1) } if (creahtml == 1) { if (!file.exists("Informe de Resultados.html")) .archivo <- HTMLInitFile(file.path(getwd()), "Informe de Resultados", BackGroundColor=" else .archivo <- file.path(getwd(), "Informe de Resultados.html") titulo <- paste("Diagrama de barras agrupadas para : ",fila, " y ", columna, sep="") HTML(as.title(titulo),file=.archivo) nombre.archivo <- paste("BarrasAgrupadasR",gsub(":","",substr(Sys.time(),12,19)), ".jpg",sep="") dev.print(jpeg, filename=paste(getwd(),"/",nombre.archivo,sep=""), width=500, height=500) HTMLInsertGraph(nombre.archivo,file=.archivo,append=TRUE) HTMLhr(file = .archivo) } closeDialog() tkfocus(CommanderWindow()) } OKCancelHelp(helpSubject="barplot",reset="barras.agrupadas",apply="barras.agrupadas") tkgrid(getFrame(filaVar), labelRcmdr(variablesFrame, text=" "), getFrame(columnaVar), sticky="nw") tkgrid(variablesFrame, sticky="w") tkgrid(subsetFrame, sticky="w") tkgrid(tablaFrame, sticky="w") tkgrid(opsFrame, sticky="w") dialogSuffix(use.tabs=TRUE,grid.buttons=TRUE,tabs=c('dataTab','statisticsTab','optionsTab'), tab.names=c("Datos","Estadisticos","Opciones")) } mosaicofun <- function(rowvar,colvar,subset=NULL,data){ .Tabla <- eval(parse(text=paste('xtabs(~',rowvar,'+',colvar, if (!is.null(subset)) {paste(',subset=',subset,'')}, ',data=',data,')'))) titulo <- paste("Grafico de mosaico para ",rowvar," y ",colvar, sep="") mosaicplot(.Tabla,main=titulo,col=1:dim(.Tabla)[2]) box() } grafico.mosaico <- function(){ defecto <- list(fila.inicial=NULL,columna.inicial=NULL, subconjunto.inicial=gettextRcmdr("<all valid cases>"), echo.inicial="0",creahtml.inicial="0",tab.inicial=0) dialog.valores <- getDialog("grafico.mosaico",defecto) initializeDialog(title=gettextRcmdr("Grafico de Mosaico"),use.tabs=TRUE, tabs=c('dataTab','optionsTab')) variablesFrame <- tkframe(dataTab) filaVar <- variableListBox(variablesFrame, Factors(), title=gettextRcmdr("Variables (escoja una)"), initialSelection=varPosn(dialog.valores$fila.inicial,"factor")) columnaVar <- variableListBox(variablesFrame, Factors(), title=gettextRcmdr("Variables (escoja una)"), initialSelection=varPosn(dialog.valores$columna.inicial,"factor")) subsetBox(dataTab, subset.expression=dialog.valores$subconjunto.inicial) checkBoxes(optionsTab,frame="opsFrame",boxes=c("echocodigo","creahtml"), initialValues=c(dialog.valores$echo.inicial,dialog.valores$creahtml.inicial), labels=gettextRcmdr(c("Mostrar en pantalla el codigo de R ejecutado ","Generar informe de resultados ")), title = gettextRcmdr("Opciones")) onOK <- function(){ tab <- if(as.character(tkselect(notebook)) == dataTab$ID) 0 else 1 fila <- getSelection(filaVar) columna <- getSelection(columnaVar) if (length(fila) == 0 || length(columna) == 0){ errorCondition(recall=grafico.mosaico, message=gettextRcmdr("Debe seleccionar dos variables.")) return() } if (fila == columna) { errorCondition(recall=grafico.mosaico, message=gettextRcmdr("Debe seleccionar dos variables distintas.")) return() } subconjunto <- tclvalue(subsetVariable) echocodigo <- tclvalue(echocodigoVariable) creahtml <- tclvalue(creahtmlVariable) putDialog("grafico.mosaico",list(fila.inicial=fila,columna.inicial=columna, subconjunto.inicial=subconjunto,echo.inicial=echocodigo, creahtml.inicial=creahtml,tab.inicial=tab)) if (trim.blanks(subconjunto) == gettextRcmdr("<all valid cases>")) instruccion1 <- paste("mosaicofun(rowvar='",fila, "', colvar='",columna, "', data='",ActiveDataSet(),"')", sep="") else { instruccion1 <- paste("mosaicofun(rowvar='",fila, "', colvar='",columna, "', subset='",subconjunto, "', data='",ActiveDataSet(),"')", sep="") } justDoIt(instruccion1) if (echocodigo == 1) { logger(instruccion1) } if (creahtml == 1) { if (!file.exists("Informe de Resultados.html")) .archivo <- HTMLInitFile(file.path(getwd()), "Informe de Resultados", BackGroundColor=" else .archivo <- file.path(getwd(), "Informe de Resultados.html") titulo <- paste("Grafico de mosaico para : ",fila, " y ", columna, sep="") HTML(as.title(titulo),file=.archivo) nombre.archivo <- paste("GraficoMosaicoR",gsub(":","",substr(Sys.time(),12,19)), ".jpg",sep="") dev.print(jpeg, filename=paste(getwd(),"/",nombre.archivo,sep=""), width=500, height=500) HTMLInsertGraph(nombre.archivo,file=.archivo,append=TRUE) HTMLhr(file = .archivo) } closeDialog() tkfocus(CommanderWindow()) } OKCancelHelp(helpSubject="mosaicplot",reset="grafico.mosaico",apply="grafico.mosaico") tkgrid(getFrame(filaVar), labelRcmdr(variablesFrame, text=" "), getFrame(columnaVar), sticky="nw") tkgrid(variablesFrame, sticky="w") tkgrid(subsetFrame, sticky="w") tkgrid(opsFrame, sticky="w") dialogSuffix(use.tabs=TRUE,grid.buttons=TRUE,tabs=c('dataTab','optionsTab'), tab.names=c("Datos","Opciones")) } bivord <- function(rowvar,colvar,statistics=NULL,tables=FALSE,subset=NULL,pcttable=NULL,data){ res <- list() res[[1]] <- rowvar res[[2]] <- colvar res[[3]] <- statistics res[[4]] <- pcttable i <- 5 .Tabla <- eval(parse(text=paste('xtabs(~',rowvar,'+',colvar, if (!is.null(subset)) {paste(',subset=',subset,'')}, ',data=',data,')'))) res[[i]] <- .Tabla filas <- row(.Tabla) columnas <- col(.Tabla) n <- sum(.Tabla) q <- min(dim(.Tabla)) C <- sum(.Tabla * mapply(function(f, c){sum(.Tabla[(filas > f) & (columnas > c)])}, f = filas, c = columnas)) D <- sum(.Tabla * mapply(function(f, c){sum(.Tabla[(filas > f) & (columnas < c)])}, f = filas, c = columnas)) E.X <- (sum(apply(.Tabla,1,sum)^2)-n)/2 E.Y <- (sum(apply(.Tabla,2,sum)^2)-n)/2 E.XY <- (sum(.Tabla^2)-n)/2 tablares <- matrix(c(C,D,E.X,E.Y,E.XY),nrow=5,ncol=1) i <- i + 1 res[[i]] <- tablares if (tables == TRUE){ if (pcttable == "fila") { .porcentajes <- rowPercents(.Tabla) } if (pcttable == "columna") { .porcentajes <- colPercents(.Tabla) } if (pcttable == "total") { .porcentajes <- totPercents(.Tabla) } i <- i + 1 res[[i]] <- round(.porcentajes,2) } MArow <- ("Gamma" %in% statistics) + ("Tau" %in% statistics)*3 + ("Sommers" %in% statistics)*3 + ("Wilson" %in% statistics) .tablaMA <- array(dim=c(MArow,1)) if (MArow > 0){ j <- 0 if ("Gamma" %in% statistics) { gammaGK <- (C-D)/(C+D) j <- j + 1 .tablaMA[j] <- gammaGK } if ("Tau" %in% statistics) { tau.a <- (C-D)/choose(n,2) tau.b <- (C-D)/sqrt((C+D+E.X-E.XY)*(C+D+E.Y-E.XY)) tau.c <- 2*q*(C-D)/(n^2*(q-1)) j <- j + 1 .tablaMA[j:(j+2)] <- c(tau.a,tau.b,tau.c) j <- j+2 } if ("Sommers" %in% statistics) { sommers.x.y <- (C-D)/(C+D+E.X-E.XY) sommers.y.x <- (C-D)/(C+D+E.Y-E.XY) .sommers <- (C-D)/(C+D+(E.X+E.Y)/2-E.XY) j <- j + 1 .tablaMA[j:(j+2)] <- c(sommers.x.y,sommers.y.x,.sommers) j <- j+2 } if ("Wilson" %in% statistics) { .wilson <- 2*(C-D)/(choose(n,2)-E.XY) j <- j + 1 .tablaMA[j] <- .wilson } i <- i + 1 res[[i]] <- round(.tablaMA,2) } class(res) <- "bivord" res } print.bivord <- function(x,...){ cat("Tabla de contingencia para ",x[[1]], " y ",x[[2]],": \n\n",sep='') print(x[[5]]) cat("\n\n") cat("Descripcion tabla de contingencia: \n\n") tabladesc <- x[[6]] rownames(tabladesc) <- c("Pares concordantes","Pares discordantes", paste("Empates",x[[1]]),paste("Empates",x[[2]]), paste("Empates",x[[1]],"y",x[[2]])) colnames(tabladesc) <- "Valores" print(tabladesc) cat("\n\n") j<-7 if (!is.null(x[[4]])){ msg <- switch(x[[4]], 'total'='Tabla porcentajes respecto al total: ', 'fila'='Tabla porcentajes respecto a marginales fila: ', 'columna'='Tabla porcentajes respecto a marginales columna: ') cat(paste(msg,"\n\n")) print(x[[j]]) cat("\n\n") j <- j + 1 } if (sum(c("Gamma", "Tau", "Sommers", "Wilson") %in% x[[3]]) > 0){ .tablaMA <- as.data.frame(x[[j]]) rownames(.tablaMA) <- c("Gamma de Goodman-Kruskal", c("Tau a de Kendall","Tau b de Kendall","Tau c de Kendall"), c("d de Sommers X/Y", "d de Sommers Y/X","d de Sommers (simetrica)"),"e de Wilson")[ c("Gamma",rep("Tau",3),rep("Sommers",3),"Wilson") %in% x[[3]]] colnames(.tablaMA) <- "Valores" cat("Coeficientes de asociacion: \n\n") print(.tablaMA) cat("\n\n") j <- j+1 } invisible(x) } bivariante.ordinales <- function(){ defecto <- list(fila.inicial=NULL,columna.inicial=NULL, porcentajes.inicial="ninguno", gamma.inicial="0",tau.inicial="0",sommers.inicial="0",wilson.inicial="0", subconjunto.inicial=gettextRcmdr("<all valid cases>"), echo.inicial="0",creahtml.inicial="0",tab.inicial=0) dialog.valores <- getDialog("bivariante.ordinales",defecto) initializeDialog(title=gettextRcmdr("Descripcion bivariante datos ordinales"),use.tabs=TRUE, tabs=c('dataTab','statisticsTab','statistics2Tab','optionsTab')) variablesFrame <- tkframe(dataTab) filaVar <- variableListBox(variablesFrame, c(Factors(),Numeric()), title=gettextRcmdr("Variables (escoja una)"), initialSelection=varPosn(dialog.valores$fila.inicial,"factor")) columnaVar <- variableListBox(variablesFrame, c(Factors(),Numeric()), title=gettextRcmdr("Variables (escoja una)"), initialSelection=varPosn(dialog.valores$columna.inicial,"factor")) subsetBox(dataTab, subset.expression=dialog.valores$subconjunto.inicial) radioButtons(statisticsTab,name = "porcentajes", buttons = c("fila","columna", "total", "ninguno"), values = c("fila", "columna","total", "ninguno"), labels = gettextRcmdr(c("Porcentajes respecto a marginales fila", "Porcentajes respecto a marginales columna","Porcentajes respecto al total", "Ningun porcentaje")), title = gettextRcmdr("Calcular Porcentajes"), initialValue = dialog.valores$porcentajes.inicial) checkBoxes(statistics2Tab,frame="statsFrame",boxes=c("gamma","tau","sommers","wilson"), initialValues=c(dialog.valores$gamma.inicial,dialog.valores$tau.inicial, dialog.valores$sommers.inicial,dialog.valores$wilson.inicial), labels=gettextRcmdr(c("Coef. Gamma de Goodman-Kruskal ","Coefs. Tau de Kendall ","Indices d de Sommers ", "Indice e de Wilson ")), title = gettextRcmdr("Coeficientes de Asociacion")) checkBoxes(optionsTab,frame="opsFrame",boxes=c("echocodigo","creahtml"), initialValues=c(dialog.valores$echo.inicial,dialog.valores$creahtml.inicial), labels=gettextRcmdr(c("Mostrar en pantalla el codigo de R ejecutado ","Generar informe de resultados ")), title = gettextRcmdr("Opciones")) onOK <- function(){ tab <- if(as.character(tkselect(notebook)) == dataTab$ID) 0 else 1 fila <- getSelection(filaVar) columna <- getSelection(columnaVar) if (length(fila) == 0 || length(columna) == 0){ errorCondition(recall=bivariante.ordinales, message=gettextRcmdr("Debe seleccionar dos variables.")) return() } if (fila == columna) { errorCondition(recall=bivariante.ordinales, message=gettextRcmdr("Debe seleccionar dos variables distintas.")) return() } justDoIt(paste("cond1 <- !is.ordered(",paste(ActiveDataSet(),"$",fila,sep=""),")",sep="")) justDoIt(paste("cond2 <- !is.numeric(",paste(ActiveDataSet(),"$",fila,sep=""),")",sep="")) justDoIt(paste("cond3 <- !is.ordered(",paste(ActiveDataSet(),"$",columna,sep=""),")",sep="")) justDoIt(paste("cond4 <- !is.numeric(",paste(ActiveDataSet(),"$",columna,sep=""),")",sep="")) if (cond1 && cond2 || cond3 && cond4){ errorCondition(recall=bivariante.ordinales, message=gettextRcmdr("Escoja variables ordinales")) return() } remove(list=c("cond1","cond2","cond3","cond4"), envir=.GlobalEnv) porcentajes <- as.character(tclvalue(porcentajesVariable)) gammaval <- tclvalue(gammaVariable) tauval <- tclvalue(tauVariable) sommersval <- tclvalue(sommersVariable) wilsonval <- tclvalue(wilsonVariable) subconjunto <- tclvalue(subsetVariable) echocodigo <- tclvalue(echocodigoVariable) creahtml <- tclvalue(creahtmlVariable) putDialog("bivariante.ordinales",list(fila.inicial=fila,columna.inicial=columna, porcentajes.inicial=porcentajes, gamma.inicial=gammaval,tau.inicial=tauval,sommers.inicial=sommersval, wilson.inicial=wilsonval,subconjunto.inicial=subconjunto, echo.inicial=echocodigo,creahtml.inicial=creahtml,tab.inicial=tab)) selec <- as.numeric(gammaval) + as.numeric(tauval)*3 + as.numeric(sommersval)*3 + as.numeric(wilsonval) if (selec>0) stats <- paste("c(", paste(c('"Gamma"', '"Tau"', '"Sommers"', '"Wilson"') [c(gammaval,tauval,sommersval,wilsonval) == 1], collapse=", "), ")", sep="") else stats <- 'NULL' tabs <- if (porcentajes !='ninguno') TRUE else FALSE if (trim.blanks(subconjunto) == gettextRcmdr("<all valid cases>")) instruccion1 <- paste(".indices.bo <- bivord(rowvar='",fila, "', colvar='",columna,"', statistics=",stats, ", tables=",tabs, if(porcentajes!="ninguno"){paste(", pcttable='",porcentajes,"'",sep='')}, ", data='",ActiveDataSet(),"')", sep="") else { instruccion1 <- paste(".indices.bo <- bivord(rowvar='",fila, "', colvar='",columna, "', statistics=", stats, ", tables=",tabs, if(porcentajes!="ninguno"){paste(", pcttable='",porcentajes,sep='')}, "', subset='",subconjunto, "', data='",ActiveDataSet(),"')", sep="") } justDoIt(instruccion1) if (echocodigo == 1) { logger(instruccion1) } doItAndPrint(paste(".indices.bo " y ", columna, sep="")) if (creahtml == 1) { if (!file.exists("Informe de Resultados.html")) .archivo <- HTMLInitFile(file.path(getwd()), "Informe de Resultados", BackGroundColor=" else .archivo <- file.path(getwd(), "Informe de Resultados.html") titulo <- paste("Descripcion bivariante de datos ordinales: ",fila, " y ", columna, sep="") HTML(as.title(titulo),file=.archivo) HTML('Tabla de contigencia', file=.archivo) HTML(.indices.bo[[5]], file=.archivo) HTML('Descripcion tabla de contigencia', file=.archivo) tabladesc <- .indices.bo[[6]] rownames(tabladesc) <- c("Pares concordantes","Pares discordantes", paste("Empates",.indices.bo[[1]]),paste("Empates",.indices.bo[[2]]), paste("Empates",.indices.bo[[1]],"y",.indices.bo[[2]])) colnames(tabladesc) <- "Valores" HTML(tabladesc, file=.archivo) j <- 7 if (tabs == TRUE){ msg <- switch(.indices.bo[[4]], 'total'='Tabla porcentajes respecto al total: ', 'fila'='Tabla porcentajes respecto a marginales fila: ', 'columna'='Tabla porcentajes respecto a marginales columna: ') HTML(msg, file=.archivo) HTML(.indices.bo[[j]], file=.archivo) j <- j + 1 } if ( selec>0 ){ .TablaRes <- as.data.frame(.indices.bo[[j]]) rownames(.TablaRes) <- c("Gamma", c("Tau a","Tau b","Tau c"),c("d Sommers X/Y","d Sommers Y/X", "d Sommers (simetrica)"),"e Wilson")[ c("Gamma", rep("Tau",3), rep("Sommers",3), "Wilson") %in% .indices.bo[[3]]] colnames(.TablaRes) <- "Valores" HTML("Coeficientes de asociacion: ", file=.archivo) HTML(.TablaRes, file=.archivo) HTMLhr(file = .archivo) j <- j+1 } } remove(.indices.bo, envir=.GlobalEnv) closeDialog() tkfocus(CommanderWindow()) } OKCancelHelp(helpSubject="xtabs",reset="bivariante.ordinales",apply="bivariante.ordinales") tkgrid(getFrame(filaVar), labelRcmdr(variablesFrame, text=" "), getFrame(columnaVar), sticky="nw") tkgrid(variablesFrame, sticky="w") tkgrid(subsetFrame, sticky="w") tkgrid(porcentajesFrame, sticky="w") tkgrid(statsFrame, sticky="w") tkgrid(opsFrame, sticky="w") dialogSuffix(use.tabs=TRUE,grid.buttons=TRUE,tabs=c('dataTab','statisticsTab', 'statistics2Tab','optionsTab'), tab.names=c("Datos","Tablas","Estadisticos","Opciones")) } dispordfun <- function(rowvar,colvar,subset=NULL,data){ .Tabla <- eval(parse(text=paste('xtabs(~',rowvar,'+',colvar, if (!is.null(subset)) {paste(',subset=',subset,'')}, ',data=',data,')'))) def.par <- par(no.readonly = TRUE) sup <- max(rowSums(.Tabla),colSums(.Tabla)) rangox <- eval(parse(text=paste('c(min(as.numeric(',data,'$',rowvar,'),na.rm=TRUE), max(as.numeric(',data,'$',rowvar,'),na.rm=TRUE))',sep=""))) rangoy <- eval(parse(text=paste('c(min(as.numeric(',data,'$',colvar,'),na.rm=TRUE), max(as.numeric(',data,'$',colvar,'),na.rm=TRUE))',sep=""))) nf <- layout(matrix(c(2,0,1,3),2,2,byrow=TRUE), c(3,1), c(1,3), TRUE) par(mar=c(5,4,3,3)) eval(parse(text=paste('plot(as.numeric(',data,'$',rowvar,'), as.numeric(',data,'$',colvar,'),xlim=rangox,ylim=rangoy, ,xlab="',rowvar,'",ylab="',colvar,'")',sep=""))) z <- eval(parse(text=paste('with(',data,',merge(data.frame(',rowvar,',', colvar,'),melt(table(',rowvar,',',colvar,')),sort =F)$value)',sep=""))) z <- eval(parse(text=paste('1.5*z/length(',data,'$',rowvar,')',sep=""))) eval(parse(text=paste("symbols(na.omit(data.frame(",data,"$",rowvar,",",data,"$",colvar,")), circles=z,inches=F, bg='grey',fg=NA,add=T)",sep=""))) ok <- eval(parse(text=paste('is.finite(',data,'$',rowvar,') & is.finite(',data,'$',colvar,')',sep=""))) if (any(ok)) eval(parse(text=paste('lines(stats::lowess(',data,'$',rowvar,'[ok],',data,'$',colvar,'[ok], f = 2/3, iter = 3), col = "red")',sep=""))) box() par(mar=c(0,3,1,1)) eval(parse(text=paste('barplot(table(',data,'$',rowvar,'),axes=FALSE,ylim=c(0,', sup,'),space=0.1,col="grey")',sep=""))) eval(parse(text=paste('title("Diagrama de puntos para ',rowvar,' y ',colvar,'")',sep=""))) par(mar=c(3,0,1,1)) eval(parse(text=paste('barplot(table(',data,'$',colvar,'),axes=FALSE,xlim=c(0,', sup,'),space=0.1,horiz=TRUE,col="grey")',sep=""))) par(def.par) } dispersion.ordinales <- function(){ defecto <- list(fila.inicial=NULL,columna.inicial=NULL, subconjunto.inicial=gettextRcmdr("<all valid cases>"), echo.inicial="0",creahtml.inicial="0",tab.inicial=0) dialog.valores <- getDialog("dispersion.ordinales",defecto) initializeDialog(title=gettextRcmdr("Diagrama de puntos para datos ordinales"),use.tabs=TRUE, tabs=c('dataTab','optionsTab')) variablesFrame <- tkframe(dataTab) filaVar <- variableListBox(variablesFrame, Factors(), title=gettextRcmdr("Variables (escoja una)"), initialSelection=varPosn(dialog.valores$fila.inicial,"factor")) columnaVar <- variableListBox(variablesFrame, Factors(), title=gettextRcmdr("Variables (escoja una)"), initialSelection=varPosn(dialog.valores$columna.inicial,"factor")) subsetBox(dataTab, subset.expression=dialog.valores$subconjunto.inicial) checkBoxes(optionsTab,frame="opsFrame",boxes=c("echocodigo","creahtml"), initialValues=c(dialog.valores$echo.inicial,dialog.valores$creahtml.inicial), labels=gettextRcmdr(c("Mostrar en pantalla el codigo de R ejecutado ","Generar informe de resultados ")), title = gettextRcmdr("Opciones")) onOK <- function(){ tab <- if(as.character(tkselect(notebook)) == dataTab$ID) 0 else 1 fila <- getSelection(filaVar) columna <- getSelection(columnaVar) if (length(fila) == 0 || length(columna) == 0){ errorCondition(recall=barras.agrupadas, message=gettextRcmdr("Debe seleccionar dos variables.")) return() } if (fila == columna) { errorCondition(recall=barras.agrupadas, message=gettextRcmdr("Debe seleccionar dos variables distintas.")) return() } justDoIt(paste("cond1 <- !is.ordered(",paste(ActiveDataSet(),"$",fila,sep=""),")",sep="")) justDoIt(paste("cond2 <- !is.ordered(",paste(ActiveDataSet(),"$",columna,sep=""),")",sep="")) if (cond1 || cond2){ errorCondition(recall=dispersion.ordinales, message=gettextRcmdr("Escoja variables ordinales")) return() } remove(list=c("cond1","cond2"), envir=.GlobalEnv) subconjunto <- tclvalue(subsetVariable) echocodigo <- tclvalue(echocodigoVariable) creahtml <- tclvalue(creahtmlVariable) putDialog("dispersion.ordinales",list(fila.inicial=fila,columna.inicial=columna, subconjunto.inicial=subconjunto, echo.inicial=echocodigo,creahtml.inicial=creahtml,tab.inicial=tab)) if (trim.blanks(subconjunto) == gettextRcmdr("<all valid cases>")) instruccion1 <- paste("dispordfun(rowvar='",fila, "', colvar='",columna,"', data='",ActiveDataSet(),"')", sep="") else { instruccion1 <- paste("dispordfun(rowvar='",fila, "', colvar='",columna,"', subset='",subconjunto, "', data='",ActiveDataSet(),"')", sep="") } justDoIt(instruccion1) if (echocodigo == 1) { logger(instruccion1) } if (creahtml == 1) { if (!file.exists("Informe de Resultados.html")) .archivo <- HTMLInitFile(file.path(getwd()), "Informe de Resultados", BackGroundColor=" else .archivo <- file.path(getwd(), "Informe de Resultados.html") titulo <- paste("Diagrama de puntos para datos ordinales: ",fila, " y ", columna, sep="") HTML(as.title(titulo),file=.archivo) nombre.archivo <- paste("DiagramaPuntosOrdinalesR",gsub(":","",substr(Sys.time(),12,19)), ".jpg",sep="") dev.print(jpeg, filename=paste(getwd(),"/",nombre.archivo,sep=""), width=500, height=500) HTMLInsertGraph(nombre.archivo,file=.archivo,append=TRUE) HTMLhr(file = .archivo) } closeDialog() tkfocus(CommanderWindow()) } OKCancelHelp(helpSubject="plot",reset="dispersion.ordinales",apply="dispersion.ordinales") tkgrid(getFrame(filaVar), labelRcmdr(variablesFrame, text=" "), getFrame(columnaVar), sticky="nw") tkgrid(variablesFrame, sticky="w") tkgrid(subsetFrame, sticky="w") tkgrid(opsFrame, sticky="w") dialogSuffix(use.tabs=TRUE,grid.buttons=TRUE,tabs=c('dataTab','optionsTab'), tab.names=c("Datos","Opciones")) } bivnum <- function(datos,variables,stats,subconjunto=NULL){ if (is.null(subconjunto)) datos <- eval(parse(text='datos[variables]')) else datos <- eval(parse(text=paste('subset(datos,subset=',subconjunto,')[variables]'))) res <- list() res[[1]] <- variables res[[2]] <- stats res[[3]] <- subconjunto numfilas <- sum(c("Variancia","Pearson","","Spearman","Kendall") %in% stats) + ("CoefDeterm" %in% stats)* sum(c("Pearson","","Spearman","Kendall") %in% stats) .tablaAsoc <- as.data.frame(matrix(nrow=numfilas,ncol=1)) j <- 0 if ("Covariancia" %in% stats) { covariancia <- cov(datos,use='na.or.complete')[1,2] j <- j + 1 .tablaAsoc[j,]<-covariancia } if ("Pearson" %in% stats) { correlacion <- cor(datos,method='pearson',use='na.or.complete')[1,2] j <- j + 1 .tablaAsoc[j,]<-correlacion if ("CoefDeterm" %in% stats) { R2pearson <- correlacion^2 j <- j + 1 .tablaAsoc[j,]<-R2pearson } } if ("Spearman" %in% stats) { correlacion <- cor(datos,method='spearman',use='na.or.complete')[1,2] j <- j + 1 .tablaAsoc[j,]<-correlacion if ("CoefDeterm" %in% stats) { R2spearman <- correlacion^2 j <- j + 1 .tablaAsoc[j,]<-R2spearman } } if ("Kendall" %in% stats) { correlacion <- cor(datos,method='kendall',use='na.or.complete')[1,2] j <- j + 1 .tablaAsoc[j,]<-correlacion if ("CoefDeterm" %in% stats) { R2kendall <- correlacion^2 j <- j + 1 .tablaAsoc[j,]<-R2kendall } } res[[4]] <- .tablaAsoc class(res) <- "bivnum" res } print.bivnum <- function(x,...){ cat("Coeficientes de asociacion para ",x[[1]][1], " y ",x[[1]][2],": \n\n",sep='') .tabla <- as.data.frame(round(x[[4]],3)) rownames(.tabla) <- c(if ("Covariancia"%in% x[[2]]) "Covariancia",if ("Pearson"%in% x[[2]]) "r de Pearson", if ("Pearson"%in% x[[2]] & "CoefDeterm" %in% x[[2]])"r Cuadrado (Pearson)", if ("Spearman"%in% x[[2]]) "r de Spearman", if ("Spearman"%in% x[[2]] & "CoefDeterm" %in% x[[2]])"r Cuadrado (Spearman)", if ("Kendall"%in% x[[2]]) "tau de Kendall", if ("Kendall"%in% x[[2]] & "CoefDeterm" %in% x[[2]]) "r Cuadrado (Kendall)") colnames(.tabla) <- "Valores" print(.tabla) cat("\n\n") invisible(x) } bivariante.numericas <- function(){ defecto <- list(var1.inicial=NULL,var2.inicial=NULL,Cov.inicial="0", pearson.inicial="0",spearman.inicial="0",kendall.inicial="0",determ.inicial="0", subconjunto.inicial=gettextRcmdr("<all valid cases>"), echo.inicial="0",creahtml.inicial="0",tab.inicial=0) dialog.valores <- getDialog("bivariante.numericas",defecto) initializeDialog(title=gettextRcmdr("Descripcion bivariante datos cuantitativos"),use.tabs=TRUE, tabs=c('dataTab','statisticsTab','optionsTab')) variablesFrame <- tkframe(dataTab) variable1Var <- variableListBox(variablesFrame, Numeric(), title=gettextRcmdr("Variables (escoja una)"), initialSelection=varPosn(dialog.valores$var1.inicial,"numeric")) variable2Var <- variableListBox(variablesFrame, Numeric(), title=gettextRcmdr("Variables (escoja una)"), initialSelection=varPosn(dialog.valores$var2.inicial,"numeric")) subsetBox(dataTab, subset.expression=dialog.valores$subconjunto.inicial) checkBoxes(statisticsTab,frame="statsFrame",boxes=c("Cov","pearson","spearman","kendall","determ"), initialValues=c(dialog.valores$Cov.inicial,dialog.valores$pearson.inicial, dialog.valores$spearman.inicial,dialog.valores$kendall.inicial, dialog.valores$determ.inicial), labels=gettextRcmdr(c("Coeficiente de covariancia ","Coeficiente de correlacion de Pearson ", "Coeficiente de correlacion de Spearman ","Coeficiente de correlacion de Kendall ", "Coeficiente de determinacion ")), title = gettextRcmdr("Coeficientes de Asociacion")) checkBoxes(optionsTab,frame="opsFrame",boxes=c("echocodigo","creahtml"), initialValues=c(dialog.valores$echo.inicial,dialog.valores$creahtml.inicial), labels=gettextRcmdr(c("Mostrar en pantalla el codigo de R ejecutado ","Generar informe de resultados ")), title = gettextRcmdr("Opciones")) onOK <- function(){ tab <- if(as.character(tkselect(notebook)) == dataTab$ID) 0 else 1 var1 <- getSelection(variable1Var) var2 <- getSelection(variable2Var) if (length(var1) == 0 || length(var2) == 0){ errorCondition(recall=bivariante.numericas, message=gettextRcmdr("Debe seleccionar dos variables.")) return() } if (var1 == var2) { errorCondition(recall=bivariante.numericas, message=gettextRcmdr("Debe seleccionar dos variables distintas.")) return() } Covval <- tclvalue(CovVariable) pearsonval <- tclvalue(pearsonVariable) spearmanval <- tclvalue(spearmanVariable) kendallval <- tclvalue(kendallVariable) determval <- tclvalue(determVariable) subconjunto <- tclvalue(subsetVariable) echocodigo <- tclvalue(echocodigoVariable) selec <- as.numeric(Covval) + as.numeric(pearsonval) + as.numeric(spearmanval) + as.numeric(kendallval) + as.numeric(determval)*(as.numeric(pearsonval) + as.numeric(spearmanval) +as.numeric(kendallval)) if (selec == 0){ errorCondition(recall=bivariante.numericas, message=gettextRcmdr("Debe escoger algun indicador.")) return() } creahtml <- tclvalue(creahtmlVariable) putDialog("bivariante.numericas",list(var1.inicial=var1,var2.inicial=var2, Cov.inicial=Covval, pearson.inicial=pearsonval,spearman.inicial=spearmanval, kendall.inicial=kendallval,determ.inicial=determval, subconjunto.inicial=subconjunto, echo.inicial=echocodigo,creahtml.inicial=creahtml,tab.inicial=tab)) vars <- paste("c(", paste('"', c(var1,var2), '"', collapse=", ", sep=""), ")", sep="") stats <- paste("c(", paste(c('"Covariancia"','"Pearson"','"Spearman"','"Kendall"','"CoefDeterm"') [c(Covval,pearsonval,spearmanval,kendallval,determval) == 1], collapse=", "), ")", sep="") if (trim.blanks(subconjunto) == gettextRcmdr("<all valid cases>")) instruccion1 <- paste(".indices.bn <- bivnum(datos=",ActiveDataSet(),",variables=",vars,",stats=", stats, ")", sep="") else { instruccion1 <- paste(".indices.bn <- bivnum(datos=",ActiveDataSet(),",variables=c(",vars,"),stats=", stats, ", subconjunto='",subconjunto,"')", sep="") } logger(instruccion1) justDoIt(instruccion1) if (echocodigo == 1) { logger(instruccion1) } doItAndPrint(paste(".indices.bn " y ", var2, sep="")) if (creahtml == 1) { if (!file.exists("Informe de Resultados.html")) .archivo <- HTMLInitFile(file.path(getwd()), "Informe de Resultados", BackGroundColor=" else .archivo <- file.path(getwd(), "Informe de Resultados.html") titulo <- paste("Descripcion bivariante de datos cuantitativos: ",var1, " y ", var2, sep="") HTML(as.title(titulo),file=.archivo) .TablaRes <- as.data.frame(round(.indices.bn[[4]],3)) rownames(.TablaRes) <- c(if ("Covariancia"%in% .indices.bn[[2]]) "Covariancia",if ("Pearson"%in% .indices.bn[[2]]) "r de Pearson", if ("Pearson"%in% .indices.bn[[2]] & "CoefDeterm" %in% .indices.bn[[2]])"r Cuadrado (Pearson)", if ("Spearman"%in% .indices.bn[[2]]) "r de Spearman", if ("Spearman"%in% .indices.bn[[2]] & "CoefDeterm" %in% .indices.bn[[2]])"r Cuadrado (Spearman)", if ("Kendall"%in%.indices.bn[[2]]) "tau de Kendall", if ("Kendall"%in% .indices.bn[[2]] & "CoefDeterm" %in% .indices.bn[[2]]) "r Cuadrado (Kendall)") colnames(.TablaRes) <- "Valores" HTML("Coeficientes de asociacion: ", file=.archivo) HTML(.TablaRes, file=.archivo) HTMLhr(file = .archivo) HTMLhr(file = .archivo) } remove(.indices.bn, envir=.GlobalEnv) closeDialog() tkfocus(CommanderWindow()) } OKCancelHelp(helpSubject="cov",reset="bivariante.numericas",apply="bivariante.numericas") tkgrid(getFrame(variable1Var), labelRcmdr(variablesFrame, text=" "), getFrame(variable2Var), sticky="nw") tkgrid(variablesFrame, sticky="w") tkgrid(subsetFrame, sticky="w") tkgrid(statsFrame, sticky="w") tkgrid(opsFrame, sticky="w") dialogSuffix(use.tabs=TRUE,grid.buttons=TRUE,tabs=c('dataTab','statisticsTab','optionsTab'), tab.names=c("Datos","Estadisticos","Opciones")) } dispnumfun <- function(datos,variables,subconjunto=NULL){ var1 <- variables[1] var2 <- variables[2] def.par <- par(no.readonly = TRUE) if (is.null(subconjunto)) datos <- eval(parse(text='datos[variables]')) else datos <- eval(parse(text=paste('subset(datos,subset=',subconjunto,')[variables]'))) xhist <- hist(datos[,1],plot=FALSE) yhist <- hist(datos[,2],plot=FALSE) sup <- max(c(xhist$counts,yhist$counts)) rangox <- c(min(datos[,1],na.rm=TRUE),max(datos[,1],na.rm=TRUE)) rangoy <- c(min(datos[,2],na.rm=TRUE),max(datos[,2],na.rm=TRUE)) nf <- layout(matrix(c(2,0,1,3),2,2,byrow=TRUE), c(3,1), c(1,3), TRUE) par(mar=c(5,4,3,3)) plot(datos[,1],datos[,2],xlim=rangox,ylim=rangoy,xlab=var1,ylab=var2) box() par(mar=c(0,3,1,1)) barplot(xhist$counts,axes=FALSE,ylim=c(0, sup),space=0,col='grey') title(paste("Diagrama de dispersion para ",var1," y ",var2,sep="")) par(mar=c(3,0,1,1)) barplot(yhist$counts,axes=FALSE,xlim=c(0, sup),space=0,col='grey',horiz=TRUE) par(def.par) } dispersion.numericas <- function(){ defecto <- list(var1.inicial=NULL,var2.inicial=NULL,subconjunto.inicial=gettextRcmdr("<all valid cases>"), echo.inicial="0",creahtml.inicial="0",tab.inicial=0) dialog.valores <- getDialog("dispersion.numericas",defecto) initializeDialog(title=gettextRcmdr("Diagrama de dispersion para variables cuantitativas"),use.tabs=TRUE, tabs=c('dataTab','optionsTab')) variablesFrame <- tkframe(dataTab) variable1Var <- variableListBox(variablesFrame, Numeric(), title=gettextRcmdr("Variables (escoja una)"), initialSelection=varPosn(dialog.valores$var1.inicial,"numeric")) variable2Var <- variableListBox(variablesFrame, Numeric(), title=gettextRcmdr("Variables (escoja una)"), initialSelection=varPosn(dialog.valores$var2.inicial,"numeric")) subsetBox(dataTab, subset.expression=dialog.valores$subconjunto.inicial) checkBoxes(optionsTab,frame="opsFrame",boxes=c("echocodigo","creahtml"), initialValues=c(dialog.valores$echo.inicial,dialog.valores$creahtml.inicial), labels=gettextRcmdr(c("Mostrar en pantalla el codigo de R ejecutado ","Generar informe de resultados ")), title = gettextRcmdr("Opciones")) onOK <- function(){ tab <- if(as.character(tkselect(notebook)) == dataTab$ID) 0 else 1 var1 <- getSelection(variable1Var) var2 <- getSelection(variable2Var) if (length(var1) == 0 || length(var2) == 0){ errorCondition(recall=dispersion.numericas, message=gettextRcmdr("Debe seleccionar dos variables.")) return() } if (var1 == var2) { errorCondition(recall=dispersion.numericas, message=gettextRcmdr("Debe seleccionar dos variables distintas.")) return() } subconjunto <- tclvalue(subsetVariable) echocodigo <- tclvalue(echocodigoVariable) creahtml <- tclvalue(creahtmlVariable) putDialog("dispersion.numericas",list(var1.inicial=var1,var2.inicial=var2, subconjunto.inicial=subconjunto, echo.inicial=echocodigo,creahtml.inicial=creahtml,tab.inicial=tab)) vars <- paste("c(", paste('"', c(var1,var2), '"', collapse=", ", sep=""), ")", sep="") if (trim.blanks(subconjunto) == gettextRcmdr("<all valid cases>")) instruccion1 <- paste("dispnumfun(datos=",ActiveDataSet(),",variables=",vars,")", sep="") else { instruccion1 <- paste("dispnumfun(datos=",ActiveDataSet(),",variables=c(",vars,"), subconjunto='", subconjunto,"')", sep="") } justDoIt(instruccion1) if (echocodigo == 1) { logger(instruccion1) } if (creahtml == 1) { if (!file.exists("Informe de Resultados.html")) .archivo <- HTMLInitFile(file.path(getwd()), "Informe de Resultados", BackGroundColor=" else .archivo <- file.path(getwd(), "Informe de Resultados.html") titulo <- paste("Diagrama de puntos para datos cuantitativos: ",var1, " y ", var2, sep="") HTML(as.title(titulo),file=.archivo) nombre.archivo <- paste("DiagramaDispersionR",gsub(":","",substr(Sys.time(),12,19)), ".jpg",sep="") dev.print(jpeg, filename=paste(getwd(),"/",nombre.archivo,sep=""), width=500, height=500) HTMLInsertGraph(nombre.archivo,file=.archivo,append=TRUE) HTMLhr(file = .archivo) } closeDialog() tkfocus(CommanderWindow()) } OKCancelHelp(helpSubject="plot",reset="dispersion.numericas",apply="dispersion.numericas") tkgrid(getFrame(variable1Var), labelRcmdr(variablesFrame, text=" "), getFrame(variable2Var), sticky="nw") tkgrid(variablesFrame, sticky="w") tkgrid(subsetFrame, sticky="w") tkgrid(opsFrame, sticky="w") dialogSuffix(use.tabs=TRUE,grid.buttons=TRUE,tabs=c('dataTab','optionsTab'), tab.names=c("Datos","Opciones")) } winvar <- function(x,tr=.2,na.rm=FALSE){ if(na.rm)x<-x[!is.na(x)] y<-sort(x) n<-length(x) ibot<-floor(tr*n)+1 itop<-length(x)-ibot+1 xbot<-y[ibot] xtop<-y[itop] y<-ifelse(y<=xbot,xbot,y) y<-ifelse(y>=xtop,xtop,y) winvar<-var(y) winvar } yuen.test <- function(x,y,tr=.2,alpha=.05){ if(tr==.5)stop("No se puede utilizar tr=0.5") if(tr>.25)print("Aviso: con tr>.25 el control sobre el error tipo I puede ser insuficiente") x<-x[!is.na(x)] y<-y[!is.na(y)] h1<-length(x)-2*floor(tr*length(x)) h2<-length(y)-2*floor(tr*length(y)) q1<-(length(x)-1)*winvar(x,tr)/(h1*(h1-1)) q2<-(length(y)-1)*winvar(y,tr)/(h2*(h2-1)) df<-(q1+q2)^2/((q1^2/(h1-1))+(q2^2/(h2-1))) crit<-qt(1-alpha/2,df) dif<-mean(x,tr)-mean(y,tr) low<-dif-crit*sqrt(q1+q2) up<-dif+crit*sqrt(q1+q2) test<-abs(dif/sqrt(q1+q2)) pval<-2*(1-pt(test,df)) res <- list(ci=c(low,up),p.value=pval,dif=dif,se=sqrt(q1+q2), teststat=test,crit=crit,gl=df,ic=1-alpha,rec=tr) class(res)<-"yuen" res } print.yuen <- function (x,digits = max(4,getOption("digits") - 4),...) { cat("\n") cat("\t",'Prueba t de Yuen-Welch',"\n") cat("\n") cat(paste("T de Yuen = ",round(x$teststat,4),", gl = ",round(x$gl,2),", valor p = ", round(x$p.value,4),sep=""),"\n") cat("Hipotesis Alternativa: Diferencia entre medias recortadas distinta de 0","\n") cat(paste("Intervalo de confianza ",x$ic*100,"%: ",sep=""),"\n") cat("\t",round(x$ci,4),"\n") cat(paste("Estimacion puntual de la diferencia de medias recortadas al ",x$rec*100,"%: ",sep=""),"\n") cat("\t",round(x$dif,4),"\n") cat("\n\n") invisible(x) } yuenWelch.tTest <- function(){ defecto <- list(grupo.inicial=NULL,var.inicial=NULL,trim.inicial="0.2",confint.inicial=".95", echo.inicial="0",creahtml.inicial="0",tab.inicial=0) dialog.valores <- getDialog("yuenWelch.tTest",defecto) initializeDialog(title=gettextRcmdr("Prueba t de Yuen-Welch"),use.tabs=TRUE,tabs=c('dataTab', 'statisticsTab','optionsTab')) variablesFrame <- tkframe(dataTab) grupoVar <- variableListBox(variablesFrame, Factors(), title=gettextRcmdr("Grupos (escoja una)"), initialSelection=varPosn(dialog.valores$grupo.inicial,"factor")) variableVar <- variableListBox(variablesFrame, Numeric(), title=gettextRcmdr("Variables (escoja una)"), initialSelection=varPosn(dialog.valores$var.inicial,"numeric")) checkBoxes(optionsTab,frame="opsFrame",boxes=c("echocodigo","creahtml"), initialValues=c(dialog.valores$echo.inicial,dialog.valores$creahtml.inicial), labels=gettextRcmdr(c("Mostrar en pantalla el codigo de R ejecutado ","Generar informe de resultados ")), title = gettextRcmdr("Opciones")) onOK <- function(){ tab <- if(as.character(tkselect(notebook)) == dataTab$ID) 0 else 1 grupo <- getSelection(grupoVar) if (length(grupo) == 0) { errorCondition(recall=yuenWelch.tTest, message=gettextRcmdr("Debe seleccionar una variable de agrupacion.")) return() } varresp <- getSelection(variableVar) if (length(varresp) == 0) { errorCondition(recall=yuenWelch.tTest, message=gettextRcmdr("Debe seleccionar una variable de respuesta.")) return() } echocodigo <- tclvalue(echocodigoVariable) creahtml <- tclvalue(creahtmlVariable) rec <- as.numeric(tclvalue(trimVariable)) if (rec > 1 | rec < 0) { rec <- 0.2 Message(message=gettextRcmdr("Proporcion de recorte invalida, se utilizara valor por defecto."), type="warning") } ic <- as.numeric(tclvalue(ConfIntVariable)) if ( ic < .0 || ic > 1. || !is.numeric(ic) ) { ic <- 0.95 Message(message=gettextRcmdr("Nivel de confianza invalido, se utilizara valor por defecto."), type="warning") } putDialog("yuenWelch.tTest",list(grupo.inicial=grupo,var.inicial=varresp, trim.inicial=rec,confint.inicial=ic, echo.inicial=echocodigo,creahtml.inicial=creahtml,tab.inicial=tab)) if (creahtml == 1) { if (!file.exists("Informe de Resultados.html")) .archivo <- HTMLInitFile(file.path(getwd()), "Informe de Resultados", BackGroundColor=" else .archivo <- file.path(getwd(), "Informe de Resultados.html") titulo <- paste("Prueba t de Yuen-Welch: ",varresp, " por ", grupo, sep="") HTML(as.title(titulo),file=.archivo) } closeDialog() instruccion1 <- paste("x <-", ActiveDataSet(),"$",varresp,"[",ActiveDataSet(),"$",grupo, "==levels(",ActiveDataSet(),"$",grupo,")[1]]",sep="") justDoIt(instruccion1) instruccion2 <- paste("y <- ", ActiveDataSet(),"$",varresp,"[",ActiveDataSet(),"$",grupo, "==levels(",ActiveDataSet(),"$",grupo,")[2]]",sep="") justDoIt(instruccion2) instruccion3 <- paste("ywttest <- yuen.test(x,y,tr=",rec,",alpha=1-",ic,")",sep="") justDoIt(instruccion3) if (echocodigo == 1) { logger(instruccion1) logger(instruccion2) logger(instruccion3) } doItAndPrint(paste("ywttest if (creahtml == 1) { HTML('Prueba t de Yuen-Welch', file=.archivo) HTML(paste("datos: ",ActiveDataSet(),"$",varresp," por ",ActiveDataSet(),"$",grupo,sep=""), file=.archivo) HTML(paste("T de Yuen = ",round(ywttest[[5]],4),", gl = ",round(ywttest[[7]],2),", valor p = ", round(ywttest[[2]],4),sep=""), file=.archivo) HTML("Hipotesis Alternativa: Diferencia entre medias recortadas distinta de 0", file=.archivo) HTML(paste("Intervalo de confianza ",ic*100,"%: ",sep=""), file=.archivo) HTML(round(ywttest[[1]],4), file=.archivo) HTML(paste("Estimacion puntual de la diferencia de medias recortadas al ",rec*100,"%: ",sep=""), file=.archivo) HTML(round(ywttest[[3]],4), file=.archivo) HTMLhr(file = .archivo) } remove(list=c('x','y','ywttest'), envir=.GlobalEnv) tkfocus(CommanderWindow()) } OKCancelHelp(helpSubject="t.test",reset="yuenWelch.tTest",apply="yuenWelch.tTest") tkgrid(getFrame(grupoVar), labelRcmdr(variablesFrame, text=" "), getFrame(variableVar), sticky="nw") tkgrid(variablesFrame, sticky="w") groupsLabel(groupsBox=grupoVar,dataTab) trimFrame <- tkframe(statisticsTab) trimVariable <- tclVar(dialog.valores$trim.inicial) trimField <- ttkentry(trimFrame, width="8", textvariable=trimVariable) tkgrid(labelRcmdr(trimFrame,text=gettextRcmdr("Proporcion datos recortados = "),font="RcmdrTitleFont"), trimField,sticky="w") ConfIntFrame <- tkframe(statisticsTab) ConfIntVariable <- tclVar(dialog.valores$confint.inicial) ConfIntField <- ttkentry(ConfIntFrame, width="8", textvariable=ConfIntVariable) tkgrid(labelRcmdr(ConfIntFrame,text=gettextRcmdr("Nivel de Confianza = "),font="RcmdrTitleFont"), ConfIntField,sticky="w") tkgrid(trimFrame, sticky="nw") tkgrid(ConfIntFrame, sticky="nw") tkgrid(opsFrame, sticky="w") dialogSuffix(use.tabs=TRUE,grid.buttons=TRUE,tabs=c('dataTab','statisticsTab','optionsTab'), tab.names=c("Datos","Estadisticos","Opciones")) } UMWfun <- function(y,x,alternativa,conf.int,prueba,data){ res <- list() res[[1]] <- x res[[2]] <- y res[[3]] <- data i <- 4 meds <- eval(parse(text=paste("tapply(",data,"$", y,",",data,"$",x, ", median, na.rm=TRUE)", sep=""))) res[[4]] <- meds g1 <- eval(parse(text=paste("with(",data,",",y,"[as.numeric(factor(",x,"))==1])",sep=""))) g2 <- eval(parse(text=paste("with(",data,",",y,"[as.numeric(factor(",x,"))==2])",sep=""))) rangos <- rank(c(na.omit(g1),na.omit(g2))) R1 <- sum(rangos[1:length(g1)]) R2 <- sum(rangos[(length(na.omit(g1))+1):length(rangos)]) Rangos <- eval(parse(text=paste("matrix(round(c(R1/length(na.omit(g1)),R1,R2/length(na.omit(g2)),R2),2), nrow=2,byrow=T,dimnames=list(levels(",data,"$",x,"),c('Rango promedio','Suma Rangos')))",sep=""))) res[[5]] <- Rangos if (prueba == "default"){ UMW <- eval(parse(text=paste("wilcox.test(",y, " ~ ",x, ', alternative="', alternativa, '",conf.int=TRUE,conf.level=',conf.int,",data=",data, ")", sep=""))) } if (prueba == "normal"){ UMW <- eval(parse(text=paste("wilcox.test(",y, " ~ ",x, ', alternative="', alternativa, '",conf.int=TRUE,conf.level=',conf.int,",data=",data, "exact=FALSE, correct=FALSE)",sep=""))) } if (prueba == "correct"){ UMW <- eval(parse(text=paste("wilcox.test(",y, " ~ ",x, ', alternative="', alternativa, '",conf.int=TRUE,conf.level=',conf.int,",data=",data, "exact=FALSE, correct=TRUE)",sep=""))) } else { UMW <- eval(parse(text=paste("wilcox.test(",y, " ~ ",x, ", alternative='", alternativa, "', exact=", prueba=="exact", ", correct=", prueba=="correct",", conf.int=TRUE, conf.level=",conf.int,", data=", data, ")", sep=""))) } res[[6]] <- UMW class(res) <- "UMW" res } print.UMW <- function (x,digits = max(4,getOption("digits") - 4),...) { cat('Medianas para',x[[2]],"segun",x[[1]],"\n") cat("\n") print(x[[4]]) cat("\n\n") cat("Resumen descriptivo por rangos \n") cat("\n") print(x[[5]]) cat("\n\n") cat('Prueba U de Mann-Whitney para',x[[2]],"por",x[[1]],"\n") cat("\n") print(x[[6]]) cat("\n\n") invisible(x) } U.Mann.Whitney <- function(){ defecto <- list(grupo.inicial=NULL,var.inicial=NULL,alt.inicial="two.sided",confint.inicial=".95", prueba.inicial="default",echo.inicial="0",creahtml.inicial="0",tab.inicial=0) dialog.valores <- getDialog("U.Mann.Whitney",defecto) initializeDialog(title=gettextRcmdr("Prueba U de Mann-Whitney"),use.tabs=TRUE,tabs=c('dataTab', 'statisticsTab','optionsTab')) variablesFrame <- tkframe(dataTab) grupoVar <- variableListBox(variablesFrame, Factors(), title=gettextRcmdr("Grupos (escoja una)"), initialSelection=varPosn(dialog.valores$grupo.inicial,"factor")) variableVar <- variableListBox(variablesFrame, Numeric(), title=gettextRcmdr("Variables (escoja una)"), initialSelection=varPosn(dialog.valores$var.inicial,"numeric")) checkBoxes(optionsTab,frame="opsFrame",boxes=c("echocodigo","creahtml"), initialValues=c(dialog.valores$echo.inicial,dialog.valores$creahtml.inicial), labels=gettextRcmdr(c("Mostrar en pantalla el codigo de R ejecutado ","Generar informe de resultados ")), title = gettextRcmdr("Opciones")) onOK <- function(){ tab <- if(as.character(tkselect(notebook)) == dataTab$ID) 0 else 1 grupo <- getSelection(grupoVar) if (length(grupo) == 0) { errorCondition(recall=U.Mann.Whitney, message=gettextRcmdr("Debe seleccionar una variable de agrupacion.")) return() } varresp <- getSelection(variableVar) if (length(varresp) == 0) { errorCondition(recall=U.Mann.Whitney, message=gettextRcmdr("Debe seleccionar una variable de respuesta.")) return() } echocodigo <- tclvalue(echocodigoVariable) creahtml <- tclvalue(creahtmlVariable) ic <- as.numeric(tclvalue(ConfIntVariable)) if ( ic < .0 || ic > 1. || !is.numeric(ic) ) { ic <- 0.95 Message(message=gettextRcmdr("Nivel de confianza invalido, se utilizara valor por defecto."), type="warning") } alternativa <- as.character(tclvalue(alternativaVariable)) prueba <- as.character(tclvalue(pruebaVariable)) putDialog("U.Mann.Whitney",list(grupo.inicial=grupo,var.inicial=varresp, alt.inicial=alternativa,confint.inicial=ic,prueba.inicial=prueba, echo.inicial=echocodigo,creahtml.inicial=creahtml,tab.inicial=tab)) .baseDatosActiva <- ActiveDataSet() opts <- options(warn=-1) instruccion1 <- paste("UMW <- UMWfun(y='", varresp, "',x='", grupo, "', alternativa='", alternativa, "',conf.int=",ic,",prueba='",prueba,"',data='", .baseDatosActiva, "')", sep="") justDoIt(instruccion1) if (echocodigo==1) logger(instruccion1) doItAndPrint(paste("UMW closeDialog() if (creahtml == 1) { if (!file.exists("Informe de Resultados.html")) .archivo <- HTMLInitFile(file.path(getwd()), "Informe de Resultados", BackGroundColor=" else .archivo <- file.path(getwd(), "Informe de Resultados.html") titulo <- paste("Prueba U de Mann-Whitney: ",varresp, " por ", grupo, sep="") HTML(as.title(titulo),file=.archivo) HTML(paste('Medianas para ',varresp," segun ",grupo,sep=""), file=.archivo) .medstabla <- as.data.frame(matrix(UMW[[4]],2,1,dimnames=list(names(UMW[[4]]),"Mediana"))) HTML(.medstabla,file=.archivo) HTML('Resumen Descriptivo',file=.archivo) HTML(as.data.frame(UMW[[5]]),file=.archivo) HTML(paste('Prueba U de Mann-Whitney',if(prueba=='exact')" (exacta)", if(prueba=='correct')" (Normal con correccion por continuidad)", if(prueba=='normal')" (Normal)",sep=""),file=.archivo) HTML(paste("datos: ",ActiveDataSet(),"$",varresp," segun ",ActiveDataSet(),"$",grupo,sep=""), file=.archivo) if (UMW[[6]][3] > 0.0001) pval<-paste(" = ",round(UMW[[6]][[3]],4),sep="") else pval<- " < 0.0001" HTML(paste("U = ",round(UMW[[6]][[1]],4),", valor p",pval,sep=""), file=.archivo) HTML("Hipotesis Alternativa: Diferencia entre distribuciones distinta de 0", file=.archivo) HTML(paste("Intervalo de confianza ",ic*100,"%: ",sep=""), file=.archivo) HTML(round(UMW[[6]][[8]],4), file=.archivo) HTML(paste("Estimacion puntual de la diferencia de medianas: ",sep=""), file=.archivo) meddif <- UMW[[6]][[9]] names(meddif) <- NULL HTML(round(meddif,4), file=.archivo) HTMLhr(file = .archivo) } if (echocodigo == 1) logger("remove('UMW')") remove('UMW', envir=.GlobalEnv) tkfocus(CommanderWindow()) } OKCancelHelp(helpSubject="wilcox.test",reset="U.Mann.Whitney",apply="U.Mann.Whitney") tkgrid(getFrame(grupoVar), labelRcmdr(variablesFrame, text=" "), getFrame(variableVar), sticky="nw") tkgrid(variablesFrame, sticky="w") groupsLabel(groupsBox=grupoVar,dataTab) statsFrame <- tkframe(statisticsTab) radioButtons(statsFrame,name="alternativa", buttons=c("twosided", "less", "greater"), values=c("two.sided", "less", "greater"), labels=gettextRcmdr(c("Bilateral", "Diferencia < 0", "Diferencia > 0")), title=gettextRcmdr("Hipotesis alternativa"), initialValue= dialog.valores$alt.inicial) radioButtons(statsFrame,name="prueba", buttons=c("default", "exact", "normal", "correct"), labels=gettextRcmdr(c("Por defecto", "Exacta", "Aproximacion normal", "Aprox. normal con\ncorrecc. continuidad")), title=gettextRcmdr("Tipo de Prueba"), initialValue= dialog.valores$prueba.inicial) ConfIntFrame <- tkframe(statsFrame) ConfIntVariable <- tclVar(dialog.valores$confint.inicial) ConfIntField <- ttkentry(ConfIntFrame, width = "6", textvariable = ConfIntVariable) tkgrid(labelRcmdr(ConfIntFrame, text = gettextRcmdr("Nivel de confianza"), fg = getRcmdr("title.color"), font="RcmdrTitleFont"), sticky = "w") tkgrid(ConfIntField, sticky = "w") tkgrid(alternativaFrame, labelRcmdr(statsFrame, text = " "), ConfIntFrame, labelRcmdr(statsFrame, text = " "), pruebaFrame, sticky = "nw") tkgrid(statsFrame, sticky = "nw") tkgrid(opsFrame, sticky="w") dialogSuffix(use.tabs=TRUE,grid.buttons=TRUE,tabs=c('dataTab','statisticsTab','optionsTab'), tab.names=c("Datos","Estadisticos","Opciones")) } TWfun <- function(var1,var2,alternativa,conf.int,prueba,data){ res <- list() res[[1]] <- var1 res[[2]] <- var2 res[[3]] <- data meddif <- eval(parse(text=paste("median(", data, "$", var1, " - ", data, "$", var2, ", na.rm=TRUE)", sep=""))) res[[4]] <- meddif m1 <- eval(parse(text=paste(data,"$",var1,sep=""))) m2 <- eval(parse(text=paste(data,"$",var2,sep=""))) difs <- na.omit((m1-m2)[(m1-m2)!=0]) Rpos <- sum(rank(abs(difs))[difs>0]) difpos <- sum(difs>0) Rneg <- sum(rank(abs(difs))[difs<0]) difneg <- sum(difs<0) empates <- sum((m1-m2)==0) Rangos <- matrix(round(c(difpos,if (difpos !=0) Rpos/difpos else 0, Rpos,difneg,if (difneg !=0) Rneg/difneg else 0,Rneg,empates,0,0),2),nrow=3,byrow=T, dimnames=list(c('Rangos positivos','Rangos negativos','Empates'),c('Frecuencia','Rango promedio','Suma Rangos'))) res[[5]] <- Rangos if (prueba == "default"){ TW <- eval(parse(text=paste("wilcox.test(",data,"$",var1, ",",data,"$",var2, ", alternative='", alternativa, "',conf.int=TRUE,conf.level=",conf.int,",paired=TRUE)", sep=""))) } if (prueba == "normal"){ TW <- eval(parse(text=paste("wilcox.test(",data,"$",var1, ",",data,"$",var2, ", alternative='", alternativa, "',conf.int=TRUE,conf.level=",conf.int,",exact=FALSE, correct=FALSE,paired=TRUE)", sep=""))) } if (prueba == "correct"){ TW <- eval(parse(text=paste("wilcox.test(",data,"$",var1, ",",data,"$",var2, ", alternative='", alternativa, "',conf.int=TRUE,conf.level=",conf.int,",exact=FALSE, correct=TRUE,paired=TRUE)", sep=""))) } else { TW <- eval(parse(text=paste("wilcox.test(",data,"$",var1, ",",data,"$",var2, ", alternative='", alternativa, "',conf.int=TRUE,conf.level=",conf.int,",exact=TRUE, correct=FALSE,paired=TRUE)", sep=""))) } res[[6]] <- TW class(res) <- "TW" res } print.TW <- function (x,digits = max(4,getOption("digits") - 4),...) { cat('Diferencia de medianas para',x[[1]],"y",x[[2]],":",x[[4]],"\n") cat("\n\n") cat("Resumen descriptivo por rangos \n") cat("\n") print(x[[5]]) cat("\n\n") cat('Prueba T de Wilcoxon para',x[[1]],"y",x[[2]],"\n") cat("\n") print(x[[6]]) cat("\n\n") invisible(x) } pruebaT.Wilcoxon <- function(){ defecto <- list(var1.inicial=NULL,var2.inicial=NULL,alt.inicial="two.sided",confint.inicial=".95", prueba.inicial="default",echo.inicial="0",creahtml.inicial="0",tab.inicial=0) dialog.valores <- getDialog("pruebaT.Wilcoxon",defecto) initializeDialog(title=gettextRcmdr("Prueba T de Wilcoxon"),use.tabs=TRUE,tabs=c('dataTab', 'statisticsTab','optionsTab')) variablesFrame <- tkframe(dataTab) variable1Var <- variableListBox(variablesFrame, Numeric(), title=gettextRcmdr("Variable 1 (escoja una)"), initialSelection=varPosn(dialog.valores$var1.inicial,"numeric")) variable2Var <- variableListBox(variablesFrame, Numeric(), title=gettextRcmdr("Variable 2 (escoja una)"), initialSelection=varPosn(dialog.valores$var2.inicial,"numeric")) checkBoxes(optionsTab,frame="opsFrame",boxes=c("echocodigo","creahtml"), initialValues=c(dialog.valores$echo.inicial,dialog.valores$creahtml.inicial), labels=gettextRcmdr(c("Mostrar en pantalla el codigo de R ejecutado ","Generar informe de resultados ")), title = gettextRcmdr("Opciones")) onOK <- function(){ tab <- if(as.character(tkselect(notebook)) == dataTab$ID) 0 else 1 var1 <- getSelection(variable1Var) if (length(var1) == 0) { errorCondition(recall=pruebaT.Wilcoxon, message=gettextRcmdr("Debe seleccionar una variable de agrupacion.")) return() } var2 <- getSelection(variable2Var) if (length(var2) == 0) { errorCondition(recall=pruebaT.Wilcoxon, message=gettextRcmdr("Debe seleccionar una variable de respuesta.")) return() } echocodigo <- tclvalue(echocodigoVariable) creahtml <- tclvalue(creahtmlVariable) ic <- as.numeric(tclvalue(ConfIntVariable)) if ( ic < .0 || ic > 1. || !is.numeric(ic) ) { ic <- 0.95 Message(message=gettextRcmdr("Nivel de confianza invalido, se utilizara valor por defecto."), type="warning") } alternativa <- as.character(tclvalue(alternativaVariable)) prueba <- as.character(tclvalue(pruebaVariable)) putDialog("pruebaT.Wilcoxon",list(var1.inicial=var1,var2.inicial=var2, alt.inicial=alternativa,confint.inicial=ic,prueba.inicial=prueba, echo.inicial=echocodigo,creahtml.inicial=creahtml,tab.inicial=tab)) opts <- options(warn=-1) .baseDatosActiva <- ActiveDataSet() instruccion1 <- paste("TW <- TWfun(var1='", var1, "',var2='", var2, "', alternativa='", alternativa, "',conf.int=",ic,",prueba='",prueba,"',data='", .baseDatosActiva, "')", sep="") justDoIt(instruccion1) if (echocodigo==1) logger(instruccion1) doItAndPrint(paste("TW if (creahtml == 1) { if (!file.exists("Informe de Resultados.html")) .archivo <- HTMLInitFile(file.path(getwd()), "Informe de Resultados", BackGroundColor=" else .archivo <- file.path(getwd(), "Informe de Resultados.html") titulo <- paste("Prueba de Wilcoxon (muestras relacionadas) para: ",var1, " y ", var2, sep="") HTML(as.title(titulo),file=.archivo) HTML(paste('Diferencia de medianas entre ',var1," y ",var2," : ",TW[[4]],sep=""), file=.archivo) HTML(paste('Resumen Descriptivo para ', var1, ' - ', var2,sep=""),file=.archivo) HTML(as.data.frame(TW[[5]]),file=.archivo) HTML(paste('Prueba T de Wilcoxon',if(prueba=='exact')" (exacta)", if(prueba=='correct')" (Normal con correccion por continuidad)", if(prueba=='normal')" (Normal)",sep=""),file=.archivo) HTML(paste("datos: ",ActiveDataSet(),"$",var1," y ",ActiveDataSet(),"$",var2,sep=""), file=.archivo) if (TW[[6]][[3]] > 0.0001) pval<-paste(" = ",round(TW[[6]][[3]],4),sep="") else pval<- " < 0.0001" HTML(paste("V = ",round(TW[[6]][[1]],4),", valor p",pval,sep=""), file=.archivo) HTML("Hipotesis Alternativa: Diferencia entre distribuciones distinta de 0", file=.archivo) HTML(paste("Intervalo de confianza ",ic*100,"%: ",sep=""), file=.archivo) HTML(round(TW[[6]][[8]],4), file=.archivo) HTML(paste("Estimacion puntual de la (pseudo)mediana de las diferencias: ",sep=""), file=.archivo) meddifest <- TW[[6]][[9]] names(meddifest) <- NULL HTML(round(meddifest,4), file=.archivo) HTMLhr(file = .archivo) } if (echocodigo == 1) logger("remove('TW')") remove('TW', envir=.GlobalEnv) closeDialog() tkfocus(CommanderWindow()) } OKCancelHelp(helpSubject="wilcox.test",reset="pruebaT.Wilcoxon",apply="pruebaT.Wilcoxon") tkgrid(getFrame(variable1Var), labelRcmdr(variablesFrame, text=" "), getFrame(variable2Var), sticky="nw") tkgrid(variablesFrame, sticky="w") statsFrame <- tkframe(statisticsTab) radioButtons(statsFrame,name="alternativa", buttons=c("twosided", "less", "greater"), values=c("two.sided", "less", "greater"), labels=gettextRcmdr(c("Bilateral", "Diferencia < 0", "Diferencia > 0")), title=gettextRcmdr("Hipotesis alternativa"), initialValue= dialog.valores$alt.inicial) ConfIntFrame <- tkframe(statsFrame) ConfIntVariable <- tclVar(dialog.valores$confint.inicial) ConfIntField <- ttkentry(ConfIntFrame, width = "6", textvariable = ConfIntVariable) radioButtons(statsFrame,name="prueba", buttons=c("default", "exact", "normal", "correct"), values = c("default", "exact","normal", "correct"), labels=gettextRcmdr(c("Por defecto", "Exacta", "Aproximacion normal", "Aprox. normal con\ncorrecc. continuidad")), title=gettextRcmdr("Tipo de Prueba"), initialValue= dialog.valores$prueba.inicial) tkgrid(labelRcmdr(ConfIntFrame, text = gettextRcmdr("Nivel de confianza"), fg = getRcmdr("title.color"), font="RcmdrTitleFont"), sticky = "w") tkgrid(ConfIntField, sticky = "w") tkgrid(alternativaFrame, labelRcmdr(statsFrame, text = " "), ConfIntFrame, labelRcmdr(statsFrame, text = " "), pruebaFrame, sticky = "nw") tkgrid(statsFrame, sticky = "nw") tkgrid(opsFrame, sticky="w") dialogSuffix(use.tabs=TRUE,grid.buttons=TRUE,tabs=c('dataTab','statisticsTab','optionsTab'), tab.names=c("Datos","Estadisticos","Opciones")) } formafun <- function(data){ variable <- unlist(strsplit(deparse(substitute(data)), "[$]"))[2] res <- list() res[[1]] <- variable n <- length(na.omit(data)) sesgo <- (n*sum((data-mean(data,na.rm=TRUE))^3,na.rm=TRUE))/((n-1)*(n-2))/(sd(data,na.rm=TRUE)^3) res[[2]] <- round(sesgo,2) error.simetria <- sqrt((6*n*(n-1))/((n-2)*(n+1)*(n+3))) res[[3]]<-round(error.simetria,2) sim.estandar <- sesgo/error.simetria res[[4]] <- round(sim.estandar,2) if (sign(sim.estandar) > 0) valor.p <- 2*pnorm(sim.estandar,lower.tail=FALSE) else valor.p <- 2*pnorm(sim.estandar) res[[5]] <- round(valor.p,3) class(res) <- "Zforma" res } print.Zforma <- function (x,digits = max(4,getOption("digits") - 4),...) { cat('Coeficiente de asimetria para ',x[[1]],": ",x[[2]],"\n",sep='') cat("\n") cat('Error tipico del coeficiente de asimetria para ',x[[1]],": ",x[[3]],"\n",sep='') cat("\n") cat('Coeficiente de simetria estandarizado para ',x[[1]],": ",x[[4]],"\n",sep='') cat("\n") cat('Significacion estadistica (bilateral) asociada para ',x[[1]],": ",x[[5]],"\n",sep='') cat("\n") invisible(x) } prueba.conformidad.forma <- function(){ defecto <- list(var.inicial=NULL,echo.inicial="0",creahtml.inicial="0",tab.inicial=0) dialog.valores <- getDialog("prueba.conformidad.forma",defecto) initializeDialog(title=gettextRcmdr("Prueba conformidad parametro de forma"), use.tabs=TRUE,tabs=c('dataTab','optionsTab')) variablesFrame <- tkframe(dataTab) variableVar <- variableListBox(variablesFrame, Numeric(), title=gettextRcmdr("Variables (escoja una)"), initialSelection=varPosn(dialog.valores$var.inicial,"numeric")) checkBoxes(optionsTab,frame="opsFrame",boxes=c("echocodigo","creahtml"), initialValues=c(dialog.valores$echo.inicial,dialog.valores$creahtml.inicial), labels=gettextRcmdr(c("Mostrar en pantalla el codigo de R ejecutado ","Generar informe de resultados ")), title = gettextRcmdr("Opciones")) onOK <- function(){ tab <- if(as.character(tkselect(notebook)) == dataTab$ID) 0 else 1 var <- getSelection(variableVar) if (length(var) == 0) { errorCondition(recall=prueba.conformidad.forma, message=gettextRcmdr("Debe seleccionar una variable.")) return() } echocodigo <- tclvalue(echocodigoVariable) creahtml <- tclvalue(creahtmlVariable) opts <- options(warn=-1) vars <- var bd <- paste(ActiveDataSet(), "$", vars, sep="") options(opts) putDialog("prueba.conformidad.forma",list(var.inicial=var,echo.inicial=echocodigo,creahtml.inicial=creahtml, tab.inicial=tab)) instruccion1 <- paste("pruebaZ.forma <- formafun(data=",bd,")", sep="") if (echocodigo == 1) { logger(instruccion1) } justDoIt(instruccion1) doItAndPrint(paste("pruebaZ.forma if (creahtml == 1) { if (!file.exists("Informe de Resultados.html")) .archivo <- HTMLInitFile(file.path(getwd()), "Informe de Resultados", BackGroundColor=" else .archivo <- file.path(getwd(), "Informe de Resultados.html") titulo <- paste("Prueba de conformidad respecto al parametro de forma para: ",var, sep="") HTML(as.title(titulo),file=.archivo) HTML('Prueba de Conformidad para el parametro de forma',file=.archivo) HTML(paste("datos: ",ActiveDataSet(),"$",var,sep=""), file=.archivo) if (pruebaZ.forma[[5]] > 0.0001) pval<-paste(" = ",round(pruebaZ.forma[[5]],4),sep="") else pval<- " < 0.0001" HTML(paste("Coeficiente de simetria = ",round(pruebaZ.forma[[2]],4),", Error tipico = ",round(pruebaZ.forma[[3]],4), sep=""),file=.archivo) HTML(paste("Coeficiente de simetria estandarizado = ",round(pruebaZ.forma[[4]],4),", valor p",pval,sep=""), file=.archivo) HTML("Hipotesis Alternativa: Parametro beta distinto de 0", file=.archivo) HTMLhr(file = .archivo) } if (echocodigo == 1) logger("remove('pruebaZ.forma')") remove('pruebaZ.forma', envir=.GlobalEnv) closeDialog() tkfocus(CommanderWindow()) } OKCancelHelp(helpSubject="RCmdrPlugin.EACSPIR",reset="prueba.conformidad.forma",apply="prueba.conformidad.forma") tkgrid(getFrame(variableVar), sticky="nw") tkgrid(variablesFrame, sticky="w") tkgrid(opsFrame, sticky="w") dialogSuffix(use.tabs=TRUE,grid.buttons=TRUE,tabs=c('dataTab','optionsTab'), tab.names=c("Datos","Opciones")) } apuntfun <- function(data){ variable <- unlist(strsplit(deparse(substitute(data)), "[$]"))[2] res <- list() res[[1]] <- variable n <- length(na.omit(data)) curtosis <-c(n*(n+1)*sum((data-mean(data,na.rm=TRUE))^4,na.rm=TRUE)/((n-1)*(n-2)*(n-3))-3*sum((data- mean(data,na.rm=TRUE))^2,na.rm=TRUE)^2/((n-2)*(n-3)))/(sd(data,na.rm=TRUE)^4) res[[2]] <- round(curtosis,2) error.curtosis <- sqrt((24*n*(n-1)^2)/((n-3)*(n-2)*(n+3)*(n+5))) res[[3]]<-round(error.curtosis,2) curtosis.estandar <- curtosis/error.curtosis res[[4]] <- round(curtosis.estandar,2) if (sign(curtosis.estandar) > 0) valor.p <- 2*pnorm(curtosis.estandar,lower.tail=FALSE) else valor.p <- 2*pnorm(curtosis.estandar) res[[5]] <- round(valor.p,3) class(res) <- "Zapunt" res } print.Zapunt <- function (x,digits = max(4,getOption("digits") - 4),...) { cat('Coeficiente de apuntamiento para ',x[[1]],": ",x[[2]],"\n",sep='') cat("\n") cat('Error tipico del coeficiente de apuntamiento para ',x[[1]],": ",x[[3]],"\n",sep='') cat("\n") cat('Coeficiente de apuntamiento estandarizado para ',x[[1]],": ",x[[4]],"\n",sep='') cat("\n") cat('Significacion estadistica (bilateral) asociada para ',x[[1]],": ",x[[5]],"\n",sep='') cat("\n") invisible(x) } prueba.conformidad.apuntamiento <- function(){ defecto <- list(var.inicial=NULL,echo.inicial="0",creahtml.inicial="0",tab.inicial=0) dialog.valores <- getDialog("prueba.conformidad.apuntamiento",defecto) initializeDialog(title=gettextRcmdr("Prueba conformidad parametro de apuntamiento"), use.tabs=TRUE,tabs=c('dataTab','optionsTab')) variablesFrame <- tkframe(dataTab) variableVar <- variableListBox(variablesFrame, Numeric(), title=gettextRcmdr("Variables (escoja una)"), initialSelection=varPosn(dialog.valores$var.inicial,"numeric")) checkBoxes(optionsTab,frame="opsFrame",boxes=c("echocodigo","creahtml"), initialValues=c(dialog.valores$echo.inicial,dialog.valores$creahtml.inicial), labels=gettextRcmdr(c("Mostrar en pantalla el codigo de R ejecutado ","Generar informe de resultados ")), title = gettextRcmdr("Opciones")) onOK <- function(){ tab <- if(as.character(tkselect(notebook)) == dataTab$ID) 0 else 1 var <- getSelection(variableVar) if (length(var) == 0) { errorCondition(recall=prueba.conformidad.apuntamiento, message=gettextRcmdr("Debe seleccionar una variable.")) return() } echocodigo <- tclvalue(echocodigoVariable) creahtml <- tclvalue(creahtmlVariable) opts <- options(warn=-1) vars <- var bd <- paste(ActiveDataSet(), "$", vars, sep="") options(opts) putDialog("prueba.conformidad.apuntamiento",list(var.inicial=var,echo.inicial=echocodigo,creahtml.inicial=creahtml, tab.inicial=tab)) instruccion1 <- paste("pruebaZ.apuntamiento <- apuntfun(data=",bd,")", sep="") if (echocodigo == 1) { logger(instruccion1) } justDoIt(instruccion1) doItAndPrint(paste("pruebaZ.apuntamiento if (creahtml == 1) { if (!file.exists("Informe de Resultados.html")) .archivo <- HTMLInitFile(file.path(getwd()), "Informe de Resultados", BackGroundColor=" else .archivo <- file.path(getwd(), "Informe de Resultados.html") titulo <- paste("Prueba de conformidad respecto al parametro de apuntamiento para: ",var, sep="") HTML(as.title(titulo),file=.archivo) } closeDialog() if (creahtml == 1) { HTML('Prueba de Conformidad para el parametro de apuntamiento',file=.archivo) HTML(paste("datos: ",ActiveDataSet(),"$",var,sep=""), file=.archivo) if (pruebaZ.apuntamiento[[5]] > 0.0001) pval<-paste(" = ",round(pruebaZ.apuntamiento[[5]],4),sep="") else pval<- " < 0.0001" HTML(paste("Coeficiente de apuntamiento = ",round(pruebaZ.apuntamiento[[2]],4),", Error tipico = ", round(pruebaZ.apuntamiento[[3]],4), sep=""),file=.archivo) HTML(paste("Coeficiente de apuntamiento estandarizado = ",round(pruebaZ.apuntamiento[[4]],4), ", valor p",pval,sep=""),file=.archivo) HTML("Hipotesis Alternativa: Parametro gamma distinto de 0", file=.archivo) HTMLhr(file = .archivo) } if (echocodigo == 1) logger("remove('pruebaZ.apuntamiento')") remove('pruebaZ.apuntamiento', envir=.GlobalEnv) tkfocus(CommanderWindow()) } OKCancelHelp(helpSubject="RCmdrPlugin.EACSPIR",reset="prueba.conformidad.apuntamiento", apply="prueba.conformidad.apuntamiento") tkgrid(getFrame(variableVar), sticky="nw") tkgrid(variablesFrame, sticky="w") tkgrid(opsFrame, sticky="w") dialogSuffix(use.tabs=TRUE,grid.buttons=TRUE,tabs=c('dataTab','optionsTab'), tab.names=c("Datos","Opciones")) } tam.muestra <-function(conf,e,est=c("proporcion","media"),inf=TRUE,N=NULL,pi=0.5,sigma=NULL){ if ((conf >= 1) || (conf <= 0)) stop("Especifique el valor para el nivel de confianza"); alfa <- 1-conf if (!is.numeric(e)) stop("Especifique el valor de precision"); if ( (inf==FALSE) && !is.numeric(N) ) stop("Especifique el tamano de la poblacion") est <- match.arg(est) if (est == "proporcion"){ if ((pi > 1) || (pi < 0)) stop("Especifique el valor para la proporcion poblacional"); if (inf == TRUE) n <- qnorm(alfa/2)^2*pi*(1-pi)/e^2 else n <- qnorm(alfa/2)^2*pi*(1-pi)*N/(e^2*(N-1)+qnorm(alfa/2)^2*pi*(1-pi)) res <- list(parametro=est,prop=pi,precision=e,confianza=conf,muestra=n) class(res) <- "tmuestra" } if (est == "media"){ if (!is.numeric(sigma)) stop("Especifique el valor para la desviacion tipica poblacional"); if (inf == TRUE) n <- qnorm(alfa/2)^2*sigma^2/e^2 else n <- qnorm(alfa/2)^2*sigma^2*N/(e^2*(N-1)+qnorm(alfa/2)^2*sigma^2) res <- list(parametro=est,desv=sigma,precision=e,confianza=conf,muestra=n) class(res) <- "tmuestra" } res } print.tmuestra <- function (x,digits = max(4,getOption("digits") - 4),...) { if (x$parametro == 'proporcion') { cat("\n") cat("Parametro a estimar: ",x$parametro, " = ", x$prop, "\n") cat("Precision: ", x$precision, "\n") cat("Nivel de confianza: ", x$confianza, "\n") cat("Tamano de la muestra requerido: ", x$muestra, "observaciones", "\n") } if (x$parametro == 'media') { cat("\n") cat("Parametro a estimar: ",x$parametro, "\n") cat("Sigma = ", x$desv, "\n") cat("Precision: ", x$precision, "\n") cat("Nivel de confianza: ", x$confianza, "\n") cat("Tamano de la muestra requerido: ", x$muestra, "observaciones", "\n") } cat("\n") invisible(x) } determ.tam.proporcion <- function(){ defecto <- list(prop.inicial="0.5",pobN.inicial="<auto>",precision.inicial="0.05",confint.inicial=".95", echo.inicial="0",creahtml.inicial="0",tab.inicial=0) dialog.valores <- getDialog("determ.tam.proporcion",defecto) initializeDialog(title=gettextRcmdr("Determinacion tamano muestra: proporciones"), use.tabs=TRUE,tabs=c('statisticsTab','optionsTab')) checkBoxes(optionsTab,frame="opsFrame",boxes=c("echocodigo","creahtml"), initialValues=c(dialog.valores$echo.inicial,dialog.valores$creahtml.inicial), labels=gettextRcmdr(c("Mostrar en pantalla el codigo de R ejecutado ","Generar informe de resultados ")), title = gettextRcmdr("Opciones")) onOK <- function(){ tab <- if(as.character(tkselect(notebook)) == statisticsTab$ID) 0 else 1 proporcion <- as.numeric(tclvalue(propVariable)) pobN <- tclvalue(pobNVariable) precision <- as.numeric(tclvalue(precisionVariable)) echocodigo <- tclvalue(echocodigoVariable) confianza <- as.numeric(tclvalue(ConfIntVariable)) creahtml <- tclvalue(creahtmlVariable) if ((proporcion > 1) || (proporcion < 0)) { errorCondition(recall=determ.tam.proporcion, message=gettextRcmdr("Especifique un valor del parametro proporcion.")) return() } if (!is.numeric(precision)) { precision <- 0.05 Message(message=gettextRcmdr("Valor de precision invalido, se utilizara valor por defecto.")) return() } if (pobN == gettextRcmdr("<auto>")) N <- NULL else { N <- as.numeric(pobN) if ( !is.numeric(N)) { N <- NULL Message(message=gettextRcmdr("Tamano de la poblacion invalido, se utilizara valor por defecto.")) return() } } if ( confianza < .0 || confianza > 1. || !is.numeric(confianza) ) { confianza <- 0.95 Message(message=gettextRcmdr("Nivel de confianza invalido, se utilizara valor por defecto."), type="warning") } putDialog("determ.tam.proporcion",list(prop.inicial=proporcion,pobN.inicial=if (is.null(N)) "<auto>" else N, precision.inicial=precision,confint.inicial=confianza, echo.inicial=echocodigo,creahtml.inicial=creahtml,tab.inicial=tab)) if (creahtml == 1) { if (!file.exists("Informe de Resultados.html")) .archivo <- HTMLInitFile(file.path(getwd()), "Informe de Resultados", BackGroundColor=" else .archivo <- file.path(getwd(), "Informe de Resultados.html") titulo <- "Determinacion del tamano de la muestra: proporciones" HTML(as.title(titulo),file=.archivo) } closeDialog() if (is.numeric(N)) instruccion <- paste("tam.muestra(conf=",confianza,",e=",precision,",est='proporcion'", ",inf=FALSE,N=",N,",pi=",proporcion,")",sep="") else instruccion <- paste("dtm <- tam.muestra(conf=",confianza,",e=",precision,",est='proporcion'", ",inf=TRUE,N=NULL,pi=",proporcion,")",sep="") justDoIt(instruccion) if (echocodigo==1) logger(instruccion) doItAndPrint("dtm if (creahtml == 1) { HTML('Determinacion del tamano de la muestra: Caso proporcion',file=.archivo) HTML(dtm,file= .archivo) HTMLhr(file = .archivo) } if (echocodigo == 1) logger("remove(list=c('dtm'))") remove(list=c('dtm'), envir=.GlobalEnv) tkfocus(CommanderWindow()) } OKCancelHelp(helpSubject="RcmdrPugin.EACSPIR",reset="determ.tam.proporcion",apply="determ.tam.proporcion") propFrame <- tkframe(statisticsTab) propVariable <- tclVar(dialog.valores$prop.inicial) propField <- ttkentry(propFrame, width="8", textvariable=propVariable) tkgrid(labelRcmdr(propFrame,text=gettextRcmdr("Parametro proporcion = "),font="RcmdrTitleFont"), propField,sticky="w") pobNFrame <- tkframe(statisticsTab) pobNVariable <- tclVar(dialog.valores$pobN.inicial) pobNField <- ttkentry(pobNFrame, width="8", textvariable=pobNVariable) tkgrid(labelRcmdr(pobNFrame,text=gettextRcmdr("Tamano poblacional = "),font="RcmdrTitleFont"), pobNField,sticky="w") precisionFrame <- tkframe(statisticsTab) precisionVariable <- tclVar(dialog.valores$precision.inicial) precisionField <- ttkentry(precisionFrame, width="8", textvariable=precisionVariable) tkgrid(labelRcmdr(precisionFrame,text=gettextRcmdr("Valor de precision = "),font="RcmdrTitleFont"), precisionField,sticky="w") ConfIntFrame <- tkframe(statisticsTab) ConfIntVariable <- tclVar(dialog.valores$confint.inicial) ConfIntField <- ttkentry(ConfIntFrame, width="8", textvariable=ConfIntVariable) tkgrid(labelRcmdr(ConfIntFrame,text=gettextRcmdr("Nivel de Confianza = "),font="RcmdrTitleFont"), ConfIntField,sticky="w") tkgrid(propFrame, sticky="nw") tkgrid(pobNFrame, sticky="nw") tkgrid(precisionFrame, sticky="nw") tkgrid(ConfIntFrame, sticky="nw") tkgrid(opsFrame, sticky="nw") dialogSuffix(use.tabs=TRUE,grid.buttons=TRUE,tabs=c('statisticsTab','optionsTab'), tab.names=c("Estadisticos","Opciones")) } determ.tam.media <- function(){ defecto <- list(sigma.inicial="1.0",pobN.inicial="<auto>",precision.inicial="0.10",confint.inicial=".95", echo.inicial="0",creahtml.inicial="0",tab.inicial=0) dialog.valores <- getDialog("determ.tam.media",defecto) initializeDialog(title=gettextRcmdr("Determinacion tamano muestra: medias"), use.tabs=TRUE,tabs=c('statisticsTab','optionsTab')) checkBoxes(optionsTab,frame="opsFrame",boxes=c("echocodigo","creahtml"), initialValues=c(dialog.valores$echo.inicial,dialog.valores$creahtml.inicial), labels=gettextRcmdr(c("Mostrar en pantalla el codigo de R ejecutado ","Generar informe de resultados ")), title = gettextRcmdr("Opciones")) onOK <- function(){ tab <- if(as.character(tkselect(notebook)) == statisticsTab$ID) 0 else 1 sigma <- as.numeric(tclvalue(sigmaVariable)) pobN <- tclvalue(pobNVariable) precision <- as.numeric(tclvalue(precisionVariable)) echocodigo <- tclvalue(echocodigoVariable) confianza <- as.numeric(tclvalue(ConfIntVariable)) creahtml <- tclvalue(creahtmlVariable) if (!is.numeric(sigma)) { errorCondition(recall=determ.tam.media, message=gettextRcmdr("Especifique un valor del parametro sigma.")) return() } if (!is.numeric(precision)) { precision <- 0.05 Message(message=gettextRcmdr("Valor de precision invalido, se utilizara valor por defecto.")) return() } if (pobN == gettextRcmdr("<auto>")) N <- NULL else { N <- as.numeric(pobN) if ( !is.numeric(N)) { N <- NULL Message(message=gettextRcmdr("Tamano de la poblacion invalido, se utilizara valor por defecto.")) return() } } if ( confianza < .0 || confianza > 1. || !is.numeric(confianza) ) { confianza <- 0.95 Message(message=gettextRcmdr("Nivel de confianza invalido, se utilizara valor por defecto."), type="warning") } if (creahtml == 1) { if (!file.exists("Informe de Resultados.html")) .archivo <- HTMLInitFile(file.path(getwd()), "Informe de Resultados", BackGroundColor=" else .archivo <- file.path(getwd(), "Informe de Resultados.html") titulo <- "Determinacion del tamano de la muestra: medias" HTML(as.title(titulo),file=.archivo) } putDialog("determ.tam.media",list(sigma.inicial=sigma,pobN.inicial=if (is.null(N)) "<auto>" else N, precision.inicial=precision,confint.inicial=confianza, echo.inicial=echocodigo,creahtml.inicial=creahtml,tab.inicial=tab)) closeDialog() if (is.numeric(N)) instruccion <- paste("dtm <- tam.muestra(conf=",confianza,",e=",precision,",est='media'", ",inf=FALSE,N=",N,",sigma=",sigma,")",sep="") else instruccion <- paste("dtm <- tam.muestra(conf=",confianza,",e=",precision,",est='media'", ",inf=TRUE,N=NULL,sigma=",sigma,")",sep="") justDoIt(instruccion) if (echocodigo==1) logger(instruccion) doItAndPrint("dtm if (creahtml == 1) { HTML('Determinacion del tamano de la muestra: Caso media',file=.archivo) HTML(dtm,file= .archivo) HTMLhr(file = .archivo) } if (echocodigo == 1) logger("remove(list=c('dtm'))") remove(list=c('dtm'), envir=.GlobalEnv) tkfocus(CommanderWindow()) } OKCancelHelp(helpSubject="RcmdrPugin.EACSPIR",reset="determ.tam.media",apply="determ.tam.media") sigmaFrame <- tkframe(statisticsTab) sigmaVariable <- tclVar(dialog.valores$sigma.inicial) sigmaField <- ttkentry(sigmaFrame, width="8", textvariable=sigmaVariable) tkgrid(labelRcmdr(sigmaFrame,text=gettextRcmdr("Parametro sigma = "),font="RcmdrTitleFont"), sigmaField,sticky="w") pobNFrame <- tkframe(statisticsTab) pobNVariable <- tclVar(dialog.valores$pobN.inicial) pobNField <- ttkentry(pobNFrame, width="8", textvariable=pobNVariable) tkgrid(labelRcmdr(pobNFrame,text=gettextRcmdr("Tamano poblacional = "),font="RcmdrTitleFont"), pobNField,sticky="w") precisionFrame <- tkframe(statisticsTab) precisionVariable <- tclVar(dialog.valores$precision.inicial) precisionField <- ttkentry(precisionFrame, width="8", textvariable=precisionVariable) tkgrid(labelRcmdr(precisionFrame,text=gettextRcmdr("Valor de precision = "),font="RcmdrTitleFont"), precisionField,sticky="w") ConfIntFrame <- tkframe(statisticsTab) ConfIntVariable <- tclVar(dialog.valores$confint.inicial) ConfIntField <- ttkentry(ConfIntFrame, width="8", textvariable=ConfIntVariable) tkgrid(labelRcmdr(ConfIntFrame,text=gettextRcmdr("Nivel de Confianza = "),font="RcmdrTitleFont"), ConfIntField,sticky="w") tkgrid(sigmaFrame, sticky="nw") tkgrid(pobNFrame, sticky="nw") tkgrid(precisionFrame, sticky="nw") tkgrid(ConfIntFrame, sticky="nw") tkgrid(opsFrame, sticky="nw") dialogSuffix(use.tabs=TRUE,grid.buttons=TRUE,tabs=c('statisticsTab','optionsTab'), tab.names=c("Estadisticos","Opciones")) } normfun <- function(variable,stats,group=NULL){ res <- list() res[[1]] <- variable res[[2]] <- group res[[3]] <- stats i <- 4 opts <- options(warn=-1) if ('Pearsontest' %in% stats) { if (!is.null(group)) .prueba.pearson <- eval(parse(text=paste("by(",variable,",",group,",pearson.test)",sep=""))) else .prueba.pearson <- eval(parse(text=paste("pearson.test(",variable,")",sep=""))) if (!is.null(group)){ for (j in 1:dim(.prueba.pearson)) .prueba.pearson[[j]]$data.name <- variable } res[[i]] <- .prueba.pearson i <- i + 1 } if ('ADtest' %in% stats) { if (!is.null(group)){ .prueba.AD <- eval(parse(text=paste("by(",variable,",",group,",ad.test)",sep=""))) for (j in 1:dim(.prueba.AD)) .prueba.AD[[j]]$data.name <- variable } else .prueba.AD <- eval(parse(text=paste("ad.test(",variable,")",sep=""))) res[[i]] <- .prueba.AD i <- i + 1 } if ('KStest' %in% stats) { if (!is.null(group)){ .prueba.KS <- eval(parse(text=paste("by(",variable,"," ,group,",function(x)ks.test(x,'pnorm',mean(x,na.rm=T),sd(x,na.rm=T)))" ,sep=""))) for (j in 1:dim(.prueba.KS)) .prueba.KS[[j]]$data.name <- variable } else .prueba.KS <- eval(parse(text=paste("ks.test(",variable,",'pnorm',mean(", variable,",na.rm=T),sd(",variable,",na.rm=T))",sep=""))) res[[i]] <- .prueba.KS i <- i + 1 } if ('Shapirotest' %in% stats) { if (!is.null(group)){ .prueba.shapiro <- eval(parse(text=paste(".prueba.shapiro <- by(",variable,",",group,",shapiro.test)",sep=""))) for (j in 1:dim(.prueba.shapiro)) .prueba.shapiro[[j]]$data.name <- variable } else .prueba.shapiro <- eval(parse(text=paste("shapiro.test(",variable,")",sep=""))) res[[i]] <- .prueba.shapiro i <- i + 1 } class(res) <- "prnorm" res } print.prnorm <- function(x,...){ j<-4 if ("Pearsontest" %in% x[[3]]){ cat(" print(x[[j]]) cat("\n\n") j <- j+1 } if ("ADtest" %in% x[[3]]){ cat(" print(x[[j]]) cat("\n\n") j <- j+1 } if ("KStest" %in% x[[3]]){ cat(" print(x[[j]]) cat("\n\n") j <- j+1 } if ("Shapirotest" %in% x[[3]]){ cat(" print(x[[j]]) cat("\n\n") j <- j+1 } invisible(x) } normgrfun <- function(datos){ par(mfrow=c(2,2)) variable <- unlist(strsplit(deparse(substitute(datos)), "[$]"))[2] datos <- as.vector(na.omit(datos)) plot(density(datos),main=paste('Densidad suavizada para ',variable,sep=""),ylab='Densidades') box() x <- datos h <- hist(x,freq=TRUE,plot=FALSE) plot(h,col='red', xlab='Intervalos', ylab='Frecuencias',main=paste('Histograma para ',variable,sep="")) xfit<-seq(min(x,na.rm=T),max(x,na.rm=T),length=1000) yfit<-dnorm(xfit,mean=mean(x,na.rm=T),sd=sd(x,na.rm=T)) yfit<-yfit*diff(h$mids[1:2])*length(x) lines(xfit, yfit, col='blue', lwd=2) box() z <- as.numeric(scale(x)) qqnorm(z,xlab='Cuantilas teoricas',ylab='Cuantilas empiricas',main=paste('Grafico QQ para ',variable,sep="")) abline(0,1) box() plot(sort(z),pnorm(sort(z)),type='l',col='red', main=paste("Grafico de cuantilas para ",variable,sep=""),xlab='Puntuaciones Z', ylab='Probabilidad Acumulada') plot(ecdf(z),add=TRUE) box() } pruebas.normalidad <- function(){ defecto <- list(var.inicial=NULL,pearson.inicial="0",ks.inicial="0",ad.inicial="0",shapiro.inicial="0", grupo.inicial=NULL,graficos.inicial="0",echo.inicial="0",creahtml.inicial="0",tab.inicial=0) dialog.valores <- getDialog("pruebas.normalidad",defecto) initializeDialog(title=gettextRcmdr("Pruebas de Ajuste Distribucion Normal"), use.tabs=TRUE,tabs=c('dataTab','statisticsTab','optionsTab')) variablesFrame <- tkframe(dataTab) variableVar <- variableListBox(variablesFrame, Numeric(), title=gettextRcmdr("Variables (escoja una)"), initialSelection=varPosn(dialog.valores$var.inicial,"numeric")) groupsBox(recall=pruebas.normalidad, label=gettextRcmdr("Pruebas segun:"), initialLabel=if (is.null(dialog.valores$grupo.inicial)) gettextRcmdr("Pruebas segun grupos") else paste(gettextRcmdr("Pruebas segun:"), dialog.valores$grupo.inicial), initialGroup=dialog.valores$grupo.inicial, window = dataTab) checkBoxes(statisticsTab,frame="statsFrame",boxes=c("pearson","ks","ad","shapiro","graficos"), initialValues=c(dialog.valores$pearson.inicial,dialog.valores$ks.inicial, dialog.valores$ad.inicial,dialog.valores$shapiro.inicial, dialog.valores$graficos.inicial), labels=gettextRcmdr(c("Prueba Ji-Cuadrado de Pearson ", "Prueba de Kolmogorov-Smirnov ", "Prueba Anderson-Darling ", "Prueba Shapiro-Wilk ", "Representaciones graficas ")), title = gettextRcmdr("Pruebas de normalidad")) checkBoxes(optionsTab,frame="opsFrame",boxes=c("echocodigo","creahtml"), initialValues=c(dialog.valores$echo.inicial,dialog.valores$creahtml.inicial), labels=gettextRcmdr(c("Mostrar en pantalla el codigo de R ejecutado ","Generar informe de resultados ")), title = gettextRcmdr("Opciones")) onOK <- function(){ var <- getSelection(variableVar) if (length(var) == 0) { errorCondition(recall=pruebas.normalidad, message=gettextRcmdr("Debe seleccionar una variable.")) return() } echocodigo <- tclvalue(echocodigoVariable) creahtml <- tclvalue(creahtmlVariable) pearsonval <- tclvalue(pearsonVariable) adval <- tclvalue(adVariable) ksval <-tclvalue(ksVariable) shapiroval <- tclvalue(shapiroVariable) grafval <- tclvalue(graficosVariable) seleccion <- as.numeric(pearsonval) + as.numeric(adval) + as.numeric(ksval) + as.numeric(shapiroval) + as.numeric(grafval) if (seleccion == 0){ errorCondition(recall=pruebas.normalidad, message=gettextRcmdr("Debe escoger algun indicador.")) return() } putDialog("pruebas.normalidad",list(grupo.inicial=if (.groups != FALSE) .groups else NULL,var.inicial=var, pearson.inicial=pearsonval,ad.inicial=adval,ks.inicial=ksval, shapiro.inicial=shapiroval,graficos.inicial=grafval, echo.inicial=echocodigo,creahtml.inicial=creahtml,tab.inicial=tab)) .BaseDatosActiva <- ActiveDataSet() if (.groups != FALSE) { grupos <- paste(.BaseDatosActiva, "$", .groups, sep="") } variable <- paste(.BaseDatosActiva, "$", var, sep="") stats <- paste("c(", paste(c('"Pearsontest"', '"ADtest"', '"KStest"', '"Shapirotest"') [c(pearsonval, adval, ksval, shapiroval) == 1],collapse=", "), ")", sep="") if (.groups != FALSE) instruccion1 <- paste(".norm.test <- normfun(var='",variable, "', stats=", stats, ", group='",grupos, "')", sep="") else instruccion1 <- paste(".norm.test <- normfun(var='",variable, "', stats=", stats, ")", sep="") justDoIt(instruccion1) if (echocodigo == 1) { logger(instruccion1) } doItAndPrint(".norm.test if (creahtml == 1) { if (!file.exists("Informe de Resultados.html")) .archivo <- HTMLInitFile(file.path(getwd()), "Informe de Resultados", BackGroundColor=" else .archivo <- file.path(getwd(), "Informe de Resultados.html") titulo <- paste("Pruebas de ajuste a la distribucion normal para: ",var, sep="") HTML(as.title(titulo),file=.archivo) j <- 4 if (pearsonval == 1) { if (.groups == FALSE){ HTML('Prueba de ajuste a la normal: Ji-Cuadrado de Pearson ',file=.archivo) HTML(paste("datos: ",ActiveDataSet(),"$",var,sep=""), file=.archivo) if (.norm.test[[j]][[2]] > 0.0001) pval<-paste(" = ",round(.norm.test[[j]][[2]],4),sep="") else pval<- " < 0.0001" HTML(paste("Ji Cuadrado de Pearson = ",round(.norm.test[[j]][[1]],4),", valor p",pval,sep=""), file=.archivo) j <- j+1 HTMLhr(file = .archivo) } else { nombres <- eval(parse(text=paste("levels(",.norm.test[[2]][[1]],")",sep=''))) HTML('Prueba de ajuste a la normal: Ji-Cuadrado de Pearson ',file=.archivo) for (i in 1:dim(.norm.test[[j]])){ HTML(paste("datos: ",ActiveDataSet(),"$",var," y ",grupos," = ",nombres[i],sep=""), file=.archivo) if (.norm.test[[j]][[i]]$p.value > 0.0001) pval<-paste(" = ",round(.norm.test[[j]][[i]]$p.value,4),sep="") else pval<- " < 0.0001" HTML(paste("Ji Cuadrado de Pearson = ",round(.norm.test[[j]][[i]]$statistic,4),", valor p",pval,sep=""), file=.archivo) HTML("----------------------------------------------------------------------------------",file=.archivo) } j <- j+1 HTMLhr(file = .archivo) } } if (adval == 1){ if (.groups == FALSE){ HTML('Prueba de ajuste a la normal: Anderson-Darling ',file=.archivo) HTML(paste("datos: ",ActiveDataSet(),"$",var,sep=""), file=.archivo) if (.norm.test[[j]][[2]] > 0.0001) pval<-paste(" = ",round(.norm.test[[j]][[2]],4),sep="") else pval<- " < 0.0001" HTML(paste("A = ",round(.norm.test[[j]][[1]],4),", valor p",pval,sep=""), file=.archivo) j <- j+1 HTMLhr(file = .archivo) } else { nombres <- eval(parse(text=paste("levels(",.norm.test[[2]][[1]],")",sep=''))) HTML('Prueba de ajuste a la normal: Anderson-Darling ',file=.archivo) for (i in 1:dim(.norm.test[[j]])){ HTML(paste("datos: ",ActiveDataSet(),"$",var," y ",grupos," = ",nombres[i],sep=""), file=.archivo) if (.norm.test[[j]][[i]]$p.value > 0.0001) pval<-paste(" = ",round(.norm.test[[j]][[i]]$p.value,4),sep="") else pval<- " < 0.0001" HTML(paste("A = ",round(.norm.test[[j]][[i]]$statistic,4),", valor p",pval,sep=""), file=.archivo) HTML("----------------------------------------------------------------------------------",file=.archivo) } j <- j+1 HTMLhr(file = .archivo) } } if (ksval == 1){ if (.groups == FALSE){ HTML('Prueba de ajuste a la normal: Kolmogorov-Smirnov ',file=.archivo) HTML(paste("datos: ",ActiveDataSet(),"$",var,sep=""), file=.archivo) if (.norm.test[[j]][[2]] > 0.0001) pval<-paste(" = ",round(.norm.test[[j]][[2]],4),sep="") else pval<- " < 0.0001" HTML(paste("D = ",round(.norm.test[[j]][[1]],4),", valor p",pval,sep=""), file=.archivo) j <- j+1 HTMLhr(file = .archivo) } else { nombres <- eval(parse(text=paste("levels(",.norm.test[[2]][[1]],")",sep=''))) HTML('Prueba de ajuste a la normal: Kolmogorov-Smirnov ',file=.archivo) for (i in 1:dim(.norm.test[[j]])){ HTML(paste("datos: ",ActiveDataSet(),"$",var," y ",grupos," = ",nombres[i],sep=""), file=.archivo) if (.norm.test[[j]][[i]]$p.value > 0.0001) pval<-paste(" = ",round(.norm.test[[j]][[i]]$p.value,4),sep="") else pval<- " < 0.0001" HTML(paste("D = ",round(.norm.test[[j]][[i]]$statistic,4),", valor p",pval,sep=""), file=.archivo) HTML("----------------------------------------------------------------------------------",file=.archivo) } j <- j+1 HTMLhr(file = .archivo) } } if (shapiroval == 1){ if (.groups == FALSE){ HTML('Prueba de ajuste a la normal: Shapiro-Wilk ',file=.archivo) HTML(paste("datos: ",ActiveDataSet(),"$",var,sep=""), file=.archivo) if (.norm.test[[j]][[2]] > 0.0001) pval<-paste(" = ",round(.norm.test[[j]][[2]],4),sep="") else pval<- " < 0.0001" HTML(paste("W = ",round(.norm.test[[j]][[1]],4),", valor p",pval,sep=""), file=.archivo) j <- j+1 HTMLhr(file = .archivo) } else { nombres <- eval(parse(text=paste("levels(",.norm.test[[2]][[1]],")",sep=''))) HTML('Prueba de ajuste a la normal: Shapiro-Wilk ',file=.archivo) for (i in 1:dim(.norm.test[[j]])){ HTML(paste("datos: ",ActiveDataSet(),"$",var," y ",grupos," = ",nombres[i],sep=""), file=.archivo) if (.norm.test[[j]][[i]]$p.value > 0.0001) pval<-paste(" = ",round(.norm.test[[j]][[i]]$p.value,4),sep="") else pval<- " < 0.0001" HTML(paste("W = ",round(.norm.test[[j]][[i]]$statistic,4),", valor p",pval,sep=""), file=.archivo) HTML("----------------------------------------------------------------------------------",file=.archivo) } j <- j+1 HTMLhr(file = .archivo) } } } closeDialog() if (.groups != FALSE & grafval ==1){ grafval <- 0.95 Message(message=gettextRcmdr("Analisis segun variable de agrupacion: No se realizaran graficos agrupados."), type="warning") } if (grafval == 1){ instruccion1 <- paste("normgrfun(datos=",variable,")", sep="") justDoIt(instruccion1) if (echocodigo == 1) { logger(instruccion1) } if (creahtml == 1) { titulo <- paste("Graficas para variable ",var,sep="") HTML(as.title(titulo),file=.archivo) nombre.archivo <- paste("GraficasNormR",gsub(":","",substr(Sys.time(),12,19)), ".jpg",sep="") dev.print(jpeg, filename=paste(getwd(),"/",nombre.archivo,sep=""), width=500, height=500) HTMLInsertGraph(nombre.archivo,file=.archivo,append=TRUE) HTMLhr(file = .archivo) } } remove(.norm.test, envir=.GlobalEnv) tkfocus(CommanderWindow()) } OKCancelHelp(helpSubject="RcmdrPlugin.EACSPIR",reset="pruebas.normalidad",apply="pruebas.normalidad") tkgrid(getFrame(variableVar), sticky="nw") tkgrid(variablesFrame, sticky="w") tkgrid(statsFrame, sticky="nw") tkgrid(opsFrame, sticky="w") tkgrid(groupsFrame, sticky = "w", padx=6) dialogSuffix(use.tabs=TRUE,grid.buttons=TRUE,tabs=c('dataTab','statisticsTab','optionsTab'), tab.names=c("Datos","Estadisticos","Opciones")) } avarMRfun <- function(.baseDatosActiva, idvar, intra, mr, sctype,descrip){ res <- list() res[[1]] <- .baseDatosActiva res[[2]] <- descrip datos.ANOVAMR <- eval(parse(text=paste("ezANOVA(.baseDatosActiva,dv=.(",noquote(mr),"),wid=.(",noquote(idvar),"), within=.(",noquote(intra),"),type=",sctype,",detailed=TRUE)"))) res[[3]] <- datos.ANOVAMR[[1]] j <- 4 if (length(levels(.baseDatosActiva[[2]])) >= 3){ res[[4]] <- datos.ANOVAMR[[2]] res[[5]] <- datos.ANOVAMR[[3]] j <- 6 } if (descrip == 1) { descriptivo.ANOVAMR <- eval(parse(text=paste("ezStats(.baseDatosActiva,dv=.(",noquote(mr),"), wid=.(",noquote(idvar),"),within=.(",noquote(intra),"))"))) res[[j]] <- descriptivo.ANOVAMR } class(res) <- "avarMR" res } print.avarMR <- function(x,...){ cat('Resumen ANOVA: \n\n') print(x[[3]]) cat('\n\n') j <- 4 if (length(levels(x[[1]][[2]])) >= 3){ cat('Prueba Esfericidad de Mauchly: \n\n') print(x[[4]]) cat('\n\n') cat('Correcciones Esfericidad: \n\n') print(x[[5]]) cat("\n\n") j <- 6 } if (x[[2]] == TRUE){ cat('Descriptivos ANOVA: \n\n') print(x[[j]]) cat("\n\n") } invisible(x) } avarMRgraf <- function(.baseDatosActiva,idvar,intra,mr){ grafico.Medias <- eval(parse(text=paste("ezPlot(.baseDatosActiva,dv=.(",noquote(mr),"), wid=.(",noquote(idvar),"),within=.(",noquote(intra),"), x = .(",noquote(intra),"), do_lines = FALSE,x_lab = '",intra, "',y_lab = '",mr,"')"))) print(grafico.Medias) } avar.MR <- function(){ defecto <- list(var.inicial=NULL,ID.inicial=NULL,intra.inicial="f.intrasujeto",medrep.inicial="medida.rep", descrip.inicial="0",grafico.inicial="0",SC.inicial="3", echo.inicial="0",creahtml.inicial="0",tab.inicial=0) dialog.valores <- getDialog("avar.MR",defecto) initializeDialog(title=gettextRcmdr("ANOVA Medidas Repetidas"), use.tabs=TRUE,tabs=c('dataTab','statisticsTab','optionsTab')) variablesFrame <- tkframe(dataTab) variableVar <- variableListBox(variablesFrame, Numeric(), title=gettextRcmdr("Medidas repetidas (escoja dos o mas)"), selectmode="multiple", initialSelection=varPosn(dialog.valores$var.inicial,"numeric")) IDVar <- variableListBox(variablesFrame, title=gettextRcmdr("Variable de identificacion (Opcional)"), initialSelection=varPosn(dialog.valores$ID.inicial)) checkBoxes(statisticsTab,frame="statsFrame",boxes=c("descrip","grafico"), initialValues=c(dialog.valores$descrip.inicial,dialog.valores$grafico.inicial), labels=gettextRcmdr(c("Mostrar descriptivos del ANOVA ", "Mostrar grafico de medias ")), title = gettextRcmdr("Pruebas Descriptivas")) radioButtons(statisticsTab, name="SCuadrados", buttons=c("SC1Boton", "SC2Boton","SC3Boton"), values=c(1,2,3),labels=gettextRcmdr(c("Tipo I", "Tipo II", "Tipo III")), title=gettextRcmdr("Suma de Cuadrados:"),initialValue=dialog.valores$SC.inicial) checkBoxes(optionsTab,frame="opsFrame",boxes=c("echocodigo","creahtml"), initialValues=c(dialog.valores$echo.inicial,dialog.valores$creahtml.inicial), labels=gettextRcmdr(c("Mostrar en pantalla el codigo de R ejecutado ","Generar informe de resultados ")), title = gettextRcmdr("Opciones")) onOK <- function(){ tab <- if(as.character(tkselect(notebook)) == dataTab$ID) 0 else 1 var <- getSelection(variableVar) if (length(var) < 2) { errorCondition(recall=avar.MR, message=gettextRcmdr("Debe seleccionar 2 variables como minimo.")) return() } idvar <-getSelection(IDVar) if (length(idvar)==0) var <- paste('"', var, '"', sep="") else { var <- paste('"', c(idvar,var), '"', sep="") } echocodigo <- tclvalue(echocodigoVariable) creahtml <- tclvalue(creahtmlVariable) descripval <- tclvalue(descripVariable) grafval <- tclvalue(graficoVariable) intra <- tclvalue(intraVariable) mr <- tclvalue(medrepVariable) sctype <- as.numeric(tclvalue(SCuadradosVariable)) putDialog("avar.MR",list(var.inicial=getSelection(variableVar), ID.inicial=if (length(idvar) != 0) idvar else NULL, intra.inicial=intra,medrep.inicial=mr, descrip.inicial=descripval, grafico.inicial=grafval,SC.inicial=sctype, echo.inicial=echocodigo,creahtml.inicial=creahtml,tab.inicial=tab)) if (length(idvar) == 0){ instruccion <- paste(".baseDatosActiva <- na.omit(",ActiveDataSet(),"[,c(", paste(var, collapse=","),")])",sep="") justDoIt(instruccion) instruccion2 <- "ObsNumero <- as.factor(1:nrow(.baseDatosActiva))" justDoIt(instruccion2) instruccion3 <- ".baseDatosActiva <- cbind(.baseDatosActiva,ObsNumero)" justDoIt(instruccion3) instruccion4 <- paste(".baseDatosActiva <- melt.data.frame(.baseDatosActiva, id.vars=c('ObsNumero'), variable_name='", intra,"')",sep='') justDoIt(instruccion4) idvar <- "ObsNumero" justDoIt(paste("colnames(.baseDatosActiva)[3] <- '",mr,"'",sep='')) } else{ instruccion <- paste(".baseDatosActiva <- na.omit(",ActiveDataSet(),"[,c(", paste(var, collapse=","),")])",sep="") justDoIt(instruccion) instruccion2 <- paste(".baseDatosActiva <- melt.data.frame(.baseDatosActiva, id.vars='",idvar,"',variable_name='", intra,"')",sep='') justDoIt(instruccion2) justDoIt(paste("colnames(.baseDatosActiva)[3] <- '",mr,"'",sep='')) } instruccion1 <- paste(" .prueba.avarMR <- avarMRfun(.baseDatosActiva, idvar='", idvar, "',intra='",intra, "',mr='",mr,"',sctype=",sctype,",descrip=",as.logical(as.numeric(descripval)),")", sep="") justDoIt(instruccion1) if (echocodigo == 1) { logger(instruccion1) } doItAndPrint(".prueba.avarMR if (grafval == 1){ instruccion1 <- paste(" avarMRgraf(.baseDatosActiva, idvar='", idvar, "',intra='",intra, "',mr='",mr,"')", sep="") justDoIt(instruccion1) if (echocodigo == 1) { logger(instruccion1) } } closeDialog() if (creahtml == 1) { if (!file.exists("Informe de Resultados.html")) .archivo <- HTMLInitFile(file.path(getwd()), "Informe de Resultados", BackGroundColor=" else .archivo <- file.path(getwd(), "Informe de Resultados.html") titulo <- "ANOVA de Medidas Repetidas" HTML(as.title(titulo),file=.archivo) HTML("Resumen ANOVA",file=.archivo) HTML(as.data.frame(.prueba.avarMR[[3]]),file=.archivo) j <- 4 if (length(levels(.baseDatosActiva[[2]])) >= 3){ HTML("Prueba Esfericidad de Mauchly",file=.archivo) HTML(as.data.frame(.prueba.avarMR[[4]]),file=.archivo) HTML("Correcciones Esfericidad",file=.archivo) HTML(as.data.frame(.prueba.avarMR[[5]]),file=.archivo) j <- 6 } if (descripval == 1) { HTML("Descripcion ANOVA",file=.archivo) HTML(as.data.frame(.prueba.avarMR[[j]]),file=.archivo) } if (grafval == 1) { HTML("Grafica de medias ",file=.archivo) nombre.archivo <- paste("GraficaMediasANOVAMR",gsub(":","",substr(Sys.time(),12,19)), ".jpg",sep="") dev.print(jpeg, filename=paste(getwd(),"/",nombre.archivo,sep=""), width=500, height=500) HTMLInsertGraph(nombre.archivo,file=.archivo,append=TRUE) HTMLhr(file = .archivo) } if (grafval != 1) HTMLhr(file = .archivo) } remove(list=c('.baseDatosActiva','.prueba.avarMR'), envir=.GlobalEnv) tkfocus(CommanderWindow()) } OKCancelHelp(helpSubject="RcmdrPlugin.EACSPIR",reset="avar.MR",apply="avar.MR") tkgrid(getFrame(variableVar), labelRcmdr(variablesFrame, text=" "), getFrame(IDVar), sticky="nw") tkgrid(variablesFrame, sticky="w") intraFrame <- tkframe(dataTab) intraVariable <- tclVar(dialog.valores$intra.inicial) intraField <- ttkentry(intraFrame, width="12", textvariable=intraVariable) tkgrid(labelRcmdr(intraFrame,text=gettextRcmdr("Nombre del factor Intrasujetos: "),font="RcmdrTitleFont"), intraField,sticky="w") medrepFrame <- tkframe(dataTab) medrepVariable <- tclVar(dialog.valores$medrep.inicial) medrepField <- ttkentry(medrepFrame, width="12", textvariable=medrepVariable) tkgrid(labelRcmdr(medrepFrame,text=gettextRcmdr("Nombre de la variable cuantitativa: "),font="RcmdrTitleFont"), medrepField,sticky="w") tkgrid(intraFrame, sticky="nw") tkgrid(medrepFrame, sticky="nw") tkgrid(SCuadradosFrame, sticky="nw") tkgrid(statsFrame, sticky="nw") tkgrid(opsFrame, sticky="w") dialogSuffix(use.tabs=TRUE,grid.buttons=TRUE,tabs=c('dataTab','statisticsTab','optionsTab'), tab.names=c("Datos","Estadisticos","Opciones")) } ayuda.RcmdrPlugin.EACSPIR <- function(){ doItAndPrint("help(\"RcmdrPlugin.EACSPIR\")") invisible(NULL) }
MultLogLik <- function(x, nvec, paramch=1) { k <- length(x) p <- invbaselogit(x[-k])$probs if (paramch==1) { f <- (exp(x[k])-1)/(exp(x[k])+1) } if (paramch==2) { minp <- min(p) minf <- -minp/(1-minp) f <- (exp(x[k])+minf)/(exp(x[k])+1) } list("MultLogLik"=MultLogLikP(p, f, nvec)) } MultLogLikP <- function(p, f, nvec) { k <- length(p) if (length(nvec) != k * (k+1)/2) { stop("length mistmatch between p and nvec") } if (is.matrix(p)) { if (nrow(p) == 1) p <- c(p) else stop("p should be a vector") } minp <- min(p) minf <- -minp/(1-minp) if (is.na(minp) || is.na(f) || f < minf) { MultLogLik <- -Inf } else { Q <- (1-f) * p %*% t(p) + f * diag(p) R <- rep(1:k, times=k) C <- rep(1:k, each=k) Q[R > C] <- 2 * Q[R > C] qvec <- Q[R >= C] if (any(qvec <= 0 | qvec > 1)) { MultLogLik <- -Inf } else { MultLogLik <- sum(nvec * log(qvec)) } } return(MultLogLik) }
library(purrr) library(repurrrsive) map(sw_films, "characters") %>% map_int(length) %>% set_names(map_chr(sw_films, "title")) %>% sort() sw_species[[1]]$eye_colors map_chr(sw_species, "eye_colors") %>% strsplit(", ") %>% map_int(length) %>% set_names(map_chr(sw_species, "name")) map_lgl(sw_planets[[61]], ~ "unknown" %in% .x) %>% sum() map_int(sw_planets, ~ map_lgl(.x, ~ "unknown" %in% .x) %>% sum()) %>% set_names(map_chr(sw_planets, "name")) %>% sort(decreasing = TRUE)
compare_accuracy <- function(..., rank_by = NULL, quiet = FALSE) { if (!is.logical(quiet)) { abort_argument_type("quiet", must = "be logical", not = quiet) } models <- list(...) models_name <- as.character(match.call(expand.dots = FALSE)$`...`) needs_refit <- purrr::map_lgl(models, get_fit_method) models <- purrr::map2(needs_refit, models, refit_lmerMod) models_accuracy <- purrr::map(models, accuracy) models_class <- purrr::map(models_accuracy, attributes) models_class <- purrr::map_chr(models_class, "model_class") models_accuracy <- purrr::map_dfr(models_accuracy, cbind) models_info <- data.frame(Model = models_name, Class = models_class) if (isFALSE(quiet)) { warn_compare_accuracy(models, models_class, needs_refit) } compare <- cbind(models_info, models_accuracy) compare <- dplyr::select( compare, .data$Model, .data$Class, tidyselect::starts_with("R2"), tidyselect::everything() ) if (!is.null(rank_by)) { if (rank_by %in% names(compare)) { dplyr::arrange(compare, .data[[rank_by]]) } else { abort_argument_value("rank_by", names(compare)) } } else { compare } } warn_compare_accuracy <- function(models, models_class, needs_refit) { models_response <- purrr::map2(models, models_class, get_model_response) same_response <- all( purrr::map_lgl(models_response, ~ identical(.x, models_response[[1]])) ) if (isFALSE(same_response)) { rlang::warn("Not all models have the same response variable.") } same_class <- all( purrr::map_lgl(models_class, ~ identical(.x, models_class[[1]])) ) if (isFALSE(same_class)) { rlang::warn("Not all models are of the same class.") } if (any(needs_refit)) { rlang::warn("Some models were refit using maximum likelihood.") } } get_model_response <- function(model, model_class) { if (grepl("lvmisc_cv_model", model_class)) { model <- attributes(model)$lvmisc_cv_model } formula <- stats::formula(model) outcome <- as.character(rlang::f_lhs(formula)) model_data <- stats::model.frame(model) model_data[[outcome]] } get_fit_method <- function(model) { if ("lmerMod" %in% class(model)) { REML <- grepl("REML", summary(model)$methTitle) } else { REML <- FALSE } REML } refit_lmerMod <- function(needs_refit, model) { requireNamespace("lme4", quietly = TRUE) if (isTRUE(needs_refit)) { model_formula <- stats::formula(model) model_data <- stats::model.frame(model) lme4::lmer(model_formula, model_data, REML = FALSE) } else { model } }
context("MODIStsp Test 6: http download on \"combined\" datasets and mosaicing of MODIS tiles") test_that( "Tests on MODIStsp", { skip_on_cran() skip_on_travis() MODIStsp(test = 6) out_files_dat <- list.files( file.path(tempdir(), "MODIStsp/LAI_8Days_500m_v61"), pattern = "\\.tif$", recursive = TRUE, full.names = TRUE) file_sizes_dat <- file.info(out_files_dat)$size means <- unlist( lapply(out_files_dat, FUN = function(x) { mean(suppressWarnings(raster::getValues(raster::raster(x))), na.rm = T) }) ) expect_equal(means, c(145.8004, 145.7715), tolerance = 0.001, scale = 1) r <- raster::raster(out_files_dat[1]) expect_true(sf::st_is_longlat(st_crs(r))) expect_equal(raster::res(r), c(0.01, 0.01), tolerance = 0.001, scale = 1) context("MODIStsp Test 6: No Reprocessing works as expected") t1 <- Sys.time() MODIStsp(test = 6) tt <- Sys.time() - t1 expect_true(tt < 5) unlink(out_files_dat) context("MODIStsp Test 6: multiple nodata and nodata_change") MODIStsp(test = "06a") means <- unlist( lapply(out_files_dat, FUN = function(x) { mean(raster::getValues(suppressWarnings(raster::raster(x))), na.rm = T) }) ) expect_equal(means, c(1.315164, 1.247541), tolerance = 0.001, scale = 1) unlink(out_files_dat) } )
library(devtools) library(dplyr) library(readr) january_2018 <- as_tibble(read_csv("inst/extdata/january_2018.csv")) usethis::use_data(january_2018, overwrite = TRUE)
check_delete_args <- function(ds, p, cols_mis, stochastic) { if (!is_df_or_matrix(ds)) { stop("ds must be a data.frame or a matrix") } if (is.numeric(p)) { if (length(p) != 1L && length(p) != length(cols_mis)) { stop("p must be of length 1 or length must equal cols_mis") } else { if (any(p < 0 | p > 1)) { stop("probabilties in p must be between 0 and 1") } } } else { stop("p must be numeric") } if (is.numeric(cols_mis)) { if (any(cols_mis < 1 | cols_mis > ncol(ds))) { stop("indices in cols_mis must be in 1:ncol(ds)") } } else if (is.character(cols_mis)) { if (!all(cols_mis %in% colnames(ds))) { stop("all entries of cols_mis must be in colnames(ds)") } } else { stop("cols_mis must be a vector of column names or indices of ds") } if (anyDuplicated(cols_mis) != 0) { duplicated_cols <- unique(cols_mis[duplicated(cols_mis)]) warning( "there are duplicates in cols_mis:\n", duplicated_cols, "\n this may result in a too high percentage of missing values" ) } if (!is.logical(stochastic)) { stop("stochastic must be logical") } else if (length(stochastic) != 1L) { stop("the length of stochastic must be 1") } } check_delete_args_MCAR <- function(ds, p, cols_mis, stochastic, p_overall) { check_delete_args( ds = ds, p = p, cols_mis = cols_mis, stochastic = stochastic ) if (!is.logical(p_overall) | length(p_overall) != 1L) { stop("p_overall must be logical of length 1") } else if (p_overall & !stochastic & length(p) != 1L) { stop("if p_overall = TRUE, then length(p) must be 1") } } check_delete_args_MAR <- function(ds, p, cols_mis, cols_ctrl, stochastic) { check_delete_args( ds = ds, p = p, cols_mis = cols_mis, stochastic = stochastic ) if (!is.null(cols_ctrl)) { if (is.numeric(cols_ctrl)) { if (any(cols_ctrl < 1 | cols_ctrl > ncol(ds))) { stop("indices in cols_ctrl must be in 1:ncol(ds)") } } else if (is.character(cols_ctrl)) { if (!all(cols_ctrl %in% colnames(ds))) { stop("all entries of cols_ctrl must be in colnames(ds)") } } else { stop("cols_ctrl must be a vector of column names or indices of ds") } } if (any(is.na(ds[, cols_ctrl]))) { stop("cols_ctrl must be completely observed; no NAs in ds[, cols_ctrl] allowed") } if (length(cols_mis) != length(cols_ctrl)) { stop("length(cols_mis) must equal length(cols_ctrl)") } if (any(cols_ctrl %in% cols_mis)) { stop( "to ensure MAR no ctrl_col is allowed to be in cols_mis;\n", "problematic cols_ctrl:\n", paste(cols_ctrl[cols_ctrl %in% cols_mis], collapse = ", ") ) } } check_delete_args_MNAR <- function(ds, p, cols_mis, stochastic) { check_delete_args(ds = ds, p = p, cols_mis = cols_mis, stochastic = stochastic) if (any(is.na(ds[, cols_mis]))) { stop("cols_mis must be completely observed; no NAs in ds[, cols_mis] allowed") } } check_cols_ctrl_1_to_x <- function(ds, cols_ctrl) { cols_prob <- integer(0) for (k in seq_along(cols_ctrl)) { if (!(is.ordered(ds[, cols_ctrl[k], drop = TRUE]) | is.numeric(ds[, cols_ctrl[k], drop = TRUE]))) { cols_prob <- c(cols_prob, cols_ctrl[k]) } } if (length(cols_prob) > 0L) { stop( "all cols_ctrl must be numeric or ordered factors;\n", "problematic column(s): ", paste(cols_prob, collapse = ", ") ) } TRUE } find_groups <- function(x, cutoff_fun, prop, use_lpSolve, ordered_as_unordered, ...) { unique_x <- unique(x) nr_unique <- length(unique_x) if (nr_unique == 1) { warning("grouping not possible, because x is constant") groups <- list(g1 = seq_along(x), g2 = NULL) } else if (is.factor(x) && (ordered_as_unordered || !is.ordered(x))) { groups <- find_groups_by_prop(x, prop = prop, use_lpSolve) } else { cutoff_fun <- match.fun(cutoff_fun) groups <- find_groups_by_cutoff_val(x, cutoff_fun(x, ...)) } groups } find_groups_by_cutoff_val <- function(x, cutoff_val) { below <- x < cutoff_val above <- which(!below) below <- which(below) if ((length(below) == 0L) && length(unique(x)) != 1L) { below <- x <= cutoff_val above <- which(!below) below <- which(below) } list(g1 = below, g2 = above) } find_groups_by_prop <- function(x, prop, use_lpSolve = TRUE) { ux <- unique(x) nr_ux <- tabulate(match(x, ux)) if (use_lpSolve) { if (requireNamespace("lpSolve", quietly = TRUE)) { solution <- lpSolve::lp( direction = "min", objective.in = nr_ux, const.mat = matrix(nr_ux, nrow = 1), const.dir = ">=", const.rhs = prop * length(x), all.bin = TRUE ) if (solution$status == 0) { g1_ux <- ux[solution$solution > 0] } else { stop("lpSolve found no solution") } } else { stop("Package \"lpSolve\" needed. Either install it or use \"use_lpSolve = FALSE\".") } } else { g1_ux <- cumsum(nr_ux) <= ceiling(prop * length(x)) g1_ux <- ux[g1_ux] } if (length(g1_ux) == 0L && length(unique(x)) != 1) { g1_ux <- ux[1] } find_groups_by_values(x, g1_ux) } find_groups_by_values <- function(x, values) { g1 <- x %in% values g2 <- which(!g1) g1 <- which(g1) list(g1 = g1, g2 = g2) } adjust_p <- function(p, cols_mis) { if (length(p) == 1L) { p <- rep(p, length(cols_mis)) } p } calc_nr_mis_g1 <- function(nr_g1, p_mis_g1, nr_g2, nr_mis, x) { if (nr_mis == 0L) { nr_mis_g1 <- 0L } else if (nr_g2 == 0L) { nr_mis_g1 <- nr_mis } else { nr_mis_g1_ceil <- ceiling(nr_g1 * p_mis_g1) nr_mis_g1_floor <- floor(nr_g1 * p_mis_g1) odds_ceil <- nr_mis_g1_ceil / nr_g1 / ((nr_mis - nr_mis_g1_ceil) / nr_g2) odds_floor <- nr_mis_g1_floor / nr_g1 / ((nr_mis - nr_mis_g1_floor) / nr_g2) if (abs(1 / x - odds_ceil) < abs(1 / x - odds_floor)) { nr_mis_g1 <- nr_mis_g1_ceil } else { nr_mis_g1 <- nr_mis_g1_floor } } nr_mis_g1 }
fdskrls <- function(object,...){ d <- ncol(object$X) n <- nrow(object$X) lengthunique <- function(x){length(unique(x))} fdderivatives =object$derivatives fdavgderivatives =object$avgderivatives fdvar.var.avgderivatives=object$var.avgderivatives binaryindicator <-which(apply(object$X,2,lengthunique)==2) if(length(binaryindicator)==0){ } else { est <- se <- matrix(NA,nrow=1,ncol=length(binaryindicator)) diffsstore <- matrix(NA,nrow=n,ncol=length(binaryindicator)) for(i in 1:length(binaryindicator)){ X1 <- X0 <- object$X X1[,binaryindicator[i]] <- max(X1[,binaryindicator[i]]) X0[,binaryindicator[i]] <- min(X0[,binaryindicator[i]]) Xall <- rbind(X1,X0) h <- matrix(rep(c(1/n,-(1/n)),each=n),ncol=1) pout <- predict(object,newdata=Xall,se=TRUE) est[1,i] <- t(h)%*%pout$fit se[1,i] <- as.vector(sqrt(t(h)%*%pout$vcov.fit%*%h))*sqrt(2) diffs <- pout$fit[1:n]-pout$fit[(n+1):(2*n)] diffsstore[,i] <- diffs } object$derivatives[,binaryindicator] <- diffsstore object$avgderivatives[,binaryindicator] <- est object$var.avgderivatives[,binaryindicator] <- se^2 object$binaryindicator[,binaryindicator] <- TRUE } return(invisible(object)) }
numtocat.syn <- function(data, numtocat = NULL, print.flag = TRUE, cont.na = NULL, catgroups = 5, style.groups = "quantile") { if (!is.data.frame(data)) stop("Data must be a data.frame.\n", call. = FALSE) varnames <- names(data) if (!is.null(numtocat)) { if (is.numeric(numtocat)) { if (!all(numtocat %in% 1:length(data))) stop("Column indices must be between 1 and ", length(data), ".", sep = "", call. = FALSE) varnos <- numtocat numtocat <- names(data)[varnos] } else { if (!all(numtocat %in% varnames)) stop("Variable(s) ", paste(numtocat[!numtocat %in% varnames], collapse = ", "), " not in data.\n", sep = "", call. = FALSE) varnos <- match(numtocat,varnames) } vclass <- sapply(data[, varnos, drop = FALSE], is.numeric) if (!all(vclass)) stop("Variable(s) in numtocat (", paste(numtocat[!vclass], collapse = ", "), ") not numeric.\n", sep = "", call. = FALSE) } else { varnos <- (1:length(data))[sapply(data, is.numeric)] numtocat <- names(data)[varnos] } if (length(catgroups) == 1) catgroups <- rep(catgroups,length(numtocat)) else if (length(catgroups) != length(numtocat)) stop("catgroups must be a single number or a vector of the same length as numtocat.\n", call. = FALSE) if (any(catgroups < 2)) stop("catgroups must all be > 1.", call. = FALSE) if (!is.null(cont.na)) { if (!is.list(cont.na)) stop("cont.na must be a list.\n", call. = FALSE) if (!all(names(cont.na) %in% numtocat)) stop("Variable(s): ", paste(names(cont.na)[!names(cont.na) %in% numtocat],collapse = ", "), " in cont.na not in the variables being grouped.\n", call. = FALSE) cna <- as.list(rep(NA,length(numtocat))) for (i in 1:length(cont.na)) cna[[match(names(cont.na)[i],numtocat)]] <- cont.na[[i]] } else { cna <- as.list(rep(NA,length(numtocat))) } names(cna) <- numtocat if (print.flag == TRUE) cat("Variable(s) ", paste(numtocat, collapse = ", "), " grouped into categories.\n", sep = "") breaks <- vector("list", length(varnos)); names(breaks) <- numtocat levels <- vector("list", length(varnos)); names(levels) <- numtocat orig <- data[, varnos, drop = FALSE] names(orig) <- paste("orig", names(orig), sep = ".") for (i in 1:length(varnos)) { grpd <- group_var(data[, varnos[i]], cont.na = cna[[i]], n = catgroups[i], style = style.groups) data[, varnos[i]] <- grpd$x breaks[[i]] <- grpd$breaks levels[[i]] <- grpd$levels } return(list(data = data, breaks = breaks, levels = levels, orig = orig, cont.na = cna, numtocat = numtocat, ind = varnos)) } group_var <- function(x, n = 5, style = "quantile", cont.na = NA) { if (!is.numeric(x)) stop("x must be numeric.\n", call. = FALSE) xnm <- x[!(x %in% cont.na) & !is.na(x)] my_breaks <- unique(classIntervals(xnm, n = n, style = style)$brks) xnm_grouped <- cut(xnm, breaks = my_breaks, dig.lab = 8, right = FALSE, include.lowest = TRUE) my_levels <- c(levels(xnm_grouped), cont.na[!is.na(cont.na)]) x[!(x %in% cont.na) & !is.na(x)] <- as.character(xnm_grouped) x <- as.factor(x) list(x = x, breaks = my_breaks, levels = my_levels) }
cv.stenv <- function(X, Y, q, u, m, nperm) { Y <- as.matrix(Y) a <- dim(Y) n <- a[1] r <- a[2] p <- ncol(X) prederr <- rep(0, nperm) for (i in 1:nperm) { id <- sample(n, n) Xn <- X[id, ] Yn <- Y[id, ] Yn <- as.matrix(Yn) for (j in 1:m) { id.test <- (floor((j - 1) * n / m) + 1) : ceiling(j * n / m) id.train <- setdiff(1:n, id.test) X.train <- Xn[id.train, ] Y.train <- Yn[id.train, ] X.test <- Xn[id.test, ] Y.test <- Yn[id.test, ] n.test <- length(id.test) fit <- stenv(X.train, Y.train, q, u, asy = F) betahat <- fit$beta muhat <- fit$mu resi <- as.matrix(Y.test - matrix(1, n.test, 1) %*% t(muhat) - as.matrix(X.test) %*% betahat) sprederr <- apply(resi, 1, function(x) sum(x ^ 2)) prederr[i] <- prederr[i] + sum(sprederr) } } return(sqrt(mean(prederr / n))) }
plot.eyefit <- function(x, ...){ xv <- seq(0, x$max.dist, l=201) yv <- max(apply(summary(x)[,c("sigmasq", "tausq")],1,sum)) plot(xv, yv, type="n", ...) lines(x) return(invisible()) } lines.eyefit <- function(x, ...){ lapply(x, lines.variomodel, ...) return(invisible()) } summary.eyefit <- function(object, ...){ if(length(object) == 0) return(NULL) else{ res <- data.frame(t(rep(0,7))) names(res) <-c("cov.model","sigmasq","phi","tausq", "kappa", "kappa2", "practicalRange") for(i in 1:length(object)){ tmp <- unclass(unlist(object[[i]])) if (tmp["cov.model"] != "gneiting.matern") tmp["kappa2"] <- NA if (all(tmp["cov.model"] != c("powered.exponential","cauchy","gencauchy","matern"))) tmp["kappa"] <- NA res[i,] <- tmp[c("cov.model","cov.pars1","cov.pars2","nugget", "kappa", "kappa2", "practicalRange")] } } return(res) } print.summary.eyefit <- function(x, ...){ print(x, ...) return(invisible()) } print.eyefit <- function(x, ...){ print(summary(x), ...) return(invisible()) } eyefit <- function(vario, silent=FALSE){ if(!requireNamespace("tcltk", quietly=TRUE)) stop("package tcltk is required to run eyefit()") geterrmessage() done <- tclVar(0) eyefit.env <- new.env() assign("eyefit.tmp", list(), envir=eyefit.env) dmax <- max(vario$u) kappa1 <- tclVar("0.5") kappa2 <- tclVar("1.0") kernel<- tclVar("exponential") mdist <- tclVar(max(vario$u)) nugget <- tclVar(0.1*(max(vario$v))) sill <- tclVar(0.8*(max(vario$v))) range <- tclVar(dmax/3) replot <- function(...) { k <- as.character(tclObj(kernel)) kp1 <- as.numeric(tclObj(kappa1)) kp2 <- as.numeric(tclObj(kappa2)) maxdist <- as.numeric(tclObj(mdist)) sigmasq <- as.numeric(tclObj(sill)) phi <- as.numeric(tclObj(range)) tausq <- as.numeric(tclObj(nugget)) eval(substitute(plot(vario))) fit <- get("eyefit.tmp", envir=eyefit.env) lapply(fit, function(x) lines.variomodel(seq(0, maxdist, l=100), cov.model=x$cov.model, kappa=x$kappa, cov.pars=x$cov.pars, nug=x$nug, max.dist=x$max.dist)) if (k == "gneiting.matern" |k == "gencauchy" ) { lines.variomodel(x=seq(0,maxdist,l=100), cov.model=k, kappa=c(kp1,kp2), cov.pars = c(sigmasq,phi),nug=tausq,max.dist=maxdist) } else if (k == "powered.exponential" || k =="cauchy" || k == "matern") { lines.variomodel(x=seq(0,maxdist,l=100), cov.model=k, kappa=kp1, cov.pars = c(sigmasq,phi),nug=tausq,max.dist=maxdist) } else lines.variomodel(x=seq(0,maxdist,l=100), cov.model=k, cov.pars=c(sigmasq,phi), nug=tausq,max.dist=maxdist) } redraw <- function(...) { var <- as.character(tclObj(kernel)) if (var == "gneiting.matern" | var == "gencauchy") { tkconfigure(entry.kappa1, state="normal") tkconfigure(ts5, state="normal") tkfocus(entry.kappa1) tkconfigure(entry.kappa2, state="normal") tkconfigure(ts6, state="normal") } else if (var == "powered.exponential" || var =="cauchy" || var == "matern") { tkconfigure(entry.kappa1,state="normal") tkconfigure(ts5,state="normal") tkfocus(entry.kappa1) tkconfigure(entry.kappa2,state="disabled") tkconfigure(ts6,state="disabled") } else { tkconfigure(ts5,state="disabled") tkconfigure(ts6,state="disabled") tkconfigure(entry.kappa1,state="disabled") tkconfigure(entry.kappa2,state="disabled") } replot() } base <- tktoplevel() tkwm.title(base, "Eyefit 1.0") spec.frm <- tkframe(base,borderwidth=2) left.frm <- tkframe(spec.frm) right.frm <- tkframe(spec.frm) frame1 <- tkframe(left.frm, relief="groove", borderwidth=2) tkpack(tklabel(frame1,text="Parameters"),fill="both",side="top") entry.mdist <-tkentry(frame1,width="4",textvariable=mdist) tkpack(ts1<-tkscale(frame1, label="Max. Distance",command=replot, from=0.00, to=dmax, showvalue=0, variable=mdist, resolution=0.01, orient="horiz",relief="groove"), fill="both",expand=1,padx=3,pady=2,ipadx=3,ipady=2,side="left") tkpack(entry.mdist,fill="none",side="right") frame3 <- tkframe(left.frm, relief="groove", borderwidth=2) tkpack(tklabel(frame3,text="Cov. Parameters"),fill="both",side="top") entry.sill <-tkentry(frame3,width="4",textvariable=sill) tkpack(ts2<-tkscale(frame3, label="Sill (sigmasq):",command=replot, from=0.00, to=2*max(vario$v), showvalue=0, variable=sill, resolution=0.01, orient="horiz",relief="groove"), fill="none",expand=1,padx=3,pady=2,ipadx=3,ipady=2,side="left") tkpack(entry.sill,side="right") frame4 <- tkframe(left.frm, relief="groove", borderwidth=2) entry.range <-tkentry(frame4,width="4",textvariable=range) tkpack(ts3<-tkscale(frame4, label="Range (phi):",command=replot, from=0.00, to=2*dmax, showvalue=1, variable=range, resolution=0.01, orient="horiz",relief="groove"), fill="x",expand=1,padx=3,pady=2,ipadx=3,ipady=2,side="left") tkpack(entry.range,side="right") frame5 <- tkframe(left.frm, relief="groove", borderwidth=2) tkpack(tklabel(frame5,text="Nugget"),fill="both",side="top") entry.nugget <-tkentry(frame5,width="4",textvariable=nugget) tkpack(ts4<-tkscale(frame5, label="Nugget (tausq):",command=replot, from=0.00, to=2*max(vario$v), showvalue=1, variable=nugget, resolution=0.01, orient="horiz",relief="groove"), fill="x",expand=1,padx=3,pady=2,ipadx=3,ipady=2,side="left") tkpack(entry.nugget,side="right") frame6 <- tkframe(left.frm, relief="groove", borderwidth=2) tkpack(tklabel(frame6,text="Kappa"),fill="both",side="top") entry.kappa1<-tkentry(frame6,width="4",textvariable=kappa1,state="disabled") tkpack(ts5<-tkscale(frame6, label="Kappa 1:",command=replot, from=0.00, to=10.00, showvalue=1, variable=kappa1,state="disabled", resolution=0.01, orient="horiz",relief="groove"), fill="x",expand=1,padx=3,pady=2,ipadx=3,ipady=2,side="left") tkpack(entry.kappa1,side="right",fill="none") frame7 <- tkframe(left.frm, relief="groove", borderwidth=2) entry.kappa2 <-tkentry(frame7,width="4",textvariable=kappa2,state="disabled") tkpack(ts6<-tkscale(frame7, label="Kappa 2:",command=replot, from=0.00, to=10.00, showvalue=1, variable=kappa2,state="disabled", resolution=0.01, orient="horiz",relief="groove"), fill="x",expand=1,padx=3,pady=2,ipadx=3,ipady=2,side="left") tkpack(entry.kappa2,side="right",fill="none") frame2 <- tkframe(right.frm, relief="groove", borderwidth=2) tkpack(tklabel(frame2, text="Function")) for ( i in c("cauchy","gencauchy","circular","cubic","exponential","gaussian", "gneiting","gneiting.matern","linear","matern","power", "powered.exponential","pure.nugget","spherical","wave") ) { tmp <- tkradiobutton(frame2, command=redraw, text=i, value=i, variable=kernel) tkpack(tmp, anchor="w") } OnOK <- function(){ replot() } OnQuit <- function(){ tclvalue(done)<-2 } OnClear <- function(aux=vario){ assign("eyefit.tmp", list(), envir=eyefit.env) plot(aux) } OnSave <- function(){ k <- as.character(tclObj(kernel)) kp1 <- as.numeric(tclObj(kappa1)) if(k == "gneiting.matern") kp2 <- as.numeric(tclObj(kappa2)) else kp2 <- NULL maxdist <- as.numeric(tclObj(mdist)) sigmasq <- as.numeric(tclObj(sill)) phi <- as.numeric(tclObj(range)) tausq <- as.numeric(tclObj(nugget)) aux <- list(cov.model=k, cov.pars=c(sigmasq, phi), nugget=tausq, kappa=c(kp1,kp2), lambda = vario$lambda, trend = vario$trend, practicalRange = practicalRange(cov.model=k, phi = phi, kappa = kp1), max.dist=maxdist) oldClass(aux) <- "variomodel" assign("eyefit.tmp", c(get("eyefit.tmp", envir=eyefit.env),list(aux)), envir=eyefit.env) replot() } tkpack(frame1, frame3, frame4, frame5, frame6, frame7, fill="x") tkpack(frame2, fill="x") tkpack(left.frm, right.frm,side="left", anchor="n") c.but <- tkbutton(base,text="Clear", command=function(){OnClear(vario)}) q.but <- tkbutton(base, text="Quit", command=OnQuit) save.but <- tkbutton(base, text="Save", command=OnSave) tkpack(spec.frm) tkpack(q.but, side="right") tkpack(c.but, side="left") tkpack(save.but, side="right") replot() tkbind(entry.kappa1, "<Return>", function(){replot()}) tkbind(entry.kappa2, "<Return>", function(){replot()}) tkbind(base, "<Destroy>", function() tclvalue(done)<-2) tkwait.variable(done) tkdestroy(base) if (!silent){ fit <- get("eyefit.tmp", envir=eyefit.env) oldClass(fit) <- "eyefit" return(fit) } else return(invisible()) }
hmmsim2.cont <- function(workparm, M, n, zeroindex, emit_x=NULL, zeroinfl_x=NULL, timeindex){ if(floor(M)!=M | M<2) stop("The number of latent states must be an integer greater than or equal to 2!") tempmat <- matrix(0,nrow=n,ncol=1) ncovprior <- 0 covprior <- tempmat ncovtpm <- 0 covtpm <- tempmat if(is.null(emit_x)){ ncovemit <- 0 covemit <- ncol(emit_x) }else{ ncovemit <- ncol(emit_x) covemit <- emit_x } if(is.null(zeroinfl_x)){ ncovzeroinfl <- 0 covzeroinfl <- tempmat }else{ ncovzeroinfl <- ncol(zeroinfl_x) covzeroinfl <- zeroinfl_x } if(ncovprior+ncovtpm+ncovemit+ncovzeroinfl==0){ stop("Need at least 1 covariates!") }else{ result <- hmm_cov_gen_cont(workparm, M, n, ncovprior, covprior, ncovtpm, covtpm, ncovzeroinfl, covzeroinfl, ncovemit, covemit, zeroindex, timeindex) series <- result[,1] state <- result[,2] return(list(series=series,state=state)) } }
strm <- function(formula, id,data, listw,time=2,wide=FALSE,filter_options=NULL, returndf=FALSE,...){ formin <- formula if(missing(wide) | wide == FALSE){ wide <- FALSE } else { warning("Data is in wide format. strm assumes you include the temporally-lagged explanatory variables manually.") wide <- wide } if (returndf==TRUE){ returndf <- TRUE } else { returndf <- FALSE } y <- deparse(formula(formin)[[2]]) xs <- attributes(terms(formin))$term.labels modframe0 <- cbind.data.frame(model.frame(formin, data=data), data[,which(names(data)%in% c(y,xs)==FALSE)]) if(time==1){ warning("You have set time = 1, indicating a spatial error model. No temporal component will be assessed.") outdf <- createlagvars(data = modframe0, vars=c(y,xs), id=id, time=1,wide, filter_options) rhs <- paste(c(xs), collapse=" + ") outdfnames <- names(outdf) outdfnamesclean <- gsub("*\\(*)*","",outdfnames) names(outdf) <- outdfnamesclean y <- gsub("*\\(*)*","",y) rhs <- gsub("*\\(*)*","",rhs) formout <- as.formula(paste0(y," ~ ", rhs)) message("The spatio-temporal regression model fitted:") message(deparse(formout)) modframe <- model.frame(formout, data=outdf) res<- spatialreg::errorsarlm(modframe,listw=listw,...) } else { if (wide==FALSE){ outdf <- createlagvars(data = modframe0, vars=c(y,xs), id=id, time=time,wide, filter_options) xs_Tlags <- rep(list(0), (time-1)) y_lags <- rep(list(0), (time-1)) for (i in 1:(time-1)){ xs_Tlags[[i]] <- paste0(xs,".","Tlag",i) y_lags[[i]] <- paste0(y,".","Tlag",i) } xs_Tlags <- as.vector(unlist(xs_Tlags)) y_lags <- as.vector(unlist(y_lags)) rhs <- paste(c(xs,xs_Tlags, y_lags), collapse=" + ") } else { outdf <- createlagvars(data = modframe0, vars=c(y,xs), id=id, time=time,wide, filter_options) rhs <- paste(c(xs), collapse=" + ") } outdfnames <- names(outdf) outdfnamesclean <- gsub("*\\(*)*","",outdfnames) names(outdf) <- outdfnamesclean y <- gsub("*\\(*)*","",y) rhs <- gsub("*\\(*)*","",rhs) formout <- as.formula(paste0(y," ~ ", rhs)) message("The spatio-temporal regression model fitted:") message(deparse(formout)) modframe <- model.frame(formout, data=outdf) res<- spatialreg::errorsarlm(modframe, listw=listw, ...) } if(returndf == TRUE){ return(list(res=res, modframe = modframe)) } else { return(res) } }
null_to_defeault <- function(x, d){ if ( is.null(x) ){ d }else{ x } }
test_that("NHL - Get NHL conferences info", { skip_on_cran() x <- nhl_conferences_info(conference_id = 7) cols <- c( "conference_id", "name", "link", "abbreviation", "short_name", "active" ) expect_equal(colnames(x), cols) expect_s3_class(x, 'data.frame') })
RFPW<-function(z){ n<-length(z) f.star<-function(tmp,i,j,k){ sign(tmp[i]+tmp[j]-2*tmp[k])+sign(tmp[i]+tmp[k]-2*tmp[j])+sign(tmp[j]+tmp[k]-2*tmp[i]) } f.vals<-numeric(n*(n-1)*(n-2)/6) iter<-1 for(i in 1:(n-2)){ for(j in (i+1):(n-1)){ for(k in (j+1):n){ f.vals[iter]<-f.star(z,i,j,k) iter<-iter+1 } } } T.stat<-sum(f.vals) b.calc<-function(s){ A<-B<-E<-0; if(s<(n-1)){ for(j in (s+1):(n-1)){ for(k in (j+1):n){ A=A+f.star(z,s,j,k) } } } if(s>1&&s<n){ for(j in 1:(s-1)){ for(k in (s+1):n){ B<-B+f.star(z,j,s,k) } } } if(s>2){ for(j in 1:(s-2)){ for(k in (j+1):(s-1)){ E<-E+f.star(z,j,k,s) } } } return(A+B+E) } b.vals<-unlist(lapply(1:n,b.calc)) b2.calc<-function(u,v){ A<-B<-E<-0; if(u>1){ for(j in 1:(u-1)){ A<-A+f.star(z,j,u,v) } } if((v-u)>1){ for(j in (u+1):(v-1)){ B<-B+f.star(z,u,j,v) } } if(v<n){ for(j in (v+1):n){ E<-E+f.star(z,u,v,j) } } return(A+B+E) } b2.vals<-numeric(n*(n-1)/2) iter<-1 for(i in 1:(n-1)){ for(j in (i+1):n){ b2.vals[iter]<-b2.calc(i,j) iter<-iter+1 } } sigma2.hat<-(n-3)*(n-4)/((n-1)*(n-2))*sum(b.vals^2)+(n-3)/(n-4)*sum(b2.vals^2)+n*(n-1)*(n-2)/6-(1-(n-3)*(n-4)*(n-5)/(n*(n-1)*(n-2)))*T.stat^2 outp<-list() outp$obs.stat<-T.stat/sqrt(sigma2.hat) outp$p.val<-2*(1-pnorm(abs(outp$obs.stat))) outp }
riem.rsup <- function(riemobj, weight=NULL, c=5, maxiter=50, eps=1e-5){ DNAME = paste0("'",deparse(substitute(riemobj)),"'") if (!inherits(riemobj,"riemdata")){ stop(paste0("* riem.rsup : input ",DNAME," should be an object of 'riemdata' class.")) } N = length(riemobj$data) myc = max(sqrt(.Machine$double.eps), as.double(c)) mymult = 1/myc myiter = max(50, as.integer(maxiter)) myeps = min(max(as.double(eps),0),1e-5) if ((is.null(weight)&&(length(weight)==0))){ myweight = rep(1/N, N) } else { myweight = as.double(weight) if (length(weight)!=N){ stop("* riem.rsup : 'weight' vector should be of matching length as the given data.") } if (any(weight)<=0){ stop("* riem.rsup : 'weight' vector should contain nonnegative real numbers only.") } } tmprun = clustering_sup_intrinsic(riemobj$name, riemobj$data, myweight, mymult, myiter, myeps) limit3d = tmprun$limits pdmat = tmprun$distance objmat = stats::as.dist(pdmat) mink = 2 maxk = min(10, round(N/2)) fimport = utils::getFromNamespace("hidden_kmedoids_best", "maotai") hcout = fimport(objmat, mink, maxk) k.opt = as.integer(hcout$opt.k) k.label = hcout$label[,(k.opt-1)] output = list() output$distance = pdmat output$cluster = k.label return(output) }
rprobdist <- function (dim, d, cond, alpha=1) { if (missing(d)) d = length(dim) else if (length(dim) < d) dim = dim * rep.int(1L, d) else if (length(dim) > d) stop("More than 'd' dimensions supplied") if (any(dim < 0)) stop("Dimensions must be non-negative") if (any(alpha < 0)) stop("Parameters must be non-negative") pars = rep(alpha, length.out=prod(dim)) out = c(rdirichlet(1, pars)) if (length(dim) > 1) dim(out) = dim if (!missing(cond)) { if (any(cond > length(dim)) || any(cond <= 0)) stop("cond must be ") out = conditionTable(out, seq_along(dim)[-cond], cond, order=FALSE) } return(out) }
NonLinearNoiseReduction <- function(HRVData, embeddingDim = NULL, radius = NULL , ECGsamplingFreq = NULL ) { kSdDenoising = 3 kthreshold = 1e-06 VerboseMessage(HRVData$Verbose, "Denoising RR time series using nonlinear techniques") CheckNIHR(HRVData) estimations = automaticEstimation(HRVData,timeLag=1,embeddingDim) embeddingDim = estimations[[2]] if (is.null(ECGsamplingFreq)) { RRresolution = diff(unique(sort(HRVData$Beat$RR))) RRresolution = ifelse(RRresolution < kthreshold, 0, RRresolution) zero.pos = which(RRresolution == 0) if (length(zero.pos) > 0){ RRresolution = RRresolution[-zero.pos] } Ts = median(RRresolution) VerboseMessage(HRVData$Verbose, paste("Estimated ECG resolution is ", rhrvFormat(Ts)," ms")) }else { Ts = 1000 / ECGsamplingFreq } noise = runif(n=length(HRVData$Beat$RR),min=-(Ts/2),max=(Ts/2)) HRVData$Beat$RR = HRVData$Beat$RR + noise if (is.null(radius)){ sdUniformDist = Ts/sqrt(12) radius = kSdDenoising * sdUniformDist } RRseries = nonLinearNoiseReduction(time.series=HRVData$Beat$RR, embedding.dim=embeddingDim, radius = radius) time = diffinv(tail(RRseries,-1))/1000 time = time + HRVData$Beat$Time[[1]] HRVData$Beat$Time = time HRVData$Beat$RR = NULL HRVData$Beat$niHR =NULL HRVData = BuildNIHR(HRVData) return(HRVData) }
sankoff.quartet <- function(dat, cost, p, l, weight) { erg <- .Call('sankoffQuartet', sdat = dat, sn = p, scost = cost, sk = l) sum(weight * erg) } parsimony <- function(tree, data, method = "fitch", cost=NULL, site = "pscore"){ if (!inherits(data, "phyDat")) stop("data must be of class phyDat") method <- match.arg(method, c("fitch", "sankoff")) if(!any(is.binary(tree)) || !is.null(cost)) method <- "sankoff" if (method == "sankoff") result <- sankoff(tree, data, cost=cost, site = site) if (method == "fitch") result <- fitch(tree, data, site = site) result } compressSites <- function(data) { attrData <- attributes(data) lev <- attr(data, "levels") LEV <- attr(data, "allLevels") l <- length(lev) nr <- attr(data, "nr") nc <- length(data) data <- unlist(data, FALSE, FALSE) attr(data, "dim") <- c(nr, nc) uni <- match(lev, LEV) fun <- function(x, uni) { u <- unique.default(x) res <- if (any(is.na(match(u, uni)))) return(x) match(x, u) } data <- apply(data, 1, fun, uni) index <- grp_duplicated(data, MARGIN=2L) pos <- which(!duplicated(index)) ntaxa <- nrow(data) res <- vector("list", ntaxa) for(i in seq_len(ntaxa)) res[[i]] <- data[i, pos] attrData$weight <- tapply(attrData$weight, index, sum) attrData$index <- NULL attrData$nr <- length(attrData$weight) attrData$compressed <- TRUE attributes(res) <- attrData res } parsinfo <- function(x, exact=TRUE) { nstates <- attr(x, "nc") up <- upperBound(x) eps <- 1e-8 low <- up low[up > (nstates - eps)] <- nstates - 1 if(exact){ ind <- which( (up > (1+eps)) & (up < (nstates-eps)) ) if(length(ind)>0) low[ind] <- lowerBound(getRows( x, ind )) ind <- which(low == up) } else ind <- which(up < (1+eps) ) cbind(ind, low[ind]) } lowerBound <- function(x, cost = NULL) { nc <- attr(x, "nc") nr <- attr(x, "nr") contrast <- attr(x, "contrast") rownames(contrast) <- attr(x, "allLevels") colnames(contrast) <- attr(x, "levels") nmax <- nrow(contrast) z <- matrix(unlist(x, FALSE, FALSE), length(x), length(attr(x, "weight")), byrow = TRUE) states <- apply(z, 2, unique.default, nmax = nmax) if(inherits(states, "matrix"))states <- asplit(states, 2) singles <- which(rowSums(contrast) == 1) noinfo <- which(rowSums(contrast) == nc) ambiguous <- which( (rowSums(contrast) > 1) & (rowSums(contrast) < nc)) fun <- function(states, contrast, singles, noinfo, ambiguous) { if (length(states) == 1) return(0) states <- setdiff(states, noinfo) if ( (length(states) == 0) | (length(states) == 1)) return(0) if (any(states %in% ambiguous)) { n <- 0 contrast <- contrast[states, , drop = FALSE] while (nrow(contrast) > 0) { m <- which.max(colSums(contrast)) contrast <- contrast[contrast[, m] == 0, , drop = FALSE] n <- n + 1 } return(n - 1) } else return(length(states) - 1) } res <- sapply(states, fun, contrast, singles, noinfo, ambiguous) res } upperBound <- function(x, cost = NULL) { tree <- stree(length(x), tip.label = names(x)) if (is.null(cost)) cost <- 1 - diag(attr(x, "nc")) sankoff(tree, x, cost = cost, site = "site") } CI <- function(tree, data, cost = NULL, sitewise = FALSE) { if (sitewise) pscore <- sankoff(tree, data, cost = cost, site = "site") else pscore <- sankoff(tree, data, cost = cost) weight <- attr(data, "weight") data <- subset(data, tree$tip.label) m <- lowerBound(data, cost = cost) if (sitewise) { return( (m / pscore)[attr(data, "index")]) } sum(m * weight) / pscore } RI <- function(tree, data, cost = NULL, sitewise = FALSE) { if (sitewise) pscore <- sankoff(tree, data, cost = cost, site = "site") else pscore <- sankoff(tree, data, cost = cost) data <- subset(data, tree$tip.label) weight <- attr(data, "weight") m <- lowerBound(data, cost = cost) g <- upperBound(data, cost = cost) if (sitewise) { res <- (g - pscore) / (g - m) return(res[attr(data, "index")]) } m <- sum(m * weight) g <- sum(g * weight) (g - pscore) / (g - m) } old2new.phyDat <- function(obj) { att <- attributes(obj) l <- length(obj) contrast <- attr(obj, "contrast") nr <- attr(obj, "nr") X <- matrix(rep(rowSums(contrast), each = nr), nrow = nr) for (i in 1:l) obj[[i]][obj[[i]] > 0] <- 1 res <- vector("list", l) contrast[contrast == 0] <- 1e6 for (i in 1:l) { tmp <- tcrossprod(obj[[i]], contrast) - X res[[i]] <- unlist(apply(tmp, 1, function(x) which(x < 1e-6)[1])) } attributes(res) <- att res } new2old.phyDat <- function(data) { contrast <- attr(data, "contrast") for (i in seq_along(data)) data[[i]] <- contrast[data[[i]], , drop = FALSE] data } prepareDataSankoff <- function(data) { contrast <- attr(data, "contrast") contrast[contrast == 0] <- 1e+06 contrast[contrast == 1] <- 0 for (i in seq_along(data)) data[[i]] <- contrast[data[[i]], , drop = FALSE] data } fit.sankoff <- function(tree, data, cost, returnData = c("pscore", "site", "data")) { tree <- reorder(tree, "postorder") returnData <- match.arg(returnData) node <- tree$edge[, 1] edge <- tree$edge[, 2] weight <- attr(data, "weight") nr <- attr(data, "nr") q <- length(tree$tip.label) nc <- attr(data, "nc") m <- length(edge) + 1 dat <- vector(mode = "list", length = m) dat[1:q] <- data[tree$tip.label] node <- as.integer(node - 1) edge <- as.integer(edge - 1) mNodes <- as.integer(max(node) + 1) tips <- as.integer( (seq_along(tree$tip.label)) - 1) res <- .Call('sankoff3', dat, as.numeric(cost), as.integer(nr), as.integer(nc), node, edge, mNodes, tips) root <- getRoot(tree) erg <- .Call('C_rowMin', res[[root]], as.integer(nr), as.integer(nc)) if (returnData == "site") return(erg) pscore <- sum(weight * erg) result <- pscore if (returnData == "data") { result <- list(pscore = pscore, dat = res) } result } pnodes <- function(tree, data, cost) { tree <- reorder(tree, "postorder") node <- tree$edge[, 1] edge <- tree$edge[, 2] nr <- nrow(data[[1]]) nc <- ncol(data[[1]]) node <- as.integer(node - 1) edge <- as.integer(edge - 1) .Call('pNodes', data, as.numeric(cost), as.integer(nr), as.integer(nc), node, edge) } indexNNI <- function(tree) { parent <- tree$edge[, 1] child <- tree$edge[, 2] ind <- which(child %in% parent) Nnode <- tree$Nnode edgeMatrix <- matrix(0, (Nnode - 1), 5) pvector <- integer(max(parent)) pvector[child] <- parent tips <- !logical(max(parent)) tips[parent] <- FALSE cvector <- vector("list", max(parent)) for (i in seq_along(parent)) cvector[[parent[i]]] <- c(cvector[[parent[i]]], child[i]) k <- 0 for (i in ind) { p1 <- parent[i] p2 <- child[i] e34 <- cvector[[p2]] ind1 <- cvector[[p1]] e12 <- ind1[ind1 != p2] if (pvector[p1]) e12 <- c(p1, e12) edgeMatrix[k + 1, ] <- c(e12, e34, p2) k <- k + 1 } attr(edgeMatrix, "root") <- cvector[[min(parent)]] edgeMatrix } sankoff.nni <- function(tree, data, cost, ...) { if (is.rooted(tree)) tree <- reorder(unroot(tree), "postorder") INDEX <- indexNNI(tree) rootEdges <- attr(INDEX, "root") if (!inherits(data, "phyDat")) stop("data must be of class phyDat") levels <- attr(data, "levels") l <- length(levels) weight <- attr(data, "weight") p <- attr(data, "nr") i <- 1 tmp <- fit.sankoff(tree, data, cost, returnData = "data") p0 <- tmp[[1]] datf <- tmp[[2]] datp <- pnodes(tree, datf, cost) parent <- tree$edge[, 1] m <- dim(INDEX)[1] k <- min(parent) pscore <- numeric(2 * m) for (i in 1:m) { ei <- INDEX[i, ] datn <- datf[ei[1:4]] if (!(ei[5] %in% rootEdges)) datn[1] <- datp[ei[1]] pscore[(2 * i) - 1] <- sankoff.quartet(datn[ c(1, 3, 2, 4)], cost, p, l, weight) pscore[(2 * i)] <- sankoff.quartet(datn[ c(1, 4, 3, 2)], cost, p, l, weight) } swap <- 0 candidates <- pscore < p0 while (any(candidates)) { ind <- which.min(pscore) pscore[ind] <- Inf if (ind %% 2) swap.edge <- c(2, 3) else swap.edge <- c(2, 4) tree2 <- changeEdge(tree, INDEX[(ind + 1) %/% 2, swap.edge]) test <- fit.sankoff(tree2, data, cost, "pscore") if (test >= p0) candidates[ind] <- FALSE if (test < p0) { p0 <- test swap <- swap + 1 tree <- tree2 candidates[ind] <- FALSE indi <- which(rep(colSums(apply(INDEX, 1, match, INDEX[(ind + 1) %/% 2, ], nomatch = 0)) > 0, each = 2)) candidates[indi] <- FALSE pscore[indi] <- Inf } } list(tree = tree, pscore = p0, swap = swap) } optim.parsimony <- function(tree, data, method = "fitch", cost = NULL, trace = 1, rearrangements = "SPR", ...) { if (method == "fitch") result <- optim.fitch(tree = tree, data = data, trace = trace, rearrangements = rearrangements, ...) if (method == "sankoff") result <- optim.sankoff(tree = tree, data = data, cost = cost, trace = trace, ...) result } pratchet <- function(data, start = NULL, method = "fitch", maxit = 1000, minit = 10, k = 10, trace = 1, all = FALSE, rearrangements = "SPR", perturbation = "ratchet", ...) { eps <- 1e-08 trace <- trace - 1 start_trees <- vector("list", maxit) search_trees <- vector("list", maxit) tree <- NULL mp <- Inf ROOTED <- FALSE weight <- attr(data, "weight") v <- rep(seq_along(weight), weight) w <- logical(length(weight)) if(method=="fitch") data <- removeParsimonyUninfomativeSites(data, recursive=TRUE) else data <- unique(data) if(!is.null(attr(data, "informative"))) w[attr(data, "informative")] <- TRUE else w[] <- TRUE star_tree <- ifelse(attr(data, "nr") == 0, TRUE, FALSE) add_taxa <- ifelse(is.null(attr(data, "duplicated")), FALSE, TRUE) nTips <- length(data) if (nTips < (3L + !ROOTED) || star_tree) { nam <- names(data) if (star_tree) tree <- stree(length(nam), tip.label = nam) else tree <- stree(nTips, tip.label = nam) if(add_taxa) tree <- addTaxa(tree, attr(data, "duplicated")) if(!ROOTED) tree <- unroot(tree) return(tree) } if (perturbation != "random_addition"){ if(is.null(start)) start <- optim.parsimony(fastme.ols(dist.hamming(data)), data, trace = trace-1, method = method, rearrangements = rearrangements, ...) tree <- start label <- intersect(tree$tip.label, names(data)) if (!is.binary(tree)){ tree <- multi2di(tree) if(method=="fitch") tree <- unroot(tree) } data <- subset(data, label) tree <- keep.tip(tree, label) attr(tree, "pscore") <- parsimony(tree, data, method = method, ...) mp <- attr(tree, "pscore") if (trace >= 0) print(paste("Best pscore so far:", attr(tree, "pscore"))) } FUN <- function(data, tree, method, rearrangements, ...) optim.parsimony(tree, data = data, method = method, rearrangements = rearrangements, ...) result <- tree if(!is.null(attr(data, "duplicated"))){ result <- addTaxa(result, attr(data, "duplicated")) } on.exit({ if (!all && inherits(result, "multiPhylo")) result <- result[[1]] if (length(result) == 1) result <- result[[1]] env <- new.env() start_trees <- start_trees[seq_len(i)] search_trees <- search_trees[seq_len(i)] class(start_trees) <- "multiPhylo" class(search_trees) <- "multiPhylo" start_trees <- .compressTipLabel(start_trees) search_trees <- .compressTipLabel(search_trees) assign("start_trees", start_trees, envir=env) assign("search_trees", search_trees, envir=env) if(perturbation == "ratchet" && all(Ntip(trees) > 3)) { spl <- as.splits(start_trees) result <- addConfidences(result, spl) if (inherits(result, "multiPhylo")) result <- .compressTipLabel(result) } attr(result, "env") <- env return(result) }) kmax <- 1 nTips <- length(tree$tip.label) for (i in seq_len(maxit)) { if (perturbation == "ratchet") { bsw <- tabulate(sample(v, replace = TRUE), length(weight))[w] bs_ind <- which(bsw > 0) bs_data <- getRows(data, bs_ind) attr(bs_data, "weight") <- bsw[bs_ind] if(length(bs_ind) > 0)p_trees <- optim.parsimony(tree, bs_data, trace = trace, method = method, rearrangements = rearrangements, ...) else p_trees <- stree(length(data), tip.label = names(data)) trees <- optim.parsimony(p_trees, data, trace = trace, method = method, rearrangements = rearrangements, ...) } if (perturbation == "stochastic") { p_trees <- rNNI(tree, floor(nTips / 2)) trees <- optim.parsimony(p_trees, data, trace = trace, method = method, rearrangements = rearrangements, ...) } if (perturbation == "random_addition") { p_trees <- random.addition(data) trees <- optim.parsimony(p_trees, data, trace = trace, method = method, rearrangements = rearrangements, ...) } if(!is.null(attr(data, "duplicated"))){ p_trees <- addTaxa(p_trees, attr(data, "duplicated")) trees <- addTaxa(trees, attr(data, "duplicated")) } start_trees[[i]] <- p_trees search_trees[[i]] <- trees pscores <- attr(trees, "pscore") mp1 <- min(pscores) if ( (mp1 + eps) < mp) { kmax <- 1 result <- trees tree <- trees mp <- mp1 } else{ kmax <- kmax + 1 if( all && (mp1 < (mp + eps)) && all(RF.dist(trees, result) > 0)) result <- c(result, trees) } if (trace >= 0) print(paste("Best pscore so far:", mp)) if ( (kmax >= k) && (i >= minit)) break() } } optim.sankoff <- function(tree, data, cost = NULL, trace = 1, ...) { if (!inherits(tree, "phylo")) stop("tree must be of class phylo") if (is.rooted(tree)) tree <- unroot(tree) tree <- reorder(tree, "postorder") if (!inherits(data, "phyDat")) stop("data must be of class phyDat") addTaxa <- FALSE mapping <- map_duplicates(data) if (!is.null(mapping)) { addTaxa <- TRUE tree2 <- drop.tip(tree, mapping[, 1]) tree2 <- unroot(tree2) tree <- reorder(tree2, "postorder") } rt <- FALSE dat <- prepareDataSankoff(data) l <- attr(dat, "nc") if (is.null(cost)) { cost <- matrix(1, l, l) cost <- cost - diag(l) } tree$edge.length <- NULL swap <- 0 iter <- TRUE pscore <- fit.sankoff(tree, dat, cost, "pscore") on.exit({ if (rt) tree <- acctran(tree, data) if (addTaxa) { if (rt) tree <- add.tips(tree, tips = mapping[, 1], where = mapping[, 2], edge.length = rep(0, nrow(mapping))) else tree <- add.tips(tree, tips = mapping[, 1], where = mapping[, 2]) } attr(tree, "pscore") <- pscore return(tree) }) while (iter) { res <- sankoff.nni(tree, dat, cost, ...) tree <- res$tree if (trace > 1) cat("optimize topology: ", pscore, "-->", res$pscore, "\n") pscore <- res$pscore swap <- swap + res$swap if (res$swap == 0) iter <- FALSE } if (trace > 0) cat("Final p-score", pscore, "after ", swap, "nni operations \n") }
CommT.legendpos <- function (in_data) { annot_x_list = annot_y_list = xlim_thres_list = c() for (i in split(in_data, in_data$gene_id)) { xlim_thres_list = c(annot_x_list, quantile(i[,"KF_dist"], probs = c(0.9999))) annot_y_list = c(annot_y_list, max(table(cut(i[,"KF_dist"], breaks=100)))) } xlim_thres_pos = quantile(xlim_thres_list, probs = c(0.95)) annot_x_pos = quantile(xlim_thres_list, probs = c(0.80))[[1]] annot_y_pos = max(annot_y_list) out_l = list("xlim_thres_pos"=xlim_thres_pos, "annot_x_pos"=annot_x_pos, "annot_y_pos"=annot_y_pos) return(out_l) }
is_an_empty_string <- function(x, .xname = get_name_in_parent(x)) { if(!(ok <- is_a_string(x))) return(ok) if(!is_empty_character(x)) { return( false( gettext("%s contains characters."), .xname ) ) } TRUE } is_a_non_empty_string <- function(x, .xname = get_name_in_parent(x)) { if(!(ok <- is_a_string(x))) return(ok) if(!is_non_empty_character(x)) { return( false( gettext("%s has no characters."), .xname ) ) } TRUE } is_a_missing_or_empty_string <- function(x, .xname = get_name_in_parent(x)) { if(!(ok <- is_a_string(x, .xname))) return(ok) if(!is_missing_or_empty_character(x)) { return( false( gettext("%s is not missing and contains characters."), .xname ) ) } TRUE } is_a_non_missing_nor_empty_string <- function(x, .xname = get_name_in_parent(x)) { if(!(ok <- is_a_string(x))) return(ok) if(!is_non_missing_nor_empty_character(x)) { return( false( gettext("%s is missing or has no characters."), .xname ) ) } TRUE }
writeNamedRegionToFile <- function(file, data, name, formula = NA, ..., styleAction = XLC$STYLE_ACTION.XLCONNECT,clearNamedRegions=FALSE) { wb <- loadWorkbook(file, create = !file.exists(file)) setStyleAction(wb, styleAction) existingNames <- getDefinedNames(wb) toClear <- intersect(name[clearNamedRegions], existingNames) clearNamedRegion(wb, toClear) if(!is.na(formula)) { sheets = extractSheetName(formula) createSheet(wb, sheets[sheets != ""]) createName(wb, name, formula) } writeNamedRegion(wb, data, name, ...) saveWorkbook(wb) invisible(wb) }
bin2resp <- function (rmat, to.data.frame = FALSE) { name <- colnames(rmat) n <- ncol(rmat) mat <- matrix(NA,nrow=nrow(rmat),ncol=ncol(rmat)) for(i in 1:n) {mat[,i] <- ifelse(rmat[,i]==1,name[i],NA)} p <- nrow(rmat) part <- list() for(j in 1:p) { resps <- na.omit(mat[j,]) attributes(resps)$na.action <- NULL part[[row.names(rmat)[j]]] <- resps } if(to.data.frame) { nlen <- vector("numeric",length=length(part)) num <- length(nlen) for(i in 1:num) {nlen[i] <- length(part[[i]])} mlen <- max(nlen) part.df <- matrix("",nrow=mlen,ncol=num) for(i in 1:num) { reps <- mlen - nlen[i] part.df[,i] <- c(unlist(part[[i]]),rep("",reps)) } part <- as.data.frame(part.df) colnames(part) <- row.names(rmat) part <- t(part) } return(part) }
svdr <- function(x, k, tol=1e-5, it=100L, extra=min(10L, dim(x) - k), center=NULL, Q=NULL, return.Q=FALSE) { eps2 <- .Machine$double.eps ^ (4 / 5) n <- min(ncol(x), k + extra) if (isTRUE(center)) center <- colMeans(x) if (is.null(Q)) Q <- matrix(rnorm(ncol(x) * n), ncol(x)) d <- rep(0, k) for (j in 1:it) { if (is.null(center)) { Q <- qr.Q(qr(x %*% Q)) B <- crossprod(x, Q) Q <- qr.Q(qr(B)) } else { Q <- qr.Q(qr(x %*% Q - rep(1, nrow(x)) %*% crossprod(center, Q))) B <- crossprod(Q, x) - tcrossprod(crossprod(Q, rep(1, nrow(x))), center) Q <- qr.Q(qr(t(B))) } d1 <- svd(B, nu=0, nv=0)$d[1:k] idx <- d1 > eps2 if (all(! idx)) break if (max(abs((d1[idx] - d[idx]) / d[idx])) < tol) break d <- d1 } if (return.Q) Q1 <- Q if (is.null(center)) { Q <- qr.Q(qr(x %*% Q)) B <- crossprod(Q, x) } else { Q <- qr.Q(qr(x %*% Q - rep(1, nrow(x)) %*% crossprod(center, Q))) B <- crossprod(Q, x) - tcrossprod(crossprod(Q, rep(1, nrow(x))), center) } s <- svd(B) s$u <- Q %*% s$u s$u <- s$u[, 1:k] s$d <- s$d[1:k] s$v <- s$v[, 1:k] s$mprod <- 2 * j + 1 if (return.Q) s$Q <- Q1 s }
tribble <- function(...) { data <- extract_frame_data_from_dots(...) turn_frame_data_into_tibble(data$frame_names, data$frame_rest) } frame_matrix <- function(...) { data <- extract_frame_data_from_dots(...) turn_frame_data_into_frame_matrix(data$frame_names, data$frame_rest) } extract_frame_data_from_dots <- function(...) { dots <- list2(...) frame_names <- extract_frame_names_from_dots(dots) if (length(frame_names) == 0 && length(dots) != 0) { cnd_signal(error_tribble_needs_columns()) } frame_rest <- dots[-seq_along(frame_names)] if (!is.null(names(frame_rest))) { cnd_signal(error_tribble_named_after_tilde()) } if (length(frame_rest) == 0L) { frame_rest <- unspecified() } validate_rectangular_shape(frame_names, frame_rest) list(frame_names = frame_names, frame_rest = frame_rest) } extract_frame_names_from_dots <- function(dots) { frame_names <- character() for (i in seq_along(dots)) { el <- dots[[i]] if (!is.call(el)) { break } if (!identical(el[[1]], as.name("~"))) { break } if (length(el) != 2) { cnd_signal(error_tribble_lhs_column_syntax(el[[2]])) } candidate <- el[[2]] if (!(is.symbol(candidate) || is.character(candidate))) { cnd_signal(error_tribble_rhs_column_syntax(candidate)) } frame_names <- c(frame_names, as.character(candidate)) } frame_names } validate_rectangular_shape <- function(frame_names, frame_rest) { if (length(frame_names) == 0 && length(frame_rest) == 0) return() if (length(frame_rest) %% length(frame_names) != 0) { cnd_signal(error_tribble_non_rectangular( length(frame_names), length(frame_rest) )) } } turn_frame_data_into_tibble <- function(names, rest) { if (is_empty(names)) return(new_tibble(list(), nrow = 0)) nrow <- length(rest) / length(names) dim(rest) <- c(length(names), nrow) dimnames(rest) <- list(names, NULL) frame_mat <- t(rest) frame_col <- turn_matrix_into_column_list(frame_mat) new_tibble(frame_col, nrow = nrow) } turn_matrix_into_column_list <- function(frame_mat) { frame_col <- vector("list", length = ncol(frame_mat)) names(frame_col) <- colnames(frame_mat) for (i in seq_len(ncol(frame_mat))) { col <- frame_mat[, i] if (inherits(col, "list") && !some(col, needs_list_col)) { subclass_tribble_c_errors( names(frame_col)[[i]], col <- vec_c(!!! unname(col)) ) } frame_col[[i]] <- unname(col) } return(frame_col) } turn_frame_data_into_frame_matrix <- function(names, rest) { list_cols <- which(map_lgl(rest, needs_list_col)) if (has_length(list_cols)) { cnd_signal(error_frame_matrix_list(list_cols)) } frame_ncol <- length(names) frame_mat <- matrix(unlist(rest), ncol = frame_ncol, byrow = TRUE) colnames(frame_mat) <- names frame_mat } subclass_tribble_c_errors <- function(name, code) { withCallingHandlers( code, vctrs_error = function(cnd) { cnd_signal(error_tribble_c(name, cnd)) } ) } error_tribble_needs_columns <- function() { tibble_error("Must specify at least one column using the `~name` syntax.") } error_tribble_named_after_tilde <- function() { tibble_error("When using the `~name` syntax, subsequent values must not have names.") } error_tribble_lhs_column_syntax <- function(lhs) { tibble_error(problems( "All column specifications must use the `~name` syntax.", paste0("Found ", expr_label(lhs), " on the left-hand side of `~`.") )) } error_tribble_rhs_column_syntax <- function(rhs) { tibble_error(problems( 'All column specifications must use the `~name` or `~"name"` syntax.', paste0("Found ", expr_label(rhs), " on the right-hand side of `~`.") )) } error_tribble_non_rectangular <- function(cols, cells) { tibble_error(bullets( "Data must be rectangular:", paste0("Found ", cols, " columns."), paste0("Found ", cells, " cells."), info = paste0(cells, " is not an integer multiple of ", cols, ".") )) } error_frame_matrix_list <- function(pos) { tibble_error(problems( "All values must be atomic:", pluralise_commas("Found list-valued element(s) at position(s) ", pos, ".") )) } error_tribble_c <- function(name, cnd) { cnd$message <- paste0("Can't create column ", tick(name), ": ", cnd_header(cnd)) cnd$class <- c(tibble_error_class("tribble_c"), class(cnd)) cnd }