code
stringlengths 1
13.8M
|
---|
NULL
NULL
CompCase=function(mydata){
sum(is.na(apply(mydata,1,mean)))
mydata<-mydata[!is.na(apply(mydata,1,mean)),]
}
NULL
pbc.sample=function(){
Z=list()
D=CompCase(survival::pbc[,c(2:4,10:14)]);
Z$time=D$time/365.25;
Z$status=as.numeric(D$status==2);
Z$group=as.numeric(D$trt==2);
Z$covariates=as.matrix(D[,4:8]);
Z
}
NULL
plot.surv2sample=function(x, measure=NULL,baseline=0,...){
if(is.null(measure)){
y=x$survfit ; class(y)="survfit" ; plot(y,...)
}
if(measure=="relative percentile"){
xx=x$quanprobs
if(baseline==0){y=x$contrast.ratio01}else{y=x$contrast.ratio10}
yy=y[(nrow(y)-length(xx)+1):nrow(y),]
plotrix::plotCI(xx, yy[,1], uiw=yy[,3], liw=yy[,2], xlab="percent", ylab="relative time (95%CI)",...)
}
}
NULL
rmstreg=function(y, delta, x, arm, tau, type="difference", conf.int=0.95)
{
label.low = paste0("lower ", conf.int)
label.upp = paste0("upper ", conf.int)
if(type!="difference" && type!="ratio" && type!="lossratio")
print("Type must be difference, ratio or lossratio.")
if(type=="difference" || type=="ratio" || type=="lossratio"){
n=length(y)
x=cbind(1, x)
p=length(x[1,])
y0=pmin(y, tau)
d0=delta
d0[y0==tau]=1
d10=d0[arm==1]
d00=d0[arm==0]
y10=y0[arm==1]
y00=y0[arm==0]
x1=x[arm==1,]
x0=x[arm==0,]
n1=length(d10)
n0=length(d00)
id1=order(y10)
y10=y10[id1]
d10=d10[id1]
x1=x1[id1,]
id0=order(y00)
y00=y00[id0]
d00=d00[id0]
x0=x0[id0,]
fitc1=survfit(Surv(y10, 1-d10)~1)
fitc0=survfit(Surv(y00, 1-d00)~1)
weights1=d10/rep(fitc1$surv, table(y10))
weights0=d00/rep(fitc0$surv, table(y00))
weights=c(weights1, weights0)
if(type=="difference")
{fitt=lm(c(y10,y00)~rbind(x1, x0)-1, weights=weights)
beta0=fitt$coef
error1=y10-as.vector(x1%*%beta0)
score1=x1*weights1*error1
error0=y00-as.vector(x0%*%beta0)
score0=x0*weights0*error0
}
if(type=="ratio")
{fitt=glm(c(y10,y00)~rbind(x1, x0)-1, family="quasipoisson", weights=weights)
beta0=fitt$coef
error1=y10-exp(as.vector(x1%*%beta0))
score1=x1*weights1*error1
error0=y00-exp(as.vector(x0%*%beta0))
score0=x0*weights0*error0
}
if(type=="lossratio")
{fitt=glm(c(tau-y10,tau-y00)~rbind(x1, x0)-1, family="quasipoisson", weights=weights)
beta0=fitt$coef
error1=tau-y10-exp(as.vector(x1%*%beta0))
score1=x1*weights1*error1
error0=tau-y00-exp(as.vector(x0%*%beta0))
score0=x0*weights0*error0
}
kappa.arm1=matrix(0, n1, p)
for(i in 1:n1)
{kappa1=score1[i,]
kappa2=apply(score1[y10>=y10[i],,drop=F], 2, sum)*(1-d10[i])/sum(y10>=y10[i])
kappa3=rep(0, p)
for(k in 1:n1)
{ if(y10[k]<=y10[i])
kappa3=kappa3+apply(score1[y10>=y10[k],,drop=F], 2, sum)*(1-d10[k])/(sum(y10>=y10[k]))^2
}
kappa.arm1[i,]=kappa1+kappa2-kappa3
}
kappa.arm0=matrix(0, n0, p)
for(i in 1:n0)
{kappa1=score0[i,]
kappa2=apply(score0[y00>=y00[i],,drop=F], 2, sum)*(1-d00[i])/sum(y00>=y00[i])
kappa3=rep(0, p)
for(k in 1:n0)
{if(y00[k]<=y00[i])
kappa3=kappa3+apply(score0[y00>=y00[k],,drop=F], 2, sum)*(1-d00[k])/(sum(y00>=y00[k]))^2
}
kappa.arm0[i,]=kappa1+kappa2-kappa3
}
if(type=="difference")
{gamma=t(kappa.arm1)%*%kappa.arm1+t(kappa.arm0)%*%kappa.arm0
A=t(x)%*%x
varbeta=solve(A)%*%gamma%*%solve(A)
}
if(type=="ratio" || type=="lossratio")
{gamma=t(kappa.arm1)%*%kappa.arm1+t(kappa.arm0)%*%kappa.arm0
A=t(x*exp(as.vector(x%*%beta0)))%*%x
varbeta=solve(A)%*%gamma%*%solve(A)
}
if(type=="difference")
{beta0=beta0
se0=sqrt(diag(varbeta))
z0=beta0/se0
p0=1-pchisq(z0^2, 1)
cilow=beta0-se0*abs(qnorm((1-conf.int)/2))
cihigh=beta0+se0*abs(qnorm((1-conf.int)/2))
result=cbind(coef=beta0, "se(coef)"=se0, z=z0, p=p0, label.low=cilow, label.upp=cihigh)
colnames(result)=c("coef", "se(coef)", "z", "p", label.low, label.upp)
}
if(type=="ratio" || type=="lossratio")
{beta0=beta0
se0=sqrt(diag(varbeta))
z0=beta0/se0
p0=1-pchisq(z0^2, 1)
r0=exp(beta0)
cilow=exp(beta0-se0*abs(qnorm((1-conf.int)/2)))
cihigh=exp(beta0+se0*abs(qnorm((1-conf.int)/2)))
result=cbind(coef=beta0, "se(coef)"=se0, z=z0, p=p0, "exp(coef)"=exp(beta0), label.low=cilow, label.upp=cihigh)
colnames(result)=c("coef", "se(coef)", "z", "p", "exp(coef)", label.low, label.upp)
}
if(p==2)
rownames(result)=c("intercept", "x")
if(p>2)
rownames(result)=c("intercept", colnames(x[,-1]))
return(result)
}
}
NULL
rmstaug=function(y, delta, x, arm, tau, type="difference", conf.int=0.95)
{
label.low = paste0("lower ", conf.int)
label.upp = paste0("upper ", conf.int)
if(type!="difference" && type!="ratio" && type!="lossratio")
print("Type must be difference, ratio or lossratio.")
if(type=="difference" || type=="ratio" || type=="lossratio"){
n=length(y)
x=as.matrix(x)
p=length(x[1,])
pi=mean(arm)
y0=pmin(y, tau)
d0=delta
d0[y0==tau]=1
d10=d0[arm==1]
d00=d0[arm==0]
y10=y0[arm==1]
y00=y0[arm==0]
x1=x[arm==1,,drop=F]
x0=x[arm==0,,drop=F]
n1=length(d10)
n0=length(d00)
id1=order(y10)
y10=y10[id1]
d10=d10[id1]
x1=x1[id1,,drop=F]
id0=order(y00)
y00=y00[id0]
d00=d00[id0]
x0=x0[id0,,drop=F]
fitc1=survfit(Surv(y10, 1-d10)~1)
fitc0=survfit(Surv(y00, 1-d00)~1)
weights1=d10/rep(fitc1$surv, table(y10))
weights0=d00/rep(fitc0$surv, table(y00))
weights=c(weights1, weights0)
if(type=="difference")
{fitt=lm(c(y10,y00)~rep(c(1, 0), c(n1, n0)), weights=weights)
beta0=fitt$coef
error1=y10-beta0[1]-beta0[2]
score1=cbind(1, rep(1, n1))*weights1*error1
error0=y00-beta0[1]
score0=cbind(1, rep(0, n0))*weights0*error0
}
if(type=="ratio")
{fitt=glm(c(y10,y00)~rep(c(1, 0), c(n1, n0)), family="quasipoisson", weights=weights)
beta0=fitt$coef
error1=y10-exp(beta0[1]+beta0[2])
score1=cbind(1, rep(1, n1))*weights1*error1
error0=y00-exp(beta0[1])
score0=cbind(1, rep(0, n0))*weights0*error0
}
if(type=="lossratio")
{fitt=glm(c(tau-y10,tau-y00)~rep(c(1, 0), c(n1, n0)), family="quasipoisson", weights=weights)
beta0=fitt$coef
error1=tau-y10-exp(beta0[1]+beta0[2])
score1=cbind(1, rep(1, n1))*weights1*error1
error0=tau-y00-exp(beta0[1])
score0=cbind(1, rep(0, n0))*weights0*error0
}
kappa.arm1=matrix(0, n1, 2)
for(i in 1:n1)
{kappa1=score1[i,]
kappa2=apply(score1[y10>=y10[i],,drop=F], 2, sum)*(1-d10[i])/sum(y10>=y10[i])
kappa3=rep(0, 2)
for(k in 1:n1)
{ if(y10[k]<=y10[i])
kappa3=kappa3+apply(score1[y10>=y10[k],,drop=F], 2, sum)*(1-d10[k])/(sum(y10>=y10[k]))^2
}
kappa.arm1[i,]=kappa1+kappa2-kappa3
}
kappa.arm0=matrix(0, n0, 2)
for(i in 1:n0)
{kappa1=score0[i,]
kappa2=apply(score0[y00>=y00[i],,drop=F], 2, sum)*(1-d00[i])/sum(y00>=y00[i])
kappa3=rep(0, 2)
for(k in 1:n0)
{if(y00[k]<=y00[i])
kappa3=kappa3+apply(score0[y00>=y00[k],,drop=F], 2, sum)*(1-d00[k])/(sum(y00>=y00[k]))^2
}
kappa.arm0[i,]=kappa1+kappa2-kappa3
}
if(type=="difference")
{
A=cbind(c(n1+n0, n1), c(n1, n1))
betainf=solve(A)%*%t(rbind(kappa.arm1, kappa.arm0))
}
if(type=="ratio" || type=="lossratio")
{mu1=exp(beta0[1]+beta0[2])
mu0=exp(beta0[1])
A=cbind(c(n1*mu1+n0*mu0, n1*mu1), c(n1*mu1, n1*mu1))
betainf=solve(A)%*%t(rbind(kappa.arm1, kappa.arm0))
}
aug=rbind(x1*(1-pi), -x0*pi)
fit=lm(t(betainf)~aug-1)
if(type=="difference")
{beta0=beta0
se0=sqrt(diag(betainf%*%t(betainf)))
z0=beta0/se0
p0=1-pchisq(z0^2, 1)
cilow=beta0-se0*abs(qnorm((1-conf.int)/2))
cihigh=beta0+se0*abs(qnorm((1-conf.int)/2))
result.ini=cbind(coef=beta0, "se(coef)"=se0, z=z0, p=p0, label.low=cilow, label.upp=cihigh)
colnames(result.ini)=c("coef", "se(coef)", "z", "p", label.low, label.upp)
beta.aug=beta0-apply(aug%*%fit$coef,2,sum)
se.aug=sqrt(diag(t(fit$res)%*%fit$res))*sqrt((n1+n0)/(n1+n0-p))
z.aug=beta.aug/se.aug
p.aug=1-pchisq(z.aug^2, 1)
cilow.aug=beta.aug-se.aug*abs(qnorm((1-conf.int)/2))
cihigh.aug=beta.aug+se.aug*abs(qnorm((1-conf.int)/2))
result.aug=cbind(coef=beta.aug, "se(coef)"=se.aug, z=z.aug, p=p.aug, label.low=cilow.aug, label.upp=cihigh.aug)
colnames(result.aug)=c("coef", "se(coef)", "z", "p", label.low, label.upp)
}
if(type=="ratio" || type=="lossratio")
{beta0=beta0
se0=sqrt(diag(betainf%*%t(betainf)))
z0=beta0/se0
p0=1-pchisq(z0^2, 1)
cilow=beta0-se0*abs(qnorm((1-conf.int)/2))
cihigh=beta0+se0*abs(qnorm((1-conf.int)/2))
result.ini=cbind(coef=beta0, "se(coef)"=se0, z=z0, p=p0, "exp(coef)"=exp(beta0), label.low=exp(cilow), label.upp=exp(cihigh))
colnames(result.ini)=c("coef", "se(coef)", "z", "p", "exp(coef)", label.low, label.upp)
beta.aug=beta0-apply(aug%*%fit$coef,2,sum)
se.aug=sqrt(diag(t(fit$res)%*%fit$res))*sqrt((n1+n0)/(n1+n0-p))
z.aug=beta.aug/se.aug
p.aug=1-pchisq(z.aug^2, 1)
cilow.aug=beta.aug-se.aug*abs(qnorm((1-conf.int)/2))
cihigh.aug=beta.aug+se.aug*abs(qnorm((1-conf.int)/2))
result.aug=cbind(coef=beta.aug, "se(coef)"=se.aug, z=z.aug, p=p.aug, "exp(coef)"=exp(beta.aug), label.low=exp(cilow.aug), label.upp=exp(cihigh.aug))
colnames(result.aug)=c("coef", "se(coef)", "z", "p", "exp(coef)", label.low, label.upp)
}
rownames(result.ini)=rownames(result.aug)=c("intercept", "arm")
return(list(result.ini=result.ini, result.aug=result.aug))
}
}
NULL
NULL
KM2.pert <- function(time, status, npert=300, timepoints=c(12,24,36,40), quanprobs=c(0.1, 0.15, 0.2), tau_start=0, tau){
indata=cbind(time, status)
N=nrow(indata)
KK=npert+1
k.time=length(timepoints) ; p.time=matrix(0, nrow=KK, ncol=k.time)
k.quan=length(quanprobs) ; q.time=matrix(0, nrow=KK, ncol=k.quan)
rmst=rep(0, KK)
p.time.ave =rep(0, KK)
q.time.ave =rep(0, KK)
i=1
ft= survfit(Surv(indata[,1], indata[,2])~1)
if(tau_start!=0){
rmst[i]=summary(ft, rmean=tau)$table[5] - summary(ft, rmean=tau_start)$table[5]
}else{
rmst[i]=summary(ft, rmean=tau)$table[5]
}
for (k in 1:k.time){
idx=ft$time<timepoints[k] ; p.time[i, k]=min(ft$surv[idx])}
for (k in 1:k.quan){
idx1=round(ft$surv,digits=14) <= (1-quanprobs[k]) ;
idx2=round(ft$surv,digits=14) < (1-quanprobs[k]) ;
if(sum(as.numeric(idx1))==0){
q.time[i, k]=NA
}else{
if(sum(as.numeric(idx1)) == sum(as.numeric(idx2))){
q.time[i, k]= min(ft$time[idx1])
}else{
q.time[i, k]=(min(ft$time[idx1]) + min(ft$time[idx2]))/2
}
}
}
p.time.ave[i]=mean(p.time[i,])
q.time.ave[i]=mean(q.time[i,])
for (i in 2:KK){
ft= survfit(Surv(indata[,1], indata[,2])~1, weight=rexp(N))
if(tau_start!=0){
rmst[i]=summary(ft, rmean=tau)$table[5] - summary(ft, rmean=tau_start)$table[5]
}else{
rmst[i]=summary(ft, rmean=tau)$table[5]
}
for (k in 1:k.time){
idx=ft$time<timepoints[k] ; p.time[i, k]=min(ft$surv[idx])}
for (k in 1:k.quan){
idx1=round(ft$surv,digits=14) <= (1-quanprobs[k]) ;
idx2=round(ft$surv,digits=14) < (1-quanprobs[k]) ;
if(sum(as.numeric(idx1)) == sum(as.numeric(idx2))){
q.time[i, k]= min(ft$time[idx1])
}else{
q.time[i, k]=(min(ft$time[idx1]) + min(ft$time[idx2]))/2
}
}
p.time.ave[i]=mean(p.time[i,])
q.time.ave[i]=mean(q.time[i,])
}
Z=list()
Z$percentiles = data.frame(q.time); colnames(Z$percentiles)=quanprobs
Z$tyearprobs = data.frame(p.time) ; colnames(Z$tyearprobs) = timepoints
Z$rmst = rmst
Z$tau = tau
Z$tau_start = tau_start
Z$tyearprobs.ave=p.time.ave
Z$percentiles.ave=q.time.ave
return(Z)
}
NULL
GG2.boot=function(time, status, npert=300, timepoints=c(12,24,36,40), quanprobs=c(0.1, 0.15, 0.2), tau){
indata=cbind(time, status)
N=nrow(indata)
KK=npert+1
k.time=length(timepoints) ; p.time=matrix(0, nrow=KK, ncol=k.time)
k.quan=length(quanprobs) ; q.time=matrix(0, nrow=KK, ncol=k.quan)
rmst=rep(0, KK)
p.time.ave =rep(0, KK)
q.time.ave =rep(0, KK)
i=1
ft=flexsurvreg(Surv(indata[,1], indata[,2])~1, dist="gengamma")
parm=ft$res[,1]
integrand=function(x){1-pgengamma(x, mu=parm[1], sigma = parm[2], Q=parm[3])}
aa=integrate(integrand, lower=0, upper=tau)
rmst[i]=aa$value
for (k in 1:k.time){
p.time[i, k]=1-pgengamma(timepoints[k], mu=parm[1], sigma = parm[2], Q=parm[3])}
for (k in 1:k.quan){
q.time[i, k]=qgengamma(quanprobs[k], mu=parm[1], sigma = parm[2], Q=parm[3])}
p.time.ave[i]=mean(p.time[i,])
q.time.ave[i]=mean(q.time[i,])
for (i in 2:KK){
bs=sample(N, replace=TRUE)
bdata=indata[bs,]
ft=flexsurvreg(Surv(bdata[,1], bdata[,2])~1, dist="gengamma")
parm=ft$res[,1]
integrand=function(x){1-pgengamma(x, mu=parm[1], sigma = parm[2], Q=parm[3])}
aa=integrate(integrand, lower=0, upper=tau)
rmst[i]=aa$value
for (k in 1:k.time){
p.time[i, k]=1-pgengamma(timepoints[k], mu=parm[1], sigma = parm[2], Q=parm[3])}
for (k in 1:k.quan){
q.time[i, k]=qgengamma(quanprobs[k], mu=parm[1], sigma = parm[2], Q=parm[3])}
p.time.ave[i]=mean(p.time[i,])
q.time.ave[i]=mean(q.time[i,])
}
Z=list()
Z$percentiles=data.frame(q.time); colnames(Z$percentiles)= quanprobs
Z$tyearprobs=data.frame(p.time) ; colnames(Z$tyearprobs) = timepoints
Z$rmst=rmst
Z$tau=tau
Z$tyearprobs.ave=p.time.ave
Z$percentiles.ave=q.time.ave
return(Z)
}
NULL
surv2sample <- function(time, status, arm, npert=1000, timepoints=c(12,24,36,40), quanprobs =c(0.1, 0.15, 0.2), tau_start=0, tau, SEED=NULL, procedure="KM", conf.int=0.95){
if(!is.null(SEED)){ set.seed(SEED) }
idx=arm==0; tt=time[idx]; tau0max=max(tt)
idx=arm==1; tt=time[idx]; tau1max=max(tt)
tau_max = min(tau0max, tau1max)
if(!is.null(tau)){
if(tau > tau_max){
stop(paste("The truncation time, tau, needs to be shorter than or equal to the minimum of the largest observed time on each of the two groups: ", round(tau_max, digits=3)))
}
}
if(is.null(tau)){
stop(paste("The truncation time, tau, was not specified. It needs to be specified by users."))
}
if(procedure=="KM"){
idx=arm==0; km0=KM2.pert(time[idx], status[idx], npert=npert, timepoints=timepoints, quanprobs = quanprobs, tau_start=tau_start, tau=tau)
idx=arm==1; km1=KM2.pert(time[idx], status[idx], npert=npert, timepoints=timepoints, quanprobs = quanprobs, tau_start=tau_start, tau=tau)
}
if(procedure=="GG"){
idx=arm==0; km0=GG2.boot(time[idx], status[idx], npert=npert, timepoints=timepoints, quanprobs = quanprobs, tau=tau)
idx=arm==1; km1=GG2.boot(time[idx], status[idx], npert=npert, timepoints=timepoints, quanprobs = quanprobs, tau=tau)
}
q_ci = function(x){quantile(x, prob=c((1-conf.int)/2, 1-(1-conf.int)/2))}
time_interval = tau - tau_start
wk0=cbind(km0$rmst, tau-km0$rmst, km0$tyearprobs, km0$percentiles, km0$tyearprobs.ave, km0$percentiles.ave)
wk1=cbind(km1$rmst, tau-km1$rmst, km1$tyearprobs, km1$percentiles, km1$tyearprobs.ave, km1$percentiles.ave)
se0=apply(wk0[-1,], 2, sd)
se1=apply(wk1[-1,], 2, sd)
ci0=apply(wk0[-1,], 2, q_ci)
ci1=apply(wk1[-1,], 2, q_ci)
measure=c("RMST","Loss time", paste("Prob at",timepoints), paste("Quantile at", quanprobs*100,"%"), "Ave of t-year event rates","Ave percentiles")
out.group0=cbind(t(wk0[1,]), t(ci0), se0)
out.group1=cbind(t(wk1[1,]), t(ci1), se1)
rownames(out.group0)=measure
rownames(out.group1)=measure
colnames(out.group0)=c("Est.", paste0("Lower ", conf.int*100, "%"), paste0("Upper ", conf.int*100, "%"), "SE")
colnames(out.group1)=c("Est.", paste0("Lower ", conf.int*100, "%"), paste0("Upper ", conf.int*100, "%"), "SE")
K=ncol(wk0)
outq=c()
for (k in 1:K){
q0=wk0[,k] ; q1=wk1[,k]
diff01=q0-q1
diff10=q1-q0
ratio01=q0/q1
ratio10=q1/q0
outq=cbind(outq, diff01, diff10, ratio01, ratio10)
}
measures=rep(measure, each=4)
contrast=rep(c("Group0-Group1","Group1-Group0","Group0/Group1","Group1/Group0"), K)
if(procedure=="KM"){
se=apply(outq[-1,], 2, sd)
pval=pnorm(-abs(outq[1,])/se)*2
idx=contrast=="Group0/Group1"|contrast=="Group1/Group0"
for (j in 1:length(pval)){
if(contrast[j]=="Group0/Group1" | contrast[j]=="Group1/Group0"){
for (m in 1:length(measure)){
if(measures[j]==measure[m]){
se[j]=sqrt( (se0[m]/out.group0[m,1])^2 + (se1[m]/out.group1[m,1])^2)
}
}
}
}
pval[idx]=pnorm(-abs(log(outq[1,idx]))/se[idx])*2
lower=outq[1,] - abs(qnorm((1-conf.int)/2))*se
upper=outq[1,] + abs(qnorm((1-conf.int)/2))*se
idx=contrast=="Group0/Group1"|contrast=="Group1/Group0"
lower[idx]=exp(log(outq[1,idx]) - abs(qnorm((1-conf.int)/2))*se[idx])
upper[idx]=exp(log(outq[1,idx]) + abs(qnorm((1-conf.int)/2))*se[idx])
out.contrast=cbind(outq[1,], lower, upper, pval)
rownames(out.contrast)=paste(measures, contrast)
colnames(out.contrast)=c("Est.", paste0("Lower ", conf.int*100, "%"), paste0("Upper ", conf.int*100, "%"), "p-val")
inf.method="Perturbation resampling"
}
if(procedure=="GG"){
cband=apply(outq[-1,], 2, q_ci)
lower=cband[1,]
upper=cband[2,]
out.contrast=cbind(outq[1,], lower, upper)
rownames(out.contrast)=paste(measures, contrast)
colnames(out.contrast)=c("Est.", paste0("Lower ", conf.int*100, "%"), paste0("Upper ", conf.int*100, "%"))
inf.method="Bootstrap percentile method"
}
int.surv.group0 = cbind(out.group0[1,1]/time_interval, out.group0[1,2]/time_interval, out.group0[1,3]/time_interval)
int.surv.group1 = cbind(out.group1[1,1]/time_interval, out.group1[1,2]/time_interval, out.group1[1,3]/time_interval)
int.surv.diff01 = cbind(out.contrast[contrast=="Group0-Group1",][1,1]/time_interval, out.contrast[contrast=="Group0-Group1",][1,2]/time_interval, out.contrast[contrast=="Group0-Group1",][1,3]/time_interval, out.contrast[contrast=="Group0-Group1",][1,4])
int.surv.diff10 = cbind(out.contrast[contrast=="Group1-Group0",][1,1]/time_interval, out.contrast[contrast=="Group1-Group0",][1,2]/time_interval, out.contrast[contrast=="Group1-Group0",][1,3]/time_interval, out.contrast[contrast=="Group1-Group0",][1,4])
out.int.surv = rbind(int.surv.group0, int.surv.group1)
out.int.surv.diff = rbind(int.surv.diff01, int.surv.diff10)
rownames(out.int.surv) = c("Integrated survival rate Group0", "Integrated survival rate Group1")
colnames(out.int.surv) = c("Est.", paste0("Lower ", conf.int*100, "%"), paste0("Upper ", conf.int*100, "%"))
rownames(out.int.surv.diff) = c("Integrated survival rate Group0-Group1", "Integrated survival rate Group1-Group0")
colnames(out.int.surv.diff) = c("Est.", paste0("Lower ", conf.int*100, "%"), paste0("Upper ", conf.int*100, "%"), "p-val")
Z=list()
Z$procedure = procedure
Z$method = inf.method
Z$survfit = survfit(Surv(time, status)~arm)
Z$tau_start = tau_start
Z$tau = tau
Z$time_interval = time_interval
Z$npert = npert
Z$timepoints = timepoints
Z$quanprobs = quanprobs
Z$contrast.all = out.contrast
Z$group0 = out.group0
Z$group1 = out.group1
Z$RMST = out.contrast[measures=="RMST",]
Z$RMLT = out.contrast[measures=="Loss time",]
Z$contrast.diff10 = out.contrast[contrast=="Group1-Group0",]
Z$contrast.diff01 = out.contrast[contrast=="Group0-Group1",]
Z$contrast.ratio01 = out.contrast[contrast=="Group0/Group1",]
Z$contrast.ratio10 = out.contrast[contrast=="Group1/Group0",]
Z$integrated_surv = out.int.surv
Z$integrated_surv.diff = out.int.surv.diff
class(Z)="surv2sample"
return(Z)
}
NULL |
session <- RevoIOQ:::saveRUnitSession(packages="tools")
isWindows <- .Platform$OS.type=="windows"
if (!exists("Revo.home"))
{
Revo.home <- R.home
}
license.stress.Revo <- function()
{
path <- Revo.home("licenses")
haveRevoScaleR <- !identical(system.file("DESCRIPTION", package="RevoScaleR") , "")
if (haveRevoScaleR) {
if (!isMicrosoftRClient()){
RevoEdition <- "Microsoft R Server"
} else {
RevoEdition <- "Microsoft R Client"
}
}
if (identical(RevoEdition, "Microsoft R Server")){
checkTrue(file.exists(file.path(path, ifelse(isWindows, "MicrosoftRServerLicense.txt", "MicrosoftRServerLicense"))))
} else {
checkTrue(file.exists(file.path(path, ifelse(isWindows, "MicrosoftRClientLicense.txt", "MicrosoftRClientLicense"))))
}
}
"test.AllLicense.stress" <- function()
{
if (identical(Revo.home(), R.home()) )
{
DEACTIVATED("Test deactivated because Microsoft R Services components are not installed on this system.")
}
res <- try(license.stress.Revo())
checkTrue(!is(res, "try-error"), msg="License stress test failed")
}
"testzzz.restore.session" <- function()
{
checkTrue(RevoIOQ:::restoreRUnitSession(session), msg="Session restoration failed")
} |
dprior <- function(x1,
x2 = NULL,
prior_par = list(mu_psi = 0, sigma_psi = 1,
mu_beta = 0, sigma_beta = 1),
what = "logor",
hypothesis = "H1") {
if ( ! is.list(prior_par) ||
! all(c("mu_psi", "sigma_psi", "mu_beta", "sigma_beta") %in%
names(prior_par))) {
stop('prior_par needs to be a named list with elements
"mu_psi", "sigma_psi", "mu_beta", and "sigma_beta',
call. = FALSE)
}
if (prior_par$sigma_psi <= 0 || prior_par$sigma_beta <= 0) {
stop('sigma_psi and sigma_beta need to be larger than 0',
call. = FALSE)
}
if ( ! (what %in%
c("logor", "or", "p1p2", "p1", "p2",
"p2givenp1", "rrisk", "arisk"))) {
stop('what needs to be either "logor", "or", "p1p2", "p1", "p2",
"p2givenp1", "rrisk", or "arisk"', call. = FALSE)
}
if ( ! (hypothesis %in% c("H1", "H+", "H-"))) {
stop('hypothesis needs to be either "H1", "H+", or "H-"',
call. = FALSE)
}
if (what %in% c("logor", "or")) {
out <- do.call(what = paste0("d", what),
args = list(x = x1,
mu_psi = prior_par[["mu_psi"]],
sigma_psi = prior_par[["sigma_psi"]],
hypothesis = hypothesis))
} else if (what == "p1p2") {
out <- do.call(what = paste0("d", what),
args = list(p1 = x1,
p2 = x2,
mu_psi = prior_par[["mu_psi"]],
sigma_psi = prior_par[["sigma_psi"]],
mu_beta = prior_par[["mu_beta"]],
sigma_beta = prior_par[["sigma_beta"]],
hypothesis = hypothesis))
} else if (what == "p2givenp1") {
out <- do.call(what = paste0("d", what),
args = list(p2 = x1,
p1 = x2,
mu_psi = prior_par[["mu_psi"]],
sigma_psi = prior_par[["sigma_psi"]],
mu_beta = prior_par[["mu_beta"]],
sigma_beta = prior_par[["sigma_beta"]],
hypothesis = hypothesis))
} else if (what %in% c("rrisk", "arisk", "p1", "p2")) {
out <- do.call(what = paste0("d", what),
args = list(x = x1,
mu_psi = prior_par[["mu_psi"]],
sigma_psi = prior_par[["sigma_psi"]],
mu_beta = prior_par[["mu_beta"]],
sigma_beta = prior_par[["sigma_beta"]],
hypothesis = hypothesis))
}
return(out)
} |
library(testthat)
context("DNAbin2kmerFreqMatrix: convert object of DNAbin into kmer frequence matrix")
test_that("DNAbin2kmerFreqMatrix: convert object of DNAbin into kmer frequence matrix",{
require(seqinr)
require(ape)
data(woodmouse)
expect_that(class(DNAbin2kmerFreqMatrix(seqs=woodmouse,kmer=3)),equals("matrix"))
}) |
collapseTree<-function(tree,...){
if(!inherits(tree,"phylo")) stop("tree should be an object of class \"phylo\".")
if(inherits(tree,"simmap")) tree<-as.phylo(tree)
if(hasArg(nodes)) nodes<-list(...)$nodes
else nodes<-TRUE
if(hasArg(hold)) hold<-list(...)$hold
else hold<-TRUE
if(hasArg(drop.extinct)) drop.extinct<-list(...)$drop.extinct
else drop.extinct<-TRUE
if(is.null(tree$edge.length)){
no.edge<-TRUE
tree<-compute.brlen(tree,power=0.5)
} else no.edge<-FALSE
cat("Click on the nodes that you would like to collapse...\n")
flush.console()
options(locatorBell=FALSE)
if(is.null(tree$node.label)) tree$node.label<-as.character(Ntip(tree)+1:tree$Nnode)
else if(any(tree$node.label=="")){
tree$node.label[which(tree$node.label)==""]<-
which(tree$node.label=="")+Ntip(tree)
}
tree$node.label<-sapply(tree$node.label,gsub,pattern=" ",replacement="_")
tree$tip.label<-sapply(tree$tip.label,gsub,pattern=" ",replacement="_")
otree<-tree<-reorder(tree)
if(hold) dev.hold()
fan(tree,...)
lastPP<-get("last_plot.phylo",envir=.PlotPhyloEnv)
points(x=lastPP$xx[1:Ntip(tree)],y=lastPP$yy[1:Ntip(tree)],
pch=21,col="blue",bg="white",cex=0.8)
points(x=lastPP$xx[1:tree$Nnode+Ntip(tree)],
y=lastPP$yy[1:tree$Nnode+Ntip(tree)],pch=21,
col="blue",bg="white",cex=1.2)
rect(par()$usr[1],par()$usr[4]-3*strheight("W"),par()$usr[2],par()$usr[4],
border=0,col=make.transparent("blue",0.2))
textbox(x=par()$usr[1:2],y=par()$usr[4],
c("Click nodes to collapse or expand\nRIGHT CLICK to stop"),
justify="c",border=0)
dev.flush()
x<-unlist(locator(1))
if(!is.null(x)){
y<-x[2]
x<-x[1]
d<-sqrt((x-lastPP$xx)^2+(y-lastPP$yy)^2)
nn<-which(d==min(d,na.rm=TRUE))
while(!is.null(x)){
obj<-list(tree)
if(nn>(Ntip(tree)+1)){
obj<-splitTree(tree,list(node=nn,
bp=tree$edge.length[which(tree$edge[,2]==nn)]))
obj[[1]]$tip.label[which(obj[[1]]$tip.label=="NA")]<-
tree$node.label[nn-Ntip(tree)]
tips<-which(tree$tip.label%in%obj[[1]]$tip.label)
theta<-atan(lastPP$yy[nn]/lastPP$xx[nn])
if(lastPP$yy[nn]>0&&lastPP$xx[nn]<0) theta<-pi+theta
else if(lastPP$yy[nn]<0&&lastPP$xx[nn]<0) theta<-pi+theta
else if(lastPP$yy[nn]<0&&lastPP$xx[nn]>0) theta<-2*pi+theta
ii<-which((c(tips,Ntip(tree)+1)-c(0,tips))>1)
if(ii>1&&ii<=length(tips))
tips<-c(tips[1:(ii-1)],theta/(2*pi)*Ntip(tree),tips[ii:length(tips)])
else if(ii==1) tips<-c(theta/(2*pi)*Ntip(tree),tips)
else if(ii>length(tips)) tips<-c(tips,theta/(2*pi)*Ntip(tree))
tree<-read.tree(text=write.tree(obj[[1]]))
M<-matrix(NA,min(c(max(4,Ntip(obj[[2]])),10)),length(tips))
for(i in 1:ncol(M)) M[,i]<-seq(from=tips[i],to=i,length.out=nrow(M))
colnames(M)<-tree$tip.label
maxY<-seq(from=sum(sapply(obj,Ntip))-length(obj)+1,to=Ntip(tree),
length.out=nrow(M))
pw<-reorder(tree,"pruningwise")
H<-nodeHeights(tree)
for(i in 1:nrow(M)){
if(hold) dev.hold()
fan(tree,pw,H,xlim=lastPP$x.lim,ylim=lastPP$y.lim,
tips=M[i,],maxY=maxY[i],...)
rect(par()$usr[1],par()$usr[4]-3*strheight("W"),
par()$usr[2],par()$usr[4],
border=0,col=make.transparent("blue",0.2))
textbox(x=par()$usr[1:2],y=par()$usr[4],
c("Click nodes to collapse or expand\nRIGHT CLICK to stop"),
justify="c",border=0)
if(nodes||i==nrow(M)){
lastPP<-get("last_plot.phylo",envir=.PlotPhyloEnv)
points(x=lastPP$xx[1:Ntip(tree)],y=lastPP$yy[1:Ntip(tree)],
pch=21,col="blue",bg="white",cex=0.8)
points(x=lastPP$xx[1:tree$Nnode+Ntip(tree)],
y=lastPP$yy[1:tree$Nnode+Ntip(tree)],pch=21,
col="blue",bg="white",cex=1.2)
}
dev.flush()
}
} else if(nn<=Ntip(tree)) {
if(tree$tip.label[nn]%in%otree$node.label){
on<-which(otree$node.label==tree$tip.label[nn])+Ntip(otree)
obj<-splitTree(otree,list(node=on,
bp=otree$edge.length[which(otree$edge[,2]==on)]))
nlabel<-tree$tip.label[nn]
tree$tip.label[nn]<-"NA"
if(nn==1) tips<-c(rep(nn,Ntip(obj[[2]])),(nn+1):Ntip(tree))
else if(nn>1&&nn<Ntip(tree))
tips<-c(1:(nn-1),rep(nn,Ntip(obj[[2]])),(nn+1):Ntip(tree))
else if(nn==Ntip(tree)) tips<-c(1:(nn-1),rep(nn,Ntip(obj[[2]])))
tree<-read.tree(text=write.tree(paste.tree(tree,obj[[2]])))
M<-matrix(NA,min(c(max(4,Ntip(obj[[2]])),10)),length(tips))
for(i in 1:ncol(M)) M[,i]<-seq(from=tips[i],to=i,length.out=nrow(M))
colnames(M)<-tree$tip.label
pw<-reorder(tree,"pruningwise")
H<-nodeHeights(tree)
for(i in 1:nrow(M)){
if(hold) dev.hold()
fan(tree,pw,H,xlim=lastPP$x.lim,ylim=lastPP$y.lim,
tips=M[i,],maxY=NULL,...)
rect(par()$usr[1],par()$usr[4]-3*strheight("W"),
par()$usr[2],par()$usr[4],
border=0,col=make.transparent("blue",0.2))
textbox(x=par()$usr[1:2],y=par()$usr[4],
c("Click nodes to collapse or expand \nRIGHT CLICK to stop"),
justify="c",border=0)
if(nodes||i==nrow(M)){
lastPP<-get("last_plot.phylo",envir=.PlotPhyloEnv)
points(x=lastPP$xx[1:Ntip(tree)],y=lastPP$yy[1:Ntip(tree)],
pch=21,col="blue",bg="white",cex=0.8)
points(x=lastPP$xx[1:tree$Nnode+Ntip(tree)],
y=lastPP$yy[1:tree$Nnode+Ntip(tree)],pch=21,
col="blue",bg="white",cex=1.2)
}
dev.flush()
}
}
} else {
cat("Collapsing to the root is not permitted. Choose another node.\n")
flush.console()
}
x<-unlist(locator(1))
if(!is.null(x)){
y<-x[2]
x<-x[1]
lastPP<-get("last_plot.phylo",envir=.PlotPhyloEnv)
d<-sqrt((x-lastPP$xx)^2+(y-lastPP$yy)^2)
nn<-which(d==min(d,na.rm=TRUE))
}
}
}
options(locatorBell=TRUE)
if(drop.extinct){
if(!is.ultrametric(otree))
cat("Input tree was not ultrametric. Ignoring argument drop.extinct.\n")
else {
th<-setNames(sapply(1:Ntip(tree),nodeheight,tree=tree),tree$tip.label)
tips<-names(th)[which(th<(mean(sapply(1:Ntip(otree),
nodeheight,tree=otree))-.Machine$double.eps^0.5))]
tree<-drop.tip(tree,tips)
}
}
if(no.edge) tree$edge.length<-NULL
tree
}
circles<-function(x,y,r,col="blue")
nulo<-mapply(draw.circle,x=x,y=y,radius=r,MoreArgs=list(border=col,
col="white",nv=20))
fan<-function(tree,pw=NULL,nH=NULL,colors="black",fsize=0.6,ftype="i",lwd=1,mar=rep(0.1,4),
add=FALSE,part=1,xlim=NULL,ylim=NULL,tips=NULL,maxY=NULL,...){
if(length(colors)==1) colors<-rep(colors,nrow(tree$edge))
ftype<-which(c("off","reg","b","i","bi")==ftype)-1
cw<-tree
if(is.null(pw)) pw<-reorder(tree,"pruningwise")
n<-Ntip(cw)
m<-cw$Nnode
Y<-vector(length=m+n)
if(is.null(tips)) tips<-1:n
if(part<1.0) Y[cw$edge[cw$edge[,2]<=n,2]]<-0:(n-1)
else Y[cw$edge[cw$edge[,2]<=n,2]]<-tips
nodes<-unique(pw$edge[,1])
for(i in 1:m){
desc<-pw$edge[which(pw$edge[,1]==nodes[i]),2]
Y[nodes[i]]<-(min(Y[desc])+max(Y[desc]))/2
}
if(is.null(maxY)) maxY<-max(Y)
Y<-setNames(Y/maxY*2*pi,1:(n+m))
Y<-part*cbind(Y[as.character(tree$edge[,2])],Y[as.character(tree$edge[,2])])
R<-if(is.null(nH)) nodeHeights(cw) else nH
x<-R*cos(Y)
y<-R*sin(Y)
par(mar=mar)
offsetFudge<-1.37
offset<-0
if(is.null(xlim)||is.null(ylim)){
pp<-par("pin")[1]
sw<-fsize*(max(strwidth(cw$tip.label,units="inches")))+
offsetFudge*offset*fsize*strwidth("W",units="inches")
alp<-optimize(function(a,H,sw,pp) (2*a*1.04*max(H)+2*sw-pp)^2,H=R,sw=sw,pp=pp,
interval=c(0,1e6))$minimum
if(part<=0.25) x.lim<-y.lim<-c(0,max(R)+sw/alp)
else if(part>0.25&&part<=0.5){
x.lim<-c(-max(R)-sw/alp,max(R)+sw/alp)
y.lim<-c(0,max(R)+sw/alp)
} else x.lim<-y.lim<-c(-max(R)-sw/alp,max(R)+sw/alp)
xlim<-x.lim
ylim<-y.lim
}
if(!add) plot.new()
plot.window(xlim=xlim,ylim=ylim,asp=1)
segments(x[,1],y[,1],x[,2],y[,2],col=colors,lwd=lwd,lend=2)
ii<-sapply(1:m+n,function(x,y) which(y==x),y=cw$edge)
r<-sapply(1:m+n,function(x,y,R) R[match(x,y)],y=cw$edge,R=R)
a1<-sapply(ii,function(x,Y) min(Y[x]),Y=Y)
a2<-sapply(ii,function(x,Y) max(Y[x]),Y=Y)
draw.arc(rep(0,tree$Nnode),rep(0,tree$Nnode),r,a1,a2,lwd=lwd,col=colors)
cw$tip.label<-gsub("_"," ",cw$tip.label)
for(i in 1:n){
ii<-which(cw$edge[,2]==i)
aa<-Y[ii,2]/(2*pi)*360
adj<-if(aa>90&&aa<270) c(1,0.25) else c(0,0.25)
tt<-if(aa>90&&aa<270) paste(cw$tip.label[i]," ",sep="") else paste(" ",
cw$tip.label[i],sep="")
aa<-if(aa>90&&aa<270) 180+aa else aa
if(ftype) text(x[ii,2],y[ii,2],tt,srt=aa,adj=adj,cex=fsize,font=ftype)
}
PP<-list(type="fan",use.edge.length=TRUE,node.pos=1,
show.tip.label=if(ftype) TRUE else FALSE,show.node.label=FALSE,
font=ftype,cex=fsize,adj=0,srt=0,no.margin=FALSE,label.offset=offset,
x.lim=xlim,y.lim=ylim,direction="rightwards",tip.color="black",
Ntip=Ntip(cw),Nnode=cw$Nnode,edge=cw$edge,
xx=c(x[sapply(1:n,function(x,y) which(x==y)[1],y=tree$edge[,2]),2],x[1,1],
if(m>1) x[sapply(2:m+n,function(x,y) which(x==y)[1],y=tree$edge[,2]),2] else c()),
yy=c(y[sapply(1:n,function(x,y) which(x==y)[1],y=tree$edge[,2]),2],y[1,1],
if(m>1) y[sapply(2:m+n,function(x,y) which(x==y)[1],y=tree$edge[,2]),2] else c()))
assign("last_plot.phylo",PP,envir=.PlotPhyloEnv)
} |
get_trait_acf = function( tree,
tip_states,
Npairs = 10000,
Nbins = NULL,
min_phylodistance = 0,
max_phylodistance = NULL,
uniform_grid = FALSE,
phylodistance_grid = NULL){
Ntips = length(tree$tip.label)
Nnodes = tree$Nnode
Nedges = nrow(tree$edge)
if(!is.numeric(tip_states)) return(list(success=FALSE, error="tip_states must be numeric"))
Npairs = min(Npairs,(length(tree$tip.label))^2)
grid_is_uniform = FALSE
if(is.null(phylodistance_grid)){
if(is.null(max_phylodistance) || (max_phylodistance<0)) max_phylodistance = max(find_farthest_tip_pair(tree)$distance)
if(is.null(Nbins)){
Nbins = max(2,Npairs/10)
}
if(uniform_grid){
phylodistance_grid = seq(from=min_phylodistance, to=max_phylodistance, length.out=(Nbins+1))[seq_len(Nbins)]
grid_is_uniform = TRUE
}else{
tip_phylodistances = sort(sample_pairwise_tip_distances(tree, Npairs=Npairs))
tip_phylodistances = tip_phylodistances[(tip_phylodistances>=min_phylodistance) & (tip_phylodistances<=max_phylodistance)]
if(length(tip_phylodistances)==0) return(list(success=FALSE, error=sprintf("Unable to determine suitable phylodistance grid: No phylodistances found in target interval")))
phylodistance_grid = sort(unique(get_inhomogeneous_grid_1D_from_samples(Xstart=min_phylodistance, Xend=max_phylodistance, Ngrid=Nbins+1, randomX=tip_phylodistances)$grid[seq_len(Nbins)]))
Nbins = length(phylodistance_grid)
}
}else{
Nbins = length(phylodistance_grid)
if(any(diff(phylodistance_grid)<=0)) return(list(success=FALSE, error="Provided phylodistance_grid must be strictly increasing"))
if(is.null(max_phylodistance)){
max_phylodistance = Inf
}else{
max_phylodistance = max(max_phylodistance,max(phylodistance_grid))
}
if(length(phylodistance_grid)>1){
grid_steps = diff(phylodistance_grid)
if(min(grid_steps)>0.9999999*max(grid_steps)) grid_is_uniform = TRUE
}else{
grid_is_uniform = TRUE
}
}
results = ACF_continuous_trait_CPP( Ntips = Ntips,
Nnodes = Nnodes,
Nedges = Nedges,
tree_edge = as.vector(t(tree$edge))-1,
edge_length = (if(is.null(tree$edge.length)) numeric() else tree$edge.length),
state_per_tip = tip_states,
max_Npairs = Npairs,
phylodistance_grid = phylodistance_grid,
max_phylodistance = max_phylodistance,
grid_is_uniform = grid_is_uniform,
verbose = FALSE,
verbose_prefix = "")
left_phylodistances = phylodistance_grid
right_phylodistances = c((if(Nbins>1) phylodistance_grid[2:Nbins] else NULL), (if(max_phylodistance==Inf) results$max_encountered_phylodistance else max_phylodistance))
centroid_phylodistances = 0.5*(left_phylodistances+right_phylodistances)
return(list(success = TRUE,
phylodistances = centroid_phylodistances,
left_phylodistances = left_phylodistances,
right_phylodistances = right_phylodistances,
autocorrelations = results$autocorrelations,
mean_abs_differences = results$mean_abs_deviations,
mean_rel_differences = results$mean_rel_deviations,
Npairs_per_distance = results$N_per_grid_point))
} |
library(tidyverse)
library(lubridate)
library(scales)
library(broom)
library(extrafont)
library(RPostgreSQL)
taxi_con = dbConnect(dbDriver("PostgreSQL"), dbname = "nyc-taxi-data", host = "localhost")
citi_con = dbConnect(dbDriver("PostgreSQL"), dbname = "nyc-citibike-data", host = "localhost")
query = function(sql, con = taxi_con) {
dbSendQuery(con, sql) %>%
fetch(n = 1e8) %>%
as_data_frame()
}
taxi_hex = "
citi_hex = "
font_family = ifelse("Open Sans" %in% fonts(), "Open Sans", "Arial")
title_font_family = ifelse("Fjalla One" %in% fonts(), "Fjalla One", "Arial")
theme_tws = function(base_size = 12) {
bg_color = "
bg_rect = element_rect(fill = bg_color, color = bg_color)
theme_bw(base_size) +
theme(
text = element_text(family = font_family),
plot.title = element_text(family = title_font_family),
plot.subtitle = element_text(size = rel(0.7), lineheight = 1),
plot.caption = element_text(size = rel(0.5), margin = unit(c(1, 0, 0, 0), "lines"), lineheight = 1.1, color = "
plot.background = bg_rect,
axis.ticks = element_blank(),
axis.text.x = element_text(size = rel(1)),
axis.title.x = element_text(size = rel(1), margin = margin(1, 0, 0, 0, unit = "lines")),
axis.text.y = element_text(size = rel(1)),
axis.title.y = element_text(size = rel(1)),
panel.background = bg_rect,
panel.border = element_blank(),
panel.grid.major = element_line(color = "grey80", size = 0.25),
panel.grid.minor = element_line(color = "grey80", size = 0.25),
panel.spacing = unit(1.25, "lines"),
legend.background = bg_rect,
legend.key.width = unit(1.5, "line"),
legend.key = element_blank(),
strip.background = element_blank()
)
}
no_axis_titles = function() {
theme(axis.title = element_blank())
} |
library(rnaturalearth)
countries110 <- ne_download(scale=110, type='countries', category='cultural')
data_object_names <- data(package = "rnaturalearth")[["results"]][,"Item"]
for (i in 1:length(data_object_names))
{
data_name <- data_object_names[i]
eval(parse(text=paste0("devtools::use_data(",data_name,", compress='xz', overwrite=TRUE)")))
} |
tar_test("tar_exist_script()", {
expect_false(tar_exist_script())
tar_script()
expect_true(tar_exist_script())
})
tar_test("custom script and store args", {
skip_on_cran()
expect_equal(tar_config_get("script"), path_script_default())
expect_equal(tar_config_get("store"), path_store_default())
expect_false(tar_exist_script(script = "example/script.R"))
tar_script(tar_target(x, 1), script = "example/script.R")
expect_true(tar_exist_script(script = "example/script.R"))
expect_false(file.exists("_targets.yaml"))
expect_equal(tar_config_get("script"), path_script_default())
expect_equal(tar_config_get("store"), path_store_default())
expect_false(file.exists(path_script_default()))
expect_false(file.exists(path_store_default()))
expect_true(file.exists("example/script.R"))
tar_config_set(script = "x")
expect_equal(tar_config_get("script"), "x")
expect_true(file.exists("_targets.yaml"))
}) |
summary.cofad_bw <- function(object, ...){
x <- object
f_tab <- matrix(c(
round(x[[1]][1] * x[[1]][5], 3), round(x[[1]][3]),
round(x[[1]][1] * x[[1]][5], 3), round(x[[1]][1], 3),
round(x[[1]][2], 3),
round(x[[1]][5] * x[[1]][4], 3), round(x[[1]][4]),
round(x[[1]][5], 3), NA, NA,
round(x[[1]][7], 3), round(x[[1]][8]),
NA, NA, NA),
byrow = T, ncol = 5)
rownames(f_tab) <- c("contrast", "within", "total")
colnames(f_tab) <- c("SS", "df", "MS", "F", "p")
r_tab <- round(matrix(c(x[[4]]), ncol = 1), 3)
rownames(r_tab) <- c("r_effectsize", "r_contrast", "r_alerting")
colnames(r_tab) <- c("effects")
out <- list(f_tab, r_tab)
names(out) <- c("F-Table", "Effects")
return(out)
}
summary.cofad_wi <- function(object, ci = .95, ...){
x <- object
L_M <- x[[2]][[1]]
L_SE <- x[[2]][2]
L_df <- x[[1]][3]
L_p <- x[[1]][2]
L_SE_ci <- qt(p = (1 - ci) / 2, df = L_df, lower.tail = F) * L_SE
L_UB <- L_M + L_SE_ci
L_LB <- L_M - L_SE_ci
L_vals <- matrix(c(
L_M, L_SE, L_df, L_p, L_LB, L_UB), ncol = 6)
L_eff <- matrix(c(x[[4]][1], x[[4]][2]))
rownames(L_eff) <- c("r-contrast", "g-contrast")
colnames(L_vals) <- c("Mean", "SE", "df", "p",
"CI-lower", "CI-upper")
out <- list(L_vals, L_eff)
names(out) <- c("L-Statistics", "Effects")
return(out)
}
summary.cofad_mx <- function(object, ...){
x <- object
all_L <- as.vector(x[[6]])
all_L <- all_L[which(!is.na(all_L))]
SS_total <- sum(
(all_L - mean(all_L)) ** 2)
df_total <- length(all_L) - 1
f_tab <- matrix(c(
SS_contrast <- x[[1]][5],
df_contrast <- 1,
MS_contrast <- x[[1]][5],
F_contrast <- x[[1]][1],
p_contrast <- x[[1]][2],
SS_within <- x[[1]][6] * x[[1]][4],
df_within <- x[[1]][4],
MS_within <- x[[1]][6], NA, NA,
SS_total, df_total, NA, NA, NA),
ncol = 5, byrow = T)
f_tab <- round(f_tab, 3)
l_tab <- x[[2]]
r_tab <- round(matrix(c(x[[5]]), ncol = 1), 3)
colnames(r_tab) <- "effect"
rownames(r_tab) <- c("r_effectsize", "r_contrast", "r_alerting")
rownames(f_tab) <- c("contrast", "within", "total")
colnames(f_tab) <- c("SS", "df", "MS", "F", "p" )
out <- list(f_tab, r_tab, l_tab)
names(out) <- c("F_Table", "Effects", "Within_Groups")
return(out)
} |
test_that("Queries are constructed from linear models containing factors", {
scipen_before <- getOption("scipen")
options(scipen=999)
a <- 1:10
b <- 2*1:10
c <- as.factor(1:10)
df <- data.frame(a,b,c)
formula = b ~ a + c
model <- lm(formula, data = df)
intercept <- model$coefficients[["(Intercept)"]]
a_coefficient <- model$coefficients[["a"]]
c2_coefficient <- model$coefficients[["c2"]]
c3_coefficient <- model$coefficients[["c3"]]
c4_coefficient <- model$coefficients[["c4"]]
c5_coefficient <- model$coefficients[["c5"]]
c6_coefficient <- model$coefficients[["c6"]]
c7_coefficient <- model$coefficients[["c7"]]
c8_coefficient <- model$coefficients[["c8"]]
c9_coefficient <- model$coefficients[["c9"]]
c10_coefficient <- model$coefficients[["c10"]]
expected <- paste(
intercept, " + ", a_coefficient, "*a", " + ",
"(CASE WHEN c = ", "'2'", " THEN ", c2_coefficient,
" WHEN c = ", "'3'", " THEN ", c3_coefficient,
" WHEN c = ", "'4'", " THEN ", c4_coefficient,
" WHEN c = ", "'5'", " THEN ", c5_coefficient,
" WHEN c = ", "'6'", " THEN ", c6_coefficient,
" WHEN c = ", "'7'", " THEN ", c7_coefficient,
" WHEN c = ", "'8'", " THEN ", c8_coefficient,
" WHEN c = ", "'9'", " THEN ", c9_coefficient,
" WHEN c = ", "'10'", " THEN ", 0,
" ELSE 0 END)",
sep=""
)
sql <- modelc::modelc(model)
expect_equal(sql, expected)
options(scipen=scipen_before)
}) |
x=1:10
x
x1
(x1 <- 1:20)
(x1=1:30)
(x2=c(1,2,13,4,5))
class(x2)
(x3=letters[1:10])
class(x3)
LETTERS[1:26]
(x3b = c('a',"Henry","4"))
class(x3b)
(x4=c(T,FALSE,TRUE,T,F))
class(x4)
x5=c(3L,5L)
class(x5)
x5a = c(3,5)
class(x5a)
(x5b = c(1, 'a',T, 4L))
class(x5b)
(x6 = seq(0,100,by=3))
methods(class='numeric')
?seq
ls()
x6
length(x6)
x6[20]
x6[3]
x6[c(2, 4)]
x6[-1]
x6[-c(1:10, 15:20)]
x6[c(2, -4)]
x6[-c(1,5,20)]
x = x[1:4]; x
x6 ; rev(x6)
sort(x6)
sort(x6, decreasing=T)
x6[ x6 > 10 & x6 < 40]
length(x6[ x6 > 10 & x6 < 40])
tail(x6)
?tail
tail(x6, n=5)
x6[length(x6)/2]
x6[length(x6)/2] =99
x6[length(x6)/2]
x6[1:5] = 99
head(x6)
(x=100:111); length(x)
matrix(1, nrow=4, ncol=2)
(m1 = matrix(100:111, nrow=4))
(m2 = matrix(x, ncol=3, byrow=T))
matrix(x, ncol=6)
class(m1)
attributes(m1)
dim(m1)
m1
m1[1,2:3]
m1[c(1,3),]
m1[,-c(1,3), drop=F]
m2[m2 > 105 & m2 < 110]
m1
colnames(m1)=c('C1','C2','C3')
rownames(m1)=c('R1','R2','R3','R4')
colMeans(m1) ; rowMeans(m1)
colSums(m1) ; rowSums(m1)
min(m1); max(m1);sd(m1)
pie(colSums(m1))
barplot(rowSums(m1), col=1:4, ylim=c(0,200))
(rollno = 1:30)
(sname = paste('student',1:30,sep=''))
(gender = sample(c('M','F'), size=30, replace=T, prob=c(.7,.3)))
(marks1 = floor(rnorm(30,mean= 50,sd=10)))
(marks2 = ceiling(rnorm(30,40,5)))
(course = sample(c('BBA','MBA'), size=30, replace=T, prob=c(.5,.5)))
(grades = sample(c(LETTERS[1:5]), size=30, replace=T))
rollno; sname; gender ; marks1 ; marks2; course; grades
df1= data.frame(rollno, sname, gender, marks1, marks2, course, grades, stringsAsFactors = F)
head(df1)
str(df1)
head(df1,n=3)
tail(df1)
class(df1)
summary(df1)
df1
head(df1)
df1$sname
df1$gender = factor(df1$gender)
df1$course = factor(df1$course)
df1$grades = factor(df1$grades, ordered=T, levels=c('E','D','C','B','A'))
str(df1)
summary(df1)
df1
df1$gender
df1[1:3 , c(2,4)]
df1[ marks2 < 50 & gender=='F', c('rollno', 'sname','gender', 'marks1')]
range(df1$marks2)
df1[ marks1 > 50 & gender=='F', c(1,2)]
df1[ marks1 > 50 | gender=='F', ]
names(df1)
dim(df1)
aggregate(df1$marks1, by=list(df1$gender), FUN=mean)
aggregate(marks1 ~ gender, data=df1, FUN=mean)
aggregate(cbind(marks1, marks2) ~ gender + course, data=df1, FUN=mean)
?aggregate
df1[ order(df1$gender, df1$marks1),]
df1$grades
df1[ order(df1$course, df1$gender),]
df1[ order(df1$course, desc(df1$grades)),]
df1[ order(df1$course, df1$grades),]
fivenum(df1$marks1); summary(df1$marks1)
boxplot(df1$marks1)
abline(h=fivenum(df1$marks1), col=1:5,lwd=2)
boxplot(marks1 ~ gender, data=df1)
boxplot(marks2 ~ course, data=df1)
boxplot(marks2 ~ course, data=df1, col=c('red','green'))
title("Box Plot of Marks2 vs Course")
boxplot(marks2 ~ grades, data=df1, col=1:5)
aggregate(cbind(marks1, marks2) ~ gender, data=df1, FUN=mean)
library(dplyr)
head(df1)
df1 %>% select(sname, gender, marks1) %>% head
df1 %>% filter(marks2 > 45)
df1 %>% filter(marks1 > 45 & gender == 'F')
names(df1)
head(df1)
df1 %>% group_by(course,gender) %>% summarise(MEAN1 = mean(marks1), MAX2 = max(marks2))
df1 %>% group_by(course,gender, grades) %>% count
df1 %>% sample_n(2)
df1 %>% sample_frac(.3)
out2 <- df1 %>% group_by(gender) %>% sample_frac(.2)
out2
table(df1$gender)
df1 %>% arrange(gender, course, desc(marks1)) %>% select(gender, course, marks1) |
relRisk<- function(formula, id, waves = NULL,
data = parent.frame(), subset = NULL,
contrasts = NULL, na.action = na.omit,
corstr = "indep",
ncopy = 1000, control = geese.control(),
b = NULL, alpha = NULL) {
family <- binomial("log")
scall <- match.call()
mnames <- c("", "formula", "data", "offset", "subset", "na.action", "id", "waves")
cnames <- names(scall)
cnames <- cnames[match(mnames,cnames,0)]
mcall <- scall[cnames]
if (is.null(mcall$id)) mcall$id <- as.name("id")
mcall[[1]] <- as.name("model.frame")
m <- eval(mcall, parent.frame())
y <- model.extract(m, "response")
if (is.null(dim(y))) N <- length(y) else N <- dim(y)[1]
mterms <- attr(m, "terms")
x <- model.matrix(mterms, m, contrasts)
offset <- model.extract(m, "offset")
if (is.null(offset)) offset <- rep(0, N)
w <- rep(1 - 1 / ncopy, N)
w.copy <- rep(1 / ncopy, N)
y.copy <- 1 - y
id <- model.extract(m, id)
waves <- model.extract(m, waves)
Y <- c(y, y.copy)
W <- c(w, w.copy)
X <- rbind(x, x)
ID <- c(id, id + max(id))
Waves <- c(waves, waves)
Offset <- c(offset, offset)
Freq <- rep(c(2, 1), each = N)
fit0 <- glm.fit(X, Y, offset = Offset, weights = Freq, family = family)
fit1 <- glm.fit(X, Y, offset = Offset, family = family, weights = W, start = fit0$coefficients)
ans <- geese.fit(X, Y, ID, Offset, weights = W, waves = Waves,
family = family, control = control, corstr = corstr,
b = fit1$coefficients, scale.fix = TRUE)
ans <- c(ans, list(call=scall, formula=formula))
class(ans) <- "geese"
ans
} |
skip_if_vcr_off <- function() {
if (!requireNamespace("testthat", quietly = TRUE)) {
stop(
paste0(
"This function is meant to be used within testthat tests.",
"Please install testthat."
)
)
}
if (
nzchar(Sys.getenv("VCR_TURN_OFF")) &&
as.logical(Sys.getenv("VCR_TURN_OFF"))
) {
testthat::skip("Not run when vcr is off")
}
} |
RwlInfo = function (rwl, print = TRUE, chrono = NULL)
{
yr.range = function(x) {
yr.vec = as.numeric(names(x))
mask = !is.na(x)
range(yr.vec[mask])
}
acf1 = function(x) {
x = x[!is.na(x)]
ar1 = acf(x, lag.max = 1, plot = FALSE)
ar1$acf[2]
}
skew = function(x) {
x = x[!is.na(x)]
sum((x - mean(x))^3)/(length(x) * sd(x)^3)
}
if (is.null(chrono))
chrono <- apply(rwl, 1, mean, na.rm = TRUE)
info.fun = function(x, chrono) {
out = c(rep(NA, 12))
out[1] = yr.range(x)[1]
out[2] = yr.range(x)[2]
out[3] = out[2] - out[1] + 1
out[4] = cor(x, chrono, use = "pairwise.complete.obs")
out[5] = mean(x, na.rm = TRUE)
out[6] = median(x, na.rm = TRUE)
out[7] = sd(x, na.rm = TRUE)
out[8] = skew(x)
out[9] = sens1(x)
out[10] = sens2(x)
out[11] = gini.coef(x)
out[12] = acf1(x)
return(out)
}
out = t(apply(rwl, 2, info.fun, chrono))
colnames(out) <- c("First", "Last", "Span", "Corr", "Mean",
"Median", "SD", "Skew", "Sens1", "Sens2", "Gini", " Ar1")
col.mean <- c(NA, NA, round(apply(out[, 3:12], 2, mean),
3))
out <- rbind(out, col.mean)
rownames(out)[nrow(out)] = "Mean "
out[, -c(1:3)] = round(out[, -c(1:3)], 3)
out[, 3] = round(out[, 3], 0)
if (print) {
cat(rep("=", 98), "\n", sep = "")
WriteMatrix(out, na = "", sep = "|", ID = T, ID.name = "Seq",
col.width = 6, row.name = "Series ")
cat(rep("=", 98), "\n", sep = "")
}
else {
return(out)
}
} |
library("testthat")
library("spectrolab")
context("Spectra subsetting by")
spec = as_spectra(spec_matrix_example, name_idx = 1)
by_def = names(spec)
by_rnd = c(rep(1, 5), rep(2, 10), rep(3, 35))
test_that("by factor that isn't a sample name works", {
expect_true( nrow(subset_by(spec, by = by_rnd, n_min = 6, n_max = 20)) == 30 )
})
test_that("by of wrong length throws", {
expect_error( subset_by(spec, by = by_def[ 1 : floor(nrow(spec) / 2)],
n_min = 1, n_max = 5) )
})
test_that("by of wrong length throws", {
expect_error( subset_by(spec, by = NULL, n_min = 1, n_max = 5))
})
test_that("zero n_max throws an error", {
expect_error( subset_by(spec, by = by_def, n_min = 1, n_max = 0))
})
test_that("n_max is larger than n_min", {
expect_error( subset_by(spec, by = by_def, n_min = 5, n_max = 2))
})
test_that("n_max = 1 will return a subetted obj", {
expect_lt( nrow(subset_by(spec, by = by_def, n_min = 1, n_max = 1)), nrow(spec) )
})
test_that("n_min = 5 will return a subetted obj", {
expect_lt( nrow(subset_by(spec, by = by_def, n_min = 5, n_max = Inf)), nrow(spec) )
})
test_that("null if n_min is too large", {
expect_null( subset_by(spec, by = by_def, n_min = 100, n_max = Inf) )
})
test_that("same spec obj is returned if n_min and n_max are wide enough", {
expect_true( nrow(subset_by(spec, by = by_def,
n_min = 1, n_max = Inf)) == nrow(spec))
}) |
library(act)
all.tiers <- act::info(examplecorpus)$tiers
all.tiers["A", "tier.count"]
all.tiers["B", "tier.count"]
tierNames <- c("A", "B")
x<- examplecorpus
x <- act::tiers_delete(examplecorpus, tierNames=tierNames)
x@history[length(x@history)]
act::info(x)$tiers$tier.name |
grace <- function(Y, X, L, lambda.L, lambda.1 = 0, lambda.2 = 0, normalize.L = FALSE, K = 10, verbose = FALSE){
checkdata(X, Y, L)
lambda.L <- unique(sort(lambda.L, decreasing = TRUE))
lambda.1 <- unique(sort(lambda.1, decreasing = TRUE))
lambda.2 <- unique(sort(lambda.2, decreasing = TRUE))
ori.Y <- Y
ori.X <- X
if(min(lambda.L) < 0 | min(lambda.2) < 0 | min(lambda.1) < 0){
stop("Error: Tuning parameters must be non-negative.")
}
if(min(lambda.L) == 0 & min(lambda.2) == 0 & min(lambda.1) == 0 & length(lambda.L) == 1 & length(lambda.2) == 1 & length(lambda.1) == 1){
stop("Error: At least one of the tuning parameters must be positive.")
}
Y <- Y - mean(Y)
n <- nrow(X)
p <- ncol(X)
scale.fac <- attr(scale(X), "scaled:scale")
X <- scale(X)
if(normalize.L){
diag(L)[diag(L) == 0] <- 1
L <- diag(1 / sqrt(diag(L))) %*% L %*% diag(1 / sqrt(diag(L)))
}
emin <- min(eigen(min(lambda.L) * L + min(lambda.2) * diag(p))$values)
if(emin < 1e-5){
stop("Error: The penalty matrix (lambda.L * L + lambda.2 * I) is not always positive definite for all tuning parameters. Consider increase the value of lambda.2.")
}
if((length(lambda.L) > 1) | (length(lambda.1) > 1) | (length(lambda.2) > 1)){
tun <- cvGrace(X, Y, L, lambda.L, lambda.1, lambda.2, K)
lambda.L <- tun[1]
lambda.1 <- tun[2]
lambda.2 <- tun[3]
if(!verbose){
print(paste("Tuning parameters selected by ", K, "-fold cross-validation:", sep = ""))
print(paste("lambda.L = ", lambda.L, sep = ""))
print(paste("lambda.1 = ", lambda.1, sep = ""))
print(paste("lambda.2 = ", lambda.2, sep = ""))
}
}
Lnew <- lambda.L * L + lambda.2 * diag(p)
eL <- eigen(Lnew)
S <- eL$vectors %*% sqrt(diag(eL$values))
l1star <- lambda.1
Xstar <- rbind(X, t(S)) / sqrt(2)
Ystar <- c(Y, rep(0, p))
gammastar <- l1star / sqrt(2) / 2 / (n + p)
betahatstar <- glmnet(Xstar, Ystar, lambda = gammastar, intercept = FALSE, standardize = FALSE, thresh = 1e-11)$beta[, 1]
betahat <- betahatstar / sqrt(2)
truebetahat <- betahat / scale.fac
truealphahat <- mean(ori.Y - ori.X %*% truebetahat)
return(list(intercept = truealphahat, beta = truebetahat))
} |
AAMR <- function (Data.Name, JK = NULL, CL = NULL,
PeriodEnd = NULL, Period = NULL)
{
v013 <- rweight <- sex <- exposure <- agegrp <- death <- NULL
Data.Name <- Data.Name[!Data.Name$v005 == 0, ]
Data.Name$ID <- seq.int(nrow(Data.Name))
if (is.null(CL)) {
Z <- stats::qnorm(.025,lower.tail=FALSE)
} else {
Z <- stats::qnorm((100-CL)/200,lower.tail=FALSE)
}
if (is.null(Period)){Periodmsg = 84} else {Periodmsg = Period}
if (is.null(PeriodEnd)){
PeriodEndy_ <- as.integer((mean(Data.Name$v008) - 1)/12)+1900
PeriodEndm_ <- round(mean(Data.Name$v008) - ((PeriodEndy_ - 1900) * 12),0)
PeriodEndm_m <- round(min(Data.Name$v008) - ((PeriodEndy_ - 1900) * 12),0)
PeriodEndm_x <- round(max(Data.Name$v008) - ((PeriodEndy_ - 1900) * 12),0)
} else {
dates <- paste(PeriodEnd, "01", sep = "-")
PeriodEndm_ <- as.numeric(format(as.Date(dates), "%m"))
PeriodEndy_ <- as.numeric(format(as.Date(dates), "%Y"))
if (PeriodEndm_ >= round(mean(Data.Name$v008) - (((as.integer((mean(Data.Name$v008) - 1)/12)+1900) - 1900) * 12),0) &
PeriodEndy_ >= as.integer((mean(Data.Name$v008) - 1)/12)+1900)
message(crayon::bold("Note:", "\n",
"You specified a reference period that ends after the survey fieldwork dates....."), "\n",
"1. Make sure the dates in the survey are coded according to the Gregorian calendar.", "\n",
"2. If the dates are coded according to the Gregorian calendar, use a proper PeriodEnd that came before the time of the survey.", "\n",
"3. If the dates are not coded according to the Gregorian calendar, use a PeriodEnd according to the used calendar.")
}
if (is.null(PeriodEnd)){
cat("\n", crayon::white$bgBlue$bold("The current function calculated AAMR based on a reference period of"),
crayon::red$bold$underline(Periodmsg), crayon::white$bold$bgBlue("months"), "\n", crayon::white$bold$bgBlue("The reference period ended at the time of the interview, in"), crayon::red$bold$underline(PeriodEndy_ + round(PeriodEndm_/12,digits=2)), "OR", crayon::red$bold$underline(month.abb[PeriodEndm_m]), "-", crayon::red$bold$underline(month.abb[PeriodEndm_x]), crayon::red$bold$underline(PeriodEndy_), "\n",
crayon::white$bold$bgBlue("The average reference period is"), crayon::red$bold$underline(round((PeriodEndy_ + PeriodEndm_/12)-(Periodmsg/24), digits =2)), "\n")
} else {
cat("\n", crayon::white$bgBlue$bold("The current function calculated AAMR based on a reference period of"),
crayon::red$bold$underline(Periodmsg), crayon::white$bold$bgBlue("months"), "\n", crayon::white$bold$bgBlue("The reference period ended in"), crayon::red$bold$underline(PeriodEndy_ + round(PeriodEndm_/12,digits=2)), "OR", crayon::red$bold$underline(month.abb[PeriodEndm_]), crayon::red$bold$underline(PeriodEndy_), "\n",
crayon::white$bold$bgBlue("The average reference period is"), crayon::red$bold$underline(round((PeriodEndy_ + PeriodEndm_/12)-(Periodmsg/24), digits =2)), "\n")
}
Data.Name$id <- c(as.factor(Data.Name$v021))
Data.Name$rweight = Data.Name$v005 / 1000000
DeathEx <- DataPrepareM(Data.Name, PeriodEnd, Period)
if (is.null(JK)){PSU <- 0} else {PSU <- max(as.numeric(DeathEx$id))}
options(dplyr.summarise.inform = FALSE)
AGEDIST <- (dplyr::group_by(Data.Name, v013) %>% summarise(x = sum(rweight)))$x/sum(Data.Name$rweight)
options(survey.lonely.psu = "adjust")
dstrat <- survey::svydesign(id = ~ v021, strata = ~ v022, weights = ~ rweight, data = DeathEx)
ASMR <- (survey::svyby(~ death, by = ~ agegrp+sex, denominator = ~ exposure,
design = dstrat, survey::svyratio))[, 3]
aamr <- c(sum(ASMR[1:7] * AGEDIST), sum(ASMR[8:14] * AGEDIST))
N = (dplyr::group_by(DeathEx, sex) %>% summarise(x = sum(exposure)))$x
WN = (survey::svyby(~ exposure, by = ~ sex, design = dstrat, survey::svytotal))$exposure
deaths <- WN*(aamr/1000)
AAMR_DEFT = sqrt(survey::svyby(~ death, by = ~ sex, denominator = ~ exposure,
design = dstrat, deff = "replace", survey::svyratio)$DEff)
SEX <- c("FEMALES","MALES")
JKres <- matrix(0, nrow = PSU, ncol = 2)
dimnames(JKres) <- list(NULL, c("AAMRj_f","AAMRj_m"))
if (is.null(JK)){
RESULTS <- cbind.data.frame(SEX, round(deaths, 0), round(WN, 0), aamr, round(N, 0), row.names = NULL)
names(RESULTS) <- c("SEX", "Deaths", "Exposure_years", "AAMR", "N")
list(RESULTS)
} else {
for (i in unique(as.numeric(DeathEx$id)))
{
Data.NameJ <- Data.Name[which(!Data.Name$id == i), ]
AGEDISTj <- (dplyr::group_by(Data.NameJ, v013) %>% summarise(x = sum(rweight)))$x/sum(Data.NameJ$rweight)
DeathExJ <- DeathEx[which(!DeathEx$id == i), ]
ASMRj <- (dplyr::group_by(DeathExJ, sex, agegrp) %>% summarise(x = sum(death*rweight)))$x/
(dplyr::group_by(DeathExJ, sex, agegrp) %>% summarise(x = sum(exposure*rweight)))$x
JKres[i,1] <- sum(ASMRj[1:7] * AGEDISTj)
JKres[i,2] <- sum(ASMRj[8:14] * AGEDISTj)
}
AAMRjf = JKres[1:PSU, 1]
AAMRjm = JKres[1:PSU, 2]
JKSEf = ((PSU * aamr[1] - (PSU-1) * AAMRjf)-aamr[1])^2
JKSEm = ((PSU * aamr[2] - (PSU-1) * AAMRjm)-aamr[2])^2
SE = c(sqrt(sum(JKSEf) / (PSU * (PSU-1))), sqrt(sum(JKSEm) / (PSU * (PSU-1))))
RSE = SE / aamr
LCI = aamr - (Z * SE)
LCI[LCI <= 0] = 0
UCI = aamr + (Z * SE)
PSUs = c(PSU,PSU)
RESULTS <- cbind.data.frame(SEX, round(deaths, 0), round(WN, 0), round(aamr,3), round(SE,3), round(N, 0), round(AAMR_DEFT,3), round(RSE,3), round(LCI,3), round(UCI,3), PSUs, row.names = NULL)
names(RESULTS) <- c("SEX","Deaths", "Exposure_years", "AAMR", "SE", "N", "DEFT", "RSE", "LCI", "UCI", "iterations")
list(RESULTS)
}
} |
substi <- function(x,y,pr=TRUE)
{
if(length(x)!=length(y))
stop("lengths of x and y are different")
nf <- is.factor(x) + is.factor(y)
if(nf==1)
stop("both x and y must be factor variables if either is")
isna <- is.na(x)
vnames <- sys.call()[c(2,3)]
if(pr) {
cat("Variables:",vnames,"\n")
cat("Used first variable:",sum(!is.na(x)),"\n")
cat("Used second variable:",sum(is.na(x) & !is.na(y)),"\n")
}
if(nf) {
levs <- unique(c(levels(x),levels(y)))
x <- as.character(x)
y <- as.character(y)
x[isna] <- y[isna]
x <- factor(x,levs)
y <- factor(y,levs)
} else
x[isna] <- y[isna]
ss <- ifelse(isna & is.na(y),NA,ifelse(isna,2,1))
attr(ss,"names") <- NULL
ss <- factor(ss,labels=vnames)
if(pr)
cat("Obs:",sum(!is.na(x))," Obs missing:",sum(is.na(x)),"\n")
attr(x,"substi.source") <- ss
attr(x,'class') <- c("substi",attr(x,'class'))
x
}
substi.source <- function(x) attr(x,"substi.source")
"[.substi" <- function(x, ...)
{
ss <- attr(x,"substi.source")
ats <- attributes(x)
ats$dimnames <- ats$dim <- ats$names <- ats$substi.source <-
attr(x,'class') <- NULL
x <- (x)[...]
attributes(x) <- ats
attr(x,"substi.source") <- ss[...]
x
}
print.substi <- function(x, ...)
{
i <- unclass(attr(x, "substi.source"))
if(!length(i)) {
print.default(x)
return(invisible())
}
if(is.factor(x))
w <- as.character(x)
else w <- format(x)
names(w) <- names(x)
w[i==2] <- paste(w[i==2], "*", sep = "")
attr(w, "label") <- attr(w, "substi.source") <- attr(w, "class") <- NULL
print.default(w, quote = FALSE)
invisible()
}
as.data.frame.substi <- function(x, row.names = NULL, optional = FALSE, ...)
{
nrows <- length(x)
if(!length(row.names)) {
if(length(row.names <- names(x)) == nrows &&
!any(duplicated(row.names))) {
}
else if(optional)
row.names <- character(nrows)
else row.names <- as.character(1:nrows)
}
value <- list(x)
if(!optional)
names(value) <- deparse(substitute(x))[[1]]
structure(value, row.names=row.names, class='data.frame')
} |
expect_equal(
sapply(iris, n_distinct),
sapply(iris, function(.) length(unique(.))),
info = "n_distinct() gives the correct results on a data.frame"
)
df_var <- data.frame(
l = c(TRUE, FALSE, FALSE),
i = c(1, 1, 2),
d = Sys.Date() + c(1, 1, 2),
f = factor(letters[c(1, 1, 2)]),
n = c(1, 1, 2) + 0.5,
t = Sys.time() + c(1, 1, 2),
c = letters[c(1, 1, 2)],
stringsAsFactors = FALSE
)
expect_equal(
sapply(df_var, n_distinct),
sapply(df_var, function(.) length(unique(.))),
info = "n_distinct() gives correct results for key types"
)
expect_equal(
n_distinct(c(1.0, NA, NA)),
2,
info = "n_distinct() treats NA correctly"
)
expect_equal(
n_distinct(1, 1:4),
4,
info = "n_distinct() recycles length 1 vectors"
)
expect_equal(
n_distinct(1:4, 1),
4,
info = "n_distinct() recycles length 1 vectors"
)
x <- iris$Sepal.Length
y <- iris$Sepal.Width
expect_equal(
n_distinct(iris$Sepal.Length, iris$Sepal.Width),
n_distinct(x, y),
info = "n_distinct() handles unnamed"
)
expect_identical(
data.frame(x = 42) %>% summarise(n = n_distinct(.data$x)),
data.frame(n = 1L),
info = "n_distinct() respects .data"
)
rm(df_var, x, y)
expect_equal(
n_distinct(c(0, 1, 1, 2, 3, 5, 8, NA), na.rm = TRUE),
6L,
info = "na.rm removes NAs"
)
expect_equal(
n_distinct(list(c(1, 1, 2), c(1, 2, 3))),
2L,
info = "n_distinct() can handle nested lists"
) |
test_that("model fitting", {
skip_if_not(TEST_MODEL_FITTING)
with_parallel({
model <- "RPartModel"
expect_output(test_model_binary(model))
expect_output(test_model_factor(model))
expect_output(test_model_numeric(model))
expect_output(test_model_ordered(model))
expect_output(test_model_Surv(model))
})
}) |
options(replace.assign=TRUE)
options(width=80)
opts_chunk$set(tidy=FALSE,
highlight=TRUE,
fig.show='hold', cache=FALSE, par=TRUE)
knit_hooks$set(par=function(before, options, envir){
if (before && options$fig.show!='none')
par(mar=c(5,4,2,2) + 0.1,
cex.lab=.95,cex.axis=.9
,mgp=c(2,.7,0),tcl=-.3
)
}, crop=hook_pdfcrop)
options(width=72)
library(gWidgets2)
options(guiToolkit="RGtk2")
win <- gwindow("Basic example", visible=FALSE)
gp <- gvbox(container=win)
btn <- gbutton("click me for a message", container=gp)
addHandlerClicked(btn, handler=function(h,...) {
galert("Hello world!", parent = win)
})
visible(win) <- TRUE
lorem <- "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
win <- gwindow("Nested groups")
g <- gvbox(container=win)
g$set_borderwidth(10L)
txt <- gtext(lorem, container=g,
expand=TRUE, fill=TRUE)
bg <- ggroup(cont=g)
addSpring(bg)
gbutton("dismiss", container=bg,
handler=function(h,...) dispose(win))
gbutton("about", container=bg, handler=function(h,...) {
gmessage("Shows lorem ipsum text", parent=win)
})
win <- gwindow("t-test", visible=FALSE)
g <- gvbox(container=win)
g$set_borderwidth(10L)
flyt <- gformlayout(container=g, expand=TRUE)
gedit("", initial.msg="variable",
label="x", container=flyt)
gcombobox(c("two.sided", "less", "greater"),
label="alternative", container=flyt)
gedit("0", coerce.with=as.numeric,
label="mu", container=flyt)
gcheckbox("", checked=FALSE,
label="paired", container=flyt)
gslider(from=0.5, to = 1.0, by=.01, value=0.95,
label="conf.level", container=flyt)
bg <- ggroup(container=g)
addSpring(bg)
gbutton("values...", container=bg, handler=function(h,...) {
print(svalue(flyt))
})
addSpring(g)
size(win) <- c(400, 250)
visible(win) <- TRUE
win <- gwindow("handler example", visible=FALSE)
g <- gvbox(container=win)
f <- gframe("Ethnicity", container=g)
cb <- gcheckboxgroup(c("White",
"American Indian and Alaska Native",
"Asian",
"Black or African American",
"Native Hawaiian and Other Pacific Islander"),
container=f)
bg <- ggroup(cont=g); addSpring(bg)
b <- gbutton("Go", container=bg)
enabled(b) <- FALSE
addHandlerChanged(cb, handler=function(h,...) {
enabled(b) <- length(svalue(h$obj)) > 0
})
visible(win) <- TRUE
about <- "
A simple GUI to simplify the loading and unloading of packages.
This GUI uses `gcheckboxgroup`, with its `use.table` argument, to
present the user with familiar checkboxes to indicate selection.
Some indexing jujitsu is needed to pull out which value is checked to
trigger the event.
"
installed <- installed.packages()
installed_packages <- installed[, "Package"]
package_status <- function() {
installed_packages %in% loadedNamespaces()
}
w <- gwindow("package manager", visible=FALSE)
g <- gvbox(cont=w)
g$set_borderwidth(10L)
a <- package_status()
tbl <- gcheckboxgroup(installed_packages, checked=package_status(),
use.table=TRUE,
expand=TRUE, container=g)
bg <- ggroup(cont=g)
addSpring(bg)
gbutton("About", container=bg, handler=function(...) {
w1 <- gwindow("About", parent=w, visible=FALSE)
g <- gvbox(container=w1); g$set_borderwidth(10)
glabel(about, container=g, expand=TRUE)
gseparator(container=g)
bg <- ggroup(cont=g)
addSpring(bg)
gbutton("dismiss", cont=bg, handler=function(h,...) {
dispose(w1)
})
visible(w1) <- TRUE
})
visible(w) <- TRUE
update_tbl <- function(...) {
blockHandlers(tbl)
on.exit(unblockHandlers(tbl))
svalue(tbl, index=TRUE) <- package_status()
}
addHandlerChanged(tbl, handler=function(h, ...) {
ind <- svalue(h$obj, index=TRUE)
old_ind <- which(package_status())
if(length(x <- setdiff(old_ind, ind))) {
message("detach ", installed_packages[x])
pkg <- sprintf("package:%s", installed_packages[x])
detach(pkg, unload=TRUE, character.only=TRUE)
} else if (length(x <- setdiff(ind, old_ind))) {
require(installed_packages[x], character.only=TRUE)
}
update_tbl()
})
about <- "GUI to upgrade installed packages"
repos <- getOption("repos")
repos["CRAN"] <- "http://streaming.stat.iastate.edu/CRAN/"
options(repos = repos)
pkg <- old.packages()[,c("Package", "Installed", "ReposVer")]
w <- gwindow("Upgrade installed packages", visible=FALSE)
g <- gvbox(container=w)
g$set_borderwidth(10)
fg <- ggroup(container=g)
glabel("Filter by:", container=fg)
fltr <- gedit("", initial.msg="Filter by regexp",
container=fg)
tbl <- gtable(pkg, chosen.col=1, multiple=TRUE,
container=g, expand=TRUE)
bg <- ggroup(container=g); addSpring(bg)
gbutton("About", container=bg, handler=function(h,...) {
w1 <- gwindow("About", parent=w, visible=FALSE)
g <- gvbox(container=w1); g$set_borderwidth(10)
glabel(about, container=g, expand=TRUE)
bg <- ggroup(container=g); addSpring(bg)
gbutton("dismiss", container=bg,
handler=function(h,...) dispose(w1))
visible(w1) <- TRUE
})
update_btn <- gbutton("Update selected", container=bg,
handler=function(h,...) {
pkgs <- svalue(tbl)
if(length(pkgs) == 0) return()
sapply(pkgs, install.packages)
tbl[] <- pkg <<-
old.packages()[,c("Package", "Installed", "ReposVer")]
svalue(fltr) <- ""
})
enabled(update_btn) <- FALSE
visible(w) <- TRUE
addHandlerKeystroke(fltr, handler=function(h,...) {
regexp <- svalue(h$obj)
if(nchar(regexp) > 0 && regexp != "") {
ind <- grepl(regexp, pkg[, 'Package'])
visible(tbl) <- ind
} else {
visible(tbl) <- rep(TRUE, nrow(pkg))
}
})
addHandlerSelectionChanged(tbl, handler=function(h,...) {
enabled(update_btn) <- length(svalue(h$obj))
}) |
NewInput.MM1KK <- function(lambda=0, mu=0, k=1, method=3)
{
res <- list(lambda = lambda, mu = mu, k = k, method = method)
class(res) <- "i_MM1KK"
res
}
CheckInput.i_MM1KK <- function(x, ...)
{
MM1KK_class <- "The class of the object x has to be M/M/1/K/K (i_MM1KK)"
MM1KK_anomalous <- "Some value of lambda, mu or k is anomalous. Check the values."
MM1KK_method <- "method variable has to be 0 to be exact calculus, 1 to be aproximate calculus, 2 to use Jain's Method or 3 to use Poisson truncated distribution"
if (!inherits(x, "i_MM1KK"))
stop(MM1KK_class)
if (is.anomalous(x$lambda) || is.anomalous(x$mu) || is.anomalous(x$k))
stop(MM1KK_anomalous)
if (x$lambda < 0)
stop(ALL_lambda_zpositive)
if (x$mu <= 0)
stop(ALL_mu_positive)
if (x$k < 1)
stop(ALL_k_warning)
if (!is.wholenumber(x$k))
stop(ALL_k_integer)
if (x$method != 0 && x$method != 1 && x$method != 2 && x$method != 3)
stop(MM1KK_method)
}
MM1KK_InitPn_Aprox_Aux <- function(n, lambda, mu, c, k, m)
{
(lfactorial(k) - lfactorial(k-n)) + (n * log(lambda/mu))
}
MM1KK_InitPn_Aprox <- function(x)
{
ProbFactCalculus(x$lambda, x$mu, 1, x$k, x$k, x$k,
MM1KK_InitPn_Aprox_Aux, MM1KK_InitPn_Aprox_Aux, MM1KK_InitPn_Aprox_Aux)
}
MM1KK_InitPn_Exact <- function(x)
{
pn <- c(0:x$k)
z <- x$mu / x$lambda
u <- x$lambda / x$mu
pn[1] <- B_erlang(x$k, z)
totu <- 1
totk <- 1
i <- 2
while (i <= (x$k + 1))
{
totu <- totu * u
totk <- totk * ((x$k + 1) - i + 1)
pn[i] <- pn[1] * totu * totk
i <- i + 1
}
pn
}
MM1KK_method2_Aux <- function(x, i)
{
r <- x$lambda/x$mu
if (i == 0)
{
(x$k - i) * r / (i+1)
}
else
{
(x$k - i) * r
}
}
MM1KK_method2_Prod <- function(x,n)
{
prod <- 1
for (i in 0:(n-1))
{
prod <- prod * MM1KK_method2_Aux(x, i)
}
prod
}
MM1KK_method2_Prob <- function(x)
{
pn <- c()
sumAux <- 1
for (i in (1:x$k))
{
sumAux <- sumAux + MM1KK_method2_Prod(x, i)
}
pn[1] <- 1/sumAux
for (i in 2:(x$k+1))
{
pn[i] <- MM1KK_method2_Aux(x, i-2) * pn[i-1]
}
pn
}
MM1KK_method3_Prob <- function(x)
{
z <- x$mu/x$lambda
funMethod3 <- function(n){ dpois(x$k-n, z)/ppois(x$k, z) }
pn <- sapply(0:x$k, funMethod3)
pn
}
MM1KK_InitPn <- function(x)
{
if (x$method == 0)
pn <- MM1KK_InitPn_Exact(x)
else if (x$method == 1)
pn <- MM1KK_InitPn_Aprox(x)
else if (x$method == 2)
pn <- MM1KK_method2_Prob(x)
else
pn <- MM1KK_method3_Prob(x)
pn
}
QueueingModel.i_MM1KK <- function(x, ...)
{
CheckInput.i_MM1KK(x, ...)
z <- x$mu / x$lambda
Pn <- MM1KK_InitPn(x)
RO <- 1 - Pn[1]
Throughput <- x$mu * RO
L <- x$k - (Throughput / x$lambda)
W <- (x$k / Throughput) - ( 1 / x$lambda)
Wq <- W - (1 / x$mu)
Lq <- Throughput * Wq
WWs <- (x$k / RO) - z
SP <- 1 + z
QnAux <- function(n){ Pn[n] * (x$k - (n-1)) / (x$k - L) }
Qn <- sapply(1:x$k, QnAux)
if (x$k == 1)
{
Wqq <- NA
Lqq <- NA
}
else
{
Wqq <- Wq / (1 - Qn[1])
Lqq <- Wqq * x$mu
}
FW <- function(t){
aux <- function(i, t) { Qn[i] * ppois(i-1, x$mu * t) }
1 - sum(sapply(seq(1, x$k, 1), aux, t))
}
if (x$k == 1)
FWq <- function(t){ 0 }
else
{
FWq <- function(t){
aux <- function(i, t) { Qn[i+1] * ppois(i-1, x$mu * t) }
1 - sum(sapply(seq(1, x$k-1, 1), aux, t))
}
}
VN <- sum( (0:x$k)^2 * Pn ) - (L^2)
xFWc <- Vectorize(function(t){t * (1 - FW(t))})
xFWqc <- Vectorize(function(t){t * (1 - FWq(t))})
FWInt <- integrate(xFWc, 0, Inf)
if (FWInt$message == "OK")
VT <- (2 * FWInt$value) - (W^2)
else
VT <- NA
if (x$k == 1)
{
VNq <- 0
VTq <- 0
}
else
{
VNq <- sum( c(0, 0, 1:(x$k-1))^2 * Pn ) - (Lq^2)
FWqInt <- integrate(xFWqc, 0, Inf)
if (FWqInt$message == "OK")
VTq <- (2 * FWqInt$value) - (Wq^2)
else
VTq <- NA
}
res <- list(
Inputs=x, RO = RO, Lq = Lq, VNq = VNq, Wq = Wq, VTq = VTq, Throughput = Throughput,
L = L, VN = VN, W = W, VT = VT, Lqq = Lqq, Wqq = Wqq, WWs = WWs, SP = SP, Pn = Pn, Qn = Qn, FW = FW, FWq = FWq
)
class(res) <- "o_MM1KK"
res
}
Inputs.o_MM1KK <- function(x, ...) { x$Inputs }
RO.o_MM1KK <- function(x, ...) { x$RO }
Lq.o_MM1KK <- function(x, ...) { x$Lq }
VNq.o_MM1KK <- function(x, ...) { x$VNq }
Wq.o_MM1KK <- function(x, ...) { x$Wq }
VTq.o_MM1KK <- function(x, ...) { x$VTq }
L.o_MM1KK <- function(x, ...) { x$L }
VN.o_MM1KK <- function(x, ...) { x$VN }
W.o_MM1KK <- function(x, ...) { x$W }
VT.o_MM1KK <- function(x, ...) { x$VT }
Lqq.o_MM1KK <- function(x, ...) { x$Lqq }
Wqq.o_MM1KK <- function(x, ...) { x$Wqq }
WWs.o_MM1KK <- function(x, ...) { x$WWs }
SP.o_MM1KK <- function(x, ...) { x$SP }
Pn.o_MM1KK <- function(x, ...) { x$Pn }
Qn.o_MM1KK <- function(x, ...) { x$Qn }
Throughput.o_MM1KK <- function(x, ...) { x$Throughput }
Report.o_MM1KK <- function(x, ...)
{
reportAux(x)
}
summary.o_MM1KK <- function(object, ...)
{
aux <- list(el=CompareQueueingModels(object))
class(aux) <- "summary.o_MM1"
aux
}
print.summary.o_MM1KK <- function(x, ...)
{
print_summary(x, ...)
} |
test_that("use_addin() creates the first addins.dcf as promised", {
create_local_package()
use_addin("addin.test")
addin_dcf <- read_utf8(proj_path("inst", "rstudio", "addins.dcf"))
expected_file <- path_package("usethis", "templates", "addins.dcf")
addin_dcf_expected <- read_utf8(expected_file)
addin_dcf_expected[3] <- "Binding: addin.test"
addin_dcf_expected[5] <- ""
expect_equal(addin_dcf, addin_dcf_expected)
}) |
AnovaTest <-
function(ResMMEst , TestedCombination=NULL , Type = "TypeIII" , Cofactor = NULL , X = NULL , formula = NULL , VarList = NULL , NbCores=1){
if (length(ResMMEst[[1]]) != 8) stop("ResMMEst should be the output of the function MMEst")
if (Type == "KR"){
return(.AnovaTest_KR(ResMMEst , TestedCombination , Cofactor , X , formula , VarList , NbCores))
}else{
if (!is.null(TestedCombination)){
if (is.matrix(TestedCombination)) TestedCombination <- list(TestedCombination)
if (!is.list(TestedCombination)) stop("TestedCombination should be either a list of matrices or a matrix")
TestedCombination <- lapply(1:length(TestedCombination) , function(ind) {
c <- TestedCombination[[ind]]
QR <- qr(c)
if (QR$rank != nrow(c)){
message(paste0("Contrast matrix number " ,ind," was not full rank and has been reduced."))
return(matrix(c[QR$pivot[1:QR$rank],],ncol=ncol(c)))
}else{
return(c)
}
})
Res <- mclapply(ResMMEst , function(x) {
Beta <- x$Beta
VarBeta <- x$VarBeta
Test <- t(sapply(TestedCombination , function(C) {
if (ncol(C)!=length(Beta)){
Stat <- NA
Pval <- NA
df <- NA
}else{
rgC <- qr(C)$rank
CBeta <- tcrossprod(C,t(Beta))
Stat <- crossprod(CBeta, solve(tcrossprod(C,tcrossprod(C,VarBeta)), CBeta))
Pval <- pchisq(Stat , df = rgC , lower.tail=FALSE)
df <- rgC
}
return(c(Stat,Pval,df))
}))
colnames(Test) <- c("Wald","pval","df")
rownames(Test) <- names(TestedCombination)
return(Test)
},mc.cores=NbCores)
names(Res) <- names(ResMMEst)
}else{
Factors <- ResMMEst[[1]]$Factors
if (Type=="TypeI"){
Res <- mclapply(ResMMEst , function(x) {
Beta <- x$Beta
Attr <- x$attr
CommonAttr <- lapply(unique(Attr) , function(y) which(Attr==y))
names(CommonAttr) <- c("(Intercept)",Factors[unique(Attr)[-1]])
MatTI <- lapply(names(CommonAttr) , function(y){
mat <- as.numeric(1:length(Beta) %in% CommonAttr[[y]])
return(mat)
})
VarBeta <- x$VarBeta
Chol <- chol(solve(VarBeta))
TypeIcomp <- tcrossprod(Chol,t(Beta))^2
Test <- t(sapply(MatTI , function(y) {
if (length(y)!=length(Beta)){
Stat <- NA
Pval <- NA
df <- NA
}else{
Stat <- sum(y*TypeIcomp)
Pval <- pchisq(Stat , df=sum(y) , lower.tail=FALSE)
df = sum(y)
}
return(c(Stat,Pval,df))
}))
colnames(Test) <- c("Wald (Type I)","pval","df")
rownames(Test) <- names(CommonAttr)
return(Test)
},mc.cores=NbCores)
names(Res) <- names(ResMMEst)
}
if (Type=="TypeIII"){
Res <- mclapply(ResMMEst , function(x) {
Beta <- x$Beta
Attr <- x$attr
CommonAttr <- lapply(unique(Attr) , function(y) which(Attr==y))
names(CommonAttr) <- c("(Intercept)",Factors[unique(Attr)[-1]])
MatTIII <- lapply(names(CommonAttr) , function(y){
EffectSelected <- CommonAttr[[y]]
mat <- t(sapply(EffectSelected , function(z) as.numeric(1:length(Beta)==z)))
return(mat)
})
VarBeta <- x$VarBeta
Test <- t(sapply(MatTIII , function(C) {
if (ncol(C)!=length(Beta)){
Stat <- NA
Pval <- NA
df <- NA
}else{
rgC <- qr(C)$rank
CBeta <- tcrossprod(C,t(Beta))
Stat <- crossprod(CBeta, solve(tcrossprod(C,tcrossprod(C,VarBeta)), CBeta))
Pval <- pchisq(Stat , df = rgC , lower.tail=FALSE)
df = rgC
}
return(c(Stat,Pval,df))
}))
colnames(Test) <- c("Wald (Type III)","pval","df")
rownames(Test) <- names(CommonAttr)
return(Test)
},mc.cores=NbCores)
names(Res) <- names(ResMMEst)
}
if ((Type!="TypeI")&&(Type!="TypeIII")) warning("AnovaTest computes TypeI or TypeIII test when TestedCombination is NULL")
}
CompNA <- sum(unlist(mclapply(Res,function(x) sum(is.na(x[,2])) , mc.cores=NbCores)))
if (CompNA > 0) message(paste0(CompNA," tests were not performed because of incompatible dimension"))
return(Res)
}
} |
Rho.p<-function(xin, p.param, dist, p1=0, p2=1)
{
xi.p <- q.sample(p.param, dist, p1,p2)
lowerlim <- -Inf
upperlim <- xi.p
sampleuse<-xin[which(xin<=upperlim )]
xpoints<-seq(min(sampleuse), max(sampleuse), length=50)
pdfest<- d.sample(xpoints, dist, p1,p2)
cdfest<-p.sample(xpoints, dist, p1,p2)
n<-length(xpoints)
psi1<- sum(pdfest * cdfest)/n
psi2<- sum(pdfest )/n
psi3<- sum(pdfest^2 )/n
denom<- p.param * psi3 - psi2^2
rhop<- ifelse(denom<0, 0, 2*sqrt(3)/p.param * ( psi1 - p.param/2 * psi2 )/sqrt(p.param * psi3 - psi2^2))
rhop
} |
VI.aov <- function(x, Describe=FALSE, ...)
{
GroupL <- interaction(x$model[, -1], sep = ":")
FNames = attr(x$terms, 'term.labels')
for (Factor in FNames) {
cat("\nThe p value for", Factor, "is",
round(anova(x)[which(FNames == Factor), 5], 4))
}
cat("\n\nThe ratios of the group standard deviations to the overall standard deviation \n",
"(groups ordered by increasing mean) are:\n",
round(tapply(x$residuals, GroupL, sd) /
sqrt(sum(x$residuals ^ 2) / x$df.residual), 2))
cat("\n \n")
return(invisible(NULL))
}
VI.summary.lm <- function(x, Describe=FALSE, ...) {
CoeTable <- x$coe
if (row.names(CoeTable)[1] == "(Intercept)") {
IsInter = 1
} else {
IsInter = 0
}
SigPValues <- numeric(nrow(CoeTable) - IsInter)
for (Term in 1:length(SigPValues)) {
if (CoeTable[Term + IsInter, 4] <= 0.01) {
SigPValues[Term] = 0.01
} else if (CoeTable[Term + IsInter, 4] <= 0.05) {
SigPValues[Term] = 0.05
} else if (CoeTable[Term + IsInter, 4] <= 0.1) {
SigPValues[Term] = 0.1
}
}
for (SigLevel in c(0.01, 0.05, 0.1)) {
SigTerms <- which(SigPValues == SigLevel)
if (length(SigTerms) != 0) {
cat('The', ifelse(length(SigTerms) == 1, " term which is ",
" terms which are;"), 'significant to ', SigLevel * 100,
ifelse(length(SigTerms) == 1, "% is", "% are"), '\n', sep = "")
for (Term in 1:length(SigTerms)) {
Index = SigTerms[Term] + IsInter
cat(row.names(CoeTable)[Index], 'with an estimate of',
CoeTable[Index, 1], 'and P-Value of', CoeTable[Index, 4], '\n')
}
cat('\n')
}
}
NonSigTerms <- which(SigPValues == 0)
if (length(NonSigTerms) != 0) {
if (length(NonSigTerms) == 1) {
cat('The term', row.names(CoeTable)[NonSigTerms + IsInter],
'is not significant to 10%.')
} else {
NoOfTerms <- length(NonSigTerms)
cat('The terms',
paste(row.names(CoeTable)[NonSigTerms[1:(NoOfTerms - 1)] + IsInter],
collapse = ", "), 'and',
row.names(CoeTable)[NonSigTerms[NoOfTerms] + IsInter],
'are not significant to 10%.')
}
}
}
VI.TukeyHSD <- function(x, Describe=FALSE, ...)
{
CI <- attr(x, 'conf.level')
for (Comparison in 1:length(x)) {
CTable = x[[names(x)[Comparison]]]
SignPValues = (CTable[, 4] <= (1 - CI))
if (any(SignPValues == TRUE)) {
cat("For term ", names(x)[Comparison],
" the comparisons which are significant at ", (1 - CI) * 100,
"% are:\n", sep = "")
for (DRow in 1:length(SignPValues)) {
if (SignPValues[DRow] == TRUE) {
SComp = strsplit(rownames(CTable)[DRow], "-")[[1]]
cat(SComp[1], "and", SComp[2], "with a difference of",
round(CTable[DRow, 1], 2), "and P-value of",
round(CTable[DRow, 4], 4), "\n")
}
}
} else {
cat("For term ", names(x)[Comparison],
" there are no comparisons significant at ", (1 - CI) * 100, "%\n",
sep = "")
}
cat("\n")
}
return(invisible(NULL))
} |
context("R Markdown")
test_that("The chunk header parser works as expected", {
cases <- list(
list(
input = "```{r}",
type = "md",
expected = list(engine = "r")
),
list(
input = "```{r a-b-c}",
type = "md",
expected = list(engine = "r", label = "a-b-c")
),
list(
input = "```{r, a-b-c}",
type = "md",
expected = list(engine = "r", label = "a-b-c")
),
list(
input = "```{r, a-b-c, a=1+1}",
type = "md",
expected = list(engine = "r", label = "a-b-c", a = quote(1 + 1))
),
list(
input = "```{python}",
type = "md",
expected = list(engine = "python")
),
list(
input = "```{r engine = 'Rcpp'}",
type = "md",
expected = list(engine = "Rcpp")
),
list(
input = "```{r, engine = 'Rcpp'}",
type = "md",
expected = list(engine = "Rcpp")
),
list(
input = "```{r a?weird?label}",
type = "md",
expected = list(engine = "r", label = "a?weird?label")
),
list(
input = "```{r a'weird'label, engine = 'bash'}",
type = "md",
expected = list(engine = "bash", label = "a'weird'label")
),
list(
input = "```{r, 'a=weird=label', engine = 'bash'}",
type = "md",
expected = list(engine = "bash", label = "a=weird=label")
),
list(
input = "<<a-b-c>>=",
type = "rnw",
expected = list(engine = "r", label = "a-b-c")
),
list(
input = "<<a-b-c, a=1, b=2>>=",
type = "rnw",
expected = list(engine = "r", label = "a-b-c", a = 1, b = 2)
)
)
for (case in cases) {
output <- renv_knitr_options_header(case$input, case$type)
expect_same_elements(output, case$expected)
}
})
test_that("we can parse chunk YAML options", {
cases <- list(
list(
input = "
expected = list(a = TRUE)
),
list(
input = "
expected = list(a = TRUE)
)
)
for (case in cases) {
output <- renv_knitr_options_chunk(case$input)
expect_same_elements(output, case$expected)
}
}) |
clique <- function (dist,alphac,minsize=1,mult=100)
{
if (class(dist) != 'dist')
stop("The first argument must be of class 'dist'")
if (alphac < 0 || alphac > 1)
stop("alphac must be [0,1]")
sim <- 1-as.matrix(dist)
rows <- mult * nrow(sim)
cols <- ncol(sim)
top <- 0
bottom <- 0
orig <-0
ds <- matrix(0,nrow=rows,ncol=cols)
left <- rep(0,rows)
tmp <- .Fortran('clique',
as.double(sim),
ds=as.integer(ds),
as.integer(left),
as.integer(rows),
as.integer(cols),
as.double(1-alphac),
top=as.integer(top),
bottom=as.integer(bottom),
orig=as.integer(orig),
PACKAGE='optpart')
if (tmp$orig < 0) {
print('Memory overflow. Increase parameter mult and try again')
out <- NULL
} else {
musubx <- 1 - matrix(tmp$ds,ncol=cols)[tmp$top:tmp$bottom,]
test <- apply(musubx,1,sum) >= minsize
musubx <- musubx[test,]
colnames(musubx) <- attr(dist,'Labels')
member <- list()
for (i in 1:nrow(musubx)) {
member[[i]] <- seq(1:ncol(musubx))[musubx[i,]==1]
}
out <- list(musubx=musubx,member=member,alphac=alphac,
names= attr(dist,'Labels'))
attr(out,'class') <- 'clique'
attr(out,'call') <- match.call()
attr(out,'timestamp') <- date()
}
out
}
clique.test <- function (cliq,env,minsize=2,plotit=FALSE)
{
size <- nrow(cliq$musubx)
probs <- rep(NA,size)
for (i in 1:size) {
if (sum(cliq$musubx[i,]) < minsize) probs[i] <- NA
else probs[i] <- envrtest(cliq$musubx[i,],env,plotit=plotit)$prob
if (plotit) readline('hit return to continue')
}
if (plotit) {
plot(sort(probs))
abline(h=0.05,col=2)
}
invisible(probs)
}
summary.clique <- function(object,...)
{
num <- nrow(object$musubx)
minsize <- min(apply(object$musubx>0,1,sum))
maxsize <- max(apply(object$musubx>0,1,sum))
cat(paste(num,'maximal cliques at alphac = ',object$alphac),"\n")
cat(paste('minimum size = ',minsize,"\n"))
cat(paste('maximum size = ',maxsize,"\n"))
}
plot.clique <- function(x, panel='all', ...)
{
if (panel == 'all' || panel == 1) {
plot(sort(apply(x$musubx>0,1,sum)),xlab='clique',ylab='size')
if (panel == 'all')
readline('hit return to continue : ')
}
if (panel == 'all' || panel == 2) {
plot(sort(apply(x$musubx>0,2,sum)),xlab='plot',ylab='number of cliques')
}
}
clique.size <- function (cli)
{
if (!inherits(cli,'clique'))
stop("You must pass an argument of class 'clique' from clique()")
out <- apply(cli$musubx,1,sum)
out
}
clique.occ <- function (cli)
{
if (!inherits(cli,'clique'))
stop("You must pass an argument of class 'clique' from clique()")
out <- apply(cli$musubx,2,sum)
out
}
clique.members <- function (cli,which='ALL')
{
if (!inherits(cli,'clique'))
stop("The first argument must be of class 'clique' from clique()")
names <- cli$names
for (i in 1:length(cli$member)) {
x <- names[cli$member[[i]]]
if (which=='ALL' | which %in% x) {
cat("\n")
cat(x)
}
}
cat ("\n")
}
clique.venn <- function (cli,a,b)
{
if (!inherits(cli,'clique'))
stop("The first argument must be of class 'clique' from clique()")
numcli <- nrow(cli$musubx)
if (a > numcli | b > numcli)
stop(paste("Clique numbers must be less than",numcli+1))
inter <- intersect(cli$member[[a]],cli$member[[b]])
cat("\n")
cat(setdiff(cli$member[[a]],cli$member[[b]]))
cat("\n")
cat(inter)
cat("\n")
cat(setdiff(cli$member[[b]],cli$member[[a]]))
cat("\n")
} |
print.summpopiita<-function(x, ...){
cat("\n \t Inductive Item Tree Analysis in population values\n")
cat("\nAlgorithm:")
if(x$v == 1){cat(" minimized corrected IITA\n")}
if(x$v == 2){cat(" corrected IITA\n")}
if(x$v == 3){cat(" original IITA\n")}
cat("\npopulation diff values:\n")
print(round(x$pop.diff, digits = 3))
cat("\npopulation error rates:\n")
print(round(x$error.pop, digits = 3))
cat("\npopulation matrix:\n")
print(round(x$pop.matrix, digits =3))
cat("\nobtained selection set:\n")
print(x$selection.set)
} |
ggplot.train <- function(data = NULL, mapping = NULL, metric = data$metric[1], plotType = "scatter", output = "layered",
nameInStrip = FALSE, highlight = FALSE, ..., environment = NULL) {
if(!(output %in% c("data", "layered", "ggplot"))) stop("'outout' should be either 'data', 'ggplot' or 'layered'")
params <- data$modelInfo$parameters$parameter
paramData <- data$modelInfo$parameters
if(grepl("adapt", data$control$method))
warning("When using adaptive resampling, this plot may not accurately capture the relationship between the tuning parameters and model performance.")
plotIt <- "yes"
if(all(params == "parameter"))
{
plotIt <- "There are no tuning parameters for this model."
} else {
dat <- data$results
if(data$method == "nb") dat$usekernel <- factor(ifelse(dat$usekernel, "Nonparametric", "Gaussian"))
if(data$method == "gam") dat$select <- factor(ifelse(dat$select, "Feature Selection", "No Feature Selection"))
if(data$method == "qrnn") dat$bag <- factor(ifelse(dat$bag, "Bagging", "No Bagging"))
if(data$method == "C5.0") dat$winnow <- factor(ifelse(dat$winnow, "Winnowing", "No Winnowing"))
if(data$method == "M5") dat$rules <- factor(ifelse(dat$rules == "Yes", "Rules", "Trees"))
paramValues <- apply(dat[,as.character(params),drop = FALSE],
2,
function(x) length(unique(x)))
if(any(paramValues > 1))
{
params <- names(paramValues)[paramValues > 1]
paramData <- subset(paramData, parameter %in% params)
} else plotIt <- "There are no tuning parameters with more than 1 value."
}
if(plotIt == "yes")
{
p <- length(params)
dat <- dat[, c(metric, params)]
resampText <- resampName(data, FALSE)
resampText <- paste(metric, resampText)
} else stop(plotIt)
p <- ncol(dat) - 1
if(p > 1) {
numUnique <- unlist(lapply(dat[, -1], function(x) length(unique(x))))
numUnique <- sort(numUnique, decreasing = TRUE)
dat <- dat[, c(metric, names(numUnique))]
}
if(output == "data") return(dat)
if(data$control$search == "random") return(random_search_plot(data, metric = metric))
if(plotType == "scatter") {
if (highlight) {
bstRes <- data$results
for (par in as.character(params))
bstRes <- bstRes[which(bstRes[, par] == data$bestTune[, par]), ]
if (nrow(bstRes) > 1)
stop("problem in extracting model$bestTune row from model$results")
}
dnm <- names(dat)
if(p > 1 && is.numeric(dat[, 3])) dat[, 3] <- factor(format(dat[, 3]))
if(p > 2 & nameInStrip) {
strip_vars <- names(dat)[-(1:3)]
strip_lab <- as.character(subset(data$modelInfo$parameters, parameter %in% strip_vars)$label)
for(i in seq_along(strip_vars))
dat[, strip_vars[i]] <- factor(paste(strip_lab[i], dat[, strip_vars[i]], sep = ": "))
}
if (p >= 3)
for (col in 1:(p-2)) {
lvls <- as.character(unique(dat[, dnm[col+3]]))
dat[, dnm[col+3]] <- factor(dat[, dnm[col+3]], levels = lvls)
if (highlight)
bstRes[, dnm[col+3]] <- factor(bstRes[, dnm[col+3]], levels = lvls)
}
out <- ggplot(dat, aes_string(x = dnm[2], y = dnm[1]))
out <- out + ylab(resampText)
out <- out + xlab(paramData$label[paramData$parameter == dnm[2]])
if (highlight)
out <- out + geom_point(data = bstRes,
aes_string(x = dnm[2], y = dnm[1]),
size = 4, shape = 5)
if(output == "layered") {
if(p >= 2) {
leg_name <- paramData$label[paramData$parameter == dnm[3]]
out <- out + geom_point(aes_string(color = dnm[3], shape = dnm[3]))
out <- out + geom_line(aes_string(color = dnm[3]))
out <- out + scale_colour_discrete(name = leg_name) +
scale_shape_discrete(name = leg_name)
} else out <- out + geom_point() + geom_line()
if(p == 3)
out <- out + facet_wrap(as.formula(paste("~", dnm[4])))
if(p == 4)
out <- out + facet_grid(as.formula(paste(names(dat)[4], "~", names(dat)[5])))
if(p > 4) stop("The function can only handle <= 4 tuning parameters for scatter plots. Use output = 'ggplot' to create your own")
}
}
if(plotType == "level") {
if(p == 1) stop("Two tuning parameters are required for a level plot")
dnm <- names(dat)
if(is.numeric(dat[,2])) dat[,2] <- factor(format(dat[,2]), levels = format(sort(unique(dat[,2]))))
if(is.numeric(dat[,3])) dat[,3] <- factor(format(dat[,3]), levels = format(sort(unique(dat[,3]))))
if(p > 2 & nameInStrip) {
strip_vars <- names(dat)[-(1:3)]
strip_lab <- as.character(subset(data$modelInfo$parameters, parameter %in% strip_vars)$label)
for(i in seq_along(strip_vars))
dat[, strip_vars[i]] <- factor(
paste(strip_lab[i], format(dat[, strip_vars[i]]), sep = ": "),
levels = paste(strip_lab[i], format(sort(unique(dat[, strip_vars[i]]))), sep = ": ")
)
}
out <- ggplot(dat, aes_string(x = dnm[2], y = dnm[3], fill = metric))
out <- out + ylab(paramData$label[paramData$parameter == dnm[3]])
out <- out + xlab(paramData$label[paramData$parameter == dnm[2]])
if(output == "layered") {
out <- out + geom_tile()
if(p == 3)
out <- out + facet_wrap(as.formula(paste("~", dnm[4])))
if(p == 4)
out <- out + facet_grid(as.formula(paste(dnm[4], "~", dnm[5])))
if(p > 4) stop("The function can only handle <= 4 tuning parameters for level plots. Use output = 'ggplot' to create your own")
}
}
out
}
ggplot.rfe <- function(data = NULL, mapping = NULL, metric = data$metric[1],
output = "layered", ..., environment = NULL) {
if(!(output %in% c("data", "layered", "ggplot")))
stop("'outout' should be either 'data', 'ggplot' or 'layered'")
resampText <- resampName(data, FALSE)
resampText <- paste(metric, resampText)
if(output == "data") return(data$results)
if(any(names(data$results) == "Num_Resamples")) {
data$results <-
subset(data$results, Num_Resamples >= floor(.5 * length(data$control$index)))
}
notBest <- subset(data$results, Variables != data$bestSubset)
best <- subset(data$results, Variables == data$bestSubset)
out <- ggplot(data$results, aes_string(x = "Variables", y = metric))
if(output == "ggplot") return(out)
out <- out + geom_line()
out <- out + ylab(resampText)
out <- out + geom_point(data = notBest, aes_string(x = "Variables", y = metric))
out <- out + geom_point(data=best, aes_string(x = "Variables", y = metric),
size = 3, colour="blue")
out
}
random_search_plot <- function(x, metric = x$metric[1]) {
params <- x$modelInfo$parameters
p_names <- as.character(params$parameter)
exclude <- NULL
for(i in seq(along = p_names)) {
if(all(is.na(x$results[, p_names[i]])))
exclude <- c(exclude, i)
}
if(length(exclude) > 0) p_names <- p_names[-exclude]
x$results <- x$results[, c(metric, p_names)]
res <- x$results[complete.cases(x$results),]
combos <- res[, p_names, drop = FALSE]
nvals <- unlist(lapply(combos, function(x) length(unique(x))))
p_names <- p_names[which(nvals > 1)]
if(nrow(combos) == 1 | length(p_names) == 0)
stop("Can't plot results with a single tuning parameter combination")
combos <- combos[, p_names, drop = FALSE]
nvals <- sort(nvals[p_names], decreasing = TRUE)
is_num <- unlist(lapply(combos, function(x) is.numeric(x) | is.integer(x)))
num_cols <- names(is_num)[is_num]
other_cols <- names(is_num)[!is_num]
num_num <- sum(is_num)
num_other <- length(p_names) - num_num
if(num_other == 0) {
if(num_num == 1) {
out <- ggplot(res, aes_string(x = num_cols[1], y = metric)) +
geom_point() + xlab(as.character(params$label[params$parameter == num_cols[1]]))
} else {
if(num_num == 2) {
out <- ggplot(res, aes_string(x = num_cols[1], y = num_cols[2], size = metric)) +
geom_point() +
xlab(as.character(params$label[params$parameter == num_cols[1]])) +
ylab(as.character(params$label[params$parameter == num_cols[2]]))
} else {
vert <- melt(res[, c(metric, num_cols)], id.vars = metric, variable.name = "parameter")
vert <- merge(vert, params)
names(vert)[names(vert) == "label"] <- "Parameter"
out <- ggplot(vert, aes_string(x = "value", y = metric)) +
geom_point() + facet_wrap(~Parameter, scales = "free_x") + xlab("")
}
}
} else {
if(num_other == length(p_names)) {
if(num_other == 1) {
out <- ggplot(res, aes_string(x = other_cols[1], y = metric)) +
geom_point() +
xlab(as.character(params$label[params$parameter == other_cols[1]]))
} else {
if(num_other == 2) {
out <- ggplot(res, aes_string(x = other_cols[1], shape = other_cols[2], y = metric)) +
geom_point() + geom_line(aes_string(group = other_cols[2])) +
xlab(as.character(params$label[params$parameter == other_cols[1]]))
} else {
if(num_other == 3) {
pname <- as.character(params$label[params$parameter == other_cols[3]])
res[,other_cols[3]] <- paste0(pname, ": ", res[,other_cols[3]])
out <- ggplot(res, aes_string(x = other_cols[1], shape = other_cols[2], y = metric)) +
geom_point() + geom_line(aes_string(group = other_cols[2])) +
facet_grid(paste0(".~", other_cols[3])) +
xlab(as.character(params$label[params$parameter == other_cols[1]]))
} else {
stop(paste("There are",
num_other, "non-numeric variables; I don't have code for",
"that Dave"))
}
}
}
} else {
vert <- melt(res[, c(metric, num_cols, other_cols)],
id.vars = c(metric, other_cols),
variable.name = "parameter")
vert <- merge(vert, params)
names(vert)[names(vert) == "label"] <- "Parameter"
if(num_other == 1) {
out <- ggplot(vert, aes_string(x = "value", y = metric, color = other_cols)) +
geom_point() + facet_wrap(~Parameter, scales = "free_x") + xlab("")
} else {
stop(paste("There are", num_num, "numeric tuning variables and",
num_other, "non-numeric variables; I don't have code for",
"that Dave"))
}
}
}
out
} |
expected <- eval(parse(text="\"unknown\""));
test(id=0, code={
argv <- eval(parse(text="list(\"Byte Code Compiler\")"));
.Internal(Encoding(argv[[1]]));
}, o=expected); |
create_predict_fun <- function(model, task, predict.fun = NULL, type = NULL) {
UseMethod("create_predict_fun")
}
create_predict_fun.WrappedModel <- function(model, task, predict.fun = NULL, type = NULL) {
if (!requireNamespace("mlr")) {
"Please install the mlr package."
}
if (task == "classification") {
function(newdata) {
pred <- predict(model, newdata = newdata)
if (model$learner$predict.type == "response") {
pred <- mlr::getPredictionResponse(pred)
factor_to_dataframe(pred)
} else {
mlr::getPredictionProbabilities(pred, cl = model$task.desc$class.levels)
}
}
} else if (task == "regression") {
function(newdata) {
pred <- predict(model, newdata = newdata)
data.frame(.prediction = mlr::getPredictionResponse(pred))
}
} else {
stop(sprintf("Task type '%s' not supported", task))
}
}
create_predict_fun.Learner <- function(model, task, predict.fun = NULL, type = NULL) {
if (!requireNamespace("mlr3")) {
"Please install the mlr3 package."
}
if (task == "classification") {
function(newdata) {
if (model$predict_type == "response") {
pred <- predict(model, newdata = newdata)
factor_to_dataframe(pred)
} else {
data.frame(predict(model, newdata = newdata, predict_type = "prob"), check.names = FALSE)
}
}
} else if (task == "regression") {
function(newdata) {
data.frame(predict(model, newdata = newdata))
}
} else {
stop(sprintf("Task type '%s' not supported", task))
}
}
create_predict_fun.train <- function(model, task, predict.fun = NULL, type = NULL) {
if (task == "classification") {
function(newdata) {
if (is.null(type)) {
pred <- predict(model, newdata = newdata)
} else {
pred <- predict(model, newdata = newdata, type = type)
}
if (is_label(pred)) {
pred <- factor_to_dataframe(pred)
}
pred
}
} else if (task == "regression") {
function(newdata) {
if (is.null(type)) {
prediction <- predict(model, newdata = newdata)
} else {
prediction <- predict(model, newdata = newdata, type = type)
}
data.frame(.prediction = prediction, check.names = FALSE)
}
} else {
stop(sprintf("task of type %s not allowed.", task))
}
}
create_predict_fun.NULL <- function(model, task, predict.fun = NULL, type = NULL) {
function(newdata) {
pred <- predict.fun(newdata = newdata)
if (is_label(pred)) {
factor_to_dataframe(pred)
}
data.frame(pred, check.names = FALSE)
}
}
create_predict_fun.default <- function(model, task, predict.fun = NULL, type = NULL) {
if (is.null(predict.fun)) {
if (is.null(type)) {
predict.fun <- function(object, newdata) predict(object, newdata)
} else {
predict.fun <- function(object, newdata) predict(object, newdata, type = type)
}
}
function(newdata) {
pred <- do.call(predict.fun, list(model, newdata = newdata))
if (is_label(pred)) {
pred <- factor_to_dataframe(pred)
}
data.frame(pred, check.names = FALSE)
}
}
create_predict_fun.keras.engine.training.Model <- function(model, task, predict.fun = NULL, type = NULL) {
if (is.null(predict.fun)) {
predict.fun <- function(object, newdata) predict(object, newdata)
}
function(newdata) {
pred <- do.call(predict.fun, list(model, newdata = as.matrix(newdata)))
data.frame(pred, check.names = FALSE)
}
}
create_predict_fun.H2ORegressionModel <- function(model, task, predict.fun = NULL, type = NULL) {
function(newdata) {
newdata2 <- h2o::as.h2o(newdata)
as.data.frame(h2o::h2o.predict(model, newdata = newdata2))
}
}
create_predict_fun.H2OBinomialModel <- function(model, task, predict.fun = NULL, type = NULL) {
function(newdata) {
newdata2 <- h2o::as.h2o(newdata)
as.data.frame(h2o::h2o.predict(model, newdata = newdata2))[, -1]
}
}
create_predict_fun.H2OMultinomialModel <- function(model, task, predict.fun = NULL, type = NULL) {
function(newdata) {
newdata2 <- h2o::as.h2o(newdata)
as.data.frame(h2o::h2o.predict(model, newdata = newdata2))[, -1]
}
}
factor_to_dataframe <- function(fac) {
check_vector(fac)
res <- data.frame(model.matrix(~ fac - 1, data.frame(fac = fac), sep = ":"))
colnames(res) <- substring(colnames(res), 4)
res
} |
getOptim <- function(object) {
if (!is.DstarM(object)) {
stop("Input must be of class DstarM.", call. = FALSE)
} else {
name <- names(object)[1]
if (name == "Bestvals") {
return(object$GlobalOptimizer$optim$bestval)
} else if (name == "r.hat") {
return(sapply(object$GlobalOptimizer, function(x) x$optim$bestval))
} else {
warning("No optimizer information available for this object.")
return(NULL)
}
}
} |
plot_cond <- function(obs,xmat,gxvalues,model,nc,breaks,finebr,showpoints,
showlines,maintitle,ylim,angle=-45,density=20,col="black",
jitter=NULL,xlab="Distance",ylab="Detection probability",
subtitle=TRUE,...){
selection <- xmat$detected[xmat$observer!=obs]==1
selmat <- (xmat[xmat$observer==obs,])[selection,]
shist <- hist(xmat$distance[xmat$observer!= obs & xmat$detected==1],
breaks=breaks, plot = FALSE)
mhist <- hist(xmat$distance[xmat$timesdetected== 2 & xmat$observer==obs],
breaks=breaks, plot = FALSE)
if(length(mhist$counts) < length(shist$counts)){
prop <- c(mhist$counts/shist$counts[1:length(mhist$counts)],
rep(0, (length(shist$counts) - length(mhist$counts))))
}else{
prop <- mhist$counts/shist$counts
}
mhist$density <- prop
mhist$equidist <- FALSE
mhist$intensities <- mhist$density
histline(mhist$density, breaks=breaks, lineonly=FALSE, xlab=xlab, ylab=ylab,
ylim=ylim, angle=angle, density=density, col=col,
det.plot=TRUE, ...)
if(showlines){
line <- average.line.cond(finebr,obs,model)
linevalues <- line$values
xgrid <- line$xgrid
lines(xgrid,linevalues,...)
}
if(showpoints){
ifelse(is.null(jitter),
jitter.p<-1,
jitter.p<-rnorm(length(gxvalues),1,jitter))
points(selmat$distance,gxvalues*jitter.p,...)
}
if(maintitle!=""){
if(subtitle){
title(paste(maintitle,
"\nConditional detection probability\nObserver=",
obs ," | Observer = ",3-obs),...)
}else{
title(maintitle)
}
}else{
if(subtitle){
title(paste("Conditional detection probability\nObserver=",
obs ," | Observer = ",3-obs),...)
}
}
} |
library(sgd)
library(ggplot2)
generate.data <- function(N, d) {
l2 <- function(x) sqrt(sum(x**2))
X <- matrix(rnorm(N*d, mean=0, sd=1/sqrt(N)), nrow=N, ncol=d)
theta <- runif(d)
theta <- theta * 6 *sqrt(d) / l2(theta)
ind <- rbinom(N, size=1, prob=.95)
epsilon <- ind * rnorm(N) + (1-ind) * rep(10 ,N)
Y <- X %*% theta + epsilon
return(list(y=Y, X=X, theta=theta))
}
N <- 1000
d <- 200
set.seed(42)
data <- generate.data(N, d)
dat <- data.frame(y=data$y, x=data$X)
sgd.theta <- sgd(y ~ .-1, data=dat, model="m", sgd.control=list(method="sgd",
lr.control=c(15, NA, NA, 1/2), npass=10, pass=T))
plot(sgd.theta, data$theta, label="sgd", type="mse-param") +
geom_hline(yintercept=1.5, color="green") |
lpc.fit.spline <- function(lpcsl, num.knots=100){
nbranch <- length(lpcsl)-1
knots.pi <- list()
knots.coords <- list()
for (r in 0:nbranch) {
knots.pi[[r+1]] <- round(lpcsl[[r+1]]$range[1] + 0:(num.knots-1)/(num.knots-1) * (lpcsl[[r+1]]$range[2]-lpcsl[[r+1]]$range[1]), digits=6)
coords <- matrix(ncol=num.knots,nrow=length(lpcsl[[r+1]]$splinefun))
for (j in 1:length(lpcsl[[r+1]]$splinefun))
coords[j,] <- lpcsl[[r+1]]$splinefun[[j]](knots.pi[[r+1]])
knots.coords[[r+1]] <- coords
}
list(knots.coords=knots.coords, knots.pi=knots.pi)
} |
TLMoments <- function(x, ...) {
args <- list(...)
if ("max.order" %in% names(args) && !are.integer.like(args$max.order))
stop("max.order must be integer-like. ")
if ("na.rm" %in% names(args) && !is.logical(args$na.rm))
stop("na.rm must be TRUE or FALSE. ")
UseMethod("TLMoments")
}
returnTLMoments <- function(out, leftrim, rightrim, order, ...) {
class <- class(out$lambdas)
args <- list(...)
if (!exists("func", args)) args$func <- "TLMoments"
if (sum(names(args) == "func") >= 2) {
newfunc <- as.vector(unlist(args[names(args) == "func"]))
args$func <- NULL
args$func <- newfunc
}
if (!exists("n", args) && exists("data", args)) {
if (inherits(out$lambdas, "numeric")) {
args$n <- sum(!is.na(args$data))
} else if (inherits(out$lambdas, "matrix")) {
args$n <- apply(args$data, 2, function(y) sum(!is.na(y)))
} else if (inherits(out$lambdas, "list")) {
args$n <- vapply(args$data, length, numeric(1))
} else if (inherits(out$lambdas, "data.frame")) {
args$n <- aggregate(args$formula, args$data, length)[[getFormulaSides(args$formula)$lhs]]
}
}
attr(out, "leftrim") <- leftrim
attr(out, "rightrim") <- rightrim
attr(out, "order") <- order
attr(out, "source") <- args
class(out) <- c("TLMoments", "list")
out
}
TLMoments.numeric <- function(x, leftrim = 0L, rightrim = 0L, max.order = 4L,
na.rm = FALSE, computation.method = "auto",
...) {
if (computation.method == "auto")
computation.method <- select_computation(leftrim, rightrim)
ls <- TLMoment(x, order = 1L:max.order, leftrim = leftrim, rightrim = rightrim, na.rm = na.rm, computation.method = computation.method)
out <- list(
lambdas = ls,
ratios = calcRatios(ls)
)
returnTLMoments(out, leftrim, rightrim, 1L:max.order,
tl.computation.method = computation.method, data = x)
}
TLMoments.matrix <- function(x, leftrim = 0L, rightrim = 0L, max.order = 4L,
na.rm = FALSE, computation.method = "auto",
...) {
if (computation.method == "auto")
computation.method <- select_computation(leftrim, rightrim)
ls <- apply(x, 2, TLMoment, order = 1L:max.order, leftrim = leftrim, rightrim = rightrim, na.rm = na.rm, computation.method = computation.method)
if (max.order == 1) {
dim(ls) <- c(1, ncol(x))
}
out <- list(
lambdas = ls,
ratios = apply(ls, 2, calcRatios)
)
returnTLMoments(out, leftrim, rightrim, 1L:max.order,
tl.computation.method = computation.method, data = x)
}
TLMoments.list <- function(x, leftrim = 0L, rightrim = 0L, max.order = 4L, na.rm = FALSE,
computation.method = "auto",
...) {
if (computation.method == "auto")
computation.method <- select_computation(leftrim, rightrim)
ls <- lapply(x, TLMoment, order = 1L:max.order, leftrim = leftrim, rightrim = rightrim, na.rm = na.rm, computation.method = computation.method)
out <- list(
lambdas = ls,
ratios = lapply(ls, calcRatios)
)
returnTLMoments(out, leftrim, rightrim, 1L:max.order,
tl.computation.method = computation.method, data = x)
}
TLMoments.data.frame <- function(x, formula, leftrim = 0L, rightrim = 0L, max.order = 4L,
na.rm = FALSE, computation.method = "auto",
...) {
if (computation.method == "auto")
computation.method <- select_computation(leftrim, rightrim)
x <- correctNames(x, "[L|T][0-9]*", ".")
formula <- correctNames(formula, "[L|T][0-9]*", ".")
nam <- getFormulaSides(formula, names(x))
agg <- aggregate(nam$new.formula, data = x, FUN = TLMoment, order = 1L:max.order, leftrim = leftrim, rightrim = rightrim, na.rm = na.rm, computation.method = computation.method)
out <- list(
lambdas = cbind(agg[-length(agg)], as.data.frame(agg[[length(agg)]])),
ratios = cbind(agg[-length(agg)], as.data.frame(t(apply(agg[[length(agg)]], 1, calcRatios)[-1, ])))
)
returnTLMoments(out, leftrim, rightrim, 1L:max.order,
tl.computation.method = computation.method, data = x, formula = nam$new.formula)
}
TLMoments.PWMs <- function(x, leftrim = 0L, rightrim = 0L, ...) {
if (any(diff(attr(x, "order")) != 1))
stop("PWM order must not have gaps")
UseMethod("TLMoments.PWMs")
}
TLMoments.PWMs.numeric <- function(x, leftrim = 0L, rightrim = 0L, ...) {
ls <- PWM_to_TLMoments(x, leftrim, rightrim)
out <- list(
lambdas = setNames(ls, paste0("L", seq_along(ls))),
ratios = calcRatios(ls)
)
do.call(returnTLMoments, c(
list(out = out, leftrim = leftrim, rightrim = rightrim, order = seq_along(ls)),
func = "TLMoments.PWMs",
pwms = list(removeAttributes(x)),
attr(x, "source")
))
}
TLMoments.PWMs.matrix <- function(x, leftrim = 0L, rightrim = 0L, ...) {
ls <- apply(x, 2, function(xx) {
PWM_to_TLMoments(xx, leftrim, rightrim)
})
rownames(ls) <- paste0("L", seq_along(ls[, 1]))
out <- list(
lambdas = ls,
ratios = apply(ls, 2, calcRatios)
)
do.call(returnTLMoments, c(
list(out = out, leftrim = leftrim, rightrim = rightrim, order = seq_along(ls[, 1])),
func = "TLMoments.PWMs",
pwms = list(removeAttributes(x)),
attr(x, "source")
))
}
TLMoments.PWMs.list <- function(x, leftrim = 0L, rightrim = 0L, ...) {
ls <- lapply(x, function(xx) {
PWM_to_TLMoments(xx, leftrim, rightrim)
})
ls <- lapply(ls, function(l) setNames(l, paste0("L", seq_along(l))))
out <- list(
lambdas = ls,
ratios = lapply(ls, calcRatios)
)
do.call(returnTLMoments, c(
list(out = out, leftrim = leftrim, rightrim = rightrim, order = seq_along(ls[[1]])),
func = "TLMoments.PWMs",
pwms = list(removeAttributes(x)),
attr(x, "source")
))
}
TLMoments.PWMs.data.frame <- function(x, leftrim = 0L, rightrim = 0L, ...) {
pwms <- x[, grep("beta[0-9]*", names(x)), drop = FALSE]
fac <- x[, !grepl("beta[0-9]*", names(x)), drop = FALSE]
ls <- apply(pwms, 1, function(xx) {
PWM_to_TLMoments(xx, leftrim, rightrim)
})
ratios <- apply(ls, 2, calcRatios)
ratios <- as.data.frame(t(ratios))
lambdas <- as.data.frame(t(ls))
names(lambdas) <- paste0("L", 1L:ncol(lambdas))
out <- list(
lambdas = cbind(fac, lambdas),
ratios = cbind(fac, ratios)
)
do.call(returnTLMoments, c(
list(out = out, leftrim = leftrim, rightrim = rightrim, order = 1L:ncol(lambdas)),
func = "TLMoments.PWMs",
pwms = list(removeAttributes(x)),
attr(x, "source")
))
}
TLMoments.parameters <- function(x,
leftrim = attr(x, "source")$trimmings[1],
rightrim = attr(x, "source")$trimmings[2],
max.order = 4L,
...) {
if (!is.null(max.order) && !are.integer.like(max.order))
stop("max.order must be integer-like. ")
if (!is.null(max.order) && max.order <= 0)
stop("max.order must be positive. ")
if ((!is.null(leftrim) && !are.integer.like(leftrim)) || (!is.null(rightrim) && !are.integer.like(rightrim)))
stop("leftrim and rightrim must be integer-like. ")
if ((!is.null(leftrim) && leftrim < 0) || (!is.null(rightrim) && rightrim < 0))
stop("leftrim and rightrim must be non-negative. ")
UseMethod("TLMoments.parameters")
}
TLMoments.parameters.numeric <- function(x,
leftrim = attr(x, "source")$trimmings[1],
rightrim = attr(x, "source")$trimmings[2],
max.order = 4L,
...) {
if (is.null(leftrim)) leftrim <- 0L
if (is.null(rightrim)) rightrim <- 0L
if (is.null(attr(x, "source")$lambdas) ||
!identical(attr(x, "source")$trimmings, c(leftrim, rightrim)) ||
(!is.null(attr(x, "source")$tl.order) && max(attr(x, "source")$tl.order) != max.order)) {
ls <- calcTLMom(max.order, leftrim, rightrim, qfunc = getQ(x))
} else {
ls <- attr(x, "source")$lambdas
}
out <- list(
lambdas = setNames(ls, paste0("L", seq_along(ls))),
ratios = calcRatios(ls)
)
do.call(returnTLMoments,c(
list(out = out, leftrim = leftrim, rightrim = rightrim, order = 1L:max.order),
func = "TLMoments.parameters",
distr = attr(x, "distribution"),
parameters = list(removeAttributes(x)),
attr(x, "source")
))
}
TLMoments.parameters.matrix <- function(x,
leftrim = attr(x, "source")$trimmings[1],
rightrim = attr(x, "source")$trimmings[2],
max.order = 4L,
...) {
if (is.null(leftrim)) leftrim <- 0L
if (is.null(rightrim)) rightrim <- 0L
if (is.null(attr(x, "source")$lambdas) ||
!identical(attr(x, "source")$trimmings, c(leftrim, rightrim)) ||
(!is.null(attr(x, "source")$tl.order) && max(attr(x, "source")$tl.order) != max.order)) {
ls <- apply(x, 2, function(xx) {
calcTLMom(max.order, leftrim, rightrim,
qfunc = do.call(getQ, c(x = attr(x, "distribution"), as.list(xx))))
})
} else {
ls <- attr(x, "source")$lambdas
}
rownames(ls) <- paste0("L", seq_along(ls[, 1]))
out <- list(
lambdas = ls,
ratios = apply(ls, 2, calcRatios)
)
do.call(returnTLMoments,c(
list(out = out, leftrim = leftrim, rightrim = rightrim, order = 1L:max.order),
func = "TLMoments.parameters",
distr = attr(x, "distribution"),
parameters = list(removeAttributes(x)),
attr(x, "source")
))
}
TLMoments.parameters.list <- function(x,
leftrim = attr(x, "source")$trimmings[1],
rightrim = attr(x, "source")$trimmings[2],
max.order = 4L,
...) {
if (is.null(leftrim)) leftrim <- 0L
if (is.null(rightrim)) rightrim <- 0L
if (is.null(attr(x, "source")$lambdas) ||
!identical(attr(x, "source")$trimmings, c(leftrim, rightrim)) ||
(!is.null(attr(x, "source")$tl.order) && max(attr(x, "source")$tl.order) != max.order)) {
ls <- lapply(x, function(xx) {
calcTLMom(max.order, leftrim, rightrim,
qfunc = do.call(getQ, c(x = attr(x, "distribution"), as.list(xx))))
})
} else {
ls <- attr(x, "source")$lambdas
}
ls <- lapply(ls, function(l) setNames(l, paste0("L", seq_along(l))))
out <- list(
lambdas = ls,
ratios = lapply(ls, calcRatios)
)
do.call(returnTLMoments,c(
list(out = out, leftrim = leftrim, rightrim = rightrim, order = 1L:max.order),
func = "TLMoments.parameters",
distr = attr(x, "distribution"),
parameters = list(removeAttributes(x)),
attr(x, "source")
))
}
TLMoments.parameters.data.frame <- function(x,
leftrim = attr(x, "source")$trimmings[1],
rightrim = attr(x, "source")$trimmings[2],
max.order = 4L,
...) {
if (is.null(leftrim)) leftrim <- 0L
if (is.null(rightrim)) rightrim <- 0L
nam <- getFormulaSides(attr(x, "source")$formula)
if (is.null(attr(x, "source")$lambdas) ||
!identical(attr(x, "source")$trimmings, c(leftrim, rightrim)) ||
(!is.null(attr(x, "source")$tl.order) && max(attr(x, "source")$tl.order) != max.order)) {
ls <- apply(x[!(names(x) %in% nam$rhs)], 1, function(xx) {
calcTLMom(max.order, leftrim, rightrim,
qfunc = do.call(getQ, c(x = attr(x, "distribution"), as.list(xx))))
})
if (max.order == 1) {
ls <- rbind(ls, deparse.level = 0)
}
ls <- as.data.frame(t(ls))
names(ls) <- paste0("L", 1:max.order)
fac <- x[nam$rhs]
} else {
dat <- attr(x, "source")$lambdas
fac <- dat[nam$rhs]
ls <- dat[!(names(dat) %in% nam$rhs)]
}
if (max.order > 1) {
ratios <- t(apply(ls, 1, calcRatios))[, -1, drop = FALSE]
} else {
ratios <- matrix(NA, nrow = nrow(ls), ncol = 0)
}
out <- list(
lambdas = cbind(fac, as.data.frame(ls)),
ratios = cbind(fac, as.data.frame(ratios))
)
do.call(returnTLMoments,c(
list(out = out, leftrim = leftrim, rightrim = rightrim, order = 1L:max.order),
func = "TLMoments.parameters",
distr = attr(x, "distribution"),
parameters = list(removeAttributes(x)),
attr(x, "source")
))
}
print.TLMoments <- function(x, ...) {
tmp <- x
attributes(tmp) <- NULL
dim(tmp) <- dim(x)
names(tmp) <- names(x)
dimnames(tmp) <- dimnames(x)
print(tmp)
invisible(x)
} |
p2rho <-
function(Pz, TempK, RH){
if (nargs() < 3 ) {cat("USAGE: result = function(Pressure, TempK, RH) \n"); return()}
R_d = 287.04
e_v_star = 0
e_0 = 0
P_d = 0
rho_d = 0
rho_v = 0
e_v_star = wvapsat(TempK, 0)
e_0 = e_v_star*RH/100.0
P_d = Pz - e_0
rho_d = 100.*P_d /(R_d*TempK)
rho_v = 0.622*100.*e_0/(R_d*TempK)
p2rho = rho_d + rho_v
return(p2rho)
} |
residuals.fittedlooplist <- function(object,...){
g <- object
thenames <- g$Estimates[,1:(which(colnames(g$Estimates)=="n")-1)]
thelengths <- lapply(g$models, function(x) length(x$pred.x))
rowvec <- mapply(function(x,y) rep(x,each=y),1:length(thelengths),y=thelengths)
thenames <- thenames[rowvec,]
thefittedx<-lapply(g$models,function (x) residuals.fittedloop(x)[,"input"])
thefittedx <- unlist(thefittedx)
thefittedy<-lapply(g$models,function (x) residuals.fittedloop(x)[,"output"])
thefittedy <- unlist(thefittedy)
thegeom<-lapply(g$models,function (x) residuals.fittedloop(x)[,"geometric"])
thegeom <- unlist(thegeom)
data.frame(thenames,"input"=thefittedx,"output"=thefittedy,"geometric"=thegeom)
}
residuals.fittedlooplist2r <- function(object,...){
g <- object
thenames <- g$Estimates[,1:(which(colnames(g$Estimates)=="n")-1)]
thelengths <- lapply(g$models, function(x) length(x$pred.x))
rowvec <- mapply(function(x,y) rep(x,each=y),1:length(thelengths),y=thelengths)
thenames <- thenames[rowvec,]
thefittedx<-lapply(g$models,function (x) residuals.loop2r(x)[,"input"])
thefittedx <- unlist(thefittedx)
thefittedy<-lapply(g$models,function (x) residuals.loop2r(x)[,"output"])
thefittedy <- unlist(thefittedy)
thegeom<-lapply(g$models,function (x) residuals.loop2r(x)[,"geometric"])
thegeom <- unlist(thegeom)
data.frame(thenames,"input"=thefittedx,"output"=thefittedy,"geometric"=thegeom)
} |
context("ebirdnotable")
test_that("ebirdnotable works correctly", {
skip_on_cran()
out <- ebirdnotable(lat=42, lng=-70, max = 40)
expect_is(out, "data.frame")
expect_equal(dim(out), c(40,13))
expect_is(out$comName, "character")
expect_is(out$howMany, "integer")
expect_equal(NCOL(ebirdnotable(region='US-OH', regtype='subnational1')), 13)
simpler <- ebirdnotable(lat=42, lng=-70, max = 40, simple = TRUE)
expect_equal(dim(simpler), c(40,13))
expect_gt(
system.time(ebirdnotable(lat=42, lng=-70, max = 10, sleep = 1))[[3]]
, 1)
}) |
cvolumdya<-function(volofatom,component,AtomlistNext){
componum<-length(component)
volume<-matrix(0,componum,1)
for (i in 1:componum){
numofatoms<-0
pointer<-component[i]
while (pointer>0){
numofatoms<-numofatoms+1
pointer<-AtomlistNext[pointer]
}
volume[i]<-numofatoms*volofatom
}
return(volume)
} |
zelazo <- list(
active = c(9.00, 9.50, 9.75,10.00,13.00, 9.50),
passive = c(11.00,10.00,10.00,11.75,10.50,15.00),
none = c(11.50,12.00, 9.00,11.50,13.25,13.00),
ctr.8w = c(13.25,11.50,12.00,13.50,11.50)) |
separateAdditionalSyntax = function(line.simple){
temp = trimws(unlist(strsplit(x = line.simple, split = "<-")))
lhs = temp[1]
if (length(grep(pattern = "-", x = lhs)) > 0) {
lhs = getVariableList(variableText = temp[1])
} else {
lhs = trimws(unlist(strsplit(x = lhs, split = " ")))
}
rhs = temp[2]
tempRHS = trimws(unlist(strsplit(x = rhs, split = "\\(")))
latents = list()
distributions = list()
priors = list()
if (tempRHS[1] == "latent"){
latents = as.list(paste(lhs, "<-", rhs))
names(latents) = lhs
} else if (tempRHS[1] == "observed"){
distributions = as.list(paste(lhs, "<-", rhs))
names(distributions) = lhs
} else if (tempRHS[1] == "prior"){
priors = as.list(paste(lhs, "<-", rhs))
names(priors) = lhs
} else {
stop(paste0("Blatent syntax error: Unrecognized command ", tempRHS[1], "\n From Line: ", line.simple))
}
test = list(latents = latents, distributions = distributions, priors = priors)
return(test)
} |
"plot.fitEmax" <-
function(x,int=0,plotResid=FALSE,clev=0.9,
predict=TRUE,plotci=TRUE,plotDif=FALSE,
xlab='Dose',
ylab=ifelse(plotResid,'Residuals',ifelse(plotDif,
'Difference With Placebo','Response')),
symbol=NULL,symbolLabel='Group',symbolShape=8,symbolColor='red',symbolSize=4,
bwidth=NULL, xlim=NULL, xat=NULL, ylim=NULL, logScale=FALSE, ngrid=200,
plot=TRUE, ...){
outplot<-combplot(x=x,bayes=FALSE,int=int,plotResid=plotResid,
clev=clev, predict=predict,plotci=plotci,plotDif=plotDif,
xlab=xlab,ylab=ylab,
symbol=symbol,symbolLabel=symbolLabel,symbolShape=symbolShape,
symbolColor=symbolColor,symbolSize=symbolSize,
bwidth=bwidth, xlim=xlim, xat=xat, ylim=ylim, logScale=logScale, ngrid=ngrid,
plot=plot, ...)
return(invisible(outplot))
}
"plot.fitEmaxB" <-
function(x,int=0,plotResid=FALSE,clev=0.9,
predict=TRUE,plotci=TRUE,plotDif=FALSE,
xlab='Dose',
ylab=ifelse(plotResid,'Residuals',ifelse(plotDif,
'Difference With Placebo','Response')),
symbol=NULL,symbolLabel='Group',symbolShape=8,symbolColor='red',symbolSize=4,
bwidth=NULL, xlim=NULL, xat=NULL, ylim=NULL, logScale=FALSE, ngrid=200,
plot=TRUE, ...){
outplot<-combplot(x=x,bayes=TRUE,int=int,plotResid=plotResid,
clev=clev, predict=predict,plotci=plotci,plotDif=plotDif,
xlab=xlab,ylab=ylab,
symbol=symbol,symbolLabel=symbolLabel,symbolShape=symbolShape,
symbolColor=symbolColor,symbolSize=symbolSize,
bwidth=bwidth,
xlim=xlim,xat=xat,ylim=ylim,
logScale=logScale, ngrid=ngrid,
plot=plot, ...)
return(invisible(outplot))
}
combplot <-
function(x,bayes,int=0,plotResid=FALSE,clev=0.9,
predict=TRUE,plotci=TRUE,plotDif=FALSE,
xlab='Dose',
ylab=ifelse(plotResid,'Residuals',ifelse(plotDif,
'Difference With Placebo','Response')),
symbol=NULL,symbolLabel='Group',symbolShape=8,symbolColor='red',
symbolSize=4,
bwidth=NULL,
xlim=NULL, xat=NULL,
ylim=NULL,
logScale=FALSE,
ngrid=ngrid,
plot=TRUE, ...){
if(plotDif && is.null(ylab)){
ylab<-'Y Diff'
}else if(plotResid && is.null(ylab)){
ylab<-'Residuals'
}else if(is.null(ylab))ylab<-"Y"
clevup<- 0.5+clev/2
clevlow<-0.5-clev/2
cadj<- abs(qnorm((1-clev)/2))
nolegend<-is.null(symbol)
y<-x$y
dose<-x$dose
prot<-as.numeric(x$prot)
protlab<-levels(x$prot)
count<-x$count
binary<-x$binary
if(!bayes){
if(!binary){
residSD<-sigma(x)
}else residSD<-NA
}
if(isTRUE(plotDif & plotResid))warning('plotDif is ignored when plotResid is TRUE')
if(is.null(symbol)){symbol<-factor(rep(1,length(y)))
}else symbol<-factor(symbol)
if(length(symbol)!=length(y))stop('Symbol variable has invalid length')
if(length(symbol)!=length(y))stop('Symbol variable has invalid length')
if(int>0){
nprot<-int
nstart<-int
doselev<-sort(unique(dose[prot==int]))
}else{
nprot<-max(prot)
nstart<-1
doselev<-sort(unique(dose))
}
dmax<-max(doselev)*1.1
dmin<-min(c(0,doselev))-0.1*dmax
if(is.null(xlim))xlim<-c(dmin,dmax)
dgrid<-seq(0,xlim[2],length=ngrid)
dgrid <- c(dgrid, doselev)
dgrid <- sort(unique(dgrid))
ngridsup<-length(dgrid)
if(!is.null(xat)){
if(min(xat)<xlim[1] | max(xat)>xlim[2]) stop('Tickmark locations are outside X limit')
}
protD<-NULL
doseLevVec<-NULL
fitvec<-NULL
cilvec<-NULL
cihvec<-NULL
pilvec<-NULL
pihvec<-NULL
protG<-NULL
predvecG<-NULL
dgridvec<-NULL
protDS<-NULL
ymvecDS<-NULL
dosevecDS<-NULL
predvalDS<-NULL
symDS<-NULL
for(k in nstart:nprot){
yS<-y[prot==k]
doseS<-dose[prot==k]
countS<-count[prot==k]
protS<-prot[prot==k]
symS<-levels(symbol)[symbol[prot==k]]
doselev<-sort(unique(doseS))
ndose<-length(doselev)
symlev<-sort(unique(symS))
nsym<-length(symlev)
ym <- NULL
dvec <- NULL
symvec <- NULL
nds <- 0
for(i in 1:ndose){
for(j in 1:nsym){
ind<-((doseS==doselev[i]) & (symS==symlev[j]))
ng0<-sum(ind)
if(ng0>0){
ymhold<-weighted.mean(yS[ind],countS[ind])
if(isTRUE(plotDif & i==1))ym0<-ymhold
if(plotDif)ymhold<-ymhold-ym0
ym<-c(ym,ymhold)
dvec<-c(dvec,doselev[i])
symvec<-c(symvec,symlev[j])
nds<-nds+1
}
}
}
if(bayes){
seout<-predict(x,doselev,int=k,clev=clev)
if(!plotDif){
fitp<-seout$predMed
cil<-seout$lb
cih<-seout$ub
}else{
fitp<-seout$fitdifMed
cil<-seout$lbdif
cih<-seout$ubdif
}
nsub<-apply(tapply(countS,list(doseS,symS),sum),1,min,na.rm=TRUE)
pmean<-seout$simResp
sigsim<-seout$sigsim
nsim<-nrow(pmean)
pil<-numeric(ndose)
pih<-numeric(ndose)
for(i in 1:ndose){
if(!binary){ ppred<-rnorm(nsim,pmean[,i],sigsim/sqrt(nsub[i]))
}else ppred<-rbinom(nsim,nsub[i],pmean[,i])/nsub[i]
if(i==1)pp0<-ppred
if(plotDif)ppred<-ppred-pp0
pil[i]<-quantile(ppred,probs=clevlow)
pih[i]<-quantile(ppred,probs=clevup)
}
predvals<-predict(x,dgrid,int=k,clev=clev)$predMed
predvalSym<-predict(x,dvec,int=k,clev=clev)$predMed
if(plotDif){
predvals<-predvals-predvals[1]
predvalSym<-predvalSym-predvalSym[1]
}
}else{
seout<-predict(x,doselev,int=k,clev=clev)
if(!plotDif){
fitp<-seout$pred
se<-seout$se
cil<-seout$lb
cih<-seout$ub
}else{
ppred<-seout$pred
fitp<-seout$fitdif
se<-seout$sedif
cil<-seout$lbdif
cih<-seout$ubdif
}
nsub<-apply(tapply(countS,list(doseS,symS),sum),1,min,na.rm=TRUE)
if(!binary){
if(!plotDif){
sepred<-sqrt( se^2 + (residSD^2)/nsub )
pil<-fitp-cadj*sepred
pih<-fitp+cadj*sepred
}else{
sepred<-sqrt( se^2 + (residSD^2)/nsub + (residSD^2)/nsub[1] )
sepred[1]<-0
pil<-fitp-cadj*sepred
pih<-fitp+cadj*sepred
}
}else{
if(!plotDif){
sepred<-sqrt( (se/(fitp*(1-fitp)))^2 + 1/(nsub*fitp*(1-fitp)) )
pil<-plogis(qlogis(fitp)-cadj*sepred)
pih<-plogis(qlogis(fitp)+cadj*sepred)
}else{
sepred<-sqrt(se^2+ppred*(1-ppred)/nsub + ppred[1]*(1-ppred[1])/nsub[1])
sepred[1]<-0
pil<-fitp-cadj*sepred
pih<-fitp+cadj*sepred
}
}
predvals<-predict(x,dgrid,int=k,clev=clev)$pred
predvalSym<-predict(x,dvec,int=k,clev=clev)$pred
if(plotDif){
predvals<-predvals-predvals[1]
predvalSym<-predvalSym-predvalSym[1]
}
}
protD<-c(protD,rep(k,ndose))
doseLevVec<-c(doseLevVec,doselev)
fitvec<-c(fitvec,fitp)
cilvec<-c(cilvec,cil)
cihvec<-c(cihvec,cih)
pilvec<-c(pilvec,pil)
pihvec<-c(pihvec,pih)
protG<-c(protG,rep(k,ngridsup))
predvecG<-c(predvecG,predvals)
dgridvec<-c(dgridvec,dgrid)
protDS<-c(protDS,rep(k,nds))
ymvecDS<-c(ymvecDS,ym)
dosevecDS<-c(dosevecDS,dvec)
symDS<-c(symDS,symvec)
predvalDS<-c(predvalDS,predvalSym)
}
residuals<-ymvecDS-predvalDS
symDS<-factor(symDS)
nlevsym<-length(levels(symDS))
nshape<-length(symbolShape)
if(nshape!=nlevsym && nshape==1)symbolShape<-rep(symbolShape,nlevsym)
ncolor<-length(symbolColor)
if(ncolor!=nlevsym && ncolor==1)symbolColor<-rep(symbolColor,nlevsym)
if(int)protlab<-protlab[int]
if(plotResid & !logScale){
lplot<-ggplot(data.frame(dosevecDS,residuals,symDS,protDS=factor(protDS,labels=protlab)),
aes(x=dosevecDS,y=residuals))
lplot<-lplot+geom_point(aes(shape=symDS,color=symDS),size=symbolSize)
lplot<-lplot+scale_color_manual(name=symbolLabel,values=symbolColor)
lplot<-lplot+scale_shape_manual(name=symbolLabel,values=symbolShape)
lplot<-lplot + geom_hline(yintercept=0,linetype=2)
if(length(unique(prot))>1)lplot<-lplot+facet_wrap(~protDS,ncol=min(nprot,3))
lplot<-lplot+ylab(ylab) + xlab(xlab) + theme_bw()
if(!is.null(ylim)){lplot<-lplot+coord_cartesian(xlim=xlim,ylim=ylim)
}else lplot<-lplot+coord_cartesian(xlim=xlim)
}
else if(plotResid & logScale){
x0 <- dosevecDS
if(sum(x0==0)){
xtemp <- sort(unique(dosevecDS))[2]^2/sort(unique(dosevecDS))[3]
dosevecDSlog <- dosevecDS
dosevecDSlog[dosevecDS==0] <- xtemp
xlimlog <- c(log(xtemp)-(log(xlim[2])-log(xtemp))/10,
log(xlim[2])+(log(xlim[2])-log(xtemp))/10)
}else{
xtemp <- sort(unique(dosevecDS))[1]
dosevecDSlog <- dosevecDS
xlimlog <- c(log(xtemp)-(log(xlim[2])-log(xtemp))/10,
log(xlim[2])+(log(xlim[2])-log(xtemp))/10)
}
lplot<-ggplot(data.frame(dosevecDSlog,residuals,symDS,protDS=factor(protDS,labels=protlab)),
aes(x=log(dosevecDSlog),y=residuals))
lplot<-lplot+geom_point(aes(shape=symDS,color=symDS),size=symbolSize)
lplot<-lplot+scale_color_manual(name=symbolLabel,values=symbolColor)
lplot<-lplot+scale_shape_manual(name=symbolLabel,values=symbolShape)
lplot<-lplot + geom_hline(yintercept=0,linetype=2)
if(is.null(xat)) lplot <- lplot + scale_x_continuous(breaks=log(sort(unique(dosevecDSlog))),
labels=sort(unique(dosevecDS)))
if(length(unique(prot))>1)lplot<-lplot+facet_wrap(~protDS,ncol=min(nprot,3))
if(!is.null(ylim)){lplot<-lplot+coord_cartesian(xlim=xlimlog,ylim=ylim)
}else lplot<-lplot+coord_cartesian(xlim=xlimlog)
}
else if(!plotResid & !logScale){
if(is.null(bwidth)){werrbar<-min(diff(sort(unique(dosevecDS))))*(0.4)
}else werrbar<-bwidth
lplot<-ggplot(data.frame(cilvec,cihvec,pilvec,pihvec,
doseLevVec,protD=factor(protD,labels=protlab)))
lplot<-lplot+scale_color_manual(name=symbolLabel,values=symbolColor)
lplot<-lplot+scale_shape_manual(name=symbolLabel,values=symbolShape)
if(length(unique(prot))>1)lplot<-lplot+facet_wrap(~protD,ncol=min(nprot,5))
if(predict)lplot<-lplot+geom_errorbar(aes(x=doseLevVec,ymax=pihvec,ymin=pilvec),size=1.1,
color='grey',width=werrbar)
if(plotci)lplot<-lplot+geom_errorbar(aes(x=doseLevVec,ymax=cihvec,ymin=cilvec),width=0,size=1.1,color='black')
lplot<-lplot+geom_line(data=data.frame(dgridvec=dgridvec,predvecG=predvecG,
protD=factor(protG,labels=protlab)),
aes(x=dgridvec,y=predvecG),color='black',size=1.1, ...)
lplot<-lplot+geom_point(data=data.frame(ymvecDS,dosevecDS,symDS,protD=factor(protDS,labels=protlab)),
aes(x=dosevecDS,y=ymvecDS,shape=symDS,color=symDS),
size=symbolSize)
lplot<-lplot+ylab(ylab) + xlab(xlab) + theme_bw()
if(!is.null(ylim)){lplot<-lplot+coord_cartesian(xlim=xlim,ylim=ylim)
}else lplot<-lplot+coord_cartesian(xlim=xlim)
}
else if(!plotResid & logScale){
x0 <- doseLevVec
if(sum(x0==0)){
xtemp <- sort(unique(doseLevVec))[2]^2/sort(unique(doseLevVec))[3]
doseLevVeclog <- doseLevVec
dgridveclog <- dgridvec
dosevecDSlog <- dosevecDS
doseLevVeclog[doseLevVec==0] <- dgridveclog[dgridvec==0] <- dosevecDSlog[dosevecDS==0] <- xtemp
bench_doseLevVeclog <- sort(unique(doseLevVeclog))
xlimlog <- c(log(xtemp)-(log(xlim[2])-log(xtemp))/10,
log(xlim[2])+(log(xlim[2])-log(xtemp))/10)
werrbarlog <- min(diff(sort(unique(log(dosevecDSlog)))))*(0.4)
if(plotDif){
mindose <- min(dosevecDS[dosevecDS>0])
index <- which(doseLevVeclog>=mindose)
indexgrid <- which(dgridveclog>=mindose)
doseLevVec <- doseLevVec[index]
doseLevVeclog <- doseLevVeclog[index]
dgridveclog <-dgridveclog[indexgrid]
predvecG <- predvecG[indexgrid]
protG <- protG[indexgrid]
dosevecDSlog <- dosevecDSlog[index]
cilvec <- cilvec[index]
cihvec <- cihvec[index]
pilvec <- pilvec[index]
pihvec <- pihvec[index]
ymvecDS <- ymvecDS[index]
protD <- protD[index]
protDS <- protDS[index]
symDS <- symDS[index]
fitvec <- fitvec[index]
xlimlog <- c(log(mindose)-(log(xlim[2])-log(mindose))/10,
log(xlim[2])+(log(xlim[2])-log(mindose))/10)
}
lplot<-ggplot(data.frame(cilvec,cihvec,pilvec,pihvec,
doseLevVec, doseLevVeclog, protD=factor(protD,labels=protlab)))
lplot<-lplot+scale_color_manual(name=symbolLabel,values=symbolColor)
lplot<-lplot+scale_shape_manual(name=symbolLabel,values=symbolShape)
if(length(unique(prot))>1)lplot<-lplot+facet_wrap(~protD,ncol=min(nprot,5))
if(predict)lplot<-lplot+geom_errorbar(aes(x=log(doseLevVeclog),ymax=pihvec,ymin=pilvec),size=1.1,
color='grey',width=werrbarlog)
if(plotci)lplot<-lplot+geom_errorbar(aes(x=log(doseLevVeclog),ymax=cihvec,ymin=cilvec),width=0,size=1.1,
color='black')
data=data.frame(dgridveclog,predvecG=predvecG,protD=factor(protG,labels=protlab))
data1 <- subset(data, data$dgridveclog < bench_doseLevVeclog [2] & data$dgridveclog >= xtemp)
data2 <- subset(data, data$dgridveclog >= bench_doseLevVeclog [2])
lplot<-lplot+geom_line(data=data1, aes(x=log(dgridveclog),y=predvecG),color='black',size=1.1, linetype="dashed")
lplot<-lplot+geom_line(data=data2, aes(x=log(dgridveclog),y=predvecG),color='black',size=1.1, linetype="solid")
lplot<-lplot+geom_point(data=data.frame(ymvecDS,dosevecDSlog,symDS,protD=factor(protDS,labels=protlab)),
aes(x=log(dosevecDSlog),y=ymvecDS,shape=symDS,color=symDS),
size=symbolSize)
if(is.null(xat)) lplot <- lplot + scale_x_continuous(breaks=log(sort(unique(doseLevVeclog))),
labels=sort(unique(doseLevVec)))
if(!is.null(ylim)){lplot<-lplot+coord_cartesian(xlim=xlimlog,ylim=ylim)
}else lplot<-lplot+coord_cartesian(xlim=xlimlog)
}else{
xtemp <- sort(unique(doseLevVec))[1]^2/sort(unique(doseLevVec))[2]
doseLevVeclog <- doseLevVec
dgridveclog <- dgridvec
dosevecDSlog <- dosevecDS
dgridveclog[dgridvec==0] <- xtemp
bench_doseLevVeclog <- sort(unique(doseLevVeclog))
xlimlog <- c(log(xtemp)-(log(xlim[2])-log(xtemp))/10,
log(xlim[2])+(log(xlim[2])-log(xtemp))/10)
werrbarlog <- min(diff(sort(unique(log(dosevecDSlog)))))*(0.4)
if(plotDif){
mindose <- min(dosevecDS[dosevecDS>0])
index <- which(doseLevVeclog>=mindose)
indexgrid <- which(dgridveclog>=mindose)
doseLevVec <- doseLevVec[index]
doseLevVeclog <- doseLevVeclog[index]
dgridveclog <-dgridveclog[indexgrid]
predvecG <- predvecG[indexgrid]
protG <- protG[indexgrid]
dosevecDSlog <- dosevecDSlog[index]
cilvec <- cilvec[index]
cihvec <- cihvec[index]
pilvec <- pilvec[index]
pihvec <- pihvec[index]
ymvecDS <- ymvecDS[index]
protD <- protD[index]
protDS <- protDS[index]
symDS <- symDS[index]
fitvec <- fitvec[index]
xlimlog <- c(log(mindose)-(log(xlim[2])-log(mindose))/10,
log(xlim[2])+(log(xlim[2])-log(mindose))/10)
}
lplot<-ggplot(data.frame(cilvec,cihvec,pilvec,pihvec,
doseLevVec,doseLevVeclog,protD=factor(protD,labels=protlab)))
lplot<-lplot+scale_color_manual(name=symbolLabel,values=symbolColor)
lplot<-lplot+scale_shape_manual(name=symbolLabel,values=symbolShape)
if(length(unique(prot))>1)lplot<-lplot+facet_wrap(~protD,ncol=min(nprot,5))
if(predict)lplot<-lplot+geom_errorbar(aes(x=log(doseLevVeclog),ymax=pihvec,ymin=pilvec),size=1.1,
color='grey',width=werrbarlog)
if(plotci)lplot<-lplot+geom_errorbar(aes(x=log(doseLevVeclog),ymax=cihvec,ymin=cilvec),width=0,size=1.1,color='black')
data=data.frame(dgridveclog,predvecG=predvecG,protD=factor(protG,labels=protlab))
data1 <- subset(data, data$dgridveclog < bench_doseLevVeclog[1] & data$dgridveclog >= xtemp)
data2 <- subset(data, data$dgridveclog >= bench_doseLevVeclog[1])
lplot<-lplot+geom_line(data=data1, aes(x=log(dgridveclog),y=predvecG),color='black',size=1.1, linetype="dashed")
lplot<-lplot+geom_line(data=data2, aes(x=log(dgridveclog),y=predvecG),color='black',size=1.1, linetype="solid")
lplot<-lplot+geom_point(data=data.frame(ymvecDS,dosevecDSlog,symDS,protD=factor(protDS,labels=protlab)),
aes(x=log(dosevecDSlog),y=ymvecDS,shape=symDS,color=symDS),
size=symbolSize)
if(is.null(xat)) lplot <- lplot + scale_x_continuous(breaks=log(sort(unique(doseLevVeclog))),
labels=sort(unique(doseLevVec)))
if(!is.null(ylim)){lplot<-lplot+coord_cartesian(xlim=xlimlog,ylim=ylim)
}else lplot<-lplot+coord_cartesian(xlim=xlimlog)
}
}
lplot <- lplot +ylab(ylab) + xlab(xlab) + theme_bw()
lplot <- lplot+ theme(panel.grid.major.x=element_blank(),
panel.grid.minor.x=element_blank(),
panel.grid.major.y=element_line(size=0.1))
if(nolegend)lplot<-lplot + theme(legend.position = "none")
if(!is.null(xat)){
if(!logScale) lplot <- lplot + scale_x_continuous(breaks=xat,
labels =xat)
if(logScale){
xatbench <- xat
xat[xat==0] <- doselev[2]^2/doselev[3]
lplot <- lplot + scale_x_continuous(breaks=log(xat),
labels =xatbench)
}
}
if(plot){
print(lplot)
}
return(invisible(list(lplot=lplot,plotdata=cbind(prot=protD,dose=doseLevVec,fit=fitvec,
cil=cilvec,cih=cihvec,
pil=pilvec,pih=pihvec))))
} |
. = NULL
volcano2G <- function(foldchange,
pvals,
labels,
pthresh=0.1,
log2FCThresh=0.5,
main=NULL,
xlab="log2 FC",
ylab="-log10(Q Value)",
xlim=c(-5,5),
ylim=c(0,-log10(min(pvals, na.rm=TRUE))),
size=1,
segment.size=0.3,
segement.alpha=0.3,
pseudo = NULL,
colors = NULL
)
{
results <- data.frame(log2FoldChange = foldchange, pvalue= pvals, labels=labels )
fcLabel <- paste("Q Value <", pthresh, "& |FC| >", log2FCThresh)
if(is.null(results$significance)){
results$significance = ifelse(results$pvalue < pthresh & abs(results$log2FoldChange) > log2FCThresh ,
fcLabel ,"Not Sig" )
if(!is.null(pseudo)){
results$significance[is.na(pseudo)] <- "pseudo"
colors <- c("black", "green", "red" )
}else{
colors <- c("black", "red")
}
}
log2FoldChange <- NULL
pvalue <- NULL
p = ggplot(results, aes(log2FoldChange, -log10(pvalue))) +
geom_point(aes_string(col="significance")) +
scale_color_manual(values=colors)
p = p + ggplot2::geom_hline(yintercept=-log10(pthresh), col=4, lty=2)
p = p + ggplot2::geom_vline(xintercept=c(-log2FCThresh,log2FCThresh), col=4,lty=2)
filtres <- subset(results, pvalue<pthresh & abs(log2FoldChange)>log2FCThresh )
p = p + geom_text_repel(data=filtres, aes_string(label='labels'), size=size, segment.size = segment.size, segment.alpha = segement.alpha)
if(!is.null(main)){
p = p + ggtitle(main)
}
p = p + xlab(xlab)
p = p + ylab(ylab)
p = p + xlim(xlim[1],xlim[2])
p = p + ylim(ylim[1],ylim[2])
return(p)
}
volcano2GB <- function(dataX,
foldchange = "log2FC",
pvalue = "q.mod",
labels = "names",
pthresh=0.1,
log2FCThresh=0.5,
main=NULL,
xlab="log2 FC",
ylab="-log10(Q Value)",
repel.text.size=1,
repel.segment.size=0.5,
repel.segement.alpha=0.5,
pseudo= NULL
)
{
dataX <- dataX %>% mutate(yvalue = -log10(!!rlang::sym(pvalue)))
fcLabel <- paste(pvalue, "<", pthresh, "& |",foldchange,"| >", log2FCThresh)
colors <- NULL
if(is.null(dataX$significance)){
dataX$significance = ifelse(dataX[,pvalue] < pthresh & abs(dataX[,foldchange]) > log2FCThresh ,
fcLabel ,"Not Sig" )
if(!is.null(pseudo)){
dataX$significance[is.na(pseudo)] <- "pseudo"
colors <- c("black", "green", "red" )
}else{
colors <- c("black", "red")
}
}
p = ggplot(dataX, aes_string(foldchange, "yvalue")) +
geom_point(aes_string(col="significance"))
if(!is.null(colors)){
p = p + scale_color_manual(values=colors)
}
p = p + ggplot2::geom_hline(yintercept=-log10(pthresh), col=4, lty=2)
p = p + ggplot2::geom_vline(xintercept=c(-log2FCThresh,log2FCThresh), col=4,lty=2)
filtres <- dataX %>% filter( UQ(rlang::sym(pvalue)) < pthresh & abs( UQ(sym(foldchange) )) > log2FCThresh )
p = p + geom_text_repel(data = filtres,
aes_string(label=labels),
size = repel.text.size,
segment.size = repel.segment.size,
segment.alpha = repel.segement.alpha)
if(!is.null(main)){
p = p + ggtitle(main)
}
p = p + xlab(xlab)
p = p + ylab(ylab)
return(p)
}
addSpecialProteins <- function(p,
dataX,
special,
foldchange = "log2FC",
pvalue = "q.mod",
labels = "names"){
negLog10 <- function(x){-log10(x)}
dataX <- dataX %>% mutate_at(c("yvalue" = pvalue), negLog10)
testx <- function(x, special){tmp <- x %in% special; x[!tmp] <- NA; as.character(x)}
dataX <- dataX %>% mutate_at(c("names2" = labels) , funs(testx(., special)))
xx <- dataX %>% filter_at("names2",all_vars(!is.na(.)))
if(nrow(xx) == 0){
return(p)
}
p <- p + geom_point(data = xx, aes_string(foldchange, "yvalue"), color="cyan", shape=2)
p <- p + geom_text_repel(data = dataX,
aes_string(label="names2"), color="blue")
p
} |
vpc_opt <- function(bins = 'jenks',
n_bins = 'auto',
bin_mid = 'mean',
pred_corr = FALSE,
pred_corr_lower_bnd = 0,
pi = c(0.025, 0.975),
ci = c(0.025, 0.975),
lloq = NULL,
uloq = NULL,
rtte = FALSE,
rtte_calc_diff = TRUE,
events = NULL,
kmmc = NULL,
reverse_prob = FALSE,
as_percentage = TRUE) {
list(bins = bins, n_bins = n_bins, bin_mid = bin_mid, pred_corr = pred_corr,
pred_corr_lower_bnd = pred_corr_lower_bnd, pi = pi, ci = ci, lloq = lloq,
uloq = uloq, rtte = rtte, rtte_calc_diff = rtte_calc_diff, events = events,
kmmc = kmmc, reverse_prob = reverse_prob, as_percentage = as_percentage,
usr_call = names(match.call()[-1]))
}
get_psn_vpc_strat <- function(psn_cmd) {
if (stringr::str_detect(psn_cmd, '-stratify_on')) {
psn_cmd %>%
{stringr::str_match(string = ., pattern = '-stratify_on=\\s*([^\\s]+)')[1, 2]} %>%
stringr::str_split(',') %>%
purrr::flatten_chr()
}
}
psn_vpc_parser <- function(xpdb, psn_folder, psn_bins, opt, quiet) {
psn_folder <- parse_title(string = psn_folder, xpdb = xpdb, quiet = quiet,
problem = default_plot_problem(xpdb))
if (!dir.exists(psn_folder)) {
stop('The `psn_folder`:', psn_folder, ' could not be found.', call. = FALSE)
}
msg('Importing PsN generated data', quiet)
if (!dir.exists(file_path(psn_folder, 'm1')) &
file.exists(file_path(psn_folder, 'm1.zip'))) {
msg('Unziping PsN m1 folder', quiet)
utils::unzip(zipfile = file_path(psn_folder, 'm1.zip'),
exdir = file_path(psn_folder, ''))
unzip <- TRUE
} else {
unzip <- FALSE
}
obs_data <- read_nm_tables(file = dir(file_path(psn_folder, 'm1'), pattern = 'original.npctab')[1],
dir = file.path(psn_folder, 'm1'), quiet = TRUE)
sim_data <- read_nm_tables(file = dir(file_path(psn_folder, 'm1'), pattern = 'simulation.1.npctab')[1],
dir = file.path(psn_folder, 'm1'), quiet = TRUE)
if (unzip) unlink(x = file_path(psn_folder, 'm1'), recursive = TRUE, force = TRUE)
if (file.exists(file_path(psn_folder, 'version_and_option_info.txt'))) {
psn_opt <- readr::read_lines(file = file_path(psn_folder, 'version_and_option_info.txt'))
psn_cmd <- psn_opt[which(stringr::str_detect(psn_opt, '^Command:')) + 1]
psn_opt <- dplyr::tibble(raw = psn_opt[stringr::str_detect(psn_opt,'^-')]) %>%
tidyr::separate(col = 'raw', into = c('arg', 'value'), sep = '=') %>%
dplyr::mutate(arg = stringr::str_replace(.$arg, '^-', ''))
obs_cols <- list(id = 'ID', idv = psn_opt$value[psn_opt$arg == 'idv'],
dv = psn_opt$value[psn_opt$arg == 'dv'], pred = 'PRED')
sim_cols <- obs_cols
if (!any(opt$usr_call == 'pred_corr')) {
pred_corr <- as.logical(as.numeric(psn_opt$value[psn_opt$arg == 'predcorr']))
if (!is.na(pred_corr)) opt$pred_corr <- pred_corr
}
if (!any(opt$usr_call == 'lloq')) {
lloq <- as.numeric(psn_opt$value[psn_opt$arg == 'lloq'])
if (length(lloq) > 0 && !is.na(lloq)) opt$lloq <- lloq
}
if (!any(opt$usr_call == 'uloq')) {
uloq <- as.numeric(psn_opt$value[psn_opt$arg == 'uloq'])
if (length(uloq) > 0 && !is.na(uloq)) opt$uloq <- uloq
}
nsim <- ifelse(!stringr::str_detect(psn_cmd, '-sampl'), 'na',
stringr::str_match(psn_cmd, '-sampl[a-z]+=\\s*([^\\s]+)')[1, 2])
} else {
msg('PsN file `version_and_option_info.txt` not found. Using default options.', quiet)
obs_cols <- c(id = 'ID', idv = 'TIME', dv = 'DV', pred = 'PRED')
sim_cols <- obs_cols
}
if (file.exists(file_path(psn_folder, 'vpc_bins.txt')) && !any(opt$usr_call == 'bins') && psn_bins) {
psn_bins <- readr::read_lines(file = file_path(psn_folder, 'vpc_bins.txt')) %>%
.[nchar(.) > 0] %>%
utils::tail(n = 1) %>%
stringr::str_replace('^.+=', '') %>%
{stringr::str_split(., ':')[[1]]} %>%
{stringr::str_split(., ',')} %>%
purrr::map(~as.numeric(.x))
if (!any(is.na(psn_bins[[1]]))) {
opt$bins <- psn_bins[[1]]
msg(c('Using PsN-defined binning', ifelse(length(unique(psn_bins)) == 1 , '',
'. Only a single bin_array (i.e. first) can be used by xpose.')), quiet)
} else {
warning('Failed to read PsN-defined binning.', call. = FALSE)
}
}
list(obs_data = obs_data, obs_cols = obs_cols,
sim_data = sim_data, sim_cols = sim_cols,
opt = opt, psn_folder = psn_folder,
psn_cmd = psn_cmd, nsim = nsim)
} |
plot_ple <- function(object, target=NULL, type="waterfall", ...) {
if (is.null(object$mu_train)){
stop("Check ple model fit, no training estimates available.")
}
mu_hat <- object$mu_train
family <- object$family
if (is.null(mu_hat$Subgrps)) {
mu_hat$Subgrps <- rep("Overall", dim(mu_hat)[1])
}
if (is.null(target)) {
ple_name <- colnames(mu_hat)[grepl("diff", colnames(mu_hat))]
ple_name <- ple_name[1]
mu_hat$PLE <- mu_hat[[ple_name]]
}
if (!is.null(target)) {
ple_name <- target
mu_hat$PLE <- mu_hat[[target]]
}
pieces <- unlist(strsplit(ple_name, "_"))
if (pieces[1] %in% c("diff")) {
if (family=="gaussian") {
ple.label <- paste("E(Y|X,A=", pieces[2], ")-", "E(Y|X,A=", pieces[3], ")", sep="")
}
if (family=="binomial") {
ple.label <- paste("P(Y=1|X,A=", pieces[2], ")-", "P(Y=1|X,A=", pieces[3], ")", sep="")
}
if (family=="survival") {
if (object$ple=="ranger") {
treetype <- object$treetype
ple.label <- paste("RMST(X,A=", pieces[2], ")-", "RMST(X,A=", pieces[3], ")", sep="")
}
if (object$ple %in% c("linear", "glmnet")) {
ple.label <- paste("logHR(X,A=", pieces[2], ")-", "logHR(X,A=", pieces[3], ")", sep="")
}
}
}
if (pieces[1] != "diff") {
ple.label <- ple_name
}
y.label <- paste("Estimates:", ple.label)
x.label <- y.label
mu_hat$id = 1:nrow(mu_hat)
if (type=="waterfall") {
res = ggplot2::ggplot(mu_hat, ggplot2::aes(x=reorder(id, PLE), y=PLE, fill=Subgrps)) +
ggplot2::geom_bar(stat="identity") +
ggplot2::ggtitle( paste("Waterfall Plot: Patient-level Estimates,", ple.label)) +
ggplot2::ylab(y.label) +
ggplot2::xlab("")+
ggplot2::theme_bw() +
ggplot2::theme(axis.line.x = ggplot2::element_blank(),
axis.text.x = ggplot2::element_blank(),
axis.ticks.x = ggplot2::element_blank(),
axis.title.y = ggplot2::element_text(face="bold",angle=90))
}
if (type=="density") {
x.label <- y.label
res = ggplot2::ggplot(mu_hat, ggplot2::aes(PLE, fill=Subgrps)) +
ggplot2::geom_density(alpha=0.30) +
ggplot2::xlab(x.label) +
ggplot2::ggtitle(paste("Density Plot: Patient-Level Estimates,", ple.label))+
ggplot2::theme(plot.title=ggplot2::element_text(size=16,face="bold"),
axis.text.y=ggplot2::element_blank(),
axis.ticks.y=ggplot2::element_blank(),
axis.text.x=ggplot2::element_text(face="bold"),
axis.title=ggplot2::element_text(size=12,face="bold"))+
ggplot2::theme_bw()
}
return(res)
} |
"polls_2008" |
Randomization.Coc <- do (5000) * diff( prop( response ~ shuffle(treatment), data = Cocaine ) )
head(Randomization.Coc) |
ac <- function(x) {
class(x) <- c("nested_list", "character")
x
}
test_that("empty", {
empty <- "{empty}" %>% ac()
expect_equal(nested_list(c()), empty)
expect_equal(nested_list(list()), empty)
expect_equal(nested_list(NULL), empty)
expect_equal(nested_list(""), ac(""))
x <- list(list(list()))
comp <- "1. 1. {empty}" %>% ac()
expect_equal(nested_list(x), comp)
})
test_that("unnamed vectors", {
x <- "A"
comp <- "A" %>% ac()
expect_equal(nested_list(x), comp)
x <- 1:3
comp <- "1. 1\n2. 2\n3. 3" %>% ac()
expect_equal(nested_list(x), comp)
x <- 1:3
comp <- "1. `1`\n2. `2`\n3. `3`" %>% ac()
expect_equal(nested_list(x, quote = "`"), comp)
})
test_that("unnamed vectors", {
x <- c(a = "A", b = "B")
comp <- "* a: A\n* b: B" %>% ac()
expect_equal(nested_list(x), comp)
x <- c(a = "A", b = "B")
comp <- ">* a: A\n>* b: B" %>% ac()
expect_equal(nested_list(x, pre = ">"), comp)
})
test_that("unnamed lists", {
x <- list(list())
comp <- "1. {empty}" %>% ac()
expect_equal(nested_list(x), comp)
x <- list(c())
comp <- "1. {empty}" %>% ac()
expect_equal(nested_list(x), comp)
x <- list("A", "B")
comp <- "1. A\n2. B" %>% ac()
expect_equal(nested_list(x), comp)
x <- list("A", "B")
comp <- " 1. A\n 2. B" %>% ac()
expect_equal(nested_list(x, pre = " "), comp)
})
test_that("named lists", {
x <- list(a = list())
comp <- "* a: {empty}" %>% ac()
expect_equal(nested_list(x), comp)
x <- list(a = c())
comp <- "* a: {empty}" %>% ac()
expect_equal(nested_list(x), comp)
x <- list(a = 1)
comp <- "* a: 1" %>% ac()
expect_equal(nested_list(x), comp)
x <- list(a = 1)
comp <- " * a: 1" %>% ac()
expect_equal(nested_list(x, pre = " "), comp)
x <- list(a = 1, 2)
comp <- "* a: 1\n* {2}: 2" %>% ac()
expect_equal(nested_list(x), comp)
})
test_that("nested lists", {
x <- list(list("A", "B"), list("C", "D"))
comp <- paste0("1. \n 1. A\n 2. B\n",
"2. \n 1. C\n 2. D") %>% ac()
expect_equal(nested_list(x), comp)
x <- list(x1 = list("A", "B"), x2 = list("C", "D"))
comp <- paste0("* x1: \n 1. A\n 2. B\n",
"* x2: \n 1. C\n 2. D") %>% ac()
expect_equal(nested_list(x), comp)
x <- list(x1 = list(a = "A", b = "B"), x2 = list())
comp <- paste0("* x1: \n * a: A\n * b: B\n",
"* x2: {empty}") %>% ac()
expect_equal(nested_list(x), comp)
})
test_that("code", {
f1 <- function(a = 1) {
a + 10
}
x <- list(
f1 = f1,
f2 = function() { "hi"}
)
comp <- "* f1:
```r
function (a = 1)
{
a + 10
}
```
* f2:
```r
function ()
{
\"hi\"
}
```" %>% ac()
expect_equal(nested_list(x), comp)
comp2 <- strsplit(comp, "\n")[[1]] %>%
paste0(">", .) %>%
paste(collapse = "\n") %>%
ac()
expect_equal(nested_list(x, pre = ">"), comp2)
})
test_that("example", {
x <- list(
a = list(a1 = "Named", a2 = "List"),
b = list("Unnamed", "List"),
c = c(c1 = "Named", c2 = "Vector"),
d = c("Unnamed", "Vector"),
e = list(e1 = list("A", "B", "C"),
e2 = list(a = "A", b = "B"),
e3 = c("A", "B", "C"),
e4 = 100),
f = "not a list or vector"
)
comp <- "* a:
* a1: Named
* a2: List
* b:
1. Unnamed
2. List
* c:
* c1: Named
* c2: Vector
* d:
1. Unnamed
2. Vector
* e:
* e1:
1. A
2. B
3. C
* e2:
* a: A
* b: B
* e3:
1. A
2. B
3. C
* e4: 100
* f: not a list or vector" %>% ac()
expect_equal(nested_list(x), comp)
}) |
first_dimensions_match = function(e1, e2) {
d1 = dim(e1)
d2 = dim(e2)
n = min(length(d1), length(d2))
all.equal(d1[n], d2[n])
}
Ops.stars <- function(e1, e2) {
if (inherits(e1, "stars") && inherits(e2, "stars") && !first_dimensions_match(e1, e2))
stop("(first) dimensions of e1 and e2 do not match")
ret = if (missing(e2))
lapply(e1, .Generic)
else if (!inherits(e2, "stars"))
lapply(e1, .Generic, e2 = e2)
else {
if (!is.null(dim(e1)) &&
!isTRUE(all.equal(dim(e1), dim(e2), check.attributes = FALSE))) {
stopifnot(length(e2) == 1)
lapply(e1, .Generic, e2 = as.vector(e2[[1]]))
} else
mapply(.Generic, e1, e2, SIMPLIFY = FALSE)
}
if (any(sapply(ret, function(x) is.null(dim(x)))))
ret = lapply(ret, function(x) { dim(x) = dim(e1); x })
if (! inherits(e1, "stars"))
setNames(st_as_stars(ret, dimensions = st_dimensions(e2)), names(e2))
else
st_as_stars(ret, dimensions = st_dimensions(e1))
}
Math.stars = function(x, ...) {
ret = lapply(x, .Generic, ...)
st_as_stars(ret, dimensions = st_dimensions(x))
}
Ops.stars_proxy <- function(e1, e2) {
if (!inherits(e1, "stars_proxy"))
stop("first argument in expression needs to be the stars_proxy object")
if (missing(e2))
collect(e1, match.call(), .Generic, "e1", env = environment())
else
collect(e1, match.call(), .Generic, c("e1", "e2"), env = environment())
}
Math.stars_proxy = function(x, ...) {
collect(x, match.call(), .Generic, env = environment())
}
has_single_arg = function(fun, dots) {
sum(!(names(as.list(args(fun))) %in% c("", "...", names(dots)))) <= 1
}
can_single_arg = function(fun) {
!inherits(try(fun(1:10), silent = TRUE), "try-error")
}
st_apply = function(X, MARGIN, FUN, ...) UseMethod("st_apply")
st_apply.stars = function(X, MARGIN, FUN, ..., CLUSTER = NULL, PROGRESS = FALSE, FUTURE = FALSE,
rename = TRUE, .fname, single_arg = has_single_arg(FUN, list(...)) || can_single_arg(FUN),
keep = FALSE) {
if (missing(.fname))
.fname <- paste(deparse(substitute(FUN), 50), collapse = "\n")
if (is.character(MARGIN))
MARGIN = match(MARGIN, names(dim(X)))
dX = dim(X)[MARGIN]
if (PROGRESS && !requireNamespace("pbapply", quietly = TRUE))
stop("package pbapply required, please install it first")
if (FUTURE && !requireNamespace("future.apply", quietly = TRUE))
stop("package future.apply required, please install it first")
fn = function(y, ...) {
ret = if (PROGRESS)
pbapply::pbapply(X = y, MARGIN = MARGIN, FUN = FUN, ..., cl = CLUSTER)
else {
if (is.null(CLUSTER) && !FUTURE)
apply(X = y, MARGIN = MARGIN, FUN = FUN, ...)
else if (FUTURE) {
oopts = options(future.globals.maxSize = +Inf)
on.exit(options(oopts))
future.apply::future_apply(y, MARGIN = MARGIN, FUN = FUN, ...)
} else
parallel::parApply(CLUSTER, X = y, MARGIN = MARGIN, FUN = FUN, ...)
}
if (is.array(ret))
ret
else
array(ret, dX)
}
no_margin = setdiff(seq_along(dim(X)), MARGIN)
ret = if (single_arg)
lapply(X, fn, ...)
else
lapply(X, function(a) do.call(FUN, setNames(append(asplit(a, no_margin), list(...)), NULL)))
dim_ret = dim(ret[[1]])
ret = if (length(dim_ret) == length(MARGIN)) {
if (length(ret) == 1 && rename && make.names(.fname) == .fname)
ret = setNames(ret, .fname)
st_stars(ret, st_dimensions(X)[MARGIN])
} else {
dim_no_margin = dim(X)[-MARGIN]
if (length(no_margin) > 1 && dim(ret[[1]])[1] == prod(dim_no_margin)) {
r = attr(st_dimensions(X), "raster")
new_dim = c(dim_no_margin, dim(ret[[1]])[-1])
for (i in seq_along(ret))
dim(ret[[i]]) = new_dim
dims = st_dimensions(X)[c(no_margin, MARGIN)]
} else {
orig = st_dimensions(X)[MARGIN]
r = attr(orig, "raster")
dims = if (keep) {
c(st_dimensions(X)[no_margin], orig)
} else {
dim1 = if (!is.null(dimnames(ret[[1]])[[1]]))
create_dimension(values = dimnames(ret[[1]])[[1]])
else
create_dimension(to = dim_ret[1])
c(structure(list(dim1), names = .fname), orig)
}
}
st_stars(ret, dimensions = create_dimensions(dims, r))
}
for (i in seq_along(ret))
names(dim(ret[[i]])) = names(st_dimensions(ret))
ret
}
if (!isGeneric("%in%"))
setGeneric("%in%", function(x, table) standardGeneric("%in%"))
setMethod("%in%", signature(x = "stars"),
function(x, table) {
st_stars(lapply(x, function(y) structure(y %in% table, dim = dim(y))),
st_dimensions(x))
}
) |
helper_scale_nmf_matrix <- function(Signature, Exposure, K, handle_cn = FALSE) {
W <- Signature
H <- Exposure
if (handle_cn) {
has_cn <- grepl("^CN[^C]", rownames(Signature)) | startsWith(rownames(Signature), "copynumber")
if (any(has_cn)) {
W <- W[has_cn, ]
}
}
for (j in seq_len(K)) {
Signature[, j] <- Signature[, j] * rowSums(H)[j]
Exposure[j, ] <- Exposure[j, ] * colSums(W)[j]
}
return(list(Signature = Signature, Exposure = Exposure))
} |
carray <- function(array, margin = 3L, rows = TRUE, columns = TRUE) {
if (length(dim(array)) != 3L)
stop("Argument 'array' must be a three-way array.")
if (length(margin) != 1L) {
warning("Only the first element of argument 'margin' is used.")
margin <- margin[1L]
}
ind <- seq_len(3L)
ind_rm <- ind[-margin]
row_ind <- ind_rm[1L]
col_ind <- ind_rm[2L]
dims <- dim(array)
dims_rm <- dims[-margin]
row_dim <- dims_rm[1L]
col_dim <- dims_rm[2L]
if (rows) {
rmns <- apply(array, sort(c(row_ind, margin)), mean)
rmns <- rep(rmns, each = col_dim)
rmns <- array(rmns, dim = c(col_dim, dims[-col_ind]))
perm <- switch(margin, c(2:3, 1), c(2, 3, 1), c(2:1, 3))
rmns <- aperm(rmns, perm)
array <- array - rmns
}
if (columns) {
cmns <- apply(array, sort(c(col_ind, margin)), mean)
cmns <- rep(cmns, each = row_dim)
cmns <- array(cmns, dim = c(row_dim, dims[-row_ind]))
perm <- switch(margin, c(2, 1, 3), 1:3, 1:3)
cmns <- aperm(cmns, perm)
array <- array - cmns
}
return(array)
} |
svg.triangle <- function(corners, col='blue', seg=1, emissive=rgb(0.03, 0.15, 0.21), opacity = 1, name = 'triangle',
ontop = FALSE, return.shape = FALSE, plot = TRUE){
if('svg' == getOption("svgviewr_glo_type")) stop("'webgl' mode must be used to enable mesh drawing. This can be done by adding the following parameter to the svg.new() function call: mode='webgl'. This will become the default mode by version 1.4.")
if(seg > 1){
edge1_len <- dppt_svg(corners[1,], corners[2,])
edge1_vec <- uvector_svg(corners[1,]-corners[2,])
edge1_spa <- edge1_len / seg
edge2_len <- dppt_svg(corners[2,], corners[3,])
edge2_vec <- uvector_svg(corners[3,]-corners[2,])
edge2_spa <- edge2_len / seg
edge3_len <- dppt_svg(corners[1,], corners[3,])
edge3_vec <- uvector_svg(corners[3,]-corners[1,])
edge3_spa <- edge3_len / seg
edge1_pts <- edge2_pts <- edge3_pts <- matrix(NA, seg-1, 3)
for(i in 1:(seg-1)){
edge1_pts[i, ] <- corners[2,] + i*edge1_spa*edge1_vec
edge2_pts[i, ] <- corners[2,] + i*edge2_spa*edge2_vec
edge3_pts[i, ] <- corners[1,] + i*edge3_spa*edge3_vec
}
vertices <- rbind(corners[2,], edge1_pts[1,], edge2_pts[1,])
if(seg > 2){
for(i in 2:(seg-1)){
int_len <- dppt_svg(edge1_pts[i, ], edge2_pts[i, ])
int_vec <- uvector_svg(edge2_pts[i, ]-edge1_pts[i, ])
int_spa <- int_len / i
vertices <- rbind(vertices, edge1_pts[i, ])
for(j in 1:(i-1)){
vertices <- rbind(vertices, edge1_pts[i, ] + j*int_spa*int_vec)
}
vertices <- rbind(vertices, edge2_pts[i, ])
}
}else{
}
vertices <- rbind(vertices, corners[1,], edge3_pts, corners[3,])
faces <- matrix(NA, 0, 3)
start_face <- 0
for(i in 1:max(2, (seg))){
for(j in 1:((i-1)*2+1)){
if(j == 1 || j %% 2 == 1){
faces <- rbind(faces, c(start_face, start_face + i, start_face + i + 1))
start_face <- start_face + 1
}else{
faces <- rbind(faces, c(start_face, start_face - 1, start_face + i))
}
}
}
}else{
vertices <- corners
faces <- c(0,1,2)
}
if(!plot) return(list('vertices'=vertices, 'faces'=faces))
if('svg' == getOption("svgviewr_glo_type")){
if(is.vector(faces)) faces <- matrix(faces, 1, 3)
svg.points(vertices[1,], col='red')
svg.points(vertices[2:(nrow(vertices)-1), ])
svg.points(vertices[nrow(vertices),], col='blue')
svg.text(vertices, labels=0:(nrow(vertices)-1), font.size=0.1)
if(!is.null(faces)){
faces <- cbind(faces, faces[,1])
svg.pathsC(lapply(seq_len(nrow(faces)), function(i) faces[i,]+1), col='black', opacity.fill=0.2)
}
}else{
env <- as.environment(getOption("svgviewr_glo_env"))
add_at <- length(svgviewr_env$svg$mesh)+1
svgviewr_env$svg$mesh[[add_at]] <- list()
svgviewr_env$svg$mesh[[add_at]]$name <- name
svgviewr_env$svg$mesh[[add_at]]$vertices <- t(vertices)
svgviewr_env$svg$mesh[[add_at]]$faces <- t(faces)
svgviewr_env$svg$mesh[[add_at]]$col <- setNames(webColor(col), NULL)
svgviewr_env$svg$mesh[[add_at]]$opacity <- setNames(opacity, NULL)
svgviewr_env$svg$mesh[[add_at]]$emissive <- setNames(webColor(emissive), NULL)
svgviewr_env$svg$mesh[[add_at]]$computeVN <- TRUE
svgviewr_env$svg$mesh[[add_at]]$parseModel <- FALSE
svgviewr_env$svg$mesh[[add_at]]$depthTest <- !ontop
svgviewr_env$ref$names <- c(svgviewr_env$ref$names, name)
svgviewr_env$ref$num <- c(svgviewr_env$ref$num, add_at)
svgviewr_env$ref$type <- c(svgviewr_env$ref$type, 'mesh')
if(!is.null(corners)){
obj_ranges <- apply(corners, 2, 'range', na.rm=TRUE)
}else{
obj_ranges <- apply(vertices, 2, 'range', na.rm=TRUE)
}
corners <- lim2corners(obj_ranges)
svgviewr_env$svg$mesh[[add_at]][['lim']] <- obj_ranges
svgviewr_env$svg$mesh[[add_at]][['corners']] <- corners
}
if(return.shape){
return(list('vertices'=vertices, 'faces'=faces))
}else{
return(NULL)
}
} |
staple_bin_img = function(
x,
set_orient = FALSE,
verbose = TRUE,
...) {
if (verbose) {
message("Reshaping images")
}
x = reshape_img(x = x, set_orient = set_orient,
verbose = verbose)
first_image = x$first_image
all_nifti = x$all_nifti
x = x$x
if (verbose) {
message("Running STAPLE for binary matrix")
}
res = staple_bin_mat(x, verbose = verbose, ...)
if (verbose) {
message("Creating output probability image/array")
}
outimg = array(res$probability,
dim = dim(first_image))
if (all_nifti) {
hdr = RNifti::niftiHeader(first_image)
hdr$cal_max = 1
hdr$cal_min = 0
hdr$datatype = 16
hdr$bitpix = 32
outimg = RNifti::updateNifti(
outimg, template = hdr)
}
if (verbose) {
message("Creating output prior image/array")
}
priorimg = array(res$prior,
dim = dim(first_image))
if (all_nifti) {
priorimg = RNifti::updateNifti(
priorimg, template = hdr)
}
if (verbose) {
message("Creating label image (probability >= 0.5)")
}
label = array(res$label,
dim = dim(first_image))
if (all_nifti) {
hdr$datatype = 2
hdr$bitpix = 8
label = RNifti::updateNifti(
label, template = hdr)
}
res$probability = outimg
res$label = label
res$prior = priorimg
rm(list = c("outimg", "priorimg", "label"))
gc()
return(res)
}
staple_multi_img = function(
x,
set_orient = FALSE,
verbose = TRUE,
...) {
if (verbose) {
message("Reshaping images")
}
x = reshape_img(x = x, set_orient = set_orient,
verbose = verbose)
first_image = x$first_image
all_nifti = x$all_nifti
x = x$x
res = staple_multi_mat(x, ...)
if (all_nifti) {
hdr = RNifti::niftiHeader(first_image)
hdr$cal_max = 1
hdr$cal_min = 0
hdr$datatype = 16
hdr$bitpix = 32
}
if (verbose) {
message("Creating output probability images/arrays")
}
n_level = ncol(res$probability)
outimg = lapply(seq(n_level), function(ind) {
probability = res$probability[, ind]
outimg = array(
probability,
dim = dim(first_image))
if (all_nifti) {
outimg = RNifti::updateNifti(
outimg, template = hdr)
}
return(outimg)
})
names(outimg) = colnames(res$probability)
res$probability = outimg
rm(list = "outimg"); gc()
priorimg = lapply(seq(n_level), function(ind) {
probability = res$prior[, ind]
outimg = array(
probability,
dim = dim(first_image))
if (all_nifti) {
outimg = RNifti::updateNifti(
outimg, template = hdr)
}
return(outimg)
})
names(priorimg) = colnames(res$prior)
res$prior = priorimg
rm(list = "priorimg"); gc()
if (verbose) {
message("Creating output label image/array")
}
label = array(
res$label,
dim = dim(first_image))
if (all_nifti) {
hdr$datatype = 8
hdr$bitpix = 32
label = RNifti::updateNifti(
label, template = hdr)
}
res$label = label
return(res)
} |
graphrate.fun <-
function(objres=NULL, fittedlambda=NULL, emplambda=NULL, t=NULL,
lint=NULL,typeI='Disjoint', tit='',scax=NULL,scay=NULL, xlegend='topleft',histWgraph=TRUE)
{
if (is.null(objres)&(is.null(fittedlambda)|is.null(t)|is.null(emplambda)|is.null(lint)))
stop ('Argument objres or vector of arguments (fittedlambda, emplambda, t) must be specified')
if (is.null(objres)=='FALSE')
{
fittedlambda<-objres$fittedlambda
emplambda<-objres$emplambda
typeI<-objres$typeI
t<-objres$mlePP@t
if (typeI=='Disjoint') t<-t[objres$pm]
lint<-objres$lint
}
if (histWgraph==TRUE) dev.new(record=TRUE)
par(mfrow=c(1,1))
if (is.null(scay)==TRUE)
{
yminn<-min(emplambda,fittedlambda,na.rm=TRUE)
ymaxx<-max(emplambda,fittedlambda,na.rm=TRUE)
scay<-c(yminn,ymaxx)
}
if (is.null(scax)==TRUE) scax<-c(min(t, na.rm=TRUE), max(t, na.rm=TRUE))
plot(t, emplambda, cex = 0.5, xlab = "time", ylab = "empirical and fitted occurrence rates",
ylim=scay,xlim=scax, type = "l",lty=1)
lines(t, fittedlambda, col='red')
legend(x=xlegend, legend=c('Empirical rate', 'Fitted rate'), col=c('black', 'red'), lty=c(1,1), cex=0.8)
title(sub=paste('Rates calculated in', typeI, 'intervals of length', lint, sep=' '), cex=0.7)
mtext(paste(" Model: ", tit, sep=''), outer = TRUE, line = -2,cex=1)
return(NULL)
} |
resolveTies <- function(data, contestants, column) {
numJudges <- ncol(data)
majority <- ifelse(c(numJudges/2) %% 1 == 0,numJudges/2 + 1, ceiling(numJudges/2))
sumscoreThreshold <- column
nextScore <- column+1
sumscores <- apply(data[contestants,], 1, function(a){
sum(a[which(a <= sumscoreThreshold)])
})
winner <- contestants[which.min(sumscores)]
winnerScore <- sumscores[which(contestants == winner)]
tiedwinner <- any(winnerScore == sumscores[
which(contestants %in% setdiff(contestants,winner))])
if (!tiedwinner) {
return(list(winnerfound="sumscore",
winner=winner))
}
else if(tiedwinner) {
if (length(sumscores[which(as.vector(table(sumscores)) > 1)]) == 1){
while(tiedwinner & nextScore <= nrow(data)) {
nscores <- apply(data[contestants,], 1, function(a){
length(which(a == nextScore))
})
winner <- contestants[which.max(nscores)]
winnerScore <- nscores[which(contestants == winner)]
tiedwinner <- any(winnerScore == nscores[
which(contestants %in% setdiff(contestants,winner))])
if (!tiedwinner) {
return(list(winnerfound="nextscore",
winner=winner))
} else {
nextScore <- nextScore + 1
}
}
if (nextScore > nrow(data)) {
reducedData <- apply(data[contestants,], 2, function(a) {order(a)})
reducedRanking <- rankContestants(reducedData)
winner <- contestants[which(reducedRanking ==1)]
if(length(winner) == 1)
return(list(winnerfound="recursivecontests",
winner=winner))
else{
return(list(winnerfound = "nowinner", winner = winner))
}
}
}
else if(length(sumscores[which(as.vector(table(sumscores)) > 1)]) > 1){
tiebreakContestants = contestants[which(sumscores == min(sumscores))]
reducedData <- apply(data[tiebreakContestants,], 2, function(a) {order(a)})
reducedRanking = rankContestants(reducedData)
winner = tiebreakContestants[order(reducedRanking, decreasing = T)]
return(list(winnerfound="sumscoretie",
winner=winner))
}
}
} |
NULL
.gtoolbar.guiWidgetsToolkittcltk <- function(toolkit,
toolbar.list=list(),
style = c("both","icons","text","both-horiz"),
container = NULL,
... ) {
GToolBar$new(toolkit,
toolbar.list=toolbar.list, style=style,
container=container ,...)
}
GToolBar <- setRefClass("GToolBar",
contains="GBoxContainer",
fields=list(
toolbar_list="list",
style="character"
),
methods=list(
initialize=function(toolkit=NULL,
toolbar.list=list(),
style = c("both", "icons", "text", "both-horiz"),
container = NULL,
...) {
if(!is(container, "GWindow")) {
message(gettext("gtoolbar requires a gwindow instance as a parent container"))
return()
}
widget <<- ggroup(horizontal=TRUE, spacing=0, expand=TRUE, fill="x",
container=container$toolbar_area)
initFields(block=widget,
toolbar_list=list(),
style=style,
horizontal=TRUE
)
set_spacing(0)
add_toolbar_items(toolbar.list)
callSuper(toolkit)
},
get_widget=function() {
widget$widget
},
add_toolbar_items=function(items) {
"Map a toolbar list, a named list of gaction items or gsepartor items"
sapply(items, function(item) {
if(is(item, "GAction"))
add_gaction_toolitem(item)
else if(is(item, "GSeparator"))
add_gseparator_toolitem()
})
widget$show()
toolbar_list <<- gWidgets2:::merge.list(toolbar_list, items)
},
add_gaction_toolitem=function(obj) {
"Helper to add a gaction item"
btn <- gbutton(action=obj, container=widget, expand=FALSE)
style_map <- list("both"="center", "icons"="image", "text"="text", "both-horiz"="left")
tkconfigure(btn$widget, compound=style_map[[style]], style="Toolbutton")
},
add_gseparator_toolitem=function() {
"Helper to add a separator"
gseparator(horizontal=FALSE, container=widget)
},
clear_toolbar=function() {
"Clear toolbar items"
widget$remove_children()
},
get_value=function( ...) {
toolbar_list
},
set_value=function(value, ...) {
"Clear toolbar, add anew"
clear_toolbar()
add_toolbar_items(value)
}
)) |
session <- RevoIOQ:::saveRUnitSession(packages="tools")
graphicsDevice.stress.png <- function()
{
png(filename = "testplot.png")
plot(1:10)
dev.off()
checkTrue(file.exists("testplot.png"))
unlink("testplot.png")
}
graphicsDevice.stress.jpg <- function()
{
jpeg(filename = "testplot.jpg")
plot(1:10)
dev.off()
checkTrue(file.exists("testplot.jpg"))
unlink("testplot.jpg")
}
graphicsDevice.stress.svg <- function()
{
svg(filename = "testplot.svg")
plot(1:10)
dev.off()
checkTrue(file.exists("testplot.svg"))
unlink("testplot.svg")
}
graphicsDevice.stress.cairo_pdf <- function()
{
cairo_pdf(filename = "testplot.pdf")
plot(1:10)
dev.off()
checkTrue(file.exists("testplot.pdf"))
unlink("testplot.pdf")
}
graphicsDevice.stress.cairo_ps <- function()
{
cairo_ps(filename = "testplot.ps")
plot(1:10)
dev.off()
checkTrue(file.exists("testplot.ps"))
unlink("testplot.ps")
}
"test.graphicsDevices.stress" <- function()
{
res <- try(graphicsDevice.stress.png())
checkTrue(!is(res, "try-error"), msg="PNG Graphics Device stress test failed")
res <- try(graphicsDevice.stress.jpg())
checkTrue(!is(res, "try-error"), msg="JPG Graphics Device stress test failed")
res <- try(graphicsDevice.stress.svg())
checkTrue(!is(res, "try-error"), msg="SVG Graphics Device stress test failed")
res <- try(graphicsDevice.stress.cairo_pdf())
checkTrue(!is(res, "try-error"), msg="Cairo PDF Graphics Device stress test failed")
res <- try(graphicsDevice.stress.cairo_ps())
checkTrue(!is(res, "try-error"), msg="Cairo PS Graphics Device stress test failed")
}
"testzzz.restore.session" <- function()
{
checkTrue(RevoIOQ:::restoreRUnitSession(session), msg="Session restoration failed")
} |
.onAttach <- function(...) {
if (!isTRUE(getOption("syberia.silent"))) {
packageStartupMessage(paste0("Loading ", crayon::red("Syberia"), "...\n"))
}
if (isTRUE(getOption("syberia.autoload_bettertrace", TRUE)) &&
!identical(Sys.getenv("CI"), "TRUE")) {
if (!is.element("devtools", utils::installed.packages()[, 1])) {
packageStartupMessage(crayon::yellow(" ...Installing devtools\n"))
utils::install.packages("devtools")
}
if (!requireNamespace("bettertrace", quietly = TRUE)) {
packageStartupMessage(crayon::yellow(" ...Installing github.com/robertzk/bettertrace\n"))
devtools::install_github("robertzk/bettertrace")
}
library(bettertrace)
}
makeActiveBinding("project", env = globalenv(),
function() getFromNamespace("active_project", "syberia")())
makeActiveBinding("resource", env = globalenv(),
function() getFromNamespace("active_project", "syberia")()$resource)
try({
syberia_engine()
packageStartupMessage(crayon::yellow(
"Loaded syberia project ", sQuote(active_project()$root()), "...\n"
))
}, silent = TRUE)
}
.onDetach <- function(...) {
try(silent = TRUE, detach("syberia:shims"))
}
.onUnload <- function(...) {
try(silent = TRUE, detach("syberia:shims"))
} |
get_all_node_depths = function(tree, as_edge_count=FALSE){
Ntips = length(tree$tip.label)
Nnodes = tree$Nnode;
depths = get_mean_depth_per_node_CPP( Ntips = Ntips,
Nnodes = Nnodes,
Nedges = nrow(tree$edge),
tree_edge = as.vector(t(tree$edge))-1,
edge_length = (if(as_edge_count || is.null(tree$edge.length)) numeric() else tree$edge.length));
return(depths);
} |
tidy_name <- function(x) {
new_spec_names <- unlist(lapply(x, function(y) {
split_str <- unlist(stringr::str_split(y, "_"))
return(paste0(
stringr::str_to_upper(stringr::str_sub(split_str[1], 1, 1)),
split_str[2],
collapse = ""
))
}))
return(new_spec_names)
} |
context("Testing find_write_match()")
uid <- as.character(random_hash())
data_product1 <- file.path("data_product", "write", "wildcard", uid, "1")
data_product2 <- file.path("data_product", "write", "wildcard", uid, "1", "2")
coderun_description <- "Register a file in the pipeline"
dataproduct_description <- "A csv file"
namespace1 <- "username"
endpoint <- Sys.getenv("FDP_endpoint")
config_file <- file.path(tempdir(), "config_files", "outputglobbing",
paste0("config_", uid, ".yaml"))
create_config(path = config_file,
description = coderun_description,
input_namespace = namespace1,
output_namespace = namespace1)
add_write(path = config_file,
data_product = data_product1,
description = dataproduct_description,
file_type = "csv")
add_write(path = config_file,
data_product = data_product2,
description = dataproduct_description,
file_type = "csv")
fair_run(path = config_file, skip = TRUE)
config <- file.path(Sys.getenv("FDP_CONFIG_DIR"), "config.yaml")
script <- file.path(Sys.getenv("FDP_CONFIG_DIR"), "script.sh")
handle <- initialise(config, script)
test_that("data products recorded in working config", {
writes <- handle$yaml$write
testthat::expect_equal(writes[[1]]$data_product, data_product1)
testthat::expect_equal(writes[[2]]$data_product, data_product2)
testthat::expect_equal(writes[[1]]$use$version, "0.0.1")
testthat::expect_equal(writes[[2]]$use$version, "0.0.1")
})
path1 <- link_write(handle, data_product1)
uid1 <- paste0(uid, "_1")
df1 <- data.frame(a = uid1, b = uid1)
write.csv(df1, path1)
path2 <- link_write(handle, data_product2)
uid2 <- paste0(uid, "_2")
df2 <- data.frame(a = uid2, b = uid2)
write.csv(df2, path2)
finalise(handle)
data_product3 <- file.path("data_product", "write", "wildcard", uid, "*")
use_version <- "${{MAJOR}}"
config_file <- file.path(tempdir(), "config_files", "outputglobbing",
paste0("config2_", uid, ".yaml"))
create_config(path = config_file,
description = coderun_description,
input_namespace = namespace1,
output_namespace = namespace1)
add_write(path = config_file,
data_product = data_product3,
description = dataproduct_description,
file_type = "csv",
use_version = use_version)
fair_run(path = config_file, skip = TRUE)
config <- file.path(Sys.getenv("FDP_CONFIG_DIR"), "config.yaml")
script <- file.path(Sys.getenv("FDP_CONFIG_DIR"), "script.sh")
handle <- initialise(config, script)
test_that("data products recorded in working config", {
writes <- handle$yaml$write
testthat::expect_equal(writes[[1]]$data_product, data_product3)
testthat::expect_equal(writes[[2]]$data_product, data_product2)
testthat::expect_equal(writes[[3]]$data_product, data_product1)
testthat::expect_equal(writes[[1]]$use$version, "1.0.0")
testthat::expect_equal(writes[[2]]$use$version, "1.0.0")
testthat::expect_equal(writes[[3]]$use$version, "1.0.0")
aliases <- find_write_match(handle, data_product3)
testthat::expect_true(all(aliases %in% c(data_product1, data_product2,
data_product3)))
})
data_product4 <- file.path(dirname(data_product3), "new")
path4 <- link_write(handle = handle,
data_product = data_product4)
uid4 <- paste0(uid, "_1")
df4 <- data.frame(a = uid4, b = uid4)
write.csv(df4, path4)
path5 <- link_write(handle = handle,
data_product = data_product2)
uid5 <- paste0(uid, "_1")
df5 <- data.frame(a = uid5, b = uid5)
write.csv(df5, path5)
test_that("data products recorded in working config", {
outputs <- handle$outputs
testthat::expect_equal(outputs$data_product[1], data_product4)
testthat::expect_equal(outputs$data_product[2], data_product2)
testthat::expect_equal(outputs$use_version[1], "1.0.0")
testthat::expect_equal(outputs$use_version[2], "1.0.0")
}) |
getsizeratios <-
function (bycx, ac, method = "fast")
{
K1 = nrow(ac)
nc = length(bycx)
if (method == "fast") {
bwx = bycx %*% t(ac) %*% solve(ac %*% t(ac))
sizeratios = rep(0, K1)
for (i in 1:K1) {
divisor = sqrt(1 + sum(bwx[1:i]^2))
betachat = bycx - bwx[, 1:i, drop = FALSE] %*% ac[1:i,
, drop = FALSE]
scaledbetac = sqrt(nc/(nc - i)) * betachat/divisor
sizeratios[i] = median(abs(as.vector(ac[i, ])/as.vector(scaledbetac)))
}
return(sizeratios)
}
else if (method == "leave1out") {
bycx = as.vector(bycx)
A = Aj = ajtB = bwx = t(bycx) %*% t(ac)
B = Bj = ac %*% t(ac)
sizeratios = rep(0, K1)
scaledbetac = rep(0, nc)
temp = .C("getsizeratios", as.double(A), as.double(B),
as.double(Aj), as.double(Bj), as.double(bycx), as.double(ac),
as.double(ajtB), as.double(sizeratios), as.double(scaledbetac),
as.double(bwx), as.integer(K1), as.integer(nc))
return(temp[[8]])
}
else return(0)
} |
library(biostat3)
library(dplyr)
library(rstpm2)
head(brv)
brv %>% select(couple, id, sex, doe, dosp, dox, fail) %>% filter(couple<=5) %>% arrange(couple, id)
brv <- mutate(brv, age_entry = as.numeric(doe - dob) / 365.24,
att_age = as.numeric(dox - dob) / 365.24,
t_at_risk = att_age - age_entry)
survRate(Surv(age_entry, att_age, fail) ~ sex, data=brv)
poisson22b <- glm( fail ~ sex + offset( log( t_at_risk) ), family=poisson, data=brv)
summary( poisson22b )
biostat3::eform(poisson22b)
select(brv, sex, age_entry) %>%
group_by(sex) %>%
summarise(meanAgeAtEntry = mean(age_entry))
brv2 <- mutate(brv,
id=NULL,
y_before_sp_dth = as.numeric(doe -dosp) / 365.24,
y_after_sp_dth = as.numeric(dox - dosp) / 365.24)
brvSplit <- survSplit(brv2, cut = 0, end="y_after_sp_dth", start="y_before_sp_dth", id="id",event="fail")
brvSplit <- mutate(brvSplit,
t_sp_at_risk = y_after_sp_dth - y_before_sp_dth,
brv = ifelse(y_after_sp_dth > 0, 1, 0))
brvSplit %>% select(couple, id, sex, doe, dosp, dox, fail, y_before_sp_dth, y_after_sp_dth, t_sp_at_risk) %>% filter(couple<=5) %>% arrange(couple, id)
poisson22d <- glm( fail ~ brv + offset( log(t_sp_at_risk) ), family=poisson, data=brvSplit)
summary(poisson22d)
biostat3::eform(poisson22d)
poisson22e1 <- glm( fail ~ brv + offset( log(t_sp_at_risk) ), family=poisson, data=filter(brvSplit, sex==1))
summary(poisson22e1)
biostat3::eform(poisson22e1)
poisson22e2 <- glm( fail ~ brv + offset( log(t_sp_at_risk) ), family=poisson, data=filter(brvSplit, sex==2))
summary(poisson22e2)
biostat3::eform(poisson22e2)
brvSplit2 <- mutate(brvSplit,
sex = as.factor(sex),
brv = as.factor(brv))
poisson22e3 <- glm( fail ~ sex + brv:sex + offset( log(t_sp_at_risk) ), family=poisson, data=brvSplit2)
summary(poisson22e3)
biostat3::eform(poisson22e3)
brvSplit3 <- brvSplit2 %>%
mutate(age_sp_dth = as.numeric(dosp - dob) / 365.24,
age_start = age_sp_dth + y_before_sp_dth,
age_end = age_sp_dth + y_after_sp_dth)
age_cat <- seq(70,100,5)
brvSplit4 <- survSplit(brvSplit3, cut=age_cat, start="age_start", end="age_end", event="fail", zero = 0)
brvSplit4 <- mutate(brvSplit4,
t_at_risk = age_end- age_start,
age = cut(age_end, age_cat))
survRate(Surv(t_at_risk, fail) ~ age, data=brvSplit4)
poisson22f1 <- glm( fail ~ brv + age + offset( log(t_at_risk) ), family=poisson, data=brvSplit4)
summary(poisson22f1)
biostat3::eform(poisson22f1)
poisson22f2 <- glm( fail ~ brv +age + sex + offset( log(t_at_risk) ), family=poisson, data=brvSplit4)
summary(poisson22f2)
biostat3::eform(poisson22f2)
poisson22g <- glm( fail ~ age + sex + brv:sex + offset( log(t_at_risk) ), family=poisson, data=brvSplit4)
summary(poisson22g)
biostat3::eform(poisson22g)
summary(coxph(Surv(age_start, age_end, fail) ~ brv,
data = brvSplit4))
summary(coxph(Surv(age_start, age_end, fail) ~ brv + sex,
data = brvSplit4))
summary(coxph(Surv(age_start, age_end, fail) ~ sex + sex:brv,
data = brvSplit4)) |
NULL
hisee <- function(y, ...) UseMethod("hisee")
hisee.formula <- function(formula, data=list(),
clusterID,
waves = NULL,
contrasts = NULL,
subset,
...)
{
mf <- match.call(expand.dots = FALSE)
m <- match(c("formula", "data", "clusterID", "waves", "subset"), names(mf), 0L)
mf <- mf[c(1L, m)]
if (is.null(mf$clusterID)){
mf$clusterID <- as.name("clusterID")
}
if (is.null(mf$waves)){
mf$waves <- NULL
}
mf$drop.unused.levels <- TRUE
mf[[1L]] <- quote(stats::model.frame)
mf <- eval(mf, parent.frame())
clusterID <- model.extract(mf, clusterID)
if(is.null(clusterID)){
stop("clusterID variable not found.")
}
waves <- model.extract(mf, waves)
y <- model.response(mf, "numeric")
x <- model.matrix(attr(mf, "terms"), data=mf, contrasts)
if(all(x[,1] ==1)){
x <- x[,-1]
}
if(any(colSums(x) == 0)){
cat("
cat(colnames(x)[colSums(x) == 0])
cat("\n")
stop("The above factors are not found in the given observations")
}
results <- hisee.default(y, x,
clusterID = clusterID,
waves = waves,
...)
results$call <- match.call()
results$call <- contrasts
results
}
hisee.default <- function(y, x,
waves = NULL,
...){
results <- hisee.fit(y, x,
waves = waves,
...)
results$call <- match.call()
results
}
hisee.fit <-
function(y, x, family,
clusterID, waves = NULL, groupID = 1:ncol(x),
corstr="independence", alpha = NULL,
intercept = TRUE,
offset = 0,
control = sgee.control(maxIt = 200, epsilon = 0.05,
stoppingThreshold = min(length(y), ncol(x))-intercept,
undoThreshold = 0),
standardize = TRUE,
verbose = FALSE,
...){
maxIt <- control$maxIt
epsilon <- control$epsilon
undoThreshold <- control$undoThreshold
interceptLimit <- control$interceptLimit
if(undoThreshold >= epsilon){
if(verbose){
cat(paste0("****** undoThreshold too large! reducing threshold now **********\n"))
}
undoThreshold <- epsilon/10
}
if(is.null(control$stoppingThreshold)){
stoppingThreshold <- min(length(y), ncol(x))-intercept
} else {
stoppingThreshold <- control$stoppingThreshold
}
p <- ncol(x)
if (is.character(family)){
family <- get(family, mode = "function", envir = parent.frame())
}
if (is.function(family)){
family <- family()
}
if(standardize){
unstandardizedX <- x
if(intercept){
x <- scale(x)
} else{
x <- scale(x, center = FALSE)
}
}
if(is.null(waves)){
clusz <- unlist(sapply(unique(clusterID), function(x) {sum(clusterID == x)}))
waves <- as.integer(unlist(sapply(clusz, function(x) 1:x)))
}
r <- 1
q <- 1
beta <- rep(0,p)
phi <- stats::sd(y)^2
if(is.null(alpha)){
alpha <- 0
}
beta0 <- 0
meanLink <- family$linkfun
meanLinkInv <- family$linkinv
varianceLink <- family$variance
mu.eta <- family$mu.eta
path <- matrix(rep(0,(maxIt)*(p + intercept)), nrow = maxIt)
phiPath <- matrix(rep(0,(maxIt)*r), nrow = maxIt)
alphaPath <- matrix(rep(0,(maxIt)*q), nrow = maxIt)
clusterIDs <- unique(clusterID)
numClusters <- length(clusterIDs)
maxClusterSize <- max(waves)
stoppedOn <- maxIt
R <- genCorMat(corstr = corstr, rho = alpha, maxClusterSize = maxClusterSize)
RInv <- solve(R)
cat("\n")
oldDelta <- rep(0, length(beta))
it <- 0
while (it <maxIt){
it <- it +1
if(verbose){
cat(paste0("****** Beginning iteration
}
GEEValues <- evaluateGEE(y = y,
x = x,
beta = beta,
beta0 = beta0,
intercept,
phi = phi,
offset = offset,
RInv = RInv,
numClusters = numClusters,
clusterID = clusterID,
waves = waves,
meanLinkInv = meanLinkInv,
mu.eta = mu.eta,
varianceLink = varianceLink,
corstr = corstr,
maxClusterSize = maxClusterSize,
interceptLimit = interceptLimit)
beta0 <- GEEValues$beta0
phi <- GEEValues$phiHat
alpha <- GEEValues$rhoHat
RInv <- GEEValues$RInv
sumMean <- GEEValues$sumMean
a <- rep(0, length(unique(groupID)))
for (j in unique(groupID)){
currentGroupIndex <- groupID == j
aCurrent <- sumMean[currentGroupIndex]
a[j] <- sqrt(sum(aCurrent^2))/sqrt(length(aCurrent))
}
delta <- which(a == max(a))
theGroup <- groupID == delta
aCurrent <- sumMean[theGroup]
maxGradient <- max(abs(aCurrent))
deltaIndex <- abs(aCurrent) == maxGradient
if(verbose){
}
if (sum(abs(oldDelta[theGroup] + (deltaIndex * epsilon * sign(aCurrent[deltaIndex]))))<= undoThreshold){
if(verbose){
cat(paste0("****** Step Undone! Reducing Stepsize **********\n"))
}
if(it>2){
if (intercept){
beta <- path[it - 2,-1]
} else {
beta <- path[it - 2,]
}
} else{
beta <- rep(0, length(beta))
}
epsilon <- epsilon/2
it <- it - 2
oldDelta <- rep(0, length(beta))
if(undoThreshold >= epsilon){
if(verbose){
cat(paste0("****** undoThreshold too large! reducing threshold now **********\n"))
}
undoThreshold <- epsilon/10
}
} else {
oldDelta <- rep(0, length(beta))
oldDelta[theGroup] <- (deltaIndex * epsilon * sign(aCurrent[deltaIndex]))
beta[theGroup] <- beta[theGroup] + (deltaIndex * epsilon * sign(aCurrent[deltaIndex]))
if(intercept){
path[it,] <- c(beta0, beta)
}
else{
path[it,] <- beta
}
phiPath[it,] <- phi
alphaPath[it,] <- alpha
if(((sum(beta != 0) >= stoppingThreshold) | sum(a) < 0.5 )& (it< maxIt) ){
print("stopped on")
print(it)
print(a[delta])
path[((it+1):maxIt),] <- matrix(rep(path[it,],(maxIt - it)),
nrow = (maxIt - it),
byrow = TRUE)
phiPath[((it+1):maxIt),] <- matrix(rep(phiPath[it,],(maxIt - it)),
nrow = (maxIt - it),
byrow = TRUE)
alphaPath[((it+1):maxIt),] <- matrix(rep(alphaPath[it,],(maxIt - it)),
nrow = (maxIt - it),
byrow = TRUE)
stoppedOn <- it
break
}
}
}
result <- list(path = path,
gammaPath = phiPath,
alphaPath = alphaPath,
stoppedOn = stoppedOn,
maxIt = maxIt,
y = y,
x = x,
intercept = intercept,
clusterID = clusterID,
groupID = groupID,
family = family,
offset = offset,
epsilon = epsilon)
if(standardize){
result$x <- unstandardizedX
temp <- path
if(intercept){
temp[,-1] <- t(t(path[,-1]) /attr(x, "scaled:scale"))
temp[,1] <- path[,1] - crossprod(t(path[,-1]),
(attr(x, "scaled:center")/attr(x, "scaled:scale")))
} else{
temp <- t(t(path) /attr(x, "scaled:scale"))
}
result$standardizedPath <- path
result$path <- temp
result$standardizedX <- x
}
class(result) <- "sgee"
result
} |
.pi_T_sample <- function(scaled_doses, n = 10000,
alpha_mean, alpha_sd,
beta_mean, beta_sd) {
alpha <- rnorm(n, alpha_mean, alpha_sd)
beta <- rnorm(n, beta_mean, beta_sd)
A <- as.matrix(data.frame(alpha, beta))
B <- as.matrix(data.frame(1, scaled_doses))
inv.logit(A %*% t(B))
}
.pi_T_moments <- function(scaled_doses, n = 10000,
alpha_mean, alpha_sd,
beta_mean, beta_sd) {
samp <- .pi_T_sample(scaled_doses, n, alpha_mean, alpha_sd, beta_mean,
beta_sd)
list(
mean = colMeans(samp),
sd = apply(samp, 2, sd)
)
}
.pi_E_sample <- function(scaled_doses, n = 10000,
gamma_mean, gamma_sd,
zeta_mean, zeta_sd,
eta_mean, eta_sd) {
gamma <- rnorm(n, gamma_mean, gamma_sd)
zeta <- rnorm(n, zeta_mean, zeta_sd)
eta <- rnorm(n, eta_mean, eta_sd)
A <- as.matrix(data.frame(gamma, zeta, eta))
B <- as.matrix(data.frame(1, scaled_doses, scaled_doses^2))
inv.logit(A %*% t(B))
}
.pi_E_moments <- function(scaled_doses, n = 10000,
gamma_mean, gamma_sd,
zeta_mean, zeta_sd,
eta_mean, eta_sd) {
samp <- .pi_E_sample(scaled_doses, n, gamma_mean, gamma_sd, zeta_mean,
zeta_sd, eta_mean, eta_sd)
list(mean = colMeans(samp), sd = apply(samp, 2, sd))
}
.normal_ess <- function(mean, sd) {
a <- (1 - mean) * (mean / sd)^2 - mean
b <- a * (1 - mean) / mean
list(a = a, b = b, ess = a + b)
}
.ess <- function(pi_star) {
x <- sapply(
1:length(pi_star$mean),
function(i) .normal_ess(pi_star$mean[i], pi_star$sd[i])$ess
)
mean(x)
}
get_efftox_priors <- function(doses = NULL, scaled_doses = NULL,
pi_T, ess_T, pi_E, ess_E, num_samples = 10^4,
seed = 123) {
if(is.null(scaled_doses)) {
if(is.null(doses)) {
stop('Either doses or scaled_doses should be a numerical vector.')
} else {
y <- log(doses) - mean(log(doses))
}
} else {
y <- scaled_doses
}
.f <- function(x) {
set.seed(seed)
pi_T_star <- .pi_T_moments(scaled_doses = y, n = num_samples,
alpha_mean = x[1], alpha_sd = x[2],
beta_mean = x[3], beta_sd = x[4])
ess_T_star <- .ess(pi_T_star)
pi_E_star <- .pi_E_moments(scaled_doses = y, n = num_samples,
gamma_mean = x[5], gamma_sd = x[6],
zeta_mean = x[7], zeta_sd = x[8],
eta_mean = 0, eta_sd = 0.2)
ess_E_star <- .ess(pi_E_star)
obj <- sum((pi_T_star$mean - pi_T)^2) + sum((pi_E_star$mean - pi_E)^2)
obj <- obj + 0.1 * ((ess_T_star - ess_T)^2 + (ess_E_star - ess_E)^2)
obj <- obj + 0.2 * ((x[2] - x[4])^2 + (x[6] - x[8])^2)
obj
}
par <- c(0, 1, 0, 1, 0, 1, 0, 1)
x <- optim(par, fn = .f, method = "Nelder-Mead")
efftox_priors(alpha_mean = x$par[1], alpha_sd = x$par[2],
beta_mean = x$par[3], beta_sd = x$par[4],
gamma_mean = x$par[5], gamma_sd = x$par[6],
zeta_mean = x$par[7], zeta_sd = x$par[8],
eta_mean = 0, eta_sd = 0.2,
psi_mean = 0, psi_sd = 1)
} |
read.bin <- function(binfile,
outfile = NULL,
start = NULL,
end = NULL,
Use.Timestamps = FALSE,
verbose = TRUE,
do.temp = TRUE,
do.volt = TRUE,
calibrate = TRUE,
downsample = NULL,
blocksize,
virtual = FALSE,
mmap.load = (.Machine$sizeof.pointer >= 8),
pagerefs = TRUE, ...){
invisible(gc())
requireNamespace("mmap")
options(warn = -1)
if (verbose){options(warn=0)}
opt.args <- c("gain","offset","luxv","voltv", "warn")
warn <- FALSE
gain <- offset <- NULL
luxv <- voltv <- NULL
argl <- as.list(match.call())
argind <- pmatch(names(argl),opt.args)
argind <- which(!is.na(argind))
if (length(argind) > 0){
called.args <- match.arg(names(argl),
opt.args,
several.ok = TRUE)
for(i in 1:length(called.args)){
assign(called.args[i],
eval(argl[[argind[i]]]))
}
}
nobs <- 300
reclength <- 10
position.data <- 10
position.temperature <- 6
position.volts <- 7
orig.opt <- options(digits.secs = 3)
pos.rec1 <- npages <- t1c <- t1midnight <- pos.inc <- headlines <- NA
header = header.info(binfile, more = T)
commasep = unlist(header)[17] == ","
H = attr(header, "calibration")
for (i in 1:length(H)) assign(names(H)[i], H[[i]])
if ((!exists("pos.rec1")) || (is.na(pos.rec1))) mmap.load = FALSE
if ((mmap.load == T) &&
(length(pagerefs)) < 2) {
pagerefs = TRUE
}
if (missing(blocksize)){
blocksize = Inf
if (npages > 10000) blocksize = 10000
}
freqint = round(freq)
if (!is.null(downsample)) {
if (verbose) {
cat("Downsampling to ", round(freq/downsample[1],2) , " Hz \n")
if (nobs %% downsample[1] != 0)
cat("Warning, downsample divisor not factor of ", nobs, "!\n")
if ( downsample[1] != floor( downsample[1]) )
cat("Warning, downsample divisor not integer!\n")
}
}
if (verbose) {
cat("Number of pages in binary file:", npages, "\n")
}
freqseq <- seq(0, by = 1/freq, length = nobs)
timespan <- nobs/freq
timestampsc <- seq(t1c, by = timespan, length = npages)
timestamps <- seq(t1, by = timespan, length = npages)
tnc <- timestampsc[npages]
tn <- timestamps[npages]
if (Use.Timestamps == TRUE){
start_precise = start
end_precise = end
}
if (is.null(start)) {
start <- 1
}
if (is.null(end)) {
end <- npages
}
if (Use.Timestamps == TRUE){
if (start >= 0 &
start <= 1 &
!missing(start)){
stop("Please eneter the start parameter as a timestamp if using Use.Timestamps = TRUE")
}
if (end >= 0 &
end <= 1 &
!missing(end)){
stop("Please eneter the end parameter as a timestap if using Use.Timestamps = TRUE")
}
if (is.numeric(start)){
start = findInterval(start - 0.5, timestamps, all.inside = T)
t1 = timestamps[start+1]
} else{
stop(cat("Please enter the start as a numeric timestamp"))
}
if (is.numeric(end)){
end = findInterval(end, timestamps, all.inside = T) +1
} else{
stop(cat("Please enter the start as a numeric timestamp"))
}
} else{
if (is.numeric(start)) {
if ((start[1] > npages)) {
stop(cat("Please input valid start and end times between ",
t1c, " and ", tnc, " or pages between 1 and ",
npages, ".\n\n"), call. = FALSE)
} else if (start[1] < 1) {
start = pmax(ceiling( start * npages),1)
}
}
if (is.numeric(end)) {
if ((end[1] <= 1)) {
end= ceiling(end * npages)
}
else {
end <- pmin(end, npages)
}
}
if (is.character(start)) {
start <- parse.time(start,
format = "seconds",
start = t1,
startmidnight = t1midnight)
start = findInterval(start - 0.5,
timestamps,
all.inside = T)
t1 = timestamps[start+1]
}
if (is.character(end)) {
end <- parse.time(end, format = "seconds", start = t1, startmidnight = t1midnight)
end = findInterval(end, timestamps, all.inside = T) +1
}
}
index <- NULL
for (i in 1:length(start)){
index = c(index, start[i]:end[i])
}
if (length(index) == 0) {
if (npages > 15) {
stop("No pages to process with specified timestamps. Please try again.\n",
call. = FALSE)
}
else {
stop("No pages to process with specified timestamps.
Please try again. Timestamps in binfile are:\n\n",
paste(timestampsc, collapse = " \n"), " \n\n",
call. = FALSE)
}
}
if (do.temp) {
temperature <- NULL
}
if (calibrate) {
if (!is.null(gain)) {
if (!is.numeric(gain)) {
stop("Please enter 3 valid values for the x,y,z gains.\n")
}
else {
xgain <- gain[1]
ygain <- gain[2]
zgain <- gain[3]
}
}
if (!is.null(offset)) {
if (!is.numeric(offset)) {
stop("Please enter 3 valid values for the x,y,z offsets.\n")
}
else {
xoffset <- offset[1]
yoffset <- offset[2]
zoffset <- offset[3]
}
}
if (!is.null(voltv)) {
if (!is.numeric(voltv)) {
stop("Please enter a valid value for the volts.\n")
}
else {
volts <- voltv
}
}
if (!is.null(luxv)) {
if (!is.numeric(luxv)) {
stop("Please enter a valid value for the lux.\n")
}
else {
lux <- luxv
}
}
}
nstreams <- length(index)
if(warn){
if (nstreams > 100) {
cat("About to read and process", nstreams, "datasets. Continue? Press Enter or control-C to quit.\n")
scan(, quiet = TRUE)
}
}
data <- NULL
if (mmap.load) {
numstrip <- function(dat, size = 4, sep = "." ){
apply(matrix(dat, size), 2, function(t)
as.numeric(sub(sep, ".", rawToChar(as.raw(t[t != 58])), fixed = TRUE)))
}
offset = pos.rec1 - 2
rec2 = offset + pos.inc
if ((identical(pagerefs , FALSE)) || is.null(pagerefs)){
pagerefs = NULL
} else if (length(pagerefs) < max(index)){
textobj = mmap(binfile, char(), prot = mmapFlags("PROT_READ"))
if (is.mmap(textobj)){
startoffset = max(pagerefs, offset) + pos.inc
if (identical(pagerefs, TRUE)) pagerefs = NULL
numblocks2 = 1
blocksize2 = min(blocksize, max(index+1))*3600
if ( (length(textobj) - startoffset) > blocksize2 ){
numblocks2 = ceiling((length(textobj) - startoffset) /blocksize2)
}
curr = startoffset
for (i in 1:numblocks2){
pagerefs = c(pagerefs, grepRaw("Recorded Data",
textobj[curr + 1: min(blocksize2, length(textobj) - curr)],
all = T)+ curr-2)
curr = curr + blocksize2
if (length(pagerefs) >= max(index)) break
}
if (curr >= length(textobj)){
pagerefs = c(pagerefs, length(textobj) - grepRaw("[0-9A-Z]",
rev(textobj[max(pagerefs):length(textobj)]))+2)
}
if (verbose) cat("Calculated page references... \n")
munmap(textobj)
invisible(gc())
} else {
pagerefs = NULL
warning("Failed to compute page refs")
}
}
mmapobj = mmap(binfile, uint8(), prot = mmapFlags("PROT_READ"))
if (!is.mmap(mmapobj)){
warning("MMAP failed, switching to ReadLine. (Likely insufficient address space)")
mmap.load = FALSE
}
if (is.null(pagerefs)){
print("WARNING: Estimating data page references. This can fail if data format is unusual!")
digitstring = cumsum(c(offset,10*(pos.inc), 90 *(pos.inc + 1) ,
900 *( pos.inc +2 ), 9000*(pos.inc +3) ,
90000*(pos.inc +4) , 900000*(pos.inc +5),
9000000 * (pos.inc + 6)))
digitstring[1] = digitstring[1] + pos.inc
getindex = function(pagenumbers, raw = F ){
digits = floor(log10(pagenumbers))
if (raw){
return( digitstring[digits+1] + (pagenumbers - 10^digits)*(pos.inc+digits ))
} else {
return( rep(digitstring[digits+1] + (pagenumbers - 10^digits)*(pos.inc+digits),
each = nobs * 12) -((nobs*12):1))
}
}
} else {
getindex = function(pagenumbers, raw = F){
if (raw){
return(pagerefs[pagenumbers])
}else{
return(rep(pagerefs[pagenumbers], each = nobs * 12 ) -((nobs*12):1))
}
}
}
} else{
fc2 = file(binfile, "rt")
tmpd <- readLines(fc2, n = headlines)
replicate ( min( index - 1 ), is.character(readLines(fc2, n=reclength)))
}
numblocks = 1
blocksize = min(blocksize, nstreams)
if (nstreams > blocksize ){
if (verbose) cat("Splitting into ", ceiling(nstreams/blocksize), " chunks.\n")
numblocks = ceiling(nstreams/blocksize)
}
Fulldat = NULL
Fullindex = index
index.orig = index
if (verbose) {
cat("Processing...\n")
pb <- txtProgressBar(min = 0, max = 100,style = 1)
}
start.proc.time <- Sys.time()
if(!is.null(downsample)){
downsampleoffset = 1
if (length(downsample) == 2){
downsampleoffset = downsample[2]
downsample = downsample[1]
}
}
if (virtual){
if (is.null(downsample)) downsample = 1
if (verbose) close(pb)
if (exists("fc2")) close(fc2)
if (exists("mmapobj")) munmap(mmapobj)
Fulldat = timestamps[index]
if (verbose) cat("Virtually loaded",
length(Fulldat)*length(freqseq)/downsample,
"records at", round(freq/downsample,2),
"Hz (Will take up approx ",
round(56 * as.double(length(Fulldat) * length(freqseq)/downsample )/1000000)
,"MB of RAM)\n")
if (verbose) cat(format.GRtime(Fulldat[1],
format = "%y-%m-%d %H:%M:%OS3 (%a)")," to ", format.GRtime(tail(Fulldat,1) +
nobs /freq,format = "%y-%m-%d %H:%M:%OS3 (%a)"), "\n")
output = list(data.out = Fulldat,
page.timestamps = timestampsc[index.orig],
freq= as.double(freq)/downsample,
filename =tail(strsplit(binfile, "/")[[1]],1),
page.numbers = index.orig,
call = argl,
nobs = floor(length(freqseq)/downsample) ,
pagerefs = pagerefs, header = header)
class(output) = "VirtAccData"
return(invisible( output ))
}
voltages = NULL
lastread = min(index) - 1
for (blocknumber in 1: numblocks){
index = Fullindex[1:min(blocksize, length(Fullindex))]
Fullindex = Fullindex[-(1:blocksize)]
proc.file <- NULL
if (!mmap.load){
tmpd <- readLines(fc2, n = (max(index) -lastread) * reclength )
bseq = (index - lastread -1 ) * reclength
lastread = max(index)
if (do.volt){
vdata = tmpd[bseq + position.volts]
if (commasep) vdata = sub(",", ".", vdata, fixed = TRUE)
voltages = c(voltages, as.numeric(substring(vdata, 17, nchar(vdata))))
}
if (is.null(downsample)){
data <- strsplit(paste(tmpd[ bseq + position.data], collapse = ""), "")[[1]]
if (do.temp) {
tdata <- tmpd[bseq + position.temperature]
if (commasep) tdata = sub(",", ".", tdata, fixed = TRUE)
temp <- as.numeric(substring(tdata, 13, nchar(tdata)))
temperature <- rep(temp, each = nobs)
}
rm(tmpd)
proc.file <- convert.hexstream(data)
nn <- rep(timestamps[index], each = length(freqseq)) + freqseq
} else {
data <- strsplit(paste(tmpd[ bseq + position.data], collapse = ""), "")[[1]]
if (do.temp) {
tdata <- tmpd[bseq + position.temperature]
if (commasep) tdata = sub(",", ".", tdata, fixed = TRUE)
temp <- as.numeric(substring(tdata, 13, nchar(tdata)))
temperature <- rep(temp, each = nobs)
}
rm(tmpd)
proc.file <- convert.hexstream(data)
nn <- rep(timestamps[index], each = length(freqseq)) + freqseq
positions = downsampleoffset +
(0: floor(( nobs * length(index) - downsampleoffset )/downsample)) * downsample
proc.file = proc.file[, positions]
if (do.temp){
temperature = temperature[positions]
}
nn = nn[positions]
downsampleoffset = downsample - (nobs*blocksize - downsampleoffset )%% downsample
}
} else {
infeed = getindex(index)
infeed = infeed[!is.na(infeed)]
tmp = mmapobj[infeed]
proc.file = convert.intstream(tmp)
pageindices = getindex(index, raw = T)
firstrec = as.raw(mmapobj[pageindices[1]:pageindices[2]])
a = grepRaw("Temperature:", firstrec)
b = grepRaw(ifelse(commasep, ",", "."), firstrec, offset = a, fixed = TRUE)
c = grepRaw("Battery voltage:", firstrec, offset = b)
d = grepRaw("Device", firstrec, offset = c)
tind = (b-2):(c-2) - length(firstrec)
vind = (c+16):(d-2) - length(firstrec)
if (do.temp){
tempfeed = rep(pageindices, each = length(tind)) + tind
tempfeed = tempfeed[!is.na(tempfeed)]
temperature = rep(numstrip(mmapobj[tempfeed],
size = length(tind), sep = ifelse(commasep, ",", ".") ),
each = nobs)
}
nn <- rep(timestamps[index], each = length(freqseq)) + freqseq
if (!is.null(downsample)){
positions = downsampleoffset +
(0: floor(( nobs * length(index) - downsampleoffset )/downsample)) * downsample
proc.file = proc.file[, positions]
nn = nn[positions]
if (do.temp){
temperature = temperature[positions]
}
downsampleoffset = downsample - (nobs*blocksize - downsampleoffset) %% downsample
}
if (do.volt){
voltfeed = rep(pageindices, each = length(vind)) + vind
voltfeed = voltfeed[!is.na(voltfeed)]
voltages = c(voltages, numstrip(mmapobj[voltfeed],
size = length(vind) , sep = ifelse(commasep, ",", ".")) )
}
}
if (verbose) setTxtProgressBar(pb, 100 * (blocknumber-0.5) / numblocks )
if (calibrate) {
proc.file[1, ] <- (proc.file[1, ] * 100 - xoffset)/xgain
proc.file[2, ] <- (proc.file[2, ] * 100 - yoffset)/ygain
proc.file[3, ] <- (proc.file[3, ] * 100 - zoffset)/zgain
proc.file[4, ] <- proc.file[4, ] * lux/volts
}
if ( length(proc.file[1,]) < length(nn)){
nn = nn[1:(length((proc.file[1,])))]
}
proc.file <- t(proc.file)
proc.file <- cbind(nn, proc.file)
cnames <- c("timestamp", "x", "y", "z", "light", "button")
if (do.temp) {
proc.file <- cbind(proc.file, temperature)
colnames(proc.file) <- c(cnames, "temperature")
}
else {
colnames(proc.file) <- cnames
}
Fulldat = rbind(Fulldat, proc.file)
if (verbose) setTxtProgressBar(pb, 100 * blocknumber / numblocks)
}
if (verbose) close(pb)
freq = freq * nrow(Fulldat) / (nobs * nstreams)
end.proc.time <- Sys.time()
cat("Processing took:", format(round(as.difftime(end.proc.time -
start.proc.time), 3)), ".\n")
cat("Loaded", nrow(Fulldat), "records (Approx ",
round(object.size(Fulldat)/1000000) ,"MB of RAM)\n")
cat(format.GRtime( Fulldat[1,1], format = "%y-%m-%d %H:%M:%OS3 (%a)"),
" to ", format.GRtime(tail(Fulldat[,1],1) , format = "%y-%m-%d %H:%M:%OS3 (%a)"), "\n")
if (!mmap.load){
close(fc2)
} else {
munmap(mmapobj)
}
if (Use.Timestamps == TRUE){
Fulldat = Fulldat[Fulldat[,1] >= start_precise &
Fulldat[,1] <= end_precise, ]
}
processedfile <- list(data.out = Fulldat,
page.timestamps = timestampsc[index.orig],
freq = freq,
filename = tail(strsplit(binfile, "/")[[1]],1),
page.numbers = index.orig,
call = argl,
page.volts = voltages,
pagerefs = pagerefs,
header = header)
class(processedfile) = "AccData"
if (is.null(outfile)) {
return(processedfile)
}
else {
save(processedfile, file = outfile)
}
}
convert.hexstream <-function(stream){
maxint <- 2^(12-1)
packet <-bitShiftL(strtoi(stream, 16),4*(2:0))
packet<-rowSums(matrix(packet,ncol=3,byrow=TRUE))
packet[packet>=maxint] <- -(maxint - (packet[packet>=maxint] - maxint))
packet<-matrix(packet, nrow=4)
packet1 <- bitShiftL(strtoi(stream, 16),4*(2:0))
packet1 <-rowSums(matrix(packet1,ncol=3,byrow=TRUE))
maxint1 = 2^12
packet1[packet1>=maxint1] <- -(maxint1 - (packet1[packet1>=maxint1] - maxint1))
packet1<-matrix(packet1, nrow=4)
light <- bitShiftR(packet1[4,],2)
button <-bitShiftR(bitAnd(packet[4,],2),1)
packet<-rbind(packet[1:3,],light,button)
packet
}
convert.intstream <- function(stream){
maxint <- 2^(12 - 1)
stream1 = stream - 48 - 7 * (stream > 64)
packet<- drop(matrix(stream1, ncol = 3, byrow = T) %*% 16^(3: 1 - 1))
packet[packet>=maxint] <- -2*maxint + (packet[packet>=maxint] )
packet<-matrix(packet,nrow=4)
maxint1 <- 2^(12)
stream2 = stream - 48 - 7 * (stream > 64)
packet1<- drop(matrix(stream2, ncol = 3, byrow = T) %*% 16^(3: 1 - 1))
packet1[packet1>=maxint1] <- -2*maxint1 + (packet1[packet1>=maxint1] )
packet1<-matrix(packet1,nrow=4)
light = abs(floor(packet1[4,] / 4 -> ltmp))
rbind(packet[1:3,], light, (ltmp-light) >0.49)
}
is.POSIXct <- function(x) inherits(x, "POSIXct")
is.POSIXlt <- function(x) inherits(x, "POSIXlt")
is.POSIXt <- function(x) inherits(x, "POSIXt")
is.Date <- function(x) inherits(x, "Date") |
sourceCppFunction <- function(func, isVoid, dll, symbol) {
args <- names(formals(func))
body <- quote(CALL_PLACEHOLDER(EXTERNALNAME, ARG))[c(
1:2,
rep(3, length(args))
)]
for (i in seq(along.with = args)) body[[i + 2]] <- as.symbol(args[i])
body[[1L]] <- .Call
body[[2L]] <- getNativeSymbolInfo(symbol, dll)$address
if (isVoid) {
body <- call("invisible", body)
}
body(func) <- body
func
} |
test_that("genind2genpop works with missing loci", {
data(nancycats)
p17 <- nancycats[pop = 17, loc = 3:4]
p <- genind2genpop(p17)
expect_s4_class(p, "genpop")
ptab <- tab(p, freq = TRUE)
expect_equal(nrow(ptab), 1L)
expect_equal(ncol(ptab), sum(nAll(p17)))
expect_false(any(is.na(ptab)))
}) |
stepwise.PIC <- function(x, py, nvarmax = 100, alpha = 0.1) {
x <- as.matrix(x)
n <- nrow(x)
npy <- ncol(py)
cpy <- cpyPIC <- NULL
icpy <- 0
z <- NULL
isig <- T
icoloutz <- 1:npy
while (isig) {
npicmax <- npy - icpy
pictemp <- rep(0, npicmax)
y <- py[, icoloutz]
pictemp <- pic.calc(x, as.matrix(y), z)$pic
ctmp <- order(-pictemp)[1]
cpytmp <- icoloutz[ctmp]
picmaxtmp <- pictemp[ctmp]
if (!is.null(z)) {
df <- n - ncol(z)
} else {
df <- n
}
t <- qt(1 - alpha, df = df)
picthres <- sqrt(t^2 / (t^2 + df))
if (picmaxtmp > picthres) {
cpy <- c(cpy, cpytmp)
cpyPIC <- c(cpyPIC, picmaxtmp)
z <- cbind(z, py[, cpytmp])
icoloutz <- icoloutz[-ctmp]
icpy <- icpy + 1
if ((npy - icpy) == 0 | icpy >= nvarmax) isig <- F
} else {
isig <- F
if (icpy == 0 & picmaxtmp > 0) {
cpy <- cpytmp
cpyPIC <- picmaxtmp
z <- py[, cpytmp]
}
}
}
if (!is.null(z)) {
out <- pw.calc(x, py, cpy, cpyPIC)
outwt <- out$pw
lstwt <- abs(lsfit(z, x)$coef)
return(list(
cpy = cpy, cpyPIC = cpyPIC,
wt = outwt, lstwet = lstwt,
icpy = icpy
))
} else {
message("None of the provided predictors is related to the response variable")
}
}
calc.scaleSTDratio <- function(x, zin, zout) {
if (!missing(zout)) {
xhat <- knnregl1cv(x, zout)
stdratxzout <- sqrt(var(x - xhat) / var(x))
zinhat <- knnregl1cv(zin, zout)
stdratzinzout <- sqrt(var(zin - zinhat) / var(zin))
return(0.5 * (stdratxzout + stdratzinzout))
} else {
return(1)
}
}
pic.calc <- function(X, Y, Z = NULL) {
if (is.null(Z)) {
x.in <- X
y.in <- Y
} else {
x.in <- X - knnregl1cv(X, Z)
y.in <- apply(Y, 2, function(i) i - knnregl1cv(i, Z))
}
pmi <- apply(y.in, 2, function(i) pmi.calc(x.in, i))
tmp <- pmi
tmp[tmp < 0] <- 0
pic <- sqrt(1 - exp(-2 * tmp))
return(list(pmi = as.numeric(pmi), pic = as.numeric(pic)))
}
pw.calc <- function(x, py, cpy, cpyPIC) {
wt <- NA
Z <- as.matrix(py[, cpy])
if (ncol(Z) == 1) {
wt <- calc.scaleSTDratio(x, Z) * cpyPIC
if (wt == 0) wt <- 1
} else {
for (i in seq_along(cpy)) wt[i] <- calc.scaleSTDratio(x, Z[, i], Z[, -i]) * cpyPIC[i]
}
return(list(pw = wt / sum(wt)))
}
knnregl1cv <- function(x, z, k = 0, pw) {
x <- as.matrix(x)
n <- nrow(x)
if (k == 0) {
k <- floor(0.5 + 3 * (sqrt(n)))
}
z <- as.matrix(z)
nz <- ncol(z)
sd <- sqrt(diag(var(z)))
if (missing(pw)) {
pw <- rep(1, nz)
}
for (j in 1:nz) z[, j] <- z[, j] / (sd[j] / pw[j])
d <- as.matrix(dist(z))
ord1 <- apply(d, 2, order)
ord <- ord1[2:(k + 1), ]
kern <- 1 / (1:k) / sum(1 / (1:k))
xhat <- rep(0, n)
for (j in 1:k) xhat <- xhat + x[ord[j, ]] * kern[j]
return(xhat)
}
pmi.calc <- function(X, Y) {
N <- length(X)
pdf.X <- kernel.est.uvn(X)
pdf.Y <- kernel.est.uvn(Y)
pdf.XY <- kernel.est.mvn(cbind(X, Y))
calc <- log(pdf.XY / (pdf.X * pdf.Y))
return(sum(calc) / N)
}
kernel.est.uvn <- function(Z) {
N <- length(Z)
sigma <- 1.5 * bw.nrd0(Z)
constant <- sqrt(2 * pi) * sigma * N
dens <- vapply(1:N, function(i) sum(exp(-(Z - Z[i])^2 / (2 * sigma^2))) / constant, numeric(1))
return(dens)
}
kernel.est.mvn <- function(Z) {
N <- nrow(Z)
d <- ncol(Z)
Cov <- cov(Z)
det.Cov <- det(Cov)
sigma <- 1.5 * (4 / (d + 2))^(1 / (d + 4)) * N^(-1 / (d + 4))
constant <- (sqrt(2 * pi) * sigma)^d * sqrt(det.Cov) * N
dens <- vapply(1:N, function(i) sum(exp(-mahalanobis(Z, center = Z[i, ], cov = Cov) / (2 * sigma^2))) / constant, numeric(1))
return(dens)
} |
mox.tree <- function(tree,...)
{
info.node=list()
type=NULL
terminal=NULL
perc=NULL
var=NULL
mox=NULL
if(length(tree@nodes)>1)
{
for (n in tree@nodes)
{
if (n@id==1)
{
length.root=length(n@elements)
}
if (length(n@childs)>0)
{
info.node[[length(info.node)+1]]=data.frame(n@info@variable,n@id,n@childs)
}
if(length(n@childs)==0)
{
type="leaf"
terminal="yes"
}
if(n@father==0)
{
type="root"
terminal="no"
}
if(n@father!=0 && length(n@childs)!=0)
{
type="node"
terminal="no"
}
perc=round((length(n@elements)/length.root)*100,2)
data=data.frame(n@id,n@father,showDeepth(n),type,terminal,length(n@elements),perc)
mox=rbind(mox,data)
}
data.info.node=NULL
for(i in 1:length(info.node)){data.info.node=rbind(data.info.node,info.node[[i]])}
names(data.info.node)[2]="n.father"
names(data.info.node)[3]="n.id"
MOX=merge(mox, data.info.node,by="n.id",all.x=TRUE)[,-9]
names(MOX)=c("Node","Parent","Depth","Type","Terminal","Size","Percent","Variable","Category")
MOX
}
else
{
MOX=NULL
}
return(MOX)
} |
mewma.ad <- function(l, cE, p, delta=0, r=20, n=20, type="cond", hs=0, ntype=NULL, qm0=20, qm1=qm0) {
if ( l<=0 | l>1 ) stop("l has to be between 0 and 1")
if ( cE<=0 ) stop("threshold c has to be positive")
if ( p<1 ) stop("wrong dimension parameter")
if ( delta<0 ) stop("wrong magnitude value")
if ( r<4 ) stop("resolution too small")
if ( n<5 ) stop("more quadrature nodes needed")
itype <- pmatch(tolower(type), c("cond", "cycl")) - 1
if ( is.na(itype) ) stop("wrong type of steady-state density")
if ( hs<0 ) stop("wrong head start value")
if ( r<4 ) stop("resolution too small")
if ( qm0<5 ) stop("more quadrature nodes needed")
if ( qm1<5 ) stop("more quadrature nodes needed")
if ( is.null(ntype) ) {
if ( delta <1e-10 ) {
ntype <- "gl2"
} else {
if ( p==2 ) {
ntype <- "gl3"
} else {
ntype <- "gl5"
}
}
}
qtyp <- pmatch(tolower(ntype), c("gl", "co", "ra", "cc", "mc", "sr", "co2", "gl2", "gl3", "gl4", "gl5", "co3", "co4", "ngl1", "ngl2", "ngl3", "ngl4", "ngl5")) - 1
if ( is.na(qtyp) ) stop("invalid type of numerical algorithm")
ad <- .C("mewma_ad", as.double(l), as.double(cE), as.integer(p), as.double(delta), as.integer(r),
as.integer(n), as.integer(itype), double(hs), as.integer(qtyp), as.integer(qm0), as.integer(qm1),
ans=double(length=1), PACKAGE="spc")$ans
names(ad) <- NULL
ad
} |
svc <- paws::codestarnotifications()
test_that("list_event_types", {
expect_error(svc$list_event_types(), NA)
})
test_that("list_event_types", {
expect_error(svc$list_event_types(MaxResults = 20), NA)
})
test_that("list_notification_rules", {
expect_error(svc$list_notification_rules(), NA)
})
test_that("list_notification_rules", {
expect_error(svc$list_notification_rules(MaxResults = 20), NA)
})
test_that("list_targets", {
expect_error(svc$list_targets(), NA)
})
test_that("list_targets", {
expect_error(svc$list_targets(MaxResults = 20), NA)
}) |
setMethod("initialize","value.labels",function(.Object,...){
args <- list(...)
values <- args$values
labels <- args[[1]]
ii <- order(values)
values <- values[ii]
labels <- labels[ii]
[email protected] <- labels
.Object@values <- values
if(validObject(.Object)) return(.Object)
})
setValidity("value.labels",function(object){
if(length([email protected])==length(object@values)){
if(length(unique([email protected]))<=length(unique(object@values))) TRUE
else paste("More labels than labelled values:\n",
" ",length(unique([email protected])),"unique labels\n",
" ",length(unique(object@values)),"labelled values")
}
else paste("There are",length(object@values),"values, but",
length([email protected]),"labels")
})
setMethod("labels","NULL",function(object,...)NULL)
setMethod("labels","item",function(object,...)[email protected])
setMethod("labels<-",signature(x="item",value="ANY"),function(x,value){
[email protected]<-as(value,"value.labels")
x
})
setMethod("labels<-",signature(x="ANY",value="NULL"),function(x,value){
x
})
setMethod("labels<-",signature(x="item",value="NULL"),function(x,value){
[email protected]<-NULL
x
})
setMethod("labels<-",signature(x="vector",value="ANY"),function(x,value)as.item(x,
labels=as(value,"value.labels")))
format.value.labels <- function(x,...){
paste(format(x@values,justify="right"),format(sQuote([email protected]),justify="left"))
}
print.value.labels <- function(x,...) writeLines(format.value.labels(x))
setMethod("show","value.labels",function(object){
writeLines(c("",
" Values and labels:",
"",
paste(" ",format.value.labels(object)),
""))
})
setMethod("[",signature(x="value.labels",i="numeric",j="missing",drop="missing"),
function(x,i) new("value.labels",[email protected][i], values=x@values[i])
)
setMethod("[",signature(x="value.labels",i="logical",j="missing",drop="missing"),
function(x,i)
new("value.labels",[email protected][i], values=x@values[i]))
setAs(from="numeric",to="value.labels",function(from,to){
if(length(names(from))){
if(any(dups <- duplicated(names(from))))
warning("Duplicate labels ",
paste(sQuote(unique(names(from)[dups])),collapse=" "),
call.=FALSE)
if(any(duplicated(from))) warning("Duplicate values",call.=FALSE)
new("value.labels",names(from),values=unname(from))
}
else new("value.labels",character(0),values=logical(0))
})
setAs(from="character",to="value.labels",function(from,to){
if(length(names(from))){
if(any(dups <- duplicated(names(from))))
warning("Duplicate labels",
paste(sQuote(unique(names(from)[dups])),collapse=" "),
call.=FALSE)
if(any(duplicated(from))) warning("Duplicate values",call.=FALSE)
new("value.labels",names(from),values=unname(from))
}
else new("value.labels",character(0),values=logical(0))
})
setAs(from="value.labels",to="numeric",function(from,to)
structure(as.vector(from@values),[email protected])
)
setAs(from="value.labels",to="character",function(from,to)
[email protected]
)
setMethod("as.vector","value.labels",function(x,mode="any")
structure(
as.vector(x@values,mode=mode),
[email protected]
)
)
setMethod("Arith",signature(e1="value.labels",e2="ANY"),
function(e1,e2){
if(!is(e2,"value.labels"))
e2 <- as(e2,"value.labels")
vals <- e1@values
labs <- [email protected]
newvals <- e2@values
newlabs <- [email protected]
upd.vals <- intersect(vals,newvals)
upd.labs <- newlabs[newvals %in% upd.vals]
tmp <- setdiff(newvals,upd.vals)
newlabs <- newlabs[match(tmp,newvals,nomatch=0L)]
newvals <- tmp
if(.Generic == "+"){
labs <- c(labs[vals %nin% upd.vals],upd.labs,newlabs)
vals <- c(vals[vals %nin% upd.vals],upd.vals,newvals)
ii <- order(vals)
vals <- vals[ii]
labs <- labs[ii]
}
else if(.Generic == "-"){
labs <- labs[vals %nin% upd.vals]
vals <- vals[vals %nin% upd.vals]
ii <- order(vals)
vals <- vals[ii]
labs <- labs[ii]
}
else stop("unsupported operator ",dQuote(.Generic))
new("value.labels",labs,
values = vals)
})
setMethod("has.value.labels","ANY",function(x)FALSE)
setMethod("has.value.labels","item",function(x)length([email protected])>0)
setMethod("is.labelled",signature(x="item.vector"),function(x){
if(!length([email protected])) return(logical(length(x)))
cl <- [email protected]
x %in% cl@values
})
add_value_labels <- function(x,v){
if(length(labels(x)))
labels(x) <- labels(x) + v
else
labels(x) <- v
x
} |
extract_sparse_parts <- function(A) {
if (!requireNamespace("Matrix"))
stop("You have to install the Matrix package to call 'extract_sparse_parts'")
if (!is(A, 'Matrix'))
A <- Matrix::Matrix(A, sparse=TRUE, doDiag=FALSE)
A <- Matrix::t(A)
A <- as(A, "dgCMatrix")
return(.Call(extract_sparse_components, A))
} |
test_that("get_last_path_part() works", {
expect_last_part <- function(x, tail) {
expect_equal(get_last_path_part(x), tail)
}
expect_last_part("~", "~/")
expect_last_part("~/", "~/")
expect_last_part("abc", "abc")
expect_last_part("abc/", "abc/")
expect_last_part("~/abc", "abc")
expect_last_part("~/abc/", "abc/")
expect_last_part("~/abc/def", "def")
expect_last_part("~/abc/def/", "def/")
expect_last_part("abc/def", "def")
expect_last_part("abc/def/", "def/")
expect_last_part("~/abc/def/ghi", "ghi")
expect_last_part("~/abc/def/ghi/", "ghi/")
expect_last_part("abc/def/ghi", "ghi")
expect_last_part("abc/def/ghi/", "ghi/")
})
test_that("resolve_paths() works, basic scenarios", {
dr_folder <-
list(kind = "drive
ancestors <- tibble(
name = c("a", "b", "c"),
id = c("1", "2", "3"),
drive_resource = list(
c(dr_folder, parents = list(list())),
c(dr_folder, parents = list(list("1"))),
c(dr_folder, parents = list(list("2")))
)
)
x <- tibble(
name = "d", id = "4",
drive_resource = list(list(kind = "drive
)
with_mock(
root_id = function() "", {
out <- resolve_paths(as_dribble(x), ancestors)
}
)
expect_equal(out$path, "a/b/c/d")
x$drive_resource <- list(c(dr_folder, parents = list(list("3"))))
with_mock(
root_id = function() "", {
out <- resolve_paths(as_dribble(x), ancestors)
}
)
expect_equal(out$path, "a/b/c/d/")
x <- tibble(
name = "e", id = "4",
drive_resource = list(list(kind = "drive
)
with_mock(
root_id = function() "", {
out <- resolve_paths(as_dribble(x), ancestors)
}
)
expect_equal(out$path, "e")
})
test_that("resolve_paths() works, with some name duplication", {
dr_folder <-
list(kind = "drive
ancestors <- tibble(
name = c("~", "a", "a", "b", "b", "b", "a"),
id = c("1", "2", "3", "4", "5", "6", "7"),
id_parent = c(NA, "1", "1", "1", "2", "3", "4"),
drive_resource = list(
c(dr_folder, parents = list(list())),
c(dr_folder, parents = list(list("1"))),
c(dr_folder, parents = list(list("1"))),
c(dr_folder, parents = list(list("1"))),
c(dr_folder, parents = list(list("2"))),
c(dr_folder, parents = list(list("3"))),
c(dr_folder, parents = list(list("4")))
)
)
x <- tibble(
name = c("c", "d"), id = c("8", "9"),
drive_resource = list(
list(kind = "drive
list(kind = "drive
)
)
with_mock(
root_id = function() "", {
out <- resolve_paths(as_dribble(x), ancestors)
}
)
expect_equal(out$path[1], "~/a/b/c")
expect_equal(out$path[2], "~/b/a/d")
}) |
expected <- eval(parse(text="c(\"aa\", \"row.names\")"));
test(id=0, code={
argv <- eval(parse(text="list(\"^..dfd.\", \"\", c(\"aa\", \"..dfd.row.names\"), FALSE, FALSE, FALSE, FALSE)"));
.Internal(`sub`(argv[[1]], argv[[2]], argv[[3]], argv[[4]], argv[[5]], argv[[6]], argv[[7]]));
}, o=expected); |
url2raster <- function(src)
{
ext <- tail(strsplit(src, split = ".", fixed = TRUE)[[1]], 1)
if (file.exists(src)) file <- src
else
{
file <- tempfile(fileext = paste0(".", ext))
download.file(src, destfile = file, mode = "wb", quiet = TRUE)
on.exit(unlink(file))
}
readWith <- switch(ext,
png = list(readPNG, readJPEG),
list(readJPEG, readPNG))
r <- try(readWith[[1]](file, native = TRUE), silent = TRUE)
if (inherits(r, "try-error"))
r <- try(readWith[[2]](file, native = TRUE), silent = TRUE)
if (inherits(r, "try-error"))
stop("'%s' does not appear to be a PNG or JPEG file.", src)
r
}
panel.xyimage <-
function(x, y,
subscripts,
groups = NULL,
pch = NULL,
cex = 1,
...,
grid = FALSE, abline = NULL)
{
if (all(is.na(x) | is.na(y))) return()
if (!is.character(pch))
stop("'pch' must be a character vector giving path(s) or URL(s) of PNG or JPEG files.")
if (!identical(grid, FALSE))
{
if (!is.list(grid))
grid <- switch(as.character(grid),
"TRUE" = list(h = -1, v = -1, x = x, y = y),
"h" = list(h = -1, v = 0, y = y),
"v" = list(h = 0, v = -1, x = x),
list(h = 0, v = 0))
do.call(panel.grid, grid)
}
if (!is.null(abline))
{
if (is.numeric(abline)) abline <- as.list(abline)
do.call(panel.abline, abline)
}
if (is.null(groups))
{
pch.raster <- url2raster(pch[1])
grid.raster(x, y, image = pch.raster,
width = unit(cex * 10, "mm"),
height = unit(cex * 10, "mm"),
default.units = "native")
}
else
{
groups <- as.factor(groups)
cex <- rep(cex, length = nlevels(groups))
pch <- rep(pch, length = nlevels(groups))
pch.raster <- lapply(pch, url2raster)
g <- as.numeric(groups)[subscripts]
ug <- unique(g)
for (i in ug)
{
w <- (g == i)
grid.raster(x[w], y[w], image = pch.raster[[i]],
width = unit(cex[i] * 8, "mm"),
height = unit(cex[i] * 8, "mm"),
default.units = "native")
}
}
} |
if (Sys.getenv("POSTGRES_USER") != "" & Sys.getenv("POSTGRES_HOST") != "" & Sys.getenv("POSTGRES_DATABASE") != "") {
stopifnot(require(RPostgreSQL))
stopifnot(require(datasets))
drv <- dbDriver("PostgreSQL")
con <- dbConnect(drv,
user=Sys.getenv("POSTGRES_USER"),
password=Sys.getenv("POSTGRES_PASSWD"),
host=Sys.getenv("POSTGRES_HOST"),
dbname=Sys.getenv("POSTGRES_DATABASE"),
port=ifelse((p<-Sys.getenv("POSTGRES_PORT"))!="", p, 5432))
if (dbExistsTable(con, "rockdata")) {
print("Removing rockdata\n")
dbRemoveTable(con, "rockdata")
}
dbWriteTable(con, "rockdata", rock)
res <- dbGetQuery(con, "SELECT * FROM rockdata WHERE peri > $1 LIMIT 10", 4000)
print(res)
res <- dbGetQuery(con, "SELECT * FROM rockdata WHERE peri > $1 AND shape < $2 LIMIT $3", c(4000, 0.2, 10))
print(res)
if (dbExistsTable(con, "rockdata")) {
print("Removing rockdata\n")
dbRemoveTable(con, "rockdata")
}
dbDisconnect(con)
} |
effx<-function(response,
type="metric",
fup=NULL,
exposure,
strata=NULL,
control=NULL,
weights=NULL,
eff=NULL,
alpha=0.05,
base=1,
digits=3,
data=NULL)
{
rname<-deparse(substitute(response))
ename<-deparse(substitute(exposure))
if (!missing(strata)) {
sname<-deparse(substitute(strata))
}
if(!missing(control)) {
control.arg <- substitute(control)
}
type <- match.arg(type, c("metric", "failure", "count", "binary"))
if (missing(response))
stop("Must specify the response","\n")
if (missing(exposure))
stop("Must specify the exposure","\n")
if (type == "failure" && missing(fup)) {
stop("Must specify a follow-up variable when type is failure")
}
if(rname==ename)stop("Same variable specified as response and exposure")
if (!missing(strata)) {
if(rname==sname)stop("Same variable specified as response and strata")
if(sname==ename)stop("Same variable specified as strata and exposure")
}
if (!missing(data)) {
exposure <- eval(substitute(exposure), data)
response <- eval(substitute(response), data)
if (!missing(strata))
strata <- eval(substitute(strata), data)
if (!missing(control))
control <- eval(substitute(control), data)
if (!missing(fup))
fup <- eval(substitute(fup), data)
if (!missing(weights)) {
weights <- eval(substitute(weights), data)
}
}
if(is.logical(response)) response <- as.numeric(response)
if(!is.numeric(response))
stop("Response must be numeric, not a factor")
if (!missing(weights) && type != "binary") {
stop("weights only allowed for a binary response")
}
if (!missing(strata) && !is.factor(strata))
stop("Stratifying variable must be a factor")
if(type=="binary") {
if( is.null(eff) ) eff<-"OR"
if( !(eff %in% c("OR","RR") ) ) stop( "Only RR and OR allowed for binary response" )
response <- as.numeric(response)
tmp<-(response==0 | response==1)
if(all(tmp,na.rm=TRUE)==FALSE)
stop("Binary response must be logical or coded 0,1 or NA")
}
if(type=="count") fup<-is.na(response)*1
if(type=="failure") {
if( is.null(eff) ) eff<-"RR"
response <- as.numeric(response)
tmp<-(response==0 | response==1)
if(all(tmp,na.rm=TRUE)==FALSE)
stop("Failure response must be logical or coded 0,1 or NA")
}
if(class(exposure)[1]=="ordered") {
exposure<-factor(exposure, ordered=F)
}
if (!missing(control)) {
if (is.list(control)) {
control.names <- sapply(control.arg, deparse)
if (control.names[1] == "list" &&
length(control.names) == length(control) + 1)
{
control.names <- control.names[-1]
}
else {
control.names <-
paste0(deparse(control.arg), "[", 1:length(control), "]")
}
names(control) <- control.names
}
else {
control <- list(control)
names(control) <- deparse(control.arg)
}
}
cat("---------------------------------------------------------------------------","\n")
cat("response : ", rname, "\n")
cat("type : ", type, "\n")
cat("exposure : ", ename, "\n")
if(!missing(control))cat("control vars : ",names(control),"\n")
if(!missing(strata)) {
cat("stratified by : ",sname,"\n")
}
cat("\n")
if(is.factor(exposure)) {
cat(ename,"is a factor with levels: ")
cat(paste(levels(exposure),collapse=" / "),"\n")
exposure <- Relevel( exposure, base )
cat( "baseline is ", levels( exposure )[1] ,"\n")
}
else {
cat(ename,"is numeric","\n")
}
if(!missing(strata)) {
cat(sname,"is a factor with levels: ")
cat(paste(levels(strata),collapse="/"),"\n")
}
if(type=="metric")cat("effects are measured as differences in means","\n")
if(type=="binary")
{
if( eff=="OR" | is.null(eff))cat("effects are measured as odds ratios","\n")
if( eff=="RR" )cat("effects are measured as relative risk","\n")
}
if(type=="failure")
{
if( eff=="RR" | is.null(eff))cat("effects are measured as rate ratios","\n")
if( eff=="RD" )cat("effects are measured as rate differences","\n")
}
cat("---------------------------------------------------------------------------","\n")
cat("\n")
if ( type=="metric") family<-gaussian
if ( type=="binary") family<-binomial(link=logit)
if ( type=="failure" | type=="count") family<-poisson(link=log)
if ( !is.null(eff) )
{
if (type=="binary" & eff=="RR") family<-binomial(link=log)
if (type=="failure" & eff=="RD") family<-poisson(link=identity)
}
if(is.factor(exposure)) {
nlevE<-length(levels(exposure))
}
if(is.factor(exposure)) {
cat("effect of",ename,"on",rname,"\n")
}
else {
cat("effect of an increase of 1 unit in",ename,"on",rname,"\n")
}
if(!missing(control)) {
cat("controlled for",names(control),"\n\n")
}
if(!missing(strata)) {
cat("stratified by",sname,"\n\n")
}
if(missing(strata)) {
if(type=="metric") {
if(missing(control)) {
m<-glm(response~exposure,family=family)
cat("number of observations ",m$df.null+1,"\n\n")
mm<-glm(response~1,family=family,subset=!is.na(exposure))
}
else {
m<-glm(response~.+exposure,family=family,
subset=!is.na(exposure),data=control)
cat("number of observations ",m$df.null+1,"\n\n")
mm<-glm(response~.,family=family,
subset=!is.na(exposure),data=control)
}
res<-ci.lin(m,subset=c("Intercept","exposure"),alpha=alpha)
res<-res[,c(1,5,6)]
}
if(type=="binary") {
if(missing(control)) {
m<-glm(response~exposure,family=family,weights=weights)
cat("number of observations ",m$df.null+1,"\n\n")
mm<-glm(response~1,family=family,subset=!is.na(exposure),weights=weights)
}
else {
m<-glm(response~.+exposure,family=family,
subset=!is.na(exposure),data=control,weights=weights)
cat("number of observations ",m$df.null+1,"\n\n")
mm<-glm(response~.,family=family,
subset=!is.na(exposure),data=control,weights=weights)
}
res<-ci.lin(m,subset=c("Intercept","exposure"),Exp=TRUE,alpha=alpha)
res<-res[,c(5,6,7)]
}
if (type=="failure" | type=="count") {
if (missing(control)) {
m<-glm(response/fup~exposure,weights=fup,family=family)
cat("number of observations ",m$df.null+1,"\n\n")
mm<-glm(response/fup~1,weights=fup,family=family,
subset=!is.na(exposure))
}
else {
m<-glm(response/fup~.+exposure,weights=fup,family=family, data=control)
cat("number of observations ",m$df.null+1,"\n\n")
mm<-glm(response/fup~.,weights=fup,family=family,
subset=!is.na(exposure),data=control)
}
res<-ci.exp(m,subset=c("Intercept","exposure"),alpha=alpha,Exp=(eff=="RR"))
}
res<-signif(res,digits)
colnames(res)[1]<-c("Effect")
if(is.factor(exposure)) {
ln <- levels(exposure)
rownames(res)[2:nlevE]<-paste(ln[2:nlevE],"vs",ln[1])
}
aov <- anova(mm,m,test="Chisq")
print( res[-1,] )
cat("\nTest for no effects of exposure on",
aov[2,3],"df:",
"p-value=",format.pval(aov[2,5],digits=3),"\n")
invisible(list(res,paste("Test for no effects of exposure on",
aov[2,3],"df:","p-value=",format.pval(aov[2,5],digits=3))))
}
if(!missing(strata)) {
sn <- levels(strata)
nlevS<-length(levels(strata))
if(type=="metric") {
if(missing(control)) {
m<-glm(response~strata/exposure,family=family)
cat("number of observations ",m$df.null+1,"\n\n")
mm<-glm(response~strata+exposure,family=family)
}
else {
m <-glm(response~strata/exposure + .,family=family,
data=control)
cat("number of observations ",m$df.null+1,"\n\n")
mm <-glm(response~strata+exposure + .,family=family,
data=control)
}
res<-ci.lin(m,subset=c("strata"),alpha=alpha)[c(-1:-(nlevS-1)),c(1,5,6)]
}
if(type=="binary") {
if(missing(control)) {
m<-glm(response~strata/exposure,family=family,weights=weights)
cat("number of observations ",m$df.null+1,"\n\n")
mm<-glm(response~strata+exposure,family=family,weights=weights)
}
else {
m <-glm(response~strata/exposure + .,family=family,
data=control,weights=weights)
cat("number of observations ",m$df.null+1,"\n\n")
mm <-glm(response~strata+exposure + .,family=family,
data=control,weights=weights)
}
res<-ci.exp(m,subset=c("strata"),alpha=alpha)[c(-1:-(nlevS-1)),]
}
if (type=="failure" | type=="count") {
if(missing(control)) {
m<-glm(response/fup~strata/exposure,weights=fup,family=family)
cat("number of observations ",m$df.null+1,"\n\n")
mm<-glm(response~strata+exposure,weights=fup,family=family)
}
else {
m <-glm(response/fup~.+strata/exposure,weights=fup,family=family,data=control)
cat("number of observations ",m$df.null+1,"\n\n")
mm<-glm(response/fup~.+strata+exposure,weights=fup,family=family,data=control)
}
res<-ci.exp(m,subset=c("strata"),alpha=alpha)[c(-1:-(nlevS-1)),]
}
res<-signif(res,digits)
colnames(res)[1]<-c("Effect")
if(is.factor(exposure)) {
ln<-levels(exposure)
newrownames<-NULL
for(i in c(1:(nlevE-1))) {
newrownames<-c(newrownames,
paste("strata",sn[1:nlevS],"level",ln[i+1],"vs",ln[1]))
}
}
else {
newrownames<-paste("strata",sn[1:nlevS])
}
rownames(res)<-newrownames
aov<-anova(mm,m,test="Chisq")
print( res )
cat("\nTest for effect modification on",
aov[2,3],"df:","p-value=",format.pval(aov[2,5],digits=3),"\n")
invisible(list(res,paste("Test for effect modification on",
aov[2,3],"df:","p-value=",format.pval(aov[2,5],digits=3))))
}
} |
library(dplyr)
library(tidyr)
library(distributional)
test_that("vanilla dots geoms and stats work", {
skip_if_no_vdiffr()
set.seed(1234)
p = tribble(
~dist, ~x,
"norm", rnorm(20),
"t", rt(20, 3)
) %>%
unnest(x) %>%
ggplot()
vdiffr::expect_doppelganger("vanilla geom_dots",
p + geom_dots(aes(x = dist, y = x))
)
vdiffr::expect_doppelganger("vanilla geom_dotsh",
p + geom_dots(aes(y = dist, x = x))
)
vdiffr::expect_doppelganger("stat_dotsh with a group with 1 dot",
p + stat_dots(aes(y = dist, x = x, color = x > 2))
)
vdiffr::expect_doppelganger("stat_dotsh with a group with 2 dots",
p + stat_dots(aes(y = dist, x = x, color = x > 1))
)
set.seed(1234)
p = tribble(
~dist, ~x, ~datatype,
"norm", rnorm(20), "slab",
"t", rt(20, 3), "slab"
) %>%
unnest(x) %>%
bind_rows(tribble(
~ dist, ~x, ~datatype, ~lower, ~upper,
"norm", 0, "interval", -1, 1,
"t", 0, "interval", -2, 2
)) %>%
ggplot()
vdiffr::expect_doppelganger("vanilla geom_dotsinterval",
p + geom_dotsinterval(aes(y = dist, x = x, xmin = lower, xmax = upper, datatype = datatype))
)
set.seed(1234)
p = tribble(
~dist, ~x,
"norm", rnorm(100),
"t", rt(100, 3)
) %>%
unnest(x) %>%
ggplot()
vdiffr::expect_doppelganger("vanilla stat_dotsinterval",
p + stat_dotsinterval(aes(x = dist, y = x), quantiles = 20)
)
vdiffr::expect_doppelganger("vanilla stat_dotsintervalh",
p + stat_dotsinterval(aes(y = dist, x = x), quantiles = 20)
)
})
test_that("coordinate transformations work", {
skip_if_no_vdiffr()
set.seed(1234)
p = tribble(
~dist, ~x, ~datatype,
"norm", rnorm(20), "slab",
"t", rt(20, 3), "slab"
) %>%
unnest(x) %>%
bind_rows(tribble(
~ dist, ~x, ~datatype, ~lower, ~upper,
"norm", 0, "interval", -1, 1,
"t", 0, "interval", -2, 2
)) %>%
ggplot() +
geom_dotsinterval(aes(y = dist, x = x, xmin = lower, xmax = upper, datatype = datatype))
vdiffr::expect_doppelganger("coord_flip with dotsinterval",
p + coord_flip()
)
expect_error(
print(p + coord_polar(), newpage = FALSE),
"geom_dotsinterval does not work properly with non-linear coordinates"
)
})
test_that("scale transformations work", {
skip_if_no_vdiffr()
p = data.frame(x = dist_sample(list(qlnorm(ppoints(20))))) %>%
ggplot(aes(xdist = x, y = 0))
vdiffr::expect_doppelganger("transformed scale with dist_sample",
p + stat_dist_dotsinterval() + scale_x_log10()
)
p = data.frame(x = qlnorm(ppoints(20))) %>%
ggplot(aes(x = x, y = 0))
vdiffr::expect_doppelganger("transformed scale with sample data on x",
p + stat_dist_dotsinterval() + scale_x_log10()
)
p = data.frame(x = qlnorm(ppoints(100))) %>%
ggplot(aes(x = x, y = 0))
vdiffr::expect_doppelganger("transformed scale, sample data, quantiles",
p + stat_dist_dotsinterval(quantiles = 20) + scale_x_log10()
)
})
test_that("stat_dist_dots[interval] works", {
skip_if_no_vdiffr()
p = tribble(
~dist, ~args,
"norm", list(0, 1),
"t", list(3)
) %>%
ggplot(aes(dist = dist, args = args))
vdiffr::expect_doppelganger("vanilla stat_dist_dots",
p + stat_dist_dots(aes(x = dist), n = 20, quantiles = 20)
)
vdiffr::expect_doppelganger("vanilla stat_dist_dotsinterval",
p + stat_dist_dotsinterval(aes(x = dist), n = 20, quantiles = 20)
)
vdiffr::expect_doppelganger("vanilla stat_dist_dotsintervalh",
p + stat_dist_dotsinterval(aes(y = dist), n = 20, quantiles = 20)
)
})
test_that("stat_dist_dots works on NA data", {
skip_if_no_vdiffr()
p = data.frame(
x = c("norm", NA, "norm"),
y = c("a","b", NA)
) %>%
ggplot(aes(dist = x, y = y))
expect_warning(vdiffr::expect_doppelganger("stat_dist_dots with na.rm = FALSE",
p + stat_dist_dots(na.rm = FALSE, quantiles = 20)
), "Removed 1 rows containing non-finite values")
vdiffr::expect_doppelganger("stat_dist_dots with na.rm = TRUE",
p + stat_dist_dots(na.rm = TRUE, quantiles = 20)
)
})
test_that("stat_dist_dots works on distributional objects", {
skip_if_no_vdiffr()
p = data.frame(
x = dist_normal(0:1, 1:2),
y = c("a","b")
) %>%
ggplot(aes(dist = x, y = y))
vdiffr::expect_doppelganger("stat_dist_dots with dist_normal",
p + stat_dist_dots(quantiles = 20)
)
})
test_that("geom_dots binwidth can be specified in unit()s", {
skip_if_no_vdiffr()
vdiffr::expect_doppelganger("geom_dots with unit() binwidth",
mtcars %>%
ggplot(aes(y = mpg)) +
geom_dots(binwidth = unit(0.1, "native")) +
facet_grid(~ am, scales = "free")
)
})
test_that("geom_dots allows constraints on binwidth", {
skip_if_no_vdiffr()
p = data.frame(x = ppoints(20)) %>%
ggplot(aes(x = x, y = 0L))
vdiffr::expect_doppelganger("max binwidth",
p + geom_dots(binwidth = unit(c(0, 1/40), "npc"))
)
vdiffr::expect_doppelganger("min binwidth",
p + geom_dots(binwidth = unit(c(1/4, Inf), "npc"))
)
})
test_that("dotplot layouts work", {
skip_if_no_vdiffr()
vdiffr::expect_doppelganger("weave top",
mtcars %>%
ggplot(aes(x = mpg)) +
geom_dots(layout = "weave", side = "top")
)
vdiffr::expect_doppelganger("weave bottom",
mtcars %>%
ggplot(aes(x = mpg)) +
geom_dots(layout = "weave", side = "bottom")
)
vdiffr::expect_doppelganger("weave both",
mtcars %>%
ggplot(aes(x = mpg)) +
geom_dots(layout = "weave", side = "both")
)
vdiffr::expect_doppelganger("swarm top",
mtcars %>%
ggplot(aes(x = mpg)) +
geom_dots(layout = "swarm")
)
vdiffr::expect_doppelganger("swarm bottom",
mtcars %>%
ggplot(aes(x = mpg)) +
geom_dots(layout = "swarm", side = "bottom")
)
vdiffr::expect_doppelganger("swarm both",
mtcars %>%
ggplot(aes(x = mpg)) +
geom_dots(layout = "swarm", side = "both")
)
vdiffr::expect_doppelganger("swarm vertical",
mtcars %>%
ggplot(aes(y = mpg)) +
geom_dots(layout = "swarm")
)
})
test_that("dot order is correct", {
skip_if_no_vdiffr()
p = data.frame(x = qnorm(ppoints(50))) %>%
ggplot(aes(x = x, fill = stat(x < 0)))
vdiffr::expect_doppelganger("weave dot order",
p +
geom_dots(layout = "weave") +
geom_vline(xintercept = 0)
)
vdiffr::expect_doppelganger("swarm dot order",
p +
geom_dots(layout = "swarm") +
geom_vline(xintercept = 0)
)
})
test_that("na.rm is propagated to quantile dotplot", {
skip_if_no_vdiffr()
vdiffr::expect_doppelganger("na.rm with quantile arg",
data.frame(x = qnorm(ppoints(100), 1)) %>%
ggplot(aes(x, y = 0)) +
stat_dots(na.rm = TRUE, quantiles = 20) +
scale_x_continuous(limits = c(0,4))
)
})
test_that("geom_dots works with NA in non-data axis", {
skip_if_no_vdiffr()
p = mtcars %>%
ggplot(aes(x = mpg, y = factor(cyl))) +
scale_y_discrete(limits = c("4", "6"))
expect_warning(vdiffr::expect_doppelganger("NA on y axis",
p + geom_dots(na.rm = FALSE)
))
vdiffr::expect_doppelganger("removed NA on y axis",
p + geom_dots(na.rm = TRUE)
)
})
test_that("empty slab from NA removal works", {
skip_if_no_vdiffr()
vdiffr::expect_doppelganger("dots with no slab from NA removal", {
data.frame(x = c(1, NA), datatype = c("interval", "slab")) %>%
ggplot(aes(x = x, xmin = x - 1, xmax = x + 1, datatype = datatype)) +
geom_dotsinterval(na.rm = TRUE)
})
})
test_that("geom_dots works on discrete distributions", {
skip_if_no_vdiffr()
vdiffr::expect_doppelganger("one integer bin",
data.frame(x = rep(1L, 10)) %>%
ggplot(aes(x = x, y = 0)) +
stat_dots(orientation = "horizontal") +
geom_hline(yintercept = 0.9)
)
vdiffr::expect_doppelganger("three integer bins",
data.frame(x = c(rep(1L, 10), rep(2L, 12), rep(3L, 5))) %>%
ggplot(aes(x = x, y = 0)) +
stat_dots(orientation = "horizontal") +
geom_hline(yintercept = 0.9)
)
vdiffr::expect_doppelganger("one character bin",
data.frame(x = rep("a", 10)) %>%
ggplot(aes(x = x, y = 0)) +
stat_dots(orientation = "horizontal") +
geom_hline(yintercept = 0.9)
)
vdiffr::expect_doppelganger("three character bins",
data.frame(x = c(rep("a", 10), rep("b", 12), rep("c", 5))) %>%
ggplot(aes(x = x, y = 0)) +
stat_dots(orientation = "horizontal") +
geom_hline(yintercept = 0.9)
)
})
test_that("geom_dots correctly adjusts dot size for stroke size", {
skip_if_no_vdiffr()
p = data.frame(x = ppoints(40)) %>%
ggplot(aes(x = x))
vdiffr::expect_doppelganger("size = 1 and 3",
p +
geom_dots(aes(y = "a"), binwidth = 1/20, size = 1, color = "black") +
geom_dots(aes(y = "b"), binwidth = 1/20, size = 3, color = "black")
)
})
test_that("side, justification, and scale can vary", {
skip_if_no_vdiffr()
vdiffr::expect_doppelganger("varying side",
mtcars %>%
ggplot(aes(x = mpg, y = cyl,
side = case_when(cyl == 4 ~ "top", cyl == 6 ~ "both", cyl == 8 ~ "bottom"),
)) +
stat_dotsinterval(orientation = "horizontal")
)
vdiffr::expect_doppelganger("varying side and just",
mtcars %>%
ggplot(aes(x = mpg, y = cyl,
side = case_when(cyl == 4 ~ "top", cyl == 6 ~ "both", cyl == 8 ~ "bottom"),
justification = case_when(cyl == 4 ~ 1, cyl == 6 ~ 0.25, cyl == 8 ~ 0)
)) +
stat_dotsinterval(orientation = "horizontal", scale = 0.5)
)
vdiffr::expect_doppelganger("varying scale, side, just",
tibble(
x = c(0, rep(1, 9), 0),
group = c(rep("a", 4), rep("b", 7)),
scale = c(rep(1/3, 4), rep(2/3, 7)),
side = c(rep("top", 4), rep("bottom", 7)),
justification = c(rep(0, 4), rep(1, 7))
) %>%
ggplot(aes(x = x, y = group, scale = scale, side = side, justification = justification, color = group)) +
stat_dots()
)
}) |
rows.cntr.scatter <- function (data, x = 1, y = 2, filter=FALSE, cex.labls=3){
cntr1=cntr2=labels.final=NULL
ncols <- ncol(data)
nrows <- nrow(data)
numb.dim.cols <- ncol(data) - 1
numb.dim.rows <- nrow(data) - 1
a <- min(numb.dim.cols, numb.dim.rows)
pnt_labls <- rownames(data)
res <- CA(data, ncp = a, graph = FALSE)
dfr <- data.frame(lab = pnt_labls, cntr1 = res$row$contrib[,x] * 10, cntr2 = res$row$contrib[, y] * 10, coord1=res$row$coord[,x], coord2=res$row$coord[,y])
dfr$labels1 <- ifelse(dfr$coord1 < 0, "-", "+")
dfr$labels2 <- ifelse(dfr$coord2 < 0, "-", "+")
dfr$labels.final <- paste0(dfr$lab, " (",dfr$labels1,",",dfr$labels2, ")")
xmax <- max(dfr[, 2]) + 10
ymax <- max(dfr[, 3]) + 10
limit.value <- max(xmax, ymax)
ifelse(filter==FALSE, dfr <- dfr, dfr <- subset(dfr, cntr1>(100/nrows)*10 | cntr2>(100/nrows)*10))
p <- ggplot(dfr, aes(x = cntr1, y = cntr2)) + geom_point(alpha = 0.8) +
geom_hline(yintercept = round((100/nrows) * 10, digits = 0), colour = "red", linetype = "dashed") +
geom_vline(xintercept = round((100/nrows) *10, digits = 0), colour = "red", linetype = "dashed") +
scale_y_continuous(limits = c(0, limit.value)) +
scale_x_continuous(limits = c(0,limit.value)) +
geom_abline(intercept = 0, slope = 1, colour="
theme(panel.background = element_rect(fill="white", colour="black")) +
geom_text_repel(data = dfr, aes(label = labels.final), size = cex.labls) +
labs(x = paste("Row categories' contribution (permills) to Dim.",x), y = paste("Row categories' contribution (permills) to Dim.", y)) +
coord_fixed(ratio = 1, xlim = NULL, ylim = NULL, expand = TRUE)
return(p)
} |
NULL
get_intercept <- function(object) {
check_and_get_ipriorKernel(object)
object$intercept
}
get_y <- function(object) {
check_and_get_ipriorKernel(object)
if (is.categorical(object)) {
warning("Categorical variables were numerised.", call. = FALSE)
}
res <- as.numeric(object$y + get_intercept(object))
names(res) <- rownames(object$y)
res
}
get_size <- function(object, units = "kB", standard = "SI") {
check_and_get_ipriorKernel(object)
print(object.size(object), units = units, standard = standard)
}
get_hyp <- function(object) {
check_and_get_ipriorMod(object)
res <- object$param.full
if (length(res) > 0) return(res)
else cat("NA")
}
get_lambda <- function(object) {
tmp <- get_hyp(object)
res <- tmp[grep("lambda", names(tmp))]
if (length(res) > 0) return(res)
else cat("NA")
}
get_psi <- function(object) {
tmp <- get_hyp(object)
res <- tmp[grep("psi", names(tmp))]
if (length(res) > 0) return(res)
else cat("NA")
}
get_lengthscale <- function(object) {
tmp <- get_hyp(object)
res <- tmp[grep("lengthscale", names(tmp))]
if (length(res) > 0) return(res)
else cat("NA")
}
get_hurst <- function(object) {
tmp <- get_hyp(object)
res <- tmp[grep("hurst", names(tmp))]
if (length(res) > 0) return(res)
else cat("NA")
}
get_offset <- function(object) {
tmp <- get_hyp(object)
res <- tmp[grep("offset", names(tmp))]
if (length(res) > 0) return(res)
else cat("NA")
}
get_degree <- function(object) {
if (is.kern_poly(object)) {
tmp <- get_kernels(object)
return(get_polydegree(tmp))
} else {
cat("NA")
}
}
get_se <- function(object) {
check_and_get_ipriorMod(object)
expand_theta(object$se, object$ipriorKernel$thetal$theta.drop, NA)
}
get_kernels <- function(object) {
if (is.ipriorMod(object)) theta <- object$theta
if (is.ipriorKernel(object)) theta <- object$thetal$theta
check_and_get_ipriorKernel(object)
param.tab <- theta_to_param(theta, object)
res <- param.tab$kernel
names(res) <- object$xname
res
}
get_kern_matrix <- function(object, theta = NULL, newdata) {
if (is.ipriorMod(object)) {
if (missing(newdata)) {
res <- get_Hlam(object$ipriorKernel, object$theta, FALSE)
} else {
list2env(before_predict(object, newdata), envir = environment())
res <- get_Htildelam(object$ipriorKernel, object$theta, xstar)
}
return(res)
} else if (is.ipriorKernel(object)) {
if (missing(newdata)) {
res <- get_Hlam(object, object$thetal$theta, FALSE)
} else {
list2env(before_predict(list(ipriorKernel = object), newdata),
envir = environment())
res <- get_Htildelam(object, object$thetal$theta, xstar)
}
return(res)
}
}
get_prederror <- function(object, error.type = c("RMSE", "MSE")) {
check_and_get_ipriorMod(object)
error.type <- match.arg(toupper(error.type), c("RMSE", "MSE"))
if (error.type == "MSE") fun <- function(x) x
if (error.type == "RMSE") fun <- function(x) sqrt(x)
train.error <- c("Training" = object$train.error)
if (is.ipriorKernel_cv(object)) {
res <- fun(c(train.error, "Test" = object$test$test.error))
} else {
res <- fun(train.error)
}
names(res) <- paste(names(res), error.type)
res
}
get_mse <- function(object) get_prederror(object, "MSE")
get_rmse <- function(object) get_prederror(object, "RMSE")
get_estl <- function(object) {
check_and_get_ipriorKernel(object)
unlist(object$estl)
}
get_method <- function(object) {
check_and_get_ipriorMod(object)
cat(object$est.method)
}
get_convergence <- function(object) {
check_and_get_ipriorMod(object)
cat(object$est.conv)
}
get_niter <- function(object) {
check_and_get_ipriorMod(object)
niter <- object$niter
maxit <- object$control$maxit
cat("Iterations:", paste0(niter, "/", maxit, "."))
}
get_time <- function(object) {
check_and_get_ipriorMod(object)
object$time
}
get_theta <- function(object) {
check_and_get_ipriorMod(object)
object$theta
} |
expected <- eval(parse(text="structure(\"Seed\", .Dim = c(1L, 1L))"));
test(id=0, code={
argv <- eval(parse(text="list(structure(\"Seed\", .Dim = c(1L, 1L)))"));
.Internal(t.default(argv[[1]]));
}, o=expected); |
MCP_soft <- function(z,lambda,a=3){
return( S_soft(z,lambda)/(1-1/a) * (abs(z) - a*lambda <= 0) + z * (abs(z) - a*lambda > 0) )
} |
require(gamboostLSS)
set.seed(1907)
x1 <- rnorm(1000)
x2 <- rnorm(1000)
x3 <- rnorm(1000)
x4 <- rnorm(1000)
x5 <- rnorm(1000)
x6 <- rnorm(1000)
mu <- exp(1.5 +1 * x1 +0.5 * x2 -0.5 * x3 -1 * x4)
sigma <- exp(-0.4 * x3 -0.2 * x4 +0.2 * x5 +0.4 * x6)
y <- numeric(1000)
for( i in 1:1000)
y[i] <- rnbinom(1, size = sigma[i], mu = mu[i])
dat <- data.frame(x1, x2, x3, x4, x5, x6, y)
model <- glmboostLSS(y ~ ., families = NBinomialLSS(), data = dat,
control = boost_control(mstop = 10),
center = TRUE)
mstop(model)
model2 <- glmboostLSS(y ~ ., families = NBinomialLSS(), data = dat,
control = boost_control(mstop = list(mu = 10, sigma = 20)),
center = TRUE)
mstop(model2)
f1 <- fitted(model, parameter = "mu", type = "response")
f2 <- fitted(model, parameter = "sigma", type = "response")
model3 <- glmboost(y ~ ., family = NBinomialSigma(mu = f1, sigma = f2,
stabilization = "none"),
data = dat,
control = boost_control(mstop = 10),
center = TRUE)
tmp <- coef(model3) + coef(model)$sigma
stopifnot(max(abs(tmp - coef(model2)$sigma)) < sqrt(.Machine$double.eps))
layout(matrix(c(1:4, 6, 5), byrow = TRUE, ncol = 2))
plot(model, xlim = c(0,20), ylim = range(sapply(coef(model2), range)))
plot(model2, xlim = c(0, 20), ylim = range(sapply(coef(model2), range)))
plot(model, xlim = c(0,20), ylim = range(sapply(coef(model2), range)),
parameter = "sigma")
cp <- coef(model3, aggregate = "cumsum")
cp <- matrix(unlist(cp), nrow = length(cp), byrow = TRUE)
cp <- cp + coef(model)$sigma
cp <- cbind(coef(model)$sigma, cp)
cf <- cp[, ncol(cp)]
col <- hcl(h = 40, l = 50, c = abs(cf)/max(abs(cf)) * 490)
matlines(10:20, t(cp), type = "l", xlab = "Number of boosting iterations",
ylab = "Coefficients", col = col)
ms <- list(mu = 10, sigma = 20)
model <- glmboostLSS(y ~ ., families = NBinomialLSS(), data = dat,
control = boost_control(mstop = ms, trace = TRUE),
center = TRUE)
model[c(20, 30)]
ms <- list(mu = 20, sigma = 30)
modela <- glmboostLSS(y ~ ., families = NBinomialLSS(), data = dat,
control = boost_control(mstop = ms, trace = TRUE),
center = TRUE)
stopifnot(max(abs(coef(model)[[1]] - coef(modela)[[1]]))
< sqrt(.Machine$double.eps))
stopifnot(max(abs(coef(model)[[2]] - coef(modela)[[2]]))
< sqrt(.Machine$double.eps))
model[40]
mstop(model)
modelb <- glmboostLSS(y ~ ., families = NBinomialLSS(), data = dat,
control = boost_control(mstop = 40, trace = TRUE),
center = TRUE)
stopifnot(all.equal(risk(model), risk(modelb)))
model <- glmboostLSS(y ~ ., families = NBinomialLSS(), data = dat,
control = boost_control(mstop = 10, trace = TRUE),
center = TRUE)
model[20]
model2 <- glmboostLSS(y ~ ., families = NBinomialLSS(), data = dat,
control = boost_control(mstop = 20, trace = TRUE),
center = TRUE)
stopifnot(all.equal(risk(model), risk(model2)))
ms <- list(mu = 10, sigma = 20)
model <- glmboostLSS(y ~ ., families = NBinomialLSS(), data = dat,
control = boost_control(mstop = ms, trace = TRUE),
center = TRUE)
model[c(5,10)]
ms <- list(mu = 5, sigma = 10)
model2 <- glmboostLSS(y ~ ., families = NBinomialLSS(), data = dat,
control = boost_control(mstop = ms, trace = TRUE),
center = TRUE)
stopifnot(all.equal(risk(model), risk(model2)))
ms <- list(mu = 10, sigma = 20)
model <- glmboostLSS(y ~ ., families = NBinomialLSS(), data = dat,
control = boost_control(mstop = ms, trace = TRUE),
center = TRUE)
model[c(10,25)]
mstop(model)
ms <- list(mu = 10, sigma = 25)
model2 <- glmboostLSS(y ~ ., families = NBinomialLSS(), data = dat,
control = boost_control(mstop = ms, trace = TRUE),
center = TRUE)
stopifnot(all.equal(risk(model), risk(model2)))
ms <- list(mu = 10, sigma = 20)
model <- glmboostLSS(y ~ ., families = NBinomialLSS(), data = dat,
control = boost_control(mstop = ms, trace = TRUE),
center = TRUE)
model[c(10,15)]
mstop(model)
ms <- list(mu = 10, sigma = 15)
model2 <- glmboostLSS(y ~ ., families = NBinomialLSS(), data = dat,
control = boost_control(mstop = ms, trace = TRUE),
center = TRUE)
stopifnot(all.equal(risk(model), risk(model2)))
ms <- list(mu = 10, sigma = 20)
model <- glmboostLSS(y ~ ., families = NBinomialLSS(), data = dat,
control = boost_control(mstop = ms, trace = TRUE),
center = TRUE)
model[c(10,9)]
mstop(model)
ms <- list(mu = 10, sigma = 9)
model2 <- glmboostLSS(y ~ ., families = NBinomialLSS(), data = dat,
control = boost_control(mstop = ms, trace = TRUE),
center = TRUE)
stopifnot(all.equal(risk(model), risk(model2)))
nus <- list(mu = 0, sigma = 0.2)
model <- glmboostLSS(y ~ ., families = NBinomialLSS(), data = dat,
control = boost_control(mstop = 10, nu = nus, trace = TRUE),
center = TRUE)
stopifnot(all(coef(model)[[1]] == 0))
stopifnot(any(coef(model)[[2]] != 0)) |
den2Q_qd <- function(densityCurves, dSup, t_vec) {
n = nrow(densityCurves)
m = length(t_vec)
res = list()
m_dSup = length(dSup)
if(min(densityCurves) < 0) {
stop("Please correct negative or zero probability density estimates.")
}
if (length(dSup) < 25) {
stop("please give densely observed density curves, with length(dSup) >= 25 ")
}
res_list_dSup = sapply(1:n, function(i) {
dens = densityCurves[i, ]
if (abs(fdapace::trapzRcpp(X = dSup, dens) - 1) > 1e-05) {
dens = dens/fdapace::trapzRcpp(X = dSup, Y = dens)
}
cdf_raw = fdapace::cumtrapzRcpp(X = dSup, Y = dens)
spline_fit = splinefun(x = dSup, y = cdf_raw, method = "hyman")
fitted_cdf = spline_fit(dSup, deriv = 0)
fitted_pdf = spline_fit(dSup, deriv = 1)
fitted_pdf_prime = spline_fit(dSup, deriv = 2)
if(any(fitted_pdf==0)) {
index = which(fitted_pdf == 0)
fitted_pdf[index] = min(fitted_pdf[-index])
fitted_pdf = fitted_pdf/fdapace::trapzRcpp(X = dSup, Y = fitted_pdf)
fitted_cdf = fdapace::cumtrapzRcpp(X = dSup, Y = fitted_pdf)
}
return(cbind(cdf = fitted_cdf, pdf = fitted_pdf, pdf_prime = fitted_pdf_prime))
})
Qobs_t = t(apply(res_list_dSup[1:m_dSup, ], MARGIN = 2, FUN = function(fitted_cdf) {
unique_index = !duplicated(fitted_cdf)
approx(x = unique(fitted_cdf), y = dSup[unique_index], xout = t_vec,
rule = c(2, 2))[[2]]
}))
qobs_t = t(sapply(1:n, FUN = function(i) {
fitted_cdf = res_list_dSup[1:m_dSup, i]
unique_index = !duplicated(fitted_cdf)
approx(x = unique(fitted_cdf), y = 1/res_list_dSup[(m_dSup+1):(2*m_dSup), i][unique_index], xout = t_vec,
rule = c(2, 2))[[2]]
}))
qobs_prime_t = t(sapply(1:n, FUN = function(i) {
fitted_cdf = res_list_dSup[1:m_dSup, i]
unique_index = !duplicated(fitted_cdf)
approx(x = unique(fitted_cdf), y = (-1/res_list_dSup[(m_dSup+1):(2*m_dSup), i]^3 * res_list_dSup[(2*m_dSup+1):(3*m_dSup), i])[unique_index], xout = t_vec,
rule = c(2, 2))[[2]]
}))
res$Qobs = Qobs_t
res$qobs = qobs_t
res$qobs_prime = qobs_prime_t
res$fobs = 1/res$qobs
return(res)
} |
"stabiliser_example" |
library(OpenMx)
data(demoOneFactor)
manifests <- names(demoOneFactor)
latents <- c("G")
template <- mxModel(
"template", type="RAM",
manifestVars = manifests,
latentVars = latents,
mxPath(from=latents, to=manifests, values=rnorm(length(manifests))),
mxPath(from=manifests, arrows=2, values=rlnorm(length(manifests))),
mxPath(from=latents, arrows=2, free=FALSE, values=1.0),
mxPath(from = 'one', to = manifests, values=rnorm(length(manifests))))
factorRaw <- mxModel(template, name="OneFactorRaw",
mxData(demoOneFactor, type="raw"))
factorCov <- mxModel(template, name="OneFactorCov",
mxData(observed=cov(demoOneFactor), means=colMeans(demoOneFactor),
type="cov", numObs=nrow(demoOneFactor)))
plan <- mxComputeSequence(list(
mxComputeOnce('fitfunction', 'fit'),
mxComputeNumericDeriv(checkGradient=FALSE, hessian=FALSE, iterations=2),
mxComputeReportDeriv(),
mxComputeReportExpectation()
))
factorRaw <- mxRun(mxModel(factorRaw, plan))
factorCov <- mxRun(mxModel(factorCov, plan))
omxCheckCloseEnough(factorRaw$output$fit, factorCov$output$fit + prod(dim(demoOneFactor))*log(2*pi), 1e-10)
omxCheckCloseEnough(factorRaw$output$gradient, factorCov$output$gradient, 1e-5) |
check_predictions <- function(object,
iterations = 50,
check_range = FALSE,
re_formula = NULL,
...) {
if (isTRUE(insight::model_info(object, verbose = FALSE)$is_bayesian) &&
isFALSE(inherits(object, "BFBayesFactor"))) {
insight::check_if_installed(
"bayesplot",
"to create posterior prediction plots for Stan models"
)
bayesplot::pp_check(object)
} else if (isTRUE(inherits(object, "BFBayesFactor"))) {
insight::format_message(stop(
"Posterior preditive checks not yet supported for BayesFactor models",
call. = FALSE
))
} else {
pp_check.lm(
object,
iterations = iterations,
check_range = check_range,
re_formula = re_formula,
...
)
}
}
pp_check.lm <- function(object,
iterations = 50,
check_range = FALSE,
re_formula = NULL,
...) {
out <- tryCatch(
{
stats::simulate(object, nsim = iterations, re.form = re_formula, ...)
},
error = function(e) {
NULL
}
)
if (is.null(out)) {
stop(insight::format_message(sprintf("Could not simulate responses. Maybe there is no 'simulate()' for objects of class '%s'?", class(object)[1])), call. = FALSE)
}
response <- insight::get_response(object)
resp_string <- insight::find_terms(object)$response
pattern <- "^(scale|exp|expm1|log|log1p|log10|log2|sqrt)"
if (!is.null(resp_string) && grepl(paste0(pattern, "\\("), resp_string)) {
out <- .backtransform_sims(out, resp_string)
}
out$y <- response
attr(out, "check_range") <- check_range
class(out) <- c("performance_pp_check", "see_performance_pp_check", class(out))
out
}
pp_check.glm <-
pp_check.glmmTMB <-
pp_check.glm.nb <-
pp_check.lme <-
pp_check.merMod <-
pp_check.MixMod <-
pp_check.mle2 <-
pp_check.negbin <-
pp_check.polr <-
pp_check.rma <-
pp_check.vlm <-
pp_check.wbm <-
pp_check.lm
posterior_predictive_check <- check_predictions
check_posterior_predictions <- check_predictions
print.performance_pp_check <- function(x, verbose = TRUE, ...) {
original <- x$y
replicated <- x[which(names(x) != "y")]
if (min(replicated) > min(original)) {
if (verbose) {
insight::print_color(
insight::format_message("Warning: Minimum value of original data is not included in the replicated data.", "Model may not capture the variation of the data."),
"red"
)
}
}
if (max(replicated) < max(original)) {
if (verbose) {
insight::print_color(
insight::format_message("Warning: Maximum value of original data is not included in the replicated data.", "Model may not capture the variation of the data."),
"red"
)
}
}
if (requireNamespace("see", quietly = TRUE)) {
NextMethod()
}
invisible(x)
}
plot.performance_pp_check <- function(x, ...) {
insight::check_if_installed("see", "to plot posterior predictive checks")
NextMethod()
}
.backtransform_sims <- function(sims, resp_string) {
if (grepl("log(log(", resp_string, fixed = TRUE)) {
sims[] <- lapply(sims, function(i) exp(exp(i)))
} else if (grepl("log(", resp_string, fixed = TRUE)) {
sims[] <- lapply(sims, function(i) exp(i))
} else if (grepl("log1p(", resp_string, fixed = TRUE)) {
sims[] <- lapply(sims, function(i) expm1(i))
} else if (grepl("log10(", resp_string, fixed = TRUE)) {
sims[] <- lapply(sims, function(i) 10^i)
} else if (grepl("log2(", resp_string, fixed = TRUE)) {
sims[] <- lapply(sims, function(i) 2^i)
} else if (grepl("sqrt(", resp_string, fixed = TRUE)) {
sims[] <- lapply(sims, function(i) i^2)
} else if (grepl("exp(", resp_string, fixed = TRUE)) {
sims[] <- lapply(sims, function(i) log(i))
} else if (grepl("expm1(", resp_string, fixed = TRUE)) {
sims[] <- lapply(sims, function(i) log1p(i))
}
sims
} |
library(tidyverse)
library(here)
library(jkmisc)
library(ggraph)
library(tidygraph)
library(glue)
library(ggtext)
library(magick)
ikea <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-11-03/ikea.csv')
lvl_one <- ikea %>%
group_by(category) %>%
summarize(price = sum(price),
n = n()) %>%
mutate(from = "root") %>%
rename(to = category)
lvl_two <- ikea %>%
group_by(category, name) %>%
summarize(price = sum(price),
n = n()) %>%
rename(from = category,
to = name) %>%
mutate(idx = row_number())
edges <- bind_rows(lvl_one, lvl_two) %>%
select(from, to, n, price) %>%
distinct()
root <- summarize(edges, across(c(price, n), sum),
node = "root")
lvl_one_nodes <- lvl_one %>%
select(node = to, n, price)
lvl_two_nodes <- lvl_two %>%
ungroup() %>%
select(node = to, n, price, idx)
nodes <- bind_rows(root, lvl_one_nodes, lvl_two_nodes) %>%
distinct(node, n, price) %>%
select(node, n, price)
graph <- tbl_graph(nodes, edges)
final_graph <- graph %>%
activate(nodes) %>%
filter(!node_is_isolated())
stem_labels <- create_layout(final_graph, layout = 'dendrogram', circular = TRUE) %>%
filter(leaf == FALSE) %>%
slice(-1) %>%
mutate(percent = n/sum(n, na.rm = TRUE)) %>%
mutate(label = str_to_upper(str_replace_all(str_wrap(node, 10), "(?<=.)(?!$)", " "))) %>%
mutate(xend = case_when(node == "Sofas & armchairs" ~ x - 0.1,
node == "Sideboards, buffets & console tables" ~ x -0.07,
node == "Outdoor furniture" ~ x + 0.01,
node == "Room dividers" ~ x + 0.02,
node == "Nursery furniture" ~ x + 0.05,
node == "Children's furniture" ~ x + 0.1,
node == "Chests of drawers & drawer units" ~ x + 0.15,
TRUE ~ x)) %>%
mutate(yend = case_when(node == "Sofas & armchairs" ~ y + 0.1,
node == "Room dividers" ~ y,
TRUE ~ y)) %>%
mutate(xold = x,
x = xend,
yold = y,
y = yend)
lines <- stem_labels %>%
mutate(xold = case_when(node == "Sofas & armchairs" ~ xold + 0.01,
TRUE ~ xold),
y = case_when(node == "Sofas & armchairs" ~ y - 0.1,
TRUE ~ y))
groups <- final_graph %>%
activate(edges) %>%
as_tibble() %>%
mutate(idx = row_number()) %>%
filter(idx > 18) %>%
group_by(from) %>%
summarize(idx = range(idx))
bars <- create_layout(final_graph, layout = 'dendrogram', circular = TRUE) %>%
right_join(groups, by = c(".ggraph.index" = "idx")) %>%
mutate(x_item = rep(c("x", "xend"), 17)) %>%
pivot_wider(names_from = x_item, values_from = x) %>%
mutate(y_item = rep(c("y", "yend"), 17)) %>%
pivot_wider(names_from = y_item, values_from = y) %>%
group_by(from) %>%
summarize(across(.ggraph.orig_index:yend, mean, na.rm = TRUE)) %>%
mutate(circular = as.logical(circular))
plot <- ggraph(final_graph, layout = 'dendrogram', circular = TRUE) +
geom_edge_diagonal(colour = "
geom_node_text(aes(x = x*3, y = y*3, label = glue("{label}\n({scales::percent(percent, accuracy = 0.1)})"), filter = leaf == FALSE & node != 'root', hjust = ifelse(between(node_angle(x,y), 90, 270), 1, 0)), size = 3, color = "white", family = "Noto Sans Bold", data = stem_labels) +
geom_segment(aes(x = 2*xold, xend = 2.8*x, y = 2*y, yend = 2.8*yend), data = lines, color = "white", size = 0.2) +
geom_node_point(aes(filter = leaf), colour = "
geom_segment(data = filter(bars, from == 2), aes(x = x, xend = xend, y = y, yend = yend, group = 1)) +
labs(x = NULL,
y = NULL,
title = NULL,
subtitle = NULL,
caption = "**Data**: IKEA & Kaggle | **Graphic**: @jakekaupp") +
theme_jk(dark = TRUE,
grid = FALSE,
markdown = TRUE) +
theme(legend.position= "none",
plot.background = element_rect(fill = "
axis.text.x = element_blank(),
axis.text.y = element_blank()) +
expand_limits(x = c(-2, 2), y = c(-2, 2)) +
coord_equal()
ggsave(here("2020", "week45", "tw45_plot.png"), plot, width = 12, height = 12)
image_read(here("2020", "week45", "tw45_plot.png")) %>%
image_trim() %>%
image_write(here("2020", "week45", "tw45_plot.png")) |
require(distrEx)
options("newDevice"=TRUE)
D1 <- PrognCondDistribution(Error = Td(1))
D2 <- PrognCondDistribution(Error = Td(3))
D3 <- PrognCondDistribution(Error = ConvexContamination(Norm(), Norm(4,1), size=0.1))
D4 <- PrognCondDistribution(Error = ConvexContamination(Norm(), Norm(0,9), size=0.1))
D5 <- PrognCondDistribution(Error = ConvexContamination(Norm(), Norm(0,9), size=0.2))
y <- seq(from = 0, to = 8, length = 100)
f <- function(y, e1){ E(e1, fun = function(x){x[1]}, cond = y) }
system.time(erg1 <- sapply(y, f, D1))
system.time(erg2 <- sapply(y, f, D2))
system.time(erg3 <- sapply(y, f, D3))
system.time(erg4 <- sapply(y, f, D4))
system.time(erg5 <- sapply(y, f, D5))
post.mod <- function(cond, e1) {
optimize(f = d(e1), interval = c(q.l(e1)(1e-3, cond),
q.l(e1)(1e-3, cond, lower.tail = FALSE)),
tol = .Machine$double.eps^0.25, maximum = TRUE, cond = cond)$maximum
}
D0 <- PrognCondDistribution()
system.time(perg0 <- sapply(y, post.mod, D0))
system.time(perg1 <- sapply(y, post.mod, D1))
system.time(perg2 <- sapply(y, post.mod, D2))
system.time(perg3 <- sapply(y, post.mod, D3))
system.time(perg4 <- sapply(y, post.mod, D4))
system.time(perg5 <- sapply(y, post.mod, D5))
plot(y, 0.5*y, type = "l")
lines(y, erg1, col = "red")
lines(y, erg2, col = "blue")
lines(y, erg3, col = "orange")
lines(y, erg4, col = "darkgreen")
lines(y, erg5, col = "darkred")
title("Posterior Mean")
windows()
plot(y, perg0, type = "l", ylim = c(-0.5, 4))
lines(y, perg1, col = "red")
lines(y, perg2, col = "blue")
lines(y, perg3, col = "orange")
lines(y, perg4, col = "darkgreen")
lines(y, perg5, col = "darkred")
title("Posterior Modus") |
mackWolfeTest <- function(x, ...) UseMethod("mackWolfeTest")
mackWolfeTest.default <-
function(x, g, p = NULL, nperm=1000,...)
{
if (is.list(x)) {
if (length(x) < 2L)
stop("'x' must be a list with at least 2 elements")
DNAME <- deparse(substitute(x))
x <- lapply(x, function(u) u <- u[complete.cases(u)])
k <- length(x)
l <- sapply(x, "length")
if (any(l == 0))
stop("all groups must contain data")
g <- factor(rep(1 : k, l))
p <- x$p
nperm <- x$nperm
x <- unlist(x)
}
else {
if (length(x) != length(g))
stop("'x' and 'g' must have the same length")
DNAME <- paste(deparse(substitute(x)), "and",
deparse(substitute(g)))
OK <- complete.cases(x, g)
x <- x[OK]
g <- g[OK]
if (!all(is.finite(g)))
stop("all group levels must be finite")
g <- factor(g)
k <- nlevels(g)
if (k < 2)
stop("all observations are in the same group")
}
if (!is.null(p)){
if (p > k){
stop("Selected 'p' > Nr. of groups: ", p, " > ", k)
} else if (p < 1){
stop("Selected 'p' < 1: ", p)
}
}
Rij <- rank(x)
n <- tapply(x, g, length)
Ustat.fn <- function(Rij, g, k){
lev <- levels(g)
U <- diag(k)
.fn <- function(Ri, Rj){
tmp <- sum(
unlist(
sapply(Ri, function(i)
length(Rj[Rj > i])
)
)
)
return(tmp)
}
for(i in 2:k){
for(j in 1:(i-1)){
U[i,j] <- .fn(Rij[g==lev[i]], Rij[g==lev[j]])
U[j,i] <- .fn(Rij[g==lev[j]], Rij[g==lev[i]])
}
}
return(U)
}
Ap.fn <- function(p, U){
tmp1 <- 0
if (p > 1){
for(i in 1:(p-1)){
for (j in (i+1):p){
tmp1 <- tmp1 + U[i,j]
}
}
}
tmp2 <- 0
if (p < k){
for (i in p:(k-1)){
for(j in (i+1):k){
tmp2 <- tmp2 + U[j,i]
}
}
}
return(tmp1 + tmp2)
}
N1.fn <- function(p, n) sum(n[1:p])
N2.fn <- function(p, n) sum(n[p:k])
meanAt <- function(p, n){
N1 <- N1.fn(p, n)
N2 <- N2.fn(p, n)
return((N1^2 + N2^2 - sum(n^2) - n[p]^2)/4)
}
varAt <- function(p, n){
N1 <- N1.fn(p, n)
N2 <- N2.fn(p, n)
N <- sum(n)
var0 <- (2 * (N1^3 + N2^3) +
3 * (N1^2 + N2^2) -
sum(n^2 * (2 * n + 3)) - n[p]^2 *
(2 * n[p] + 3) + 12 * n[p] *
N1 * N2 - 12 * n[p]^2 * N) / 72
return(var0)
}
if (!is.null(p)){
if(sum(table(x) - 1) > 0){
warning(c("Ties are present. Exact variances can not be computed.",
" p-values are over-estimated."))
}
U <- Ustat.fn(Rij, g, k)
EST <- c("Ap" = Ap.fn(p, U))
MEAN <- meanAt(p, n)
SD <- sqrt(varAt(p,n))
METHOD <- c("Mack-Wolfe test for umbrella alternatives",
"with known peak")
STAT <- (EST - MEAN)/ SD
names(STAT) <- NULL
names(STAT) <- "z"
PVAL <- pnorm(STAT, lower.tail=FALSE)
} else {
U <- Ustat.fn(Rij, g, k)
Ap <- sapply(1:k, function(p) Ap.fn(p, U))
mean0 <- sapply(1:k, function(p) meanAt(p, n))
var0 <- sapply(1:k, function(p) varAt(p, n))
Astar <- (Ap - mean0) / sqrt(var0)
STAT <- c("Ap*" = max(Astar))
p <- which(Astar == STAT)
EST <- NULL
mt <- sapply(1:nperm, function(i){
ix <- sample(Rij)
Uix <- Ustat.fn(ix, g, k)
Apix <- sapply(1:k, function(p) Ap.fn(p, Uix))
Astarix <- (Apix - mean0) / sqrt(var0)
max(Astarix)
})
PVAL <- length(mt[mt > STAT]) / nperm
METHOD <- c("Mack-Wolfe test for umbrella alternatives",
"with unknown peak")
}
ans <- list(method = METHOD,
data.name = DNAME,
p.value = PVAL,
statistic = STAT,
alternative = paste0("\ntheta_1 <= ... <= theta_p >= ... >= theta_k, p = ",p),
estimates = EST)
class(ans) <- "htest"
ans
}
mackWolfeTest.formula <-
function(formula, data, subset, na.action, p = NULL, nperm=1000, ...)
{
mf <- match.call(expand.dots=FALSE)
m <- match(c("formula", "data", "subset", "na.action"), names(mf), 0L)
mf <- mf[c(1L, m)]
mf[[1L]] <- quote(stats::model.frame)
if(missing(formula) || (length(formula) != 3L))
stop("'formula' missing or incorrect")
mf <- eval(mf, parent.frame())
if(length(mf) > 2L)
stop("'formula' should be of the form response ~ group")
DNAME <- paste(names(mf), collapse = " by ")
names(mf) <- NULL
y <- do.call("mackWolfeTest", c(as.list(mf), p = p, nperm=nperm))
y$data.name <- DNAME
y
} |
testData = createData(sampleSize = 40, family = gaussian(),
randomEffectVariance = 0)
fittedModel <- lm(observedResponse ~ Environment1, data = testData)
res = simulateResiduals(fittedModel)
testTemporalAutocorrelation(res, time = testData$time)
timeSeries1 = createData(sampleSize = 40, family = gaussian(),
randomEffectVariance = 0)
timeSeries1$location = 1
timeSeries2 = createData(sampleSize = 40, family = gaussian(),
randomEffectVariance = 0)
timeSeries2$location = 2
testData = rbind(timeSeries1, timeSeries2)
fittedModel <- lm(observedResponse ~ Environment1, data = testData)
res = simulateResiduals(fittedModel)
res = recalculateResiduals(res, group = testData$time)
testTemporalAutocorrelation(res, time = unique(testData$time))
res = recalculateResiduals(res, sel = testData$location == 1)
testTemporalAutocorrelation(res, time = unique(testData$time))
\dontrun{
set.seed(1)
C <- exp(-as.matrix(dist(seq(0,50,by=.5))))
obs <- as.numeric(mvtnorm::rmvnorm(1,sigma=C))
opar <- par(mfrow = c(1,2))
image(C, main = "Specified autocorrelation (covariance)")
plot(obs, type = "l", main = "Time series")
par(opar)
x = replicate(1000, as.numeric(mvtnorm::rmvnorm(1,sigma=C)))
res <- createDHARMa(x, obs, integerResponse = F)
plot(res)
testTemporalAutocorrelation(res, time = 1:length(res$scaledResiduals))
res <- createDHARMa(x, obs, integerResponse = F, rotation = C)
testUniformity(res)
testTemporalAutocorrelation(res, time = 1:length(res$scaledResiduals))
res <- createDHARMa(x, obs, integerResponse = F, rotation = "estimated")
testUniformity(res)
testTemporalAutocorrelation(res, time = 1:length(res$scaledResiduals))
} |
as_seqinr_alignment <- function (x, ...) {
UseMethod("as_seqinr_alignment", x)
}
as_seqinr_alignment.bioseq_dna <- function(x, ...) {
check_dna(x)
s <- x
attributes(s) <- NULL
res <- list(nb = length(x),
nam = names(x),
seq = s)
class(res) <- "alignment"
return(res)
}
as_seqinr_alignment.bioseq_rna <- function(x, ...) {
check_rna(x)
s <- x
attributes(s) <- NULL
res <- list(nb = length(x),
nam = names(x),
seq = s)
class(res) <- "alignment"
return(res)
}
as_seqinr_alignment.bioseq_aa <- function(x, ...) {
check_aa(x)
s <- x
attributes(s) <- NULL
res <- list(nb = length(x),
nam = names(x),
seq = s)
class(res) <- "alignment"
return(res)
} |
"ecld.mpnum" <- function(object, x)
{
if ([email protected]) return(ecd.mpfr(x))
if (class(x)=="list") return(simplify2array(x))
return(x)
}
"ecld.ifelse" <- function(object, test, yes, no) {
rs <- ifelse(test, ecld.mpnum(object, yes), ecld.mpnum(object, no))
ecld.mpnum(object, rs)
}
"ecld.sapply" <- function(object, x, FUN, ...) {
rs <- sapply(x, FUN, ...)
ecld.mpnum(object, rs)
}
"ecld.mclapply" <- function(object, x, FUN, ...) {
rs <- parallel::mclapply(x, FUN, ...)
ecld.mpnum(object, rs)
} |
local({
wrap.file <- function() tcltk::tclvalue(file.name) <- tcltk::tcl("tk_getOpenFile")
wrap.mask <- function() tcltk::tclvalue(mask) <- tcltk::tcl("tk_getOpenFile")
do <- function(){
if(tcltk::tclvalue(alt) == "File Summary") fs()
if(tcltk::tclvalue(alt) == "Plot Time Series") pts()
if(tcltk::tclvalue(alt) == "Plot Periodogram") period()
if(tcltk::tclvalue(alt) == "Image Slice") im.sl()
if(tcltk::tclvalue(alt) == "Image Volume") im.vol()
if(tcltk::tclvalue(alt) == "Movie") im.mov()
if(tcltk::tclvalue(alt) == "Spectral Summary") im.spec()
}
fs <- function(...) f.analyze.file.summary(tcltk::tclvalue(file.name))
pts <- function(...) {
plot(f.read.analyze.ts(tcltk::tclvalue(file.name),
as.numeric(tcltk::tclvalue(x)),
as.numeric(tcltk::tclvalue(y)),
as.numeric(tcltk::tclvalue(z))),
typ = "l", ylab = "fMRI response",
xlab = "Scans")
}
period <- function(...){
par(mfrow = c(1, 1), mar = c(4, 4, 5, 5))
a <- f.read.analyze.ts(tcltk::tclvalue(file.name),
as.numeric(tcltk::tclvalue(x)),
as.numeric(tcltk::tclvalue(y)),
as.numeric(tcltk::tclvalue(z)))
b <- fft(a) / sqrt(2 * pi * length(a))
b <- b[10:floor(length(b) / 2) + 1]
b <- Mod(b)^2
plot(b, ylab = "Periodogram", xlab = "Fourier Frequency")
}
im.sl <- function(...){
par(mfrow = c(1, 1), mar = c(0, 0, 0, 0))
a <- f.read.analyze.slice(tcltk::tclvalue(file.name),
as.numeric(tcltk::tclvalue(z)),
as.numeric(tcltk::tclvalue(t)))
image(a)
par(mfrow = c(1, 1), mar = c(4, 4, 5, 5))
}
im.vol <- function(...){
a <- f.read.analyze.header(tcltk::tclvalue(file.name))$dim
d <- ceiling(sqrt(a[4]))
par(mfrow =c(d, d), mar = c(0, 0, 0, 0))
b <- array(0, dim = a[2:4])
for(i in 1:a[4]){
b[, , i] <- f.read.analyze.slice(tcltk::tclvalue(file.name),
i,
as.numeric(tcltk::tclvalue(t)))
}
for(i in 1:a[4]){
image(b[, , i], axes = FALSE)
box()
}
par(mfrow = c(1, 1), mar = c(4, 4, 5, 5))
}
im.mov <- function(...){
par(mfrow = c(1, 1), mar = c(0, 0, 0, 0))
a <- f.read.analyze.header(tcltk::tclvalue(file.name))$dim
b <- array(0, dim = c(a[2], a[3], a[5]))
for(i in 1:a[5]){
b[, , i] <- f.read.analyze.slice(tcltk::tclvalue(file.name),
as.numeric(tcltk::tclvalue(z)),
i)
}
image(b[, , 1], axes = FALSE)
for(i in 2:a[5]){
image(b[, , i], axes = FALSE, add = TRUE)
}
par(mfrow = c(1, 1), mar = c(4, 4, 5, 5))
}
im.spec <- function(...){
par(mfrow = c(1, 1), mar = c(4, 4, 5, 5))
if(tcltk::tclvalue(mask) == "") tcltk::tclvalue(mask) <- FALSE
a <- f.spectral.summary(tcltk::tclvalue(file.name), tcltk::tclvalue(mask))
par(mfrow = c(1, 1), mar = c(4, 4, 5, 5))
}
mask <- tcltk::tclVar("sdasd")
alt <- tcltk::tclVar()
x <- tcltk::tclVar()
y <- tcltk::tclVar()
z <- tcltk::tclVar()
t <- tcltk::tclVar()
if(.Platform$OS.type == "windows") flush.console()
base <- tcltk::tktoplevel()
tcltk::tkwm.title(base, "ANALYZE file explore")
f1 <- tcltk::tkframe(base, relief = "groove", borderwidth = 2)
file.name <- tcltk::tclVar()
tcltk::tkpack(tcltk::tkentry(f1, textvariable = file.name, width = 40))
file.find.but <- tcltk::tkbutton(f1, text = "Select File", command = wrap.file)
tcltk::tkpack(file.find.but)
mask <- tcltk::tclVar()
tcltk::tkpack(tcltk::tkentry(f1, textvariable = mask, width = 40))
mask.find.but <- tcltk::tkbutton(f1, text = "Select Mask File", command = wrap.mask)
tcltk::tkpack(mask.find.but)
opt.rbuts <- tcltk::tkframe(base, relief = "groove", borderwidth = 2)
tcltk::tkpack(tcltk::tklabel(opt.rbuts, text = "Options"))
alt <- tcltk::tclVar()
for (i in c("File Summary",
"Plot Time Series",
"Plot Periodogram",
"Image Slice",
"Image Volume",
"Movie",
"Spectral Summary")) {
tmp <- tcltk::tkradiobutton(opt.rbuts, text = i, variable = alt, value = i)
tcltk::tkpack(tmp, anchor = "w")
}
fr2 <- tcltk::tkframe(base, relief = "groove", borderwidth = 2)
x <- tcltk::tclVar()
x.entry <- tcltk::tkentry(fr2, textvariable = x)
y <- tcltk::tclVar()
y.entry <- tcltk::tkentry(fr2, textvariable = y)
z <- tcltk::tclVar()
z.entry <- tcltk::tkentry(fr2, textvariable = z)
t <- tcltk::tclVar()
t.entry <- tcltk::tkentry(fr2, textvariable = t)
tcltk::tkgrid(f1)
tcltk::tkgrid(tcltk::tklabel(fr2, text = "Variables"), columnspan = 2)
tcltk::tkgrid(tcltk::tklabel(fr2, text = "x variable"), x.entry)
tcltk::tkgrid(tcltk::tklabel(fr2, text = "y variable"), y.entry)
tcltk::tkgrid(tcltk::tklabel(fr2, text = "z variable"), z.entry)
tcltk::tkgrid(tcltk::tklabel(fr2, text = "t variable"), t.entry)
tcltk::tkgrid(opt.rbuts)
tcltk::tkgrid(fr2)
fr3 <- tcltk::tkframe(base, borderwidth = 2)
q.but <- tcltk::tkbutton(fr3, text = "Quit",
command = function() tcltk::tkdestroy(base))
ok.but <- tcltk::tkbutton(fr3, text = "OK", command = do)
tcltk::tkgrid(ok.but, q.but)
tcltk::tkgrid(fr3)
}) |
Subsets and Splits