code
stringlengths
1
13.8M
postmed <- function (x, s = 1, w = 0.5, prior = "laplace", a = 0.5) { pr <- substring(prior, 1, 1) if(pr == "l") muhat <- postmed.laplace(x, s, w, a) if(pr == "c") { if(any(s != 1)) stop(paste("Only standard deviation of 1 is allowed", "for Cauchy prior.")) muhat <- postmed.cauchy(x, w) } return(muhat) }
garchSim <- function(spec = garchSpec(), n = 100, n.start = 100, extended = FALSE) { stopifnot(class(spec) == "fGARCHSPEC") model = spec@model if (spec@rseed != 0) set.seed(spec@rseed) n = n + n.start if (spec@distribution == "norm") z = rnorm(n) if (spec@distribution == "ged") z = rged(n, nu = model$shape) if (spec@distribution == "std") z = rstd(n, nu = model$shape) if (spec@distribution == "snorm") z = rsnorm(n, xi = model$skew) if (spec@distribution == "sged") z = rsged(n, nu = model$shape, xi = model$skew) if (spec@distribution == "sstd") z = rsstd(n, nu = model$shape, xi = model$skew) delta = model$delta z = c(rev(spec@presample[, 1]), z) h = c(rev(spec@presample[, 2]), rep(NA, times = n)) y = c(rev(spec@presample[, 3]), rep(NA, times = n)) m = length(spec@presample[, 1]) names(z) = names(h) = names(y) = NULL mu = model$mu ar = model$ar ma = model$ma omega = model$omega alpha = model$alpha gamma = model$gamma beta = model$beta deltainv = 1/delta order.ar = length(ar) order.ma = length(ma) order.alpha = length(alpha) order.beta = length(beta) eps = h^deltainv*z for (i in (m+1):(n+m)) { h[i] = omega + sum(alpha*(abs(eps[i-(1:order.alpha)]) - gamma*(eps[i-(1:order.alpha)]))^delta) + sum(beta*h[i-(1:order.beta)]) eps[i] = h[i]^deltainv * z[i] y[i] = mu + sum(ar*y[i-(1:order.ar)]) + sum(ma*eps[i-(1:order.ma)]) + eps[i] } data = cbind( z = z[(m+1):(n+m)], sigma = h[(m+1):(n+m)]^deltainv, y = y[(m+1):(n+m)]) rownames(data) = as.character(1:n) data = data[-(1:n.start),] from <- timeDate(format(Sys.time(), format = "%Y-%m-%d")) - NROW(data)*24*3600 charvec <- timeSequence(from = from, length.out = NROW(data)) ans <- timeSeries(data = data[, c(3,2,1)], charvec = charvec) colnames(ans) <- c("garch", "sigma", "eps") ans <- if (extended) ans else ans[,"garch"] attr(ans, "control") <- list(garchSpec = spec) ans }
pal_uchicago <- function(palette = c("default", "light", "dark"), alpha = 1) { palette <- match.arg(palette) if (alpha > 1L | alpha <= 0L) stop("alpha must be in (0, 1]") raw_cols <- ggsci_db$"uchicago"[[palette]] raw_cols_rgb <- col2rgb(raw_cols) alpha_cols <- rgb( raw_cols_rgb[1L, ], raw_cols_rgb[2L, ], raw_cols_rgb[3L, ], alpha = alpha * 255L, names = names(raw_cols), maxColorValue = 255L ) manual_pal(unname(alpha_cols)) } scale_color_uchicago <- function(palette = c("default", "light", "dark"), alpha = 1, ...) { palette <- match.arg(palette) discrete_scale("colour", "uchicago", pal_uchicago(palette, alpha), ...) } scale_colour_uchicago <- scale_color_uchicago scale_fill_uchicago <- function(palette = c("default", "light", "dark"), alpha = 1, ...) { palette <- match.arg(palette) discrete_scale("fill", "uchicago", pal_uchicago(palette, alpha), ...) }
output$radar1 <- rAmCharts::renderAmCharts({ dp <- data.frame(Eye = c('Blue', 'Brown', 'Green', 'Hazel') , Male = c(101, 98, 33, 47), Female = c(114, 122, 31, 46)) pipeR::pipeline( amRadarChart(startDuration = 0, categoryField = 'Eye', dataProvider = dp), addGraph(balloonText = '(male) [[category]]: [[value]]', valueField = 'Male', title = 'Male', bullet = 'round'), addGraph(balloonText = '(female) [[category]]: [[value]]', valueField = 'Female', title = 'Female', bullet = 'round'), addValueAxis(gridType = 'circles') ) }) output$code_radar1 <- renderText({ " dp <- data.frame(Eye = c('Blue', 'Brown', 'Green', 'Hazel') , Male = c(101, 98, 33, 47), Female = c(114, 122, 31, 46)) pipeR::pipeline( amRadarChart(startDuration = 0, categoryField = 'Eye', dataProvider = dp), addGraph(balloonText = '(male) [[category]]: [[value]]', valueField = 'Male', title = 'Male', bullet = 'round'), addGraph(balloonText = '(female) [[category]]: [[value]]', valueField = 'Female', title = 'Female', bullet = 'round'), addValueAxis(gridType = 'circles') ) " }) output$radar3 <- rAmCharts::renderAmCharts({ dp <- data.frame(Eye = c('Blue' ,'Brown' , 'Green', 'Hazel'), Male = c(101, 98, 33, 47), Female = c(114, 122, 31, 46)) pipeR::pipeline( amRadarChart(startDuration = 0, categoryField = 'Eye', dataProvider = dp), addGraph(balloonText = '(male) [[category]]: [[value]]', valueField = 'Male', title = 'Male',fillAlphas = 0.5,bullet = 'xError'), addGraph(balloonText = '(female) [[category]]: [[value]]', valueField = 'Female', title = 'Female', bullet = 'round'), setLegend(position = 'right'), addTitle(text='Title exemple') ) }) output$code_radar3 <- renderText({ " dp <- data.frame(Eye = c('Blue' ,'Brown' , 'Green', 'Hazel'), Male = c(101, 98, 33, 47), Female = c(114, 122, 31, 46)) pipeR::pipeline( amRadarChart(startDuration = 0, categoryField = 'Eye', dataProvider = dp), addGraph(balloonText = '(male) [[category]]: [[value]]', valueField = 'Male', title = 'Male',fillAlphas = 0.5,bullet = 'xError'), addGraph(balloonText = '(female) [[category]]: [[value]]', valueField = 'Female', title = 'Female', bullet = 'round'), setLegend(position = 'right'), addTitle(text='Title exemple') ) " }) output$radar2 <- rAmCharts::renderAmCharts({ data('data_wind') data_wind$category <- c('N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NO') pipeR::pipeline( amRadarChart(theme = 'light', startDuration = 0, categoryField = 'category', dataProvider = data_wind), addValueAxis(gridType = 'circles', minimum = 0, autoGridCount = FALSE, axisAlpha = 0.2, fillAlpha = 0.05, fillColor = ' gridAlpha = 0.08, position = 'left'), addGuide(angle = 225, fillAlpha = 0.3, fillColor = ' tickLength = 0, toAngle = 315, toValue = 5, value = 0, lineAlpha = 0), addGuide(angle = 45, fillAlpha = 0.3, fillColor = ' tickLength = 0, toAngle = 135, toValue = 5, value = 0, lineAlpha = 0), addGraph(balloonText = '[[category]]: [[value]] m/s', bullet = 'round', fillAlphas = 0.3, valueField = 'weak') ) }) output$code_radar2 <- renderText({ " data('data_wind') data_wind$category <- c('N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NO') pipeR::pipeline( amRadarChart(theme = 'light', startDuration = 0, categoryField = 'category', dataProvider = data_wind), addValueAxis(gridType = 'circles', minimum = 0, autoGridCount = FALSE, axisAlpha = 0.2, fillAlpha = 0.05, fillColor = ' gridAlpha = 0.08, position = 'left'), addGuide(angle = 225, fillAlpha = 0.3, fillColor = ' tickLength = 0, toAngle = 315, toValue = 5, value = 0, lineAlpha = 0), addGuide(angle = 45, fillAlpha = 0.3, fillColor = ' tickLength = 0, toAngle = 135, toValue = 5, value = 0, lineAlpha = 0), addGraph(balloonText = '[[category]]: [[value]] m/s', bullet = 'round', fillAlphas = 0.3, valueField = 'weak') ) " })
source("./prep_data/prep_functions.R") library(readxl) library(dplyr) library(tidyr) library(data.table) library(sf) library(magrittr) library(ggplot2) matching <- function(data_mun=NULL, y0){ temp <- data_mun %>% select(c(paste0("clu",y0),clu_new)) %>% filter(!is.na(clu_new)) %>% arrange(get(paste0("clu",y0)),clu_new) %>% filter(!(get(paste0("clu",y0))==clu_new) ) if (nrow(temp) > 1) { temp$diff <- 0 for(i in 2:nrow(temp)){ if (is.na(temp[,c(paste0("clu",y0))][i-1]) | is.na( temp[,c("clu_new")][i-1]) ) next else if (temp[,c(paste0("clu",y0))][i] == temp[,c(paste0("clu",y0))][i-1] & temp[,c("clu_new")][i] == temp[,c("clu_new")][i-1]) temp$diff[i] <- 1 } temp <- temp %>% filter(diff != 1) temp <- temp %>% select(-diff) } temp <- temp %>% mutate(!!paste0("clu",quo_name(y0)) := ifelse(is.na(get(paste0("clu",y0))),-999999999,get(paste0("clu",y0)))) rep_c<-0 repeat { rep_c <- (rep_c + 1) while (sum(temp[,c(paste0("clu",y0))] == lag(temp[,c(paste0("clu",y0))],1),na.rm = T) != 0) { for(i in 2:nrow(temp)) if (temp[,c(paste0("clu",y0))][i] == temp[,c(paste0("clu",y0))][i-1]) temp[,c(paste0("clu",y0))][i] <- temp$clu_new[i] for(i in 2:nrow(temp)) if (temp$clu_new[i] == temp[,c(paste0("clu",y0))][i]) temp$clu_new[i] <- temp$clu_new[i-1] temp<- temp[order(temp[,1],temp[,2]),] temp <- temp %>% filter( !(get(paste0("clu",y0)) == clu_new) ) temp$diff <- 0 for(i in 2:nrow(temp)){ if (is.na(temp[,c(paste0("clu",y0))][i-1]) | is.na( temp[,c("clu_new")][i-1]) ) next else if (temp[,c(paste0("clu",y0))][i] == temp[,c(paste0("clu",y0))][i-1] & temp[,c("clu_new")][i] == temp[,c("clu_new")][i-1]) temp$diff[i] <- 1 } temp <- temp %>% filter(diff != 1) temp <- temp %>% select(-diff) } temp2 <- temp temp2 <- temp2 %>% rename(help = clu_new, clu_new = paste0("clu",y0) ) temp2 <- bind_rows(temp,temp2) %>% mutate_all(function(x) ifelse(is.na(x),-999999999,x)) temp2<- temp2[order(temp2[,2],-xtfrm(temp2[,3])),] if (sum(temp2$clu_new == lead(temp2$clu_new,1) & temp2$help != -999999999,na.rm = T) != 0) { temp3 <- temp temp3 <- temp3 %>% rename(clu_new2 = clu_new, clu_new = paste0("clu",y0) ) temp3 <- left_join(temp,temp3) temp3 <- temp3 %>% mutate(clu_new2 = ifelse(is.na(clu_new2),clu_new,clu_new2)) temp3 <- temp3 %>% filter( get(paste0("clu",y0))!=-999999999 ) temp3 <- temp3 %>% filter( !is.na(get(paste0("clu",y0))) ) temp3 <- temp3 %>% select(-clu_new) temp3 <- temp3 %>% rename(clu_new = clu_new2) temp3<- temp3[order(temp3[,1],temp3[,2]),] temp3 <- temp3 %>% filter( !(get(paste0("clu",y0)) == clu_new) ) temp3$diff <- 0 for(i in 2:nrow(temp3)){ if (is.na(temp3[,c(paste0("clu",y0))][i-1]) | is.na( temp3[,c("clu_new")][i-1]) ) next else if (temp3[,c(paste0("clu",y0))][i] == temp3[,c(paste0("clu",y0))][i-1] & temp3[,c("clu_new")][i] == temp3[,c("clu_new")][i-1]) temp3$diff[i] <- 1 } temp3 <- temp3 %>% filter(diff != 1) temp <- temp3 %>% select(-diff) rm(temp3) } if (rep_c == 3){ break } } temp <- as.data.table(temp) %>% mutate(!!paste0("clu",quo_name(y0)) := as.numeric(as.character(get(paste0("clu",y0))))) data_mun <- data_mun %>% select(-clu_new) %>% left_join(temp) %>% mutate(!!paste0("clu",quo_name(y0)) := ifelse(!(is.na(clu_new)),clu_new,get(paste0("clu",y0)))) %>% select(-clu_new) rm(temp,temp2) return(data_mun) } table_amc <- function(startyear=NULL, endyear=NULL){ if((startyear %in% c(1872,1900,1911,1920,1933,1940, 1950,1960,1970,1980,1991,2000,2010)) & (endyear %in% c(1872,1900,1911,1920,1933,1940, 1950,1960,1970,1980,1991,2000,2010))){ message(paste0("Loading amc algorithm for ", startyear, " to ", endyear,"\n")) }else { stop("Error: Invalid Value to argument.") } y0 <- startyear while (y0 != endyear) { if (y0==startyear){ data_mun <- readr::read_rds("./prep_data/amc_algorithm/_Crosswalk_pre.rds") } else{ data_mun <- get(paste0("_Crosswalk_",y_1)) } if (y0==1872) { y1 <- 1900 } else if (y0==1900) { y1 <- 1911 } else if (y0==1911) { y1 <- 1920 } else if (y0==1920) { y1 <- 1933 } else if (y0==1933) { y1 <- 1940 } else if (y0==1940) { y1 <- 1950 } else if (y0==1950) { y1 <- 1960 } else if (y0==1960) { y1 <- 1970 } else if (y0==1970) { y1 <- 1980 } else if (y0==1980) { y1 <- 1991 } else if (y0==1991) { y1 <- 2000 } else if (y0==2000) { y1 <- 2010 } else if (y0==2010) { y1 <- 2020 } else { y1 <- 2030 } ano_dest <- paste0("n_dest",y0) ano_dest1 <- paste0("dest1",y0) exist_dummy1 <- paste0("exist_d",y1) exist_dummy0 <- paste0("exist_d",y0) cluster0 <- paste0("clu",y0) cluster1 <- paste0("clu",quo_name(y0)) cluster_original <- paste0("clu",quo_name(y0),"_orig") data_mun <- data_mun %>% mutate(ch_match = as.numeric(get( ano_dest ))) data_mun[,c(exist_dummy1)] <- as.numeric(data_mun[,c(exist_dummy1)]) data_mun[,c(exist_dummy0)] <- as.numeric(data_mun[,c(exist_dummy0)]) if (y0 == startyear) { data_mun <- data_mun %>% mutate(uf_amc = as.numeric(uf_amc)) %>% arrange(uf_amc, get(ano_dest1), desc(get(exist_dummy0)), final_name) a <- data_mun %>% select(c(uf_amc, ano_dest1)) %>% unique() %>% filter(get(ano_dest1) != "") a <- a %>% mutate(!!cluster1 := rownames(a), !!cluster1 := as.numeric(get(cluster0))) data_mun <- left_join(data_mun, a) rm(a) setDT(data_mun)[, paste0(cluster_original) := get(cluster0) ] data_mun <- as.data.frame(data_mun) } else { data_mun[,c(cluster0)] <- NA data_mun <- data_mun %>% mutate(!!cluster1 := get(paste0("clu",y_1,"_final"))) %>% arrange(get(cluster0),desc(get(ano_dest1)),code2010) for(i in 2:(nrow(data_mun)) ){ if (data_mun[,c(ano_dest1)][i] !="" & is.na(data_mun[,c(cluster0)][i])) data_mun[,c(cluster0)][i] <- data_mun[,c(cluster0)][i-1] + 1 } } data_mun <- data_mun %>% mutate(ch_match = ifelse(code2010==2205706 & y0==1872,ch_match-1, ifelse(code2010==4204202 & y0==1911,ch_match-1, ifelse(code2010==4209003 & y0==1911,ch_match-1, ifelse(code2010==4213609 & y0==1911,ch_match-1, ifelse(code2010==4208104 & y0==1911,ch_match-1, ifelse(code2010==4210100 & y0==1911,ch_match-1, ifelse(code2010==1100205 & y0==1911,ch_match-1,ch_match)))))))) data_mun$clu_new <- NA data_mun <- data_mun %>% arrange(uf_amc, get(ano_dest1), desc(get(exist_dummy0)), final_name) for(i in 2:nrow(data_mun)){ if (data_mun[,c(ano_dest1)][i] == data_mun[,c(ano_dest1)][i-1] & !is.na(data_mun[,c(cluster0)][i-1]) & data_mun[,c(ano_dest1)][i] != "" ) data_mun$clu_new[i] <- data_mun[,c(cluster0)][i-1] } for(i in 2:nrow(data_mun)){ if (data_mun[,c(ano_dest1)][i] == data_mun[,c(ano_dest1)][i-1] & !is.na(data_mun[,c("clu_new")][i-1])) data_mun$clu_new[i] <- data_mun$clu_new[i-1] } data_mun <- data_mun %>% mutate(ch_match = ifelse( !is.na(clu_new), ch_match-1, ch_match) ) data_mun <- matching(data_mun=data_mun, y0=y0) for (p in 2:5) { if (paste0("dest",p,y0) %in% colnames(data_mun)) { data_mun <- data_mun %>% mutate(!!paste0("mis",quo_name(y0)) := ifelse(get(ano_dest) >= p,get(paste0("dest",p,y0)),NA)) data_mun <- data_mun %>% mutate(target = ifelse(!is.na(get(paste0("mis",y0))),1,0)) data_mun$clu_new <- NA data_mun <- data_mun %>% mutate(!!paste0("mis",quo_name(y0)) := ifelse(target==0 & get(exist_dummy1) == 1, get(paste0("dest1",y1)), get(paste0("mis",y0)))) data_mun <- data_mun %>% arrange(uf_amc, get(paste0("mis",y0)), desc(target), final_name) for(i in 1:(nrow(data_mun)-1) ){ if (data_mun[,c(paste0("mis",y0))][i] == data_mun[,c(paste0("mis",y0))][i+1] & !is.na(data_mun[,c(cluster0)][i+1]) & data_mun[,c("target")][i] == 1 ) data_mun$clu_new[i] <- data_mun[,c(cluster0)][i+1] } data_mun <- data_mun %>% mutate(!!paste0("mis",quo_name(y0)) := ifelse(target==0 & get(exist_dummy0)==1, get(ano_dest1),get(paste0("mis",y0)))) data_mun <- data_mun %>% arrange(uf_amc, get(paste0("mis",y0)), desc(target), final_name) for(i in 1:(nrow(data_mun)-1) ){ if (data_mun[,c(paste0("mis",y0))][i] == data_mun[,c(paste0("mis",y0))][i+1] & !is.na(data_mun[,c(cluster0)][i+1]) & data_mun[,c("target")][i] == 1 & is.na(data_mun[,c("clu_new")][i])) data_mun$clu_new[i] <- data_mun[,c(cluster0)][i+1] } data_mun <- data_mun %>% mutate(!!paste0("mis",quo_name(y0)) := ifelse(target==0,final_name,get(paste0("mis",y0)))) data_mun <- data_mun %>% arrange(uf_amc, get(paste0("mis",y0)), desc(target), final_name) for(i in 1:(nrow(data_mun)-1)){ if (data_mun[,c(paste0("mis",y0))][i] == data_mun[,c(paste0("mis",y0))][i+1] & !is.na(data_mun[,c(cluster0)][i+1]) & data_mun[,c("target")][i] == 1 & is.na(data_mun[,c("clu_new")][i])) data_mun$clu_new[i] <- data_mun[,c(cluster0)][i+1] } data_mun <- data_mun %>% mutate(ch_match = ifelse(!is.na(clu_new),ch_match-1,ch_match)) %>% select(-c("target",paste0("mis",y0))) data_mun <- matching(data_mun=data_mun, y0=y0) } } data_mun <- data_mun %>% mutate( !!paste0("mis",quo_name(y0)) := ifelse(ch_match > 0 ,get(ano_dest1),NA), target = ifelse(!is.na(get(paste0("mis",y0))),1,0)) data_mun$clu_new<-NA data_mun <- data_mun %>% mutate(!!paste0("mis",quo_name(y0)) := ifelse(target==0 & get(exist_dummy1) == 1, get(paste0("dest1",y1)), get(paste0("mis",y0)))) data_mun <- data_mun %>% arrange(uf_amc, get(paste0("mis",y0)), desc(target), final_name) for(i in 1:(nrow(data_mun)-1) ){ if (data_mun[,c(paste0("mis",y0))][i] == data_mun[,c(paste0("mis",y0))][i+1] & !is.na(data_mun[,c(cluster0)][i+1]) & data_mun[,c("target")][i] == 1) data_mun$clu_new[i] <- data_mun[,c(cluster0)][i+1] } data_mun <- data_mun %>% mutate(!!paste0("mis",quo_name(y0)) := ifelse(target==0 & get(exist_dummy0)==1, get(ano_dest1),get(paste0("mis",y0)))) data_mun <- data_mun %>% arrange(uf_amc, get(paste0("mis",y0)), desc(target), final_name) for(i in 1:(nrow(data_mun)-1) ){ if (data_mun[,c(paste0("mis",y0))][i] == data_mun[,c(paste0("mis",y0))][i+1] & !is.na(data_mun[,c(cluster0)][i+1]) & data_mun[,c("target")][i] == 1) data_mun$clu_new[i] <- data_mun[,c(cluster0)][i+1] } data_mun <- data_mun %>% mutate(ch_match = ifelse(!is.na(data_mun$clu_new),ch_match-1,ch_match)) %>% select(-c("target",paste0("mis",y0))) data_mun <- matching(data_mun=data_mun, y0=y0) if (any(data_mun$ch_match != 0 | !is.na(data_mun$ch_match))){ data_mun$clu_new<-NA data_mun <- data_mun %>% mutate(!!paste0("mis",quo_name(y0)) := ifelse(ch_match>0,get(ano_dest1),NA)) data_mun <- data_mun %>% arrange(uf_amc, get(paste0("mis",y0))) for(i in 2:nrow(data_mun)){ if (!is.na(data_mun[,c(paste0("mis",y0))][i]) & !is.na(data_mun[,c(paste0("mis",y0))][i-1]) & data_mun[,c("uf_amc")][i] == data_mun[,c("uf_amc")][i-1]) data_mun[,c(paste0("mis",y0))][i] <- data_mun[,c(paste0("dest1",y1))][i] } for(i in 2:nrow(data_mun)){ if (is.na(data_mun[,c(paste0("mis",y0))][i-1]) ) next else if (data_mun[,c(paste0("mis",y0))][i] == data_mun[,c(paste0("mis",y0))][i-1] & !is.na(data_mun[,c(cluster0)][i-1]) & !is.na(data_mun[,c(paste0("mis",y0))][i]) & data_mun[,c("ch_match")][i] != 0 ) data_mun$clu_new[i] <- data_mun[,c(cluster0)][i-1] } for(i in 2:nrow(data_mun)){ if (is.na(data_mun[,c(paste0("mis",y0))][i-1]) ) next else if (data_mun[,c(paste0("mis",y0))][i] == data_mun[,c(paste0("mis",y0))][i-1] & !is.na(data_mun[,c(cluster0)][i-1]) & !is.na(data_mun[,c(paste0("mis",y0))][i]) & data_mun[,c("ch_match")][i] != 0 ) data_mun$ch_match[i] <- data_mun$ch_match[i-1] } for(i in 1:(nrow(data_mun)-1)){ if(is.na(data_mun[,c(paste0("mis",y0))][i+1]) ) next else if (data_mun[,c(paste0("mis",y0))][i] == data_mun[,c(paste0("mis",y0))][i+1] & !is.na(data_mun[,c(cluster0)][i+1]) & !is.na(data_mun[,c(paste0("mis",y0))][i]) & data_mun[,c("ch_match")][i] != 0 ) data_mun$ch_match[i] <- data_mun$ch_match[i-1] } data_mun <- matching(data_mun=data_mun, y0=y0) } data_mun <- data_mun %>% mutate(!!paste0("clu",quo_name(y0),"_final") := dense_rank(get(cluster0))) data_mun <- data_mun[ , !(names(data_mun) %in% c(ano_dest1, paste0("dest2",y0), paste0("dest3",y0), paste0("dest4",y0), paste0("dest5",y0), exist_dummy0, ano_dest, "ch_match"))] %>% dplyr::arrange(uf_amc,get(cluster0),code2010) assign(paste0("_Crosswalk_",y0),data_mun) y_1 <- y0 y0 <- y1 } data_mun <- get(paste0("_Crosswalk_",y_1)) data_mun <- data_mun %>% select_if(colnames(data_mun) %in% c("uf_amc","code2010","final_name","clu1872_final", "clu1900_final","clu1911_final","clu1920_final","clu1933_final", "clu1940_final","clu1950_final","clu1960_final","clu1970_final", "clu1980_final","clu1991_final","clu2000_final","clu2010_final")) %>% mutate(!!paste0("clu",quo_name(y_1),"_final") := as.numeric(get(paste0("clu",y_1,"_final"))), !!paste0("clu",quo_name(y_1),"_final2") := get(paste0("clu",y_1,"_final"))) if (startyear<=1872){ n0 <- data_mun %>% filter(final_name=="Granja") %>% select(paste0("clu",y_1,"_final")) data_mun <- data_mun %>% mutate(!!paste0("clu",y_1,"_final2") := ifelse(code2010==2205706,n0,get(paste0("clu",y_1,"_final")))) } if (startyear<=1911 & endyear>=1911){ n0 <- data_mun %>% filter(final_name=="Palmas" & uf_amc == 15) %>% select(paste0("clu",y_1,"_final")) data_mun <- data_mun %>% mutate(!!paste0("clu",y_1,"_final2") := ifelse(code2010==4204202,n0, ifelse(code2010==4209003,n0, ifelse(code2010==4213609,n0,get(paste0("clu",y_1,"_final")))))) n0 <- data_mun %>% filter(final_name=="Rio Negro" & uf_amc==15) %>% select(paste0("clu",y_1,"_final")) data_mun <- data_mun %>% mutate(!!paste0("clu",y_1,"_final2") := ifelse(code2010==4208104,n0, ifelse(code2010==4210100,n0, get(paste0("clu",y_1,"_final"))))) n0 <- data_mun %>% filter(final_name=="Humaita" & uf_amc==1) %>% select(paste0("clu",y_1,"_final")) data_mun <- data_mun %>% mutate(!!paste0("clu",y_1,"_final2") := ifelse(code2010==1100205,n0,get(paste0("clu",y_1,"_final")))) } if (startyear<=1940 | endyear>=1960){ n0 <- data_mun %>% filter(code2010==3104700) %>% select(paste0("clu",y_1,"_final")) data_mun <- data_mun %>% mutate(!!paste0("clu",y_1,"_final2") := ifelse(code2010==3203304,n0, ifelse(code2010==3200904,n0,get(paste0("clu",y_1,"_final"))))) rm(n0) } if(endyear <= 1970){ data_mun <- data_mun %>% mutate(code_state = as.numeric(substr(code2010,1,2)), code_state = ifelse(code_state == 50,51,code_state), code_state = ifelse(code_state == 17,52,code_state), code2010 = substr(code2010,3,6), code2010 = as.numeric(paste0(code_state,code2010))) %>% select(-c(code_state)) } if(endyear == 1980){ data_mun <- data_mun %>% mutate(code_state = as.numeric(substr(code2010,1,2)), code_state = ifelse(code_state == 17,52,code_state), code2010 = substr(code2010,3,6), code2010 = as.numeric(paste0(code_state,code2010))) %>% select(-c(code_state)) } data_mun <- data_mun %>% arrange(uf_amc) %>% mutate(clu_final = dense_rank(unlist(get(paste0("clu",y_1,"_final2"))))) %>% select(-c(paste0("clu",y_1,"_final2"))) data_mun <- data_mun %>% mutate( uf_amc = ifelse(uf_amc %in% c(1, 20),1, ifelse(uf_amc %in% c(4, 5),4, ifelse(uf_amc %in% c(6),5, ifelse(uf_amc %in% c(7),6, ifelse(uf_amc %in% c(8),7, ifelse(uf_amc %in% c(9),8, ifelse(uf_amc %in% c(10),9, ifelse(uf_amc %in% c(11),10, ifelse(uf_amc %in% c(12,18),11, ifelse(uf_amc %in% c(13),12, ifelse(uf_amc %in% c(14),13, ifelse(uf_amc %in% c(15,16),14, ifelse(uf_amc %in% c(17),15, ifelse(uf_amc %in% c(19),16,uf_amc)))))))))))))), uf_amc_lb = ifelse(uf_amc %in% c(1),"AM/MT/(RO/RR/MS)", ifelse(uf_amc %in% c(2),"PA/(AP)", ifelse(uf_amc %in% c(3),"MA", ifelse(uf_amc %in% c(4),"PI/CE", ifelse(uf_amc %in% c(5),"RN", ifelse(uf_amc %in% c(6),"PB", ifelse(uf_amc %in% c(7),"PE", ifelse(uf_amc %in% c(8),"AL", ifelse(uf_amc %in% c(9),"SE", ifelse(uf_amc %in% c(10),"BA", ifelse(uf_amc %in% c(11),"ES/MG", ifelse(uf_amc %in% c(12),"RJ", ifelse(uf_amc %in% c(13),"SP", ifelse(uf_amc %in% c(14),"PR/SC", ifelse(uf_amc %in% c(15),"RS", ifelse(uf_amc %in% c(16),"GO/(DF/TO)",uf_amc))))))))))))))))) data_mun <- data_mun %>% dplyr::arrange(clu_final,uf_amc,code2010) data_mun <- data_mun %>% dplyr::group_by(clu_final,uf_amc) %>% mutate(help = ifelse(!is.na(clu_final) & row_number()==1,1,NA)) data_mun <- data_mun %>% dplyr::arrange(help,uf_amc,code2010) %>% ungroup() data_mun <- data_mun %>% dplyr::group_by(help,uf_amc) %>% mutate(amc_n=ifelse(help==1,row_number(),NA)) data_mun <- data_mun %>% ungroup() %>% dplyr::arrange(uf_amc,clu_final,code2010) %>% as.data.frame() for(i in 2:nrow(data_mun)){ if (is.na(data_mun[,c("amc_n")][i]) ) data_mun$amc_n[i] <- data_mun$amc_n[i-1] } data_mun <- data_mun %>% mutate(amc = ifelse(!is.na(clu_final),uf_amc*1000,NA), amc = amc + amc_n) %>% select(-c(amc_n, help)) data_mun <- data_mun %>% arrange(uf_amc, clu_final, final_name) data_mun <- setDT(data_mun)[, .(final_name, code2010, amc)] setnames(data_mun, c('name_muni', 'code_muni_2010', 'code_amc')) head(data_mun) data_mun <- subset(data_mun, !is.na(code_amc)) data_mun$code_muni_2010 <- as.integer(data_mun$code_muni_2010) code_list <- setDT(data_mun)[, .(list_code_muni_2010 = paste(code_muni_2010, collapse = ','), list_name_muni_2010 = paste(code_muni_2010, collapse = ',') ), by=code_amc] head(code_list) dir.create(file.path("shapes_in_sf_all_years_cleaned"), showWarnings = FALSE) dir.create(file.path("shapes_in_sf_all_years_cleaned/amc/"), showWarnings = FALSE) dir.create(file.path(paste0("shapes_in_sf_all_years_cleaned/amc/",startyear,"/")), showWarnings = FALSE) dir <- paste0("./shapes_in_sf_all_years_cleaned/amc/",startyear,"/") saveRDS(data_mun,paste0(dir,"AMC_",startyear,"_",endyear,".rds")) assign(paste0("_Crosswalk_final_",startyear,"_",endyear),data_mun) map <- geobr::read_municipality(year= endyear, code_muni = 'all', simplified = FALSE) map$code_muni <- as.integer(map$code_muni) if(endyear <= 1980){ data_mun_sf <- left_join(map %>% mutate(code_muni = as.numeric(substr(code_muni,1,6))), data_mun %>% select(-c(name_muni)), by=c('code_muni'='code_muni_2010' )) } else{ data_mun_sf <- left_join(map, data_mun %>% select(-c(name_muni)), by=c('code_muni'='code_muni_2010' )) } data_mun_sf <- data_mun_sf %>% filter(!is.na(code_amc)) data_mun_sf <- dissolve_polygons(mysf = data_mun_sf, group_column="code_amc") data_mun_sf <- dplyr::left_join(data_mun_sf, code_list) head(data_mun_sf) class(data_mun_sf$list_code_muni_2010) data_mun_sf_simplified <- simplify_temp_sf(data_mun_sf) data_mun_sf <- to_multipolygon(data_mun_sf) data_mun_sf_simplified <- to_multipolygon(data_mun_sf_simplified) file.name <- paste0(dir,"AMC_",startyear,"_",endyear,".gpkg") sf::st_write(data_mun_sf, file.name , delete_layer = TRUE) file.name <- paste0(dir,"AMC_",startyear,"_",endyear,"_simplified.gpkg") sf::st_write(data_mun_sf_simplified, file.name , delete_layer = TRUE) message(paste0('Just saved ', file.name) ) }
library(cheddar) options(continue=' ') options(width=90) options(prompt='> ') options(SweaveHooks = list(fig=function() par(mgp=c(2.5,1,0), mar=c(4,4,2,1), oma=c(0,0,1,0), cex.main=0.8))) data(TL84) print(TL84) NumberOfNodes(TL84) NumberOfTrophicLinks(TL84) head(NPS(TL84, c('category', 'Log10MNBiomass', TS='TrophicSpecies', TL='PreyAveragedTrophicLevel')), 10) getOption("SweaveHooks")[["fig"]]() PlotNPS(TL84, 'Log10M', 'Log10N') getOption("SweaveHooks")[["fig"]]() PlotNvM(TL84) models <- NvMLinearRegressions(TL84) colours <- PlotLinearModels(models) legend("topright", sapply(models, FormatLM), lty=1, col=colours) getOption("SweaveHooks")[["fig"]]() PlotNPS(TL84, 'Log10M', 'PreyAveragedTrophicLevel') getOption("SweaveHooks")[["fig"]]() PlotTLPS(TL84, 'resource.Log10M', 'consumer.Log10M') getOption("SweaveHooks")[["fig"]]() PlotPredationMatrix(TL84) data(pHWebs) CollectionCPS(pHWebs, c('lat', 'long', 'pH', S='NumberOfNodes', L='NumberOfTrophicLinks', 'L/S'='LinkageDensity', C='DirectedConnectance', Slope='NvMSlope', B='FractionBasalNodes', I='FractionIntermediateNodes', T='FractionTopLevelNodes'))
sim_comp_pop <- function(simSetup, fun = comp_var(), by = "") { fun <- if(by == "") fun else apply_by(by, fun) sim_setup(simSetup, new("sim_fun", order = 4, call = match.call(), fun)) } sim_comp_sample <- function(simSetup, fun = comp_var(), by = "") { fun <- if(by == "") fun else apply_by(by, fun) sim_setup(simSetup, new("sim_fun", order = 6, call = match.call(), fun)) } sim_comp_agg <- function(simSetup, fun = comp_var(), by = "") { fun <- if(by == "") fun else apply_by(by, fun) sim_setup(simSetup, new("sim_fun", order = 8, call = match.call(), fun)) }
release_questions <- function() { c( "Have you removed piwikproRTests in DESCRIPTION?" ) } release_questions <- function() { c( "Have you updated NEWS.md?" ) } release_questions <- function() { c( "Have you set Version in DESCRIPTON?" ) }
ACE <- function(y = "y", predictor = "~s(x)", restriction = "positive", eps = 0.01, itmax = 10, data = data,...){ y = data[,y] if(restriction=="positive"){ H <- function(x) exp(x) H_ <- function(x) log(x) H1 <-function(x) exp(x) } if(restriction=="correlation"){ H <- function(x) { x[x>3] <- 3 x[x<(-3)] <- -3 tanh(x) } H_ <- function(x) atanh(x) H1 <- function(x) { x[x > 3] <- 3 x[x < (-3)] <- -3 1-tanh(x)**2} } if(restriction=="correlation" & mean(y) >= 1){ eta0 <- H_(0.99) } else { if(restriction=="correlation" & mean(y) <= -1){ eta0 <- H_(-0.99) } else { eta0 <- H_(mean(y)) } } mu0 <- H(eta0) iter <- 0 continuar <- TRUE while (continuar) { iter <- iter + 1 res <- log((y-mu0)**2) var <- exp(predict(gam(as.formula(paste0("res", parse(text = predictor))), data = data))) der <- H1(eta0) var[which(var < 0.01)] <- 0.01 w <- der**2 / var z <- eta0 + (y-mu0) / der fit <- gam(as.formula(paste0("z", parse(text = predictor))), data = data, weights = w,...) eta <- predict(fit) mu <- H(eta) MSE0 <- mean(y - mu0)**2 MSE <- mean(y - mu)**2 error <- abs(MSE - MSE0) / MSE0 if (error < eps | iter > itmax) continuar <- FALSE eta0 <- eta mu0 <- mu } return(list(fit=fit,error = error)) }
library(rvest) library(tidyr) page <- read_html("http://www.zillow.com/homes/for_sale/Greenwood-IN/fsba,fsbo,fore,cmsn_lt/house_type/52333_rid/39.638414,-86.011362,39.550714,-86.179419_rect/12_zm/0_mmm/") houses <- page %>% html_elements(".photo-cards li article") z_id <- houses %>% html_attr("id") address <- houses %>% html_element(".zsg-photo-card-address") %>% html_text() price <- houses %>% html_element(".zsg-photo-card-price") %>% html_text() %>% readr::parse_number() params <- houses %>% html_element(".zsg-photo-card-info") %>% html_text() %>% strsplit("\u00b7") beds <- params %>% purrr::map_chr(1) %>% readr::parse_number() baths <- params %>% purrr::map_chr(2) %>% readr::parse_number() house_area <- params %>% purrr::map_chr(3) %>% readr::parse_number()
valid_call <- function(message = "Hello", title = NULL, priority = 0, attachment = NULL, user = get_pushover_user(), app = get_pushover_app(), device = NULL, sound = NULL, url = NULL, url_title = NULL, format = "html", retry = 60, expire = 3600, callback = NULL, timestamp = NULL) { pushover( message = message, title = title, priority = priority, attachment = attachment, user = user, app = app, device = device, sound = sound, url = url, url_title = url_title, format = format, retry = retry, expire = expire, callback = callback, timestamp = timestamp ) } random_string <- function(n) { paste0(sample(c(LETTERS, letters, 0:9), n, replace = TRUE), collapse = "") } test_that("input validation works", { expect_error(valid_call(message = "")) expect_error(valid_call(message = random_string(1025))) expect_error(valid_call(message = NA_character_)) expect_error(valid_call(message = 21)) expect_error(valid_call(message = c("msg 1", "msg 2"))) expect_error(valid_call(title = NA_character_)) expect_error(valid_call(title = 21)) expect_error(valid_call(title = TRUE)) expect_error(valid_call(title = c("msg 1", "msg 2"))) expect_error(valid_call(title = random_string(251))) expect_error(valid_call(priority = NULL)) expect_error(valid_call(priority = NA)) expect_error(valid_call(priority = "0")) expect_error(valid_call(priority = c(0, 1))) expect_error(valid_call(priority = -3)) expect_error(valid_call(priority = 0.1)) expect_error(valid_call(priority = 3)) expect_error(valid_call(attachment = NA_character_)) expect_error(valid_call(attachment = "")) expect_error(valid_call(attachment = 3)) expect_error(valid_call(attachment = "/blah/notafile.jpg")) expect_error(valid_call(user = "")) expect_error(valid_call(user = NA_character_)) expect_error(valid_call(user = 21)) expect_error(valid_call( user = c("uQiRzpo4DXghDmr9QzzfQu27cmVRsG", "uQiRzpo4DXghDmr9QzzfQu27cmVRsG") )) expect_error(valid_call(app = "")) expect_error(valid_call(app = NA_character_)) expect_error(valid_call(app = 21)) expect_error(valid_call(app = random_string(12))) expect_error(valid_call(device = "")) expect_error(valid_call(device = NA_character_)) expect_error(valid_call(device = random_string(26))) expect_error(valid_call(sound = "")) expect_error(valid_call(sound = NA_character_)) expect_error(valid_call(sound = 21)) expect_error(valid_call(sound = "notasound")) expect_error(valid_call(url = "")) expect_error(valid_call(url = NA_character_)) expect_error(valid_call(url = 21)) expect_error(valid_call(url = random_string(513))) expect_error(valid_call(url_title = "")) expect_error(valid_call(url_title = NA_character_)) expect_error(valid_call(url_title = 21)) expect_error(valid_call(url_title = random_string(101))) expect_error(valid_call(format = "")) expect_error(valid_call(format = NA_character_)) expect_error(valid_call(format = NULL)) expect_error(valid_call(format = 21)) expect_error(valid_call(format = "word")) expect_error(valid_call(retry = 20)) expect_error(valid_call(retry = FALSE)) expect_error(valid_call(retry = NA_integer_)) expect_error(valid_call(retry = 34.56789)) expect_error(valid_call(retry = 60, expire = 45)) expect_error(valid_call(retry = 10801)) expect_error(valid_call(retry = FALSE)) expect_error(valid_call(retry = NA_integer_)) expect_error(valid_call(retry = 123.456789)) expect_error(valid_call(callback = "")) expect_error(valid_call(callback = NA_character_)) expect_error(valid_call(callback = 21)) expect_error(valid_call(timestamp = -1)) expect_error(valid_call(callback = NA_integer_)) expect_error(valid_call(callback = 21.214142)) })
setMethod("clv.controlflow.estimate.put.inputs", signature = signature(clv.fitted="clv.fitted.spending"), definition = function(clv.fitted, verbose, remove.first.transaction, ...){ clv.fitted <- callNextMethod() [email protected] <- remove.first.transaction return(clv.fitted) }) setMethod(f = "clv.controlflow.predict.check.inputs", signature = signature(clv.fitted="clv.fitted.spending"), definition = function(clv.fitted, verbose, ...){ err.msg <- c() err.msg <- c(err.msg, .check_user_data_single_boolean(b=verbose, var.name="verbose")) check_err_msg(err.msg) }) setMethod("clv.controlflow.check.newdata", signature(clv.fitted="clv.fitted.spending"), definition = function(clv.fitted, user.newdata, ...){ err.msg <- c() if(!is(object = user.newdata, class2 = "clv.data")){ err.msg <- c(err.msg, paste0("The parameter newdata needs to be a clv data object of class clv.data or a subclass thereof.")) }else{ if(!clv.data.has.spending(user.newdata)) err.msg <- c(err.msg, paste0("The newdata object needs to contain spending data in order to predict spending with it.")) } check_err_msg(err.msg) }) setMethod("clv.controlflow.predict.build.result.table", signature(clv.fitted="clv.fitted.spending"), definition = function(clv.fitted, verbose, ...){ dt.predictions <- copy(clv.fitted@cbs[, "Id"]) return(dt.predictions) }) setMethod("clv.controlflow.predict.get.has.actuals", signature(clv.fitted="clv.fitted.spending"), definition = function(clv.fitted, dt.predictions){ return(clv.data.has.holdout([email protected])) }) setMethod("clv.controlflow.predict.add.actuals", signature(clv.fitted="clv.fitted.spending"), definition = function(clv.fitted, dt.predictions, has.actuals, verbose, ...){ actual.mean.spending <- i.actual.mean.spending <- Price <- NULL if(!has.actuals){ return(dt.predictions) }else{ dt.actual.spending <- clv.data.get.transactions.in.holdout.period([email protected]) dt.actual.spending <- dt.actual.spending[, list(actual.mean.spending = mean(Price)), keyby="Id"] dt.predictions[dt.actual.spending, actual.mean.spending := i.actual.mean.spending, on="Id"] dt.predictions[is.na(actual.mean.spending), actual.mean.spending := 0] return(dt.predictions) } }) setMethod("clv.controlflow.predict.post.process.prediction.table", signature = signature(clv.fitted="clv.fitted.spending"), function(clv.fitted, dt.predictions, has.actuals, verbose, ...){ if(has.actuals){ cols <- c("Id", "actual.mean.spending", "predicted.mean.spending") }else{ cols <- c("Id", "predicted.mean.spending") } setcolorder(dt.predictions, cols) return(dt.predictions) })
lazyarray <- function( path, storage_format, dim, dimnames = NULL, multipart = TRUE, prefix = "", multipart_mode = 1, compress_level = 50L, file_names = list('', seq_len(dim[[length(dim)]]))[[multipart + 1]], meta_name = 'lazyarray.meta', read_only = FALSE, quiet = FALSE, ... ){ if(file.exists(path) && !dir.exists(path)){ stop('lazyarray path must be a directory path, but a file was found.') } if(!dir.exists(path)){ arr <- create_lazyarray( path = path, storage_format = storage_format, dim = dim, dimnames = dimnames, compress_level = compress_level, prefix = prefix, multipart = multipart, multipart_mode = multipart_mode, file_names = file_names, meta_name = meta_name) if(read_only){ arr <- load_lazyarray(path = path, read_only = TRUE, meta_name = meta_name) } return(arr) } if(file.exists(file.path(path, meta_name))){ arr <- load_lazyarray(path = path, read_only = read_only, meta_name = meta_name) return(arr) } if(!quiet){ message('meta file not found, create one with existing files') } if(multipart){ if(length(file_names) != dim[[length(dim)]]){ stop('path exists, but cannot find meta file. Please specify file_names\n', ' See ', sQuote('?lazyarray'), ' for more details') } path <- normalizePath(path) fs <- file.path(path, sprintf('%s%s.fst', prefix, file_names)) fe <- file.exists(fs) if(any(fe)){ fs <- fs[fe] ds <- sapply(fs, function(f){ tryCatch({ meta <- cpp_fst_meta_orig(normalizePath(f)) if(inherits(meta, 'fst_error')){ stop(meta) } meta }, error = function(e){ stop('Cannot open array file(s). \n ', f) }) c(meta$nrOfCols, meta$nrOfRows) }, USE.NAMES = FALSE) ds <- unique(t(ds)) if(length(ds) != 2){ stop('All existing files must be homogeneous') } mp_dim <- dim[-length(dim)] len1 <- prod(mp_dim) len2 <- ds[[1]] * ds[[2]] if(storage_format == 'complex'){ len1 <- len1 * 2 } if(len1 != len2){ stop('Dimension provided does not match with existing files') } if(multipart_mode == 1){ last_d <- ds[[1]] if(storage_format != 'complex'){ last_d <- last_d * 2 } if(last_d != 2){ stop('Multipart mode=1, partition dimension should be ', paste(mp_dim, collapse = 'x'), 'x1, but invalid dimension found.') } part_dimension <- c(mp_dim, 1) } else { part_dimension <- mp_dim } } else { if( multipart_mode == 1 ){ part_dimension <- dim part_dimension[length(dim)] <- 1 } else if(multipart_mode == 2){ part_dimension <- dim[-length(dim)] } } } else { if(length(file_names) == 0){ file_names <- '' } if(length(file_names) != 1){ stop('path exists, but cannot find meta file. Please specify file_names\n', ' See ', sQuote('?lazyarray'), ' for more details') } path <- normalizePath(path) f <- file.path(path, sprintf('%s%s.fst', prefix, file_names)) meta <- tryCatch({ meta <- cpp_fst_meta_orig(f) if(inherits(meta, 'fst_error')){ stop(meta) } meta }, error = function(e){ stop('Cannot open array file(s). \n ', f) }) last_dim <- meta$nrOfCols prev_dim <- meta$nrOfRows if(last_dim != dim[length(dim)] || (last_dim * prev_dim != prod(dim))){ stop(sprintf( 'Array dimension not match, expected last dimension to be %d and total length %d, but last dim(%d) and length(%d) is given', last_dim, prev_dim * last_dim, dim[[length(dim)]], prod(dim) )) } part_dimension <- dim } meta <- list( lazyarray_version = 0, file_format = 'fst', storage_format = storage_format, dim = dim, dimnames = dimnames, partitioned = multipart, prefix = prefix, part_dimension = part_dimension, postfix = '.fst', compress_level = compress_level, file_names = file_names ) meta_path <- file.path(path, meta_name) save_yaml(meta, meta_path) ClassLazyArray$new(path = path, read_only = read_only, meta_name = meta_name) } auto_clear_lazyarray <- function(x, onexit = FALSE){ if(requireNamespace('dipsaus', quietly = TRUE)){ path <- dirname(x$storage_path) path <- normalizePath(path) dipsaus::shared_finalizer(x, key = path, function(e){ e$remove_data(force = TRUE) }, onexit = onexit) rm(path) } rm(x, onexit) invisible() }
estimateNuisance <- function( split_data_list, model_parms, alphas, glmer_fit, root_options, vec_dfm_no_alphas, verbose ){ basic_arg_list <- list( split_data_list = split_data_list, model_parms = model_parms, alphas = alphas ) CFBI_arg_list <- append(basic_arg_list, list( glmer_fit = glmer_fit, CFBI_numstart = 50, root_options = root_options, verbose = verbose )) CFBI_estimates <- do.call(getEstdCFBI_eeroot, CFBI_arg_list) MCFP_arg_list <- append(basic_arg_list, list( CFBI_estimates = CFBI_estimates, vec_dfm_no_alphas = vec_dfm_no_alphas, verbose = verbose )) MCFP_tidy_estimates <- do.call(estimateMCFP, MCFP_arg_list) out_list <- list( CFBI_estimates = CFBI_estimates, MCFP_tidy_estimates = MCFP_tidy_estimates ) } getEstdCFBI_eeroot <- function( split_data_list, model_parms, alphas, glmer_fit, CFBI_numstart, root_options = NULL, verbose ){ if(verbose){print(paste("II. Estimate CFBI"))} ckpt_time <- Sys.time() beta_here <- model_parms[-length(model_parms)] theta_here <- model_parms[length(model_parms)] names(beta_here) <- names(theta_here) <- NULL new_param_list <- list( beta = beta_here, theta = theta_here ) starting_dfm <- getStartingCFBI( new_param_list = new_param_list, glmer_fit = glmer_fit, alphas = alphas, CFBI_numstart = CFBI_numstart ) CFBI_estimate <- rep(NA_real_, length(alphas)) for (alpha_num in 1:length(alphas)) { alpha <- alphas[alpha_num] if (alpha_num>1){ckpt_time <- checkpointTimer(time1=ckpt_time, verbose)} if (verbose) {print(paste("II. solving for alpha_num", alpha_num, "of", length(alphas), "; alpha=", alpha))} est_CFBI1Alpha_args <- list( split_data_list = split_data_list, model_parms = model_parms, alpha = alpha, starting_dfm = starting_dfm, root_options = root_options ) CFBI_alpha_solved <- do.call(getCFBI1Alpha, est_CFBI1Alpha_args) CFBI_estimate[alpha_num] <- CFBI_alpha_solved$root } if (alpha_num == length(alphas)){ ckpt_time <- checkpointTimer(time1=ckpt_time,verbose) } CFBI_estimate } getStartingCFBI <- function( new_param_list, glmer_fit, alphas, CFBI_numstart ){ starting_CFBIs <- seq(from=-3, to = 3,length.out=CFBI_numstart) starting_alphas <- guessStartingAlphas( starting_CFBIs = starting_CFBIs, new_param_list = new_param_list, glmer_fit = glmer_fit ) starting_dfm <- data.frame( starting_alphas = unlist(starting_alphas), starting_CFBIs = starting_CFBIs ) max_start_alpha <- starting_dfm$starting_alphas[nrow(starting_dfm)] min_start_alpha <- starting_dfm$starting_alphas[1] if ( sum(alphas>max_start_alpha)>=3) { print("expanding grid of starting values for CFBI") starting_CFBIs <- seq(from=2.5, to = 10, by = .75) starting_alphas <- guessStartingAlphas( starting_CFBIs = starting_CFBIs, new_param_list = new_param_list, glmer_fit = glmer_fit ) starting_dfm2 <- data.frame( starting_alphas = unlist(starting_alphas), starting_CFBIs = starting_CFBIs ) starting_dfm <- rbind(starting_dfm,starting_dfm2) } if ( sum(alphas<min_start_alpha)>=3) { print("expanding grid of starting values for CFBI") starting_CFBIs <- seq(from=-10, to = -2.5, by = .75) starting_alphas <- guessStartingAlphas( starting_CFBIs = starting_CFBIs, new_param_list = new_param_list, glmer_fit = glmer_fit ) starting_dfm2 <- data.frame( starting_alphas = unlist(starting_alphas), starting_CFBIs = starting_CFBIs ) starting_dfm <- rbind(starting_dfm,starting_dfm2) } max_start_alpha <- starting_dfm$starting_alphas[nrow(starting_dfm)] min_start_alpha <- starting_dfm$starting_alphas[1] if ( sum(alphas>max_start_alpha)>3) { warning("solver may be slow for CFBI's due to large values of alpha") } if ( sum(alphas<min_start_alpha)>3) { warning("solver may be slow for CFBI's due to small values of alpha") } return(starting_dfm) } guessStartingAlphas <- function( starting_CFBIs, new_param_list, glmer_fit ){ starting_alphas <- lapply(starting_CFBIs, function(start_val){ new_param_list$beta[1] <- start_val indiv_probs <- suppressMessages( stats::predict( glmer_fit, newparams = new_param_list, type = "response" ) ) if ("try-error" %in% class(indiv_probs)){ indiv_probs <- 99 } mean(indiv_probs) }) } getCFBI1Alpha <- function( alpha, split_data_list, model_parms, starting_dfm, root_options ){ ordered_rows <- order(abs(starting_dfm$starting_alphas - alpha)) starting_estimate <- mean(starting_dfm[ordered_rows,]$starting_CFBIs[1:2]) CFBI_root_args <- list( geex_list = list( eeFUN = CFBI_only_EstFun, splitdt = split_data_list ), start = starting_estimate, root_options = root_options, alpha = alpha, model_parms = model_parms ) do.call(calculateRoots,CFBI_root_args) } calculateRoots <- function(geex_list, start, root_options, ...) { psi_i <- lapply(geex_list$splitdt, function(data_list_i) { force(data_list_i) geex_list$eeFUN(data_list = data_list_i, ...) }) psi <- function(theta) { psii <- lapply(psi_i, function(f) { do.call(f, args = append(list(theta = theta), geex_list$ee_args)) }) apply(checkArray(simplify2array(psii)), 1, sum) } root_args <- append(root_options, list(f = psi, start = start)) do.call(rootSolve::multiroot, args = root_args) } estimateMCFP <- function( split_data_list, model_parms, CFBI_estimates, alphas, vec_dfm_no_alphas, verbose ){ ckpt_time <- Sys.time() if(verbose){print('III. Estimate MCFP')} MCFP_onealpha_dfms <- lapply(1:length(alphas), function(alpha_num) { if (alpha_num > 1) { ckpt_time <- checkpointTimer(time1 = ckpt_time,verbose)} if(verbose){print(paste('III. alpha num', alpha_num, 'of', length(alphas)))} MCFP_onealpha_dfm <- getMCFP1AlphaNum( alpha_num = alpha_num, alpha = alphas[alpha_num], CFBI_estimates = CFBI_estimates, split_data_list = split_data_list, model_parms = model_parms, vec_dfm_no_alphas = vec_dfm_no_alphas ) }) MCFP_estimates_dfm <- do.call(rbind,MCFP_onealpha_dfms) if (nrow(MCFP_estimates_dfm)!=(length(alphas)*nrow(vec_dfm_no_alphas))) { stop( 'MCFP_estimates_dfm must have one row for each row in vec_dfm_no_alphas' )} ckpt_time <- checkpointTimer(time1=ckpt_time, verbose) row.names(MCFP_estimates_dfm) <- NULL MCFP_estimates_dfm } getMCFP1AlphaNum <- function( alpha_num, alpha, CFBI_estimates, split_data_list, model_parms, vec_dfm_no_alphas ){ if(length(CFBI_estimates)==1){ CFBI <- CFBI_estimates } else { CFBI <- CFBI_estimates[alpha_num] } MCFP_onealpha_allgroups_list <- lapply(split_data_list, function(data_list){ force(data_list) MCFP_onealpha_onegroup_vec <- MCFP_EstFun_LHS( model_parms = model_parms, CFBI = CFBI, vec_dfm_no_alphas = vec_dfm_no_alphas, model_DV_vec = data_list$model_DV_vec, model_mat = data_list$model_matrix ) if (nrow(vec_dfm_no_alphas)!= length(MCFP_onealpha_onegroup_vec)) {stop( 'MCFP_onealpha_onegroup_vec must have one prob for each row in vec_dfm_no_alphas' )} MCFP_onealpha_onegroup_vec }) MCFP_onealpha_allgroups <- do.call(cbind, MCFP_onealpha_allgroups_list) if (ncol(MCFP_onealpha_allgroups) != length(split_data_list)) { stop( 'MCFP_onealpha_allgroups must have one row for each group' )} if (nrow(MCFP_onealpha_allgroups)!=nrow(vec_dfm_no_alphas)) { stop( 'MCFP_onealpha_allgroups must have one column for each alpha' )} MCFP_onealpha_avg <- apply( MCFP_onealpha_allgroups, 1, function(x){mean(stats::na.omit(x))}) MCFP_onealpha_avg <- as.vector(MCFP_onealpha_avg) if (length(MCFP_onealpha_avg)!=nrow(vec_dfm_no_alphas)){ stop("MCFP_onealpha_avg should be a vector of nrow(vec_dfm_no_alphas) probs") } mcfp_onealpha_dfm <- vec_dfm_no_alphas mcfp_onealpha_dfm$alpha <- alpha mcfp_onealpha_dfm$alpha_num <- alpha_num mcfp_onealpha_dfm$CFBI <- CFBI mcfp_onealpha_dfm$MCFP <- MCFP_onealpha_avg mcfp_onealpha_dfm }
'dlcd' <- function(x, lcd, uselog=FALSE, eps=10^-10) { if(class(lcd) != "LogConcDEAD") { stop("error: lcd must be of class LogConcDEAD") } d <- ncol(lcd$x) if(is.vector(x) && length(x)==d) { x <- matrix(x,ncol=d) } if( is.vector( x ) && d==1 ) { x <- matrix( x ) } if(is.matrix(x) && ncol(x)==d) { isout <- apply( lcd$outnorm %*% ( t( x ) - lcd$midpoint ) - lcd$outdist, 2, max ) > eps vals <- apply( lcd$bunique %*% t( x ) - lcd$betaunique, 2, min ) + ifelse( isout, -Inf, 0 ) if( uselog ) return( vals ) else return( exp( vals ) ) } else stop("error: x must be a vector, or a numeric matrix with ",d," columns") }
mptmodel <- function(y, weights = NULL, spec, treeid = NULL, optimargs = list(control = list(reltol = .Machine$double.eps^(1/1.2), maxit = 1000), init = NULL), start = NULL, vcov = TRUE, estfun = FALSE, ...) { if(missing(y)) stop("response missing") stopifnot(class(spec) == "mptspec") if(is.null(dim(y))) y <- matrix(y, nrow=1L, dimnames=list(NULL, names(y))) y <- as.matrix(y) nsubj <- nrow(y) if(NCOL(y) != length(spec$prob)) stop("number of response categories and model equations do not match") if(is.null(weights)) weights <- 1L weights <- rep(weights, length.out = nsubj) nsubj <- sum(weights > 0L) tid <- if(length(treeid) == NCOL(y)) factor(treeid) else if(length(spec$treeid) == NCOL(y)) spec$treeid else if(!is.null(colnames(y))) factor(gsub("([^.]+)\\..*", "\\1", colnames(y))) else rep(1, NCOL(y)) ysum <- colSums(y * weights) if(is.null(start)) { start <- spec$par[is.na(spec$par)] start[] <- 0 } else { if(is.null(names(start))) names(start) <- names(spec$par[is.na(spec$par)]) start <- qlogis(start) } nll <- function(par) -sum(ysum * log(spec$par2prob(plogis(par)))) grad <- function(par) { yp <- drop(ysum/spec$par2prob(plogis(par))) dp <- spec$par2deriv(plogis(par))$deriv -drop(dp %*% yp) * dlogis(par) } if (!is.null(optimargs$init)) { start[] <- qlogis(optimargs$init) } optimargs$init <- NULL optArgs <- list(par=start, fn=nll, gr=grad, method="BFGS") optArgs <- c(optArgs, as.list(optimargs)) opt <- do.call(optim, optArgs) coef <- opt$par loglik <- -opt$value pcat <- spec$par2prob(plogis(coef)) snam <- if(!is.null(names(spec$prob))) names(spec$prob) else if(!is.null(colnames(y))) colnames(y) else ave(as.character(tid), tid, FUN = function(a) paste(a, seq_along(a), sep=".")) ncat <- table(tid) ntrees <- length(ncat) nbytree <- tapply(ysum, tid, sum) n <- setNames(nbytree[as.character(tid)], snam) fitted <- n*pcat G2 <- 2*sum(ysum*log(ysum/fitted), na.rm=TRUE) df <- sum(ncat - 1) - length(coef) gof <- c(G2=G2, df=df, pval = pchisq(G2, df, lower.tail=FALSE)) if(df == 0 && abs(G2) < sqrt(.Machine$double.eps)) { gof["G2"] <- 0 gof["pval"] <- 1 } rval <- list( y = y, coefficients = coef, loglik = loglik, nobs = nsubj, npar = length(start), weights = if(isTRUE(all.equal(weights, rep(1, nsubj)))) NULL else weights, fitted = fitted, goodness.of.fit = gof, ntrees = ntrees, n = n, pcat = setNames(pcat, snam), treeid = tid, spec = spec, optim = opt, ysum = setNames(ysum, snam) ) class(rval) <- "mptmodel" if(estfun) rval$estfun <- estfun.mptmodel(rval) return(rval) } logLik.mptmodel <- function(object, ...) structure(object$loglik, df = object$npar, class = "logLik") coef.mptmodel <- function(object, logit = FALSE, ...){ coef <- object$coefficients if (logit) { nm <- paste0("logit(", names(coef), ")") setNames(coef, nm) } else { plogis(coef) } } estfun.mptmodel <- function(x, logit = TRUE, ...) { dp <- t(x$spec$par2deriv(coef(x, logit=FALSE))$deriv) ef <- x$y %*% (dp/x$pcat) if (logit) ef <- t(dlogis(coef(x, logit=TRUE)) * t(ef)) dimnames(ef) <- list(rownames(x$y), names(coef(x, logit=logit))) if(!is.null(x$weights)) ef <- ef * weights ef } vcov.mptmodel <- function(object, logit = TRUE, what = c("vcov", "fisher"), ...){ what <- match.arg(what) coef <- coef(object, logit=logit) H <- function(par, y = object$ysum, spec = object$spec){ pp <- spec$par2prob(par) yp <- drop(y/pp) dp <- spec$par2deriv(par)$deriv npar <- length(par) H <- matrix(NA, npar, npar) for (i in seq_len(npar)) for (j in i:npar) H[i, j] <- yp %*% (dp[i, ]*dp[j, ]/pp) H[lower.tri(H)] <- t(H)[lower.tri(H)] dimnames(H) <- list(names(par), names(par)) H } if (logit) { if (what == "vcov") 1/tcrossprod(dlogis(coef)) * solve(H(plogis(coef))) else tcrossprod(dlogis(coef)) * H(plogis(coef)) } else { if (what == "vcov") solve(H(coef)) else H(coef) } } confint.mptmodel <- function(object, parm, level = 0.95, logit = TRUE, ...) { cf <- coef(object, logit=logit) pnames <- names(cf) if (missing(parm)) parm <- pnames else if (is.numeric(parm)) parm <- pnames[parm] a <- (1 - level)/2 a <- c(a, 1 - a) pct <- paste(format(100*a, trim=TRUE, scientific=FALSE, digits=3), "%") fac <- qnorm(a) ci <- array(NA, dim = c(length(parm), 2L), dimnames = list(parm, pct)) ses <- sqrt(diag(vcov(object, logit=logit)))[parm] ci[] <- cf[parm] + ses %o% fac ci } print.mptmodel <- function(x, digits = max(3, getOption("digits") - 3), logit=FALSE, ...){ cat("\nMultinomial processing tree (MPT) models\n\n") cat("Parameter estimates:\n") print.default(format(coef(x, logit=logit), digits=digits), print.gap=2, quote = FALSE) G2 <- x$goodness.of.fit[1] df <- x$goodness.of.fit[2] pval <- x$goodness.of.fit[3] cat("\nGoodness of fit (2 log likelihood ratio):\n") cat("\tG2(", df, ") = ", format(G2, digits=digits), ", p = ", format(pval, digits=digits), "\n", sep="") cat("\n") invisible(x) } plot.mptmodel <- function(x, logit = FALSE, xlab = "Parameter", ylab = "Estimate", ...){ coef <- coef(x, logit=logit) plot(coef, axes=FALSE, xlab = xlab, ylab = ylab, ...) axis(1, seq_along(coef), names(coef)) axis(2) box() } nobs.mptmodel <- function(object, ...) object$nobs summary.mptmodel <- function(object, ...){ x <- object coef <- coef(x, logit=TRUE) pcoef <- coef(x, logit=FALSE) s.err <- tryCatch(sqrt(diag(vcov(x, logit=TRUE))), error = function(e) rep(NA, length(coef))) tvalue <- coef / s.err pvalue <- 2 * pnorm(-abs(tvalue)) dn <- c("Estimate", "Logit Estim.", "Std. Error") coef.table <- cbind(pcoef, coef, s.err, tvalue, pvalue) dimnames(coef.table) <- list(names(pcoef), c(dn, "z value", "Pr(>|z|)")) aic <- AIC(x) ans <- list(ntrees=x$ntrees, coefficients=coef.table, aic=aic, gof=x$goodness.of.fit) class(ans) <- "summary.mptmodel" return(ans) } print.summary.mptmodel <- function(x, digits = max(3, getOption("digits") - 3), cs.ind = 2:3, ...){ cat("\nCoefficients:\n") printCoefmat(x$coef, digits=digits, cs.ind=cs.ind, ...) cat("\nLikelihood ratio G2:", format(x$gof[1], digits=digits), "on", x$gof[2], "df,", "p-value:", format(x$gof[3], digits=digits), "\n") cat( "AIC: ", format(x$aic, digits=max(4, digits + 1)), sep="") cat("\n") cat("Number of trees:", x$ntrees, "\n") invisible(x) } deviance.mptmodel <- function(object, ...) object$goodness.of.fit["G2"] predict.mptmodel <- function(object, newdata = NULL, ...){ if(is.null(newdata)) fitted(object) else { stopifnot(length(newdata) == length(object$n)) object$pcat * newdata } } mptspec <- function(..., .restr = NULL) { spec <- match.call() restr <- spec$.restr if(!is.null(restr)) { if(as.character(restr[[1L]]) != "list") stop(".restr must be list") restr1 <- restr restrcl <- sapply(restr1[-1L], class) restr <- sapply(restr1[-1L], function(s) paste(deparse(s), collapse="")) restr <- paste(names(restr), " = ", ifelse(restrcl == "numeric", "", "expression("), restr, ifelse(restrcl == "numeric", "", ")[[1L]]"), collapse = ", ") } spec$.restr <- NULL spec <- as.list(spec[-1L]) treeid <- NULL if (is.character(whichmod <- spec[[1]])) { modcall <- switch(EXPR = whichmod, "1HT" = expression( "1.1" = r + (1 - r)*b, "1.2" = (1 - r)*(1 - b), "2.1" = b, "2.2" = 1 - b ), "2HT" = expression( "1.1" = r + (1 - r)*b, "1.2" = (1 - r)*(1 - b), "2.1" = (1 - d)*b, "2.2" = (1 - d)*(1 - b) + d ), "PairAsso" = expression( "1.1" = p*q*r, "1.2" = p*q*(1 - r), "1.3" = p*(1 - q)*r, "1.4" = (1 - p) + p*(1 - q)*(1 - r) ), "proCNI" = expression( "1.1" = C + (1 - C)*(1 - N)*(1 - I), "1.2" = (1 - C)*N + (1 - C)*(1 - N)*I, "2.1" = C + (1 - C)*(1 - N)*J, "2.2" = (1 - C)*N + (1 - C)*(1 - N)*(1 - J), "3.1" = (1 - C)*(1 - N)*(1 - I), "3.2" = C + (1 - C)*N + (1 - C)*(1 - N)*I, "4.1" = (1 - C)*(1 - N)*J, "4.2" = C + (1 - C)*N + (1 - C)*(1 - N)*(1 - J) ), "prospec" = expression( "1.1" = C1*P*(1 - M1)*(1 - g) + C1*(1 - P) + (1 - C1)*P*(1 - M1)*(1 - g)*c + (1 - C1)*(1 - P)*c, "1.2" = (1 - C1)*P*(1 - M1)*(1 - g)*(1 - c) + (1 - C1)*(1 - P)*(1 - c), "1.3" = C1*P*M1 + C1*P*(1 - M1)*g + (1 - C1)*P*M1 + (1 - C1)*P*(1 - M1)*g, "2.1" = (1 - C2)*P*(1 - M1)*(1 - g)*c + (1 - C2)*(1 - P)*c, "2.2" = C2*P*(1 - M1)*(1 - g) + C2*(1 - P) + (1 - C2)*P*(1 - M1)*(1 - g)*(1 - c) + (1 - C2)*(1 - P)*(1 - c), "2.3" = C2*P*M1 + C2*P*(1 - M1)*g + (1 - C2)*P*M1 + (1 - C2)*P*(1 - M1)*g, "3.1" = C1*P*M2 + C1*P*(1 - M1)*(1 - g) + C1*(1 - P) + (1 - C1)*P*M2*c + (1 - C1)*P*(1 - M1)*(1 - g)*c + (1 - C1)*(1 - P)*c, "3.2" = (1 - C1)*P*M2*(1 - c) + (1 - C1)*P*(1 - M2)*(1 - g)*(1 - c) + (1 - C1)*(1 - P)*(1 - c), "3.3" = C1*P*(1 - M2)*g + (1 - C1)*P*(1 - M2)*g, "4.1" = (1 - C2)*P*M2*c + (1 - C2)*P*(1 - M2)*(1 - g)*c + (1 - C2)*(1 - P)*c, "4.2" = C2*P*M2 + C2*P*(1 - M2)*(1 - g) + C2*(1 - P) + (1 - C2)*P*M2*(1 - c) + (1 - C2)*P*(1 - M2)*(1 - g)*(1 - c) + (1 - C2)*(1 - P)*(1 - c), "4.3" = C2*P*(1 - M2)*g + (1 - C2)*P*(1 - M2)*g ), "rmodel" = expression( "1.1" = b, "1.2" = 1 - b, "2.1" = g, "2.2" = 1 - g, "3.1" = r*a + (1 - r)*b*a, "3.2" = r*(1 - a) + (1 - r)*(1 - b)*(1 - a), "3.3" = (1 - r)*(1 - b)*a, "3.4" = (1 - r)*b*(1 - a) ), "SourceMon" = expression( "1.1" = D1*d1 + D1*(1 - d1)*g + (1 - D1)*b*g, "1.2" = D1*(1 - d1)*(1 - g) + (1 - D1)*b*(1 - g), "1.3" = (1 - D1)*(1 - b), "2.1" = D2*(1 - d2)*g + (1 - D2)*b*g, "2.2" = D2*d2 + D2*(1 - d2)*(1 - g) + (1 - D2)*b*(1 - g), "2.3" = (1 - D2)*(1 - b), "3.1" = b*g, "3.2" = b*(1 - g), "3.3" = 1 - b ), "SR" = expression( "1.1" = c*r, "1.2" = (1 - c)*u^2, "1.3" = 2*(1 - c)*u*(1 - u), "1.4" = c*(1 - r) + (1 - c)*(1 - u)^2, "2.1" = u, "2.2" = 1 - u ), "SR2" = expression( "1.1" = c*r, "1.2" = (1 - c)*u^2, "1.3" = 2*(1 - c)*u*(1 - u), "1.4" = c*(1 - r) + (1 - c)*(1 - u)^2 ), "WST" = expression( "1.1" = (1 - a)*(1 - P)*(1 - p)*(1 - Q)*(1 - q), "1.2" = a*c*(1 - d)*(1 - sb)*i + (1 - a)*(1 - P)*(1 - p)*(1 - Q)*q, "1.3" = a*c*(1 - d)*sb*i + (1 - a)*(1 - P)*(1 - p)*Q*(1 - q), "1.4" = a*(1 - c)*(1 - x)*(1 - d)*i + (1 - a)*(1 - P)*(1 - p)*Q*q, "1.5" = a*c*d*(1 - sf)*i + (1 - a)*(1 - P)*p*(1 - Q)*(1 - q), "1.6" = a*(1 - c)*x*(1 - sfb)*i + (1 - a)*(1 - P)*p*(1 - Q)*q, "1.7" = a*c*d*(1 - sf)*(1 - i) + a*c*(1 - d)*sb*(1 - i) + (1 - a)*(1 - P)*p*Q*(1 - q), "1.8" = (1 - a)*(1 - P)*p*Q*q, "1.9" = a*c*d*sf*i + (1 - a)*P*(1 - p)*(1 - Q)*(1 - q), "1.10" = a*c*d*sf*(1 - i) + a*c*(1 - d)*(1 - sb)*(1 - i) + (1 - a)*P*(1 - p)*(1 - Q)*q, "1.11" = a*(1 - c)*x*sfb*i + (1 - a)*P*(1 - p)*Q*(1 - q), "1.12" = (1 - a)*P*(1 - p)*Q*q, "1.13" = a*(1 - c)*(1 - x)*d*i + (1 - a)*P*p*(1 - Q)*(1 - q), "1.14" = (1 - a)*P*p*(1 - Q)*q, "1.15" = (1 - a)*P*p*Q*(1 - q), "1.16" = a*(1 - c)*x*sfb*(1 - i) + a*(1 - c)*x*(1 - sfb)*(1 - i) + a*(1 - c)*(1 - x)*d*(1 - i) + a*(1 - c)*(1 - x)*(1 - d)*(1 - i) + (1 - a)*P*p*Q*q ), NULL ) if(is.null(modcall)) stop("'...' has to be either an expression or one of:\n", " '1HT', '2HT', 'PairAsso', 'proCNI', 'prospec', 'rmodel',\n", " 'SourceMon', 'SR', 'SR2', 'WST'.\n") nm <- do.call(rbind, strsplit(names(modcall), "\\.")) treeid <- as.numeric(nm[, 1]) if (!is.null(spec$.replicates) && spec$.replicates > 1) { ntrees <- max(treeid) treeid <- rep(treeid, spec$.replicates) + rep(seq(0, ntrees*(spec$.replicates - 1), ntrees), each=nrow(nm)) pd <- getParseData(parse(text=modcall, keep.source=TRUE)) pat <- paste0("(", paste(unique(pd$text[pd$token == "SYMBOL"]), collapse="|"), ")") newcall <- NULL for (i in seq_len(spec$.replicates)) newcall <- c(newcall, gsub(pat, paste0("\\1", i), modcall)) modcall <- setNames(parse(text=newcall), paste(treeid, nm[, 2], sep=".")) } spec <- modcall } spec <- lapply(spec, function(s) paste(deparse(s), collapse="")) if(!is.null(restr)) { spec <- lapply(spec, function(s) { s <- sprintf("substitute(%s, list(%s))", s, restr) deparse(eval(parse(text = s))) }) } if(!is.null(restr)) restr <- lapply(restr1[-1L], as.expression) prob <- lapply(spec, function(s) parse(text=s, keep.source=TRUE)) if(is.null(treeid) && !is.null(names(prob))) treeid <- gsub("([^.]+)\\..*", "\\1", names(prob)) pars <- unique(unlist(lapply(prob, function(e) { pd <- getParseData(e) pd$text[pd$token == "SYMBOL"] }))) pars <- structure(rep.int(NA_real_, length(pars)), .Names = pars) par2prob <- function(par) { pars <- pars if(sum(is.na(pars)) != length(par)) stop("numbers of parameters do not match") pars[is.na(pars)] <- par pars <- as.list(pars) rval <- sapply(prob, eval, pars) names(rval) <- names(prob) return(rval) } deriv <- lapply(prob, deriv3, names(pars)) names(deriv) <- names(prob) par2deriv <- function(par) { pars <- pars na_pars <- is.na(pars) if(sum(na_pars) != length(par)) stop("numbers of parameters do not match") pars[na_pars] <- par pars <- as.list(pars) deriv1 <- rbind( sapply(deriv, function(ex) attr(eval(ex, pars), "gradient"))) rownames(deriv1) <- names(pars) deriv1 <- deriv1[na_pars, , drop = FALSE] list(deriv = deriv1) } retval <- list( par2prob = par2prob, par2deriv = par2deriv, prob = prob, deriv = deriv, par = pars, restr = restr, treeid = if(!is.null(treeid)) factor(treeid) ) class(retval) <- "mptspec" retval } update.mptspec <- function(object, .restr = NULL, ...){ spec <- match.call() restr <- spec$.restr spec <- unlist(object$prob) if(!is.null(restr)){ if(as.character(restr[[1L]]) != "list") stop(".restr must be list") spec$.restr <- restr } do.call(mptspec, spec) } print.mptspec <- function(x, ...){ print(unlist(x$prob), ...) }
library("robustbase") data("coleman") set.seed(1234) folds <- cvFolds(nrow(coleman), K = 5, R = 10) fitLm <- lm(Y ~ ., data = coleman) cvFitLm <- cvLm(fitLm, cost = rtmspe, folds = folds, trim = 0.1) fitLmrob <- lmrob(Y ~ ., data = coleman, k.max = 500) cvFitLmrob <- cvLmrob(fitLmrob, cost = rtmspe, folds = folds, trim = 0.1) fitLts <- ltsReg(Y ~ ., data = coleman) cvFitLts <- cvLts(fitLts, cost = rtmspe, folds = folds, trim = 0.1) cvFits <- cvSelect(LS = cvFitLm, MM = cvFitLmrob, LTS = cvFitLts) cvFits dotplot(cvFits) fitLts50 <- ltsReg(Y ~ ., data = coleman, alpha = 0.5) cvFitLts50 <- cvLts(fitLts50, cost = rtmspe, folds = folds, fit = "both", trim = 0.1) fitLts75 <- ltsReg(Y ~ ., data = coleman, alpha = 0.75) cvFitLts75 <- cvLts(fitLts75, cost = rtmspe, folds = folds, fit = "both", trim = 0.1) cvFitsLts <- cvSelect("0.5" = cvFitLts50, "0.75" = cvFitLts75) cvFitsLts dotplot(cvFitsLts)
"metalonda_test_data"
check_lgl <- function(x, coerce = FALSE, x_name = substitute(x), error = TRUE) { x_name <- chk_deparse(x_name) check_flag_internal(coerce) check_flag_internal(error) if(coerce) attributes(x) <- NULL check_scalar(x, values = TRUE, x_name = x_name, error = error) } check_flag <- function(x, coerce = FALSE, x_name = substitute(x), error = TRUE) { x_name <- chk_deparse(x_name) check_lgl(x, coerce = coerce, x_name = x_name, error = error) } check_flag_na <- function(x, coerce = TRUE, x_name = substitute(x), error = TRUE) { .Deprecated("check_scalar") x_name <- chk_deparse(x_name) check_flag_internal(coerce) check_flag_internal(error) if(coerce) attributes(x) <- NULL check_scalar(x, values = c(TRUE, NA), x_name = x_name, error = error) }
setMethod("sketchGrid", signature( layers = "ANY", shapeCross = "ANY"), function(i, j, rowLimit, colLimit, layers, shapeCross, excludeCenter, ...) { coordCross <- extendHorVer(i = i, j = j, shapeCross = shapeCross, rowLimit = rowLimit, colLimit = colLimit) coordCirc <- circularExtension(i = i, j = j, layers = layers, rowLimit = rowLimit, colLimit = colLimit) if(identical(excludeCenter,FALSE)) { coordGrid <- rbind(cbind(i,j), coordCross, coordCirc) } else { coordGrid <- rbind(coordCross, coordCirc) } plot.new() plot.window(xlim = c(0,colLimit), ylim = c(0,rowLimit)) axis(2,at=1:rowLimit, labels=rowLimit:1, cex.axis=0.5) axis(1,at=1:colLimit, labels=1:colLimit, cex.axis=0.5) mtext("column", 1, line = 3, font = 2) mtext("row", 2, line = 3, font = 2) points(x = rep(1:colLimit,rowLimit), y = (rowLimit+1)- rep(1:rowLimit, each = colLimit)) points(x = coordGrid[,2], y = (rowLimit + 1)-coordGrid[,1], pch = 21, bg = "black") } )
neg2ELratio_t1t2 <- function(formula, group_order, t1, t2, nboot) { fit <- survfit(update(formula,.~1)) fit_group = survfit(formula) group = eval(parse(text = labels(terms(formula)))) fit1 = fit_group[group = group_order[[1]]] fit2 = fit_group[group = group_order[[2]]] NBOOT <- nboot fit_time_restrict_boot <- (fit$n.event != 0 & fit$time <= t2 & fit$time >= t1) mm <- length(fit$time[fit_time_restrict_boot]) S1_hat_Wei <- ((c(1, fit1$surv)[cumsum(c(0, fit$time) %in% c(0, fit1$time))])[-1])[fit_time_restrict_boot] S2_hat_Wei <- ((c(1, fit2$surv)[cumsum(c(0, fit$time) %in% c(0, fit2$time))])[-1])[fit_time_restrict_boot] nn <- c(fit1$n, fit2$n) T_11 <- min((fit$time[fit_time_restrict_boot])[S1_hat_Wei < 1]) T_21 <- min((fit$time[fit_time_restrict_boot])[S2_hat_Wei < 1]) T_1m <- max((fit$time[fit_time_restrict_boot])[S1_hat_Wei > 0]) T_2m <- max((fit$time[fit_time_restrict_boot])[S2_hat_Wei > 0]) lowerb <- max(T_11, T_21) upperb <- min(T_1m, T_2m) lowerbindx_boot <- which.min(abs(fit$time[fit_time_restrict_boot] - lowerb)) upperbindx_boot <- which.min(abs(fit$time[fit_time_restrict_boot] - upperb)) if (lowerbindx_boot >= upperbindx_boot) { warning("lowerbindx_boot >= upperbindx_boot in computing the integral and sup statistic.\nEither your sample size is too small or the overlapping region of the two samples is empty or just one observed event time.") return (NULL) } Td_sort_boot <- (fit$time[fit_time_restrict_boot])[lowerbindx_boot:upperbindx_boot] return(list(fit = fit, fit1 = fit1, fit2 = fit2, NBOOT = NBOOT, fit_time_restrict_boot = fit_time_restrict_boot, mm = mm, nn = nn, T_11 = T_11, T_21 = T_21, lowerbindx_boot = lowerbindx_boot, upperbindx_boot = upperbindx_boot, Td_sort_boot = Td_sort_boot)) }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(JWileymisc) test <- testDistribution(mtcars$mpg, "normal") head(test$Data) table(test$Data$isEV) plot(test) test <- testDistribution(mtcars$mpg, "normal", extremevalues = "theoretical", ev.perc = .10) head(test$Data) table(test$Data$isEV) plot(test) test$Data[isEV == "Yes"] mtcars[test$Data[isEV == "Yes", OriginalOrder], ] test <- testDistribution(mtcars$mpg, "normal", extremevalues = "empirical", ev.perc = .10) head(test$Data) table(test$Data$isEV) plot(test) testN <- testDistribution(mtcars$mpg, "normal", extremevalues = "theoretical", ev.perc = .05) testG <- testDistribution(mtcars$mpg, "gamma", extremevalues = "theoretical", ev.perc = .05) testN$Distribution$LL testG$Distribution$LL plot(testN) plot(testG) m <- lm(mpg ~ hp * factor(cyl), data = mtcars) md <- modelDiagnostics(m, ev.perc = .05) plot(md, ncol = 1) md$extremeValues mtcars[md$extremeValues$Index, 1:4] m2 <- lm(mpg ~ hp * factor(cyl), data = mtcars[-md$extremeValues$Index, ]) round(data.frame( M1 = coef(m), M2 = coef(m2), PercentChange = coef(m2) / coef(m) * 100 - 100), 2) if (requireNamespace("pander", quietly = TRUE)) { pander::pandoc.table(round(data.frame( M1 = coef(m), M2 = coef(m2), PercentChange = coef(m2) / coef(m) * 100 - 100), 2), justify = "left") } else { "" } md2 <- modelDiagnostics(m2, ev.perc = .05) plot(md2, ask = FALSE, ncol = 1) md2$extremeValues
as_factor = function(x, levels, ordered = is.ordered(x)) { assert_flag(ordered) levels = unique(as.character(levels)) levels = levels[!is.na(levels)] if (is.factor(x)) { if (!identical(levels(x), levels) || ordered != is.ordered(x)) { x = factor(x, levels = levels, ordered = ordered) } } else { x = factor(as.character(x), levels = levels, ordered = ordered) } x }
context("utils_table - T1. Correct values for summarize_long.numeric") test_that("T1.1. Correct mean values for numeric values", { values <- 1:5 summary <- visR::summarize_long(values) testthat::expect_equal(summary[[1]]$mean, base::mean(values)) }) test_that("T1.2. Correct min value for numeric values", { values <- 1:5 summary <- visR::summarize_long(values) testthat::expect_equal(summary[[1]]$min, base::min(values)) }) test_that("T1.3. Correct max value for numeric values", { values <- 1:5 summary <- visR::summarize_long(values) testthat::expect_equal(summary[[1]]$max, base::max(values)) }) test_that("T1.4. Correct Q1 value for numeric values", { values <- 1:5 summary <- visR::summarize_long(values) testthat::expect_equal(summary[[1]]$Q1, stats::quantile(values)[2]) }) test_that("T1.5. Correct Q3 value for numeric values", { values <- 1:5 summary <- visR::summarize_long(values) testthat::expect_equal(summary[[1]]$Q3, stats::quantile(values)[4]) }) test_that("T1.6. Correct SD value for numeric values", { values <- 1:5 summary <- visR::summarize_long(values) testthat::expect_equal(summary[[1]]$sd, stats::sd(values)) }) test_that("T1.7. Correct median value for numeric values", { values <- 1:5 summary <- visR::summarize_long(values) testthat::expect_equal(summary[[1]]$median, stats::median(values)) }) test_that("T1.8. Integers as correctly dispatched to summarize_long.numeric", { values <- 1:5 testthat::expect_equal(visR::summarize_long(values), visR::summarize_long(as.integer(values))) }) context("utils_table - T2. Correct values for summarize_long.factors") test_that("T2.1. Correct count of factor values", { values <- base::as.factor(c("A", "A", "B")) summary <- visR::summarize_long(values) testthat::expect_equal(summary[[1]]$`N A`, base::sum(values=="A")) }) test_that("T2.2. Correct perentage of factor values", { values <- base::as.factor(c("A", "A", "B")) summary <- visR::summarize_long(values) testthat::expect_equal(base::round(summary[[1]]$`% A`, 2), base::round((base::sum(values=="A")/base::length(values))*100, 2)) }) context("utils_table - T3. Correct values for summarize_long.default") test_that("T3.1. Correct count of unique values", { values <- c("A", "A", "B") summary <- visR::summarize_long(values) testthat::expect_equal(summary[[1]]$unique_values, base::length(base::unique(values))) }) test_that("T3.1. Correct count of missing values", { values <- c("A", "A", "B") summary <- visR::summarize_long(values) testthat::expect_equal(summary[[1]]$nmiss, 0) }) context("utils_table - T4. Correct values for summarize_short.numeric") test_that("T4.1. Correct mean values for numeric values in summarize_short", { values <- 1:5 summary <- visR::summarize_short(values) num <- base::paste0(base::round(base::mean(values),2), " (", base::round(stats::sd(values),2), ")") testthat::expect_equal(summary[[1]]$`Mean (SD)`, num) }) test_that("T4.2. Correct median values for numeric values in summarize_short", { values <- 1:5 summary <- visR::summarize_short(values) num <- base::paste0(base::round(stats::median(values),2), " (", base::round(stats::quantile(values, probs=0.25, na.rm = TRUE),2), "-", base::round(stats::quantile(values, probs=0.75, na.rm = TRUE),2), ")") testthat::expect_equal(summary[[1]]$`Median (IQR)`, num) }) test_that("T4.3. Correct range values for numeric values in summarize_short", { values <- 1:5 summary <- visR::summarize_short(values) num <- base::paste0(base::round(base::min(values),2), "-", base::round(base::max(values),2)) testthat::expect_equal(summary[[1]]$`Min-max`, num) }) test_that("T4.4. Correct missing values for numeric values in summarize_short", { values <- 1:5 summary <- visR::summarize_short(values) num <- base::paste0(base::sum(is.na(values)), " (",base::sum(is.na(values))/base::length(values) , "%)") testthat::expect_equal(summary[[1]]$Missing, num) }) context("utils_table - T5. Correct values for summarize_short.factor and summarize_short.string") test_that("T5.1. Correct value for factors in summarize_short", { values <- base::as.factor(c("A", "A", "B")) summary <- visR::summarize_short(values) num <- base::paste0(base::sum(values=="A"), " (", round(base::sum(values=="A")/base::length(values)*100, 1), "%)") testthat::expect_equal(summary[[1]]$A , num) }) test_that("T5.2. Correct default value in summarize_short", { values <- c("A", "A", "B") summary <- visR::summarize_short(values) num <- base::paste0(base::sum(values=="A"), " (", round(base::sum(values=="A")/base::length(values)*100, 1), "%)") testthat::expect_equal(summary[[1]]$`Unique values`, as.character(base::sum(values=="A"))) })
dRUMAuxMix <- function(yi,Ni,X,sim=12000,burn=2000,b0,B0,start,verbose=500){ starttime=proc.time()[3] if(!is.vector(yi)) stop("the counts yi must be a vector") if(!is.vector(Ni)) stop("the numbers of trials Ni must be a vector") if(!is.matrix(X)) stop("the design X must be a matrix") if(length(yi)!=length(Ni)) stop("yi and Ni must have same length") if(any(is.na(yi))) stop("can't handle NAs in yi") if(any(is.na(Ni))) stop("can't handle NAs in Ni") if(any(is.na(X))) stop("can't handle NAs in X") if(verbose<0) stop("verbose must be a non-negative integer") yi=as.integer(yi) Ni=as.integer(Ni) verbose=as.integer(verbose) if(any(Ni==0)){ X=X[(Ni>0),,drop=FALSE] yi=yi[(Ni>0)] Ni=Ni[(Ni>0)] } dims=ncol(X) t=length(yi) if(t!=nrow(X)) stop("wrong dimensions") if(missing(b0)) b0=rep(0,dims) if(missing(B0)) B0=diag(10,nrow=dims,ncol=dims) B0inv=solve(B0) B0invb0=B0inv%*%b0 indi1=as.numeric(yi>0) indi2=as.numeric(yi<Ni) pidach=pmin(pmax(yi/Ni,0.05),0.95) lam0=pidach/(1-pidach) U=rgamma(t,shape=Ni,rate=1+lam0) V=rgamma(t,shape=yi,rate=1) W=rgamma(t,shape=Ni-yi,rate=lam0) yiStar0=-log((U+indi2*W)/(U+indi1*V)) if(missing(start)) start=rep(0,dims) beta_new=start lam_new=lam0 yiStar_new=yiStar0 beta=matrix(NA,dims,sim) tX=t(X) H=5 mixture=cbind(matrix(0,nrow=t,ncol=5),matrix(1,nrow=t,ncol=5)) for(i in seq_len(t)){ mixture[i,1:length(compmix(Ni[i])$probs)]=compmix(Ni[i])$probs mixture[i,6:(6+length(compmix(Ni[i])$probs)-1)]=compmix(Ni[i])$var } probs=mixture[,1:5] vars=mixture[,6:10] vecvars=as.vector(t(vars)) st=H*(0:(t-1)) sd=sqrt(vars) logpr=log(probs) logsd=log(sd) pos=numeric(t) sr2=numeric(t) trickmat=outer(seq_len(H),seq_len(H),"<=") vertfkt=matrix(0,nrow=t,ncol=H) pre=probs/sd twovar=-2*vars yStar=function(lam_new){ U=rgamma(t,shape=Ni,rate=1+lam_new) V=rgamma(t,shape=yi,rate=1) W=rgamma(t,shape=Ni-yi,rate=lam_new) -log((U+indi2*W)/(U+indi1*V)) } for(s in seq_len(sim)){ if(s==(burn+1)){stop1=proc.time()[3]} Pr=pre*exp(rep.int((yiStar_new-log(lam_new))^2,H)/twovar) vertfkt=Pr%*%trickmat pos=rowSums(vertfkt[,H]*runif(t) > vertfkt)+1 sr2=vecvars[st+pos] Xtilde=X/sr2 sum1=tX%*%Xtilde BN=solve(B0inv+sum1) tC=t(chol(BN)) XtYstar=X*yiStar_new sum2=colSums(XtYstar/sr2) mN=B0invb0+sum2 bN=BN%*%mN beta_new=as.vector(bN+tC%*%rnorm(dims,0,1)) lam_new=exp(X%*%beta_new) yiStar_new=yStar(lam_new) beta[,s]=beta_new if(verbose>0){ if(is.element(s,c(1:5,10,20,50,100,200,500))){ cat("sim =", s,"/ duration of iter proc so far:", round(diff<-proc.time()[3]-starttime,2), "sec., expected time to end:", round((diff/(s-1)*sim-diff)/60,2), " min. \n") flush.console() } else if(s%%verbose==0){ cat("sim =", s,"/ duration of iter proc so far:", round(diff<-proc.time()[3]-starttime,2), "sec., expected time to end:", round((diff/(s-1)*sim-diff)/60,2), " min. \n") flush.console() } } } finish=proc.time()[3] duration=finish-starttime duration_wBI=finish-stop1 out <- list(beta=beta,sim=sim,burn=burn,dims=dims,t=t,b0=b0,B0=B0,duration=duration,duration_wBI=duration_wBI) class(out) <- "binomlogit" return(out) }
los_ra_index_summary_tbl <- function(.data, .max_los = 15, .alos_col, .elos_col, .readmit_rate, .readmit_bench) { max_los_var_expr <- .max_los alos_col_var_expr <- rlang::enquo(.alos_col) elos_col_var_expr <- rlang::enquo(.elos_col) readmit_rate_var_expr <- rlang::enquo(.readmit_rate) readmit_bench_var_expr <- rlang::enquo(.readmit_bench) if (!is.data.frame(.data)) { stop(call. = FALSE, "(data) is not a data-frame/tibble. Please provide.") } if (!(.max_los)) { max_los_var_expr = stats::quantile(!!alos_col_var_expr)[[4]] } if (rlang::quo_is_missing(alos_col_var_expr)) { stop(call. = FALSE, "(.alos_col) is missing. Please supply.") } if (rlang::quo_is_missing(elos_col_var_expr)) { stop(call. = FALSE, "(.elos_col) is missing. Please supply.") } if (rlang::quo_is_missing(readmit_rate_var_expr)) { stop(call. = FALSE, "(.readmit_rate) is missing. Please supply.") } if (rlang::quo_is_missing(readmit_bench_var_expr)) { stop(call. = FALSE, "(.readmit_bench) is missing. Please supply.") } if (ncol(.data) > 4) { stop(call. = FALSE, "(.data) has more than 4 columns. Please fix.") } df_tbl <- tibble::as_tibble(.data) %>% dplyr::mutate(alos = { { alos_col_var_expr } } %>% as.integer() %>% as.double()) df_summary_tbl <- df_tbl %>% dplyr::mutate(los_group = dplyr::case_when(alos > max_los_var_expr ~ max_los_var_expr , TRUE ~ alos)) %>% dplyr::group_by(los_group) %>% dplyr::summarise( tot_visits = dplyr::n(), tot_los = sum(alos, na.rm = TRUE), tot_elos = sum({ { elos_col_var_expr } }, na.rm = TRUE) , tot_ra = sum({ { readmit_rate_var_expr } }, na.rm = TRUE) , tot_perf = base::round(base::mean({ { readmit_bench_var_expr } }, na.rm = TRUE), digits = 2) ) %>% dplyr::ungroup() %>% dplyr::mutate(tot_rar = dplyr::case_when(tot_ra != 0 ~ base::round(( tot_ra / tot_visits ), digits = 2), TRUE ~ 0)) %>% dplyr::mutate(los_index = dplyr::case_when(tot_elos != 0 ~ (tot_los / tot_elos), TRUE ~ 0)) %>% dplyr::mutate(rar_index = dplyr::case_when((tot_rar != 0 & tot_perf != 0) ~ (tot_rar / tot_perf), TRUE ~ 0)) %>% dplyr::mutate(los_ra_var = base::abs(1 - los_index) + base::abs(1 - rar_index)) %>% dplyr::select(los_group, los_index, rar_index, los_ra_var) return(df_summary_tbl) } named_item_list <- function(.data, .group_col) { group_var_expr <- rlang::enquo(.group_col) if (!is.data.frame(.data)) { stop(call. = FALSE, "(.data) is not a data.frame/tibble. Please supply") } if (rlang::quo_is_missing(group_var_expr)) { stop(call. = FALSE, "(.group_col) is missing. Please supply") } data_tbl <- tibble::as_tibble(.data) data_tbl_list <- data_tbl %>% dplyr::group_split({ { group_var_expr } }) names(data_tbl_list) <- data_tbl_list %>% purrr::map( ~ dplyr::pull(., { { group_var_expr } })) %>% purrr::map( ~ base::as.character(.)) %>% purrr::map( ~ base::unique(.)) return(data_tbl_list) } category_counts_tbl <- function(.data, .count_col, .arrange_value = TRUE, ...){ count_col_var_expr <- rlang::enquo(.count_col) arrange_value <- .arrange_value if(!is.data.frame(.data)){ stop(call. = FALSE,"(.data) is missing. Please supply.") } if(rlang::quo_is_missing(count_col_var_expr)){ stop(call. = FALSE,"(.count_col) is missing. Please supply.") } data <- tibble::as_tibble(.data) data_tbl <- data %>% dplyr::group_by(...) %>% dplyr::count({{count_col_var_expr}}) %>% dplyr::ungroup() if(arrange_value) { data_tbl <- data_tbl %>% dplyr::arrange(dplyr::desc(n)) } return(data_tbl) } top_n_tbl <- function( .data , .n_records , .arrange_value = TRUE , ... ) { top_n_var_expr <- rlang::enquo(.n_records) group_var_expr <- rlang::quos(...) arrange_value <- .arrange_value if (!is.data.frame(.data)) { stop(call. = FALSE, "(data) is not a data-frame/tibble. Please provide.") } if (rlang::quo_is_missing(top_n_var_expr)) { stop(call. = FALSE, "(.n_records) is missing. Please provide.") } data <- tibble::as_tibble(.data) data_tbl <- data %>% dplyr::count(...) if(arrange_value) { data_tbl <- data_tbl %>% dplyr::arrange(dplyr::desc(n)) } data_tbl <- data_tbl %>% dplyr::slice(1:( {{top_n_var_expr}} )) return(data_tbl) } ts_census_los_daily_tbl <- function(.data, .keep_nulls_only = FALSE, .start_date_col, .end_date_col, .by_time = "day"){ start_date_var_expr <- rlang::enquo(.start_date_col) end_date_var_expr <- rlang::enquo(.end_date_col) by_var_expr <- .by_time if(!is.data.frame(.data)){ stop(call. = FALSE,"(.data) is not a data.frame/tibble. Please supply.") } if(rlang::quo_is_missing(start_date_var_expr)){ stop(call. = FALSE,"(.start_date_col) is missing. Please supply.") } if(rlang::quo_is_missing(end_date_var_expr)){ stop(call. = FALSE,"(.end_date_col) is missing. Please supply.") } keep_nulls_only_bool <- .keep_nulls_only data_tbl <- tibble::as_tibble(.data) all_dates_tbl <- data_tbl %>% dplyr::select( {{ start_date_var_expr }} , {{ end_date_var_expr }} ) %>% purrr::set_names("start_date","end_date") %>% dplyr::mutate(start_date = as.Date(start_date)) %>% dplyr::mutate(end_date = as.Date(end_date)) all_dates_tbl <- all_dates_tbl %>% dplyr::filter(!is.na(start_date)) %>% dplyr::filter(!is.na(end_date)) start_date <- min(all_dates_tbl[[1]], all_dates_tbl[[2]]) end_date <- max(all_dates_tbl[[1]], all_dates_tbl[[2]]) today <- Sys.Date() ts_day_tbl <- timetk::tk_make_timeseries( start_date = start_date , end_date = end_date , by = by_var_expr ) %>% tibble::as_tibble() %>% dplyr::rename("date"="value") %>% dplyr::mutate(date = as.Date(date)) res <- sqldf::sqldf( " SELECT * FROM ts_day_tbl AS A LEFT JOIN all_dates_tbl AS B ON start_date <= A.date AND start_date >= A.date " ) res <- tibble::as_tibble(res) %>% dplyr::arrange(end_date) los_tbl <- res %>% dplyr::mutate( los = dplyr::case_when( !is.na(end_date) ~ difftime( end_date, start_date, units = by_var_expr ) %>% as.integer() , TRUE ~ difftime( today, start_date, units = by_var_expr ) %>% as.integer() ) ) %>% dplyr::mutate(census = 1) %>% dplyr::arrange(date) if(!keep_nulls_only_bool){ data_final_tbl <- los_tbl } else { data_final_tbl <- los_tbl %>% dplyr::filter(is.na(end_date)) } return(data_final_tbl) }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) require(FunChisq) x <- matrix(c(12,26,18,0,8,12), nrow=2, ncol=3, byrow=TRUE) x res <- fun.chisq.test(x, method="exact") print(res) pval.text <- format.pval(res$p.value, digits=2) xif.text <- format.pval(res$estimate, digits=2) plot_table( x, xlab="CIMP", ylab="p53 mutation", col="seagreen3", main=bquote(italic(P)~'='~.(pval.text)*','~~italic(xi[f])~'='~.(xif.text)))
ggplot_build_set <- function() { if (!is_installed("ggplot2")) return(NULL) ggplot_build_restore() ggplot_build <- getFromNamespace("ggplot_build", "ggplot2") .globals$ggplot_build <- getFromNamespace("ggplot_build.ggplot", "ggplot2") assign_in_namespace <- assignInNamespace ensure_s3_methods_matrix() assign_in_namespace("ggplot_build.ggplot", ggthematic_build, "ggplot2") if (is_installed("gganimate")) { .globals$gganim_build <- getFromNamespace("ggplot_build.gganim", "gganimate") formals(ggthematic_build)$ggplot_build <- .globals$gganim_build assign_in_namespace("ggplot_build.gganim", ggthematic_build, "gganimate") } } ggplot_build_restore <- function() { if (is.function(.globals$ggplot_build)) { ggplot_build <- getFromNamespace("ggplot_build", "ggplot2") assign_in_namespace <- assignInNamespace ensure_s3_methods_matrix() assign_in_namespace("ggplot_build.ggplot", .globals$ggplot_build, "ggplot2") rm("ggplot_build", envir = .globals) if (is.function(.globals$gganim_build)) { assign_in_namespace("ggplot_build.gganim", .globals$gganim_build, "gganimate") rm("gganim_build", envir = .globals) } } } ensure_s3_methods_matrix <- function(pkg = "ggplot2") { S3 <- .getNamespaceInfo(asNamespace(pkg), "S3methods") S3 <- matrix(as.character(S3), nrow = nrow(S3), ncol = ncol(S3)) setNamespaceInfo(asNamespace(pkg), "S3methods", S3) } ggthematic_build <- function(p, ggplot_build = NULL, theme = NULL) { theme <- theme %||% thematic_get_theme(resolve = TRUE) ggplot_build <- ggplot_build %||% .globals$ggplot_build if (!is.function(ggplot_build)) { stop("`ggplot_build` must be a function", call. = FALSE) } if (!length(theme)) { return(ggplot_build(p)) } fg <- theme$fg bg <- theme$bg accent <- theme$accent[1] qualitative <- theme$qualitative sequential <- theme$sequential geoms <- c( lapply(p$layers, function(x) x$geom), lapply( c("GeomPoint", "GeomLine", "GeomPolygon"), getFromNamespace, "ggplot2" ) ) user_defaults <- lapply(geoms, function(geom) geom$default_aes) Map(function(geom, user_default) { geom$default_aes$colour <- adjust_color(user_default$colour, bg, fg, accent) geom$default_aes$fill <- adjust_color(user_default$fill, bg, fg, accent) if ("family" %in% names(geom$default_aes)) { geom$default_aes$family <- theme$font$family geom$default_aes$size <- user_default$size * theme$font$scale } }, geoms, user_defaults) on.exit({ Map(function(x, y) { x$default_aes <- y }, geoms, user_defaults) }, add = TRUE) scale_defaults <- list() if (!is_na_scalar(qualitative)) { scale_defaults$ggplot2.discrete.colour <- qualitative scale_defaults$ggplot2.discrete.fill <- qualitative } if (!is_na_scalar(sequential)) { scale_defaults$ggplot2.continuous.colour <- function(...) { ggplot2::scale_colour_gradientn(..., colours = sequential) } scale_defaults$ggplot2.continuous.fill <- function(...) { ggplot2::scale_fill_gradientn(..., colours = sequential) } scale_defaults$ggplot2.binned.colour <- function(...) { ggplot2::scale_colour_stepsn(..., colours = sequential) } scale_defaults$ggplot2.binned.fill <- function(...) { ggplot2::scale_fill_stepsn(..., colours = sequential) } } if (has_proper_ggplot_scale_defaults()) { old_scales <- do.call(options, scale_defaults) on.exit({options(old_scales)}, add = TRUE) } else { if (!is_na_scalar(sequential)) { if (!p$scales$has_scale("colour")) { colour_continuous <- tryGet("scale_colour_continuous", envir = p$plot_env) assign("scale_colour_continuous", scale_defaults$ggplot2.continuous.colour, envir = p$plot_env) on.exit({ restore_scale("scale_colour_continuous", colour_continuous, envir = p$plot_env) }, add = TRUE) } if (!p$scales$has_scale("fill")) { fill_continuous <- tryGet("scale_fill_continuous", envir = p$plot_env) assign("scale_fill_continuous", scale_defaults$ggplot2.continuous.fill, envir = p$plot_env) on.exit({ restore_scale("scale_fill_continuous", fill_continuous, envir = p$plot_env) }, add = TRUE) } } if (!is_na_scalar(qualitative)) { if (!p$scales$has_scale("colour")) { colour_discrete <- tryGet("scale_colour_discrete", envir = p$plot_env) assign( "scale_colour_discrete", function(...) ggplot2::discrete_scale("colour", "qualitative", qualitative_pal(qualitative), ...), envir = p$plot_env ) on.exit({ restore_scale("scale_colour_discrete", colour_discrete, envir = p$plot_env) }, add = TRUE) } if (!p$scales$has_scale("fill")) { fill_discrete <- tryGet("scale_fill_discrete", envir = p$plot_env) assign( "scale_fill_discrete", function(...) ggplot2::discrete_scale("fill", "qualitative", qualitative_pal(qualitative), ...), envir = p$plot_env ) on.exit({ restore_scale("scale_fill_discrete", fill_discrete, envir = p$plot_env) }, add = TRUE) } } } theme_final <- theme_thematic(theme) theme_user <- resolve_theme_inheritance(p$theme) for (name in names(theme_user)) { theme_final[[name]] <- ggplot2::merge_element( new = theme_user[[name]], old = theme_final[[name]] ) } p$theme <- theme_final ggplot_build(p) } theme_thematic <- function(theme = .globals$theme) { ggtheme <- computed_theme_elements(ggplot2::theme_get()) `%missing%` <- function(x, y) { if (identical(x, "transparent")) return(y) x %OR% y } old_bg <- ggtheme$plot.background$fill %missing% .globals$base_params$bg %missing% "white" old_fg <- ggtheme$title$colour %missing% "black" new_fg <- theme$fg new_bg <- theme$bg update_color <- function(color) { amt <- amount_of_mixture(color, old_bg, old_fg) mix_colors(new_bg, new_fg, amt) } update_element <- function(element, name) { UseMethod("update_element") } update_element.element_text <- function(element, name) { ggplot2::element_text( colour = update_color(element$colour), size = element$size * theme$font$scale, family = if (!identical(theme$font$family, "")) theme$font$family ) } update_element.element_rect <- function(element, name) { ggplot2::element_rect( fill = update_color(element$fill), colour = update_color(element$colour) ) } update_element.element_line <- function(element, name) { ggplot2::element_line( colour = update_color(element$colour) ) } update_element.element_blank <- function(element, name) { if (name %in% c("plot.background", "panel.background")) { ggplot2::element_rect(fill = new_bg, colour = new_bg) } else { element } } update_element.default <- function(element, name) NULL ggtheme <- Map(function(x, y) update_element(x, y), ggtheme, names(ggtheme)) do.call(ggplot2::theme, dropNulls(ggtheme)) } computed_theme_elements <- function(ggtheme) { theme_default <- ggplot2::theme_grey() elements <- names(ggplot2::get_element_tree()) if (identical(attr(ggtheme, "complete"), FALSE)) { ggtheme <- theme_default + ggtheme } computed <- rlang::set_names(lapply(elements, calc_element_safe, ggtheme), elements) dropNulls(computed) } resolve_theme_inheritance <- function(p_theme) { if (!length(p_theme)) { return(p_theme) } relationships <- theme_relationships() while(nrow(relationships) > 0) { idx <- !relationships$parent %in% relationships$child for (i in which(idx)) { this_relationship <- relationships[i, ] this_kid <- this_relationship$child this_parent <- this_relationship$parent parent_el <- p_theme[[this_parent]] kid_el <- p_theme[[this_kid]] if (is.null(parent_el)) { next } p_theme[[this_kid]] <- if (!is.null(kid_el)) { ggplot2::merge_element(new = kid_el, old = parent_el) } else { parent_el } } relationships <- relationships[!idx, ] } p_theme } theme_relationships <- function() { inherits <- vapply(ggplot2::get_element_tree(), function(x) { x$inherit %||% "" }, character(1)) relations <- data.frame(child = names(inherits), parent = inherits, stringsAsFactors = FALSE) relations[relations$parent != "", ] } calc_element_safe <- function(x, ...) { tryCatch(ggplot2::calc_element(x, ...), error = function(e) x) } restore_scale <- function(name, x, envir) { if (is.null(x)) rm(name, envir = envir) else assign(name, x, envir = envir) } has_proper_ggplot_scale_defaults <- function() { packageVersion("ggplot2") >= "3.3.2" } qualitative_pal <- function(codes) { function(n) { if (n <= length(codes)) { codes[seq_len(n)] } else { scales::hue_pal()(n) } } } is_na_scalar <- function(x) { if (length(x) != 1) { return(FALSE) } is.na(x) }
ChileClimateData <- function(Estaciones = "INFO", Parametros, inicio, fin, Region = FALSE){ sysEstaciones <- system.file("extdata", "Estaciones.csv", package = "AtmChile") tablaEstaciones <- read.csv(sysEstaciones, sep = "," , dec =".", encoding = "UTF-8") if(Estaciones[1] == "INFO"){ return(tablaEstaciones) } if(fin < inicio){ stop("Verificar fechas de inicio y fin") } url1 <- "https://climatologia.meteochile.gob.cl/application/datos/getDatosSaclim/" parametros_list <- c("Temperatura", "PuntoRocio", "Humedad", "Viento", "PresionQFE", "PresionQFF") intervalo <- inicio:fin lenInEstaciones <- length(Estaciones) lenInParametros <- length(Parametros) lenEstaciones <- nrow(tablaEstaciones) lenParametros <- length(parametros_list) lendate <- length(intervalo) start <- as.POSIXct(strptime(paste("01-01-", inicio, "00:00:00", sep =""), format = "%d-%m-%Y %H:%M:%S")) end <- as.POSIXct(strptime(paste("31-12-", fin, "23:00:00", sep =""), format = "%d-%m-%Y %H:%M:%S")) date = NULL date <- seq(start, end, by = "hour") date <- format(date, format = "%d-%m-%Y %H:%M:%S") df <- NULL df2 <- NULL data_total <- data.frame() if(Region == TRUE){ r <- 7 }else{ r <- 1 } for(i in 1:lenInEstaciones){ for(j in 1:lenEstaciones){ if(Estaciones[i] == tablaEstaciones[j, r]){ estacion_var <- tablaEstaciones[j, 1] Latitud <- tablaEstaciones[j, 5] Longitud <- tablaEstaciones[j, 6] Nombre <- rep(tablaEstaciones[j, 4], length(date)) Latitud <- rep(tablaEstaciones[j, 5], length(date)) Longitud <- rep(tablaEstaciones[j, 6], length(date)) data <- data.frame(date, Nombre, Latitud, Longitud) setDT(data) for(k in 1:lenInParametros){ for(l in 1:lenParametros){ if(Parametros[k] == parametros_list[l]){ for(m in 1:lendate){ temp <- tempfile() temp1 <- tempfile() url3 <- paste(url1, estacion_var,"_",intervalo[m], "_", parametros_list[l], "_", sep = "") print(url3) filename <- paste(estacion_var,"_",intervalo[m],"_", parametros_list[l], ".zip", sep = "") csvname <- paste(estacion_var,"_",intervalo[m],"_", parametros_list[l], "_.csv", sep = "") CSV <- NULL try({ download.file(url3, temp, method = "curl") suppressWarnings({ try({ CSV<- read.csv(unzip(temp, csvname), sep = ";", dec = ".", encoding = "UTF-8") }, silent = T) }) }, silent = TRUE) if(is.null(CSV)| length(CSV) == 0){ momento1 <- as.POSIXct(strptime(paste("01-01-", intervalo[m], "00:00:00", sep =""), format = "%d-%m-%Y %H:%M:%S")) momento2 <- as.POSIXct(strptime(paste("31-12-", intervalo[m], "23:00:00", sep =""), format = "%d-%m-%Y %H:%M:%S")) momento <- seq(momento1, momento2, by = "hour") CodigoNacional <-rep("", length(momento)) momento <- format(momento, format = "%d-%m-%Y %H:%M:%S") if(parametros_list[l] == "Temperatura"){ Ts_Valor<- rep("", length(momento)) CSV <- data.frame(CodigoNacional, momento, Ts_Valor) }else if(parametros_list[l] == "PuntoRocio"){ Td_Valor<- rep("", length(momento)) CSV <- data.frame(CodigoNacional, momento, Td_Valor) }else if(parametros_list[l] == "Humedad"){ HR_Valor<- rep("", length(momento)) CSV <- data.frame(CodigoNacional, momento, HR_Valor) }else if(parametros_list[l] == "Viento"){ dd_Valor<- rep("", length(momento)) ff_Valor<- rep("", length(momento)) VRB_Valor<- rep("", length(momento)) CSV <- data.frame(CodigoNacional, momento, dd_Valor,ff_Valor, VRB_Valor) }else if(parametros_list[l] == "PresionQFE"){ QFE_Valor<- rep("", length(momento)) CSV <- data.frame(CodigoNacional, momento, QFE_Valor) }else if(parametros_list[l] == "PresionQFF"){ QFF_Valor<- rep("", length(momento)) CSV <- data.frame(CodigoNacional, momento, QFF_Valor) } } df<- rbind(df, CSV) suppressWarnings({ file.remove(csvname) }) unlink(temp) } if(parametros_list[l] == "Viento"){ df2 <- data.frame(df[2], df[3], df[4], df[5]) }else{ df2 <- data.frame(df[2], df[3]) } setDT(df2) data <- data[df2, on = c("date" = "momento")] df <- NULL df2 <- NULL } } } if(is.null(data_total)){ data_total<-data }else{ data_total<-rbind(data_total, data) } } } } data_total$date <- format(as.POSIXct(strptime(data_total$date, format = "%d-%m-%Y %H:%M:%S")), format = "%d/%m/%Y %H:%M") data_total <- data_total[!(is.na(data_total$date)),] data_total <- data_total[!(is.na(data_total$Nombre)),] for(i in 3:ncol(data_total)){ data_total[[i]] <- as.numeric(data_total[[i]]) } data_total <- as.data.frame(data_total) return(data_total) }
context("2-level lme objects") set.seed(20190513) suppressMessages(library(lme4, quietly=TRUE)) library(nlme, quietly=TRUE, warn.conflicts=FALSE) library(mlmRev, quietly=TRUE, warn.conflicts=FALSE) obj_A <- lme(weight ~ Time * Diet, data=BodyWeight, ~ Time | Rat) obj_A2 <- update(obj_A, weights = varPower()) obj_A3 <- update(obj_A, correlation = corExp(form = ~ Time)) obj_A4 <- update(obj_A2, correlation = corExp(form = ~ Time)) obj_B <- lme(distance ~ age, random = ~ age, data = Orthodont) test_that("bread works", { expect_true(check_bread(obj_A, cluster = BodyWeight$Rat, y = BodyWeight$weight)) expect_true(check_bread(obj_A2, cluster = BodyWeight$Rat, y = BodyWeight$weight, tol = 5 * 10^-5)) expect_true(check_bread(obj_A3, cluster = BodyWeight$Rat, y = BodyWeight$weight)) expect_true(check_bread(obj_A4, cluster = BodyWeight$Rat, y = BodyWeight$weight)) expect_true(check_bread(obj_B, cluster = Orthodont$Subject, y = Orthodont$distance)) expect_equal(vcov(obj_A), obj_A$sigma^2 * bread(obj_A) / v_scale(obj_A)) expect_equal(vcov(obj_A2), obj_A2$sigma^2 * bread(obj_A2) / v_scale(obj_A2)) expect_equal(vcov(obj_A3), obj_A3$sigma^2 * bread(obj_A3) / v_scale(obj_A3)) expect_equal(vcov(obj_A4), obj_A4$sigma^2 * bread(obj_A4) / v_scale(obj_A4)) expect_equal(vcov(obj_B), obj_B$sigma^2 * bread(obj_B) / v_scale(obj_B)) }) test_that("vcovCR options work for CR2", { CR2_A <- vcovCR(obj_A, type = "CR2") expect_equal(vcovCR(obj_A, cluster = BodyWeight$Rat, type = "CR2"), CR2_A) expect_equal(vcovCR(obj_A, type = "CR2", inverse_var = TRUE), CR2_A) expect_false(identical(vcovCR(obj_A, type = "CR2", inverse_var = FALSE), CR2_A)) target <- targetVariance(obj_A) expect_equal(vcovCR(obj_A, type = "CR2", target = target, inverse_var = TRUE), CR2_A) attr(CR2_A, "inverse_var") <- FALSE expect_equal(vcovCR(obj_A, type = "CR2", target = target, inverse_var = FALSE), CR2_A) CR2_A2 <- vcovCR(obj_A2, type = "CR2") expect_equal(vcovCR(obj_A2, cluster = BodyWeight$Rat, type = "CR2"), CR2_A2) expect_equal(vcovCR(obj_A2, type = "CR2", inverse_var = TRUE), CR2_A2) expect_false(identical(vcovCR(obj_A2, type = "CR2", inverse_var = FALSE), CR2_A2)) target <- targetVariance(obj_A2) expect_equal(vcovCR(obj_A2, type = "CR2", target = target, inverse_var = TRUE), CR2_A2) attr(CR2_A2, "inverse_var") <- FALSE expect_equal(vcovCR(obj_A2, type = "CR2", target = target, inverse_var = FALSE), CR2_A2) CR2_A3 <- vcovCR(obj_A3, type = "CR2") expect_equal(vcovCR(obj_A3, cluster = BodyWeight$Rat, type = "CR2"), CR2_A3) expect_equal(vcovCR(obj_A3, type = "CR2", inverse_var = TRUE), CR2_A3) expect_false(identical(vcovCR(obj_A3, type = "CR2", inverse_var = FALSE), CR2_A3)) target <- targetVariance(obj_A3) expect_equal(vcovCR(obj_A3, type = "CR2", target = target, inverse_var = TRUE), CR2_A3) attr(CR2_A3, "inverse_var") <- FALSE expect_equal(vcovCR(obj_A3, type = "CR2", target = target, inverse_var = FALSE), CR2_A3) CR2_B <- vcovCR(obj_B, type = "CR2") expect_equal(vcovCR(obj_B, cluster = Orthodont$Subject, type = "CR2"), CR2_B) expect_equal(vcovCR(obj_B, type = "CR2", inverse_var = TRUE), CR2_B) expect_false(identical(vcovCR(obj_B, type = "CR2", inverse_var = FALSE), CR2_B)) target <- targetVariance(obj_B) expect_equal(vcovCR(obj_B, type = "CR2", target = target, inverse_var = TRUE), CR2_B) attr(CR2_B, "inverse_var") <- FALSE expect_equal(vcovCR(obj_B, type = "CR2", target = target, inverse_var = FALSE), CR2_B) }) test_that("vcovCR options work for CR4", { CR4_A <- vcovCR(obj_A, type = "CR4") expect_equal(vcovCR(obj_A, cluster = BodyWeight$Rat, type = "CR4"), CR4_A) expect_equal(vcovCR(obj_A, type = "CR4", inverse_var = TRUE), CR4_A) expect_false(identical(vcovCR(obj_A, type = "CR4", inverse_var = FALSE), CR4_A)) target <- targetVariance(obj_A) expect_equal(vcovCR(obj_A, type = "CR4", target = target, inverse_var = TRUE), CR4_A) attr(CR4_A, "inverse_var") <- FALSE expect_equal(vcovCR(obj_A, type = "CR4", target = target, inverse_var = FALSE), CR4_A) CR4_B <- vcovCR(obj_B, type = "CR4") expect_equal(vcovCR(obj_B, cluster = Orthodont$Subject, type = "CR4"), CR4_B) expect_equal(vcovCR(obj_B, type = "CR4", inverse_var = TRUE), CR4_B) expect_false(identical(vcovCR(obj_B, type = "CR4", inverse_var = FALSE), CR4_B)) target <- targetVariance(obj_B) expect_equal(vcovCR(obj_B, type = "CR4", target = target, inverse_var = TRUE), CR4_B) attr(CR4_B, "inverse_var") <- FALSE expect_equal(vcovCR(obj_B, type = "CR4", target = target, inverse_var = FALSE), CR4_B) }) test_that("CR2 and CR4 are target-unbiased", { expect_true(check_CR(obj_A, vcov = "CR2")) expect_true(check_CR(obj_B, vcov = "CR2")) expect_true(check_CR(obj_A, vcov = "CR4")) expect_true(check_CR(obj_B, vcov = "CR4")) }) CR_types <- paste0("CR",0:4) test_that("Order doesn't matter.", { check_sort_order(obj_A, BodyWeight) }) test_that("clubSandwich works with dropped observations", { dat_miss <- BodyWeight dat_miss$weight[sample.int(nrow(BodyWeight), size = round(nrow(BodyWeight) / 10))] <- NA obj_dropped <- update(obj_A, data = dat_miss, na.action = na.omit) obj_complete <- update(obj_A, data = dat_miss, subset = !is.na(weight)) CR_drop <- lapply(CR_types, function(x) vcovCR(obj_dropped, type = x)) CR_complete <- lapply(CR_types, function(x) vcovCR(obj_complete, type = x)) expect_equal(CR_drop, CR_complete) test_drop <- lapply(CR_types, function(x) coef_test(obj_dropped, vcov = x, test = "All", p_values = FALSE)) test_complete <- lapply(CR_types, function(x) coef_test(obj_complete, vcov = x, test = "All", p_values = FALSE)) expect_equal(test_drop, test_complete) }) test_that("lme agrees with gls", { lme_fit <- lme(weight ~ Time * Diet, data=BodyWeight, ~ 1 | Rat) gls_fit <- gls(weight ~ Time * Diet, data=BodyWeight, correlation = corCompSymm(form = ~ 1 | Rat)) CR_lme <- lapply(CR_types, function(x) vcovCR(lme_fit, type = x)) CR_gls <- lapply(CR_types, function(x) vcovCR(gls_fit, type = x)) expect_equivalent(CR_lme, CR_gls, tolerance = 10^-4) test_lme <- lapply(CR_types, function(x) coef_test(lme_fit, vcov = x, test = "All", p_values = FALSE)) test_gls <- lapply(CR_types, function(x) coef_test(gls_fit, vcov = x, test = "All", p_values = FALSE)) compare_ttests(test_lme, test_gls) constraints <- c(combn(length(coef(lme_fit)), 2, simplify = FALSE), combn(length(coef(lme_fit)), 3, simplify = FALSE)) Wald_lme <- Wald_test(lme_fit, constraints = constrain_zero(constraints), vcov = "CR2", test = "All") Wald_gls <- Wald_test(gls_fit, constraints = constrain_zero(constraints), vcov = "CR2", test = "All") compare_Waldtests(Wald_lme, Wald_gls) }) test_that("Emply levels are dropped in model_matrix", { data(AchievementAwardsRCT) AA_RCT_females <- subset(AchievementAwardsRCT, sex=="Girl" & year != "1999") AA_RCT_females <- within(AA_RCT_females, { sibs_4 <- siblings >= 4 treated2001 <- treated * (year=="2001") }) lme_fit <- lme(Bagrut_status ~ year * school_type + father_ed + mother_ed + immigrant + sibs_4 + qrtl + treated2001:half, random = ~ 1 | school_id, data = AA_RCT_females) betas <- fixef(lme_fit) X <- model_matrix(lme_fit) expect_identical(names(betas), colnames(X)) }) test_that("Possible to cluster at higher level than random effects", { n_districts <- 10 n_schools_per <- rnbinom(n_districts, size = 4, prob = 0.3) n_schools <- sum(n_schools_per) n_students_per <- 10 n_students <- n_schools * n_students_per district_id <- factor(rep(1:n_districts, n_schools_per * n_students_per)) school_id <- factor(rep(1:sum(n_schools_per), each = n_students_per)) student_id <- 1:n_students Y <- rnorm(n_districts)[district_id] + rnorm(n_schools)[school_id] + rnorm(n_students) X <- rnorm(n_students) dat <- data.frame(district_id, school_id, student_id, Y, X) dat_scramble <- dat[sample(nrow(dat)),] lme_2level <- lme(Y ~ X, random = ~ 1 | school_id, data = dat) V <- vcovCR(lme_2level, type = "CR2", cluster = dat$district_id) expect_is(V, "vcovCR") expect_error(vcovCR(lme_2level, type = "CR2", cluster = dat_scramble$district_id)) V_scramble <- vcovCR(lme(Y ~ X, random = ~ 1 | school_id, data = dat_scramble), type = "CR2", cluster = dat_scramble$district_id) expect_equal(as.matrix(V), as.matrix(V_scramble)) })
turnover <- function(df, time.var, species.var, abundance.var, replicate.var=NA, metric="total") { if(is.na(replicate.var)){ check_single_onerep(df, time.var, species.var) output <- turnover_allyears(df, time.var, species.var, abundance.var, metric) } else { df[replicate.var] <- if(is.factor(df[[replicate.var]])) { factor(df[[replicate.var]]) } else { df[replicate.var] } check_single(df, time.var, species.var, replicate.var) df <- df[order(df[[replicate.var]]),] X <- split(df, df[replicate.var]) out <- lapply(X, FUN=turnover_allyears, time.var, species.var, abundance.var, metric) ID <- unique(names(out)) out <- mapply(function(x, y) "[<-"(x, replicate.var, value = y) , out, ID, SIMPLIFY = FALSE) output <- do.call("rbind", out) } row.names(output) <- NULL return(as.data.frame(output)) } turnover_allyears <- function(df, time.var, species.var, abundance.var, metric=c("total", "disappearance","appearance")) { metric = match.arg(metric) check_numeric(df, time.var, abundance.var) df <- df[order(df[[time.var]]),] df <- df[which(df[[abundance.var]]>0),] templist <- split(df, df[[time.var]]) t1 <- templist[-length(templist)] t2 <- templist[-1] out <- Map(turnover_twoyears, t1, t2, species.var, metric) output <- as.data.frame(unlist(out)) names(output)[1] = metric alltemp <- unique(df[[time.var]]) output[time.var] = alltemp[2:length(alltemp)] return(output) } turnover_twoyears <- function(d1, d2, species.var, metric=c("total", "disappearance","appearance")){ metric = match.arg(metric) d1spp <- as.character(unique(d1[[species.var]])) d2spp <- as.character(unique(d2[[species.var]])) commspp <- intersect(d1spp, d2spp) disappear <- length(d1spp)-length(commspp) appear <- length(d2spp)-length(commspp) totrich <- sum(disappear, appear, length(commspp)) if(metric == "total"){ output <- ((appear+disappear)/totrich) } else { if(metric == "appearance"){ output <- appear/totrich } else { if(metric == "disappearance"){ output <- disappear/totrich } } } return(output) }
library(h2o) h2o.init(max_mem_size = "50g", nthreads = -1) dx_train <- h2o.importFile("train-1m.csv") dx_test <- h2o.importFile("test.csv") dx_train$DepTime <- dx_train$DepTime/2500 dx_test$DepTime <- dx_test$DepTime/2500 dx_train$Distance <- log10(dx_train$Distance)/4 dx_test$Distance <- log10(dx_test$Distance)/4 Xnames <- names(dx_train)[which(names(dx_train)!="dep_delayed_15min")] system.time({ md <- h2o.deeplearning(x = Xnames, y = "dep_delayed_15min", training_frame = dx_train, activation = "Rectifier", hidden = c(200,200), adaptive_rate = FALSE, rate = 0.01, rate_annealing = 0, momentum_start = 0.9, momentum_stable = 0.9, nesterov_accelerated_gradient = FALSE, epochs = 1) }) h2o.performance(md, dx_test)@metrics$AUC
config <- config::get(file = system.file("configurations", "plumber.yml", package = pkg_name(), mustWork = TRUE)) modify_url <- purrr::partial(httr::modify_url, url = "", scheme = config$scheme, hostname = config$host, port = config$port) expect_success_status <- function(response) expect_equal(httr::status_code(response), 200) expect_bad_request_status <- function(response) expect_equal(httr::status_code(response), 400) extract_content_text <- purrr::partial(httr::content, as = "text", encoding = "UTF-8") test_http("list_tables returns a vector with table names", { url <- modify_url(path = c("route_name", "list_tables")) expect_success_status(response <- httr::GET(url)) output <- extract_content_text(response) %>% jsonlite::fromJSON(flatten = TRUE) expect_type(output, "character") expect_true("mtcars" %in% output) }) test_http("read_table returns a data.frame", { url <- modify_url(path = c("route_name", "read_table")) expect_success_status(response <- httr::GET(url, query = list(name = "mtcars"))) output <- extract_content_text(response) %>% jsonlite::fromJSON(flatten = TRUE) expect_s3_class(output, "data.frame") }) test_http("read_table returns an informative error message", { url <- modify_url(path = c("route_name", "read_table")) expect_bad_request_status(response <- httr::GET(url, query = list(name = "xxx"))) output <- extract_content_text(response) %>% jsonlite::fromJSON(flatten = TRUE) expect_match(output$error, "should be one of") }) test_http("write_table copies a data.frame to the route_name", { url <- modify_url(path = c("route_name", "write_table")) body <- list(name = "zzz", value = datasets::sleep) expect_success_status(response <- httr::POST(url, body = body, encode = "json")) output <- extract_content_text(response) %>% jsonlite::fromJSON(flatten = TRUE) expect_equivalent(output, list()) url <- modify_url(path = c("route_name", "list_tables")) expect_success_status(response <- httr::GET(url)) output <- extract_content_text(response) %>% jsonlite::fromJSON(flatten = TRUE) expect_true("zzz" %in% output) })
plot.capthist <- function(x, rad = 5, hidetraps = FALSE, tracks = FALSE, title = TRUE, subtitle = TRUE, add = FALSE, varycol = TRUE, icolours = NULL, randcol = FALSE, lab1cap = FALSE, laboffset = 4, ncap = FALSE, splitocc = NULL, col2 = 'green', type = c("petal", "n.per.detector", "n.per.cluster", "sightings", "centres", "telemetry"), cappar = list(cex=1.3, pch=16, col='blue'), trkpar = list(col='blue', lwd=1), labpar = list(cex=0.7, col='black'), ...) { if (ms(x)) { if ((prod(par()$mfrow) < length(x)) & !add) warning("screen layout does not allow for all sessions and some plots may be lost;", " set par mfrow") sapply (x, plot.capthist, rad = rad, hidetraps = hidetraps, tracks = tracks, title = title, subtitle = subtitle, add = add, varycol = varycol, icolours = icolours, randcol = randcol, lab1cap = lab1cap, laboffset = laboffset, ncap = ncap, splitocc = splitocc, col2 = col2, type = type, cappar = cappar, trkpar = trkpar, labpar = labpar, ...) } else { plotproxcapt <- function (xy, occ, icol, emphasis = FALSE) { oxy <- order(occ) xy <- xy[oxy,] occ <- occ[oxy] xy[,1] <- xy[,1] + cos(occ * 2 * pi / nocc) * rad xy[,2] <- xy[,2] - sin(occ * 2 * pi / nocc) * rad if (!is.null(splitocc)) { colr <- ifelse(occ<splitocc,cappar$col, col2) par(trkpar) if (tracks) lines (xy, col = colr) par(cappar) points (xy, col = colr) } else { par(trkpar) if (varycol) par(col=icol) if (tracks) lines (xy) par(cappar) if (varycol) par(col=icol) points (xy) if (emphasis) points (xy, col='black', bg=par()$col, pch=21) } } plotpolygoncapt <- function (xy, icol, emphasis = FALSE) { par(trkpar) if (varycol) par(col=icol) if (tracks) lines (xy) par(cappar) if (varycol) par(col=icol) points (xy) if (emphasis) points (xy, col='black', bg=par()$col, pch=21) } labcapt <- function (n) { if ( detectr[1] %in% c('proximity', 'count', 'polygonX', 'transectX', 'signal', 'signalnoise', 'polygon', 'transect', 'unmarked', 'presence') ) { warning ("labels not implemented for this detector type") } else { xn <- apply(abs(x[n,,,drop=FALSE]),2,sum) o1 <- sum(cumsum(xn)==0)+1 t1 <- which(x[n,o1,]>0) dx <- (cos((1:nocc) * 2 * pi / nocc) * rad)[o1] dy <- (sin((1:nocc) * 2 * pi / nocc) * rad)[o1] par(labpar) if (varycol) par(col=n) laboffsety <- ifelse (length(laboffset)==2, laboffset[2], laboffset[1]) text (traps$x[t1]+dx+laboffset[1], traps$y[t1]-dy+laboffsety, row.names(x)[n]) } } labhead <- function (n, df) { par(labpar) if (varycol) par(col=n) laboffsety <- ifelse (length(laboffset)==2, laboffset[2], laboffset[1]) text (head(df[[n]],1)$x++laboffset[1], head(df[[n]],1)$y+laboffsety, row.names(x)[n]) } ncapt <- function (x) { if (detectr[1] %in% .localstuff$polydetectors) { stop ("ncap does not work with polygon and similar detectors") } temp <- t(apply (abs(x),c(2,3),sum)) dx <- rep(cos((1:nocc) * 2 * pi / nocc) * rad, rep(nrow(traps),nocc)) dy <- rep(sin((1:nocc) * 2 * pi / nocc) * rad, rep(nrow(traps),nocc)) par(labpar) par(adj=0.5) OK <- temp>0 text ((traps$x[row(temp)]+dx)[OK], (traps$y[row(temp)]-dy)[OK], as.character(temp[OK])) } plotsignal <- function (df, minsignal, maxsignal,n) { .localstuff$i <- .localstuff$i+1 dx <- rep( (cos((.localstuff$i) * 2 * pi / n) * rad), nrow(df)) dy <- rep( (sin((.localstuff$i) * 2 * pi / n) * rad), nrow(df)) sq <- order(df$signal) df <- df[sq,] df$trap <- as.character(df$trap) if (maxsignal>minsignal) greycol <- grey(0.7 * (1 - (df$signal-minsignal)/(maxsignal-minsignal))) else greycol <- grey(0.5) if (tracks) lines (traps$x[df$trap]+dx, traps$y[df$trap]-dy, col=greycol) par(cappar) points (traps[df$trap,'x']+dx, traps[df$trap,'y']-dy, col = greycol) } plotsightings <- function (x) { Tu <- Tu(x) Tu0 <- Tu marking <- Tu if (is.null(Tu)) stop ("sightings type requires sighting data Tu") markocc <- markocc(traps(x)) Tu0[Tu!=0] <- NA Tu0[,markocc>0] <- NA Tu[Tu==0] <- NA marking[,markocc<1] <- NA dx <- rep((cos((1:nocc) * 2 * pi / nocc) * rad), each = nrow(Tu)) dy <- rep((sin((1:nocc) * 2 * pi / nocc) * rad), each = nrow(Tu)) dx0 <- dx; dx0[is.na(Tu0)] <- NA if (all(detector(traps(x)) %in% c('polygon'))) { centres <- split(traps(x), polyID(traps(x))) centres <- lapply(centres, function(xy) apply(xy[-1,,drop=FALSE], 2, mean)) trapxy <- data.frame(do.call(rbind,centres)) names(trapxy) <- c('x','y') } else trapxy <- traps(x) par(labpar) text (rep(trapxy$x, nocc) + dx, rep(trapxy$y, nocc) - dy, Tu, cex = 0.8) par(cappar) points (rep(trapxy$x, nocc) + dx0, rep(trapxy$y, nocc) - dy, pch = 1, cex = 0.7) dx[is.na(marking)] <- NA points (rep(trapxy$x, nocc) + dx, rep(trapxy$y, nocc) - dy, pch=16, cex=0.4) } plotcentres <- function (x) { xtraps <- traps(x) meanxya <- function(xy) apply(xy, 2, mean) meanxy <- function(trp) apply(xtraps[trp,],2,mean) if (all(detector(traps(x)) %in% 'telemetry')) { xyl <- telemetryxy(x) xyl <- lapply(xyl, meanxya) xy <- do.call(rbind, xyl) } else if (!any(detector(traps(x)) %in% .localstuff$polydetectors)) { trplist <- split(trap(x, sortorder = 'ksn'), animalID(x, sortorder = 'ksn')) xyl <- lapply(trplist, meanxy) xy <- do.call(rbind, xyl) } else { xyl <- telemetryxy(x) if (is.null(xyl)) xyl <- split(xy(x), animalID(x, sortorder = "ksn")) xyl <- lapply(xyl, meanxya) xy <- do.call(rbind, xyl) } if (rad>0) xy <- xy + (runif(2*nrow(xy))-0.5) * rad points (xy, ...) } x <- check3D(x) opal <- palette() ; on.exit(palette(opal)) type <- match.arg(type) traps <- traps(x) detectr <- expanddet(x) if (is.null(rownames(x)) && nrow(x)>0) { warning ("capthist has no rownames; using 1:nrow") rownames(x) <- 1:nrow(x) } if (all(detectr == 'telemetry')) { type <- 'telemetry' } if (type =='telemetry') nocc <- sum(detectr == 'telemetry') else nocc <- sum(detectr != 'telemetry') if (type %in% c('petal','centres')) cappar <- replacedefaults (list(cex=1.3, pch=16, col='blue'), cappar) if (type == 'sightings') cappar <- replacedefaults (list(cex=1, pch=16, col='blue'), cappar) if (type %in% c('n.per.cluster','n.per.detector')) cappar <- replacedefaults (list(cex = 3, pch = 21), cappar) trkpar <- replacedefaults (list(col='blue', lwd=1), trkpar) labpar <- replacedefaults (list(cex=0.7, col='black'), labpar) initialpar <- par(cappar) if (!add) { if (type=="telemetry") { xyl <- telemetryxy(x) xy <- do.call(rbind, xyl) xl <- range(xy[,1]) yl <- range(xy[,2]) tr <- expand.grid(x=xl, y=yl) class(tr) <- c('traps', 'data.frame') plot(tr, hidetr=TRUE, ...) } else { plot(traps, hidetr=hidetraps, ...) } } if (nrow(x) == 0) { warning("no detections in capthist object") type <- 'null' } if (is.null(icolours)) icolours <- topo.colors((nrow(x)+1)*1.5) if (varycol) { if (randcol) icolours <- sample(icolours) test <- try (palette(icolours)) if (inherits(test, 'try-error')) stop ("requested too many colours; ", "try with varycol = FALSE") icol <- 0 } else { } if (type == 'petal') { if ((nocc == 1) & ! (detectr[1] %in% c('signal','signalnoise'))) rad <- 0 if ( detectr[1] %in% .localstuff$polydetectors ) { lxy <- split (xy(x), animalID(x, names = FALSE, sortorder = "ksn")) mapply (plotpolygoncapt, lxy, 1:length(lxy)) } else if ( detectr[1] %in% c('signal','signalnoise') ) { .localstuff$i <- 0 temp <- data.frame( ID = animalID(x, sortorder = "ksn"), occ = occasion(x, sortorder = "ksn"), trap = trap(x, sortorder = "ksn"), signal = signal(x)) lsignal <- split(temp, animalID(x, names = FALSE, sortorder = "ksn")) lapply(lsignal, plotsignal, minsignal = min(temp$signal), maxsignal = max(temp$signal), n=nrow(x)) } else { xydf <- as.data.frame(traps(x)[trap(x, sortorder = 'snk'),]) occ <- occasion(x, sortorder = 'snk') OK <- detectr[occ] != 'telemetry' ID <- factor(animalID(x), levels = rownames(x)) lxy <- split(xydf[OK,], ID[OK]) occ <- split(occ[OK], ID[OK]) if (tracks & any(unlist(sapply(occ, duplicated)))) warning("track for repeat detections on same occasion", " joins points in arbitrary sequence") mapply(plotproxcapt, lxy, occ, 1:length(lxy), telemetered(x)) } if (lab1cap) { if ( detectr[1] %in% .localstuff$polydetectors ) { lxy <- split (xy(x), animalID(x, names = FALSE, sortorder = "ksn")) sapply(1:nrow(x), labhead, df=lxy) } else { sapply(1:nrow(x), labcapt) } } if (ncap) { ncapt(x)} } else if (type %in% c('n.per.cluster','n.per.detector')) { if (type == 'n.per.detector') { temp <- table(trap(x, sortorder = 'snk'), animalID(x, sortorder = 'snk'))>0 nj <- apply(temp,1,sum) centres <- traps(x)[names(nj),] } else if (type == 'n.per.cluster') { nj <- cluster.counts(x) centres <- cluster.centres(traps) centres <- centres[nj>0,] nj <- nj[nj>0] } else stop ("unrecognised type") if (is.null(icolours)) { icolours <- topo.colors(max(nj)*1.5) } palette (icolours) npal <- length(icolours) if (max(nj) < npal) { cols <- npal-nj } else { cols <- round(npal * (1-nj/max(nj))) } if (cappar$pch == 21) fg <- 'black' else fg <- cols par(cappar) points(centres, col = fg, bg = cols, pch = cappar$pch, cex = cappar$cex) if (ncap) { par(labpar) par(adj=0.5) vadj <- diff(par()$usr[3:4])/500 text(centres$x, centres$y + vadj, nj) } tempcol <- npal- (1:max(nj)) output <- data.frame( legend = 1:max(nj), col = tempcol, colour = icolours[tempcol], stringsAsFactors = FALSE ) } else if (type == 'sightings') { plotsightings(x) } else if (type == 'centres') { plotcentres(x) } else if (type == 'telemetry') { lxy <- telemetryxy(x) seqnum <- match(names(lxy), rownames(x)) caught <- apply(abs(x[seqnum,detectr!='telemetry',,drop=FALSE]),1,sum)>0 mapply (plotpolygoncapt, lxy, seqnum, caught) } else if (type != 'null') stop ("type not recognised") if (type == 'telemetry') { nocc <- sum(detectr == 'telemetry') nd <- sum(abs(x)[,detectr == 'telemetry',]) nanimal <- length(telemetryxy(x)) } else { nocc <- sum(detectr != 'telemetry') nd <- sum(abs(x)[,detectr != 'telemetry',]) nanimal <- sum(apply(abs(x)[,detectr != 'telemetry',,drop=FALSE],1,sum)>0) } pl <- if (nocc>1) 's' else '' if (type == 'sightings') { markocc <- markocc(traps(x)) Tu <- Tu(x) nd <- sum(Tu) nocc <- sum(markocc<1) } if (type == 'telemetry') { nd <- sum(sapply(lxy,nrow)) nocc <- sum(detector(traps(x))=="telemetry") nanimal <- length(lxy) } if (is.logical(title)) { txt <- ifelse (is.null(session(x)), paste(deparse(substitute(x)), collapse=''), session(x)) title <- ifelse(title, txt, '') } if (title != '') { par(col='black') mtext(side=3,line=1.2, text = title, cex=0.7) } if (is.logical(subtitle)) { subtitle <- if (subtitle) { if (type == 'sightings') { if (any(markocc<0)) paste0(nocc, ' sighting occasion', pl, ', ', nd, ' sightings of marked and unmarked animals') else paste0(nocc, ' sighting occasion', pl, ', ', nd, ' sightings of unmarked animals') } else if (type == 'telemetry') paste0(nocc, ' occasion', pl, ', ', nd, ' fixes,', nanimal, ' animals') else paste0(nocc, ' occasion', pl, ', ', nd, ' detections, ', nanimal, ' animals') } else '' } if (subtitle != '') { par(col='black') mtext(text = subtitle, side=3,line=0.2, cex=0.7) } par(initialpar) if (type %in% c('n.per.detector','n.per.cluster')) invisible(output) else invisible(nd) } } plotMCP <- function(x, add = FALSE, col = 'black', fill = NA, lab1cap = FALSE, laboffset = 4, ncap = FALSE, ...) { plotone <- function (df, col, fill) { if (nrow(df)>0) { par(fg=col) polygon(df, col=fill) } } mcp <- function (df) { if (nrow(df)>1) { df <- df[chull(df[,1], df[,2]),] rbind(df, df[1,]) } else df } if (ms(x)) { lapply(x, plotMCP, add = add, col = col, ...) } else { xyl <- telemetryxy(x) if (is.null(xyl)) { if (all(detector(traps(x)) %in% c('polygon','polygonX'))) xyl <- split(xy(x), animalID(x, sortorder = 'ksn')) else { df <- as.data.frame(traps(x)[trap(x, names = FALSE, sortorder = 'snk'),]) xyl <- split(df, animalID(x, sortorder = 'snk')) } } if (!add) plot(traps(x), ...) fg <- par()$fg on.exit(par(fg=fg)) if (missing(col)) col <- 'black' xymcp <- lapply(xyl, mcp) if (length(xymcp)>0) { mapply(plotone, xymcp, col, fill) if (lab1cap | ncap) { labhead <- function(xy, nam, num, col) { laboffsety <- ifelse (length(laboffset)==2, laboffset[2], laboffset[1]) if (ncap) text (xy[1,1] + laboffset[1], xy[1,2] + laboffsety, num, col=col) else text (xy[1,1] + laboffset[1], xy[1,2] + laboffsety, nam, col=col) } mapply(labhead, xymcp, names(xyl), sapply(xyl,nrow), col) } } invisible(xyl) } } occasionKey <- function (capthist, noccasions, rad = 3, x, y, px = 0.9, py = 0.9, title = 'Occasion', ...) { if (missing(x)) { ux <- par()$usr[1:2] x <- ux[1] + px * diff(ux) } if (missing(y)) { uy <- par()$usr[3:4] y <- uy[1] + py * diff(uy) } if (!missing(capthist)) { if (ms(capthist)) stop ("occasionKey requires single-session capthist") noccasions <- ncol(capthist) } else { if (missing (noccasions)) stop ("occasionKey requires one of capthist or noccasions") } dx <- cos((1:noccasions) * 2 * pi / noccasions) * rad dy <- sin((1:noccasions) * 2 * pi / noccasions) * rad points (x,y, cex = 0.5) text (x, y+rad*2.3, title, ...) text (x+dx, y-dy, 1:noccasions, ...) }
"CredentialForm1"
nlsmnc <-function(formula, start, trace=FALSE, data=NULL, control=list(),...){ if (! is.null(data)){ for (dfn in names(data)) { cmd<-paste(dfn,"<-data$",dfn,"") eval(parse(text=cmd)) } } ctrl<-list( watch=FALSE, phi=1, lamda=0.0001, offset=100, laminc=10, lamdec=4 ) ncontrol <- names(control) nctrl <- names(ctrl) for (onename in ncontrol) { if (!(onename %in% nctrl)) { if (trace) cat("control ",onename," is not in default set\n") } ctrl[onename]<-control[onename] } phiroot<-sqrt(ctrl$phi) lamda<-ctrl$lamda offset<-ctrl$offset laminc<-ctrl$laminc lamdec<-ctrl$lamdec vn <- all.vars(parse(text=formula)) pnum<-start pnames<-names(pnum) if (trace) { parpos <- match(names(pnum), vn) datvar<-vn[-parpos] for (dvn in datvar){ cat("Data variable ",dvn,":") print(eval(parse(text=dvn))) } } if (is.character(formula)){ es<-formula } else { tstr<-as.character(formula) es<-paste(tstr[[2]],"~",tstr[[3]],'') } parts<-strsplit(as.character(es), "~")[[1]] if (length(parts)!=2) stop("Model expression is incorrect!") lhs<-parts[1] rhs<-parts[2] resexp<-paste(rhs,"-",lhs, collapse=" ") npar<-length(start) for (i in 1:npar){ joe<-paste(names(pnum)[[i]],"<-",pnum[[i]]) eval(parse(text=joe)) } gradexp<-deriv(parse(text=resexp), names(start)) if (is.null(data)){ resbest<-eval(parse(text=resexp)) } else {resbest<-with(data, eval(parse(text=resexp))) } ssbest<-crossprod(resbest) feval<-1 pbest<-pnum feval<-1 jeval<-0 if (trace) { cat("lamda:",lamda," SS = ",ssbest," at ") print(pnum) } ssquares<-.Machine$double.xmax newjac<-TRUE eqcount<-0 while (eqcount < npar) { if (newjac) { if (is.null(data)){ J0<-eval(gradexp) } else {J0<-with(data, eval(gradexp))} Jac<-attr(J0,"gradient") jeval<-jeval+1 if (any(is.na(Jac))) stop("NaN in Jacobian") JTJ<-crossprod(Jac) gjty<-t(Jac)%*%resbest dde<-diag(diag(JTJ))+phiroot*diag(npar) } Happ<-JTJ+lamda*dde s1<-qr.solve(Happ,gjty) Rmat<-try(chol(Happ)) matfail<-FALSE if (class(Rmat) == "try-error") { matfail<-TRUE } else { solfail<-FALSE delta<-try(backsolve(Rmat,forwardsolve(t(Rmat),gjty))) if (class(delta)=="try-error") solfail=TRUE } if (matfail || solfail) { if (lamda<1000*.Machine$double.eps) lamda<-1000*.Machine$double.eps lamda<-laminc*lamda newjac<-FALSE if (trace) cat(" Equation solution failure\n") } else { pnum<-pbest-delta names(pnum)<-pnames eqcount<-length(which((offset+pbest)==(offset+pnum))) if (eqcount<npar) { for (i in 1:npar){ joe<-paste(names(pnum)[[i]],"<-",pnum[[i]]) eval(parse(text=joe)) } feval<-feval+1 if (is.null(data)){ resid<-eval(parse(text=resexp)) } else {resid<-with(data, eval(parse(text=resexp)))} ssquares<-as.numeric(crossprod(resid)) if (ssquares>=ssbest) { if (lamda<1000*.Machine$double.eps) lamda<-1000*.Machine$double.eps lamda<-laminc*lamda newjac<-FALSE if(trace) cat(">= lamda=",lamda,"\n") } else { if (trace) { cat("<< lamda=",lamda,"\n") cat(" SS = ",ssquares," evals J/F:",jeval,"/",feval," eqcount=",eqcount,"\n") print(pnum) } lamda<-lamdec*lamda/laminc ssbest<-ssquares resbest<-resid pbest<-pnum if (trace) { cat("<< Lamda=",lamda,"\n") } newjac<-TRUE } if (ctrl$watch) tmp<-readline() } else { if (trace) cat("No parameter change\n") } } } result<-list(coeffs=pnum,ssquares=ssbest, resid=resbest, jacobian=Jac, feval=feval, jeval=jeval) }
httpResponse <- function(status = 200L, content_type = "text/html; charset=UTF-8", content = "", headers = list()) { headers <- as.list(headers) if (is.null(headers$`X-UA-Compatible`)) headers$`X-UA-Compatible` <- "IE=edge,chrome=1" resp <- list(status = status, content_type = content_type, content = content, headers = headers) class(resp) <- 'httpResponse' return(resp) } joinHandlers <- function(handlers) { if (length(handlers) == 0) return(function(req) NULL) if (is.function(handlers)) return(handlers) handlers <- lapply(handlers, function(h) { if (is.character(h)) return(staticHandler(h)) else return(h) }) handlers <- handlers[!sapply(handlers, is.null)] if (length(handlers) == 0) return(function(req) NULL) if (length(handlers) == 1) return(handlers[[1]]) function(req) { for (handler in handlers) { response <- handler(req) if (!is.null(response)) return(response) } return(NULL) } } routeHandler <- function(prefix, handler) { force(prefix) force(handler) if (identical("", prefix)) return(handler) if (length(prefix) != 1 || !isTRUE(grepl("^/[^\\]+$", prefix))) { stop("Invalid URL prefix \"", prefix, "\"") } pathPattern <- paste("^\\Q", prefix, "\\E/", sep = "") function(req) { if (isTRUE(grepl(pathPattern, req$PATH_INFO))) { origScript <- req$SCRIPT_NAME origPath <- req$PATH_INFO on.exit({ req$SCRIPT_NAME <- origScript req$PATH_INFO <- origPath }, add = TRUE) pathInfo <- substr(req$PATH_INFO, nchar(prefix)+1, nchar(req$PATH_INFO)) req$SCRIPT_NAME <- paste(req$SCRIPT_NAME, prefix, sep = "") req$PATH_INFO <- pathInfo return(handler(req)) } else { return(NULL) } } } routeWSHandler <- function(prefix, wshandler) { force(prefix) force(wshandler) if (identical("", prefix)) return(wshandler) if (length(prefix) != 1 || !isTRUE(grepl("^/[^\\]+$", prefix))) { stop("Invalid URL prefix \"", prefix, "\"") } pathPattern <- paste("^\\Q", prefix, "\\E/", sep = "") function(ws) { req <- ws$request if (isTRUE(grepl(pathPattern, req$PATH_INFO))) { origScript <- req$SCRIPT_NAME origPath <- req$PATH_INFO on.exit({ req$SCRIPT_NAME <- origScript req$PATH_INFO <- origPath }, add = TRUE) pathInfo <- substr(req$PATH_INFO, nchar(prefix)+1, nchar(req$PATH_INFO)) req$SCRIPT_NAME <- paste(req$SCRIPT_NAME, prefix, sep = "") req$PATH_INFO <- pathInfo return(wshandler(ws)) } else { return(NULL) } } } staticHandler <- function(root) { force(root) return(function(req) { if (!identical(req$REQUEST_METHOD, 'GET')) return(NULL) path <- URLdecode(req$PATH_INFO) if (is.null(path)) return(httpResponse(400, content="<h1>Bad Request</h1>")) if (path == '/') path <- '/index.html' if (grepl('\\', path, fixed = TRUE)) return(NULL) abs.path <- resolve(root, path) if (is.null(abs.path)) return(NULL) content.type <- getContentType(abs.path) response.content <- readBin(abs.path, 'raw', n=file.info(abs.path)$size) return(httpResponse(200, content.type, response.content)) }) } HandlerList <- R6Class("HandlerList", portable = FALSE, class = FALSE, public = list( handlers = list(), add = function(handler, key, tail = FALSE) { if (!is.null(handlers[[key]])) stop("Key ", key, " already in use") newList <- structure(names=key, list(handler)) if (length(handlers) == 0) handlers <<- newList else if (tail) handlers <<- c(handlers, newList) else handlers <<- c(newList, handlers) }, remove = function(key) { handlers[key] <<- NULL }, clear = function() { handlers <<- list() }, invoke = function(...) { for (handler in handlers) { result <- handler(...) if (!is.null(result)) return(result) } return(NULL) } ) ) HandlerManager <- R6Class("HandlerManager", portable = FALSE, class = FALSE, public = list( handlers = "HandlerList", wsHandlers = "HandlerList", initialize = function() { handlers <<- HandlerList$new() wsHandlers <<- HandlerList$new() }, addHandler = function(handler, key, tail = FALSE) { handlers$add(handler, key, tail) }, removeHandler = function(key) { handlers$remove(key) }, addWSHandler = function(wsHandler, key, tail = FALSE) { wsHandlers$add(wsHandler, key, tail) }, removeWSHandler = function(key) { wsHandlers$remove(key) }, clear = function() { handlers$clear() wsHandlers$clear() }, createHttpuvApp = function() { list( onHeaders = function(req) { maxSize <- getOption('shiny.maxRequestSize') %||% (5 * 1024 * 1024) if (maxSize <= 0) return(NULL) reqSize <- 0 if (length(req$CONTENT_LENGTH) > 0) reqSize <- as.numeric(req$CONTENT_LENGTH) else if (length(req$HTTP_TRANSFER_ENCODING) > 0) reqSize <- Inf if (reqSize > maxSize) { return(list(status = 413L, headers = list('Content-Type' = 'text/plain'), body = 'Maximum upload size exceeded')) } else { return(NULL) } }, call = .httpServer( function (req) { hybrid_chain( hybrid_chain( withCallingHandlers(withLogErrors(handlers$invoke(req)), error = function(cond) { sanitizeErrors <- getOption('shiny.sanitize.errors', FALSE) if (inherits(cond, 'shiny.custom.error') || !sanitizeErrors) { stop(cond$message, call. = FALSE) } else { stop(paste("An error has occurred. Check your logs or", "contact the app author for clarification."), call. = FALSE) } } ), catch = function(err) { httpResponse(status = 500L, content_type = "text/html; charset=UTF-8", content = as.character(htmltools::htmlTemplate( system_file("template", "error.html", package = "shiny"), message = conditionMessage(err) )) ) } ), function(resp) { maybeInjectAutoreload(resp) } ) }, loadSharedSecret() ), onWSOpen = function(ws) { return(wsHandlers$invoke(ws)) } ) }, .httpServer = function(handler, checkSharedSecret) { filter <- getOption('shiny.http.response.filter') if (is.null(filter)) filter <- function(req, response) response function(req) { if (!checkSharedSecret(req$HTTP_SHINY_SHARED_SECRET)) { return(list(status=403, body='<h1>403 Forbidden</h1><p>Shared secret mismatch</p>', headers=list('Content-Type' = 'text/html'))) } head_request <- FALSE if (identical(req$REQUEST_METHOD, "HEAD")) { head_request <- TRUE req$REQUEST_METHOD <- "GET" } response <- handler(req) res <- hybrid_chain(response, function(response) { if (is.null(response)) response <- httpResponse(404, content="<h1>Not Found</h1>") if (inherits(response, "httpResponse")) { headers <- as.list(response$headers) headers$'Content-Type' <- response$content_type response <- filter(req, response) if (head_request) { headers$`Content-Length` <- getResponseContentLength(response, deleteOwnedContent = TRUE) return(list( status = response$status, body = "", headers = headers )) } else { return(list( status = response$status, body = response$content, headers = headers )) } } else { return(response) } }) } } ) ) maybeInjectAutoreload <- function(resp) { if (get_devmode_option("shiny.autoreload", FALSE) && isTRUE(grepl("^text/html($|;)", resp$content_type)) && is.character(resp$content)) { resp$content <- gsub( "</head>", "<script src=\"shared/shiny-autoreload.js\"></script>\n</head>", resp$content, fixed = TRUE ) } resp } getResponseContentLength <- function(response, deleteOwnedContent) { force(deleteOwnedContent) result <- if (is.character(response$content) && length(response$content) == 1) { nchar(response$content, type = "bytes") } else if (is.raw(response$content)) { length(response$content) } else if (is.list(response$content) && !is.null(response$content$file)) { if (deleteOwnedContent && isTRUE(response$content$owned)) { on.exit(unlink(response$content$file, recursive = FALSE, force = FALSE), add = TRUE) } file.info(response$content$file)$size } else { warning("HEAD request for unexpected content class ", class(response$content)[[1]]) NULL } if (is.na(result)) { return(NULL) } else { return(result) } }
sentenceTokenParse <- function(text, docId = "create", removePunc=TRUE, removeNum=TRUE, toLower=TRUE, stemWords=TRUE, rmStopWords=TRUE){ sentenceDf <- sentenceParse(text, docId=docId) tokenDfList <- lapply(seq_along(sentenceDf$sentence), function(i) { sentVec <- sentenceDf$sentence[i] tokenList <- tokenize(text = sentVec, removePunc = removePunc, removeNum = removeNum, toLower = toLower, stemWords = stemWords, rmStopWords=rmStopWords) subTokenDfList <- lapply(seq_along(tokenList), function(j) { data.frame(docId=sentenceDf$docId[i], sentenceId=sentenceDf$sentenceId[i], token=tokenList[[j]], stringsAsFactors = FALSE) }) do.call('rbind', subTokenDfList) }) tokenDf <- do.call('rbind', tokenDfList) tokenDf <- tokenDf[!is.na(tokenDf$token),] class(tokenDf) <- "data.frame" list(sentences=sentenceDf, tokens=tokenDf) }
context("test-delete_node.R") test_that("delete_node handles bad inputs correctly", { expect_error(delete_node(), regexp = "argument \"nid\" is missing") })
current.mode <- tmap_mode("plot") data(NLD_muni) qtm(NLD_muni, theme = "NLD") + tm_scale_bar(position=c("left", "bottom")) tmap_mode(current.mode)
summary.logistic_regression <- function( object, digits=4, file=NULL, ...) { mdmb_regression_summary( object=object, digits=digits, file=file, ...) }
context('Test all functions used for mirroring') test_that('Best plane works', { s <- matrix(1:21, ncol = 3, nrow = 7) m <- midline(s, 1:4) expect_equal(sum(m$n^2), 1) expect_true(length(m$n) == 3) expect_true(length(m$d) == 1) expect_true(all(names(m) == c('n', 'd'))) expect_true(all( sapply(m, is.numeric))) }) test_that('Best plane returns the best plane.', { set.seed(3) s <- cbind(rnorm(10), rnorm(10), 0) pl <- bestplane(s) expect_equal(pl$n, c(0,0,1)) expect_equal(drop(pl$n[1] + pl$n[2] - pl$d), 0.0) }) test_that('midline returns best plane', { s <- cbind(rnorm(14), rnorm(14), 0) pl <- midline(s, 1:14) pl2 <- midline(s, c(2:5, 9:12)) expect_equal(drop(pl$n[1] + pl$n[2] - pl$d), 0.0) expect_equal(drop(pl2$n[1] + pl2$n[2] - pl2$d), 0.0) }) test_that('bestplane and midline return same values when no missing data.', { s <- cbind(rnorm(14), rnorm(14), 0) p1 <- bestplane(s) l1 <- 1:14 p2 <- midline(s, l1) expect_equal(p1, p2) set.seed(99) s <- cbind(rnorm(14), rnorm(14), 0) p1 <- bestplane(s) l1 <- 1:14 p2 <- midline(s, l1) expect_equal(p1, p2) }) test_that('Mirrorfill1 replaces points correctly.', { s <- cbind(rnorm(14), rnorm(14), 0) s <- rbind(s, c(1, 2, 1), c(NA, NA, NA)) mirrorS <- mirrorfill1(s, l1 = 1:14, l2 = c(15, 16)) expect_equal(mirrorS[16, ], c(1, 2, -1)) }) test_that('Mirrorfill1 replaces points correctly with l1 as 2 col matrix.', { s <- cbind(rnorm(14), rnorm(14), 0) s <- rbind(s, c(1, 2, 1), c(NA, NA, NA), c(3, 4, -2), c(NA, NA, NA)) mirrorS <- mirrorfill1(s, l1 = 1:14, l2 = matrix(15:18, byrow = TRUE, ncol = 2)) expect_equal(mirrorS[16, ], c(1, 2, -1)) expect_equal(mirrorS[18, ], c(3, 4, 2)) }) test_that('Reflect works', { n <- c(0, 0, 1) d <- 0 p <- c(1, 1, 1) p2 <- reflect(p, n, d) expect_equal(p2, c(1, 1, -1)) }) test_that('mirrorfill returns errors when it should.', { expect_error(mirrorfill(s, l1 = c(2:7, 9:14), l2 = c(99, 100))) }) test_that('mirrorfill works correctly.', { a <- array(rep(1:36, 4), dim = c(12, 3, 4)) a[, 3, ] <- 0 a[1:4, 3, ] <- c(1, -1, 2, -2) a[c(1, 3), 1:2, ] <- a[c(2, 4), 1:2, ] missinga <- a missinga[c(1, 3), , 1] <- NA mirrorA <- mirrorfill(missinga, l1 = 5:12, l2 = 1:4) expect_equal(mirrorA, a) l2.m <- matrix(1:4, byrow = TRUE, ncol = 2) mirrorA2 <- mirrorfill(missinga, l1 = 5:12, l2 = l2.m) expect_equal(mirrorA2, a) }) test_that('mirrorfill works correctly when multiple specimens have missing data.', { a <- array(rep(1:36, 4), dim = c(12, 3, 4)) a[, 3, ] <- 0 a[1:4, 3, ] <- c(1, -1, 2, -2) a[c(1, 3), 1:2, ] <- a[c(2, 4), 1:2, ] missinga <- a missinga[c(1, 3), , 1:3] <- NA mirrorA <- mirrorfill(missinga, l1 = 5:12, l2 = 1:4) expect_equal(mirrorA, a) l2.m <- matrix(1:4, byrow = TRUE, ncol = 2) mirrorA2 <- mirrorfill(missinga, l1 = 5:12, l2 = l2.m) expect_equal(mirrorA2, a) }) test_that('mirror fill handles all missing vs not missing cases correctly.', { a <- array(rep(1:36, 4), dim = c(12, 3, 4)) a[, 3, ] <- 0 a[1:8, 3, ] <- c(1, -1, 2, -2) a[c(1, 3, 5, 7), 1:2, ] <- a[c(2, 4, 6, 8), 1:2, ] a[7, 1, 4] <- 9999 missinga <- a missinga[c(1, 2), , 1] <- NA missinga[3, , 2] <- NA missinga[6, , 3] <- NA mirrorA <- mirrorfill(missinga, l1 = 9:12, l2 = 1:8) expect_true(all(is.na(mirrorA[c(1, 2), , 1]))) expect_equal(mirrorA[, , 2], a[, , 2]) expect_equal(mirrorA[, , 3], a[, , 3]) expect_equal(mirrorA[7, 1, 4], 9999) expect_false(mirrorA[7, 1, 4] == mirrorA[4, 1, 3]) expect_true(mirrorA[4, 1, 3] == mirrorA[4, 1, 2]) expect_true(mirrorA[4, 1, 3] == mirrorA[4, 1, 1]) })
rep.int <- function(x, times) .Internal(rep.int(x, times)) rep_len <- function(x, length.out) .Internal(rep_len(x, length.out)) rep.factor <- function(x, ...) { y <- NextMethod() structure(y, class=class(x), levels=levels(x)) }
depth_distribution <- function(distribution, head_mat = NULL, tail_mat = NULL){ if(is.null(head_mat)&is.null(tail_mat)){ stop("You need to specify a head_mat or tail_mat argument") }else if((!is.null(head_mat))&(is.null(tail_mat))){ out <- depth_distribution_head(distribution, head_mat) }else if((is.null(head_mat))&(!is.null(tail_mat))){ out <- depth_distribution_tail(distribution, tail_mat) }else if((!is.null(head_mat))&(!is.null(tail_mat))){ out <- depth_distribution_unique(distribution, head = head_mat, tail = tail_mat) } return(out) }
context("test-dataalignment") test_that("multiplication works", { expect_equal(2 * 2, 4) })
mgPLS = function(DataX, DataY, Group, ncomp=NULL, Scale=FALSE, Gcenter=FALSE, Gscale=FALSE){ check(DataX, Group) check(DataY, Group) if ((nrow(DataX) != nrow(DataY))) stop("Oops unequal number of rows in 'DataX' and 'DataY'.") if (is.data.frame(DataX) == TRUE) { DataX = as.matrix(DataX) } if (is.data.frame(DataY) == TRUE) { DataY = as.matrix(DataY) } if(is.null(ncomp)) {ncomp = 2} if(is.null(colnames(DataX))) { colnames(DataX) = paste('VX', 1:ncol(DataX), sep='') } if(is.null(colnames(DataY))) { colnames(DataY) = paste('VY', 1:ncol(DataY), sep='') } DataX = as.data.frame(DataX, row.names = NULL) DataY = as.data.frame(DataY, row.names = NULL) Group = as.factor(Group) DataX = as.matrix(DataX) rownames(DataX) = Group DataY = as.matrix(DataY) rownames(DataY) = Group M = length(levels(Group)) P = dim(DataX)[2] Q = dim(DataY)[2] n = as.vector(table(Group)) N = sum(n) H = ncomp DataX = scale(DataX, center = Gcenter, scale = Gscale) DataY = scale(DataY, center = Gcenter, scale = Gscale) DataXm = split(DataX, Group) DataYm = split(DataY, Group) Concat.X = Concat.Y = NULL for(m in 1:M){ DataXm[[m]] = matrix(DataXm[[m]], nrow=n[m]) DataXm[[m]] = scale(DataXm[[m]], center=TRUE, scale=Scale) DataYm[[m]] = matrix(DataYm[[m]], nrow=n[m]) DataYm[[m]] = scale(DataYm[[m]], center=TRUE, scale=Scale) Concat.X = rbind(Concat.X, DataXm[[m]]) Concat.Y = rbind(Concat.Y, DataYm[[m]]) } colnames(Concat.X) = colnames(DataX) colnames(Concat.Y) = colnames(DataY) rownames(Concat.X) = rownames(DataX) rownames(Concat.Y) = rownames(DataY) res = list() res$DataXm = DataXm res$DataYm = DataYm res$Concat.X = Concat.X res$Concat.Y = Concat.Y aCommonX = matrix(0, ncol=H, nrow=P) TGlobalX = matrix(0, ncol=H, nrow=N) UGlobalY = matrix(0, ncol=H, nrow=N) bCommonY = matrix(0, ncol=H, nrow=Q) aGroupX = vector("list",M) bGroupY = vector("list",M) TGroupX = vector("list",M) UGroupY = vector("list",M) for(m in 1:M){ aGroupX[[m]] = matrix(0,nrow=P, ncol=H) bGroupY[[m]] = matrix(0,nrow=Q, ncol=H) rownames(aGroupX[[m]]) = colnames(DataX) colnames(aGroupX[[m]]) = paste("Dim", 1:H, sep="") rownames(bGroupY[[m]]) = colnames(DataY) colnames(bGroupY[[m]]) = paste("Dim", 1:H, sep="") TGroupX[[m]] = matrix(0,nrow=n[m],ncol=H) UGroupY[[m]] = matrix(0,nrow=n[m],ncol=H) } aCommonX_STAR = matrix(0,nrow=P,ncol=H) COV = vector("list",H) COVm = vector("list",H) ppbeta = matrix(0,nrow=P,ncol=H) betay = vector("list",H) cum.expvar.Xm = matrix(0, ncol=H, nrow=M) cum.expvar.Ym = matrix(0, ncol=H, nrow=M) nor2x = sum((Concat.X)^2) exp_var = c(0) nor2y= sum((Concat.Y)^2) exp_vary = c(0) res$noncumper.inertiglobal = matrix(0, ncol=ncomp, nrow=1) colnames(res$noncumper.inertiglobal) = paste("Dim", 1:ncomp, sep="") for(h in 1:H){ eps = 1e-6 w = stats::rnorm(P) w = w/as.numeric(sqrt(t(w)%*%w)) x=1.0; tTold=0; wTold=w; uTold=0; vTold=0; iter =0; covv = 0 covvm = 0 tt = matrix(0,nrow=N) tmm = list() umm = list() while (x>eps){ sumyx=0 for (m in 1:M){ ccc = t(DataYm[[m]]) %*% DataXm[[m]] %*% w sumyx = sumyx+ccc } v= sumyx / as.numeric(sqrt(sum((sumyx)^2))) for (m in 1:M){ um = DataYm[[m]] %*% v umm[[m]]=um } u = (Concat.Y) %*% v sumxy=0 for (m in 1:M){ ccc = t(DataXm[[m]]) %*% DataYm[[m]] %*% v aGroupX[[m]][,h]=ccc/as.numeric(sqrt(sum((ccc)^2))) sumxy = sumxy+ccc } w = sumxy / as.numeric(sqrt(sum((sumxy)^2))) for (m in 1:M){ tm = DataXm[[m]] %*% w TGroupX[[m]][,h] = tm ddd = t(DataYm[[m]]) %*% tm bGroupY[[m]][,h] = ddd/as.numeric(sqrt(sum((ddd)^2))) tmm[[m]] = tm } t = (Concat.X) %*% w tt = cbind(tt,t) iter=iter+1 if (iter > 1){ xT = crossprod(t-tTold) yw = crossprod(v-vTold) x = max(xT,yw); } covv[iter]=(cov(u, t)) tTold= t; wTold= w; uTold= u; vTold= v; sum_cov=0 for(m in 1:M){ sum_cov= sum_cov+( (n[m]-1) * cov(tmm[[m]],umm[[m]]) ) } covvm[iter] = sum_cov } aCommonX[,h] = wTold TGlobalX[,h] = t UGlobalY[,h] = u bCommonY[,h] = v COV[[h]] = covv COVm[[h]]=covvm project.global=TGlobalX[,h] %*% ginv( t(TGlobalX[,h]) %*% TGlobalX[,h]) %*% t(TGlobalX[,h]) project.data.global=project.global %*% res$Concat.X res$noncumper.inertiglobal[h] = round(100*sum(diag(t(project.data.global) %*% project.data.global))/ sum(diag(t(res$Concat.X) %*% res$Concat.X)),1) ppbeta[,h] = t(res$Concat.X)%*% TGlobalX[,h]/(c(( t(TGlobalX[,h])%*% TGlobalX[,h]))) if(h==1){aCommonX_STAR[, h]=aCommonX[,h]} if(h>=2){ Mat <- diag(P) for (k in 2 : h) { mat <- t(TGlobalX[, k-1]) %*% res$Concat.X/ as.numeric(t(TGlobalX[, k-1])%*%TGlobalX[, k-1]) Mat <- Mat %*% (diag(P) - aCommonX[, k-1] %*% mat) } aCommonX_STAR[, h] <- Mat %*% aCommonX[, h] } dd = coefficients(lm(res$Concat.Y ~TGlobalX[,1:h])) if(Q==1){betay[[h]]=(dd[-1])} if(Q>=2){betay[[h]]=(dd[-1,])} res$coefficients[[h]] = as.matrix(aCommonX_STAR[,1:h]) %*% (betay[[h]]) colnames(res$coefficients[[h]]) = colnames(Concat.Y) rownames(res$coefficients[[h]]) = colnames(Concat.X) wp = crossprod(Concat.X, t) / drop(crossprod(t)) wy = crossprod(Concat.Y, t) / drop(crossprod(t)) Concat.X = Concat.X - t%*% t(wp) Concat.Y = Concat.Y - t %*% t(wy) exp_var_new= 100* as.numeric(t(t) %*% res$Concat.X %*% t(res$Concat.X) %*% t/ as.vector((t(t)%*%t)) )/nor2x exp_var=append(exp_var, exp_var_new) exp_var_newy= 100* as.numeric(t(t) %*% res$Concat.Y %*% t(res$Concat.Y) %*% t/ as.vector((t(t)%*%t)) )/nor2y exp_vary=append(exp_vary, exp_var_newy) DataXm = split(Concat.X, Group) DataYm = split(Concat.Y, Group) for(m in 1:M){ DataXm[[m]] = matrix(DataXm[[m]], ncol=P) colnames(DataXm[[m]]) = colnames(Concat.X) DataYm[[m]] = matrix(DataYm[[m]], ncol=Q) colnames(DataYm[[m]]) = colnames(Concat.Y) } } expvarX = exp_var[-1] cumexpvarX = cumsum(expvarX) EVX = matrix(c(expvarX, cumexpvarX), ncol=2) rownames(EVX) = paste("Dim", 1:H, sep="") colnames(EVX) = c("Explained.Var", "Cumulative") expvarY = exp_vary[-1] cumexpvarY = cumsum(expvarY) EVY = matrix(c(expvarY, cumexpvarY), ncol=2) rownames(EVY) = paste("Dim", 1:H, sep="") colnames(EVY) = c("Explained.Var", "Cumulative") for(m in 1:M){ for(h in 1:H){ proj= TGroupX[[m]][,1:h] %*% ginv(t(TGroupX[[m]][,1:h]) %*% TGroupX[[m]][,1:h]) %*% t(TGroupX[[m]][,1:h]) xm_hat= proj %*% DataXm[[m]] explain_varx=sum(diag( xm_hat %*% t(xm_hat) ))/sum(diag( DataXm[[m]] %*% t(DataXm[[m]]) )) ym_hat= proj %*% DataYm[[m]] explain_vary = sum(diag( ym_hat %*% t(ym_hat) ))/sum(diag( DataYm[[m]] %*% t(DataYm[[m]]) )) cum.expvar.Xm[m,h] = explain_varx cum.expvar.Ym[m,h] = explain_vary } } res$coefficients.Y <- t(coefficients(lm(Concat.Y ~ TGlobalX - 1))) rownames(res$coefficients.Y) = colnames(res$Concat.Y) colnames(res$coefficients.Y) = paste("Dim", 1:H, sep="") loadings_matricesW = list() loadings_matricesW[[1]] = aCommonX for(m in 2:(M+1)){ loadings_matricesW[[m]] = aGroupX[[(m-1)]] } loadings_matricesV = list() loadings_matricesV[[1]] = bCommonY for(m in 2:(M+1)){ loadings_matricesV[[m]] = bGroupY[[(m-1)]] } NAMES = c("Commonload", levels(Group)) similarityA =similarity_function(loadings_matrices=loadings_matricesW, NAMES) similarityB =similarity_function(loadings_matrices=loadings_matricesV, NAMES) similarityA_noncum = similarity_noncum(loadings_matrices=loadings_matricesW, NAMES) similarityB_noncum = similarity_noncum(loadings_matrices=loadings_matricesV, NAMES) rownames(aCommonX) = colnames(res$Concat.X) rownames(bCommonY) = colnames(res$Concat.Y) rownames(TGlobalX) = rownames(res$Concat.X) rownames(UGlobalY) = rownames(res$Concat.Y) colnames(aCommonX) = paste("Dim", 1:H, sep="") colnames(bCommonY) = paste("Dim", 1:H, sep="") colnames(TGlobalX) = paste("Dim", 1:H, sep="") colnames(UGlobalY) = paste("Dim", 1:H, sep="") for(m in 1: M){ colnames(TGroupX[[m]]) = paste("Dim", 1:H, sep="") } res$Components.Global = list(X = TGlobalX, Y = UGlobalY) res$Components.Group = list(X = TGroupX) res$loadings.common = list(X = aCommonX, Y = bCommonY) res$loadings.Group = list(X = aGroupX, Y = bGroupY) colnames(cum.expvar.Xm) = paste("Dim", 1:H, sep="") colnames(cum.expvar.Ym) = paste("Dim", 1:H, sep="") rownames(cum.expvar.Xm) = levels(Group) rownames(cum.expvar.Ym) = levels(Group) res$expvar = list(X = EVX, Y = EVY) res$cum.expvar.Group = list(X = cum.expvar.Xm, Y = cum.expvar.Ym) res$Similarity.Common.Group.load = list(X = similarityA, Y = similarityB) res$Similarity.noncum.Common.Group.load = list(X = similarityA_noncum , Y = similarityB_noncum) class(res) = c("mgPLS", "mg") return(res) } print.mgPLS <- function(x, ...) { cat("\nMultigroup Partial Least Squares Regression\n") cat(rep("-",43), sep="") cat("\n$loadings.common ", "Common loadings") cat("\n") invisible(x) }
race <- hijack(r_sample_factor, name = "Race", x = c("White", "Hispanic", "Black", "Asian", "Bi-Racial", "Native", "Other", "Hawaiian"), prob = c(0.637, 0.163, 0.122, 0.047, 0.019, 0.007, 0.002, 0.0015) )
context("Select Threshold") data2 <- get(load("../data/example2.RData")) test_that("SelectThreshold works", { expect_setequal(selectThreshold(0.1)(data2, 'clase', IEPConsistency())$featuresSelected, c('x1', 'x2', 'x4', 'x5', 'x3', 'x6')) expect_setequal(selectThreshold(0.6)(data2, 'clase', IEPConsistency())$featuresSelected, c('x2', 'x4', 'x5', 'x3', 'x6')) expect_setequal(selectThreshold(0.9)(data2, 'clase', IEPConsistency())$featuresSelected, c('x6')) }) test_that("Name is set", { expect_equal(attr(selectThreshold(),'name'),"Select Threshold"); expect_equal(attr(selectThreshold(),'shortName'),"selectThreshold"); })
min0 <- function(x, na.rm=TRUE){ sd1 <- stats0( x=x, FUN=min, na.rm=na.rm ) return(sd1) }
ciROCemp <- function(rocit_emp, level){ if(!(methods::is(rocit_emp, "rocit"))){ stop("Argument is not of class \"rocit\" ") } argMethod <- rocit_emp$method if(argMethod != "empirical"){ stop("Rocit object method is not \"empirical\" ") } pos_count <- rocit_emp$pos_count neg_count <- rocit_emp$neg_count pos_D <- rocit_emp$pos_D neg_D <- rocit_emp$neg_D TPR <- rocit_emp$TPR FPR <- rocit_emp$FPR c <- rocit_emp$Cutoff max_nD <- max(neg_D) min_nD <- min(neg_D) ppdf_temp <- approxfun(density(pos_D)) npdf_temp <- approxfun(density(neg_D)) ppdf <- function(x){ ifelse(is.na(ppdf_temp(x)), 0, ppdf_temp(x)) } npdf <- function(x){ ifelse(is.na(npdf_temp(x)), 0, npdf_temp(x)) } ncdf_2 <- function(y){ retval <- rep(NA, length(y)) for(i in 1:length(y)){ x <- y[i] if(x>max(neg_D)){retval[i] <- 1}else{ if(x<min(neg_D)){retval[i] <- 0}else{ bw <- (x-min(neg_D))/1000 myX <- seq(min(neg_D), x, bw) myY <- npdf(myX) retval[i] <- sum(diff(myX)*(myY[-1]+myY[-length(myY)]))/2 } } } return(retval) } nSurv <- function(x) {1-ncdf_2(x)} binwidht <- (max_nD-min_nD)/10000 DummyX <- seq(min_nD-0.001,max_nD+0.001,binwidht) DummyY <- nSurv(DummyX) c_starfun=approxfun(DummyY,DummyX) c_starfun2 <- function(x){ ifelse(x==0, max_nD, ifelse(x==1,min_nD,c_starfun(x))) } c_star <- c_starfun2(FPR) var_term2 <- (npdf(c_star)/ppdf(c_star))^2 * FPR * (1-FPR)/neg_count var_term1 <- TPR * (1-TPR)/pos_count SE_TPR <- sqrt(var_term1 + var_term2) multiplier <- qnorm((1+level)/2) upper <- TPR + multiplier * SE_TPR lower <- TPR - multiplier * SE_TPR upFun <- function(x) {min(c(1,x))} lowFun <- function(x) {max(c(0,x))} upper <- sapply(upper, upFun) lower <- sapply(lower, lowFun) TPR0 <- which(TPR == 0) TPR1 <- which(TPR == 1) lower[TPR1] <- 1 upper[TPR0] <- 0 returnval <- list(`ROC estimation method` = rocit_emp$method, `Confidence level` = paste0(100*level,"%"), FPR = FPR, TPR = TPR, LowerTPR = lower, UpperTPR = upper) return(returnval) }
fn2fix <- function(i,posx, PA=FALSE, NumProcess=2, type='Poisson', dist='normal', lambdaMarg=NULL, lambdaParent=NULL, lambdaNumP=NULL, sigmaC=1, minC=-1, maxC=1,fixed.seed=1) { fixed.seed<-fixed.seed+i aux<-DistSimfix(posx=posx, NumProcess=NumProcess, type=type, dist=dist, lambdaMarg=lambdaMarg, lambdaParent=lambdaParent, lambdaNumP=lambdaNumP, sigmaC=sigmaC, minC=minC, maxC=maxC, PA=PA, info=FALSE,fixed.seed=fixed.seed) return(aux) }
context("test partial eval") test_that("namespace operators always evaluated locally", { expect_equal(partial_eval(quote(base::sum(1, 2))), 3) expect_equal(partial_eval(quote(base:::sum(1, 2))), 3) }) test_that("namespaced calls to dplyr functions are stripped", { expect_equal(partial_eval(quote(dplyr::n())), expr(n())) }) test_that("use quosure environment for unevaluted formulas", { x <- 1 expect_equal(partial_eval(expr(~x)), ~1) }) test_that("respects tidy evaluation pronouns", { x <- "X" X <- "XX" expect_equal(partial_eval(expr(.data$x)), expr(x)) expect_equal(partial_eval(expr(.data[["x"]])), expr(x)) expect_equal(partial_eval(expr(.data[[x]])), expr(X)) expect_equal(partial_eval(expr(.env$x)), "X") expect_equal(partial_eval(expr(.env[["x"]])), "X") expect_equal(partial_eval(expr(.env[[x]])), "XX") })
ZIPF <- function (mu.link = "log") { mstats <- checklink("mu.link", "ZIPF", substitute(mu.link),c("inverse", "log", "sqrt", "identity")) structure( list( family = c("ZIPF", "zipf distribution"), parameters = list(mu = TRUE), nopar = 1, type = "Discrete", mu.link = as.character(substitute(mu.link)), mu.linkfun = mstats$linkfun, mu.linkinv = mstats$linkinv, mu.dr = mstats$mu.eta, dldm = function(y,mu) { nd <- numeric.deriv(dZIPF(y, mu, log=TRUE), "mu", delta=0.001) dldm <- as.vector(attr(nd, "gradient")) dldm }, d2ldm2 = function(y,mu) { nd <- numeric.deriv(dZIPF(y, mu, log=TRUE), "mu", delta=0.001) dldm <- as.vector(attr(nd, "gradient")) d2ldv2 <- -dldm*dldm d2ldv2 }, G.dev.incr = function(y,mu,...) -2*dZIPF(x = y, mu = mu, log = TRUE), rqres = expression(rqres(pfun="pZIPF", type="Discrete", ymin=1, y=y, mu=mu)), mu.initial =expression({mu <- rep(.1,length(y)) } ), mu.valid = function(mu) all(mu > 0), y.valid = function(y) all(y >= 1), mean = function(mu) ifelse(mu > 1, zetaP(mu) / zetaP(mu +1), Inf), variance = function(mu) ifelse(mu > 2, (zetaP(mu + 1) * zetaP(mu - 1) - (zetaP(mu))^2) / (zetaP(mu + 1))^2, Inf) ), class = c("gamlss.family","family")) } dZIPF<- function(x, mu = 1, log = FALSE) { if (any(mu <= 0) ) stop(paste("mu must be greater than 0 ", "\n", "")) if (any(x < 1) ) stop(paste("x must be >=1", "\n", "")) ly <- max(length(x),length(mu)) x <- rep(x, length = ly) mu <- rep(mu, length = ly) logL <- -(mu+1)*log(x)-log(zetaP(mu+1)) lik <- if (log) logL else exp(logL) as.numeric(lik) } pZIPF <- function(q, mu = 1, lower.tail = TRUE, log.p = FALSE) { Zeta.aux<- function (shape, qq) { LLL <- max(length(shape), length(qq)) if (length(shape) != LLL) shape <- rep_len(shape, LLL) if (length(qq) != LLL) qq <- rep_len(qq, LLL) if (any(qq < 12 - 1)) warning("all values of argument 'q' should be 12 or more") aa <- qq B2 <- c(1/6, -1/30, 1/42, -1/30, 5/66, -691/2730, 7/6, -3617/510) kk <- length(B2) ans <- 1/((shape - 1) * (1 + aa)^(shape - 1)) + 0.5/(1 + aa)^shape term <- (shape/2)/(1 + aa)^(shape + 1) ans <- ans + term * B2[1] for (mm in 2:kk) { term <- term * (shape + 2 * mm - 3) * (shape + 2 * mm - 2)/((2 * mm - 1) * 2 * mm * (1 + aa)^2) ans <- ans + term * B2[mm] } ifelse(aa - 1 <= qq, ans, rep(0, length(ans))) } if (any(mu <= 0) ) stop(paste("mu must be greater than 0 ", "\n", "")) if (any(q < 1) ) stop(paste("y must be >=0", "\n", "")) ly <- max(length(q),length(mu)) q <- rep(q, length = ly) mu <- rep(mu, length = ly) ans <- rep_len(0, ly) qfloor <- floor(q) for (nn in 1:(12 - 1)) ans <- ans + as.numeric(nn <= qfloor)/nn^(mu + 1) vecTF <- (12 - 1 <= qfloor) if (lower.tail) { if (any(vecTF)) ans[vecTF] <- zetaP(mu[vecTF] + 1) - Zeta.aux(mu[vecTF] + 1, qfloor[vecTF] + 1) } else { ans <- zetaP(mu + 1) - ans if (any(vecTF)) ans[vecTF] <- Zeta.aux(mu[vecTF] + 1, qfloor[vecTF] + 1) } cdf <- ans/zetaP(mu + 1) cdf } qZIPF <- function(p, mu = 1, lower.tail = TRUE, log.p = FALSE, max.value = 10000) { if (any(mu <= 0) ) stop(paste("mu must be greater than 0 ", "\n", "")) if (any(p < 0) | any(p > 1.0001)) stop(paste("p must be between 0 and 1", "\n", "")) if (log.p==TRUE) p <- exp(p) else p <- p if (lower.tail==TRUE) p <- p else p <- 1-p ly <- length(p) QQQ <- rep(0,ly) nmu <- rep(mu, length = ly) for (i in seq(along=p)) { cumpro <- 0 if (p[i]+0.000000001 >= 1) QQQ[i] <- Inf else { for (j in seq(from = 1, to = max.value)) { cumpro <- pZIPF(j, mu = nmu[i], log.p = FALSE) QQQ[i] <- j if (p[i] <= cumpro ) break } } } QQQ } rZIPF <- function(n, mu = 1, max.value = 10000) { if (any(mu <= 0) ) stop(paste("mu must be greater than 0 ", "\n", "")) if (any(n <= 0)) stop(paste("n must be a positive integer", "\n", "")) n <- ceiling(n) p <- runif(n) r <- qZIPF(p, mu = mu, max.value = max.value) as.integer(r) } zetaP <-function (x) { Zeta.aux<- function (shape, qq) { LLL <- max(length(shape), length(qq)) if (length(shape) != LLL) shape <- rep_len(shape, LLL) if (length(qq) != LLL) qq <- rep_len(qq, LLL) if (any(qq < 12 - 1)) warning("all values of argument 'q' should be 12 or more") aa <- qq B2 <- c(1/6, -1/30, 1/42, -1/30, 5/66, -691/2730, 7/6, -3617/510) kk <- length(B2) ans <- 1/((shape - 1) * (1 + aa)^(shape - 1)) + 0.5/(1 + aa)^shape term <- (shape/2)/(1 + aa)^(shape + 1) ans <- ans + term * B2[1] for (mm in 2:kk) { term <- term * (shape + 2 * mm - 3) * (shape + 2 * mm - 2)/((2 * mm - 1) * 2 * mm * (1 + aa)^2) ans <- ans + term * B2[mm] } ifelse(aa - 1 <= qq, ans, rep(0, length(ans))) } aa <- 12 ans <- 0 for (ii in 0:(aa - 1)) ans <- ans + 1/(1 + ii)^x ans <- ans + Zeta.aux(shape = x, aa) ans }
setClass("yuima.law",representation(rng = "function", density = "function", cdf = "function", quantile = "function", characteristic = "function", param.measure = "character", time.var = "character", dim = "numLike") ) setMethod("initialize", "yuima.law", function(.Object, rng = function(n,...){}, density = function(x,...){}, cdf = function(q,...){}, quantile = function(p,...){}, characteristic = function(u,...){}, param.measure = character(), time.var = character(), dim = NA ){ .Object@rng <- rng .Object@density <- density .Object@cdf <- cdf .Object@quantile <- quantile .Object@characteristic <- characteristic [email protected] <- param.measure [email protected] <- time.var .Object@dim <- dim return(.Object) } ) setMethod("rand","yuima.law", function(object, n, param, ...){ res <- aux.rand(object, n, param, ...) return(res) } ) setMethod("dens","yuima.law", function(object, x, param, log = FALSE, ...){ res <- aux.dens(object, x, param, log, ...) return(res) } ) setMethod("cdf","yuima.law", function(object, q, param, ...){ res <- aux.cdf(object, q, param, log, ...) return(res) } ) setMethod("quant","yuima.law", function(object, p, param, ...){ res <- aux.quant(object, p, param, ...) return(res) } ) setMethod("char","yuima.law", function(object, u, param, ...){ res <- aux.char(object, u, param, ...) return(res) } ) setLaw <- function(rng = function(n,...){NULL}, density = function(x,...){NULL}, cdf = function(q,...){NULL}, quant = function(p,...){NULL}, characteristic = function(u,...){NULL}, time.var="t", dim = NA){ param <- NULL param.rng <- extrapParam(myfun = rng, time.var = time.var, aux.var = "n" ) CondRng<- FALSE if(all(param.rng %in% "...")){ }else{ CondRng <- TRUE param <- param.rng } param.dens <- extrapParam(myfun = density, time.var = time.var, aux.var = "x" ) CondDens<- FALSE if(all(param.dens %in% "...")){ }else{ CondDens <- TRUE param <- param.dens } if(CondDens){ if(CondRng){ if(!all(param.dens %in% param.rng)){ yuima.stop("dens and rng have different parameters") } } } param.cdf <- extrapParam(myfun = cdf, time.var = time.var, aux.var = "q" ) if(all(param.cdf %in% "...")){ }else{ if(is.null(param)){ param <- param.cdf }else{ if(!all(param %in% param.cdf)){ yuima.stop("cdf has different parameters") } } } param.quant <- extrapParam(myfun = quant, time.var = time.var, aux.var = "p" ) if(all(param.quant %in% "...")){ }else{ if(is.null(param)){ param <- param.quant }else{ if(!all(param %in% param.quant)){ yuima.stop("quantile has different parameters") } } } param.char <- extrapParam(myfun = characteristic, time.var = time.var, aux.var = "u" ) if(all(param.char %in% "...")){ }else{ if(is.null(param)){ param <- param.char }else{ if(!all(param %in% param.char)){ yuima.stop("quantile has different parameters") } } } if(is.null(param)){ param<-character() } res <- new("yuima.law", rng = rng, density = density, cdf = cdf, characteristic = characteristic, quantile = quant, param.measure = param, time.var = time.var, dim = NA) return(res) } extrapParam <- function(myfun, time.var, aux.var){ dummy <- names(as.list(args(myfun))) dummy <- dummy[-length(dummy)] if(dummy[1] != aux.var){ yuima.stop("Change rand.var or charac.var ...") } cond <- dummy %in% time.var dummy.par <- dummy[!cond] dummy <- dummy.par[!dummy.par%in%aux.var] return(dummy) }
test_that('trialr_crm_selector matches dfcrm_selector.', { skeleton <- c(0.1, 0.2, 0.4, 0.55) target <- 0.2 scale = sqrt(0.75) outcomes <- '2NNT 2NNN 3NTT 2NNT' model1 <- get_dfcrm(skeleton = skeleton, target = target, scale = scale) fit1 <- model1 %>% fit(outcomes) model2 <- get_trialr_crm(skeleton = skeleton, target = target, model = 'empiric', beta_sd = scale) fit2 <- model2 %>% fit(outcomes) expect_equal(model2$model, 'empiric') expect_equal(model2$extra_args$beta_sd, sqrt(0.75)) expect_equal(recommended_dose(fit1), recommended_dose(fit2)) epsilon <- 0.02 expect_true(all(abs(mean_prob_tox(fit1) - mean_prob_tox(fit2)) < epsilon)) skeleton <- c(0.1, 0.2, 0.33, 0.45, 0.6, 0.7, 0.8) target <- 0.33 outcomes <- '1NNN 2NNN 3NTT 2NNN 3TNN 3TNT 2NNN' model1 <- get_dfcrm(skeleton = skeleton, target = target, intcpt = 4, model = 'logistic') fit1 <- model1 %>% fit(outcomes) model2 <- get_trialr_crm(skeleton = skeleton, target = target, model = 'logistic', a0 = 4, beta_mean = 0, beta_sd = sqrt(1.34)) fit2 <- model2 %>% fit(outcomes) expect_equal(model2$model, 'logistic') expect_equal(model2$extra_args$a0, 4) expect_equal(model2$extra_args$beta_mean, 0) expect_equal(model2$extra_args$beta_sd, sqrt(1.34)) expect_equal(recommended_dose(fit1), recommended_dose(fit2)) epsilon <- 0.02 expect_true(all(abs(mean_prob_tox(fit1) - mean_prob_tox(fit2)) < epsilon)) }) test_that('trialr_crm_selector matches bcrm.', { dose <- c(1, 2.5, 5, 10, 15, 20, 25, 30, 40, 50, 75, 100, 150, 200, 250) skeleton <- c(0.010, 0.015, 0.020, 0.025, 0.030, 0.040, 0.050, 0.100, 0.170, 0.300, 0.400, 0.500, 0.650, 0.800, 0.900) target <- 0.30 df <- data.frame( patient=1:18, dose = rep(c(1:4, 7), c(3, 4, 5, 4, 2)), tox = rep(0:1, c(16, 2))) bcrm_dose <- 9 bcrm_prob_tox <- c(0.07015495, 0.08657340, 0.10073468, 0.11345014, 0.12513580, 0.14632099, 0.16543985, 0.24440829, 0.33268033, 0.46747152, 0.55775747, 0.64098831, 0.75674204, 0.86470521, 0.93341409) outcomes <- '1NNN 2NNNN 3NNNN 4NNNN 7TT' fit2 <- get_trialr_crm(skeleton = skeleton, target = target, model = 'empiric', beta_sd = 1.34, seed = 2020) %>% fit(outcomes = outcomes) expect_equal(bcrm_dose, recommended_dose(fit2)) epsilon <- 0.02 expect_true(all(abs(bcrm_prob_tox - mean_prob_tox(fit2)) < epsilon)) }) test_that('empiric trialr_crm_selector supports correct interface.', { skeleton <- c(0.05, 0.1, 0.25, 0.4, 0.6) target <- 0.25 model = 'empiric' model_fitter <- get_trialr_crm(skeleton = skeleton, target = target, model = model, beta_sd = 1) x <- fit(model_fitter, '1NNN 2NTT') expect_equal(tox_target(x), 0.25) expect_true(is.numeric(tox_target(x))) expect_equal(num_patients(x), 6) expect_true(is.integer(num_patients(x))) expect_equal(cohort(x), c(1,1,1, 2,2,2)) expect_true(is.integer(cohort(x))) expect_equal(length(cohort(x)), num_patients(x)) expect_equal(doses_given(x), unname(c(1,1,1, 2,2,2))) expect_true(is.integer(doses_given(x))) expect_equal(length(doses_given(x)), num_patients(x)) expect_equal(tox(x), c(0,0,0, 0,1,1)) expect_true(is.integer(tox(x))) expect_equal(length(tox(x)), num_patients(x)) expect_equal(num_tox(x), 2) expect_true(is.integer(num_tox(x))) expect_true(all((model_frame(x) - data.frame(patient = c(1,2,3,4,5,6), cohort = c(1,1,1,2,2,2), dose = c(1,1,1,2,2,2), tox = c(0,0,0,0,1,1))) == 0)) expect_equal(nrow(model_frame(x)), num_patients(x)) expect_equal(num_doses(x), 5) expect_true(is.integer(tox(x))) expect_equal(dose_indices(x), 1:5) expect_true(is.integer(dose_indices(x))) expect_equal(length(dose_indices(x)), num_doses(x)) expect_equal(recommended_dose(x), 1) expect_true(is.integer(recommended_dose(x))) expect_equal(length(recommended_dose(x)), 1) expect_equal(continue(x), TRUE) expect_true(is.logical(continue(x))) expect_equal(n_at_dose(x), c(3,3,0,0,0)) expect_true(is.integer(n_at_dose(x))) expect_equal(length(n_at_dose(x)), num_doses(x)) expect_equal(n_at_dose(x, dose = 0), 0) expect_true(is.integer(n_at_dose(x, dose = 0))) expect_equal(length(n_at_dose(x, dose = 0)), 1) expect_equal(n_at_dose(x, dose = 1), 3) expect_true(is.integer(n_at_dose(x, dose = 1))) expect_equal(length(n_at_dose(x, dose = 1)), 1) expect_equal(n_at_dose(x, dose = 'recommended'), 3) expect_true(is.integer(n_at_dose(x, dose = 'recommended'))) expect_equal(length(n_at_dose(x, dose = 'recommended')), 1) expect_equal(n_at_recommended_dose(x), 3) expect_true(is.integer(n_at_recommended_dose(x))) expect_equal(length(n_at_recommended_dose(x)), 1) expect_equal(is_randomising(x), FALSE) expect_true(is.logical(is_randomising(x))) expect_equal(length(is_randomising(x)), 1) expect_equal(unname(prob_administer(x)), c(0.5,0.5,0,0,0)) expect_true(is.numeric(prob_administer(x))) expect_equal(length(prob_administer(x)), num_doses(x)) expect_equal(tox_at_dose(x), c(0,2,0,0,0)) expect_true(is.integer(tox_at_dose(x))) expect_equal(length(tox_at_dose(x)), num_doses(x)) expect_true(is.numeric(empiric_tox_rate(x))) expect_equal(length(empiric_tox_rate(x)), num_doses(x)) expect_true(is.numeric(mean_prob_tox(x))) expect_equal(length(mean_prob_tox(x)), num_doses(x)) expect_true(is.numeric(median_prob_tox(x))) expect_equal(length(median_prob_tox(x)), num_doses(x)) expect_true(is.logical(dose_admissible(x))) expect_equal(length(dose_admissible(x)), num_doses(x)) expect_true(is.numeric(prob_tox_quantile(x, p = 0.9))) expect_equal(length(prob_tox_quantile(x, p = 0.9)), num_doses(x)) expect_true(is.numeric(prob_tox_exceeds(x, 0.5))) expect_equal(length(prob_tox_exceeds(x, 0.5)), num_doses(x)) expect_true(is.logical(supports_sampling(x))) expect_true(is.data.frame(prob_tox_samples(x))) expect_true(is.data.frame(prob_tox_samples(x, tall = TRUE))) expect_error(summary(x), NA) expect_output(print(x)) expect_true(tibble::is_tibble(as_tibble(x))) expect_true(nrow(as_tibble(x)) >= num_doses(x)) x <- fit(model_fitter, '') expect_equal(tox_target(x), 0.25) expect_true(is.numeric(tox_target(x))) expect_equal(num_patients(x), 0) expect_true(is.integer(num_patients(x))) expect_equal(cohort(x), integer(0)) expect_true(is.integer(cohort(x))) expect_equal(length(cohort(x)), num_patients(x)) expect_equal(doses_given(x), integer(0)) expect_true(is.integer(doses_given(x))) expect_equal(length(doses_given(x)), num_patients(x)) expect_equal(tox(x), integer(0)) expect_true(is.integer(tox(x))) expect_equal(length(tox(x)), num_patients(x)) expect_equal(num_tox(x), 0) expect_true(is.integer(num_tox(x))) mf <- model_frame(x) expect_equal(nrow(mf), 0) expect_equal(ncol(mf), 4) expect_equal(num_doses(x), 5) expect_true(is.integer(num_doses(x))) expect_equal(dose_indices(x), 1:5) expect_true(is.integer(dose_indices(x))) expect_equal(length(dose_indices(x)), num_doses(x)) expect_equal(recommended_dose(x), 1) expect_true(is.integer(recommended_dose(x))) expect_equal(length(recommended_dose(x)), 1) expect_equal(continue(x), TRUE) expect_true(is.logical(continue(x))) expect_equal(n_at_dose(x), c(0,0,0,0,0)) expect_true(is.integer(n_at_dose(x))) expect_equal(length(n_at_dose(x)), num_doses(x)) expect_equal(n_at_dose(x, dose = 0), 0) expect_true(is.integer(n_at_dose(x, dose = 0))) expect_equal(length(n_at_dose(x, dose = 0)), 1) expect_equal(n_at_dose(x, dose = 1), 0) expect_true(is.integer(n_at_dose(x, dose = 1))) expect_equal(length(n_at_dose(x, dose = 1)), 1) expect_equal(n_at_dose(x, dose = 'recommended'), 0) expect_true(is.integer(n_at_dose(x, dose = 'recommended'))) expect_equal(length(n_at_dose(x, dose = 'recommended')), 1) expect_equal(n_at_recommended_dose(x), 0) expect_true(is.integer(n_at_recommended_dose(x))) expect_equal(length(n_at_recommended_dose(x)), 1) expect_equal(is_randomising(x), FALSE) expect_true(is.logical(is_randomising(x))) expect_equal(length(is_randomising(x)), 1) expect_true(is.numeric(prob_administer(x))) expect_equal(length(prob_administer(x)), num_doses(x)) expect_equal(tox_at_dose(x), c(0,0,0,0,0)) expect_true(is.integer(tox_at_dose(x))) expect_equal(length(tox_at_dose(x)), num_doses(x)) expect_true(is.numeric(empiric_tox_rate(x))) expect_equal(length(empiric_tox_rate(x)), num_doses(x)) expect_true(is.numeric(mean_prob_tox(x))) expect_equal(length(mean_prob_tox(x)), num_doses(x)) expect_true(is.numeric(median_prob_tox(x))) expect_equal(length(median_prob_tox(x)), num_doses(x)) expect_true(is.logical(dose_admissible(x))) expect_equal(length(dose_admissible(x)), num_doses(x)) expect_true(is.numeric(prob_tox_quantile(x, p = 0.9))) expect_equal(length(prob_tox_quantile(x, p = 0.9)), num_doses(x)) expect_true(is.numeric(prob_tox_exceeds(x, 0.5))) expect_equal(length(prob_tox_exceeds(x, 0.5)), num_doses(x)) expect_true(is.logical(supports_sampling(x))) expect_true(is.data.frame(prob_tox_samples(x))) expect_true(is.data.frame(prob_tox_samples(x, tall = TRUE))) expect_error(summary(x), NA) expect_output(print(x)) expect_true(tibble::is_tibble(as_tibble(x))) expect_true(nrow(as_tibble(x)) >= num_doses(x)) outcomes <- tibble( cohort = c(1,1,1, 2,2,2), dose = c(1,1,1, 2,2,2), tox = c(0,0, 0,0, 1,1) ) x <- fit(model_fitter, outcomes) expect_equal(tox_target(x), 0.25) expect_true(is.numeric(tox_target(x))) expect_equal(num_patients(x), 6) expect_true(is.integer(num_patients(x))) expect_equal(cohort(x), c(1,1,1, 2,2,2)) expect_true(is.integer(cohort(x))) expect_equal(length(cohort(x)), num_patients(x)) expect_equal(doses_given(x), c(1,1,1, 2,2,2)) expect_true(is.integer(doses_given(x))) expect_equal(length(doses_given(x)), num_patients(x)) expect_equal(tox(x), c(0,0,0, 0,1,1)) expect_true(is.integer(tox(x))) expect_equal(length(tox(x)), num_patients(x)) expect_equal(num_tox(x), 2) expect_true(is.integer(num_tox(x))) expect_true(all((model_frame(x) - data.frame(patient = c(1,2,3,4,5,6), cohort = c(1,1,1,2,2,2), dose = c(1,1,1,2,2,2), tox = c(0,0,0,0,1,1))) == 0)) expect_equal(nrow(model_frame(x)), num_patients(x)) expect_equal(num_doses(x), 5) expect_true(is.integer(tox(x))) expect_equal(dose_indices(x), 1:5) expect_true(is.integer(dose_indices(x))) expect_equal(length(dose_indices(x)), num_doses(x)) expect_equal(recommended_dose(x), 1) expect_true(is.integer(recommended_dose(x))) expect_equal(length(recommended_dose(x)), 1) expect_equal(continue(x), TRUE) expect_true(is.logical(continue(x))) expect_equal(n_at_dose(x), c(3,3,0,0,0)) expect_true(is.integer(n_at_dose(x))) expect_equal(length(n_at_dose(x)), num_doses(x)) expect_equal(n_at_dose(x, dose = 0), 0) expect_true(is.integer(n_at_dose(x, dose = 0))) expect_equal(length(n_at_dose(x, dose = 0)), 1) expect_equal(n_at_dose(x, dose = 1), 3) expect_true(is.integer(n_at_dose(x, dose = 1))) expect_equal(length(n_at_dose(x, dose = 1)), 1) expect_equal(n_at_dose(x, dose = 'recommended'), 3) expect_true(is.integer(n_at_dose(x, dose = 'recommended'))) expect_equal(length(n_at_dose(x, dose = 'recommended')), 1) expect_equal(n_at_recommended_dose(x), 3) expect_true(is.integer(n_at_recommended_dose(x))) expect_equal(length(n_at_recommended_dose(x)), 1) expect_equal(is_randomising(x), FALSE) expect_true(is.logical(is_randomising(x))) expect_equal(length(is_randomising(x)), 1) expect_equal(unname(prob_administer(x)), c(0.5,0.5,0,0,0)) expect_true(is.numeric(prob_administer(x))) expect_equal(length(prob_administer(x)), num_doses(x)) expect_equal(tox_at_dose(x), c(0,2,0,0,0)) expect_true(is.integer(tox_at_dose(x))) expect_equal(length(tox_at_dose(x)), num_doses(x)) expect_true(is.numeric(empiric_tox_rate(x))) expect_equal(length(empiric_tox_rate(x)), num_doses(x)) expect_true(is.numeric(mean_prob_tox(x))) expect_equal(length(mean_prob_tox(x)), num_doses(x)) expect_true(is.numeric(median_prob_tox(x))) expect_equal(length(median_prob_tox(x)), num_doses(x)) expect_true(is.logical(dose_admissible(x))) expect_equal(length(dose_admissible(x)), num_doses(x)) expect_true(is.numeric(prob_tox_quantile(x, p = 0.9))) expect_equal(length(prob_tox_quantile(x, p = 0.9)), num_doses(x)) expect_true(is.numeric(prob_tox_exceeds(x, 0.5))) expect_equal(length(prob_tox_exceeds(x, 0.5)), num_doses(x)) expect_true(is.logical(supports_sampling(x))) expect_true(is.data.frame(prob_tox_samples(x))) expect_true(is.data.frame(prob_tox_samples(x, tall = TRUE))) expect_error(summary(x), NA) expect_output(print(x)) expect_true(tibble::is_tibble(as_tibble(x))) expect_true(nrow(as_tibble(x)) >= num_doses(x)) }) test_that('logistic trialr_crm_selector supports correct interface.', { skeleton <- c(0.05, 0.1, 0.25, 0.4, 0.6) target <- 0.25 model = 'logistic' model_fitter <- get_trialr_crm(skeleton = skeleton, target = target, model = model, a0 = 2, beta_mean = 0, beta_sd = 1) x <- fit(model_fitter, '1NNN 2NTT') expect_equal(tox_target(x), 0.25) expect_true(is.numeric(tox_target(x))) expect_equal(num_patients(x), 6) expect_true(is.integer(num_patients(x))) expect_equal(cohort(x), c(1,1,1, 2,2,2)) expect_true(is.integer(cohort(x))) expect_equal(length(cohort(x)), num_patients(x)) expect_equal(doses_given(x), unname(c(1,1,1, 2,2,2))) expect_true(is.integer(doses_given(x))) expect_equal(length(doses_given(x)), num_patients(x)) expect_equal(tox(x), c(0,0,0, 0,1,1)) expect_true(is.integer(tox(x))) expect_equal(length(tox(x)), num_patients(x)) expect_equal(num_tox(x), 2) expect_true(is.integer(num_tox(x))) expect_true(all((model_frame(x) - data.frame(patient = c(1,2,3,4,5,6), cohort = c(1,1,1,2,2,2), dose = c(1,1,1,2,2,2), tox = c(0,0,0,0,1,1))) == 0)) expect_equal(nrow(model_frame(x)), num_patients(x)) expect_equal(num_doses(x), 5) expect_true(is.integer(tox(x))) expect_equal(dose_indices(x), 1:5) expect_true(is.integer(dose_indices(x))) expect_equal(length(dose_indices(x)), num_doses(x)) expect_equal(recommended_dose(x), 1) expect_true(is.integer(recommended_dose(x))) expect_equal(length(recommended_dose(x)), 1) expect_equal(continue(x), TRUE) expect_true(is.logical(continue(x))) expect_equal(n_at_dose(x), c(3,3,0,0,0)) expect_true(is.integer(n_at_dose(x))) expect_equal(length(n_at_dose(x)), num_doses(x)) expect_equal(n_at_dose(x, dose = 0), 0) expect_true(is.integer(n_at_dose(x, dose = 0))) expect_equal(length(n_at_dose(x, dose = 0)), 1) expect_equal(n_at_dose(x, dose = 1), 3) expect_true(is.integer(n_at_dose(x, dose = 1))) expect_equal(length(n_at_dose(x, dose = 1)), 1) expect_equal(n_at_dose(x, dose = 'recommended'), 3) expect_true(is.integer(n_at_dose(x, dose = 'recommended'))) expect_equal(length(n_at_dose(x, dose = 'recommended')), 1) expect_equal(n_at_recommended_dose(x), 3) expect_true(is.integer(n_at_recommended_dose(x))) expect_equal(length(n_at_recommended_dose(x)), 1) expect_equal(is_randomising(x), FALSE) expect_true(is.logical(is_randomising(x))) expect_equal(length(is_randomising(x)), 1) expect_equal(unname(prob_administer(x)), c(0.5,0.5,0,0,0)) expect_true(is.numeric(prob_administer(x))) expect_equal(length(prob_administer(x)), num_doses(x)) expect_equal(tox_at_dose(x), c(0,2,0,0,0)) expect_true(is.integer(tox_at_dose(x))) expect_equal(length(tox_at_dose(x)), num_doses(x)) expect_true(is.numeric(empiric_tox_rate(x))) expect_equal(length(empiric_tox_rate(x)), num_doses(x)) expect_true(is.numeric(mean_prob_tox(x))) expect_equal(length(mean_prob_tox(x)), num_doses(x)) expect_true(is.numeric(median_prob_tox(x))) expect_equal(length(median_prob_tox(x)), num_doses(x)) expect_true(is.logical(dose_admissible(x))) expect_equal(length(dose_admissible(x)), num_doses(x)) expect_true(is.numeric(prob_tox_quantile(x, p = 0.9))) expect_equal(length(prob_tox_quantile(x, p = 0.9)), num_doses(x)) expect_true(is.numeric(prob_tox_exceeds(x, 0.5))) expect_equal(length(prob_tox_exceeds(x, 0.5)), num_doses(x)) expect_true(is.logical(supports_sampling(x))) expect_true(is.data.frame(prob_tox_samples(x))) expect_true(is.data.frame(prob_tox_samples(x, tall = TRUE))) expect_error(summary(x), NA) expect_output(print(x)) expect_true(tibble::is_tibble(as_tibble(x))) expect_true(nrow(as_tibble(x)) >= num_doses(x)) x <- fit(model_fitter, '') expect_equal(tox_target(x), 0.25) expect_true(is.numeric(tox_target(x))) expect_equal(num_patients(x), 0) expect_true(is.integer(num_patients(x))) expect_equal(cohort(x), integer(0)) expect_true(is.integer(cohort(x))) expect_equal(length(cohort(x)), num_patients(x)) expect_equal(doses_given(x), integer(0)) expect_true(is.integer(doses_given(x))) expect_equal(length(doses_given(x)), num_patients(x)) expect_equal(tox(x), integer(0)) expect_true(is.integer(tox(x))) expect_equal(length(tox(x)), num_patients(x)) expect_equal(num_tox(x), 0) expect_true(is.integer(num_tox(x))) mf <- model_frame(x) expect_equal(nrow(mf), 0) expect_equal(ncol(mf), 4) expect_equal(num_doses(x), 5) expect_true(is.integer(num_doses(x))) expect_equal(dose_indices(x), 1:5) expect_true(is.integer(dose_indices(x))) expect_equal(length(dose_indices(x)), num_doses(x)) expect_equal(recommended_dose(x), 1) expect_true(is.integer(recommended_dose(x))) expect_equal(length(recommended_dose(x)), 1) expect_equal(continue(x), TRUE) expect_true(is.logical(continue(x))) expect_equal(n_at_dose(x), c(0,0,0,0,0)) expect_true(is.integer(n_at_dose(x))) expect_equal(length(n_at_dose(x)), num_doses(x)) expect_equal(n_at_dose(x, dose = 0), 0) expect_true(is.integer(n_at_dose(x, dose = 0))) expect_equal(length(n_at_dose(x, dose = 0)), 1) expect_equal(n_at_dose(x, dose = 1), 0) expect_true(is.integer(n_at_dose(x, dose = 1))) expect_equal(length(n_at_dose(x, dose = 1)), 1) expect_equal(n_at_dose(x, dose = 'recommended'), 0) expect_true(is.integer(n_at_dose(x, dose = 'recommended'))) expect_equal(length(n_at_dose(x, dose = 'recommended')), 1) expect_equal(n_at_recommended_dose(x), 0) expect_true(is.integer(n_at_recommended_dose(x))) expect_equal(length(n_at_recommended_dose(x)), 1) expect_equal(is_randomising(x), FALSE) expect_true(is.logical(is_randomising(x))) expect_equal(length(is_randomising(x)), 1) expect_true(is.numeric(prob_administer(x))) expect_equal(length(prob_administer(x)), num_doses(x)) expect_equal(tox_at_dose(x), c(0,0,0,0,0)) expect_true(is.integer(tox_at_dose(x))) expect_equal(length(tox_at_dose(x)), num_doses(x)) expect_true(is.numeric(empiric_tox_rate(x))) expect_equal(length(empiric_tox_rate(x)), num_doses(x)) expect_true(is.numeric(mean_prob_tox(x))) expect_equal(length(mean_prob_tox(x)), num_doses(x)) expect_true(is.numeric(median_prob_tox(x))) expect_equal(length(median_prob_tox(x)), num_doses(x)) expect_true(is.logical(dose_admissible(x))) expect_equal(length(dose_admissible(x)), num_doses(x)) expect_true(is.numeric(prob_tox_quantile(x, p = 0.9))) expect_equal(length(prob_tox_quantile(x, p = 0.9)), num_doses(x)) expect_true(is.numeric(prob_tox_exceeds(x, 0.5))) expect_equal(length(prob_tox_exceeds(x, 0.5)), num_doses(x)) expect_true(is.logical(supports_sampling(x))) expect_true(is.data.frame(prob_tox_samples(x))) expect_true(is.data.frame(prob_tox_samples(x, tall = TRUE))) expect_error(summary(x), NA) expect_output(print(x)) expect_true(tibble::is_tibble(as_tibble(x))) expect_true(nrow(as_tibble(x)) >= num_doses(x)) outcomes <- tibble( cohort = c(1,1,1, 2,2,2), dose = c(1,1,1, 2,2,2), tox = c(0,0, 0,0, 1,1) ) x <- fit(model_fitter, outcomes) expect_equal(tox_target(x), 0.25) expect_true(is.numeric(tox_target(x))) expect_equal(num_patients(x), 6) expect_true(is.integer(num_patients(x))) expect_equal(cohort(x), c(1,1,1, 2,2,2)) expect_true(is.integer(cohort(x))) expect_equal(length(cohort(x)), num_patients(x)) expect_equal(doses_given(x), c(1,1,1, 2,2,2)) expect_true(is.integer(doses_given(x))) expect_equal(length(doses_given(x)), num_patients(x)) expect_equal(tox(x), c(0,0,0, 0,1,1)) expect_true(is.integer(tox(x))) expect_equal(length(tox(x)), num_patients(x)) expect_equal(num_tox(x), 2) expect_true(is.integer(num_tox(x))) expect_true(all((model_frame(x) - data.frame(patient = c(1,2,3,4,5,6), cohort = c(1,1,1,2,2,2), dose = c(1,1,1,2,2,2), tox = c(0,0,0,0,1,1))) == 0)) expect_equal(nrow(model_frame(x)), num_patients(x)) expect_equal(num_doses(x), 5) expect_true(is.integer(tox(x))) expect_equal(dose_indices(x), 1:5) expect_true(is.integer(dose_indices(x))) expect_equal(length(dose_indices(x)), num_doses(x)) expect_equal(recommended_dose(x), 1) expect_true(is.integer(recommended_dose(x))) expect_equal(length(recommended_dose(x)), 1) expect_equal(continue(x), TRUE) expect_true(is.logical(continue(x))) expect_equal(n_at_dose(x), c(3,3,0,0,0)) expect_true(is.integer(n_at_dose(x))) expect_equal(length(n_at_dose(x)), num_doses(x)) expect_equal(n_at_dose(x, dose = 0), 0) expect_true(is.integer(n_at_dose(x, dose = 0))) expect_equal(length(n_at_dose(x, dose = 0)), 1) expect_equal(n_at_dose(x, dose = 1), 3) expect_true(is.integer(n_at_dose(x, dose = 1))) expect_equal(length(n_at_dose(x, dose = 1)), 1) expect_equal(n_at_dose(x, dose = 'recommended'), 3) expect_true(is.integer(n_at_dose(x, dose = 'recommended'))) expect_equal(length(n_at_dose(x, dose = 'recommended')), 1) expect_equal(n_at_recommended_dose(x), 3) expect_true(is.integer(n_at_recommended_dose(x))) expect_equal(length(n_at_recommended_dose(x)), 1) expect_equal(is_randomising(x), FALSE) expect_true(is.logical(is_randomising(x))) expect_equal(length(is_randomising(x)), 1) expect_equal(unname(prob_administer(x)), c(0.5,0.5,0,0,0)) expect_true(is.numeric(prob_administer(x))) expect_equal(length(prob_administer(x)), num_doses(x)) expect_equal(tox_at_dose(x), c(0,2,0,0,0)) expect_true(is.integer(tox_at_dose(x))) expect_equal(length(tox_at_dose(x)), num_doses(x)) expect_true(is.numeric(empiric_tox_rate(x))) expect_equal(length(empiric_tox_rate(x)), num_doses(x)) expect_true(is.numeric(mean_prob_tox(x))) expect_equal(length(mean_prob_tox(x)), num_doses(x)) expect_true(is.numeric(median_prob_tox(x))) expect_equal(length(median_prob_tox(x)), num_doses(x)) expect_true(is.logical(dose_admissible(x))) expect_equal(length(dose_admissible(x)), num_doses(x)) expect_true(is.numeric(prob_tox_quantile(x, p = 0.9))) expect_equal(length(prob_tox_quantile(x, p = 0.9)), num_doses(x)) expect_true(is.numeric(prob_tox_exceeds(x, 0.5))) expect_equal(length(prob_tox_exceeds(x, 0.5)), num_doses(x)) expect_true(is.logical(supports_sampling(x))) expect_true(is.data.frame(prob_tox_samples(x))) expect_true(is.data.frame(prob_tox_samples(x, tall = TRUE))) expect_error(summary(x), NA) expect_output(print(x)) expect_true(tibble::is_tibble(as_tibble(x))) expect_true(nrow(as_tibble(x)) >= num_doses(x)) }) test_that('logistic2 trialr_crm_selector supports correct interface.', { skeleton <- c(0.05, 0.1, 0.25, 0.4, 0.6) target <- 0.25 model = 'logistic2' model_fitter <- get_trialr_crm(skeleton = skeleton, target = target, model = model, alpha_mean = -2, alpha_sd = 1, beta_mean = 0, beta_sd = 1) x <- fit(model_fitter, '1NNN 2NTT') expect_equal(tox_target(x), 0.25) expect_true(is.numeric(tox_target(x))) expect_equal(num_patients(x), 6) expect_true(is.integer(num_patients(x))) expect_equal(cohort(x), c(1,1,1, 2,2,2)) expect_true(is.integer(cohort(x))) expect_equal(length(cohort(x)), num_patients(x)) expect_equal(doses_given(x), unname(c(1,1,1, 2,2,2))) expect_true(is.integer(doses_given(x))) expect_equal(length(doses_given(x)), num_patients(x)) expect_equal(tox(x), c(0,0,0, 0,1,1)) expect_true(is.integer(tox(x))) expect_equal(length(tox(x)), num_patients(x)) expect_equal(num_tox(x), 2) expect_true(is.integer(num_tox(x))) expect_true(all((model_frame(x) - data.frame(patient = c(1,2,3,4,5,6), cohort = c(1,1,1,2,2,2), dose = c(1,1,1,2,2,2), tox = c(0,0,0,0,1,1))) == 0)) expect_equal(nrow(model_frame(x)), num_patients(x)) expect_equal(num_doses(x), 5) expect_true(is.integer(tox(x))) expect_equal(dose_indices(x), 1:5) expect_true(is.integer(dose_indices(x))) expect_equal(length(dose_indices(x)), num_doses(x)) expect_equal(recommended_dose(x), 2) expect_true(is.integer(recommended_dose(x))) expect_equal(length(recommended_dose(x)), 1) expect_equal(continue(x), TRUE) expect_true(is.logical(continue(x))) expect_equal(n_at_dose(x), c(3,3,0,0,0)) expect_true(is.integer(n_at_dose(x))) expect_equal(length(n_at_dose(x)), num_doses(x)) expect_equal(n_at_dose(x, dose = 0), 0) expect_true(is.integer(n_at_dose(x, dose = 0))) expect_equal(length(n_at_dose(x, dose = 0)), 1) expect_equal(n_at_dose(x, dose = 1), 3) expect_true(is.integer(n_at_dose(x, dose = 1))) expect_equal(length(n_at_dose(x, dose = 1)), 1) expect_equal(n_at_dose(x, dose = 'recommended'), 3) expect_true(is.integer(n_at_dose(x, dose = 'recommended'))) expect_equal(length(n_at_dose(x, dose = 'recommended')), 1) expect_equal(n_at_recommended_dose(x), 3) expect_true(is.integer(n_at_recommended_dose(x))) expect_equal(length(n_at_recommended_dose(x)), 1) expect_equal(is_randomising(x), FALSE) expect_true(is.logical(is_randomising(x))) expect_equal(length(is_randomising(x)), 1) expect_equal(unname(prob_administer(x)), c(0.5,0.5,0,0,0)) expect_true(is.numeric(prob_administer(x))) expect_equal(length(prob_administer(x)), num_doses(x)) expect_equal(tox_at_dose(x), c(0,2,0,0,0)) expect_true(is.integer(tox_at_dose(x))) expect_equal(length(tox_at_dose(x)), num_doses(x)) expect_true(is.numeric(empiric_tox_rate(x))) expect_equal(length(empiric_tox_rate(x)), num_doses(x)) expect_true(is.numeric(mean_prob_tox(x))) expect_equal(length(mean_prob_tox(x)), num_doses(x)) expect_true(is.numeric(median_prob_tox(x))) expect_equal(length(median_prob_tox(x)), num_doses(x)) expect_true(is.logical(dose_admissible(x))) expect_equal(length(dose_admissible(x)), num_doses(x)) expect_true(is.numeric(prob_tox_quantile(x, p = 0.9))) expect_equal(length(prob_tox_quantile(x, p = 0.9)), num_doses(x)) expect_true(is.numeric(prob_tox_exceeds(x, 0.5))) expect_equal(length(prob_tox_exceeds(x, 0.5)), num_doses(x)) expect_true(is.logical(supports_sampling(x))) expect_true(is.data.frame(prob_tox_samples(x))) expect_true(is.data.frame(prob_tox_samples(x, tall = TRUE))) expect_error(summary(x), NA) expect_output(print(x)) expect_true(tibble::is_tibble(as_tibble(x))) expect_true(nrow(as_tibble(x)) >= num_doses(x)) x <- fit(model_fitter, '') expect_equal(tox_target(x), 0.25) expect_true(is.numeric(tox_target(x))) expect_equal(num_patients(x), 0) expect_true(is.integer(num_patients(x))) expect_equal(cohort(x), integer(0)) expect_true(is.integer(cohort(x))) expect_equal(length(cohort(x)), num_patients(x)) expect_equal(doses_given(x), integer(0)) expect_true(is.integer(doses_given(x))) expect_equal(length(doses_given(x)), num_patients(x)) expect_equal(tox(x), integer(0)) expect_true(is.integer(tox(x))) expect_equal(length(tox(x)), num_patients(x)) expect_equal(num_tox(x), 0) expect_true(is.integer(num_tox(x))) mf <- model_frame(x) expect_equal(nrow(mf), 0) expect_equal(ncol(mf), 4) expect_equal(num_doses(x), 5) expect_true(is.integer(num_doses(x))) expect_equal(dose_indices(x), 1:5) expect_true(is.integer(dose_indices(x))) expect_equal(length(dose_indices(x)), num_doses(x)) expect_equal(recommended_dose(x), 1) expect_true(is.integer(recommended_dose(x))) expect_equal(length(recommended_dose(x)), 1) expect_equal(continue(x), TRUE) expect_true(is.logical(continue(x))) expect_equal(n_at_dose(x), c(0,0,0,0,0)) expect_true(is.integer(n_at_dose(x))) expect_equal(length(n_at_dose(x)), num_doses(x)) expect_equal(n_at_dose(x, dose = 0), 0) expect_true(is.integer(n_at_dose(x, dose = 0))) expect_equal(length(n_at_dose(x, dose = 0)), 1) expect_equal(n_at_dose(x, dose = 1), 0) expect_true(is.integer(n_at_dose(x, dose = 1))) expect_equal(length(n_at_dose(x, dose = 1)), 1) expect_equal(n_at_dose(x, dose = 'recommended'), 0) expect_true(is.integer(n_at_dose(x, dose = 'recommended'))) expect_equal(length(n_at_dose(x, dose = 'recommended')), 1) expect_equal(n_at_recommended_dose(x), 0) expect_true(is.integer(n_at_recommended_dose(x))) expect_equal(length(n_at_recommended_dose(x)), 1) expect_equal(is_randomising(x), FALSE) expect_true(is.logical(is_randomising(x))) expect_equal(length(is_randomising(x)), 1) expect_true(is.numeric(prob_administer(x))) expect_equal(length(prob_administer(x)), num_doses(x)) expect_equal(tox_at_dose(x), c(0,0,0,0,0)) expect_true(is.integer(tox_at_dose(x))) expect_equal(length(tox_at_dose(x)), num_doses(x)) expect_true(is.numeric(empiric_tox_rate(x))) expect_equal(length(empiric_tox_rate(x)), num_doses(x)) expect_true(is.numeric(mean_prob_tox(x))) expect_equal(length(mean_prob_tox(x)), num_doses(x)) expect_true(is.numeric(median_prob_tox(x))) expect_equal(length(median_prob_tox(x)), num_doses(x)) expect_true(is.logical(dose_admissible(x))) expect_equal(length(dose_admissible(x)), num_doses(x)) expect_true(is.numeric(prob_tox_quantile(x, p = 0.9))) expect_equal(length(prob_tox_quantile(x, p = 0.9)), num_doses(x)) expect_true(is.numeric(prob_tox_exceeds(x, 0.5))) expect_equal(length(prob_tox_exceeds(x, 0.5)), num_doses(x)) expect_true(is.logical(supports_sampling(x))) expect_true(is.data.frame(prob_tox_samples(x))) expect_true(is.data.frame(prob_tox_samples(x, tall = TRUE))) expect_error(summary(x), NA) expect_output(print(x)) expect_true(tibble::is_tibble(as_tibble(x))) expect_true(nrow(as_tibble(x)) >= num_doses(x)) outcomes <- tibble( cohort = c(1,1,1, 2,2,2), dose = c(1,1,1, 2,2,2), tox = c(0,0, 0,0, 1,1) ) x <- fit(model_fitter, outcomes) expect_equal(tox_target(x), 0.25) expect_true(is.numeric(tox_target(x))) expect_equal(num_patients(x), 6) expect_true(is.integer(num_patients(x))) expect_equal(cohort(x), c(1,1,1, 2,2,2)) expect_true(is.integer(cohort(x))) expect_equal(length(cohort(x)), num_patients(x)) expect_equal(doses_given(x), c(1,1,1, 2,2,2)) expect_true(is.integer(doses_given(x))) expect_equal(length(doses_given(x)), num_patients(x)) expect_equal(tox(x), c(0,0,0, 0,1,1)) expect_true(is.integer(tox(x))) expect_equal(length(tox(x)), num_patients(x)) expect_equal(num_tox(x), 2) expect_true(is.integer(num_tox(x))) expect_true(all((model_frame(x) - data.frame(patient = c(1,2,3,4,5,6), cohort = c(1,1,1,2,2,2), dose = c(1,1,1,2,2,2), tox = c(0,0,0,0,1,1))) == 0)) expect_equal(nrow(model_frame(x)), num_patients(x)) expect_equal(num_doses(x), 5) expect_true(is.integer(tox(x))) expect_equal(dose_indices(x), 1:5) expect_true(is.integer(dose_indices(x))) expect_equal(length(dose_indices(x)), num_doses(x)) expect_equal(recommended_dose(x), 2) expect_true(is.integer(recommended_dose(x))) expect_equal(length(recommended_dose(x)), 1) expect_equal(continue(x), TRUE) expect_true(is.logical(continue(x))) expect_equal(n_at_dose(x), c(3,3,0,0,0)) expect_true(is.integer(n_at_dose(x))) expect_equal(length(n_at_dose(x)), num_doses(x)) expect_equal(n_at_dose(x, dose = 0), 0) expect_true(is.integer(n_at_dose(x, dose = 0))) expect_equal(length(n_at_dose(x, dose = 0)), 1) expect_equal(n_at_dose(x, dose = 1), 3) expect_true(is.integer(n_at_dose(x, dose = 1))) expect_equal(length(n_at_dose(x, dose = 1)), 1) expect_equal(n_at_dose(x, dose = 'recommended'), 3) expect_true(is.integer(n_at_dose(x, dose = 'recommended'))) expect_equal(length(n_at_dose(x, dose = 'recommended')), 1) expect_equal(n_at_recommended_dose(x), 3) expect_true(is.integer(n_at_recommended_dose(x))) expect_equal(length(n_at_recommended_dose(x)), 1) expect_equal(is_randomising(x), FALSE) expect_true(is.logical(is_randomising(x))) expect_equal(length(is_randomising(x)), 1) expect_equal(unname(prob_administer(x)), c(0.5,0.5,0,0,0)) expect_true(is.numeric(prob_administer(x))) expect_equal(length(prob_administer(x)), num_doses(x)) expect_equal(tox_at_dose(x), c(0,2,0,0,0)) expect_true(is.integer(tox_at_dose(x))) expect_equal(length(tox_at_dose(x)), num_doses(x)) expect_true(is.numeric(empiric_tox_rate(x))) expect_equal(length(empiric_tox_rate(x)), num_doses(x)) expect_true(is.numeric(mean_prob_tox(x))) expect_equal(length(mean_prob_tox(x)), num_doses(x)) expect_true(is.numeric(median_prob_tox(x))) expect_equal(length(median_prob_tox(x)), num_doses(x)) expect_true(is.logical(dose_admissible(x))) expect_equal(length(dose_admissible(x)), num_doses(x)) expect_true(is.numeric(prob_tox_quantile(x, p = 0.9))) expect_equal(length(prob_tox_quantile(x, p = 0.9)), num_doses(x)) expect_true(is.numeric(prob_tox_exceeds(x, 0.5))) expect_equal(length(prob_tox_exceeds(x, 0.5)), num_doses(x)) expect_true(is.logical(supports_sampling(x))) expect_true(is.data.frame(prob_tox_samples(x))) expect_true(is.data.frame(prob_tox_samples(x, tall = TRUE))) expect_error(summary(x), NA) expect_output(print(x)) expect_true(tibble::is_tibble(as_tibble(x))) expect_true(nrow(as_tibble(x)) >= num_doses(x)) })
github_api_repo_subscribe = function(repo, subscribed, ignored){ arg_is_chr_scalar(repo) arg_is_lgl_scalar(subscribed, ignored) if (subscribed == ignored) cli_stop("{.code subscribed != ignored} must be true") ghclass_api_v3_req( endpoint = "PUT /repos/:owner/:repo/subscription", owner = get_repo_owner(repo), repo = get_repo_name(repo), subscribed = subscribed, ignored = ignored ) } repo_watch = function(repo) { arg_is_chr(repo) res = purrr::map( repo, function(repo, notifications) { res = purrr::safely(github_api_repo_subscribe)( repo, subscribed = TRUE, ignored = FALSE ) status_msg( res, "Watched {.val {repo}}.", "Failed to watch {.val {repo}}." ) } ) invisible(res) } repo_ignore = function(repo) { arg_is_chr(repo) res = purrr::map( repo, function(repo, notifications) { res = purrr::safely(github_api_repo_subscribe)( repo, subscribed = FALSE, ignored = TRUE ) status_msg( res, "Ignored repo {.val {repo}}.", "Failed to ignore repo {.val {repo}}." ) } ) invisible(res) }
multiPersonIBD = function(x, ids, complete = FALSE, verbose = FALSE) { N = length(ids) if(N < 2) stop2("`length(ids)` must be at least 2") if(N > 6) stop2("length(ids) > 6: Not implemented yet") inb = inbreeding(x, ids) if(any(isInbred <- inb > .Machine$double.eps)) { message(paste0(sprintf(" Individual '%s' is inbred (f = %g)", ids[isInbred], inb[isInbred]), collapse = "\n")) stop2("This function requires all `ids` individuals to be non-inbred") } if(!hasParentsBeforeChildren(x)) x = parentsBeforeChildren(x) x = foundersFirst(x) mem = initialiseGKMemo(x, counters = c("i", "itriv", "iimp", "ifound", "ilook", "irec")) allPatterns = MULTIPATTERNS_NONINBRED[[N]] usePatterns = removeImpossiblePatterns(allPatterns, x, ids, verbose = verbose) ids2 = rep(ids, each = 2) coefs = apply(usePatterns, 1, function(r) { kp = r[1:(2*N)] weight = r[2*N + 1] g = generalisedKinship(x, split(ids2, kp), mem = mem) 2^N * weight * g }) if(verbose) printCounts2(mem) glist = lapply(seq(1, 2*N, by = 2), function(i) paste(usePatterns[, i], usePatterns[, i+1], sep = " ")) res = as.data.frame(glist, col.names = as.character(ids), optional = TRUE, stringsAsFactors = FALSE) res = cbind(Prob = coefs, res) if(!complete) res = res[res$Prob > 0, , drop = FALSE] res } standardAlleleSeq = function(x) { res = integer(length(x)) a = x[1] i = 1L while(TRUE) { res[x == a] = i a = x[match(0, res)] if(is.na(a)) break i = i + 1 } res } minimalPattern = function(x) { if(is.matrix(x)) { res = apply(x, 1, minimalPattern) return(res) } if(!is.numeric(x) || any(as.integer(x) != x)) stop("The input must be a vector of integers:", toString(x)) n = length(x) if(n %% 2 != 0) stop("Input vector must have even length, not ", toString(x)) insertAt = function(y, pos, value) { y[y == value] = max(y) + 1 y[pos] = value y } nPairs = n/2 even = 2 * seq_len(nPairs) odd = even - 1 i = 0 for(k in seq_len(nPairs)) { a = x[2*k - 1] b = x[2*k] if(a == b) { if(a > i) { x = insertAt(x, x == a, i + 1) i = i + 1 } next } n.new = sum(a > i, b > i) if(n.new == 2) { idx.a = x == a idx.b = x == b grps.a = idx.a[odd] | idx.a[even] grps.b = idx.b[odd] | idx.b[even] diffs = grps.a != grps.b swap = any(diffs) && grps.b[match(TRUE, diffs)] x = insertAt(x, idx.a, value = if(swap) i+2 else i+1) x = insertAt(x, idx.b, value = if(swap) i+1 else i+2) i = i + 2 } else if (n.new == 1) { x = insertAt(x, x == max(a,b), i + 1) i = i + 1 } if((g1 <- x[2*k - 1]) > (g2 <- x[2*k])) { x[2*k - 1] = g2 x[2*k] = g1 } } x } expandSwaps = function(x, makeUnique = TRUE) { n = length(x)/2 res = matrix(0L, nrow = 2*n, ncol = 2^n) for(i in 1:n) { rows = c(2*i-1, 2*i) g = x[rows] swap = rep(c(FALSE, TRUE), each = 2^(n-i), length.out = 2^n) res[rows, !swap] = g res[rows, swap] = g[2:1] } res = apply(res, 2, standardAlleleSeq) if(makeUnique) res = unique.matrix(res, MARGIN = 2) t.default(res) } removeImpossiblePatterns = function(patterns, x, ids, verbose = TRUE) { N = length(ids) if(length(ids) < 3) return(patterns[, 1:(2*N + 1)]) nr = nrow(patterns) kappas = kappaIBD(x, ids) nonz = lapply(1:nrow(kappas), function(i) (0:2)[kappas[i, 3:5] > 0]) names(nonz) = sapply(combn(N, 2, simplify = FALSE), paste, collapse = "-") for(p in names(nonz)) { goodrows = patterns[, p] %in% nonz[[p]] patterns = patterns[goodrows, , drop = FALSE] } if(verbose) message(sprintf("State space reduction: %d --> %d", nr, nrow(patterns))) patterns }
plot_dym_sp <- function(subnic, sp, xlab=NULL, ylab=NULL, main=NA, col.axis="azure3", lty.axis=2, lwd.axis=2, border.E="black", col.E=" lty.E=1, lwd.E=1, col.NR =" border.NR ="black", lty.NR=1, lwd.NR=1, col.NR.lab="black", cex.NR.lab=0.7, pch.NR.pos= 21, col.NR.pos="black", col.NR.pt="black", cex.NR.pos=1, border.SR="black", col.SR=" lty.SR=1, lwd.SR=1, col.SR.lab="black", cex.SR.lab=0.7, fac.SR.lab=1.2, pch.SR.pos= 21, col.SR.pos=" col.SR.pt="black", cex.SR.pos=1, col.arrow="black", angle.arrow=20, lwd.arrow=2, length.arrow=0.1, font.sp=2, leg=T, posi.leg="topleft", bty.leg="n", ...){ fac <- subnic$factor lev <- levels(fac) ar_sub <- subarea(subnic) eig <- round(subnic$eig/sum(subnic$eig)*100,2)[1:2] E <- ar_sub$E if(pch.SR.pos<21|pch.SR.pos>25){ col.SR.pt <- col.SR.pos } if(pch.NR.pos<21|pch.NR.pos>25){ col.NR.pt <- col.NR.pos } NR <- ar_sub$NR[[sp]] if(is.null(xlab)){ xlab=paste(paste("OMI1",eig[1], sep=" "),"%",sep="")} if(is.null(ylab)){ ylab=paste(paste("OMI2",eig[2], sep=" "),"%",sep="")} plot(subnic$ls, main=main, xlab= xlab, ylab= ylab, type="n",...) polygon(E$x, E$y, border=border.E, col=col.E, lty=lty.E, lwd=lwd.E) polygon(NR$x,NR$y, border=border.NR, col=col.NR, lty=lty.NR,lwd= lwd.NR) nami <- paste(sp, lev, sep="") spli <- subnic$sub[rownames(subnic$sub)%in%nami,] colnames(spli) <- colnames(subnic$li) levi <- sub(sp,"",nami) M <- length(levi) if(is.na(col.NR.lab[M])){ col.SRi <- rep(col.SR,M) border.SRi <- rep(border.SR,M) } for (j in 1:M){ SR <- ar_sub$SR[[lev[j]]] SR <- SR[[nami[j]]] if (length(SR$x)>2){ polygon(SR$x,SR$y, border=border.SRi[j], col=col.SRi[j],lty=lty.SR, lwd=lwd.SR) } else { points(SR$x,SR$y,pch=pch.SR.pos,col=col.SR.pt[j], bg=col.SR.pos[j], cex=cex.SR.pos) } } abline(h=0, lty=lty.axis, lwd=lwd.axis, col=col.axis) abline(v=0, lty=lty.axis, lwd=lwd.axis, col=col.axis) arrows(rep(0,M),rep(0,M),spli[,1], spli[,2], angle=angle.arrow, col=col.arrow,lwd=lwd.arrow, length=length.arrow) points(spli[,1], spli[,2], pch=pch.SR.pos, col=col.SR.pt, bg=col.SR.pos, cex=cex.SR.pos) points(subnic$li[sp,1], subnic$li[sp,2], pch=pch.NR.pos, col=col.NR.pt, bg=col.NR.pos, cex=cex.NR.pos) li <- rbind(subnic$li[sp,], spli) if(anyNA(li)){ li <- li[-which(is.na(li)==T),] } if(sum(round(apply(li,2,diff),1))==0){ text(subnic$li[sp,1]*fac.SR.lab,subnic$li[sp,2]*fac.SR.lab,sp, col=col.NR.lab, cex=cex.NR.lab, font = font.sp) } else { li <- rbind(subnic$li[sp,]*fac.SR.lab, spli*fac.SR.lab) text(li[,1],li[,2],rownames(li),col=c(col.NR.lab,col.SR.lab), cex=c(cex.NR.lab,rep(cex.SR.lab,dim(spli)[1])), font = font.sp) } if(isTRUE(leg)){ filli <- c(col.E, col.NR,NA,col.SR,NA) borderi <- c(border.E, border.NR,NA, border.SR,NA) col.leg <- c(NA,NA, col.NR.pt,NA,col.SR.pt) col.bg <- c(NA,NA, col.NR.pos,NA,col.SR.pos) pch.leg <- c(NA,NA,pch.NR.pos,NA,pch.SR.pos) tex.leg <- c("E","NR","NR position","SR","SR position") lty.leg <- c(0,0,NA,0,NA) lwd.leg <- c(0,0,NA,0,NA) posi.cex <-c(NA,NA,cex.NR.pos,NA,cex.SR.pos) if(is.na(col.E)){ filli[1] <- NA borderi[1] <- NA tex.leg[1] <- NA } if(is.na(col.NR)){ filli[2] <- NA borderi[2] <- NA tex.leg[2] <- NA } if(anyNA(col.SR)){ filli[4] <- NA borderi[4] <- NA tex.leg[4] <- NA } if(anyNA(cex.NR.pos)){ posi.cex[3] <- NA tex.leg[3] <- NA } if(anyNA(cex.SR.pos)){ posi.cex[5] <- NA tex.leg[5] <- NA } if(lty.E>1){ pch.leg[1] <- NA lty.leg[1] <- lty.E lwd.leg[1] <- lwd.E } if (lty.NR>1){ pch.leg[2] <- NA lty.leg[2] <- lty.NR lwd.leg[2] <- lwd.NR } if (lty.SR>1){ pch.leg[4] <- NA lty.leg[4] <- lty.SR lwd.leg[4] <- lwd.SR } legend(posi.leg, legend=tex.leg, fill =filli, border=borderi, pch=pch.leg, col=col.leg, pt.cex = posi.cex, pt.bg=col.bg, lty=lty.leg, pt.lwd=c(NA,NA,1,NA,1), lwd=lwd.leg, bty=bty.leg,...) } }
spl2Db <- function(x.coord,y.coord, at.var=NULL,at.levels=NULL, nsegments = c(10,10), degree = c(3,3), penaltyord = c(2,2),nestorder = c(1,1), minbound=NULL, maxbound=NULL, method="Lee", what="bits" ) { if(length(degree) == 1){degree <- rep(degree,2) } if(length(nsegments) == 1){nsegments <- rep(nsegments,2) } if(length(penaltyord) == 1){penaltyord <- rep(penaltyord,2) } if(length(nestorder) == 1){nestorder <- rep(nestorder,2) } x.coord.name <- as.character(substitute(list(x.coord)))[-1L] y.coord.name <- as.character(substitute(list(y.coord)))[-1L] if(is.null(at.var)){ at.var <- rep("A",length(x.coord)) at.name <- "FIELDINST" at.levels <- "A" }else{ at.name <- as.character(substitute(list(at)))[-1L] if(length(at.var) != length(x.coord)){stop("at.var has different length than x.coord and y.coord, please fix.", call. = FALSE)} if(is.null(at.levels)){at.levels <- levels(as.factor(at.var))} } index <- 1:length(x.coord) if(!is.numeric(x.coord)){stop("x.coord argument in spl2D() needs to be numeric.", call. = FALSE)} if(!is.numeric(y.coord)){stop("y.coord argument in spl2D() needs to be numeric.", call. = FALSE)} dat <- data.frame(x.coord, y.coord, at.var, index); colnames(dat) <- c(x.coord.name,y.coord.name,at.name,"index") missby <- which(is.na(dat[,at.name])) if(length(missby)>0){stop("We will split using the at.name argument and you have missing values in this column.\nPlease correct.", call. = FALSE)} dat[,at.name] <- as.factor(dat[,at.name]) data0 <- split(dat, dat[,at.name]) names(data0) <- levels(dat[,at.name]) nasx <- which(is.na(dat[,x.coord.name])) nasy <- which(is.na(dat[,y.coord.name])) if(length(nasx) > 0 | length(nasy) >0){ stop("x.coord and y.coord columns cannot have NA's", call. = FALSE) } multires <- lapply(data0, function(dxy){ TPXZg <- tpsmmbwrapper(columncoordinates=x.coord.name, rowcoordinates=y.coord.name, maxbound=maxbound, minbound=minbound, penaltyord=penaltyord, data=dxy, nsegments=nsegments, nestorder=nestorder, asreml="grp", method=method) fC <- TPXZg$data[,TPXZg$grp$TP.R.1_fcol] fR <- TPXZg$data[,TPXZg$grp$TP.C.1_frow] fC.R <- TPXZg$data[,TPXZg$grp$TP.R.2_fcol] C.fR <- TPXZg$data[,TPXZg$grp$TP.C.2_frow] fC.fR <- TPXZg$data[,TPXZg$grp$TP_fcol_frow] rest <- TPXZg$data[,min(c(which(colnames(TPXZg$data)=="TP.col"),which(colnames(TPXZg$data)=="TP.row"))):(min(c(TPXZg$grp$TP.R.1_fcol,TPXZg$grp$TP.C.1_frow))-1)] return(list(fC,fR,fC.R,C.fR,fC.fR,rest)) }) names(multires) <- at.levels toFill <- lapply(data0,function(x){x$index}) myNames <- list() for(k in 1:6){ myNames[[k]] <- lapply(multires,function(x){colnames(x[[k]])}) }; names(myNames) <- c("fC","fR","fC.R", "C.fR","fC.fR","rest") Zup <- list() Zup2 <- list() Kup <- list() typevc <- numeric() re_name <- character() counter <- 1 counter2 <- 1 for(k in 1:6){ for(j in 1:length(multires)){ if(names(multires)[j] %in% at.levels){ Z <- matrix(0,nrow=nrow(dat),ncol=length(myNames[[k]][[j]])) colnames(Z) <- myNames[[k]][[j]] prov <- multires[[j]][[k]] Z[toFill[[j]],colnames(prov)] <- as.matrix(prov) attr(Z,"variables") <- c(x.coord.name, y.coord.name) if(k < 6){ Zup[[counter]] <- Z names(Zup)[counter] <- paste0(names(multires)[j],":",names(myNames)[k]) Gu1 <- diag(ncol(Z)); colnames(Gu1) <- rownames(Gu1) <- colnames(Z) Kup[[counter]] <- Gu1 typevc[counter] <- 1 re_name[counter] <- names(Zup)[counter] counter <- counter + 1 }else{ Zup2[[counter2]] <- Z names(Zup2)[counter2] <- paste0(names(multires)[j],":",names(myNames)[k]) counter2 <- counter2 + 1 } } } } Gti=NULL Gtc=NULL vcs <- diag(length(Zup)); rownames(vcs) <- colnames(vcs) <- names(Zup) if(what=="bits"){ namess2 <- c(x.coord.name, y.coord.name) S3 <- list(Z=Zup,K=Kup,Gti=Gti,Gtc=Gtc,typevc=typevc,re_name=re_name,vcs=vcs, terms=namess2) }else if(what == "base"){ S3 <- do.call(cbind,Zup2) }else{stop("method not recognized.",call. = FALSE)} return(S3) } spl2Dmats <- function(x.coord.name, y.coord.name, data, at.name, at.levels, nsegments = NULL, minbound=NULL, maxbound=NULL, degree = c(3,3), penaltyord = c(2,2), nestorder = c(1,1), method="Lee" ) { x.coord <- data[,x.coord.name] y.coord <- data[,y.coord.name] data[,paste0(x.coord.name,"f")] <- as.factor(data[,x.coord.name]) data[,paste0(y.coord.name,"f")] <- as.factor(data[,y.coord.name]) if(!is.numeric(x.coord)){stop("x.coord argument in spl2D() needs to be numeric.", call. = FALSE)} if(!is.numeric(y.coord)){stop("y.coord argument in spl2D() needs to be numeric.", call. = FALSE)} if(missing(at.name)){ dat <- data.frame(x.coord, y.coord); colnames(dat) <- c(x.coord.name,y.coord.name) dat$FIELDINST <- "FIELD1" at.name="FIELDINST" dat[,at.name] <- as.factor(dat[,at.name]) data0 <- split(dat, dat[,at.name]) at.levels="FIELD1" data[,at.name] <- "FIELD1" }else{ check <- which(colnames(data)==at.name) if(length(check)==0){stop("at.name column not found in the data provided", call. = FALSE)}else{ at <- data[,at.name] dat <- data.frame(x.coord, y.coord, at); colnames(dat) <- c(x.coord.name,y.coord.name,at.name) missby <- which(is.na(dat[,at.name])) if(length(missby)>0){stop("We will split using the at.name argument and you have missing values in this column.\nPlease correct.", call. = FALSE)} dat[,at.name] <- as.factor(dat[,at.name]) data0 <- split(dat, dat[,at.name]) names(data0) <- levels(dat[,at.name]) } } if(missing(at.levels)){ at.levels <- levels(dat[,at.name]) } nasx <- which(is.na(dat[,x.coord.name])) nasy <- which(is.na(dat[,y.coord.name])) if(length(nasx) > 0 | length(nasy) >0){ stop("x.coord and y.coord columns cannot have NA's", call. = FALSE) } multires <- lapply(data0, function(dxy){ TPXZg <- tpsmmbwrapper(columncoordinates=x.coord.name, rowcoordinates=y.coord.name, maxbound=maxbound, minbound=minbound, penaltyord=penaltyord, data=dxy, nsegments=nsegments, nestorder=nestorder, asreml="grp", method=method) fC <- TPXZg$data[,TPXZg$grp$TP.R.1_fcol] fR <- TPXZg$data[,TPXZg$grp$TP.C.1_frow] fC.R <- TPXZg$data[,TPXZg$grp$TP.R.2_fcol] C.fR <- TPXZg$data[,TPXZg$grp$TP.C.2_frow] fC.fR <- TPXZg$data[,TPXZg$grp$TP_fcol_frow] rest <- TPXZg$data[,min(c(which(colnames(TPXZg$data)=="TP.col"),which(colnames(TPXZg$data)=="TP.row"))):(min(c(TPXZg$grp$TP.R.1_fcol,TPXZg$grp$TP.C.1_frow))-1)] all <- TPXZg$data[,TPXZg$grp$All] return(list(fC,fR,fC.R,C.fR,fC.fR,all,rest)) }) nrows <- unlist(lapply(data0,nrow)) end <- numeric(); for(l in 1:length(nrows)){end[l] <- sum(nrows[1:l]) } start <- numeric(); for(l in 1:length(nrows)){start[l] <- end[l]-nrows[l]+1 } nColList <- list() for(k in 1:6){ nColList[[k]] <- unlist(lapply(multires,function(x){colnames(x[[k]])})) } uniqueNames <- lapply(nColList,unique) Zl <- list() for(k in 1:6){ Z <- matrix(0,nrow=nrow(dat),ncol=length(uniqueNames[[k]])) colnames(Z) <- uniqueNames[[k]] for(j in 1:length(multires)){ if(names(multires)[j] %in% at.levels){ prov <- multires[[j]][[k]] Z[start[j]:end[j],colnames(prov)] <- as.matrix(prov) } } attr(Z,"variables") <- c(x.coord.name, y.coord.name) Zl[[k]] <- Z } names(Zl) <- c("fC","fR","fC.R", "C.fR","fC.fR","all") data[,at.name] <- as.factor(data[,at.name]) dataToreturn <- split(data, data[at.name]) dataToreturn <- do.call(rbind,dataToreturn) rest <- lapply(multires,function(x){x[[7]]}) rest <- do.call(rbind,rest) dataToreturn <- cbind(dataToreturn,rest) Zl$data <- dataToreturn return(Zl) } tpsmmbwrapper <- function (columncoordinates, rowcoordinates, data, nsegments=NULL, minbound=NULL, maxbound=NULL, degree = c(3, 3), penaltyord = c(2, 2), nestorder = c(1, 1), asreml = "mbf", eigenvalues = "include", method = "Lee", stub = NULL) { if (missing(columncoordinates)) stop("columncoordinates argument must be set") if (missing(rowcoordinates)) stop("rowcoordinates argument must be set") if (missing(data)) stop("data argument must be set") col <- sort(unique(data[[columncoordinates]])) nuc <- length(col) col.match <- match(data[[columncoordinates]], col) row <- sort(unique(data[[rowcoordinates]])) nur <- length(row) row.match <- match(data[[rowcoordinates]], row) nv <- length(data[[columncoordinates]]) if (is.null(minbound)) { cminval <- min(col) rminval <- min(row) } else { cminval <- min(c(minbound[1], min(col))) if (length(minbound) < 2) { rminval <- min(c(minbound[1], min(row))) } else { rminval <- min(c(minbound[2], min(row))) } } if (is.null(maxbound)) { cmaxval <- max(col) rmaxval <- max(row) } else { cmaxval <- max(c(maxbound[1], max(col))) if (length(maxbound) < 2) { rmaxval <- max(c(maxbound[1], max(row))) } else { rmaxval <- max(c(maxbound[2], max(row))) } } if (is.null(nsegments)) { nsegcol <- nuc - 1 nsegrow <- nur - 1 } else { nsegcol <- max(c(nsegments[1], 2)) } if (length(nsegments) < 2) { nsegrow <- max(c(nsegments[1], 2)) } else { nsegrow <- max(c(nsegments[2], 2)) } nestcol <- floor(nestorder[1]) if (length(nestorder) < 2) nestrow <- floor(nestorder[1]) else nestrow <- floor(nestorder[2]) nsncol <- 0 if (nestcol > 1) { if (nsegcol%%nestcol != 0) warning("Column nesting ignored: number of column segments must be a multiple of nesting order") else nsncol <- nsegcol/nestcol } nsnrow <- 0 if (nestrow > 1) { if (nsegrow%%nestrow != 0) warning("Row nesting ignored: number of row segments must be a multiple of nesting order") else nsnrow <- nsegrow/nestrow } Bc <- bbasis(col, cminval, cmaxval, nsegcol, degree[1]) nc <- ncol(Bc) if (length(degree) < 2) degr <- degree[1] else degr <- degree[2] Br <- bbasis(row, rminval, rmaxval, nsegrow, degr) nr <- ncol(Br) if (nsncol > 0) { Bcn <- bbasis(col, cminval, cmaxval, nsncol, degree[1]) ncn <- ncol(Bcn) } else ncn <- nc if (nsnrow > 1) { Brn <- bbasis(row, rminval, rmaxval, nsnrow, degr) nrn <- ncol(Brn) } else nrn <- nr diff.c <- penaltyord[[1]] Dc <- diff(diag(nc), diff = diff.c) svd.c <- svd(crossprod(Dc)) nbc <- nc - diff.c U.Zc <- svd.c$u[, c(1:nbc)] U.Xc <- svd.c$u[, -c(1:nbc)] L.c <- sqrt(svd.c$d[c(1:nbc)]) diagc <- L.c^2 BcU <- Bc %*% U.Zc BcX <- Bc %*% U.Xc BcULi <- BcU %*% diag(1/L.c) if ("include" %in% eigenvalues) { BcZmat.df <- as.data.frame(BcULi) BcZmat <- BcULi } else { BcZmat.df <- as.data.frame(BcU) BcZmat <- BcU } BcZmat.df$TP.col <- col mat1c <- matrix(rep(1, nuc), nrow = nuc) BcXadj <- BcX - mat1c %*% t(mat1c) %*% BcX/nuc Xfc <- (svd(crossprod(BcXadj)))$u[, c(ncol(BcXadj):1)] BcX <- BcX %*% Xfc if (BcX[1, 1] < 0) BcX[, 1] <- -1 * BcX[, 1] if (BcX[1, 2] > 0) BcX[, 2] <- -1 * BcX[, 2] if (nsncol > 0) { Dcn <- diff(diag(ncn), diff = diff.c) svd.cn <- svd(crossprod(Dcn)) nbcn <- ncn - diff.c U.Zcn <- svd.cn$u[, c(1:nbcn)] U.Xcn <- svd.cn$u[, -c(1:nbcn)] L.cn <- sqrt(svd.cn$d[c(1:nbcn)]) BcnU <- Bcn %*% U.Zcn BcnX <- Bcn %*% U.Xcn } else { nbcn <- nbc BcnU <- BcU L.cn <- L.c } if (length(penaltyord) < 2) { diff.r <- penaltyord[1] } else { diff.r <- penaltyord[2] } Dr <- diff(diag(nr), diff = diff.r) svd.r <- svd(crossprod(Dr)) nbr <- nr - diff.r U.Zr <- svd.r$u[, c(1:nbr)] U.Xr <- svd.r$u[, -c(1:nbr)] L.r <- sqrt(svd.r$d[c(1:nbr)]) diagr <- L.r^2 BrU <- Br %*% U.Zr BrX <- Br %*% U.Xr BrULi <- BrU %*% diag(1/L.r) if ("include" %in% eigenvalues) { BrZmat.df <- as.data.frame(BrULi) BrZmat <- BrULi } else { BrZmat.df <- as.data.frame(BrU) BrZmat <- BrU } BrZmat.df$TP.row <- row mat1r <- matrix(rep(1, nur), nrow = nur) BrXadj <- BrX - mat1r %*% t(mat1r) %*% BrX/nur Xfr <- (svd(crossprod(BrXadj)))$u[, c(ncol(BrXadj):1)] BrX <- BrX %*% Xfr if (BrX[1, 1] < 0) BrX[, 1] <- -1 * BrX[, 1] if (BrX[1, 2] > 0) BrX[, 2] <- -1 * BrX[, 2] if (nsnrow > 0) { Drn <- diff(diag(nrn), diff = diff.r) svd.rn <- svd(crossprod(Drn)) nbrn <- nrn - diff.r U.Zrn <- svd.rn$u[, c(1:nbrn)] U.Xrn <- svd.rn$u[, -c(1:nbrn)] L.rn <- sqrt(svd.rn$d[c(1:nbrn)]) BrnU <- Brn %*% U.Zrn BrnX <- Brn %*% U.Xrn } else { nbrn <- nbr BrnU <- BrU L.rn <- L.r } A <- 10^(floor(log10(max(row))) + 1) row.index <- rep(row, times = nuc) col.index <- rep(col, each = nur) index <- A * col.index + row.index C.R <- A * data[[columncoordinates]] + data[[rowcoordinates]] BcrZ1 <- BcnU[col.match, ] %x% matrix(rep(1, nbrn), nrow = 1, ncol = nbrn) BcrZ2 <- matrix(rep(1, nbcn), nrow = 1, ncol = nbcn) %x% BrnU[row.match, ] BcrZ <- BcrZ1 * BcrZ2 diagrx <- rep(L.cn^2, each = nbrn) diagcx <- rep(L.rn^2, times = nbcn) if ("Lee" %in% method) { diagcr <- diagrx + diagcx } if ("Wood" %in% method) { diagcr <- diagrx * diagcx } if (!("Lee" %in% method) & !("Wood" %in% method)) { stop("Invalid setting of method argument") } BcrZLi <- BcrZ %*% diag(1/sqrt(diagcr)) if ("include" %in% eigenvalues) { BcrZmat.df <- as.data.frame(BcrZLi) BcrZmat <- BcrZLi } else { BcrZmat.df <- as.data.frame(BcrZ) BcrZmat <- BcrZ } BcrZmat.df$TP.CxR <- C.R tracelist <- list() for (i in 1:diff.c) { nm <- paste0("Xc", i, ":Zr") tempmat <- (BcX[col.match, i] %x% matrix(rep(1, nbr), nrow = 1)) * BrZmat[row.match, ] if ("include" %in% eigenvalues) tempmatsc <- tempmat else tempmatsc <- tempmat * (rep(1, nv) %*% matrix((1/diagr), nrow = 1)) tracelist[nm] <- sum(tempmatsc * tempmat) } for (i in 1:diff.r) { nm <- paste0("Zc:Xr", i) tempmat <- BcZmat[col.match, ] * (matrix(rep(1, nbc), nrow = 1) %x% BrX[row.match, i]) if ("include" %in% eigenvalues) tempmatsc <- tempmat else tempmatsc <- tempmat * (rep(1, nv) %*% matrix((1/diagc), nrow = 1)) tracelist[nm] <- sum(tempmatsc * tempmat) } if ("include" %in% eigenvalues) tracelist["Zc:Zr"] <- sum(BcrZmat * BcrZmat) else { tempmatsc <- BcrZmat * (rep(1, nv) %*% matrix((1/diagcr), nrow = 1)) tracelist["Zc:Zr"] <- sum(tempmatsc * BcrZmat) } outdata <- as.data.frame(data) outdata$TP.col <- data[[columncoordinates]] outdata$TP.row <- data[[rowcoordinates]] outdata$TP.CxR <- C.R BcrX1 <- BcX[col.match, ] %x% matrix(rep(1, diff.r), nrow = 1) BcrX2 <- matrix(rep(1, diff.c), nrow = 1) %x% BrX[row.match, ] BcrX <- BcrX1 * BcrX2 fixed <- list() fixed$col <- data.frame(row.names = C.R) for (i in 1:diff.c) { c.fixed <- paste("TP.C", ".", i, sep = "") outdata[c.fixed] <- BcX[col.match, i] fixed$col[c.fixed] <- BcX[col.match, i] } fixed$row <- data.frame(row.names = C.R) for (i in 1:diff.r) { r.fixed <- paste("TP.R", ".", i, sep = "") outdata[r.fixed] <- BrX[row.match, i] fixed$row[r.fixed] <- BrX[row.match, i] } ncolX <- diff.c * diff.r fixed$int <- data.frame(row.names = C.R) for (i in 1:ncolX) { cr.fixed <- paste("TP.CR", ".", i, sep = "") outdata[cr.fixed] <- BcrX[, i] fixed$int[cr.fixed] <- BcrX[, i] } if (!missing(stub)) { cname <- paste0("BcZ", stub, ".df") rname <- paste0("BrZ", stub, ".df") crname <- paste0("BcrZ", stub, ".df") } else { cname <- "BcZ.df" rname <- "BrZ.df" crname <- "BcrZ.df" } mbftext <- paste0("list(TP.col=list(key=c(\"TP.col\",\"TP.col\"),cov=\"", cname, "\"),") mbftext <- paste0(mbftext, "TP.row=list(key=c(\"TP.row\",\"TP.row\"),cov=\"", rname, "\"),") mbftext <- paste0(mbftext, "TP.CxR=list(key=c(\"TP.CxR\",\"TP.CxR\"),cov=\"", crname, "\"))") mbflist <- eval(parse(text = mbftext)) if ("grp" %in% asreml) { grp <- list() listnames <- list() start <- length(outdata) start0 <- start scale <- 1 j <- 1 for (i in 1:diff.c) { nm0 <- paste0(names(fixed$col[i]), "_frow") listnames[j] <- nm0 for (k in 1:nbr) { nm <- paste0(nm0, "_", k) outdata[nm] <- scale * fixed$col[[i]] * BrZmat[row.match, k] } grp[[j]] <- seq(from = start + 1, to = start + nbr, by = 1) start <- start + nbr j <- j + 1 } for (i in 1:diff.r) { nm0 <- paste0(names(fixed$row[i]), "_fcol") listnames[j] <- nm0 for (k in 1:nbc) { nm <- paste0(nm0, "_", k) outdata[nm] <- scale * fixed$row[[i]] * BcZmat[col.match, k] } grp[[j]] <- seq(from = start + 1, to = start + nbc, by = 1) start <- start + nbc j <- j + 1 } m <- 0 nm0 <- "TP_fcol_frow" listnames[j] <- nm0 for (k in 1:(nbrn * nbcn)) { nm <- paste0(nm0, "_", k) outdata[nm] <- scale * BcrZmat[, k] } grp[[j]] <- seq(from = start + 1, to = start + (nbcn * nbrn), by = 1) end <- start + (nbcn * nbrn) j <- j + 1 listnames[j] <- "All" grp[[j]] <- seq(from = start0 + 1, to = end, by = 1) grp <- structure(grp, names = listnames) } if ("sepgrp" %in% asreml) { grp <- list() listnames <- list() start <- length(outdata) nm0 <- "TP_C" listnames[1] <- nm0 for (i in 1:diff.c) { nm <- paste0(nm0, "_", i) outdata[nm] <- fixed$col[[i]] } grp[[1]] <- seq(from = start + 1, to = start + diff.c, by = 1) start <- start + diff.c nm0 <- "TP_R" listnames[2] <- nm0 for (i in 1:diff.r) { nm <- paste0(nm0, "_", i) outdata[nm] <- fixed$row[[i]] } grp[[2]] <- seq(from = start + 1, to = start + diff.r, by = 1) start <- start + diff.r nm0 <- "TP_fcol" listnames[3] <- nm0 for (k in 1:nbc) { nm <- paste0(nm0, "_", k) outdata[nm] <- BcZmat[col.match, k] } grp[[3]] <- seq(from = start + 1, to = start + nbc, by = 1) start <- start + nbc nm0 <- "TP_frow" listnames[4] <- nm0 for (k in 1:nbr) { nm <- paste0(nm0, "_", k) outdata[nm] <- BrZmat[row.match, k] } grp[[4]] <- seq(from = start + 1, to = start + nbr, by = 1) start <- start + nbr grp <- structure(grp, names = listnames) nm0 <- "TP_fcol_frow" listnames[5] <- nm0 for (k in 1:(nbrn * nbcn)) { nm <- paste0(nm0, "_", k) outdata[nm] <- BcrZmat[, k] } grp[[5]] <- seq(from = start + 1, to = start + (nbcn * nbrn), by = 1) grp <- structure(grp, names = listnames) } if ("own" %in% asreml) { grp <- list() listnames <- list() listnames[1] <- "All" start <- length(outdata) nm0 <- "Xc_Zr" Xc_Zr <- (BcX[col.match, ] %x% matrix(rep(1, nbr), nrow = 1)) * (matrix(rep(1, diff.c), nrow = 1) %x% BrZmat[row.match, ]) nXc_Zr <- ncol(Xc_Zr) for (i in 1:nXc_Zr) { nm <- paste0(nm0, "_", i) outdata[nm] <- Xc_Zr[, i] } nm0 <- "Zc_Xr" Zc_Xr <- (BcZmat[col.match, ] %x% matrix(rep(1, diff.r), nrow = 1)) * (matrix(rep(1, nbc), nrow = 1) %x% BrX[row.match, ]) nZc_Xr <- ncol(Zc_Xr) for (i in 1:nZc_Xr) { nm <- paste0(nm0, "_", i) outdata[nm] <- Zc_Xr[, i] } nm0 <- "Zc_Zr" Zc_Zr <- BcrZmat nZc_Zr <- ncol(Zc_Zr) for (i in 1:nZc_Zr) { nm <- paste0(nm0, "_", i) outdata[nm] <- Zc_Zr[, i] } grp[[1]] <- seq(from = start + 1, to = start + nXc_Zr + nZc_Xr + nZc_Zr, by = 1) grp <- structure(grp, names = listnames) } res <- list() res$data <- outdata res$mbflist <- mbflist res[["BcZ.df"]] <- BcZmat.df res[["BrZ.df"]] <- BrZmat.df res[["BcrZ.df"]] <- BcrZmat.df res$dim <- c(diff.c = diff.c, nbc = nbc, nbcn = nbcn, diff.r = diff.r, nbr = nbr, nbrn = nbrn) res$trace <- tracelist if ("grp" %in% asreml) res$grp <- grp if ("sepgrp" %in% asreml) res$grp <- grp if ("own" %in% asreml) res$grp <- grp if ("mbf" %in% asreml) res$grp <- NULL if (!("include" %in% eigenvalues)) res$eigen <- list(diagc = diagc, diagr = diagr, diagcr = diagcr) res } bbasis <- function (x, xl, xr, ndx, deg) { tpower <- function(x, t, p) { (x - t)^p * (x > t) } dx <- (xr - xl)/ndx knots <- seq(xl - deg * dx, xr + deg * dx, by = dx) P <- outer(x, knots, tpower, deg) n <- dim(P)[2] D <- diff(diag(n), diff = deg + 1)/(gamma(deg + 1) * dx^deg) B <- (-1)^(deg + 1) * P %*% t(D) B }
polar_init <- function(data, x, ...) { stopifnot(is.data.frame(data)) data$y <- 1L calls <- lapply(as.list(match.call()), function(x) { if (is.symbol(x)) as.character(x) else x }) stopifnot(!is.null(calls$x)) ggplot(data, aes_string(calls$x, "y")) + geom_point(...) + coord_polar() + expand_limits(y = c(0, 1)) + theme( axis.text.y = element_blank(), axis.line.y = element_blank(), axis.ticks.y = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank() ) + labs(y = NULL, x = NULL) } polar_connect <- function(data, x1, x2, ...) { stopifnot(is.data.frame(data)) calls <- lapply(as.list(match.call()), function(x) { if (is.symbol(x)) as.character(x) else x }) stopifnot(!is.null(calls$x1), !is.null(calls$x2)) aes_args <- list( x = calls$x1, y = 1, xend = calls$x2, yend = 1 ) alist <- calls[setdiff(names(calls), c("x1", "x2", "", "data"))] if (length(alist) > 0) { dot_list <- alist aes_appends <- sapply(alist, function(x) { x %in% colnames(data) }) if (sum(aes_appends) > 0) { aes_args <- c(aes_args, alist[aes_appends]) dot_list <- alist[!aes_appends] } } else { dot_list <- list(...) } my_aes <- do.call("aes_string", aes_args) do.call("geom_segment_straight", args = c( list( mapping = my_aes, data = data ), dot_list ) ) }
.groupByDistrict <- function(x, opts, fun = c(sum)) { x <- merge(x, opts$districtsDef, by = "area", allow.cartesian = TRUE) areasInData <- unique(x$area) districts <- intersect(x$district, opts$districtsDef$district) districtsDef <- split(opts$districtsDef$area, opts$districtsDef$district) for (d in districts) { missingAreas <- setdiff(districtsDef[[d]], areasInData) if (length(missingAreas) > 0) warning("The following areas belongs to district ", d, " but are not in 'x': ", paste(missingAreas, collapse = ", ")) } x[, area := NULL] idVars <- .idCols(x) if (length(fun) == 1) fun <- rep(fun, ncol(x) - length(idVars)) x[, mapply(function(x, f) {f(x)}, x = .SD, f = fun, SIMPLIFY=FALSE), by = idVars] } .merge_Col_Area_D <- function(x = NULL, colMerge = NULL, opts=NULL, allX = TRUE){ if (!is.null(x$districts)){ for(oneCol in colMerge){ byarea <- .get_by_area(x) bydistrict <- .get_by_district(x) ColAreas <- x$areas[, mget(oneCol), by = byarea] ColDistricts <- .groupByDistrict(ColAreas, opts) class(ColDistricts) <- c("data.table", "data.frame") if(!(oneCol %in% names(x$districts))){ x$districts <- merge(x$districts, ColDistricts, by = bydistrict) }else{ x$districts <- merge(x$districts, ColDistricts, by = bydistrict, all.x = allX, all.y = !allX) } if(paste0(oneCol,".x") %in% names(x$districts)){ if(!(oneCol %in% names(x$districts))){ if(allX){ x$districts[, c(oneCol):= get(paste0(oneCol,".x"))] }else{ x$districts[, c(oneCol):= get(paste0(oneCol,".y"))] } } x$districts[, c(paste0(oneCol,".x")) := NULL] x$districts[, c(paste0(oneCol,".y")) := NULL] } } } return(x) }
{} stepArchetypes <- function(..., k, nrep = 3, method = archetypes, verbose = TRUE) { mycall <- match.call() as <- list() for ( i in 1:length(k) ) { as[[i]] <- list() class(as[[i]]) <- 'repArchetypes' for ( j in seq_len(nrep) ) { if ( verbose ) cat('\n*** k=', k[i], ', rep=', j, ':\n', sep='') as[[i]][[j]] <- method(..., k=k[i]) } } return(structure(as, class='stepArchetypes', call=mycall)) } setOldClass('repArchetypes') setOldClass('stepArchetypes') `[.stepArchetypes` <- function(x, i) { y <- unclass(x)[i] attributes(y) <- attributes(x) return(y) } print.stepArchetypes <- function(x, ...) { cat('StepArchetypes object\n\n') cat(deparse(attr(x, 'call')), '\n') } summary.stepArchetypes <- function(object, ...) { print(object) ps <- nparameters(object) for ( i in seq_along(object) ) { cat('\nk=', ps[i], ':\n', sep='') print(object[[i]], full=FALSE) } } setMethod('parameters', signature = c(object = 'stepArchetypes'), function(object, ...) { lapply(object, parameters) }) nparameters.stepArchetypes <- function(object, ...) { return(sapply(object, nparameters)) } rss.stepArchetypes <- function(object, ...) { ret <- t(sapply(object, rss)) rownames(ret) <- paste('k', nparameters(object), sep='') return(ret) } bestModel.stepArchetypes <- function(object, ...) { zsmin <- lapply(object, bestModel) if ( length(zsmin) == 1 ) return(zsmin[[1]]) else return(zsmin) } print.repArchetypes <- function(x, ...) { for ( i in seq_along(x) ) print(x[[i]], ...) invisible(x) } setMethod('parameters', signature = signature(object = 'repArchetypes'), function(object, ...) { lapply(object, parameters) }) rss.repArchetypes <- function(object, ...) { ret <- sapply(object, rss) names(ret) <- paste('r', seq_along(ret), sep='') return(ret) } nparameters.repArchetypes <- function(object, ...) { nparameters(object[[1]]) } bestModel.repArchetypes <- function(object, ...) { m <- which.min(rss(object)) if ( length(m) == 0 ) return(object[[1]]) else return(object[[m]]) }
search_and_replace_in_source <- function(input, replacements = NULL, output = NULL, preventOverwriting = TRUE, encoding = "UTF-8", rlWarn = rock::opts$get(rlWarn), silent=FALSE) { if (file.exists(input)) { res <- readLines(input, encoding=encoding, warn = rlWarn); } else { res <- input; } if (is.null(replacements)) { stop("You have to specify one or more replacements. Specify them in a list ", "containing vectors that each have two elements. The first is the ", "regular expression to search for; the second is the replacement. For ", "example:\n\n", "replacements=list(c('firstStringToLookFor', 'firstReplacement'),\n", " c('secondStringToLookFor', 'secondReplacement'))\n\n", "Also see the examples in the manual, which you can view with:\n\n", "?rock::search_and_replace_in_source\n"); } else { for (i in seq_along(replacements)) { res <- gsub(replacements[[i]][1], replacements[[i]][2], res, perl=TRUE); } } if (is.null(output)) { attr(res, "output") <- "returned"; return(res); } else { if (!dir.exists(dirname(output))) { stop("The directory specified where the output file '", basename(output), "' is supposed to be written ('", dirname(output), "') does not exist."); } if (file.exists(output) && preventOverwriting) { if (!silent) { message("File '", output, "' exists, and `preventOverwriting` was `TRUE`, so I did not ", "write the 'post-search-replace-source' to disk."); } attr(res, "output") <- "existed"; } else { con <- file(description=output, open="w", encoding=encoding); writeLines(text=res, con=con); close(con); attr(res, "output") <- "written"; } if (!silent) { message("I just wrote a 'post-search-replace-source' to file '", output, "'. Note that this file may be overwritten if this ", "script is ran again (unless `preventOverwriting` is set to `TRUE`). ", "Therefore, make sure to copy it to ", "another directory, or rename it, before starting to code this source!"); } return(invisible(res)); } }
dt1 <- simulation_model1(seed = 50) test_that("linfinity handles strange data", { expect_error(linfinity_depth(dt = list())) expect_error(linfinity_depth(dt = data.frame()) ) expect_error(linfinity_depth(dt = matrix(NA, nrow = 1, ncol = 3))) expect_error(linfinity_depth(dt = matrix(c(1:2, NA), nrow = 1, ncol = 3))) }) test_that("linfinity_depth gives correct result", { linda <- linfinity_depth(dt1$data) expect_equal(order(linda)[1:10], c(43, 53, 70, 20, 96, 36, 14, 3, 18, 16)) expect_equal(order(linda)[90:100], c(24, 74, 87, 25, 34, 83, 80, 76, 23, 90, 47)) })
mixbeta <- function(..., param=c("ab", "ms", "mn")) { mix <- mixdist3(...) param <- match.arg(param) mix[c(2,3),] <- switch(param, ab=mix[c(2,3),], ms=t(ms2beta(mix[2,], mix[3,], FALSE)), mn=t(mn2beta(mix[2,], mix[3,], FALSE))) rownames(mix) <- c("w", "a", "b") assert_that(all(mix["a",]>=0)) assert_that(all(mix["b",]>=0)) class(mix) <- c("betaMix", "mix") likelihood(mix) <- "binomial" mix } ms2beta <- function(m, s, drop=TRUE) { n <- m*(1-m)/s^2 - 1 assert_that(all(n>=0)) ab <- cbind(a=n*m, b=n*(1-m)) if(drop) ab <- drop(ab) ab } mn2beta <- function(m, n, drop=TRUE) { assert_that(all(n>=0)) ab <- cbind(a=n*m, b=n*(1-m)) if(drop) ab <- drop(ab) ab } print.betaMix <- function(x, ...) { cat("Univariate beta mixture\n") NextMethod() } print.betaBinomialMix <- function(x, digits=NULL, ...) { cat("Univariate beta binomial mixture\nn = ", attr(x, "n"),"\n", sep="") NextMethod() } summary.betaMix <- function(object, probs=c(0.025,0.5,0.975), ...) { p <- object[1,] a <- object[2,] b <- object[3,] m <- a/(a+b) v <- m*(1-m)/(a+b+1) m2 <- v + m^2 mmix <- sum(p * m) vmix <- sum(p * (m2 - (mmix)^2) ) q <- c() if(length(probs) != 0) { q <- qmix.betaMix(object, p=probs) names(q) <- paste(format(probs*100,digits=2), "%", sep="") } c(mean=mmix, sd=sqrt(vmix), q) } summary.betaBinomialMix <- function(object, probs=c(0.025,0.5,0.975), ...) { n <- attr(object, "n") p <- object[1,] a <- object[2,] b <- object[3,] m <- n * a/(a+b) v <- n*a*b*(a+b+n)/( (a+b)^2 * ( a + b + 1 ) ) m2 <- v + m^2 mmix <- sum(p * m) vmix <- sum(p * (m2 - (mmix)^2) ) q <- qmix.betaBinomialMix(object, p=probs) if(length(q) != 0) names(q) <- paste(format(probs*100,digits=2), "%", sep="") c(mean=mmix, sd=sqrt(vmix), q) }
check_names <- function(x, names = character(0), exclusive = FALSE, order = FALSE, x_name = NULL) { chk_s3_class(names, "character") chk_unique(names) chk_not_any_na(names) chk_flag(exclusive) chk_flag(order) if (is.null(x_name)) x_name <- deparse_backtick_chk((substitute(x))) chk_string(x_name) chk_named(x, x_name = x_name) x_names <- names(x) if (!length(names)) { if (exclusive && length(x_names)) { abort_chk(x_name, " must not have any elements") } return(invisible(x)) } x_name <- backtick_chk(p0("names(", unbacktick_chk(x_name), ")")) if (length(setdiff(names, x_names))) { abort_chk(x_name, " must include ", cc(setdiff(names, x_names), conj = " and ")) } if (exclusive && length(setdiff(x_names, names))) { abort_chk(x_name, " must not include ", cc(setdiff(x_names, names), conj = " or ")) } if (order && !identical(intersect(names, x_names), intersect(x_names, names))) { abort_chk(x_name, " must include ", cc(names, conj = " and "), " in that order") } invisible(x) }
bicubic <- function(x,y,z,x0,y0){ nx <- length(x) ny <- length(y) if(dim(z)[1]!=nx) stop("dim(z)[1] and length of x differs!") if(dim(z)[2]!=ny) stop("dim(z)[2] and length of y differs!") n0 <- length(x0) if(length(y0)!=n0) stop("length of y0 and x0 differs!") ret <- .Fortran("rgbi3p", md=as.integer(1), nxd=as.integer(nx), nyd=as.integer(ny), xd=as.double(x), yd=as.double(y), zd=as.double(z), nip=as.integer(n0), xi=as.double(x0), yi=as.double(y0), zi=double(n0), ier=integer(1), wk=double(3*nx*ny), PACKAGE="akima") list(x=x0,y=y0,z=ret$zi) } bicubic.grid <- function(x,y,z,xlim=c(min(x),max(x)),ylim=c(min(y),max(y)), nx=40,ny=40,dx=NULL,dy=NULL){ Nx <- length(x) Ny <- length(y) if(dim(z)[1]!=Nx) stop("dim(z)[1] and length of x differs!") if(dim(z)[2]!=Ny) stop("dim(z)[2] and length of y differs!") if(!is.null(dx)){ xi <- seq(xlim[1],xlim[2],by=dx) nx <- length(xi) } else { xi <- seq(ylim[1],ylim[2],length=nx) } if(!is.null(dx)){ yi <- seq(ylim[1],ylim[2],by=dy) ny <- length(yi) } else { yi <- seq(ylim[1],ylim[2],length=ny) } xmat <- matrix(rep(xi,ny),nrow=ny,ncol=nx,byrow=TRUE) ymat <- matrix(rep(yi,nx),nrow=ny,ncol=nx,byrow=FALSE) xy <- cbind(c(xmat),c(ymat)) n0 <- nx*ny ret <- bicubic(x,y,z,xy[,1],xy[,2]) list(x=xi,y=yi,z=t(matrix(ret$z,nrow=ny,ncol=nx,byrow=F))) }
diveR_packages <- function(include_self = TRUE) { raw <- utils::packageDescription("diveR")$Imports imports <- strsplit(raw, ",")[[1]] parsed <- gsub("^\\s+|\\s+$", "", imports) names <- vapply(strsplit(parsed, "\\s+"), "[[", 1, FUN.VALUE = character(1)) names <- setdiff(names, presentationPackages()) if (include_self) { names <- c(names, "diveR") } names } msg <- function(..., startup = FALSE) { if (startup) { if (!isTRUE(getOption("diveR.quiet"))) { packageStartupMessage(text_col(...)) } } else { message(text_col(...)) } } text_col <- function(x) { if (!rstudioapi::isAvailable()) { return(x) } if (!rstudioapi::hasFun("getThemeInfo")) { return(x) } theme <- rstudioapi::getThemeInfo() if (isTRUE(theme$dark)) crayon::white(x) else crayon::black(x) } invert <- function(x) { if (length(x) == 0) return() stacked <- utils::stack(x) tapply(as.character(stacked$ind), stacked$values, list) } style_grey <- function(level, ...) { crayon::style( paste0(...), crayon::make_style(grDevices::grey(level), grey = TRUE) ) }
vowelsynth = function (ffs = c(270, 2200, 2800, 3400, 4400), fbw = 0.06, dur = 300, f0 = c(120,100), fs = 10000, verify = FALSE, returnsound = TRUE, noise1 = .001, noise2 = .01, power = NULL){ if (dur < 50) stop ('Duration must be at least 50 ms.') if (length (f0) > 2) stop ('Only initial and final f0 may be specified.') T = 1/fs n = round(dur/1000/T) if (!is.null(power)) n = length(power) if (is.numeric (nrow(ffs))) n = nrow(ffs) if (length(f0) == 1) f0 = c(f0,f0) f0 = exp(seq (log(f0[1]), log(f0[2]), length.out = n)) vsource = NULL spot = 1 while (length (vsource) < n*5){ tmp = f0[spot] cycle = round(fs/tmp) tmp = 2*seq (0,1, 1/(cycle*4)) - 3*seq (0,1, 1/(cycle*4))^2 tmp = c(rep (0, cycle), tmp) vsource = c(vsource, tmp) spot = spot + cycle } vsource = resample (vsource, fs, fs*5, synthfilter = TRUE) vsource = vsource + rnorm (length(vsource), sd = sd(vsource)*noise1) vsource = vsource[1:n] vsource = jitter(vsource) vsource = preemphasis (vsource, coeff = .94) x = c(1, 10 / (1000/fs), 20 / (1000/fs), n-(30 / (1000/fs)), n) if (is.null(power)) power = interpolate (x, y = c(30,55, 60,55,30), increment = 1, type = 'linear')[1:n,2] power = 10^(power/20) power = jitter(power, factor = 0.01) vsource = vsource * power output = Ffilter (vsource, ffs = ffs, fs = fs, verify = FALSE, bwp = fbw) output = output * power output = output + rnorm (length(output), sd = sd(output)*noise2) output = output /(max(abs(output)) * 1.05) if (verify == TRUE) { par (mfrow = c(2,1), mar = c(4,4,1,1)) plot ((1:n)*T*1000,output, ylab = 'Amplitude', xlab = 'Time (ms)', type = 'l', xaxs = 'i') abline (h = 0, lty = 'dotted') spectrogram (output, fs = fs, dynamicrange = 60) } if (returnsound == TRUE) output = makesound(output, "sound.wav", fs = fs) return(output) }
shiny::validate(shiny::need( check_regexes(c(search_arguments$highlight_terms, search_arguments$subset_terms)) , paste("\nInvalid regular expression. Please modify your search.") )) shiny::validate(need( check_valid_column_names(search_arguments$subset_custom_column, sv$subset) , paste("Make sure to specify only variables present in the corpus.") )) shiny::validate(need( contains_argument(search_arguments$highlight_terms) == FALSE , paste('Search arguments ("--") work only for subsetting.') )) shiny::validate(need( contains_only_valid_thresholds(isolate(collect_subset_terms())) , paste( 'Treshold argument invalid. Make sure it contains only numbers, e.g. "--4".' ) )) if (nrow(sv$subset) > 0) { shinyjs::enable("download_txt") shinyjs::enable("download_zip") if (nrow(sv$subset) <= MAX_DOCS_FOR_HTML) { shinyjs::enable("download_html") } }
{ library(vroom) data <- vroom(file, col_types = c(pickup_datetime = "c")) vroom:::vroom_materialize(data, replace = TRUE) } vroom_write(data, pipe(sprintf("pigz > %s", tempfile(fileext = ".gz"))), delim = "\t")
editor <- aceEditor("rmd", mode = "markdown", wordWrap = TRUE, fontSize = getOption("editR")$editor_font_size, theme = getOption("editR")$editor_theme, debounce = 100, autoComplete = "live", height = "auto")
expected <- eval(parse(text="structure(list(`Surv(stop, status * as.numeric(event), type = \"mstate\")` = NULL), .Names = \"Surv(stop, status * as.numeric(event), type = \\\"mstate\\\")\", class = \"data.frame\", row.names = c(NA, 300L))")); test(id=0, code={ argv <- eval(parse(text="list(structure(list(`Surv(stop, status * as.numeric(event), type = \"mstate\")` = structure(c(760, 2160, 5441, 277, 1815, 2587, 547, 1125, 2010, 2422, 6155, 1767, 61, 60, 7807, 7732, 6126, 7921, 3590, 5231, 5384, 5934, 6415, 6789, 6778, 3561, 4505, 3987, 4726, 5550, 5216, 5757, 2345, 6931, 6760, 5796, 4810, 5143, 3091, 3316, 700, 1706, 5088, 944, 2466, 1706, 7364, 1857, 9510, 9603, 31, 7479, 2006, 2588, 2983, 8761, 3932, 4201, 5293, 273, 2223, 4249, 5308, 8327, 499, 5789, 7417, 3242, 3275, 10359, 10852, 362, 9993, 1795, 3562, 4139, 4840, 4959, 547, 4119, 8308, 1674, 2953, 3776, 1369, 7911, 7519, 9318, 4370, 7301, 1642, 4169, 7417, 6117, 4536, 7235, 6723, 7397, 7428, 2084, 4066, 1673, 2860, 0, 3773, 4810, 4206, 2314, 4065, 8961, 6143, 517, 3837, 7498, 2815, 8806, 7668, 12457, 8600, 7003, 2435, 1826, 2403, 3805, 4901, 365, 6642, 3318, 3012, 1431, 2223, 4962, 5982, 638, 3346, 4996, 6800, 7454, 8887, 5024, 2833, 4232, 5238, 3186, 3380, 3382, 8100, 1766, 7184, 8059, 6008, 5047, 2236, 8165, 4224, 2844, 6256, 7370, 3560, 4939, 4941, 2230, 3068, 152, 10122, 3226, 3943, 518, 8569, 845, 2099, 8006, 8052, 9560, 0, 7965, 7470, 8133, 809, 153, 1851, 3010, 2121, 7085, 5068, 7093, 5930, 6878, 8080, 791, 6626, 3962, 1116, 1249, 9257, 1077, 566, 174, 4627, 5022, 2070, 3012, 1625, 6607, 8381, 8389, 1005, 3895, 4236, 6970, 8497, 2861, 8487, 3227, 8030, 8023, 31, 2435, 518, 4758, 7958, 7884, 4453, 6349, 7862, 1392, 3167, 6025, 4656, 1767, 7736, 2678, 2191, 3658, 7758, 8009, 2556, 3511, 7954, 822, 4321, 5151, 7545, 7576, 32, 7875, 5236, 7106, 2802, 7898, 3014, 7867, 5354, 2989, 7555, 6089, 8697, 6479, 1826, 5917, 792, 1431, 1434, 4763, 2910, 6209, 5824, 2400, 1400, 3027, 7198, 7247, 2557, 3855, 61, 7410, 1492, 7160, 7899, 5181, 7280, 3448, 7381, 2434, 6763, 7065, 1218, 1554, 7533, 7288, 2922, 5988, 2495, 5234, 9598, 2953, 2961, 4539, 3775, 6524, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 1, 2, 1, 2, 2, 1, 2, 1, 2, 1, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 1, 2, 1, 2, 2, 1, 2, 2, 0, 2, 1, 2, 2, 0, 2, 1, 2, 0, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 0, 1, 2, 1, 2, 2, 0, 1, 2, 1, 2, 2, 2, 2, 0, 2, 1, 2, 2, 0, 1, 2, 2, 0, 1, 2, 0, 2, 1, 2, 2, 1, 2, 1, 2, 2, 2, 2, 1, 2, 2, 1, 2, 0, 2, 2, 1, 0, 2, 2, 0, 0, 2, 0, 2, 1, 2, 1, 2, 2, 2, 2, 2, 1, 2, 1, 2, 2, 1, 2, 1, 0, 0, 2, 2, 1, 2, 2, 1, 2, 0, 2, 1, 2, 2, 2, 2, 0, 2, 2, 2, 0, 2, 1, 2, 1, 2, 2, 0, 2, 2, 2, 0, 2, 2, 1, 2, 0, 2, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 0, 2, 2, 2, 1, 2, 0, 2, 2, 2, 1, 2, 1, 2, 2, 2, 0, 0, 2, 1, 2, 1, 0, 1, 0, 2, 0, 0, 2, 2, 2, 2, 0, 0, 2, 2, 0, 2, 2, 2, 2, 2, 0, 2, 1, 2, 0, 0, 1, 2, 0, 2, 1, 2, 1, 2, 2, 0, 1, 2, 1, 0, 2, 0, 2, 2, 0, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1, 2, 0, 0, 1, 2, 2, 0, 2, 0, 2, 2, 0, 2, 0, 2, 2, 0, 1, 2, 0, 0, 1, 2, 1, 2, 0, 1, 2, 2, 1, 2), .Dim = c(300L, 2L), .Dimnames = list(NULL, c(\"time\", \"status\")), type = \"mright\", states = c(\"1\", \"2\"), class = \"Surv\")), .Names = \"Surv(stop, status * as.numeric(event), type = \\\"mstate\\\")\", class = \"data.frame\", row.names = c(NA, 300L)), structure(list(`Surv(stop, status * as.numeric(event), type = \"mstate\")` = NULL), .Names = \"Surv(stop, status * as.numeric(event), type = \\\"mstate\\\")\", class = \"data.frame\", row.names = c(NA, 300L)))")); .Internal(copyDFattr(argv[[1]], argv[[2]])); }, o=expected);
context("coefficients.bas") test_that("coefficients", { data("Hald") hald_gprior <- bas.lm(Y ~ ., data = Hald, prior = "ZS-null", modelprior = beta.binomial(1, 1)) expect_is(coefficients(hald_gprior), "coef.bas") expect_length(coefficients(hald_gprior, estimator='MPM'),11) expect_equal("HPM", coefficients(hald_gprior, estimator='HPM')$estimator) expect_error(coefficients(hald_gprior, estimator='BPM')) expect_null(print(coefficients(hald_gprior, estimator="BMA"))) expect_equal(coefficients(hald_gprior, estimator='HPM')$postmean, coefficients(hald_gprior, estimator='BMA', n.models=1)$postmean) coef_hald <- coef(hald_gprior) confint_hald <- confint(coef_hald) expect_is(confint_hald, "confint.bas") expect_is(confint(coef_hald, approx=FALSE, nsim=5000), "confint.bas") expect_length(confint(coef_hald, parm="X4"), 3) expect_null(plot(confint(coef_hald, parm=2:5))) expect_null(plot(confint(coef(hald_gprior, estimator='HPM')))) expect_null(plot(confint(coef(hald_gprior, estimator='HPM')), horizontal = TRUE)) expect_error(confint(coef(hald_gprior), nsim=1)) }) test_that("plot posterior coefficients", { data(UScrime, package="MASS") UScrime[,-2] <- log(UScrime[,-2]) crime_bic <- bas.lm(y ~ ., data=UScrime, n.models=2^10, prior="BIC") crime_coef <- coef(crime_bic) expect_null(plot(crime_coef, subset=2:4, ask=TRUE)) expect_null(plot(crime_coef, ask=FALSE)) })
library(sf) library(raster) library(dplyr) library(stringr) library(spData) dim(world) nrow(world) ncol(world) world_df = st_set_geometry(world, NULL) class(world_df) sel_area = world$area_km2 < 10000 summary(sel_area) small_countries = world[sel_area, ] small_countries = world[world$area_km2 < 10000, ] world1 = dplyr::select(world, name_long, pop) names(world1) world2 = dplyr::select(world, name_long:pop) world3 = dplyr::select(world, -subregion, -area_km2) world4 = dplyr::select(world, name_long, population = pop) names(world4) operators = c("`==`", "`!=`", "`>, <`", "`>=, <=`", "`&, |, !`") operators_exp = c("Equal to", "Not equal to", "Greater/Less than", "Greater/Less than or equal", "Logical operators: And, Or, Not") knitr::kable(tibble(Symbol = operators, Name = operators_exp), caption = paste("Comparison operators that return Booleans", "(TRUE/FALSE)."), caption.short = "Comparison operators that return Booleans.", booktabs = TRUE) world7 = world %>% filter(continent == "Asia") %>% dplyr::select(name_long, continent) %>% slice(1:5) world8 = slice( dplyr::select( filter(world, continent == "Asia"), name_long, continent), 1:5) world_agg1 = aggregate(pop ~ continent, FUN = sum, data = world, na.rm = TRUE) class(world_agg1) world_agg2 = aggregate(world["pop"], by = list(world$continent), FUN = sum, na.rm = TRUE) class(world_agg2) world_agg3 = world %>% group_by(continent) %>% summarize(pop = sum(pop, na.rm = TRUE)) options(scipen = 999) world %>% dplyr::select(pop, continent) %>% group_by(continent) %>% summarize(pop = sum(pop, na.rm = TRUE), n_countries = n()) %>% top_n(n = 3, wt = pop) %>% st_set_geometry(value = NULL) %>% knitr::kable(caption = paste("The top 3 most populous continents,", "and the number of countries in each."), caption.short = "Top 3 most populous continents.", booktabs = TRUE) world_coffee = left_join(world, coffee_data) class(world_coffee) names(world_coffee) plot(world_coffee["coffee_production_2017"]) coffee_renamed = rename(coffee_data, nm = name_long) world_coffee2 = left_join(world, coffee_renamed, by = c(name_long = "nm")) world_coffee_inner = inner_join(world, coffee_data) nrow(world_coffee_inner) setdiff(coffee_data$name_long, world$name_long) str_subset(world$name_long, "Dem*.+Congo") coffee_data$name_long[grepl("Congo,", coffee_data$name_long)] = str_subset(world$name_long, "Dem*.+Congo") world_coffee_match = inner_join(world, coffee_data) nrow(world_coffee_match) coffee_world = left_join(coffee_data, world) class(coffee_world) world_new = world world_new$pop_dens = world_new$pop / world_new$area_km2 world_data = world %>% st_set_geometry(NULL) class(world_data) library(spData) data("elev") data("grain") levels(grain)[[1]] = cbind(levels(grain)[[1]], wetness = c("wet", "moist", "dry")) levels(grain) factorValues(grain, grain[c(1, 11, 35)]) source("https://github.com/Robinlovelace/geocompr/raw/main/code/03-cont-raster-plot.R", print.eval = TRUE) elev[1, 1] = 0 elev[] elev[1, 1:2] = 0 library(spData) data(us_states) data(us_states_df)
expect_error(anyOutside(1:10, "a"), "character") expect_error(anyOutside(1:10, 3L, "c"), "character") expect_error(anyOutside(1:10, 1L, 10L, nas_absent = ""), "logical") expect_error(anyOutside(1:10, 1L, 10L, nas_absent = c(TRUE, FALSE)), "length") expect_error(anyOutside(1:10, 1, 10.5)) expect_identical(anyOutside(1:10, 1L, 10L), 0L) expect_identical(anyOutside(1:10, 1L, 1L), 2L) expect_identical(anyOutside(1:10, 10L, 1L), 1L) expect_identical(anyOutside(1:10, 4L, 5L), 1L) expect_identical(anyOutside(1:10, 1L, 5L), 6L) expect_identical(anyOutside(seq(0, 1, length.out = 5), 0, 1), 0L) expect_identical(anyOutside(seq(0, 1, length.out = 5), 0.9, 1), 1L) expect_identical(anyOutside(NULL), 0L) expect_identical(anyOutside(1:10 + 0, 1, 5), 6L) expect_identical(anyOutside(c(1:5, NA_real_), 1, 5), NA_integer_) expect_identical(anyOutside(c(1:5, NA_real_), 1, 5, na_is_outside = TRUE), 6L) expect_identical(anyOutside(c(1:5, NA_real_), 1, 5, na_is_outside = FALSE), 0L) expect_identical(anyOutside(c(NA, 1L), 1L, 2L), NA_integer_) expect_identical(anyOutside(c(NA, 1L), 1L, 2L, nas_absent = FALSE), NA_integer_) expect_identical(anyOutside(c(NA, 1L), 1L, 2L, nas_absent = FALSE, na_is_outside = FALSE), 0L) expect_identical(anyOutside(c(NA, 1L, 4L), 1L, 2L, na_is_outside = FALSE), 3L) expect_identical(anyOutside(c(NA, 1L, 4L), 1L, 2L, nas_absent = FALSE, na_is_outside = TRUE), 1L) expect_identical(anyOutside(c(1L, 4L, 3L), -1L, 5L, nas_absent = TRUE), 0L) expect_identical(anyOutside(c(1L, 4L, 3L), -1L, 5L, nas_absent = TRUE, na_is_outside = FALSE), 0L) expect_identical(anyOutside(c(1L, 4L, 3L), -1L, 5L, nas_absent = TRUE, na_is_outside = TRUE), 0L) expect_identical(anyOutside(c(1L, 4L, 3 ), -1 , 5 , nas_absent = TRUE, na_is_outside = TRUE), 0L) expect_identical(anyOutside(c(NA, 1L, 9L), 1L, 10L, na_is_outside = NA), NA_integer_) expect_identical(anyOutside(c(NA, 1L, 9L), 1L, 10L, na_is_outside = TRUE), 1L) expect_identical(anyOutside(c(NA, 1L, 9L), 1L, 10L, na_is_outside = FALSE), 0L) expect_identical(anyOutside(c(1:10, NA), 1L, 7L), 8L) dbl_1na5 <- as.double(c(1:5, NA, 5)) expect_identical(anyOutside(dbl_1na5, 1, 5, na_is_outside = FALSE), 0L) expect_identical(anyOutside(dbl_1na5, 1, 5), NA_integer_) expect_identical(anyOutside(dbl_1na5, 1, 4), 5L) expect_identical(anyOutside(dbl_1na5, 1, 4, nas_absent = FALSE, na_is_outside = FALSE), 5L) expect_identical(anyOutside(dbl_1na5, 1, 5, nas_absent = FALSE, na_is_outside = FALSE), 0L)
lilikoi.Loaddata<-function(filename){ Metadata <- read.csv(file=filename,check.names=F,row.names=1) dataSet <- list() dataSet$cmpd<-(colnames(Metadata)[-1]) newList <- list("Metadata"=Metadata, "dataSet"=dataSet) return(newList) }
PlotCGBN <- function(tree.1, tree.2, fontsize=NULL, pbar=FALSE, plotting=TRUE, epsilon = 10^-6) { dag <- tree.1@graph$dag node.class <- [email protected] absorbed.1 <- [email protected] absorbed.2 <- [email protected] absorbed <- union(absorbed.1, absorbed.2) var.inter <- intersect(absorbed.1, absorbed.2) var.1 <- setdiff(absorbed.1, var.inter) var.2 <- setdiff(absorbed.2, var.inter) vars <- absorbed node.names <- tree.1@node active.vars <- setdiff(node.names, vars) disc.all <- names(node.class)[node.class] cont.all <- names(node.class)[!node.class] disc.active <- intersect(disc.all, active.vars) cont.active <- intersect(cont.all, active.vars) all.active <- c(disc.active, cont.active) klds.0 <- c() sys <- Sys.info()[1] if(pbar){ if(sys=="Windows") { pb <- winProgressBar(title = "Computing posterior", min = 0, max = length(all.active), width = 300) } else { pb <- txtProgressBar(min = 0, max = length(all.active), style = 3) } } for (i in 1:length(all.active)){ if(pbar){ if(sys=="Windows") { setWinProgressBar(pb, i, title=paste("Computing posterior for ", all.active[i], ": ", round((i-1)/length(all.active)*100, 0), "% complete")) } else { setTxtProgressBar(pb, i) } } post.1 <- Marginals(tree.1, all.active[i]) post.2 <- Marginals(tree.2, all.active[i]) klds.0[i] <- SymmetricKLD(post.1[[1]][[1]], post.2[[1]][[1]], discrete = node.class[all.active[i]], epsilon = epsilon) } names(klds.0) <- all.active klds <- abs(klds.0) if(pbar){close(pb)} if (!plotting){ return(klds.0) } nAttrs <- list() node.shape <- c(rep("circle", (length(cont.all)) ), rep("box",(length(disc.all)) )) names(node.shape) <- c(cont.all, disc.all) nAttrs$shape <- node.shape if(!is.null(fontsize)){ nAttrs$fontsize <- rep(fontsize, length(node.names)) names(nAttrs$fontsize) <- node.names } max.kl <- max(klds) min.kl <- -max(klds) if (max.kl==0) { fill.post <- rep("white", length(klds.0)) } else { pseudo <- c(klds.0, -klds.0)/max.kl pseudo <- sign(pseudo)*abs(pseudo)^0.5 rbPal <- colorRampPalette(c('dodgerblue','white','red')) fill.post <- rbPal(100)[as.numeric(cut(pseudo,breaks = 100))] fill.post <- fill.post[1:length(klds.0)] } names(fill.post) <- all.active fill.1 <- rep("khaki", length(vars)) names(fill.1) <- var.1 fill.2 <- rep("orange", length(vars)) names(fill.2) <- var.2 fill.inter <- rep("gray", length(vars)) names(fill.inter) <- var.inter nAttrs$fillcolor <- c(fill.1, fill.2, fill.inter, fill.post) if(length(cont.active)>0){ par(oma=c(0,0,0,4)) graph_plot <- Rgraphviz::layoutGraph(dag, nodeAttrs=nAttrs) Rgraphviz::renderGraph(graph_plot) par(oma=c( 0,0,0,0.5)) color.bar(colorRampPalette(c("dodgerblue", "white", "red"))(1000), -signif(max.kl,1), sym=TRUE) } else { par(oma=c(0,0,0,4)) graph_plot <- Rgraphviz::layoutGraph(dag, nodeAttrs=nAttrs) Rgraphviz::renderGraph(graph_plot) par(oma=c( 0,0,0,0.5)) color.bar(colorRampPalette(c("white", "red"))(1000), min=0, max=signif(max.kl,1), sym=FALSE) } return(klds.0) } color.bar <- function(lut, min, max=-min, nticks=11, ticks=seq(min, max, len=nticks), title='', sym=TRUE) { scale = (length(lut)-1)/(max-min) n.half <- length(lut)/2 cl <- c() for (i in 1:(length(lut)-1)) { if (sym) { j <- n.half+1+sign(i-n.half)*(abs(i-n.half)/n.half)^0.5*n.half } else { j <- 1+(i/length(lut))^0.5*length(lut) } cl[i] <- lut[j] } image.plot(legend.only=TRUE, col=cl, zlim=c(min(ticks, na.rm=T), max(ticks, na.rm=T)), add=TRUE, horizontal=FALSE, legend.shrink=0.3, legend.cex=0.7, legend.lab=title) }
write_restart.SIPNET <- function(outdir, runid, start.time, stop.time, settings, new.state, RENAME = TRUE, new.params = FALSE, inputs) { rundir <- settings$host$rundir variables <- colnames(new.state) if (length(new.params$restart) > 0) { IC_extra <- data.frame(t(new.params$restart)) } else{ IC_extra <- data.frame() } if (RENAME) { file.rename(file.path(outdir, runid, "sipnet.out"), file.path(outdir, runid, paste0("sipnet.", as.Date(start.time), ".out"))) system(paste("rm", file.path(rundir, runid, "sipnet.clim"))) } else { print(paste("Files not renamed -- Need to rerun year", start.time, "before next time step")) } settings$run$start.date <- start.time settings$run$end.date <- stop.time prior.sla <- new.params[[which(!names(new.params) %in% c("soil", "soil_SDA", "restart"))[1]]]$SLA unit.conv <- 2 * (10000 / 1) * (1 / 1000) * (3.154 * 10^7) analysis.save <- list() if ("NPP" %in% variables) { analysis.save[[length(analysis.save) + 1]] <- udunits2::ud.convert(new.state$NPP, "kg/m^2/s", "Mg/ha/yr") names(analysis.save[[length(analysis.save)]]) <- c("NPP") } if ("NEE" %in% variables) { analysis.save[[length(analysis.save) + 1]] <- new.state$NEE names(analysis.save[[length(analysis.save)]]) <- c("NEE") } if ("AbvGrndWood" %in% variables) { AbvGrndWood <- udunits2::ud.convert(new.state$AbvGrndWood, "Mg/ha", "g/m^2") analysis.save[[length(analysis.save) + 1]] <- AbvGrndWood names(analysis.save[[length(analysis.save)]]) <- c("AbvGrndWood") analysis.save[[length(analysis.save) + 1]] <- IC_extra$abvGrndWoodFrac names(analysis.save[[length(analysis.save)]]) <- c("abvGrndWoodFrac") analysis.save[[length(analysis.save) + 1]] <- IC_extra$coarseRootFrac names(analysis.save[[length(analysis.save)]]) <- c("coarseRootFrac") analysis.save[[length(analysis.save) + 1]] <- IC_extra$fineRootFrac names(analysis.save[[length(analysis.save)]]) <- c("fineRootFrac") } if ("LeafC" %in% variables) { analysis.save[[length(analysis.save) + 1]] <- new.state$LeafC * prior.sla * 2 if (new.state$LeafC < 0) analysis.save[[length(analysis.save)]] <- 0 names(analysis.save[[length(analysis.save)]]) <- c("lai") } if ("Litter" %in% variables) { analysis.save[[length(analysis.save) + 1]] <- udunits2::ud.convert(new.state$Litter, 'kg m-2', 'g m-2') if (new.state$Litter < 0) analysis.save[[length(analysis.save)]] <- 0 names(analysis.save[[length(analysis.save)]]) <- c("litter") } if ("TotSoilCarb" %in% variables) { analysis.save[[length(analysis.save) + 1]] <- udunits2::ud.convert(new.state$TotSoilCarb, 'kg m-2', 'g m-2') if (new.state$TotSoilCarb < 0) analysis.save[[length(analysis.save)]] <- 0 names(analysis.save[[length(analysis.save)]]) <- c("soil") } if ("SoilMoistFrac" %in% variables) { analysis.save[[length(analysis.save) + 1]] <- new.state$SoilMoistFrac if (new.state$SoilMoistFrac < 0 || new.state$SoilMoistFrac > 1) analysis.save[[length(analysis.save)]] <- 0.5 names(analysis.save[[length(analysis.save)]]) <- c("litterWFrac") analysis.save[[length(analysis.save) + 1]] <- new.state$SoilMoistFrac if (new.state$SoilMoistFrac < 0 || new.state$SoilMoistFrac > 1) analysis.save[[length(analysis.save)]] <- 0.5 names(analysis.save[[length(analysis.save)]]) <- c("soilWFrac") } if ("SWE" %in% variables) { analysis.save[[length(analysis.save) + 1]] <- new.state$SWE/10 if (new.state$SWE < 0) analysis.save[[length(analysis.save)]] <- 0 names(analysis.save[[length(analysis.save)]]) <- c("snow") } if ("LAI" %in% variables) { analysis.save[[length(analysis.save) + 1]] <- new.state$LAI if (new.state$LAI < 0) analysis.save[[length(analysis.save)]] <- 0 names(analysis.save[[length(analysis.save)]]) <- c("lai") } if (!is.null(analysis.save) && length(analysis.save)>0){ analysis.save.mat <- data.frame(matrix(unlist(analysis.save, use.names = TRUE), nrow = 1)) colnames(analysis.save.mat) <- names(unlist(analysis.save)) }else{ analysis.save.mat <- NULL } print(runid %>% as.character()) print(analysis.save.mat) do.call(write.config.SIPNET, args = list(defaults = NULL, trait.values = new.params, settings = settings, run.id = runid, inputs = inputs, IC = analysis.save.mat)) print(runid) }
dopos <- function(pos, limits, width, height, side.legend, shift) { if(side.legend > 1L) limits <- rev(limits) shift <- c(diff(limits[[1]]), diff(limits[[2]])) * shift if(pos == "bottomleft") { xlim <- c(min(limits[[1L]], na.rm = TRUE), min(limits[[1L]], na.rm = TRUE) + width) + shift[1] ylim <- c(min(limits[[2L]], na.rm = TRUE), min(limits[[2L]], na.rm = TRUE) + height) + shift[2] } if(pos == "topleft") { xlim <- c(min(limits[[1L]], na.rm = TRUE), min(limits[[1L]], na.rm = TRUE) + width) + shift[1] ylim <- c(max(limits[[2L]], na.rm = TRUE) - height, max(limits[[2L]], na.rm = TRUE)) - shift[2] } if(pos == "topright") { xlim <- c(max(limits[[1L]], na.rm = TRUE) - width, max(limits[[1L]], na.rm = TRUE)) - shift[1] ylim <- c(max(limits[[2L]], na.rm = TRUE) - height, max(limits[[2L]], na.rm = TRUE)) - shift[2] } if(pos == "bottomright") { xlim <- c(max(limits[[1L]], na.rm = TRUE) - width, max(limits[[1L]], na.rm = TRUE)) - shift[1] ylim <- c(min(limits[[2L]], na.rm = TRUE), min(limits[[2L]], na.rm = TRUE) + height) + shift[2] } if(pos == "bottom") { m <- mean(limits[[1]] - min(limits[[1]], na.rm = TRUE), na.rm = TRUE) - 0.5 * width xlim <- c(min(limits[[1L]], na.rm = TRUE), min(limits[[1L]], na.rm = TRUE) + width) + m ylim <- c(min(limits[[2L]], na.rm = TRUE), min(limits[[2L]], na.rm = TRUE) + height) + shift[2] } if(pos == "top") { m <- mean(limits[[1]] - min(limits[[1]], na.rm = TRUE), na.rm = TRUE) - 0.5 * width xlim <- c(min(limits[[1L]], na.rm = TRUE), min(limits[[1L]], na.rm = TRUE) + width) + m ylim <- c(max(limits[[2L]], na.rm = TRUE) - height, max(limits[[2L]], na.rm = TRUE)) - shift[2] } if(pos == "left") { m <- mean(limits[[2]] - min(limits[[2]], na.rm = TRUE), na.rm = TRUE) - 0.5 * height xlim <- c(min(limits[[1L]], na.rm = TRUE), min(limits[[1L]], na.rm = TRUE) + width) + shift[1] ylim <- c(min(limits[[2L]], na.rm = TRUE), min(limits[[2L]], na.rm = TRUE) + height) + m } if(pos == "right") { m <- mean(limits[[2]] - min(limits[[2]], na.rm = TRUE), na.rm = TRUE) - 0.5 * height xlim <- c(max(limits[[1L]], na.rm = TRUE) - width, max(limits[[1L]], na.rm = TRUE)) - shift[1] ylim <- c(min(limits[[2L]], na.rm = TRUE), min(limits[[2L]], na.rm = TRUE) + height) + m } if(pos == "center") { mx <- mean(limits[[1]] - min(limits[[1]], na.rm = TRUE), na.rm = TRUE) - 0.5 * width my <- mean(limits[[2]] - min(limits[[2]], na.rm = TRUE), na.rm = TRUE) - 0.5 * height xlim <- c(min(limits[[1L]], na.rm = TRUE), min(limits[[1L]], na.rm = TRUE) + width) + mx ylim <- c(min(limits[[2L]], na.rm = TRUE), min(limits[[2L]], na.rm = TRUE) + height) + my } return(list(xlim = xlim, ylim = ylim)) }
bic.zipfsreg <- function( target, dataset, wei = NULL, tol = 2, ncores = 1 ) { p <- ncol(dataset) moda <- list() k <- 1 n <- length(target) con <- log(n) tool <- NULL info <- matrix( 0, ncol = 2 ) result <- NULL sela <- NULL lgy <- sum( lgamma(target + 1) ) if ( any( is.na(dataset) ) ) { warning("The dataset contains missing values (NA) and they were replaced automatically by the variable (column) median (for numeric) or by the most frequent level (mode) if the variable is factor") if ( is.matrix(dataset) ) { dataset <- apply( dataset, 2, function(x){ x[which(is.na(x))] = median(x, na.rm = TRUE) ; return(x) } ) } else { poia <- unique( which( is.na(dataset), arr.ind = TRUE )[, 2] ) for ( i in poia ) { xi <- dataset[, i] if ( is.numeric(xi) ) { xi[ which( is.na(xi) ) ] <- median(xi, na.rm = TRUE) } else if ( is.factor( xi ) ) { xi[ which( is.na(xi) ) ] <- levels(xi)[ which.max( as.vector( table(xi) ) )] } dataset[, i] <- xi } } } if ( is.null( colnames(dataset) ) ) colnames(dataset) <- paste("X", 1:p, sep = "") runtime <- proc.time() if ( is.null(wei) ) { ini <- - 2 * Rfast::zip.mle(target)$loglik + 2 * con lgy <- sum( gamma(target + 1) ) } else { ini <- - 2 * zipmle.wei(target, wei)$loglik + 2 * con lgy <- sum( wei * gamma(target + 1) ) } bico <- zip.regs(target, dataset, wei, logged = TRUE, ncores = ncores)[, 3] mat <- cbind(1:p, bico) bico <- NULL colnames(mat) <- c("variable", "BIC") rownames(mat) <- 1:p sel <- which.min( mat[, 2] ) if ( ini - mat[sel, 2] > tol ) { info[1, ] <- mat[sel, ] mat <- mat[-sel, , drop = FALSE] sela <- sel mi <- zip.reg( target, dataset[, sel], wei = wei, lgy = lgy ) tool[1] <- - 2 * mi$loglik + ( length(mi$be) + 1 ) * con moda[[ 1 ]] <- mi } else { info <- info sela <- NULL } if ( length(moda) > 0 & nrow(mat) > 0 ) { k <- 2 pn <- p - k + 1 mod <- list() if ( ncores <= 1 ) { bico <- numeric( pn ) for ( i in 1:pn ) { ma <- zip.reg( target, dataset[, c(sel, mat[i, 1]) ], wei = wei, lgy = lgy ) bico[i] <- - 2 * ma$loglik + ( length(ma$be) + 1 ) * con } mat[, 2] <- bico } else { cl <- makePSOCKcluster(ncores) registerDoParallel(cl) bico <- numeric(pn) mod <- foreach( i = 1:pn, .combine = rbind, .export = "zip.reg") %dopar% { ww <- zip.reg( target, dataset[, c(sel, mat[i, 1]) ], wei = wei, lgy = lgy ) bico[i] <- - 2 * ww$loglik + ( length(ma$be) + 1 ) * con } stopCluster(cl) mat[, 2] <- mod } ina <- which.min( mat[, 2] ) sel <- mat[ina, 1] if ( tool[1] - mat[ina, 2] <= tol ) { info <- info } else { tool[2] <- mat[ina, 2] info <- rbind(info, mat[ina, ] ) sela <- info[, 1] mat <- mat[-ina, , drop = FALSE] mi <- zip.reg( target, dataset[, sela], wei = wei, lgy = lgy ) tool[2] <- - 2 * mi$loglik + ( length(mi$be) + 1 ) * con moda[[ 2 ]] <- mi } } if ( nrow(info) > 1 & nrow(mat) > 0 ) { while ( ( k < n - 15 ) & ( tool[ k - 1 ] - tool[ k ] > tol ) & ( nrow(mat) > 0 ) ) { k <- k + 1 pn <- p - k + 1 if (ncores <= 1) { for ( i in 1:pn ) { ma <- zip.reg( target, dataset[, c(sela, mat[i, 1]) ], wei = wei, lgy = lgy ) mat[i, 2] <- - 2 * ma$loglik + ( length(ma$be) + 1 ) * con } } else { cl <- makePSOCKcluster(ncores) registerDoParallel(cl) bico <- numeric(pn) mod <- foreach( i = 1:pn, .combine = rbind, .export = "beta.reg") %dopar% { ww <- zip.reg( target, dataset[, c(sela, mat[i, 1]) ], wei = wei, lgy = lgy ) bico[i] <- - 2 * ww$loglik + ( length(ww$be) + 1 ) * con } stopCluster(cl) mat[, 2] <- mod } ina <- which.min( mat[, 2] ) sel <- mat[ina, 1] if ( tool[k - 1] - mat[ina, 2] <= tol ) { info <- rbind( info, c( -10, Inf ) ) tool[k] <- Inf } else { tool[k] <- mat[ina, 2] info <- rbind(info, mat[ina, ] ) sela <- info[, 1] mat <- mat[-ina, , drop = FALSE] ma <- zip.reg( target, dataset[, sela], wei = wei, lgy =lgy ) tool[k] <- - 2 * ma$loglik + ( length(ma$be) + 1 ) * con moda[[ k ]] <- ma } } } runtime <- proc.time() - runtime d <- length(sela) final <- NULL if ( d >= 1 ) { colnames(xx) <- paste("V", sela, sep = "") final <- zip.reg( target, dataset[, sela], wei = wei ) info <- info[1:d, , drop = FALSE ] colnames(info) <- c( "variables", "BIC" ) rownames(info) <- info[, 1] } list(runtime = runtime, mat = t(mat), info = info, ci_test = "testIndZIP", final = final ) }
bboptim <- function(data, ParameterNames=NULL, respName=NULL, control=list(), force=FALSE, optimizers=blackbox.getOption("optimizers"), precision=1e-3) { np <- ncol(data)-1L if (is.null(ParameterNames)) ParameterNames <- colnames(data)[seq(np)] if (is.null(respName)) respName <- colnames(data)[np+1L] sorted_etc <- prepareData(data=data,ParameterNames=ParameterNames, respName=respName,verbose=FALSE) fnscale <- control$fnscale maximizeBool <- control$maximize if (is.null(maximizeBool)) { maximizeBool <- ! ( is.null(fnscale) || fnscale >= 0 ) } else if (is.null(fnscale)) { if (maximizeBool) fnscale <- -1 } else stop("Mixing controls 'maximize' and 'fnscale' is dangerous. Please correct.") gcvres <- calcGCV(sorted_etc, force=force, decreasing=maximizeBool, optimizers=optimizers ) ranfix <- list(rho=1/gcvres$CovFnParam[ParameterNames], nu=gcvres$CovFnParam[["smoothness"]]) form <- as.formula(paste(respName,"~ 1 + Matern(1|",paste(ParameterNames,collapse=" + "),")")) optimizers[optimizers=="optim"] <- "L-BFGS-B" phi <- max(gcvres$pureRMSE^2,1e-8) ranfix <- c(ranfix,list(phi=phi)) if (TRUE) { oldopt <- spaMM.options(spaMM_glm_conv_silent=TRUE) thisfit <- HLCor(form,data=data,ranPars=ranfix,REMLformula=form) spaMM.options(oldopt) ranfix <- c(ranfix,list(lambda=thisfit$lambda)) etafix <- list(beta=fixef(thisfit)) } else { ranfix <- c(ranfix,list(lambda=phi/gcvres$lambdaEst)) etafix <- list() } thisfit <- fitme(form,data=sorted_etc,fixed=ranfix,etaFix=etafix, method="REML") lower <- apply(sorted_etc[,ParameterNames,drop=FALSE],2,min) upper <- apply(sorted_etc[,ParameterNames,drop=FALSE],2,max) if ( ! maximizeBool ) { init <- thisfit$data[which.min(predict(thisfit)),ParameterNames] optr_fitted <- list(par=init,value=min(predict(thisfit,newdata=thisfit$data))) } else { init <- thisfit$data[which.max(predict(thisfit)),ParameterNames] optr_fitted <- list(par=init,value=max(predict(thisfit,newdata=thisfit$data))) } mse <- attr(predict(thisfit,init,variances=list(linPred=TRUE,dispVar=TRUE)),"predVar")[1] mse <- max(0,mse) optr_fitted$RMSE <- sqrt(mse) if ("L-BFGS-B" %in% optimizers) { if (is.null(control$parscale)) control$parscale <- (upper-lower) optr <- optim(init, function(v) {as.numeric(predict(thisfit,newdata=v))}, lower=lower,upper=upper,control=control,method="L-BFGS-B") } else if ("lbfgsb3c" %in% optimizers){ if ( maximizeBool ) { ufn <- function (v) { - as.numeric(predict(thisfit,newdata=v)) } } else { ufn <- function (v) { as.numeric(predict(thisfit,newdata=v)) } } if ( ! requireNamespace("lbfgsb3c",quietly=TRUE) ) { stop("Package lbfgsb3c not installed.") } optr <- lbfgsb3c::lbfgsb3c(par=unlist(init),fn=ufn,lower=lower,upper=upper) if ( maximizeBool ) {optr$value <- - optr$value} } else if ("bobyqa" %in% optimizers) { if ( maximizeBool ) { ufn <- function (v) { - as.numeric(predict(thisfit,newdata=v)) } } else { ufn <- function (v) { as.numeric(predict(thisfit,newdata=v)) } } control <- list(rhobeg=min(abs(upper-lower))/20) control$rhoend <- max(1,control$rhobeg)/1e6 if ( ! requireNamespace("minqa",quietly=TRUE) ) { stop("Package minqa not installed.") } optr <- minqa::bobyqa(par=unlist(init),fn=ufn,lower=lower,upper=upper,control=control) if ( maximizeBool ) {optr$value <- - optr$fval} else {optr$value <- optr$fval} } else { if ( maximizeBool ) { ufn <- function (v) { - as.numeric(predict(thisfit,newdata=v)) } } else { ufn <- function (v) { as.numeric(predict(thisfit,newdata=v)) } } optr <- nloptr(x0=unlist(init),eval_f=ufn,lb=lower,ub=upper, opts=list(algorithm="NLOPT_LN_BOBYQA",maxeval=-1)) if ( maximizeBool ) {optr$value <- - optr$objective} else {optr$value <- optr$objective} optr$par <- optr$solution } colTypes <- list(ParameterNames=ParameterNames,respName=respName) eta <- predict(thisfit,newdata=optr$par,variances=list(linPred=TRUE,dispVar=TRUE)) RMSE <- sqrt(max(0,attr(eta,"predVar"))) reltol <- control$reltol if (is.null(reltol)) reltol <- sqrt(.Machine$double.eps) if (maximizeBool) { convergence <- (optr_fitted$value > optr$value-reltol) } else convergence <- (optr_fitted$value < optr$value+reltol) conv_crits <- c(objective=convergence,precision=(get_predVar(thisfit,optr$par)<precision)) resu <- list(fit=thisfit,optr_fitted=optr_fitted,optr=optr,callArgs = as.list(match.call())[-1],colTypes=colTypes, GCVmethod=gcvres$GCVmethod,RMSE=RMSE,conv_crits=conv_crits) class(resu) <- c("list","bboptim") return(resu) } print.bboptim <- function(x,...) { if (all(x$conv_crits)) { cat("Apparent convergence at optimum:\n") print(x["optr"],...) cat("Other elements of bboptim object not fully shown:", paste(setdiff(names(x),c("optr","convergence")),collapse=", ")) } else { reasons <- c(objective="optimum objective not reached",precision="target precision not reached")[ ! (x$conv_crits)] cat("Apparent optimum not ascertained: ") cat(paste(reasons,collapse = " & ")) cat("\nInferred optimum among fitted points:\n") print(unlist(x[["optr_fitted"]]),...) cat("Inferred optimum over all space:\n") print(c(unlist(x[["optr"]][c("par","value")]),RMSE=signif(x$RMSE,4)),...) cat("Other elements of bboptim object not fully shown:", paste(setdiff(names(x),c("optr_fitted","RMSE","convergence")),collapse=", ")) } } summary.bboptim <- function(object,...) { print(x=object,...) } bbrhull <- function(n, from=10*n, vT, object, fixed=NULL, outputVars=object$colTypes$ParameterNames) { trypoints <- data.frame(rvolTriangulation(from, vT)) colnames(trypoints) <- colnames(vT$vertices) if (! is.null(fixed)) { trypoints <- cbind(trypoints, fixed) } if ("Migraine" %in% blackbox.getOption("usedBy")) { trypoints <- apply(trypoints, 1, tofullKrigingspace) if (length(outputVars)>1L) { trypoints <- t(trypoints) } else trypoints <- matrix(trypoints,ncol=1L) } colnames(trypoints) <- outputVars trypred <- predict(object, newdata=as.data.frame(trypoints), variances=list(predVar=TRUE)) trySE <- attr(trypred, "predVar") trySE[trySE<0] <- 0 trySE <- sqrt(trySE) Qmax <- object$Qmax if (is.null(Qmax)) { Qmin <- object$Qmin tryQ <- trypred - 1.96*trySE expectedImprovement <- trySE*dnorm((tryQ-Qmin)/trySE)+(Qmin-tryQ)*pnorm((Qmin-tryQ)/trySE) } else { tryQ <- trypred + 1.96*trySE expectedImprovement <- trySE*dnorm((Qmax-tryQ)/trySE)+(tryQ-Qmax)*pnorm((tryQ-Qmax)/trySE) } trypoints <- trypoints[order(expectedImprovement, decreasing=TRUE)[seq_len(n)], outputVars, drop=FALSE] return(trypoints) } rbb <- function(object,n=NULL,from=NULL,focus=0.75) { if (focus<0 || focus>1) { focus <- max(0,min(1,focus)) message.redef(paste("'focus' outside (0,1), set to",focus)) } ParameterNames <- object$colTypes$ParameterNames np <- length(ParameterNames) if (is.null(n)) { n <- floor(10*(1+3*log(np))) n <- min(n,2^(np+1)) } if (is.null(from)) { from <- n* floor(10*(1+3*log(np))) } if (from<=2*n) stop("from < 2*n: please increase 'from' relative to 'n'") ycolname <- object$colTypes$respName obspred <- predict(object$fit,variances=list(linPred=TRUE,dispVar=TRUE),binding=ycolname) obsSE <- attr(obspred,"predVar") obsSE[obsSE<0] <- 0 fnscale <- object$callArgs$control$fnscale if ( ! is.null(fnscale) && fnscale < 0) { object$fit$Qmax <- max(obspred[,ycolname]+1.96 * sqrt(obsSE)) ordr <- order(obspred[,ycolname],decreasing=TRUE) } else { object$fit$Qmin <- min(obspred[,ycolname]-1.96 * sqrt(obsSE)) ordr <- order(obspred[,ycolname],decreasing=FALSE) } vT <- volTriangulationWrapper(object$fit$data[,ParameterNames,drop=FALSE]) candidates <- bbrhull(round(n*(1-focus)), from=from,vT, object$fit,outputVars=ParameterNames) if (FALSE) { ntop <- min(nrow(obspred),4*np) vT <- volTriangulationWrapper(object$fit$data[ordr[seq(ntop)],ParameterNames,drop=FALSE]) candidates2 <- bbrhull(n-nrow(candidates)-1L, from=from/2,vT, object$fit,outputVars=ParameterNames) } else { whichSimplex <- locatePointinvT(object$optr$par,vT) if (length(whichSimplex)==1L) { simplex <- vT$vertices[vT$simplicesTable[whichSimplex,],,drop=FALSE] candidates2 <- replicate(n-nrow(candidates)-1L, rsimplex(simplex=simplex)) if (np == 1L) { candidates2 <- as.matrix(candidates2) } else candidates2 <- t(candidates2) rownames(candidates2) <- NULL colnames(candidates2) <- ParameterNames } else { subvT <- subsimplices.volTriangulation(vT,whichSimplex) candidates2 <- rvolTriangulation(n=n-nrow(candidates)-1L,subvT) } } candidates <- rbind(candidates,candidates2,object$optr$par) candidatesWPred <- predict(object$fit,newdata=candidates,binding=ycolname) poolWresp <- rbind(object$fit$data,candidatesWPred) uli <- .ULI(poolWresp[,1:np,drop=FALSE]) if (any(table(uli[-length(uli)])>2L)) { if (blackbox.getOption("dump_frames")) { warning("Some candidate(s) in >2 copies.") dump.frames(dumpto = "dump_in_rbb",to.file=TRUE) } else stop("Some candidate(s) in >2 copies.") } table_uli <- table(uli) curr_nrep_optr <- table_uli[uli[length(uli)]] if (curr_nrep_optr==1L) { candidates <- rbind(candidates,object$optr$par) ndoublons <- 0L } else if (curr_nrep_optr==3L) { candidates <- candidates[-nrow(candidates),,drop=FALSE] ndoublons <- 2L } else if (curr_nrep_optr>3L) { stop("Candidate optimum already in >2 copies in candidate points.") } else ndoublons <- 1L if (ndoublons>0L) { singletonsWresp <- poolWresp[which(uli %in% which(table_uli==1L)),,drop=FALSE] if (nrow(singletonsWresp)>0L) { whichPts <- order(singletonsWresp[,ycolname], decreasing=( ! is.null(fnscale) && fnscale < 0))[seq_len(ndoublons)] candidates <- rbind(candidates,singletonsWresp[whichPts,1:np]) } } if ( ! inherits(candidates,"data.frame")) { if (blackbox.getOption("dump_frames")) { warning("! inherits(candidates,\"data.frame\").") dump.frames(dumpto = "another_dump_in_rbb",to.file=TRUE) } else stop("! inherits(candidates,\"data.frame\").") } candidates }
gx.rqpca.loadplot <- function (save, main = "", crit = 0.3, cex = 0.8, cex.axis = 0.7, cex.main = 0.8) { frame() old.par <- par(); on.exit(par(old.par)) par(pty = "m", las = 1) if (main == "") banner <- paste("PC loadings >", crit, "for", deparse(substitute(save)), "\ndata source:", save$input) else banner <- main l <- save$rload range.l <- range(l) ly <- -1; uy <- 1 if (range.l[1] < -0.975) ly <- range.l[1] - 0.1 if (range.l[2] > 0.975) uy <- range.l[2] + 0.1 k <- dim(l)[2] p <- dim(l)[1] lnam <- save$matnames[[2]] plot(cbind(c(0, 1, 1, 0, 0), c(uy, uy, ly, ly, uy)), type = "l", axes = FALSE, xlab = "", ylab = "") segments(0, 0, 1, 0) if (uy > 1) segments(0, 1, 1, 1, lty = 2) segments(0, 0.5, 1, 0.5, lty = 2) segments(0, -0.5, 1, -0.5, lty = 2) if (ly < -1) segments(0, -1, 1, -1, lty = 2) tplace1 = -0.3 mtext("-1", side = 2, at = -1, line = tplace1, cex = cex.axis) mtext("-0.5", side = 2, at = -0.5, line = tplace1, cex = cex.axis) mtext("0", side = 2, at = 0, line = tplace1, cex = cex.axis) mtext("+0.5", side = 2, at = 0.5, line = tplace1, cex = cex.axis) mtext("+1", side = 2, at = 1, line = tplace1, cex = cex.axis) title(banner, cex.main = cex.main) bb <- apply(l^2, 2, sum)/sum(l^2) bb1 <- cumsum(bb) cumpct <- cumsum(save$econtrib) mtext("0%", side = 3, at = 0, line = tplace1, cex = 0.7) tplace2 = -0.5 for (i in 1:k) { segments(bb1[i], uy, bb1[i], ly) lplot <- abs(l[, i]) > crit lsel <- l[lplot, i] names(lsel) <- lnam[lplot] if (i == 1) { mtext(paste(round(cumpct[i]), "%", sep = ""), side = 3, at = bb1[i], line = tplace1, cex = cex.axis) chardist <- bb[1]/(length(lsel) + 1) text(seq(from = chardist, by = chardist, length = length(lsel)), lsel, names(lsel), cex = cex) mtext(paste("PC-", round(i), sep = ""), side = 1, at = bb1[i]/2, line = tplace2, cex = cex.axis) } else { if (length(lsel) >= 1) { mtext(paste(round(cumpct[i]), "%", sep = ""), side = 3, at = bb1[i], line = tplace1, cex = cex.axis) chardist <- (bb1[i] - bb1[i - 1])/(length(lsel) + 1) text(seq(from = bb1[i - 1] + chardist, by = chardist, length = length(lsel)), lsel, names(lsel), cex = cex) mtext(paste("PC-", round(i), sep = ""), side = 1, at = bb[i]/2 + bb1[i - 1], line = tplace2, cex = cex.axis) } } } invisible() }
roll.spillover <- function (data, width, n.ahead = 10, index=c("orthogonalized", "generalized"), ortho.type = c("single", "partial", "total"), ...) { if (!(class(data) == "zoo")) { stop("\nPlease provide an object of class 'zoo', generated by 'as.zoo'.\n") } K <- ncol(data)+1 roll.index <- switch(match.arg(index), orthogonalized = { switch(match.arg(ortho.type), single={rollapply(data, width = width, FUN = function(z) { O.spillover(VAR(z,...), ortho.type = c("single"))[K,K] }, by.column = FALSE, align = "right")}, partial={rollapply(data, width = width, FUN = function(z) { O.spillover(VAR(z,...), ortho.type = c("partial"))[K,K] }, by.column = FALSE, align = "right")}, total={rollapply(data, width = width, FUN = function(z) { O.spillover(VAR(z,...), ortho.type = c("total"))[K,K] }, by.column = FALSE, align = "right")}) }, generalized ={ rollapply(data, width = width, FUN = function(z) { G.spillover(VAR(z,...))[K,K] }, by.column = FALSE, align = "right") } ) return(roll.index) }
setwd(dirname(this.dir())) source("setup.R") raw_data_path <- get_inpath(this.dir()) out_data_path <- get_outpath(this.dir()) br <- read_excel(paste0(raw_data_path,"baton_rouge_police_settlements_records.xlsx"), sheet = "amounts", col_types = "text") br_po <- read_excel(paste0(raw_data_path,"baton_rouge_police_settlements_records.xlsx"), sheet = "police_officers", col_types = "text") br <- br %>% mutate(city = "Baton Rouge", state="LA") %>% mutate(amount_awarded = as.numeric(amount_awarded), calendar_year = as.numeric(calendar_year), filed_date = NA, filed_year = NA, incident_date_clean = as_date(as.numeric(incident_date),origin = '1899-12-30'), closed_date_clean = as_date(as.numeric(closed_date),origin = '1899-12-30')) nrow(br %>% filter(is.na(incident_date_clean))) nrow(br %>% filter(is.na(closed_date_clean))) nrow(br %>% filter(is.na(calendar_year))) br <- br %>% mutate(closed_date = closed_date_clean, incident_date = incident_date_clean, incident_year = year(incident_date)) br <- br %>% mutate(summary_allegations = NA, court = NA) br_po <- br_po %>% mutate(city = "Baton Rouge", state= "LA") %>% rename(calendar_year = year) %>% mutate(calendar_year = as.numeric(calendar_year), closed_date_clean = as_date(as.numeric(closed_date),origin = '1899-12-30'), closed_date = closed_date_clean) %>% select(-closed_date_clean) merged <- full_join(br,br_po) br <- br %>% select(calendar_year, city, state, incident_date, incident_year, filed_date, filed_year, closed_date, amount_awarded, other_expenses, collection, total_incurred, case_outcome, docket_number, claim_number, court, plaintiff_name, plaintiff_attorney, matter_name, location, summary_allegations) summary(br$calendar_year) nrow(br %>% group_by_all() %>% filter(n()>1)) nrow(br %>% group_by(docket_number) %>% filter(n()>1)) table(br$summary_allegations) print(paste("There are",nrow(br %>% filter(is.na(closed_date))),"rows missing closed date")) print(paste("There are",nrow(br %>% filter(is.na(calendar_year))),"rows missing calendar year")) print(paste("There are",nrow(br %>% filter(is.na(amount_awarded))),"rows missing amount awarded")) print(paste("There are",nrow(br %>% filter(amount_awarded==0)),"rows with amount awarded = 0")) print(paste("There are",nrow(br %>% filter(is.na(docket_number))),"rows missing docket number")) print("Total number of cases") print(nrow(br)) print("Total amount awarded") sum(br$amount_awarded) write.csv(br,paste0(out_data_path,"baton_rouge_edited.csv"), na = "",row.names = FALSE) write.csv(br_po,paste0(out_data_path,"baton_rouge_police_edited.csv"), na = "", row.names = FALSE)
get_data <- function(records, dir_out = NULL, md5_check = TRUE, force = FALSE, as_sf = TRUE, ..., verbose = TRUE) { if (inherits(verbose, "logical")) options(gSD.verbose = verbose) extras <- list(...) if (is.null(extras$hub)) extras$hub <- "auto" if (is.null(records$level)) records$level <- NA records <- .check_records(records, c("product", "product_group", "entity_id", "level", "record_id", "summary")) records.names <- colnames(records) groups <- unique(records$product_group) if ("sentinel" %in% groups) { .check_login("Copernicus") } if ("landsat" %in% groups) { .check_login("USGS") } if ("modis" %in% groups) { .check_login(c("USGS", "earthdata")) } if ("srtm" %in% groups) { .check_login(c("earthdata")) } if (is.null(records$download_available)) { out("Column 'download_available' not present, calling check_availabilty() to check download availability of records...") records <- check_availability(records, verbose = FALSE) if (inherits(verbose, "logical")) options(gSD.verbose = verbose) } if (all(!records$download_available)) out("All supplied records are currently not availabe for download. Use order_data() to make them available for download.", type = 3) if (any(!records$download_available)) out("Some records are currently not available for download and will be skipped (see records$download_available). Use order_data() to make them available for download.", type = 2) sub <- which(records$download_available) if (any(records[sub, ][records$product_group == "landsat", ]$level != "l1")) { records$gSD.espa_item <- NA records[sub, ][records$product_group == "landsat" & records$level != "l1", ]$gSD.espa_item <- .apply(records[sub, ][records$product_group == "landsat" & records$level != "l1", ], MARGIN = 1, function(x) { content(.get(paste0(getOption("gSD.api")$espa, "item-status/", x$order_id, "/", x$record_id), getOption("gSD.usgs_user"), getOption("gSD.usgs_pass")))[[1]][[1]] }) } records$gSD.cred <- NA records[sub, ]$gSD.cred <- .apply(records[sub, ], MARGIN = 1, function(x) { if (x["product_group"] == "sentinel") { list(.CopHub_select(x = extras$hub, p = if (isTRUE(as.logical(x[["is_gnss"]]))) "GNSS" else x[["product"]], user = getOption("gSD.dhus_user"), pw = getOption("gSD.dhus_pass"))) } else if (x["product_group"] == "srtm") { list(user = getOption("gSD.ed_user"), pw = getOption("gSD.ed_pass")) } else { NA } }) records$md5_checksum <- NA if (isTRUE(md5_check)) { out("Receiving MD5 checksums...") records[sub, ]$md5_checksum <- unlist(.apply(records[sub, ], MARGIN = 1, function(x) { if (x["product_group"] == "sentinel") { cred <- unlist(x$gSD.cred) if (!is.null(x$md5_url)) content(.get(x$md5_url, cred[1], cred[2]), USE.NAMES = F) else NA } else if (x["product_group"] == "landsat" & x$level != "l1") { strsplit(content(.get(x$gSD.espa_item$cksum_download_ur), as = "text", encoding = "UTF-8"), " ")[[1]][1] } else { NA } }, verbose = F)) } out("Assembling dataset URLs...") records$dataset_url <- NA records[sub, ]$dataset_url <- .get_ds_urls(records[sub, ]) dir_out <- .check_dir_out(dir_out, "datasets") records$gSD.dir <- paste0(dir_out, "/", records$product, "/") catch <- .sapply(records$gSD.dir, function(x) if (!dir.exists(x)) dir.create(x, recursive = T)) records$dataset_file <- NA records[sub, ]$dataset_file <- .get_ds_filenames(records[sub, ]) records$gSD.item <- 1:nrow(records) records$gSD.head <- .sapply(records$gSD.item, function(i, n = nrow(records)) paste0("[Dataset ", toString(i), "/", toString(n), "] ")) records$dataset_file <- .apply(records, MARGIN = 1, function(x) { if (isTRUE(x$download_available)) { dataset_url <- unlist(x$dataset_url, recursive = T) dataset_file <- unlist(x$dataset_file, recursive = T) cred <- unlist(x$gSD.cred) if (any(is.na(dataset_url), is.na(dataset_file))) { NA } else { download <- .sapply(1:length(dataset_url), function(i) { file.head <- gsub("]", paste0(" | File ", i, "/", length(dataset_url), "]"), x$gSD.head) .retry(.download, url = dataset_url[i], file = dataset_file[i], name = paste0(x$record_id, if (!is.na(x$level)) paste0(" (", x$level, ")") else NULL), head = file.head, type = "dataset", md5 = x$md5_checksum, prog = if (isTRUE(verbose)) TRUE else FALSE, fail = expression(out(paste0("Attempts to download '", name, "' failed.", type = 2))), retry = expression(out(paste0("[Attempt ", toString(3 - n + 1), "/3] Reattempting download of '", name, "'..."), msg = T)), delay = 0, value = T, username = if (any(x$product_group == "sentinel", x$product_group == "srtm")) cred[1] else NULL, password = if (any(x$product_group == "sentinel", x$product_group == "srtm")) cred[2] else NULL ) }) files <- dataset_file[download] if (length(files) > 0) list(files) else return(NA) } } else { out(paste0(x$gSD.head, "Skipping download of dataset '", paste0(x$record_id, if (!is.na(x$level)) paste0(" (", x$level, ")") else NULL), "', since it is not available for download..."), msg = T) return(NA) } }) records <- .check_records(records, as_sf = as_sf) return(.column_summary(records, records.names)) } getSentinel_data <- get_data getLandsat_data <- get_data getMODIS_data <- get_data
speech_url <- function(chamber, from, to){ param <- fechas_legis(from, to) out <- list() for(i in 1:length(param)){ out[[i]] <- proto_url(chamber = chamber, legislature = names(param)[i], from = parseo(param[[i]][1]), to = parseo(param[[i]][2])) } url <- unlist(out) if(is.null(url)){ stop("There are no sessions in that date range.", call. = FALSE) } return(url) }
testData = createData(sampleSize = 200, overdispersion = 0, family = gaussian()) fittedModel <- lmer(observedResponse ~ Environment1 + (1|group), data = testData) simulationOutput <- simulateResiduals(fittedModel = fittedModel) plot(simulationOutput, quantreg = T) x = plotResiduals(simulationOutput, testData$Environment1, rank = T) library(SHT) unif.2017YMq(as.matrix(x)) ks.test(x$pred, punif) ks.test(x$res, punif) library(spatstat) spatial = ppp(x$pred,x$res, c(0,1), c(0,1)) plot(spatial) x <- ppm(spatial ~ x * y + polynom(y,2), Poisson()) summary(x) plot(x) hist(simulationOutput) testResiduals(simulationOutput)
require(crs) require(quadprog) set.seed(42) n <- 1000 n.eval <- 50 x.min <- -5 x.max <- 5 lower <- -0.1 upper <- 0.1 x1 <- runif(n,x.min,x.max) x2 <- runif(n,x.min,x.max) y <- sin(sqrt(x1^2+x2^2))/sqrt(x1^2+x2^2) + rnorm(n,sd=.1) data.train <- data.frame(y,x1,x2) x1.seq <- seq(min(x1),max(x1),length=n.eval) x2.seq <- seq(min(x2),max(x2),length=n.eval) rm(y,x1,x2) data.eval <- data.frame(y=0,expand.grid(x1=x1.seq,x2=x2.seq)) model.unres <- crs(y~x1+x2, deriv=1, data=data.train, nmulti=5, basis="tensor") model.gradient.unres <- model.unres$deriv.mat summary(model.unres) B <- crs:::prod.spline(x=data.train[,-1], K=cbind(model.unres$degree,model.unres$segments), basis=model.unres$basis) B.x1 <- crs:::prod.spline(x=data.train[,-1], K=cbind(model.unres$degree,model.unres$segments), basis=model.unres$basis, deriv.index=1, deriv=1) Aymat.res.x1 <- t(B.x1%*%solve(t(B)%*%B)%*%t(B))*data.train$y B.x2 <- crs:::prod.spline(x=data.train[,-1], K=cbind(model.unres$degree,model.unres$segments), basis=model.unres$basis, deriv.index=2, deriv=1) Aymat.res.x2 <- t(B.x2%*%solve(t(B)%*%B)%*%t(B))*data.train$y Amat <- cbind(Aymat.res.x1, -Aymat.res.x1, Aymat.res.x2, -Aymat.res.x2) rm(B,B.x1,B.x2,Aymat.res.x1,Aymat.res.x2) bvec <- c(rep(lower,n), -rep(upper,n), rep(lower,n), -rep(upper,n)) QP.output <- solve.QP(Dmat=diag(n),dvec=rep(1,n),Amat=Amat,bvec=bvec) if(is.nan(QP.output$value)) stop(" solve.QP failed. Try smoother curve (larger bandwidths or polynomial order)") rm(Amat,bvec) p.hat <- QP.output$solution data.trans <- data.frame(y=p.hat*data.train$y,data.train[,2:ncol(data.train),drop=FALSE]) model.res <- crs(y~x1+x2,cv="none", degree=model.unres$degree, segments=model.unres$segments, basis=model.unres$basis, data=data.trans, deriv=1) fitted.unres <- matrix(predict(model.unres,newdata=data.eval), n.eval, n.eval) fitted.res <- matrix(predict(model.res,newdata=data.eval), n.eval, n.eval) zlim <- c(min(fitted.unres,fitted.res),max(fitted.unres,fitted.res)) par(mfrow=c(1,2)) persp(x1.seq, x2.seq, fitted.unres, main="Unconstrained Regression Spline", col="lightblue", ticktype="detailed", ylab="X2", xlab="X1", zlim=zlim, zlab="Conditional Expectation", theta=300, phi=30) persp(x1.seq, x2.seq, fitted.res, main="Constrained Regression Spline", sub="-0.1 <= g'(x1,x2) <= 0.1", col="lightblue", ticktype="detailed", ylab="X2", xlab="X1", zlim=zlim, zlab="Conditional Expectation", theta=300, phi=30) par(mfrow=c(1,1))
knitr::opts_chunk$set( collapse = TRUE, comment = " dpi = 300, fig.width = 1.8, fig.height = 1.8 ) library(ggalignment) library(dplyr) ggalignment(alignment = data.frame(img = character(), alignment = character()), font_size = 3) align_cats <- example_cats() ggalignment(align_cats, font_size = 3) cats_rect <- align_cats %>% mutate(img = c(align_cats$img[1:3], system.file("img/gray_2.png", package = "ggalignment"))) ggalignment(alignment = cats_rect, font_size = 3) cats_with_coords <- align_cats %>% mutate(x = c(0.5, -0.5, -0.5, 0.5), y = c(-0.5, -0.5, 0.5, 0.5)) ggalignment(alignment = cats_with_coords, font_size = 3) cats_with_multi_image <- align_cats %>% mutate(alignment = rep("chaotic neutral")) %>% mutate(x = c(0.5, -0.5, -0.5, 0.5), y = c(-0.5, -0.5, 0.5, 0.5)) ggalignment(alignment = cats_with_multi_image, font_size = 3) ggalignment(alignment = align_cats, font_size = 3, max_images_per_dim = 1) ggalignment(alignment = align_cats, font_size = 3, max_images_per_dim = 2) ggalignment(alignment = align_cats, font_size = 3, max_images_per_dim = 4) ggalignment(alignment = align_cats, line_type = "dotted", line_color = "seagreen1", background_color = "turquoise4", font_color = "skyblue1", font_size = 3) local_example <- data.frame(img = c("r_logo.png", "obie_portrait.png"), alignment = c("lawful good", "chaotic neutral")) ggalignment(local_example, font_size = 3) url_example <- data.frame(img = c("https://www.r-project.org/Rlogo.png", "https://avatars.githubusercontent.com/u/18043377?v=4"), alignment = c("lawful good", "chaotic neutral")) ggalignment(url_example, font_size = 3)
utils::globalVariables(c("proj_i", "S", "i")) smart_pca <- function(snp_data, packed_data = FALSE, sample_group, sample_remove = FALSE, snp_remove = FALSE, missing_value = 9, missing_impute = "remove", scaling = "drift", program_svd = "RSpectra", pc_axes = 2, sample_project = FALSE, pc_project = c(1:2)) { startT <- Sys.time() get.time <- function(t) { tt <- as.numeric(difftime(Sys.time(), t, units = "secs")) H <- tt %/% 3600 rr <- tt %% 3600 if(rr > 0) { M <- rr %/% 60 rr2 <- rr %% 60 if(rr2 > 0) { S <- round(rr2) }else{ S <- 0 } } else { M <- 0 S <- 0 } return(paste0(H, "h ", M, "m ", S, "s")) } message("Checking argument options selected...") if(!is.numeric(sample_remove)) sample_remove <- as.logical(sample_remove) if(!is.numeric(sample_project)) sample_project <- as.logical(sample_project) if(isFALSE(sample_project)) pc_project <- 0 if (program_svd == "RSpectra" & max(pc_project) > pc_axes) { stop("Dimensionality of projected space (pc_project) must be equal to or smaller than dimensionality of PCA (pc_axes)\nComputation aborted") } if (missing_impute != "remove" & missing_impute != "mean") { stop("Check spelling: missing_impute must be 'remove' or 'mean'") } if (missing_value != 9 & !is.na(missing_value)) { stop("Missing values must be coded as 9 or NA") } if (scaling != "none" & scaling != "center" & scaling != "sd" & scaling != "drift") { stop("Check spelling: scaling must be 'none', 'center', 'sd' or 'drift'") } if (program_svd != "RSpectra" & program_svd != "bootSVD") { stop("Check spelling: program_svd must be 'RSpectra' or 'bootSVD'") } if (missing_impute != "remove" & missing_impute != "mean") { stop("Check spelling: missing_impute must equal 'remove' or 'mean'") } message("Argument options are correct...") message("Loading data...") samp_dat <- data.table::data.table(sample_group) data.table::setnames(samp_dat, "Group") samp_dat[, I:= 1:.N] sampN.full <- nrow(samp_dat) sample_PCA <- 1:sampN.full if (!isFALSE(sample_remove)) { sample_PCA <- setdiff(sample_PCA, sample_remove) sample_project <- setdiff(sample_project, sample_remove) } if (!isFALSE(sample_project)) { sample_PCA <- setdiff(sample_PCA, sample_project) } sampN <- length(sample_PCA) is.binary <- function(filepath, max = 1000) { f = file(filepath, "rb", raw = TRUE) b = readBin(f, "int", max, size = 1, signed = FALSE) close(f) return(max(b) > 128) } if (is.binary(snp_data) == TRUE) { packed_data = TRUE message("Data is binary (packedancestrymap)...") } else { packed_data = FALSE } if(length(grep("\\.geno$", snp_data)) == 1) { if(isFALSE(packed_data)) { snp_dat <- vroom::vroom_fwf(file = snp_data, col_positions = vroom::fwf_widths(rep(1, sampN.full), col_names = NULL), col_types = paste(rep("i", sampN.full), collapse="")) snpN.full <- nrow(snp_dat) message(paste("Imported", snpN.full, "SNP by", sampN.full, "sample eigenstrat genotype matrix (decompressed or unpacked format)")) message(paste0("Time elapsed: ", get.time(startT))) message("Filtering data...") snp_dat1 <- do.call(cbind, snp_dat[, sample_PCA]) if (!isFALSE(sample_project)) { snp_dat2 <- do.call(cbind, snp_dat[, sample_project]) } } else { ss <- strsplit(snp_data, "\\.")[[1]] snp_data <- paste(ss[-length(ss)], collapse = ".") snp_dat <- read_packedancestrymap(pref = snp_data)$geno attr(snp_dat, "dimnames") <- NULL snpN.full <- nrow(snp_dat) message(paste("Imported", snpN.full, "SNP by", sampN.full, "sample packed eigenstrat genotype matrix (compressed or packed format)")) message(paste0("Time elapsed: ", get.time(startT))) message("Filtering data...") snp_dat1 <- snp_dat[, sample_PCA] if (!isFALSE(sample_project)) { snp_dat2 <- snp_dat[, sample_project] } missing_value <- NA } } else { snp_dat <- data.table::fread(file = snp_data, header = FALSE) snpN.full <- nrow(snp_dat) message(paste("Imported", snpN.full, "SNP by", sampN.full, "sample genotype matrix")) message(paste0("Time elapsed: ", get.time(startT))) message("Filtering data...") snp_dat1 <- do.call(cbind, snp_dat[, sample_PCA, with = FALSE]) if (!isFALSE(sample_project)) { snp_dat2 <- do.call(cbind, snp_dat[, sample_project, with=FALSE]) } else { message(paste("No samples projected after PCA computation")) } } if (length(sample_group) != ncol(snp_dat)) { stop("length(sample_group) should be equal to number of samples in dataset: computation aborted") } rm(snp_dat); gc() if (!isFALSE(snp_remove)) { snp.keep <- setdiff(1:snpN.full, snp_remove) snpN.full <- length(snp.keep) snp_dat1 <- snp_dat1[snp.keep, ] if (!isFALSE(sample_project)) { snp_dat2 <- snp_dat2[snp.keep, ] } } if (snpN.full < 3) { stop("Less than 3 SNPs remaining: computation aborted") } message(paste(snpN.full, "SNPs included in PCA", "computation")) message(paste(length(snp_remove), "SNPs omitted from PCA computation")) message(paste(length(sample_PCA), "samples included in PCA computation")) if (!isFALSE(sample_remove)) { message(paste(length(sample_remove), "samples omitted from PCA computation")) } if (!isFALSE(sample_project)) { message(paste(length(sample_project), "samples projected after PCA computation")) } message("Completed data filtering") message(paste0("Time elapsed: ", get.time(startT))) message("Scanning for invariant SNPs...") if (is.na(missing_value)) { genoMean <- rowMeans(snp_dat1, na.rm = TRUE) genoVar <- Rfast::rowVars(snp_dat1, na.rm = TRUE) } else { genoTab <- Rfast::rowTabulate(snp_dat1) genoTab <- cbind(sampN - rowSums(genoTab), genoTab) GTR <- setdiff(1:ncol(genoTab) - 1, missing_value) sumN <- rowSums(genoTab[, GTR+1]) sumX <- foreach::foreach(i = GTR, .combine = "+") %do% { i * genoTab[, i+1] } sumX2 <- foreach::foreach(i = GTR, .combine = "+") %do% { i^2 * genoTab[, i+1] } genoMean <- sumX / sumN genoVar <- ((sumX2 / sumN) - genoMean ^ 2) * (sumN / (sumN - 1)) rm(sumN, sumX, sumX2) } keepSNPs <- which(genoVar != 0) if (length(keepSNPs > 0)) { snp_dat1 <- snp_dat1[keepSNPs, ] genoMean <- genoMean[keepSNPs] genoVar <- genoVar[keepSNPs] if (!isFALSE(sample_project)) { snp_dat2 <- snp_dat2[keepSNPs, ] } } rm(keepSNPs) snpN <- nrow(snp_dat1) if (snpN == snpN.full) { message("Scan complete: no invariant SNPs found") } else { message(paste("Scan complete: removed", snpN.full - snpN, "invariant SNPs")) } message(paste0("Time elapsed: ", get.time(startT))) message("Checking for missing values...") if (is.na(missing_value)) { missI <- which(is.na(snp_dat1)) } else { missI <- which(snp_dat1 == missing_value) } if (length(missI) > 0) { Z <- missI %% snpN Z[Z == 0] <- snpN snpMissI <- sort(unique(Z)) snpMissN <- length(snpMissI) message(paste(snpMissN, "SNPs contain missing values")) if (missing_impute == "mean") { message("Imputing SNPs with missing values...") snp_dat1[missI] <- genoMean[Z] message(paste("Imputation with means completed:", length(missI), "missing values imputed")) } if (missing_impute == "remove") { message("Removing SNPs with missing values...") snp_dat1 <- snp_dat1[-snpMissI, ] if (!isFALSE(sample_project)) { snp_dat2 <- snp_dat2[-snpMissI, ] } genoMean <- genoMean[-snpMissI] genoVar <- genoVar[-snpMissI] snpN <- nrow(snp_dat1) message(paste("Removal completed:", snpMissN, "SNPs removed")) message(paste(snpN, "SNPs remaining")) } rm(missI, Z) } else { message("Scan completed: no missing values found") rm(missI) } message(paste0("Time elapsed: ", get.time(startT))) if(scaling != "none") { message("Scaling values by SNP...") if (scaling == "drift") { message("Centering and scaling by drift dispersion...") snp_drift <- sqrt((genoMean / 2) * (1 - genoMean/2)) snp_dat1 <- (snp_dat1 - genoMean) / snp_drift } if (scaling == "sd") { message("Centering and standardizing (z-scores)...") if (missing_impute == "mean") { snp_sd <- Rfast::rowVars(snp_dat1, std = TRUE) } else { snp_sd <- sqrt(genoVar) } snp_dat1 <- (snp_dat1 - genoMean) / snp_sd } if (scaling == "center") { message("Centering data...") snp_dat1 <- snp_dat1 - genoMean } message(paste0("Completed scaling using ", scaling)) message(paste0("Time elapsed: ", get.time(startT))) } else { message("Note: SNP-based scaling not used") } message(paste0("Computing singular value decomposition using ", program_svd, "...")) if (program_svd == "RSpectra") { snp_pca <- RSpectra::svds(t(snp_dat1), k = pc_axes) } else { snp_pca <- bootSVD::fastSVD(t(snp_dat1)) } if (missing_impute == "mean") { if (scaling == "sd") { snp_peigTotal <- sum(genoVar) } else { snp_peigTotal <- sum(Rfast::rowVars(snp_dat1)) } } else { snp_peigTotal <- sum(genoVar) } rm(snp_dat1); gc() message(paste0("Completed singular value decomposition using ", program_svd)) message(paste0("Time elapsed: ", get.time(startT))) message(paste0("Extracting eigenvalues and eigenvectors...")) snp_pc <- data.frame(snp_pca$u %*% diag(snp_pca$d)) colnames(snp_pc) <- paste0("PC", c(1:ncol(snp_pc))) snp_pcoef <- data.frame(snp_pca$v) colnames(snp_pcoef) <- paste0("PC", c(1:ncol(snp_pcoef))) snp_peig <- snp_pca$d ^ 2 / (sampN - 1) snp_peigN <- length(snp_peig) snp_eigVar <- snp_peig * 100 / snp_peigTotal snp_eigVarCum <- cumsum(snp_eigVar) snp_eig <- rbind(snp_peig, snp_eigVar, snp_eigVarCum) rownames(snp_eig) <- c("observed eigenvalues", "variance explained", "cumulative variance explained") colnames(snp_eig) <- paste("PC", c(1:snp_peigN), sep= "") rm(snp_pca) message("Eigenvalues and eigenvectors extracted") message(paste0("Time elapsed: ", get.time(startT))) if (!isFALSE(sample_project)) { message("Projecting ancient samples onto PCA space") message("PCA space = ", paste("PC", c(pc_project), sep = "")) sampN.anc <- ncol(snp_dat2) if (scaling == "drift") { snp_dat2 <- (snp_dat2 - genoMean) / snp_drift if(!is.na(missing_value)) { missing_value <- (missing_value - genoMean) / snp_drift } rm(genoMean, snp_drift) } if (scaling == "sd") { snp_dat2 <- (snp_dat2 - genoMean) / snp_sd if(!is.na(missing_value)) { missing_value <- (missing_value - genoMean) / snp_sd } rm(genoMean, snp_sd) } if (scaling == "center") { snp_dat2 <- snp_dat2 - genoMean if(!is.na(missing_value)) { missing_value <- missing_value - genoMean } rm(genoMean) } proj_sp <- snp_pcoef[, pc_project] aProj <- foreach::foreach(proj_i = 1:sampN.anc, .final = t, .combine = cbind) %do% { p_i <- data.table::data.table(proj_sp, S = snp_dat2[, proj_i]) if (any(is.na(missing_value))) { NAout <- p_i[!is.na(S)] } else { NAout <- p_i[S != missing_value] } x <- as.matrix(NAout[, .SD, .SDcols = 1:(ncol(NAout) - 1)]) solve(crossprod(x), crossprod(x, NAout$S)) } rm(snp_dat2, proj_sp); gc() message("Completed ancient sample projection") message(paste(sampN.anc, "ancient samples projected")) message(paste0("Time elapsed: ", get.time(startT))) } message("Tabulating PCA outputs...") sample.out <- merge(samp_dat, data.table::data.table(I = sample_PCA, Class = "PCA", snp_pc), by = "I") if (!isFALSE(sample_project)) { xx <- rep(NA, snp_peigN) names(xx) <- paste0("PC", 1:snp_peigN) proj_dt <- data.table::data.table(I = sample_project, Group = sample_group[sample_project], Class = "Projected", t(xx)) for(i in 1:ncol(aProj)){ data.table::set(proj_dt, j = colnames(aProj)[i], value = aProj[, i]) } sample.out <- rbind(sample.out, proj_dt) } if (!isFALSE(sample_remove)) { xx <- rep(NA, snp_peigN) names(xx) <- paste0("PC", 1:snp_peigN) sample.out <- rbind(sample.out, data.table::data.table(I = sample_remove, Group = sample_group[sample_remove], Class = "Removed", t(xx))) } sample.out <- sample.out[order(I)] sample.out[, I:=NULL] OUT <- list(pca.snp_loadings = snp_pcoef, pca.eigenvalues = snp_eig, pca.sample_coordinates = as.data.frame(sample.out)) message("Completed tabulations of PCA outputs...") return(OUT) }
subset_date <- function(.tibble, date_1, date_2) { filtrert_tibble <- .tibble[.tibble$Date %in% date_1:date_2,] return(filtrert_tibble) } subset_terms <- function(.tibble, terms, threshold, custom_column) { if (!is.null(terms)) { for (i in seq_along(terms)) { if (!is.na(custom_column[i])) { text_column <- rlang::sym(custom_column[i]) } else { text_column <- rlang::sym("Text") } if (is.na(threshold[i])) { threshold[i] <- 1 } .tibble <- .tibble %>% dplyr::mutate(hitcount = stringr::str_count( !!text_column, stringr::regex( terms[i], ignore_case = !search_arguments$case_sensitive ) )) %>% dplyr::filter(hitcount >= threshold[i]) } } return(.tibble) }
suppressPackageStartupMessages(library(rstanarm)) LOO.CORES <- ifelse(.Platform$OS.type == "windows", 1, 2) SEED <- 1234L set.seed(SEED) CHAINS <- 2 ITER <- 40 REFRESH <- 0 if (!exists("example_model")) { example_model <- run_example_model() } context("loo and waic") expect_equivalent_loo <- function(fit) { l <- suppressWarnings(loo(fit, cores = LOO.CORES)) w <- suppressWarnings(waic(fit)) expect_s3_class(l, "loo") expect_s3_class(w, "loo") expect_s3_class(w, "waic") att_names <- c("names", "dims", "class", "model_name", "discrete", "yhash", "formula") expect_named(attributes(l), att_names) expect_named(attributes(w), att_names) discrete <- attr(l, "discrete") expect_true(!is.na(discrete) && is.logical(discrete)) llik <- log_lik(fit) r <- loo::relative_eff(exp(llik), chain_id = rstanarm:::chain_id_for_loo(fit)) l2 <- suppressWarnings(loo(llik, r_eff = r, cores = LOO.CORES)) expect_equal(l$estimates, l2$estimates) expect_equivalent(w, suppressWarnings(waic(log_lik(fit)))) } test_that("loo & waic do something for non mcmc models", { SW(fito <- stan_glm(mpg ~ wt, data = mtcars, algorithm = "optimizing", seed = 1234L, prior_intercept = NULL, refresh = 0, prior = NULL, prior_aux = NULL)) SW(fitvb1 <- update(fito, algorithm = "meanfield", iter = ITER)) SW(fitvb2 <- update(fito, algorithm = "fullrank", iter = ITER)) SW(loo1 <- loo(fito)) SW(loo2 <- loo(fitvb1)) SW(loo3 <- loo(fitvb2)) expect_true("importance_sampling_loo" %in% class(loo1)) expect_true("importance_sampling_loo" %in% class(loo2)) expect_true("importance_sampling_loo" %in% class(loo3)) }) test_that("loo errors if model has weights", { SW( fit <- stan_glm(mpg ~ wt, data = mtcars, weights = rep_len(c(1,2), nrow(mtcars)), seed = SEED, refresh = 0, iter = 50) ) expect_error(loo(fit), "not supported") expect_error(loo(fit), "'kfold'") }) context("loo then refitting") test_that("loo issues errors/warnings", { expect_warning(loo(example_model, cores = LOO.CORES, k_threshold = 2), "Setting 'k_threshold' > 1 is not recommended") expect_error(loo(example_model, k_threshold = -1), "'k_threshold' < 0 not allowed.") expect_error(loo(example_model, k_threshold = 1:2), "'k_threshold' must be a single numeric value") expect_warning(rstanarm:::recommend_kfold(5), "Found 5") expect_warning(rstanarm:::recommend_kfold(5), "10-fold") expect_warning(rstanarm:::recommend_reloo(7), "Found 7") }) test_that("loo with k_threshold works", { SW(fit <- stan_glm(mpg ~ wt, prior = normal(0, 500), data = mtcars[25:32,], seed = 12345, iter = 5, chains = 1, cores = 1, refresh = 0)) expect_message(loo(fit, k_threshold = 0.5), "Model will be refit") SW(loo_x <- loo(example_model)) expect_message(rstanarm:::reloo(example_model, loo_x, obs = 1), "Model will be refit 1 times") }) test_that("loo with k_threshold works for edge case(s)", { y <- mtcars$mpg[1:10] x <- rexp(length(y)) SW(fit <- stan_glm(y ~ 1, refresh = 0, iter = 50)) expect_message( SW(res <- loo(fit, k_threshold = 0.1, cores = LOO.CORES)), "problematic observation\\(s\\) found" ) expect_s3_class(res, "loo") }) context("kfold") test_that("kfold does not throw an error for non mcmc models", { SW(fito <- stan_glm(mpg ~ wt, data = mtcars, algorithm = "optimizing", seed = 1234L, refresh = 0)) SW(k <- kfold(fito, K = 2)) expect_true("kfold" %in% class(k)) }) test_that("kfold throws error if K <= 1 or K > N", { expect_error(kfold(example_model, K = 1), "K > 1", fixed = TRUE) expect_error(kfold(example_model, K = 1e5), "K <= nobs(x)", fixed = TRUE) }) test_that("kfold throws error if folds arg is bad", { expect_error(kfold(example_model, K = 2, folds = 1:100), "length(folds) == N is not TRUE", fixed = TRUE) expect_error(kfold(example_model, K = 2, folds = 1:2), "length(folds) == N is not TRUE", fixed = TRUE) expect_error(kfold(example_model, K = 2, folds = seq(1,100, length.out = 56)), "all(folds == as.integer(folds)) is not TRUE", fixed = TRUE) }) test_that("kfold throws error if model has weights", { SW( fit <- stan_glm(mpg ~ wt, data = mtcars, iter = ITER, chains = CHAINS, refresh = 0, weights = runif(nrow(mtcars), 0.5, 1.5)) ) expect_error(kfold(fit), "not currently available for models fit using weights") }) test_that("kfold works on some examples", { mtcars2 <- mtcars mtcars2$wt[1] <- NA SW( fit_gaus <- stan_glm(mpg ~ wt, data = mtcars2, refresh = 0, chains = 1, iter = 10) ) SW(kf <- kfold(fit_gaus, 2)) SW(kf2 <- kfold(example_model, 2)) expect_named(kf, c("estimates", "pointwise", "elpd_kfold", "se_elpd_kfold", "p_kfold", "se_p_kfold")) expect_named(kf2, c("estimates", "pointwise", "elpd_kfold", "se_elpd_kfold", "p_kfold", "se_p_kfold")) expect_named(attributes(kf), c("names", "class", "K", "dims", "model_name", "discrete", "yhash", "formula")) expect_named(attributes(kf2), c("names", "class", "K", "dims", "model_name", "discrete", "yhash", "formula")) expect_s3_class(kf, c("kfold", "loo")) expect_s3_class(kf2, c("kfold", "loo")) expect_false(is.na(kf$p_kfold)) expect_false(is.na(kf2$p_kfold)) SW(kf <- kfold(fit_gaus, K = 2, save_fits = TRUE)) expect_true("fits" %in% names(kf)) expect_s3_class(kf$fits[[1, "fit"]], "stanreg") expect_type(kf$fits[[2, "omitted"]], "integer") expect_length(kf$fits[[2, "omitted"]], 16) }) test_that("loo_compare throws correct errors", { SW(capture.output({ mtcars$mpg <- as.integer(mtcars$mpg) fit1 <- stan_glm(mpg ~ wt, data = mtcars, iter = 5, chains = 2, refresh = 0) fit2 <- update(fit1, data = mtcars[-1, ]) fit3 <- update(fit1, formula. = log(mpg) ~ .) fit4 <- update(fit1, family = poisson("log")) l1 <- loo(fit1, cores = LOO.CORES) l2 <- loo(fit2, cores = LOO.CORES) l3 <- loo(fit3, cores = LOO.CORES) l4 <- loo(fit4, cores = LOO.CORES) w1 <- waic(fit1) k1 <- kfold(fit1, K = 3) })) expect_error(loo_compare(l1, l2), "Not all models have the same number of data points") expect_error(loo_compare(list(l4, l2, l3)), "Not all models have the same number of data points") fit1$loo <- l1 fit2$loo <- l2 fit3$loo <- l3 fit4$loo <- l4 expect_error(loo_compare(fit1, fit2), "Not all models have the same number of data points") expect_warning(loo_compare(fit1, fit3), "Not all models have the same y variable") expect_error(loo_compare(fit1, fit4), "Discrete and continuous observation models can't be compared") expect_error(loo_compare(l1, fit1), "All inputs should have class 'loo'") expect_error(loo_compare(l1), "requires at least two models") }) test_that("loo_compare works", { suppressWarnings(capture.output({ mtcars$mpg <- as.integer(mtcars$mpg) fit1 <- stan_glm(mpg ~ wt, data = mtcars, iter = 40, chains = 2, refresh = 0) fit2 <- update(fit1, formula. = . ~ . + cyl) fit3 <- update(fit2, formula. = . ~ . + gear) fit4 <- update(fit1, family = "poisson") fit5 <- update(fit1, family = "neg_binomial_2") fit1$loo <- loo(fit1, cores = LOO.CORES) fit2$loo <- loo(fit2, cores = LOO.CORES) fit3$loo <- loo(fit3, cores = LOO.CORES) fit4$loo <- loo(fit4, cores = LOO.CORES) fit5$loo <- loo(fit5, cores = LOO.CORES) k1 <- kfold(fit1, K = 2) k2 <- kfold(fit2, K = 2) k3 <- kfold(fit3, K = 3) k4 <- kfold(fit4, K = 2) k5 <- kfold(fit5, K = 2) })) expect_false(attr(fit1$loo, "discrete")) expect_false(attr(fit2$loo, "discrete")) expect_false(attr(fit3$loo, "discrete")) expect_true(attr(fit4$loo, "discrete")) expect_true(attr(fit5$loo, "discrete")) comp1 <- loo_compare(fit1, fit2) comp2 <- loo_compare(fit1, fit2, fit3) expect_s3_class(comp1, "compare.loo") expect_s3_class(comp2, "compare.loo") expect_equal(comp1[, "elpd_diff"], loo_compare(list(fit1$loo, fit2$loo))[, "elpd_diff"]) expect_equal(comp2[, "elpd_diff"], loo_compare(list(fit1$loo, fit2$loo, fit3$loo))[, "elpd_diff"]) comp1_detail <- loo_compare(fit1, fit2, detail=TRUE) expect_output(print(comp1_detail), "Model formulas") expect_equivalent(comp2, loo_compare(stanreg_list(fit1, fit2, fit3))) expect_warning(comp3 <- loo_compare(k1, k2, k3), "Not all kfold objects have the same K value") expect_true(attr(k4, "discrete")) expect_true(attr(k5, "discrete")) expect_s3_class(loo_compare(k4, k5), "compare.loo") }) context("loo and waic helpers") test_that("kfold_and_reloo_data works", { f <- rstanarm:::kfold_and_reloo_data d <- f(example_model) expect_identical(d, lme4::cbpp[, colnames(d)]) y <- rnorm(40) SW(fit <- stan_glm(y ~ 1, iter = ITER, chains = CHAINS, refresh = 0)) expect_equivalent(f(fit), model.frame(fit)) SW(fit2 <- stan_glm(mpg ~ wt, data = mtcars, subset = gear != 5, iter = ITER, chains = CHAINS, refresh = 0)) expect_equivalent(f(fit2), subset(mtcars[mtcars$gear != 5, c("mpg", "wt")])) }) test_that(".weighted works", { f <- rstanarm:::.weighted expect_equal(f(2, NULL), 2) expect_equal(f(2, 3), 6) expect_equal(f(8, 0.25), 2) expect_error(f(2), "missing, with no default") })
ghosh.inv <- function(Z = NULL, X, B, RS_label, regions){ if(!missing(regions)){ if("InputOutput" %in% class(Z)){ RS_label <- Z$RS_label if(class(regions) == "character"){ for(k in 1:length(regions)){ if(!regions[k] %in% RS_label[, 1]) stop(paste(regions[k], "is not a region in RS_label. Check spelling, capitalization, and punctuation.")) } } else if(class(regions) == "numeric" | class(regions) == "integer"){ region <- unique(RS_label[, 1]) regions <- region[regions] } } else if(!"InputOutput" %in% class(Z)){ if(missing(RS_label)) stop("Missing RS_label. This is needed to select the correct elements of Z and X to calculate the Leontief inverse.") if(class(regions) == "character"){ for(k in 1:length(regions)){ if(!regions[k] %in% RS_label[, 1]) stop(paste(regions[k], "is not a region in RS_label. Check spelling, capitalization, and punctuation.")) } } else if(class(regions) == "numeric" | class(regions) == "integer"){ region <- unique(RS_label[, 1]) regions <- region[regions] } } } if("InputOutput" %in% class(Z)){ B <- Z$B if(missing(regions)){ n <- dim(B)[1] I <- diag(n) duration <- round(8e-10 * n^3/60, 2) if(duration >= 0.1){ print(paste("Calculating the Ghoshian inverse. Should take roughtly", duration, "minutes.")) } G <- solve(I - B) } else if(!missing(regions)){ RS_label <- Z$RS_label B <- Z$B i <- which(RS_label[, 1] %in% regions) B <- B[i, i] n <- length(i) I <- diag(n) duration <- round(8e-10 * n^3/60, 2) if(duration >= 0.1){ print(paste("Calculating the Ghoshian inverse. Should take roughtly", duration, "minutes.")) } G <- solve(I - B) } } else{ if(missing(B)){ if(dim(Z)[1] != dim(Z)[2]) stop("The intermediate transaction (Z) matrix needs to be a square matrix") if(dim(Z)[1] != length(X)) stop("Check dimensions/length; Z should be a nxn matrix and X should be a nx1 vector") n <- length(X) if(n > 1500){ print("Calculating Intermediate Transaction Matrix (A)...") } xhat <- diag(c(1/X)) B <- Z * xhat } n <- dim(B)[1] if(missing(regions)){ I <- diag(n) duration <- round(8e-10 * n^3/60, 2) if(duration >= 0.1){ print(paste("Calculating the Ghoshian inverse. Should take roughtly", duration, "minutes.")) } G <- solve(I - B) } else if(!missing(regions)){ i <- which(RS_label[, 1] %in% regions) B <- B[i, i] n <- length(i) I <- diag(n) duration <- round(8e-10 * n^3/60, 2) if(duration >= 0.1){ print(paste("Calculating the Ghoshian inverse. Should take roughtly", duration, "minutes.")) } G <- solve(I - B) } } G }
context("Displaying the graph's metagraph") test_that("the display of the metagraph works", { property_graph <- create_graph() %>% add_gnm_graph( n = 100, m = 135, set_seed = 23) %>% select_nodes_by_degree( expressions = "deg >= 3") %>% set_node_attrs_ws( node_attr = type, value = "a") %>% clear_selection() %>% select_nodes_by_degree( expressions = "deg < 3") %>% set_node_attrs_ws( node_attr = type, value = "b") %>% clear_selection() %>% select_nodes_by_degree( expressions = "deg == 0") %>% set_node_attrs_ws( node_attr = type, value = "c") %>% set_node_attr_to_display( attr = type) %>% select_edges_by_node_id( nodes = get_node_ids(.) %>% sample( size = 0.15 * length(.) %>% floor())) %>% set_edge_attrs_ws( edge_attr = rel, value = "r_1") %>% invert_selection() %>% set_edge_attrs_ws( edge_attr = rel, value = "r_2") %>% clear_selection() %>% copy_edge_attrs( edge_attr_from = rel, edge_attr_to = label) metagraph_object <- display_metagraph(property_graph) expect_is( metagraph_object, c("grViz", "htmlwidget")) })
init3ordered<-function (x, p, q, r, x0) { nom <- dimnames(x) n <- dim(x) dimnames(x) <- NULL dimnames(x0) <- NULL y <- x0 dimnames(y) <- NULL dim(y) <- c(n[1], n[2] * n[3]) pii <- apply(y/sum(y), 1, sum) p <- min(p, n[1]) mj <- c(1:n[1]) Bpoly <- emerson.poly(mj, pii) Bpoly <- Bpoly[,-c(1) ] a <- diag(sqrt(pii)) %*% Bpoly[,1:p] y <- aperm(x0, c(2, 3, 1)) dim(y) <- c(n[2], n[3] * n[1]) pj <- apply(y/sum(y), 1, sum) q <- min(q, n[2]) mj <- c(1:n[2]) Bpoly <- emerson.poly(mj, pj) Bpoly <- Bpoly[,-c(1) ] b <- diag(sqrt(pj)) %*% Bpoly[, 1:q] y <- aperm(x0, c(3, 1, 2)) dim(y) <- c(n[3], n[1] * n[2]) pk <- apply(y/sum(y), 1, sum) r <- min(r, n[3]) mj <- c(1:(n[3])) Bpoly <- emerson.poly(mj, pk) Bpoly <- Bpoly[,-c(1) ] cc <- diag(sqrt(pk)) %*% Bpoly[, 1:r] dimnames(x) <- nom xsf <- flatten(x) bc <- Kron(b, cc) Z <- t(a) %*% xsf %*% bc list(a = as.matrix(a), b = as.matrix(b), cc = as.matrix(cc), g = NULL, x = x,pii=pii,pj=pj,pk=pk) }
finproducts = c('Mutual Funds', 'NPS', 'Savings Account', 'PPF', 'FD', 'Bonds', 'Stocks', 'General Insurance', 'NRI Banking', 'Car Insurance', 'Debit Card', 'Credit Card', 'Mobile Banking') finproducts
e2e_run <- function(model, nyears=20, quiet=TRUE, csv.output=FALSE) { oo <- options() on.exit(options(oo)) pkg.env$quiet <- quiet pkg.env$csv.output <- csv.output build <- build_model(model, nyears) output <- StrathE2E.run(build) aggregates <- aggregate_model_output(model, output) total.annual.catch <- extract_timeseries_annual_landings(model, build, output) annual.catch.by.gear <- disaggregate_landings_discards_by_gear(elt(build, "fleet.output"), total.annual.catch) catch.land.disc <- extract_simulated_catch_land_disc_by_gear_for_given_year(model, annual.catch.by.gear) monthly.averages <- monthly_averages_of_final_year(model, build, output, aggregates) annual.results.wholedomain <- derive_annual_results_wholedomain(model, build, output, aggregates) annual.results.offshore <- derive_annual_results_offshore(model, build, output, aggregates) annual.results.inshore <- derive_annual_results_inshore(model, build, output, aggregates) flow.matrices <- assemble_flow_matrix_from_model_annual_output(model, build, output, aggregates) model.path <- elt(model, "setup", "model.path") annual.target.data <- read_annual_target_data(model.path) monthly.target.data <- read_monthly_target_data(model.path) model.target.results <- derive_model_target_results(model, build, output, aggregates, annual.target.data) fit.to.target.data <- calculate_error_function(model, model.target.results) results <- list( build = list( model.parameters = elt(build, "model.parameters"), run = elt(build, "run"), drivers = elt(build, "drivers"), forcings = elt(build, "forcings") ), output = output, aggregates = aggregates, fleet.output = elt(build, "fleet.output"), total.annual.catch = total.annual.catch, annual.catch.by.gear = annual.catch.by.gear, final.year.outputs = list( inshore_catchmat = elt(catch.land.disc, "inshore_catchmat"), inshore_discmat = elt(catch.land.disc, "inshore_discmat"), inshore_landmat = elt(catch.land.disc, "inshore_landmat"), offshore_catchmat = elt(catch.land.disc, "offshore_catchmat"), offshore_landmat = elt(catch.land.disc, "offshore_landmat"), offshore_discmat = elt(catch.land.disc, "offshore_discmat"), monthly.averages = monthly.averages, mass_results_inshore = elt(annual.results.inshore, "mass_results"), maxmass_results_inshore = elt(annual.results.inshore, "maxmass_results"), minmass_results_inshore = elt(annual.results.inshore, "minmass_results"), annual_flux_results_inshore = elt(annual.results.inshore, "annual_flux_results"), mass_results_offshore = elt(annual.results.offshore, "mass_results"), maxmass_results_offshore = elt(annual.results.offshore, "maxmass_results"), minmass_results_offshore = elt(annual.results.offshore, "minmass_results"), annual_flux_results_offshore = elt(annual.results.offshore, "annual_flux_results"), mass_results_wholedomain = elt(annual.results.wholedomain, "mass_results"), maxmass_results_wholedomain = elt(annual.results.wholedomain, "maxmass_results"), minmass_results_wholedomain = elt(annual.results.wholedomain, "minmass_results"), annual_flux_results_wholedomain = elt(annual.results.wholedomain, "annual_flux_results"), flow_matrix_all_fluxes = elt(flow.matrices, "flow_matrix_all_fluxes"), flow_matrix_excl_spawn_recruit = elt(flow.matrices, "flow_matrix_excl_spawn_recruit"), NetworkIndexResults = elt(flow.matrices, "NetworkIndexResults"), annual.target.data = annual.target.data, monthly.target.data = monthly.target.data, annual_obj = elt(fit.to.target.data, "annual_obj"), partial_chi = elt(fit.to.target.data, "partial_chi"), opt_results = elt(fit.to.target.data, "opt_results") ) ) results }
import_local <- function(path, station_code, trace = FALSE, collMethd = c('1', '2')){ if(file.exists(paste0(path, '.zip'))){ path <- paste0(path, '.zip') } if(!file.exists(path)){ stop('Path does not exist') } if(!grepl('wq|met|nut', station_code)) stop('station_code must include wq, met, or nut') zips <- grepl('\\.zip$', path) station_code <- tolower(gsub('\\.csv$', '', station_code)) if(zips){ file_nms <- unzip(path, list = TRUE)$Name expr <- paste0(station_code, '.*', '\\.csv$') files_in <- grep(expr, file_nms, value = TRUE, ignore.case = TRUE) if(length(files_in) == 0) stop('File(s) not found.') tmp_fl <- tempfile() unzip(path, files = files_in, exdir = tmp_fl) files_in <- dir(tmp_fl, recursive = TRUE) path <- tmp_fl } else { file_nms <- dir(path) expr <- paste0('^', station_code, '.*', '\\.csv$') } files_in <- grep(expr, file_nms, value = TRUE, ignore.case = TRUE) if(length(files_in) == 0) stop('File(s) not found.') station_code <- tolower(station_code) dat <- vector('list', length(files_in)) names(dat) <- gsub('.csv', '', files_in) if(trace) cat('Loading files...\n\n') for(file_in in files_in){ if(trace) cat(file_in, '\t') tmp <- try({ read.csv(file.path(path, file_in), stringsAsFactors = FALSE) }, silent = TRUE) if('try-error' %in% class(tmp)){ raw <- readLines(file.path(path, file_in)) keep_lines <- grep(paste0('^', station_code), raw) tmp <- raw[keep_lines] tmp <- strsplit(tmp, ',') tmp <- do.call('rbind', tmp) tmp <- data.frame(tmp, stringsAsFactors = FALSE) names(tmp) <- strsplit( gsub('["\\"]', '', raw[keep_lines[1] - 1]), ',')[[1]] } names(tmp) <- tolower(names(tmp)) tmp <- tmp[, !names(tmp) %in% c('stationcode', 'isswmp')] names(tmp)[grep('datetimestamp', names(tmp), ignore.case = TRUE)] <- 'datetimestamp' tmp$datetimestamp <- time_vec(tmp$datetimestamp, station_code) nm <- gsub('.csv', '', file_in) dat[[nm]] <- tmp } if(zips) unlink(tmp_fl, recursive = TRUE) parm <- substring(station_code, 6) parm <- gsub('[0-9.*]', '', parm) nms <- param_names(parm)[[parm]] out <- do.call('rbind', dat) if('met' %in% parm & any(duplicated(out$datetimestamp)) & 'frequency' %in% names(out)){ min_step <- as.character(min(as.numeric(unique(out$frequency)))) out <- out[out$frequency %in% min_step, ] out <- out[!duplicated(out$datetimestamp),] } if(any(c('nut', 'wq') %in% parm) & any(duplicated(out$datetimestamp))){ out <- out[!duplicated(out$datetimestamp),] } out <- out[!is.na(out$datetimestamp), ] if(parm == 'nut'){ if(length(unique(out$collmethd)) == 2){ out <- out[out$collmethd %in% collMethd, ] }else{ warning('This station does not have diel sampling data. All data will be retained.', call. = FALSE) out <- out } } out <- data.frame( datetimestamp = out$datetimestamp, out[, names(out) %in% nms], row.names = seq(1, nrow(out)) ) parameters <- grep('datetimestamp|^f_|^c_', names(out), invert = TRUE, value = TRUE) out[, parameters] <- suppressWarnings( lapply(out[, parameters], function(x) as.numeric(as.character(x))) ) names(out) <- tolower(names(out)) station_code <- gsub('[0-9]*$', '', station_code) out <- swmpr(out, station_code) if(trace) cat('\n\nData imported...') return(out) }
new_rational <- function(n = integer(), d = integer()) { vec_assert(n, ptype = integer()) vec_assert(d, ptype = integer()) new_rcrd(list(n = n, d = d), class = "vctrs_rational") } rational <- function(n, d) { args <- vec_cast_common(n, d, .to = integer()) args <- vec_recycle_common(!!! args) new_rational(args[[1L]], args[[2L]]) } format.vctrs_rational <- function(x, ...) { n <- field(x, "n") d <- field(x, "d") out <- paste0(n, "/", d) out[is.na(n) | is.na(d)] <- NA out } vec_proxy_equal.vctrs_rational <- function(x) { n <- field(x, "n") d <- field(x, "d") gcd <- gcd(n, d) data.frame(n = n / gcd, d = d / gcd) } gcd <- function(x, y) { r <- x %% y ifelse(r, gcd(y, r), y) } vec_proxy_compare.vctrs_rational <- function(x, ...) { field(x, "n") / field(x, "d") } rational_methods <- list( vec_ptype_abbr.vctrs_rational = function(x, ...) "rtnl", vec_ptype_full.vctrs_rational = function(x, ...) "rational", vec_ptype2.vctrs_rational = function(x, y, ...) UseMethod("vec_ptype2.vctrs_rational"), vec_ptype2.vctrs_rational.vctrs_rational = function(x, y, ...) new_rational(), vec_ptype2.vctrs_rational.integer = function(x, y, ...) new_rational(), vec_ptype2.integer.vctrs_rational = function(x, y, ...) new_rational(), vec_cast.vctrs_rational = function(x, to, ...) UseMethod("vec_cast.vctrs_rational"), vec_cast.vctrs_rational.vctrs_rational = function(x, to, ...) x, vec_cast.double.vctrs_rational = function(x, to, ...) field(x, "n") / field(x, "d"), vec_cast.vctrs_rational.integer = function(x, to, ...) rational(x, 1), vec_proxy_equal.vctrs_rational = vec_proxy_equal.vctrs_rational, vec_proxy_compare.vctrs_rational = vec_proxy_compare.vctrs_rational ) local_rational_class <- function(frame = caller_env()) { local_methods(.frame = frame, !!!rational_methods) }