code
stringlengths
1
13.8M
`MaxZoom` <-structure(function ( latrange, lonrange, size = c(640,640) ){ SinPhi = sin(latrange * pi /180); normX = lonrange / 180; normY = (0.5 * log(abs((1 + SinPhi) / (1 -SinPhi) )) ) / pi; MaxZoom.lon <- floor(1 + log2(abs(size[1]/256/diff(normX)))); MaxZoom.lat <- floor(1 + log2(abs(size[2]/256/diff(normY)))); return(min(c(MaxZoom.lat=MaxZoom.lat,MaxZoom.lon=MaxZoom.lon))) })
library("containerit") context("Install packages from Bioconductor") test_that("installation instruction for Bioconductor package is created", { skip_if(Sys.getenv("R_VERSION") == "devel") output <- capture_output({ capture_warnings({ if (!require("BiocGenerics", character.only = TRUE)) BiocManager::install(c("BiocGenerics")) }) info <- containerit::clean_session(expr = quote(library("BiocGenerics"))) the_dockerfile <- dockerfile(info, maintainer = "o2r", image = getImageForVersion("3.3.2")) }) expected_file <- readLines("./bioconductor/Dockerfile") generated_file <- unlist(stringr::str_split(toString(the_dockerfile),"\n")) expect_equal(generated_file, expected_file) })
dloglognorm <- function(x, mean=0, sd=1) .Call("dloglognorm", x, mean, sd, PACKAGE="loglognorm") ploglognorm <- function(q, mean=0, sd=1) .Call("ploglognorm", q, mean, sd, PACKAGE="loglognorm") qloglognorm <- function(p, mean=0, sd=1) .Call("qloglognorm", p, mean, sd, PACKAGE="loglognorm") rloglognorm <- function(n, mean=0, sd=1) .Call("qloglognorm", runif(n), mean=mean, sd=sd, PACKAGE="loglognorm") mloglognorm <- function(moment, mean, sd) .Call("mloglognorm", moment, mean, sd, PACKAGE="loglognorm") eloglognorm <- function(mean, sd) .Call("mloglognorm", 1, mean, sd, PACKAGE="loglognorm") vloglognorm <- function(mean, sd) { m1 <- mloglognorm(1, mean, sd) m2 <- mloglognorm(2, mean, sd) return (m2 - m1^2) }
contPFarrivals <- function(PF, stas, proj=NULL, cont=TRUE, POINTS=TRUE, image=FALSE , col=RSEIS::tomo.colors(50), gcol="black", phase="P", add=TRUE) { if(missing(proj)) proj = NULL if(missing(cont)) cont=TRUE if(missing(POINTS)) POINTS=TRUE if(missing(image)) image=FALSE if(missing(col)) col=RSEIS::tomo.colors(50) NEX = 50 if(length(PF$STAS$sec)<1) { print("ERROR: not enough station observations, no contouring") return(NULL) } pstas = PF$STAS if(missing( phase)) { if(any(pstas$phase=="P")) { phase = "P" } if(!any(pstas$phase=="P")) { if(any(pstas$phase=="S")) { phase = "S" } } if(!any(pstas$phase=="P") & !any(pstas$phase=="S" ) ) { phase = "G" } } w1 = which.min(pstas$sec) if(length(w1)<1) { return(NULL) } wp = which(pstas$phase==phase & !is.na(pstas$lat) & !is.na(pstas$lon) ) if(length(wp)<2) { return(NULL) } stan = pstas$name[wp] arr = pstas$sec[wp] - pstas$sec[w1] if(is.null(proj)) proj = GEOmap::setPROJ(type=2, LAT0 =median(stas$lat) , LON0 = median(stas$lon) ) XY = GEOmap::GLOB.XY(stas$lat, stas$lon, proj) if(!add) { plot(XY, pch=6, xlab="km", ylab="km" , cex=.6 ) } msta = match(stan, stas$name) msta = msta[!is.na(msta)] if(length(msta)<3) { print("ERROR: not enough matching stations, no contouring") return(NULL) } xy = GEOmap::GLOB.XY( pstas$lat[wp] , pstas$lon[wp], proj) ex = seq(from=min(xy$x), to=max(xy$x), length=NEX) why = seq(from=min(xy$y), to=max(xy$y), length=NEX) DF = cbind(x=xy$x , y=xy$y , z=arr) zed = MBA::mba.surf(DF, NEX, NEX, n = 1, m = 1, h = 8, extend=FALSE)$xyz.est if(image) image(zed, col=col , add=TRUE) if(POINTS) { text(XY, labels=stas$name, pos=3, cex=.6) points(XY$x[msta] , XY$y[msta], col='red', cex=1.1) } if(cont) { contour(zed, add=TRUE, col='blue' ) } return(proj) }
chartype_frame <- function() { chars <- character() desc <- character() chars[1] <- "\u0001\u001f" desc[1] <- "C0 control code" chars[2] <- "\a\b\f\n\r\t" desc[2] <- "Named control code" chars[3] <- "abcdefuvwxyz" desc[3] <- "ASCII" chars[4] <- "\u0080\u009f" desc[4] <- "C1 control code" chars[5] <- paste0( "\u00a0\u00a1\u00a2\u00a3\u00a4\u00a5", "\u00fa\u00fb\u00fc\u00fd\u00fe\u00ff" ) desc[5] <- "Latin-1" chars[6] <- paste0( "\u0100\u0101\u0102\u0103\u0104\u0105", "\u0106\u0107\u0108\u0109\u010a\u010b" ) desc[6] <- "Unicode" chars[7] <- "\uff01\uff02\uff03\uff04\uff05\uff06" desc[7] <- "Unicode wide" chars[8] <- "\ue00\u2029" desc[8] <- "Unicode control" chars[9] <- paste0( "x\u00adx\u200bx\u200cx\u200dx\u200ex\u200f", "x\u034fx\ufeffx", intToUtf8(0xE0001), "x", intToUtf8(0xE0020), "x", intToUtf8(0xE01EF), "x" ) desc[9] <- "Unicode ignorable" chars[10] <- paste0( "a\u0300a\u0301a\u0302a\u0303a\u0304a\u0305", "a\u0306a\u0307a\u0308a\u0309a\u030aa\u030b" ) desc[10] <- "Unicode mark" chars[11] <- paste0( intToUtf8(0x1F600), intToUtf8(0x1F601), intToUtf8(0x1F602), intToUtf8(0x1F603), intToUtf8(0x1F604), intToUtf8(0x1F483) ) desc[11] <- "Emoji" chars[12] <- paste0("x", intToUtf8(0x10ffff), "x") desc[12] <- "Unassigned" chars[13] <- "\xfd\xfe\xff" desc[13] <- "Invalid" chars[14] <- "\\" desc[14] <- "Backslash" chars[15] <- '"' desc[15] <- "Quote" Encoding(chars) <- "UTF-8" data.frame(chars, desc, stringsAsFactors = FALSE) } test_that("output test (not on Windows)", { skip_if(getRversion() < "4.0") skip_on_os("windows") skip_if_not_installed("testthat", "1.3.3") suppressWarnings( expect_snapshot({ colonnade(chartype_frame(), width = 50) }) ) })
coef.basad <- function(object, ...) { verboseList <- object$verbose print(round(object$all.var, 4)) }
library(countrycode) library(readr) library(anytime) library(ggplot2) library(lubridate) library(tidyverse) library(data.table) lmort <- data.frame(read_csv("source-data/local_mortality.csv")) lmort$iso3c <- countrycode(lmort$country_name, "country.name", "iso3c") lmort$years_of_observations <- ave(lmort$year, lmort$local_unit_name, FUN = function(x) length(unique(x))) lmort <- lmort[lmort$years_of_observations >= 4, ] lmort <- lmort[!lmort$local_unit_name %in% c("Aden Governorate", "Damascus City", "Istanbul City", "Ankara City", "Hyderabad"), ] lmort <- lmort[lmort$local_unit_name != "Chennai City", ] lmort$expected_deaths <- NA lmort$expected_deaths[!lmort$local_unit_name %in% c("Jakarta Province", "Mumbai City", "Kolkata City")] <- predict(newdata = lmort[!lmort$local_unit_name %in% c("Jakarta Province", "Mumbai City", "Kolkata City"), ], lm(deaths ~ as.factor(local_unit_name)*as.factor(time)+as.factor(local_unit_name), data = lmort[lmort$year <= 2019 & !lmort$local_unit_name %in% c("Jakarta Province", "Mumbai City", "Kolkata City"), ])) lmort$expected_deaths[lmort$local_unit_name %in% c("Jakarta Province", "Mumbai City", "Kolkata City")] <- predict(newdata = lmort[lmort$local_unit_name %in% c("Jakarta Province", "Mumbai City", "Kolkata City"), ], lm(deaths ~ as.factor(local_unit_name)*year+as.factor(local_unit_name)*as.factor(time)+as.factor(local_unit_name), data = lmort[lmort$year <= 2019 & lmort$local_unit_name %in% c("Jakarta Province", "Mumbai City", "Kolkata City"), ])) dates <- data.frame(date = as.Date("2010-01-01"):as.Date("2025-01-01"), week = NA, month = NA) dates$date <- as.Date(dates$date, origin ="1970-01-01") dates$week <- week(dates$date) dates$month <- month(dates$date) dates$year <- year(dates$date) lmort$ID <- 1:nrow(lmort) monthly <- merge(lmort[lmort$time_unit == "monthly", ], dates, by.x = c("year", "time"), by.y = c("year", "month")) weekly <- merge(lmort[lmort$time_unit == "weekly", ], dates, by.x = c("year", "time"), by.y = c("year", "week")) lmort <- rbind(monthly[, intersect(colnames(monthly), colnames(weekly))], weekly[, intersect(colnames(monthly), colnames(weekly))]) lmort$n_obs <- ave(lmort$ID, lmort$ID, FUN = length) lmort$n_obs[lmort$time_unit == "weekly"] <- 7 lmort$expected_deaths <- lmort$expected_deaths / lmort$n_obs lmort$deaths <- lmort$deaths / lmort$n_obs lmort$excess_deaths <- lmort$deaths - lmort$expected_deaths inspect = T if(inspect){ ggplot(lmort[lmort$year %in% 2015:2021,], aes(x=date, y=deaths/1000))+geom_line()+facet_wrap(.~local_unit_name)+geom_line(aes(y=expected_deaths/1000, col = "expected deaths"), alpha = 0.5)+scale_y_continuous(trans = "log10") ggplot(lmort[lmort$year %in% 2015:2021,], aes(x=date, y=excess_deaths))+geom_line()+facet_wrap(.~local_unit_name) } lmort$name <- lmort$local_unit_name for(i in unique(lmort$name)){ temp <- cbind(dates, lmort[lmort$name == i, ][1, setdiff(colnames(lmort), colnames(dates))]) for(v in c("deaths", "expected_deaths", "excess_deaths", "ID", "n_obs")){ temp[, v] <- NA } lmort <- rbind(lmort, temp[!temp$date %in% lmort$date[lmort$name ==i], colnames(lmort)]) } lmort$population <- NA lmort$population[lmort$local_unit_name == "Tamil Nadu State"] <- 82722262 lmort$population[lmort$local_unit_name == "Madhya Pradesh State"] <- 86044251 lmort$population[lmort$local_unit_name == "Andhra Pradesh State"] <- 53206421 lmort$population[lmort$local_unit_name == "Mumbai City"] <- 13047654 lmort$population[lmort$local_unit_name == "Kolkata City"] <- 15634592 lmort$population[lmort$local_unit_name == "Jakarta Province"] <- 10800000 coordinates <- rbind.data.frame( c("Tamil Nadu State", 13.0836939, 80.270186, "10°45'N", "78°34'E"), c("Mumbai City", 19.0759899, 72.8773928, 19.0759899, 72.8773928), c("Jakarta Province", "-6°12′N", "106°49′E", "-6°12′N", "106°49′E"), c("Kolkata City", "22°34′N", "88°22′E", "22°34′N", "88°22′E"), c("Madhya Pradesh State", "22°43′N", "75°50′E", "23°48′N", "78°28′E"), c("Andhra Pradesh State", "17°42′N", "83°17′E", 16.50, 80.64)) library(measurements) colnames(coordinates) <- c("name", "lat_largest_city", "lng_largest_city", "centroid_lat", "centroid_long") for(i in 2:ncol(coordinates)){coordinates[, i] <- as.character(coordinates[, i])} for(i in 1:nrow(coordinates)){ for(j in 2:ncol(coordinates)){ if(is.na(as.numeric(coordinates[i, j]))){ coordinates[i, j] <- gsub("°", " ", coordinates[i, j]) coordinates[i, j] <- gsub("′N", "", coordinates[i, j]) coordinates[i, j] <- gsub("′E", "", coordinates[i, j]) coordinates[i, j] <- measurements::conv_unit(coordinates[i, j], from = 'deg_dec_min', to = 'dec_deg') } } } for(i in 2:ncol(coordinates)){coordinates[, i] <- as.numeric(coordinates[, i])} inspect = F if(inspect){ library(tidyverse) world <- map_data("world") ggplot() + geom_map( data = world, map = world, aes(map_id = region), color = "black", size = 0.1)+ geom_point(data = coordinates, aes(x= lng_largest_city, y= lat_largest_city, col = name))+ geom_point(data = coordinates, aes(x= centroid_long, y= centroid_lat, col = name), alpha = 0.3)+theme_minimal() } mob_raw <- fread("https://www.gstatic.com/covid19/mobility/Global_Mobility_Report.csv") mob <- mob_raw mob$name <- NA mob$name[mob$sub_region_1 == "Jakarta"] <- "Jakarta Province" mob$name[mob$sub_region_1 == "Andhra Pradesh" & mob$sub_region_2 == ""] <- "Andhra Pradesh State" mob$name[mob$sub_region_1 == "Madhya Pradesh" & mob$sub_region_2 == ""] <- "Madhya Pradesh State" mob$name[mob$sub_region_1 == "Tamil Nadu" & mob$sub_region_2 == ""] <- "Tamil Nadu State" mob$name[mob$sub_region_2 == "Kolkata"] <- "Kolkata City" mob$name[mob$sub_region_2 == "Mumbai"] <- "Mumbai City" mob <- mob[!is.na(mob$name), ] inspect = F if(inspect){ library(ggplot2) ggplot(mob, aes(x=date, y=residential_percent_change_from_baseline, col = name))+geom_line() } mob <- mob %>% mutate( iso3c = paste0(countrycode(country_region_code, "iso2c", "iso3c"), "_", name), ) %>% rename( mobility_retail_rec_pct_of_baseline = retail_and_recreation_percent_change_from_baseline, mobility_grocery_and_pharma_pct_of_baseline = grocery_and_pharmacy_percent_change_from_baseline, mobility_parks_pct_of_baseline = parks_percent_change_from_baseline, mobility_transit_rec_pct_of_baseline = transit_stations_percent_change_from_baseline, mobility_workplaces_rec_pct_of_baseline = workplaces_percent_change_from_baseline, ) %>% select(name, date, mobility_retail_rec_pct_of_baseline, mobility_grocery_and_pharma_pct_of_baseline, mobility_parks_pct_of_baseline, mobility_transit_rec_pct_of_baseline, mobility_workplaces_rec_pct_of_baseline) ind_states <- read_csv("source-data/ind_states_ts.csv") ind_states$name <- NA ind_states$name[ind_states$State == "Tamil Nadu"] <- "Tamil Nadu State" ind_states$name[ind_states$State == "Madhya Pradesh"] <- "Madhya Pradesh State" ind_states$name[ind_states$State == "Andhra Pradesh"] <- "Andhra Pradesh State" ind_states <- ind_states[!is.na(ind_states$name), ] ind_states$date <- ind_states$Date ind_states <- ind_states[order(ind_states$Date), ] ind_states$total_cases <- ind_states$Confirmed ind_states$total_deaths <- ind_states$Deceased ind_states$total_tests <- ind_states$Tested ind_states$new_cases <- ave(ind_states$total_cases, ind_states$name, FUN = function(x){ x <- x - c(0, x)[1:length(x)] }) ind_states$new_deaths <- ave(ind_states$total_deaths, ind_states$name, FUN = function(x){ x <- x - c(0, x)[1:length(x)] }) ind_states$new_tests <- ave(ind_states$total_tests, ind_states$name, FUN = function(x){ x <- x - c(0, x)[1:length(x)] }) ind_states <- ind_states[, c("name", "date", "total_cases", "total_deaths", "total_tests", "new_cases", "new_deaths", "new_tests")] ggplot(ind_states, aes(x=date))+geom_line(aes(y=total_tests))+facet_grid(.~name) ind_districts <- read_csv("source-data/ind_districts_ts.csv") ind_districts$name <- NA ind_districts$name[ind_districts$District == "Mumbai"] <- "Mumbai City" ind_districts$name[ind_districts$District == "Kolkata"] <- "Kolkata City" ind_districts <- ind_districts[!is.na(ind_districts$name), ] ind_districts$date <- ind_districts$Date ind_districts <- ind_districts[order(ind_districts$Date), ] ind_districts$total_cases <- ind_districts$Confirmed ind_districts$total_deaths <- ind_districts$Deceased ind_districts$total_tests <- ind_districts$Tested ind_districts$new_cases <- ave(ind_districts$total_cases, ind_districts$name, FUN = function(x){ x <- x - c(0, x)[1:length(x)] }) ind_districts$new_deaths <- ave(ind_districts$total_deaths, ind_districts$name, FUN = function(x){ x <- x - c(0, x)[1:length(x)] }) ind_districts$new_tests <- ave(ind_districts$total_tests, ind_districts$name, FUN = function(x){ x <- x - c(0, x)[1:length(x)] }) ind_districts <- ind_districts[, c("name", "date", "total_cases", "total_deaths", "total_tests", "new_cases", "new_deaths", "new_tests")] ggplot(ind_districts, aes(x=date))+geom_line(aes(y=total_cases))+facet_grid(.~name) jakarta <- read_csv("source-data/jakarta_ts.csv")[, 1:3] jakarta$date <- as.Date(jakarta$date, format = "%d/%m/%Y") jakarta <- jakarta[order(jakarta$date), ] jakarta$new_cases <- jakarta$total_cases - c(0, jakarta$total_cases)[1:nrow(jakarta)] jakarta$new_deaths <- jakarta$total_deaths - c(0, jakarta$total_deaths)[1:nrow(jakarta)] jakarta$total_tests <- NA jakarta$new_tests <- NA jakarta$name <- "Jakarta Province" jakarta <- jakarta[, c("name", "date", "total_cases", "total_deaths", "total_tests", "new_cases", "new_deaths", "new_tests")] sub_covid <- rbind(ind_states, ind_districts, jakarta) sub_covid$new_cases[sub_covid$new_cases < 0] <- NA sub_covid$new_deaths[sub_covid$new_deaths < 0] <- NA sub_covid$new_tests[sub_covid$new_tests < 0] <- NA dat <- merge(lmort, mob, by = c("date", "name"), all.x = T) dat <- merge(dat, coordinates, by = c("name"), all.x = T) dat <- merge(dat, sub_covid, by = c("date", "name"), all.x = T) dat <- dat[!is.na(dat$name), ] dat$total_cases[dat$date <= as.Date("2020-02-04") & dat$iso3c == "IND"] <- 0 dat$total_deaths[dat$date <= as.Date("2020-03-11") & dat$iso3c == "IND"] <- 0 dat$total_cases[dat$date <= as.Date("2020-03-07") & dat$iso3c == "IDN"] <- 0 dat$total_deaths[dat$date <= as.Date("2020-03-11") & dat$iso3c == "IDN"] <- 0 dat$new_cases[dat$date <= as.Date("2020-02-04") & dat$iso3c == "IND"] <- 0 dat$new_deaths[dat$date <= as.Date("2020-03-11") & dat$iso3c == "IND"] <- 0 dat$new_cases[dat$date <= as.Date("2020-03-07") & dat$iso3c == "IDN"] <- 0 dat$new_deaths[dat$date <= as.Date("2020-03-11") & dat$iso3c == "IDN"] <- 0 smooth <- function(x){ temp <- x for(i in 1:length(x)){ temp[i] <- mean(x[max(c(1,i-3)):min(c(length(x), i+3))], na.rm = T) } temp } dat <- dat[order(dat$date), ] dat$new_cases_smoothed <- ave(dat$new_cases, dat$name, FUN = smooth) dat$new_deaths_smoothed <- ave(dat$new_deaths, dat$name, FUN = smooth) dat$new_tests_smoothed <- ave(dat$new_tests, dat$name, FUN = smooth) dat <- dat %>% mutate( daily_total_deaths = deaths, daily_total_deaths_per_100k = deaths*100000/population, daily_expected_deaths = expected_deaths, daily_expected_deaths_per_100k = expected_deaths*100000/population, daily_excess_deaths = excess_deaths, daily_excess_deaths_per_100k = excess_deaths*100000/population, cumulative_daily_tests_per_100k = total_tests*1e5/population, cumulative_daily_covid_cases_per_100k = total_cases*1e5/population, cumulative_daily_covid_deaths_per_100k = total_deaths*1e5/population, daily_covid_deaths = new_deaths_smoothed, daily_covid_deaths_per_100k = (daily_covid_deaths / population) * 100000, daily_covid_cases = new_cases_smoothed, daily_covid_cases_per_100k = (daily_covid_cases / population) * 100000, daily_tests = new_tests_smoothed, daily_tests_per_100k = (daily_tests / population) * 100000, daily_positive_rate = (daily_covid_cases / daily_tests) * 100) %>% rename(centroid_latitude = centroid_lat, centroid_longitude = centroid_long, lat_capital = lat_largest_city, lng_capital = lng_largest_city) dat$population_density <- NA dat$population_density[dat$local_unit_name == "Jakarta Province" ] <- 15906.5 dat$population_density[dat$local_unit_name == "Kolkata City"] <- 22000 dat$population_density[dat$local_unit_name == "Tamil Nadu State"] <- 550 dat$population_density[dat$local_unit_name == "Mumbai City"] <- 21000 dat$population_density[dat$local_unit_name == "Andhra Pradesh State"] <- 308 dat$population_density[dat$local_unit_name == "Madhya Pradesh State"] <- 240 setdiff(colnames(country_daily_excess_deaths)[1:93], colnames(dat)) dat$daily_positive_rate[dat$daily_positive_rate > 100] <- NA dat <- dat[dat$date >= as.Date("2020-01-01"), ] dat <- dat[order(dat$date), ] leading_zeros <- function(x){ if(is.na(x[1]) & sum(is.na(x)) != length(x)){ x[1:min(which(!is.na(x))-1)] <- 0 } x } dat <- dat[order(dat$date), ] for(i in c("daily_covid_deaths", "daily_covid_deaths_per_100k", "daily_covid_cases", "daily_covid_cases_per_100k", "daily_total_deaths", "daily_total_deaths_per_100k")){ dat[, i] <- ave(dat[, i], dat$name, FUN = function(x) leading_zeros(x)) } saveRDS(dat, "output-data/model-objects/auxilliary_subnational_data.RDS")
gapCreation <- function(X, rate, begin=NULL){ Xgap <- X if(rate == 0){ warning("rate = 0, no gap created") return(X) } if(rate == 1){ stop("rate must be < 1") } gap_size <- round(rate*length(X)) if(is.null(begin)){ gap_id <- sample(1:(length(X)-gap_size), 1) } else {gap_id <- begin} Xgap[gap_id:(gap_id+gap_size-1)] <- NA gap_final <- list("output_vector" = Xgap, "input_vector" = X, "begin_gap" = gap_id, "rate" = rate, "gap_size" = gap_size) return(gap_final) }
flowplaces <- function(tab,origin=NULL,destination=NULL,fij=NULL,format, x) { if (format == "L") { tab <- tab %>% select(origin,destination,fij) names(tab) <- c("i", "j", "Fij") tab_intra <-tab %>% mutate(intra = ifelse(.data$i == .data$j, .data$Fij,0)) %>% filter(.data$intra !=0) %>% select(.data$i,.data$intra) tabOi<-tab %>% group_by(.data$i) %>% summarise(outi = n(),Oi = sum(.data$Fij)) tabDj<-tab %>% group_by(.data$j)%>% summarise(ini = n(),Dj = sum(.data$Fij)) colnames(tabDj)<-c("i","ini","Dj") as.data.frame(tabOi) as.data.frame(tabDj) tabOiDj<-left_join(tabOi,tabDj, by="i") tabOiDj <- tabOiDj %>% mutate (voli=.data$Oi+.data$Dj, bali=.data$Oi-.data$Dj, asyi=.data$bali/.data$voli) %>% mutate (intra=tab_intra$intra) tabOiDj$i<-as.character(tabOiDj$i) tabOiDj$ini<-as.numeric(tabOiDj$ini) tabOiDj$outi<-as.numeric(tabOiDj$outi) tabOiDj$Oi<-as.numeric(tabOiDj$Oi) tabOiDj$Dj<-as.numeric(tabOiDj$Dj) tabOiDj$Vol<-as.numeric(tabOiDj$voli) tabOiDj$Bal<-as.numeric(tabOiDj$bali) tabOiDj$Asy<-as.numeric(tabOiDj$asyi) tabOiDj$intra<-as.numeric(tabOiDj$intra) if (missing(x)) { message("You must specify a choice of flow places indicator computation : alltypes, ini, degi, outi, Oi,Dj, intra,...") } if (x == "allflowplaces") { return(tabOiDj) } if (x == "intra") { tabOiDj <- tabOiDj %>% select(.data$i,.data$intra) return(tabOiDj) } if (x == "ini") { tabOiDj <- tabOiDj %>% select(.data$i,.data$ini) return(tabOiDj) } if (x == "outi") { tabOiDj <- tabOiDj %>% select(.data$i,.data$outi) return(tabOiDj) } if (x == "degi") { tabOiDj <- tabOiDj %>% select(.data$i,.data$degi) return(tabOiDj) } if (x == "voli") { tabOiDj <- tabOiDj %>% select(.data$i,.data$voli) return(tabOiDj) } if (x == "bali") { tabOiDj <- tabOiDj %>% select(.data$i,.data$bali) return(tabOiDj) } if (x == "asyi") { tabOiDj <- tabOiDj %>% select(.data$i,.data$asyi) return(tabOiDj) } } }
wm_record_by_external <- function(id, type = "tsn", ...) { assert(id, c("numeric", "integer")) assert(type, "character") assert_len(id, 1) wm_GET(file.path(wm_base(), "AphiaRecordByExternalID", id), query = cc(list(type = type)), ...) } wm_record_by_external_ <- function(id = NULL, name = NULL, type = "tsn", ...) { id <- id_name(id, name) run_c(id, wm_record_by_external, type = type, on_error = warning, ...) }
context("boxes") test_that("boxes created",{ df <- data.frame( id1 = c(1,1,1,1,1,1,1,1,2,2,2,2) , id2 = c(1,1,1,1,2,2,2,2,1,1,1,1) , x = c(0,0,1,1,1,1,2,2,3,4,4,3) , y = c(0,1,1,0,1,2,2,1,3,3,4,4) ) sf_line <- sfheaders::sf_linestring( obj = df , x = "x" , y = "y" , linestring_id = "id1" ) sf <- sf_boxes( sf_line ) sfc <- sf_boxes( sf_line$geometry ) bbox <- sf_bbox( df, x = "x", y = "y" ) expect_equal( sf$geometry , sfc ) expect_equal( attr( sfc, "bbox" ) , bbox ) expect_equal( sf_bbox( sfc[1] ) , sf_bbox( df[ df$id1 == 1, ], x = "x", y = "y" ) ) expect_equal( sf_bbox( sfc[2] ) , sf_bbox( df[ df$id1 == 2, ], x = "x", y = "y" ) ) })
QC_MAF <- function(mk.mat, cross.ind = NULL, parallel = FALSE, cluster = NULL) { stopifnot(is.matrix(mk.mat), is.character(mk.mat)) MAF.vect <- function(x) { x <- x[!is.na(x)] if (length(x) == 0){ return(NA) } else { alleles <- c(vapply(X = x, FUN = function(x) unlist(strsplit(x, split = "")), FUN.VALUE = character(2))) if(length(table(alleles)) == 1){ return(0) } else { return(min(table(alleles) / length(alleles))) } } } if(is.null(cross.ind)){ if(parallel) { MAF.pop <- parApply(cl = cluster, X = mk.mat, MARGIN = 2, FUN = MAF.vect) } else { MAF.pop <- apply(X = mk.mat, MARGIN = 2, FUN = MAF.vect) } MAF <- MAF.pop class(MAF) <- c("mafRes") return(MAF) } else { if(length(cross.ind) != dim(mk.mat)[1]){ stop("'cross.ind' length is not the same as the number of genotype in 'mk.mat'") } if(parallel) { MAF.pop <- parApply(cl = cluster, X = mk.mat, MARGIN = 2, FUN = MAF.vect) } else { MAF.pop <- apply(X = mk.mat, MARGIN = 2, FUN = MAF.vect) } cross.ind <- factor(cross.ind, levels = unique(cross.ind)) MAF.vect.cr <- function(x) tapply(X = x, INDEX = cross.ind, FUN = MAF.vect) if(parallel) { MAF.cr <- parApply(cl = cluster, X = mk.mat, MARGIN = 2, FUN = MAF.vect.cr) } else { MAF.cr <- apply(X = mk.mat, MARGIN = 2, FUN = MAF.vect.cr) } MAF <- list(MAF.pop = MAF.pop, MAF.cr = MAF.cr) class(MAF) <- c("list", "mafRes") return(MAF) } }
ISNUMBER <- function(value){ is.numeric(value) }
setConstructorS3("NonPairedPSCBS", function(fit=list(), ...) { if (!is.list(fit)) { stop("Argument 'fit' is not a list: ", class(fit)[1]) } extend(PSCBS(fit=fit, ...), "NonPairedPSCBS") }) setMethodS3("getLocusData", "NonPairedPSCBS", function(fit, ..., fields=c("asis", "full")) { fields <- match.arg(fields) data <- NextMethod("getLocusData", fields="asis") if (fields == "full") { names <- colnames(data) data$isHet <- (data$muN == 1/2) if (is.null(data$rho)) { data$rho <- 2*abs(data$betaT-1/2) data$rho[!data$isHet] <- NA_real_ warning("Locus-level DH signals ('rho') did not exist and were calculated from tumor BAFs ('betaT')") } data$c1 <- 1/2*(1-data$rho)*data$CT data$c2 <- data$CT - data$c1 data$isSNP <- (!is.na(data$betaT) | !is.na(data$muN)) data$type <- ifelse(data$isSNP, "SNP", "non-polymorphic locus") data$muNx <- c("AA", "AB", "BB")[2*data$muN + 1L] data$isHetx <- c("AA|BB", "AB")[data$isHet + 1L] } data }, protected=TRUE) setMethodS3("callROH", "NonPairedPSCBS", function(fit, ...) { stop(sprintf("Cannot call ROH from '%s' data.", class(fit)[1L])) }, private=TRUE) setMethodS3("updateMeans", "NonPairedPSCBS", function(fit, from=c("loci", "segments"), adjustFor=NULL, ..., avgTCN=c("asis", "mean", "median"), avgDH=c("asis", "mean", "median"), verbose=FALSE) { from <- match.arg(from) if (!is.null(adjustFor)) { adjustFor <- Arguments$getCharacters(adjustFor) adjustFor <- tolower(adjustFor) knownValues <- c("ab", "loh", "roh") adjustFor <- match.arg(adjustFor, choices=knownValues, several.ok=TRUE) } avgTCN <- match.arg(avgTCN) avgDH <- match.arg(avgDH) verbose <- Arguments$getVerbose(verbose) if (verbose) { pushState(verbose) on.exit(popState(verbose)) } verbose && enter(verbose, "Updating mean level estimates") verbose && cat(verbose, "Adjusting for:") verbose && print(verbose, adjustFor) if (avgTCN == "asis" || avgDH == "asis") { est <- fit$params$meanEstimators if (avgTCN == "asis") { avgTCN <- est$tcn if (is.null(avgTCN)) avgTCN <- "mean" avgTCN <- match.arg(avgTCN) } if (avgDH == "asis") { avgDH <- est$dh if (is.null(avgDH)) avgDH <- "mean" avgDH <- match.arg(avgDH) } } avgList <- list( tcn = get(avgTCN, mode="function"), dh = get(avgDH, mode="function") ) segs <- getSegments(fit, splitters=TRUE) segRows <- list(tcn=fit$tcnSegRows, dh=fit$dhSegRows) nbrOfSegments <- nrow(segs) verbose && cat(verbose, "Number of segments: ", nbrOfSegments) if (is.element("ab", adjustFor)) { if (!is.element("abCall", names(segs))) { adjustFor <- setdiff(adjustFor, "ab") stop("Cannot adjust for AB, because they haven't been called.") } } if (is.element("loh", adjustFor)) { if (!is.element("lohCall", names(segs))) { adjustFor <- setdiff(adjustFor, "loh") stop("Cannot adjust for LOH, because they haven't been called.") } } if (is.element("roh", adjustFor)) { if (!is.element("rohCall", names(segs))) { adjustFor <- setdiff(adjustFor, "roh") stop("Cannot adjust for ROH, because they haven't been called.") } } if (from == "loci") { data <- getLocusData(fit) chromosome <- data$chromosome x <- data$x CT <- data$CT rho <- data$rho isSplitter <- isSegmentSplitter(fit) for (ss in seq_len(nbrOfSegments)[!isSplitter]) { verbose && enter(verbose, sprintf("Segment %d of %d", ss, nbrOfSegments)) seg <- segs[ss,] verbose && print(verbose, seg) chr <- seg[["chromosome"]] chrTag <- sprintf("chr%02d", chr) for (what in c("tcn", "dh")) { segRow <- segRows[[what]][ss,] if (!is.finite(segRow[[1]]) || !is.finite(segRow[[2]])) { next } units <- segRow[[1]]:segRow[[2]] if (what == "tcn") { value <- CT } else if (what == "dh") { value <- rho } keep <- which(!is.na(value[units])) units <- units[keep] avgFUN <- avgList[[what]] gamma <- avgFUN(value[units]) .stop_if_not(length(units) == 0 || !is.na(gamma)) key <- paste(what, "Mean", sep="") seg[[key]] <- gamma } verbose && print(verbose, seg) segs[ss,] <- seg verbose && exit(verbose) } } if (length(adjustFor) > 0) { verbose && enter(verbose, "Adjusting segment means") verbose && cat(verbose, "Adjusting for:") verbose && print(verbose, adjustFor) if (is.element("ab", adjustFor)) { verbose && enter(verbose, "Adjusting for AB") calls <- segs$abCall segs$dhMean[calls] <- 1/2 verbose && exit(verbose) } if (is.element("loh", adjustFor)) { verbose && enter(verbose, "Adjusting for LOH") calls <- segs$lohCall segs$dhMean[calls] <- 0 verbose && exit(verbose) } if (is.element("roh", adjustFor)) { verbose && enter(verbose, "Adjusting for ROH") calls <- segs$rohCall segs$dhMean[calls] <- NA_real_ verbose && exit(verbose) } verbose && exit(verbose) } verbose && enter(verbose, "Update (C1,C2) per segment") tcn <- segs$tcnMean dh <- segs$dhMean C1 <- 1/2*(1-dh)*tcn C2 <- tcn - C1 segs$c1Mean <- C1 segs$c2Mean <- C2 verbose && exit(verbose) res <- fit res$output <- segs res <- setMeanEstimators(res, tcn=avgTCN, dh=avgDH) verbose && exit(verbose) res }, private=TRUE) setMethodS3("resegment", "NonPairedPSCBS", function(fit, ..., verbose=FALSE) { verbose <- Arguments$getVerbose(verbose) if (verbose) { pushState(verbose) on.exit(popState(verbose)) } verbose && enter(verbose, "Resegmenting a ", class(fit)[1], " object") data <- getLocusData(fit) class(data) <- "data.frame" drop <- c("rho", "betaTN", "index") keep <- !is.element(colnames(data), drop) data <- data[,keep] verbose && str(verbose, data) verbose && cat(verbose, "Number of loci: ", nrow(data)) verbose && enter(verbose, "Overriding default arguments") segFcnName <- "segmentByPairedNonPSCBS" segFcn <- getMethodS3(segFcnName, "default") formals <- formals(segFcn) formals <- formals[!sapply(formals, FUN=is.language)] formals <- formals[!sapply(formals, FUN=is.name)] drop <- c("chromosome", "x", "w", "CT", "betaT", "betaN", "muN", "...") keep <- !is.element(names(formals), drop) formals <- formals[keep] params <- fit$params keep <- is.element(names(params), names(formals)) params <- params[keep] params$tbn <- NULL userArgs <- list(..., verbose=verbose) args <- formals args2 <- c(params, userArgs) for (kk in seq_along(args2)) { value <- args2[[kk]] if (!is.null(value)) { key <- names(args2)[kk] if (!is.null(key)) { args[[key]] <- value } else { args <- c(args, list(value)) } } } verbose && str(verbose, args[names(args) != "verbose"]) verbose && enter(verbose, sprintf("Calling %s()", segFcnName)) args <- c(list(data), args) verbose && cat(verbose, "Arguments:") verbose && str(verbose, args[names(args) != "verbose"]) verbose && exit(verbose) fit <- do.call(segFcnName, args) verbose && exit(verbose) verbose && exit(verbose) fit }, protected=TRUE)
library(gamlss.nl) data(la) plot(PET60~bflow,data=la) modLOGNO<- nlgamlss(y=PET60, mu.fo=~log(bflow)+log(1-(1-exp(p1))*exp(-p2/bflow)), sigma.formula=~1, mu.start = c(-.99, 110), sigma.start= -2, family=LOGNO, data=la) if(abs(deviance(modLOGNO)-2293.9) > 0.1) stop("error in nl gamlss log-NO") modNO<- nlgamlss(y=PET60, mu.fo= ~bflow*(1-p1*exp(-p2/bflow)), sigma.formula=~1, mu.start = c(.6, 90), sigma.start= 3, data=la) if(abs(deviance(modNO)-2278.7) > 0.1) stop("error in nl gamlss NO") modNO1<- nlgamlss(y=PET60, mu.fo= ~bflow*(1-(1-exp(p1))*exp(-p2/bflow)), sigma.formula=~1, mu.start = c(-.9, 90), sigma.start= 3, data=la) if(abs(deviance(modNO1)-2278.68) > 0.1) stop("error in nl gamlss NO") funnl<- function(p) bflow*(1-p[1]*exp(-p[2]/bflow)) modNO2<- nlgamlss(y=PET60, mu.fo= funnl, sigma.formula=~1, mu.start = c(.6, 90), sigma.start= 3, data=la) if(abs(deviance(modNO2)-2278.68) > 0.1) stop("error in nl gamlss NO") modGU<- nlgamlss(y=PET60, mu.fo= ~bflow*(1-p1*exp(-p2/bflow)), sigma.formula=~1, mu.start = c(.6, 110), sigma.start= 3, family=GU, data=la) if(abs(deviance(modGU)-2382.9) > 0.1) stop("error in nl gamlss GU") modGU1<- nlgamlss(y=PET60, mu.fo= ~bflow*(1-(1-exp(p1))*exp(-p2/bflow)), sigma.formula=~1, mu.start = c(-.6, 90), sigma.start= 3, family=GU, data=la) if(abs(deviance(modGU1)-2382.9) > 0.1) stop("error in nl gamlss GU") modRG<- nlgamlss(y=PET60, mu.fo= ~bflow*(1-p1*exp(-p2/bflow)), sigma.formula=~1, mu.start = c(.6, 110), sigma.start= 3, family=RG, data=la) if(abs(deviance(modRG)-2249.82) > 0.1) stop("error in nl gamlss RG") modGA<- nlgamlss(y=PET60, mu.fo= ~log(bflow)+log(1-(1-exp(p1))*exp(-p2/bflow)), sigma.formula=~1, mu.start = c(-.99, 90),, sigma.start= -.5, family=GA, data=la) if(abs(deviance(modGA)-2299.87) > 0.1) stop("error in nl gamlss GA") modIG<- nlgamlss(y=PET60, mu.fo= ~log(bflow)+log(1-(1-exp(p1))*exp(-p2/bflow)), sigma.formula=~1, mu.start = c(-.99, 90),, sigma.start= -.5, family=IG, data=la) if(abs(deviance(modIG)-2408.33) > 0.1) stop("error in nl gamlss IG") AIC(modLOGNO,modNO, modGU, modRG, modGA, modIG, k=0) modTF<- nlgamlss(y=PET60, mu.fo= ~bflow*(1-p1*exp(-p2/bflow)), sigma.formula=~1, nu.fo=~1, mu.start = c(.6, 110), sigma.start= 3, nu.start=2.5 ,family=TF, data=la) if(abs(deviance(modTF)-2273.5) > 0.1) stop("error in nl gamlss TF") modPE<- nlgamlss(y=PET60, mu.fo= ~bflow*(1-p1*exp(-p2/bflow)), sigma.formula=~1, nu.fo=~1, mu.start = c(.6, 110), sigma.start= 3, nu.start=0.6 ,family=PE, data=la) if(abs(deviance(modPE)-2275.89) > 0.1) stop("error in nl gamlss PE") modBCCG<- nlgamlss(y=PET60, mu.fo=~bflow*(1-(1-exp(p1))*exp(-p2/bflow)),sigma.formula=~1, nu.fo=~1, mu.start = c(-.9, 90), sigma.start= -2.3, nu.start=0, family=BCCG, data=la) if(abs(deviance(modBCCG)- 2293.74) > 0.1) stop("error in nl gamlss BCCG") AIC(modTF,modPE, modBCCG,k=0) modSEP<- nlgamlss(y=PET60, mu.fo= ~bflow*(1-p1*exp(-p2/bflow)), sigma.formula=~1, nu.fo=~1, mu.start = c(.6, 110), sigma.start= 3, nu.start=1, tau.start=0.6, family=SEP, data=la) if(abs(deviance(modSEP)-2273.75) > 0.1) stop("error in nl gamlss SEP") modBCT<- nlgamlss(y=PET60, mu.fo= ~bflow*(1-(1-exp(p1))*exp(-p2/bflow)), sigma.formula=~1, nu.fo=~1, mu.start=c(-.9, 90), sigma.start= -2.3, nu.start=0, tau.start=log(2.5), family=BCT, data=la, control=NL.control(hessian=FALSE)) if((deviance(modBCT)-2293.74) > 0.1) stop("error in nl gamlss BCT") modBCPE<- nlgamlss(y=PET60, mu.fo=~bflow*(1-(1-exp(p1))*exp(-p2/bflow)),sigma.formula=~1, mu.start = c(-.9, 90), sigma.start= -2.3, nu.start=0, tau.start=log(2.5), family=BCPE, data=la) if((deviance(modBCPE)- 2292.81) > 0.1) stop("error in nl gamlss BCPE") modJSU<- nlgamlss(y=PET60, mu.fo= ~bflow*(1-p1*exp(-p2/bflow)), sigma.formula=~1, nu.fo=~1, mu.start = c(.6, 110), sigma.start= 3, nu.start=1, tau.start=0.6, family=JSU, data=la) if(abs(deviance(modJSU)-2253.45) > 0.1) stop("error in nl gamlss JSU") AIC(modSEP,modBCPE,modJSU, k=0) pp<-poly(la$bflow,2) modRGSc<- nlgamlss(y=PET60, mu.fo= ~bflow*(1-(1-exp(p1))*exp(-p2/bflow)), sigma.formula=~p3+p4*pp[,1]+p5*pp[,2], mu.start = c(-.9, 90), sigma.start= c(3,-1,-2), family=RG, data=la) if(abs(deviance(modRGSc) - 2244.87) > 0.1) stop("error in nl gamlss RG") modLOGNOSc<- nlgamlss(y=PET60, mu.fo=~log(bflow)+log(1-(1-exp(p1))*exp(-p2/bflow)), sigma.formula=~p3+p4*pp[,1]+p5*pp[,2], mu.start = c(-.99, 90), sigma.start= c(3,-1,-2), family=LOGNO, data=la) if(abs(deviance(modLOGNOSc) - 2221.56) > 0.1) stop("error in nl gamlss LOGNO") modNOSc<- nlgamlss(y=PET60, mu.fo= ~bflow*(1-(1-exp(p1))*exp(-p2/bflow)), sigma.formula=~p3+p4*pp[,1]+p5*pp[,2], mu.start = c(-.9, 90), sigma.start= c(3,-1,-2), data=la) if(abs(deviance(modNOSc)-2269.99) > 0.1) stop("error in nl gamlss NO") AIC(modRGSc,modLOGNOSc,modNOSc, k=0 ) modTFSc<- nlgamlss(y=PET60, mu.fo= ~bflow*(1-p1*exp(-p2/bflow)), sigma.formula=~ p3+p4*pp[,1]+p5*pp[,2], nu.fo=~1, mu.start = c(.6, 110), sigma.start= c(3,-1,-2), nu.start=2.5 ,family=TF, data=la) if(abs(deviance(modTFSc)- 2267.42) > 0.1) stop("error in nl gamlss TF") modPESc<- nlgamlss(y=PET60, mu.fo= ~bflow*(1-p1*exp(-p2/bflow)), sigma.formula=~ p3+p4*pp[,1]+p5*pp[,2], nu.fo=~1, mu.start = c(.6, 110), sigma.start= c(3,-1,-2), nu.start=log(2) ,family=PE, data=la) if(abs(deviance(modPESc)- 2269.11) > 0.1) stop("error in nl gamlss TF") modBCCGSc<- nlgamlss(y=PET60, mu.fo=~bflow*(1-(1-exp(p1))*exp(-p2/bflow)), sigma.formula=~ p3+p4*pp[,1]+p5*pp[,2], nu.fo=~1, mu.start = c(-.9, 90), sigma.start= c(3,-1,-2), nu.start=0, family=BCCG, data=la) if((deviance(modBCCGSc)- 2221.56) > 0.1) stop("error in nl gamlss BCCGSc") AIC(modTFSc,modPESc,modBCCGSc, k=0) modBCTSc<- nlgamlss(y=PET60, mu.fo= ~bflow*(1-(1-exp(p1))*exp(-p2/bflow)), sigma.formula=~ p3+p4*pp[,1]+p5*pp[,2], nu.fo=~1, mu.start=c(-.9, 90), sigma.start= c(3,-1,-2), nu.start=0, tau.start=log(2.5), family=BCT, data=la, control=NL.control(hessian=FALSE)) if((deviance(modBCTSc)-2221.6) > 0.1) stop("error in nl gamlss BCT") modBCPESc<- nlgamlss(y=PET60, mu.fo=~bflow*(1-(1-exp(p1))*exp(-p2/bflow)), sigma.formula=~ p3+p4*pp[,1]+p5*pp[,2], mu.start = c(-.9, 90), sigma.start= c(3,-1,-2), nu.start=0, tau.start=log(2.5), family=BCPE, data=la) if((deviance(modBCPESc)- 2212.9) > 0.1) stop("error in nl gamlss BCPE") modFinal<- nlgamlss(y=PET60, mu.fo=~bflow*(1-(1-exp(p1))*exp(-p2/bflow)), sigma.formula=~ p3+p4*pp[,1]+p5*pp[,2], mu.start = c(-.9, 90), sigma.start= c(3,-1,-2), nu.start=0, tau.start=log(2.5), nu.fix=TRUE, family=BCPE, data=la) if((deviance(modBCPESc)- 2212.9) > 0.1) stop("error in nl gamlss BCPE") mylogy<-log(la$PET60) modFinal1<- nlgamlss(y=mylogy, mu.fo=~log(bflow)+log(1-p1*exp(-p2/bflow)), sigma.formula=~p3+p4*pp[,1]+p5*pp[,2], mu.start = c(.6, 40), sigma.start= c(3,-1,-2),nu.start=log(2.5), family=PE, data=la)
print.AmerPut <- function(x, ...){ cat("American Put Option\nPrice: ") cat(x$price) }
.gibbs_OMFA <- function(Q, data, iters, N, P, G, mu.zero, sigma.mu, mu, sigma.l, burnin, thinning, uni.type, uni.prior, sw, psi.alpha, psi.beta, verbose, cluster, learn.alpha, a.hyper, zeta, tune.zeta, ...) { start.time <- proc.time() sq_mat <- if(P > 50) function(x) diag(sqrt(diag(x))) else sqrt matrix <- base::matrix total <- max(iters) if(verbose) pb <- utils::txtProgressBar(min=0, max=total, style=3) n.store <- length(iters) Gseq <- seq_len(G) Pseq <- seq_len(P) Nseq <- seq_len(N) obsnames <- rownames(data) varnames <- colnames(data) colnames(data) <- NULL Q0 <- Q > 0 Q1 <- Q == 1 uni <- P == 1 sw["s.sw"] <- sw["s.sw"] && Q0 sw["l.sw"] <- sw["l.sw"] && Q0 if(sw["mu.sw"]) { mu.store <- array(0L, dim=c(P, G, n.store)) } if(sw["s.sw"]) { eta.store <- array(0L, dim=c(N, Q, n.store)) } if(sw["l.sw"]) { load.store <- array(0L, dim=c(P, Q, G, n.store)) } if(sw["psi.sw"]) { psi.store <- array(0L, dim=c(P, G, n.store)) } if(sw["pi.sw"]) { pi.store <- matrix(0L, nrow=G, ncol=n.store) } z.store <- matrix(0L, nrow=n.store, ncol=N) ll.store <- vector("integer", n.store) err.z <- zerr <- FALSE G.store <- vector("integer", n.store) mu.sigma <- 1/sigma.mu mu.prior <- mu.sigma * mu.zero sig.mu.sqrt <- sqrt(sigma.mu) l.sigma <- diag(1/sigma.l, Q) sig.l.sqrt <- sqrt(sigma.l) z <- cluster$z nn <- tabulate(z, nbins=G) nn0 <- nn > 0 nn.ind <- which(nn0) pi.alpha <- cluster$pi.alpha if(learn.alpha) { alpha.store <- ll.store alpha.shape <- a.hyper[1L] alpha.rate <- a.hyper[2L] a.rates <- vector("integer", total) } else a.rates <- 1L avgzeta <- zeta heat <- tune.zeta$heat lambda <- tune.zeta$lambda target <- tune.zeta$target zeta.tune <- tune.zeta$do startz <- tune.zeta$start.zeta stopz <- tune.zeta$stop.zeta one.uni <- is.element(uni.type, c("constrained", "single")) .sim_psi_inv <- switch(EXPR=uni.type, unconstrained=.sim_psi_uu, isotropic=.sim_psi_uc, constrained=.sim_psi_cu, single=.sim_psi_cc) .sim_psi_ip <- switch(EXPR=uni.prior, unconstrained=.sim_psi_ipu, isotropic=.sim_psi_ipc) if(isTRUE(one.uni)) { uni.shape <- switch(EXPR=uni.type, constrained=N/2 + psi.alpha, single=(N * P)/2 + psi.alpha) V <- switch(EXPR=uni.type, constrained=P, single=1L) } psi.beta <- switch(EXPR=uni.prior, isotropic=psi.beta[which.max(.ndeci(psi.beta))], psi.beta) pi.prop <- c(cluster$pi.prop, vector("integer", G - length(cluster$pi.prop))) mu <- cbind(mu, vapply(seq_len(G - length(cluster$pi.prop)), function(g) .sim_mu_p(P=P, sig.mu.sqrt=sig.mu.sqrt, mu.zero=mu.zero), numeric(P))) eta <- .sim_eta_p(N=N, Q=Q) lmat <- if(Q0) array(vapply(Gseq, function(g) .sim_load_p(Q=Q, P=P, sig.l.sqrt=sig.l.sqrt), numeric(P * Q)), dim=c(P, Q, G)) else array(0, dim=c(P, 0, G)) if(isTRUE(one.uni)) { psi.inv <- matrix(.sim_psi_ip(P=P, psi.alpha=psi.alpha, psi.beta=psi.beta), nrow=P, ncol=G) } else psi.inv <- replicate(G, .sim_psi_ip(P=P, psi.alpha=psi.alpha, psi.beta=psi.beta), simplify="array") psi.inv <- if(uni) t(psi.inv) else psi.inv if(isTRUE(one.uni)) { psi.inv[] <- 1/switch(EXPR=uni.type, constrained=colVars(data), max(colVars(data))) } else { tmp.psi <- (nn[nn0] - 1L)/pmax(rowsum(data^2, z) - rowsum(data, z)^2/nn[nn0], 0L) tmp.psi <- switch(EXPR=uni.type, unconstrained=t(tmp.psi), matrix(Rfast::rowMaxs(tmp.psi, value=TRUE), nrow=P, ncol=G, byrow=TRUE)) psi.inv[,nn > 1] <- tmp.psi[!is.nan(tmp.psi)] rm(tmp.psi) } max.p <- (psi.alpha - 1)/psi.beta inf.ind <- psi.inv > max(max.p) psi.inv[inf.ind] <- matrix(max.p, nrow=P, ncol=G)[inf.ind] rm(max.p, inf.ind) init.time <- proc.time() - start.time for(iter in seq_len(total)) { if(verbose && iter < burnin) utils::setTxtProgressBar(pb, iter) storage <- is.element(iter, iters) pi.prop <- rDirichlet(G=G, alpha=pi.alpha, nn=nn) index <- order(nn, decreasing=TRUE) pi.prop <- pi.prop[index] mu <- mu[,index, drop=FALSE] lmat <- lmat[,,index, drop=FALSE] psi.inv <- psi.inv[,index, drop=FALSE] z <- factor(z, labels=match(nn.ind, index)) z <- as.integer(levels(z))[z] nn <- nn[index] nn0 <- nn0[index] dat.g <- lapply(Gseq, function(g) data[z == g,, drop=FALSE]) c.data <- lapply(Gseq, function(g) sweep(dat.g[[g]], 2L, mu[,g], FUN="-", check.margin=FALSE)) if(Q0) { eta.tmp <- lapply(Gseq, function(g) if(nn0[g]) .sim_score(N=nn[g], lmat=lmat[,,g], Q=Q, c.data=c.data[[g]], psi.inv=psi.inv[,g], Q1=Q1) else .empty_mat(nc=Q)) EtE <- lapply(Gseq, function(g) if(nn0[g]) crossprod(eta.tmp[[g]])) lmat <- array(unlist(lapply(Gseq, function(g) matrix(if(nn0[g]) vapply(Pseq, function(j) .sim_load(l.sigma=l.sigma, Q=Q, c.data=c.data[[g]][,j], eta=eta.tmp[[g]], Q1=Q1, EtE=EtE[[g]], psi.inv=psi.inv[,g][j]), numeric(Q)) else .sim_load_p(Q=Q, P=P, sig.l.sqrt=sig.l.sqrt), nrow=P, byrow=TRUE)), use.names=FALSE), dim=c(P, Q, G)) eta <- do.call(rbind, eta.tmp)[obsnames,, drop=FALSE] } else { eta.tmp <- lapply(Gseq, function(g) eta[z == g,, drop=FALSE]) } if(isTRUE(one.uni)) { S.mat <- lapply(Gseq, function(g) { S <- c.data[[g]] - if(Q0) tcrossprod(eta.tmp[[g]], if(Q1) as.matrix(lmat[,,g]) else lmat[,,g]) else 0L; S^2 } ) psi.inv[,] <- .sim_psi_inv(uni.shape, psi.beta, S.mat, V) } else { psi.inv[,] <- vapply(Gseq, function(g) if(nn0[g]) .sim_psi_inv(N=nn[g], psi.alpha=psi.alpha, c.data=c.data[[g]], eta=eta.tmp[[g]], psi.beta=psi.beta, P=P, Q0=Q0, lmat=if(Q1) as.matrix(lmat[,,g]) else lmat[,,g]) else .sim_psi_ip(P=P, psi.alpha=psi.alpha, psi.beta=psi.beta), numeric(P)) } sum.data <- vapply(dat.g, colSums2, numeric(P)) sum.data <- if(uni) t(sum.data) else sum.data sum.eta <- lapply(eta.tmp, colSums2) mu[,] <- vapply(Gseq, function(g) if(nn0[g]) .sim_mu(mu.sigma=mu.sigma, psi.inv=psi.inv[,g], mu.prior=mu.prior, sum.data=sum.data[,g], sum.eta=sum.eta[[g]], lmat=if(Q1) as.matrix(lmat[,,g]) else lmat[,,g], N=nn[g], P=P) else .sim_mu_p(P=P, sig.mu.sqrt=sig.mu.sqrt, mu.zero=mu.zero), numeric(P)) if(learn.alpha) { MH.alpha <- .sim_alpha_o(alpha=pi.alpha, zeta=zeta, G=G, N=N, nn=nn[nn0], shape=alpha.shape, rate=alpha.rate) pi.alpha <- MH.alpha$alpha a.rates[iter] <- MH.alpha$rate if(isTRUE(zeta.tune)) { if(iter >= startz && iter < stopz) { zeta <- .tune_zeta(zeta=zeta, time=iter, l.rate=MH.alpha$l.prob, heat=heat, target=target, lambda=lambda) } avgzeta <- c(avgzeta, zeta) } } psi <- 1/psi.inv sigma <- if(uni) lapply(Gseq, function(g) as.matrix(psi[,g] + if(Q0) tcrossprod(as.matrix(lmat[,,g])) else 0L)) else lapply(Gseq, function(g) tcrossprod(lmat[,,g]) + diag(psi[,g])) log.pis <- log(pi.prop) if(uni) { log.probs <- vapply(Gseq, function(g) stats::dnorm(data, mu[,g], sq_mat(sigma[[g]]), log=TRUE) + log.pis[g], numeric(N)) } else { log.probs <- try(vapply(Gseq, function(g) dmvn(data, mu[,g], if(Q0) sigma[[g]] else sq_mat(sigma[[g]]), log=TRUE, isChol=!Q0) + log.pis[g], numeric(N)), silent=TRUE) if(zerr <- inherits(log.probs, "try-error")) { log.probs <- vapply(Gseq, function(g) { sigma <- if(Q0) is.posi_def(sigma[[g]], make=TRUE)$X.new else sq_mat(sigma[[g]]); dmvn(data, mu[,g], sigma, log=TRUE, isChol=!Q0) + log.pis[g] }, numeric(N)) } } z <- gumbel_max(probs=log.probs) nn <- tabulate(z, nbins=G) nn0 <- nn > 0 nn.ind <- which(nn0) G.non <- length(nn.ind) if(zerr && !err.z) { cat("\n"); warning("\nAlgorithm may slow due to corrections for Choleski decompositions of non-positive-definite covariance matrices\n", call.=FALSE) err.z <- TRUE } if(storage) { if(verbose) utils::setTxtProgressBar(pb, iter) new.it <- which(iters == iter) if(sw["mu.sw"]) mu.store[,,new.it] <- mu if(all(sw["s.sw"], Q0)) eta.store[,,new.it] <- eta if(all(sw["l.sw"], Q0)) load.store[,,,new.it] <- lmat if(sw["psi.sw"]) psi.store[,,new.it] <- psi if(sw["pi.sw"]) pi.store[,new.it] <- pi.prop if(learn.alpha) alpha.store[new.it] <- pi.alpha z.store[new.it,] <- as.integer(z) ll.store[new.it] <- sum(rowLogSumExps(log.probs)) G.store[new.it] <- as.integer(G.non) } } if(verbose) close(pb) Gmax <- seq_len(max(as.integer(z.store))) mu.store <- if(sw["mu.sw"]) tryCatch(mu.store[,Gmax,, drop=FALSE], error=function(e) mu.store) load.store <- if(sw["l.sw"]) tryCatch(load.store[,,Gmax,, drop=FALSE], error=function(e) load.store) psi.store <- if(sw["psi.sw"]) tryCatch(psi.store[,Gmax,, drop=FALSE], error=function(e) psi.store) pi.store <- if(sw["pi.sw"]) tryCatch(pi.store[Gmax,, drop=FALSE], error=function(e) pi.store) returns <- list(mu = if(sw["mu.sw"]) tryCatch(provideDimnames(mu.store, base=list(varnames, "", ""), unique=FALSE), error=function(e) mu.store), eta = if(all(sw["s.sw"], Q0)) tryCatch(provideDimnames(eta.store, base=list(obsnames, "", ""), unique=FALSE), error=function(e) eta.store), load = if(all(sw["l.sw"], Q0)) tryCatch(provideDimnames(load.store, base=list(varnames, "", "", ""), unique=FALSE), error=function(e) load.store), psi = if(sw["psi.sw"]) tryCatch(provideDimnames(psi.store, base=list(varnames, "", ""), unique=FALSE), error=function(e) psi.store), pi.prop = if(sw["pi.sw"]) pi.store, alpha = if(learn.alpha) alpha.store, a.rate = ifelse(learn.alpha, mean(a.rates), a.rates), z.store = z.store, ll.store = ll.store, G.store = G.store, avg.zeta = if(learn.alpha) ifelse(zeta.tune, mean(avgzeta), zeta), time = init.time) return(returns) }
expected <- eval(parse(text="-1.46941282670977e-16")); test(id=0, code={ argv <- eval(parse(text="list(-1.46941282670977e-16)")); do.call(`atan`, argv); }, o=expected);
mice_mudfold_noboot <- function(out){ out_list <- out nmice <- out_list$CALL$nmice data <- out_list$CALL$data I <- colnames(data) nrdat <- nrow(data) for_mice_dat <- data.frame(sapply(data,as.factor)) new.pred <- quickpred(for_mice_dat, method = 'kendall', mincor = out_list$CALL$mincor) imp_dati <- mice(for_mice_dat, m = nmice,predictorMatrix = new.pred, printFlag = FALSE, method = 'myfunc') dims_imp_dati <- lapply(imp_dati$imp,dim) index_which_imputed <- unlist(lapply(dims_imp_dati, function(x) ifelse(x[1] > 0, TRUE, FALSE))) mode_imputed <- lapply(imp_dati$imp[index_which_imputed], function(x) apply(x, 1, getmode)) dat_imputed <- data[,index_which_imputed] dat_imputed <- data.frame(do.call(cbind,lapply(1:sum(index_which_imputed), function(i){ y <- dat_imputed[,i] y[is.na(y)] <- mode_imputed[[i]] y }))) dt <- data dt[,index_which_imputed] <- dat_imputed out_list$CALL$mode_mice_data <- dt dati <- complete(imp_dati, "all") dati <- lapply(dati, function(x){ if (any(is.na(x))){ x <- apply(x, 2, function(y){ if(any(is.na(y))) y[is.na(y)] <- getmode(y) }) } x }) dati <- lapply(dati, function(x) data.frame(sapply(x, function(y) as.numeric(levels(y))[y]))) check_results <- lapply(dati, function(x){ out_new <- out_list out_new$CALL$data <- x data_check(out_new)}) nullvec <- sapply(check_results, is.null) if (any(nullvec)) return() list_res <- list() list_res <- out_list list_res$MUDFOLD_INFO <- list() list_res$MUDFOLD_INFO$triple_stats <- list() list_res$MUDFOLD_INFO$triple_stats$Expected_errors <- Reduce("+", lapply(check_results, function(x) x$out$MUDFOLD_INFO$triple_stats$Expected_errors )) / nmice list_res$MUDFOLD_INFO$triple_stats$Observed_errors <- Reduce("+", lapply(check_results, function(x) x$out$MUDFOLD_INFO$triple_stats$Observed_errors )) / nmice list_res$MUDFOLD_INFO$triple_stats$H_coefficients <- Reduce("+", lapply(check_results, function(x) x$out$MUDFOLD_INFO$triple_stats$H_coefficients )) / nmice out_lists <- lapply(check_results, function(x) x$out) out_lists <- lapply(1:length(dati), function(x){ out_lists[[x]]$CALL$data <-check_results[[x]]$data out_lists[[x]] }) fits <- lapply(1:nmice, function(i){ if (is.null(out_list$CALL$start.scale)){ res_first <- mudfold_fs(out_lists[[i]]) res_second <- mudfold_se(res_first) }else{ res_first <- out_lists[[i]] res_first$MUDFOLD_INFO$first_step <- NULL res_second <- mudfold_se(res_first) } return(res_second) }) non_conv <- unlist(lapply(fits, is.null)) conv <- !non_conv nconvergence <- sum(conv) convergence_rate <- (nconvergence )/ nmice list_res$MUDFOLD_INFO$mice_info <- list() list_res$MUDFOLD_INFO$mice_info$mice_out <- imp_dati list_res$MUDFOLD_INFO$mice_info$convergence <- nconvergence list_res$MUDFOLD_INFO$mice_info$convergence_rate <- convergence_rate list_res$MUDFOLD_INFO$mice_info$which_non_convergence <- which(non_conv) list_res$MUDFOLD_INFO$first_step <- list() list_res$MUDFOLD_INFO$second_step <- list() if (nconvergence > 0){ list_res$MUDFOLD_INFO$first_step$Converged <- TRUE list_res$MUDFOLD_INFO$second_step$Converged <- TRUE }else{ print(paste("NO MUDFOLD SCALE OBTAINED IN ",nmice," MICE DATASETS",sep="")) return() } nmice_effective <- c(1:nmice)[conv] summ_fits <- lapply(fits[nmice_effective], summary) Uniq_trip <- lapply(fits[nmice_effective], function(x) as.vector(x$MUDFOLD_INFO$first_step$BU)) for( i in 1:nconvergence){ ut1 <- paste(Uniq_trip[[i]],collapse = "") ut2 <- paste(rev(Uniq_trip[[i]]),collapse = "") equal_trips <- which(sapply(Uniq_trip, function(x) paste(x,collapse = "") == ut1 | paste(x,collapse = "") == ut2)) for (j in equal_trips){ Uniq_trip[[j]] <- Uniq_trip[[i]] } } Uniq_trip <- sapply(Uniq_trip, function(x) paste(x,collapse = "")) ttrips <- table(Uniq_trip) best_mice_utrip <- names(ttrips)[which.max(ttrips)] ref_fit <- which(Uniq_trip == best_mice_utrip)[1] best_mice_utrip <- fits[[ref_fit]]$MUDFOLD_INFO$first_step$BU Htrips <- sapply(names(ttrips), function(u){ z<-fits[nmice_effective] zstar <- z[which(Uniq_trip == u)] utrip_H <- mean(sapply(zstar, function(x) x$MUDFOLD_INFO$first_step$HBU)) utrip_H }) fits_all <- fits[nmice_effective] which_fits <- which(sapply(fits_all, function(x){ sum(c(x$MUDFOLD_INFO$first_step$BU)==best_mice_utrip) == 3 | sum(c(x$MUDFOLD_INFO$first_step$BU) == rev(best_mice_utrip))==3 })) fits1 <- fits_all[which_fits] utrip_H <- mean(sapply(fits1, function(x) x$MUDFOLD_INFO$first_step$HBU)) list_res$MUDFOLD_INFO$first_step$unique_triples <- sort(ttrips,decreasing = TRUE) list_res$MUDFOLD_INFO$first_step$H_unique_triples <- Htrips list_res$MUDFOLD_INFO$first_step$BU <- best_mice_utrip list_res$MUDFOLD_INFO$first_step$HBU <- utrip_H scales <- lapply(summ_fits, function(x) x$ITEM_STATS$items) for( i in 1:nconvergence){ sc1 <- paste(scales[[i]],collapse = "") sc2 <- paste(rev(scales[[i]]),collapse = "") equal_scales <- which(sapply(scales, function(x) paste(x,collapse = "") ==sc1 | paste(x,collapse = "")==sc2)) for (j in equal_scales){ scales[[j]] <- scales[[i]] } } scalescol <- sapply(scales, function(x) paste(x,collapse = "")) tscales <- table(scalescol) index_scales <- as.numeric(which(tscales== max(tscales))) names_ind_scales <- names(tscales)[index_scales] list_res$MUDFOLD_INFO$second_step$mice_scales <- tscales best_scale <- NA if (length(index_scales)==1){ best_scale <- names_ind_scales } if (length(index_scales) > 1){ name_vec_new <- names_ind_scales meanISO <- sapply(name_vec_new, function(x){ z <- fits_all[which(scalescol == x)] mean(sapply(z, function(y) y$MUDFOLD_INFO$second_step$ISOscale)) }) indexes2 <- as.numeric(which(meanISO == min(meanISO))) if (length(indexes2) == 1){ best_scale <- names(meanISO)[indexes2] } if (length(indexes2) > 1){ name_vec_new <- name_vec_new[indexes2] meanMAX <- sapply(name_vec_new, function(x){ z <- fits_all[which(scalescol == x)] mean(sapply(z, function(y) y$MUDFOLD_INFO$second_step$MAXscale)) }) indexes3 <- which(meanMAX == min(meanMAX)) if (length(indexes3) == 1){ best_scale <- names(meanMAX)[indexes3] } if (length(indexes3) > 1){ name_vec_new <- name_vec_new[indexes3] meanH <- sapply(names_ind_scales[indexes3], function(x){ z <- fits_all[which(scalescol == x)] mean(sapply(z, function(y) y$MUDFOLD_INFO$second_step$Hscale)) }) indexes4 <- which(meanH == max(meanH)) best_scale <- names(meanH)[1] } } } refscale2 <- which(scalescol == best_scale)[1] best_mice_scale <- fits_all[[refscale2]]$MUDFOLD_INFO$second_step$scale length_best_mice_scale <- length(best_mice_scale) which_summary_to_use <- which(sapply(summ_fits, function(x){ if (length(x$ITEM_STATS$items) == length_best_mice_scale){ sum(x$ITEM_STATS$items==best_mice_scale)==length_best_mice_scale | sum(x$ITEM_STATS$items==rev(best_mice_scale))==length_best_mice_scale }else{ FALSE } })) summ_fits <- summ_fits[which_summary_to_use] scale_stats <- apply(do.call(rbind,lapply(summ_fits, function(x) c(x$SCALE_STATS)$value)),2,mean) item_stats <- Reduce("+",lapply(summ_fits, function(x){ sc1c <- sum(x$ITEM_STATS$items == rev(best_mice_scale)) == length_best_mice_scale sc2c <- sum(x$ITEM_STATS$items == best_mice_scale) == length_best_mice_scale nrx <- nrow(x$ITEM_STATS) if (sc1c) x$ITEM_STATS <- x$ITEM_STATS[rev(1:nrx),] unlist(x$ITEM_STATS[,-c(1,2)]) })) / length(which_summary_to_use) av_CAM <- Reduce("+",lapply(fits_all[which_summary_to_use], function(x) x$MUDFOLD_INFO$second_step$CAM[best_mice_scale,best_mice_scale])) /length(which_summary_to_use) av_COR <- Reduce("+",lapply(fits_all[which_summary_to_use], function(x) x$MUDFOLD_INFO$second_step$CORR[best_mice_scale,best_mice_scale])) /length(which_summary_to_use) av_ADJ <- Reduce("+",lapply(fits_all[which_summary_to_use], function(x) x$MUDFOLD_INFO$second_step$ADJ[best_mice_scale,best_mice_scale])) /length(which_summary_to_use) av_DOM <- Reduce("+",lapply(fits_all[which_summary_to_use], function(x) x$MUDFOLD_INFO$second_step$DOM[best_mice_scale,best_mice_scale])) /length(which_summary_to_use) av_STAR <- CAM_STAR(av_CAM) item_stats <- matrix(item_stats, nrow = length_best_mice_scale, ncol = 8 ) ncolssumm <- ncol(summ_fits[[1]]$ITEM_STATS)-2 indx1 <- seq(1,ncol(item_stats), by=length_best_mice_scale) indx2 <- indx1 + (length_best_mice_scale-1) samples_mice <- out_list$CHECK$SAMPLE$n_persons - out_list$CHECK$SAMPLE$missing_values$missing_cols[match(best_mice_scale,colnames(data))] list_res$MUDFOLD_INFO$second_step$scale <- best_mice_scale list_res$MUDFOLD_INFO$second_step$excluded_items <- I[which(!I %in% best_mice_scale)] list_res$MUDFOLD_INFO$second_step$Lscale <- length_best_mice_scale list_res$MUDFOLD_INFO$second_step$CAM <- av_CAM list_res$MUDFOLD_INFO$second_step$CORR <- av_COR list_res$MUDFOLD_INFO$second_step$ADJ <- av_ADJ list_res$MUDFOLD_INFO$second_step$DOM <- av_DOM list_res$MUDFOLD_INFO$second_step$STAR <- av_STAR list_res$MUDFOLD_INFO$second_step$Hscale <- scale_stats[1] list_res$MUDFOLD_INFO$second_step$Hitem <- item_stats[,8] list_res$MUDFOLD_INFO$second_step$ISOitem <- item_stats[,7] list_res$MUDFOLD_INFO$second_step$MAXitem <- item_stats[,6] list_res$MUDFOLD_INFO$second_step$ISOscale <- scale_stats[2] list_res$MUDFOLD_INFO$second_step$MAXscale <- scale_stats[3] list_res$MUDFOLD_INFO$second_step$ISOitem <- item_stats[,6] list_res$MUDFOLD_INFO$second_step$OBSitem <- item_stats[,4] list_res$MUDFOLD_INFO$second_step$OBSscale<- scale_stats[4] list_res$MUDFOLD_INFO$second_step$EXPitem <- item_stats[,5] list_res$MUDFOLD_INFO$second_step$EXPscale<- scale_stats[5] index_inverse <- which(unlist(lapply(fits_all[which_summary_to_use], function(x){ ests <- x$MUDFOLD_INFO$second_step$estimates$betas[best_mice_scale] ests[1] != 1}))) thetas <- lapply(fits_all[which_summary_to_use], function(x) x$MUDFOLD_INFO$second_step$estimates$thetas) if (length(index_inverse) != 0) thetas[index_inverse] <- lapply(index_inverse, function(y) rev(thetas[[y]])) thetas <- Reduce("+", thetas) / length(which_summary_to_use) betas <- lapply(fits_all[which_summary_to_use], function(x){ ests <- x$MUDFOLD_INFO$second_step$estimates$betas[best_mice_scale] if (ests[1] != 1) ests <- abs((length_best_mice_scale+1)-ests ) ests}) betas <- Reduce("+", betas) / length(which_summary_to_use) list_res$MUDFOLD_INFO$second_step$estimates <- list(betas=betas, thetas=thetas) class(list_res) <- "mdf" return(list_res) }
siarmenu <- function() { siarversion <-"4.1" cat("------------------------------- \n") cat(paste("Welcome to Stable Isotope Analysis in R version", siarversion, "\n")) cat("Author: Andrew Parnell, University College Dublin\n") cat("Please report bugs to: [email protected]\n") cat("------------------------------- \n") cat("\n") cat("Useful: Press 0 at a prompt to return to the main menu or Esc to exit. \n \n") siardata <- list() siardata$SHOULDRUN <- FALSE siardata$EXIT <- FALSE siardata$GRAPHSONLY <- FALSE while(siardata$EXIT==FALSE) { choices <- c("Load in some data (run this first)", "Run SIAR for a single group", "Run SIAR for multiple groups", "Plot single group proportions", "Matrix plot of proportions", "Plot of proportions by source", "Save parameter output to a file", "Summary information and convergence diagnostics", "Demo (for first time users)", "Exit") title <- "The available options are:" choose <- menu(choices,title = title) if(choose == 1) { siardata <- siarloaddata(siarversion) if(siardata$SHOULDRUN==TRUE) { cat("Do you with to plot the data? (y/n) \n") plotans <- scan(what="",nlines=1,quiet=TRUE) if(plotans=="yes" || plotans=="y") { siarplotdata(siardata) } } cat("Press <Enter> to continue") readline() invisible() } if(choose == 2) { siardata <- siarsinglegrouprun(siardata) cat("Press <Enter> to continue") readline() invisible() } if(choose == 3) { siardata <- siarmultigrouprun(siardata) cat("Press <Enter> to continue") readline() invisible() } if(choose == 4) { choices2 <- c("Traditional (isosource) plot","SIAR proportions plot") title2 <- "Isosource or SIAR style plot?" choose2 <- menu(choices2,title = title2) if(choose2==1) siarhistograms(siardata,siarversion) if(choose2==2) siarproportionbygroupplot(siardata,siarversion) cat("Press <Enter> to continue") readline() invisible() } if(choose == 5) { siarmatrixplot(siardata,siarversion) cat("Press <Enter> to continue") readline() invisible() } if(choose == 6) { siarproportionbysourceplot(siardata,siarversion) } if(choose == 7) { siarsaveoutput(siardata) } if(choose == 8) { siarhdrs(siardata) cat("Press <Enter> to continue...") readline() invisible() } if(choose == 9) { siardemo(siarversion) cat("Press <Enter> to continue") readline() invisible() } if(choose == 10) { cat("Thank you. Exiting... \n") siardata$EXIT=TRUE } } }
xformimage<-function(reg, image, ...) { UseMethod('xformimage') } xformimage.character<-function(reg, image, ...){ if (is.cmtkreg(reg[1], filecheck='magic')) xformimage(as.cmtkreg(reg), image, ...) else stop("Cannot identify registration class") } xformimage.cmtkreg<-function(reg, image, transformtype=c('warp','affine'), direction=NULL, ...){ if(is.list(reg)){ regfile=as.cmtkreg(tempfile(fileext=".list")) on.exit(unlink(regfile,recursive=TRUE)) write.cmtkreg(reg, regfile) reg=regfile } transformtype=match.arg(transformtype) if(is.null(direction) && !is.null(swap<-attr(reg,'swap'))) { direction=ifelse(swap, 'inverse', 'forward') } else { direction=match.arg(direction,c('forward', "inverse"),several.ok=TRUE) } if(transformtype=='affine') { stop("Not yet implemented") } cmtk.reformatx(floating = image, registrations = rev(reg), direction=direction, ...) } xformimage.reglist<-function(reg, image, ...){ reg=simplify_reglist(reg, as.cmtk = TRUE) on.exit(unlinktempfiles_reglist(reg)) xformimage(reg, image=image, ...) } xformimage.default<-function(reg, image, ...){ if(is.matrix(reg)) { xformimage(cmtkreglist(reg), image, ...) } else { stop("Unrecognised/implemented registration type") } }
library("data.table") library("wyz.code.offensiveProgramming") library("wyz.code.rdoc") gc <- GenerationContext('inst/man-generated', overwrite_b_1 = TRUE, verbosity_b_1 = FALSE, useMarkers_b_1 = FALSE) target_package_name <- 'wyz.code.rdoc' beautifier <- beautify() pc <- ProcessingContext( extraneous_l = list( seealso = sentensize(paste('class', beautifier$codelink('ProcessingContext'), 'and class', beautifier$codelink('InputContext'))), keyword = 'documentation', concept = 'documentation generation' ) ) ic <- InputContext(pc, packageName_s_1 = 'wyz.code.rdoc') r1 <- produceManualPage(ic, pc, gc) m <- ManualPageBuilder(InputContext(NULL)) pc <- ProcessingContext( extraneous_l = list( seealso = sentensize(paste('class', beautifier$codelink('InputContext'), 'class', beautifier$codelink('ProcessingContext'), 'and class', beautifier$codelink('GenerationContext'))), keyword = 'documentation', concept = 'documentation generation' ) ) ic <- InputContext(m, packageName_s_1 = 'wyz.code.rdoc') r2 <- produceManualPage(ic, pc, gc) interpretResults(r2)
context("Testing calibration plot") test_that("Error thrown if neither the knots or df specified - both NULL", { kyph_dat <- data.frame(Kyphosis=sample(as.factor(c("absent", "present")), 100, replace=TRUE), Age = sample(seq_len(175), 100, replace=TRUE), ncol=2) y <- as.numeric(kyph_dat$Kyphosis)-1 x <- kyph_dat$Age glm1 <- glm(y~poly(x,2),family=binomial) p <- predict(glm1, type="response") expect_error(calibrate_plot(y, p, df=NULL, knots=NULL, xlim=c(0,0.6), ylim=c(0,0.6))) }) test_that("Error thrown if df is not a positive integer (if vector first element must be a positive integer)", { kyph_dat <- data.frame(Kyphosis=sample(as.factor(c("absent", "present")), 100, replace=TRUE), Age = sample(seq_len(175), 100, replace=TRUE), ncol=2) y <- as.numeric(kyph_dat$Kyphosis)-1 x <- kyph_dat$Age glm1 <- glm(y~poly(x,2),family=binomial) p <- predict(glm1, type="response") expect_error(calibrate_plot(y, p, df=0, knots=NULL, xlim=c(0,0.6), ylim=c(0,0.6))) expect_error(calibrate_plot(y, p, df=1.4, knots=NULL, xlim=c(0,0.6), ylim=c(0,0.6))) expect_error(calibrate_plot(y, p, df="Wrong", knots=NULL, xlim=c(0,0.6), ylim=c(0,0.6))) expect_error(calibrate_plot(y, p, df=c(1, 2), knots=NULL, xlim=c(0,0.6), ylim=c(0,0.6)), NA) expect_error(calibrate_plot(y, p, df=c(1.4, 2), knots=NULL, xlim=c(0,0.6), ylim=c(0,0.6))) expect_error(calibrate_plot(y, p, df=NaN, knots=NULL, xlim=c(0,0.6), ylim=c(0,0.6))) expect_error(calibrate_plot(y, p, df=NA, knots=NULL, xlim=c(0,0.6), ylim=c(0,0.6))) expect_error(calibrate_plot(y, p, df=Inf, knots=NULL, xlim=c(0,0.6), ylim=c(0,0.6))) }) test_that("Error thrown if y and p not same length", { kyph_dat <- data.frame(Kyphosis=sample(as.factor(c("absent", "present")), 100, replace=TRUE), Age = sample(seq_len(175), 100, replace=TRUE), ncol=2) y <- as.numeric(kyph_dat$Kyphosis)-1 x <- kyph_dat$Age glm1 <- glm(y~poly(x,2),family=binomial) p <- predict(glm1, type="response") p <- p[seq(length(p)-1)] expect_error(calibrate_plot(y, p)) }) test_that("Can run with defaults", { kyph_dat <- data.frame(Kyphosis=sample(as.factor(c("absent", "present")), 100, replace=TRUE), Age = sample(seq_len(175), 100, replace=TRUE), ncol=2) y <- as.numeric(kyph_dat$Kyphosis)-1 x <- kyph_dat$Age glm1 <- glm(y~poly(x,2),family=binomial) p <- predict(glm1, type="response") expect_error(calibrate_plot(y, p), NA) }) test_that("Can run with shade_col not NA", { kyph_dat <- data.frame(Kyphosis=sample(as.factor(c("absent", "present")), 100, replace=TRUE), Age = sample(seq_len(175), 100, replace=TRUE), ncol=2) y <- as.numeric(kyph_dat$Kyphosis)-1 x <- kyph_dat$Age glm1 <- glm(y~poly(x,2),family=binomial) p <- predict(glm1, type="response") expect_error(calibrate_plot(y, p, shade_col=1), NA) }) test_that("Can run with replace = FALSE", { kyph_dat <- data.frame(Kyphosis=sample(as.factor(c("absent", "present")), 100, replace=TRUE), Age = sample(seq_len(175), 100, replace=TRUE), ncol=2) y <- as.numeric(kyph_dat$Kyphosis)-1 x <- kyph_dat$Age glm1 <- glm(y~poly(x,2),family=binomial) p <- predict(glm1, type="response") expect_error(calibrate_plot(y, p, replace=FALSE), NA) }) test_that("Can run with shade_density != NULL", { kyph_dat <- data.frame(Kyphosis=sample(as.factor(c("absent", "present")), 100, replace=TRUE), Age = sample(seq_len(175), 100, replace=TRUE), ncol=2) y <- as.numeric(kyph_dat$Kyphosis)-1 x <- kyph_dat$Age glm1 <- glm(y~poly(x,2),family=binomial) p <- predict(glm1, type="response") expect_error(calibrate_plot(y, p, shade_density=2.0), NA) }) test_that("Can run all distributions", { kyph_dat <- data.frame(Kyphosis=sample(as.factor(c("absent", "present")), 100, replace=TRUE), Age = sample(seq_len(175), 100, replace=TRUE), ncol=2) y <- as.numeric(kyph_dat$Kyphosis)-1 x <- kyph_dat$Age glm1 <- glm(y~poly(x,2),family=binomial) p <- predict(glm1, type="response") expect_error(calibrate_plot(y, p, distribution = "AdaBoost"), NA) expect_error(calibrate_plot(y, p, distribution = "Bernoulli"), NA) expect_error(calibrate_plot(y, p, distribution = "CoxPH"), NA) expect_error(calibrate_plot(y, p, distribution = "Gamma"), NA) expect_error(calibrate_plot(y, p, distribution = "Gaussian"), NA) expect_error(calibrate_plot(y, p, distribution = "Laplace"), NA) expect_error(calibrate_plot(y, p, distribution = "Huberized"), NA) expect_error(calibrate_plot(y, p, distribution = "Pairwise"), NA) expect_error(calibrate_plot(y, p, distribution = "Poisson"), NA) expect_error(calibrate_plot(y, p, distribution = "Quantile"), NA) expect_error(calibrate_plot(y, p, distribution = "TDist"), NA) expect_error(calibrate_plot(y, p, distribution = "Tweedie"), NA) })
.tl_configure_columns <- function(tbl, nms) { .Tcl(sprintf("%s configure -columns {%s}", tbl$ID, paste(sprintf("0 {%s} left", nms), collapse="\n") )) sapply(seq_along(nms), function(j) .tl_set_column_editable(tbl, j)) } .tl_insert_row <- function(tbl, row) { if(length(row) == 1 && grepl(" ", row)) row <- paste("{", row, "}", sep="") tcl(tbl, "insert", "end", unlist(lapply(row, as.character))) } .tl_clear_data <- function(tbl) { tcl(tbl, "delete", "0", "end") } .tl_load_data <- function(tbl, items) { .tl_clear_data(tbl) sapply(seq_len(nrow(items)), function(i) .tl_insert_row(tbl, items[i,,drop=TRUE])) } .tl_get_cellindex <- function(tbl, i, j) { tcl(tbl, "cellindex", sprintf("%s, %s", i-1, j-1)) } .tl_get_cell_raw <- function(tbl, i, j) { raw <- tcl(tbl, "cellcget", .tl_get_cellindex(tbl, i, j), "-text") tclvalue(raw) } .tl_get_column_raw1 <- function(tbl, j) { m <- .tl_no_rows(tbl) sapply(seq_len(m), function(i) .tl_get_cell_raw(tbl, i, j)) } .tl_get_column_raw <- function(tbl, j) { tcl(tbl, "getcolumns", j-1) } .tl_get_raw <- function(tbl) { do.call(cbind, lapply(seq_len(.tl_no_cols(tbl)), function(j) .tl_get_column_raw(tbl, j))) } .coerce_raw <- function(x, values) UseMethod(".coerce_raw") .coerce_raw.default <- function(x, values) as.character(values) .coerce_raw.integer <- function(x, values) as.integer(values) .coerce_raw.numeric <- function(x, values) as.numeric(values) .coerce_raw.logical <- function(x, values) as.logical(values) .coerce_raw.factor <- function(x, values) factor(as.character(values)) .tl_set_column_name <- function(tbl, j, nm) { tcl(tbl, "columnconfigure", j-1, title=nm) } ..tl_set_column_names <- function(tbl, nms) { for(j in seq_along(nms)) .tl_set_column_name(tbl, j, nms[j]) } .tl_get_column_name <- function(tbl, j) { tail(as.character(tcl(tbl, "columnconfigure", j-1, title=NULL)), n=1) } ..tl_get_column_names <- function(tbl) { sapply(seq_len(.tl_no_cols(tbl)), function(j) .tl_get_column_name(tbl, j)) } .tl_remove_column <- function(tbl, j) { tcl(tbl, "deletecolumns", j-1, j-1) } .tl_sort_bycolumn <- function(tbl, j, decreasing=FALSE) { dir <- if(decreasing) "decreasing" else "increasing" tcl(tbl, "sortbycolumn", j-1, sprintf("-%s", dir)) } .tl_no_rows <- function(tbl) as.numeric(tcl(tbl, "childcount", "root")) .tl_no_cols <- function(tbl) as.numeric(tcl(tbl, "columncount")) .tl_set_focus_on_cell <- function(tbl, i, j) { tcl(tbl, "see", sprintf("%s, %s", i-1, j-1)) } .tl_hide_row <- function(tbl, i, hide=TRUE) { hide <- if(hide) 1 else 0 tcl(tbl, "rowconfigure", i-1, hide=hide) } .tl_hide_column <- function(tbl, j, hide=TRUE) { hide <- if(hide) 1 else 0 tcl(tbl, "columnconfigure", j-1, hide=hide) } .tl_set_column_editable <- function(tbl, j, editable=TRUE) { editable <- if(editable) "yes" else "no" tcl(tbl, "columnconfigure", j-1, editable=editable) } .tl_set_column_name <- function(tbl, j, nm) { tcl(tbl, "columnconfigure", j-1, title=nm) } ..tl_set_column_names <- function(tbl, nms) { for(j in seq_along(nms)) .tl_set_column_name(tbl, j, nms[j]) } .tl_get_column_name <- function(tbl, j) { tail(as.character(tcl(tbl, "columnconfigure", j-1, title=NULL)), n=1) } ..tl_get_column_names <- function(tbl) { sapply(seq_len(.tl_no_cols(tbl)), function(j) .tl_get_column_name(tbl, j)) } .tl_remove_column <- function(tbl, j) { tcl(tbl, "deletecolumns", j-1, j-1) } .tl_sort_bycolumn <- function(tbl, j, decreasing=FALSE) { dir <- if(decreasing) "decreasing" else "increasing" tcl(tbl, "sortbycolumn", j-1, sprintf("-%s", dir)) } .tl_no_rows <- function(tbl) as.numeric(tcl(tbl, "childcount", "root")) .tl_no_cols <- function(tbl) as.numeric(tcl(tbl, "columncount")) .tl_set_focus_on_cell <- function(tbl, i, j) { tcl(tbl, "see", sprintf("%s, %s", i-1, j-1)) } .tl_hide_row <- function(tbl, i, hide=TRUE) { hide <- if(hide) 1 else 0 tcl(tbl, "rowconfigure", i-1, hide=hide) } .tl_hide_column <- function(tbl, j, hide=TRUE) { hide <- if(hide) 1 else 0 tcl(tbl, "columnconfigure", j-1, hide=hide) } .tl_set_column_editable <- function(tbl, j, editable=TRUE) { editable <- if(editable) "yes" else "no" tcl(tbl, "columnconfigure", j-1, editable=editable) } .tl_new <- function(parent) { if(!inherits(tclRequire("tablelist", warn = FALSE), "tclObj")) stop(.gettext("Tk widget 'tablelist' could not be loaded")) block <- ttkframe(parent) xscr <- ttkscrollbar(block, orient="horizontal", command=function(...) tkxview(widget,...)) yscr <- ttkscrollbar(block, orient="vertical", command=function(...) tkyview(widget,...)) widget <- tkwidget(block, "tablelist::tablelist", resizablecolumns=1, xscrollcommand=function(...) tkset(xscr,...), yscrollcommand=function(...) tkset(yscr,...)) tcl(widget, "configure", selecttype="cell") tkgrid(widget, row=0, column=0, sticky="news") tkgrid(yscr, row=0, column=1, sticky="ns") tkgrid(xscr, row=1, column=0, sticky="ew") tkgrid.columnconfigure(block, 0, weight=1) tkgrid.rowconfigure(block, 0, weight=1) tcl("autoscroll::autoscroll", xscr) tcl("autoscroll::autoscroll", yscr) tkgrid(block, sticky="news") tkgrid.columnconfigure(top, 0, weight=1) tkgrid.rowconfigure(top, 0, weight=1) tkgrid.propagate(block, FALSE) widget } .tl_set_items <- function(widget, value, i,j,...) { if(!missing(i) || !missing(j)) { tmp <- .get_items(widget) tmp[i,j] <- value value <- tmp } .tl_load_data(widget, value) } .tl_save_data <- function(widget, nm, where) { assign(make.names(nm), .get_items(widget), where) } .get_dim <- function(widget) c(.tl_no_rows(widget), .tl_no_cols(widget)) .get_items <- function(widget, i, j, ...) { opar <- options("warn"); on.exit(options(opar)) options(list(warn=-1)) d <- .get_dim(widget) l <- lapply(seq_len(d[2]), function(j) { .coerce_raw(head[[j]], .tl_get_column_raw(widget, j)) }) m <- structure(l, .Names=..tl_get_column_names(widget), row.names=seq_len(d[1]), class="data.frame") m[i,j, ...] } .GDf <- setRefClass("GDf", fields=list( widget="ANY", block="ANY", head="ANY" ), methods=list( initialize=function(parent, items, ...) { if(!inherits(tclRequire("tablelist", warn = FALSE), "tclObj")) stop(.gettext("Tk widget 'tablelist' could not be loaded")) if(!inherits(tclRequire("autoscroll", warn = FALSE), "tclObj")) stop(.gettext("Tk widget 'autoscroll' could not be loaded")) init_widget(parent) items <- as.data.frame(items) .tl_configure_columns(widget, names(items)) set_items(value=items) head <<- head(items, n=1) }, init_widget=function(parent) { block <<- ttkframe(parent) xscr <- ttkscrollbar(block, orient="horizontal", command=function(...) tkxview(widget,...)) yscr <- ttkscrollbar(block, orient="vertical", command=function(...) tkyview(widget,...)) widget <<- tkwidget(block, "tablelist::tablelist", resizablecolumns=1, xscrollcommand=function(...) tkset(xscr,...), yscrollcommand=function(...) tkset(yscr,...)) tcl(widget, "configure", selecttype="cell") tkgrid(widget, row=0, column=0, sticky="news") tkgrid(yscr, row=0, column=1, sticky="ns") tkgrid(xscr, row=1, column=0, sticky="ew") tkgrid.columnconfigure(block, 0, weight=1) tkgrid.rowconfigure(block, 0, weight=1) tcl("autoscroll::autoscroll", xscr) tcl("autoscroll::autoscroll", yscr) tkgrid.propagate(block, FALSE) }, set_items=function(value, i,j,...) { if(!missing(i) || !missing(j)) { tmp <- .get_items() tmp[i,j] <- value value <- tmp } .tl_load_data(widget, value) }, save_data=function(nm, where) { "Save data set" tcl(widget, "finishediting") assign(make.names(nm), .get_items(), where) }, .get_items=function(i, j, ...) { opar <- options("warn"); on.exit(options(opar)) options(list(warn=-1)) d <- .get_dim() l <- lapply(seq_len(d[2]), function(j) { .coerce_raw(head[[j]], .tl_get_column_raw(widget, j)) }) m <- structure(l, .Names=..tl_get_column_names(widget), row.names=seq_len(d[1]), class="data.frame") m[i,j, ...] }, get_names=function() ..tl_get_column_names(widget), set_names=function(values, ...) ..tl_set_column_names(widget,values), .get_dim=function() c(.tl_no_rows(widget), .tl_no_cols(widget)), get_length=function() .get_dim()[2], hide_row=function(i, hide=TRUE) .tl_hide_row(widget, i, hide), hide_column=function(j, hide=TRUE) .tl_hide_column(widget, j, hide), set_editable=function(j, value=TRUE) .tl_set_column_editable(widget, j, value), focus_cell=function(i,j) tl_set_focus_on_cel(widget, i, j), sort_bycolumn=function(j, decreasing=FALSE) { .tl_sort_bycolumn(widget, j, decreasing) } )) editDictionary <- function(df) { top <- tktoplevel() tkwm.geometry(top, tkwm.geometry(CommanderWindow())) df <- cbind(rownames(df), df) names(df)[[1]] <- .gettext("Original.Word") tl <- .GDf(top, df) tkgrid(tl$block, sticky="news") tkgrid.columnconfigure(top, 0, weight=1) tkgrid.rowconfigure(top, 0, weight=1) tl$set_editable(1, FALSE) tl$set_editable(2, FALSE) tl$set_editable(4, FALSE) .env <- environment() onImport <- function() { file <- tclvalue(tkgetOpenFile(filetypes=sprintf('{"%s" {".csv" ".CSV"}}', .gettext("Comma-separated values (CSV) file")), parent=top)) if (file == "") { tkfocus(CommanderWindow()) return() } excerpt <- readLines(file, 50) n1 <- sum(sapply(gregexpr(",", excerpt), length)) n2 <- sum(sapply(gregexpr(";", excerpt), length)) if(n1 > n2) df2 <- read.csv(file, stringsAsFactors=FALSE) else df2 <- read.csv2(file, stringsAsFactors=FALSE) if(!.gettext("Original.Word") %in% names(df2) || !.gettext("Stemmed.Term") %in% names(df2)) { .Message(sprintf(.gettext("Data set must contain columns named \"%s\" and \"%s\"."), .gettext("Original.Word"), .gettext("Stemmed.Term")), type="error", parent=top) return() } tkgrab.release(top) tkdestroy(top) df2 <- merge(df[make.names(c(.gettext("Original.Word"), .gettext("Occurrences"), .gettext("Stopword")))], df2[make.names(c(.gettext("Original.Word"), .gettext("Stemmed.Term")))], by=.gettext("Original.Word"), all.x=TRUE, all.y=FALSE) df2[[.gettext("Stemmed.Term")]] <- as.character(df2[[.gettext("Stemmed.Term")]]) df2[is.na(df2[[.gettext("Stemmed.Term")]]), .gettext("Stemmed.Term")] <- "" rownames(df2) <- df2[[.gettext("Original.Word")]] df2 <- df2[make.names(c(.gettext("Stemmed.Term"), .gettext("Occurrences"), .gettext("Stopword")))] df <<- editDictionary(df2) } onExport <- function() { tl$save_data("df", .env) rownames(.env$df) <- .env$df[[1]] .env$df <- .env$df[-1] file <- tclvalue(tkgetSaveFile(filetypes=sprintf('{"%s" {".csv" ".CSV"}}', .gettext("Comma-separated values (CSV) file")), defaultextension="csv", initialfile="dictionary.csv", parent=top)) if (file == "") { tkfocus(CommanderWindow()) return() } .env$df <- cbind(rownames(.env$df), .env$df) names(.env$df)[[1]] <- .gettext("Original.Word") write.csv(.env$df, file=file, row.names=FALSE) .Message(.gettext(sprintf("Stemming dictionary saved to \"%s\".", file))) } onOK <- function() { tl$save_data("df", .env) rownames(.env$df) <- .env$df[[1]] .env$df <- .env$df[-1] tkgrab.release(top) tkdestroy(top) } buttonsFrame <- tkframe(top) leftButtonsBox <- tkframe(buttonsFrame) rightButtonsBox <- tkframe(buttonsFrame) importButton <- buttonRcmdr(leftButtonsBox, text=.gettext("Import stemming dictionary"), command=onImport) exportButton <- buttonRcmdr(leftButtonsBox, text=.gettext("Export stemming dictionary"), command=onExport) OKbutton <- buttonRcmdr(rightButtonsBox, text=gettextRcmdr("OK"), width=12, command=onOK, default="active", image="::image::okIcon", compound="left") tkgrid(importButton, exportButton, sticky="ew", padx=6) tkgrid(OKbutton, sticky="e", padx=6) tkgrid.configure(leftButtonsBox, rightButtonsBox, pady=6, sticky="ew") tkgrid.configure(buttonsFrame, sticky="ew") tkgrid.columnconfigure(buttonsFrame, 0, weight=1) tkgrid.columnconfigure(buttonsFrame, 1, weight=1) tkgrid.configure(leftButtonsBox, sticky="w") tkgrid.configure(rightButtonsBox, sticky="e") tkgrab.set(top) tkwait.window(top) .env$df }
.plotbaselinerisk <- function(x,event=1,legend.loc="topleft",legend,add=FALSE,...) { if(missing(x)) stop("The argument x should be specified") nbevt <- length(x$N)-9 if(length(event)!=1) stop("Please specify only one event") if(!(event %in% c(1:nbevt))) stop("Argument event is not correct") if(is.na(as.logical(add))) stop("add should be TRUE or FALSE") if((x$conv==1|x$conv==2|x$conv==3)& (sum(is.na(x$predSurv)==0))) { ng <- x$ng dots <- list(...) if(length(list(...)$main)) { title1 <- as.character(eval(dots$main)) dots <- dots[setdiff(names(dots),"main")] } else title1 <- "Class-specific baseline risk functions" if(length(list(...)$col)) { color <- as.vector(eval(dots$col)) dots <- dots[-which(names(dots)=="col")] } else color <- 1:ng if(length(list(...)$type)) { type1 <- eval(dots$type) dots <- dots[-which(names(dots)=="type")] } else type1 <- "l" if(length(list(...)$xlab)) { xlab1 <- as.character(eval(dots$xlab)) dots <- dots[setdiff(names(dots),"xlab")] } else xlab1 <- "Time" if(length(list(...)$ylab)) { ylab1 <- as.character(eval(dots$ylab)) dots <- dots[setdiff(names(dots),"ylab")] } else ylab1 <- "Baseline risk function" if(length(list(...)$lty)) { lty1 <- eval(dots$lty) dots <- dots[-which(names(dots)=="lty")] } else lty1 <- 1:ng if(missing(legend)) legend <- paste("class",1:ng,sep="") if(length(list(...)$box.lty)) { box.lty1 <- as.integer(eval(dots$box.lty)) dots <- dots[setdiff(names(dots),"box.lty")] } else box.lty1 <- 0 if(length(list(...)$inset)) { inset1 <- eval(dots$inset) dots <- dots[setdiff(names(dots),"inset")] } else inset1 <- c(0.05,0.05) names.plot <- c("adj","ann","asp","axes","bg","bty","cex","cex.axis","cex.lab","cex.main","cex.sub","col","col.axis", "col.lab","col.main","col.sub","crt","err","family","fig","fin","font","font.axis","font.lab","font.main","font.sub", "frame.plot","lab","las","lend","lheight","ljoin","lmitre","lty","lwd","mai","main","mar","mex","mgp","mkh","oma", "omd","omi","pch","pin","plt","ps","pty","smo","srt","sub","tck","tcl","type","usr","xaxp","xaxs","xaxt","xlab", "xlim","xpd","yaxp","yaxs","yaxt","ylab","ylbias","ylim") dots.plot <- dots[intersect(names(dots),names.plot)] if(!isTRUE(add)) { do.call("matplot",c(dots.plot,list(x=x$predSurv[,1],y=x$predSurv[,(1+(event-1)*ng+1:ng)],xlab=xlab1,ylab=ylab1,main=title1,type=type1,col=color,lty=lty1))) } else { do.call("matlines",c(dots.plot,list(x=x$predSurv[,1],y=x$predSurv[,(1+(event-1)*ng+1:ng)],type=type1,col=color,lty=lty1))) } names.legend <- c("fill","border","lty","lwd","pch","angle","density","bg","box.lwd", "box.lty","box.col","pt.bg","cex","pt.cex","pt.lwd","xjust","yjust","x.intersp","y.intersp","adj","text.width", "text.col","text.font","merge","trace","plot","ncol","horiz","title","xpd","title.col","title.adj","seg.len") dots.leg <- dots[intersect(names(dots),names.legend)] if(!is.null(legend)) { do.call("legend",c(dots.leg,list(x=legend.loc,legend=legend,col=color,box.lty=box.lty1,inset=inset1,lty=lty1))) } } else { cat("Output can not be produced. The program stopped abnormally or there was an error in the computation of the estimated baseline risk functions and survival functions.\n") } }
`dominant` <- function (o) UseMethod("dominant")
recordPlot <- function(load=NULL, attach=NULL) { if(dev.cur() == 1L) stop("no current device to record from") res <- .External2(C_getSnapshot) attr(res, "pid") <- Sys.getpid() attr(res, "Rversion") <- getRversion() attr(res, "load") <- as.character(load) attr(res, "attach") <- as.character(attach) class(res) <- "recordedplot" res } replayPlot <- function(x, reloadPkgs=FALSE) { if(!inherits(x, "recordedplot")) stop(gettextf("argument is not of class %s", dQuote("recordedplot")), domain = NA) pid <- attr(x, "pid") if (doRestore <- (is.null(pid) || pid != Sys.getpid())) { x <- restoreRecordedPlot(x, reloadPkgs) } restore <- function(e) { if(doRestore) stop("invalid \"recordedplot\": ", conditionMessage(e)) .External2(C_playSnapshot, restoreRecordedPlot(x, reloadPkgs)) } r <- tryCatch(.External2(C_playSnapshot, x), error = restore) invisible(r) } print.recordedplot <- function(x, ...) { replayPlot(x) invisible(x) } restoreRecordedPlot <- function(plot, reloadPkgs) { snapshotRversion <- attr(plot, "Rversion") if (is.null(snapshotRversion)) { warning("snapshot recorded in different R version (pre 3.3.0)") } else if (snapshotRversion != getRversion()) { warning(gettextf("snapshot recorded in different R version (%s)", snapshotRversion)) } if (!is.null(snapshotRversion) && snapshotRversion >= R_system_version("3.3.0")) { for (i in seq_along(plot)[-1]) { library(attr(plot[[i]], "pkgName"), character.only=TRUE) } if (reloadPkgs) { load <- attr(plot, "load") for (i in load) { loadNamespace(i) } attach <- attr(plot, "attach") for (i in attach) { library(i, character.only=TRUE) } } } for (i in seq_along(plot[[1]])) { symbol <- plot[[c(1L, i, 2L, 1L)]] if (inherits(symbol, "NativeSymbolInfo")) { name <- (if(!is.null(symbol$package)) symbol$package else symbol$dll)[["name"]] pkgDLL <- getLoadedDLLs()[[name]] nativeSymbol <- getNativeSymbolInfo(name = symbol$name, PACKAGE = pkgDLL, withRegistrationInfo = TRUE) if (nativeSymbol$numParameters != symbol$numParameters) { stop("snapshot contains invalid graphics call") } plot[[c(1L, i, 2L, 1L)]] <- nativeSymbol } } plot }
model <- function(...) Model(...)
library(VLMC) set.seed(21001) c0 <- proc.time() f1 <- c(1,0,0,0) f2 <- rep(1:0,2) (dt2 <- rep(c(f1,f1,f2,f1,f2,f2,f1),2)) dt3 <- c(unlist(sapply(1:5, function(k) c(rep(0,k),1))), rep(1,6)) (vlmc.dt2c15 <- vlmc(dt2, cutoff = 1.5)) draw(vlmc.dt2c15) noquote(cbind(fit = predict(vlmc.dt2c15, type = "response"), probs = pr <- predict(vlmc.dt2c15), lev = predict(vlmc.dt2c15, type = "depth"), ID = (pid <- predict(vlmc.dt2c15, type = "id")), flags = {ff <- attr(pr,"flags"); ff[ff == "0"] <- ""; ff}, context= id2ctxt(pid, m=2, alpha=TRUE) )) (vlmc.dt2c.1 <- vlmc(dt2, cutoff = .1)) (vlmc.dt2c0 <- vlmc(dt2, cutoff = 0, thresh = 1)) draw(vlmc.dt2c.1) pp.1 <- predict(vlmc.dt2c.1) p.1 <- predict(vlmc.dt2c.1, type="response") pid.1 <- predict(vlmc.dt2c.1, type="id.node") (pl.1 <- predict(vlmc.dt2c.1, type="depth")) noquote(cbind(pp.1,fit=p.1, "="=c("<>","")[1+(dt2==p.1)], lev= pl.1, id= pid.1, flags = attr(p.1,"flags"), context = id2ctxt(pid.1, m=2, alpha=TRUE) )) predict(vlmc.dt2c.1, type = "ALL") draw(vlmc.dt2c0) draw(vlmc.dt2c0, cumulative = FALSE) (p0 <- predict(vlmc.dt2c0, type="response")) all(dt2[-1] == abs(p0[-1])) pp <- predict(vlmc.dt2c0) !any(is.na(match(pp[-1,],0:1))) p.id <- predict(vlmc.dt2c0, type="id.node") p.lev <- predict(vlmc.dt2c0, type="depth") noquote(cbind(pp, flags = attr(p.id,"flags"), ID= p.id, lev = p.lev, ctxt = id2ctxt(p.id,m=2, a=TRUE))) predict(vlmc.dt2c0, type="ALL") p.dt2c0dt3 <- predict(vlmc.dt2c0, dt3) which(is.na(unname(p.dt2c0dt3[-1,1]))) predict(vlmc.dt2c0, dt3, type = "ALL") prm <- cbind(fit = predict(vlmc.dt2c0, dt3, type = "response"), probs = (pr <- predict(vlmc.dt2c0, dt3)), lev = predict(vlmc.dt2c0, dt3, type = "depth"), ID = (pid <- predict(vlmc.dt2c0, dt3, type = "id")), flags = attr(pr,"flags")) noquote(cbind(prm, context = id2ctxt(pid, m=2, alpha=TRUE))) mod <- vlmc(rep(1, 99)) pr <- predict(mod, c(1, 0, 1)) stopifnot(pr[-1] == 1) cat("Time elapsed:", format(proc.time() - c0),"\n")
dmcSim <- function(amp = 20, tau = 30, drc = 0.5, bnds = 75, resDist = 1, resMean = 300, resSD = 30, aaShape = 2, spShape = 3, sigm = 4, nTrl = 100000, tmax = 1000, spDist = 0, spLim = c(-75, 75), spBias = 0, drDist = 0, drShape = 3, drLim = c(0.1, 0.7), rtMax = 5000, fullData = FALSE, nTrlData = 5, nDelta = 9, pDelta = vector(), tDelta = 1, nCAF = 5, printInputArgs = TRUE, printResults = TRUE, setSeed = FALSE, seedValue = 1) { if (length(pDelta) != 0) { nDelta <- length(pDelta) if (tDelta == 2) { nDelta <- nDelta + 1 } } dmc <- dmcCppR( r_in = list(amp = amp, tau = tau, drc = drc, bnds = bnds, resDist = resDist, resMean = resMean, resSD = resSD, aaShape = aaShape, spShape = spShape, spBias = spBias, sigm = sigm, nTrl = nTrl, tmax = tmax, rtMax = rtMax, fullData = fullData, nTrlData = nTrlData, nDelta = nDelta, pDelta = pDelta, tDelta = tDelta, nCAF = nCAF, spDist = spDist, spLimLow = spLim[1], spLimHigh = spLim[2], drDist = drDist, drShape = drShape, drLimLow = drLim[1], drLimHigh = drLim[2], printInputArgs = printInputArgs, printResults = printResults, setSeed = setSeed, seedValue = seedValue) ) summary <- dmc$summary dmc$summary <- NULL dmc$summary <- as.data.frame(rbind(summary$comp, summary$incomp)) names(dmc$summary) <- c("rtCor", "sdRtCor", "perErr", "rtErr", "sdRtErr", "perSlow") dmc$summary <- cbind(Comp = c("comp", "incomp"), dmc$summary) dmc$caf <- as.data.frame(cbind(Bin = 1:nCAF, accPerComp = summary$caf_comp, accPerIncomp = summary$caf_incomp, meanEffect = ((100 - summary$caf_incomp) - (100 - summary$caf_comp)) * 100)) dmc$delta <- as.data.frame(cbind(Bin = 1:nDelta, meanComp = summary$delta_correct_comp, meanIncomp = summary$delta_correct_incomp, meanBin = summary$delta_correct_mean, meanEffect = summary$delta_correct_delta)) dmc$delta_errs <- as.data.frame(cbind(Bin = 1:nDelta, meanComp = summary$delta_errors_comp, meanIncomp = summary$delta_errors_incomp, meanBin = summary$delta_errors_mean, meanEffect = summary$delta_errors_delta)) dmc$prms <- data.frame( amp = amp, tau = tau, drc = drc, bnds = bnds, resMean = resMean, resSD = resSD, aaShape = aaShape, spShape = spShape, spBias = spBias, sigm = sigm, nTrl = nTrl, nTrlData = nTrlData, tmax = tmax, resDist = resDist, spDist = spDist, spLim1 = spLim[1], spLim2 = spLim[2], drDist = drDist, drShape = drShape, drLim1 = drLim[1], drLim2 = drLim[2] ) class(dmc) <- "dmcsim" return(dmc) } dmcSims <- function(params, printInputArgs = FALSE, printResults = FALSE) { params <- expand.grid(params) if (ncol(params) > 1) { uparams <- params[, lengths(lapply(params, unique)) != 1, drop = FALSE] } else { uparams <- params } params <- setNames(split(params, seq(nrow(params))), rownames(params)) dmc <- vector("list", length(params)) for (i in seq_along(params)) { dmcInputs <- params[[i]] message("DMC ", i, " of ", length(params), ": ", paste0(names(dmcInputs), "=", dmcInputs, sep = "", collapse = ", ")) dmcInputs$printInputArgs <- printInputArgs dmcInputs$printResults <- printResults dmc[[i]] <- do.call(dmcSim, dmcInputs) dmc[[i]]$params <- uparams } class(dmc) <- "dmclist" return(dmc) } dmcSimApp <- function() { shiny::runApp(system.file('dmcSimApp', package = "DMCfun")) }
recTensor <- function(S = NULL, A = NULL, idx = 1:3, reverse = FALSE){ if (is(S)[1] == "Tensor") { X_bar <- S if(length(dim(S)) > 3){ idx <- seq_along(A) } } else if ("numeric" %in% is(S) && length(S) == 1) { X_bar <- rand_tensor(rep(1, length=length(idx))) X_bar@data[] <- S } else if ("numeric" %in% is(S) && length(S) != 1) { X_bar <- rand_tensor(sapply(A, nrow)) X_bar@data[] <- 0 for (n in seq_along(S)) { cmd = paste0("X_bar@data[", paste(rep("n", length=length(A)), collapse=","), "] <- S[n]") eval(parse(text=cmd)) } } if (!reverse) { for (n in idx) { X_bar <- ttm(X_bar, t(A[[n]]), m = n) } } else { for (n in idx) { X_bar <- ttm(X_bar, A[[n]], m = n) } } return(X_bar) }
library("mclust") library("cluster") p <- 4 K <- 6 n <- 200 n.files <- 100 omega <- c(0.4, 0.3, 0.25, 0.2, 0.15, 0.1, 0.05, 0.01, 0.005, 0.001) set.seed(1234) AR.Mclust <- rep(NA, n.files) AR.Kmeans <- rep(NA, n.files) AR.PAM <- rep(NA, n.files) AR.Ward <- rep(NA, n.files) P.Mclust <- rep(NA, n.files) P.Kmeans <- rep(NA, n.files) P.PAM <- rep(NA, n.files) P.Ward <- rep(NA, n.files) VI.Mclust <- rep(NA, n.files) VI.Kmeans <- rep(NA, n.files) VI.PAM <- rep(NA, n.files) VI.Ward <- rep(NA, n.files) for (bo in omega){ for (i in 1:n.files){ Q <- MixSim(BarOmega = bo, K = K, p = p) A <- simdataset(n = n, Pi = Q$Pi, Mu = Q$Mu, S = Q$S) id.Mclust <- try(Mclust(A$X, G = K, model = "VVV")$class) if (inherits(id.Mclust, what = "try-error") || (is.null(id.Mclust))) id.Mclust <- rep(1, n) id.Kmeans <- kmeans(A$X, K, iter.max = 1000, nstart = 10)$cluster id.PAM <- pam(A$X, K)$clustering d <- dist(A$X, method = "euclidean") id.Ward <- cutree(hclust(d = d, method = "ward"), k = K) AR.Mclust[i] <- RandIndex(A$id, id.Mclust)$AR AR.Kmeans[i] <- RandIndex(A$id, id.Kmeans)$AR AR.PAM[i] <- RandIndex(A$id, id.PAM)$AR AR.Ward[i] <- RandIndex(A$id, id.Ward)$AR P.Mclust[i] <- ClassProp(A$id, id.Mclust) P.Kmeans[i] <- ClassProp(A$id, id.Kmeans) P.PAM[i] <- ClassProp(A$id, id.PAM) P.Ward[i] <- ClassProp(A$id, id.Ward) VI.Mclust[i] <- VarInf(A$id, id.Mclust) VI.Kmeans[i] <- VarInf(A$id, id.Kmeans) VI.PAM[i] <- VarInf(A$id, id.PAM) VI.Ward[i] <- VarInf(A$id, id.Ward) } cat("Omega =", bo, "\n\n") cat("Mclust: AR mean =", mean(AR.Mclust), " sd =", sd(AR.Mclust), "\n") cat("Mclust: P mean =", mean(P.Mclust), " sd =", sd(P.Mclust), "\n") cat("Mclust: VI mean =", mean(VI.Mclust), " sd =", sd(VI.Mclust), "\n\n") cat("Kmeans: AR mean =", mean(AR.Kmeans), " sd =", sd(AR.Kmeans), "\n") cat("Kmeans: P mean =", mean(P.Kmeans), " sd =", sd(P.Kmeans), "\n") cat("Kmeans: VI mean =", mean(VI.Kmeans), " sd =", sd(VI.Kmeans), "\n\n") cat("PAM: AR mean =", mean(AR.PAM), " sd =", sd(AR.PAM), "\n") cat("PAM: P mean =", mean(P.PAM), " sd =", sd(P.PAM), "\n") cat("PAM: VI mean =", mean(VI.PAM), " sd =", sd(VI.PAM), "\n\n") cat("Ward: AR mean =", mean(AR.Ward), " sd =", sd(AR.Ward), "\n") cat("Ward: P mean =", mean(P.Ward), " sd =", sd(P.Ward), "\n") cat("Ward: VI mean =", mean(VI.Ward), " sd =", sd(VI.Ward), "\n\n") }
all_named <- function(x) { if (length(x) == 0) return(TRUE) !is.null(names(x)) && all(names(x) != "") } "%||%" <- function(x, y) if (is.null(x)) y else x compact <- function(x) Filter(Negate(is.null), x) to_env <- function(x, quiet = FALSE) { if (is.environment(x)) { x } else if (is.list(x)) { list2env(x) } else if (is.function(x)) { environment(x) } else if (length(x) == 1 && is.character(x)) { if (!quiet) message("Using environment ", x) as.environment(x) } else if (length(x) == 1 && is.numeric(x) && x > 0) { if (!quiet) message("Using environment ", search()[x]) as.environment(x) } else { stop("Input can not be coerced to an environment", call. = FALSE) } }
test_that("check_if_date returns appropriate values", { date_plot <- ggplot(ggplot2::economics, aes(x = date, y = unemploy)) + geom_line() date_plot_built <- ggplot2::ggplot_build(date_plot) date_plot_checked <- check_if_date(date_plot_built) expect_true(date_plot_checked$x_date) expect_false(date_plot_checked$y_date) expect_length(date_plot_checked, 2) expect_is(date_plot_checked, "list") non_date_plot <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() non_date_plot_built <- ggplot2::ggplot_build(non_date_plot) non_date_plot_checked <- check_if_date(non_date_plot_built) expect_false(non_date_plot_checked$x_date) expect_false(non_date_plot_checked$y_date) expect_length(date_plot_checked, 2) expect_is(date_plot_checked, "list") }) test_that("num_to_date() returns expected values", { expect_identical(num_to_date(12025), as.Date("2002-12-04")) expect_null(num_to_date(NULL)) expect_error(num_to_date("12025")) }) test_that("correct_scales() corrects scales", { p <- ggplot(ggplot2::economics, aes(x = date, y = unemploy)) + geom_line() + coord_flip() built_plot <- ggplot2::ggplot_build(p) plot_click <- list( x = 9492.364, y = 11950.13, coords_css = list( x = 487, y = 108 ) ) corrected_scales <- correct_scales( plot_click, check_if_date(built_plot), ggplot2::summarise_coord(built_plot)$flip ) expect_null(corrected_scales$xmin) expect_identical(corrected_scales$x, as.Date(plot_click$y, origin = "1970-01-01")) expect_identical(corrected_scales$y, plot_click$x) })
tau2.m.solver <- function(w, Qm){ f <- function(tau2){ out <- sum(sqrt(1 + w*tau2)) - Qm*sqrt(3.14159/2) return(out) } f <- Vectorize(f) n <- length(w) tau2.upp <- sum(1/w)*(Qm^2/n*2/3.14159 - 1) tau2.upp <- max(c(tau2.upp, 0.01)) f.low <- f(0) f.upp <- f(tau2.upp) if(f.low*f.upp > 0){ tau2.m <- 0 }else{ tau2.m <- uniroot(f, interval = c(0, tau2.upp)) tau2.m <- tau2.m$root } return(tau2.m) }
QCcorrectionMultiPoly3<-function(LCdata) { pos=1; envir=as.environment(pos); LCdata<-LCdata LCdataframe<-as.data.frame(LCdata) LCdataQC<-subset(LCdata,LCdata$QC==1) variables<-c("QC","Day") nDAY<-ddply(LCdataframe,variables,summarise,nSamples=sum(!is.na(LCdataframe$QC))) nDAYQC<-nDAY[nDAY$QC==1,] nDAYQC<-na.omit(nDAYQC) Day1<-list(nDAYQC$Day) Day2<-as.data.frame(Day1) Day<-dim(Day2)[1] a=1; while (a<(Day+1)){ assign(paste0('Day_',Day2[a,]),subset(LCdata,(LCdata$Day==(Day2[a,]))),envir=envir); assign(paste0('QCsDay_',Day2[a,]),subset(LCdataQC,(LCdataQC$Day==(Day2[a,]))),envir=envir); a<-a+1 } matrix.names<-paste0('Day_',Day2[1,]:Day2[Day,]) list<-lapply(matrix.names,get, envir=envir) matrixQC.names<-paste0('QCsDay_',Day2[1,]:Day2[Day,]) listQC<-lapply(matrixQC.names,get) PreCompoundsList<-colnames(LCdata) InfoColumns<-c("Sample","Order","QC","Day") CompoundsList<-setdiff(PreCompoundsList,InfoColumns) n=1; while(n<(Day+1)){ bb<-as.data.frame(listQC[n],envir=envir) cc<-as.data.frame(list[n],envir=envir) m=1; while(m<(length(CompoundsList)+1)){ lm<-lm(bb[,CompoundsList[m]]~poly(bb[,"Order"],3,raw=TRUE)); cc[,paste0(CompoundsList[m],'QC')]<-QCregression(coefficients(lm)[1],coefficients(lm)[2],coefficients(lm)[3],coefficients(lm)[4],cc[,"Order"]); m<-m+1 } if(exists("PreNormLCdata")){PreNormLCdata<-rbind(PreNormLCdata,cc) } else {PreNormLCdata<-cc} n<-n+1 } p=1; while(p<(length(CompoundsList)+1)){ PreNormLCdata[,paste0(CompoundsList[p],'_Norm')]<-PreNormLCdata[,(CompoundsList[p])]/PreNormLCdata[,paste0(CompoundsList[p],'QC')] p<-p+1 } NormLCdata1<-PreNormLCdata[,grepl("Norm",names(PreNormLCdata))] NormLCdata2<-PreNormLCdata[,InfoColumns] NormLCdata<-cbind(NormLCdata2,NormLCdata1) return(NormLCdata) }
context('Test convertPrevalence.') test_that('convertPrevalence works for all reasonable inputs', { pr <- seq(0, 1, 0.2) min_in <- c(1, 5, 10) max_in <- c(6, 15, 20) min_out <- c(2, 6, 9) max_out <- c(5, 13, 16) all_combs <- expand.grid(pr, min_in, max_in, min_out, max_out) names(all_combs) <- c('pr', 'min_in', 'max_in', 'min_out', 'max_out') all_combs <- all_combs[all_combs$min_in < all_combs$max_in & all_combs$min_out < all_combs$max_out, ] pr_standardised <- convertPrevalence(all_combs$pr, all_combs$min_in, all_combs$max_in, all_combs$min_out, all_combs$max_out) expect_true(all(pr_standardised <= 1)) expect_true(all(pr_standardised >= 0)) }) test_that('convertPrevalence works with gething parameters', { pr <- seq(0, 1, 0.2) min_in <- c(1, 5, 10) max_in <- c(6, 15, 20) min_out <- c(2, 6, 9) max_out <- c(5, 13, 16) all_combs <- expand.grid(pr, min_in, max_in, min_out, max_out) names(all_combs) <- c('pr', 'min_in', 'max_in', 'min_out', 'max_out') all_combs <- all_combs[all_combs$min_in < all_combs$max_in & all_combs$min_out < all_combs$max_out, ] pr_standardised <- convertPrevalence(all_combs$pr, all_combs$min_in, all_combs$max_in, all_combs$min_out, all_combs$max_out, parameters = 'Pv_Gething2012') expect_true(all(pr_standardised <= 1)) expect_true(all(pr_standardised >= 0)) }) test_that('NAs get handled right', { set.seed(1) pr <- runif(20, 0.1, 0.15) min_in <- sample(1:5, 20, replace = TRUE) max_in <- rep(8, 20) min_out <- rep(2, 20) max_out <- rep(10, 20) pr[2] <- NA min_in[3] <- NA max_in[4] <- NA pr_standardised <- convertPrevalence(pr, min_in, max_in, min_out, max_out) expect_true(all(is.na(pr_standardised[2:4]))) expect_true(all(!is.na(pr_standardised[c(1, 5:20)]))) expect_error(convertPrevalence(0.1, 2, 5, NA, 10)) expect_error(convertPrevalence(0.1, 2, 5, 2, NA)) })
basepredict.polr = function(model, values, sim.count = 1000, conf.int = 0.95, sigma=NULL, set.seed=NULL, type = c("any", "simulation", "bootstrap"), summary = TRUE){ if(sum("polr" %in% class(model)) == 0){ stop("model has to be of type polr()") } if(length(values) != length(coef(model))){ stop("the length of values is not identical to the number of coefficient of the model") } if(!is.numeric(sim.count) | round(sim.count) != sim.count){ stop("sim.count has to be whole number") } if(!is.numeric(conf.int)){ stop("conf.int has to be numeric") } if(!is.null(set.seed) & !is.numeric(set.seed)){ stop("set.seed must be numeric") } type = match.arg(type) if(type == "any"){ if(nrow(model.frame(model)) < 500){ type = "bootstrap" message("Type not specified: Using bootstrap as n < 500") }else{ type = "simulation" message("Type not specified: Using simulation as n >= 500") } } l = length(values) if(is.null(sigma)){ sigma = stats::vcov(model) } if(nrow(sigma) != length(model$coefficients) + length(model$zeta)){ warning("sigma and coef/zeta do not match, ignoring the specified sigma") sigma = stats::vcov(model) } level.count = length(model$lev) kappa.count = level.count - 1 x = values estim = c(model$coefficients, model$zeta) kappa = list() for(i in 1:kappa.count){ kappa[[length(kappa)+1]] = matrix(NA, nrow=sim.count, ncol=1, byrow=TRUE) } pred = matrix(NA,nrow = sim.count, ncol = level.count,byrow=TRUE) if(!is.null(set.seed)){ set.seed(set.seed) } if(type == "simulation"){ estim_draw = MASS::mvrnorm(sim.count, estim, sigma) }else{ boot = function(x, model){ data = model.frame(model) sample_data = data[sample(seq_len(nrow(data)), replace = TRUE), ] model_updated = update(model, data = sample_data) c(model_updated$coefficients, model_updated$zeta) } estim_draw = do.call('rbind', lapply(seq_len(sim.count), boot, model)) } beta_draw = estim_draw[,1:l] for(i in 1:kappa.count){ kappa[[i]][,] = estim_draw[,l+i] } if(is.null(dim(beta_draw))){ beta_draw = as.matrix(beta_draw) } for(j in 1:level.count){ if(j == 1){ pred[,j] = exp(kappa[[j]] - beta_draw %*% x) / (1 + exp(kappa[[j]] - beta_draw %*% x)) }else if(j == level.count){ pred[,j] = 1 / (1 + exp(kappa[[j-1]] - beta_draw %*% x)) }else{ pred[,j] = exp(kappa[[j]] - beta_draw %*% x) / (1 + exp(kappa[[j]] - beta_draw %*% x)) - exp(kappa[[j-1]] - beta_draw %*% x) / (1 + exp(kappa[[j-1]] - beta_draw %*% x)) } } if(!summary){ return(pred) } confint_lower = (1 - conf.int) / 2 result = matrix(NA, nrow = level.count, ncol=3) for(i in 1:level.count){ result[i,] = c(mean(pred[,i]), quantile(pred[,i], prob = c(confint_lower, 1 - confint_lower))) } colnames(result) = c("mean",paste0(100 * confint_lower,"%"),paste0(100 * (1 - confint_lower),"%")) rownames(result) = model$lpred return(result) }
test_that("Test my ggplot.lmfit function: ", { expect_true(is.ggplot(ggplot.lmfit(1:10, 2:11))) })
fetch_chebi <- function(relation = FALSE) { if (!requireNamespace("httr", quietly = TRUE)) { stop("Package \"httr\" is needed for this function to work. Please install it.", call. = FALSE) } if (relation == TRUE) { chebi_relation_result <- httr::GET("ftp://ftp.ebi.ac.uk/pub/databases/chebi/Flat_file_tab_delimited/relation.tsv", config = httr::config(connecttimeout = 60) ) chebi_relation <- suppressMessages(httr::content(chebi_relation_result, type = "text/tab-separated-values", progress = FALSE, show_col_types = FALSE )) chebi_relation_clean <- chebi_relation %>% dplyr::filter(.data$STATUS == "C") %>% dplyr::select(-c(.data$ID, .data$STATUS)) %>% dplyr::rename(incoming = .data$FINAL_ID) %>% dplyr::rename(ID = .data$INIT_ID) %>% janitor::clean_names() return(chebi_relation_clean) } chebi_chemical_data_result <- httr::GET("ftp://ftp.ebi.ac.uk/pub/databases/chebi/Flat_file_tab_delimited/chemical_data.tsv", config = httr::config(connecttimeout = 60) ) chebi_chemical_data <- suppressMessages(httr::content(chebi_chemical_data_result, type = "text/tab-separated-values", progress = FALSE, show_col_types = FALSE )) chebi_compounds_download <- readLines(gzcon(url("ftp://ftp.ebi.ac.uk/pub/databases/chebi/Flat_file_tab_delimited/compounds.tsv.gz"))) chebi_compounds <- utils::read.delim(textConnection(chebi_compounds_download), quote = "", stringsAsFactors = FALSE ) chebi_names_download <- readLines(gzcon(url("ftp://ftp.ebi.ac.uk/pub/databases/chebi/Flat_file_tab_delimited/names.tsv.gz"))) chebi_names <- utils::read.delim(textConnection(chebi_names_download), quote = "", stringsAsFactors = FALSE ) chebi_accession_result <- httr::GET("ftp://ftp.ebi.ac.uk/pub/databases/chebi/Flat_file_tab_delimited/database_accession.tsv", config = httr::config(connecttimeout = 60) ) chebi_accession <- suppressMessages(httr::content(chebi_accession_result, type = "text/tab-separated-values", progress = FALSE, show_col_types = FALSE )) chebi_compounds_clean <- chebi_compounds %>% dplyr::filter(.data$STAR == 3) %>% dplyr::select(-c( .data$SOURCE, .data$NAME, .data$STATUS, .data$MODIFIED_ON, .data$CREATED_BY )) %>% dplyr::na_if("null") %>% dplyr::mutate(PARENT_ID = as.numeric(.data$PARENT_ID)) chebi_accession_clean <- chebi_accession %>% dplyr::distinct(.data$COMPOUND_ID, .data$TYPE, .data$ACCESSION_NUMBER) %>% dplyr::rename(ID = .data$COMPOUND_ID) %>% dplyr::rename(TYPE_ACCESSION = .data$TYPE) chebi_chemical_data_clean <- chebi_chemical_data %>% dplyr::distinct(.data$COMPOUND_ID, .data$TYPE, .data$CHEMICAL_DATA) %>% dplyr::rename(ID = .data$COMPOUND_ID) %>% tidyr::pivot_wider( names_from = .data$TYPE, values_from = .data$CHEMICAL_DATA, values_fn = list ) %>% tidyr::unnest(cols = c( .data$FORMULA, .data$MASS, .data$CHARGE, .data$`MONOISOTOPIC MASS` )) chebi_compounds_names_clean <- chebi_compounds %>% dplyr::filter(.data$STAR == 3) %>% dplyr::distinct(.data$ID, .data$NAME) %>% dplyr::na_if("null") %>% dplyr::filter(!is.na(.data$NAME)) %>% dplyr::mutate(TYPE_NAME = "STANDARD") %>% dplyr::select(.data$ID, .data$TYPE_NAME, .data$NAME) chebi_names_clean <- chebi_names %>% dplyr::distinct(.data$COMPOUND_ID, .data$NAME, .data$TYPE) %>% dplyr::rename(ID = .data$COMPOUND_ID, TYPE_NAME = .data$TYPE) %>% dplyr::bind_rows(chebi_compounds_names_clean) chebi <- chebi_compounds_clean %>% dplyr::left_join(chebi_names_clean, by = "ID") %>% dplyr::left_join(chebi_accession_clean, by = "ID") %>% dplyr::left_join(chebi_chemical_data_clean, by = "ID") parent_ids <- chebi %>% dplyr::filter(!is.na(.data$PARENT_ID)) %>% dplyr::pull(var = .data$PARENT_ID) %>% unique() parent_info <- chebi %>% dplyr::filter(.data$ID %in% parent_ids) %>% dplyr::select(c( .data$ID, .data$NAME, .data$TYPE_NAME, .data$DEFINITION, .data$TYPE_ACCESSION, .data$ACCESSION_NUMBER, .data$FORMULA, .data$MASS, .data$CHARGE, .data$`MONOISOTOPIC MASS` )) parent_complete <- chebi %>% dplyr::filter(!is.na(.data$PARENT_ID)) %>% dplyr::select(-c( .data$NAME, .data$TYPE_NAME, .data$DEFINITION, .data$TYPE_ACCESSION, .data$ACCESSION_NUMBER, .data$FORMULA, .data$MASS, .data$CHARGE, .data$`MONOISOTOPIC MASS` )) %>% dplyr::left_join(parent_info, by = c("PARENT_ID" = "ID")) chebi <- chebi %>% dplyr::filter(is.na(.data$PARENT_ID)) %>% dplyr::bind_rows(parent_complete) %>% dplyr::arrange(.data$ID) %>% janitor::clean_names() chebi }
VectorDistribution <- R6Class("VectorDistribution", inherit = DistributionWrapper, lock_objects = FALSE, lock_class = FALSE, public = list( initialize = function(distlist = NULL, distribution = NULL, params = NULL, shared_params = NULL, name = NULL, short_name = NULL, decorators = NULL, vecdist = NULL, ids = NULL, ...) { if (!is.null(ids)) { ids <- as.character(assert_alphanum(ids)) } if (!is.null(decorators)) { suppressMessages(decorate(self, decorators)) } if (!is.null(vecdist)) { if (checkmate::testList(vecdist)) { dist <- as.character(unlist(vecdist[[1]]$modelTable$Distribution[[1]])) if (is.null(ids)) { ids <- paste0(get(dist)$public_fields$short_name, seq.int(sum(sapply(vecdist, function(.x) nrow(.x$modelTable))))) } else { checkmate::assertCharacter(ids, unique = TRUE) } private$.modelTable <- as.data.table(data.frame(Distribution = dist, shortname = ids)) private$.distlist <- FALSE private$.univariate <- vecdist[[1]]$.__enclos_env__$private$.univariate private$.pdf <- vecdist[[1]]$.__enclos_env__$private$.pdf private$.cdf <- vecdist[[1]]$.__enclos_env__$private$.cdf private$.quantile <- vecdist[[1]]$.__enclos_env__$private$.quantile private$.rand <- vecdist[[1]]$.__enclos_env__$private$.rand params <- unlist(lapply(vecdist, function(.x) { vals <- .x$parameters()$values pf <- unique(get_prefix(names(vals))) lapply(pf, function(i) { v <- vals[grepl(i, names(vals))] names(v) <- unprefix(names(v)) v }) }), FALSE) parameters <- do.call(get(paste0("getParameterSet.", dist)), c(params[[1]], shared_params)) parameters$rep(length(params), prefix = ids) names(params) <- ids params <- unlist(params, recursive = FALSE) names(params) <- gsub(".", "__", names(params), fixed = TRUE) parameters$values <- params super$initialize( distlist = if (vecdist[[1]]$distlist) unlist(lapply(vecdist, function(.x) .x$wrappedModels()), recursive = FALSE) else NULL, name = paste0("Vector: ", length(ids), " ", dist, "s"), short_name = paste0("Vec", length(ids), get(dist)$public_fields$short_name), description = paste0("Vector of ", length(ids), " ", dist, "s"), support = do.call(setproduct, lapply(vecdist, function(.x) .x$properties$support)), type = do.call(setproduct, lapply(vecdist, function(.x) .x$traits$type)), valueSupport = vecdist[[1]]$traits$valueSupport, variateForm = "multivariate", parameters = parameters ) invisible(self) } else { private$.modelTable <- vecdist$modelTable private$.distlist <- vecdist$distlist private$.univariate <- vecdist$.__enclos_env__$private$.univariate private$.pdf <- vecdist$.__enclos_env__$private$.pdf private$.cdf <- vecdist$.__enclos_env__$private$.cdf private$.quantile <- vecdist$.__enclos_env__$private$.quantile private$.rand <- vecdist$.__enclos_env__$private$.rand parameters <- vecdist$parameters() if (checkmate::testClass(vecdist, "MixtureDistribution")) { parameters$remove(prefix = "mix") } super$initialize( distlist = distlist, name = vecdist$name, short_name = vecdist$short_name, description = vecdist$description, support = vecdist$properties$support, type = vecdist$traits$type, valueSupport = vecdist$traits$valueSupport, variateForm = "multivariate", parameters = parameters ) if (is.null(name)) self$name <- gsub("Product|Mixture", "Vector", self$name) if (is.null(short_name)) self$short_name <- gsub("Prod|Mix", "Vec", self$short_name) self$description <- gsub("Product|Mixture", "Vector", self$description) invisible(self) } } else { if (is.null(distlist)) { if (is.null(distribution) | (is.null(params))) { stop("Either distlist or distribution and params must be provided.") } distribution <- match.arg(distribution, c(listDistributions(simplify = TRUE), listKernels(simplify = TRUE))) if (grepl("Empirical", distribution)) { stop("Empirical and EmpiricalMV not currently available for `distribution/params` constructor, use `distlist` instead.") } if (!checkmate::testList(params)) { params <- apply(params, 1, as.list) } if (distribution == "Geometric" & "trials" %in% names(unlist(params))) { stop("For Geometric distributions either `trials` must be passed to `shared_params` or `distlist` should be used.") } if (distribution == "NegativeBinomial" & "form" %in% names(unlist(params))) { stop("For NegativeBinomial distributions either `form` must be passed to `shared_params` or `distlist` should be used.") } if (is.null(shared_params)) { shared_params <- list() } else { if (!checkmate::testList(shared_params)) { shared_params <- as.list(shared_params) } } private$.sharedparams <- shared_params pdist <- get(distribution) if (is.null(ids)) { shortname <- pdist$public_fields$short_name shortnames <- NULL } else { shortname <- shortnames <- ids } if (!is.null(names(params)) && all(grepl("__", names(params)))) { pf <- unique(get_prefix(names(params))) shortnames <- pf } else { if (is.null(shortnames)) { shortnames <- sprintf("%s%d", shortname, seq(length(params))) } if (length(drop_null(params))) { names(params) <- shortnames params <- unlist(params, recursive = FALSE) names(params) <- gsub(".", "__", names(params), fixed = TRUE) } } lng <- length(shortnames) parameters <- tryCatch(get(paste0("getParameterSet.", distribution)), error = function(e) NULL) if (!is.null(parameters)) { parameters <- do.call(parameters, c(params[[1]], shared_params)) parameters$rep(lng, prefix = shortname) parameters$values <- params } private$.modelTable <- as.data.table( data.frame( Distribution = distribution, shortname = shortnames ) ) private$.univariate <- pdist$private_fields$.traits$variateForm == "univariate" if (!length(private$.univariate)) { private$.univariate <- pdist$get_inherit()$private_fields$.trait$variateForm == "univariate" } valueSupport <- pdist$private_fields$.traits$valueSupport if (!length(valueSupport)) { valueSupport <- pdist$get_inherit()$private_fields$.trait$valueSupport } pdist_pri <- pdist[["private_methods"]] if (!is.null(pdist_pri[[".pdf"]])) { private$.pdf <- function(x1, log) {} body(private$.pdf) <- substitute( { fun <- function(x, log) {} body(fun) <- substitute(FUN) dpqr <- data.table() if (private$.univariate) { if (ncol(x1) == 1) { dpqr <- fun(unlist(x1), log = log) } else if (nrow(x1) == 1) { dpqr <- fun(x1, log = log) if (nrow(dpqr) > 1) { dpqr <- diag(as.matrix(dpqr)) } } else { for (i in seq_len(ncol(x1))) { a_dpqr <- fun(unlist(x1[, i]), log = log) a_dpqr <- if (class(a_dpqr)[1] == "numeric") a_dpqr[i] else a_dpqr[, i] dpqr <- cbind(dpqr, a_dpqr) } } } else { if (length(dim(x1)) == 2) { dpqr <- data.table(matrix(fun(x1, log = log), nrow = nrow(x1))) } else { for (i in seq_len(dim(x1)[3])) { mx <- x1[, , i] if (class(mx)[1] == "numeric") { mx <- matrix(mx, nrow = 1) } a_dpqr <- fun(mx, log = log) a_dpqr <- if (class(a_dpqr)[1] == "numeric") a_dpqr[i] else a_dpqr[, i] dpqr <- cbind(dpqr, a_dpqr) } } } return(dpqr) }, list(FUN = body(pdist_pri[[".pdf"]])) ) } if (!is.null(pdist_pri[[".cdf"]])) { private$.cdf <- function(x1, lower.tail, log.p) {} body(private$.cdf) <- substitute( { fun <- function(x, lower.tail, log.p) {} body(fun) <- substitute(FUN) dpqr <- data.table() if (private$.univariate) { if (ncol(x1) == 1) { dpqr <- fun(unlist(x1), lower.tail = lower.tail, log.p = log.p) } else if (nrow(x1) == 1) { dpqr <- fun(x1, lower.tail = lower.tail, log.p = log.p) if (nrow(dpqr) > 1) { dpqr <- diag(as.matrix(dpqr)) } } else { for (i in seq(ncol(x1))) { a_dpqr <- fun(unlist(x1[, i]), lower.tail = lower.tail, log.p = log.p) a_dpqr <- if (class(a_dpqr)[1] == "numeric") a_dpqr[i] else a_dpqr[, i] dpqr <- cbind(dpqr, a_dpqr) } } } return(dpqr) }, list(FUN = body(pdist_pri[[".cdf"]])) ) } if (!is.null(pdist_pri[[".quantile"]])) { private$.quantile <- function(x1, lower.tail, log.p) {} body(private$.quantile) <- substitute( { fun <- function(p, lower.tail, log.p) {} body(fun) <- substitute(FUN) dpqr <- data.table() if (ncol(x1) == 1) { dpqr <- fun(unlist(x1), lower.tail = lower.tail, log.p = log.p) } else if (nrow(x1) == 1) { dpqr <- fun(x1, lower.tail = lower.tail, log.p = log.p) if (nrow(dpqr) > 1) { dpqr <- diag(as.matrix(dpqr)) } } else { for (i in seq_len(ncol(x1))) { a_dpqr <- fun(unlist(x1[, i]), lower.tail = lower.tail, log.p = log.p) a_dpqr <- if (class(a_dpqr)[1] == "numeric") a_dpqr[i] else a_dpqr[, i] dpqr <- cbind(dpqr, a_dpqr) } } return(dpqr) }, list(FUN = body(pdist_pri[[".quantile"]])) ) } if (!is.null(pdist_pri[[".rand"]])) { private$.rand <- function(x1) {} body(private$.rand) <- substitute( { fun <- function(n) {} body(fun) <- substitute(FUN) return(fun(x1)) }, list(FUN = body(pdist_pri[[".rand"]])) ) } } else { private$.distlist <- TRUE distribution <- c() if (is.null(ids)) { shortname <- character(0) } else { shortname <- checkmate::assertCharacter(ids, unique = TRUE) } vf <- distlist[[1]]$traits$variateForm paramlst <- vector("list", length(distlist)) vs <- distlist[[1]]$traits$valueSupport for (i in seq_along(distlist)) { stopifnot(distlist[[i]]$traits$variateForm == vf) if (is.null(ids)) { shortname <- c(shortname, distlist[[i]]$short_name) } distribution <- c(distribution, distlist[[i]]$name) if (!is.null(distlist[[i]]$parameters())) { paramlst[[i]] <- distlist[[i]]$parameters() } vs <- c(vs, distlist[[i]]$traits$valueSupport) } valueSupport <- if (length(unique(vs)) == 1) vs[[1]] else "mixture" if (is.null(ids)) { shortname <- makeUniqueNames(shortname) } parameters <- NULL names(distlist) <- shortname private$.univariate <- vf == "univariate" private$.modelTable <- as.data.table( data.frame(Distribution = distribution, shortname = shortname) ) private$.pdf <- function(x, log = FALSE) { dpqr <- data.table() if (private$.univariate) { for (i in seq_len(ncol(x))) { a_dpqr <- self[i]$pdf(x[, i], log = log) dpqr <- cbind(dpqr, a_dpqr) } } else { for (i in seq_len(dim(x)[[3]])) { a_dpqr <- self[i]$pdf(data = matrix(x[, , i], nrow = nrow(x), ncol = ncol(x)), log = log) dpqr <- cbind(dpqr, a_dpqr) } } return(dpqr) } private$.cdf <- function(x, lower.tail = TRUE, log.p = FALSE) { dpqr <- data.table() if (private$.univariate) { for (i in seq(ncol(x))) { a_dpqr <- self[i]$cdf(x[, i], lower.tail = lower.tail, log.p = log.p) dpqr <- cbind(dpqr, a_dpqr) } } else { for (i in seq(dim(x)[3])) { a_dpqr <- self[i]$cdf(data = matrix(x[, , i], nrow = nrow(x), ncol = ncol(x)), lower.tail = lower.tail, log.p = log.p) dpqr <- cbind(dpqr, a_dpqr) } } return(dpqr) } private$.quantile <- function(x, lower.tail = TRUE, log.p = FALSE) { dpqr <- data.table() for (i in seq(ncol(x))) { a_dpqr <- self[i]$quantile(x[, i], lower.tail = lower.tail, log.p = log.p) dpqr <- cbind(dpqr, a_dpqr) } return(dpqr) } private$.rand <- function(n) { if (private$.univariate) { if (n == 1) { return(matrix(sapply(self$wrappedModels(), function(x) x$rand(n)), nrow = 1)) } else { return(sapply(self$wrappedModels(), function(x) x$rand(n))) } } else { return(lapply(self$wrappedModels(), function(x) x$rand(n))) } } } ndist <- nrow(private$.modelTable) dst <- unique(self$modelTable$Distribution) if (length(dst) == 1 & dst[[1]] %in% c(listDistributions(simplify = TRUE), listKernels(simplify = TRUE))) { distribution <- get(as.character(unlist(self$modelTable[1, 1]))) if (is.null(name)) { name <- paste0( "Vector: ", ndist, " ", distribution$public_fields$name, "s" ) } if (is.null(short_name)) { short_name <- paste0( "Vec", ndist, distribution$public_fields$short_name ) } description <- paste0("Vector of ", ndist, " ", distribution$public_fields$name, "s") type <- distribution$new()$traits$type^ndist support <- type } else { type <- do.call(setproduct, lapply(distlist, function(x) x$traits$type)) support <- type if (ndist > 3) { if (is.null(name)) name <- paste("Vector:", ndist, "Distributions") if (is.null(short_name)) short_name <- paste0("Vec", ndist, "Dists") description <- paste0("Vector of ", ndist, " distributions.") } else { if (is.null(name)) name <- paste("Vector:", paste0(distribution, collapse = ", ")) if (is.null(short_name)) short_name <- paste0(shortname, collapse = "Vec") description <- paste0("Vector of: ", paste0(shortname, collapse = ", ")) } } super$initialize( distlist = distlist, name = name, short_name = short_name, description = description, support = support, type = type, valueSupport = valueSupport, variateForm = "multivariate", parameters = parameters, ... ) } }, getParameterValue = function(id, ...) { vals <- private$.parameters$get_values(id) if (!is.null(names(vals))) { names(vals) <- get_n_prefix(names(vals)) } vals }, wrappedModels = function(model = NULL) { if (is.null(model)) { if (private$.distlist) { distlist <- private$.wrappedModels } else { distlist <- lapply(private$.modelTable$shortname, function(x) { pars <- self$parameters()[prefix = x]$values dist <- do.call(get(as.character(unlist(private$.modelTable$Distribution[[1]])))$new, c(pars, list(decorators = self$decorators))) return(dist) }) } } else { models <- subset(private$.modelTable, shortname == model)$shortname if (length(models) == 0) { stop(sprintf("No distribution called %s.", model)) } if (private$.distlist) { distlist <- private$.wrappedModels[models] } else { distlist <- lapply(models, function(x) { dist <- do.call(get(as.character(unlist(private$.modelTable$Distribution[[1]])))$new, list(decorators = self$decorators)) dist$setParameterValue(lst = self$parameters()[prefix = x]$values) return(dist) }) } } if (length(distlist) == 1) { return(distlist[[1]]) } else { names(distlist) <- as.character(unlist(private$.modelTable$shortname)) return(distlist) } }, strprint = function(n = 10) { names <- as.character(unlist(self$modelTable$shortname)) lng <- length(names) if (lng > (2 * n)) { names <- c(names[1:n], "...", names[(lng - n + 1):lng]) } return(names) }, mean = function(...) { if (self$distlist) { ret <- sapply(seq(nrow(private$.modelTable)), function(i) { ifnerror(self[i]$mean(...), error = NaN) }) } else { f <- get(as.character(unlist(self$modelTable$Distribution[[1]])))$public_methods$mean if (is.null(f)) { f <- get(as.character(unlist(self$modelTable$Distribution[[1]])))$get_inherit()$ public_methods$mean } if (is.null(f)) { stop("Not implemented for this distribution.") } formals(f) <- c(list(self = self), alist(... = )) ret <- f() if (length(ret) == 1) { ret <- rep(ret, nrow(self$modelTable)) } } if (is.null(dim(ret))) { names(ret) <- as.character(unlist(private$.modelTable[, "shortname"])) } else { ret <- data.table(t(ret)) colnames(ret) <- as.character(unlist(private$.modelTable[, "shortname"])) } return(ret) }, mode = function(which = "all") { if (self$distlist) { ret <- sapply(seq(nrow(private$.modelTable)), function(i) { ifnerror(self[i]$mode(which), error = NaN) }) } else { f <- get(as.character(unlist(self$modelTable$Distribution[[1]])))$public_methods$mode if (is.null(f)) { f <- get(as.character(unlist(self$modelTable$Distribution[[1]])))$get_inherit()$ public_methods$mode } if (is.null(f)) { stop("Not implemented for this distribution.") } formals(f) <- list(self = self, which = which) ret <- f() if (length(ret) == 1) { ret <- rep(ret, nrow(self$modelTable)) } } if (is.null(dim(ret))) { names(ret) <- as.character(unlist(private$.modelTable[, "shortname"])) } else { if (as.character(unlist(self$modelTable$Distribution[[1]])) != "MultivariateNormal") { ret <- t(ret) } ret <- data.table(ret) colnames(ret) <- as.character(unlist(private$.modelTable[, "shortname"])) } return(ret) }, median = function() { self$quantile(0.5) }, variance = function(...) { if (self$distlist) { ret <- sapply(seq(nrow(private$.modelTable)), function(i) { ifnerror(self[i]$variance(...), error = NaN) }) } else { f <- get(as.character(unlist(self$modelTable$Distribution[[1]])))$public_methods$variance if (is.null(f)) { f <- get(as.character(unlist(self$modelTable$Distribution[[1]])))$get_inherit()$ public_methods$variance } if (is.null(f)) { stop("Not implemented for this distribution.") } formals(f) <- c(list(self = self), alist(... = )) ret <- f() if (length(ret) == 1) { ret <- rep(ret, nrow(self$modelTable)) } } if (is.null(dim(ret))) { names(ret) <- as.character(unlist(private$.modelTable[, "shortname"])) } else { dimnames(ret)[3] <- as.list(private$.modelTable[, "shortname"]) } return(ret) }, skewness = function(...) { if (self$distlist) { ret <- sapply(seq(nrow(private$.modelTable)), function(i) { ifnerror(self[i]$skewness(...), error = NaN) }) } else { f <- get(as.character(unlist(self$modelTable$Distribution[[1]])))$public_methods$skewness if (is.null(f)) { f <- get(as.character(unlist(self$modelTable$Distribution[[1]])))$get_inherit()$ public_methods$skewness } if (is.null(f)) { stop("Not implemented for this distribution.") } formals(f) <- c(list(self = self), alist(... = )) ret <- f() if (length(ret) == 1) { ret <- rep(ret, nrow(self$modelTable)) } } names(ret) <- as.character(unlist(private$.modelTable[, "shortname"])) return(ret) }, kurtosis = function(excess = TRUE, ...) { if (self$distlist) { ret <- sapply(seq(nrow(private$.modelTable)), function(i) { ifnerror(self[i]$kurtosis(excess, ...), error = NaN) }) } else { f <- get(as.character(unlist(self$modelTable$Distribution[[1]])))$public_methods$kurtosis if (is.null(f)) { f <- get(as.character(unlist(self$modelTable$Distribution[[1]])))$get_inherit()$ public_methods$kurtosis } if (is.null(f)) { stop("Not implemented for this distribution.") } formals(f) <- c(list(self = self, excess = excess), alist(... = )) ret <- f() if (length(ret) == 1) { ret <- rep(ret, nrow(self$modelTable)) } } names(ret) <- as.character(unlist(private$.modelTable[, "shortname"])) return(ret) }, entropy = function(base = 2, ...) { if (self$distlist) { ret <- sapply(seq(nrow(private$.modelTable)), function(i) { ifnerror(self[i]$entropy(base, ...), error = NaN) }) } else { f <- get(as.character(unlist(self$modelTable$Distribution[[1]])))$public_methods$entropy if (is.null(f)) { f <- get(as.character(unlist(self$modelTable$Distribution[[1]])))$get_inherit()$ public_methods$entropy } formals(f) <- c(list(self = self, base = base), alist(... = )) ret <- f() if (length(ret) == 1) { ret <- rep(ret, nrow(self$modelTable)) } } names(ret) <- as.character(unlist(private$.modelTable[, "shortname"])) return(ret) }, mgf = function(t, ...) { if (!self$distlist) { warning("mgf not currently efficiently vectorised, may be slow.") } ret <- sapply(seq(nrow(private$.modelTable)), function(i) { ifnerror(self[i]$mgf(t, ...), error = NaN) }) if (is.null(dim(ret))) { names(ret) <- as.character(unlist(private$.modelTable[, "shortname"])) } else { ret <- data.table(ret) colnames(ret) <- as.character(unlist(private$.modelTable[, "shortname"])) } return(ret) }, cf = function(t, ...) { if (!self$distlist) { warning("cf not currently efficiently vectorised, may be slow.") } ret <- sapply(seq(nrow(private$.modelTable)), function(i) { ifnerror(self[i]$cf(t, ...), error = NaN) }) if (is.null(dim(ret))) { names(ret) <- as.character(unlist(private$.modelTable[, "shortname"])) } else { ret <- data.table(ret) colnames(ret) <- as.character(unlist(private$.modelTable[, "shortname"])) } return(ret) }, pgf = function(z, ...) { if (!self$distlist) { warning("pgf not currently efficiently vectorised, may be slow.") } ret <- sapply(seq(nrow(private$.modelTable)), function(i) { ifnerror(self[i]$pgf(z, ...), error = NaN) }) if (is.null(dim(ret))) { names(ret) <- as.character(unlist(private$.modelTable[, "shortname"])) } else { ret <- data.table(ret) colnames(ret) <- as.character(unlist(private$.modelTable[, "shortname"])) } return(ret) }, pdf = function(..., log = FALSE, simplify = TRUE, data = NULL) { if (is.null(data)) { data <- as.matrix(data.table(...)) } else if (length(dim(data)) == 2) { data <- as.matrix(data) } if (ncol(data) != nrow(self$modelTable) & ncol(data) > 1 & private$.univariate) { stopf("Expected data with %s or 1 columns, received %s.", nrow(self$modelTable), ncol(data)) } if (private$.univariate) { if (private$.distlist & ncol(data) == 1) { data <- matrix(rep(data, nrow(private$.modelTable)), nrow = nrow(data), ncol = nrow(private$.modelTable)) } dpqr <- private$.pdf(data, log = log) if (class(dpqr)[1] == "numeric") { dpqr <- matrix(dpqr, ncol = nrow(private$.modelTable)) } dpqr <- as.data.table(dpqr) colnames(dpqr) <- as.character(unlist(private$.modelTable[, 2])) return(dpqr) } else { if (ncol(data) == 1) { stop("Distribution is multivariate but values have only been passed to one argument.") } if ((inherits(data, "array") | inherits(data, "matrix")) & private$.distlist) { if (is.na(dim(data)[3])) { data <- array(rep(data, nrow(private$.modelTable)), dim = c(nrow(data), ncol(data), nrow(private$.modelTable)) ) } } dpqr <- private$.pdf(data, log = log) colnames(dpqr) <- as.character(unlist(private$.modelTable[, 2])) return(dpqr) } }, cdf = function(..., lower.tail = TRUE, log.p = FALSE, simplify = TRUE, data = NULL) { if (is.null(data)) { data <- as.matrix(data.table(...)) } if (ncol(data) != nrow(self$modelTable) & ncol(data) > 1 & private$.univariate) { stopf("Expected data with %s or 1 columns, received %s.", nrow(self$modelTable), ncol(data)) } if (private$.univariate) { if (ncol(data) == 1 & private$.distlist) { data <- matrix(rep(data, nrow(private$.modelTable)), nrow = nrow(data)) } } else { if (ncol(data) == 1) { stop("Distribution is multivariate but values have only been passed to one argument.") } else if (inherits(data, "array") | inherits(data, "matrix")) { if (is.na(dim(data)[3]) & private$.distlist) { data <- array(rep(data, nrow(private$.modelTable)), dim = c(nrow(data), ncol(data), nrow(private$.modelTable)) ) } } } dpqr <- private$.cdf(data, lower.tail = lower.tail, log.p = log.p) if (class(dpqr)[1] == "numeric") { dpqr <- matrix(dpqr, ncol = nrow(private$.modelTable)) } dpqr <- as.data.table(dpqr) colnames(dpqr) <- as.character(unlist(private$.modelTable[, 2])) return(dpqr) }, quantile = function(..., lower.tail = TRUE, log.p = FALSE, simplify = TRUE, data = NULL) { if (is.null(data)) { data <- as.matrix(data.table(...)) } if (ncol(data) != nrow(self$modelTable) & ncol(data) > 1 & private$.univariate) { stopf("Expected data with %s or 1 columns, received %s.", nrow(self$modelTable), ncol(data)) } if (private$.univariate) { if (ncol(data) == 1 & private$.distlist) { data <- matrix(rep(data, nrow(private$.modelTable)), nrow = nrow(data)) } } else { stop("Quantile not possible for non-univariate distributions.") } dpqr <- private$.quantile(data, lower.tail = lower.tail, log.p = log.p) if (class(dpqr)[1] == "numeric") { dpqr <- matrix(dpqr, ncol = nrow(private$.modelTable)) } dpqr <- as.data.table(dpqr) colnames(dpqr) <- as.character(unlist(private$.modelTable[, 2])) return(dpqr) }, rand = function(n, simplify = TRUE) { if (length(n) > 1) { n <- length(n) } data <- n if (private$.univariate) { dpqr <- as.data.table(private$.rand(data)) colnames(dpqr) <- as.character(unlist(private$.modelTable[, 2])) return(dpqr) } else { dpqr <- private$.rand(data) dpqr <- array(unlist(dpqr), c(nrow(dpqr[[1]]), ncol(dpqr[[1]]), length(dpqr))) dimnames(dpqr) <- list(NULL, paste0("V", seq(ncol(dpqr))), as.character(unlist(private$.modelTable$shortname))) return(dpqr) } } ), active = list( modelTable = function() { private$.modelTable }, distlist = function() { return(private$.distlist) }, ids = function() { as.character(unlist(private$.modelTable$shortname)) } ), private = list( .univariate = logical(0), .distlist = FALSE, .sharedparams = list(), .properties = list(), .traits = list(type = NA, valueSupport = "mixture", variateForm = "multivariate"), .trials = logical(0) ) ) .distr6$wrappers <- append(.distr6$wrappers, list(VectorDistribution = VectorDistribution)) "[.VectorDistribution" <- function(vecdist, i) { if (checkmate::testCharacter(i)) { checkmate::assertSubset(i, as.character(unlist(vecdist$modelTable$shortname))) i <- match(i, as.character(unlist(vecdist$modelTable$shortname)), 0) } i <- i[i %in% (seq_len(nrow(vecdist$modelTable)))] if (length(i) == 0) { stop("Index i too large, should be less than or equal to ", nrow(vecdist$modelTable)) } decorators <- vecdist$decorators if (!vecdist$distlist) { distribution <- as.character(unlist(vecdist$modelTable[1, 1])) if (length(i) == 1) { id <- as.character(unlist(vecdist$modelTable[i, 2])) dist <- get(distribution)$new(decorators = decorators) pri <- get_private(dist) pri$.parameters <- vecdist$parameters()[prefix = id] return(dist) } else { id <- as.character(unlist(vecdist$modelTable[i, 2])) pars <- vecdist$parameters()$values pars <- pars[grepl(paste0(id, collapse = "|"), names(pars))] return(VectorDistribution$new( distribution = distribution, params = pars, decorators = decorators, shared_params = vecdist$.__enclos_env__$private$.sharedparams, ids = vecdist$modelTable$shortname[i] )) } } else { if (length(i) == 1) { dist <- vecdist$wrappedModels()[[i]] if (!is.null(decorators)) { suppressMessages(decorate(dist, decorators)) } return(dist) } else { return(VectorDistribution$new( distlist = vecdist$wrappedModels()[i], decorators = decorators, ids = vecdist$modelTable$shortname[i] )) } } } as.VectorDistribution <- function(object) { if (checkmate::testClass(object, "VectorDistribution")) { return(VectorDistribution$new(vecdist = object)) } else { stop("Object must inherit from VectorDistribution.") } } length.VectorDistribution <- function(x) { nrow(x$modelTable) }
context("inspect_imb pair of dataframes") data("starwars", package = "dplyr") data("band_instruments", package = "dplyr") data("storms", package = "dplyr") data(mtcars, airquality) test_that("Output with two identical df inputs data frame", { expect_is(inspect_imb(mtcars, mtcars), "data.frame") expect_is(inspect_imb(band_instruments, band_instruments), "data.frame") expect_is(inspect_imb(starwars, starwars), "data.frame") expect_is(inspect_imb(storms, storms), "data.frame") expect_is(inspect_imb(airquality, airquality), "data.frame") }) test_that("Output with two different inputs data frame", { set.seed(10) expect_is(inspect_imb(mtcars, mtcars %>% dplyr::sample_n(100, replace = T)), "data.frame") expect_is(inspect_imb(band_instruments, band_instruments %>% dplyr::sample_n(100, replace = T)) , "data.frame") expect_is(inspect_imb(starwars, starwars %>% dplyr::sample_n(100, replace = T)), "data.frame") expect_is(inspect_imb(storms, storms %>% dplyr::sample_n(100, replace = T)), "data.frame") expect_is(inspect_imb(airquality, airquality%>% dplyr::sample_n(100, replace = T)), "data.frame") })
topic_name <- "test_topic" sub_name <- "test_subscription" snap_name <- "test_snapshot" schema_name <- "test_schema" schema_def <- list( type = "record", name = "myRecord", fields = list( list( name = "cost", type = "int", default = 200 ), list( name = "object", type = "string", default = "blender" ) ) ) msg <- list(cost = 12, object = "fork") %>% jsonlite::toJSON(auto_unbox = TRUE) %>% charToRaw() %>% base64enc::base64encode() %>% PubsubMessage() labels = list(a = "1", b = "2") retention_duration= 1800 skip_if_no_token <- function() { skip_on_cran() skip_on_travis() } if(file.exists("../../.gcp_creds.json")) { pubsub_auth(json_file = "../../.gcp_creds.json") } else { message("No authentication file found for testing") }
if (requiet("testthat") && requiet("insight") && requiet("lfe")) { x <- rnorm(1000) x2 <- rnorm(length(x)) id <- factor(sample(20, length(x), replace = TRUE)) firm <- factor(sample(13, length(x), replace = TRUE)) id.eff <- rnorm(nlevels(id)) firm.eff <- rnorm(nlevels(firm)) u <- rnorm(length(x)) y <- x + 0.5 * x2 + id.eff[id] + firm.eff[firm] + u x3 <- rnorm(length(x)) x4 <- sample(12, length(x), replace = TRUE) Q <- 0.3 * x3 + x + 0.2 * x2 + id.eff[id] + 0.3 * log(x4) - 0.3 * y + rnorm(length(x), sd = 0.3) W <- 0.7 * x3 - 2 * x + 0.1 * x2 - 0.7 * id.eff[id] + 0.8 * cos(x4) - 0.2 * y + rnorm(length(x), sd = 0.6) y <- y + Q + W dat <- data.frame(y, x, x2, x3, x4, id, firm, Q, W) m1 <- felm(y ~ x + x2 | id + firm | (Q | W ~ x3 + factor(x4)), data = dat) test_that("model_info", { expect_true(model_info(m1)$is_linear) }) test_that("find_predictors", { expect_identical( find_predictors(m1), list( conditional = c("x", "x2"), instruments = c("Q", "W", "x3", "x4") ) ) expect_identical(find_predictors(m1, effects = "random"), list(random = c("id", "firm"))) expect_identical( find_predictors(m1, effects = "all", flatten = TRUE), c("x", "x2", "id", "firm", "Q", "W", "x3", "x4") ) }) test_that("find_random", { expect_identical(find_random(m1), list(random = c("id", "firm"))) }) test_that("get_random", { expect_identical(colnames(get_random(m1)), c("id", "firm")) }) test_that("find_response", { expect_identical(find_response(m1), "y") }) test_that("get_response", { expect_equal(get_response(m1), dat$y) }) test_that("get_predictors", { expect_equal( colnames(get_predictors(m1)), c("x", "x2", "Q", "W", "x3", "x4") ) }) test_that("link_inverse", { expect_equal(link_inverse(m1)(.2), .2, tolerance = 1e-5) }) test_that("get_data", { expect_equal(nrow(get_data(m1)), 1000) expect_equal( colnames(get_data(m1)), c("y", "x", "x2", "id", "firm", "Q", "W", "x3", "x4") ) }) test_that("find_formula", { expect_length(find_formula(m1), 3) expect_equal( find_formula(m1), list( conditional = as.formula("y ~ x + x2"), random = as.formula("~id + firm"), instruments = as.formula("~(Q | W ~ x3 + factor(x4))") ), ignore_attr = TRUE ) }) test_that("find_terms", { expect_equal( find_terms(m1), list( response = "y", conditional = c("x", "x2"), random = c("id", "firm"), instruments = c("(Q", "W x3", "factor(x4))") ) ) expect_equal( find_terms(m1, flatten = TRUE), c("y", "x", "x2", "id", "firm", "(Q", "W x3", "factor(x4))") ) }) test_that("find_variables", { expect_equal( find_variables(m1), list( response = "y", conditional = c("x", "x2"), random = c("id", "firm"), instruments = c("Q", "W", "x3", "x4") ) ) expect_equal( find_variables(m1, flatten = TRUE), c("y", "x", "x2", "id", "firm", "Q", "W", "x3", "x4") ) }) test_that("n_obs", { expect_equal(n_obs(m1), 1000) }) test_that("linkfun", { expect_false(is.null(link_function(m1))) }) test_that("find_parameters", { expect_equal( find_parameters(m1), list(conditional = c("x", "x2", "Q(fit)", "W(fit)")) ) expect_equal(nrow(get_parameters(m1)), 4) expect_equal( get_parameters(m1)$Parameter, c("x", "x2", "Q(fit)", "W(fit)") ) }) test_that("is_multivariate", { expect_false(is_multivariate(m1)) }) test_that("find_statistic", { expect_identical(find_statistic(m1), "t-statistic") }) }
source("helper/helper.R") wb = function(...) backports:::...length() if (exists("...length", envir = baseenv())) { f = get("...length", envir = baseenv()) wf = function(...) f() expect_same = makeCompareFun(wf, wb) expect_same(1) expect_same(1, 2) expect_same() } expect_identical(wb(1, "a", "b", "c"), 4L) expect_identical(wb(2, "a", "b"), 3L) expect_identical(wb(1), 1L) expect_identical(wb(), 0L) f = function(n) backports:::...length() expect_error(f(), "current call") expect_error(f(1), "current call")
context("methods") expect_ellipsis <- function(name, method) { sym <- as.name(name) eval(bquote({ .(sym) <- method expect_true("..." %in% names(formals(.(sym)))) })) } test_that("all methods have ellipsis", { symbols <- ls(env = asNamespace("DBI")) objects <- mget(symbols, env = asNamespace("DBI"), mode = "function", ifnotfound = rep(list(NULL), length(symbols))) is_method <- vapply(objects, inherits, "standardGeneric", FUN.VALUE = logical(1L)) methods <- objects[is_method] Map(expect_ellipsis, names(methods), methods) })
lav_model_nvcov_bootstrap <- function(lavmodel = NULL, lavsamplestats = NULL, lavoptions = NULL, lavimplied = NULL, lavh1 = NULL, lavdata = NULL, lavcache = NULL, lavpartable = NULL) { if(!is.null(lavoptions$bootstrap)) { R <- lavoptions$bootstrap } else { R <- 1000L } boot.type <- "ordinary" if("bollen.stine" %in% lavoptions$test) { boot.type <- "bollen.stine" } TEST <- NULL COEF <- lav_bootstrap_internal(object = NULL, lavmodel. = lavmodel, lavsamplestats. = lavsamplestats, lavpartable. = lavpartable, lavoptions. = lavoptions, lavdata. = lavdata, R = R, verbose = lavoptions$verbose, type = boot.type, FUN = ifelse(boot.type == "bollen.stine", "coeftest", "coef"), warn = -1L) if(boot.type == "bollen.stine") { nc <- ncol(COEF) TEST <- COEF[,nc] COEF <- COEF[,-nc] } nboot <- nrow(COEF) NVarCov <- lavsamplestats@ntotal * (cov(COEF) * (nboot-1)/nboot ) attr(NVarCov, "BOOT.COEF") <- COEF attr(NVarCov, "BOOT.TEST") <- TEST NVarCov } lav_model_nvcov_robust_sem <- function(lavmodel = NULL, lavsamplestats = NULL, lavdata = NULL, lavcache = NULL, lavimplied = NULL, lavh1 = NULL, lavoptions = NULL, use.ginv = FALSE) { if(lavmodel@estimator == "ML" && lavoptions$mimic == "Mplus") { E.inv <- lav_model_information_expected_MLM(lavmodel = lavmodel, lavsamplestats = lavsamplestats, extra = TRUE, augmented = TRUE, inverted = TRUE, use.ginv = use.ginv) } else { E.inv <- lav_model_information(lavmodel = lavmodel, lavsamplestats = lavsamplestats, lavdata = lavdata, lavimplied = lavimplied, lavh1 = lavh1, lavoptions = lavoptions, extra = TRUE, augmented = TRUE, inverted = TRUE, use.ginv = use.ginv) } if(inherits(E.inv, "try-error")) { return(E.inv) } Delta <- attr(E.inv, "Delta") WLS.V <- attr(E.inv, "WLS.V") Gamma <- lavsamplestats@NACOV if(lavmodel@estimator == "ML" && lavoptions$mimic == "Mplus" && [email protected]) { for(g in 1:lavsamplestats@ngroups) { gg1 <- (lavsamplestats@nobs[[g]]-1)/lavsamplestats@nobs[[g]] if([email protected]) { nvar <- NCOL([email protected][[g]]) } else { nvar <- NCOL(lavsamplestats@cov[[g]]) } G11 <- Gamma[[g]][1:nvar, 1:nvar, drop = FALSE] Gamma[[g]][1:nvar, 1:nvar] <- G11 * gg1 } } tDVGVD <- matrix(0, ncol=ncol(E.inv), nrow=nrow(E.inv)) for(g in 1:lavsamplestats@ngroups) { fg <- lavsamplestats@nobs[[g]] /lavsamplestats@ntotal if(lavoptions$mimic == "Mplus") { fg1 <- (lavsamplestats@nobs[[g]]-1)/lavsamplestats@ntotal } else { fg1 <- fg } if(lavmodel@estimator == "DWLS" || lavmodel@estimator == "ULS") { WD <- WLS.V[[g]] * Delta[[g]] } else { WD <- WLS.V[[g]] %*% Delta[[g]] } tDVGVD <- tDVGVD + fg*fg/fg1 * crossprod(WD, Gamma[[g]] %*% WD) } NVarCov <- (E.inv %*% tDVGVD %*% E.inv) attr(NVarCov, "Delta") <- Delta if( (lavoptions$information[1] == lavoptions$information[2]) && (lavoptions$h1.information[1] == lavoptions$h1.information[2]) && (lavoptions$observed.information[1] == lavoptions$observed.information[2]) ) { attr(NVarCov, "E.inv") <- E.inv attr(NVarCov, "WLS.V") <- WLS.V } NVarCov } lav_model_nvcov_robust_sandwich <- function(lavmodel = NULL, lavsamplestats = NULL, lavdata = NULL, lavoptions = NULL, lavimplied = NULL, lavh1 = NULL, lavcache = NULL, use.ginv = FALSE) { E.inv <- lav_model_information(lavmodel = lavmodel, lavsamplestats = lavsamplestats, lavdata = lavdata, lavcache = lavcache, lavimplied = lavimplied, lavh1 = lavh1, lavoptions = lavoptions, extra = FALSE, augmented = TRUE, inverted = TRUE, use.ginv = use.ginv) if(inherits(E.inv, "try-error")) { return(E.inv) } lavoptions2 <- lavoptions if(!is.null(lavoptions$h1.information.meat)) { lavoptions2$information <- lavoptions$information.meat } if(!is.null(lavoptions$h1.information.meat)) { lavoptions2$h1.information <- lavoptions$h1.information.meat } B0 <- lav_model_information_firstorder(lavmodel = lavmodel, lavsamplestats = lavsamplestats, lavdata = lavdata, lavcache = lavcache, lavimplied = lavimplied, lavh1 = lavh1, lavoptions = lavoptions2, extra = TRUE, check.pd = FALSE, augmented = FALSE, inverted = FALSE, use.ginv = use.ginv) NVarCov <- E.inv %*% B0 %*% E.inv attr(NVarCov, "B0.group") <- attr(B0, "B0.group") if( (lavoptions$information[1] == lavoptions$information[2]) && (lavoptions$h1.information[1] == lavoptions$h1.information[2]) && (lavoptions$observed.information[1] == lavoptions$observed.information[2]) ) { attr(NVarCov, "E.inv") <- E.inv } NVarCov } lav_model_nvcov_two_stage <- function(lavmodel = NULL, lavsamplestats = NULL, lavoptions = NULL, lavimplied = NULL, lavh1 = NULL, lavdata = NULL, use.ginv = FALSE) { if(is.null(lavoptions) && is.null(lavoptions$information[1])) { lavoptions <- list(information = "observed", observed.information = "h1", h1.information = "structured") } if(lavoptions$information[1] == "observed" && lavoptions$observed.information[1] != "h1") { stop("lavaan ERROR: two.stage + observed information currently only works with observed.information = ", dQuote("h1")) } if(!is.null(lavdata@weights[[1]])) { stop("lavaan ERROR: two.stage + sampling.weights is not supported yet") } if(!is.null([email protected]) && length([email protected][[1]]) > 0L) { stop("lavaan ERROR: two.stage + fixed.x = TRUE is not supported yet") } E.inv <- lav_model_information(lavmodel = lavmodel, lavsamplestats = lavsamplestats, lavdata = lavdata, lavoptions = lavoptions, lavimplied = lavimplied, lavh1 = lavh1, extra = TRUE, augmented = TRUE, inverted = TRUE, use.ginv = use.ginv) Delta <- attr(E.inv, "Delta") WLS.V <- attr(E.inv, "WLS.V") attr(E.inv, "Delta") <- NULL attr(E.inv, "WLS.V") <- NULL if(inherits(E.inv, "try-error")) { return(E.inv) } if(is.null(WLS.V)) { stop("lavaan ERROR: WLS.V/H/A1 is NULL, observed.information = hessian?") } Gamma <- vector("list", length = lavsamplestats@ngroups) tDVGVD <- matrix(0, ncol=ncol(E.inv), nrow=nrow(E.inv)) for(g in 1:lavsamplestats@ngroups) { fg <- lavsamplestats@nobs[[g]] /lavsamplestats@ntotal fg1 <- fg WD <- WLS.V[[g]] %*% Delta[[g]] if(lavoptions$h1.information[1] == "unstructured") { MU <- [email protected][[g]]$mu SIGMA <- [email protected][[g]]$sigma } else { MU <- lavimplied$mean[[g]] SIGMA <- lavimplied$cov[[g]] } if(lavoptions$se == "two.stage") { if(lavoptions$information[1] == "expected") { Info <- lav_mvnorm_missing_information_expected( Y = lavdata@X[[g]], Mp = lavdata@Mp[[g]], wt = lavdata@weights[[g]], Mu = MU, Sigma = SIGMA, x.idx = [email protected][[g]]) } else { Info <- lav_mvnorm_missing_information_observed_samplestats( Yp = lavsamplestats@missing[[g]], Mu = MU, Sigma = SIGMA, x.idx = [email protected][[g]]) } Gamma[[g]] <- lav_matrix_symmetric_inverse(Info) } else { if(length(lavdata@cluster) > 0L) { cluster.idx <- lavdata@Lp[[g]]$cluster.idx[[2]] } else { cluster.idx <- NULL } Gamma[[g]] <- lav_mvnorm_missing_h1_omega_sw(Y = lavdata@X[[g]], Mp = lavdata@Mp[[g]], Yp = lavsamplestats@missing[[g]], wt = lavdata@weights[[g]], cluster.idx = cluster.idx, Mu = MU, Sigma = SIGMA, x.idx = [email protected][[g]], information = lavoptions$information[1]) } tDVGVD <- tDVGVD + fg*fg/fg1 * crossprod(WD, Gamma[[g]] %*% WD) } NVarCov <- (E.inv %*% tDVGVD %*% E.inv) attr(NVarCov, "Delta") <- Delta attr(NVarCov, "Gamma") <- Gamma if( (lavoptions$information[1] == lavoptions$information[2]) && (lavoptions$h1.information[1] == lavoptions$h1.information[2]) && (lavoptions$observed.information[1] == lavoptions$observed.information[2]) ) { attr(NVarCov, "E.inv") <- E.inv attr(NVarCov, "WLS.V") <- WLS.V } NVarCov } lav_model_vcov <- function(lavmodel = NULL, lavsamplestats = NULL, lavoptions = NULL, lavdata = NULL, lavpartable = NULL, lavcache = NULL, lavimplied = NULL, lavh1 = NULL, use.ginv = FALSE) { likelihood <- lavoptions$likelihood information <- lavoptions$information[1] se <- lavoptions$se verbose <- lavoptions$verbose mimic <- lavoptions$mimic if(se == "none" || se == "external" || se == "twostep") { return( matrix(0, 0, 0) ) } if(se == "standard") { NVarCov <- lav_model_information(lavmodel = lavmodel, lavsamplestats = lavsamplestats, lavdata = lavdata, lavcache = lavcache, lavimplied = lavimplied, lavh1 = lavh1, lavoptions = lavoptions, extra = FALSE, augmented = TRUE, inverted = TRUE, use.ginv = use.ginv) } else if(se == "first.order") { NVarCov <- lav_model_information_firstorder(lavmodel = lavmodel, lavsamplestats = lavsamplestats, lavdata = lavdata, lavcache = lavcache, lavimplied = lavimplied, lavh1 = lavh1, lavoptions = lavoptions, extra = TRUE, check.pd = FALSE, augmented = TRUE, inverted = TRUE, use.ginv = use.ginv) } else if(se == "robust.sem" || se == "robust.cluster.sem") { NVarCov <- lav_model_nvcov_robust_sem(lavmodel = lavmodel, lavsamplestats = lavsamplestats, lavcache = lavcache, lavdata = lavdata, lavimplied = lavimplied, lavh1 = lavh1, lavoptions = lavoptions, use.ginv = use.ginv) } else if(se == "robust.huber.white" || se == "robust.cluster") { NVarCov <- lav_model_nvcov_robust_sandwich(lavmodel = lavmodel, lavsamplestats = lavsamplestats, lavdata = lavdata, lavcache = lavcache, lavimplied = lavimplied, lavh1 = lavh1, lavoptions = lavoptions, use.ginv = use.ginv) } else if(se %in% c("two.stage", "robust.two.stage")) { NVarCov <- lav_model_nvcov_two_stage(lavmodel = lavmodel, lavsamplestats = lavsamplestats, lavoptions = lavoptions, lavdata = lavdata, lavimplied = lavimplied, lavh1 = lavh1, use.ginv = use.ginv) } else if(se == "bootstrap") { NVarCov <- try( lav_model_nvcov_bootstrap(lavmodel = lavmodel, lavsamplestats = lavsamplestats, lavoptions = lavoptions, lavdata = lavdata, lavimplied = lavimplied, lavh1 = lavh1, lavcache = lavcache, lavpartable = lavpartable), silent=TRUE ) } else { warning("lavaan WARNING: unknown se type: ", se) } if(! inherits(NVarCov, "try-error") ) { if(lavmodel@estimator %in% c("ML","PML","FML") && likelihood == "normal") { if(lavdata@nlevels == 1L) { N <- lavsamplestats@ntotal if(lavoptions$mimic == "lm" && .hasSlot(lavmodel, "modprop") && all(lavmodel@modprop$uvreg)) { N <- sum( unlist(lavsamplestats@nobs) - (unlist(lavmodel@modprop$nexo) + 1L) ) } } else { N <- 0 for(g in 1:lavsamplestats@ngroups) { N <- N + lavdata@Lp[[g]]$nclusters[[2]] } } } else { N <- lavsamplestats@ntotal - lavsamplestats@ngroups } VarCov <- 1/N * NVarCov if(!is.null(lavoptions$check.vcov) && lavoptions$check.vcov) { eigvals <- eigen(VarCov, symmetric = TRUE, only.values = TRUE)$values neq <- 0L niq <- 0L if(nrow([email protected]) > 0L) { ceq.idx <- attr([email protected], "ceq.idx") cin.idx <- attr([email protected], "cin.idx") ina.idx <- attr([email protected], "inactive.idx") if(length(ceq.idx) > 0L) { neq <- qr([email protected][ceq.idx,,drop=FALSE])$rank } if(length(cin.idx) > 0L) { niq <- length(cin.idx) - length(ina.idx) } neiq <- neq + niq if(neiq > 0L) { eigvals <- rev(eigvals)[- seq_len(neiq)] } } min.val <- min(eigvals) if(min.val < .Machine$double.eps^(3/4) && lavoptions$warn) { if(min.val > 0) { txt <- c("The variance-covariance matrix of the estimated parameters (vcov) does not appear to be positive definite! The smallest eigenvalue (= ", sprintf("%e", min(min.val)), ") is close to zero. This may be a symptom that the model is not identified.") warning(lav_txt2message(txt)) } else { txt <- c("The variance-covariance matrix of the estimated parameters (vcov) does not appear to be positive definite! The smallest eigenvalue (= ", sprintf("%e", min(min.val)), ") is smaller than zero. This may be a symptom that the model is not identified.") warning(lav_txt2message(txt)) } } } } else { if(lavoptions$warn) { txt <- "Could not compute standard errors! The information matrix could not be inverted. This may be a symptom that the model is not identified." warning(lav_txt2message(txt)) } VarCov <- NULL } VarCov } lav_model_vcov_se <- function(lavmodel, lavpartable, VCOV = NULL, BOOT = NULL) { if(is.null(VCOV)) { se <- rep(as.numeric(NA), [email protected]) se[ lavpartable$free == 0L ] <- 0.0 return(se) } x.var <- diag(VCOV) x.var[x.var < 0] <- as.numeric(NA) x.se <- sqrt( x.var ) GLIST <- lav_model_x2GLIST(lavmodel = lavmodel, x = x.se, type = "free") se <- lav_model_get_parameters(lavmodel = lavmodel, GLIST = GLIST, type = "user", extra = FALSE) se[ which(lavpartable$free == 0L) ] <- 0.0 def.idx <- which(lavpartable$op == ":=") if(length(def.idx) > 0L) { if(!is.null(BOOT)) { BOOT.def <- apply(BOOT, 1L, [email protected]) if(length(def.idx) == 1L) { BOOT.def <- as.matrix(BOOT.def) } else { BOOT.def <- t(BOOT.def) } def.cov <- cov(BOOT.def ) } else { x <- lav_model_get_parameters(lavmodel = lavmodel, type = "free") JAC <- try(lav_func_jacobian_complex(func = [email protected], x = x), silent=TRUE) if(inherits(JAC, "try-error")) { JAC <- lav_func_jacobian_simple(func = [email protected], x = x) } def.cov <- JAC %*% VCOV %*% t(JAC) } diag.def.cov <- diag(def.cov) diag.def.cov[ diag.def.cov < 0 ] <- as.numeric(NA) se[def.idx] <- sqrt(diag.def.cov) } se }
mtcars by(data, INDICES, FUN, ..., simplify = TRUE) split(mtcars, mtcars$am) mtcars$am; mtcars$mpg by(mtcars$mpg,mtcars$am, FUN=mean ) by(warpbreaks[, 1:2], warpbreaks[,"tension"], summary) by(warpbreaks[, 1:2], warpbreaks[,"tension"], mean) by(iris$Sepal.Width , iris$Species , summary ) by(iris, iris$Species, length) by(x=mtcars, mtcars$am, function(x) mean(x)) by(iris, iris$Species, mean) by(iris$Sepal.Width, iris$Species, mean) df=data.frame(a=c(1:15),b=c(1,1,2,2,2,2,3,4,4,4,5,5,6,7,7)) by(df,factor(df$b),sum) df df2=data.frame(a=c(1:15),k=c(1:15),b=c(1,1,2,2,2,2,3,4,4,4,5,5,6,7,7)) by(df2,factor(df2$b),sum) df2 ?by bo1 = by(data= mtcars[,'mpg'], INDICES=mtcars[,'cyl'], summary) str(bo1) by(data= mtcars[,'mpg'], INDICES=mtcars[,'cyl'], max) by(data= mtcars[,'disp'], INDICES=mtcars[,c('vs','am')], mean) by(data= mtcars[,c('disp','wt')], INDICES=mtcars[,c('vs','am')], mean) aggregate(mtcars[,c('disp','wt')], mtcars[,c('vs','am')], mean) by(data= mtcars[,c('disp','wt')], INDICES=mtcars[,c('vs','am')], summary)
SUE.fitted.values <- function(fit){ mf=model.frame(formula=fit$p$formula, data=fit$p$data) z=(as.matrix(mf[,-1])%*%as.matrix(fit$coeff[-1])+fit$coeff[1]) z }
require_a <- function (traits, value, pcall = NULL) { " character -> a -> call|string -> boolean test if the value has the required traits, if it doesn't throw a helpful error. decorate with pcall so the error will look like it came from the user's function of choice." valid_pcall <- !is.null(pcall) && ( is.character(pcall) || is.call(pcall)) pcall <- if (valid_pcall) { deparse_to_string(pcall) } else { deparse_to_string( sys.call() ) } force_error_handler <- function (error) { stop(paste0(pcall, ": ", error$message), call. = FALSE) } tryCatch( { force(traits) }, error = force_error_handler) tryCatch( { force(value) }, error = force_error_handler) tryCatch( { force(pcall) }, error = force_error_handler) if (missing(value)) { report$missing_value(pcall) } if (missing(traits)) { report$missing_traits(pcall) } if (!is.character(traits)) { report$traits_not_character(pcall, traits) } (length(traits) == 0) || check_traits( validate_traits( traits, pcall ), value, pcall) } validate_traits <- function (trait_string, pcall) { "character -> call -> [character] takes the raw traits string, and transforms it into a list of trait groups to test" delimiter <- '[ \t\n\r]+' lapply( trait_string, function (compound_trait) { traits <- strsplit(compound_trait, split = delimiter)[[1]] invalid <- setdiff( traits, c(trait_tests$valid_traits, paste0("!", trait_tests$valid_traits)) ) if (length(invalid) == 0) { traits } else { report$invalid_traits(pcall, invalid) } }) } check_traits <- function (trait_vector, value, pcall) { "does the value have at least one group of traits? if yes, return true. otherwise, throw a descriptive error." error_handler <- function (error) { report$error_encountered( pcall, error, inputs = list( value = value, value = trait)) } warning_handler <- function (warning) { report$warning_encountered( pcall, warning, inputs = list( value = value, trait = trait)) } for (compound_trait in trait_vector) { compound_trait_matched <- TRUE for (trait in compound_trait) { trait_matched <- tryCatch({ has_trait <- if (substring(trait, 1, 1) == "!") { trait_tests[[ substring(trait, 2) ]] } else { trait_tests[[trait]] } trait_matched <- has_trait(value) if (!is_boolean(trait_matched)) { report$non_boolean( pcall, inputs = list( value = value, trait = trait), actual = trait_matched) } if (substring(trait, 1, 1) == "!") { !trait_matched } else { trait_matched } }, error = error_handler, warning = warning_handler ) if (!trait_matched) { compound_trait_matched <- FALSE break } } if (compound_trait_matched) { break } } compound_trait_matched ||report$no_match( pcall, value, trait_vector) } implemented_traits <- function () { "print all traits available in the current version" cat('currently implemented traits:\n', paste0(trait_tests$valid_traits, collapse = ", ") ) } add_trait <- function (name, trait_test) { "string -> (a -> boolean) -> null side-effectful. add a new trait to the trait tests" pcall <- sys.call() require_a("string", name, pcall) require_a("unary function", trait_test) if (name %in% trait_tests$valid_traits) { report$trait_overridden(pcall, name) } trait_tests[[name]] <- trait_test trait_tests$valid_traits <- ls(trait_tests) }
library(cif) qtr2<-iculomb ssize <-nrow(qtr2) cal <- seq(from=as.Date("2020-02-24"), by="days",length.out = ssize) ic = log(qtr2$terapia_intensiva) hws=log(qtr2$ricoverati_con_sintomi) y <- cbind(ic,hws) colnames(y) <- make.names(c("ic","hws")) ssize <-nrow(qtr2) cal <- seq(from=as.Date("2020-02-24"), by="days",length.out = ssize) n<- nrow(y); nlag=4; nhstar=0; booseas <- F; pntdates <-NA; drop1<-NA; drop2<-NA; npl<-c(nrow(y), ncol(y), nlag) breaks <- NA ndet=c(2,1); begtrim=7; endtrim=7; nforecast=7; npred=0; befpn<-c(begtrim,endtrim,nforecast,npred,nhstar) longcal<-seq(from=cal[1], by="days",length.out = n+npred) det1 <- ec.datadet1(n,befpn,breaks) det2 <- ec.datadet2(det1,booseas,pntdates) ymat <- ec.datalag(y,nlag) oua1<-ec.main(y=y,ndet=ndet,nlag,befpn,breaks,booseas, pntdates,drop1=NA,drop2=NA,cal=cal) ix <- t(as.matrix(cbind(oua1$tablefap[c(1,3,4,6,9,10,13,14),3]))) barplot(ix, main = "Performance of the VEC model relative to the Random Walk", xlab = "", col = c("red","green","blue"), beside = TRUE ) abline(h=1, col="blue", lty=2, lwd=1) ix <- t(as.matrix(cbind(oua1$tablefap[c(1,3,4,6,9,10,13,14),3]))) rownames(ix)<-c("Model1") myylim<-c(min(ix),max(ix)); yvec<-c(0.1,0.3,1,3,10,30) plot(y=ix,x=seq(1:8),type="p",ylim=myylim,main="VEC model compared to the Random Walk",font.main=1,pch=19,col="blue",ylab="",xlab="",xaxt="n", yaxt="n"); xtick<-seq(1:8) xticklab<-colnames(ix) text(x=xtick, par("usr")[3], labels = xticklab, srt = 0, pos = 1, offset=1, xpd = TRUE) ytick<- round(seq(min(ix),max(ix),length.out = 5),digits = 2) yticklab<-round(seq(min(ix),max(ix),length.out = 5),digits = 2) axis(side=2, at=ytick, labels = FALSE) text(par("usr")[1], y=ytick, labels = yticklab, srt = 0, pos = 2, xpd = TRUE) ytick1<- 1 yticklab1<-1 axis(side=2, at=ytick1, labels = FALSE) text(par("usr")[1], y=ytick1, labels = yticklab1, srt = 0, pos = 2, xpd = TRUE) abline(h=1, col="black", lty=2, lwd=1)
rfa <- function(pers_obj, na_treat=0, tr=FALSE ,use="complete.obs", res="stdr", method="pearson", cor=TRUE){ obj <- expscore(pers_obj, na_treat=na_treat) if (tr==TRUE) {obj <- lapply(obj,t)} Eni <- obj$Eni Yni <- obj$Yni Zni <- obj$Zni Y2ni <- obj$Y2ni Z2ni <- obj$Z2ni if( !(any(res==c("sr","stdr","srsq","stdrsq"))) ){stop("wrong type of residuals selected","\n", "check argument 'res'","\n")} if( class(cor)!="logical" ){stop("argument 'cor' must be of class \"logical\"","\n")} if(res=="sr"){resi <- Yni} if(res=="stdr"){resi <- Zni} if(res=="srsq"){resi <- Y2ni} if(res=="stdrsq"){resi <- Z2ni} if(cor==TRUE){matr <- cor(x=resi, use=use, method=method)} if(cor==FALSE){matr <- cov(x=resi, use=use, method=method)} eig <- eigen(matr) rownames(eig$vectors) <- row.names(matr) Cname<-nchar(paste(dim(matr)[1])) colnames(eig$vectors) <-paste("Comp",formatC(1:dim(matr)[1], width = Cname, format = "d", flag = "0"),sep=".") eigen.values <- eig$values variance.total <- sum(eig$values) variance.proportion <- eig$values/sum(eig$values) loadings <- eig$vectors erg <- list(pers_obj=pers_obj, pca=list(eigen.values=eigen.values, loadings=loadings, variance.proportion=variance.proportion, variance.total=variance.total, transposed=tr)) class(erg) <- c("rfa","list") return(erg) }
harvest <- tsibble( year = rep(2010:2012, 2), fruit = rep(c("kiwi", "cherry"), each = 3), kilo = sample(1:10, size = 6), key = fruit, index = year ) test_that("error for existing `.id`", { expect_error( slide_tsibble(harvest, .size = 2, .id = "kilo"), "Can't overwrite existing column `kilo`." ) }) test_that("slide_tsibble()", { res <- slide_tsibble(harvest, .size = 2) expect_equal(NROW(res), NROW(harvest) + 2L) expect_named(res, c(names(harvest), ".id")) expect_equal(res$.id, c(rep(1:2, each = 4))) }) test_that("tile_tsibble()", { res <- tile_tsibble(harvest, .size = 2, .id = "tile_id") expect_equal(NROW(res), NROW(harvest)) expect_named(res, c(names(harvest), "tile_id")) expect_equal(res$tile_id, c(rep(1, 4), rep(2, 2))) }) test_that("stretch_tsibble()", { res <- stretch_tsibble(harvest) expect_equal(NROW(res), NROW(harvest) * 2) expect_equal(res$.id, c(rep(1, 2), rep(2, 4), rep(3, 6))) })
LASheader <- function(data = list()) {return(new("LASheader", data))} as.list.LASheader <- function(x, ...) { PHB <- x@PHB VLR <- list(`Variable Length Records` = x@VLR) EVLR <- list(`Extended Variable Length Records` = x@EVLR) return(c(PHB, VLR, EVLR)) }
context("fpkm") test_that("fpkm works as expected", { dds <- DESeqDataSetFromMatrix(matrix(c(1:4,2 * 1:4), ncol=2), DataFrame(x=1:2), ~ 1) rowRanges(dds) <- GRanges("1", IRanges(start=0:3 * 10 + 1, width=10)) expect_equal(fpkm(dds)[1,1], 1e5 * 100, tolerance=.1) expect_equal(fpm(dds)[1,1], 1e5, tolerance=.1) expect_equal(fpm(dds, robust=FALSE)[1,1], 1e5) })
hybridSearchAlgorithm <- function(hybridSearcher, params=list()){ if(!is.list(params)){ stop('The hybrid search algorithm parameters are not in a list.') } algorithms <- list('LCC') switch(hybridSearcher, 'LCC'={ do.call(LCC,params) }, { stop('The hybrid search algorithm passed as a parameter is not supported by the package.') } ) } attr(hybridSearchAlgorithm,'shortName') <- "hybridSearchAlgorithm" attr(hybridSearchAlgorithm,'name') <- "Hybrid search algorithm generator" attr(hybridSearchAlgorithm,'methods') <- c('LCC')
NULL print.verbatim <- function(x, ...) { for(i in seq_along(x)) { cat("```\n") print(x[[i]], ...) cat("\n```\n\n") } invisible(x) } verbatim <- function(...) { structure(list(...), class = "verbatim") } code.chunk <- function(..., chunk.opts = "r") { if(!is.character(chunk.opts) || length(chunk.opts) != 1) stop("'chunk.opts' should be a single character string") Call <- match.call() Call[[1]] <- NULL Call$chunk.opts <- NULL if(length(Call) == 0) Call[[1]] <- "" set_attr(set_attr(Call, "chunk.opts", chunk.opts), "class", c("code.chunk", class(Call))) } print.code.chunk <- function(x, ...) { cat("```{", attr(x, "chunk.opts"), "}\n", sep = "") lapply(x, function(elt) if(is.character(elt)) cat(elt, "\n", sep = "") else print(elt)) cat("```\n\n") }
clean_runs <- function(runs = ls_runs(runs_dir = runs_dir), runs_dir = getOption("tfruns.runs_dir", "runs"), confirm = interactive()) { if (!missing(runs)) run_dirs <- as_run_dir(runs) else run_dirs <- list_run_dirs(runs_dir = runs_dir) if (length(run_dirs) == 0) { message("No runs found to clean.") return(invisible(NULL)) } archive_dir <- file.path(runs_dir, "archive") if (confirm) { prompt <- readline(sprintf("Move %d run directories to %s? [Y/n]: ", length(run_dirs), archive_dir)) if (nzchar(prompt) && tolower(prompt) != 'y') return(invisible(NULL)) } if (!utils::file_test("-d", archive_dir)) dir.create(archive_dir, recursive = TRUE) file.rename(run_dirs, file.path(archive_dir, basename(run_dirs))) message(sprintf('Moved %d runs to %s (purge_runs() to remove permanently)', length(run_dirs), archive_dir)) invisible(NULL) } purge_runs <- function(runs_dir = getOption("tfruns.runs_dir", "runs"), confirm = interactive()) { archive_dir <- file.path(runs_dir, "archive") run_dirs <- list_run_dirs(runs_dir = archive_dir) if (confirm) { prompt <- readline(sprintf("Permanently remove %d run directories from %s? [Y/n]: ", length(run_dirs), archive_dir)) if (nzchar(prompt) && tolower(prompt) != 'y') return(invisible(NULL)) } unlink(run_dirs, recursive = TRUE) message(sprintf("Permanently removed %d runs", length(run_dirs))) invisible(NULL) }
library(checkargs) context("isPositiveIntegerOrNaOrNanOrInfVectorOrNull") test_that("isPositiveIntegerOrNaOrNanOrInfVectorOrNull works for all arguments", { expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(NULL, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(TRUE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(FALSE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(NA, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(0, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(-1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(-0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(NaN, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(-Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull("", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull("X", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(c(TRUE, FALSE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(c(FALSE, TRUE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(c(NA, NA), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(c(0, 0), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(c(-1, -2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(c(-0.1, -0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(c(0.1, 0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(c(1, 2), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(c(NaN, NaN), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(c(-Inf, -Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(c(Inf, Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(c("", "X"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(c("X", "Y"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(NULL, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(TRUE, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(FALSE, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(NA, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(0, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(-1, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(-0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(NaN, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(-Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isPositiveIntegerOrNaOrNanOrInfVectorOrNull("", stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isPositiveIntegerOrNaOrNanOrInfVectorOrNull("X", stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(c(TRUE, FALSE), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(c(FALSE, TRUE), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(c(NA, NA), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(c(0, 0), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(c(-1, -2), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(c(-0.1, -0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(c(0.1, 0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(c(1, 2), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(c(NaN, NaN), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(c(-Inf, -Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(c(Inf, Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(c("", "X"), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isPositiveIntegerOrNaOrNanOrInfVectorOrNull(c("X", "Y"), stopIfNot = TRUE, message = NULL, argumentName = NULL)) })
tam_calc_exp <- function( rprobs, A, np, est.xsi.index, itemwt, indexIP.no, indexIP.list2, Avector ) { CC <- dim(rprobs)[2] TP <- dim(rprobs)[3] NXSI <- dim(A)[3] NI <- dim(A)[1] rprobsL1 <- as.vector( rprobs ) AL1 <- Avector rprobsL1 <- tam_rcpp_calc_exp_redefine_vector_na( A=rprobsL1, val=0 ) res <- tam_rcpp_calc_exp( NP=np, rprobs=rprobsL1, A=AL1, INDEXIPNO=indexIP.no, INDEXIPLIST2=indexIP.list2, ESTXSIINDEX=est.xsi.index, C=CC, ITEMWT=itemwt, NR=NI*CC, TP=TP ) return(res) } calc_exp_TK3 <- tam_calc_exp
cross_correlation <- function(X = NULL, wl = 512, bp = "pairwise.freq.range", ovlp = 70, dens = NULL, wn ='hanning', cor.method = "pearson", parallel = 1, path = NULL, pb = TRUE, na.rm = FALSE, cor.mat = NULL, output = "cor.mat", compare.matrix = NULL, type = "spectrogram", nbands = 40, method = 1) { on.exit(pbapply::pboptions(type = .Options$pboptions$type), add = TRUE) argms <- methods::formalArgs(cross_correlation) opt.argms <- if(!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 names(opt.argms)[names(opt.argms) == "wav.path"] <- "path" opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] call.argms <- as.list(base::match.call())[-1] opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] if (length(opt.argms) > 0) for (q in 1:length(opt.argms)) assign(names(opt.argms)[q], opt.argms[[q]]) if (is.null(path)) path <- getwd() else if (!dir.exists(path) & !is_extended_selection_table(X)) stop("'path' provided does not exist") else path <- normalizePath(path) if (!any(is.data.frame(X), is_selection_table(X), is_extended_selection_table(X))) stop("X is not of a class 'data.frame', 'selection_table' or 'extended_selection_table'") if (is_extended_selection_table(X) & length(unique(attr(X, "check.results")$sample.rate)) > 1) stop("all wave objects in the extended selection table must have the same sampling rate (they can be homogenized using resample_est_waves())") if (any(is.na(c(X$end, X$start)))) stop("NAs found in start and/or end") if (nrow(X) == 1 & is.null(compare.matrix)) stop("you need more than one selection to do cross-correlation") if (bp[1] == "pairwise.freq.range" & is.null(X$bottom.freq)) stop("'bp' must be supplied when no frequency range columns are found in 'X' (bottom.freq & top.freq)") if(is.null(bp[1])) stop("'bp' must be supplied") if (!is.null(dens)) write(file = "", x = "'dens' has been deprecated and will be ignored") if (!is.null(cor.mat)) write(file = "", x = "'dens' has been deprecated and will be ignored") if (!any(output %in% c("cor.mat", "list"))) stop("'output' must be either 'cor.mat' or 'list'") if (!is.numeric(wl)) stop("'wl' must be a numeric vector of length 1") else { if (!is.vector(wl)) stop("'wl' must be a numeric vector of length 1") else{ if (!length(wl) == 1) stop("'wl' must be a numeric vector of length 1")}} if (!is.numeric(ovlp)) stop("'ovlp' must be a numeric vector of length 1") else { if (!is.vector(ovlp)) stop("'ovlp' must be a numeric vector of length 1") else{ if (!length(ovlp) == 1) stop("'ovlp' must be a numeric vector of length 1")}} if (!is_extended_selection_table(X)){ fs <- list.files(path = path, pattern = "\\.wav$", ignore.case = TRUE) if (length(unique(X$sound.files[(X$sound.files %in% fs)])) != length(unique(X$sound.files))) write(file = "", x = paste(length(unique(X$sound.files))-length(unique(X$sound.files[(X$sound.files %in% fs)])), ".wav file(s) not found")) d <- which(X$sound.files %in% fs) if (length(d) == 0){ stop("The .wav files are not in the working directory") } else { X <- X[d, ] } } if (!is.numeric(parallel)) stop("'parallel' must be a numeric vector of length 1") if (any(!(parallel %% 1 == 0),parallel < 1)) stop("'parallel' should be a positive integer") if (is_extended_selection_table(X) & length(unique(attr(X, "check.results")$sample.rate)) > 1) stop("sampling rate must be the same for all selections") X$selection.id <- paste(X$sound.files, X$selec, sep = "-") if (!is.null(compare.matrix)) { X <- X[X$selection.id %in% unique(c(compare.matrix)), , drop = FALSE] if (!any(names(call.argms) == "method")) method <- 2 } if (pb){ max.stps <- getOption("warbleR.steps") if (is.null(max.stps)) if (method == 1) max.stps <- 2 else max.stps <- 1 } if (is.null(compare.matrix)) spc.cmbs.org <- spc.cmbs <- t(combn(X$selection.id, 2)) else { if (all(c(compare.matrix) %in% X$selection.id)) spc.cmbs.org <- spc.cmbs <- compare.matrix else { complt.sf <- setdiff(c(compare.matrix), X$selection.id) wvdr <- duration_wavs(files = complt.sf, path = path) names(wvdr)[2] <- "end" wvdr$start <- 0 wvdr$selec <- "whole.file" wvdr$selection.id <- paste(wvdr$sound.files, wvdr$selec, sep = "-") out <- lapply(1:nrow(wvdr), function(x) { sls <- setdiff(c(compare.matrix[compare.matrix[, 1] %in% wvdr$sound.files[x] | compare.matrix[, 2] %in% wvdr$sound.files[x], ]), wvdr$sound.files[x]) suppressWarnings(df <- data.frame( wvdr[x, ], channel = min(X$channel[X$selection.id %in% sls]), bottom.freq = min(X$bottom.freq[X$selection.id %in% sls]), top.freq = max(X$top.freq[X$selection.id %in% sls]) )) return(df) }) wvdr <- do.call(rbind, out) int.nms <- intersect(names(X), names(wvdr)) X <- rbind(as.data.frame(X)[, int.nms, drop = FALSE], wvdr[, int.nms]) for (i in complt.sf) compare.matrix[compare.matrix == i] <- paste(i, "whole.file", sep = "-") spc.cmbs.org <- spc.cmbs <- compare.matrix } } spc_FUN <- function(j, pth, W, wlg, ovl, w, nbnds) { clp <- warbleR::read_wave(X = W, index = j, path = pth) if (type == "spectrogram") spc <- seewave::spectro(wave = clp, wl = wlg, ovlp = ovl, wn = w, plot = FALSE, fftw = TRUE, norm = TRUE) if (type == "mfcc") { spc <- melfcc(clp, nbands = nbnds, hoptime = (wlg / [email protected]) * (ovl / 100), wintime = wlg / [email protected], dcttype = "t3", fbtype = "htkmel", spec_out = TRUE) names(spc)[2] <- "amp" spc$amp <- t(spc$amp) spc$freq <- seq(0, [email protected] / 2000, length.out = nbnds) } spc$amp[is.infinite(spc$amp)] <- NA return(spc) } if (method == 1){ if (pb) if (type == "spectrogram") write(file = "", x = paste0("creating spectrogram matrices (step 1 of ", max.stps,"):")) else write(file = "", x = paste0("creating MFCC matrices (step 1 of ", max.stps,"):")) pbapply::pboptions(type = ifelse(pb, "timer", "none")) if (Sys.info()[1] == "Windows" & parallel > 1) cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) else cl <- parallel spcs <- pbapply::pblapply(X = 1:nrow(X), cl = cl, function(e) spc_FUN(j = e, pth = path, W = X, wlg = wl, ovl = ovlp, w = wn, nbnds = nbands)) if (!is_extended_selection_table(X) & length(unique(sapply(spcs, function(x) length(x$freq)))) > 1) stop("sampling rate must be the same for all selections") names(spcs) <- X$selection.id } XC_FUN <- function(spc1, spc2, b = bp, cm = cor.method){ spc1$amp <- spc1$amp[spc1$freq >= b[1] & spc1$freq <= b[2], ] spc2$amp <- spc2$amp[which(spc2$freq >= b[1] & spc2$freq <= b[2]), ] if(ncol(spc1$amp) > ncol(spc2$amp)) { lg.spc <- spc1$amp shrt.spc <- spc2$amp } else { lg.spc <- spc2$amp shrt.spc <- spc1$amp } shrt.lgth <- ncol(shrt.spc) - 1 stps <- ncol(lg.spc) - ncol(shrt.spc) if (stps <= 1) stps <- 1 else stps <- 1:stps cors <- sapply(stps, function(x, cor.method = cm) { warbleR::try_na(cor(c(lg.spc[, x:(x + shrt.lgth)]), c(shrt.spc), method = cm, use ='pairwise.complete.obs')) }) return(cors) } ord.shuf <- sample(1:nrow(spc.cmbs)) spc.cmbs <- spc.cmbs[ord.shuf, , drop = FALSE] if (pb) write(file = "", x = paste0("running cross-correlation (step ", max.stps," of ", max.stps,"):")) if (Sys.info()[1] == "Windows" & parallel > 1) cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) else cl <- parallel xcrrs <- pbapply::pblapply(X = 1:nrow(spc.cmbs), cl = cl, FUN = function(j, BP = bp, cor.meth = cor.method) { if (BP[1] %in% c("pairwise.freq.range", "frange")) BP <- c(min(X$bottom.freq[X$selection.id %in% spc.cmbs[j, ]]), max(X$top.freq[X$selection.id %in% spc.cmbs[j, ]])) if (method == 1) { spc1 <- spcs[[spc.cmbs[j, 1]]] spc2 <- spcs[[spc.cmbs[j, 2]]] } if (method == 2) { spc1 <- spc_FUN(j = which(X$selection.id == spc.cmbs[j, 1]), pth = path, W = X, wlg = wl, ovl = ovlp, w = wn, nbnds = nbands) spc2 <- spc_FUN(j = which(X$selection.id == spc.cmbs[j, 2]), pth = path, W = X, wlg = wl, ovl = ovlp, w = wn, nbnds = nbands) } XC_FUN(spc1 = spc1, spc2 = spc2, b = BP, cm = cor.meth) }) xcrrs <- xcrrs[order(ord.shuf)] mx.xcrrs <- sapply(xcrrs, max, na.rm = TRUE) if (is.null(compare.matrix)){ mat <- matrix(nrow = nrow(X), ncol = nrow(X)) mat[] <- 1 colnames(mat) <- rownames(mat) <- X$selection.id mat[lower.tri(mat, diag=FALSE)] <- mx.xcrrs mat <- t(mat) mat[lower.tri(mat, diag=FALSE)] <- mx.xcrrs if (na.rm) { com.case <- intersect(rownames(mat)[stats::complete.cases(mat)], colnames(mat)[stats::complete.cases(t(mat))]) if (length(which(is.na(mat))) > 0) warning(paste(length(which(is.na(mat))), "pairwise comparisons failed and were removed")) mat <- mat[rownames(mat) %in% com.case, colnames(mat) %in% com.case] if (nrow(mat) == 0) stop("Not selections remained after removing NAs (na.rm = TRUE)") } } else { mat <- data.frame(compare.matrix, score = mx.xcrrs) if (na.rm) mat <- mat[!is.infinite(mat$scores), ] } if (output == "list") { cor.lst <- lapply(1:nrow(spc.cmbs.org), function(x) { durs <- c( (X$end - X$start)[X$selection.id == spc.cmbs.org[x, 1]], (X$end - X$start)[X$selection.id == spc.cmbs.org[x, 2]] ) df <- data.frame(dyad = paste(spc.cmbs.org[x, ], collapse = "/"), sound.files = spc.cmbs.org[x, which.max(durs)], template = spc.cmbs.org[x, which.min(durs)], time = if (!is.null( xcrrs[[x]])) c(X$start[X$selection.id == spc.cmbs.org[x, 1]], X$start[X$selection.id == spc.cmbs.org[x, 2]])[which.max(durs)] + seq(min(durs)/2, max(durs) - min(durs)/2, length.out = length(xcrrs[[x]])) else NA, score = if (!is.null(xcrrs[[x]])) xcrrs[[x]] else NA) return(df) }) cor.table <- do.call(rbind, cor.lst) if (na.rm) { if (exists("com.case")) cor.table <- cor.table[cor.table$sound.files %in% com.case & cor.table$template %in% com.case, ] errors <- cor.table[is.na(cor.table$score), ] errors$score <- NULL cor.table <- cor.table[!is.infinite(cor.table$score), ] } } if (output == "cor.mat") return(mat) else{ output_list <- list(max.xcorr.matrix = mat, scores = cor.table, selection.table = X, hop.size.ms = read_wave(X, 1, header = TRUE, path = path)$sample.rate / wl, errors = if (na.rm) errors else NA) class(output_list) <- c("list", "xcorr.output") return(output_list) } } xcorr <- cross_correlation
"duane" <- function(t, init = c(1, 1), method = "Nelder-Mead", maxit = 10000, ...) { eq1 <- function(rho, theta, t) { n <- length(t) t <- cumsum(t) i <- seq(along = t) tn <- t[length(t)] rho - n / (tn^theta) } eq2 <- function(rho, theta, t) { i <- seq(along = t[1:length(t) - 1]) n <- length(t) t <- cumsum(t) tn <- t[length(t)] theta - n / (sum(log(tn / t[i]))) } global <- function(vec, t) { rho <- vec[1] theta <- vec[2] v1 <- eq1(rho, theta, t)^2 v2 <- eq2(rho, theta, t)^2 v1 + v2 } res <- optim(init, global, t = t, method = method, control = list(maxit = maxit, ...)) rho <- res$par[1] theta <- res$par[2] return(list(rho = rho, theta = theta)) } "duane.plot" <- function(rho, theta, t, xlab = "time", ylab = "Cumulated failures and estimated mean value function", main = NULL) { plot(cumsum(t), 1:length(t), type = "o", pch = 3, cex = 0.8, xlab = xlab, ylab = ylab) lines(cumsum(t), mvf.duane(rho, theta, cumsum(t)), lty = 2, type = "o", pch = 4, cex = 0.8, col = "mediumblue") legend("bottomright", c("Data", "Duane"), col = c("black", "mediumblue"), pch = c(3, 4), lty = c(1, 2)) if(!is.null(main)) { title(main) } } "littlewood.verall" <- function(t, linear = T, init = c(1, 1, 1), method = "Nelder-Mead", maxit = 10000, ...) { if(linear == T) { eq1 <- function(theta0, theta1, rho, t) { n <- length(t) i <- seq(along = t) s1 <- sum(log(theta0 + theta1 * i)) s2 <- sum(log(theta0 + theta1 * i + t[i])) (n / rho) + s1 - s2 } eq2 <- function(theta0, theta1, rho, t) { i <- seq(along = t) s1 <- rho * sum(1 / (theta0 + theta1 * i)) s2 <- (rho + 1) * sum(1 / (theta0 + theta1 * i + t[i])) s1 - s2 } eq3 <- function(theta0, theta1, rho, t) { i <- seq(along = t) s1 <- rho * sum(i / (theta0 + theta1 * i)) s2 <- (rho + 1) * sum(i / (theta0 + theta1 * i + t[i])) s1 - s2 } global.linear <- function(vec, t) { theta0 <- vec[1] theta1 <- vec[2] rho <- vec[3] v1 <- eq1(theta0, theta1, rho, t)^2 v2 <- eq2(theta0, theta1, rho, t)^2 v3 <- eq3(theta0, theta1, rho, t)^2 v1 + v2 + v3 } res <- optim(init, global.linear, t = t, method = method, control = list(maxit = maxit, ...)) theta0 <- res$par[1] theta1 <- res$par[2] rho <- res$par[3] res <- optim(c(theta0, theta1, rho), global.linear, t = t, method = method, control = list(maxit = maxit, ...)) } else { eq1 <- function(theta0, theta1, rho, t) { n <- length(t) i <- seq(along = t) s1 <- sum(log(theta0 + theta1 * i^2)) s2 <- sum(log(theta0 + theta1 * i^2 + t[i])) (n / rho) + s1 - s2 } eq2 <- function(theta0, theta1, rho, t) { i <- seq(along = t) s1 <- rho * sum(1 / (theta0 + theta1 * i^2)) s2 <- (rho + 1) * sum(1 / (theta0 + theta1 * i^2 + t[i])) s1 - s2 } eq3 <- function(theta0, theta1, rho, t) { i <- seq(along = t) s1 <- rho * sum((i^2) / (theta0 + theta1 * i^2)) s2 <- (rho + 1) * sum((i^2) / (theta0 + theta1 * i^2 + t[i])) s1 - s2 } global.quadratic <- function(vec, t) { theta0 <- vec[1] theta1 <- vec[2] rho <- vec[3] v1 <- eq1(theta0, theta1, rho, t)^2 v2 <- eq2(theta0, theta1, rho, t)^2 v3 <- eq3(theta0, theta1, rho, t)^2 v1 + v2 + v3 } res <- optim(init, global.quadratic, t = t, method = method, control = list(maxit = maxit, ...)) theta0 <- res$par[1] theta1 <- res$par[2] rho <- res$par[3] res <- optim(c(theta0, theta1, rho), global.quadratic, t = t, method = method, control = list(maxit = maxit, ...)) } theta0 <- res$par[1] theta1 <- res$par[2] rho <- res$par[3] return(list(theta0 = theta0, theta1 = theta1, rho = rho)) } "littlewood.verall.plot" <- function(theta0, theta1, rho, t, linear = T, xlab = "time", ylab = "Cumulated failures and estimated mean value function", main = NULL) { if(linear == T) { mvf.ver <- mvf.ver.lin(theta0, theta1, rho, cumsum(t)) plot(cumsum(t), 1:length(t), type = "o", pch = 3, cex = 0.8, xlab=xlab, ylab = ylab) } else { mvf.ver <- mvf.ver.quad(theta0, theta1, rho, cumsum(t)) plot(cumsum(t), 1:length(t), type = "o", pch = 3, cex = 0.8, xlab = xlab, ylab = ylab) } lines(cumsum(t), mvf.ver, lty=2, type = "o", pch = 4, cex = 0.8, col="mediumblue") legend("bottomright", c("Data", "Littlewood-Verall"), col=c("black", "mediumblue"), pch=c(3, 4), lty=c(1, 2)) if(!is.null(main)) { title(main) } } "moranda.geometric" <- function(t, init = c(0, 1), tol = .Machine$double.eps^0.25) { Dhat <- function(phi, t) { n <- length(t) i <- seq(along = t) return(phi * n / (sum(phi^i * t[i]))) } phihat <- function(phi, t) { i <- seq(along = t) n <- length(t) return((sum(i * (phi^i) * t[i]) / sum((phi^i) * t[i]) - (n + 1) / 2)^2) } min <- optimize(phihat, init, tol = tol, t = t) phi <- min$minimum D <- Dhat(phi, t) theta<- -log(phi) return(list(D = D, theta = theta)) } "moranda.geometric.plot" <- function(D, theta, t, xlab = "time", ylab = "Cumulated failures and estimated mean value function", main = NULL) { plot(cumsum(t), 1:length(t), type = "o", pch = 3, cex = 0.8, xlab = xlab, ylab = ylab) lines(cumsum(t), mvf.mor(D, theta, cumsum(t)), lty = 2, type = "o", pch = 4, cex = 0.8, col = "mediumblue") legend("bottomright", c("Data", "Moranda-Geometric"), col=c("black", "mediumblue"), pch=c(3, 4), lty=c(1, 2)) if(!is.null(main)) { title(main) } } "musa.okumoto" <- function(t, init = c(0, 1), tol = .Machine$double.eps^0.25) { theta0hat <- function(theta1, t) { n <- length(t) t <- cumsum(t) tn <- t[length(t)] return(n / log(1 + theta1 * tn)) } theta1hat <- function(theta1, t) { i <- seq(along = t) n <- length(t) t <- cumsum(t) tn <- t[length(t)] return((1 / theta1 * sum(1 / (1 + theta1 * t[i])) - n * tn / ((1 + theta1 * tn) * log(1 + theta1 * tn)))^2) } min <- optimize(theta1hat, init, tol = tol, t = t) theta1 <- min$minimum theta0 <- theta0hat(theta1, t) return(list(theta0 = theta0, theta1 = theta1)) } "musa.okumoto.plot" <- function(theta0, theta1, t, xlab = "time", ylab = "Cumulated failures and estimated mean value function", main = NULL) { plot(cumsum(t), 1:length(t), type = "o", pch = 3, cex = 0.8, xlab = xlab, ylab = ylab) lines(cumsum(t), mvf.musa(theta0, theta1, cumsum(t)), lty = 2, type = "o", pch = 4, cex = 0.8, col = "mediumblue") legend("bottomright", c("Data", "Musa-Okumoto"), col = c("black", "mediumblue"), pch = c(3, 4), lty = c(1, 2)) if(!is.null(main)) { title(main) } } "total.plot" <- function(duane.par1, duane.par2, lit.par1, lit.par2, lit.par3, mor.par1, mor.par2, musa.par1, musa.par2, t, linear = T, xlab = "time", ylab = "Cumulated failures and estimated mean value functions", main = NULL) { if(linear == T) { mvf.ver <- mvf.ver.lin(lit.par1, lit.par2, lit.par3, cumsum(t)) } else { mvf.ver <- mvf.ver.quad(lit.par1, lit.par2, lit.par3, cumsum(t)) } plot(cumsum(t), 1:length(t), type = "o", pch = 3, cex = 0.8, xlab = xlab, ylab = ylab) lines(cumsum(t), mvf.duane(duane.par1, duane.par2, cumsum(t)), lty = 2, type = "o", pch = 4, cex = 0.8, col = "mediumblue") lines(cumsum(t), mvf.ver, lty = 3, type = "o", pch = 8, cex = 0.8, col = "steelblue") lines(cumsum(t), mvf.mor(mor.par1, mor.par2, cumsum(t)), lty = 4, type = "o", pch = 0, cex = 0.8, col = "skyblue") lines(cumsum(t), mvf.musa(musa.par1, musa.par2, cumsum(t)), lty = 5, type = "o", pch = 15, cex = 0.8, col = "royalblue") legend("bottomright", c("Data", "Duane", "Littlewood-Verall", "Moranda-Geometric", "Musa-Okumoto"), col = c("black", "mediumblue", "steelblue", "skyblue", "royalblue"), pch = c(3, 4, 8, 0, 15), lty = c(1, 2, 3, 4, 5)) if(!is.null(main)) { title(main) } } "rel.plot" <- function(duane.par1, duane.par2, lit.par1, lit.par2, lit.par3, mor.par1, mor.par2, musa.par1, musa.par2, t, linear = T, ymin, ymax, xlab = "time", ylab = "relative error", main = NULL) { l <- 1:length(t) rel.duane <- (mvf.duane(duane.par1, duane.par2, cumsum(t)) - l) / l if(linear == T) { rel.ver <- (mvf.ver.lin(lit.par1, lit.par2, lit.par3, cumsum(t)) - l) / l } else { rel.ver <- (mvf.ver.quad(lit.par1, lit.par2, lit.par3, cumsum(t)) - l) / l } rel.mor <- (mvf.mor(mor.par1, mor.par2, cumsum(t)) - l) / l rel.musa <- (mvf.musa(musa.par1, musa.par2, cumsum(t)) - l) / l if(missing(ymin)) { ymin <- min(c(rel.duane, rel.ver, rel.mor, rel.musa)) } if(missing(ymax)) { ymax <- max(c(rel.duane, rel.ver, rel.mor, rel.musa)) } plot(cumsum(t), rel.duane, type = "o", pch = 4, cex = 0.8, col = "mediumblue", xlab = xlab, ylim = c(ymin, ymax), lty = 2, ylab = ylab) lines(cumsum(t), rel.ver, lty = 3, type = "o", pch = 8, cex = 0.8, col = "steelblue") lines(cumsum(t), rel.mor, lty = 4, type = "o", pch = 0, cex = 0.8, col = "skyblue") lines(cumsum(t), rel.musa, lty = 5, type = "o", pch = 15, cex = 0.8, col = "royalblue") segments(-max(cumsum(t)) * 1.05, 0, max(cumsum(t)) * 1.05, 0, lty = 3) legend("topright", c("Duane", "Littlewood-Verall", "Moranda-Geometric", "Musa-Okumoto"), col = c("mediumblue", "steelblue", "skyblue", "royalblue"), pch = c(4, 8, 0, 15), lty = c(2, 3, 4, 5)) if(!is.null(main)) { title(main) } } "mvf.duane" <- function(rho, theta, t) { if(rho <= 0 || theta <= 0) { stop("rho and theta should be larger than 0") } if(length(rho) != 1 || length(theta) != 1) { stop("rho and theta should have length 1") } return(rho * t^theta) } "mvf.mor" <- function(D, theta, t) { if(theta <= 0) { stop("theta should be larger than 0") } if(length(D) != 1 || length(theta) != 1) { stop("D and theta should have length 1") } return(1 / theta * log((D * theta * exp(theta)) * t + 1)) } "mvf.musa" <- function(theta0, theta1, t) { if(length(theta0) != 1 || length(theta1) != 1) { stop("theta0 and theta1 should have length 1") } return(theta0 * log(theta1 * t + 1)) } "mvf.ver.lin" <- function(theta0, theta1, rho, t) { if(theta1 == 0) { stop("theta1 should not be equal 0") } if(length(theta0) != 1 || length(theta1) != 1 || length(rho) != 1) { stop("theta0, theta1 and rho should have length 1") } return(1 / theta1 * sqrt(theta0^2 + 2 * theta1 * t * rho)) } "mvf.ver.quad" <- function(theta0, theta1, rho, t) { if(theta1 == 0) { stop("theta1 should not be equal 0") } if(length(theta0) != 1 || length(theta1) != 1 || length(rho) != 1) { stop("theta0, theta1 and rho should have length 1") } v1 <- (rho - 1)^(1 / 3) / ((18 * theta1)^(1 / 3)) v2 <- 4 * (theta0^3) / (9 * (rho - 1)^2 * theta1) Q1 <- (cumsum(t) + (cumsum(t)^2 + v2)^(1 / 2))^(1 / 3) Q2 <- (cumsum(t) - (cumsum(t)^2 + v2)^(1 / 2))^(1 / 3) return(3 * v1 * (Q1 + Q2)) }
library(vcfR) context("create.chromR functions") test_that("Create a null chromR",{ data("vcfR_example") chrom <- methods::new(Class="chromR") expect_is(chrom, "chromR") expect_is(chrom@vcf, "vcfR") expect_is(chrom@seq, "NULL") expect_is(chrom@ann, "data.frame") expect_equal(ncol(chrom@vcf@fix), 8) expect_equal(nrow(chrom@vcf@fix), 0) expect_equal(length(chrom@seq), 0) expect_equal(ncol(chrom@ann), 9) expect_equal(nrow(chrom@ann), 0) }) test_that("We can create a Chrom, no sequence or annotation",{ data("vcfR_example") chrom <- create.chromR(name="Supercontig_1.50", vcf=vcf, verbose=FALSE) expect_is(chrom, "chromR") expect_is(chrom@vcf, "vcfR") expect_is(chrom@seq, "NULL") expect_is(chrom@ann, "data.frame") expect_is([email protected], "data.frame") expect_is([email protected][,'POS'], "integer") expect_equal(ncol(chrom@vcf@fix), 8) expect_equal(nrow(chrom@vcf@fix) > 0, TRUE) expect_equal(length(chrom@seq), 0) expect_equal(ncol(chrom@ann), 9) expect_equal(nrow(chrom@ann), 0) expect_equal(ncol([email protected]), 5) expect_equal(nrow([email protected])>0, TRUE) }) test_that("We can create a chromR, no annotation",{ data("vcfR_example") chrom <- create.chromR(name="Supercontig_1.50", vcf=vcf, seq=dna, verbose=FALSE) expect_is(chrom, "chromR") expect_is(chrom@vcf, "vcfR") expect_is(chrom@seq, "DNAbin") expect_is(chrom@ann, "data.frame") expect_is([email protected], "data.frame") expect_equal(ncol(chrom@vcf@fix), 8) expect_equal(nrow(chrom@vcf@fix) > 0, TRUE) expect_equal(length(chrom@seq)>0, TRUE) expect_equal(ncol(chrom@ann), 9) expect_equal(nrow(chrom@ann), 0) }) test_that("We can create a chromR, no sequence",{ data("vcfR_example") chrom <- create.chromR(name="Supercontig_1.50", vcf=vcf, ann=gff, verbose=FALSE) expect_is(chrom, "chromR") expect_is(chrom@vcf, "vcfR") expect_is(chrom@seq, "NULL") expect_is(chrom@ann, "data.frame") expect_is([email protected], "data.frame") expect_equal(ncol(chrom@vcf@fix), 8) expect_equal(nrow(chrom@vcf@fix) > 0, TRUE) expect_equal(length(chrom@seq), 0) expect_equal(ncol(chrom@ann), 9) expect_equal(nrow(chrom@ann)>0, TRUE) }) test_that("We can create a chromR, no sequence, annotation greater than vcf POS",{ data("vcfR_example") gff2 <- gff gff2[23,5] <- 100000 chrom <- create.chromR(name="Supercontig_1.50", vcf=vcf, ann=gff2, verbose=FALSE) expect_equal( chrom@len, 100000) }) test_that("We can create a chromR",{ data("vcfR_example") chrom <- create.chromR(name="Supercontig_1.50", vcf=vcf, seq=dna, ann=gff, verbose=FALSE) expect_is(chrom, "chromR") expect_is(chrom@vcf, "vcfR") expect_is(chrom@seq, "DNAbin") expect_is(chrom@ann, "data.frame") expect_is([email protected], "data.frame") expect_equal(ncol(chrom@vcf@fix), 8) expect_equal(nrow(chrom@vcf@fix) > 0, TRUE) expect_equal(length(chrom@seq)>0, TRUE) expect_equal(ncol(chrom@ann), 9) expect_equal(nrow(chrom@ann)>0, TRUE) }) test_that("We implemented the mask",{ data("vcfR_example") chrom <- create.chromR(name="Supercontig_1.50", vcf=vcf, seq=dna, ann=gff, verbose=FALSE) chrom <- masker(chrom, min_DP = 300, max_DP = 700) expect_true( sum([email protected][,'mask']) < nrow([email protected]) ) }) test_that("preserve = TRUE preserves the original mask ", { data("chromR_example") chrom_preserve_mask <- masker(chrom, min_QUAL = 40, preserve = TRUE) chrom_new_mask <- masker(chrom, min_QUAL = 40, preserve = FALSE) ori_mask <- [email protected][, 'mask'] add_mask <- [email protected][, 'mask'] expect_true(sum(add_mask) < sum(ori_mask)) expect_equal(sum(ori_mask | add_mask), sum(ori_mask)) }) test_that("proc.chromR works",{ data("chromR_example") chrom <- proc.chromR(chrom, verbose = FALSE) expect_true( ncol([email protected]) >= 3 ) chrom <- proc.chromR(chrom, verbose = FALSE) expect_true( ncol([email protected]) >= 3 ) }) test_that("seq2rects works for test data",{ data("chromR_example") rects1 <- seq2rects(chrom) expect_is( rects1, "matrix" ) expect_true( nrow(rects1) > 0 ) }) test_that("seq2rects works with ns",{ data("chromR_example") rects2 <- seq2rects(chrom, chars="n") expect_is( rects2, "matrix" ) expect_true( nrow(rects2) > 0 ) }) test_that("seq2rects works when seq has no Ns",{ data("chromR_example") seq2 <- as.character( chrom@seq ) seq2[ seq2 == 'n' ] <- 'a' chrom@seq <- ape::as.DNAbin(seq2) rects2 <- seq2rects(chrom, chars="n") expect_is( rects2, "matrix" ) expect_true( nrow(rects2) == 0 ) }) test_that("chromR2vcfR works",{ data('vcfR_example') chrom <- create.chromR(name="Supercontig_1.50", vcf=vcf, seq=dna, ann=gff, verbose=FALSE) chrom <- masker(chrom, min_DP = 300, max_DP = 700) test <- chromR2vcfR(chrom, use.mask = TRUE) expect_equal(sum([email protected]$mask), nrow(test)) })
expected <- eval(parse(text="c(-41L, -36L, -12L, -18L, NA, -28L, -23L, -19L, -8L, NA, -7L, -16L, -11L, -14L, -18L, -14L, -34L, -6L, -30L, -11L, -1L, -11L, -4L, -32L, NA, NA, NA, -23L, -45L, -115L, -37L, NA, NA, NA, NA, NA, NA, -29L, NA, -71L, -39L, NA, NA, -23L, NA, NA, -21L, -37L, -20L, -12L, -13L, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, -135L, -49L, -32L, NA, -64L, -40L, -77L, -97L, -97L, -85L, NA, -10L, -27L, NA, -7L, -48L, -35L, -61L, -79L, -63L, -16L, NA, NA, -80L, -108L, -20L, -52L, -82L, -50L, -64L, -59L, -39L, -9L, -16L, -78L, -35L, -66L, -122L, -89L, -110L, NA, NA, -44L, -28L, -65L, NA, -22L, -59L, -23L, -31L, -44L, -21L, -9L, NA, -45L, -168L, -73L, NA, -76L, -118L, -84L, -85L, -96L, -78L, -73L, -91L, -47L, -32L, -20L, -23L, -21L, -24L, -44L, -21L, -28L, -9L, -13L, -46L, -18L, -13L, -24L, -16L, -13L, -23L, -36L, -7L, -14L, -30L, NA, -14L, -18L, -20L)")); test(id=0, code={ argv <- eval(parse(text="list(c(41L, 36L, 12L, 18L, NA, 28L, 23L, 19L, 8L, NA, 7L, 16L, 11L, 14L, 18L, 14L, 34L, 6L, 30L, 11L, 1L, 11L, 4L, 32L, NA, NA, NA, 23L, 45L, 115L, 37L, NA, NA, NA, NA, NA, NA, 29L, NA, 71L, 39L, NA, NA, 23L, NA, NA, 21L, 37L, 20L, 12L, 13L, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 135L, 49L, 32L, NA, 64L, 40L, 77L, 97L, 97L, 85L, NA, 10L, 27L, NA, 7L, 48L, 35L, 61L, 79L, 63L, 16L, NA, NA, 80L, 108L, 20L, 52L, 82L, 50L, 64L, 59L, 39L, 9L, 16L, 78L, 35L, 66L, 122L, 89L, 110L, NA, NA, 44L, 28L, 65L, NA, 22L, 59L, 23L, 31L, 44L, 21L, 9L, NA, 45L, 168L, 73L, NA, 76L, 118L, 84L, 85L, 96L, 78L, 73L, 91L, 47L, 32L, 20L, 23L, 21L, 24L, 44L, 21L, 28L, 9L, 13L, 46L, 18L, 13L, 24L, 16L, 13L, 23L, 36L, 7L, 14L, 30L, NA, 14L, 18L, 20L))")); do.call(`-`, argv); }, o=expected);
impute <- function(object, type = c("mar", "censored", "both"), lambda.new, rho.new) { type <- match.arg(type) if (!inherits(object, c("cggm", "cglasso"))) stop(sQuote("imput"), "function is not available for an object of class ", sQuote(class(object))) if ( class(object)[1L] == "cggm") { if (!missing(lambda.new)) stop("Argument ", sQuote("lambda.new"), " is not available for an object of class ", sQuote("cggm")) if (!missing(rho.new)) stop("Argument ", sQuote("rho.new"), " is not available for an object of class ", sQuote("cggm")) p <- npred(object$Z) out <- drop(object$Yipt) Id <- event(object$Z) if (type == "mar") { lo <- lower(object$Z) up <- upper(object$Z) for (h in seq_len(p)) { out[Id[, h] == -1L, h] <- lo[h] out[Id[, h] == +1L, h] <- up[h] } } if (type == "censored") out[Id == +9L] <- NA return(out) } if (missing(lambda.new) & missing(rho.new)) return(object$Yipt) nrho <- object$nrho rho <- object$rho nlambda <- object$nlambda lambda <- object$lambda n <- nobs(object$Z) p <- nresp(object$Z) q <- npred(object$Z) if (missing(lambda.new)) { if (q > 0) stop(sQuote("lambda.new"), " is missing") else lambda.new <- lambda } else { if (!is.vector(lambda.new)) stop(sQuote("lambda.new"), " is not a vector") if (length(lambda.new) != 1L) stop(sQuote("lambda.new"), " is not an object of length ", sQuote(1)) if (lambda.new < lambda[nlambda]) stop(sQuote("lambda.new"), "is smaller than ", sQuote(lambda[nlambda])) } if (missing(rho.new)) stop(sQuote("rho.new"), " is missing") else { if (!is.vector(rho.new)) stop(sQuote("rho.new"), " is not a vector") if (length(rho.new) != 1L) stop(sQuote("rho.new"), " is not an object of length ", sQuote(1)) if (rho.new < rho[nrho]) stop(sQuote("rho.new"), "is smaller than ", sQuote(rho[nrho])) } Yin <- object$Yipt Yout <- matrix(0, nrow = n, ncol = p, dimnames = list(dimnames(Yin)[[1L]], dimnames(Yin)[[2L]])) Id <- event(object$Z) storage.mode(rho.new) <- "double" storage.mode(lambda.new) <- "double" storage.mode(nrho) <- "integer" storage.mode(rho) <- "double" storage.mode(nlambda) <- "integer" storage.mode(lambda) <- "double" storage.mode(n) <- "integer" storage.mode(p) <- "integer" storage.mode(Yin) <- "double" storage.mode(Id) <- "integer" storage.mode(Yout) <- "double" out <- .Fortran(C_impute, newrho = rho.new, newlambda = lambda.new, nrho = nrho, rho = rho, nlambda = nlambda, lambda = lambda, n = n, p = p, Yin = Yin, Id = Id, Yout = Yout) if (type == "mar") { lo <- lower(object$Z) up <- upper(object$Z) for (h in seq_len(p)) { out$Yout[Id[, h] == -1L, h] <- lo[h] out$Yout[Id[, h] == +1L, h] <- up[h] } } if (type == "censored") out$Yout[Id == +9L] <- NA out$Yout } function2xy <- function(frml) { x <- match.arg(all.vars(frml)[2L], c("rho", "lambda")) y <- as.character(terms(frml)[[2L]]) if (length(y) == 2L) { if(y[1L] != "diag" | y[2L] != "Theta") stop(sQuote(paste0(y[1L], "(", y[2L], ")")), " is not available as response. Please, use ", sQuote("diag(Theta)")) y <- "diag(Theta)" } given <- as.character(terms(frml)[[3L]]) if (length(given) == 1L) given <- NULL else { if (given[3L] == "rho") { if (x == "rho") stop("You can not condition on ", sQuote(given[3L]), ". Please, use ", sQuote("lambda")) return(list(x = x, y = y, given = NULL)) } if (given[3L] == "lambda") { if (x == "lambda") stop("You can not condition on ", sQuote(given[3L]), ". Please, use ", sQuote("rho")) return(list(x = x, y = y, given = NULL)) } given.terms <- gsub("[[:blank:]]", "", given[3L]) given.terms <- unlist(strsplit(given.terms, split = "\n", fixed = TRUE)) if (length(given.terms) == 1L) given <- eval(parse(text = given.terms)) else { given.terms <- given.terms[2L] given.name <- unlist(strsplit(given.terms, "=", fixed = TRUE))[1L] if (!is.element(given.name, c("lambda.id", "rho.id"))) stop("Please, use ", sQuote(ifelse(x == "rho", "lambda.id", "rho.id")), " instead of ", sQuote(given.name)) if ((x == "rho" & given.name == "rho.id") | (x == "lambda" & given.name == "lambda.id")) stop("You can not condition on ", sQuote(given.name), ". Please, use ", sQuote(ifelse(given.name == "rho.id", "lambda.id", "rho.id"))) given <- eval(parse(text = given.terms)) } } out <- list(penalty = x, what = y, given = given) out }
library(frbs) data(frbsData) data.train <- frbsData$MackeyGlass1000.dt[1: 500, ] data.fit <- data.train[, 1 : 4] data.tst <- frbsData$MackeyGlass1000.dt[501 : 1000, 1 : 4] real.val <- matrix(frbsData$MackeyGlass1000.dt[501 : 1000, 5], ncol = 1) range.data <- matrix(c(0.43462, 1.3105, 0.43462, 1.3105, 0.43462, 1.3105, 0.43462, 1.3105, 0.43462, 1.3105), nrow=2) control <- list(Dthr= 0.1, max.iter = 300, step.size = 0.01, d = 2, name = "MG1000") method.type <- "DENFIS" object <- frbs.learn(data.train, range.data, method.type, control) res.fit <- predict(object, data.fit) res.test <- predict(object, data.tst) y.pred <- res.test y.real <- real.val bench <- cbind(y.pred, y.real) colnames(bench) <- c("pred. val.", "real. val.") print("Comparison DENFIS Vs Real Value on Mackey Glass Data Set") print(bench) residuals <- (y.real - y.pred) MSE <- mean(residuals^2) RMSE <- sqrt(mean(residuals^2)) SMAPE <- mean(abs(residuals)/(abs(y.real) + abs(y.pred))/2)*100 err <- c(MSE, RMSE, SMAPE) names(err) <- c("MSE", "RMSE", "SMAPE") print("DENFIS: Error Measurement: ") print(err) op <- par(mfrow = c(2, 1)) x1 <- seq(from = 1, to = nrow(res.fit)) result.fit <- cbind(data.train[, 5], res.fit) plot(x1, result.fit[, 1], col="red", main = "Mackey Glass: Fitting phase (the training data(red) Vs Sim. result(blue))", type = "l", ylab = "MG") lines(x1, result.fit[, 2], col="blue") result.test <- cbind(real.val, res.test) x2 <- seq(from = 1, to = nrow(result.test)) plot(x2, result.test[, 1], col="red", main = "Mackey Glass: Predicting phase (the Real Data(red) Vs Sim. result(blue))", type = "l", ylab = "MG") lines(x2, result.test[, 2], col="blue", type = "l") par(op)
"table.paint" <- function (df, x = 1:ncol(df), y = nrow(df):1, row.labels = row.names(df), col.labels = names(df), clabel.row = 1, clabel.col = 1, csize = 1, clegend = 1) { x <- rank(x) y <- rank(y) opar <- par(mai = par("mai"), srt = par("srt")) on.exit(par(opar)) table.prepare(x = x, y = y, row.labels = row.labels, col.labels = col.labels, clabel.row = clabel.row, clabel.col = clabel.col, grid = FALSE, pos = "paint") xtot <- x[col(as.matrix(df))] ytot <- y[row(as.matrix(df))] xdelta <- (max(x) - min(x))/(length(x) - 1)/2 ydelta <- (max(y) - min(y))/(length(y) - 1)/2 coeff <- diff(range(xtot))/15 z <- unlist(df) br0 <- pretty(z, 6) nborn <- length(br0) coeff <- diff(range(x))/15 numclass <- cut.default(z, br0, include.lowest = TRUE, labels = FALSE) valgris <- seq(1, 0, le = (nborn - 1)) h <- csize * coeff rect(xtot - xdelta, ytot - ydelta, xtot + xdelta, ytot + ydelta, col = gray(valgris[numclass])) if (clegend > 0) scatterutil.legend.square.grey(br0, valgris, h/2, clegend) }
find_data_dir <- function(){ datapath <- c("/share/opencv", "/share/opencv4", "/share/OpenCV") paths <- c( system.file('share', package = 'opencv'), paste0(data_prefix(), datapath) ) for(x in paths){ if(file.exists(x)) return(x) } stop("Failed to find opencv 'share' directory") } find_data_xml <- function(filename){ normalizePath(file.path(find_data_dir(), filename), mustWork = TRUE) }
context("sar_loga") library(sars) test_that("sar_loga returns correct results", { fit <- sar_loga(galap) expect_equal(round(fit$AICc, 2), 189.19) expect_equal(as.vector(round(fit$par[2], 2)), 30.28) expect_is(fit, "sars") expect_match(fit$normaTest[[1]], "none") expect_match(fit$homoTest[[1]], "none") expect_error(sar_linear(5), "data must be a matrix or dataframe") fit2 <- sar_loga(galap, homoTest = "cor.area", homoCor = "kendall") expect_equal(round(fit2$homoTest[[2]]$p.value, 2), 0.35) expect_match(fit2$homoTest[[2]]$method, "Kendall's rank correlation tau") }) test_that("sar_loga summary returns correct results", { fit <- sar_loga(galap, normaTest = "lillie") fs <- summary(fit) expect_equal(sum(fs$residuals), 6.439294e-15) expect_output(str(fs), "List of 16") expect_is(fs, "summary.sars") expect_equal(round(fs$normaTest[[2]]$p.value, 3), 0.658) })
"kiascv" <- function(xt,k=np,mdx=nrow(xt),fu=.dFvGet()$fu1,fb=.dFvGet()$fb1) { if (missing(xt)) messagena("xt") np <- ncol(xt) ncov <- np*(np+1)/2 cov <- single(ncov) f.res <- .Fortran("kiascvz", xt=to.single(xt), k=to.integer(k), np=to.integer(np), mdx=to.integer(mdx), ncov=to.integer(ncov), fu=to.single(fu), fb=to.single(fb), cov=to.single(cov)) list(cov=f.res$cov) }
context("itis_lsid") test_that("itis_lsid returns the correct value", { skip_on_cran() vcr::use_cassette("itis_lsid", { one <- itis_lsid("urn:lsid:itis.gov:itis_tsn:180543") two <- itis_lsid("urn:lsid:itis.gov:itis_tsn:180543", "record") three <- itis_lsid("urn:lsid:itis.gov:itis_tsn:202385", "fullrecord") four <- itis_lsid(202385) }) expect_equal(one, "180543") expect_match(as.character(two[1, "genuspart"]), "Ursus") expect_match(three$acceptedNameList$tsn, "202385") expect_null(four) expect_is(one, "character") expect_is(two, "data.frame") expect_is(three, "list") })
context("device serializer") test_that("graphics device promise domains must have a device", { expect_error( createGraphicsDevicePromiseDomain(which = c(`null device` = 1L)), "was called without opening a device" ) }) test_that("you should not call `dev_set()` with a null device", { expect_warning( dev_set(c(`null device` = 1L)), "null device" ) }) skip_on_cran() expect_device_output <- function(name, content_type, capability_type = name) { if (!is.null(capability_type)) { if (!capabilities(capability_type)) { testthat::skip("Graphics device type not supported: ", name) } } ep <- NULL pr <- pr() evaluateBlock( srcref = 3, file = c(" expr = function() { plot(1:10) }, envir = new.env(parent=globalenv()), addEndpoint = function(a, b, ...) { pr$handle(endpoint = a) }, addFilter = as.null, pr = pr ) ret <- pr$call(make_req("GET", "/test")) expect_equal(ret$status, 200) expect_equal(ret$headers$`Content-Type`, content_type) expect_true(is.raw(ret$body)) expect_gt(length(ret$body), 1000) } test_that("jpeg produces an image", { expect_device_output("jpeg", "image/jpeg") }) test_that("png produces an image", { expect_device_output("png", "image/png") }) test_that("svg produces an image", { expect_device_output("svg", "image/svg+xml", "cairo") }) test_that("bmp produces an image", { expect_device_output("bmp", "image/bmp", "cairo") }) test_that("tiff produces an image", { expect_device_output("tiff", "image/tiff") }) test_that("pdf produces an image", { expect_device_output("pdf", "application/pdf", NULL) }) context("plumb() device serializer") test_device <- local({ r <- pr(test_path("files/device.R")) function(name, content_type, capability_type = name, test_little = TRUE) { if (!capabilities(capability_type)) { testthat::skip("Graphics type not supported: ", name) } resp <- r$serve(make_req("GET", paste0("/", name)), PlumberResponse$new()) expect_equal(resp$status, 200) expect_equal(resp$headers$`Content-Type`, content_type) fullsize <- length(resp$body) expect_gt(fullsize, 1000) if (!isTRUE(test_little)) { return() } resp <- r$serve(make_req("GET", paste0("/little", name)), PlumberResponse$new()) expect_equal(resp$status, 200) expect_equal(resp$headers$`Content-Type`, content_type) expect_gt(length(resp$body), 100) expect_lt(length(resp$body), fullsize) } }) test_that("png are properly rendered", { test_device("png", "image/png") }) test_that("jpeg are properly rendered", { test_device("jpeg", "image/jpeg") }) test_that("svg are properly rendered", { test_device("svg", "image/svg+xml", capability_type = "cairo", test_little = FALSE) })
getLplusLmin <- function(sigmaE, alpha) { Lplus <- Inf Lmin <- -Inf if ( !is.na(alpha[2]) ) Lplus <- sqrt(2)*sigmaE*invErf(1-2*alpha[2]) if ( !is.na(alpha[1]) ) Lmin <- sqrt(2)*sigmaE*invErf(2*alpha[1]-1) return(list(Lplus=Lplus,Lmin=Lmin)); }
my_env <- new.env(parent = emptyenv()) matrixplot <- function(data, dataclass = NULL, diagram = NULL, dir = tempdir()) { if (rmarkdown::pandoc_available("1.12.3") == FALSE) { print(warning_pandoc) } else if (rmarkdown::pandoc_available("1.12.3") == TRUE) { if (is.data.frame(data) == FALSE) { stop( "I am so sorry, but this function only works with a data.frame input!\n", "You have provided an object of class ", class(data) ) } if (tibble::is_tibble(data) == TRUE) { stop(warning_tibble) } if (is.null(dataclass) == TRUE) { dataclass <- c("numeric", "numeric") } if (length(dataclass) == 1) { dataclass <- rep(dataclass, 2) } if (length(dataclass) != 2) { stop(paste0("The 'dataclass'", string, "vector of length 1 or 2")) } string <- " argument expects a character" if (length(dataclass) != sum(dataclass %in% dataclass_v, na.rm = TRUE)) { stop(paste0( "The 'dataclass'", string, " which values can be : '", paste0(dataclass_v, collapse = "', '"), "'" )) } if (is.null(diagram) == TRUE) { diagram <- c("scatter plot") } if (length(diagram) != sum(diagram %in% c(matrixplot_2num, fac.num_v1, fac.num_v2, fac.fac_v1, fac.fac_v1, ord.ord_v0, ord.ord_v1, ord.ord_v2), na.rm = TRUE)) { stop(paste0( "The 'diagram'", string, " which values can be : '", paste0(cbind(matrixplot_2num, fac.num_v1), collapse = "', '"), "'" )) } my_env <- new.env() dir.create(file.path(dir, "brinton_outcomes", fsep = .Platform$file.sep), showWarnings = FALSE) writeLines(output_matrix, file.path(dir, "brinton_outcomes", "matrixplot.R")) write( paste0( "cat('A matrix of ", deparse(substitute(diagram)), " produced from the " , deparse(substitute(dataclass)), " dataclasses of the ", deparse(substitute(data)), " dataframe')" ), file = file.path(dir, "brinton_outcomes", "matrixplot.R"), append = TRUE ) if (length(data[sapply(data, is.numeric)])>1 && identical(dataclass, c("numeric", "numeric")) && (diagram %in% matrixplot_2num) == TRUE) { data.num <- data[sapply(data, is.numeric)] diagram <- rep(diagram, ncol(data.num)) out = NULL write(paste0(" for (i in seq_along(data.num)[2:ncol(data.num)]) { for (j in seq_along(data.num)[c(1:i-1)]) {eval(parse(text=paste0("nui", letters[j], " <- paste0('nu', ", i, ", '", letters[j],"')")))} num.plot <- function(pp) { for (j in seq_along(data.num)[c(1:i-1)]) {eval(parse(text=paste0(" if (diagram[", j, "] == 'scatter plot') { assign(nui", letters[j], ", pp_scatterplot(data, colnames(pp[j]), colnames(pp[i]), pp_size = 3/ncol(data.num), 'black', FALSE), envir=my_env) } else if (diagram[", j, "] == 'scatter plot with trend line') { assign(nui", letters[j], ", pp_scatterplot(data, colnames(pp[j]), colnames(pp[i]), pp_size = 3/ncol(data.num), 'black', TRUE), envir=my_env) } else if (diagram[", j, "] == 'bw scatter plot') { assign(nui", letters[j], ", pp_scatterplot(data, colnames(pp[j]), colnames(pp[i]), pp_size = 3/ncol(data.num), 'bw', FALSE), envir=my_env) } else if (diagram[", j, "] == 'color scatter plot') { assign(nui", letters[j], ", pp_scatterplot(data, colnames(pp[j]), colnames(pp[i]), pp_size = 3/ncol(data.num), 'color', FALSE), envir=my_env) } else if (diagram[", j, "] == 'binned scatter plot') { assign(nui", letters[j], ", pp_binnedpointgraph(data, colnames(pp[j]), colnames(pp[i]), pp_size = 3/ncol(data.num), 'black'), envir=my_env) } else if (diagram[", j, "] == 'bw binned scatter plot') { assign(nui", letters[j], ", pp_binnedpointgraph(data, colnames(pp[j]), colnames(pp[i]), pp_size = 3/ncol(data.num), 'bw'), envir=my_env) } else if (diagram[", j, "] == 'color binned scatter plot') { assign(nui", letters[j], ", pp_binnedpointgraph(data, colnames(pp[j]), colnames(pp[i]), pp_size = 3/ncol(data.num), 'color'), envir=my_env) } else if (diagram[", j, "] == 'binned heatmap') { assign(nui", letters[j], ", pp_heatmap(data, colnames(pp[j]), colnames(pp[i]), 'black'), envir=my_env) } else if (diagram[", j, "] == 'bw binned heatmap') { assign(nui", letters[j], ", pp_heatmap(data, colnames(pp[j]), colnames(pp[i]), 'bw'), envir=my_env) } else if (diagram[", j, "] == 'color binned heatmap') { assign(nui", letters[j], ", pp_heatmap(data, colnames(pp[j]), colnames(pp[i]), 'color'), envir=my_env) } else if (diagram[", j, "] == 'hexagonal binned heatmap') { assign(nui", letters[j], ", pp_heatmap(data, colnames(pp[j]), colnames(pp[i]), 'black', 6), envir=my_env) } else if (diagram[", j, "] == 'bw hexagonal binned heatmap') { assign(nui", letters[j], ", pp_heatmap(data, colnames(pp[j]), colnames(pp[i]), 'bw', 6), envir=my_env) } else if (diagram[", j, "] == 'color hexagonal binned heatmap') { assign(nui", letters[j], ", pp_heatmap(data, colnames(pp[j]), colnames(pp[i]), 'color', 6), envir=my_env) } else if (diagram[", j, "] == 'bw heatmap') { assign(nui", letters[j], ", pp_raster(data, colnames(pp[j]), colnames(pp[i]), 'bw'), envir=my_env) } else if (diagram[", j, "] == 'color heatmap') { assign(nui", letters[j], ", pp_raster(data, colnames(pp[j]), colnames(pp[i]), 'color'), envir=my_env) } else if (diagram[", j, "] == 'contour plot') { assign(nui", letters[j], ", pp_contourmap(data, colnames(pp[j]), colnames(pp[i]), pp_size = 3/ncol(data.num), 'black'), envir=my_env) } else if (diagram[", j, "] == 'bw contour plot') { assign(nui", letters[j], ", pp_contourmap(data, colnames(pp[j]), colnames(pp[i]), pp_size = 3/ncol(data.num), 'bw'), envir=my_env) } else if (diagram[", j, "] == 'color contour plot') { assign(nui", letters[j], ", pp_contourmap(data, colnames(pp[j]), colnames(pp[i]), pp_size = 3/ncol(data.num), 'color'), envir=my_env) } else if (diagram[", j, "] == 'contour plot with data points') { assign(nui", letters[j], ", pp_contourmap(data, colnames(pp[j]), colnames(pp[i]), pp_size = 3/ncol(data.num), 'black', TRUE), envir=my_env) } else if (diagram[", j, "] == 'bw contour plot with data points') { assign(nui", letters[j], ", pp_contourmap(data, colnames(pp[j]), colnames(pp[i]), pp_size = 3/ncol(data.num), 'bw', TRUE), envir=my_env) } else if (diagram[", j, "] == 'color contour plot with data points') { assign(nui", letters[j], ", pp_contourmap(data, colnames(pp[j]), colnames(pp[i]), pp_size = 3/ncol(data.num), 'color', TRUE), envir=my_env) } else if (diagram[", j, "] == 'scatter plot with confidence ellipse') { assign(nui", letters[j], ", pp_scatterplot(data, colnames(pp[j]), colnames(pp[i]), pp_size = 3/ncol(data.num), 'black', FALSE, TRUE, FALSE), envir=my_env) } else if (diagram[", j, "] == 'bw scatter plot with confidence ellipse') { assign(nui", letters[j], ", pp_scatterplot(data, colnames(pp[j]), colnames(pp[i]), pp_size = 3/ncol(data.num), 'bw', FALSE, TRUE, FALSE), envir=my_env) } else if (diagram[", j, "] == 'color scatter plot with confidence ellipse') { assign(nui", letters[j], ", pp_scatterplot(data, colnames(pp[j]), colnames(pp[i]), pp_size = 3/ncol(data.num), 'color', FALSE, TRUE, FALSE), envir=my_env) } else if (diagram[", j, "] == 'scatter plot with marginal rugs') { assign(nui", letters[j], ", pp_scatterplot(data, colnames(pp[j]), colnames(pp[i]), pp_size = 3/ncol(data.num), 'black', FALSE, FALSE, TRUE), envir=my_env) } else if (diagram[", j, "] == 'bw scatter plot with marginal rugs') { assign(nui", letters[j], ", pp_scatterplot(data, colnames(pp[j]), colnames(pp[i]), pp_size = 3/ncol(data.num), 'bw', FALSE, FALSE, TRUE), envir=my_env) } else if (diagram[", j, "] == 'color scatter plot with marginal rugs') { assign(nui", letters[j], ", pp_scatterplot(data, colnames(pp[j]), colnames(pp[i]), pp_size = 3/ncol(data.num), 'color', FALSE, FALSE, TRUE), envir=my_env) } else if (diagram[", j, "] == 'path graph') { assign(nui", letters[j], ", pp_pathgraph(data, colnames(pp[j]), colnames(pp[i]), FALSE, 'black', pp_size = 3/ncol(data.num)), envir=my_env) } else if (diagram[", j, "] == 'bw path graph') { assign(nui", letters[j], ", pp_pathgraph(data, colnames(pp[j]), colnames(pp[i]), FALSE, 'bw', pp_size = 3/ncol(data.num)), envir=my_env) } else if (diagram[", j, "] == 'color path graph') { assign(nui", letters[j], ", pp_pathgraph(data, colnames(pp[j]), colnames(pp[i]), FALSE, 'color', pp_size = 3/ncol(data.num)), envir=my_env) } else if (diagram[", j, "] == 'point-to-point graph') { assign(nui", letters[j], ", pp_pathgraph(data, colnames(pp[j]), colnames(pp[i]), TRUE, 'black', pp_size = 3/ncol(data.num)), envir=my_env) } else if (diagram[", j, "] == 'bw point-to-point graph') { assign(nui", letters[j], ", pp_pathgraph(data, colnames(pp[j]), colnames(pp[i]), TRUE, 'bw', pp_size = 3/ncol(data.num)), envir=my_env) } else if (diagram[", j, "] == 'color point-to-point graph') { assign(nui", letters[j], ", pp_pathgraph(data, colnames(pp[j]), colnames(pp[i]), TRUE, 'color', pp_size = 3/ncol(data.num)), envir=my_env) }"))) eval(parse(text=paste0("assign('blank', blank(data, colnames(pp[i])), envir=my_env) "))) } line <- eval(parse( text=paste0("paste0('gridExtra::grid.arrange(' ,", paste0(" nui", letters[1:i-1], collapse = ",', ',"), ",', ncol=", (ncol(data.num)-1), ")')"))) write(line, file.path(dir, "brinton_outcomes", "matrixplot.R"), append=TRUE) } num.plot(data.num) } } else if (length(data[sapply(data, lubridate::is.instant)])>1 && identical(dataclass, c("datetime", "datetime")) && (diagram %in% matrixplot_2dt) == TRUE) { data.date <- data[sapply(data, lubridate::is.instant)] diagram <- rep(diagram, ncol(data.date)) out = NULL write(paste0(" for (i in seq_along(data.date)[2:ncol(data.date)]) { for (j in seq_along(data.date)[c(1:i-1)]) {eval(parse(text=paste0("dti", letters[j], " <- paste0('dt', ", i, ", '", letters[j],"')")))} date.plot <- function(pp) { for (j in seq_along(data.date)[c(1:i-1)]) {eval(parse(text=paste0(" if (diagram[", j, "] == 'scatter plot') { assign(dti", letters[j], ", pp_scatterplot(data, colnames(pp[j]), colnames(pp[i]), pp_size = 3/ncol(data.date), 'black', FALSE), envir=my_env) } else if (diagram[", j, "] == 'scatter plot with trend line') { assign(dti", letters[j], ", pp_scatterplot(data, colnames(pp[j]), colnames(pp[i]), pp_size = 3/ncol(data.date), 'black', TRUE), envir=my_env) } else if (diagram[", j, "] == 'binned scatter plot') { assign(dti", letters[j], ", pp_binnedpointgraph(data, colnames(pp[j]), colnames(pp[i]), pp_size = 3/ncol(data.date), 'black'), envir=my_env) } else if (diagram[", j, "] == 'bw binned scatter plot') { assign(dti", letters[j], ", pp_binnedpointgraph(data, colnames(pp[j]), colnames(pp[i]), pp_size = 3/ncol(data.date), 'bw'), envir=my_env) } else if (diagram[", j, "] == 'color binned scatter plot') { assign(dti", letters[j], ", pp_binnedpointgraph(data, colnames(pp[j]), colnames(pp[i]), pp_size = 3/ncol(data.date), 'color'), envir=my_env) } else if (diagram[", j, "] == 'bw heatmap') { assign(dti", letters[j], ", pp_raster(data, colnames(pp[j]), colnames(pp[i]), 'bw'), envir=my_env) } else if (diagram[", j, "] == 'color heatmap') { assign(dti", letters[j], ", pp_raster(data, colnames(pp[j]), colnames(pp[i]), 'color'), envir=my_env) } else if (diagram[", j, "] == 'contour plot') { assign(dti", letters[j], ", pp_contourmap(data, colnames(pp[j]), colnames(pp[i]), pp_size = 3/ncol(data.date), 'black'), envir=my_env) } else if (diagram[", j, "] == 'bw contour plot') { assign(dti", letters[j], ", pp_contourmap(data, colnames(pp[j]), colnames(pp[i]), pp_size = 3/ncol(data.date), 'bw'), envir=my_env) } else if (diagram[", j, "] == 'color contour plot') { assign(dti", letters[j], ", pp_contourmap(data, colnames(pp[j]), colnames(pp[i]), pp_size = 3/ncol(data.date), 'color'), envir=my_env) } else if (diagram[", j, "] == 'contour plot with data points') { assign(dti", letters[j], ", pp_contourmap(data, colnames(pp[j]), colnames(pp[i]), pp_size = 3/ncol(data.date), 'black', TRUE), envir=my_env) } else if (diagram[", j, "] == 'path graph') { assign(dti", letters[j], ", pp_pathgraph(data, colnames(pp[j]), colnames(pp[i]), FALSE, 'black', pp_size = 3/ncol(data.date)), envir=my_env) } else if (diagram[", j, "] == 'bw path graph') { assign(dti", letters[j], ", pp_pathgraph(data, colnames(pp[j]), colnames(pp[i]), FALSE, 'bw', pp_size = 3/ncol(data.date)), envir=my_env) } else if (diagram[", j, "] == 'color path graph') { assign(dti", letters[j], ", pp_pathgraph(data, colnames(pp[j]), colnames(pp[i]), FALSE, 'color', pp_size = 3/ncol(data.date)), envir=my_env) } else if (diagram[", j, "] == 'point-to-point graph') { assign(dti", letters[j], ", pp_pathgraph(data, colnames(pp[j]), colnames(pp[i]), TRUE, 'black', pp_size = 3/ncol(data.date)), envir=my_env) } else if (diagram[", j, "] == 'bw point-to-point graph') { assign(dti", letters[j], ", pp_pathgraph(data, colnames(pp[j]), colnames(pp[i]), TRUE, 'bw', pp_size = 3/ncol(data.date)), envir=my_env) } else if (diagram[", j, "] == 'color point-to-point graph') { assign(dti", letters[j], ", pp_pathgraph(data, colnames(pp[j]), colnames(pp[i]), TRUE, 'color', pp_size = 3/ncol(data.date)), envir=my_env) }"))) eval(parse(text=paste0("assign('blank', blank(data, colnames(pp[i])), envir=my_env) "))) } line <- eval(parse( text=paste0("paste0('gridExtra::grid.arrange(' ,", paste0(" dti", letters[1:i-1], collapse = ",', ',"), ",', ncol=", ncol(data.date)-1, ")')"))) write(line, file.path(dir, "brinton_outcomes", "matrixplot.R"), append=TRUE) } date.plot(data.date) } } else if (length(data[sapply(data, is.numeric)])>0 && length(data[sapply(data, lubridate::is.instant)])>0 && any(dataclass %in% "datetime") && any(dataclass %in% "numeric") && (diagram %in% datenum_v) == TRUE) { data.date <- data[sapply(data, lubridate::is.instant)] data.num <- data[sapply(data, is.numeric)] diagram <- rep(diagram, ncol(data.date)) out = NULL for (i in seq_along(data.num)) { write(paste0(" for (j in seq_along(data.date)) {eval(parse(text=paste0("dni", letters[j], " <- paste0('dn', ", i, ", '", letters[j],"')")))} datenum.plot <- function(pp) { for (j in seq_along(data.date)) {eval(parse(text=paste0(" if (diagram[", j, "] == 'scatter plot') { assign(dni", letters[j], ", pp_scatterplot(data, colnames(pp[sapply(pp, lubridate::is.instant)][j]), colnames(pp[sapply(pp, is.numeric)][i]), pp_size = 1/ncol(data.num), 'black', FALSE), envir=my_env) } else if (diagram[", j, "] == 'scatter plot with trend line') { assign(dni", letters[j], ", pp_scatterplot(data, colnames(pp[sapply(pp, lubridate::is.instant)][j]), colnames(pp[sapply(pp, is.numeric)][i]), pp_size = 1/ncol(data.num), 'black', TRUE), envir=my_env) } else if (diagram[", j, "] == 'binned scatter plot') { assign(dni", letters[j], ", pp_binnedpointgraph(data, colnames(pp[sapply(pp, lubridate::is.instant)][j]), colnames(pp[sapply(pp, is.numeric)][i]), pp_size = 1/ncol(data.num), 'black'), envir=my_env) } else if (diagram[", j, "] == 'bw binned scatter plot') { assign(dni", letters[j], ", pp_binnedpointgraph(data, colnames(pp[sapply(pp, lubridate::is.instant)][j]), colnames(pp[sapply(pp, is.numeric)][i]), pp_size = 1/ncol(data.num), 'bw'), envir=my_env) } else if (diagram[", j, "] == 'color binned scatter plot') { assign(dni", letters[j], ", pp_binnedpointgraph(data, colnames(pp[sapply(pp, lubridate::is.instant)][j]), colnames(pp[sapply(pp, is.numeric)][i]), pp_size = 1/ncol(data.num), 'color'), envir=my_env) } else if (diagram[", j, "] == 'bw heatmap') { assign(dni", letters[j], ", pp_raster(data, colnames(pp[sapply(pp, lubridate::is.instant)][j]), colnames(pp[sapply(pp, is.numeric)][i]), 'bw'), envir=my_env) } else if (diagram[", j, "] == 'color heatmap') { assign(dni", letters[j], ", pp_raster(data, colnames(pp[sapply(pp, lubridate::is.instant)][j]), colnames(pp[sapply(pp, is.numeric)][i]), 'color'), envir=my_env) } else if (diagram[", j, "] == 'contour plot with data points') { assign(dni", letters[j], ", pp_contourmap(data, colnames(pp[sapply(pp, lubridate::is.instant)][j]), colnames(pp[sapply(pp, is.numeric)][i]), pp_size = 1/ncol(data.num), 'black', TRUE), envir=my_env) } else if (diagram[", j, "] == 'path graph') { assign(dni", letters[j], ", pp_pathgraph(data, colnames(pp[sapply(pp, lubridate::is.instant)][j]), colnames(pp[sapply(pp, is.numeric)][i]), FALSE, 'black', pp_size = 0.5/ncol(data.num)), envir=my_env) } else if (diagram[", j, "] == 'bw path graph') { assign(dni", letters[j], ", pp_pathgraph(data, colnames(pp[sapply(pp, lubridate::is.instant)][j]), colnames(pp[sapply(pp, is.numeric)][i]), FALSE, 'bw', pp_size = 0.5/ncol(data.num)), envir=my_env) } else if (diagram[", j, "] == 'color path graph') { assign(dni", letters[j], ", pp_pathgraph(data, colnames(pp[sapply(pp, lubridate::is.instant)][j]), colnames(pp[sapply(pp, is.numeric)][i]), FALSE, 'color', pp_size = 0.5/ncol(data.num)), envir=my_env) } else if (diagram[", j, "] == 'point-to-point graph') { assign(dni", letters[j], ", pp_pathgraph(data, colnames(pp[sapply(pp, lubridate::is.instant)][j]), colnames(pp[sapply(pp, is.numeric)][i]), TRUE, 'black', pp_size = 1/ncol(data.num)), envir=my_env) } else if (diagram[", j, "] == 'bw point-to-point graph') { assign(dni", letters[j], ", pp_pathgraph(data, colnames(pp[sapply(pp, lubridate::is.instant)][j]), colnames(pp[sapply(pp, is.numeric)][i]), TRUE, 'bw', pp_size = 1/ncol(data.num)), envir=my_env) } else if (diagram[", j, "] == 'color point-to-point graph') { assign(dni", letters[j], ", pp_pathgraph(data, colnames(pp[sapply(pp, lubridate::is.instant)][j]), colnames(pp[sapply(pp, is.numeric)][i]), TRUE, 'color', pp_size = 1/ncol(data.num)), envir=my_env) }")))} line <- eval(parse( text=paste0("paste0('gridExtra::grid.arrange(' ,", paste0(" dni", letters[1:ncol(data.date)], collapse = ",', ',"), ",', ncol=", ncol(data.date), ")')"))) write(line, file.path(dir, "brinton_outcomes", "matrixplot.R"), append=TRUE) write(" } datenum.plot(cbind(data.num, data.date)) } } else if (length(data[sapply(data, is.numeric)])>0 && length(data[sapply(data, is.factor)][!sapply(data[sapply(data, is.factor)], is.ordered)])>0 && any(dataclass %in% "numeric") && any(dataclass %in% c("factor")) && (diagram %in% matrixplot_fac.num) == TRUE) { data.num <- data[sapply(data, is.numeric)] data.fac <- data[sapply(data, is.factor)][!sapply(data[sapply(data, is.factor)], is.ordered)] rownames(data.fac) <- NULL diagram <- rep(diagram, ncol(data.num)) out = NULL for (i in seq_along(data.fac)) { for (j in seq_along(data.num)) {eval(parse(text=paste0("fni", letters[j], " <- paste0('fn', ", i, ", '", letters[j],"')")))} facnum.plot <- function(pp) { long <- round(length(unique(pp[sapply(pp, is.factor)][[i]]))/6 + 0.6, 1) for (j in seq_along(data.num)) {eval(parse(text=paste0(" if (diagram[", j, "] == 'path graph') { assign(fni", letters[j], ", pp_basicgraph(data, colnames(pp[sapply(pp, is.numeric)][j]), colnames(pp[sapply(pp, is.factor)][i]), pp_size = 1/ncol(data.num), 'line'), envir=my_env) } else if (diagram[", j, "] == 'point graph') { assign(fni", letters[j], ", pp_basicgraph(data, colnames(pp[sapply(pp, is.numeric)][j]), colnames(pp[sapply(pp, is.factor)][i]), pp_size = 1/ncol(data.num), 'point'), envir=my_env) } else if (diagram[", j, "] == 'tile plot') { assign(fni", letters[j], ", pp_basicgraph(data, colnames(pp[sapply(pp, is.numeric)][j]), colnames(pp[sapply(pp, is.factor)][i]), pp_size = 1/ncol(data.num), 'tile'), envir=my_env) } else if (diagram[", j, "] == 'binned heatmap') { assign(fni", letters[j], ", pp_basicgraph(data, colnames(pp[sapply(pp, is.numeric)][j]), colnames(pp[sapply(pp, is.factor)][i]), pp_size = 1/ncol(data.num), 'bin', 'black'), envir=my_env) } else if (diagram[", j, "] == 'bw binned heatmap') { assign(fni", letters[j], ", pp_basicgraph(data, colnames(pp[sapply(pp, is.numeric)][j]), colnames(pp[sapply(pp, is.factor)][i]), pp_size = 1/ncol(data.num), 'bin', 'bw'), envir=my_env) } else if (diagram[", j, "] == 'color binned heatmap') { assign(fni", letters[j], ", pp_basicgraph(data, colnames(pp[sapply(pp, is.numeric)][j]), colnames(pp[sapply(pp, is.factor)][i]), pp_size = 1/ncol(data.num), 'bin', 'color'), envir=my_env) } else if (diagram[", j, "] == 'violin plot') { assign(fni", letters[j], ", pp_basicgraph(data, colnames(pp[sapply(pp, is.factor)][i]), colnames(pp[sapply(pp, is.numeric)][j]), pp_size = 1/ncol(data.num), 'violin'), envir=my_env) } else if (diagram[", j, "] == 'filled violin plot') { assign(fni", letters[j], ", pp_basicgraph(data, colnames(pp[sapply(pp, is.factor)][i]), colnames(pp[sapply(pp, is.numeric)][j]), pp_size = 1/ncol(data.num), 'violin filled'), envir=my_env) } else if (diagram[", j, "] == 'box plot') { assign(fni", letters[j], ", pp_basicgraph(data, colnames(pp[sapply(pp, is.factor)][i]), colnames(pp[sapply(pp, is.numeric)][j]), pp_size = 1/ncol(data.num), 'box'), envir=my_env) }")))} line <- eval(parse( text=paste0("paste0('gridExtra::grid.arrange(' ,", paste0(" fni", letters[1:ncol(data.num)], collapse = ",', ',"), ",', ncol=", ncol(data.num), ")')"))) write(paste0(" write(line, file.path(dir, "brinton_outcomes", "matrixplot.R"), append=TRUE) write(" } facnum.plot(cbind(data.num, data.fac)) } } else if (length(data[sapply(data, is.numeric)])>0 && length(data[sapply(data, is.ordered)])>0 && any(dataclass %in% "numeric") && any(dataclass %in% c("ordered")) && (diagram %in% matrixplot_ord.num) == TRUE) { data.num <- data[sapply(data, is.numeric)] data.ord <- data[sapply(data, is.ordered)] rownames(data.ord) <- NULL diagram <- rep(diagram, ncol(data.num)) out = NULL for (i in seq_along(data.ord)) { for (j in seq_along(data.num)) {eval(parse(text=paste0("oni", letters[j], " <- paste0('on', ", i, ", '", letters[j],"')")))} ordnum.plot <- function(pp) { long <- round(length(unique(pp[sapply(pp, is.ordered)][[i]]))/6 + 0.6, 1) for (j in seq_along(data.num)) {eval(parse(text=paste0(" if (diagram[", j, "] == 'path graph') { assign(oni", letters[j], ", pp_basicgraph(data, colnames(pp[sapply(pp, is.numeric)][j]), colnames(pp[sapply(pp, is.factor)][i]), pp_size = 1/ncol(data.num), 'line'), envir=my_env) } else if (diagram[", j, "] == 'point graph') { assign(oni", letters[j], ", pp_basicgraph(data, colnames(pp[sapply(pp, is.numeric)][j]), colnames(pp[sapply(pp, is.factor)][i]), pp_size = 1/ncol(data.num), 'point'), envir=my_env) } else if (diagram[", j, "] == 'tile plot') { assign(oni", letters[j], ", pp_basicgraph(data, colnames(pp[sapply(pp, is.numeric)][j]), colnames(pp[sapply(pp, is.factor)][i]), pp_size = 1/ncol(data.num), 'tile'), envir=my_env) } else if (diagram[", j, "] == 'binned heatmap') { assign(oni", letters[j], ", pp_basicgraph(data, colnames(pp[sapply(pp, is.numeric)][j]), colnames(pp[sapply(pp, is.factor)][i]), pp_size = 1/ncol(data.num), 'bin', 'black'), envir=my_env) } else if (diagram[", j, "] == 'bw binned heatmap') { assign(oni", letters[j], ", pp_basicgraph(data, colnames(pp[sapply(pp, is.numeric)][j]), colnames(pp[sapply(pp, is.factor)][i]), pp_size = 1/ncol(data.num), 'bin', 'bw'), envir=my_env) } else if (diagram[", j, "] == 'color binned heatmap') { assign(oni", letters[j], ", pp_basicgraph(data, colnames(pp[sapply(pp, is.numeric)][j]), colnames(pp[sapply(pp, is.factor)][i]), pp_size = 1/ncol(data.num), 'bin', 'color'), envir=my_env) } else if (diagram[", j, "] == 'violin plot') { assign(oni", letters[j], ", pp_basicgraph(data, colnames(pp[sapply(pp, is.factor)][i]), colnames(pp[sapply(pp, is.numeric)][j]), pp_size = 1/ncol(data.num), 'violin'), envir=my_env) } else if (diagram[", j, "] == 'filled violin plot') { assign(oni", letters[j], ", pp_basicgraph(data, colnames(pp[sapply(pp, is.factor)][i]), colnames(pp[sapply(pp, is.numeric)][j]), pp_size = 1/ncol(data.num), 'violin filled'), envir=my_env) } else if (diagram[", j, "] == 'box plot') { assign(oni", letters[j], ", pp_basicgraph(data, colnames(pp[sapply(pp, is.factor)][i]), colnames(pp[sapply(pp, is.numeric)][j]), pp_size = 1/ncol(data.num), 'box'), envir=my_env) }")))} line <- eval(parse( text=paste0("paste0('gridExtra::grid.arrange(' ,", paste0(" oni", letters[1:ncol(data.num)], collapse = ",', ',"), ",', ncol=", ncol(data.num), ")')"))) write(paste0(" write(line, file.path(dir, "brinton_outcomes", "matrixplot.R"), append=TRUE) write(" } ordnum.plot(cbind(data.num, data.ord)) } } else if (length(data[sapply(data, is.ordered)])>1 && identical(dataclass, c("ordered", "ordered")) && (diagram %in% ord.ord_v0) == TRUE) { data.ord <- data[sapply(data, is.ordered)] diagram <- rep(diagram, ncol(data.ord)) out = NULL for (i in seq_along(data.ord)[2:ncol(data.ord)]) { GAheight <- length(unique(data.ord[,(i)]))/5+0.5 write(paste0(" for (j in seq_along(data.ord)[c(1:i-1)]) {eval(parse(text=paste0("ooi", letters[j], " <- paste0('oo', ", i, ", '", letters[j],"')")))} ord.plot <- function(pp) { for (j in seq_along(data.ord)[c(1:i-1)]) {eval(parse(text=paste0(" if (diagram[", j, "] == 'bw stacked bar graph') { assign(ooi", letters[j], ", pp_stackedbar(data, colnames(pp[i]), colnames(pp[j]), 'bw', 'stack', 'ordinal'), envir=my_env) } else if (diagram[", j, "] == 'color stacked bar graph') { assign(ooi", letters[j], ", pp_stackedbar(data, colnames(pp[i]), colnames(pp[j]), 'color', 'stack', 'ordinal'), envir=my_env) } else if (diagram[", j, "] == 'bw 100% stacked bar graph') { assign(ooi", letters[j], ", pp_stackedbar(data, colnames(pp[i]), colnames(pp[j]), 'bw', 'fill', 'ordinal'), envir=my_env) } else if (diagram[", j, "] == 'color 100% stacked bar graph') { assign(ooi", letters[j], ", pp_stackedbar(data, colnames(pp[i]), colnames(pp[j]), 'color', 'fill', 'ordinal'), envir=my_env) }"))) eval(parse(text=paste0("assign('blank', blank(data, colnames(pp[i])), envir=my_env) "))) } line <- eval(parse( text=paste0("paste0('gridExtra::grid.arrange(' ,", paste0(" ooi", letters[1:i-1], collapse = ",', ',"), ",', ncol=", ncol(data.ord)-1, ")')"))) write(line, file.path(dir, "brinton_outcomes", "matrixplot.R"), append=TRUE) } ord.plot(data.ord) } } else if (length(data[sapply(data, is.ordered)])>1 && identical(dataclass, c("ordered", "ordered")) && (diagram %in% ord.ord_v1) == TRUE) { data.ord <- data[sapply(data, is.ordered)] data.ord <- data.ord[, c(ncol(data.ord), 1:ncol(data.ord)-1)] diagram <- rep(diagram, ncol(data.ord)) out = NULL for (i in seq_along(data.ord)[2:ncol(data.ord)]) { GAheight <- length(unique(data.ord[,(i)]))/5+0.5 write(paste0(" for (j in seq_along(data.ord)[c(1:i-1)]) {eval(parse(text=paste0("ooi", letters[j], " <- paste0('oo', ", i, ", '", letters[j],"')")))} ord.plot <- function(pp) { for (j in seq_along(data.ord)[c(1:i-1)]) {eval(parse(text=paste0(" if (diagram[", j, "] == 'transposed bw stacked bar graph') { assign(ooi", letters[j], ", pp_stackedbar(data, colnames(pp[i]), colnames(pp[j]), 'bw', 'stack', 'ordinal'), envir=my_env) } else if (diagram[", j, "] == 'transposed color stacked bar graph') { assign(ooi", letters[j], ", pp_stackedbar(data, colnames(pp[i]), colnames(pp[j]), 'color', 'stack', 'ordinal'), envir=my_env) } else if (diagram[", j, "] == 'transposed bw 100% stacked bar graph') { assign(ooi", letters[j], ", pp_stackedbar(data, colnames(pp[i]), colnames(pp[j]), 'bw', 'fill', 'ordinal'), envir=my_env) } else if (diagram[", j, "] == 'transposed color 100% stacked bar graph') { assign(ooi", letters[j], ", pp_stackedbar(data, colnames(pp[i]), colnames(pp[j]), 'color', 'fill', 'ordinal'), envir=my_env) }"))) eval(parse(text=paste0("assign('blank', blank(data, colnames(pp[i])), envir=my_env) "))) } line <- eval(parse( text=paste0("paste0('gridExtra::grid.arrange(' ,", paste0(" ooi", letters[1:i-1], collapse = ",', ',"), ",', ncol=", ncol(data.ord)-1, ")')"))) write(line, file.path(dir, "brinton_outcomes", "matrixplot.R"), append=TRUE) } ord.plot(data.ord) } } else if (length(data[sapply(data, is.ordered)])>1 && identical(dataclass, c("ordered", "ordered")) && (diagram %in% ord.ord_v2) == TRUE) { data.ord <- data[sapply(data, is.ordered)] diagram <- rep(diagram, ncol(data.ord)) out = NULL for (i in seq_along(data.ord)[2:ncol(data.ord)]) { GAheight <- length(unique(data.ord[,(i)]))/5+1.5 write(paste0(" for (j in seq_along(data.ord)[c(1:i-1)]) {eval(parse(text=paste0("ooi", letters[j], " <- paste0('oo', ", i, ", '", letters[j],"')")))} ord.plot <- function(pp) { for (j in seq_along(data.ord)[c(1:i-1)]) {eval(parse(text=paste0(" if (diagram[", j, "] == 'bw heatmap') { assign(ooi", letters[j], ", pp_contingency(data, colnames(pp[j]), colnames(pp[i]), 'bw', 'observed'), envir=my_env) } else if (diagram[", j, "] == 'color heatmap') { assign(ooi", letters[j], ", pp_contingency(data, colnames(pp[j]), colnames(pp[i]), 'color', 'observed'), envir=my_env) } else if (diagram[", j, "] == 'color residuals heatmap') { assign(ooi", letters[j], ", pp_contingency(data, colnames(pp[j]), colnames(pp[i]), 'color', 'residuals'), envir=my_env) } else if (diagram[", j, "] == 'bw contribution to x2 heatmap') { assign(ooi", letters[j], ", pp_contingency(data, colnames(pp[j]), colnames(pp[i]), 'bw', 'contrib'), envir=my_env) } else if (diagram[", j, "] == 'color contribution to x2 heatmap') { assign(ooi", letters[j], ", pp_contingency(data, colnames(pp[j]), colnames(pp[i]), 'color', 'contrib'), envir=my_env) } else if (diagram[", j, "] == 'bw balloon plot') { assign(ooi", letters[j], ", pp_contingency(data, colnames(pp[j]), colnames(pp[i]), 'bw', 'observed', pp_geom = 'point'), envir=my_env) } else if (diagram[", j, "] == 'color balloon plot') { assign(ooi", letters[j], ", pp_contingency(data, colnames(pp[j]), colnames(pp[i]), 'color', 'observed', pp_geom = 'point'), envir=my_env) } else if (diagram[", j, "] == 'color residuals balloon plot') { assign(ooi", letters[j], ", pp_contingency(data, colnames(pp[j]), colnames(pp[i]), 'color', 'residuals', pp_geom = 'point'), envir=my_env) } else if (diagram[", j, "] == 'bw contribution to x2 balloon plot') { assign(ooi", letters[j], ", pp_contingency(data, colnames(pp[j]), colnames(pp[i]), 'bw', 'contrib', pp_geom = 'point'), envir=my_env) } else if (diagram[", j, "] == 'color contribution to x2 balloon plot') { assign(ooi", letters[j], ", pp_contingency(data, colnames(pp[j]), colnames(pp[i]), 'color', 'contrib', pp_geom = 'point'), envir=my_env) }"))) eval(parse(text=paste0("assign('blank', blank(data, colnames(pp[i])), envir=my_env) "))) } line <- eval(parse( text=paste0("paste0('gridExtra::grid.arrange(' ,", paste0(" ooi", letters[1:i-1], collapse = ",', ',"), ",', ncol=", ncol(data.ord)-1, ")')"))) write(line, file.path(dir, "brinton_outcomes", "matrixplot.R"), append=TRUE) } ord.plot(data.ord) } } else if (length(data[sapply(data, is.factor)][!sapply(data[sapply(data, is.factor)], is.ordered)])>1 && identical(dataclass, c("factor", "factor")) && (diagram %in% fac.fac_v0) == TRUE) { data.fac <- data[sapply(data, is.factor)][!sapply(data[sapply(data, is.factor)], is.ordered)] diagram <- rep(diagram, ncol(data.fac)) out = NULL for (i in seq_along(data.fac)[2:ncol(data.fac)]) { GAheight <- length(unique(data.fac[,(i)]))/5+0.5 write(paste0(" for (j in seq_along(data.fac)[c(1:i-1)]) {eval(parse(text=paste0("ffi", letters[j], " <- paste0('ff', ", i, ", '", letters[j],"')")))} fac.plot <- function(pp) { for (j in seq_along(data.fac)[c(1:i-1)]) {eval(parse(text=paste0(" if (diagram[", j, "] == 'color stacked bar graph') { assign(ffi", letters[j], ", pp_stackedbar(data, colnames(pp[i]), colnames(pp[j]), 'color', 'stack'), envir=my_env) } else if (diagram[", j, "] == 'color 100% stacked bar graph') { assign(ffi", letters[j], ", pp_stackedbar(data, colnames(pp[i]), colnames(pp[j]), 'color', 'fill'), envir=my_env) }"))) eval(parse(text=paste0("assign('blank', blank(data, colnames(pp[i])), envir=my_env) "))) } line <- eval(parse( text=paste0("paste0('gridExtra::grid.arrange(' ,", paste0(" ffi", letters[1:i-1], collapse = ",', ',"), ",', ncol=", ncol(data.fac)-1, ")')"))) write(line, file.path(dir, "brinton_outcomes", "matrixplot.R"), append=TRUE) } fac.plot(data.fac) } } else if (length(data[sapply(data, is.factor)][!sapply(data[sapply(data, is.factor)], is.ordered)])>1 && identical(dataclass, c("factor", "factor")) && (diagram %in% fac.fac_v1) == TRUE) { data.fac <- data[sapply(data, is.factor)][!sapply(data[sapply(data, is.factor)], is.ordered)] data.fac <- data.fac[, c(ncol(data.fac), 1:ncol(data.fac)-1)] diagram <- rep(diagram, ncol(data.fac)) out = NULL for (i in seq_along(data.fac)[2:ncol(data.fac)]) { GAheight <- length(unique(data.fac[,(i)]))/5+0.5 write(paste0(" for (j in seq_along(data.fac)[c(1:i-1)]) {eval(parse(text=paste0("ffi", letters[j], " <- paste0('ff', ", i, ", '", letters[j],"')")))} fac.plot <- function(pp) { for (j in seq_along(data.fac)[c(1:i-1)]) {eval(parse(text=paste0(" if (diagram[", j, "] == 'transposed color stacked bar graph') { assign(ffi", letters[j], ", pp_stackedbar(data, colnames(pp[i]), colnames(pp[j]), 'color', 'stack'), envir=my_env) } else if (diagram[", j, "] == 'transposed color 100% stacked bar graph') { assign(ffi", letters[j], ", pp_stackedbar(data, colnames(pp[i]), colnames(pp[j]), 'color', 'fill'), envir=my_env) }"))) eval(parse(text=paste0("assign('blank', blank(data, colnames(pp[i])), envir=my_env) "))) } line <- eval(parse( text=paste0("paste0('gridExtra::grid.arrange(' ,", paste0(" ffi", letters[1:i-1], collapse = ",', ',"), ",', ncol=", ncol(data.fac)-1, ")')"))) write(line, file.path(dir, "brinton_outcomes", "matrixplot.R"), append=TRUE) } fac.plot(data.fac) } } else if (length(data[sapply(data, is.factor)][!sapply(data[sapply(data, is.factor)], is.ordered)])>1 && identical(dataclass, c("factor", "factor")) && (diagram %in% fac.fac_v2) == TRUE) { data.fac <- data[sapply(data, is.factor)][!sapply(data[sapply(data, is.factor)], is.ordered)] data.fac <- data.fac[, c(ncol(data.fac), 1:ncol(data.fac)-1)] diagram <- rep(diagram, ncol(data.fac)) out = NULL for (i in seq_along(data.fac)[2:ncol(data.fac)]) { GAheight <- length(unique(data.fac[,(i)]))/5+1.5 write(paste0(" for (j in seq_along(data.fac)[c(1:i-1)]) {eval(parse(text=paste0("ffi", letters[j], " <- paste0('ff', ", i, ", '", letters[j],"')")))} fac.plot <- function(pp) { for (j in seq_along(data.fac)[c(1:i-1)]) {eval(parse(text=paste0(" if (diagram[", j, "] == 'bw heatmap') { assign(ffi", letters[j], ", pp_contingency(data, colnames(pp[j]), colnames(pp[i]), 'bw', 'observed'), envir=my_env) } else if (diagram[", j, "] == 'color heatmap') { assign(ffi", letters[j], ", pp_contingency(data, colnames(pp[j]), colnames(pp[i]), 'color', 'observed'), envir=my_env) } else if (diagram[", j, "] == 'color residuals heatmap') { assign(ffi", letters[j], ", pp_contingency(data, colnames(pp[j]), colnames(pp[i]), 'color', 'residuals'), envir=my_env) } else if (diagram[", j, "] == 'bw contribution to x2 heatmap') { assign(ffi", letters[j], ", pp_contingency(data, colnames(pp[j]), colnames(pp[i]), 'bw', 'contrib'), envir=my_env) } else if (diagram[", j, "] == 'color contribution to x2 heatmap') { assign(ffi", letters[j], ", pp_contingency(data, colnames(pp[j]), colnames(pp[i]), 'color', 'contrib'), envir=my_env) } else if (diagram[", j, "] == 'bw balloon plot') { assign(ffi", letters[j], ", pp_contingency(data, colnames(pp[j]), colnames(pp[i]), 'bw', 'observed', pp_geom = 'point'), envir=my_env) } else if (diagram[", j, "] == 'color balloon plot') { assign(ffi", letters[j], ", pp_contingency(data, colnames(pp[j]), colnames(pp[i]), 'color', 'observed', pp_geom = 'point'), envir=my_env) } else if (diagram[", j, "] == 'color residuals balloon plot') { assign(ffi", letters[j], ", pp_contingency(data, colnames(pp[j]), colnames(pp[i]), 'color', 'residuals', pp_geom = 'point'), envir=my_env) } else if (diagram[", j, "] == 'bw contribution to x2 balloon plot') { assign(ffi", letters[j], ", pp_contingency(data, colnames(pp[j]), colnames(pp[i]), 'bw', 'contrib', pp_geom = 'point'), envir=my_env) } else if (diagram[", j, "] == 'color contribution to x2 balloon plot') { assign(ffi", letters[j], ", pp_contingency(data, colnames(pp[j]), colnames(pp[i]), 'color', 'contrib', pp_geom = 'point'), envir=my_env) }"))) eval(parse(text=paste0("assign('blank', blank(data, colnames(pp[i])), envir=my_env) "))) } line <- eval(parse( text=paste0("paste0('gridExtra::grid.arrange(' ,", paste0(" ffi", letters[1:i-1], collapse = ",', ',"), ",', ncol=", ncol(data.fac)-1, ")')"))) write(line, file.path(dir, "brinton_outcomes", "matrixplot.R"), append=TRUE) } fac.plot(data.fac) } } else if (length(data[sapply(data, is.ordered)])>0 && length(data[sapply(data, is.factor)][!sapply(data[sapply(data, is.factor)], is.ordered)])>0 && any(dataclass %in% "ordered") && any(dataclass %in% "factor") && (diagram %in% fac.ord_v0) == TRUE) { data.ord <- data[sapply(data, is.ordered)] data.fac <- data[sapply(data, is.factor)][!sapply(data[sapply(data, is.factor)], is.ordered)] rownames(data.fac) <- NULL diagram <- rep(diagram, ncol(data.ord)) out = NULL for (i in seq_along(data.fac)) { GAheight <- length(unique(data.fac[,(i)]))/5+0.5 write(paste0(" for (j in seq_along(data.ord)) {eval(parse(text=paste0("ofi", letters[j], " <- paste0('of', ", i, ", '", letters[j],"')")))} facnum.plot <- function(pp) { long <- round(length(unique(pp[sapply(pp, is.factor)][[i]]))/6 + 0.6, 1) for (j in seq_along(data.ord)) {eval(parse(text=paste0(" if (diagram[", j, "] == 'bw stacked bar graph') { assign(ofi", letters[j], ", pp_stackedbar(data, colnames(pp[sapply(pp, is.factor)][!sapply(pp[sapply(pp, is.factor)], is.ordered)][i]), colnames(pp[sapply(pp, is.ordered)][j]), 'bw', 'stack', 'ordinal'), envir=my_env) } else if (diagram[", j, "] == 'color stacked bar graph') { assign(ofi", letters[j], ", pp_stackedbar(data, colnames(pp[sapply(pp, is.factor)][!sapply(pp[sapply(pp, is.factor)], is.ordered)][i]), colnames(pp[sapply(pp, is.ordered)][j]), 'color', 'stack', 'ordinal'), envir=my_env) } else if (diagram[", j, "] == 'bw 100% stacked bar graph') { assign(ofi", letters[j], ", pp_stackedbar(data, colnames(pp[sapply(pp, is.factor)][!sapply(pp[sapply(pp, is.factor)], is.ordered)][i]), colnames(pp[sapply(pp, is.ordered)][j]), 'bw', 'fill', 'ordinal'), envir=my_env) } else if (diagram[", j, "] == 'color 100% stacked bar graph') { assign(ofi", letters[j], ", pp_stackedbar(data, colnames(pp[sapply(pp, is.factor)][!sapply(pp[sapply(pp, is.factor)], is.ordered)][i]), colnames(pp[sapply(pp, is.ordered)][j]), 'color', 'fill', 'ordinal'), envir=my_env) }")))} line <- eval(parse( text=paste0("paste0('gridExtra::grid.arrange(' ,", paste0(" ofi", letters[1:ncol(data.ord)], collapse = ",', ',"), ",', ncol=", ncol(data.ord), ")')"))) write(line, file.path(dir, "brinton_outcomes", "matrixplot.R"), append=TRUE) write(" } facnum.plot(cbind(data.ord, data.fac)) } } else if (length(data[sapply(data, is.ordered)])>0 && length(data[sapply(data, is.factor)][!sapply(data[sapply(data, is.factor)], is.ordered)])>0 && any(dataclass %in% "ordered") && any(dataclass %in% "factor") && (diagram %in% fac.ord_v1) == TRUE) { data.ord <- data[sapply(data, is.ordered)] data.fac <- data[sapply(data, is.factor)][!sapply(data[sapply(data, is.factor)], is.ordered)] rownames(data.ord) <- NULL diagram <- rep(diagram, ncol(data.fac)) out = NULL for (i in seq_along(data.ord)) { GAheight <- length(unique(data.ord[,(i)]))/5+0.5 write(paste0(" for (j in seq_along(data.fac)) {eval(parse(text=paste0("ofi", letters[j], " <- paste0('of', ", i, ", '", letters[j],"')")))} facnum.plot <- function(pp) { long <- round(length(unique(pp[sapply(pp, is.factor)][[i]]))/6 + 0.6, 1) for (j in seq_along(data.fac)) {eval(parse(text=paste0(" if (diagram[", j, "] == 'transposed color stacked bar graph') { assign(ofi", letters[j], ", pp_stackedbar(data, colnames(pp[sapply(pp, is.ordered)][i]), colnames(pp[sapply(pp, is.factor)][!sapply(pp[sapply(pp, is.factor)], is.ordered)][j]), 'color', 'stack'), envir=my_env) } else if (diagram[", j, "] == 'transposed color 100% stacked bar graph') { assign(ofi", letters[j], ", pp_stackedbar(data, colnames(pp[sapply(pp, is.ordered)][i]), colnames(pp[sapply(pp, is.factor)][!sapply(pp[sapply(pp, is.factor)], is.ordered)][j]), 'color', 'fill'), envir=my_env) }")))} line <- eval(parse( text=paste0("paste0('gridExtra::grid.arrange(' ,", paste0(" ofi", letters[1:ncol(data.fac)], collapse = ",', ',"), ",', ncol=", ncol(data.fac), ")')"))) write(line, file.path(dir, "brinton_outcomes", "matrixplot.R"), append=TRUE) write(" } facnum.plot(cbind(data.ord, data.fac)) } } else if (length(data[sapply(data, is.ordered)])>0 && length(data[sapply(data, is.factor)][!sapply(data[sapply(data, is.factor)], is.ordered)])>0 && any(dataclass %in% "ordered") && any(dataclass %in% "factor") && (diagram %in% fac.ord_v2) == TRUE) { data.ord <- data[sapply(data, is.ordered)] data.fac <- data[sapply(data, is.factor)][!sapply(data[sapply(data, is.factor)], is.ordered)] rownames(data.fac) <- NULL diagram <- rep(diagram, ncol(data.ord)) out = NULL for (i in seq_along(data.fac)) { GAheight <- length(unique(data.fac[,(i)]))/5+1.5 write(paste0(" for (j in seq_along(data.ord)) {eval(parse(text=paste0("ofi", letters[j], " <- paste0('of', ", i, ", '", letters[j],"')")))} facnum.plot <- function(pp) { long <- round(length(unique(pp[sapply(pp, is.factor)][[i]]))/6 + 0.6, 1) for (j in seq_along(data.ord)) {eval(parse(text=paste0(" if (diagram[", j, "] == 'bw heatmap') { assign(ofi", letters[j], ", pp_contingency(data, colnames(pp[sapply(pp, is.ordered)][j]), colnames(pp[sapply(pp, is.factor)][!sapply(pp[sapply(pp, is.factor)], is.ordered)][i]), 'bw', 'observed'), envir=my_env) } else if (diagram[", j, "] == 'color heatmap') { assign(ofi", letters[j], ", pp_contingency(data, colnames(pp[sapply(pp, is.ordered)][j]), colnames(pp[sapply(pp, is.factor)][!sapply(pp[sapply(pp, is.factor)], is.ordered)][i]), 'color', 'observed'), envir=my_env) } else if (diagram[", j, "] == 'color residuals heatmap') { assign(ofi", letters[j], ", pp_contingency(data, colnames(pp[sapply(pp, is.ordered)][j]), colnames(pp[sapply(pp, is.factor)][!sapply(pp[sapply(pp, is.factor)], is.ordered)][i]), 'color', 'residuals'), envir=my_env) } else if (diagram[", j, "] == 'bw contribution to x2 heatmap') { assign(ofi", letters[j], ", pp_contingency(data, colnames(pp[sapply(pp, is.ordered)][j]), colnames(pp[sapply(pp, is.factor)][!sapply(pp[sapply(pp, is.factor)], is.ordered)][i]), 'bw', 'contrib'), envir=my_env) } else if (diagram[", j, "] == 'color contribution to x2 heatmap') { assign(ofi", letters[j], ", pp_contingency(data, colnames(pp[sapply(pp, is.ordered)][j]), colnames(pp[sapply(pp, is.factor)][!sapply(pp[sapply(pp, is.factor)], is.ordered)][i]), 'color', 'contrib'), envir=my_env) } else if (diagram[", j, "] == 'bw balloon plot') { assign(ofi", letters[j], ", pp_contingency(data, colnames(pp[sapply(pp, is.ordered)][j]), colnames(pp[sapply(pp, is.factor)][!sapply(pp[sapply(pp, is.factor)], is.ordered)][i]), 'bw', 'observed', pp_geom = 'point'), envir=my_env) } else if (diagram[", j, "] == 'color balloon plot') { assign(ofi", letters[j], ", pp_contingency(data, colnames(pp[sapply(pp, is.ordered)][j]), colnames(pp[sapply(pp, is.factor)][!sapply(pp[sapply(pp, is.factor)], is.ordered)][i]), 'color', 'observed', pp_geom = 'point'), envir=my_env) } else if (diagram[", j, "] == 'color residuals balloon plot') { assign(ofi", letters[j], ", pp_contingency(data, colnames(pp[sapply(pp, is.ordered)][j]), colnames(pp[sapply(pp, is.factor)][!sapply(pp[sapply(pp, is.factor)], is.ordered)][i]), 'color', 'residuals', pp_geom = 'point'), envir=my_env) } else if (diagram[", j, "] == 'bw contribution to x2 balloon plot') { assign(ofi", letters[j], ", pp_contingency(data, colnames(pp[sapply(pp, is.ordered)][j]), colnames(pp[sapply(pp, is.factor)][!sapply(pp[sapply(pp, is.factor)], is.ordered)][i]), 'bw', 'contrib', pp_geom = 'point'), envir=my_env) } else if (diagram[", j, "] == 'color contribution to x2 balloon plot') { assign(ofi", letters[j], ", pp_contingency(data, colnames(pp[sapply(pp, is.ordered)][j]), colnames(pp[sapply(pp, is.factor)][!sapply(pp[sapply(pp, is.factor)], is.ordered)][i]), 'color', 'contrib', pp_geom = 'point'), envir=my_env) }")))} line <- eval(parse( text=paste0("paste0('gridExtra::grid.arrange(' ,", paste0(" ofi", letters[1:ncol(data.ord)], collapse = ",', ',"), ",', ncol=", ncol(data.ord), ")')"))) write(line, file.path(dir, "brinton_outcomes", "matrixplot.R"), append=TRUE) write(" } facnum.plot(cbind(data.ord, data.fac)) } } else {stop("The combination of these data and graphic type has not been still considered, or maybe the data does not include the types of data considered by the 'dataclass' argument, or maybe the data does not have two columns of the dataclass set.")} } else {stop(warning_wp_dc)} rmarkdown::render(file.path(dir, "brinton_outcomes", "matrixplot.R", fsep = .Platform$file.sep), "html_document", envir=my_env) pander::openFileInOS(file.path(dir, "brinton_outcomes", "matrixplot.html", fsep = .Platform$file.sep)) }
[ { "title": "Durban R Users Group Meetup: 24 February 2016 @ The Green Door", "href": "http://datascience-africa.org/2016/02/260/" }, { "title": "Le Monde puzzle [ "href": "https://xianblog.wordpress.com/2013/11/30/le-monde-puzzle-842/" }, { "title": "By: Super Nerdy Cool » Build multiarch R (32 bit and 64 bit) on Debian/Ubuntu", "href": "http://blog.nguyenvq.com/blog/2011/07/11/r-from-source/comment-page-1/" }, { "title": "October 24: 4th MilanoR meeting. Agenda", "href": "http://www.milanor.net/blog/october-24-4th-milanor-meeting-agenda/" }, { "title": "Webinar: Big-Data Trees for R", "href": "http://blog.revolutionanalytics.com/2014/04/webinar-big-data-trees-for-r.html" }, { "title": "The Good oL’ Titanic Kaggle Competition pt. 1", "href": "http://www.numbrcrunch.com/blog/the-good-ol-titanic-kaggle-competition-pt-1" }, { "title": "Minimalist Maps", "href": "http://freakonometrics.hypotheses.org/20241" }, { "title": "How many more R-bloggers posts can I expect?", "href": "http://www.magesblog.com/2014/01/how-many-more-r-bloggers-posts-can-i.html" }, { "title": "R/Finance 2009 Overview", "href": "https://feedproxy.google.com/~r/FossTrading/~3/mdBDXTSE4Eo/rfinance-2009-overview.html" }, { "title": "Twitter at conferences", "href": "http://chem-bla-ics.blogspot.com/2015/11/twitter-at-conferences.html" }, { "title": "Kenneth French Gift to the Finance World", "href": "http://timelyportfolio.blogspot.com/2011/06/kenneth-french-gift-to-finance-world.html" }, { "title": "Installing and Starting SparkR Locally on Windows OS and RStudio", "href": "https://web.archive.org/web/http://blog.sparkiq-labs.com/2015/07/26/installing-and-starting-sparkr-locally-on-windows-os-and-rstudio/" }, { "title": "Timezone conversion in R", "href": "https://web.archive.org/web/http://blog.anomdev.com/2016/07/26/227/" }, { "title": "Serious stats companion web site now live: sample chapter, data and R scripts", "href": "https://seriousstats.wordpress.com/2012/03/23/serious-stats-companion-web-site-now-live/" }, { "title": "Ross Ihaka in Sunday Star Times", "href": "http://blog.revolutionanalytics.com/2010/07/ross-ihaka-in-sunday-star-times.html" }, { "title": "Load PostGIS geometries in R without rgdal", "href": "http://geospatial.commons.gc.cuny.edu/2014/01/14/load-postgis-geometries-in-r-without-rgdal/" }, { "title": "Importing Generic Function from Other Package: A Tip on Writing a R Package", "href": "http://yusung.blogspot.com/2009/01/importing-generic-function-from-other.html" }, { "title": "SSH tunnels on Windows for R", "href": "https://itsalocke.com/ssh-tunnels-windows-r/" }, { "title": "Statisticians at JSM consider themselves \"Data Scientists\"", "href": "http://blog.revolutionanalytics.com/2011/08/statisticians-at-jsm-consider-themselves-data-scientists.html" }, { "title": "Common R Programming Errors Faced by Beginners", "href": "https://www.quantinsti.com/blog/common-errors-r/" }, { "title": "First Derivative of the Multivariate Normal Densities with RcppArmadillo", "href": "http://gallery.rcpp.org/articles/dmvnorm-deriv-arma/" }, { "title": "Slides from Rcpp talk in Sydney", "href": "http://dirk.eddelbuettel.com/blog/2013/07/13/" }, { "title": "Free Stanford online course on Statistical Learning (with R) starting on 19 Jan 2015", "href": "https://rdatamining.wordpress.com/2014/11/21/free-stanford-online-course-on-statistical-learning-with-r-starting-on-19-jan-2015/" }, { "title": "Should you teach Python or R for data science?", "href": "http://www.dataschool.io/python-or-r-for-data-science/" }, { "title": "Running RStudio on Digital Ocean, AWS etc Using Tutum and Docker Containers", "href": "https://blog.ouseful.info/2015/06/24/running-rstudio-on-digital-ocean-aws-etc-using-tutum-and-docker-containers/" }, { "title": "Interview with a forced convert from Matlab to R", "href": "http://www.burns-stat.com/interview-with-a-forced-convert-from-matlab-to-r/?utm_source=rss&utm_medium=rss&utm_campaign=interview-with-a-forced-convert-from-matlab-to-r" }, { "title": "Stochastic reserving with R: ChainLadder 0.1.5-1 released", "href": "http://www.magesblog.com/2011/11/stochastic-reserving-with-r-chainladder.html" }, { "title": "Un-Wrapping a Sphere with R", "href": "https://casoilresource.lawr.ucdavis.edu/" }, { "title": "Hofstader’s Chaotic Sequence", "href": "https://web.archive.org/web/http://playingwithr.blogspot.com/2011/04/hofstaders-chaotic-sequence.html" }, { "title": "SAS vs Open Source", "href": "http://blog.revolutionanalytics.com/2010/10/sas-vs-open-source.html" }, { "title": "Installing R/RStudio on Ubuntu 14.04", "href": "http://www.thertrader.com/2014/09/22/installing-rrstudio-on-ubuntu-14-04/" }, { "title": "Not only CRAN downloads and Shiny … but also .. rCharts", "href": "http://www.premiersoccerstats.com/wordpress/?p=1413" }, { "title": "Example 8.11: violin plots", "href": "https://feedproxy.google.com/~r/SASandR/~3/_1yl_6LFQyw/example-811-violin-plots.html" }, { "title": "Now you can start every R tutorial for free @DataCamp", "href": "https://www.datacamp.com/community/blog/now-can-start-every-r-tutorial-free-datacamp" }, { "title": "Time series equivalence of brains and markets", "href": "https://feedproxy.google.com/~r/PortfolioProbeRLanguage/~3/koL-g5LJFUI/" }, { "title": "Re-introducing Radiant: A shiny interface for R", "href": "http://vnijs.github.io/blog/2016/09/re-introducing-radiant.html" }, { "title": "Revolution Newsletter: June 2012", "href": "http://blog.revolutionanalytics.com/2012/06/revolution-newsletter-june-2012.html" }, { "title": "The R Journal (Volume 3/2, December 2011) is out", "href": "https://www.r-bloggers.com/the-r-journal-volume-32-december-2011-is-out/" }, { "title": "Life expectancy and retirement age in USA", "href": "http://blog.revolutionanalytics.com/2013/01/life-expectancy-and-retirement-age-in-usa.html" }, { "title": "Extracting the Epidemic Model: Going Beyond Florence Nightingale Part II", "href": "http://perfdynamics.blogspot.com/2013/02/extracting-epidemic-model-going-beyond.html" }, { "title": "getting ICES 1903-1949 catch statistics into R", "href": "http://fishvice.blogspot.com/2012/01/getting-ices-1903-1949-catch-statistics.html" }, { "title": "Change in temperature in Netherlands over the last century", "href": "http://wiekvoet.blogspot.com/2014/11/change-in-temperature-in-netherlands.html" }, { "title": "Analyzing the 2011-2012 California Health Inteview Survey with R", "href": "http://blog.ryanwalker.us/2014/06/analyzing-2011-2012-california-health.html" }, { "title": "Saving the world with R", "href": "https://web.archive.org/web/http://blog.revolution-computing.com/2010/04/saving-the-world-with-r.html" }, { "title": "OpenCPU release 1.4.6: gzip and systemd", "href": "https://www.opencpu.org/posts/opencpu-release-1-4-6/" }, { "title": "Review: Kölner R Meeting 5 October 2012", "href": "https://feedproxy.google.com/~r/blogspot/rKuKM/~3/OvOYWBMPido/review-kolner-r-meeting-5-october-2012.html" }, { "title": "Outlawing Gay Marriage", "href": "http://www.johnmyleswhite.com/notebook/2010/01/10/outlawing-gay-marriage/" }, { "title": "SAS PROC MCMC example in R: Nonlinear Poisson Regression Multilevel Random-Effects Model", "href": "http://wiekvoet.blogspot.com/2015/03/sas-proc-mcmc-example-in-r-nonlinear.html" }, { "title": "Comparison between 15 different cities…", "href": "http://using-r-project.blogspot.com/2009/09/comparison-between-15-different-cities.html" }, { "title": "Early stopping and penalized likelihood", "href": "http://andrewgelman.com/2011/07/06/early_stopping/" } ]
read.STdata <- function(file, header = FALSE, dec = ".", sep = "", iclx, icly, iclt, icldate = c(icl.date = 0, iclty = 0, icltm = 0, icltd = 0), icltime = c(icl.time = 0, icltH = 0, icltM = 0, icltS = 0), iclvr, iclsp = 0, missing.v = NA, save.as = "data.frame", date.format = c("code",format = NA), bytime = NA, tlag, time.zone = ""){ is.scalar <- function (x){length(x) == 1L && is.vector(x, mode = "numeric")} if(time.zone == ""){ if(is.na(Sys.timezone())){ message("Start error message. The current time zone is not set in your system.") message("Please set the specific time zone by using the parameter time.zone.") stop("End error message. Stop running.") }else{ time.zone <- Sys.timezone() } } if (is.scalar(iclx) == FALSE || is.scalar(icly) == FALSE || is.scalar(iclvr) == FALSE || is.scalar(iclsp) == FALSE) { message("Start error message. Some of the arguments iclsp, iclx, icly, iclt, iclvr are not numeric.") stop("End error message. Stop running.")} if(is.vector(icldate) == FALSE || is.vector(icltime) == FALSE){ message("Start error message. The arguments icldate or icltime are not vector.") stop("End error message. Stop running.")} if(iclx != as.integer(iclx) || icly != as.integer(icly) || iclt != as.integer(iclt) || iclvr != as.integer(iclvr) || icldate[1] != as.integer(icldate[1]) || icltime[1] != as.integer(icltime[1]) || iclsp != as.integer(iclsp) || icldate[2] != as.integer(icldate[2]) || icltime[2] != as.integer(icltime[2]) || icldate[3] != as.integer(icldate[3]) || icltime[3] != as.integer(icltime[3]) || icldate[4] != as.integer(icldate[4]) || icltime[4] != as.integer(icltime[4])){ iclx <- as.integer(iclx) icly <- as.integer(icly) iclt <- as.integer(iclt) icldate <- as.integer(icldate) icltime <- as.integer(icltime) iclvr <- as.integer(iclvr) iclsp <- as.integer(iclsp) message("Warning message: the arguments iclsp, iclx, icly, iclvr are forced to be integer numbers.") } if(iclx == 0 || icly == 0 || iclvr == 0){ message("Start error message. The columns iclx, icly, iclvr have to be defined.") stop("End error message. Stop running.") } if (save.as != "data.frame" && save.as != "STFDF"){ message("Start error message. The class of data has to be data.frame or STFDF. The class entered is not allowed.") stop("End error message. Stop running.") } if(is.vector(date.format) == FALSE){ message("Start error message. The argument date.format is not a vector.") stop("End error message. Stop running.") } iflagt <- 0 if(date.format[1] == "code"){ if(is.na(date.format[2]) == FALSE){ message("Start error message. The argument date.format[2] is not valid: it has to be set equal to NA.") stop("End error message. Stop running.") } date_format <- 0 }else{ if(date.format[1] == "year"){ date_format <- 0 iflagt <- 1 }else{ if(date.format[1] == "yearmon"){ date_format <- date.format[2] }else{ if(date.format[1] == "yearqtr"){ date_format <- date.format[2] }else{ if(date.format[1] == "Date"){ date_format <- date.format[2] }else{ if(date.format[1] == "POSIX"){ date_format <- date.format[2] }else{ message("Start error message. The argument date.format is not admissible.") stop("End error message. Stop running.") }}}}}} if(bytime != "%Y" && bytime != "%y" && bytime != "%m" && bytime != "%q" && bytime != "%d" && bytime != "%H" && bytime != "%M" && bytime != "%S" && is.na(bytime) != TRUE){ message("Start error message. The parameter in bytime is not in the required format.") stop("End error message. Stop running.")} if(date_format == 0 && iclt == 0 && iflagt == 0){ message("Start error message. The arguments iclt and date.format are not consistent: please set one of them.") stop("End error message. Stop running.")} if(date_format != 0 && iclt != 0){ message("Start error message. The arguments iclt and date.format are not consistent: please set only one of them.") stop("End error message. Stop running.")} if(date_format != 0 && length(setdiff(icldate, 0)) == 0){ message("Start error message. The arguments icldate and date.format are not consistent: no column has been indicated for dates.") stop("End error message. Stop running.")} if(date_format != 0 && icldate[1] != 0 && length(setdiff(icldate[2:4], 0)) > 0){ message("Start error message. The arguments icldate and date.format are not consistent: too many columns have been indicated for dates.") stop("End error message. Stop running.")} if(date.format[1] != "year" && date.format[1] != "yearmon" && date.format[1] != "yearqtr"){ if(date_format != 0 && icldate[1] == 0 && length(setdiff(icldate[2:4], 0)) < 3){ message("Start error message. The arguments icldate and date.format are not consistent: no information about columns for year or month or day.") stop("End error message. Stop running.")}}else{ if(date.format[1] == "yearmon" || date.format[1] == "yearqtr"){ if(icldate[1] == 0 && length(setdiff(icldate[2:3], 0)) < 2){ message("Start error message. The arguments icldate and date.format are not consistent: no information about columns for year or month/quarter.") stop("End error message. Stop running.")}} if(date.format[1] == "year"){ if(icldate[1] == 0 && icldate[2] == 0){ message("Start error message. The arguments icldate and date.format are not consistent: no information about column for year.") stop("End error message. Stop running.")} if(date.format[2] != "%Y" && date.format[2] != "%y"){ message("Start error message. The arguments date.format[1] and date.format[2] are not consistent.") stop("End error message. Stop running.")} if(is.na(bytime) == FALSE){ message("Start error message. The arguments bytime is not consistent. Please use the default choice NA.") stop("End error message. Stop running.")} date.format[1] <- "code" if(icldate[1] != 0){ iclt <- icldate[1] }else{iclt <- icldate[2] icldate[2] <- 0} } } if(date.format[1] == "yearmon" || date.format[1] == "yearqtr"){ if(icldate[1] == 0 && length(setdiff(icldate[2:4], 0)) == 3){ icldate[4] <- 0 message("Warning message: the argument in icldate[4] is forced to be zero for classes yearmon or yearqtr.")} if(icltime[1] != 0 || length(setdiff(icltime[2:4], 0)) != 0){ icltime <- 0 message("Warning message: the arguments in icltime are forced to be zero for classes yearmon or yearqtr.")} }else{ if(date_format != 0 && icltime[1] != 0 && length(setdiff(icltime[2:4], 0)) > 0){ message("Start error message. The arguments icltime and date.format are not consistent: too many columns have been indicated for hours.") stop("End error message. Stop running.")} if(regexpr('%H', date_format)[1] > 0 && icltime[1] == 0 && icltime[2] == 0){ message("Start error message. The argument date.format includes hours but no column in icltime provides information about hour.") stop("End error message. Stop running.")} if(regexpr('%H', date_format)[1] > 0 && regexpr('%M', date_format)[1] > 0 && icltime[1] == 0 && (icltime[2] == 0 || icltime[3] == 0)){ message("Start error message. The argument date.format includes hours and minutes but some information about hours or minutes are missing in icltime.") stop("End error message. Stop running.")} if((regexpr('%H', date_format)[1] > 0 && regexpr('%M', date_format)[1] > 0 && regexpr('%S', date_format)[1] > 0) && icltime[1] == 0 && (icltime[2] == 0 || icltime[3] == 0 || icltime[4] == 0)){ message("Start error message. The argument date.format includes hours, minutes and seconds but some information are missing in icltime.") stop("End error message. Stop running.")}} if(is.scalar(tlag) == FALSE || tlag <= 0){ message("Start error message. The argument tlag has to be integer and greater than zero.") stop("End error message. Stop running.")} iclw1 <- c(iclx,icly,iclt,iclvr,iclsp) iclw1 <- iclw1[iclw1 != 0] iclw2 <- icldate[icldate != 0] iclw3 <- icltime[icltime != 0] if(sum(match(duplicated(c(iclw1,iclw2,iclw3)),TRUE,nomatch = 0)) > 0){ message("Start error message. The columns (iclx, icly, ...) indicated have to be different.") stop("End error message. Stop running.") } if(is.scalar(tlag) == FALSE){ tlag <- as.integer(tlag) message("Warning message: the argument tlag is forced to be integer.") } if(is.na(bytime) == FALSE){ if(bytime == "%S"){ if(regexpr('%S', date_format)[1] < 0){ message("Start error message. The arguments bytime = %S and date.format are not consistent.") stop("End error message. Stop running.")} }else{ if(bytime == "%M"){ if(regexpr('%M', date_format)[1] < 0){ message("Start error message. The arguments bytime = %M and date.format are not consistent.") stop("End error message. Stop running.") }}else{ if(bytime == "%H"){ if(regexpr('%H', date_format)[1] < 0){ message("Start error message. The arguments bytime = %H and date.format are not consistent.") stop("End error message. Stop running.") }}else{ if(bytime == "%d"){ if(regexpr('%d', date_format)[1] < 0){ message("Start error message. The arguments bytime = %d and date.format are not consistent.") stop("End error message. Stop running.") }}else{ if(bytime == "%m"){ if((regexpr('%m', date_format)[1] < 0)){ message("Start error message. The arguments bytime = %m and date.format are not consistent.") stop("End error message. Stop running.") }}else{ if(bytime == "%q"){ if((regexpr('%q', date_format)[1] < 0)){ message("Start error message. The arguments bytime = %q and date.format are not consistent.") stop("End error message. Stop running.") }}else{ if(bytime == "%Y" || bytime == "%y"){ if((regexpr('%Y', date_format)[1] < 0) && (regexpr('%y', date_format)[1] < 0)){ message("Start error message. The arguments bytime = %q and date.format are not consistent.") stop("End error message. Stop running.") }}else{ message("Start error message. The argument bytime is not admissible.") stop("End error message. Stop running.") }}}}}}}} nskip <- 0 if(header == TRUE){ nskip <- 1 } importFl <- utils::read.table(file, dec = dec, sep = sep, skip = nskip, na.strings = missing.v) importFl[importFl == missing.v] <- NA ndata <- dim(importFl)[1] if(date_format != 0){ i <- 1 while(i <= ndata){ if(icldate[1] == 0){ if(icldate[2] != 0){ i.date <- importFl[i,icldate[2]] if(icldate[3] != 0){ i.date <- paste(i.date,importFl[i,icldate[3]], sep=" ") if(icldate[4] != 0){ i.date <- paste(i.date,importFl[i,icldate[4]], sep=" ") } }else{ if(icldate[4] != 0){ message("Start error message. The date cannot be defined: it is specified the column for the day but not the column for the month.") stop("End error message. Stop running.")}}}else{ message("Start error message. The date cannot be defined: the column for the year is not specified.") stop("End error message. Stop running.")} }else{i.date <- importFl[i,icldate[1]]} if(length(setdiff(icltime, 0)) != 0){ if(icltime[1] == 0){ if(icltime[2] != 0){ i.time <- importFl[i,icltime[2]] if(icltime[3] != 0){ i.time <- paste(i.time,importFl[i,icltime[3]], sep=" ") if(icltime[4] != 0){ i.time <- paste(i.time,importFl[i,icltime[4]], sep=" ") } }else{ if(icltime[4] != 0){ message("Start error message. The time cannot be defined: it is specified the column for the second but not the column for the minute.") stop("End error message. Stop running.")}} }else{ message("Start error message. The time cannot be defined: the column for the hour is not specified.") stop("End error message. Stop running.")} }else{i.time <- importFl[i,icltime[1]]} importFl[i, "icldate"] <- paste(i.date, i.time) }else{importFl[i, "icldate"] <- i.date} if(date.format[1] != "yearmon" && date.format[1] != "yearqtr"){ if(is.na(as.POSIXlt((importFl[i,"icldate"]), date_format, tz = time.zone)) == TRUE){ message("Start error message. One of the possible causes is that:") message("- the dates in the file are not in the format specified in date.format or") message("- the data format is not valid or") message("- the dates in the file are not consistent with the given timezone (check for errors in dates involved in daylight saving time).") stop("End error message. Stop running.")} }else{ if(date.format[1] == "yearmon"){ if(is.na(as.yearmon(as.character(importFl[i,"icldate"]), date_format)) == TRUE){ message("Start error message. The dates in the file are not in the format specified in date.format or the data format is not valid.") message("It might be hepful to provide dates with numeric elements.") stop("End error message. Stop running.")}} if(date.format[1] == "yearqtr"){ if(is.na(as.yearqtr(as.character(importFl[i,"icldate"]), date_format)) == TRUE){ message("Start error message. The dates in the file are not in the format specified in date.format or the data format is not valid.") message("It might be hepful to provide dates with numeric elements.") stop("End error message. Stop running.")}} } i <- i+1 } if(date.format[1] != "yearmon" && date.format[1] != "yearqtr"){ i.date <- as.POSIXlt((importFl[,"icldate"]), format = date_format, tz = time.zone) if(regexpr('%Y', date_format)[1] < 0){ date_format <- "%y-%m-%d %H:%M:%S"}else{ date_format <- "%Y-%m-%d %H:%M:%S"} }else{ if(date.format[1] == "yearmon"){ i.date <- as.POSIXlt(as.yearmon(as.character(importFl[,"icldate"]), format = date_format)) }else{i.date <- as.POSIXlt(as.yearqtr(as.character(importFl[,"icldate"]), format = date_format))} } if(bytime == "%m"){ i.date <- as.POSIXlt(as.yearmon(i.date)) date.format[1] <- "yearmon" if(regexpr('%Y', date_format)[1] < 0){ date_format <- "%y-%m-%d"}else{ date_format <- "%Y-%m-%d"} } if(bytime == "%q"){ i.date <- as.POSIXlt(as.yearqtr(i.date)) date.format[1] <- "yearqtr" if(regexpr('%Y', date_format)[1] < 0){ date_format <- "%y-%m-%d"}else{ date_format <- "%Y-%m-%d"} } if(bytime == "%d"){ i.date <- as.POSIXlt(as.Date(i.date)) if(regexpr('%Y', date_format)[1] < 0){ date_format <- "%y-%m-%d"}else{ date_format <- "%Y-%m-%d"} } if(bytime == "%H"){ minute(i.date) <- 0 second(i.date) <- 0 } if(bytime == "%M"){ second(i.date) <- 0 } if(bytime == "%Y" || bytime == "%y"){ i.date <- year(i.date) date.format[1] <- "code" date_format <- 0 bytime <- NA if(regexpr('%Y', date.format)[2] < 0){ date.format[2] <- "%y"}else{ date.format[2] <- "%Y"} iclt <- ncol(importFl) iflagt <- 1 } importFl <- importFl[,-c(ncol(importFl))] importFl <- cbind(importFl,i.date) names(importFl)[names(importFl) == "i.date"] <- "iclt" iclt <- ncol(importFl) }else{ if(is.numeric(importFl[1,iclt]) == FALSE){ message("Start error message. The temporal codes in the file are not numeric.") stop("End error message. Stop running.")} names(importFl)[iclt] <- "iclt" } importFl1 <- importFl[order(importFl[, iclx], importFl[, icly], importFl[, iclt]), ] code.time <- unique(importFl1[, iclt]) tpar1 <- min(code.time) tpar2 <- max(code.time) vec.date <- c(tpar1) if(date.format[1] == "Date" || date.format[1] == "POSIX"){ if(bytime == "%d"){ tpar1 <- as.POSIXlt(as.Date(tpar1)) tpar2 <- as.POSIXlt(as.Date(tpar2)) vec.date.w <- as.POSIXlt(as.Date(tpar1)) vec.date <- as.character(vec.date) }else{ tpar1 <- as.POSIXlt(tpar1) tpar2 <- as.POSIXlt(tpar2) vec.date.w <- as.POSIXlt(tpar1) vec.date <- format(round(as.POSIXlt(vec.date, format="%Y-%m-%d %H:%M:%S")), "%Y-%m-%d %H:%M:%S") } }else{ vec.date <- as.character(vec.date) if(date.format[1] == "yearmon"){ tpar1 <- as.POSIXlt(as.yearmon(tpar1)) tpar2 <- as.POSIXlt(as.yearmon(tpar2)) vec.date.w <- as.POSIXlt(as.yearmon(tpar1)) } if(date.format[1] == "yearqtr"){ tpar1 <- as.POSIXlt(as.yearqtr(tpar1)) tpar2 <- as.POSIXlt(as.yearqtr(tpar2)) vec.date.w <- as.POSIXlt(as.yearqtr(tpar1)) } if(date.format[1] == "code"){ vec.date.w <- tpar1 } } if(length(unique(c(tpar1,tpar2))) ==1){ message("Start error message. The initial observed date or temporal point is coincident with the final one, thus the data structure is not spatio-temporal.") stop("End error message. Stop running.") } if(date_format != 0){ if(bytime == "%d" || bytime == "%H" || bytime == "%M" || bytime == "%S"){ if(bytime == "%d"){delta.time <- difftime(tpar2, tpar1, units = "days")} if(bytime == "%H"){delta.time <- difftime(tpar2, tpar1, units = "hours")} if(bytime == "%M"){delta.time <- difftime(tpar2, tpar1, units = "mins")} if(bytime == "%S"){delta.time <- difftime(tpar2, tpar1, units = "secs")} }else{ if(bytime == "%m"){ delta.time <- length(seq(from=as.Date(tpar1), to=as.Date(tpar2), by='month')) - 1 }else{ if(bytime == "%q"){ delta.time <- length(seq(from=as.Date(tpar1), to=as.Date(tpar2), by='quarter')) - 1 }}}}else{delta.time <- tpar2-tpar1} if(tlag>(delta.time)){ message("Start error message. The argument tlag is not consistent: it has to be less than the temporal observed interval.") stop("End error message. Stop running.")} i <- 1 while(delta.time >= tlag){ i <- i + 1 if(date_format != 0){ if(bytime == "%Y" || bytime == "%y"){ year(vec.date.w) <- year(vec.date.w) + tlag } if(bytime == "%d"){ day(vec.date.w) <- day(vec.date.w) + tlag } if(bytime == "%m"){ month(vec.date.w) <- month(vec.date.w) + tlag } if(bytime == "%q"){ month(vec.date.w) <- month(vec.date.w) + tlag*3 } if(bytime == "%H"){ delta.w <- vec.date.w hour(delta.w) <- hour(vec.date.w) + tlag if(is.na(delta.w) == TRUE){ vec.date.w1 <-vec.date.w hour(vec.date.w1) <- hour(vec.date.w1) + tlag + 1 if(difftime(vec.date.w1, vec.date.w, units = "hours") < tlag){ hour(vec.date.w1) <- hour(vec.date.w1) + 1 } hour(vec.date.w) <- hour(vec.date.w1) }else{ hour(vec.date.w) <- hour(vec.date.w) + tlag} } if(bytime == "%M"){ delta.w <- vec.date.w minute(delta.w) <- minute(vec.date.w) + tlag if(is.na(delta.w) == TRUE){ vec.date.w1 <-vec.date.w minute(vec.date.w1) <- minute(vec.date.w1) + tlag + 60 if(difftime(vec.date.w1, vec.date.w, units = "mins") < tlag){ minute(vec.date.w1) <- minute(vec.date.w1) + 60 } minute(vec.date.w) <- minute(vec.date.w1) }else{ minute(vec.date.w) <- minute(vec.date.w) + tlag} } if(bytime == "%S"){ delta.w <- vec.date.w second(delta.w) <- second(vec.date.w) + tlag if(is.na(delta.w) == TRUE){ vec.date.w1 <-vec.date.w second(vec.date.w1) <- second(vec.date.w1) + tlag + 3600 if(difftime(vec.date.w1, vec.date.w, units = "secs") < tlag){ second(vec.date.w1) <- second(vec.date.w1) + 3600 } second(vec.date.w) <- second(vec.date.w1) }else{ second(vec.date.w) <- second(vec.date.w) + tlag} } if(bytime == "%d" || bytime == "%H" || bytime == "%M" || bytime == "%S"){ if(bytime == "%d"){delta.time <- difftime(tpar2, vec.date.w, units = "days")} if(bytime == "%H"){delta.time <- difftime(tpar2, vec.date.w, units = "hours")} if(bytime == "%M"){delta.time <- difftime(tpar2, vec.date.w, units = "mins")} if(bytime == "%S"){delta.time <- difftime(tpar2, vec.date.w, units = "secs")} }else{ if(bytime == "%m"){ delta.time <- length(seq(from=as.Date(vec.date.w), to=as.Date(tpar2), by='month')) - 1 }else{ if(bytime == "%q"){ delta.time <- length(seq(from=as.Date(vec.date.w), to=as.Date(tpar2), by='quarter')) - 1 }}} }else{ vec.date.w <- vec.date.w + tlag delta.time <- tpar2-vec.date.w } vec_date <- vec.date.w if(date.format[1] == "POSIX" && bytime != "%d"){ if(hour(vec_date) == 0 && minute(vec_date) == 0 && second(vec_date) == 0){ vec_date <- format(round(as.POSIXlt(vec.date.w, format="%Y-%m-%d %H:%M:%S")), "%Y-%m-%d %H:%M:%S") }} vec.date <- rbind(vec.date,as.character(vec_date)) } n.time <- length(unique(importFl1[, iclt])) for(i in 1:n.time){ if(date.format[1] == "POSIX" && bytime != "%d"){ if(hour(importFl1[i, iclt]) == 0 && minute(importFl1[i, iclt]) == 0 && second(importFl1[i, iclt]) == 0){ importFl1[i, iclt] <- format(round(as.POSIXlt(importFl1[i, iclt], format="%Y-%m-%d %H:%M:%S")), "%Y-%m-%d %H:%M:%S") }} } importFl1[[iclt]] <- as.character(importFl1[,iclt]) importFl1 <- subset(importFl1, iclt %in% vec.date) if(date_format != 0){ if(date.format[1] == "Date" || date.format[1] == "POSIX"){ if(bytime == "%d"){ importFl1[[iclt]] <- as.POSIXlt(as.Date(importFl1[,iclt], format = date_format)) }else{ importFl1[[iclt]] <- (as.POSIXlt(importFl1[,iclt], format = date_format, tz = time.zone)) } }else{ if(date.format[1] == "yearmon"){ importFl1[[iclt]] <- as.POSIXlt(as.yearmon((importFl1[,iclt]), format = date_format)) } if(date.format[1] == "yearqtr"){ importFl1[[iclt]] <- as.POSIXlt(as.yearqtr((importFl1[,iclt]), format = date_format)) } } }else{importFl1[[iclt]]<-as.numeric(importFl1[,iclt])} sp <- cbind(importFl1[, iclx], importFl1[, icly]) sp <- unique(sp) n.stat <- nrow(sp) n.time <- length(unique(importFl1[, iclt])) code.time <- unique(importFl1[, iclt]) tpar2 <- max(code.time) if(date_format != 0){ if(date.format[1] == "Date" || date.format[1] == "POSIX"){ if(bytime == "%d"){ tpar2 <- as.POSIXlt(as.Date(tpar2)) }else{ tpar2 <- (as.POSIXlt(tpar2))} }else{ if(date.format[1] == "yearmon"){ tpar2 <- as.POSIXlt(as.yearmon(tpar2)) } if(date.format[1] == "yearqtr"){ tpar2 <- as.POSIXlt(as.yearqtr(tpar2)) } }}else{tpar2 <- as.numeric(tpar2)} if(length(unique(c(tpar1,tpar2))) == 1){ message("Start error message. There is no temporal point for the selected tlag increment.") message("Thus the data structure is not spatio-temporal.") stop("End error message. Stop running.") } for(i in 1:n.stat){ if(date_format != 0){ if(sum(match(duplicated(importFl1[(importFl1[iclx] == sp[i,1] & importFl1[icly] == sp[i,2]),iclt]), TRUE, nomatch = 0)) >= 1){ message("Start error message. According to the argument 'bytime = '", bytime,", there are more than one observation for a fixed spatial point and a fixed time point.") stop("End error message. Stop running.")} }else{ if(sum(match(duplicated(importFl1[(importFl1[iclx] == sp[i,1] & importFl1[icly] == sp[i,2]),iclt]), TRUE, nomatch = 0)) >= 1){ message("Start error message. There are more than one observation for a fixed spatial point and a fixed time point.") stop("End error message. Stop running.")}}} if(iclsp == 0){ importFl1 <- importFl1[,c(iclx,icly,iclt,iclvr)] colnames(importFl1) <- c("iclx","icly","iclt","iclvr") importFlw <- data.frame(iclx=NA,icly=NA,iclt=NA,iclvr=NA) importFlfull <- importFl1[1,] colnames(importFlfull) <- c("iclx","icly","iclt", "iclvr") }else{ importFl1 <- importFl1[,c(iclsp,iclx,icly,iclt,iclvr)] colnames(importFl1) <- c("iclsp","iclx","icly","iclt","iclvr") importFlw <- data.frame(iclsp=NA,iclx=NA,icly=NA,iclt=NA,iclvr=NA) importFlfull <- importFl1[1,] colnames(importFlfull) <- c("iclsp","iclx","icly","iclt", "iclvr") iclsp <- "iclsp" } iclx <- "iclx" icly <- "icly" iclvr <- "iclvr" iclt <- "iclt" if(date.format[1] == "POSIX" && bytime != "%d"){ if(hour(importFlfull[[iclt]]) == 0 && minute(importFlfull[[iclt]]) == 0 && second(importFlfull[[iclt]]) == 0){ importFlfull[[iclt]] <- format(round(as.POSIXlt(importFlfull[[iclt]], format="%Y-%m-%d %H:%M:%S")), "%Y-%m-%d %H:%M:%S") }} importFlfull[[iclt]] <- as.character(importFlfull[[iclt]]) t1 <- importFl1[1,iclt] if(date_format != 0){ if(date.format[1] == "Date" || date.format[1] == "POSIX"){ if(bytime == "%d"){ t1 <- as.POSIXlt(as.Date(t1)) }else{ t1 <- as.POSIXlt(t1)} }else{ if(date.format[1] == "yearmon"){ t1 <- as.POSIXlt(as.yearmon(t1)) } if(date.format[1] == "yearqtr"){ t1 <- as.POSIXlt(as.yearqtr(t1)) } } }else{t1 <- as.numeric(t1)} importFlw <- importFl1[1,] j <- 1 if(date_format != 0){ if(bytime == "%d" || bytime == "%H" || bytime == "%M" || bytime == "%S"){ if(bytime == "%d"){ delta.time <- difftime(t1,tpar1, units = "days") } if(bytime == "%H"){ delta.time <- difftime(t1,tpar1, units = "hours") } if(bytime == "%M"){ delta.time <- difftime(t1,tpar1, units = "mins") } if(bytime == "%S"){ delta.time <- difftime(t1,tpar1, units = "secs") } }else{ if(bytime == "%m"){ delta.time <- length(seq(from=as.Date(tpar1), to=as.Date(t1), by='month')) - 1 }else{ if(bytime == "%q"){ delta.time <- length(seq(from=as.Date(tpar1), to=as.Date(t1), by='quarter')) - 1 } } } }else{ delta.time <- t1-tpar1} while(delta.time >= tlag){ j <- j + 1 if(as.integer(j/500) == (j/500) ){ message("The first ", j, " values have been included in the data file.") } if(date_format != 0){ if(bytime == "%Y" || bytime == "%y"){ year(t1) <- year(t1) - tlag } if(bytime == "%d"){ day(t1) <- day(t1) - tlag } if(bytime == "%m"){ month(t1) <- month(t1) - tlag } if(bytime == "%q"){ month(t1) <- month(t1) - tlag*3 } if(bytime == "%H"){ delta.w <- t1 hour(delta.w) <- hour(t1) - tlag if(is.na(delta.w) == TRUE){ t11 <- t1 hour(t11) <- hour(t11) - tlag - 1 if(difftime(t1, t11, units = "hours") < tlag){ hour(t11) <- hour(t11) - 1 } hour(t1) <- hour(t11) }else{ hour(t1) <- hour(t1) - tlag} } if(bytime == "%M"){ delta.w <- t1 minute(delta.w) <- minute(t1) - tlag if(is.na(delta.w) == TRUE){ t11 <- t1 minute(t11) <- minute(t11) - tlag - 60 if(difftime(t1, t11, units = "mins") < tlag){ minute(t11) <- minute(t11) - 60 } minute(t1) <- minute(t11) }else{ minute(t1) <- minute(t1) - tlag} } if(bytime == "%S"){ delta.w <- t1 second(delta.w) <- second(t1) - tlag if(is.na(delta.w) == TRUE){ t11 <- t1 second(t11) <- second(t11) - tlag - 3600 if(difftime(t1, t11, units = "secs") < tlag){ second(t11) <- second(t11) - 3600 } second(t1) <- second(t11) }else{ second(t1) <- second(t1) - tlag} } if(date.format[1] == "Date" || date.format[1] == "POSIX"){ if(bytime == "%d"){ importFlw[[iclt]]<- as.POSIXlt(as.Date(t1)) }else{ importFlw[[iclt]]<- (as.POSIXlt(t1))} }else{ if(date.format[1] == "yearmon"){ importFlw[[iclt]]<- as.POSIXlt(as.yearmon(t1)) } if(date.format[1] == "yearqtr"){ importFlw[[iclt]]<- as.POSIXlt(as.yearqtr(t1)) } } }else{ t1 <- t1 - tlag importFlw[[iclt]]<- importFlw[1,iclt] - tlag } importFlw[[iclvr]]<- NA if(date.format[1] == "POSIX" && bytime != "%d"){ if(hour(importFlw[[iclt]]) == 0 && minute(importFlw[[iclt]]) == 0 && second(importFlw[[iclt]]) == 0){ importFlw[[iclt]] <- format(round(as.POSIXlt(importFlw[[iclt]], format="%Y-%m-%d %H:%M:%S")), "%Y-%m-%d %H:%M:%S") }} importFlw[[iclt]] <- as.character(importFlw[[iclt]]) importFlfull <- rbind(importFlw,importFlfull) if(date_format != 0){ if(bytime == "%d" || bytime == "%H" || bytime == "%M" || bytime == "%S"){ if(bytime == "%d"){delta.time <- difftime(t1,tpar1, units = "days")} if(bytime == "%H"){delta.time <- difftime(t1,tpar1, units = "hours")} if(bytime == "%M"){delta.time <- difftime(t1,tpar1, units = "mins")} if(bytime == "%S"){delta.time <- difftime(t1,tpar1, units = "secs")} }else{ if(bytime == "%m"){ delta.time <- length(seq(from=as.Date(tpar1), to=as.Date(t1), by='month')) - 1 }else{ if(bytime == "%q"){ delta.time <- length(seq(from=as.Date(tpar1), to=as.Date(t1), by='quarter')) - 1 } } } }else{delta.time <- t1-tpar1} } i <- 2 ndata <- dim(importFl1)[1] while (i<= ndata) { if((importFl1[i-1,iclx] == importFl1[i,iclx]) && (importFl1[i-1,icly] == importFl1[i,icly])){ t1 <- importFl1[i-1,iclt] t2 <- importFl1[i,iclt] if(date_format != 0){ if(date.format[1] == "Date" || date.format[1] == "POSIX"){ if(bytime == "%d"){ t1 <- as.POSIXlt(as.Date(t1)) t2 <- as.POSIXlt(as.Date(t2)) }else{ t1 <- as.POSIXlt(t1) t2 <- as.POSIXlt(t2) } }else{ if(date.format[1] == "yearmon"){ t1 <- as.POSIXlt(as.yearmon(t1)) t2 <- as.POSIXlt(as.yearmon(t2)) } if(date.format[1] == "yearqtr"){ t1 <- as.POSIXlt(as.yearqtr(t1)) t2 <- as.POSIXlt(as.yearqtr(t2)) } } }else{ t1 <- as.numeric(t1) t2 <- as.numeric(t2)} if(date_format != 0){ if(bytime == "%d" || bytime == "%H" || bytime == "%M" || bytime == "%S"){ if(bytime == "%d"){ delta.time <- difftime(t2, t1, units = "days") } if(bytime == "%H"){ delta.time <- difftime(t2, t1, units = "hours") } if(bytime == "%M"){ delta.time <- difftime(t2, t1, units = "mins") } if(bytime == "%S"){ delta.time <- difftime(t2, t1, units = "secs") } }else{ if(bytime == "%m"){ delta.time <- length(seq(from=as.Date(t1), to=as.Date(t2), by='month')) - 1 }else{ if(bytime == "%q"){ delta.time <- length(seq(from=as.Date(t1), to=as.Date(t2), by='quarter')) - 1 } } } }else{delta.time <- t2-t1} while(delta.time > tlag){ j <- j + 1 if(as.integer(j/500) == (j/500) ){ message("The first ", j, " values have been included in the data file.") } importFlw<-importFl1[i-1,] if(date_format != 0){ if(bytime == "%Y" || bytime == "%y"){ year(t1) <- year(t1) + tlag } if(bytime == "%d"){ day(t1) <- day(t1) + tlag } if(bytime == "%m"){ month(t1) <- month(t1) + tlag } if(bytime == "%q"){ month(t1) <- month(t1) + tlag*3 } if(bytime == "%H"){ delta.w <- t1 hour(delta.w) <- hour(t1) + tlag if(is.na(delta.w) == TRUE){ t11 <- t1 hour(t11) <- hour(t11) + tlag + 1 if(difftime(t11, t1, units = "hours") < tlag){ hour(t11) <- hour(t11) + 1 } hour(t1) <- hour(t11) }else{ hour(t1) <- hour(t1) + tlag} } if(bytime == "%M"){ delta.w <- t1 minute(delta.w) <- minute(t1) + tlag if(is.na(delta.w) == TRUE){ t11 <- t1 minute(t11) <- minute(t11) + tlag + 60 if(difftime(t11, t1, units = "mins") < tlag){ minute(t11) <- minute(t11) + 60 } minute(t1) <- minute(t11) }else{ minute(t1) <- minute(t1) + tlag} } if(bytime == "%S"){ delta.w <- t1 second(delta.w) <- second(t1) + tlag if(is.na(delta.w) == TRUE){ t11 <- t1 second(t11) <- second(t11) + tlag + 3600 if(difftime(t11, t1, units = "secs") < tlag){ second(t11) <- second(t11) + 3600 } second(t1) <- second(t11) }else{ second(t1) <- second(t1) + tlag} } if(date.format[1] == "Date" || date.format[1] == "POSIX"){ if(bytime == "%d"){ importFlw[[iclt]]<- as.POSIXlt(as.Date(t1)) }else{ importFlw[[iclt]]<- as.POSIXlt(t1)} }else{ if(date.format[1] == "yearmon"){ importFlw[[iclt]]<- as.POSIXlt(as.yearmon(t1)) } if(date.format[1] == "yearqtr"){ importFlw[[iclt]]<- as.POSIXlt(as.yearqtr(t1)) } } }else{ t1 <- t1 + tlag importFlw[[iclt]]<- t1 } importFlw[[iclvr]]<- NA if(date.format[1] == "POSIX" && bytime != "%d"){ if(hour(importFlw[[iclt]]) == 0 && minute(importFlw[[iclt]]) == 0 && second(importFlw[[iclt]]) == 0){ importFlw[[iclt]] <- format(round(as.POSIXlt(importFlw[[iclt]], format="%Y-%m-%d %H:%M:%S")), "%Y-%m-%d %H:%M:%S") }} importFlw[[iclt]] <- as.character(importFlw[[iclt]]) importFlfull <- rbind(importFlfull, importFlw) if(date_format != 0){ if(bytime == "%d" || bytime == "%H" || bytime == "%M" || bytime == "%S"){ if(bytime == "%d"){delta.time <- difftime(t2, t1, units = "days")} if(bytime == "%H"){delta.time <- difftime(t2, t1, units = "hours")} if(bytime == "%M"){delta.time <- difftime(t2, t1, units = "mins")} if(bytime == "%S"){delta.time <- difftime(t2, t1, units = "secs")} }else{ if(bytime == "%m"){ delta.time <- length(seq(from=as.Date(t1), to=as.Date(t2), by='month')) - 1 }else{ if(bytime == "%q"){ delta.time <- length(seq(from=as.Date(t1), to=as.Date(t2), by='quarter')) - 1 } } } }else{delta.time <- t2 - t1} } importFlw <- importFl1[i,] if(date.format[1] == "POSIX" && bytime != "%d"){ if(hour(importFlw[[iclt]]) == 0 && minute(importFlw[[iclt]]) == 0 && second(importFlw[[iclt]]) == 0){ importFlw[[iclt]] <- format(round(as.POSIXlt(importFlw[[iclt]], format="%Y-%m-%d %H:%M:%S")), "%Y-%m-%d %H:%M:%S") }} importFlw[[iclt]] <- as.character(importFlw[1, iclt]) importFlfull <- rbind(importFlfull, importFlw) i <- i + 1 j <- j +1 }else{ if(importFl1[i-1,iclt] != tpar2){ t2 <- importFl1[i-1,iclt] if(date_format != 0){ if(date.format[1] == "Date" || date.format[1] == "POSIX"){ if(bytime == "%d"){ t2 <- as.POSIXlt(as.Date(t2)) }else{ t2 <- as.POSIXlt(t2)} }else{ if(date.format[1] == "yearmon"){ t2 <- as.POSIXlt(as.yearmon(t2)) } if(date.format[1] == "yearqtr"){ t2 <- as.POSIXlt(as.yearqtr(t2)) } } }else{t2 <- as.numeric(t2)} if(date_format != 0){ if(bytime == "%d" || bytime == "%H" || bytime == "%M" || bytime == "%S"){ if(bytime == "%d"){delta.time <- difftime(tpar2, t2, units = "days")} if(bytime == "%H"){delta.time <- difftime(tpar2, t2, units = "hours")} if(bytime == "%M"){delta.time <- difftime(tpar2, t2, units = "mins")} if(bytime == "%S"){delta.time <- difftime(tpar2, t2, units = "secs")} }else{ if(bytime == "%m"){ delta.time <- length(seq(from=as.Date(t2), to=as.Date(tpar2), by='month')) - 1 }else{ if(bytime == "%q"){ delta.time <- length(seq(from=as.Date(t2), to=as.Date(tpar2), by='quarter')) - 1 } } } }else{delta.time <- tpar2-t2} while(delta.time >= tlag){ j <- j +1 if(as.integer(j/500) == (j/500) ){ message("The first ", j, " values have been included in the data file.") } importFlw <- importFl1[i - 1,] if(date_format != 0){ if(bytime == "%Y" || bytime == "%y"){ year(t2) <- year(t2) + tlag } if(bytime == "%d"){ day(t2) <- day(t2) + tlag } if(bytime == "%m"){ month(t2) <- month(t2) + tlag } if(bytime == "%q"){ month(t2) <- month(t2) + tlag*3 } if(bytime == "%H"){ delta.w <- t2 hour(delta.w) <- hour(t2) + tlag if(is.na(delta.w) == TRUE){ t11 <- t2 hour(t11) <- hour(t11) + tlag + 1 if(difftime(t11, t2, units = "hours") < tlag){ hour(t11) <- hour(t11) + 1 } hour(t2) <- hour(t11) }else{ hour(t2) <- hour(t2) + tlag} } if(bytime == "%M"){ delta.w <- t2 minute(delta.w) <- minute(t2) + tlag if(is.na(delta.w) == TRUE){ t11 <- t2 minute(t11) <- minute(t11) + tlag + 60 if(difftime(t11, t2, units = "mins") < tlag){ minute(t11) <- minute(t11) + 60 } minute(t2) <- minute(t11) }else{ minute(t2) <- minute(t2) + tlag} } if(bytime == "%S"){ delta.w <- t2 second(delta.w) <- second(t2) + tlag if(is.na(delta.w) == TRUE){ t11 <- t2 second(t11) <- second(t11) + tlag + 3600 if(difftime(t11, t2, units = "secs") < tlag){ second(t11) <- second(t11) + 3600 } second(t2) <- second(t11) }else{ second(t2) <- second(t2) + tlag} } if(date.format[1] == "Date" || date.format[1] == "POSIX"){ if(bytime == "%d"){ t2 <- as.POSIXlt(as.Date(t2)) importFlw[[iclt]]<- as.POSIXlt(as.Date(t2)) }else{ importFlw[[iclt]]<- (as.POSIXlt(t2)) } }else{ if(date.format[1] == "yearmon"){ importFlw[[iclt]]<- as.POSIXlt(as.yearmon(t2)) } if(date.format[1] == "yearqtr"){ importFlw[[iclt]]<- as.POSIXlt(as.yearqtr(t2)) } } }else{ t2 <- t2 + tlag importFlw[[iclt]] <- t2 } importFlw[[iclvr]] <- NA if(date.format[1] == "POSIX" && bytime != "%d"){ if(hour(importFlw[[iclt]]) == 0 && minute(importFlw[[iclt]]) == 0 && second(importFlw[[iclt]]) == 0){ importFlw[[iclt]] <- format(round(as.POSIXlt(importFlw[[iclt]], format="%Y-%m-%d %H:%M:%S")), "%Y-%m-%d %H:%M:%S") }} importFlw[[iclt]] <- as.character(importFlw[[iclt]]) importFlfull <- rbind(importFlfull, importFlw) if(date_format != 0){ if(bytime == "%d" || bytime == "%H" || bytime == "%M" || bytime == "%S"){ if(bytime == "%d"){delta.time <- difftime(tpar2, t2, units = "days")} if(bytime == "%H"){delta.time <- difftime(tpar2, t2, units = "hours")} if(bytime == "%M"){delta.time <- difftime(tpar2, t2, units = "mins")} if(bytime == "%S"){delta.time <- difftime(tpar2, t2, units = "secs")} }else{ if(bytime == "%m"){ delta.time <- length(seq(from=as.Date(t2), to=as.Date(tpar2), by='month')) - 1 }else{ if(bytime == "%q"){ delta.time <- length(seq(from=as.Date(t2), to=as.Date(tpar2), by='quarter')) - 1 } } }}else{delta.time <- tpar2-t2} } } t1 <- importFl1[i,iclt] t0 <- tpar1 if(date_format != 0){ if(date.format[1] == "Date" || date.format[1] == "POSIX"){ if(bytime == "%d"){ t1 <- as.POSIXlt(as.Date(t1)) t0 <- as.POSIXlt(as.Date(t0)) }else{ t0 <- as.POSIXlt(t0) t1 <- as.POSIXlt(t1)} }else{ if(date.format[1] == "yearmon"){ t1 <- as.POSIXlt(as.yearmon(t1)) t0 <- as.POSIXlt(as.yearmon(t0)) } if(date.format[1] == "yearqtr"){ t1 <- as.POSIXlt(as.yearqtr(t1)) t0 <- as.POSIXlt(as.yearqtr(t0)) } } }else{ t0 <- as.numeric(t0) t1 <- as.numeric(t1)} importFlw <-importFl1[i,] if(date_format != 0){ if(bytime == "%d" || bytime == "%H" || bytime == "%M" || bytime == "%S"){ if(bytime == "%d"){delta.time <- difftime(t1, t0, units = "days")} if(bytime == "%H"){delta.time <- difftime(t1, t0, units = "hours")} if(bytime == "%M"){delta.time <- difftime(t1, t0, units = "mins")} if(bytime == "%S"){delta.time <- difftime(t1, t0, units = "secs")} }else{ if(bytime == "%m"){ delta.time <- length(seq(from=as.Date(t0), to=as.Date(t1), by='month')) - 1 }else{ if(bytime == "%q"){ delta.time <- length(seq(from=as.Date(t0), to=as.Date(t1), by='quarter')) - 1 } } } }else{ delta.time <- t1-t0 } while(delta.time >= tlag){ j <- j +1 if(as.integer(j/500) == (j/500) ){ message("The first ", j, " values have been included in the data file.") } if(date_format != 0){ if(date.format[1] == "Date" || date.format[1] == "POSIX"){ if(bytime == "%d"){ importFlw[[iclt]]<- as.POSIXlt(as.Date(t0)) }else{ importFlw[[iclt]]<- (as.POSIXlt(t0))} }else{ if(date.format[1] == "yearmon"){ importFlw[[iclt]]<- as.POSIXlt(as.yearmon(t0)) } if(date.format[1] == "yearqtr"){ importFlw[[iclt]]<- as.POSIXlt(as.yearqtr(t0)) } } if(bytime == "%Y" || bytime == "%y"){ year(t0) <- year(t0) + tlag } if(bytime == "%d"){ day(t0) <- day(t0) + tlag } if(bytime == "%m"){ month(t0) <- month(t0) + tlag } if(bytime == "%q"){ month(t0) <- month(t0) + tlag*3 } if(bytime == "%H"){ delta.w <- t0 hour(delta.w) <- hour(t0) + tlag if(is.na(delta.w) == TRUE){ t11 <- t0 hour(t11) <- hour(t11) + tlag + 1 if(difftime(t11, t0, units = "hours") < tlag){ hour(t11) <- hour(t11) + 1 } hour(t0) <- hour(t11) }else{ hour(t0) <- hour(t0) + tlag} } if(bytime == "%M"){ delta.w <- t0 minute(delta.w) <- minute(t0) + tlag if(is.na(delta.w) == TRUE){ t11 <- t0 minute(t11) <- minute(t11) + tlag + 60 if(difftime(t11, t0, units = "mins") < tlag){ minute(t11) <- minute(t11) + 60 } minute(t0) <- minute(t11) }else{ minute(t0) <- minute(t0) + tlag} } if(bytime == "%S"){ delta.w <- t0 second(delta.w) <- second(t0) + tlag if(is.na(delta.w) == TRUE){ t11 <- t0 second(t11) <- second(t11) + tlag + 3600 if(difftime(t11, t0, units = "secs") < tlag){ second(t11) <- second(t11) + 3600 } second(t0) <- second(t11) }else{ second(t0) <- second(t0) + tlag} } }else{ importFlw[[iclt]] <- t0 t0 <- t0 + tlag } importFlw[[iclvr]]<- NA if(date.format[1] == "POSIX" && bytime != "%d"){ if(hour(importFlw[[iclt]]) == 0 && minute(importFlw[[iclt]]) == 0 && second(importFlw[[iclt]]) == 0){ importFlw[[iclt]] <- format(round(as.POSIXlt(importFlw[[iclt]], format="%Y-%m-%d %H:%M:%S")), "%Y-%m-%d %H:%M:%S") }} importFlw[[iclt]] <- as.character(importFlw[[iclt]]) importFlfull <- rbind(importFlfull,importFlw) if(date_format != 0){ if(bytime == "%d" || bytime == "%H" || bytime == "%M" || bytime == "%S"){ if(bytime == "%d"){delta.time <- difftime(t1, t0, units = "days")} if(bytime == "%H"){delta.time <- difftime(t1, t0, units = "hours")} if(bytime == "%M"){delta.time <- difftime(t1, t0, units = "mins")} if(bytime == "%S"){delta.time <- difftime(t1, t0, units = "secs")} }else{ if(bytime == "%m"){ delta.time <- length(seq(from=as.Date(t0), to=as.Date(t1), by='month')) - 1 }else{ if(bytime == "%q"){ delta.time <- length(seq(from=as.Date(t0), to=as.Date(t1), by='quarter')) - 1 } } } }else{ delta.time <- t1-t0 } } importFlw <- importFl1[i,] if(date.format[1] == "POSIX" && bytime != "%d"){ if(hour(importFlw[[iclt]]) == 0 && minute(importFlw[[iclt]]) == 0 && second(importFlw[[iclt]]) == 0){ importFlw[[iclt]] <- format(round(as.POSIXlt(importFlw[[iclt]], format="%Y-%m-%d %H:%M:%S")), "%Y-%m-%d %H:%M:%S") }} importFlw[[iclt]] <- as.character(importFlw[1, iclt]) importFlfull <- rbind(importFlfull, importFlw) i <- i +1 j <- j+1 } } if(importFl1[ndata,iclt] != tpar2){ t2 <- importFl1[ndata,iclt] if(date_format != 0){ if(date.format[1] == "Date" || date.format[1] == "POSIX"){ if(bytime == "%d"){ t2 <- as.POSIXlt(as.Date(t2)) }else{t2 <- as.POSIXlt(t2)} }else{ if(date.format[1] == "yearmon"){ t2 <- as.POSIXlt(as.yearmon(t2)) } if(date.format[1] == "yearqtr"){t2 <- as.POSIXlt(as.yearqtr(t2))} }}else{t2 <- as.numeric(t2)} importFlw <-importFl1[ndata,] if(date_format != 0){ if(bytime == "%d" || bytime == "%H" || bytime == "%M" || bytime == "%S"){ if(bytime == "%d"){delta.time <- difftime(tpar2, t2, units = "days")} if(bytime == "%H"){delta.time <- difftime(tpar2, t2, units = "hours")} if(bytime == "%M"){delta.time <- difftime(tpar2, t2, units = "mins")} if(bytime == "%S"){delta.time <- difftime(tpar2, t2, units = "secs")} }else{ if(bytime == "%m"){ delta.time <- length(seq(from=as.Date(t2), to=as.Date(tpar2), by='month')) - 1 }else{ if(bytime == "%q"){ delta.time <- length(seq(from=as.Date(t2), to=as.Date(tpar2), by='quarter')) - 1 } } } }else{ delta.time <- tpar2-t2 } while(delta.time >= tlag){ j <- j +1 if(as.integer(j/500) == (j/500) ){ message("The first ", j, " values have been included in the data file.") } if(date_format != 0){ if(bytime == "%Y" || bytime == "%y"){ year(t2) <- year(t2) + tlag } if(bytime == "%d"){ day(t2) <- day(t2) + tlag } if(bytime == "%m"){ month(t2) <- month(t2) + tlag } if(bytime == "%q"){ month(t2) <- month(t2) + tlag*3 } if(bytime == "%H"){ delta.w <- t2 hour(delta.w) <- hour(t2) + tlag if(is.na(delta.w) == TRUE){ t11 <- t2 hour(t11) <- hour(t11) + tlag + 1 if(difftime(t11, t2, units = "hours") < tlag){ hour(t11) <- hour(t11) + 1 } hour(t2) <- hour(t11) }else{ hour(t2) <- hour(t2) + tlag} } if(bytime == "%M"){ delta.w <- t2 minute(delta.w) <- minute(t2) + tlag if(is.na(delta.w) == TRUE){ t11 <- t2 minute(t11) <- minute(t11) + tlag + 60 if(difftime(t11, t2, units = "mins") < tlag){ minute(t11) <- minute(t11) + 60 } minute(t2) <- minute(t11) }else{ minute(t2) <- minute(t2) + tlag} } if(bytime == "%S"){ delta.w <- t2 second(delta.w) <- second(t2) + tlag if(is.na(delta.w) == TRUE){ t11 <- t2 second(t11) <- second(t11) + tlag + 3600 if(difftime(t11, t2, units = "secs") < tlag){ second(t11) <- second(t11) + 3600 } second(t2) <- second(t11) }else{ second(t2) <- second(t2) + tlag} } if(date.format[1] == "Date" || date.format[1] == "POSIX"){ if(bytime == "%d"){ importFlw[[iclt]] <- as.POSIXlt(as.Date(t2)) }else{ importFlw[[iclt]] <- as.POSIXlt(t2)} }else{ if(date.format[1] == "yearmon"){ importFlw[[iclt]] <- as.POSIXlt(as.yearmon(t2)) } if(date.format[1] == "yearqtr"){ importFlw[[iclt]] <- as.POSIXlt(as.yearqtr(t2)) } } }else{ t2 <- t2 + tlag importFlw[[iclt]] <- t2 } importFlw[[iclvr]] <- NA if(date.format[1] == "POSIX" && bytime != "%d"){ if(hour(importFlw[[iclt]]) == 0 && minute(importFlw[[iclt]]) == 0 && second(importFlw[[iclt]]) == 0){ importFlw[[iclt]] <- format(round(as.POSIXlt(importFlw[[iclt]], format="%Y-%m-%d %H:%M:%S")), "%Y-%m-%d %H:%M:%S") }} importFlw[[iclt]] <- as.character(importFlw[[iclt]]) importFlfull <- rbind(importFlfull, importFlw) if(date_format != 0){ if(bytime == "%d" || bytime == "%H" || bytime == "%M" || bytime == "%S"){ if(bytime == "%d"){delta.time <- difftime(tpar2, t2, units = "days")} if(bytime == "%H"){delta.time <- difftime(tpar2, t2, units = "hours")} if(bytime == "%M"){delta.time <- difftime(tpar2, t2, units = "mins")} if(bytime == "%S"){delta.time <- difftime(tpar2, t2, units = "secs")} }else{ if(bytime == "%m"){ delta.time <- length(seq(from=as.Date(t2), to=as.Date(tpar2), by='month')) - 1 }else{ if(bytime == "%q"){ delta.time <- length(seq(from=as.Date(t2), to=as.Date(tpar2), by='quarter')) - 1 } } } }else{delta.time <- tpar2-t2} } } if(date_format != 0){ if(date.format[1] == "Date" || date.format[1] == "POSIX"){ if(bytime == "%d"){ importFlfull[[iclt]] <- as.Date(as.character(importFlfull[[iclt]]), format = date_format) }else{ importFlfull[[iclt]] <- as.POSIXlt(importFlfull[[iclt]], format = date_format, tz = time.zone) }}else{ if(date.format[1] == "yearmon"){ importFlfull[[iclt]] <- as.yearmon(importFlfull[[iclt]], format = date_format) } if(date.format[1] == "yearqtr"){ importFlfull[[iclt]] <- as.yearqtr(importFlfull[[iclt]], format = date_format)} }}else{importFlfull[[iclt]] <- as.numeric(importFlfull[[iclt]])} n.time <- length(unique(importFlfull[, iclt])) if (iclsp == 0) { ID_points <- c(rep(1:n.stat, each = n.time)) ID_points <- paste("id_", ID_points , sep = "") importFlfull[,"iclsp"] <- ID_points } if (save.as == "data.frame") { if (date_format != 0 || iflagt == 1) { ID_times <- c(rep(1:n.time, times = n.stat)) importFlfull[,"timeIndex"] <- ID_times importFlfull <- importFlfull[,c("iclsp", "iclx","icly","timeIndex","iclt","iclvr")] colnames(importFlfull) <- c("spatialIndex","x","y","timeIndex","date","variable") }else{ importFlfull <- importFlfull[,c("iclsp", "iclx","icly","iclt","iclvr")] colnames(importFlfull) <- c("spatialIndex","x","y","timeIndex","variable")} return(importFlfull) } if (save.as == "STFDF") { if(date_format == 0 && iflagt == 0){ message("Start error message. The data set cannot be saved as STFDF since time information is missing.") stop("End error message. Stop running.") } importFl <- importFlfull sp <- cbind(importFl[, iclx], importFl[, icly]) sp <- unique(sp) sp.names <- unique(importFl[, iclsp]) colnames(sp) <- c("x", "y") sp2 <- sp::SpatialPoints(sp) row.names(sp2) <- sp.names n.time <- length(unique(importFl[, iclt])) if(iflagt == 1){ importFl[[iclt]]<-as.character(importFl[,iclt]) data.time <- (as.Date(unique(importFl[,iclt]), format = date.format[2])) month(data.time) <- 1 day(data.time) <- 1 }else{data.time <- unique(importFl[,iclt])} mydata <- importFl[, iclvr] mydata <- matrix(mydata, ncol = n.time, byrow = TRUE) stfdf <- STFDF(sp2, data.time, data.frame(variable = as.vector(as.matrix(mydata)))) return(stfdf) } }
styleSingle <- function(col, lwd, alpha, fill, fill.alpha, rad, marker) { style <- NULL if(!missing(marker)) { if(length(marker)==1) { style <- append(style, paste0("icon: null, color: \"", getHex(marker), "\", size: \"m\"")) } else if(length(marker)==3) { if(is.na(marker[1])) marker[1] <- "null" else marker[1] <- paste0("\"", marker[1], "\"") if(is.na(marker[2])) marker[2] <- "null" else marker[2] <- paste0("\"", getHex(marker[2]), "\"") if(is.na(marker[3])) marker[3] <- "\"m\"" else marker[3] <- paste0("\"", marker[3], "\"") style <- append(style, paste0("icon: ", marker[1], ", color: ", marker[2], ", size: ", marker[3])) } else stop("Markers are specified by 'icon', 'color' and 'size' or just by 'color' value") attr(style, "marker") <- "marker" } else { if(!missing(col)) { if(is.na(col)) style <- append(style, "stroke: false") else style <- append(style, paste("color: \"", getHex(col), "\"", sep="")) } if(!missing(lwd)) { if(missing(col)) style <- append(style, paste("weight:", lwd)) else if(!is.na(col)) style <- append(style, paste("weight:", lwd)) } if(!missing(alpha)) { if(missing(col)) style <- append(style, paste("opacity:", alpha)) else if(!is.na(col)) style <- append(style, paste("opacity:", alpha)) } if(!missing(fill)) { if(is.na(fill)) style <- append(style, "fill: false") else style <- append(style, paste("fillColor: \"", getHex(fill), "\"", sep="")) } if(!missing(fill.alpha)) { if(missing(fill)) style <- append(style, paste("fillOpacity:", fill.alpha)) else if(!is.na(fill)) style <- append(style, paste("fillOpacity:", fill.alpha)) } if(!missing(rad)) style <- append(style, paste("radius:", rad)) } if(is.null(style)) stop("No style parameters defined") attr(style, "style.type") <- "single" class(style) <- c("leafletr.style", "single.style") return(style) }
get_kcal_vo2_conversion <- function( RER, kcal_table = c("Lusk", "Peronnet", "both") ) { kcal_table <- match.arg( kcal_table, c("Lusk", "Peronnet", "both", "ERROR"), TRUE ) if ("both" %in% kcal_table) kcal_table <- c("Lusk", "Peronnet") sapply( kcal_table, function(x) { kcal_table <- switch( x, "Lusk" = lusk, "Peronnet" = peronnet ) index <- which.min( abs(kcal_table$Non_Protein_RQ - RER) ) kcal_table$kCal_per_Liter_O2_Uptake[index] } ) }
digitize2d <- function (filelist, nlandmarks, scale=NULL, tpsfile, MultScale=FALSE,verbose = TRUE) { flist <- dir() if (sum(which(flist == tpsfile)) == 0) { newdata <- array(0, c(nlandmarks, 2, length(filelist))) dimnames(newdata)[[3]] <- as.list(filelist) writeland.tps(newdata, tpsfile) } olddat <- readland.tps2(file=tpsfile, specID = "ID") newdata<-olddat$coords inscale<-olddat$scale names <- dimnames(newdata)[[3]] if (dim(newdata)[3] != length(filelist)) { stop("Filelist not the same length as input TPS file.") } if (length(na.omit(match(names, filelist))) != length(filelist)) { stop("Filelist does not contain the same specimens as TPS file.") } if(length(scale) != length(filelist)){ if(length(scale)==1) { cat("Only 1 scale measure provided. Will use scale =", scale, " for all specimens.\n") scale = rep(scale, length(filelist)) } } digitized <- apply(two.d.array(newdata), 1, sum) digstart <- min(which(digitized == 0)) if(is.infinite(digstart)){ stop("It appears that all specimens have already been digitized.") } scalebar=vector(length=length(filelist)) if(digstart>1){scalebar[1:(digstart-1)]<-inscale[1:(digstart-1)]} for (i in digstart:length(filelist)) { cat(paste("Digitizing specimen", i, "in filelist"), "\n") spec.name <- unlist(strsplit(basename(filelist[i]), "\\."))[1] specimen <- readJPEG(filelist[i], native = T) plot(seq(0, dim(specimen)[2], length.out = 10), seq(0, dim(specimen)[1], length.out = 10), type = "n", xlab = "x", ylab = "y", asp = 1, tck = 0, xaxt = "n", yaxt = "n") rasterImage(specimen, 1, 1, dim(specimen)[2], dim(specimen)[1]) if (is.null(scale)) { cat("Scale not provided! Proceed with caution.\n") scalebar = NULL } if (!is.null(scale)) { cat("Set scale =", scale[i], "\n") scalebar[i] <- picscale(scale[i]) } selected <- matrix(NA, nrow = nlandmarks, ncol = 2) fix <- NULL if (verbose == TRUE) { for (ii in 1:nlandmarks) { cat("Select landmark ", ii, "\n") keep <- ans <- NULL fix <- locator(n = 1, type = "p", col = "black", cex = 4, pch = 21, bg = "red") cat(paste("Keep Landmark ", ii, "(y/n/a)?"), "\n") ans <- readLines(n = 1) if (ans == "y") { selected[ii, 1] <- fix$x selected[ii, 2] <- fix$y } if (ans == "a") { selected[ii, 1] <- NA selected[ii, 2] <- NA points(fix, type = "n", col = "black", cex = 1, pch = 21, bg = "red") } if (ans == "n") { cat(paste("Select Landmark ", ii, " Again"), "\n") } while (ans == "n") { fix <- locator(n = 1, type = "p", col = "black", cex = 4, pch = 21, bg = "red") cat(paste("Keep Landmark ", ii, "(y/n)?"), "\n") ans <- readLines(n = 1) if (ans == "y") { selected[ii, 1] <- fix$x selected[ii, 2] <- fix$y } if (ans == "n") { cat(paste("Select Landmark ", ii, " Again"), "\n") } } } } if (verbose == FALSE) { cat("Select landmarks 1:", nlandmarks, "\n", sep = "") for (ii in 1:nlandmarks) { fix <- locator(n = 1, type = "p", col = "black", cex = 4, pch = 21, bg = "red") selected[ii, 1] <- fix$x selected[ii, 2] <- fix$y } } newdata[, , i] <- selected if(MultScale==TRUE){newdata[,,i]<-selected*scalebar[i]} if(is.null(scalebar)){writeland.tps(newdata, tpsfile)} if(!is.null(scalebar) && MultScale==FALSE){ writeland.tps(newdata, tpsfile, scale = scalebar)} if(!is.null(scalebar) && MultScale==TRUE){ writeland.tps(newdata, tpsfile)} if (i < length(filelist)) { cat(paste("Continue to next specimen (y/n)?"), "\n") ans <- readLines(n = 1) if (ans == "n") { break } } } cat(paste("All specimens from session have been digitized to", tpsfile), "\n") }
mvmscjs=function(x,ddl,fullddl,dml,model_data=NULL,parameters,accumulate=TRUE,initial=NULL,method, hessian=FALSE,debug=FALSE,chunk_size=1e7,refit,itnmax=NULL,control=NULL,scale, re=FALSE,compile=FALSE,extra.args="",clean=TRUE,sup,...) { accumulate=FALSE nocc=x$nocc xstart=x$start if(!is.null(ddl$Phi$time.interval)) time.intervals=matrix(fullddl$Phi$time.interval[fullddl$Phi$stratum==x$strata.labels[1]],nrow(x$data),ncol=nocc-1,byrow=TRUE) else if(is.vector(x$time.intervals)) time.intervals=matrix(x$time.intervals,nrow=nrow(x$data),ncol=nocc-1,byrow=TRUE) else time.intervals=x$time.intervals chmat=x$ehmat strata.labels=x$strata.labels uS=x$unobserved x=x$data freq=NULL if(!is.null(x$freq))freq=x$freq ch=x$ch imat=process.ch(ch,freq,all=FALSE) if(is.null(initial)) { par=list(Psi=rep(0,ncol(dml$Psi$fe)), p=rep(0,ncol(dml$p$fe)), Phi=rep(0,ncol(dml$Phi$fe))) if(ncol(dml$pi$fe)>0) par$pi=rep(0,ncol(dml$pi$fe)) if(ncol(dml$delta$fe)>0) par$delta=rep(0,ncol(dml$delta$fe)) } else par=set.initial(names(dml),dml,initial)$par model_data=list(Phi.dm=dml$Phi$fe,p.dm=dml$p$fe,Psi.dm=dml$Psi$fe,delta.dm=dml$delta$fe,pi.dm=dml$pi$fe,imat=imat,Phi.fixed=parameters$Phi$fixed, p.fixed=parameters$p$fixed,Psi.fixed=parameters$Psi$fixed,delta.fixed=parameters$delta$fixed, pi.fixed=parameters$pi$fixed,time.intervals=time.intervals) if(accumulate) { cat("Accumulating capture histories based on design. This can take awhile.\n") flush.console() model_data.save=model_data }else model_data.save=model_data scale=1 scale=set.scale(names(dml),model_data,scale) model_data=scale.dm(model_data,scale) if(!re) tpl="mvms" else stop("random effect portion not completed for this model") setup_admb(tpl,compile,clean,re=FALSE) con=file(paste(tpl,".dat",sep=""),open="wt") n=length(model_data$imat$freq) write(n,con,append=FALSE) nocc=model_data$imat$nocc write(nocc,con,append=TRUE) nS=length(strata.labels) write(nS,con,append=TRUE) nobs=length(sup$obslevels) write(nobs,con,append=TRUE) write(sup$np,con,append=TRUE) write(t(chmat),con,ncolumns=nocc,append=TRUE) write(model_data$imat$first,con,ncolumns=n,append=TRUE) if(!re) { write(model_data$imat$freq,con,ncolumns=n,append=TRUE) } else { if(any(model_data$imat$freq!=1))stop("\n cannot use random effects with frequency >1") } write(t(model_data$time.intervals),con,ncolumns=nocc-1,append=TRUE) if(!is.null(ddl$Phi$fix)) model_data$Phi.dm[!is.na(ddl$Phi$fix),]=0 if(ncol(model_data$Phi.dm)!=0) { select=vector("logical",length=ncol(model_data$Phi.dm)) for (i in 1:ncol(model_data$Phi.dm)) select[i]=any(model_data$Phi.dm[,i]!=0) model_data$Phi.dm=model_data$Phi.dm[,select,drop=FALSE] } phidm=model_data$Phi.dm phifix=rep(-1,nrow(phidm)) if(!is.null(ddl$Phi$fix)) phifix[!is.na(ddl$Phi$fix)]=ddl$Phi$fix[!is.na(ddl$Phi$fix)] slist=simplify_indices(cbind(phidm,phifix)) write(ncol(phidm),con,append=TRUE) write(length(slist$set),con,append=TRUE) if(ncol(phidm)>0) write(t(phidm[slist$set,,drop=FALSE]),con,ncolumns=ncol(phidm),append=TRUE) write(phifix[slist$set],con,append=TRUE) write(slist$indices[ddl$Phi.indices],con,append=TRUE) if(!is.null(ddl$p$fix)) model_data$p.dm[!is.na(ddl$p$fix),]=0 if(ncol(model_data$p.dm)!=0) { select=vector("logical",length=ncol(model_data$p.dm)) for (i in 1:ncol(model_data$p.dm)) select[i]=any(model_data$p.dm[,i]!=0) model_data$p.dm=model_data$p.dm[,select,drop=FALSE] } pdm=model_data$p.dm pfix=rep(-1,nrow(pdm)) if(!is.null(ddl$p$fix)) pfix[!is.na(ddl$p$fix)]=ddl$p$fix[!is.na(ddl$p$fix)] slist=simplify_indices(cbind(pdm,pfix)) write(ncol(pdm),con,append=TRUE) write(length(slist$set),con,append=TRUE) if(ncol(pdm)>0) write(t(pdm[slist$set,,drop=FALSE]),con,ncolumns=ncol(pdm),append=TRUE) write(pfix[slist$set],con,append=TRUE) write(slist$indices[ddl$p.indices],con,append=TRUE) write(nrow(sup$indices_forp),con,append=TRUE) write(t(sup$indices_forp),con,append=TRUE) if(!is.null(ddl$Psi$fix)) model_data$Psi.dm[!is.na(ddl$Psi$fix),]=0 if(ncol(model_data$Psi.dm)!=0) { select=vector("logical",length=ncol(model_data$Psi.dm)) for (i in 1:ncol(model_data$Psi.dm)) select[i]=any(model_data$Psi.dm[,i]!=0) model_data$Psi.dm=model_data$Psi.dm[,select,drop=FALSE] } psidm=model_data$Psi.dm psifix=rep(-1,nrow(psidm)) if(!is.null(ddl$Psi$fix)) psifix[!is.na(ddl$Psi$fix)]=ddl$Psi$fix[!is.na(ddl$Psi$fix)] slist=simplify_indices(cbind(psidm,psifix)) write(ncol(psidm),con,append=TRUE) write(length(slist$set),con,append=TRUE) if(ncol(psidm)>0) write(t(psidm[slist$set,,drop=FALSE]),con,ncolumns=ncol(psidm),append=TRUE) write(psifix[slist$set],con,append=TRUE) write(slist$indices[ddl$Psi.indices],con,append=TRUE) if(!is.null(ddl$delta$fix)) model_data$delta.dm[!is.na(ddl$delta$fix),]=0 if(ncol(model_data$delta.dm)!=0) { select=vector("logical",length=ncol(model_data$delta.dm)) for (i in 1:ncol(model_data$delta.dm)) select[i]=any(model_data$delta.dm[,i]!=0) model_data$delta.dm=model_data$delta.dm[,select,drop=FALSE] } deltadm=model_data$delta.dm deltafix=rep(-1,nrow(deltadm)) if(!is.null(ddl$delta$fix)) deltafix[!is.na(ddl$delta$fix)]=ddl$delta$fix[!is.na(ddl$delta$fix)] slist=simplify_indices(cbind(deltadm,deltafix)) write(ncol(deltadm),con,append=TRUE) write(length(slist$set),con,append=TRUE) if(ncol(deltadm)>0) write(t(deltadm[slist$set,,drop=FALSE]),con,ncolumns=ncol(deltadm),append=TRUE) write(deltafix[slist$set],con,append=TRUE) write(slist$indices[ddl$delta.indices],con,append=TRUE) if(!is.null(ddl$pi$fix)) model_data$pi.dm[!is.na(ddl$pi$fix),]=0 if(ncol(model_data$pi.dm)!=0) { select=vector("logical",length=ncol(model_data$pi.dm)) for (i in 1:ncol(model_data$pi.dm)) select[i]=any(model_data$pi.dm[,i]!=0) model_data$pi.dm=model_data$pi.dm[,select,drop=FALSE] } pidm=model_data$pi.dm pifix=rep(-1,nrow(pidm)) if(!is.null(ddl$pi$fix)) pifix[!is.na(ddl$pi$fix)]=ddl$pi$fix[!is.na(ddl$pi$fix)] slist=simplify_indices(cbind(pidm,pifix)) write(ncol(pidm),con,append=TRUE) write(length(slist$set),con,append=TRUE) if(ncol(pidm)>0) write(t(pidm[slist$set,,drop=FALSE]),con,ncolumns=ncol(pidm),append=TRUE) write(pifix[slist$set],con,append=TRUE) write(slist$indices[ddl$pi.indices],con,append=TRUE) unkinit=as.numeric(all(is.na(xstart[,1])) | all(!is.na(xstart[,1]))) write(unkinit,con,append=TRUE) if(!debug) write(0,con,append=TRUE) else write(1,con,append=TRUE) close(con) con=file(paste(tpl,".pin",sep=""),open="wt") if(ncol(dml$Phi$fe)>0) write(par$Phi,con,ncolumns=length(par$Phi),append=FALSE) if(ncol(dml$p$fe)>0) write(par$p,con,ncolumns=length(par$p),append=TRUE) if(ncol(dml$delta$fe)>0) write(par$delta,con,ncolumns=length(par$delta),append=TRUE) if(ncol(dml$Psi$fe)>0) write(par$Psi,con,ncolumns=length(par$Psi),append=TRUE) if(ncol(dml$pi$fe)>0) write(par$pi,con,ncolumns=length(par$pi),append=TRUE) close(con) if(hessian) xx=run_admb(tpl,extra.args=extra.args) else xx=run_admb(tpl,extra.args=paste(extra.args,"-nohess")) convergence=attr(xx,"status") if(is.null(convergence))convergence=0 res=read_admb(tpl) beta=list(unscale.par(c(res$coeflist$phibeta,res$coeflist$pbeta,res$coeflist$dbeta,res$coeflist$psibeta,res$coeflist$pi),scale)) parnames=names(unlist(beta)) fixed.npar=length(unlist(beta)) if(!is.null(res$hes)) { beta.vcv=solvecov(res$hes)$inv rownames(res$hes)=parnames colnames(res$hes)=rownames(res$hes) if(all(diag(beta.vcv>0))) res$cor=beta.vcv/outer(sqrt(diag(beta.vcv)),sqrt(diag(beta.vcv))) } else beta.vcv=res$vcov rownames(beta.vcv)=parnames colnames(beta.vcv)=rownames(beta.vcv) rownames(res$cor)=rownames(beta.vcv) colnames(res$cor)=rownames(beta.vcv) res$vcov=NULL optim.details=c(fn=res$fn,maxgrad=res$maxgrad,eratio=res$eratio) options=list(extra.args=extra.args) res$cor=NULL res$maxgrad=NULL results=c(beta=beta,neg2lnl=-2*res$loglik,AIC=-2*res$loglik+2*res$npar,convergence=convergence) results$hessian=res$hes results$optim.details=optim.details results$options=options results$coeflist=res$coeflist results$npar=list(npar=res$npar,npar_sdrpt=res$npar_sdrpt,npar_total=res$npar_total) results$beta.vcv=beta.vcv res=results res$model_data=model_data.save class(res)=c("crm","admb","mle","mvmscjs") return(res) }
IBM_theoretical_contrast <- function(par, theo.par, fixed.p.X = NULL, G = NULL, comp.dist, comp.param, sample1, sample2) { stopifnot( (length(comp.dist) == 4) & (length(comp.param) == 4) ) if (any(sapply(comp.dist, is.null)) | any(sapply(comp.param, is.null))) { stop("All components must be specified in the two admixture models to be able to compute the theoretical contrast.") } exp.comp.dist <- paste0("p", comp.dist) if (any(exp.comp.dist == "pmultinom")) { exp.comp.dist[which(exp.comp.dist == "pmultinom")] <- "stepfun" } comp_theo <- sapply(X = exp.comp.dist, FUN = get, pos = "package:stats", mode = "function") for (i in 1:length(comp_theo)) assign(x = names(comp_theo)[i], value = comp_theo[[i]]) make.expr.step <- function(i) paste(names(comp_theo)[i],"(x = 1:", length(comp.param[[i]][[2]]), paste(", y = ", paste("cumsum(c(0,", paste(comp.param[[i]][[2]], collapse = ","), "))", sep = ""), ")", sep = ""), sep = "") make.expr <- function(i) paste(names(comp_theo)[i],"(z,", paste(names(comp.param[[i]]), "=", comp.param[[i]], sep = "", collapse = ","), ")", sep="") expr <- vector(mode = "character", length = length(exp.comp.dist)) expr[which(exp.comp.dist == "stepfun")] <- sapply(which(exp.comp.dist == "stepfun"), make.expr.step) expr[which(expr == "")] <- sapply(which(expr == ""), make.expr) expr <- unlist(expr) if (any(exp.comp.dist == "stepfun")) { F1.fun <- eval(parse(text = expr[1])) G1.fun <- eval(parse(text = expr[2])) F2.fun <- eval(parse(text = expr[3])) G2.fun <- eval(parse(text = expr[4])) F1 <- function(z) F1.fun(z) G1 <- function(z) G1.fun(z) F2 <- function(z) F2.fun(z) G2 <- function(z) G2.fun(z) } else { F1 <- function(z) { eval(parse(text = expr[1])) } G1 <- function(z) { eval(parse(text = expr[2])) } F2 <- function(z) { eval(parse(text = expr[3])) } G2 <- function(z) { eval(parse(text = expr[4])) } } G1equalG2 <- is_equal_knownComp(comp.dist, comp.param) support <- detect_support_type(sample1, sample2) if (support == "continuous") { densite.G <- stats::density(G, bw = "SJ", adjust = 0.5, kernel = "gaussian") supp.integration <- c(min(G), max(G)) } else { supp.integration <- G } if (is.null(fixed.p.X)) { integrand <- function(z, par) { if (support == "continuous") { densite.G.dataPoint <- stats::approx(densite.G$x, densite.G$y, xout = z)$y } else { densite.G.dataPoint <- 1 / length(table(c(sample1,sample2))) } F.X.dataPoint <- (1/par[1]) * ((theo.par[1]*F1(z) + (1-theo.par[1])*G1(z)) - (1-par[1])*G1(z)) F.Y.dataPoint <- (1/par[2]) * ((theo.par[2]*F2(z) + (1-theo.par[2])*G2(z)) - (1-par[2])*G2(z)) weighted.difference <- (F.X.dataPoint - F.Y.dataPoint)^2 * densite.G.dataPoint weighted.difference } } else { if (G1equalG2) stopifnot(!is.null(fixed.p.X)) integrand <- function(z, par) { if (support == "continuous") { densite.G.dataPoint <- stats::approx(densite.G$x, densite.G$y, xout = z)$y } else { densite.G.dataPoint <- 1 / length(table(c(sample1,sample2))) } F.X.dataPoint <- (1/fixed.p.X) * ((theo.par[1]*F1(z) + (1-theo.par[1])*G1(z)) - (1-fixed.p.X)*G1(z)) F.Y.dataPoint <- (1/par) * ((theo.par[2]*F2(z) + (1-theo.par[2])*G2(z)) - (1-par)*G2(z)) weighted.difference <- (F.X.dataPoint - F.Y.dataPoint)^2 * densite.G.dataPoint weighted.difference } } if (support == "continuous") { res <- stats::integrate(integrand, lower = supp.integration[1], upper = supp.integration[2], par, subdivisions = 10000L, rel.tol = 1e-03)$value } else { res <- sum( unlist(sapply(supp.integration, integrand, par)) ) } return(res) }
library(knitr) opts_chunk$set(comment = "", warning = FALSE, message = FALSE, fig.height = 4.94, fig.width = 8, out.width = "690px", out.height = "426px") oldOpt <- options(scipen = 10, width = 95) Hilbert <- function(n) { structure(outer(1:n, 1:n, function(r, c) 1/(r+c-1)), dimnames = list(paste0("R",1:n), paste0("C", 1:n))) } H5 <- Hilbert(5) kable(H5, align = "c") library(dplyr) library(fractional) H5 %>% fractional %>% as.character %>% kable(align = "r") library(dplyr) (x <- matrix(1:9/12, 3, 3) %>% fractional) (xr <- 1/x) x + 10 (x2 <- x^2) (sx2 <- sqrt(x2)) fractional(sx2) solve(xr) %>% fractional numerators(x2) denominators(x2) oldWidth <- options(width = 80) F <- c(1,1,numeric(15)) for(i in 3:17) F[i] <- F[i-1] + F[i-2] F (phi <- (sqrt(5) + 1)/2) vfractional(phi, eps = 0, maxConv = 1:16) options(oldWidth) library(ggplot2) N <- 500000 set.seed(3210) rat(rnorm(N), eps = 1.0e-07)[, "n"] %>% table(x = .) %>% as.data.frame(responseName = "f") %>% ggplot(.) + aes(x = x, y = f/N) + geom_bar(stat = "identity", fill = "steel blue") + ylab("Relative frequency") + xlab("Convergents")
library(sievetest) data(lignite) fi <- system.file("lignite.csv",package="sievetest",mustWork=T) my_std <- read.std(file=fi) plot(lignite) plot(my_std) plot(lignite[1]) summary(lignite) sieve_aperture_size <- c(500, 200, 90, 0) mass_ppc_retained <- c(1.01, 24, 42.8, 32.190) md <- desc.std(Title="Coal powder, learning std") my_std2 <- std(a=sieve_aperture_size, r=mass_ppc_retained, desc=md) new_gr <- c(my_std2,lignite[2]) plot(new_gr) summary(lignite[[2]]$lmfit) newdesc <- desc.std(Title="Lignite (weghted lm)",x=lignite[2]) lignite_twk <- tweak.std(x=lignite[2],lmargs=list(weights=c(0,1,1,1)),desc=newdesc) new_gr2 <- c(lignite[2],lignite_twk) plot(new_gr2)
gg_roc.rfsrc <- function(object, which.outcome, oob=TRUE, ...){ if (sum(inherits(object, c("rfsrc", "grow"), TRUE) == c(1, 2)) != 2 & sum(inherits(object, c("rfsrc", "predict"), TRUE) == c(1, 2)) != 2 & !inherits(object, "randomForest")) { stop("This function only works for objects of class `(rfsrc, grow)', '(rfsrc, predict)' or 'randomForest.") } if(!inherits(object, "class")){ stop("gg_roc only works with classification forests") } if(missing(which.outcome)) which.outcome <- "all" if(object$family != "class") stop("gg_roc is intended for classification forests only.") gg_dta <- calc_roc.rfsrc(object, object$yvar, which.outcome=which.outcome, oob=oob) class(gg_dta) <- c("gg_roc", class(gg_dta)) invisible(gg_dta) } gg_roc <- function (object, which.outcome, oob, ...) { UseMethod("gg_roc", object) } gg_roc.randomForest <- function(object, ...){ stop("gg_roc is not yet support for randomForest objects") } gg_roc.default <- gg_roc.rfsrc
s0 <- function() { activities <- data.frame( id = c( 1, 2, 3), name = c("A", "B", "C"), duration = c( 3, 2, 4) ) relations <- data.frame( from = c(), to = c() ) schedule <- Schedule$new(activities, relations) schedule$title <- "A project" schedule$reference <- "From criticalpath" schedule } s1 <- function() { activities <- data.frame( id = c( 1, 2, 3), name = c("A", "B", "C"), duration = c( 3, 2, 4) ) relations <- data.frame( from = c(1), to = c(2) ) schedule <- Schedule$new(activities, relations) schedule$title <- "A project" schedule$reference <- "From criticalpath" schedule } s2 <- function() { activities <- data.frame( id = c( 1, 2, 3), name = c("A", "B", "C"), duration = c( 3, 2, 4) ) relations <- data.frame( from = c(1), to = c(3) ) schedule <- Schedule$new(activities, relations) schedule$title <- "A project" schedule$reference <- "From criticalpath" schedule } s3 <- function() { activities <- data.frame( id = c( 1, 2, 3), name = c("A", "B", "C"), duration = c( 3, 2, 4) ) relations <- data.frame( from = c(1, 1), to = c(2, 3) ) schedule <- Schedule$new(activities, relations) schedule$title <- "A project" schedule$reference <- "From criticalpath" schedule } s4 <- function() { activities <- data.frame( id = c( 1, 2, 3), name = c("A", "B", "C"), duration = c( 3, 2, 4) ) relations <- data.frame( from = c(2), to = c(3) ) schedule <- Schedule$new(activities, relations) schedule$title <- "A project" schedule$reference <- "From criticalpath" schedule } s5 <- function() { activities <- data.frame( id = c( 1, 2, 3), name = c("A", "B", "C"), duration = c( 3, 2, 4) ) relations <- data.frame( from = c(1, 2), to = c(2, 3) ) schedule <- Schedule$new(activities, relations) schedule$title <- "A project" schedule$reference <- "From criticalpath" schedule } s6 <- function() { activities <- data.frame( id = c( 1, 2, 3), name = c("A", "B", "C"), duration = c( 3, 2, 4) ) relations <- data.frame( from = c(1, 2), to = c(3, 3) ) schedule <- Schedule$new(activities, relations) schedule$title <- "A project" schedule$reference <- "From criticalpath" schedule } s7 <- function() { activities <- data.frame( id = c( 1, 2, 3), name = c("A", "B", "C"), duration = c( 3, 2, 4) ) relations <- data.frame( from = c(1, 1, 2), to = c(2, 3, 3) ) schedule <- Schedule$new(activities, relations) schedule$title <- "A project" schedule$reference <- "From criticalpath" schedule } test_that("There is no Gantt matrix for a schedule with zero duration!", { schedule <- Schedule$new() schedule$add_activity(1) schedule$add_activity(2) schedule$add_activity(3) expect_error(schedule$gantt_matrix()) }) test_that("A,B,C", { schedule <- s0() expect_equal(schedule$duration, 4) mtx <- base::matrix( c( 1,1,1,0, 1,1,0,0, 1,1,1,1 ), byrow = TRUE, ncol = 4 ) gantt <- schedule$gantt_matrix() expect_true(identical(as.numeric(gantt[1,]), mtx[1,])) expect_true(identical(as.numeric(gantt[2,]), mtx[2,])) expect_true(identical(as.numeric(gantt[3,]), mtx[3,])) xygantt <- schedule$xy_gantt_matrix(gantt) expect_equal(nrow(xygantt), sum(gantt)) }) test_that("A->B, C", { schedule <- s1() expect_equal(schedule$duration, 5) gantt <- schedule$gantt_matrix() expect_true(identical(as.numeric(gantt[1,]), c(1,1,1,0,0))) expect_true(identical(as.numeric(gantt[2,]), c(0,0,0,1,1))) expect_true(identical(as.numeric(gantt[3,]), c(1,1,1,1,0))) xygantt <- schedule$xy_gantt_matrix(gantt) expect_equal(nrow(xygantt), sum(gantt)) }) test_that("A->C, B", { schedule <- s2() expect_equal(schedule$duration, 7) gantt <- schedule$gantt_matrix() expect_true(identical(as.numeric(gantt[1,]), c(1,1,1,0,0,0,0))) expect_true(identical(as.numeric(gantt[2,]), c(1,1,0,0,0,0,0))) expect_true(identical(as.numeric(gantt[3,]), c(0,0,0,1,1,1,1))) xygantt <- schedule$xy_gantt_matrix(gantt) expect_equal(nrow(xygantt), sum(gantt)) }) test_that("A->B, A->C", { schedule <- s3() expect_equal(schedule$duration, 7) gantt <- schedule$gantt_matrix() expect_true(identical(as.numeric(gantt[1,]), c(1,1,1,0,0,0,0))) expect_true(identical(as.numeric(gantt[2,]), c(0,0,0,1,1,0,0))) expect_true(identical(as.numeric(gantt[3,]), c(0,0,0,1,1,1,1))) xygantt <- schedule$xy_gantt_matrix(gantt) expect_equal(nrow(xygantt), sum(gantt)) }) test_that("B->C, A", { schedule <- s4() expect_equal(schedule$duration, 6) gantt <- schedule$gantt_matrix() expect_true(identical(as.numeric(gantt[1,]), c(1,1,1,0,0,0))) expect_true(identical(as.numeric(gantt[2,]), c(1,1,0,0,0,0))) expect_true(identical(as.numeric(gantt[3,]), c(0,0,1,1,1,1))) xygantt <- schedule$xy_gantt_matrix(gantt) expect_equal(nrow(xygantt), sum(gantt)) }) test_that("A->B, B->C", { schedule <- s5() expect_equal(schedule$duration, 9) gantt <- schedule$gantt_matrix() expect_true(identical(as.numeric(gantt[1,]), c(1,1,1,0,0,0,0,0,0))) expect_true(identical(as.numeric(gantt[2,]), c(0,0,0,1,1,0,0,0,0))) expect_true(identical(as.numeric(gantt[3,]), c(0,0,0,0,0,1,1,1,1))) xygantt <- schedule$xy_gantt_matrix(gantt) expect_equal(nrow(xygantt), sum(gantt)) }) test_that("A->C, B->C", { schedule <- s6() expect_equal(schedule$duration, 7) gantt <- schedule$gantt_matrix() expect_true(identical(as.numeric(gantt[1,]), c(1,1,1,0,0,0,0))) expect_true(identical(as.numeric(gantt[2,]), c(1,1,0,0,0,0,0))) expect_true(identical(as.numeric(gantt[3,]), c(0,0,0,1,1,1,1))) xygantt <- schedule$xy_gantt_matrix(gantt) expect_equal(nrow(xygantt), sum(gantt)) }) test_that("A->B, A->C, B->C", { schedule <- s7() expect_equal(schedule$duration, 9) gantt <- schedule$gantt_matrix() expect_true(identical(as.numeric(gantt[1,]), c(1,1,1,0,0,0,0,0,0))) expect_true(identical(as.numeric(gantt[2,]), c(0,0,0,1,1,0,0,0,0))) expect_true(identical(as.numeric(gantt[3,]), c(0,0,0,0,0,1,1,1,1))) xygantt <- schedule$xy_gantt_matrix(gantt) expect_equal(nrow(xygantt), sum(gantt)) }) test_that("First and last activity's durations equal zero ", { schedule <- Schedule$new() schedule$title <- "Fictitious Project Example" schedule$reference <- "VANHOUCKE, Mario. Measuring time: improving project performance using earned value management. Gent: Springer, 2009, p. 18" schedule$add_act_rel( 1, "a1" , 0, c(2,3,4)) schedule$add_act_rel( 2, "a2" , 4, c(5)) schedule$add_act_rel( 3, "a3" , 9, c(10)) schedule$add_act_rel( 4, "a4" , 1, c(6)) schedule$add_act_rel( 5, "a5" , 4, c(9)) schedule$add_act_rel( 6, "a6" , 5, c(7)) schedule$add_act_rel( 7, "a7" , 1, c(8,11)) schedule$add_act_rel( 8, "a8" , 7, c(12)) schedule$add_act_rel( 9, "a9" , 8, c(12)) schedule$add_act_rel( 10, "a10", 3, c(12)) schedule$add_act_rel( 11, "a11", 3, c(12)) schedule$add_act_rel( 12, "a12", 0) gantt <- schedule$gantt_matrix() expect_true(identical(as.numeric(gantt[ 1,]), c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0))) expect_true(identical(as.numeric(gantt[ 2,]), c(1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0))) expect_true(identical(as.numeric(gantt[ 3,]), c(1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0))) expect_true(identical(as.numeric(gantt[ 4,]), c(1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0))) expect_true(identical(as.numeric(gantt[ 5,]), c(0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0))) expect_true(identical(as.numeric(gantt[ 6,]), c(0,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0))) expect_true(identical(as.numeric(gantt[ 7,]), c(0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0))) expect_true(identical(as.numeric(gantt[ 8,]), c(0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0))) expect_true(identical(as.numeric(gantt[ 9,]), c(0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1))) expect_true(identical(as.numeric(gantt[10,]), c(0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0))) expect_true(identical(as.numeric(gantt[11,]), c(0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0))) expect_true(identical(as.numeric(gantt[12,]), c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0))) }) test_that("First and last activity's durations equal zero, and durations chagend.", { schedule <- Schedule$new() schedule$title <- "Fictitious Project Example" schedule$reference <- "VANHOUCKE, Mario. Measuring time: improving project performance using earned value management. Gent: Springer, 2009, p. 18" schedule$add_act_rel( 1, "a1" , 0, c(2,3,4)) schedule$add_act_rel( 2, "a2" , 4, c(5)) schedule$add_act_rel( 3, "a3" , 9, c(10)) schedule$add_act_rel( 4, "a4" , 1, c(6)) schedule$add_act_rel( 5, "a5" , 4, c(9)) schedule$add_act_rel( 6, "a6" , 5, c(7)) schedule$add_act_rel( 7, "a7" , 1, c(8,11)) schedule$add_act_rel( 8, "a8" , 7, c(12)) schedule$add_act_rel( 9, "a9" , 8, c(12)) schedule$add_act_rel( 10, "a10", 3, c(12)) schedule$add_act_rel( 11, "a11", 3, c(12)) schedule$add_act_rel( 12, "a12", 0) new_durations <- c(0, 6, 11, 1, 4, 3, 2, 8, 8, 5, 4, 0) schedule$change_durations(new_durations) gantt <- schedule$gantt_matrix() expect_true(identical(as.numeric(gantt[ 1,]), c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0))) expect_true(identical(as.numeric(gantt[ 2,]), c(1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0))) expect_true(identical(as.numeric(gantt[ 3,]), c(1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0))) expect_true(identical(as.numeric(gantt[ 4,]), c(1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0))) expect_true(identical(as.numeric(gantt[ 5,]), c(0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0))) expect_true(identical(as.numeric(gantt[ 6,]), c(0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0))) expect_true(identical(as.numeric(gantt[ 7,]), c(0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0))) expect_true(identical(as.numeric(gantt[ 8,]), c(0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0))) expect_true(identical(as.numeric(gantt[ 9,]), c(0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1))) expect_true(identical(as.numeric(gantt[10,]), c(0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0))) expect_true(identical(as.numeric(gantt[11,]), c(0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0))) expect_true(identical(as.numeric(gantt[12,]), c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0))) }) test_that("Período com número negativo deve funcionar.", { activities <- data.frame( id = c( 1L, 2L, 3L), name = c( "A", "B", "C"), duration = c( 5L, 8L, 10L) ) relations <- data.frame( from = c( 1L, 2L), to = c( 2L, 3L), type = c("FF", "FF"), lag = c( 0L, 0L) ) schedule <- Schedule$new(activities, relations) schedule$title <- "A project" schedule$reference <- "From criticalpath" gantt <- schedule$gantt_matrix() expect_true(identical(as.numeric(colnames(gantt)), c(-4, -3, -2, -1, 0, 1, 2, 3, 4, 5))) expect_true(identical(as.numeric(gantt[ 1,]), c(0,0,0,0,0,1,1,1,1,1))) expect_true(identical(as.numeric(gantt[ 2,]), c(0,0,1,1,1,1,1,1,1,1))) expect_true(identical(as.numeric(gantt[ 3,]), c(1,1,1,1,1,1,1,1,1,1))) })
sqs <- paws::sqs() sqs <- sqs$create_queue( QueueName = "ExampleQueue" ) sqs$send_message( QueueUrl = sqs$QueueUrl, MessageBody = "foo" ) sqs$get_queue_attributes( QueueUrl = sqs$QueueUrl, AttributeNames = "All" ) msg <- sqs$receive_message( QueueUrl = sqs$QueueUrl ) sqs$delete_message( QueueUrl = sqs$QueueUrl, ReceiptHandle = msg$Messages[[1]]$ReceiptHandle ) sqs$delete_queue( QueueUrl = sqs$QueueUrl )
sample_simple_CPT<-function(parent_list, child_states_n, child_prior=NULL, b=2, obs_states=NULL) { parent_names<-names(parent_list) parent_n_states<-sapply(parent_list,function(x) x[1]) parent_weights<-sapply(parent_list,function(x) x[2]) if(is.null(child_prior)) child_prior<-rep(1/length(child_states_n),length(child_states_n)) ranking_child<-interpolate_gaps(c(-1,rep(NA,child_states_n-2),1))$interp gamma<-list() for(a in 1:length(parent_names)) {gamma[[a]]<-matrix(nrow=child_states_n,ncol=parent_n_states[a]) for(c in 1:child_states_n) gamma[[a]][c,]<-ranking_child[c]*interpolate_gaps(c(-1,rep(NA,parent_n_states[a]-2),1))$interp} vecs <- mapply(seq, 1, rev(sapply(gamma,ncol))) if(is.matrix(vecs)) vecs<-lapply(seq_len(ncol(vecs)), function(i) vecs[,i]) tmp <- t(do.call(expand.grid, vecs)) row.names(tmp)<-rev(row.names(tmp)) tmp<-tmp[nrow(tmp):1,] CPT<-matrix(0,nrow=child_states_n,ncol=prod(parent_n_states)) if(length(gamma)==1) for(i in 1:length(gamma)) CPT<-CPT+gamma[[i]][,tmp[i]] else for(i in 1:length(gamma)) CPT<-CPT+gamma[[i]][,tmp[i,]] CPT<-b^CPT CPT<-CPT*child_prior for(i in 1:ncol(CPT)) CPT[,i]<-CPT[,i]/sum(CPT[,i]) assign_states<-function(x) {if(x==1) out<-"normal" if(x==2) out<-c("low","high") if(x==3) out<-c("low","medium","high") if(x==4) out<-c("low","medium low","medium high","high") if(x==5) out<-c("very low","low","medium","high","very high") if(x==6) out<-c("very low", "low","medium low","medium high","high","very high") if(x==7) out<-c("very low", "low", "medium low","medium","medium high","high","very high") if(x>7) out<-paste("state",1:x) return(out) } row.names(CPT)<-assign_states(child_states_n) colnames(CPT)<-paste("col_",1:ncol(CPT),sep="") parent_states<-sapply(parent_n_states,assign_states) if(is.matrix(parent_states)) parent_states<-lapply(seq_len(ncol(parent_states)), function(i) parent_states[,i]) leg_tab<-tmp if(length(gamma)==1) leg_tab<-data.frame(matrix(parent_states[[1]],nrow=1)) else {for(i in 1:nrow(leg_tab)) leg_tab[i,]<-parent_states[[i]][tmp[i,]]} colnames(leg_tab)<-paste("col_",1:ncol(leg_tab),sep="") row.names(leg_tab)<-parent_names if(!is.null(obs_states)) {sampled<-sample_CPT(list(CPT,leg_tab),obs_states) return(list(CPT=CPT,column_legend=leg_tab,sampled=sampled))} else return(list(CPT=CPT,column_legend=leg_tab)) }
"DHpop_map"
raster_pdf <- function(filename = "Rplots.pdf", width = NULL, height = NULL, units = NULL, res = NULL, png_function = NULL, pdf_function = NULL, ...) { width <- get_value_or_default("width", width) height <- get_value_or_default("height", height) units <- get_value_or_default("units", units) res <- get_value_or_default("res", res) units <- match.arg(units, choices = c("in", "cm", "mm", "px")) width <- convert_to_inches(width, units = units, res = res) height <- convert_to_inches(height, units = units, res = res) pngs <- tempfile(pattern = "raster_pdf-", fileext = "-%05i.png") if (is.null(png_function)) { png_function <- grDevices::png } png_function <- match.fun(png_function) png_function( filename = pngs, width = width, height = height, units = "in", res = res, ... ) device <- list( filename = filename, pngs = pngs, width = width, height = height, pdf_function = pdf_function ) raster_pdf_device(device = device) } agg_pdf <- function(...) { if (requireNamespace("ragg", quietly = TRUE)) { raster_pdf(..., png_function = ragg::agg_png) } else { warning( "Package \"ragg\" not available; falling back to grDevices::png().", call. = FALSE ) raster_pdf(...) } }
SampleMat2 <- function( ref, ratio, as.logi = FALSE ){ set.seed(as.double(Sys.time()) + as.numeric(format(Sys.time(), "%OS6"))*1000000) ntot <- length(ref) npres<- sum(ref) ncal <- ceiling(ntot*ratio) pres <- sample(which(ref==1), ceiling(npres*ratio)) absc <- sample(which(ref==0), ncal-length(pres)) if(as.logi){ calib <- rep(FALSE, ntot) calib[c(pres,absc)] <- TRUE eval <- !calib } else{ calib <- c(pres,absc) eval <- (1:ntot)[-c(pres,absc)] } return(list("calibration"=calib, "evaluation"=eval)) }
if (Sys.getenv("POSTGRES_USER") != "" & Sys.getenv("POSTGRES_HOST") != "" & Sys.getenv("POSTGRES_DATABASE") != "") { stopifnot(require(RPostgreSQL)) stopifnot(require(datasets)) drv <- dbDriver("PostgreSQL") con <- dbConnect(drv, user=Sys.getenv("POSTGRES_USER"), password=Sys.getenv("POSTGRES_PASSWD"), host=Sys.getenv("POSTGRES_HOST"), dbname=Sys.getenv("POSTGRES_DATABASE"), port=ifelse((p<-Sys.getenv("POSTGRES_PORT"))!="", p, 5432)) if (dbExistsTable(con, "rockdata")) { print("Removing rockdata\n") dbRemoveTable(con, "rockdata") } dbWriteTable(con, "rockdata", rock) cat("Does rockdata exist? ") print(res <- dbExistsTable(con, "rockdata")) cat("Does public.rockdata exist? ") print(res <- dbExistsTable(con, "public.rockdata")) if (dbExistsTable(con, "rockdata")) { print("Removing rockdata\n") dbRemoveTable(con, "rockdata") } dbDisconnect(con) }
emStMoE <- function(X, Y, K, p = 3, q = 1, n_tries = 1, max_iter = 1500, threshold = 1e-6, verbose = FALSE, verbose_IRLS = FALSE) { top <- 0 try_EM <- 0 best_loglik <- -Inf while (try_EM < n_tries) { try_EM <- try_EM + 1 if (n_tries > 1 && verbose) { message("EM try number: ", try_EM, "\n") } param <- ParamStMoE(X = X, Y = Y, K = K, p = p, q = q) param$initParam(segmental = TRUE) iter <- 0 converge <- FALSE prev_loglik <- -Inf stat <- StatStMoE(paramStMoE = param) while (!converge && (iter <= max_iter)) { stat$EStep(param, calcTau = TRUE, calcE1 = TRUE, calcE2 = TRUE, calcE3 = FALSE) reg_irls <- param$MStep(stat, calcAlpha = TRUE, calcBeta = TRUE, verbose_IRLS = verbose_IRLS) stat$EStep(param, calcTau = FALSE, calcE1 = TRUE, calcE2 = TRUE, calcE3 = FALSE) param$MStep(stat , calcSigma2 = TRUE, verbose_IRLS = verbose_IRLS) stat$EStep(param, calcTau = FALSE, calcE1 = TRUE, calcE2 = TRUE, calcE3 = FALSE) param$MStep(stat , calcLambda = TRUE, verbose_IRLS = verbose_IRLS) stat$EStep(param, calcTau = FALSE, calcE1 = TRUE, calcE2 = TRUE, calcE3 = TRUE) param$MStep(stat , calcNu = TRUE, verbose_IRLS = verbose_IRLS) stat$computeLikelihood(reg_irls) iter <- iter + 1 if (verbose) { message("EM - StMoE: Iteration: ", iter, " | log-likelihood: " , stat$loglik) } converge <- abs((stat$loglik - prev_loglik) / prev_loglik) <= threshold if (is.na(converge)) { converge <- FALSE } prev_loglik <- stat$loglik stat$stored_loglik <- c(stat$stored_loglik, stat$loglik) } if (stat$loglik > best_loglik) { statSolution <- stat$copy() paramSolution <- param$copy() best_loglik <- stat$loglik } if (n_tries > 1 && verbose) { message("Max value of the log-likelihood: ", stat$loglik, "\n\n") } } statSolution$MAP() if (n_tries > 1 && verbose) { message("Max value of the log-likelihood: ", statSolution$loglik, "\n") } statSolution$computeStats(paramSolution) return(ModelStMoE(param = paramSolution, stat = statSolution)) }
NULL .onUnload <- function (libpath) { library.dynam.unload("opentimsr", libpath) } all_columns = c('frame','scan','tof','intensity','mz','inv_ion_mobility','retention_time') setClass('OpenTIMS', slots = c(path.d='character', handle='externalptr', min_frame='integer', max_frame='integer', min_scan='integer', max_scan='integer', min_intensity='integer', max_intensity='integer', min_retention_time='numeric', max_retention_time='numeric', min_inv_ion_mobility='numeric', max_inv_ion_mobility='numeric', min_mz='numeric', max_mz='numeric', frames='data.frame', all_columns='character') ) setMethod('show', 'OpenTIMS', function(object) cat(paste0(class(object), "(", tdf_no_peaks_total(object@handle), ")", "\n", separator=''))) setMethod('length', 'OpenTIMS', function(x) tdf_no_peaks_total(x@handle)) setMethod("[", signature(x = "OpenTIMS", i = "ANY"), function(x, i){ i = as.integer(i) stopifnot(all(x@min_frame <= i, i <= x@max_frame)) return(tdf_get_indexes(x@handle, i)) }) setMethod("range", "OpenTIMS", function(x, from, to, by=1L){ from = as.integer(from) to = as.integer(to) by = as.integer(by) stopifnot(from >= x@min_frame, to <= x@max_frame + 1, by >= 0) tdf_get_range(x@handle, from, to, by) }) table2df = function(opentims, names){ analysis.tdf = file.path([email protected], 'analysis.tdf') sql_conn = DBI::dbConnect(RSQLite::SQLite(), analysis.tdf) on.exit(DBI::dbDisconnect(sql_conn)) tables = lapply(names, function(name) DBI::dbReadTable(sql_conn, name)) names(tables) = names return(tables) } tables_names = function(opentims){ analysis.tdf = file.path([email protected], 'analysis.tdf') sql_conn = DBI::dbConnect(RSQLite::SQLite(), analysis.tdf) on.exit(DBI::dbDisconnect(sql_conn)) tables_names = DBI::dbListTables(sql_conn) return(tables_names) } OpenTIMS = function(path.d){ analysis.tdf = file.path(path.d, 'analysis.tdf') sql_conn = DBI::dbConnect(RSQLite::SQLite(), analysis.tdf) on.exit(DBI::dbDisconnect(sql_conn)) frames = DBI::dbReadTable(sql_conn, 'Frames') GlobalMetadata = DBI::dbReadTable(sql_conn, 'GlobalMetadata') GlobalMetadata = array(GlobalMetadata$Value, dimnames=list(GlobalMetadata$Key)) handle = tdf_open(path.d, frames) min_frame = as.integer(min(frames$Id)) max_frame = as.integer(max(frames$Id)) min_scan = 1L max_scan = as.integer(max(frames$NumScans)) min_intensity = 0L max_intensity = max(frames$MaxIntensity) min_retention_time = min(frames$Time) max_retention_time = max(frames$Time) min_inv_ion_mobility = as.numeric(GlobalMetadata['OneOverK0AcqRangeLower']) max_inv_ion_mobility = as.numeric(GlobalMetadata['OneOverK0AcqRangeUpper']) min_mz = as.numeric(GlobalMetadata['MzAcqRangeLower']) max_mz = as.numeric(GlobalMetadata['MzAcqRangeUpper']) new("OpenTIMS", path.d=path.d, handle=handle, min_frame=min_frame, max_frame=max_frame, min_scan=min_scan, max_scan=max_scan, min_intensity=min_intensity, max_intensity=max_intensity, min_retention_time=min_retention_time, max_retention_time=max_retention_time, min_inv_ion_mobility=min_inv_ion_mobility, max_inv_ion_mobility=max_inv_ion_mobility, min_mz=min_mz, max_mz=max_mz, frames=frames, all_columns=all_columns) } min_max_measurements = function(opentims){ data.frame(stat=c('min','max'), frame=c(opentims@min_frame,opentims@max_frame), scan=c(opentims@min_scan, opentims@max_scan), intensity=c(opentims@min_intensity, opentims@max_intensity), retention.time=c(opentims@min_retention_time, opentims@max_retention_time), inv_ion_mobility=c(opentims@min_inv_ion_mobility, opentims@max_inv_ion_mobility), mz=c(opentims@min_mz, opentims@max_mz)) } MS1 = function(opentims) opentims@frames$Id[opentims@frames$MsMsType == 0] explore.tdf.tables = function(opentims, ...){ for(table_name in tables_names(opentims)){ print(table_name) df = table2df(opentims, table_name) print(head(df,...)) print(tail(df,...)) readline("PRESS ENTER") } print('Get full tables using "table2df".') } peaks_per_frame_cnts = function(opentims){ opentims@frames$NumPeaks } retention_times = function(opentims){ opentims@frames$Time } query = function(opentims, frames, columns=all_columns){ col = opentims@all_columns %in% columns if(!all(columns %in% all_columns)) stop(paste0("Wrong column names. Choose among:\n", paste0(all_columns, sep=" ", collapse=""))) df = tdf_extract_frames( opentims@handle, frames, get_frames = col[1], get_scans = col[2], get_tofs = col[3], get_intensities = col[4], get_mzs = col[5], get_inv_ion_mobilities = col[6], get_retention_times = col[7] ) as.data.frame(df)[,columns, drop=F] } query_slice = function(opentims, from=NULL, to=NULL, by=1, columns=all_columns){ col = opentims@all_columns %in% columns if(is.null(from)) from = opentims@min_frame if(is.null(to)) to = opentims@max_frame df = tdf_extract_frames_slice( opentims@handle, from, to + 1, by, get_frames = col[1], get_scans = col[2], get_tofs = col[3], get_intensities = col[4], get_mzs = col[5], get_inv_ion_mobilities = col[6], get_retention_times = col[7] ) as.data.frame(df)[,columns, drop=F] } get_left_frame = function(x,y) ifelse(x > y[length(y)], NA, findInterval(x, y, left.open=T) + 1) get_right_frame = function(x,y) ifelse(x < y[1], NA, findInterval(x, y, left.open=F)) rt_query = function(opentims, min_retention_time, max_retention_time, columns=all_columns){ RTS = retention_times(opentims) min_frame = get_left_frame(min_retention_time, RTS) max_frame = get_right_frame(max_retention_time, RTS) if(is.na(min_frame) | is.na(max_frame)) stop("The [min_retention_time,max_retention_time] interval does not hold any data.") query_slice(opentims, from=min_frame, to=max_frame, columns=columns) } download_bruker_proprietary_code = function( target.folder, net_url=paste0("https://github.com/MatteoLacki/opentims_bruker_bridge/", "raw/main/opentims_bruker_bridge/"), mode="wb", ...){ sys_info = Sys.info() if(sys_info['sysname'] == "Linux"){ print("Welcome to a real OS.") url_ending = file="libtimsdata.so" } if(sys_info['sysname'] == "Windows"){ print("Detected Windows. Like seriously?") file = "timsdata.dll" if(sys_info['machine'] == "x86-64"){ url_ending="win64/timsdata.dll" } else { print("Assuming 32 bits") url_ending="win32/timsdata.dll" } } url = paste0(net_url, url_ending) target.file = file.path(target.folder, file) print(paste0("Downloading from: ", url)) download.file(url, target.file, mode="wb", ...) target.file } CloseTIMS = function(opentims){ tdf_close(opentims@handle) } setup_bruker_so = function(path) .setup_bruker_so(path)
ltrcrfsrc <- function(formula, data, ntree = 1000, mtry = NULL, ytry = NULL, nodesize = NULL, nodedepth = NULL, splitrule = NULL, nsplit = 10, importance = c(FALSE, TRUE, "none", "permute", "random", "anti"), block.size = if (any(is.element(as.character(importance), c("none", "FALSE")))) NULL else 10, ensemble = c("all", "oob", "inbag"), bootstrap = c("by.root", "by.node", "none", "by.user"), samptype = c("swor", "swr"), samp = NULL, membership = FALSE, sampsize = if (samptype == "swor") function(x){x * .632} else function(x){x}, na.action = c("na.omit", "na.impute"), nimpute = 1, ntime, cause, proximity = FALSE, distance = FALSE, forest.wt = FALSE, xvar.wt = NULL, yvar.wt = NULL, split.wt = NULL, case.wt = NULL, forest = TRUE, var.used = c(FALSE, "all.trees", "by.tree"), split.depth = c(FALSE, "all.trees", "by.tree"), seed = NULL, do.trace = FALSE, statistics = FALSE, ...) { univariate.nomenclature = TRUE user.option <- list(...) impute.only <- is.hidden.impute.only(user.option) terminal.qualts <- is.hidden.terminal.qualts(user.option) terminal.quants <- is.hidden.terminal.quants(user.option) perf.type <- is.hidden.perf.type(user.option) rfq <- is.hidden.rfq(user.option) gk.quantile <- is.hidden.gk.quantile(user.option) quantile.regr <- is.hidden.quantile.regr(user.option) prob <- is.hidden.prob(user.option) prob.epsilon <- is.hidden.prob.epsilon(user.option) lot <- is.hidden.lot(user.option) hdim <- lot$hdim base.learner <- is.hidden.base.learner(user.option) vtry <- is.hidden.vtry(user.option) holdout.array <- is.hidden.holdout.array(user.option) holdout.specs <- is.hidden.holdout.specs(user.option) empirical.risk <- is.hidden.empirical.risk(user.option) ensemble <- match.arg(ensemble, c("all", "oob", "inbag")) bootstrap <- match.arg(bootstrap, c("by.root", "by.node", "none", "by.user")) if (bootstrap == "by.node" || bootstrap == "none") { ensemble <- "inbag" } importance <- match.arg(as.character(importance), c(FALSE, TRUE, "none", "permute", "random", "anti")) na.action <- match.arg(na.action, c("na.omit", "na.impute")) proximity <- match.arg(as.character(proximity), c(FALSE, TRUE, "inbag", "oob", "all")) distance <- match.arg(as.character(distance), c(FALSE, TRUE, "inbag", "oob", "all")) var.used <- match.arg(as.character(var.used), c("FALSE", "all.trees", "by.tree")) split.depth <- match.arg(as.character(split.depth), c("FALSE", "all.trees", "by.tree")) if (var.used == "FALSE") var.used <- FALSE if (split.depth == "FALSE") split.depth <- FALSE if (missing(data)) stop("data is missing") if (missing(formula) | (!missing(formula) && is.null(formula))) { if (is.null(ytry)) { formula <- as.formula("Unsupervised() ~ .") } else { formula <- as.formula(paste("Unsupervised(", ytry, ")~.")) } } formulaPrelim <- parseFormula(formula, data, ytry) my.call <- match.call() my.call$formula <- eval(formula) if (any(is.na(data))) { data <- parseMissingData(formulaPrelim, data) miss.flag <- TRUE } else { miss.flag <- FALSE } formulaDetail <- finalizeFormula(formulaPrelim, data) ntree <- round(ntree) if (ntree < 1) stop("Invalid choice of 'ntree'. Cannot be less than 1.") if (!is.null(nodesize) && nodesize < 1) stop("Invalid choice of 'nodesize'. Cannot be less than 1.") if (!is.null(nodedepth)) nodedepth = round(nodedepth) else nodedepth = -1 nimpute <- round(nimpute) if (nimpute < 1) stop("Invalid choice of 'nimpute'. Cannot be less than 1.") seed <- get.seed(seed) family <- formulaDetail$family xvar.names <- formulaDetail$xvar.names yvar.names <- formulaDetail$yvar.names if (length(xvar.names) == 0) { stop("something seems wrong: your formula did not define any x-variables") } if (family != "unsupv" && length(yvar.names) == 0) { stop("something seems wrong: your formula did not define any y-variables") } if (family == "class") { if (length(setdiff(levels(data[, yvar.names]), unique(data[, yvar.names]))) > 0) { warning("empty classes found when implementing classification\n") } } data <- rm.na.levels(data, xvar.names) data <- rm.na.levels(data, yvar.names) yfactor <- extract.factor(data, yvar.names) xfactor <- extract.factor(data, xvar.names) yvar.types <- get.yvar.type(family, yfactor$generic.types, yvar.names) yvar.nlevels <- get.yvar.nlevels(family, yfactor$nlevels, yvar.names, data) xvar.types <- get.xvar.type(xfactor$generic.types, xvar.names) xvar.nlevels <- get.xvar.nlevels(xfactor$nlevels, xvar.names, data) data <- finalizeData(c(yvar.names, xvar.names), data, na.action, miss.flag) data.row.names <- rownames(data) data.col.names <- colnames(data) xvar <- as.matrix(data[, xvar.names, drop = FALSE]) rownames(xvar) <- colnames(xvar) <- NULL n <- nrow(xvar) n.xvar <- ncol(xvar) mtry <- get.grow.mtry(mtry, n.xvar, family) samptype <- match.arg(samptype, c("swor", "swr")) if (bootstrap == "by.root") { if (!is.function(sampsize) && !is.numeric(sampsize)) { stop("sampsize must be a function or number specifying size of subsampled data") } if (is.function(sampsize)) { sampsize.function <- sampsize } else { sampsize.function <- make.samplesize.function(sampsize / nrow(xvar)) } sampsize <- round(sampsize.function(nrow(xvar))) if (sampsize < 1) { stop("sampsize must be greater than zero") } if (samptype == "swor" && (sampsize > nrow(xvar))) { sampsize.function <- function(x){x} sampsize <- nrow(xvar) } samp <- NULL } else if (bootstrap == "by.user") { if (is.null(samp)) { stop("samp must not be NULL when bootstrapping by user") } ntree <- ncol(samp) sampsize <- colSums(samp) if (sum(sampsize == sampsize[1]) != ntree) { stop("sampsize must be identical for each tree") } sampsize <- sampsize[1] sampsize.function <- make.samplesize.function(sampsize[1] / nrow(xvar)) } else { sampsize <- nrow(xvar) samptype <- "swr" sampsize.function <- function(x){x} } case.wt <- get.weight(case.wt, n) split.wt <- get.weight(split.wt, n.xvar) forest.wt <- match.arg(as.character(forest.wt), c(FALSE, TRUE, "inbag", "oob", "all")) if (family == "unspv") { yvar.wt <- NULL } else { yvar.wt <- get.weight(yvar.wt, length(yvar.types)) } xvar.wt <- get.weight(xvar.wt, n.xvar) yvar <- as.matrix(data[, yvar.names, drop = FALSE]) if(dim(yvar)[2] == 0) { yvar <- NULL } if (miss.flag) { n.miss <- get.nmiss(xvar, yvar) } else { n.miss <- 0 } if (impute.only && n.miss == 0) { return(data) } remove(data) big.data <- FALSE event.info <- get.grow.event.info(yvar, family, ntime = ntime) splitinfo <- get.grow.splitinfo(formulaDetail, splitrule, hdim, nsplit, event.info$event.type) if (family == "surv" || family == "surv-CR") { if (length(event.info$event.type) > 1) { if (missing(cause) || is.null(cause)) { cause <- NULL cause.wt <- rep(1, length(event.info$event.type)) } else { if (length(cause) == 1) { if (cause >= 1 && cause <= length(event.info$event.type)) { cause.wt <- rep(0, length(event.info$event.type)) cause.wt[cause] <- 1 } else { cause.wt <- rep(1, length(event.info$event.type)) } } else { if (length(cause) == length(event.info$event.type) && all(cause >= 0) && !all(cause == 0)) { cause.wt <- cause / sum(cause) } else { cause.wt <- rep(1, length(event.info$event.type)) } } } } else { cause <- NULL cause.wt = 1 } family <- get.coerced.survival.fmly(family, event.info$event.type, splitinfo$name) } else { cause <- cause.wt <- NULL } nodesize <- get.grow.nodesize(family, nodesize) if ((bootstrap != "by.root") && (bootstrap != "by.user")) { importance <- "none" perf.type <- "none" } if (family == "unsupv") { importance <- "none" perf.type <- "none" } if (impute.only) { forest <- FALSE proximity <- FALSE distance <- FALSE var.used <- FALSE split.depth <- FALSE membership <- FALSE perf.type <- "none" importance <- "none" terminal.qualts <- FALSE terminal.quants <- FALSE } if (!is.null(holdout.array)) { if (nrow(holdout.array) != n.xvar | ncol(holdout.array) != ntree) { stop("dimension of holdout.array does not conform to p x ntree") } vtry <- 1 } gk.quantile <- get.gk.quantile(gk.quantile) prob.assign <- global.prob.assign(prob, prob.epsilon, gk.quantile, quantile.regr, splitinfo$name, n) prob <- prob.assign$prob prob.epsilon <- prob.assign$prob.epsilon if (terminal.qualts | terminal.quants) { forest <- TRUE } ensemble.bits <- get.ensemble(ensemble) impute.only.bits <- get.impute.only(impute.only, n.miss) var.used.bits <- get.var.used(var.used) split.depth.bits <- get.split.depth(split.depth) importance.bits <- get.importance(importance) bootstrap.bits <- get.bootstrap(bootstrap) forest.bits <- get.forest(forest) proximity.bits <- get.proximity(TRUE, proximity) distance.bits <- get.distance(TRUE, distance) membership.bits <- get.membership(membership) statistics.bits <- get.statistics(statistics) split.cust.bits <- get.split.cust(splitinfo$cust) perf.type <- get.perf(perf.type, impute.only, family) perf.bits <- get.perf.bits(perf.type) rfq <- get.rfq(rfq) rfq.bits <- get.rfq.bits(rfq, family) gk.quantile.bits <- get.gk.quantile.bits(gk.quantile) empirical.risk.bits <- get.empirical.risk.bits(empirical.risk) samptype.bits <- get.samptype(samptype) forest.wt.bits <- get.forest.wt(TRUE, bootstrap, forest.wt) na.action.bits <- get.na.action(na.action) block.size <- get.block.size(block.size, ntree) terminal.qualts.bits <- get.terminal.qualts(terminal.qualts, FALSE) terminal.quants.bits <- get.terminal.quants(terminal.quants, FALSE) do.trace <- get.trace(do.trace) nativeOutput <- tryCatch({.Call("rfsrcGrow", as.integer(do.trace), as.integer(seed), as.integer(ensemble.bits + impute.only.bits + var.used.bits + split.depth.bits + importance.bits + bootstrap.bits + forest.bits + proximity.bits + perf.bits + rfq.bits + gk.quantile.bits + statistics.bits + empirical.risk.bits), as.integer(samptype.bits + forest.wt.bits + distance.bits + na.action.bits + split.cust.bits + membership.bits + terminal.qualts.bits + terminal.quants.bits), as.integer(splitinfo$index), as.integer(splitinfo$nsplit), as.integer(mtry), lot, base.learner, as.integer(vtry), as.integer(holdout.array), holdout.specs, as.integer(formulaDetail$ytry), as.integer(nodesize), as.integer(nodedepth), as.integer(length(cause.wt)), as.double(cause.wt), as.integer(ntree), as.integer(n), as.integer(length(yvar.types)), as.character(yvar.types), as.integer(yvar.nlevels), as.double(as.vector(yvar)), as.integer(n.xvar), as.character(xvar.types), as.integer(xvar.nlevels), as.integer(sampsize), as.integer(samp), as.double(case.wt), as.double(split.wt), as.double(yvar.wt), as.double(xvar.wt), as.double(xvar), as.integer(length(event.info$time.interest)), as.double(event.info$time.interest), as.integer(nimpute), as.integer(block.size), as.integer(length(prob)), as.double(prob), as.double(prob.epsilon), as.double(NULL), as.integer(get.rf.cores()))}, error = function(e) { print(e) NULL}) if (is.null(nativeOutput)) { if (impute.only) { return(NULL) } else { stop("An error has occurred in the grow algorithm. Please turn trace on for further analysis.") } } if (n.miss > 0) { imputed.data <- matrix(nativeOutput$imputation, nrow = n.miss, byrow = FALSE) imputed.indv <- imputed.data[, 1] imputed.data <- as.matrix(imputed.data[, -1, drop = FALSE]) nativeOutput$imputation <- NULL if (nimpute > 1) { if (grepl("surv", family)) { yvar[imputed.indv, 1] <- imputed.data[, 1] yvar[imputed.indv, 2] <- imputed.data[, 2] xvar[imputed.indv, ] <- imputed.data[, -c(1:2), drop = FALSE] } else { if (!is.null(yvar.types)) { yvar[imputed.indv, ] <- imputed.data[, 1:length(yvar.types), drop = FALSE] xvar[imputed.indv, ] <- imputed.data[, -c(1:length(yvar.types)), drop = FALSE] } else { xvar[imputed.indv, ] <- imputed.data } } imputed.indv <- NULL imputed.data <- NULL imputedOOBData <- NULL na.action = "na.omit" } else { colnames(imputed.data) <- c(yvar.names, xvar.names) imputed.data <- as.data.frame(imputed.data) } } xvar <- as.data.frame(xvar) rownames(xvar) <- data.row.names colnames(xvar) <- xvar.names xvar <- map.factor(xvar, xfactor) if (family != "unsupv") { yvar <- as.data.frame(yvar) colnames(yvar) <- yvar.names } else { yvar <- NULL } if (family != "unsupv") { if (family == "regr+" | family == "class+" | family == "mix+") { yvar <- map.factor(yvar, yfactor) } else { yvar <- amatrix.remove.names(map.factor(yvar, yfactor)) } } pi.hat <- NULL if (family == "class" && rfq) { pi.hat <- table(yvar) / length(yvar) } if ((n.miss > 0) & (nimpute < 2)) { imputed.data <- map.factor(imputed.data, xfactor) if (family != "unsupv") { imputed.data <- map.factor(imputed.data, yfactor) } } if (forest) { nativeArraySize = 0 if (hdim == 0) { mwcpCountSummary = rep (0, 1) nativeFactorArray <- vector("list", 1) } else { mwcpCountSummary = rep (0, hdim) nativeFactorArray <- vector("list", hdim) } pivot <- which(names(nativeOutput) == "treeID") if (hdim == 0) { offset = 0 } else { offset = 7 if (!is.null(base.learner)) { if (base.learner$trial.depth > 1) { offset = 9 } } } nullO <- lapply(1:ntree, function(b) { if (nativeOutput$leafCount[b] > 0) { nativeArraySize <<- nativeArraySize + (2 * nativeOutput$leafCount[b]) - 1 mwcpCountSummary[1] <<- mwcpCountSummary[1] + nativeOutput$mwcpCT[b] if (hdim > 1) { offset = offset + 2 for (i in 0:(hdim-2)) { mwcpCountSummary[i+2] <<- mwcpCountSummary[i+2] + nativeOutput[[pivot + offset + (5 * (hdim-1)) + i]][b] } offset = offset - 2 } } else { nativeArraySize <<- nativeArraySize + 1 } NULL }) rm(nullO) nativeArray <- as.data.frame(cbind(nativeOutput$treeID[1:nativeArraySize], nativeOutput$nodeID[1:nativeArraySize])) nativeArrayHeader <- c("treeID", "nodeID") nativeArray <- as.data.frame(cbind(nativeArray, nativeOutput$parmID[1:nativeArraySize], nativeOutput$contPT[1:nativeArraySize], nativeOutput$mwcpSZ[1:nativeArraySize])) nativeArrayHeader <- c(nativeArrayHeader, "parmID", "contPT", "mwcpSZ") if (mwcpCountSummary[1] > 0) { nativeFactorArray[[1]] <- nativeOutput$mwcpPT[1:mwcpCountSummary[1]] } nativeFactorArrayHeader <- "mwcpPT" if (!is.null(base.learner)) { if (base.learner$trial.depth > 1) { nativeArray <- as.data.frame(cbind(nativeArray, nativeOutput$augmXone[1:nativeArraySize], nativeOutput$augmXtwo[1:nativeArraySize])) nativeArrayHeader <- c(nativeArrayHeader, "augmXone", "augmXtwo") } } if (hdim > 0) { nativeArray <- as.data.frame(cbind(nativeArray, nativeOutput[[pivot + offset]][1:nativeArraySize])) nativeArrayHeader <- c(nativeArrayHeader, "hcDim") nativeArray <- as.data.frame(cbind(nativeArray, nativeOutput[[pivot + offset + 1]][1:nativeArraySize])) nativeArrayHeader <- c(nativeArrayHeader, "contPTR") } if (hdim > 1) { offset = offset + 2 for (i in 0:(hdim-2)) { nativeArray <- as.data.frame(cbind(nativeArray, nativeOutput[[pivot + offset + (0 * (hdim-1)) + i]][1:nativeArraySize])) nativeArrayHeader <- c(nativeArrayHeader, paste("parmID", i+2, sep="")) nativeArray <- as.data.frame(cbind(nativeArray, nativeOutput[[pivot + offset + (1 * (hdim-1)) + i]][1:nativeArraySize])) nativeArrayHeader <- c(nativeArrayHeader, paste("contPT", i+2, sep="")) nativeArray <- as.data.frame(cbind(nativeArray, nativeOutput[[pivot + offset + (2 * (hdim-1)) + i]][1:nativeArraySize])) nativeArrayHeader <- c(nativeArrayHeader, paste("contPTR", i+2, sep="")) nativeArray <- as.data.frame(cbind(nativeArray, nativeOutput[[pivot + offset + (3 * (hdim-1)) + i]][1:nativeArraySize])) nativeArrayHeader <- c(nativeArrayHeader, paste("mwcpSZ", i+2, sep="")) if (mwcpCountSummary[i+2] > 0) { nativeFactorArray[[i+2]] <- nativeOutput[[pivot + offset + (4 * (hdim-1)) + i]][1:mwcpCountSummary[i+2]] } nativeFactorArrayHeader <- c(nativeFactorArrayHeader, paste("mwcpPT", i+2, sep="")) if (!is.null(base.learner)) { if (base.learner$trial.depth > 1) { nativeArray <- as.data.frame(cbind(nativeArray, nativeOutput[[pivot + offset + (6 * (hdim-1)) + i]][1:nativeArraySize])) nativeArrayHeader <- c(nativeArrayHeader, paste("augmXone", i+2, sep="")) nativeArray <- as.data.frame(cbind(nativeArray, nativeOutput[[pivot + offset + (7 * (hdim-1)) + i]][1:nativeArraySize])) nativeArrayHeader <- c(nativeArrayHeader, paste("augmXtwo", i+2, sep="")) } } } } names(nativeArray) <- nativeArrayHeader names(nativeFactorArray) <- nativeFactorArrayHeader if (terminal.qualts | terminal.quants) { temp <- 2 * (nodesize - 1) if (sampsize > temp) { treeTheoreticalMaximum <- sampsize - temp; } else { treeTheoreticalMaximum <- 1; } forestTheoreticalMaximum <- treeTheoreticalMaximum * ntree offset <- 0 valid.mcnt.indices <- rep(list(0), ntree) for (b in 1:ntree){ if (b > 1) { offset <- offset + treeTheoreticalMaximum } valid.mcnt.indices[[b]] <- (offset + 1):(offset + nativeOutput$leafCount[b]) } valid.mcnt.indices <- unlist(valid.mcnt.indices) if (terminal.quants) { if (grepl("surv", family)) { offset <- 0 valid.2D.surv.indices <- unlist(lapply(1:ntree, function(b) { if (b > 1) { offset <<- offset + (treeTheoreticalMaximum * length(event.info$event.type) * length(event.info$time.interest)) } (offset + 1):(offset + nativeOutput$leafCount[b] * length(event.info$event.type) * length(event.info$time.interest)) })) offset <- 0 valid.1D.surv.indices <- unlist(lapply(1:ntree, function(b) { if (b > 1) { offset <<- offset + (treeTheoreticalMaximum * length(event.info$time.interest)) } (offset + 1):(offset + nativeOutput$leafCount[b] * length(event.info$time.interest)) })) offset <- 0 valid.mort.indices <- unlist(lapply(1:ntree, function(b) { if (b > 1) { offset <<- offset + (treeTheoreticalMaximum * length(event.info$event.type)) } (offset + 1):(offset + nativeOutput$leafCount[b] * length(event.info$event.type)) })) } else { class.index <- which(yvar.types != "R") class.count <- length(class.index) regr.index <- which(yvar.types == "R") regr.count <- length(regr.index) if (class.count > 0) { levels.count <- array(0, class.count) counter <- 0 for (i in class.index) { counter <- counter + 1 levels.count[counter] <- yvar.nlevels[i] } offset <- 0 valid.clas.indices <- unlist(lapply(1:ntree, function(b) { if (b > 1) { offset <<- offset + (treeTheoreticalMaximum * sum(levels.count)) } (offset + 1):(offset + nativeOutput$leafCount[b] * sum(levels.count)) })) } if (regr.count > 0) { offset <- 0 valid.regr.indices <- unlist(lapply(1:ntree, function(b) { if (b > 1) { offset <<- offset + (treeTheoreticalMaximum * regr.count) } (offset + 1):(offset + nativeOutput$leafCount[b] * regr.count) })) } } } nativeArrayTNDS <- list(if(!is.null(nativeOutput$tnSURV)) nativeOutput$tnSURV[valid.1D.surv.indices] else NULL, if(!is.null(nativeOutput$tnMORT)) nativeOutput$tnMORT[valid.mort.indices] else NULL, if(!is.null(nativeOutput$tnNLSN)) nativeOutput$tnNLSN[valid.1D.surv.indices] else NULL, if(!is.null(nativeOutput$tnCSHZ)) nativeOutput$tnCSHZ[valid.2D.surv.indices] else NULL, if(!is.null(nativeOutput$tnCIFN)) nativeOutput$tnCIFN[valid.2D.surv.indices] else NULL, if(!is.null(nativeOutput$tnREGR)) nativeOutput$tnREGR[valid.regr.indices] else NULL, if(!is.null(nativeOutput$tnCLAS)) nativeOutput$tnCLAS[valid.clas.indices] else NULL, nativeOutput$rmbrMembership, nativeOutput$ambrMembership, nativeOutput$tnRCNT[valid.mcnt.indices], nativeOutput$tnACNT[valid.mcnt.indices]); names(nativeArrayTNDS) <- c("tnSURV","tnMORT","tnNLSN","tnCSHZ","tnCIFN","tnREGR","tnCLAS", "tnRMBR", "tnAMBR", "tnRCNT", "tnACNT") } else { nativeArrayTNDS <- NULL } forest.out <- list(forest = TRUE, hdim = hdim, base.learner = base.learner, nativeArray = nativeArray, nativeFactorArray = nativeFactorArray, totalNodeCount = dim(nativeArray)[1], nodesize = nodesize, nodedepth = nodedepth, ntree = ntree, family = family, splitrule = splitinfo$name, yvar = yvar, yvar.names = yvar.names, xvar = xvar, xvar.names = xvar.names, seed = nativeOutput$seed, bootstrap = bootstrap, sampsize = sampsize.function, samptype = samptype, samp = samp, case.wt = case.wt, terminal.qualts = terminal.qualts, terminal.quants = terminal.quants, nativeArrayTNDS = nativeArrayTNDS, version = "2.9.3", na.action = na.action, perf.type = perf.type, rfq = rfq, gk.quantile = gk.quantile, quantile.regr = quantile.regr, prob = prob, prob.epsilon = prob.epsilon, block.size = block.size) if (grepl("surv", family)) { forest.out$time.interest <- event.info$time.interest } class(forest.out) <- c("ltrcrrf", "forest", family) if (big.data) { class(forest.out) <- c(class(forest.out), "bigdata") } } else { forest.out <- list(forest = FALSE, hdim = hdim, base.learner = base.learner, nodesize = nodesize, nodedepth = nodedepth, ntree = ntree, family = family, splitrule = splitinfo$name, yvar = yvar, yvar.names = yvar.names, xvar = xvar, xvar.names = xvar.names, seed = nativeOutput$seed, bootstrap = bootstrap, sampsize = sampsize.function, samptype = samptype, samp = samp, case.wt = case.wt, version = "2.9.3", na.action = na.action, perf.type = perf.type, rfq = rfq, gk.quantile = gk.quantile, quantile.regr = quantile.regr, prob = prob, prob.epsilon = prob.epsilon, block.size = block.size) } if (proximity != FALSE) { proximity.out <- matrix(0, n, n) count <- 0 for (k in 1:n) { proximity.out[k,1:k] <- nativeOutput$proximity[(count+1):(count+k)] proximity.out[1:k,k] <- proximity.out[k,1:k] count <- count + k } nativeOutput$proximity <- NULL } else { proximity.out <- NULL } if (distance != FALSE) { distance.out <- matrix(0, n, n) count <- 0 for (k in 1:n) { distance.out[k,1:k] <- nativeOutput$distance[(count+1):(count+k)] distance.out[1:k,k] <- distance.out[k,1:k] count <- count + k } nativeOutput$distance <- NULL } else { distance.out <- NULL } if (forest.wt != FALSE) { forest.wt.out <- matrix(nativeOutput$weight, c(n, n), byrow = TRUE) nativeOutput$weight <- NULL } else { forest.wt.out <- NULL } if (membership) { membership.out <- matrix(nativeOutput$nodeMembership, c(n, ntree)) inbag.out <- matrix(nativeOutput$bootMembership, c(n, ntree)) nativeOutput$nodeMembership <- NULL nativeOutput$bootMembership <- NULL } else { membership.out <- NULL inbag.out <- NULL } if (var.used != FALSE) { if (var.used == "all.trees") { var.used.out <- nativeOutput$varUsed names(var.used.out) <- xvar.names } else { var.used.out <- matrix(nativeOutput$varUsed, nrow = ntree, byrow = TRUE) colnames(var.used.out) <- xvar.names } nativeOutput$varUsed <- NULL } else { var.used.out <- NULL } if (split.depth != FALSE) { if (split.depth == "all.trees") { split.depth.out <- array(nativeOutput$splitDepth, c(n, n.xvar)) } else { split.depth.out <- array(nativeOutput$splitDepth, c(n, n.xvar, ntree)) } nativeOutput$splitDepth <- NULL } else { split.depth.out <- NULL } if (statistics) { node.stats <- as.data.frame(cbind(nativeOutput$spltST[1:nativeArraySize])) colnames(node.stats) <- "spltST" node.mtry.stats <- t(array(nativeOutput$mtryST[1:nativeArraySize], c(mtry, forest.out$totalNodeCount))) node.mtry.index <- t(array(nativeOutput$mtryID[1:nativeArraySize], c(mtry, forest.out$totalNodeCount))) if (family == "unsupv") { node.ytry.index <- t(array(nativeOutput$uspvST[1:nativeArraySize], c(formulaDetail$ytry, forest.out$totalNodeCount))) } else { node.ytry.index <- NULL } } else { node.stats <- NULL node.mtry.stats <- NULL node.mtry.index <- NULL node.ytry.index <- NULL } empr.risk <- NULL oob.empr.risk <- NULL if (empirical.risk) { if (!is.null(nativeOutput$emprRisk)) { empr.risk <- array(nativeOutput$emprRisk, c(lot$treesize, ntree)) nativeOutput$emprRisk <- NULL } if (!is.null(nativeOutput$oobEmprRisk)) { oob.empr.risk <- array(nativeOutput$oobEmprRisk, c(lot$treesize, ntree)) nativeOutput$oobEmprRisk <- NULL } } if (!is.null(holdout.specs)) { holdout.blk <- nativeOutput$holdoutBlk nativeOutput$holdoutBlk <- NULL } else { holdout.blk = NULL } rfsrcOutput <- list( call = my.call, family = family, n = n, ntree = ntree, nimpute = nimpute, mtry = mtry, nodesize = nodesize, nodedepth = nodedepth, nsplit = splitinfo$nsplit, yvar = yvar, yvar.names = yvar.names, xvar = xvar, xvar.names = xvar.names, xvar.wt = xvar.wt, split.wt = split.wt, cause.wt = cause.wt, leaf.count = nativeOutput$leafCount, proximity = proximity.out, forest = forest.out, forest.wt = forest.wt.out, distance = distance.out, membership = membership.out, splitrule = splitinfo$name, inbag = inbag.out, var.used = var.used.out, imputed.indv = (if (n.miss > 0) imputed.indv else NULL), imputed.data = (if (n.miss > 0) imputed.data else NULL), split.depth = split.depth.out, node.stats = node.stats, node.mtry.stats = node.mtry.stats, node.mtry.index = node.mtry.index, node.ytry.index = node.ytry.index, ensemble = ensemble, holdout.array = holdout.array, block.size = block.size, holdout.blk = holdout.blk, empr.risk = empr.risk, oob.empr.risk = oob.empr.risk ) remove(yvar) remove(xvar) nativeOutput$leafCount <- NULL remove(proximity.out) remove(forest.out) remove(forest.wt.out) remove(distance.out) remove(membership.out) remove(inbag.out) remove(var.used.out) if (n.miss > 0) remove(imputed.indv) if (n.miss > 0) remove(imputed.data) remove(split.depth.out) remove(holdout.array) remove(empr.risk) remove(oob.empr.risk) survOutput <- NULL classOutput <- NULL regrOutput <- NULL if (!impute.only) { if (grepl("surv", family)) { if ((length(event.info$event.type) > 1) && (splitinfo$name != "l2.impute") && (splitinfo$name != "logrankscore")) { coerced.event.count <- length(event.info$event.type) } else { coerced.event.count <- 1 } if (family == "surv") { ens.names <- list(NULL, NULL) mortality.names <- list(NULL, NULL) err.names <- list(NULL, NULL) vimp.names <- list(NULL, xvar.names) } else { ens.names <- list(NULL, NULL, c(paste("condCHF.", 1:length(event.info$event.type), sep = ""))) mortality.names <- list(NULL, paste("event.", 1:length(event.info$event.type), sep = "")) cif.names <- list(NULL, NULL, c(paste("CIF.", 1:length(event.info$event.type), sep = ""))) err.names <- list(c(paste("event.", 1:length(event.info$event.type), sep = "")), NULL) vimp.names <- list(paste("event.", 1:length(event.info$event.type), sep = ""), xvar.names) } chf <- (if (!is.null(nativeOutput$allEnsbCHF)) adrop3d.last(array(nativeOutput$allEnsbCHF, c(n, length(event.info$time.interest), length(event.info$event.type)), dimnames=ens.names), coerced.event.count) else NULL) nativeOutput$allEnsbCHF <- NULL survOutput <- list(chf = chf) remove(chf) chf.oob <- (if (!is.null(nativeOutput$oobEnsbCHF)) adrop3d.last(array(nativeOutput$oobEnsbCHF, c(n, length(event.info$time.interest), length(event.info$event.type)), dimnames=ens.names), coerced.event.count) else NULL) nativeOutput$oobEnsbCHF <- NULL survOutput = c(survOutput, chf.oob = list(chf.oob)) remove(chf.oob) predicted <- (if (!is.null(nativeOutput$allEnsbMRT)) adrop2d.last(array(nativeOutput$allEnsbMRT, c(n, length(event.info$event.type)), dimnames=mortality.names), coerced.event.count) else NULL) nativeOutput$allEnsbMRT <- NULL survOutput = c(survOutput, predicted = list(predicted)) remove(predicted) predicted.oob <- (if (!is.null(nativeOutput$oobEnsbMRT)) adrop2d.last(array(nativeOutput$oobEnsbMRT, c(n, length(event.info$event.type)), dimnames=mortality.names), coerced.event.count) else NULL) nativeOutput$oobEnsbMRT <- NULL survOutput <- c(survOutput, predicted.oob = list(predicted.oob)) remove(predicted.oob) survival <- (if (!is.null(nativeOutput$allEnsbSRV)) matrix(nativeOutput$allEnsbSRV, c(n, length(event.info$time.interest))) else NULL) nativeOutput$allEnsbSRV <- NULL survOutput <- c(survOutput, survival = list(survival)) remove(survival) survival.oob <- (if (!is.null(nativeOutput$oobEnsbSRV)) matrix(nativeOutput$oobEnsbSRV, c(n, length(event.info$time.interest))) else NULL) nativeOutput$oobEnsbSRV <- NULL survOutput <- c(survOutput, survival.oob = list(survival.oob)) remove(survival.oob) cif <- (if (!is.null(nativeOutput$allEnsbCIF)) array(nativeOutput$allEnsbCIF, c(n, length(event.info$time.interest), length(event.info$event.type)), dimnames=cif.names) else NULL) nativeOutput$allEnsbCIF <- NULL survOutput <- c(survOutput, cif = list(cif)) remove(cif) cif.oob <- (if (!is.null(nativeOutput$oobEnsbCIF)) array(nativeOutput$oobEnsbCIF, c(n, length(event.info$time.interest), length(event.info$event.type)), dimnames=cif.names) else NULL) nativeOutput$oobEnsbCIF <- NULL survOutput = c(survOutput, cif.oob = list(cif.oob)) remove(cif.oob) if (!is.null(nativeOutput$perfSurv)) { err.rate <- adrop2d.first(array(nativeOutput$perfSurv, c(length(event.info$event.type), ntree), dimnames=err.names), coerced.event.count) nativeOutput$perfSurv <- NULL if (family == "surv-CR") { survOutput = c(survOutput, err.rate = list(t(err.rate))) } else { survOutput = c(survOutput, err.rate = list(err.rate)) } remove(err.rate) } if (!is.null(nativeOutput$blockSurv)) { err.block.rate <- adrop2d.first(array(nativeOutput$blockSurv, c(length(event.info$event.type), floor(ntree/block.size)), dimnames=err.names), coerced.event.count) nativeOutput$blockSurv <- NULL if (family == "surv-CR") { survOutput = c(survOutput, err.block.rate = list(t(err.block.rate))) } else { survOutput = c(survOutput, err.block.rate = list(err.block.rate)) } remove(err.block.rate) } if (!is.null(nativeOutput$vimpSurv)) { importance <- adrop2d.first(array(nativeOutput$vimpSurv, c(length(event.info$event.type), n.xvar), dimnames = vimp.names), coerced.event.count) nativeOutput$vimpSurv <- NULL if (family == "surv-CR") { survOutput = c(survOutput, importance = list(t(importance))) } else { survOutput = c(survOutput, importance = list(importance)) } remove(importance) } survOutput = c( survOutput, list( time.interest = event.info$time.interest, ndead = sum(na.omit(event.info$cens) != 0)) ) if (!is.null(nativeOutput$holdoutSurv)) { holdout.vimp <- vector("list", length(rfsrcOutput$holdout.blk)) names(holdout.vimp) <- xvar.names holdout.offset <- rfsrcOutput$holdout.blk * length(event.info$event.type) holdout.offset.sum <- c(0, cumsum(holdout.offset)) for (i in 1:length(holdout.vimp)) { if (rfsrcOutput$holdout.blk[i] > 0) { if (length(event.info$event.type) > 1) { holdout.vimp[[i]] <- array(nativeOutput$holdoutSurv[(holdout.offset.sum[i] + 1) : holdout.offset.sum[i+1]], c(length(event.info$event.type), rfsrcOutput$holdout.blk[i])) } else { holdout.vimp[[i]] <- nativeOutput$holdoutSurv[(holdout.offset.sum[i] + 1) : holdout.offset.sum[i+1]] } } else { holdout.vimp[[i]] = NA } } survOutput = c(survOutput, holdout.vimp = list(holdout.vimp)) remove(holdout.vimp) } if(univariate.nomenclature) { rfsrcOutput <- c(rfsrcOutput, survOutput) } else { rfsrcOutput <- c(rfsrcOutput, survOutput = list(survOutput)) } } else { class.index <- which(yvar.types != "R") resp.clas.count <- length(class.index) regr.index <- which(yvar.types == "R") resp.regr.count <- length(regr.index) if (resp.clas.count > 0) { classOutput <- vector("list", resp.clas.count) names(classOutput) <- yvar.names[class.index] levels.count <- array(0, resp.clas.count) levels.names <- vector("list", resp.clas.count) counter <- 0 for (i in class.index) { counter <- counter + 1 levels.count[counter] <- yvar.nlevels[i] if (yvar.types[i] == "C") { levels.names[[counter]] <- yfactor$levels[[which(yfactor$factor == yvar.names[i])]] } else { levels.names[[counter]] <- yfactor$order.levels[[which(yfactor$order == yvar.names[i])]] } } tree.offset <- array(1, ntree) if (ntree > 1) { tree.offset[2:ntree] <- sum(1 + levels.count) } tree.offset <- cumsum(tree.offset) block.offset <- array(1, floor(ntree/block.size)) if (floor(ntree/block.size) > 1) { block.offset[2:floor(ntree/block.size)] <- sum(1 + levels.count) } block.offset <- cumsum(block.offset) vimp.offset <- array(1, n.xvar) if (n.xvar > 1) { vimp.offset[2:n.xvar] <- sum(1 + levels.count) } vimp.offset <- cumsum(vimp.offset) iter.ensb.start <- 0 iter.ensb.end <- 0 if (!is.null(nativeOutput$holdoutClas)) { holdout.offset.x <- rfsrcOutput$holdout.blk * (sum(1 + levels.count)) holdout.offset.sum.x <- c(0, cumsum(holdout.offset.x)) holdout.offset.r <- 0 } for (i in 1:resp.clas.count) { iter.ensb.start <- iter.ensb.end iter.ensb.end <- iter.ensb.end + (levels.count[i] * n) ens.names <- list(NULL, levels.names[[i]]) err.names <- c("all", levels.names[[i]]) vimp.names <- list(c("all", levels.names[[i]]), xvar.names) predicted <- (if (!is.null(nativeOutput$allEnsbCLS)) array(nativeOutput$allEnsbCLS[(iter.ensb.start + 1):iter.ensb.end], c(n, levels.count[i]), dimnames=ens.names) else NULL) classOutput[[i]] <- list(predicted = predicted) response <- (if (!is.null(predicted)) getltrc.bayes.rule(predicted, pi.hat) else NULL) classOutput[[i]] <- c(classOutput[[i]], class = list(response)) remove(predicted) remove(response) predicted.oob <- (if (!is.null(nativeOutput$oobEnsbCLS)) array(nativeOutput$oobEnsbCLS[(iter.ensb.start + 1):iter.ensb.end], c(n, levels.count[i]), dimnames=ens.names) else NULL) classOutput[[i]] <- c(classOutput[[i]], predicted.oob = list(predicted.oob)) response.oob <- (if (!is.null(predicted.oob)) getltrc.bayes.rule(predicted.oob, pi.hat) else NULL) classOutput[[i]] <- c(classOutput[[i]], class.oob = list(response.oob)) remove(predicted.oob) remove(response.oob) if (!is.null(nativeOutput$perfClas)) { err.rate <- array(0, c(1 + levels.count[i], ntree)) for (j in 1: (1 + levels.count[i])) { err.rate[j, ] <- nativeOutput$perfClas[tree.offset] tree.offset <- tree.offset + 1 } row.names(err.rate) <- err.names classOutput[[i]] <- c(classOutput[[i]], err.rate = list(t(err.rate))) remove(err.rate) } if (!is.null(nativeOutput$blockClas)) { err.block.rate <- array(0, c(1 + levels.count[i], floor(ntree/block.size))) for (j in 1: (1 + levels.count[i])) { err.block.rate[j, ] <- nativeOutput$blockClas[block.offset] block.offset <- block.offset + 1 } row.names(err.block.rate) <- err.names classOutput[[i]] <- c(classOutput[[i]], err.block.rate = list(t(err.block.rate))) remove(err.block.rate) } if (!is.null(nativeOutput$vimpClas)) { importance <- array(0, c(1 + levels.count[i], n.xvar), dimnames=vimp.names) for (j in 1: (1 + levels.count[i])) { importance[j, ] <- nativeOutput$vimpClas[vimp.offset] vimp.offset <- vimp.offset + 1 } classOutput[[i]] <- c(classOutput[[i]], importance = list(t(importance))) remove(importance) } if (!is.null(nativeOutput$holdoutClas)) { holdout.vimp <- vector("list", length(rfsrcOutput$holdout.blk)) names(holdout.vimp) <- xvar.names if (i > 1) { holdout.offset.r <- holdout.offset.r + (1 + levels.count[i-1]) } for (k in 1:length(holdout.vimp)) { if (rfsrcOutput$holdout.blk[k] > 0) { offset.x <- holdout.offset.sum.x[k] offset.b <- 0 index.m <- NULL for (m in 1:rfsrcOutput$holdout.blk[k]) { if (m > 1) { offset.b <- offset.b + (sum(1 + levels.count)) } index.m <- c(index.m, seq(from = offset.x + offset.b + holdout.offset.r + 1, by = 1, length.out = levels.count[i] + 1)) } holdout.vimp[[k]] = array(nativeOutput$holdoutClas[index.m], c(levels.count[i] + 1, rfsrcOutput$holdout.blk[k])) } else { holdout.vimp[[k]] = NA } } classOutput[[i]] = c(classOutput[[i]], holdout.vimp = list(holdout.vimp)) remove(holdout.vimp) } } nativeOutput$allEnsbCLS <- NULL nativeOutput$oobEnsbCLS <- NULL nativeOutput$perfClas <- NULL nativeOutput$blockClas <- NULL nativeOutput$vimpClas <- NULL nativeOutput$holdoutClas <- NULL if(univariate.nomenclature) { if ((resp.clas.count == 1) & (resp.regr.count == 0)) { names(classOutput) <- NULL rfsrcOutput <- c(rfsrcOutput, unlist(classOutput, recursive=FALSE)) } else { rfsrcOutput <- c(rfsrcOutput, classOutput = list(classOutput)) } } else { rfsrcOutput <- c(rfsrcOutput, classOutput = list(classOutput)) } } if (resp.regr.count > 0) { regrOutput <- vector("list", resp.regr.count) names(regrOutput) <- yvar.names[regr.index] tree.offset <- array(1, ntree) if (ntree > 1) { tree.offset[2:ntree] <- length(regr.index) } tree.offset <- cumsum(tree.offset) block.offset <- array(1, floor(ntree/block.size)) if (floor(ntree/block.size) > 1) { block.offset[2:floor(ntree/block.size)] <- length(regr.index) } block.offset <- cumsum(block.offset) vimp.offset <- array(1, n.xvar) if (n.xvar > 1) { vimp.offset[2:n.xvar] <- length(regr.index) } vimp.offset <- cumsum(vimp.offset) iter.ensb.start <- 0 iter.ensb.end <- 0 iter.qntl.start <- 0 iter.qntl.end <- 0 if (!is.null(nativeOutput$holdoutRegr)) { holdout.offset.x <- rfsrcOutput$holdout.blk * resp.regr.count holdout.offset.sum.x <- c(0, cumsum(holdout.offset.x)) holdout.offset.r <- 0 } for (i in 1:resp.regr.count) { iter.ensb.start <- iter.ensb.end iter.ensb.end <- iter.ensb.end + n iter.qntl.start <- iter.qntl.end iter.qntl.end <- iter.qntl.end + (length(prob) * n) vimp.names <- xvar.names predicted <- (if (!is.null(nativeOutput$allEnsbRGR)) array(nativeOutput$allEnsbRGR[(iter.ensb.start + 1):iter.ensb.end], n) else NULL) regrOutput[[i]] <- list(predicted = predicted) remove(predicted) predicted.oob <- (if (!is.null(nativeOutput$oobEnsbRGR)) array(nativeOutput$oobEnsbRGR[(iter.ensb.start + 1):iter.ensb.end], n) else NULL) regrOutput[[i]] <- c(regrOutput[[i]], predicted.oob = list(predicted.oob)) remove(predicted.oob) quantile <- (if (!is.null(nativeOutput$allEnsbQNT)) array(nativeOutput$allEnsbQNT[(iter.qntl.start + 1):iter.qntl.end], c(n, length(prob))) else NULL) regrOutput[[i]] <- c(regrOutput[[i]], quantile = list(quantile)) remove(quantile) quantile.oob <- (if (!is.null(nativeOutput$oobEnsbQNT)) array(nativeOutput$oobEnsbQNT[(iter.qntl.start + 1):iter.qntl.end], c(n, length(prob))) else NULL) regrOutput[[i]] <- c(regrOutput[[i]], quantile.oob = list(quantile.oob)) remove(quantile.oob) if (!is.null(nativeOutput$perfRegr)) { err.rate <- nativeOutput$perfRegr[tree.offset] tree.offset <- tree.offset + 1 regrOutput[[i]] <- c(regrOutput[[i]], err.rate = list(err.rate)) remove(err.rate) } if (!is.null(nativeOutput$blockRegr)) { err.block.rate <- nativeOutput$blockRegr[block.offset] block.offset <- block.offset + 1 regrOutput[[i]] <- c(regrOutput[[i]], err.block.rate = list(err.block.rate)) remove(err.block.rate) } if (!is.null(nativeOutput$vimpRegr)) { importance <- nativeOutput$vimpRegr[vimp.offset] names(importance) <- xvar.names vimp.offset <- vimp.offset + 1 regrOutput[[i]] <- c(regrOutput[[i]], importance = list(importance)) remove(importance) } if (!is.null(nativeOutput$holdoutRegr)) { holdout.vimp <- vector("list", length(rfsrcOutput$holdout.blk)) names(holdout.vimp) <- xvar.names if (i > 1) { holdout.offset.r <- holdout.offset.r + 1 } for (k in 1:length(holdout.vimp)) { if (rfsrcOutput$holdout.blk[k] > 0) { offset.x <- holdout.offset.sum.x[k] offset.b <- 0 index.m <- NULL for (m in 1:rfsrcOutput$holdout.blk[k]) { if (m > 1) { offset.b <- offset.b + resp.regr.count } index.m <- c(index.m, offset.x + offset.b + holdout.offset.r + 1) } holdout.vimp[[k]] <- nativeOutput$holdoutRegr[index.m] } else { holdout.vimp[[k]] <- NA } } regrOutput[[i]] <- c(regrOutput[[i]], holdout.vimp = list(holdout.vimp)) } } nativeOutput$allEnsbRGR <- NULL nativeOutput$oobEnsbRGR <- NULL nativeOutput$allEnsbQNT <- NULL nativeOutput$oobEnsbQNT <- NULL nativeOutput$perfRegr <- NULL nativeOutput$blockRegr <- NULL nativeOutput$vimpRegr <- NULL nativeOutput$holdoutRegr <- NULL if(univariate.nomenclature) { if ((resp.clas.count == 0) & (resp.regr.count == 1)) { names(regrOutput) <- NULL rfsrcOutput <- c(rfsrcOutput, unlist(regrOutput, recursive=FALSE)) } else { rfsrcOutput <- c(rfsrcOutput, regrOutput = list(regrOutput)) } } else { rfsrcOutput <- c(rfsrcOutput, regrOutput = list(regrOutput)) } } } } class(rfsrcOutput) <- c("ltrcrfsrc", "grow", family) if (big.data) { class(rfsrcOutput) <- c(class(rfsrcOutput), "bigdata") } return(rfsrcOutput) }
monthmean<-function(data,resp,offsetpop=NULL,adjmonth=FALSE){ if (is.null(data)==TRUE){stop("must have an input data set (data)")} if (is.null(resp)==TRUE){stop("must have an input variable (resp)")} nnn<-names(data) if (any(nnn=='year')==FALSE){stop("data set must contain a variable with the 4 digit year called 'year'")} if (any(nnn=='month')==FALSE){stop("data set must contain a variable with the numeric month called 'month'")} days<-flagleap(data) mean<-vector(length=12,mode='numeric') if (adjmonth=='thirty') adjf=30 if (adjmonth=='average') adjf=365.25/12 if (is.null(offsetpop)==TRUE) adjp=1 else adjp=with(data,eval(offsetpop)) xxxx=subset(data,select=resp)[,1] for (i in 1:12){ if (adjmonth!=FALSE) mean[i]<-mean(xxxx[data$month==i]*(adjf/days$ndaysmonth[i])/adjp) else mean[i]<-mean(xxxx[data$month==i]/adjp) } toret<-list() toret$mean<-as.vector(mean) class(toret)<-'Monthmean' return(toret) }
originize_file <- function( file, pkgs = getOption("origin.pkgs", .packages()), overwrite = getOption("origin.overwrite", TRUE), ask_before_applying_changes = getOption("origin.ask_before_applying_changes", TRUE), ignore_comments = getOption("origin.ignore_comments", TRUE), check_conflicts = getOption("origin.check_conflicts", TRUE), check_base_conflicts = getOption("origin.check_base_conflicts", TRUE), add_base_packages = getOption("origin.add_base_packages", FALSE), excluded_functions = getOption("origin.excluded_functions", list()), verbose = getOption("origin.verbose", FALSE), use_markers = getOption("origin.use_markers_for_logging", TRUE), path_to_local_functions = getOption("origin.path_to_local_functions", NULL), check_local_conflicts = getOption("origin.check_local_conflicts", TRUE) ) { if (!file.exists(file)) { stop("No file in this path\n", file) } script <- suppressWarnings(readLines(file)) originize_wrap(scripts = list(script), files = file, type = "writeLines", pkgs = pkgs, overwrite = overwrite, ask_before_applying_changes = ask_before_applying_changes, ignore_comments = ignore_comments, check_conflicts = check_conflicts, check_base_conflicts = check_base_conflicts, add_base_packages = add_base_packages, excluded_functions = excluded_functions, verbose = verbose, use_markers = use_markers, path_to_local_functions = path_to_local_functions, check_local_conflicts = check_local_conflicts) return(invisible(NULL)) }
EBPRS <- function(train,test,N1,N0,robust=T){ if(missing(test)==T){ temp0 <- extractInfo(train) train <- temp0$train } else{ temp0 <- extractInfo(train,test) train <- temp0$train bim <- temp0$bim cat("Coordinating the ref alleles...","\n") colnames(train)[which(colnames(train)=="a1")] <- "A1" colnames(train)[which(colnames(train)=="a2")] <- "A2" colnames(train)[which(colnames(train)=="or")] <- "OR" colnames(train)[which(colnames(train)=="p")] <- "P" sig=agtc(train$A1,train$A2,bim[,5],bim[,6]) train$OR=(train$OR)^sig train <- train[train$OR>0,] } z <- -qnorm(train$P/2)*sign(log(train$OR)) se <- log(train$OR)/z z[which(is.na(z))] <- 0 se[which(is.na(se))] <- 1 cat("Utilizing EM algorithm to derive pi0 and sigma02","\n") if(robust==F){ temp <- snpEM(z,empNull=F,beta0=(length(z)/20), K=3) }else{ temp <- snpEMrobust(z, K=3, maxIter=1000, tol=1e-3, empNull=F, boot=1, info=TRUE) } res <- findpara_ltdr(n0=N0,n1=N1,SE=se,beta=log(train$OR),z=z,pi0Hat=temp$pi0,sigma02=temp$sigma2,ltdr=temp$ltdr,lfdr=temp$lfdr) cat("Estimating the parameters.","\n") muHatnew <- res$muHat/sqrt(res$sigmaHat2) muHatnew[which(is.na(muHatnew))] <- 0 result <- data.frame(train,effectsize=muHatnew) write.table(result,"res_para.txt") cat("Completed.","\n") if(missing(test)==F){ cat("Now calculating scores \n") S <- generateScore(muHatnew, temp0$bed) tt <- validate(S, test$fam[,6]) return(list(result=result,S=S,r2=tt$r2,AUC=tt$AUC,muHat=res$muHat,sigmaHat2=res$sigmaHat2,pi0=temp$pi0,sigma02=temp$sigma02,eff=muHatnew)) } else{ return(list(result=result,muHat=res$muHat,sigmaHat2=res$sigmaHat2,pi0=temp$pi0,sigma02=temp$sigma02,eff=muHatnew)) } }
movies <- function(fixed_range = TRUE, hscale = NA, vscale = hscale) { panel.launch <- function(menu.panel) { if (menu.panel$demo == "binomial") { discrete(distn = "binomial", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == "geometric") { if (fixed_range) { discrete(distn = "geometric", var_support = 0:30, hscale = hscale, vscale = vscale) } else { discrete(distn = "geometric", hscale = hscale, vscale = vscale) } } else if (menu.panel$demo == "hypergeometric") { discrete(distn = "hypergeometric", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == "negative binomial") { if (fixed_range) { discrete(distn = "negative binomial", var_support = 0:100, hscale = hscale, vscale = vscale) } else { discrete(distn = "negative binomial", hscale = hscale, vscale = vscale) } } else if (menu.panel$demo == "Poisson") { if (fixed_range) { discrete(distn = "poisson", var_support = 0:20, hscale = hscale, vscale = vscale) } else { discrete(distn = "poisson", hscale = hscale, vscale = vscale) } } else if (menu.panel$demo == "beta") { continuous(distn = "beta", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == "Cauchy") { if (fixed_range) { continuous(distn = "cauchy", var_range = c(-20, 20), hscale = hscale, vscale = vscale) } else { continuous(distn = "cauchy", hscale = hscale, vscale = vscale) } } else if (menu.panel$demo == "chi-squared") { if (fixed_range) { continuous(distn = "chi-squared", var_range = c(0, 15), hscale = hscale, vscale = vscale) } else { continuous(distn = "chi-squared", hscale = hscale, vscale = vscale) } } else if (menu.panel$demo == "exponential") { if (fixed_range) { continuous(distn = "exponential", var_range = c(0, 10), hscale = hscale, vscale = vscale) } else { continuous(distn = "exponential", hscale = hscale, vscale = vscale) } } else if (menu.panel$demo == "F") { if (fixed_range) { continuous(distn = "f", var_range = c(0, 10), hscale = hscale, vscale = vscale) } else { continuous(distn = "f", hscale = hscale, vscale = vscale) } } else if (menu.panel$demo == "gamma") { if (fixed_range) { continuous(distn = "gamma", var_range = c(0, 20), hscale = hscale, vscale = vscale) } else { continuous(distn = "gamma", hscale = hscale, vscale = vscale) } } else if (menu.panel$demo == "GEV") { if (fixed_range) { continuous(distn = "gev", var_range = c(-5, 15), hscale = hscale, vscale = vscale) } else { continuous(distn = "gev", hscale = hscale, vscale = vscale) } } else if (menu.panel$demo == "GP") { if (fixed_range) { continuous(distn = "gp", var_range = c(-3, 15), hscale = hscale, vscale = vscale) } else { continuous(distn = "gp", hscale = hscale, vscale = vscale) } } else if (menu.panel$demo == "lognormal") { if (fixed_range) { continuous(distn = "lognormal", var_range = c(0, 15), hscale = hscale, vscale = vscale) } else { continuous(distn = "lognormal", hscale = hscale, vscale = vscale) } } else if (menu.panel$demo == "normal") { if (fixed_range) { continuous(distn = "normal", var_range = c(-8, 8), hscale = hscale, vscale = vscale) } else { continuous(distn = "normal", hscale = hscale, vscale = vscale) } } else if (menu.panel$demo == "Student t") { if (fixed_range) { continuous(distn = "t", var_range = c(-10, 10), hscale = hscale, vscale = vscale) } else { continuous(distn = "t", hscale = hscale, vscale = vscale) } } else if (menu.panel$demo == "uniform") { if (fixed_range) { continuous(distn = "uniform", var_range = c(-2, 3), hscale = hscale, vscale = vscale) } else { continuous(distn = "uniform", hscale = hscale, vscale = vscale) } } else if (menu.panel$demo == "Weibull") { if (fixed_range) { continuous(distn = "weibull", var_range = c(0, 10), hscale = hscale, vscale = vscale) } else { continuous(distn = "weibull", hscale = hscale, vscale = vscale) } } else if (menu.panel$demo == "correlation coefficient") { correlation(n = 10, hscale = hscale, vscale = vscale) } else if (menu.panel$demo == "Mean") { clt(distn = "exponential", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == "Maximum") { ett(distn = "exponential", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == "Median") { cltq(distn = "exponential", p = 0.5, hscale = hscale, vscale = vscale) } else if (menu.panel$demo == "Mean vs median, normal") { mean_vs_median() } else if (menu.panel$demo == "Mean vs median, Student t(2)") { mean_vs_median(t_df = 2) } else if (menu.panel$demo == "Lower quartile") { cltq(distn = "exponential", p = 0.25, hscale = hscale, vscale = vscale) } else if (menu.panel$demo == "Upper quartile") { cltq(distn = "exponential", p = 0.75, hscale = hscale, vscale = vscale) } else if (menu.panel$demo == "Leverage and influence") { lev_inf(hscale = hscale, vscale = vscale) } else if (menu.panel$demo == "Wald, Wilks and Score tests") { wws(model = "binom", theta0 = 0.5, hscale = hscale, vscale = vscale) } else if (menu.panel$demo == "Testing simple hypotheses") { shypo(mu0 = 0, eff = 5, n = 1, hscale = hscale, vscale = vscale) } else if (menu.panel$demo == "beta ") { ett(distn = "beta", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == "Cauchy ") { ett(distn = "cauchy", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == "chi-squared ") { ett(distn = "chi-squared", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == "exponential ") { ett(distn = "exponential", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == "F ") { ett(distn = "f", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == "gamma ") { ett(distn = "gamma", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == "generalized Pareto ") { ett(distn = "gp", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == "log-normal ") { ett(distn = "log-normal", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == "negated GEV ") { ett(distn = "ngev", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == "normal ") { ett(distn = "normal", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == "Student t ") { ett(distn = "t", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == "uniform ") { ett(distn = "uniform", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == "Weibull ") { ett(distn = "weibull", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == " beta") { clt(distn = "beta", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == " binomial") { clt(distn = "binomial", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == " chi-squared") { clt(distn = "chi-squared", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == " exponential") { clt(distn = "exponential", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == " F") { clt(distn = "f", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == " gamma") { clt(distn = "gamma", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == " generalized Pareto") { clt(distn = "gp", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == " geometric") { clt(distn = "geometric", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == " hypergeometric") { clt(distn = "hypergeometric", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == " GEV") { clt(distn = "gev", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == " log-normal") { clt(distn = "log-normal", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == " negative binomial") { clt(distn = "binomial", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == " normal") { clt(distn = "normal", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == " Poisson") { clt(distn = "poisson", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == " Student t") { clt(distn = "t", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == " uniform") { clt(distn = "uniform", hscale = hscale, vscale = vscale) } else if (menu.panel$demo == " Weibull") { clt(distn = "weibull", hscale = hscale, vscale = vscale) } return(menu.panel) } menu.panel <- rpanel::rp.control("Movies", homer = FALSE, number.list = list(), ss = list(), trans = list(), theta = list()) menu.list <- list(list("Discrete", "binomial", "geometric", "hypergeometric", "negative binomial", "Poisson" ), list("Continuous", "beta", "Cauchy", "chi-squared", "exponential", "F", "gamma", "GEV", "GP", "lognormal", "normal", "Student t", "uniform", "Weibull" ), list("Sampling distributions", "Correlation coefficient", "Mean", "Maximum", "Median", "Mean vs median, normal", "Mean vs median, Student t(2)", "Lower quartile", "Upper quartile" ), list("CLT", " beta", " binomial", " Cauchy", " chi-squared", " exponential", " F", " gamma", " generalized Pareto", " geometric", " hypergeometric", " log-normal", " GEV", " negative binomial", " normal", " Poisson", " Student t", " uniform", " Weibull" ), list("Regression", "Leverage and influence" ), list("Hypothesis testing", "Wald, Wilks and Score tests", "Testing simple hypotheses" ), list("Extremal types", "beta ", "Cauchy ", "chi-squared ", "exponential ", "F ", "gamma ", "generalized Pareto ", "log-normal ", "negated GEV ", "normal ", "Student t ", "uniform ", "Weibull " ) ) demo <- NULL rpanel::rp.menu(menu.panel, variable = demo, labels = menu.list, action = panel.launch) image.file <- file.path(system.file(package = "rpanel"), "images", "cartoons.gif") rpanel::rp.image(menu.panel, image.file) return(invisible()) }
require(properties) props <- list(key1 = "value1", key2 = "value2", key3 = "value3") propFilePath <- tempfile(tmpdir = ".") write.properties(propFilePath, props) expectedLines = c("key1=value1", "key2=value2", "key3=value3") stopifnot(all.equal(readLines(propFilePath), expectedLines)) file.remove(propFilePath) expectedProps <- read.properties(system.file("testFiles", "test2.properties", package = "properties")) propFilePath <- tempfile(tmpdir = ".") write.properties(propFilePath, expectedProps) props <- read.properties(propFilePath) stopifnot(all.equal(props, expectedProps)) file.remove(propFilePath) props <- read.properties(system.file("testFiles", "test3.properties", package = "properties")) propFilePath <- tempfile(tmpdir = ".") write.properties(propFilePath, props, fields = c("key2", "key7")) expectedLines <- c("key2=value2", "key7=value7") stopifnot(all.equal(readLines(propFilePath), expectedLines)) file.remove(propFilePath) expectedProps <- read.properties(system.file("testFiles", "test4.properties", package = "properties")) propFilePath <- tempfile(tmpdir = ".") write.properties(propFilePath, expectedProps) props <- read.properties(propFilePath) stopifnot(all.equal(props, expectedProps)) file.remove(propFilePath)
od_REX <- function(Fx, crit="D", h=NULL, w1=NULL, alg.AA="REX", eff=0.999999, it.max=Inf, t.max=60, echo=TRUE, track=TRUE) { cl <- match.call() verify(cl, Fx = Fx, crit = crit, h = h, w1 = w1, alg.AA = alg.AA, eff = eff, it.max = it.max, t.max = t.max, echo = echo, track = track) n <- nrow(Fx); m <- ncol(Fx) if (crit %in% c("C", "c") && is.null(h)) h <- c(rep(0, m - 1), 1) if (!is.null(w1) && sum(w1) != 1) { message("w1 not perfectly normalized; normalizing.") w1 <- w1 / sum(w1) } if (crit == "D") { if (alg.AA == "REX") res <- od_D_REX(Fx = Fx, w1 = w1, ver = 1, gamma = 4, eff = eff, it.max = it.max, t.max = t.max, track = track) if (alg.AA == "MUL") res <- od_D_MUL(Fx = Fx, w1 = w1, eff = eff, it.max = it.max, t.max = t.max, track = track) if (alg.AA == "VDM") res <- od_D_VDM(Fx = Fx, w1 = w1, eff = eff, it.max = it.max, t.max = t.max, track = track) } if (crit == "A") { if (alg.AA == "REX") res <- od_A_REX(Fx = Fx, w1 = w1, ver = 1, gamma = 1, eff = eff, it.max = it.max, t.max = t.max, track = track) if (alg.AA == "MUL") res <- od_A_MUL(Fx = Fx, w1 = w1, lambda = 0.5, eff = eff, it.max = it.max, t.max = t.max, track = track) if (alg.AA == "VDM") res <- od_A_VDM(Fx = Fx, w1 = w1, eff = eff, it.max = it.max, t.max = t.max, track = track) } if (crit == "I") { if (alg.AA == "REX") res <- od_A_REX(Fx = Fx_ItoA(Fx, echo = FALSE), w1 = w1, ver = 1, gamma = 1, eff = eff, it.max = it.max, t.max = t.max, track = track) if (alg.AA == "MUL") res <- od_A_MUL(Fx = Fx_ItoA(Fx, echo = FALSE), w1 = w1, lambda = 0.5, eff = eff, it.max = it.max, t.max = t.max, track = track) if (alg.AA == "VDM") res <- od_A_VDM(Fx = Fx_ItoA(Fx, echo = FALSE), w1 = w1, eff = eff, it.max = it.max, t.max = t.max, track = track) } if (crit == "C") { if (alg.AA == "REX") res <- od_A_REX(Fx = Fx_CtoA(Fx, h, echo = FALSE), w1 = w1, ver = 1, gamma = 1, eff = eff, it.max = it.max, t.max = t.max, track = track) if (alg.AA == "MUL") res <- od_A_MUL(Fx = Fx_CtoA(Fx, h, echo = FALSE), w1 = w1, lambda = 0.5, eff = eff, it.max = it.max, t.max = t.max, track = track) if (alg.AA == "VDM") res <- od_A_VDM(Fx = Fx_CtoA(Fx, h, echo = FALSE), w1 = w1, eff = eff, it.max = it.max, t.max = t.max, track = track) } if (crit == "c") { message("Linear programming reformulation will be used for c-optimality.") res <- od_c_LP(Fx, h, track) } supp <- (1:n)[res$w.best > 0] res <- list(call = cl, w.best = res$w.best, supp = supp, w.supp = res$w.best[supp], M.best = infmat(Fx, res$w.best, echo = FALSE), Phi.best = optcrit(Fx, res$w.best, crit, h, echo = FALSE), eff.best = res$eff.best, n.iter = res$n.iter, t.act = res$t.act) return(res) }