content large_stringlengths 0 6.46M | path large_stringlengths 3 331 | license_type large_stringclasses 2 values | repo_name large_stringlengths 5 125 | language large_stringclasses 1 value | is_vendor bool 2 classes | is_generated bool 2 classes | length_bytes int64 4 6.46M | extension large_stringclasses 75 values | text stringlengths 0 6.46M |
|---|---|---|---|---|---|---|---|---|---|
#1.1
#i)
x <- rnorm(100, -1, sqrt(2.5))
e <- rnorm(100, 0, sqrt(3))
y <- 2.5 + 2 * x + e
par(mfrow = c(1,1))
plot(x, y, xlab = "x", ylab = "y", pch = 20, main = "1.1 Y versus X")
abline(model <- lm(y ~ x))
#ii)
abline(mod25 <- lm(y[1:25] ~ x[1:25]), col = "red")
abline(mod25 <- lm(y[26:100] ~ x[26:100]), col = "green")
#not the same because the data the regression is based off of is different.
#iii)
mean(y)
#true: 0.5 (just plug via equation)
#iv)
bound <- qnorm(c(0.075), 0, sqrt(3))
print(bound)
abline(model$coefficients[1] + bound, model$coefficients[2], lty = 2)
abline(model$coefficients[1] - bound, model$coefficients[2], lty = 2)
#percent that fall in. Makes sense since we did an 85% interval.
length(model$residuals[model$residuals^2 < bound^2])
#1.2) Leverage Effect.
#i)
lev <- read.csv("leverage.csv")
summary(lev)
spxr <- diff(log(lev$SPX))
vixr <- diff(log(lev$VIX))
plot(vixr, spxr, xlab = "VIX Returns", ylab = "SPX Returns", pch = 20, main = "SPX vs VIX Returns")
summary(spx.model <- lm(spxr ~ vixr) )
print(b1 <- cor(spxr, vixr) * sd(spxr) / sd(vixr) )
print(b0 <- mean(spxr) - b1 * mean(vixr))
abline(spx.model)
#iii)
print(lev.aov <- anova(spx.model) )
#SST is 2938350, SSE is 890392, SSR = SST - SSE = 2047958
lev.aov$'Sum Sq'[1] / (lev.aov$'Sum Sq'[1] + lev.aov$'Sum Sq'[2])
(lev.aov$'Sum Sq'[1] + lev.aov$'Sum Sq'[2])
sum(spx.model$residual^2)
cor(vixr, spxr)^2
#variance explained above: 0.3030245
#iv) Not too sure what they are asking here....
x <- c(0, 0.1, 0.2, 0.3, 0.4)
y <- c(1, 2, 3, 4, 5)
summary(lm(y ~ x) )
#v) Assuming that the VIX level is in the range of the data set...
bound <- qnorm(0.05, sd= 0.025)
print( spxlow <- b0 + b1 * 0.1 + bound )
print( spxlow <- b0 + b1 * 0.1 - bound )
#1.3
#i)
van <- read.csv("vanguard.csv")
summary(van)
print(len<-dim(van)[1])
RetSPX <- diff(log(van$SPX))*52-van$TBILL[2:(len)]/100
Retvan <- 52*log(van[2:len,2:(dim(van)[2]-2)])-52*log(van[1:len-1,2:(dim(van)[2]-2)])-van$TBILL[2:(len)]/100
summary(CAPM <- lm(as.matrix(Retvan) ~ RetSPX, data = van))
plot(CAPM$coefficients[2,], CAPM$coeff[1,], col = 0, xlab = "beta", ylab = "alpha")
text(x=CAPM$coeff[2,], y=CAPM$coeff[1,], labels=names(van)[2:(dim(van)[2]-2)], col=2)
| /Pset2.R | no_license | Karagul/Applied-Regression-Analysis | R | false | false | 2,303 | r | #1.1
#i)
x <- rnorm(100, -1, sqrt(2.5))
e <- rnorm(100, 0, sqrt(3))
y <- 2.5 + 2 * x + e
par(mfrow = c(1,1))
plot(x, y, xlab = "x", ylab = "y", pch = 20, main = "1.1 Y versus X")
abline(model <- lm(y ~ x))
#ii)
abline(mod25 <- lm(y[1:25] ~ x[1:25]), col = "red")
abline(mod25 <- lm(y[26:100] ~ x[26:100]), col = "green")
#not the same because the data the regression is based off of is different.
#iii)
mean(y)
#true: 0.5 (just plug via equation)
#iv)
bound <- qnorm(c(0.075), 0, sqrt(3))
print(bound)
abline(model$coefficients[1] + bound, model$coefficients[2], lty = 2)
abline(model$coefficients[1] - bound, model$coefficients[2], lty = 2)
#percent that fall in. Makes sense since we did an 85% interval.
length(model$residuals[model$residuals^2 < bound^2])
#1.2) Leverage Effect.
#i)
lev <- read.csv("leverage.csv")
summary(lev)
spxr <- diff(log(lev$SPX))
vixr <- diff(log(lev$VIX))
plot(vixr, spxr, xlab = "VIX Returns", ylab = "SPX Returns", pch = 20, main = "SPX vs VIX Returns")
summary(spx.model <- lm(spxr ~ vixr) )
print(b1 <- cor(spxr, vixr) * sd(spxr) / sd(vixr) )
print(b0 <- mean(spxr) - b1 * mean(vixr))
abline(spx.model)
#iii)
print(lev.aov <- anova(spx.model) )
#SST is 2938350, SSE is 890392, SSR = SST - SSE = 2047958
lev.aov$'Sum Sq'[1] / (lev.aov$'Sum Sq'[1] + lev.aov$'Sum Sq'[2])
(lev.aov$'Sum Sq'[1] + lev.aov$'Sum Sq'[2])
sum(spx.model$residual^2)
cor(vixr, spxr)^2
#variance explained above: 0.3030245
#iv) Not too sure what they are asking here....
x <- c(0, 0.1, 0.2, 0.3, 0.4)
y <- c(1, 2, 3, 4, 5)
summary(lm(y ~ x) )
#v) Assuming that the VIX level is in the range of the data set...
bound <- qnorm(0.05, sd= 0.025)
print( spxlow <- b0 + b1 * 0.1 + bound )
print( spxlow <- b0 + b1 * 0.1 - bound )
#1.3
#i)
van <- read.csv("vanguard.csv")
summary(van)
print(len<-dim(van)[1])
RetSPX <- diff(log(van$SPX))*52-van$TBILL[2:(len)]/100
Retvan <- 52*log(van[2:len,2:(dim(van)[2]-2)])-52*log(van[1:len-1,2:(dim(van)[2]-2)])-van$TBILL[2:(len)]/100
summary(CAPM <- lm(as.matrix(Retvan) ~ RetSPX, data = van))
plot(CAPM$coefficients[2,], CAPM$coeff[1,], col = 0, xlab = "beta", ylab = "alpha")
text(x=CAPM$coeff[2,], y=CAPM$coeff[1,], labels=names(van)[2:(dim(van)[2]-2)], col=2)
|
#' BSI - Bare Soil Index
#'
#' BSI can be used for soil mapping and crop identification. This index relates the Blue, Red, Near Infrared and Short Wave Infrared bands.
#'
#' @param B A raster layer object with the reflectance values for the Blue band.
#' @param R A raster layer object with the reflectance values for the Red band.
#' @param NIR A raster layer object with the reflectance values for the Near Infrared band.
#' @param SWIR1 A raster layer object with the reflectance values for the Short Wave Infrared band.
#' @return BSI - Bare Soil Index.
#'
#' @examples
#' library(raster)
#' path_files <- system.file("extdata/", package="nightmares")
#' bands <- stack(list.files(path_files,".tif", full.names=TRUE))
#' x <- ref_oli(bands, sun.elev= 67.97)
#' BSI(x[[2]], x[[4]], x[[5]], x[[6]])
#'
#' @references
#' Rikimaru et al., 2002. Tropical forest cover density mapping. Tropical Ecology, 43, 39-47.
#' \url{https://www.geo.university/pages/spectral-indices-with-multispectral-satellite-data}.
#' @export
#' @import raster
BSI <- function (B, R, NIR, SWIR1) {
if (missing(B)) {
stop("Required data missing. Please, enter the reflectance values for the Blue band")
}
if (missing(R)) {
stop("Required data missing. Please, select the reflectance values for the Red band")
}
if (missing(NIR)) {
stop("Required data missing. Please, enter the reflectance values for the Near Infrared band")
}
if (missing(SWIR1)) {
stop("Required data missing. Please, enter the reflectance values for the Short Wave Infrared band")
}
BSI <- ((SWIR1+R)-(NIR+B))/((SWIR1+R)+(NIR+B))
}
| /R/BSI.R | no_license | cran/nightmares | R | false | false | 1,651 | r | #' BSI - Bare Soil Index
#'
#' BSI can be used for soil mapping and crop identification. This index relates the Blue, Red, Near Infrared and Short Wave Infrared bands.
#'
#' @param B A raster layer object with the reflectance values for the Blue band.
#' @param R A raster layer object with the reflectance values for the Red band.
#' @param NIR A raster layer object with the reflectance values for the Near Infrared band.
#' @param SWIR1 A raster layer object with the reflectance values for the Short Wave Infrared band.
#' @return BSI - Bare Soil Index.
#'
#' @examples
#' library(raster)
#' path_files <- system.file("extdata/", package="nightmares")
#' bands <- stack(list.files(path_files,".tif", full.names=TRUE))
#' x <- ref_oli(bands, sun.elev= 67.97)
#' BSI(x[[2]], x[[4]], x[[5]], x[[6]])
#'
#' @references
#' Rikimaru et al., 2002. Tropical forest cover density mapping. Tropical Ecology, 43, 39-47.
#' \url{https://www.geo.university/pages/spectral-indices-with-multispectral-satellite-data}.
#' @export
#' @import raster
BSI <- function (B, R, NIR, SWIR1) {
if (missing(B)) {
stop("Required data missing. Please, enter the reflectance values for the Blue band")
}
if (missing(R)) {
stop("Required data missing. Please, select the reflectance values for the Red band")
}
if (missing(NIR)) {
stop("Required data missing. Please, enter the reflectance values for the Near Infrared band")
}
if (missing(SWIR1)) {
stop("Required data missing. Please, enter the reflectance values for the Short Wave Infrared band")
}
BSI <- ((SWIR1+R)-(NIR+B))/((SWIR1+R)+(NIR+B))
}
|
#
# EE622: Advanced Machine Learning
# Prof. Amit Sethi
# Assignment 1: HDLSS Lung Cancer Data Analysis
#
# Name: Duddu Sai Meher Karthik
# Roll No. : 130101084
#
#
library(Biobase)
library(GEOquery)
library(glmnet) #for models + regularization
library(mice) #for data imputation
library(lattice) #for 1D cluster visualization
library(dbscan) #for cluster analysis
library(caret) #confusion matrix calculation
library(proc) #ROC/AUC comparison (NOTE: couldn't complete this analysis)
gds2771 <- getGEO(filename='B:/Acad/Course Material/Semester 7/EE622/Assignment1/GDS2771.soft.gz') # Make sure path is correct as per your working folder. Could be './GDS2771.soft.gz'
eset2771 <- GDS2eSet(gds2771) # See http://www2.warwick.ac.uk/fac/sci/moac/people/students/peter_cock/r/geo/
data2771 <- cbind2(c('disease.state',pData(eset2771)$disease.state),t(Table(gds2771)[,2:194]))
colnames(data2771) = data2771[1, ] # the first row will be the header
data2771 = data2771[-1, ]
# WRITE YOUR CODE BELOW THIS LINE
df <- as.data.frame(data2771)
df <- subset(df, df[,1] != "3") # Remove suspected cancer cases from data - 5 in number
df <- as.data.frame(apply(df, 2, function(x) as.numeric(x))) # Convert columns to numeric
#Handling missing data
# Step 1: Eliminate all genes which contain missing values for all samples
df <- df[, colSums(is.na(df)) < nrow(df)]
# Step 2: Impute values for all genes which contain partial missing values (using mean)
# Note: This dataset doesn't require this step, as after step 1, all na values disappear. Method kept for completeness
df <- if (sum(is.na(df)) > 0) mice(df, method = "mean") else df # Final number of genes = 22216
#Dividing dataset into testing and training sets
SPLIT.PERCENTAGE = 0.75 # 75-25 training-to-testing ratio
train.size = floor(nrow(df)*SPLIT.PERCENTAGE)
set.seed(101) #to ensure reproducibility
train.idx <- sample(nrow(df), size = train.size)
train_x <- as.matrix(df[train.idx, -1]) #The training dataset features
train_y <- df[train.idx, 1] #The training dataset annotation vector
test_x <- as.matrix(df[-train.idx, -1]) #The testing dataset features
test_y <- df[-train.idx, 1] #The testing dataset annotation vector
#Error computation function
get_error <- function(pred_y, test_y) {
return (mean(pred_y != test_y))
}
#Experiment 1: Linear regression with Lasso and 10-fold cross-validation (mean-squared error)
#Note: All features normalized (standardized) before training, and rescaled before prediction
cvfit_e1 = cv.glmnet(x=train_x, y=train_y, nfolds=10, family="gaussian", type.measure="mse", alpha=1, standardize=TRUE)
pred_y <- predict(cvfit_e1, newx=test_x, s="lambda.min") #Choosing knee-point lambda value
# Applying thresholding to the predicted values for comparison purposes (threshold - 1.5 for 2-class)
REGRESSION.THRESHOLD = 1.5
pred_y <- lapply(pred_y, function(x) {if (x > REGRESSION.THRESHOLD) 2 else 1} )
# Deliverables
# 1. Accuracy in terms of error rate
err_per1 <- get_error(pred_y, test_y)
# 2. Graph of cross-validation of lambda and min lambda value
# plot(cvfit_e1)
# cvfit_e1$lambda.min
# 3. Number of non-zero coefficients
coef_e1 <- abs(coef(cvfit_e1, s="lambda.min"))
nz_idx <- which(coef_e1 != 0)
# length(nz_idx)
# plot(cvfit_e3$glmnet.fit$lambda, cvfit_e3$glmnet.fit$df, type="o", col="red", ylab="Number of non-zero coefficients", xlab="Lambda")
# 4. Top 10 important genes
nz_wt_sorted <- sort(coef_e1[nz_idx], decreasing = TRUE, index.return=TRUE)
nz_genes_e1 <- rownames(coef_e1)[nz_idx][nz_wt_sorted$ix[nz_wt_sorted$ix != 1]] #Exclude the 'Intercept' field
# nz_genes_e1[1:10]
#Experiment 2: Linear regression with Ridge
#Note: All features normalized (standardized) before training, and rescaled before prediction
cvfit_e2 = cv.glmnet(x=train_x, y=train_y, nfolds=10, type.measure="mse", family="gaussian", alpha=0, standardize=TRUE)
pred_y <- predict(cvfit_e2, newx=test_x, s="lambda.min") #Choosing knee-point lambda value
# Applying thresholding to the predicted values for comparison purposes (threshold - 1.5 for 2-class)
REGRESSION.THRESHOLD = 1.5
pred_y <- lapply(pred_y, function(x) {if (x > REGRESSION.THRESHOLD) 2 else 1} )
# Deliverables
# 1. Accuracy in terms of error rate
err_per2 <- get_error(pred_y, test_y)
# 2. Graph of cross-validation of lambda and min lambda value
# plot(cvfit_e2)
# cvfit_e2$lambda.min
# 3. Grouping effect in ridge
coef_e2 <- abs(coef(cvfit_e2, s="lambda.min"))
coefe <- as.matrix(scale(coef_e2[-1])) #To remove intercept and scale coefficients
cl <- dbscan::dbscan(coefe, eps=0.25, minPts=5)
stripplot(coefe, col="red", xlab="Grouping of coefficients in Ridge (Linear)")
nz_idx <- which(coef_e2 != 0)
# length(nz_idx)
# 4. Top 10 important genes
nz_wt_sorted <- sort(coef_e2[nz_idx], decreasing = TRUE, index.return=TRUE)
nz_genes_e2 <- rownames(coef_e2)[nz_idx][nz_wt_sorted$ix[nz_wt_sorted$ix != 1]] #Exclude the 'Intercept' field
# nz_genes_e2[1:10]
# 5. Cluster Analysis
coefe <- as.matrix(coef_e2[-1])
#Experiment 3: Choosing value of mixing parameter(alpha) of elasticnet using cross-validation
a <- matrix(NA,51,3)
j=1
i=0
for(i in seq(0,1,by=0.02))
{
cvfit_e2 = cv.glmnet(x=train_x, y=train_y, nfolds=10, type.measure="mse", family="gaussian", alpha=i, standardize=TRUE)
a[j,1] <- i
a[j,2] <- cvfit_e2$lambda.min
a[j,3] <- min(cvfit_e2$cvm)
j=j+1
}
colnames(a) <- c("alpha","lambda_min","crossval_mean_error")
df_1 <- data.frame(a)
plot(crossval_mean_error ~ alpha,df_1,type="l")
cvm_min <- min(a[,"crossval_mean_error"])
index = which(a[,"crossval_mean_error"]==cvm_min)
alphamin = df_1[index,"alpha"]
# from the plot, the elastic net parameters are alphamin= 0.04
# applying the elastic net with 10 folds for the alphamin
cvfit_enet = cv.glmnet(x=train_x, y=train_y, nfolds=10, type.measure="mse", family="gaussian", alpha=alphamin, standardize=TRUE)
pred_y <- predict(cvfit_enet, newx=test_x, s="lambda.min") #Choosing knee-point lambda value
# Applying thresholding to the predicted values for comparison purposes (threshold - 1.5 for 2-class)
REGRESSION.THRESHOLD = 1.5
pred_y <- lapply(pred_y, function(x) {if (x > REGRESSION.THRESHOLD) 2 else 1} )
# Deliverables
# 1. Accuracy in terms of error rate
err_per_enet <- get_error(pred_y, test_y)
# 2. Graph of cross-validation of lambda
# plot(cvfit_e2)
# cvfit_e2$lambda.min
# 3. Number of non-zero coefficients
coef_enet <- abs(coef(cvfit_enet, s="lambda.min"))
nz_idx <- which(coef_enet != 0)
# length(nz_idx)
# plot(cvfit_enet$glmnet.fit$lambda, cvfit_enet$glmnet.fit$df, type="o", col="red", ylab="Number of non-zero coefficients", xlab="Lambda")
# 4. Grouping effect elasticnet
coefe <- as.matrix(scale(coef_enet[-1])) #To remove intercept and scale coefficients
cl <- dbscan::dbscan(coefe, eps=0.30, minPts=5)
stripplot(coefe, col="red", xlab="Grouping of coefficients in Ridge (Linear)")
# 5. Top 10 important genes
nz_wt_sorted <- sort(coef_enet[nz_idx], decreasing = TRUE, index.return=TRUE)
nz_genes_enet <- rownames(coef_enet)[nz_idx][nz_wt_sorted$ix[nz_wt_sorted$ix != 1]] #Exclude the 'Intercept' field
# nz_genes_enet[1:10]
#Experiment 4: Logistic regression with Lasso
#Note: All features normalized (standardized) before training, and rescaled before prediction
cvfit_e3 = cv.glmnet(x=train_x, y=train_y, nfolds=10, family="binomial", type.measure="class", alpha=1, standardize=TRUE)
pred_y <- predict(cvfit_e3, newx=test_x, s="lambda.min", type="class") #Choosing knee-point lambda value
# Deliverables
# 1. Accuracy in terms of error rate
err_per3 <- get_error(pred_y, test_y)
# 2. Graph of cross-validation of lambda and min lambda value
# plot(cvfit_e3)
# cvfit_e3$lambda.min
# 3. Variation in non-zero coefficients
coef_e3 <- abs(coef(cvfit_e3, s="lambda.min"))
nz_idx <- which(coef_e3 != 0)
# length(nz_idx)
# plot(cvfit_e3$glmnet.fit$lambda, cvfit_e3$glmnet.fit$df, type="o", col="red", ylab="Number of non-zero coefficients", xlab="Lambda")
# 4. Top 10 important genes
nz_wt_sorted <- sort(coef_e3[nz_idx], decreasing = TRUE, index.return=TRUE)
nz_genes_e3 <- rownames(coef_e3)[nz_idx][nz_wt_sorted$ix[nz_wt_sorted$ix != 1]] #Exclude the 'Intercept' field
# nz_genes_e3[1:10]
#Experiment 5: Logistic regression with Ridge
#Note: All features normalized (standardized) before training, and rescaled before prediction
cvfit_e4 = cv.glmnet(x=train_x, y=train_y, nfolds=10, family="binomial", type.measure="class", alpha=0, standardize=TRUE)
pred_y <- predict(cvfit_e4, newx=test_x, s="lambda.min", type="class") #Choosing knee-point lambda value
# Deliverables
# 1. Accuracy in terms of error rate
err_per4 <- get_error(pred_y, test_y)
# 2. Graph of cross-validation of lambda and min lambda value
# plot(cvfit_e4)
# cvfit_e4$lambda.min
# 3. Grouping effect in ridge
coef_e4 <- abs(coef(cvfit_e4, s="lambda.min"))
coefe <- as.matrix(scale(coef_e4[-1])) #To remove intercept and scale coefficients
cl <- dbscan::dbscan(coefe, eps=0.25, minPts=5)
stripplot(coefe)
# 4. Top 10 important genes
nz_idx <- which(coef_e4 != 0)
# length(nz_idx)
nz_wt_sorted <- sort(coef_e4[nz_idx], decreasing = TRUE, index.return=TRUE)
nz_genes_e4 <- rownames(coef_e4)[nz_idx][nz_wt_sorted$ix[nz_wt_sorted$ix != 1]] #Exclude the 'Intercept' field
# nz_genes_e4[1:10]
#Experiment 6: Choosing value of mixing parameter(alpha) of elasticnet using cross-validation
b <- matrix(NA,51,3)
j=1
i=0
for(i in seq(0,1,by=0.02))
{
cvfit_enet2 = cv.glmnet(x=train_x, y=train_y, nfolds=10, type.measure="class", family="binomial", alpha=i, standardize=TRUE)
b[j,1] <- i
b[j,2] <- cvfit_enet2$lambda.min
b[j,3] <- min(cvfit_enet2$cvm)
j=j+1
}
colnames(b) <- c("alpha","lambda_min","crossval_mean_error")
df_2 <- data.frame(b)
plot(crossval_mean_error ~ alpha,df_2,type="o", col="red", xlab="Alpha", ylab="Crossvalidation Mean Error")
cvm_min <- min(b[,"crossval_mean_error"])
index = which(b[,"crossval_mean_error"]==cvm_min)
alphamin = df_2[index,"alpha"]
# from the plot, the elastic net parameters are alphamin= 0.28
cvfit_enet2 = cv.glmnet(x=train_x, y=train_y, nfolds=10, family="binomial", type.measure="class", alpha=alphamin, standardize=TRUE)
pred_y <- predict(cvfit_enet2, newx=test_x, s="lambda.min", type="class") #Choosing knee-point lambda value
# Deliverables
# 1. Accuracy in terms of error rate
err_per_enet2 <- get_error(pred_y, test_y)
# 2. Graph of cross-validation of lambda and min lambda value
# plot(cvfit_e1)
# cvfit_e1$lambda.min
# 3. Number of non-zero coefficients
coef_e3 <- abs(coef(cvfit_e3, s="lambda.min"))
nz_idx <- which(coef_e3 != 0)
# length(nz_idx)
# plot(cvfit_enet$glmnet.fit$lambda, cvfit_enet$glmnet.fit$df, type="o", col="red", ylab="Number of non-zero coefficients", xlab="Lambda")
# 4. Grouping effect elasticnet
coefe <- as.matrix(scale(coef_enet[-1])) #To remove intercept and scale coefficients
cl <- dbscan::dbscan(coefe, eps=0.30, minPts=5)
stripplot(coefe, col="red", xlab="Grouping of coefficients in Ridge (Logistic)")
# 5. Top 10 important genes
nz_wt_sorted <- sort(coef_e3[nz_idx], decreasing = TRUE, index.return=TRUE)
nz_genes_enet2 <- rownames(coef_e3)[nz_idx][nz_wt_sorted$ix[nz_wt_sorted$ix != 1]] #Exclude the 'Intercept' field
# nz_genes_e3[1:10]
# Identify common genes in important genes found in all models
Reduce(intersect, list(nz_genes_e1, nz_genes_e2, nz_genes_e3[1:50], nz_genes_e4[1:50], nz_genes_enet[1:50], nz_genes_enet2))
| /HDLSS_Cancer/AnalyzeGDS2771_130101084.R | no_license | gokart23/ML | R | false | false | 11,492 | r | #
# EE622: Advanced Machine Learning
# Prof. Amit Sethi
# Assignment 1: HDLSS Lung Cancer Data Analysis
#
# Name: Duddu Sai Meher Karthik
# Roll No. : 130101084
#
#
library(Biobase)
library(GEOquery)
library(glmnet) #for models + regularization
library(mice) #for data imputation
library(lattice) #for 1D cluster visualization
library(dbscan) #for cluster analysis
library(caret) #confusion matrix calculation
library(proc) #ROC/AUC comparison (NOTE: couldn't complete this analysis)
gds2771 <- getGEO(filename='B:/Acad/Course Material/Semester 7/EE622/Assignment1/GDS2771.soft.gz') # Make sure path is correct as per your working folder. Could be './GDS2771.soft.gz'
eset2771 <- GDS2eSet(gds2771) # See http://www2.warwick.ac.uk/fac/sci/moac/people/students/peter_cock/r/geo/
data2771 <- cbind2(c('disease.state',pData(eset2771)$disease.state),t(Table(gds2771)[,2:194]))
colnames(data2771) = data2771[1, ] # the first row will be the header
data2771 = data2771[-1, ]
# WRITE YOUR CODE BELOW THIS LINE
df <- as.data.frame(data2771)
df <- subset(df, df[,1] != "3") # Remove suspected cancer cases from data - 5 in number
df <- as.data.frame(apply(df, 2, function(x) as.numeric(x))) # Convert columns to numeric
#Handling missing data
# Step 1: Eliminate all genes which contain missing values for all samples
df <- df[, colSums(is.na(df)) < nrow(df)]
# Step 2: Impute values for all genes which contain partial missing values (using mean)
# Note: This dataset doesn't require this step, as after step 1, all na values disappear. Method kept for completeness
df <- if (sum(is.na(df)) > 0) mice(df, method = "mean") else df # Final number of genes = 22216
#Dividing dataset into testing and training sets
SPLIT.PERCENTAGE = 0.75 # 75-25 training-to-testing ratio
train.size = floor(nrow(df)*SPLIT.PERCENTAGE)
set.seed(101) #to ensure reproducibility
train.idx <- sample(nrow(df), size = train.size)
train_x <- as.matrix(df[train.idx, -1]) #The training dataset features
train_y <- df[train.idx, 1] #The training dataset annotation vector
test_x <- as.matrix(df[-train.idx, -1]) #The testing dataset features
test_y <- df[-train.idx, 1] #The testing dataset annotation vector
#Error computation function
get_error <- function(pred_y, test_y) {
return (mean(pred_y != test_y))
}
#Experiment 1: Linear regression with Lasso and 10-fold cross-validation (mean-squared error)
#Note: All features normalized (standardized) before training, and rescaled before prediction
cvfit_e1 = cv.glmnet(x=train_x, y=train_y, nfolds=10, family="gaussian", type.measure="mse", alpha=1, standardize=TRUE)
pred_y <- predict(cvfit_e1, newx=test_x, s="lambda.min") #Choosing knee-point lambda value
# Applying thresholding to the predicted values for comparison purposes (threshold - 1.5 for 2-class)
REGRESSION.THRESHOLD = 1.5
pred_y <- lapply(pred_y, function(x) {if (x > REGRESSION.THRESHOLD) 2 else 1} )
# Deliverables
# 1. Accuracy in terms of error rate
err_per1 <- get_error(pred_y, test_y)
# 2. Graph of cross-validation of lambda and min lambda value
# plot(cvfit_e1)
# cvfit_e1$lambda.min
# 3. Number of non-zero coefficients
coef_e1 <- abs(coef(cvfit_e1, s="lambda.min"))
nz_idx <- which(coef_e1 != 0)
# length(nz_idx)
# plot(cvfit_e3$glmnet.fit$lambda, cvfit_e3$glmnet.fit$df, type="o", col="red", ylab="Number of non-zero coefficients", xlab="Lambda")
# 4. Top 10 important genes
nz_wt_sorted <- sort(coef_e1[nz_idx], decreasing = TRUE, index.return=TRUE)
nz_genes_e1 <- rownames(coef_e1)[nz_idx][nz_wt_sorted$ix[nz_wt_sorted$ix != 1]] #Exclude the 'Intercept' field
# nz_genes_e1[1:10]
#Experiment 2: Linear regression with Ridge
#Note: All features normalized (standardized) before training, and rescaled before prediction
cvfit_e2 = cv.glmnet(x=train_x, y=train_y, nfolds=10, type.measure="mse", family="gaussian", alpha=0, standardize=TRUE)
pred_y <- predict(cvfit_e2, newx=test_x, s="lambda.min") #Choosing knee-point lambda value
# Applying thresholding to the predicted values for comparison purposes (threshold - 1.5 for 2-class)
REGRESSION.THRESHOLD = 1.5
pred_y <- lapply(pred_y, function(x) {if (x > REGRESSION.THRESHOLD) 2 else 1} )
# Deliverables
# 1. Accuracy in terms of error rate
err_per2 <- get_error(pred_y, test_y)
# 2. Graph of cross-validation of lambda and min lambda value
# plot(cvfit_e2)
# cvfit_e2$lambda.min
# 3. Grouping effect in ridge
coef_e2 <- abs(coef(cvfit_e2, s="lambda.min"))
coefe <- as.matrix(scale(coef_e2[-1])) #To remove intercept and scale coefficients
cl <- dbscan::dbscan(coefe, eps=0.25, minPts=5)
stripplot(coefe, col="red", xlab="Grouping of coefficients in Ridge (Linear)")
nz_idx <- which(coef_e2 != 0)
# length(nz_idx)
# 4. Top 10 important genes
nz_wt_sorted <- sort(coef_e2[nz_idx], decreasing = TRUE, index.return=TRUE)
nz_genes_e2 <- rownames(coef_e2)[nz_idx][nz_wt_sorted$ix[nz_wt_sorted$ix != 1]] #Exclude the 'Intercept' field
# nz_genes_e2[1:10]
# 5. Cluster Analysis
coefe <- as.matrix(coef_e2[-1])
#Experiment 3: Choosing value of mixing parameter(alpha) of elasticnet using cross-validation
a <- matrix(NA,51,3)
j=1
i=0
for(i in seq(0,1,by=0.02))
{
cvfit_e2 = cv.glmnet(x=train_x, y=train_y, nfolds=10, type.measure="mse", family="gaussian", alpha=i, standardize=TRUE)
a[j,1] <- i
a[j,2] <- cvfit_e2$lambda.min
a[j,3] <- min(cvfit_e2$cvm)
j=j+1
}
colnames(a) <- c("alpha","lambda_min","crossval_mean_error")
df_1 <- data.frame(a)
plot(crossval_mean_error ~ alpha,df_1,type="l")
cvm_min <- min(a[,"crossval_mean_error"])
index = which(a[,"crossval_mean_error"]==cvm_min)
alphamin = df_1[index,"alpha"]
# from the plot, the elastic net parameters are alphamin= 0.04
# applying the elastic net with 10 folds for the alphamin
cvfit_enet = cv.glmnet(x=train_x, y=train_y, nfolds=10, type.measure="mse", family="gaussian", alpha=alphamin, standardize=TRUE)
pred_y <- predict(cvfit_enet, newx=test_x, s="lambda.min") #Choosing knee-point lambda value
# Applying thresholding to the predicted values for comparison purposes (threshold - 1.5 for 2-class)
REGRESSION.THRESHOLD = 1.5
pred_y <- lapply(pred_y, function(x) {if (x > REGRESSION.THRESHOLD) 2 else 1} )
# Deliverables
# 1. Accuracy in terms of error rate
err_per_enet <- get_error(pred_y, test_y)
# 2. Graph of cross-validation of lambda
# plot(cvfit_e2)
# cvfit_e2$lambda.min
# 3. Number of non-zero coefficients
coef_enet <- abs(coef(cvfit_enet, s="lambda.min"))
nz_idx <- which(coef_enet != 0)
# length(nz_idx)
# plot(cvfit_enet$glmnet.fit$lambda, cvfit_enet$glmnet.fit$df, type="o", col="red", ylab="Number of non-zero coefficients", xlab="Lambda")
# 4. Grouping effect elasticnet
coefe <- as.matrix(scale(coef_enet[-1])) #To remove intercept and scale coefficients
cl <- dbscan::dbscan(coefe, eps=0.30, minPts=5)
stripplot(coefe, col="red", xlab="Grouping of coefficients in Ridge (Linear)")
# 5. Top 10 important genes
nz_wt_sorted <- sort(coef_enet[nz_idx], decreasing = TRUE, index.return=TRUE)
nz_genes_enet <- rownames(coef_enet)[nz_idx][nz_wt_sorted$ix[nz_wt_sorted$ix != 1]] #Exclude the 'Intercept' field
# nz_genes_enet[1:10]
#Experiment 4: Logistic regression with Lasso
#Note: All features normalized (standardized) before training, and rescaled before prediction
cvfit_e3 = cv.glmnet(x=train_x, y=train_y, nfolds=10, family="binomial", type.measure="class", alpha=1, standardize=TRUE)
pred_y <- predict(cvfit_e3, newx=test_x, s="lambda.min", type="class") #Choosing knee-point lambda value
# Deliverables
# 1. Accuracy in terms of error rate
err_per3 <- get_error(pred_y, test_y)
# 2. Graph of cross-validation of lambda and min lambda value
# plot(cvfit_e3)
# cvfit_e3$lambda.min
# 3. Variation in non-zero coefficients
coef_e3 <- abs(coef(cvfit_e3, s="lambda.min"))
nz_idx <- which(coef_e3 != 0)
# length(nz_idx)
# plot(cvfit_e3$glmnet.fit$lambda, cvfit_e3$glmnet.fit$df, type="o", col="red", ylab="Number of non-zero coefficients", xlab="Lambda")
# 4. Top 10 important genes
nz_wt_sorted <- sort(coef_e3[nz_idx], decreasing = TRUE, index.return=TRUE)
nz_genes_e3 <- rownames(coef_e3)[nz_idx][nz_wt_sorted$ix[nz_wt_sorted$ix != 1]] #Exclude the 'Intercept' field
# nz_genes_e3[1:10]
#Experiment 5: Logistic regression with Ridge
#Note: All features normalized (standardized) before training, and rescaled before prediction
cvfit_e4 = cv.glmnet(x=train_x, y=train_y, nfolds=10, family="binomial", type.measure="class", alpha=0, standardize=TRUE)
pred_y <- predict(cvfit_e4, newx=test_x, s="lambda.min", type="class") #Choosing knee-point lambda value
# Deliverables
# 1. Accuracy in terms of error rate
err_per4 <- get_error(pred_y, test_y)
# 2. Graph of cross-validation of lambda and min lambda value
# plot(cvfit_e4)
# cvfit_e4$lambda.min
# 3. Grouping effect in ridge
coef_e4 <- abs(coef(cvfit_e4, s="lambda.min"))
coefe <- as.matrix(scale(coef_e4[-1])) #To remove intercept and scale coefficients
cl <- dbscan::dbscan(coefe, eps=0.25, minPts=5)
stripplot(coefe)
# 4. Top 10 important genes
nz_idx <- which(coef_e4 != 0)
# length(nz_idx)
nz_wt_sorted <- sort(coef_e4[nz_idx], decreasing = TRUE, index.return=TRUE)
nz_genes_e4 <- rownames(coef_e4)[nz_idx][nz_wt_sorted$ix[nz_wt_sorted$ix != 1]] #Exclude the 'Intercept' field
# nz_genes_e4[1:10]
#Experiment 6: Choosing value of mixing parameter(alpha) of elasticnet using cross-validation
b <- matrix(NA,51,3)
j=1
i=0
for(i in seq(0,1,by=0.02))
{
cvfit_enet2 = cv.glmnet(x=train_x, y=train_y, nfolds=10, type.measure="class", family="binomial", alpha=i, standardize=TRUE)
b[j,1] <- i
b[j,2] <- cvfit_enet2$lambda.min
b[j,3] <- min(cvfit_enet2$cvm)
j=j+1
}
colnames(b) <- c("alpha","lambda_min","crossval_mean_error")
df_2 <- data.frame(b)
plot(crossval_mean_error ~ alpha,df_2,type="o", col="red", xlab="Alpha", ylab="Crossvalidation Mean Error")
cvm_min <- min(b[,"crossval_mean_error"])
index = which(b[,"crossval_mean_error"]==cvm_min)
alphamin = df_2[index,"alpha"]
# from the plot, the elastic net parameters are alphamin= 0.28
cvfit_enet2 = cv.glmnet(x=train_x, y=train_y, nfolds=10, family="binomial", type.measure="class", alpha=alphamin, standardize=TRUE)
pred_y <- predict(cvfit_enet2, newx=test_x, s="lambda.min", type="class") #Choosing knee-point lambda value
# Deliverables
# 1. Accuracy in terms of error rate
err_per_enet2 <- get_error(pred_y, test_y)
# 2. Graph of cross-validation of lambda and min lambda value
# plot(cvfit_e1)
# cvfit_e1$lambda.min
# 3. Number of non-zero coefficients
coef_e3 <- abs(coef(cvfit_e3, s="lambda.min"))
nz_idx <- which(coef_e3 != 0)
# length(nz_idx)
# plot(cvfit_enet$glmnet.fit$lambda, cvfit_enet$glmnet.fit$df, type="o", col="red", ylab="Number of non-zero coefficients", xlab="Lambda")
# 4. Grouping effect elasticnet
coefe <- as.matrix(scale(coef_enet[-1])) #To remove intercept and scale coefficients
cl <- dbscan::dbscan(coefe, eps=0.30, minPts=5)
stripplot(coefe, col="red", xlab="Grouping of coefficients in Ridge (Logistic)")
# 5. Top 10 important genes
nz_wt_sorted <- sort(coef_e3[nz_idx], decreasing = TRUE, index.return=TRUE)
nz_genes_enet2 <- rownames(coef_e3)[nz_idx][nz_wt_sorted$ix[nz_wt_sorted$ix != 1]] #Exclude the 'Intercept' field
# nz_genes_e3[1:10]
# Identify common genes in important genes found in all models
Reduce(intersect, list(nz_genes_e1, nz_genes_e2, nz_genes_e3[1:50], nz_genes_e4[1:50], nz_genes_enet[1:50], nz_genes_enet2))
|
c DCNF-Autarky [version 0.0.1].
c Copyright (c) 2018-2019 Swansea University.
c
c Input Clause Count: 5829
c Performing E1-Autarky iteration.
c Remaining clauses count after E-Reduction: 5829
c
c Input Parameter (command line, file):
c input filename QBFLIB/Letombe/Abduction/par16-5-c-50.qdimacs
c output filename /tmp/dcnfAutarky.dimacs
c autarky level 1
c conformity level 0
c encoding type 2
c no.of var 2382
c no.of clauses 5829
c no.of taut cls 0
c
c Output Parameters:
c remaining no.of clauses 5829
c
c QBFLIB/Letombe/Abduction/par16-5-c-50.qdimacs 2382 5829 E1 [] 0 341 2041 5829 NONE
| /code/dcnf-ankit-optimized/Results/QBFLIB-2018/E1/Experiments/Letombe/Abduction/par16-5-c-50/par16-5-c-50.R | no_license | arey0pushpa/dcnf-autarky | R | false | false | 622 | r | c DCNF-Autarky [version 0.0.1].
c Copyright (c) 2018-2019 Swansea University.
c
c Input Clause Count: 5829
c Performing E1-Autarky iteration.
c Remaining clauses count after E-Reduction: 5829
c
c Input Parameter (command line, file):
c input filename QBFLIB/Letombe/Abduction/par16-5-c-50.qdimacs
c output filename /tmp/dcnfAutarky.dimacs
c autarky level 1
c conformity level 0
c encoding type 2
c no.of var 2382
c no.of clauses 5829
c no.of taut cls 0
c
c Output Parameters:
c remaining no.of clauses 5829
c
c QBFLIB/Letombe/Abduction/par16-5-c-50.qdimacs 2382 5829 E1 [] 0 341 2041 5829 NONE
|
\name{SoilWeb_spatial_query}
\alias{SoilWeb_spatial_query}
\title{Get SSURGO Data via Spatial Query}
\description{Get SSURGO Data via Spatial Query to SoilWeb}
\usage{
SoilWeb_spatial_query(bbox = NULL, coords = NULL, what = "mapunit", source = "soilweb")
}
\arguments{
\item{bbox}{a bounding box in WGS84 geographic coordinates, see examples}
\item{coords}{a coordinate pair in WGS84 geographic coordinates, see examples}
\item{what}{data to query, currently ignored}
\item{source}{the data source, currently ignored}
}
\note{This function should be considered experimental; arguments, results, and side-effects could change at any time. SDA now supports spatial queries, consider using \code{\link{SDA_query_features}} instead.}
\details{Data are currently available from SoilWeb. These data are a snapshot of the "official" data. The snapshot date is encoded in the "soilweb_last_update" column in the function return value. Planned updates to this function will include a switch to determine the data source: "official" data via USDA-NRCS servers, or a "snapshot" via SoilWeb.}
\value{The data returned from this function will depend on the query style. See examples below.}
\author{D.E. Beaudette}
\examples{
# query by bbox
\dontrun{SoilWeb_spatial_query(bbox=c(-122.05, 37, -122, 37.05))}
# query by coordinate pair
\dontrun{SoilWeb_spatial_query(coords=c(-121, 38))}
}
\keyword{manip}
| /man/SSURGO_spatial_query.Rd | no_license | bocinsky/soilDB | R | false | false | 1,447 | rd | \name{SoilWeb_spatial_query}
\alias{SoilWeb_spatial_query}
\title{Get SSURGO Data via Spatial Query}
\description{Get SSURGO Data via Spatial Query to SoilWeb}
\usage{
SoilWeb_spatial_query(bbox = NULL, coords = NULL, what = "mapunit", source = "soilweb")
}
\arguments{
\item{bbox}{a bounding box in WGS84 geographic coordinates, see examples}
\item{coords}{a coordinate pair in WGS84 geographic coordinates, see examples}
\item{what}{data to query, currently ignored}
\item{source}{the data source, currently ignored}
}
\note{This function should be considered experimental; arguments, results, and side-effects could change at any time. SDA now supports spatial queries, consider using \code{\link{SDA_query_features}} instead.}
\details{Data are currently available from SoilWeb. These data are a snapshot of the "official" data. The snapshot date is encoded in the "soilweb_last_update" column in the function return value. Planned updates to this function will include a switch to determine the data source: "official" data via USDA-NRCS servers, or a "snapshot" via SoilWeb.}
\value{The data returned from this function will depend on the query style. See examples below.}
\author{D.E. Beaudette}
\examples{
# query by bbox
\dontrun{SoilWeb_spatial_query(bbox=c(-122.05, 37, -122, 37.05))}
# query by coordinate pair
\dontrun{SoilWeb_spatial_query(coords=c(-121, 38))}
}
\keyword{manip}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/twitter.senator.R
\docType{data}
\name{twitter.senator}
\alias{twitter.senator}
\title{Senator Information Data}
\format{A data frame with 91 rows and 4 variables:
\describe{
\item{ screen_name }{ character: Twitter screen name }
\item{ name }{ character: name of senator }
\item{ party }{ character: party (D = Democrat, R = Republican, I = Independent) }
\item{ state }{ character: state abbreviation }
}}
\usage{
twitter.senator
}
\description{
Contains information about each US Senator in the Twitter network analysis from
\emph{QSS} Section 5.2.3.
}
\details{
See \emph{QSS} Table 5.4.
}
\references{
\itemize{
\item{ Imai, Kosuke. 2017. \emph{Quantitative Social Science: An Introduction}.
Princeton University Press. \href{http://press.princeton.edu/titles/11025.html}{URL}. }
\item {Pablo Barberá; Birds of the Same Feather Tweet Together:
Bayesian Ideal Point Estimation Using Twitter Data. \emph{Political Analysis} 2015;
23 (1): 76-91. doi: 10.1093/pan/mpu011 }
}
}
\keyword{datasets}
| /man/twitter.senator.Rd | no_license | sugano-nu/qss-package | R | false | true | 1,080 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/twitter.senator.R
\docType{data}
\name{twitter.senator}
\alias{twitter.senator}
\title{Senator Information Data}
\format{A data frame with 91 rows and 4 variables:
\describe{
\item{ screen_name }{ character: Twitter screen name }
\item{ name }{ character: name of senator }
\item{ party }{ character: party (D = Democrat, R = Republican, I = Independent) }
\item{ state }{ character: state abbreviation }
}}
\usage{
twitter.senator
}
\description{
Contains information about each US Senator in the Twitter network analysis from
\emph{QSS} Section 5.2.3.
}
\details{
See \emph{QSS} Table 5.4.
}
\references{
\itemize{
\item{ Imai, Kosuke. 2017. \emph{Quantitative Social Science: An Introduction}.
Princeton University Press. \href{http://press.princeton.edu/titles/11025.html}{URL}. }
\item {Pablo Barberá; Birds of the Same Feather Tweet Together:
Bayesian Ideal Point Estimation Using Twitter Data. \emph{Political Analysis} 2015;
23 (1): 76-91. doi: 10.1093/pan/mpu011 }
}
}
\keyword{datasets}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/unstructured_interpolation.R
\name{triangular_interpolation}
\alias{triangular_interpolation}
\title{Function for various types of triangular ['linear'] interpolation of unstructured data.}
\usage{
triangular_interpolation(xy, vals, newPts, useNearestNeighbour = TRUE)
}
\arguments{
\item{xy}{= point locations associated with the values to interpolate from (typically nx2 matrix)}
\item{vals}{= values at xy (can be a matix with 1 or more colums and the same number of rows as xy)}
\item{newPts}{= points where we want interpolated values (typically mx2 matrix)}
\item{useNearestNeighbour}{= TRUE/FALSE (effect described above)}
}
\value{
matrix/vector with as many columns as 'vals' and as many rows as 'newPts', containing the 'vals' interpolated to 'newPts'
}
\description{
Delanay triangulation is supported, as well as a method based on linear interpolation
from the 3 nearest neighbour of the interpolation point, with limiting. \cr
If useNearestNeighbour = FALSE then it provides a wrapper around the delanay triangulation used in the 'geometry' package.
Unfortunately the look-up can be slow with this method for large point clouds. \cr
If useNearestNeighbour=TRUE, we find the 3 nearest xy neighbours of each point to interpolate to, and
interpolate using the plane defined by those 3 neighbours. Limiting is used
to ensure the interpolated value does not exceed the range of the xy
neighbours. This method is fast since it relies only an a fast nearest neighbours implementation (via FNN)
}
\examples{
# Make a single triangle in the plane z=x+y, and interpolate from it
xy = matrix(c(0, 0, 0, 1, 1, 1), ncol=2, byrow=TRUE)
vals = c(0, 1, 2) # z=x+y
newPts = matrix(c(0.5, 0.5, 0.3, 0.3), ncol=2, byrow=TRUE)
out = triangular_interpolation(xy, vals, newPts)
stopifnot(all.equal(out, c(1.0,0.6)))
# Re-order triangle
xy = xy[3:1,]
vals = vals[3:1]
out = triangular_interpolation(xy, vals, newPts)
stopifnot(all.equal(out,c(1.0,0.6)))
#another one, with formula z=0.5*x+0.2*y+7
xy = matrix(c(-1, -1, 1, -0.5, 0.5, 1), ncol=2,byrow=2)
vals = 0.5*xy[,1]+0.2*xy[,2]+7
newPts = matrix(c(0,0, 0.5, 0.3),ncol=2,byrow=TRUE)
expectedVals = 0.5*newPts[,1]+0.2*newPts[,2]+7
out = triangular_interpolation(xy,vals,newPts)
stopifnot(all.equal(out,expectedVals))
# A point outside the triangle
newPts = matrix(c(-1,0, -1, 1), ncol=2, byrow=TRUE)
out = triangular_interpolation(xy, vals, newPts, useNearestNeighbour=FALSE)
stopifnot(all(is.na(out)))
# Failure is expected here if using approximate triangulation based on nearest neighbour methods
# A single point
newPts = matrix(c(0,0), ncol=2)
out = triangular_interpolation(xy, vals, newPts)
stopifnot(out == 7)
# Points on the triangle
newPts = xy
out = triangular_interpolation(xy, vals, newPts)
stopifnot(all(out == vals))
# Point on an edge
newPts = matrix(0.5*(xy[1,]+xy[2,]), ncol=2)
out = triangular_interpolation(xy, vals, newPts)
stopifnot(all(out == 0.5*(vals[1]+vals[2])))
}
| /R/rptha/man/triangular_interpolation.Rd | permissive | GeoscienceAustralia/ptha | R | false | true | 3,130 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/unstructured_interpolation.R
\name{triangular_interpolation}
\alias{triangular_interpolation}
\title{Function for various types of triangular ['linear'] interpolation of unstructured data.}
\usage{
triangular_interpolation(xy, vals, newPts, useNearestNeighbour = TRUE)
}
\arguments{
\item{xy}{= point locations associated with the values to interpolate from (typically nx2 matrix)}
\item{vals}{= values at xy (can be a matix with 1 or more colums and the same number of rows as xy)}
\item{newPts}{= points where we want interpolated values (typically mx2 matrix)}
\item{useNearestNeighbour}{= TRUE/FALSE (effect described above)}
}
\value{
matrix/vector with as many columns as 'vals' and as many rows as 'newPts', containing the 'vals' interpolated to 'newPts'
}
\description{
Delanay triangulation is supported, as well as a method based on linear interpolation
from the 3 nearest neighbour of the interpolation point, with limiting. \cr
If useNearestNeighbour = FALSE then it provides a wrapper around the delanay triangulation used in the 'geometry' package.
Unfortunately the look-up can be slow with this method for large point clouds. \cr
If useNearestNeighbour=TRUE, we find the 3 nearest xy neighbours of each point to interpolate to, and
interpolate using the plane defined by those 3 neighbours. Limiting is used
to ensure the interpolated value does not exceed the range of the xy
neighbours. This method is fast since it relies only an a fast nearest neighbours implementation (via FNN)
}
\examples{
# Make a single triangle in the plane z=x+y, and interpolate from it
xy = matrix(c(0, 0, 0, 1, 1, 1), ncol=2, byrow=TRUE)
vals = c(0, 1, 2) # z=x+y
newPts = matrix(c(0.5, 0.5, 0.3, 0.3), ncol=2, byrow=TRUE)
out = triangular_interpolation(xy, vals, newPts)
stopifnot(all.equal(out, c(1.0,0.6)))
# Re-order triangle
xy = xy[3:1,]
vals = vals[3:1]
out = triangular_interpolation(xy, vals, newPts)
stopifnot(all.equal(out,c(1.0,0.6)))
#another one, with formula z=0.5*x+0.2*y+7
xy = matrix(c(-1, -1, 1, -0.5, 0.5, 1), ncol=2,byrow=2)
vals = 0.5*xy[,1]+0.2*xy[,2]+7
newPts = matrix(c(0,0, 0.5, 0.3),ncol=2,byrow=TRUE)
expectedVals = 0.5*newPts[,1]+0.2*newPts[,2]+7
out = triangular_interpolation(xy,vals,newPts)
stopifnot(all.equal(out,expectedVals))
# A point outside the triangle
newPts = matrix(c(-1,0, -1, 1), ncol=2, byrow=TRUE)
out = triangular_interpolation(xy, vals, newPts, useNearestNeighbour=FALSE)
stopifnot(all(is.na(out)))
# Failure is expected here if using approximate triangulation based on nearest neighbour methods
# A single point
newPts = matrix(c(0,0), ncol=2)
out = triangular_interpolation(xy, vals, newPts)
stopifnot(out == 7)
# Points on the triangle
newPts = xy
out = triangular_interpolation(xy, vals, newPts)
stopifnot(all(out == vals))
# Point on an edge
newPts = matrix(0.5*(xy[1,]+xy[2,]), ncol=2)
out = triangular_interpolation(xy, vals, newPts)
stopifnot(all(out == 0.5*(vals[1]+vals[2])))
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/util.R
\name{select}
\alias{select}
\title{Very simple select for mbtools artifacts. Just gets a particular entry.}
\usage{
select(object, entry)
}
\arguments{
\item{object}{A mbtools artifact returned from a workflow step.}
\item{entry}{The name of the entry to get.}
}
\value{
The requested entry.
}
\description{
Very simple select for mbtools artifacts. Just gets a particular entry.
}
| /man/select.Rd | permissive | Gibbons-Lab/mbtools | R | false | true | 469 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/util.R
\name{select}
\alias{select}
\title{Very simple select for mbtools artifacts. Just gets a particular entry.}
\usage{
select(object, entry)
}
\arguments{
\item{object}{A mbtools artifact returned from a workflow step.}
\item{entry}{The name of the entry to get.}
}
\value{
The requested entry.
}
\description{
Very simple select for mbtools artifacts. Just gets a particular entry.
}
|
# Folling R:
mgm <- NULL
mgmfit <- NULL
# Null function:
null <- function(...) NULL
### IsingFit ###
# prep fun (make binary if needed):
binarize <- function(x, split = "median", na.rm=TRUE, removeNArows = TRUE, verbose = TRUE){
x <- as.data.frame(x)
if (all(unlist(x) %in% c(0,1))){
return(x)
} else {
if (is.function(split)){
splitName <- deparse(substitute(split))
} else {
splitName <- split
}
if (verbose){
warning(paste("Splitting data by",splitName))
}
if (is.character(split) || is.function(split)){
splits <- sapply(x,split,na.rm=na.rm)
} else {
splits <- rep(split, length=ncol(x))
}
for (i in seq_len(ncol(x))){
x[,i] <- 1 * (x[,i] < splits[i])
}
if (removeNArows){
x <- x[apply(x,1,function(xx)all(!is.na(xx))),,drop=FALSE]
}
return(x)
}
}
### ARGUMENT ESTIMATOR ###
# Construct the estimator:
bootnet_argEstimator <- function(data, prepFun, prepArgs, estFun, estArgs, graphFun, graphArgs, intFun, intArgs, verbose = TRUE){
# prepArgs$verbose <- verbose
if ("verbose" %in% names(formals(prepFun))){
prepArgs$verbose <- verbose
}
# Compute input:
input <- do.call(prepFun, c(list(data), prepArgs))
# Compute network:
res <- do.call(estFun, c(list(input),estArgs))
# Extract network:
sampleGraph <- do.call(graphFun,c(list(res), graphArgs))
# Extract graph:
intercepts <- do.call(intFun,c(list(res), intArgs))
# Return:
return(list(graph=sampleGraph, intercepts = intercepts))
}
### EBIC GLASSO ESTIMATOR ###
bootnet_EBICglasso <- function(
data, # Dataset used
tuning = 0.5, # tuning parameter
corMethod = c("cor_auto","cov","cor","npn"), # Correlation method
missing = c("pairwise","listwise","fiml","stop"),
sampleSize = c("maximum","minimim"), # Sample size when using missing = "pairwise"
verbose = TRUE,
corArgs = list(), # Extra arguments to the correlation function
refit = FALSE,
...
){
# Check arguments:
corMethod <- match.arg(corMethod)
missing <- match.arg(missing)
sampleSize <- match.arg(sampleSize)
# Message:
if (verbose){
msg <- "Estimating Network. Using package::function:"
msg <- paste0(msg,"\n - qgraph::EBICglasso for EBIC model selection\n - using glasso::glasso")
if (corMethod == "cor_auto"){
msg <- paste0(msg,"\n - qgraph::cor_auto for correlation computation\n - using lavaan::lavCor")
}
if (corMethod == "npn"){
msg <- paste0(msg,"\n - huge::huge.npn for nonparanormal transformation")
}
# msg <- paste0(msg,"\n\nPlease reference accordingly\n")
message(msg)
}
# First test if data is a data frame:
if (!(is.data.frame(data) || is.matrix(data))){
stop("'data' argument must be a data frame")
}
# If matrix coerce to data frame:
if (is.matrix(data)){
data <- as.data.frame(data)
}
# Obtain info from data:
N <- ncol(data)
Np <- nrow(data)
# Check missing:
if (missing == "stop"){
if (any(is.na(data))){
stop("Missing data detected and missing = 'stop'")
}
}
# Correlate data:
# npn:
if (corMethod == "npn"){
data <- huge::huge.npn(data)
corMethod <- "cor"
}
# cor_auto:
if (corMethod == "cor_auto"){
args <- list(data=data,missing=missing,verbose=verbose)
if (length(corArgs) > 0){
for (i in seq_along(corArgs)){
args[[names(corArgs)[[i]]]] <- corArgs[[i]]
}
}
corMat <- do.call(qgraph::cor_auto,args)
} else if (corMethod%in%c("cor","cov")){
# Normal correlations
if (missing == "fiml"){
stop("missing = 'fiml' only supported with corMethod = 'cor_auto'")
}
use <- switch(missing,
pairwise = "pairwise.complete.obs",
listwise = "complete.obs")
args <- list(x=data,use=use)
if (length(corArgs) > 0){
for (i in seq_along(corArgs)){
args[[names(corArgs)[[i]]]] <- corArgs[[i]]
}
}
corMat <- do.call(corMethod,args)
} else stop ("Correlation method is not supported.")
# Sample size:
if (missing == "listwise"){
sampleSize <- nrow(na.omit(data))
} else{
if (sampleSize == "maximum"){
sampleSize <- sum(apply(data,1,function(x)!all(is.na(x))))
} else {
sampleSize <- sum(apply(data,1,function(x)!any(is.na(x))))
}
}
# Estimate network:
Results <- qgraph::EBICglasso(corMat,
n = sampleSize,
gamma = tuning,
returnAllResults = TRUE,
refit = refit,
...)
# Return:
return(list(graph=Results$optnet,results=Results))
}
### PCOR ESTIMATOR ###
bootnet_pcor <- function(
data, # Dataset used
corMethod = c("cor_auto","cov","cor","npn"), # Correlation method
missing = c("pairwise","listwise","fiml","stop"),
sampleSize = c("maximum","minimim"), # Sample size when using missing = "pairwise"
verbose = TRUE,
corArgs = list(), # Extra arguments to the correlation function
threshold = 0
){
# Check arguments:
corMethod <- match.arg(corMethod)
missing <- match.arg(missing)
sampleSize <- match.arg(sampleSize)
if (identical(threshold,"none")){
threshold <- 0
}
# Message:
if (verbose){
msg <- "Estimating Network. Using package::function:"
msg <- paste0(msg,"\n - qgraph::qgraph(..., graph = 'pcor') for network computation")
if (corMethod == "cor_auto"){
msg <- paste0(msg,"\n - qgraph::cor_auto for correlation computation\n - using lavaan::lavCor")
}
if (corMethod == "npn"){
msg <- paste0(msg,"\n - huge::huge.npn for nonparanormal transformation")
}
if (threshold != "none"){
if (threshold != "locfdr"){
msg <- paste0(msg,"\n - psych::corr.p for significance thresholding")
} else {
msg <- paste0(msg,"\n - fdrtool for false discovery rate")
}
}
# msg <- paste0(msg,"\n\nPlease reference accordingly\n")
message(msg)
}
# First test if data is a data frame:
if (!(is.data.frame(data) || is.matrix(data))){
stop("'data' argument must be a data frame")
}
# If matrix coerce to data frame:
if (is.matrix(data)){
data <- as.data.frame(data)
}
# Obtain info from data:
N <- ncol(data)
Np <- nrow(data)
# Check missing:
if (missing == "stop"){
if (any(is.na(data))){
stop("Missing data detected and missing = 'stop'")
}
}
# Correlate data:
# npn:
if (corMethod == "npn"){
data <- huge::huge.npn(data)
corMethod <- "cor"
}
# cor_auto:
if (corMethod == "cor_auto"){
args <- list(data=data,missing=missing,verbose=verbose)
if (length(corArgs) > 0){
for (i in seq_along(corArgs)){
args[[names(corArgs)[[i]]]] <- corArgs[[i]]
}
}
corMat <- do.call(qgraph::cor_auto,args)
} else if (corMethod%in%c("cor","cov")){
# Normal correlations
if (missing == "fiml"){
stop("missing = 'fiml' only supported with corMethod = 'cor_auto'")
}
use <- switch(missing,
pairwise = "pairwise.complete.obs",
listwise = "complete.obs")
args <- list(x=data,use=use)
if (length(corArgs) > 0){
for (i in seq_along(corArgs)){
args[[names(corArgs)[[i]]]] <- corArgs[[i]]
}
}
corMat <- do.call(corMethod,args)
} else stop ("Correlation method is not supported.")
# Sample size:
if (missing == "listwise"){
sampleSize <- nrow(na.omit(data))
} else{
if (sampleSize == "maximum"){
sampleSize <- sum(apply(data,1,function(x)!all(is.na(x))))
} else {
sampleSize <- sum(apply(data,1,function(x)!any(is.na(x))))
}
}
# Estimate network:
Results <- getWmat(qgraph::qgraph(corMat,graph = "pcor",DoNotPlot = TRUE,threshold=threshold, sampleSize = sampleSize))
# Return:
return(list(graph=Results,results=Results))
}
### COR ESTIMATOR ###
bootnet_cor <- function(
data, # Dataset used
corMethod = c("cor_auto","cov","cor","npn"), # Correlation method
missing = c("pairwise","listwise","fiml","stop"),
sampleSize = c("maximum","minimim"), # Sample size when using missing = "pairwise"
verbose = TRUE,
corArgs = list(), # Extra arguments to the correlation function
threshold = 0
){
# Check arguments:
corMethod <- match.arg(corMethod)
missing <- match.arg(missing)
sampleSize <- match.arg(sampleSize)
if (identical(threshold,"none")){
threshold <- 0
}
# Message:
if (verbose){
msg <- "Estimating Network. Using package::function:"
# msg <- paste0(msg,"\n - qgraph::qgraph(..., graph = 'cor') for network computation")
if (corMethod == "cor_auto"){
msg <- paste0(msg,"\n - qgraph::cor_auto for correlation computation\n - using lavaan::lavCor")
}
if (corMethod == "npn"){
msg <- paste0(msg,"\n - huge::huge.npn for nonparanormal transformation")
}
if (threshold != "none"){
if (threshold != "locfdr"){
msg <- paste0(msg,"\n - psych::corr.p for significance thresholding")
} else {
msg <- paste0(msg,"\n - fdrtool for false discovery rate")
}
}
# msg <- paste0(msg,"\n\nPlease reference accordingly\n")
message(msg)
}
# First test if data is a data frame:
if (!(is.data.frame(data) || is.matrix(data))){
stop("'data' argument must be a data frame")
}
# If matrix coerce to data frame:
if (is.matrix(data)){
data <- as.data.frame(data)
}
# Obtain info from data:
N <- ncol(data)
Np <- nrow(data)
# Check missing:
if (missing == "stop"){
if (any(is.na(data))){
stop("Missing data detected and missing = 'stop'")
}
}
# Correlate data:
# npn:
if (corMethod == "npn"){
data <- huge::huge.npn(data)
corMethod <- "cor"
}
# cor_auto:
if (corMethod == "cor_auto"){
args <- list(data=data,missing=missing,verbose=verbose)
if (length(corArgs) > 0){
for (i in seq_along(corArgs)){
args[[names(corArgs)[[i]]]] <- corArgs[[i]]
}
}
corMat <- do.call(qgraph::cor_auto,args)
} else if (corMethod%in%c("cor","cov")){
# Normal correlations
if (missing == "fiml"){
stop("missing = 'fiml' only supported with corMethod = 'cor_auto'")
}
use <- switch(missing,
pairwise = "pairwise.complete.obs",
listwise = "complete.obs")
args <- list(x=data,use=use)
if (length(corArgs) > 0){
for (i in seq_along(corArgs)){
args[[names(corArgs)[[i]]]] <- corArgs[[i]]
}
}
corMat <- do.call(corMethod,args)
} else stop ("Correlation method is not supported.")
# Sample size:
if (missing == "listwise"){
sampleSize <- nrow(na.omit(data))
} else{
if (sampleSize == "maximum"){
sampleSize <- sum(apply(data,1,function(x)!all(is.na(x))))
} else {
sampleSize <- sum(apply(data,1,function(x)!any(is.na(x))))
}
}
# Estimate network:
Results <- getWmat(qgraph::qgraph(corMat,graph = "cor",DoNotPlot = TRUE,threshold=threshold, sampleSize = sampleSize))
# Return:
return(list(graph=Results,results=Results))
}
### ISINGFIT ESTIMATOR ###
bootnet_IsingFit <- function(
data, # Dataset used
tuning = 0.25, # tuning parameter
missing = c("listwise","stop"),
verbose = TRUE,
rule = c("AND","OR"),
split = "median"
){
# Check arguments:
missing <- match.arg(missing)
rule <- match.arg(rule)
# Message:
if (verbose){
msg <- "Estimating Network. Using package::function:"
msg <- paste0(msg,"\n - IsingFit::IsingFit for network computation\n - Using glmnet::glmnet")
# msg <- paste0(msg,"\n\nPlease reference accordingly\n")
message(msg)
}
# First test if data is a data frame:
if (!(is.data.frame(data) || is.matrix(data))){
stop("'data' argument must be a data frame")
}
# If matrix coerce to data frame:
if (is.matrix(data)){
data <- as.data.frame(data)
}
# Check missing:
if (missing == "stop"){
if (any(is.na(data))){
stop("Missing data detected and missing = 'stop'")
}
} else {
# listwise:
data <- na.omit(data)
}
# Obtain info from data:
N <- ncol(data)
Np <- nrow(data)
# Binarize:
if (!all(data %in% c(0,1))){
data <- bootnet::binarize(data, split = split, verbose = verbose)
}
# Estimate network:
Results <- IsingFit::IsingFit(data, AND = rule == "AND", gamma = tuning,progressbar = verbose,plot = FALSE)
# Return:
return(list(graph = Results$weiadj, intercepts = Results$thresholds,
results = Results))
}
### ISINGSAMPLER ESTIMATOR ###
bootnet_IsingSampler <- function(
data, # Dataset used
missing = c("listwise","stop"),
verbose = TRUE,
split = "median",
method = c("default","ll","pl","uni","bi")
){
# Check arguments:
missing <- match.arg(missing)
method <- match.arg(method)
# Message:
if (verbose){
msg <- "Estimating Network. Using package::function:"
msg <- paste0(msg,"\n - IsingSampler::EstimateIsing for network computation")
# msg <- paste0(msg,"\n\nPlease reference accordingly\n")
message(msg)
}
# First test if data is a data frame:
if (!(is.data.frame(data) || is.matrix(data))){
stop("'data' argument must be a data frame")
}
# If matrix coerce to data frame:
if (is.matrix(data)){
data <- as.data.frame(data)
}
if (method == "default"){
if (ncol(data) > 20){
method <- "uni"
if (verbose){
message("'method' set to 'uni'")
}
} else {
method <- "ll"
if (verbose){
message("'method' set to 'll'")
}
}
}
# Check missing:
if (missing == "stop"){
if (any(is.na(data))){
stop("Missing data detected and missing = 'stop'")
}
} else {
# listwise:
data <- na.omit(data)
}
# Obtain info from data:
N <- ncol(data)
Np <- nrow(data)
# Binarize:
if (!all(data %in% c(0,1))){
data <- bootnet::binarize(data, split = split, verbose = verbose)
}
# Estimate network:
Results <- IsingSampler::EstimateIsing(as.matrix(data), method = method)
# Return:
return(list(graph = Results$graph, intercepts = Results$thresholds,
results = Results))
}
### PCOR ESTIMATOR ###
bootnet_adalasso <- function(
data, # Dataset used
missing = c("listwise","stop"),
verbose = TRUE,
nFolds = 10 # Number of folds
){
# Check arguments:
missing <- match.arg(missing)
# Message:
if (verbose){
msg <- "Estimating Network. Using package::function:"
msg <- paste0(msg,"\n - parcor::adalasso.net for network computation")
# msg <- paste0(msg,"\n\nPlease reference accordingly\n")
message(msg)
}
# First test if data is a data frame:
if (!(is.data.frame(data) || is.matrix(data))){
stop("'data' argument must be a data frame")
}
# If matrix coerce to data frame:
if (is.matrix(data)){
data <- as.data.frame(data)
}
# Obtain info from data:
N <- ncol(data)
Np <- nrow(data)
# Check missing:
if (missing == "stop"){
if (any(is.na(data))){
stop("Missing data detected and missing = 'stop'")
}
} else {
# listwise:
data <- na.omit(data)
}
# Estimate network:
Results <- parcor::adalasso.net(data, k = nFolds)
# Return:
return(list(graph=as.matrix(Matrix::forceSymmetric(Results$pcor.adalasso)),results=Results))
}
### HUGE ESTIMATOR ###
bootnet_huge <- function(
data, # Dataset used
tuning = 0.5,
missing = c("listwise","stop"),
verbose = TRUE,
npn = TRUE, # Compute nonparanormal?
criterion = c("ebic","ric","stars")
# method = c("glasso","mb","ct")
){
# Check arguments:
missing <- match.arg(missing)
criterion <- match.arg(criterion)
# method <- match.arg(method)
# Message:
if (verbose){
msg <- "Estimating Network. Using package::function:"
msg <- paste0(msg,"\n - huge::huge for network computation")
msg <- paste0(msg,"\n - huge::huge.npn for nonparanormal transformation")
# msg <- paste0(msg,"\n\nPlease reference accordingly\n")
message(msg)
}
# First test if data is a data frame:
if (!(is.data.frame(data) || is.matrix(data))){
stop("'data' argument must be a data frame")
}
# If matrix coerce to data frame:
if (is.matrix(data)){
data <- as.data.frame(data)
}
# Obtain info from data:
N <- ncol(data)
Np <- nrow(data)
# Check missing:
if (missing == "stop"){
if (any(is.na(data))){
stop("Missing data detected and missing = 'stop'")
}
} else {
# listwise:
data <- na.omit(data)
}
# Nonparanormal:
if (npn){
data <- huge::huge.npn(na.omit(as.matrix(data)),verbose = verbose)
}
# Estimate network:
Results <- huge::huge.select(huge::huge(data,method = "glasso",verbose=verbose), criterion = criterion,verbose = verbose,ebic.gamma = tuning)
# Return:
return(list(
graph=as.matrix(qgraph::wi2net(as.matrix(Results$opt.icov))),
results=Results))
}
### MGM ESTIMATOR ###
bootnet_mgm <- function(
data, # Dataset used
type,
level,
tuning = 0.5,
missing = c("listwise","stop"),
verbose = TRUE,
criterion = c("EBIC","CV"),
nFolds = 10,
order = 2,
rule = c("AND","OR"),
binarySign, # Detected by default
... # mgm functions
# method = c("glasso","mb","ct")
){
# Check arguments:
missing <- match.arg(missing)
criterion <- match.arg(criterion)
rule <- match.arg(rule)
# method <- match.arg(method)
# Message:
if (verbose){
msg <- "Estimating Network. Using package::function:"
msg <- paste0(msg,"\n - mgm::mgm for network computation\n - Using glmnet::glmnet")
# msg <- paste0(msg,"\n\nPlease reference accordingly\n")
message(msg)
}
# First test if data is a data frame:
if (!(is.data.frame(data) || is.matrix(data))){
stop("'data' argument must be a data frame")
}
# # If matrix coerce to data frame:
# if (is.matrix(data)){
# data <- as.data.frame(data)
# }
# If is not a matrix coerce to matrix (because mgm is silly):
# if (!is.matrix(data)){
data <- as.matrix(data)
# }
# Obtain info from data:
N <- ncol(data)
Np <- nrow(data)
# Check missing:
if (missing == "stop"){
if (any(is.na(data))){
stop("Missing data detected and missing = 'stop'")
}
} else {
# listwise:
data <- na.omit(data)
}
# Set type automatically:
if (missing(type)){
if (verbose){
message("'type' argument not assigned. Setting type to 'c' for all binary variables and 'g' for all other variables.")
}
type <- ifelse(apply(data,2,function(x)all(x%in%c(0,1))),"c","g")
}
if (length(type) != ncol(data)){
type <- rep(type, ncol(data))
}
# Set level automatically:
if (missing(level)){
if (verbose){
message("'level' argument not assigned. Setting level to 1 for all Gaussian/Poisson variables and number of unique values for all categorical variables")
}
level <- ifelse(type == "c", apply(data,2,function(x)length(unique(x))),1)
}
if (length(level) != ncol(data)){
level <- rep(level, ncol(data))
}
# Estimate:
# mgmfun <- "mgmfit"
# if (packageVersion("mgm") >= "1.2.0"){
# Check if all categorical binary variables are encoded 0 and 1:
if (missing(binarySign)){
if (any(type == "c" & level == 2)){
whichBinary <- which(type == "c" & level == 2)
enc <- apply(data[,whichBinary],2,function(x)all(x[!is.na(x)]%in%c(0L,1L)))
if (!all(enc)){
binarySign <- FALSE
} else {
binarySign <- TRUE
}
} else {
binarySign <- FALSE
}
}
log <- capture.output(Results <- mgm::mgm(
data,verbatim = !verbose, warnings = verbose, signInfo = FALSE,
type=type,
level=level,
lambdaSel = criterion,
lambdaFolds = nFolds,
lambdaGam = tuning,
k = order,
pbar = verbose,
ruleReg = rule, saveData = FALSE, binarySign = binarySign, ...))
# Warn for unsigned:
if (any(Results$pairwise$signs==0,na.rm = TRUE)){
warning("Bootnet does not support unsigned edges and treats these as positive edges.")
}
Results$pairwise$signs[is.na(Results$pairwise$signs)] <- 0
# Graph:
Graph <- Results$pairwise$wadj
Graph <- ifelse(Results$pairwise$signs==-1,-Graph,Graph)
#
# } else {
# log <- capture.output(Results <- do.call(mgmfun,list(
# data,
# type=type,
# lev=lev,
# lambda.sel = criterion,
# folds = nFolds,
# gam = tuning,
# d = degree,
# pbar = verbose,
# rule.reg = rule)))
#
# # Warn for unsigned:
# if (any(Results$signs==0,na.rm = TRUE)){
# warning("Bootnet does not support unsigned edges and treats these as positive edges.")
# }
# Results$signs[is.na(Results$signs)] <- 0
#
# # Graph:
# Graph <- Results$wadj
# Graph <- ifelse(Results$signs==-1,-Graph,Graph)
# }
# Return:
return(list(
graph=Graph,
results=Results))
}
### RELATIVE IMPORTANCE ###
bootnet_relimp <- function(
data, # Dataset used
normalized = TRUE,
type = "lmg",
structureDefault = c("none", "custom", "EBICglasso", "pcor","IsingFit","IsingSampler", "huge","adalasso","mgm"),
missing = c("listwise","stop"),
..., # Arguments sent to the structure function
verbose = TRUE,
threshold = 0
){
nVar <- ncol(data)
structureDefault <- match.arg(structureDefault)
# Check missing:
missing <- match.arg(missing)
if (missing == "stop"){
if (any(is.na(data))){
stop("Missing data detected and missing = 'stop'")
}
} else {
# listwise:
data <- na.omit(data)
}
# Compute structure (if needed)
if (structureDefault != "none"){
if (verbose){
message("Computing network structure")
msg <- "Computing network structure. Using package::function:"
if (structureDefault == "EBICglasso"){
msg <- paste0(msg,"\n - qgraph::EBICglasso for EBIC model selection\n - using glasso::glasso")
}
if (structureDefault == "pcor"){
msg <- paste0(msg,"\n - qgraph::qgraph(..., graph = 'pcor') for network computation")
}
if (structureDefault == "IsingFit"){
msg <- paste0(msg,"\n - IsingFit::IsingFit for network computation\n - Using glmnet::glmnet")
}
if (structureDefault == "IsingSampler"){
msg <- paste0(msg,"\n - IsingSampler::EstimateIsing for network computation")
}
if (structureDefault == "adalasso"){
msg <- paste0(msg,"\n - parcor::adalasso.net for network computation")
}
if (structureDefault == "huge"){
msg <- paste0(msg,"\n - huge::huge for network computation")
msg <- paste0(msg,"\n - huge::huge.npn for nonparanormal transformation")
}
if (structureDefault == "mgm"){
msg <- paste0(msg,"\n - mgm::mgm for network computation")
}
message(msg)
}
if (structureDefault == "custom"){
struc <- estimateNetwork(data, ...)
} else {
struc <- estimateNetwork(data, default = structureDefault, ..., verbose = FALSE)
}
struc <- struc$graph!=0
} else {
struc <- matrix(TRUE, nVar,nVar)
}
diag(struc) <- FALSE
# Empty matrix:
relimp <- matrix(0, nVar,nVar)
if (is.null(names(data))){
names(data) <- paste0("V",seq_len(nVar))
}
Vars <- names(data)
# For every node, compute incomming relative importance:
if (verbose){
msg <- "Computing relative importance network. Using package::function:\n - relaimpo::calc.relimp for edge weight estimation"
message(msg)
pb <- txtProgressBar(0,nVar,style=3)
}
for (i in 1:nVar){
if (any(struc[-i,i])){
formula <- as.formula(paste0(Vars[i]," ~ ",paste0(Vars[-i][struc[-i,i]],collapse=" + ")))
if (sum(struc[-i,i])==1){
# Only one predictor
if (normalized){
relimp[-i,i][struc[-i,i]] <- 1
} else {
res <- lm(formula, data)
sum <- summary(res)
relimp[-i,i][struc[-i,i]] <- sum$r.squared
}
} else {
res <- calc.relimp(formula, data, rela = normalized)
relimp[-i,i][struc[-i,i]] <- res@lmg
}
}
if (verbose){
setTxtProgressBar(pb, i)
}
}
if (verbose){
close(pb)
}
# threshold:
relimp <- ifelse(relimp<threshold,0,relimp)
# Return:
return(relimp)
}
| /R/defaultFunctions.R | no_license | tkasci/bootnet | R | false | false | 24,739 | r | # Folling R:
mgm <- NULL
mgmfit <- NULL
# Null function:
null <- function(...) NULL
### IsingFit ###
# prep fun (make binary if needed):
binarize <- function(x, split = "median", na.rm=TRUE, removeNArows = TRUE, verbose = TRUE){
x <- as.data.frame(x)
if (all(unlist(x) %in% c(0,1))){
return(x)
} else {
if (is.function(split)){
splitName <- deparse(substitute(split))
} else {
splitName <- split
}
if (verbose){
warning(paste("Splitting data by",splitName))
}
if (is.character(split) || is.function(split)){
splits <- sapply(x,split,na.rm=na.rm)
} else {
splits <- rep(split, length=ncol(x))
}
for (i in seq_len(ncol(x))){
x[,i] <- 1 * (x[,i] < splits[i])
}
if (removeNArows){
x <- x[apply(x,1,function(xx)all(!is.na(xx))),,drop=FALSE]
}
return(x)
}
}
### ARGUMENT ESTIMATOR ###
# Construct the estimator:
bootnet_argEstimator <- function(data, prepFun, prepArgs, estFun, estArgs, graphFun, graphArgs, intFun, intArgs, verbose = TRUE){
# prepArgs$verbose <- verbose
if ("verbose" %in% names(formals(prepFun))){
prepArgs$verbose <- verbose
}
# Compute input:
input <- do.call(prepFun, c(list(data), prepArgs))
# Compute network:
res <- do.call(estFun, c(list(input),estArgs))
# Extract network:
sampleGraph <- do.call(graphFun,c(list(res), graphArgs))
# Extract graph:
intercepts <- do.call(intFun,c(list(res), intArgs))
# Return:
return(list(graph=sampleGraph, intercepts = intercepts))
}
### EBIC GLASSO ESTIMATOR ###
bootnet_EBICglasso <- function(
data, # Dataset used
tuning = 0.5, # tuning parameter
corMethod = c("cor_auto","cov","cor","npn"), # Correlation method
missing = c("pairwise","listwise","fiml","stop"),
sampleSize = c("maximum","minimim"), # Sample size when using missing = "pairwise"
verbose = TRUE,
corArgs = list(), # Extra arguments to the correlation function
refit = FALSE,
...
){
# Check arguments:
corMethod <- match.arg(corMethod)
missing <- match.arg(missing)
sampleSize <- match.arg(sampleSize)
# Message:
if (verbose){
msg <- "Estimating Network. Using package::function:"
msg <- paste0(msg,"\n - qgraph::EBICglasso for EBIC model selection\n - using glasso::glasso")
if (corMethod == "cor_auto"){
msg <- paste0(msg,"\n - qgraph::cor_auto for correlation computation\n - using lavaan::lavCor")
}
if (corMethod == "npn"){
msg <- paste0(msg,"\n - huge::huge.npn for nonparanormal transformation")
}
# msg <- paste0(msg,"\n\nPlease reference accordingly\n")
message(msg)
}
# First test if data is a data frame:
if (!(is.data.frame(data) || is.matrix(data))){
stop("'data' argument must be a data frame")
}
# If matrix coerce to data frame:
if (is.matrix(data)){
data <- as.data.frame(data)
}
# Obtain info from data:
N <- ncol(data)
Np <- nrow(data)
# Check missing:
if (missing == "stop"){
if (any(is.na(data))){
stop("Missing data detected and missing = 'stop'")
}
}
# Correlate data:
# npn:
if (corMethod == "npn"){
data <- huge::huge.npn(data)
corMethod <- "cor"
}
# cor_auto:
if (corMethod == "cor_auto"){
args <- list(data=data,missing=missing,verbose=verbose)
if (length(corArgs) > 0){
for (i in seq_along(corArgs)){
args[[names(corArgs)[[i]]]] <- corArgs[[i]]
}
}
corMat <- do.call(qgraph::cor_auto,args)
} else if (corMethod%in%c("cor","cov")){
# Normal correlations
if (missing == "fiml"){
stop("missing = 'fiml' only supported with corMethod = 'cor_auto'")
}
use <- switch(missing,
pairwise = "pairwise.complete.obs",
listwise = "complete.obs")
args <- list(x=data,use=use)
if (length(corArgs) > 0){
for (i in seq_along(corArgs)){
args[[names(corArgs)[[i]]]] <- corArgs[[i]]
}
}
corMat <- do.call(corMethod,args)
} else stop ("Correlation method is not supported.")
# Sample size:
if (missing == "listwise"){
sampleSize <- nrow(na.omit(data))
} else{
if (sampleSize == "maximum"){
sampleSize <- sum(apply(data,1,function(x)!all(is.na(x))))
} else {
sampleSize <- sum(apply(data,1,function(x)!any(is.na(x))))
}
}
# Estimate network:
Results <- qgraph::EBICglasso(corMat,
n = sampleSize,
gamma = tuning,
returnAllResults = TRUE,
refit = refit,
...)
# Return:
return(list(graph=Results$optnet,results=Results))
}
### PCOR ESTIMATOR ###
bootnet_pcor <- function(
data, # Dataset used
corMethod = c("cor_auto","cov","cor","npn"), # Correlation method
missing = c("pairwise","listwise","fiml","stop"),
sampleSize = c("maximum","minimim"), # Sample size when using missing = "pairwise"
verbose = TRUE,
corArgs = list(), # Extra arguments to the correlation function
threshold = 0
){
# Check arguments:
corMethod <- match.arg(corMethod)
missing <- match.arg(missing)
sampleSize <- match.arg(sampleSize)
if (identical(threshold,"none")){
threshold <- 0
}
# Message:
if (verbose){
msg <- "Estimating Network. Using package::function:"
msg <- paste0(msg,"\n - qgraph::qgraph(..., graph = 'pcor') for network computation")
if (corMethod == "cor_auto"){
msg <- paste0(msg,"\n - qgraph::cor_auto for correlation computation\n - using lavaan::lavCor")
}
if (corMethod == "npn"){
msg <- paste0(msg,"\n - huge::huge.npn for nonparanormal transformation")
}
if (threshold != "none"){
if (threshold != "locfdr"){
msg <- paste0(msg,"\n - psych::corr.p for significance thresholding")
} else {
msg <- paste0(msg,"\n - fdrtool for false discovery rate")
}
}
# msg <- paste0(msg,"\n\nPlease reference accordingly\n")
message(msg)
}
# First test if data is a data frame:
if (!(is.data.frame(data) || is.matrix(data))){
stop("'data' argument must be a data frame")
}
# If matrix coerce to data frame:
if (is.matrix(data)){
data <- as.data.frame(data)
}
# Obtain info from data:
N <- ncol(data)
Np <- nrow(data)
# Check missing:
if (missing == "stop"){
if (any(is.na(data))){
stop("Missing data detected and missing = 'stop'")
}
}
# Correlate data:
# npn:
if (corMethod == "npn"){
data <- huge::huge.npn(data)
corMethod <- "cor"
}
# cor_auto:
if (corMethod == "cor_auto"){
args <- list(data=data,missing=missing,verbose=verbose)
if (length(corArgs) > 0){
for (i in seq_along(corArgs)){
args[[names(corArgs)[[i]]]] <- corArgs[[i]]
}
}
corMat <- do.call(qgraph::cor_auto,args)
} else if (corMethod%in%c("cor","cov")){
# Normal correlations
if (missing == "fiml"){
stop("missing = 'fiml' only supported with corMethod = 'cor_auto'")
}
use <- switch(missing,
pairwise = "pairwise.complete.obs",
listwise = "complete.obs")
args <- list(x=data,use=use)
if (length(corArgs) > 0){
for (i in seq_along(corArgs)){
args[[names(corArgs)[[i]]]] <- corArgs[[i]]
}
}
corMat <- do.call(corMethod,args)
} else stop ("Correlation method is not supported.")
# Sample size:
if (missing == "listwise"){
sampleSize <- nrow(na.omit(data))
} else{
if (sampleSize == "maximum"){
sampleSize <- sum(apply(data,1,function(x)!all(is.na(x))))
} else {
sampleSize <- sum(apply(data,1,function(x)!any(is.na(x))))
}
}
# Estimate network:
Results <- getWmat(qgraph::qgraph(corMat,graph = "pcor",DoNotPlot = TRUE,threshold=threshold, sampleSize = sampleSize))
# Return:
return(list(graph=Results,results=Results))
}
### COR ESTIMATOR ###
bootnet_cor <- function(
data, # Dataset used
corMethod = c("cor_auto","cov","cor","npn"), # Correlation method
missing = c("pairwise","listwise","fiml","stop"),
sampleSize = c("maximum","minimim"), # Sample size when using missing = "pairwise"
verbose = TRUE,
corArgs = list(), # Extra arguments to the correlation function
threshold = 0
){
# Check arguments:
corMethod <- match.arg(corMethod)
missing <- match.arg(missing)
sampleSize <- match.arg(sampleSize)
if (identical(threshold,"none")){
threshold <- 0
}
# Message:
if (verbose){
msg <- "Estimating Network. Using package::function:"
# msg <- paste0(msg,"\n - qgraph::qgraph(..., graph = 'cor') for network computation")
if (corMethod == "cor_auto"){
msg <- paste0(msg,"\n - qgraph::cor_auto for correlation computation\n - using lavaan::lavCor")
}
if (corMethod == "npn"){
msg <- paste0(msg,"\n - huge::huge.npn for nonparanormal transformation")
}
if (threshold != "none"){
if (threshold != "locfdr"){
msg <- paste0(msg,"\n - psych::corr.p for significance thresholding")
} else {
msg <- paste0(msg,"\n - fdrtool for false discovery rate")
}
}
# msg <- paste0(msg,"\n\nPlease reference accordingly\n")
message(msg)
}
# First test if data is a data frame:
if (!(is.data.frame(data) || is.matrix(data))){
stop("'data' argument must be a data frame")
}
# If matrix coerce to data frame:
if (is.matrix(data)){
data <- as.data.frame(data)
}
# Obtain info from data:
N <- ncol(data)
Np <- nrow(data)
# Check missing:
if (missing == "stop"){
if (any(is.na(data))){
stop("Missing data detected and missing = 'stop'")
}
}
# Correlate data:
# npn:
if (corMethod == "npn"){
data <- huge::huge.npn(data)
corMethod <- "cor"
}
# cor_auto:
if (corMethod == "cor_auto"){
args <- list(data=data,missing=missing,verbose=verbose)
if (length(corArgs) > 0){
for (i in seq_along(corArgs)){
args[[names(corArgs)[[i]]]] <- corArgs[[i]]
}
}
corMat <- do.call(qgraph::cor_auto,args)
} else if (corMethod%in%c("cor","cov")){
# Normal correlations
if (missing == "fiml"){
stop("missing = 'fiml' only supported with corMethod = 'cor_auto'")
}
use <- switch(missing,
pairwise = "pairwise.complete.obs",
listwise = "complete.obs")
args <- list(x=data,use=use)
if (length(corArgs) > 0){
for (i in seq_along(corArgs)){
args[[names(corArgs)[[i]]]] <- corArgs[[i]]
}
}
corMat <- do.call(corMethod,args)
} else stop ("Correlation method is not supported.")
# Sample size:
if (missing == "listwise"){
sampleSize <- nrow(na.omit(data))
} else{
if (sampleSize == "maximum"){
sampleSize <- sum(apply(data,1,function(x)!all(is.na(x))))
} else {
sampleSize <- sum(apply(data,1,function(x)!any(is.na(x))))
}
}
# Estimate network:
Results <- getWmat(qgraph::qgraph(corMat,graph = "cor",DoNotPlot = TRUE,threshold=threshold, sampleSize = sampleSize))
# Return:
return(list(graph=Results,results=Results))
}
### ISINGFIT ESTIMATOR ###
bootnet_IsingFit <- function(
data, # Dataset used
tuning = 0.25, # tuning parameter
missing = c("listwise","stop"),
verbose = TRUE,
rule = c("AND","OR"),
split = "median"
){
# Check arguments:
missing <- match.arg(missing)
rule <- match.arg(rule)
# Message:
if (verbose){
msg <- "Estimating Network. Using package::function:"
msg <- paste0(msg,"\n - IsingFit::IsingFit for network computation\n - Using glmnet::glmnet")
# msg <- paste0(msg,"\n\nPlease reference accordingly\n")
message(msg)
}
# First test if data is a data frame:
if (!(is.data.frame(data) || is.matrix(data))){
stop("'data' argument must be a data frame")
}
# If matrix coerce to data frame:
if (is.matrix(data)){
data <- as.data.frame(data)
}
# Check missing:
if (missing == "stop"){
if (any(is.na(data))){
stop("Missing data detected and missing = 'stop'")
}
} else {
# listwise:
data <- na.omit(data)
}
# Obtain info from data:
N <- ncol(data)
Np <- nrow(data)
# Binarize:
if (!all(data %in% c(0,1))){
data <- bootnet::binarize(data, split = split, verbose = verbose)
}
# Estimate network:
Results <- IsingFit::IsingFit(data, AND = rule == "AND", gamma = tuning,progressbar = verbose,plot = FALSE)
# Return:
return(list(graph = Results$weiadj, intercepts = Results$thresholds,
results = Results))
}
### ISINGSAMPLER ESTIMATOR ###
bootnet_IsingSampler <- function(
data, # Dataset used
missing = c("listwise","stop"),
verbose = TRUE,
split = "median",
method = c("default","ll","pl","uni","bi")
){
# Check arguments:
missing <- match.arg(missing)
method <- match.arg(method)
# Message:
if (verbose){
msg <- "Estimating Network. Using package::function:"
msg <- paste0(msg,"\n - IsingSampler::EstimateIsing for network computation")
# msg <- paste0(msg,"\n\nPlease reference accordingly\n")
message(msg)
}
# First test if data is a data frame:
if (!(is.data.frame(data) || is.matrix(data))){
stop("'data' argument must be a data frame")
}
# If matrix coerce to data frame:
if (is.matrix(data)){
data <- as.data.frame(data)
}
if (method == "default"){
if (ncol(data) > 20){
method <- "uni"
if (verbose){
message("'method' set to 'uni'")
}
} else {
method <- "ll"
if (verbose){
message("'method' set to 'll'")
}
}
}
# Check missing:
if (missing == "stop"){
if (any(is.na(data))){
stop("Missing data detected and missing = 'stop'")
}
} else {
# listwise:
data <- na.omit(data)
}
# Obtain info from data:
N <- ncol(data)
Np <- nrow(data)
# Binarize:
if (!all(data %in% c(0,1))){
data <- bootnet::binarize(data, split = split, verbose = verbose)
}
# Estimate network:
Results <- IsingSampler::EstimateIsing(as.matrix(data), method = method)
# Return:
return(list(graph = Results$graph, intercepts = Results$thresholds,
results = Results))
}
### PCOR ESTIMATOR ###
bootnet_adalasso <- function(
data, # Dataset used
missing = c("listwise","stop"),
verbose = TRUE,
nFolds = 10 # Number of folds
){
# Check arguments:
missing <- match.arg(missing)
# Message:
if (verbose){
msg <- "Estimating Network. Using package::function:"
msg <- paste0(msg,"\n - parcor::adalasso.net for network computation")
# msg <- paste0(msg,"\n\nPlease reference accordingly\n")
message(msg)
}
# First test if data is a data frame:
if (!(is.data.frame(data) || is.matrix(data))){
stop("'data' argument must be a data frame")
}
# If matrix coerce to data frame:
if (is.matrix(data)){
data <- as.data.frame(data)
}
# Obtain info from data:
N <- ncol(data)
Np <- nrow(data)
# Check missing:
if (missing == "stop"){
if (any(is.na(data))){
stop("Missing data detected and missing = 'stop'")
}
} else {
# listwise:
data <- na.omit(data)
}
# Estimate network:
Results <- parcor::adalasso.net(data, k = nFolds)
# Return:
return(list(graph=as.matrix(Matrix::forceSymmetric(Results$pcor.adalasso)),results=Results))
}
### HUGE ESTIMATOR ###
bootnet_huge <- function(
data, # Dataset used
tuning = 0.5,
missing = c("listwise","stop"),
verbose = TRUE,
npn = TRUE, # Compute nonparanormal?
criterion = c("ebic","ric","stars")
# method = c("glasso","mb","ct")
){
# Check arguments:
missing <- match.arg(missing)
criterion <- match.arg(criterion)
# method <- match.arg(method)
# Message:
if (verbose){
msg <- "Estimating Network. Using package::function:"
msg <- paste0(msg,"\n - huge::huge for network computation")
msg <- paste0(msg,"\n - huge::huge.npn for nonparanormal transformation")
# msg <- paste0(msg,"\n\nPlease reference accordingly\n")
message(msg)
}
# First test if data is a data frame:
if (!(is.data.frame(data) || is.matrix(data))){
stop("'data' argument must be a data frame")
}
# If matrix coerce to data frame:
if (is.matrix(data)){
data <- as.data.frame(data)
}
# Obtain info from data:
N <- ncol(data)
Np <- nrow(data)
# Check missing:
if (missing == "stop"){
if (any(is.na(data))){
stop("Missing data detected and missing = 'stop'")
}
} else {
# listwise:
data <- na.omit(data)
}
# Nonparanormal:
if (npn){
data <- huge::huge.npn(na.omit(as.matrix(data)),verbose = verbose)
}
# Estimate network:
Results <- huge::huge.select(huge::huge(data,method = "glasso",verbose=verbose), criterion = criterion,verbose = verbose,ebic.gamma = tuning)
# Return:
return(list(
graph=as.matrix(qgraph::wi2net(as.matrix(Results$opt.icov))),
results=Results))
}
### MGM ESTIMATOR ###
bootnet_mgm <- function(
data, # Dataset used
type,
level,
tuning = 0.5,
missing = c("listwise","stop"),
verbose = TRUE,
criterion = c("EBIC","CV"),
nFolds = 10,
order = 2,
rule = c("AND","OR"),
binarySign, # Detected by default
... # mgm functions
# method = c("glasso","mb","ct")
){
# Check arguments:
missing <- match.arg(missing)
criterion <- match.arg(criterion)
rule <- match.arg(rule)
# method <- match.arg(method)
# Message:
if (verbose){
msg <- "Estimating Network. Using package::function:"
msg <- paste0(msg,"\n - mgm::mgm for network computation\n - Using glmnet::glmnet")
# msg <- paste0(msg,"\n\nPlease reference accordingly\n")
message(msg)
}
# First test if data is a data frame:
if (!(is.data.frame(data) || is.matrix(data))){
stop("'data' argument must be a data frame")
}
# # If matrix coerce to data frame:
# if (is.matrix(data)){
# data <- as.data.frame(data)
# }
# If is not a matrix coerce to matrix (because mgm is silly):
# if (!is.matrix(data)){
data <- as.matrix(data)
# }
# Obtain info from data:
N <- ncol(data)
Np <- nrow(data)
# Check missing:
if (missing == "stop"){
if (any(is.na(data))){
stop("Missing data detected and missing = 'stop'")
}
} else {
# listwise:
data <- na.omit(data)
}
# Set type automatically:
if (missing(type)){
if (verbose){
message("'type' argument not assigned. Setting type to 'c' for all binary variables and 'g' for all other variables.")
}
type <- ifelse(apply(data,2,function(x)all(x%in%c(0,1))),"c","g")
}
if (length(type) != ncol(data)){
type <- rep(type, ncol(data))
}
# Set level automatically:
if (missing(level)){
if (verbose){
message("'level' argument not assigned. Setting level to 1 for all Gaussian/Poisson variables and number of unique values for all categorical variables")
}
level <- ifelse(type == "c", apply(data,2,function(x)length(unique(x))),1)
}
if (length(level) != ncol(data)){
level <- rep(level, ncol(data))
}
# Estimate:
# mgmfun <- "mgmfit"
# if (packageVersion("mgm") >= "1.2.0"){
# Check if all categorical binary variables are encoded 0 and 1:
if (missing(binarySign)){
if (any(type == "c" & level == 2)){
whichBinary <- which(type == "c" & level == 2)
enc <- apply(data[,whichBinary],2,function(x)all(x[!is.na(x)]%in%c(0L,1L)))
if (!all(enc)){
binarySign <- FALSE
} else {
binarySign <- TRUE
}
} else {
binarySign <- FALSE
}
}
log <- capture.output(Results <- mgm::mgm(
data,verbatim = !verbose, warnings = verbose, signInfo = FALSE,
type=type,
level=level,
lambdaSel = criterion,
lambdaFolds = nFolds,
lambdaGam = tuning,
k = order,
pbar = verbose,
ruleReg = rule, saveData = FALSE, binarySign = binarySign, ...))
# Warn for unsigned:
if (any(Results$pairwise$signs==0,na.rm = TRUE)){
warning("Bootnet does not support unsigned edges and treats these as positive edges.")
}
Results$pairwise$signs[is.na(Results$pairwise$signs)] <- 0
# Graph:
Graph <- Results$pairwise$wadj
Graph <- ifelse(Results$pairwise$signs==-1,-Graph,Graph)
#
# } else {
# log <- capture.output(Results <- do.call(mgmfun,list(
# data,
# type=type,
# lev=lev,
# lambda.sel = criterion,
# folds = nFolds,
# gam = tuning,
# d = degree,
# pbar = verbose,
# rule.reg = rule)))
#
# # Warn for unsigned:
# if (any(Results$signs==0,na.rm = TRUE)){
# warning("Bootnet does not support unsigned edges and treats these as positive edges.")
# }
# Results$signs[is.na(Results$signs)] <- 0
#
# # Graph:
# Graph <- Results$wadj
# Graph <- ifelse(Results$signs==-1,-Graph,Graph)
# }
# Return:
return(list(
graph=Graph,
results=Results))
}
### RELATIVE IMPORTANCE ###
bootnet_relimp <- function(
data, # Dataset used
normalized = TRUE,
type = "lmg",
structureDefault = c("none", "custom", "EBICglasso", "pcor","IsingFit","IsingSampler", "huge","adalasso","mgm"),
missing = c("listwise","stop"),
..., # Arguments sent to the structure function
verbose = TRUE,
threshold = 0
){
nVar <- ncol(data)
structureDefault <- match.arg(structureDefault)
# Check missing:
missing <- match.arg(missing)
if (missing == "stop"){
if (any(is.na(data))){
stop("Missing data detected and missing = 'stop'")
}
} else {
# listwise:
data <- na.omit(data)
}
# Compute structure (if needed)
if (structureDefault != "none"){
if (verbose){
message("Computing network structure")
msg <- "Computing network structure. Using package::function:"
if (structureDefault == "EBICglasso"){
msg <- paste0(msg,"\n - qgraph::EBICglasso for EBIC model selection\n - using glasso::glasso")
}
if (structureDefault == "pcor"){
msg <- paste0(msg,"\n - qgraph::qgraph(..., graph = 'pcor') for network computation")
}
if (structureDefault == "IsingFit"){
msg <- paste0(msg,"\n - IsingFit::IsingFit for network computation\n - Using glmnet::glmnet")
}
if (structureDefault == "IsingSampler"){
msg <- paste0(msg,"\n - IsingSampler::EstimateIsing for network computation")
}
if (structureDefault == "adalasso"){
msg <- paste0(msg,"\n - parcor::adalasso.net for network computation")
}
if (structureDefault == "huge"){
msg <- paste0(msg,"\n - huge::huge for network computation")
msg <- paste0(msg,"\n - huge::huge.npn for nonparanormal transformation")
}
if (structureDefault == "mgm"){
msg <- paste0(msg,"\n - mgm::mgm for network computation")
}
message(msg)
}
if (structureDefault == "custom"){
struc <- estimateNetwork(data, ...)
} else {
struc <- estimateNetwork(data, default = structureDefault, ..., verbose = FALSE)
}
struc <- struc$graph!=0
} else {
struc <- matrix(TRUE, nVar,nVar)
}
diag(struc) <- FALSE
# Empty matrix:
relimp <- matrix(0, nVar,nVar)
if (is.null(names(data))){
names(data) <- paste0("V",seq_len(nVar))
}
Vars <- names(data)
# For every node, compute incomming relative importance:
if (verbose){
msg <- "Computing relative importance network. Using package::function:\n - relaimpo::calc.relimp for edge weight estimation"
message(msg)
pb <- txtProgressBar(0,nVar,style=3)
}
for (i in 1:nVar){
if (any(struc[-i,i])){
formula <- as.formula(paste0(Vars[i]," ~ ",paste0(Vars[-i][struc[-i,i]],collapse=" + ")))
if (sum(struc[-i,i])==1){
# Only one predictor
if (normalized){
relimp[-i,i][struc[-i,i]] <- 1
} else {
res <- lm(formula, data)
sum <- summary(res)
relimp[-i,i][struc[-i,i]] <- sum$r.squared
}
} else {
res <- calc.relimp(formula, data, rela = normalized)
relimp[-i,i][struc[-i,i]] <- res@lmg
}
}
if (verbose){
setTxtProgressBar(pb, i)
}
}
if (verbose){
close(pb)
}
# threshold:
relimp <- ifelse(relimp<threshold,0,relimp)
# Return:
return(relimp)
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/data.R
\docType{data}
\name{cytogenetic_bands}
\alias{cytogenetic_bands}
\title{GRCh38 human cytogenetic bands.}
\format{
A data frame with 862 rows and 8 variables:
\describe{
\item{cytogenetic_band}{Cytogenetic band name. See \emph{Cytogenetic
Nomenclature} below.}
\item{chromosome}{Chromosome name: 1 through 22 (the autosomes), X or
Y.}
\item{start}{Genomic start position of the cytogenetic band. Starts at 1.}
\item{end}{Genomic end position of the cytogenetic band. End position is
included in the band interval.}
\item{length}{Length of the genomic interval of cytogenetic band.}
\item{assembly}{Assembly version, should be 'GRCh38'.}
\item{stain}{\href{https://en.wikipedia.org/wiki/Giemsa_stain}{Giemsa
stain} results: Giemsa negative, \code{'gneg'}; Giemsa positive, of
increasing intensities, \code{'gpos25'}, \code{'gpos50'}, \code{'gpos75'},
and \code{'gpos100'}; centromeric region, \code{'acen'}; heterochromatin,
either pericentric or telomeric, \code{'gvar'}; and short arm of
acrocentric chromosomes 13, 14, 15, 21, and 22 are coded as
\code{'stalk'}.}
\item{last_download_date}{Time stamp of last time this dataset was
downloaded from Ensembl.}
}
}
\source{
\url{https://rest.ensembl.org/info/assembly/homo_sapiens?content-type=application/json&bands=1}
}
\usage{
cytogenetic_bands
}
\description{
A dataset containing the GRCh38 human cytogenetic bands and their genomic
coordinates.
}
\details{
Genomic coordinates are for
\href{https://genome-blog.soe.ucsc.edu/blog/wp-content/uploads/2016/12/newInterval.png}{fully
closed} intervals.
}
\section{Cytogenetic Nomenclature}{
Cytogenetic bands are numbered from the centromere outwards in both
directions towards the telomeres on the shorter p arm and the longer q arm.
The first number or letter represents the chromosome. Chromosomes 1 through
22 (the autosomes) are designated by their chromosome number. The sex
chromosomes are designated by X or Y. The next letter represents the arm of
the chromosome: p or q.
The numbers cannot be read in the normal decimal numeric system e.g. 36, but
rather 3-6 (region 3 band 6). Counting starts at the centromere as region 1
(or 1-0), to 11 (1-1) to 21 (2-1) to 22 (2-2) etc. Subbands are added in a
similar way, e.g. 21.1 to 21.2, if the bands are small or only appear at a
higher resolution.
}
\keyword{datasets}
| /man/cytogenetic_bands.Rd | permissive | ramiromagno/gwasrapidd | R | false | true | 2,448 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/data.R
\docType{data}
\name{cytogenetic_bands}
\alias{cytogenetic_bands}
\title{GRCh38 human cytogenetic bands.}
\format{
A data frame with 862 rows and 8 variables:
\describe{
\item{cytogenetic_band}{Cytogenetic band name. See \emph{Cytogenetic
Nomenclature} below.}
\item{chromosome}{Chromosome name: 1 through 22 (the autosomes), X or
Y.}
\item{start}{Genomic start position of the cytogenetic band. Starts at 1.}
\item{end}{Genomic end position of the cytogenetic band. End position is
included in the band interval.}
\item{length}{Length of the genomic interval of cytogenetic band.}
\item{assembly}{Assembly version, should be 'GRCh38'.}
\item{stain}{\href{https://en.wikipedia.org/wiki/Giemsa_stain}{Giemsa
stain} results: Giemsa negative, \code{'gneg'}; Giemsa positive, of
increasing intensities, \code{'gpos25'}, \code{'gpos50'}, \code{'gpos75'},
and \code{'gpos100'}; centromeric region, \code{'acen'}; heterochromatin,
either pericentric or telomeric, \code{'gvar'}; and short arm of
acrocentric chromosomes 13, 14, 15, 21, and 22 are coded as
\code{'stalk'}.}
\item{last_download_date}{Time stamp of last time this dataset was
downloaded from Ensembl.}
}
}
\source{
\url{https://rest.ensembl.org/info/assembly/homo_sapiens?content-type=application/json&bands=1}
}
\usage{
cytogenetic_bands
}
\description{
A dataset containing the GRCh38 human cytogenetic bands and their genomic
coordinates.
}
\details{
Genomic coordinates are for
\href{https://genome-blog.soe.ucsc.edu/blog/wp-content/uploads/2016/12/newInterval.png}{fully
closed} intervals.
}
\section{Cytogenetic Nomenclature}{
Cytogenetic bands are numbered from the centromere outwards in both
directions towards the telomeres on the shorter p arm and the longer q arm.
The first number or letter represents the chromosome. Chromosomes 1 through
22 (the autosomes) are designated by their chromosome number. The sex
chromosomes are designated by X or Y. The next letter represents the arm of
the chromosome: p or q.
The numbers cannot be read in the normal decimal numeric system e.g. 36, but
rather 3-6 (region 3 band 6). Counting starts at the centromere as region 1
(or 1-0), to 11 (1-1) to 21 (2-1) to 22 (2-2) etc. Subbands are added in a
similar way, e.g. 21.1 to 21.2, if the bands are small or only appear at a
higher resolution.
}
\keyword{datasets}
|
## The RAINLINK package. Retrieval algorithm for rainfall mapping from microwave links
## in a cellular communication network.
##
## Version 1.21
## Copyright (C) 2021 Aart Overeem
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
## R program 'Run.R'.
## SCRIPT FOR RAINFALL ESTIMATION USING MICROWAVE LINKS.
## source("Run.R")
## Run this script by pasting the line above (source(...)) or by pasting parts of the script into the R shell.
# Note that it is not necessarily a problem if a function argument is not supplied to the function. If the
# function argument is not used, then there is no problem. Only be aware that you should use e.g.
# MaxFrequency=MaxFrequency. I.e. if you only supply MaxFrequency and the function argument before
# MaxFrequency is missing, than the function will not execute properly.
#############################################################
# 0. Load R libraries, parameter values, and other settings.#
# This also loads the RAINLINK package. #
#############################################################
source("Config.R")
# If the time zone of the employed microwave link dataset is not the same as the (local) time zone used by R on your computer, set the time zone of the microwave link dataset:
# (this is important for functions RefLevelMinMaxRSL, WetDryNearbyLinkApMinMaxRSL and Interpolation):
Sys.setenv(TZ='UTC')
# Otherwise RAINLINK can derive a wrong time interval length due to going to or from daylight saving time (DST). Timing of DST may be different between time zones, or one time zone may not have a change to/from DST.
############################
# 1. PreprocessingMinMaxRSL#
############################
# Load example data:
data(Linkdata)
# For each unique link identifier a time interval is removed if it contains more than one record. This is done by the function "PreprocessingMinMaxRSL".
# In case the records from a certain time interval and unique link identifier are the same, this would throw away data from the entire interval for this identifier,
# whereas the information would be useful. To check how often this occurs:
# length(Linkdata[,1])
# length(unique(Linkdata)[,1])
# To avoid this:
Linkdata <- unique(Linkdata)
# Add column with polarization if this column is not supplied in the link data:
if ("Polarization" %in% names(Linkdata)==FALSE)
{
Linkdata$Polarization <- rep(NA,nrow(Linkdata))
}
# When no information on polarization is provided, the above code creates a column of NA for Polarization. In the function "RainRetrievalMinMaxRSL.R" links with
# NA values for polarization are processed with a & b values determined for vertically polarized signals.
# If information on polarization of links is available, use H for horizontally polarized & V for vertically polarized in Linkdata$Polarization.
# H, V & NA may occur in the same Linkdata file.
# Run R function:
StartTime <- proc.time()
DataPreprocessed <- PreprocessingMinMaxRSL(Data=Linkdata,MaxFrequency=MaxFrequency,MinFrequency=MinFrequency,verbose=TRUE)
cat(sprintf("Finished. (%.1f seconds)\n",round((proc.time()-StartTime)[3],digits=1)))
############################################
# 2. WetDryNearbyLinkApMinMaxRSL (OPTIONAL)#
############################################
# Run R function:
StartTime <- proc.time()
WetDry <- WetDryNearbyLinkApMinMaxRSL(Data=DataPreprocessed,CoorSystemInputData=NULL,
MinHoursPmin=MinHoursPmin,PeriodHoursPmin=PeriodHoursPmin,Radius=Radius,Step8=Step8,
ThresholdMedian=ThresholdMedian,ThresholdMedianL=ThresholdMedianL,ThresholdNumberLinks=ThresholdNumberLinks,
ThresholdWetDry=ThresholdWetDry)
cat(sprintf("Finished. (%.1f seconds)\n",round((proc.time()-StartTime)[3],digits=1)))
#######################
# 3. RefLevelMinMaxRSL#
#######################
# Run R function:
StartTime <- proc.time()
Pref <- RefLevelMinMaxRSL(Data=DataPreprocessed,Dry=WetDry$Dry,HoursRefLevel=HoursRefLevel,PeriodHoursRefLevel=PeriodHoursRefLevel)
cat(sprintf("Finished. (%.1f seconds)\n",round((proc.time()-StartTime)[3],digits=1)))
# If wet-dry classification (function WetDryNearbyLinkApMinMaxRSL) has not been applied, run the R function as follows:
StartTime <- proc.time()
Pref <- RefLevelMinMaxRSL(Data=DataPreprocessed,Dry=NULL,HoursRefLevel=HoursRefLevel,PeriodHoursRefLevel=PeriodHoursRefLevel)
cat(sprintf("Finished. (%.1f seconds)\n",round((proc.time()-StartTime)[3],digits=1)))
#############################################################################################################
# 4. OutlierFilterMinMax (OPTIONAL) - Can only be applied when WetDryNearbyLinkApMinMaxRSL has been applied.#
#############################################################################################################
# Run R function:
DataOutlierFiltered <- OutlierFilterMinMaxRSL(Data=DataPreprocessed,F=WetDry$F,FilterThreshold=FilterThreshold)
######################
# 5. CorrectMinMaxRSL#
######################
# Run R function:
Pcor <- CorrectMinMaxRSL(Data=DataOutlierFiltered,Dry=WetDry$Dry,Pref=Pref)
# If wet-dry classification (function WetDryNearbyLinkApMinMaxRSL) has not been applied, run the R function as follows:
Pcor <- CorrectMinMaxRSL(Data=DataPreprocessed,Dry=NULL,Pref=Pref)
############################
# 6. RainRetrievalMinMaxRSL#
############################
kRPowerLawDataH <- read.table(FileRainRetrHorizontal)
colnames(kRPowerLawDataH) <- c("f", "a", "b")
kRPowerLawDataV <- read.table(FileRainRetrVertical)
colnames(kRPowerLawDataV) <- c("f", "a", "b")
# Run R function:
StartTime <- proc.time()
Rmean <- RainRetrievalMinMaxRSL(Aa=Aa,alpha=alpha,Data=DataOutlierFiltered,kRPowerLawDataH=kRPowerLawDataH,kRPowerLawDataV=kRPowerLawDataV,PmaxCor=Pcor$PmaxCor,PminCor=Pcor$PminCor,Pref=Pref)
cat(sprintf("Finished. (%.1f seconds)\n",round((proc.time()-StartTime)[3],digits=1)))
# If wet-dry classification (function WetDryNearbyLinkApMinMaxRSL) has not been applied, run the R function as follows:
StartTime <- proc.time()
Rmean <- RainRetrievalMinMaxRSL(Aa=Aa,alpha=alpha,Data=DataPreprocessed,kRPowerLawDataH=kRPowerLawDataH,kRPowerLawDataV=kRPowerLawDataV,PmaxCor=Pcor$PmaxCor,PminCor=Pcor$PminCor,Pref=Pref)
cat(sprintf("Finished. (%.1f seconds)\n",round((proc.time()-StartTime)[3],digits=1)))
# Write path-average rainfall data to files:
# Duration of time interval of sampling strategy (min):
TIMESTEP <- 15
# Location of output link data:
FolderRainEstimates <- paste("LinkPathRainDepths",TIMESTEP,"min",sep="")
ToFile = TRUE
if (ToFile)
{
# Create directory for output files:
if(!dir.exists(FolderRainEstimates)){ dir.create(FolderRainEstimates) }
# Write output to file
ID <- unique(DataPreprocessed$ID)
t <- sort(unique(DataPreprocessed$DateTime))
t_sec <- as.numeric(as.POSIXct(as.character(t), format = "%Y%m%d%H%M"))
dt <- min(diff(t_sec))
for (i in 1 : length(t))
{
ind <- which(DataPreprocessed$DateTime == t[i])
int_data <- data.frame(ID = DataPreprocessed$ID[ind], RainfallDepthPath = Rmean[ind] * dt / 3600,
PathLength = DataPreprocessed$PathLength[ind], XStart = DataPreprocessed$XStart[ind],
YStart = DataPreprocessed$YStart[ind], XEnd = DataPreprocessed$XEnd[ind],
YEnd = DataPreprocessed$YEnd[ind], IntervalNumber = rep(i, length(ind)),
Frequency = DataPreprocessed$Frequency[ind])
Filename <- paste(FolderRainEstimates, "/linkdata_", t[i], ".dat", sep="")
# Using na.omit removes all rows with at least 1 NA:
write.table(na.omit(int_data), Filename, row.names = FALSE, col.names = TRUE, append = FALSE, quote = FALSE)
}
}
# Note that the output files contain rainfall depths (mm). If these data are to be used for the interpolation, they must first be read ("Interpolation.R" does not read these files).
# Using the data for "Interpolation.R" requires a conversion from rainfall depth (mm) to rainfall intensity (mm/h).
###################
# 7. Interpolation#
###################
# Read grid onto which data are interpolated
RainGrid <- read.table(FileGrid, header = TRUE, sep=",")
# Duration of time interval of sampling strategy (min):
TIMESTEP <- 15
# Location of output link data:
FolderRainMaps <- paste("RainMapsLinks",TIMESTEP,"min",sep="")
# Run R function:
StartTime <- proc.time()
Interpolation(Data=DataPreprocessed,CoorSystemInputData=NULL,idp=idp,IntpMethod=IntpMethod,nmax=nmax,
NUGGET=NUGGET,RANGE=RANGE,RainGrid=RainGrid,Rmean=Rmean,SILL=SILL,Variogram=Variogram,OutputDir=FolderRainMaps)
cat(sprintf("Finished. (%.1f seconds)\n",round((proc.time()-StartTime)[3],digits=1)))
###################
# 8. Visualisation#
###################
# It seems that mapping with OpenStreetMap (``get_openstreetmap'') is no langer supported. Google Maps is also not supported anymore, unless you obtain a Google API key.
# The employed ggmap function also allows to use Stamen Maps. This functionality has been added to RAINLINK's visualisation functions.
# Executing the "RainMaps...R" functions can often give the error below for Google Maps, which is
# caused by the Google server. Apparently, maps have been downloaded too often. Just try again (and again).
# Error in data.frame(ll.lat = ll[1], ll.lon = ll[2], ur.lat = ur[1], ur.lon = ur[2]) :
# arguments imply differing number of rows: 0, 1
# In addition: Warning message:
# geocode failed with status OVER_QUERY_LIMIT, location = "De Eemhof, Zeewolde"
# Executing revgeocode(c(Lon,Lat)) can also give an error, which is probably also related to obtaining the map from the Google Maps server. Just try again (and again):
# Warning message:
# In revgeocode(c(LonLocation, LatLocation)) :
# reverse geocode failed - bad location? location = "4.85"reverse geocode failed - bad location? location = "52.39"
############################
# 8.1 RainMapsLinksTimeStep#
############################
# Date and time at which rainfall mapping starts:
DateTimeStartRainMaps <- "201109102045"
# Date and time at which rainfall mapping ends:
DateTimeEndRainMaps <- "201109102045"
# Both should be "201109102045" to reproduce Figure 5 from AMT manuscript.
# Both should be "201109102015" to reproduce Figure 7 from AMT manuscript.
# Run function RainMapsLinksTimeStep:
RainMapsLinksTimeStep(AlphaLinksTimeStep=AlphaLinksTimeStep,
AlphaPlotLocation=AlphaPlotLocation,AlphaPolygon=AlphaPolygon,
AutDefineLegendTop=AutDefineLegendTop,BBoxOSMauto=BBoxOSMauto,ColourLinks=ColourLinks,
ColoursNumber=ColoursNumber,ColourPlotLocation=ColourPlotLocation,
ColourPlotLocationText=ColourPlotLocationText,ColourScheme=ColourScheme,
ColourType=ColourType,ConversionDepthToIntensity=ConversionDepthToIntensity,
CoorSystemInputData=CoorSystemInputData,DateTimeEndRainMaps=DateTimeEndRainMaps,
DateTimeStartRainMaps=DateTimeStartRainMaps,ExtraDeg=ExtraDeg,ExtraText=ExtraText,
FigFileLinksTimeStep=FigFileLinksTimeStep,FigHeight=FigHeight,FigWidth=FigWidth,
FileGrid=FileGrid,FilePolygonsGrid=FilePolygonsGrid,FolderFigures=FolderFigures,
FolderRainMaps=FolderRainMaps,FolderRainEstimates=FolderRainEstimates,
FontFamily=FontFamily,GoogleLocDegSpecified=GoogleLocDegSpecified,
GoogleLocLat=GoogleLocLat,GoogleLocLon=GoogleLocLon,GoogleLocName=GoogleLocName,
GoogleLocNameSpecified=GoogleLocNameSpecified,GoogleMapType=GoogleMapType,
GoogleZoomlevel=GoogleZoomlevel,LabelAxisLat=LabelAxisLat,
LabelAxisLonGoogle=LabelAxisLonGoogle,LabelAxisLonOSM=LabelAxisLonOSM,
LabelAxisLonStamen=LabelAxisLonStamen,LatLocation=LatLocation,LatText=LatText,
LegendSize=LegendSize,LegendTitleLinksTimeStep=LegendTitleLinksTimeStep,LonLocation=LonLocation,
LonText=LonText,ManualScale=ManualScale,MapBackground=MapBackground,OSMBottom=OSMBottom,
OSMLeft=OSMLeft,OSMRight=OSMRight,OSMScale=OSMScale,OSMTop=OSMTop,OutputFileType=OutputFileType,
PlotLocation=PlotLocation,PixelBorderCol=PixelBorderCol,
PlotBelowScaleBottom=PlotBelowScaleBottom,PlotLocLinks=PlotLocLinks,
ScaleBottomTimeStep=ScaleBottomTimeStep,ScaleHigh=ScaleHigh,ScaleLow=ScaleLow,
ScaleTopTimeStep=ScaleTopTimeStep,SizeLinks=SizeLinks,SizePixelBorder=SizePixelBorder,
SizePlotLocation=SizePlotLocation,SizePlotTitle=SizePlotTitle,
StamenMapType=StamenMapType,StamenZoomlevel=StamenZoomlevel,
SymbolPlotLocation=SymbolPlotLocation,TitleLinks=TitleLinks,XMiddle=XMiddle,
YMiddle=YMiddle)
#########################
# 8.2 RainMapsLinksDaily#
#########################
# Date and time at which rainfall mapping starts:
DateTimeStartRainMaps <- "201109100800"
# Date and time at which rainfall mapping ends:
DateTimeEndRainMaps <- "201109110800"
# Run function RainMapsLinksDaily:
RainMapsLinksDaily(AlphaLinksDaily=AlphaLinksDaily,AlphaPlotLocation=AlphaPlotLocation,
AlphaPolygon=AlphaPolygon,AutDefineLegendTop=AutDefineLegendTop,BBoxOSMauto=BBoxOSMauto,
ColourLinks=ColourLinks,ColoursNumber=ColoursNumber,
ColourPlotLocation=ColourPlotLocation,ColourPlotLocationText=ColourPlotLocationText,
ColourScheme=ColourScheme,ColourType=ColourType,
ConversionDepthToIntensity=ConversionDepthToIntensity,
CoorSystemInputData=CoorSystemInputData,DateTimeEndRainMaps=DateTimeEndRainMaps,
DateTimeStartRainMaps=DateTimeStartRainMaps,ExtraDeg=ExtraDeg,ExtraText=ExtraText,
FigFileLinksDaily=FigFileLinksDaily,FigHeight=FigHeight,FigWidth=FigWidth,
FileGrid=FileGrid,FilePolygonsGrid=FilePolygonsGrid,FolderFigures=FolderFigures,
FolderRainMaps=FolderRainMaps,FolderRainEstimates=FolderRainEstimates,
FontFamily=FontFamily,GoogleLocDegSpecified=GoogleLocDegSpecified,
GoogleLocLat=GoogleLocLat,GoogleLocLon=GoogleLocLon,GoogleLocName=GoogleLocName,
GoogleLocNameSpecified=GoogleLocNameSpecified,GoogleMapType=GoogleMapType,
GoogleZoomlevel=GoogleZoomlevel,LabelAxisLat=LabelAxisLat,
LabelAxisLonGoogle=LabelAxisLonGoogle,LabelAxisLonOSM=LabelAxisLonOSM,
LabelAxisLonStamen=LabelAxisLonStamen,LatLocation=LatLocation,LatText=LatText,
LegendSize=LegendSize,LegendTitleLinksDaily=LegendTitleLinksDaily,LonLocation=LonLocation,LonText=LonText,
ManualScale=ManualScale,MapBackground=MapBackground,OSMBottom=OSMBottom,OSMLeft=OSMLeft,
OSMRight=OSMRight,OSMScale=OSMScale,OSMTop=OSMTop,OutputFileType=OutputFileType,PERIOD=PERIOD,
PlotLocation=PlotLocation,PixelBorderCol=PixelBorderCol,
PlotBelowScaleBottom=PlotBelowScaleBottom,PlotLocLinks=PlotLocLinks,
ScaleBottomDaily=ScaleBottomDaily,ScaleHigh=ScaleHigh,ScaleLow=ScaleLow,
ScaleTopDaily=ScaleTopDaily,SizeLinks=SizeLinks,SizePixelBorder=SizePixelBorder,
SizePlotLocation=SizePlotLocation,SizePlotTitle=SizePlotTitle,
StamenMapType=StamenMapType,StamenZoomlevel=StamenZoomlevel,
SymbolPlotLocation=SymbolPlotLocation,TIMESTEP=TIMESTEP,TitleLinks=TitleLinks,
XMiddle=XMiddle,YMiddle=YMiddle)
#############################
# 8.3 RainMapsRadarsTimeStep#
#############################
# Name and path of daily radar input file:
# NetCDF4 file for daily rainfall depths:
# Download from Climate4Impact using R (works at least for Linux):
# Paste contents of file "Radar5min/Climate4ImpactDownloadNETCDF5min.txt" in command shell.
# Path in NetCDF4 file with radar data:
PathRadarRainfallDepth <- "image1_image_data"
# Name of folder which contains 5-min radar rainfall files
FolderRadarRainMapsTimeStep <- "Radar5min"
# Run function RainMapsRadarsTimeStep:
RainMapsRadarsTimeStep(AlphaPlotLocation=AlphaPlotLocation,AlphaPolygon=AlphaPolygon,
AutDefineLegendTop=AutDefineLegendTop,BBoxOSMauto=BBoxOSMauto,
ColoursNumber=ColoursNumber,ColourPlotLocation=ColourPlotLocation,
ColourPlotLocationText=ColourPlotLocationText,ColourScheme=ColourScheme,
ColourType=ColourType,CoorSystemInputData=CoorSystemInputData,ExtraDeg=ExtraDeg,
ExtraText=ExtraText,FigFileRadarsTimeStep=FigFileRadarsTimeStep,FigHeight=FigHeight,
FigWidth=FigWidth,FileGrid=FileGrid,FilePolygonsGrid=FilePolygonsGrid,
FolderFigures=FolderFigures,FolderRadarRainMapsTimeStep=FolderRadarRainMapsTimeStep,
FontFamily=FontFamily,GoogleLocDegSpecified=GoogleLocDegSpecified,
GoogleLocLat=GoogleLocLat,GoogleLocLon=GoogleLocLon,GoogleLocName=GoogleLocName,
GoogleLocNameSpecified=GoogleLocNameSpecified,GoogleMapType=GoogleMapType,
GoogleZoomlevel=GoogleZoomlevel,LabelAxisLat=LabelAxisLat,
LabelAxisLonGoogle=LabelAxisLonGoogle,LabelAxisLonOSM=LabelAxisLonOSM,
LabelAxisLonStamen=LabelAxisLonStamen,LatLocation=LatLocation,LatText=LatText,
LegendSize=LegendSize,LegendTitleRadarsTimeStep=LegendTitleRadarsTimeStep,LonLocation=LonLocation,
LonText=LonText,ManualScale=ManualScale,MapBackground=MapBackground,
OSMBottom=OSMBottom,OSMLeft=OSMLeft,OSMRight=OSMRight,OSMScale=OSMScale,OSMTop=OSMTop,
OutputFileType=OutputFileType,PathRadarRainfallDepth=PathRadarRainfallDepth,PERIOD=PERIOD,
PlotLocation=PlotLocation,PixelBorderCol=PixelBorderCol,PlotBelowScaleBottom=PlotBelowScaleBottom,
ScaleBottomTimeStep=ScaleBottomTimeStep,ScaleHigh=ScaleHigh,ScaleLow=ScaleLow,
ScaleTopTimeStep=ScaleTopTimeStep,SizePixelBorder=SizePixelBorder,
SizePlotLocation=SizePlotLocation,SizePlotTitle=SizePlotTitle,
StamenMapType=StamenMapType,StamenZoomlevel=StamenZoomlevel,
SymbolPlotLocation=SymbolPlotLocation,TIMESTEP=TIMESTEP,TimeZone=TimeZone,
TitleRadars=TitleRadars,XMiddle=XMiddle,YMiddle=YMiddle)
##########################
# 8.4 RainMapsRadarsDaily#
##########################
DateMap <- "20110911"
# Name and path of daily radar input file:
# NetCDF4 file for daily rainfall depths:
# Download from Climate4Impact (works at least for Linux):
# path <- "http://opendap.knmi.nl/knmi/thredds/fileServer/radarprecipclim/RAD_NL25_RAC_MFBS_24H_NC/2011/09/RAD_NL25_RAC_MFBS_24H_201109110800.nc"
# download.file(path,"RAD_NL25_RAC_MFBS_24H_201109110800.nc",method="wget",quiet=F,mode="wb",cacheOK=T)
FileNameRadarDaily <- "RAD_NL25_RAC_MFBS_24H_201109110800.nc"
# Path in NetCDF4 file with radar data:
PathRadarRainfallDepth <- "image1_image_data"
# Name of folder which contains daily radar rainfall files
FolderRadarRainMapsDaily <- "Radar24H"
# Run function RainMapsRadarsDaily:
RainMapsRadarsDaily(AlphaPlotLocation=AlphaPlotLocation,AlphaPolygon=AlphaPolygon,
AutDefineLegendTop=AutDefineLegendTop,BBoxOSMauto=BBoxOSMauto,
ColoursNumber=ColoursNumber,ColourPlotLocation=ColourPlotLocation,
ColourPlotLocationText=ColourPlotLocationText,ColourScheme=ColourScheme,
ColourType=ColourType,CoorSystemInputData=CoorSystemInputData,DateMap=DateMap,
ExtraDeg=ExtraDeg,ExtraText=ExtraText,FigFileRadarsDaily=FigFileRadarsDaily,
FigHeight=FigHeight,FigWidth=FigWidth,FileGrid=FileGrid,
FileNameRadarDaily=FileNameRadarDaily,FilePolygonsGrid=FilePolygonsGrid,
FolderFigures=FolderFigures,FolderRadarRainMapsDaily=FolderRadarRainMapsDaily,
FontFamily=FontFamily,GoogleLocDegSpecified=GoogleLocDegSpecified,
GoogleLocLat=GoogleLocLat,GoogleLocLon=GoogleLocLon,GoogleLocName=GoogleLocName,
GoogleLocNameSpecified=GoogleLocNameSpecified,GoogleMapType=GoogleMapType,
GoogleZoomlevel=GoogleZoomlevel,LabelAxisLat=LabelAxisLat,
LabelAxisLonGoogle=LabelAxisLonGoogle,LabelAxisLonOSM=LabelAxisLonOSM,
LabelAxisLonStamen=LabelAxisLonStamen,LatLocation=LatLocation,LatText=LatText,
LegendSize=LegendSize,LegendTitleRadarsDaily=LegendTitleRadarsDaily,LonLocation=LonLocation,
LonText=LonText,ManualScale=ManualScale,MapBackground=MapBackground,
OSMBottom=OSMBottom,OSMLeft=OSMLeft,OSMRight=OSMRight,OSMScale=OSMScale,
OSMTop=OSMTop,OutputFileType=OutputFileType,PathRadarRainfallDepth=PathRadarRainfallDepth,
PERIOD=PERIOD,PlotLocation=PlotLocation,PixelBorderCol=PixelBorderCol,
PlotBelowScaleBottom=PlotBelowScaleBottom,ScaleBottomDaily=ScaleBottomDaily,
ScaleHigh=ScaleHigh,ScaleLow=ScaleLow,ScaleTopDaily=ScaleTopDaily,
SizePixelBorder=SizePixelBorder,SizePlotLocation=SizePlotLocation,
SizePlotTitle=SizePlotTitle,StamenMapType=StamenMapType,
StamenZoomlevel=StamenZoomlevel,SymbolPlotLocation=SymbolPlotLocation,
TimeZone=TimeZone,TitleRadars=TitleRadars,XMiddle=XMiddle,YMiddle=YMiddle)
#######################
# 8.5 ReadRainLocation#
#######################
# Load (daily) radar rainfall data:
ncFILE <- nc_open(paste(FolderRadarRainMapsDaily,"/",FileNameRadarDaily,sep=""),verbose=F)
dataf <- c(ncvar_get(ncFILE,varid="image1_image_data"))
dataf <- dataf[!is.na(dataf)]
nc_close(ncFILE)
# OR load e.g. 15-min link data:
# Duration of time interval of sampling strategy (min):
TIMESTEP <- 15
# Conversion factor from rainfall intensity (mm/h) to depth (mm):
MinutesHour <- 60
ConversionIntensityToDepth <- TIMESTEP/MinutesHour
# Location of link data:
FolderRainMaps <- paste("RainMapsLinks",TIMESTEP,"min",sep="")
# Make list of input files:
Files <- list.files(path = FolderRainMaps, all.files=FALSE,
full.names=TRUE, recursive=FALSE, pattern="linkmap")
# Select date and time for which links are to be plotted:
DateTime <- "201109110200"
condTime <- grep(DateTime,Files)
# Select file:
Filename <- Files[condTime]
# Read data from input file:
dataf <- read.table(Filename,header=TRUE)
dataf <- ConversionIntensityToDepth * dataf[,1]
# Location for which rainfall depth is to be extracted:
Lon <- 5.1214201
Lat <- 52.0907374
# Run function ReadRainLocation:
ReadRainLocation(CoorSystemInputData=CoorSystemInputData,dataf=dataf,FileGrid=FileGrid,Lat=Lat,Lon=Lon,XMiddle=XMiddle,YMiddle=YMiddle)
# R provides tools to extract the street name and municipality for a location:
revgeocode(c(Lon,Lat))
# If you would like to know the rainfall depth for a street name and municipality, R can provide you with the location in decimal degrees:
# Give latitude and longitude for location known by street name and municipality:
geocode("Domplein 1, Utrecht")
# Please note that revgeocode & geocode only work when Google API key has been obtained.
#######################
# 9. PlotLinkLocations#
#######################
# Duration of time interval of sampling strategy (min):
TIMESTEP <- 15
# Location of link data:
FolderRainEstimates <- paste("LinkPathRainDepths",TIMESTEP,"min",sep="")
# Make list of input files:
Files <- list.files(path = FolderRainEstimates, all.files=FALSE,
full.names=TRUE, recursive=FALSE, pattern="linkdata")
# Select date and time for which links are to be plotted:
DateTime <- "201109110200"
condTime <- grep(DateTime,Files)
# Select file:
Filename <- Files[condTime]
# Read data from input file:
dataf <- read.table(Filename,header=TRUE)
# Make figure smaller (if whole Netherlands is plotted):
FigWidth <- 1600
# Plot link locations on a map:
PlotLinkLocations(AlphaLinkLocations=AlphaLinkLocations,BBoxOSMauto=BBoxOSMauto,
OSMBottom=OSMBottom,ColourLinks=ColourLinks,ColourType=ColourType,dataf=dataf,
DateTime=DateTime,ExtraTextLinkLocations=ExtraTextLinkLocations,
FigFileLinkLocations=FigFileLinkLocations,FigHeight=FigHeight,
FigWidth=FigWidth,FilePolygonsGrid=FilePolygonsGrid,FolderFigures=FolderFigures,
FontFamily=FontFamily,GoogleLocDegSpecified=GoogleLocDegSpecified,
GoogleLocLat=GoogleLocLat,GoogleLocLon=GoogleLocLon,GoogleLocName=GoogleLocName,
GoogleLocNameSpecified=GoogleLocNameSpecified,GoogleMapType=GoogleMapType,
GoogleZoomlevel=GoogleZoomlevel,LabelAxisLat=LabelAxisLat,
LabelAxisLonGoogle=LabelAxisLonGoogle,LabelAxisLonOSM=LabelAxisLonOSM,
LabelAxisLonStamen=LabelAxisLonStamen,MapBackground=MapBackground,OSMLeft=OSMLeft,
OSMRight=OSMRight,OSMScale=OSMScale,OSMTop=OSMTop,OutputFileType=OutputFileType,
SizeLinks=SizeLinks,SizePlotTitle=SizePlotTitle,StamenMapType=StamenMapType,
StamenZoomlevel=StamenZoomlevel,TitleLinkLocations=TitleLinkLocations)
####################
# 10. Plot topology#
####################
Topology(Data=DataPreprocessed,CoorSystemInputData=NULL,FigNameBarplotAngle=FigNameBarplotAngle,FigNameBarplotFrequency=FigNameBarplotFrequency,
FigNameBarplotPathLength=FigNameBarplotPathLength,FigNameFrequencyVsPathLength=FigNameFrequencyVsPathLength,
FigNameScatterdensityplotFrequencyVsPathLength=FigNameScatterdensityplotFrequencyVsPathLength,Maxf=Maxf,Minf=Minf,
MaxL=MaxL,MinL=MinL,Rmean=Rmean,Stepf=Stepf,StepL=StepL)
# Note that Data object must be preprocessed if Rmean is provided.
#############################
# 11. Plot data availability#
#############################
DataAvailability(Data=DataPreprocessed,cex.axis=cex.axis,cex.lab=cex.lab,FigNameBarplotAvailabilityLinks=FigNameBarplotAvailabilityLinks,
FigNameBarplotAvailabilityLinkPaths=FigNameBarplotAvailabilityLinkPaths,
FigNameTimeseriesAvailability=FigNameTimeseriesAvailability,ps=ps,Rmean=Rmean,TimeZone=TimeZone)
# Note that Data must be preprocessed, because Rmean is used.
# Another remark concerns the function "DataAvailability". In the figure showing the time series of data availability, the first period reveals 0 availability.
# This is due to the spin-up time of RAINLINK. This period is also taken into account in the computations of data availability. To prevent his, the first period
# should be removed from the Data and Rmean object as provided to function "DataAvailability".
##########################
# 12. Compute path length#
##########################
PathLength(XStart=Linkdata$XStart,XEnd=Linkdata$XEnd,YStart=Linkdata$YStart,YEnd=Linkdata$YEnd)
| /Run.R | no_license | ludodiender/RAINLINK | R | false | false | 25,480 | r | ## The RAINLINK package. Retrieval algorithm for rainfall mapping from microwave links
## in a cellular communication network.
##
## Version 1.21
## Copyright (C) 2021 Aart Overeem
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
## R program 'Run.R'.
## SCRIPT FOR RAINFALL ESTIMATION USING MICROWAVE LINKS.
## source("Run.R")
## Run this script by pasting the line above (source(...)) or by pasting parts of the script into the R shell.
# Note that it is not necessarily a problem if a function argument is not supplied to the function. If the
# function argument is not used, then there is no problem. Only be aware that you should use e.g.
# MaxFrequency=MaxFrequency. I.e. if you only supply MaxFrequency and the function argument before
# MaxFrequency is missing, than the function will not execute properly.
#############################################################
# 0. Load R libraries, parameter values, and other settings.#
# This also loads the RAINLINK package. #
#############################################################
source("Config.R")
# If the time zone of the employed microwave link dataset is not the same as the (local) time zone used by R on your computer, set the time zone of the microwave link dataset:
# (this is important for functions RefLevelMinMaxRSL, WetDryNearbyLinkApMinMaxRSL and Interpolation):
Sys.setenv(TZ='UTC')
# Otherwise RAINLINK can derive a wrong time interval length due to going to or from daylight saving time (DST). Timing of DST may be different between time zones, or one time zone may not have a change to/from DST.
############################
# 1. PreprocessingMinMaxRSL#
############################
# Load example data:
data(Linkdata)
# For each unique link identifier a time interval is removed if it contains more than one record. This is done by the function "PreprocessingMinMaxRSL".
# In case the records from a certain time interval and unique link identifier are the same, this would throw away data from the entire interval for this identifier,
# whereas the information would be useful. To check how often this occurs:
# length(Linkdata[,1])
# length(unique(Linkdata)[,1])
# To avoid this:
Linkdata <- unique(Linkdata)
# Add column with polarization if this column is not supplied in the link data:
if ("Polarization" %in% names(Linkdata)==FALSE)
{
Linkdata$Polarization <- rep(NA,nrow(Linkdata))
}
# When no information on polarization is provided, the above code creates a column of NA for Polarization. In the function "RainRetrievalMinMaxRSL.R" links with
# NA values for polarization are processed with a & b values determined for vertically polarized signals.
# If information on polarization of links is available, use H for horizontally polarized & V for vertically polarized in Linkdata$Polarization.
# H, V & NA may occur in the same Linkdata file.
# Run R function:
StartTime <- proc.time()
DataPreprocessed <- PreprocessingMinMaxRSL(Data=Linkdata,MaxFrequency=MaxFrequency,MinFrequency=MinFrequency,verbose=TRUE)
cat(sprintf("Finished. (%.1f seconds)\n",round((proc.time()-StartTime)[3],digits=1)))
############################################
# 2. WetDryNearbyLinkApMinMaxRSL (OPTIONAL)#
############################################
# Run R function:
StartTime <- proc.time()
WetDry <- WetDryNearbyLinkApMinMaxRSL(Data=DataPreprocessed,CoorSystemInputData=NULL,
MinHoursPmin=MinHoursPmin,PeriodHoursPmin=PeriodHoursPmin,Radius=Radius,Step8=Step8,
ThresholdMedian=ThresholdMedian,ThresholdMedianL=ThresholdMedianL,ThresholdNumberLinks=ThresholdNumberLinks,
ThresholdWetDry=ThresholdWetDry)
cat(sprintf("Finished. (%.1f seconds)\n",round((proc.time()-StartTime)[3],digits=1)))
#######################
# 3. RefLevelMinMaxRSL#
#######################
# Run R function:
StartTime <- proc.time()
Pref <- RefLevelMinMaxRSL(Data=DataPreprocessed,Dry=WetDry$Dry,HoursRefLevel=HoursRefLevel,PeriodHoursRefLevel=PeriodHoursRefLevel)
cat(sprintf("Finished. (%.1f seconds)\n",round((proc.time()-StartTime)[3],digits=1)))
# If wet-dry classification (function WetDryNearbyLinkApMinMaxRSL) has not been applied, run the R function as follows:
StartTime <- proc.time()
Pref <- RefLevelMinMaxRSL(Data=DataPreprocessed,Dry=NULL,HoursRefLevel=HoursRefLevel,PeriodHoursRefLevel=PeriodHoursRefLevel)
cat(sprintf("Finished. (%.1f seconds)\n",round((proc.time()-StartTime)[3],digits=1)))
#############################################################################################################
# 4. OutlierFilterMinMax (OPTIONAL) - Can only be applied when WetDryNearbyLinkApMinMaxRSL has been applied.#
#############################################################################################################
# Run R function:
DataOutlierFiltered <- OutlierFilterMinMaxRSL(Data=DataPreprocessed,F=WetDry$F,FilterThreshold=FilterThreshold)
######################
# 5. CorrectMinMaxRSL#
######################
# Run R function:
Pcor <- CorrectMinMaxRSL(Data=DataOutlierFiltered,Dry=WetDry$Dry,Pref=Pref)
# If wet-dry classification (function WetDryNearbyLinkApMinMaxRSL) has not been applied, run the R function as follows:
Pcor <- CorrectMinMaxRSL(Data=DataPreprocessed,Dry=NULL,Pref=Pref)
############################
# 6. RainRetrievalMinMaxRSL#
############################
kRPowerLawDataH <- read.table(FileRainRetrHorizontal)
colnames(kRPowerLawDataH) <- c("f", "a", "b")
kRPowerLawDataV <- read.table(FileRainRetrVertical)
colnames(kRPowerLawDataV) <- c("f", "a", "b")
# Run R function:
StartTime <- proc.time()
Rmean <- RainRetrievalMinMaxRSL(Aa=Aa,alpha=alpha,Data=DataOutlierFiltered,kRPowerLawDataH=kRPowerLawDataH,kRPowerLawDataV=kRPowerLawDataV,PmaxCor=Pcor$PmaxCor,PminCor=Pcor$PminCor,Pref=Pref)
cat(sprintf("Finished. (%.1f seconds)\n",round((proc.time()-StartTime)[3],digits=1)))
# If wet-dry classification (function WetDryNearbyLinkApMinMaxRSL) has not been applied, run the R function as follows:
StartTime <- proc.time()
Rmean <- RainRetrievalMinMaxRSL(Aa=Aa,alpha=alpha,Data=DataPreprocessed,kRPowerLawDataH=kRPowerLawDataH,kRPowerLawDataV=kRPowerLawDataV,PmaxCor=Pcor$PmaxCor,PminCor=Pcor$PminCor,Pref=Pref)
cat(sprintf("Finished. (%.1f seconds)\n",round((proc.time()-StartTime)[3],digits=1)))
# Write path-average rainfall data to files:
# Duration of time interval of sampling strategy (min):
TIMESTEP <- 15
# Location of output link data:
FolderRainEstimates <- paste("LinkPathRainDepths",TIMESTEP,"min",sep="")
ToFile = TRUE
if (ToFile)
{
# Create directory for output files:
if(!dir.exists(FolderRainEstimates)){ dir.create(FolderRainEstimates) }
# Write output to file
ID <- unique(DataPreprocessed$ID)
t <- sort(unique(DataPreprocessed$DateTime))
t_sec <- as.numeric(as.POSIXct(as.character(t), format = "%Y%m%d%H%M"))
dt <- min(diff(t_sec))
for (i in 1 : length(t))
{
ind <- which(DataPreprocessed$DateTime == t[i])
int_data <- data.frame(ID = DataPreprocessed$ID[ind], RainfallDepthPath = Rmean[ind] * dt / 3600,
PathLength = DataPreprocessed$PathLength[ind], XStart = DataPreprocessed$XStart[ind],
YStart = DataPreprocessed$YStart[ind], XEnd = DataPreprocessed$XEnd[ind],
YEnd = DataPreprocessed$YEnd[ind], IntervalNumber = rep(i, length(ind)),
Frequency = DataPreprocessed$Frequency[ind])
Filename <- paste(FolderRainEstimates, "/linkdata_", t[i], ".dat", sep="")
# Using na.omit removes all rows with at least 1 NA:
write.table(na.omit(int_data), Filename, row.names = FALSE, col.names = TRUE, append = FALSE, quote = FALSE)
}
}
# Note that the output files contain rainfall depths (mm). If these data are to be used for the interpolation, they must first be read ("Interpolation.R" does not read these files).
# Using the data for "Interpolation.R" requires a conversion from rainfall depth (mm) to rainfall intensity (mm/h).
###################
# 7. Interpolation#
###################
# Read grid onto which data are interpolated
RainGrid <- read.table(FileGrid, header = TRUE, sep=",")
# Duration of time interval of sampling strategy (min):
TIMESTEP <- 15
# Location of output link data:
FolderRainMaps <- paste("RainMapsLinks",TIMESTEP,"min",sep="")
# Run R function:
StartTime <- proc.time()
Interpolation(Data=DataPreprocessed,CoorSystemInputData=NULL,idp=idp,IntpMethod=IntpMethod,nmax=nmax,
NUGGET=NUGGET,RANGE=RANGE,RainGrid=RainGrid,Rmean=Rmean,SILL=SILL,Variogram=Variogram,OutputDir=FolderRainMaps)
cat(sprintf("Finished. (%.1f seconds)\n",round((proc.time()-StartTime)[3],digits=1)))
###################
# 8. Visualisation#
###################
# It seems that mapping with OpenStreetMap (``get_openstreetmap'') is no langer supported. Google Maps is also not supported anymore, unless you obtain a Google API key.
# The employed ggmap function also allows to use Stamen Maps. This functionality has been added to RAINLINK's visualisation functions.
# Executing the "RainMaps...R" functions can often give the error below for Google Maps, which is
# caused by the Google server. Apparently, maps have been downloaded too often. Just try again (and again).
# Error in data.frame(ll.lat = ll[1], ll.lon = ll[2], ur.lat = ur[1], ur.lon = ur[2]) :
# arguments imply differing number of rows: 0, 1
# In addition: Warning message:
# geocode failed with status OVER_QUERY_LIMIT, location = "De Eemhof, Zeewolde"
# Executing revgeocode(c(Lon,Lat)) can also give an error, which is probably also related to obtaining the map from the Google Maps server. Just try again (and again):
# Warning message:
# In revgeocode(c(LonLocation, LatLocation)) :
# reverse geocode failed - bad location? location = "4.85"reverse geocode failed - bad location? location = "52.39"
############################
# 8.1 RainMapsLinksTimeStep#
############################
# Date and time at which rainfall mapping starts:
DateTimeStartRainMaps <- "201109102045"
# Date and time at which rainfall mapping ends:
DateTimeEndRainMaps <- "201109102045"
# Both should be "201109102045" to reproduce Figure 5 from AMT manuscript.
# Both should be "201109102015" to reproduce Figure 7 from AMT manuscript.
# Run function RainMapsLinksTimeStep:
RainMapsLinksTimeStep(AlphaLinksTimeStep=AlphaLinksTimeStep,
AlphaPlotLocation=AlphaPlotLocation,AlphaPolygon=AlphaPolygon,
AutDefineLegendTop=AutDefineLegendTop,BBoxOSMauto=BBoxOSMauto,ColourLinks=ColourLinks,
ColoursNumber=ColoursNumber,ColourPlotLocation=ColourPlotLocation,
ColourPlotLocationText=ColourPlotLocationText,ColourScheme=ColourScheme,
ColourType=ColourType,ConversionDepthToIntensity=ConversionDepthToIntensity,
CoorSystemInputData=CoorSystemInputData,DateTimeEndRainMaps=DateTimeEndRainMaps,
DateTimeStartRainMaps=DateTimeStartRainMaps,ExtraDeg=ExtraDeg,ExtraText=ExtraText,
FigFileLinksTimeStep=FigFileLinksTimeStep,FigHeight=FigHeight,FigWidth=FigWidth,
FileGrid=FileGrid,FilePolygonsGrid=FilePolygonsGrid,FolderFigures=FolderFigures,
FolderRainMaps=FolderRainMaps,FolderRainEstimates=FolderRainEstimates,
FontFamily=FontFamily,GoogleLocDegSpecified=GoogleLocDegSpecified,
GoogleLocLat=GoogleLocLat,GoogleLocLon=GoogleLocLon,GoogleLocName=GoogleLocName,
GoogleLocNameSpecified=GoogleLocNameSpecified,GoogleMapType=GoogleMapType,
GoogleZoomlevel=GoogleZoomlevel,LabelAxisLat=LabelAxisLat,
LabelAxisLonGoogle=LabelAxisLonGoogle,LabelAxisLonOSM=LabelAxisLonOSM,
LabelAxisLonStamen=LabelAxisLonStamen,LatLocation=LatLocation,LatText=LatText,
LegendSize=LegendSize,LegendTitleLinksTimeStep=LegendTitleLinksTimeStep,LonLocation=LonLocation,
LonText=LonText,ManualScale=ManualScale,MapBackground=MapBackground,OSMBottom=OSMBottom,
OSMLeft=OSMLeft,OSMRight=OSMRight,OSMScale=OSMScale,OSMTop=OSMTop,OutputFileType=OutputFileType,
PlotLocation=PlotLocation,PixelBorderCol=PixelBorderCol,
PlotBelowScaleBottom=PlotBelowScaleBottom,PlotLocLinks=PlotLocLinks,
ScaleBottomTimeStep=ScaleBottomTimeStep,ScaleHigh=ScaleHigh,ScaleLow=ScaleLow,
ScaleTopTimeStep=ScaleTopTimeStep,SizeLinks=SizeLinks,SizePixelBorder=SizePixelBorder,
SizePlotLocation=SizePlotLocation,SizePlotTitle=SizePlotTitle,
StamenMapType=StamenMapType,StamenZoomlevel=StamenZoomlevel,
SymbolPlotLocation=SymbolPlotLocation,TitleLinks=TitleLinks,XMiddle=XMiddle,
YMiddle=YMiddle)
#########################
# 8.2 RainMapsLinksDaily#
#########################
# Date and time at which rainfall mapping starts:
DateTimeStartRainMaps <- "201109100800"
# Date and time at which rainfall mapping ends:
DateTimeEndRainMaps <- "201109110800"
# Run function RainMapsLinksDaily:
RainMapsLinksDaily(AlphaLinksDaily=AlphaLinksDaily,AlphaPlotLocation=AlphaPlotLocation,
AlphaPolygon=AlphaPolygon,AutDefineLegendTop=AutDefineLegendTop,BBoxOSMauto=BBoxOSMauto,
ColourLinks=ColourLinks,ColoursNumber=ColoursNumber,
ColourPlotLocation=ColourPlotLocation,ColourPlotLocationText=ColourPlotLocationText,
ColourScheme=ColourScheme,ColourType=ColourType,
ConversionDepthToIntensity=ConversionDepthToIntensity,
CoorSystemInputData=CoorSystemInputData,DateTimeEndRainMaps=DateTimeEndRainMaps,
DateTimeStartRainMaps=DateTimeStartRainMaps,ExtraDeg=ExtraDeg,ExtraText=ExtraText,
FigFileLinksDaily=FigFileLinksDaily,FigHeight=FigHeight,FigWidth=FigWidth,
FileGrid=FileGrid,FilePolygonsGrid=FilePolygonsGrid,FolderFigures=FolderFigures,
FolderRainMaps=FolderRainMaps,FolderRainEstimates=FolderRainEstimates,
FontFamily=FontFamily,GoogleLocDegSpecified=GoogleLocDegSpecified,
GoogleLocLat=GoogleLocLat,GoogleLocLon=GoogleLocLon,GoogleLocName=GoogleLocName,
GoogleLocNameSpecified=GoogleLocNameSpecified,GoogleMapType=GoogleMapType,
GoogleZoomlevel=GoogleZoomlevel,LabelAxisLat=LabelAxisLat,
LabelAxisLonGoogle=LabelAxisLonGoogle,LabelAxisLonOSM=LabelAxisLonOSM,
LabelAxisLonStamen=LabelAxisLonStamen,LatLocation=LatLocation,LatText=LatText,
LegendSize=LegendSize,LegendTitleLinksDaily=LegendTitleLinksDaily,LonLocation=LonLocation,LonText=LonText,
ManualScale=ManualScale,MapBackground=MapBackground,OSMBottom=OSMBottom,OSMLeft=OSMLeft,
OSMRight=OSMRight,OSMScale=OSMScale,OSMTop=OSMTop,OutputFileType=OutputFileType,PERIOD=PERIOD,
PlotLocation=PlotLocation,PixelBorderCol=PixelBorderCol,
PlotBelowScaleBottom=PlotBelowScaleBottom,PlotLocLinks=PlotLocLinks,
ScaleBottomDaily=ScaleBottomDaily,ScaleHigh=ScaleHigh,ScaleLow=ScaleLow,
ScaleTopDaily=ScaleTopDaily,SizeLinks=SizeLinks,SizePixelBorder=SizePixelBorder,
SizePlotLocation=SizePlotLocation,SizePlotTitle=SizePlotTitle,
StamenMapType=StamenMapType,StamenZoomlevel=StamenZoomlevel,
SymbolPlotLocation=SymbolPlotLocation,TIMESTEP=TIMESTEP,TitleLinks=TitleLinks,
XMiddle=XMiddle,YMiddle=YMiddle)
#############################
# 8.3 RainMapsRadarsTimeStep#
#############################
# Name and path of daily radar input file:
# NetCDF4 file for daily rainfall depths:
# Download from Climate4Impact using R (works at least for Linux):
# Paste contents of file "Radar5min/Climate4ImpactDownloadNETCDF5min.txt" in command shell.
# Path in NetCDF4 file with radar data:
PathRadarRainfallDepth <- "image1_image_data"
# Name of folder which contains 5-min radar rainfall files
FolderRadarRainMapsTimeStep <- "Radar5min"
# Run function RainMapsRadarsTimeStep:
RainMapsRadarsTimeStep(AlphaPlotLocation=AlphaPlotLocation,AlphaPolygon=AlphaPolygon,
AutDefineLegendTop=AutDefineLegendTop,BBoxOSMauto=BBoxOSMauto,
ColoursNumber=ColoursNumber,ColourPlotLocation=ColourPlotLocation,
ColourPlotLocationText=ColourPlotLocationText,ColourScheme=ColourScheme,
ColourType=ColourType,CoorSystemInputData=CoorSystemInputData,ExtraDeg=ExtraDeg,
ExtraText=ExtraText,FigFileRadarsTimeStep=FigFileRadarsTimeStep,FigHeight=FigHeight,
FigWidth=FigWidth,FileGrid=FileGrid,FilePolygonsGrid=FilePolygonsGrid,
FolderFigures=FolderFigures,FolderRadarRainMapsTimeStep=FolderRadarRainMapsTimeStep,
FontFamily=FontFamily,GoogleLocDegSpecified=GoogleLocDegSpecified,
GoogleLocLat=GoogleLocLat,GoogleLocLon=GoogleLocLon,GoogleLocName=GoogleLocName,
GoogleLocNameSpecified=GoogleLocNameSpecified,GoogleMapType=GoogleMapType,
GoogleZoomlevel=GoogleZoomlevel,LabelAxisLat=LabelAxisLat,
LabelAxisLonGoogle=LabelAxisLonGoogle,LabelAxisLonOSM=LabelAxisLonOSM,
LabelAxisLonStamen=LabelAxisLonStamen,LatLocation=LatLocation,LatText=LatText,
LegendSize=LegendSize,LegendTitleRadarsTimeStep=LegendTitleRadarsTimeStep,LonLocation=LonLocation,
LonText=LonText,ManualScale=ManualScale,MapBackground=MapBackground,
OSMBottom=OSMBottom,OSMLeft=OSMLeft,OSMRight=OSMRight,OSMScale=OSMScale,OSMTop=OSMTop,
OutputFileType=OutputFileType,PathRadarRainfallDepth=PathRadarRainfallDepth,PERIOD=PERIOD,
PlotLocation=PlotLocation,PixelBorderCol=PixelBorderCol,PlotBelowScaleBottom=PlotBelowScaleBottom,
ScaleBottomTimeStep=ScaleBottomTimeStep,ScaleHigh=ScaleHigh,ScaleLow=ScaleLow,
ScaleTopTimeStep=ScaleTopTimeStep,SizePixelBorder=SizePixelBorder,
SizePlotLocation=SizePlotLocation,SizePlotTitle=SizePlotTitle,
StamenMapType=StamenMapType,StamenZoomlevel=StamenZoomlevel,
SymbolPlotLocation=SymbolPlotLocation,TIMESTEP=TIMESTEP,TimeZone=TimeZone,
TitleRadars=TitleRadars,XMiddle=XMiddle,YMiddle=YMiddle)
##########################
# 8.4 RainMapsRadarsDaily#
##########################
DateMap <- "20110911"
# Name and path of daily radar input file:
# NetCDF4 file for daily rainfall depths:
# Download from Climate4Impact (works at least for Linux):
# path <- "http://opendap.knmi.nl/knmi/thredds/fileServer/radarprecipclim/RAD_NL25_RAC_MFBS_24H_NC/2011/09/RAD_NL25_RAC_MFBS_24H_201109110800.nc"
# download.file(path,"RAD_NL25_RAC_MFBS_24H_201109110800.nc",method="wget",quiet=F,mode="wb",cacheOK=T)
FileNameRadarDaily <- "RAD_NL25_RAC_MFBS_24H_201109110800.nc"
# Path in NetCDF4 file with radar data:
PathRadarRainfallDepth <- "image1_image_data"
# Name of folder which contains daily radar rainfall files
FolderRadarRainMapsDaily <- "Radar24H"
# Run function RainMapsRadarsDaily:
RainMapsRadarsDaily(AlphaPlotLocation=AlphaPlotLocation,AlphaPolygon=AlphaPolygon,
AutDefineLegendTop=AutDefineLegendTop,BBoxOSMauto=BBoxOSMauto,
ColoursNumber=ColoursNumber,ColourPlotLocation=ColourPlotLocation,
ColourPlotLocationText=ColourPlotLocationText,ColourScheme=ColourScheme,
ColourType=ColourType,CoorSystemInputData=CoorSystemInputData,DateMap=DateMap,
ExtraDeg=ExtraDeg,ExtraText=ExtraText,FigFileRadarsDaily=FigFileRadarsDaily,
FigHeight=FigHeight,FigWidth=FigWidth,FileGrid=FileGrid,
FileNameRadarDaily=FileNameRadarDaily,FilePolygonsGrid=FilePolygonsGrid,
FolderFigures=FolderFigures,FolderRadarRainMapsDaily=FolderRadarRainMapsDaily,
FontFamily=FontFamily,GoogleLocDegSpecified=GoogleLocDegSpecified,
GoogleLocLat=GoogleLocLat,GoogleLocLon=GoogleLocLon,GoogleLocName=GoogleLocName,
GoogleLocNameSpecified=GoogleLocNameSpecified,GoogleMapType=GoogleMapType,
GoogleZoomlevel=GoogleZoomlevel,LabelAxisLat=LabelAxisLat,
LabelAxisLonGoogle=LabelAxisLonGoogle,LabelAxisLonOSM=LabelAxisLonOSM,
LabelAxisLonStamen=LabelAxisLonStamen,LatLocation=LatLocation,LatText=LatText,
LegendSize=LegendSize,LegendTitleRadarsDaily=LegendTitleRadarsDaily,LonLocation=LonLocation,
LonText=LonText,ManualScale=ManualScale,MapBackground=MapBackground,
OSMBottom=OSMBottom,OSMLeft=OSMLeft,OSMRight=OSMRight,OSMScale=OSMScale,
OSMTop=OSMTop,OutputFileType=OutputFileType,PathRadarRainfallDepth=PathRadarRainfallDepth,
PERIOD=PERIOD,PlotLocation=PlotLocation,PixelBorderCol=PixelBorderCol,
PlotBelowScaleBottom=PlotBelowScaleBottom,ScaleBottomDaily=ScaleBottomDaily,
ScaleHigh=ScaleHigh,ScaleLow=ScaleLow,ScaleTopDaily=ScaleTopDaily,
SizePixelBorder=SizePixelBorder,SizePlotLocation=SizePlotLocation,
SizePlotTitle=SizePlotTitle,StamenMapType=StamenMapType,
StamenZoomlevel=StamenZoomlevel,SymbolPlotLocation=SymbolPlotLocation,
TimeZone=TimeZone,TitleRadars=TitleRadars,XMiddle=XMiddle,YMiddle=YMiddle)
#######################
# 8.5 ReadRainLocation#
#######################
# Load (daily) radar rainfall data:
ncFILE <- nc_open(paste(FolderRadarRainMapsDaily,"/",FileNameRadarDaily,sep=""),verbose=F)
dataf <- c(ncvar_get(ncFILE,varid="image1_image_data"))
dataf <- dataf[!is.na(dataf)]
nc_close(ncFILE)
# OR load e.g. 15-min link data:
# Duration of time interval of sampling strategy (min):
TIMESTEP <- 15
# Conversion factor from rainfall intensity (mm/h) to depth (mm):
MinutesHour <- 60
ConversionIntensityToDepth <- TIMESTEP/MinutesHour
# Location of link data:
FolderRainMaps <- paste("RainMapsLinks",TIMESTEP,"min",sep="")
# Make list of input files:
Files <- list.files(path = FolderRainMaps, all.files=FALSE,
full.names=TRUE, recursive=FALSE, pattern="linkmap")
# Select date and time for which links are to be plotted:
DateTime <- "201109110200"
condTime <- grep(DateTime,Files)
# Select file:
Filename <- Files[condTime]
# Read data from input file:
dataf <- read.table(Filename,header=TRUE)
dataf <- ConversionIntensityToDepth * dataf[,1]
# Location for which rainfall depth is to be extracted:
Lon <- 5.1214201
Lat <- 52.0907374
# Run function ReadRainLocation:
ReadRainLocation(CoorSystemInputData=CoorSystemInputData,dataf=dataf,FileGrid=FileGrid,Lat=Lat,Lon=Lon,XMiddle=XMiddle,YMiddle=YMiddle)
# R provides tools to extract the street name and municipality for a location:
revgeocode(c(Lon,Lat))
# If you would like to know the rainfall depth for a street name and municipality, R can provide you with the location in decimal degrees:
# Give latitude and longitude for location known by street name and municipality:
geocode("Domplein 1, Utrecht")
# Please note that revgeocode & geocode only work when Google API key has been obtained.
#######################
# 9. PlotLinkLocations#
#######################
# Duration of time interval of sampling strategy (min):
TIMESTEP <- 15
# Location of link data:
FolderRainEstimates <- paste("LinkPathRainDepths",TIMESTEP,"min",sep="")
# Make list of input files:
Files <- list.files(path = FolderRainEstimates, all.files=FALSE,
full.names=TRUE, recursive=FALSE, pattern="linkdata")
# Select date and time for which links are to be plotted:
DateTime <- "201109110200"
condTime <- grep(DateTime,Files)
# Select file:
Filename <- Files[condTime]
# Read data from input file:
dataf <- read.table(Filename,header=TRUE)
# Make figure smaller (if whole Netherlands is plotted):
FigWidth <- 1600
# Plot link locations on a map:
PlotLinkLocations(AlphaLinkLocations=AlphaLinkLocations,BBoxOSMauto=BBoxOSMauto,
OSMBottom=OSMBottom,ColourLinks=ColourLinks,ColourType=ColourType,dataf=dataf,
DateTime=DateTime,ExtraTextLinkLocations=ExtraTextLinkLocations,
FigFileLinkLocations=FigFileLinkLocations,FigHeight=FigHeight,
FigWidth=FigWidth,FilePolygonsGrid=FilePolygonsGrid,FolderFigures=FolderFigures,
FontFamily=FontFamily,GoogleLocDegSpecified=GoogleLocDegSpecified,
GoogleLocLat=GoogleLocLat,GoogleLocLon=GoogleLocLon,GoogleLocName=GoogleLocName,
GoogleLocNameSpecified=GoogleLocNameSpecified,GoogleMapType=GoogleMapType,
GoogleZoomlevel=GoogleZoomlevel,LabelAxisLat=LabelAxisLat,
LabelAxisLonGoogle=LabelAxisLonGoogle,LabelAxisLonOSM=LabelAxisLonOSM,
LabelAxisLonStamen=LabelAxisLonStamen,MapBackground=MapBackground,OSMLeft=OSMLeft,
OSMRight=OSMRight,OSMScale=OSMScale,OSMTop=OSMTop,OutputFileType=OutputFileType,
SizeLinks=SizeLinks,SizePlotTitle=SizePlotTitle,StamenMapType=StamenMapType,
StamenZoomlevel=StamenZoomlevel,TitleLinkLocations=TitleLinkLocations)
####################
# 10. Plot topology#
####################
Topology(Data=DataPreprocessed,CoorSystemInputData=NULL,FigNameBarplotAngle=FigNameBarplotAngle,FigNameBarplotFrequency=FigNameBarplotFrequency,
FigNameBarplotPathLength=FigNameBarplotPathLength,FigNameFrequencyVsPathLength=FigNameFrequencyVsPathLength,
FigNameScatterdensityplotFrequencyVsPathLength=FigNameScatterdensityplotFrequencyVsPathLength,Maxf=Maxf,Minf=Minf,
MaxL=MaxL,MinL=MinL,Rmean=Rmean,Stepf=Stepf,StepL=StepL)
# Note that Data object must be preprocessed if Rmean is provided.
#############################
# 11. Plot data availability#
#############################
DataAvailability(Data=DataPreprocessed,cex.axis=cex.axis,cex.lab=cex.lab,FigNameBarplotAvailabilityLinks=FigNameBarplotAvailabilityLinks,
FigNameBarplotAvailabilityLinkPaths=FigNameBarplotAvailabilityLinkPaths,
FigNameTimeseriesAvailability=FigNameTimeseriesAvailability,ps=ps,Rmean=Rmean,TimeZone=TimeZone)
# Note that Data must be preprocessed, because Rmean is used.
# Another remark concerns the function "DataAvailability". In the figure showing the time series of data availability, the first period reveals 0 availability.
# This is due to the spin-up time of RAINLINK. This period is also taken into account in the computations of data availability. To prevent his, the first period
# should be removed from the Data and Rmean object as provided to function "DataAvailability".
##########################
# 12. Compute path length#
##########################
PathLength(XStart=Linkdata$XStart,XEnd=Linkdata$XEnd,YStart=Linkdata$YStart,YEnd=Linkdata$YEnd)
|
library(ffbase)
### Name: within.ffdf
### Title: Evaluate an expression in a ffdf data environment
### Aliases: within.ffdf
### ** Examples
ffdat <- as.ffdf(data.frame(x=1:10, y=10:1))
# add z to the ffdat
within(ffdat, {z <- x+y})
| /data/genthat_extracted_code/ffbase/examples/within.ffdf.Rd.R | no_license | surayaaramli/typeRrh | R | false | false | 240 | r | library(ffbase)
### Name: within.ffdf
### Title: Evaluate an expression in a ffdf data environment
### Aliases: within.ffdf
### ** Examples
ffdat <- as.ffdf(data.frame(x=1:10, y=10:1))
# add z to the ffdat
within(ffdat, {z <- x+y})
|
# Lyon A2018
#
# Simulation loi binomiale negative composée
#
#
# loi de M : binomiale negative
qq<-0.5
rr<-2
EM<-rr*(1-qq)/qq
VarM<-EM/qq
# loi de B : lognormale
mu<-log(10)-0.405
sig<-0.9
EB<-exp(mu+(sig^2)/2)
EB2<-exp(2*mu+2*(sig^2))
VarB<-EB2-EB^2
EX<-EM*EB
VarX<-EM*VarB+VarM*(EB^2)
c(EM,EB,EX)
c(VarM,VarB,VarX)
# simulation de réalisations la loi binomiale négative composée
# fixer la valeur source
set.seed(2018)
# nb de simulation
nsim<-100000
# vecteurs des réalisations de M et X
vM<-rep(0,nsim)
vX<-rep(0,nsim)
# algo de simulation des réalisations de M et X
for (i in 1:nsim)
{
U<-runif(1)
vM[i]<-qnbinom(U,rr,qq)
if (vM[i]>0) vX[i]<-sum(qlnorm(runif(vM[i]),mu,sig))
}
# valeurs exactes
c(EM,VarM,EB,VarB,EX,VarX)
# valeurs approximatives
mean(vM)
var(vM)
mean(vX)
var(vX)
# courbe des valeurs approximatives de FX(x)
plot.ecdf(vX,xlab="x")
# 100 premières valeurs des réalisations de (M,X)
cbind(1:100,vM[1:100],vX[1:100])
# approximation de FX(x)
x<-0
Fx<-sum((vX<=x))/nsim
c(x,Fx)
# approximation de VaR et TVaR de X
vXs<-sort(vX)
#vkappa<-c(0.5,0.9,0.99,0.999)
vkappa<-(1:999)/1000
vVaRX<-quantile(vX,probs=vkappa,type=1)
#cbind(vkappa,vVaRX,vXs[vkappa*nsim])
nkap<-length(vkappa)
TVaRX<-rep(0,nkap)
for (i in 1:nkap)
{
dum<-vkappa[i]*nsim+1
TVaRX[i]<-sum(vXs[dum:nsim])/(nsim*(1-vkappa[i]))
}
#cbind(vkappa,vVaRX,vXs[vkappa*nsim],TVaRX)
matplot(vkappa,cbind(vVaRX,TVaRX),type="l")
# courbe des valeurs approximatives de VaR
vu<-(1:999)/1000
vquanX<-quantile(vX,probs=vu,type=1)
plot(vu,vquanX,type="l")
| /LyonA2018_CodesR_2018-11-07 Binomiale Negative Composee Sinistres Loi LNorm.R | no_license | emarceau/ISFA2019 | R | false | false | 1,660 | r | # Lyon A2018
#
# Simulation loi binomiale negative composée
#
#
# loi de M : binomiale negative
qq<-0.5
rr<-2
EM<-rr*(1-qq)/qq
VarM<-EM/qq
# loi de B : lognormale
mu<-log(10)-0.405
sig<-0.9
EB<-exp(mu+(sig^2)/2)
EB2<-exp(2*mu+2*(sig^2))
VarB<-EB2-EB^2
EX<-EM*EB
VarX<-EM*VarB+VarM*(EB^2)
c(EM,EB,EX)
c(VarM,VarB,VarX)
# simulation de réalisations la loi binomiale négative composée
# fixer la valeur source
set.seed(2018)
# nb de simulation
nsim<-100000
# vecteurs des réalisations de M et X
vM<-rep(0,nsim)
vX<-rep(0,nsim)
# algo de simulation des réalisations de M et X
for (i in 1:nsim)
{
U<-runif(1)
vM[i]<-qnbinom(U,rr,qq)
if (vM[i]>0) vX[i]<-sum(qlnorm(runif(vM[i]),mu,sig))
}
# valeurs exactes
c(EM,VarM,EB,VarB,EX,VarX)
# valeurs approximatives
mean(vM)
var(vM)
mean(vX)
var(vX)
# courbe des valeurs approximatives de FX(x)
plot.ecdf(vX,xlab="x")
# 100 premières valeurs des réalisations de (M,X)
cbind(1:100,vM[1:100],vX[1:100])
# approximation de FX(x)
x<-0
Fx<-sum((vX<=x))/nsim
c(x,Fx)
# approximation de VaR et TVaR de X
vXs<-sort(vX)
#vkappa<-c(0.5,0.9,0.99,0.999)
vkappa<-(1:999)/1000
vVaRX<-quantile(vX,probs=vkappa,type=1)
#cbind(vkappa,vVaRX,vXs[vkappa*nsim])
nkap<-length(vkappa)
TVaRX<-rep(0,nkap)
for (i in 1:nkap)
{
dum<-vkappa[i]*nsim+1
TVaRX[i]<-sum(vXs[dum:nsim])/(nsim*(1-vkappa[i]))
}
#cbind(vkappa,vVaRX,vXs[vkappa*nsim],TVaRX)
matplot(vkappa,cbind(vVaRX,TVaRX),type="l")
# courbe des valeurs approximatives de VaR
vu<-(1:999)/1000
vquanX<-quantile(vX,probs=vu,type=1)
plot(vu,vquanX,type="l")
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/03AnalysisClass.R
\docType{methods}
\name{getlongformatminmaxconstructeddata}
\alias{getlongformatminmaxconstructeddata}
\alias{getlongformatminmaxconstructeddata,AnalysisClass-method}
\title{getlongformatminmaxconstructeddata}
\usage{
getlongformatminmaxconstructeddata(object)
\S4method{getlongformatminmaxconstructeddata}{AnalysisClass}(object)
}
\arguments{
\item{object}{(AnalysisClass or RunClass)}
}
\value{
(data frame) long format data
}
\description{
get long format of minmax normalized constructed data
}
\keyword{internal}
| /man/getlongformatminmaxconstructeddata.Rd | no_license | mvattulainen/preproviz | R | false | true | 616 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/03AnalysisClass.R
\docType{methods}
\name{getlongformatminmaxconstructeddata}
\alias{getlongformatminmaxconstructeddata}
\alias{getlongformatminmaxconstructeddata,AnalysisClass-method}
\title{getlongformatminmaxconstructeddata}
\usage{
getlongformatminmaxconstructeddata(object)
\S4method{getlongformatminmaxconstructeddata}{AnalysisClass}(object)
}
\arguments{
\item{object}{(AnalysisClass or RunClass)}
}
\value{
(data frame) long format data
}
\description{
get long format of minmax normalized constructed data
}
\keyword{internal}
|
library(dplyr)
library(reshape)
# set my work directory
wkdir <- setwd("~/Coursera/JHU-DS/GettingCleaningData/wk4")
# file handling
file <- file.path("./", "uci-dataset.zip")
dataset_dir <- file.path("./" , "UCI HAR Dataset")
if (!file.exists(file)){
url <- "https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip"
download.file(url, file, method = "curl")
}
# unzip, exdir UCI HAR Dataset
if (!file.exists(dataset_dir)){
unzip(file)
}
activity_data_labels <- read.table(paste(wkdir, "/UCI HAR Dataset/features.txt",sep=""))
features <- read.table(paste(wkdir, "/UCI HAR Dataset/features.txt",sep=""))
subject_test <- read.table(paste(wkdir, "/UCI HAR Dataset/test/subject_test.txt",sep=""))
X_test <- read.table(paste(wkdir, "/UCI HAR Dataset/test/X_test.txt",sep=""))
y_test <- read.table(paste(wkdir, "/UCI HAR Dataset/test/y_test.txt",sep=""))
subject_train <- read.table(paste(wkdir, "/UCI HAR Dataset/train/subject_train.txt",sep=""))
X_train <- read.table(paste(wkdir, "/UCI HAR Dataset/train/X_train.txt",sep=""))
y_train <- read.table(paste(wkdir, "/UCI HAR Dataset/train/y_train.txt",sep=""))
Xy_test <- cbind(subject_test, y_test, X_test)
Xy_train <- cbind(subject_train, y_train, X_train)
fullSet <- rbind(Xy_test, Xy_train)
# Test the full data set
head(fullSet, 1)
nrow(fullSet)
ncol(fullSet)
names(fullSet)
allNames <- c("subject", "activity", as.character(features$V2))
meanStdColumns <- grep("subject|activity|[Mm]ean|std", allNames, value = FALSE)
reducedSet <- fullSet[ ,meanStdColumns]
names(activity_data_labels) <- c("activityNumber", "activityName")
reducedSet$V1.1 <- activity_data_labels$activityName[reducedSet$V1.1]
reducedNames <- allNames[meanStdColumns] # Normalize names after subsetting
reducedNames <- gsub("mean", "Mean", reducedNames)
reducedNames <- gsub("std", "Std", reducedNames)
reducedNames <- gsub("gravity", "Gravity", reducedNames)
reducedNames <- gsub("[[:punct:]]", "", reducedNames)
reducedNames <- gsub("^t", "time", reducedNames)
reducedNames <- gsub("^f", "frequency", reducedNames)
reducedNames <- gsub("^anglet", "angleTime", reducedNames)
names(reducedSet) <- reducedNames # Apply new names to dataframe
tidy_Dataset <- reducedSet %>% group_by(activity, subject) %>% summarise_all(list(mean = mean))
write.table(tidy_Dataset, file = "tidy_dataset.txt", row.names = FALSE)
# Test and validate the tidy Data set, the big clean movement
head(tidy_Dataset, 1)
nrow(tidy_Dataset)
ncol(tidy_Dataset)
names(tidy_Dataset) # activity - subject (in pairs)
# read in tidy data set in detail and check so
# View(read.table("tidy_dataset.txt"))
| /GettingCleaningData/wk4/run_analysis.R | no_license | rockyanlin/GettingCleaningData | R | false | false | 2,647 | r | library(dplyr)
library(reshape)
# set my work directory
wkdir <- setwd("~/Coursera/JHU-DS/GettingCleaningData/wk4")
# file handling
file <- file.path("./", "uci-dataset.zip")
dataset_dir <- file.path("./" , "UCI HAR Dataset")
if (!file.exists(file)){
url <- "https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip"
download.file(url, file, method = "curl")
}
# unzip, exdir UCI HAR Dataset
if (!file.exists(dataset_dir)){
unzip(file)
}
activity_data_labels <- read.table(paste(wkdir, "/UCI HAR Dataset/features.txt",sep=""))
features <- read.table(paste(wkdir, "/UCI HAR Dataset/features.txt",sep=""))
subject_test <- read.table(paste(wkdir, "/UCI HAR Dataset/test/subject_test.txt",sep=""))
X_test <- read.table(paste(wkdir, "/UCI HAR Dataset/test/X_test.txt",sep=""))
y_test <- read.table(paste(wkdir, "/UCI HAR Dataset/test/y_test.txt",sep=""))
subject_train <- read.table(paste(wkdir, "/UCI HAR Dataset/train/subject_train.txt",sep=""))
X_train <- read.table(paste(wkdir, "/UCI HAR Dataset/train/X_train.txt",sep=""))
y_train <- read.table(paste(wkdir, "/UCI HAR Dataset/train/y_train.txt",sep=""))
Xy_test <- cbind(subject_test, y_test, X_test)
Xy_train <- cbind(subject_train, y_train, X_train)
fullSet <- rbind(Xy_test, Xy_train)
# Test the full data set
head(fullSet, 1)
nrow(fullSet)
ncol(fullSet)
names(fullSet)
allNames <- c("subject", "activity", as.character(features$V2))
meanStdColumns <- grep("subject|activity|[Mm]ean|std", allNames, value = FALSE)
reducedSet <- fullSet[ ,meanStdColumns]
names(activity_data_labels) <- c("activityNumber", "activityName")
reducedSet$V1.1 <- activity_data_labels$activityName[reducedSet$V1.1]
reducedNames <- allNames[meanStdColumns] # Normalize names after subsetting
reducedNames <- gsub("mean", "Mean", reducedNames)
reducedNames <- gsub("std", "Std", reducedNames)
reducedNames <- gsub("gravity", "Gravity", reducedNames)
reducedNames <- gsub("[[:punct:]]", "", reducedNames)
reducedNames <- gsub("^t", "time", reducedNames)
reducedNames <- gsub("^f", "frequency", reducedNames)
reducedNames <- gsub("^anglet", "angleTime", reducedNames)
names(reducedSet) <- reducedNames # Apply new names to dataframe
tidy_Dataset <- reducedSet %>% group_by(activity, subject) %>% summarise_all(list(mean = mean))
write.table(tidy_Dataset, file = "tidy_dataset.txt", row.names = FALSE)
# Test and validate the tidy Data set, the big clean movement
head(tidy_Dataset, 1)
nrow(tidy_Dataset)
ncol(tidy_Dataset)
names(tidy_Dataset) # activity - subject (in pairs)
# read in tidy data set in detail and check so
# View(read.table("tidy_dataset.txt"))
|
# HW, - adapted by UN - Estimating Abundance from multiple sampling capture recatpure data via multi-state
# simulating capture recapture data
require(pracma)
# ------------------------------------------------------------------------------
# Code to generate multi-state (multi-period) CRM data for 2 genders
# ------------------------------------------------------------------------------
# Name: sim.data.gender
# Objective: To generate multiple years of multi-state CMR data using the given parameter values
# Inputs: Nmale - total number of male
# Nfemale - total number of female
# T - number of years
# K - number of occasions each year, constant
# r - recruitment probabilities, length T, if not state dept specified, assume constant for genders
# - can be either one value or a vector with the first value for male, second for female
# smale - male survival, constant - next: dependent on t
# sfemale - female survival, constant - next: dependent on t
# # alpha - initial discrete state probability (length R) - seems we don't need it, maybe use again for model with temp emigration
# pmale - capture probability for each state, constant, length R, for male . next: dependent on t
# pfemale - capture probability for each state, constant, length R, for female . next: dependent on t
# # psi - transition probabilities matrix - seems we don't need it, maybe use again for model with temp emigration
# pclassmal - classification probabilities for true male. vector of 3 values, classified as male/female/unknown given male
# pclassfem - classification probabilities for true female. vector of 3 values, classified as male/female/unknown given female
# pclassmal needs to sum to 1, pclassfem needs to sum to 1, last class unknown can be missing, then = 0
# Outputs: attendance - attendance matrix, truth of which years individuals are present at the site
# encounter - encounter matrix, which years individuals were or were not seen
# state - state history matrix for each year, truth of which state individual was in whilst present at site
# state.laake - state history matrix for each year, truth of which state individual was in whilst present at site,
# style as in Laake paper. 0 = not yet born, 1 = male, present, 2 = female, present, 3 dead
# p.state - yearly true state (gender) proportion | attendance
# capture.full - capture history list with a vector for each year for all individuals, when individuals were or were not seen
# capture - capture history matrix for each year, when individuals were or were not seen
# N.attend - actual number of individuals at the site each year - to do: for all + both genders
# N.encounter - number of individuals seen each year (+ gender specific) - to do: for all + both genders
# N.seen - number of individuals seen over entire study (+ gender specific) - to do: for all + both genders
sim.data.gender <- function(Nmale, Nfemale ,T, K=1, r, smale,sfemale ,
pmale, pfemale, pclassmal, pclassfem, random = FALSE, psi = matrix(c(1,0,0,1), ncol=2,nrow=2)) {
if(sum(pclassmal) != 1 ) stop("classification probabilities must sum up to 1!")
if(sum(pclassfem) != 1 ) stop("classification probabilities must sum up to 1!")
if(length(pclassmal) == 2) pclassmal <- c(pclassmal, 0)
if(length(pclassfem) == 2) pclassfem <- c(pclassfem, 0)
if(smale < 0 | sfemale <0 | pmale < 0 | pfemale < 0 |smale >1 | sfemale >1 | pmale >1 | pfemale >1 ) stop(
"probabilities must have values between 0 and 1" )
# now run the simulation for male
# possibly change how N is coded in sim.data! to avoid having to provide 2 values
testsimmale = sim.data(N=c(Nmale,0), T=T, K=K, r=rep(0.2, times=5), s=smale, p = pmale)
# adjust the state for the animals where state was falsely coded
# we need testsimmale$state.laake, testsimmale$encounter, pclassmal
# state.obsm: 0 = not observed. 1 = observed as male, 2 = observed as female, 3 = observed as unknown gender
# get multinomial draws
tmp <- rmultinom(n=sum(testsimmale$attendance), size=1, prob=pclassmal)
# make these into a vector of 1,2, or 3
obsgender <- apply(tmp , MARGIN=2, FUN = function(x) which(x == 1))
state.obsm <- matrix(0, nrow = Nmale, ncol = T)
state.encm <- matrix(0, nrow = Nmale, ncol = 3)
noencounters <- rowSums(testsimmale$encounter)
running <- 1
for(i in 1:length(noencounters)){
if(noencounters[i]!= 0){ # if 0, go to next animal
# get no. of encounters per animal
wh <- which(testsimmale$encounter == 1)
state.obsm[i,wh] <- obsgender[running:(running+noencounters[i] - 1)]
# how many of state.obs[i,wh] are respectively 1, 2 or 3
state.encm[i,] <- c(sum(state.obsm[i,wh]==1) , sum(state.obsm[i,wh]==2), sum(state.obsm[i,wh]==3) )
# code state as 3 numbers for each indiv.: of all obs. times obs as male/female/unknown
running <- running+noencounters[i]
}
}
testsimfemale = sim.data(N=c(0, Nfemale), T=T, K=K, r=rep(0.2, times=5), s=sfemale, p = pfemale)
# adjust the state for the animals where state was falsely coded
# we need testsimmale$state.laake, testsimmale$encounter, pclassmal
# state.obsf: 0 = not observed. 1 = observed as male, 2 = observed as female, 3 = observed as unknown gender
# get multinomial draws
tmp <- rmultinom(n=sum(testsimfemale$attendance), size=1, prob=pclassmal)
# make these into a vector of 1,2, or 3
obsgender <- apply(tmp , MARGIN=2, FUN = function(x) which(x == 1))
state.obsf <- matrix(0, nrow = Nmale, ncol = T)
state.encf <- matrix(0, nrow = Nmale, ncol = 3)
noencounters <- rowSums(testsimfemale$encounter)
running <- 1
for(i in 1:length(noencounters)){
if(noencounters[i]!= 0){ # if 0, go to next animal
# get no. of encounters per animal
wh <- which(testsimfemale$encounter == 1)
state.obsf[i,wh] <- obsgender[running:(running+noencounters[i] - 1)]
# how many of state.obs[i,wh] are respectively 1, 2 or 3
state.encf[i,] <- c(sum(state.obsf[i,wh]==1) , sum(state.obsf[i,wh]==2), sum(state.obsf[i,wh]==3) )
# code state as 3 numbers for each indiv.: of all obs. times obs as male/female/unknown
running <- running+noencounters[i]
}
}
# TO DO
# now combine the results from testsimfemale and testsimmale
# observed gender proportion at each time point. HERE, we ignore whether the same animal is assessed with different gender
# at different time point. we have male, female, uncertain.
p.state.obs <- matrix(0, ncol = T, row = 3)
p.state.obsN <- matrix(0, ncol = T, row = 3)
state.enc <- rbind( state.encm , state.encf )
state.obs <- rbind(state.obsm, state.obsf)
for(t in 1:T){
p.state.obsN[,i] <- c( sum( state.obs[,i] == 1), sum( state.obs[,i] == 2),sum( state.obs[,i] == 3) )
p.state.obs[,i] <- p.state.obsN[,i] / sum( p.state.obsN[,i])
}
# what is the estimated gender proportion after readjusting the gender for animals with uncertain gender assessment
# p.state.obs.corrected # this term will be needed for decoding algorithm!
#TO DO
# eg for each animal where gender is unclear, we could use an extra category: unclear
if(random){
# randomly mix together male and female, ie. mix up all observations
neworder <- order( rnorm(sum(Nmale, Nfemale)) )
# Nmale, Nfemale
# frand = rbinom(sum(Nmale, Nfemale),1,.5) # works only if the same number of male and female
# does not work, the number needs to be exact
# neworder[frand == 0] <- 1:Nmale
# neworder[frand == 1] <-(Nmale+1):(Nmale+Nfemale)
# use neworder to reorder all outputs
# now reorder all outputs
attendance <- attendance[neworder ,]
encounter <- encounter[neworder ,]
state <- state[neworder]
state.laake <- state.laake[neworder ,];
# p.state # true gender proportion
for(j in 1:T){
capture.full[[j]] <- capture.full[[j]][neworder]
capture.0 <- which(capture.full[[j]] == 0)
capture[[j]] <- capture.full[[j]][- capture.0]
}
}
# N.obs = number of individuals seen each year (observed gender)
N.t <- matrix(0, ncol = T, nrow = 3)
N.t[2,] <- testsimmale$N.attend
N.t[3,] <- testsimfemale$N.attend
N.t[1,] <- N.t[3,] + N.t[2,];
# N.c = N.encounter - number of individuals seen each year (true gender)
N.c <- matrix(0, ncol = T, nrow = 3)
N.c[2,] <- testsimmale$N.encounter
N.c[3,] <- testsimfemale$N.encounter
N.c[1,] <- N.c[3,] + N.c[2,];
N.obs <-
nsee <- c(testsimmale$N.seen , testsimfemale$N.seen)
# state.laake: 0 not yet recruited. 1 recruited male. 2 recruited female. 3 departed
# to do: still need to refine this
return(list('attendance'=attendance, 'encounter'=encounter, 'state'=state, 'state.laake' = state.laake, 'p.state' = p.state,
'p.state.obs' = p.state.obs, 'capture.full'=capture.full, 'capture'=capture, 'N.attend'=N.t,
'N.encounter'=N.c, 'N.obs' = N.obs , 'N.seen'= c(sum(nsee),nsee ) ))
}
#head(testsim1$state.laake)
#head(testsim1$encounter)
# dim(testsim1$capture); head(testsim1$capture)
# testsim1$N.encounter
# ------------------------------------------------------------------------------
# Code to generate multi-state (multi-period) CRM data
# ------------------------------------------------------------------------------
# Name: sim.data
# Objective: To generate multiple years of multi-state stopover data using the given parameter values
# Inputs: N - total number of individuals # to do: 2 numbers - male and female
# if only one number specified, assume 1/2 male, half female
# T - number of years
# K - number of occasions each year, constant
# r - recruitment probabilities, length T, if not state dept specified, assume constant for genders - to do: make dependent on gender
# s - survival, constant - to do: make dependent on gender. next: dependent on t
# # alpha - initial discrete state probability (length R) - seems we don't need it, maybe use again for model with temp emigration
# p - capture probability for each state, constant, length R -to do: make dependent on gender. next: dependent on t
# # psi - transition probabilities matrix - seems we don't need it, maybe use again for model with temp emigration
# Outputs: attendance - attendance matrix, truth of which years individuals are present at the site
# encounter - encounter matrix, which years individuals were or were not seen
# state - state history vector for each year, truth of which state individual was in whilst present at site (male/female)
# state.laake - state history matrix for each year, truth of which state individual was in whilst present at site,
# style as in Laake paper. 0 = not yet born, 1 = male, present, 2 = female, present, 3 dead
# p.state - yearly true state (gender) proportion | attendance
# capture.full - capture history list with a vector for each year for all individuals, when individuals were or were not seen
# capture - capture history matrix for each year, when individuals were or were not seen
# N.attend - actual number of individuals at the site each year - to do: for all + both genders
# N.encounter - number of individuals seen each year (+ gender specific) - to do: for all + both genders
# N.seen - number of individuals seen over entire study (+ gender specific) - to do: for all + both genders
sim.data <- function(N, T, K=1, r, s, p, psi = matrix(c(1,0,0,1), ncol=2,nrow=2)) {
if (length(N)==1) Ngender <- c(floor(N/2) , ceiling(N/2)) else if(length(N)==2) Ngender <- N else {
stop("Only 2 different states (gender). Please specifify N correctly.") }
# if N is one number but not even, the first state will have 1 less individuum then the second state
# reassign N
N <- Ngender[1] + Ngender[2] ;
# create storage variables
attendance <- matrix(0, nrow=N, ncol=T) # next: array with gender as dimension
encounter <- matrix(1, nrow=N, ncol=T) # next: array with gender as dimension
p.state <- rep(0, times = T)
capture.full <- NULL
capture <- NULL
if(length(r)==1) r<- rep(r, times = T) else if(length(r) != T) stop("r needs to have length T");
# attendance history
# generate recruitment distribution
# recruitment <- rmultinom(1, N, r) # to do. with N and r as 2dim vector (gender)
recruitment1 <- rmultinom(1, Ngender[1], r)
recruitment2 <- rmultinom(1, Ngender[2], r)
# make vector of arrival times
# recruitment.i <- rep(1:T, recruitment) # adapt for 2-gender version
recruitment1.i <- rep(1:T, recruitment1)
recruitment2.i <- rep(1:T, recruitment2)
recruitment.i <- c(recruitment1.i, recruitment2.i);
# state <- # true state (gender), vector of length N
state <- c(rep(1, times = Ngender[1]), rep(2, times = Ngender[2]) );
state.laake <- matrix(0, nrow=N, ncol=T) # is C_t in Laake for each individual
# loop over individuals
for (i in 1:N) {
# record first attendance
attendance[i,recruitment.i[i]] <- 1 # recruitment.i[i] is the first atttendance time point
state.laake[i,recruitment.i[i]] <- state[i]
# state.laake: 0 not yet recruited. 1 recruited male. 2 recruited female. 3 departed
# if not recruited in final year
if (recruitment.i[i] < T) {
# loop over remaining occasions
for (t in recruitment.i[i]:(T-1)) {
# if present at site
if (attendance[i,t] == 1) {
# work out whether they survive until the next year
survival <- rbinom(1,1,s) # adapt with survival prob s dependent on gender
# store 0 or 1 following year
attendance[i,t+1] <- survival
if (survival == 0) state.laake[i,t+1] <- 3 else state.laake[i,t+1] <- state[i];
} else state.laake[i,t+1] <- 3 # ie departed
}
}
}
# find number that are present each year
N.t <- colSums(attendance) # + add for each gender
N1.t <- colSums(attendance[state == 1 , ]);
N2.t <- colSums(attendance[state == 2 , ]);
p.state <- N1.t / N.t # true state proportion for each primary capture occassion
# state.t <- matrix(0, nrow=N, ncol=1) # needed when we include the temp. emigration
# capture histories for each year
# loop over years
for (t in 1:T) {
# storage variables for this year
capture.t <- matrix(0, nrow=N, ncol=K)
# I will need this when the states are also temporary emigration states - then adapt this
# loop over individuals and assign states
# for (i in 1:N) {
# find the occasions when present
# present <- which(presence.t[i,] == 1)
# assign state at initial capture
# state.init <- 1+rbinom(1,1,alpha[2]) # if necessary, add alpha again as argument, if needed for temp. emigration modelling
# state.t[i,present[1]] <- state.init
# loop over remaining occasions when present and transition between states
# if (length(present) > 1) {
# for (k in present[2]:present[length(present)]) {
# if (state.t[i,k-1] == 1) {
# state.k <- 1+rbinom(1,1,psi[1,2]) # if necessary, add psi again as argument, if needed for temp. emigration modelling
# } else if (state.t[i,k-1] == 2) {
# state.k <- 1+rbinom(1,1,psi[2,2])
# }
# state.t[i,k] <- state.k
# }
# }
# }
# loop over individuals and check whether they were captured or not
for (i in 1:N) {
# capture.t is defaulted to 0
# find the primary occassions where they were present
if(attendance[i,t]==1) {
# loop over occasions
for (k in 1:K) {
# determine whether they were captured or not
# capture.t[i,k] <- state.t[i,1]*rbinom(1,1,p[state.t[i,1]])
capture.t[i,k] <- state[i]*rbinom(1,1,p[state[i] ]) # needs to be adapted if temp emigration possible
} }
}
# find which rows are all zeros in capture histories
capture.0 <- which(rowSums(capture.t) == 0)
# update encounter histories
for (c in capture.0) {
encounter[c,t] <- 0
}
# store state history for year t
# state[[t]] <- state.t - will be needed if temp. emigration is also a state
# store full capture history for year t
capture.full[[t]] <- c( capture.t) # capture.t
# store capture history for year t
capture[[t]] <- capture.t[-capture.0,]
}
# count those encountered each year
N.c <- colSums(encounter) # to do: count for both male and female and all
# count those who are seen at least once
N.seen <- N-length(which(rowSums(encounter) == 0)) # to do: count for both male and female and all
# return
return(list('attendance'=attendance, 'encounter'=encounter, 'state'=state, 'state.laake' = state.laake, 'p.state' = p.state,
'capture.full'=capture.full, 'capture'=capture, 'N.attend'=N.t, 'N.encounter'=N.c, 'N.seen'=N.seen))
}
# example
# testsim1 = sim.data(N=1000, T=5, K=1, r=rep(0.2, times=5), s=0.3, p = c(0.3,0.5))
# testsim = sim.data(N=c(1000,0), T=5, K=1, r=rep(0.2, times=5), s=0.3, p = 0.4) # only male
# testsim1$p.state; head(testsim1$encounter)
# head(testsim1$state); tail(testsim1$state)
# head(testsim1$state.laake); tail(testsim1$state.laake)
# head(testsim1$attendance)
# dim(testsim$attendance);
# head(testsim$state.laake); tail(testsim$state.laake)
# ------------------------------------------------------------------------------
# Code to generate multi-state (multi-period) CRM data WITHOUT gender
# ------------------------------------------------------------------------------
# Name: sim.data.0
# Objective: To generate multiple years of capture recapture data using the given parameter values, constant survival and capture prob
# Inputs: N - total number of individuals
# T - number of years
# K - number of occasions each year, constant
# r - recruitment probabilities, length T, if not state dept specified
# s - survival, constant - . next: dependent on t
# # alpha - initial discrete state probability (length R) - seems we don't need it, maybe use again for model with temp emigration
# p - capture probability for each state, constant, length R -to do: make dependent on gender. next: dependent on t
# Outputs: attendance - attendance matrix, truth of which years individuals are present at the site
# encounter - encounter matrix, which years individuals were or were not seen
# state - state history vector for each year, truth of which state individual was in whilst present at site (male/female)
# state.laake - state history matrix for each year, truth of which state individual was in whilst present at site,
# style as in Laake paper. 0 = not yet born, 1 = present, 3 = dead # not yet: 1 = male, present, 2 = female, present,
# p.state - yearly true state (gender) proportion | attendance
# capture.full - capture history list with a vector for each year for all individuals, when individuals were or were not seen
# capture - capture history matrix for each year, when individuals were or were not seen
# N.attend - actual number of individuals at the site each year - to do: for all + both genders
# N.encounter - number of individuals seen each year (+ gender specific) - to do: for all + both genders
# N.seen - number of individuals seen over entire study (+ gender specific) - to do: for all + both genders
sim.data.0 <- function(N, T, K=1, r, s, p, psi = matrix(c(1,0,0,1), ncol=2,nrow=2)) {
# if (length(N)==1) Ngender <- c(floor(N/2) , ceiling(N/2)) else if(length(N)==2) Ngender <- N else {
# stop("Only 2 different states (gender). Please specifify N correctly.") }
# if N is one number but not even, the first state will have 1 less individuum then the second state
# reassign N
# N <- Ngender[1] + Ngender[2] ;
# create storage variables
attendance <- matrix(0, nrow=N, ncol=T) # next: array with gender as dimension
encounter <- matrix(1, nrow=N, ncol=T) # next: array with gender as dimension
# p.state <- rep(0, times = T)
capture.full <- NULL
capture <- NULL
if(length(r)==1) r<- rep(r, times = T) else if(length(r) != T) stop("r needs to have length T");
# attendance history
# generate recruitment distribution
recruitment <- rmultinom(1, N, r) # produces a matrix wiht rows = T = lenght r , with the number of elements first recruited in each row
# to do. with N and r as 2dim vector (gender)
# recruitment1 <- rmultinom(1, Ngender[1], r)
# recruitment2 <- rmultinom(1, Ngender[2], r)
# make vector of arrival times
recruitment.i <- rep(1:T, recruitment) # a number for each individual # adapt for 2-gender version
# recruitment1.i <- rep(1:T, recruitment1)
# recruitment2.i <- rep(1:T, recruitment2)
# recruitment.i <- c(recruitment1.i, recruitment2.i);
# state <- # true state (gender), vector of length N
# state <- c(rep(1, times = Ngender[1]), rep(2, times = Ngender[2]) );
# state <- rep(1, times = N)
# now use
state <- matrix(0, nrow=N, ncol=T) # state = 0, and 1 if alive
# instead of state, I now use state.laake. state was in HW a list with attendance vector as elements for each secondary period
state.laake <- matrix(0, nrow=N, ncol=T) # is C_t in Laake for each individual
# loop over individuals
for (i in 1:N) {
# record first attendance
attendance[i,recruitment.i[i]] <- 1 # recruitment.i[i] is the first atttendance time point
state.laake[i,recruitment.i[i]] <- 1 # state[i]
state[i,recruitment.i[i]] <- 1
# state.laake: 0 not yet recruited. 1 recruited male. 2 recruited female. 3 departed
# if not recruited in final year
if (recruitment.i[i] < T) {
# loop over remaining occasions
for (t in recruitment.i[i]:(T-1)) {
# if present at site
if (attendance[i,t] == 1) {
# work out whether they survive until the next year
survival <- rbinom(1,1,s) # adapt with survival prob s dependent on gender
# store 0 or 1 following year
attendance[i,t+1] <- survival
state[i,t+1] <- survival;
if (survival == 0) { state.laake[i,t+1] <- 3
# state[i,t+1] <- 0 # it is defaulted to 0 anyway
} else { state.laake[i,t+1] <- 1;
# state[i,t+1] <- 1;
}# state[i];
} else { # ie, between first recruitment and end of study are some time points, but has died now
state.laake[i,t+1] <- 3 # ie departed -
state[i,t+1] <- 0;
# since this is developed from gender version, we have states: 0 (unborn)), 1 (alive), 3 (departed)
}
}
}
}
# find number that are present each year
N.t <- colSums(attendance) # + add for each gender
# N1.t <- colSums(attendance[state == 1 , ]);
# N2.t <- colSums(attendance[state == 2 , ]);
# p.state <- N1.t / N.t # true state proportion for each primary capture occassion
# state.t <- matrix(0, nrow=N, ncol=1) # needed when we include the temp. emigration
# capture histories for each year
# loop over years
for (t in 1:T) {
# storage variables for this year
capture.t <- matrix(0, nrow=N, ncol=K)
# I will need this when the states are also temporary emigration states - then adapt this
# loop over individuals and assign states
# for (i in 1:N) {
# find the occasions when present
# present <- which(presence.t[i,] == 1)
# assign state at initial capture
# state.init <- 1+rbinom(1,1,alpha[2]) # if necessary, add alpha again as argument, if needed for temp. emigration modelling
# state.t[i,present[1]] <- state.init
# loop over remaining occasions when present and transition between states
# if (length(present) > 1) {
# for (k in present[2]:present[length(present)]) {
# if (state.t[i,k-1] == 1) {
# state.k <- 1+rbinom(1,1,psi[1,2]) # if necessary, add psi again as argument, if needed for temp. emigration modelling
# } else if (state.t[i,k-1] == 2) {
# state.k <- 1+rbinom(1,1,psi[2,2])
# }
# state.t[i,k] <- state.k
# }
# }
# }
# loop over individuals and check whether they were captured or not
for (i in 1:N) {
# capture.t is defaulted to 0
# find the primary occassions where they were present
if(attendance[i,t]==1) {
# loop over occasions
capture.t[i,] <- rbinom(K,1,p) # needs to be adapted if temp emigration possible
# next: use time dependent capture prob! in primary time - possible would also be time dept within secondary
# for (k in 1:K) {
# determine whether they were captured or not
## capture.t[i,k] <- state.t[i,1]*rbinom(1,1,p[state.t[i,1]])
## capture.t[i,k] <- state[i]*rbinom(1,1,p[state[i] ]) # needs to be adapted if temp emigration possible
# capture.t[i,k] <- rbinom(1,1,p) # needs to be adapted if temp emigration possible
# next: use time dependent capture prob!
# }
}
}
# find which rows are all zeros in capture histories
capture.0 <- which(rowSums(capture.t) == 0) # ie for which year are all secondary capt histories = 0
# update encounter histories
for (c in capture.0) {
encounter[c,t] <- 0
}
# store state history for year t
# state[[t]] <- state.t - will be needed if temp. emigration is also a state
# store full capture history for year t
capture.full[[t]] <- c( capture.t) # capture.t
# store capture history for year t
capture[[t]] <- capture.t[-capture.0,]
}
# count those encountered each year
N.c <- colSums(encounter) # to do: count for both male and female and all
# count those who are seen at least once
N.seen <- N-length(which(rowSums(encounter) == 0)) # to do: count for both male and female and all
# return
return(list('attendance'=attendance, 'encounter'=encounter, 'state'=state, 'state.laake' = state.laake, # 'p.state' = p.state,
'capture.full'=capture.full, 'capture'=capture, 'N.attend'=N.t, 'N.encounter'=N.c, 'N.seen'=N.seen))
}
# ------------------------------------------------------------------------------
# Code to generate multi-state (multi-period) CRM data WITH temp. emigration
# ------------------------------------------------------------------------------
# this is now out of date, and replaced by sim.data.tau.time
# Name: sim.data.tau
# Objective: To generate multiple years of capture recapture data using the given parameter values, constant survival and capture prob
# Inputs: N - total number of individuals
# T - number of years
# K - number of occasions each year, constant
# r - recruitment probabilities, length T, if not state dept specified
# s - survival, constant - . next: dependent on t
# # alpha - initial discrete state probability (length R) - seems we don't need it, maybe use again for model with temp emigration
# p - capture probability for each state, constant, length R -to do: make dependent on gender. next: dependent on t
# tau - probability of temporary emigration, given 1) not temp. emigrated in previous year,
# 2) temp. emigrated in previous year,
# Outputs: attendance - attendance matrix, truth of which years individuals are present at the site
# encounter - encounter matrix, which years individuals were or were not seen
# state - state history vector for each year, truth of which state individual was in whilst present at site (male/female)
# state.laake - state history matrix for each year, truth of which state individual was in whilst present at site,
# style as in Laake paper. 0 = not yet born, 1 = alive, 2 = temp emig, 3 dead
# p.state - yearly true state (gender) proportion | attendance
# capture.full - capture history list with a vector for each year for all individuals, when individuals were or were not seen
# capture - capture history matrix for each year, when individuals were or were not seen
# N.attend - actual number of individuals at the site each year - to do: for all + both genders
# N.encounter - number of individuals seen each year (+ gender specific) - to do: for all + both genders
# N.seen - number of individuals seen over entire study (+ gender specific) - to do: for all + both genders
# temp = sim.data.tau(N=100, T=10, K=1, r= 0.6, s=0.5, p=0.5, tau = c(0.2, 0.3)) ; temp$capture.full; temp$N.attend ; temp$N.encounter; temp$N.seen
# temp$state; temp$state.laake
sim.data.tau <- function(N, T, K=1, r, s, p, tau) {
# if (length(N)==1) Ngender <- c(floor(N/2) , ceiling(N/2)) else if(length(N)==2) Ngender <- N else {
# stop("Only 2 different states (gender). Please specifify N correctly.") }
# if N is one number but not even, the first state will have 1 less individuum then the second state
# reassign N
# N <- Ngender[1] + Ngender[2] ;
if(s + tau[1] > 1) {
warning("s + tau[1] must be <= 1")
sp = s + tau[1];
s <- s/sp;
tau[1]/sp
}
# create storage variables
attendance <- matrix(0, nrow=N, ncol=T) # alive an not temp emigrated
encounter <- matrix(1, nrow=N, ncol=T) # next: array with gender as dimension
# p.state <- rep(0, times = T)
capture.full <- NULL
capture <- NULL
if(length(r)==1) r<- rep(r, times = T) else if(length(r) != T) stop("r needs to have length T");
# attendance history
# generate recruitment distribution
recruitment <- rmultinom(1, N, r) # produces a matrix with rows = T = lenght r , with the number of elements first recruited in each row
# make vector of arrival times
recruitment.i <- rep(1:T, recruitment) # a number for each individual # adapt for 2-gender version
# now use
state <- matrix(0, nrow=N, ncol=T) # state = 0, and 1 if alive
# instead of state, I now use state.laake. state was in HW a list with attendance vector as elements for each secondary period
state.laake <- matrix(0, nrow=N, ncol=T) # is C_t in Laake for each individual
# state.laake: 0 not yet recruited. 1 recruited . 2 temp. emigrated. 3 departed
# state = 1 means temp. emigrated or alive
# attendance is 1 if alive and not temp emigrated!
# loop over individuals
for (i in 1:N) {
# record first attendance
attendance[i,recruitment.i[i]] <- 1 # recruitment.i[i] is the first atttendance time point
state.laake[i,recruitment.i[i]] <- 1
state[i,recruitment.i[i]] <- 1 # state should be used later to for male/female, here: just one gender
# state.laake: 0 not yet recruited. 1 recruited . 2 temp. emigrated. 3 departed
# if not recruited in final year
if (recruitment.i[i] < T) {
# loop over remaining occasions
for (t in recruitment.i[i]:(T-1)) {
# if present at site
if (attendance[i,t] == 1) {
# work out whether they survive until the next year, or temp emigrate or die
survival <- rmultinom(1,1,c(s,tau[1], 1-s-tau[1] ) ) # adapt with survival prob s dependent on gender
surv <- which(survival == 1) # 1 = alive, 2 = temp. emig, 3 = dead
# store 0 or 1 following year
# state[i,t+1] <- survival;
state.laake[i,t+1] <- surv
if (surv == 3) { # state.laake[i,t+1] <- 3
state[i,t+1] <- 0 # it is defaulted to 0 anyway
} else if(surv == 1) {# state.laake[i,t+1] <- 1;
state[i,t+1] <- 1;
attendance[i,t+1] <- 1
} else if(surv == 2){ # temp. emigrated
# attendance[i,t+1] <- 0 # is anyway the default
state[i,t+1] <- 1; # state: 0 - dead. 1 male or no gender measured
# here: state = 1 means temp. emigrated or alive
}
# attendance is 1 if alive and not temp emigrated!
} else { # is either dead or temp emigrated
if (state.laake[i,t] == 2){ # temp. emigrated
# now probability of emigrationg again is tau[2]
emigagain <- rbinom(1,1, tau[2]) # 1 = emig 0 = alive
state[i,t+1] <- 1 # either way from temp. emig. no death
state.laake[i,t+1] <- emigagain + 1 # 1 = alive, 2 = temp. emig, 3 = dead
attendance[i,t+1] == 1 - emigagain
} else { # ie dead -
state.laake[i,t+1] <- 3
state[i,t+1] <- 0;
# since this is developed from gender version, we have states: 0 (unborn)), 1 (alive), 3 (departed)
}
}
}
}
}
# find number that are present each year
N.t <- colSums(attendance) # + add for each gender
# N1.t <- colSums(attendance[state == 1 , ]);
# N2.t <- colSums(attendance[state == 2 , ]);
# p.state <- N1.t / N.t # true state proportion for each primary capture occassion
# state.t <- matrix(0, nrow=N, ncol=1) # needed when we include the temp. emigration
# capture histories for each year
# loop over years
for (t in 1:T) {
# storage variables for this year
capture.t <- matrix(0, nrow=N, ncol=K)
# I will need this when the states are also temporary emigration states - then adapt this
# loop over individuals and assign states
# for (i in 1:N) {
# find the occasions when present
# present <- which(presence.t[i,] == 1)
# assign state at initial capture
# state.init <- 1+rbinom(1,1,alpha[2]) # if necessary, add alpha again as argument, if needed for temp. emigration modelling
# state.t[i,present[1]] <- state.init
# loop over remaining occasions when present and transition between states
# if (length(present) > 1) {
# for (k in present[2]:present[length(present)]) {
# if (state.t[i,k-1] == 1) {
# state.k <- 1+rbinom(1,1,psi[1,2]) # if necessary, add psi again as argument, if needed for temp. emigration modelling
# } else if (state.t[i,k-1] == 2) {
# state.k <- 1+rbinom(1,1,psi[2,2])
# }
# state.t[i,k] <- state.k
# }
# }
# }
# loop over individuals and check whether they were captured or not
for (i in 1:N) {
# capture.t is defaulted to 0
# find the primary occassions where they were present
if(attendance[i,t]==1) {
# loop over occasions
capture.t[i,] <- rbinom(K,1,p) # needs to be adapted if temp emigration possible
# next: use time dependent capture prob! in primary time - possible would also be time dept within secondary
# for (k in 1:K) {
# determine whether they were captured or not
## capture.t[i,k] <- state.t[i,1]*rbinom(1,1,p[state.t[i,1]])
## capture.t[i,k] <- state[i]*rbinom(1,1,p[state[i] ]) # needs to be adapted if temp emigration possible
# capture.t[i,k] <- rbinom(1,1,p) # needs to be adapted if temp emigration possible
# next: use time dependent capture prob!
# }
}
}
# find which rows are all zeros in capture histories
capture.0 <- which(rowSums(capture.t) == 0) # ie for which year are all secondary capt histories = 0
# update encounter histories
for (c in capture.0) {
encounter[c,t] <- 0
}
# store state history for year t
# state[[t]] <- state.t - will be needed if temp. emigration is also a state
# store full capture history for year t
capture.full[[t]] <- c( capture.t) # capture.t
# store capture history for year t
capture[[t]] <- capture.t[-capture.0,]
}
# count those encountered each year
N.c <- colSums(encounter) # to do: count for both male and female and all
# count those who are seen at least once
N.seen <- N-length(which(rowSums(encounter) == 0)) # to do: count for both male and female and all
# return
return(list('attendance'=attendance, 'encounter'=encounter, 'state'=state, 'state.laake' = state.laake, # 'p.state' = p.state,
'capture.full'=capture.full, 'capture'=capture, 'N.attend'=N.t, 'N.encounter'=N.c, 'N.seen'=N.seen))
}
# to do: should we allow the first time point of attendance, that the animal is already temp. emigrated?
# ------------------------------------------------------------------------------
# Code to generate multi-state (multi-period) CRM data WITH temp. emigration
# ------------------------------------------------------------------------------
# Name: sim.data.tau.t
# Objective: To generate multiple years of capture recapture data using the given parameter values, constant survival and capture prob
# Inputs: N - total number of individuals
# T - number of years
# K - number of occasions each year, constant
# r - recruitment probabilities, length T, if not state dept specified
# s - survival, dependent on t
# # alpha - initial discrete state probability (length R) - seems we don't need it, maybe use again for model with temp emigration
# p - capture probability for each state, dependent on t
# tau - probability of temporary emigration, given 1) not temp. emigrated in previous year,
# 2) temp. emigrated in previous year,
# this is now changed to be a factor which is multiplicated (1-tau)*s to the survival
# Outputs: attendance - attendance matrix, truth of which years individuals are present at the site
# encounter - encounter matrix, which years individuals were or were not seen
# state - state history matrix (vector for each year), truth of which state individual was in whilst present at site (0 = not present, 1 = present)
# state.laake - state history matrix for each year, truth of which state individual was in whilst present at site,
# style as in Laake paper. 0 = not yet born, 1 = alive, 2 = temp emig, 3 dead
# p.state - yearly true state (gender) proportion | attendance
# capture.full - capture history list with a vector for each year for all individuals, when individuals were or were not seen
# capture - capture history matrix for each year, when individuals were or were not seen
# N.attend - actual number of individuals at the site each year - to do: for all + both genders
# N.encounter - number of individuals seen each year (+ gender specific) - to do: for all + both genders
# N.seen - number of individuals seen over entire study (+ gender specific) - to do: for all + both genders
# temp = sim.data.tau.time(N=100, T=10, K=1, r= 0.6, s=rep(0.5,10)-seq(0.01, 0.1, length=10), p=rep(0.5,10)+seq(0.01, 0.1, length=10), tau = c(0.2, 0.3)) ; temp$capture.full; temp$N.attend ; temp$N.encounter; temp$N.seen
# temp$state; temp$state.laake
# 1/11.2019: this is now recoded. survprob = s*(1-tau), emig prob = s*tau, dead prob = 1-s
sim.data.tau.time <- function(N, T, K=1, r, s, p, tau) {
if(length(r)==1) r<- rep(r, times = T) else if(length(r) != T) stop("r needs to have length T");
if(length(s)==1) s<- rep(s, times = T) else if(length(s) != T) stop("s needs to have length T");
if(length(p)==1) p<- rep(p, times = T) else if(length(p) != T) stop("p needs to have length T");
if(any(s > 1)) {
stop("s must be <= 1") }
if(any(p > 1)) {
stop("p must be <= 1") }
if(any(r > 1)) {
stop("r must be <= 1") }
if(any(tau > 1)) {
stop("tau must be <= 1") }
# sp = s + tau[1];
# s <- s/sp;
# tau[1]<- tau[1]/sp
# create storage variables
attendance <- matrix(0, nrow=N, ncol=T) # alive an not temp emigrated
encounter <- matrix(1, nrow=N, ncol=T) # next: array with gender as dimension
# p.state <- rep(0, times = T)
capture.full <- NULL
capture <- NULL
# attendance history
# generate recruitment distribution
recruitment <- rmultinom(1, N, r) # produces a matrix with rows = T = lenght r , with the number of elements first recruited in each row
# make vector of arrival times
recruitment.i <- rep(1:T, recruitment) # a number for each individual # adapt for 2-gender version
# now use
state <- matrix(0, nrow=N, ncol=T) # state = 0, and 1 if alive
# instead of state, I now use state.laake. state was in HW a list with attendance vector as elements for each secondary period
state.laake <- matrix(0, nrow=N, ncol=T) # is C_t in Laake for each individual
# state.laake: 0 not yet recruited. 1 recruited . 2 temp. emigrated. 3 departed
# state = 1 means temp. emigrated or alive
# attendance is 1 if alive and not temp emigrated!
# loop over individuals
for (i in 1:N) {
# record first attendance
attendance[i,recruitment.i[i]] <- 1 # recruitment.i[i] is the first atttendance time point
state.laake[i,recruitment.i[i]] <- 1
state[i,recruitment.i[i]] <- 1 # state should be used later to for male/female, here: just one gender
# state.laake: 0 not yet recruited. 1 recruited . 2 temp. emigrated. 3 departed
# if not recruited in final year
if (recruitment.i[i] < T) {
# loop over remaining occasions
for (t in recruitment.i[i]:(T-1)) {
# if present at site
if (attendance[i,t] == 1) {
# work out whether they survive until the next year, or temp emigrate or die
# survival <- rmultinom(1,1,c(s[t],tau[1], 1-s[t]-tau[1] ) )
# recoded 1/11/2019: death prob = 1-s[t],emig prob = s[t]*tau[2]
survival <- rmultinom(1,1,c(s[t]*(1-tau[1]),s[t]*tau[1], 1-s[t] ) )
surv <- which(survival == 1) # 1 = alive, 2 = temp. emig, 3 = dead
# store 0 or 1 following year
# state[i,t+1] <- survival;
state.laake[i,t+1] <- surv
if (surv == 3) { # state.laake[i,t+1] <- 3
state[i,t+1] <- 0 # it is defaulted to 0 anyway
} else if(surv == 1) {# state.laake[i,t+1] <- 1;
state[i,t+1] <- 1;
attendance[i,t+1] <- 1
} else if(surv == 2){ # temp. emigrated
# attendance[i,t+1] <- 0 # is anyway the default
state[i,t+1] <- 1; # state: 0 - dead. 1 male or no gender measured
# here: state = 1 means temp. emigrated or alive
}
# attendance is 1 if alive and not temp emigrated!
} else { # is either dead or temp emigrated
if (state.laake[i,t] == 2){ # temp. emigrated
# lets build in a death prob.: recoded 1/11/2019: death prob = 1-s[t],emig prob = s[t]*tau[2]
survival <- rmultinom(1,1,c(s[t]*(1-tau[2]),s[t]*tau[2], 1-s[t] ) )
surv <- which(survival == 1) # 1 = alive, 2 = temp. emig, 3 = dead
# store 0 or 1 following year
# state[i,t+1] <- survival;
state.laake[i,t+1] <- surv
if (surv == 3) { # state.laake[i,t+1] <- 3
state[i,t+1] <- 0 # it is defaulted to 0 anyway
} else if(surv == 1) {# state.laake[i,t+1] <- 1;
state[i,t+1] <- 1;
attendance[i,t+1] <- 1
} else if(surv == 2){ # temp. emigrated
# attendance[i,t+1] <- 0 # is anyway the default
state[i,t+1] <- 1; # state: 0 - dead. 1 male or no gender measured
# here: state = 1 means temp. emigrated or alive
}
# now probability of emigrationg again is tau[2]
# emigagain <- rbinom(1,1, tau[2]) # 1 = emig 0 = alive
# state[i,t+1] <- 1 # either way from temp. emig. no death
# assumption here is: no death after temp emig?
# state.laake[i,t+1] <- emigagain + 1 # 1 = alive, 2 = temp. emig, 3 = dead
# attendance[i,t+1] == 1 - emigagain
} else { # ie dead -
state.laake[i,t+1] <- 3
state[i,t+1] <- 0;
# since this is developed from gender version, we have states: 0 (unborn)), 1 (alive), 3 (departed)
}
}
}
}
}
# find number that are present each year
N.t <- colSums(attendance) # + add for each gender
# N1.t <- colSums(attendance[state == 1 , ]);
# N2.t <- colSums(attendance[state == 2 , ]);
# p.state <- N1.t / N.t # true state proportion for each primary capture occassion
# state.t <- matrix(0, nrow=N, ncol=1) # needed when we include the temp. emigration
# capture histories for each year
# loop over years
for (t in 1:T) {
# storage variables for this year
capture.t <- matrix(0, nrow=N, ncol=K)
# I will need this when the states are also temporary emigration states - then adapt this
# loop over individuals and assign states
# for (i in 1:N) {
# find the occasions when present
# present <- which(presence.t[i,] == 1)
# assign state at initial capture
# state.init <- 1+rbinom(1,1,alpha[2]) # if necessary, add alpha again as argument, if needed for temp. emigration modelling
# state.t[i,present[1]] <- state.init
# loop over remaining occasions when present and transition between states
# if (length(present) > 1) {
# for (k in present[2]:present[length(present)]) {
# if (state.t[i,k-1] == 1) {
# state.k <- 1+rbinom(1,1,psi[1,2]) # if necessary, add psi again as argument, if needed for temp. emigration modelling
# } else if (state.t[i,k-1] == 2) {
# state.k <- 1+rbinom(1,1,psi[2,2])
# }
# state.t[i,k] <- state.k
# }
# }
# }
# loop over individuals and check whether they were captured or not
for (i in 1:N) {
# capture.t is defaulted to 0
# find the primary occassions where they were present
if(attendance[i,t]==1) {
# loop over occasions
capture.t[i,] <- rbinom(K,1,p[t]) # needs to be adapted if temp emigration possible
# next: use time dependent capture prob! in primary time - possible would also be time dept within secondary
# for (k in 1:K) {
# determine whether they were captured or not
## capture.t[i,k] <- state.t[i,1]*rbinom(1,1,p[state.t[i,1]])
## capture.t[i,k] <- state[i]*rbinom(1,1,p[state[i] ]) # needs to be adapted if temp emigration possible
# capture.t[i,k] <- rbinom(1,1,p) # needs to be adapted if temp emigration possible
# next: use time dependent capture prob!
# }
}
}
# find which rows are all zeros in capture histories
capture.0 <- which(rowSums(capture.t) == 0) # ie for which year are all secondary capt histories = 0
# update encounter histories
for (c in capture.0) {
encounter[c,t] <- 0
}
# store state history for year t
# state[[t]] <- state.t - will be needed if temp. emigration is also a state
# store full capture history for year t
capture.full[[t]] <- c( capture.t) # capture.t
# store capture history for year t
capture[[t]] <- capture.t[-capture.0,]
}
# count those encountered each year
N.c <- colSums(encounter) # to do: count for both male and female and all
# count those who are seen at least once
N.seen <- N-length(which(rowSums(encounter) == 0)) # to do: count for both male and female and all
# return
return(list('attendance'=attendance, 'encounter'=encounter, 'state'=state, 'state.laake' = state.laake, # 'p.state' = p.state,
'capture.full'=capture.full, 'capture'=capture, 'N.attend'=N.t, 'N.encounter'=N.c, 'N.seen'=N.seen))
}
# to do: should we allow the first time point of attendance, that the animal is already temp. emigrated?
# ------------------------------------------------------------------------------
# Code to generate robust multi-state (multi-period) CRM data WITH temp. emigration
# ------------------------------------------------------------------------------
# Name: sim.data.robust.tau.time
# Objective: To generate multiple years of capture recapture data using the given parameter values, constant survival and capture prob
# Inputs: N - total number of individuals
# T - number of years
# K - number of occasions each year, allow to vary over time, can be length = 1 or T
# r - recruitment probabilities, length T, if not state dept specified
# s - survival, dependent on t
# # alpha - initial discrete state probability (length R) - seems we don't need it, maybe use again for model with temp emigration
# p.sec - capture probability, dependent on t, assumed to be constant within primary
# here: p.sec = capt prob for each sec. point k[j] in t, prob of being obs at all in the primary time t
# is then p.prim = 1 - dbinom(x=0, size=K, prob=p.sec)
# p.prim - probability of being captured at least once in the primary occassion t, time dept
# from p.prim, can derive p.sec = 1 - nthroot(x=1 - p.prim,n=K)
# - next: could allow for additional option. eg trap shyness, or linear increase/decrease within primary
# - however, these would be only to test the general program for robustness
# for specification of p.sec or p.prim: p.sec overwrites p.prim, if both are specified!
# if K differs for each t, the same p.sec for each prim time point, does not correspond to the same p.prim
# tau - probability of temporary emigration, given 1) not temp. emigrated in previous year,
# 2) temp. emigrated in previous year,
# this is now changed to be a factor which is multiplicated (1-tau)*s to the survival
# Outputs: attendance - attendance matrix, truth of which years individuals are present at the site
# encounter - encounter matrix, number of times an individuals was seen in each year
# state - state history vector for each year, truth of which state individual was in whilst present at site (male/female)
# state.laake - state history matrix for each year, truth of which state individual was in whilst present at site,
# style as in Laake paper. 0 = not yet born, 1 = alive, 2 = temp emig, 3 dead
# p.state - yearly true state (gender) proportion | attendance
# capture.full - capture history list with a matrix for each year for all individuals, no of times in t that individuals were seen
# ? capture - capture history matrix for each year, when individuals were or were not seen
# N.attend - actual number of individuals at the site each year - to do: for all + both genders
# N.encounter - number of individuals seen each year (+ gender specific) - to do: for all + both genders
# N.seen - number of individuals seen over entire study (+ gender specific) - to do: for all + both genders
# temp = sim.data.robust.tau.time(N=100, T=10, K=5, r= 0.6, s=rep(0.5,10)-seq(0.01, 0.1, length=10), p.prim=rep(0.5,10)+seq(0.01, 0.1, length=10), tau = c(0.2, 0.3)) ;
# temp = sim.data.robust.tau.time(N=100, T=10, K=c(3,3,3,3,2,2,2,2,2,2), r= 0.6, s=rep(0.5,10)-seq(0.01, 0.1, length=10), p.prim=rep(0.5,10)+seq(0.01, 0.1, length=10), tau = c(0.2, 0.3)) ;
# temp$capture.full; temp$N.attend ; temp$N.encounter; temp$N.seen
# temp$state; temp$state.laake; temp$encounter; temp$capture
# 1/11.2019: this is now recoded. survprob = s*(1-tau), emig prob = s*tau, dead prob = 1-s
sim.data.robust.tau.time <- function(N, T, K=1, r, s, p.prim=NULL, p.sec=NULL, tau) {
if(length(r)==1) r<- rep(r, times = T) else if(length(r) != T) stop("r needs to have length T");
if(length(s)==1) s<- rep(s, times = T) else if(length(s) != T) stop("s needs to have length T");
# if(length(p)==1) p<- rep(p, times = T) else if(length(p) != T) stop("p needs to have length T");
if(length(K)==1) K<- rep(K, times = T) else if(length(K) != T) stop("K needs to have length T");
if(is.null(p.prim)) {
if(is.null(p.sec)) stop("either p.prim or p.sec need to be specified") else {
p.prim = 1 - dbinom(x=0, size=K, prob=p.sec) # returns vector if K is a vector
}
}
if(is.null(p.sec)) p.sec = 1 - nthroot(1-p.prim,K);
# from here on, we use only p = p.sec for calculations
p <- p.sec
if(length(p)==1) p<- rep(p, times = T) else if(length(p) != T) stop("p.prim / p.sec needs to have length T");
if(any(s > 1)) {
stop("s must be <= 1") }
if(any(p > 1)) {
stop("p must be <= 1") }
if(any(r > 1)) {
stop("r must be <= 1") }
if(any(tau > 1)) {
stop("tau must be <= 1") }
# sp = s + tau[1];
# s <- s/sp;
# tau[1]<- tau[1]/sp
# create storage variables
attendance <- matrix(0, nrow=N, ncol=T) # alive an not temp emigrated
encounter <- matrix(0, nrow=N, ncol=T) # encounter is a matrix with T columns
# p.state <- rep(0, times = T)
capture.full <- NULL # capture.full is a list of T matrizes with each K columns
capture <- NULL
# attendance history
# generate recruitment distribution
recruitment <- rmultinom(1, N, r) # produces a matrix with rows = T = lenght r , with the number of elements first recruited in each row
# make vector of arrival times
recruitment.i <- rep(1:T, recruitment) # a number for each individual # adapt for 2-gender version
# now use
state <- matrix(0, nrow=N, ncol=T) # state = 0, and 1 if alive
# instead of state, I now use state.laake. state was in HW a list with attendance vector as elements for each secondary period
state.laake <- matrix(0, nrow=N, ncol=T) # is C_t in Laake for each individual
# state.laake: 0 not yet recruited. 1 recruited . 2 temp. emigrated. 3 departed
# state = 1 means temp. emigrated or alive
# attendance is 1 if alive and not temp emigrated!
# loop over individuals
for (i in 1:N) {
# record first attendance
attendance[i,recruitment.i[i]] <- 1 # recruitment.i[i] is the first atttendance time point
state.laake[i,recruitment.i[i]] <- 1
state[i,recruitment.i[i]] <- 1 # state should be used later to for male/female, here: just one gender
# state.laake: 0 not yet recruited. 1 recruited . 2 temp. emigrated. 3 departed
# if not recruited in final year
if (recruitment.i[i] < T) {
# loop over remaining occasions
for (t in recruitment.i[i]:(T-1)) {
# if present at site
if (attendance[i,t] == 1) {
# work out whether they survive until the next year, or temp emigrate or die
# survival <- rmultinom(1,1,c(s[t],tau[1], 1-s[t]-tau[1] ) )
# recoded 1/11/2019: death prob = 1-s[t],emig prob = s[t]*tau[2]
survival <- rmultinom(1,1,c(s[t]*(1-tau[1]),s[t]*tau[1], 1-s[t] ) )
surv <- which(survival == 1) # 1 = alive, 2 = temp. emig, 3 = dead
# store 0 or 1 following year
# state[i,t+1] <- survival;
state.laake[i,t+1] <- surv
if (surv == 3) { # state.laake[i,t+1] <- 3
state[i,t+1] <- 0 # it is defaulted to 0 anyway
} else if(surv == 1) {# state.laake[i,t+1] <- 1;
state[i,t+1] <- 1;
attendance[i,t+1] <- 1
} else if(surv == 2){ # temp. emigrated
# attendance[i,t+1] <- 0 # is anyway the default
state[i,t+1] <- 1; # state: 0 - dead. 1 male or no gender measured
# here: state = 1 means temp. emigrated or alive
}
# attendance is 1 if alive and not temp emigrated!
} else { # is either dead or temp emigrated
if (state.laake[i,t] == 2){ # temp. emigrated
# lets build in a death prob.: recoded 1/11/2019: death prob = 1-s[t],emig prob = s[t]*tau[2]
survival <- rmultinom(1,1,c(s[t]*(1-tau[2]),s[t]*tau[2], 1-s[t] ) )
surv <- which(survival == 1) # 1 = alive, 2 = temp. emig, 3 = dead
# store 0 or 1 following year
# state[i,t+1] <- survival;
state.laake[i,t+1] <- surv
if (surv == 3) { # state.laake[i,t+1] <- 3
state[i,t+1] <- 0 # it is defaulted to 0 anyway
} else if(surv == 1) {# state.laake[i,t+1] <- 1;
state[i,t+1] <- 1;
attendance[i,t+1] <- 1
} else if(surv == 2){ # temp. emigrated
# attendance[i,t+1] <- 0 # is anyway the default
state[i,t+1] <- 1; # state: 0 - dead. 1 male or no gender measured
# here: state = 1 means temp. emigrated or alive
}
# now probability of emigrationg again is tau[2]
# emigagain <- rbinom(1,1, tau[2]) # 1 = emig 0 = alive
# state[i,t+1] <- 1 # either way from temp. emig. no death
# assumption here is: no death after temp emig?
# state.laake[i,t+1] <- emigagain + 1 # 1 = alive, 2 = temp. emig, 3 = dead
# attendance[i,t+1] == 1 - emigagain
} else { # ie dead -
state.laake[i,t+1] <- 3
state[i,t+1] <- 0;
# since this is developed from gender version, we have states: 0 (unborn)), 1 (alive), 3 (departed)
}
}
}
}
}
# find number that are present each year
N.t <- colSums(attendance) # + add for each gender
# N1.t <- colSums(attendance[state == 1 , ]);
# N2.t <- colSums(attendance[state == 2 , ]);
# p.state <- N1.t / N.t # true state proportion for each primary capture occassion
# state.t <- matrix(0, nrow=N, ncol=1) # needed when we include the temp. emigration
# capture histories for each year
# loop over years
for (t in 1:T) {
# storage variables for this year
capture.t <- matrix(0, nrow=N, ncol=K[t])
#capture.tt <- matrix(0, nrow=N, ncol=1) # i am only interested in no of captures
# I will need this when the states are also temporary emigration states - then adapt this
# loop over individuals and assign states
# for (i in 1:N) {
# find the occasions when present
# present <- which(presence.t[i,] == 1)
# assign state at initial capture
# state.init <- 1+rbinom(1,1,alpha[2]) # if necessary, add alpha again as argument, if needed for temp. emigration modelling
# state.t[i,present[1]] <- state.init
# loop over remaining occasions when present and transition between states
# if (length(present) > 1) {
# for (k in present[2]:present[length(present)]) {
# if (state.t[i,k-1] == 1) {
# state.k <- 1+rbinom(1,1,psi[1,2]) # if necessary, add psi again as argument, if needed for temp. emigration modelling
# } else if (state.t[i,k-1] == 2) {
# state.k <- 1+rbinom(1,1,psi[2,2])
# }
# state.t[i,k] <- state.k
# }
# }
# }
# loop over individuals and check whether they were captured or not
for (i in 1:N) {
# capture.t is defaulted to 0
# find the primary occassions where they were present
if(attendance[i,t]==1) {
# loop over occasions
capture.t[i,] <- rbinom(K[t],1,p[t]) # outputs K values of 0 and 1
# capture.tt[i,] <- sum(capture.ti[i,]) # rbinom(1,K,p[t]) # outputs the number between 0 and K
# next: use time dependent capture prob! in primary time - possible would also be time dept within secondary
# for (k in 1:K) {
# determine whether they were captured or not
## capture.t[i,k] <- state.t[i,1]*rbinom(1,1,p[state.t[i,1]])
## capture.t[i,k] <- state[i]*rbinom(1,1,p[state[i] ]) # needs to be adapted if temp emigration possible
# capture.t[i,k] <- rbinom(1,1,p) # needs to be adapted if temp emigration possible
# next: use time dependent capture prob!
# }
encounter[i,t] <- sum(capture.t[i,]) # i am only interested in no of captures # outputs the number between 0 and K
}
}
# find which rows are all zeros in capture histories
capture.0 <- which(rowSums(capture.t) == 0) # ie for which year are all secondary capt histories = 0
# update encounter histories
for (c in capture.0) { encounter[c,t] <- 0 } # should work anyway
# store state history for year t
# state[[t]] <- state.t - will be needed if temp. emigration is also a state
# store full capture history for year t
capture.full[[t]] <- capture.t # a matrix with N rows and K[t] columns
# store capture history for year t
capture[[t]] <- capture.t[-capture.0,]
}
# count those encountered each year
N.c <- colSums(encounter >= 1) # to do: count for both male and female and all
# count those who are seen at least once
N.seen <- N-length(which(rowSums(encounter >= 1) == 0)) # to do: count for both male and female and all
# return
return(list('attendance'=attendance, 'encounter'=encounter, 'state'=state, 'state.laake' = state.laake, # 'p.state' = p.state,
'capture.full'=capture.full, 'capture'=capture, 'N.attend'=N.t, 'N.encounter'=N.c, 'N.seen'=N.seen))
}
# ------------------------------------------------------------------------------
# Code to generate multi-state (multi-period) CRM data for 2 genders
# ------------------------------------------------------------------------------
# Name: sim.data.gender
# Objective: To generate multiple years of multi-state CMR data using the given parameter values
# Inputs: Nmale - total number of male
# Nfemale - total number of female
# T - number of years
# K - number of occasions each year, constant
# r - recruitment probabilities, length T, if not state dept specified, assume constant for genders
# - can be either one value or a vector with the first value for male, second for female
# smale - male survival, constant - next: dependent on t
# sfemale - female survival, constant - next: dependent on t
# # alpha - initial discrete state probability (length R) - seems we don't need it, maybe use again for model with temp emigration
# pmale - capture probability for each state, constant, length R, for male . next: dependent on t
# pfemale - capture probability for each state, constant, length R, for female . next: dependent on t
# # psi - transition probabilities matrix - seems we don't need it, maybe use again for model with temp emigration
# pclassmal - classification probabilities for true male. vector of 3 values, classified as male/female/unknown given male
# pclassfem - classification probabilities for true female. vector of 3 values, classified as male/female/unknown given female
# pclassmal needs to sum to 1, pclassfem needs to sum to 1, last class unknown can be missing, then = 0
# Outputs: attendance - attendance matrix, truth of which years individuals are present at the site
# encounter - encounter matrix, which years individuals were or were not seen
# state - state history matrix for each year, truth of which state individual was in whilst present at site
# state.laake - state history matrix for each year, truth of which state individual was in whilst present at site,
# style as in Laake paper. 0 = not yet born, 1 = male, present, 2 = female, present, 3 dead
# p.state - yearly true state (gender) proportion | attendance
# capture.full - capture history list with a vector for each year for all individuals, when individuals were or were not seen
# capture - capture history matrix for each year, when individuals were or were not seen
# N.attend - actual number of individuals at the site each year - to do: for all + both genders
# N.encounter - number of individuals seen each year (+ gender specific) - to do: for all + both genders
# N.seen - number of individuals seen over entire study (+ gender specific) - to do: for all + both genders
# to do: should we allow the first time point of attendance, that the animal is already temp. emigrated?
# in preparation
# ------------------------------------------------------------------------------------------------
# Code to generate robust multi-state (multi-period) CRM data WITH temp. emigration for 2 genders
# -------------------------------------------------------------------------------------------------
# Name: sim.data.robust.tau.time.gender
# Objective: To generate multiple years of capture recapture data using the given parameter values, constant survival and capture prob
# Inputs: Nmale - total number of male
# Nfemale - total number of female
# T - number of years
# K - number of occasions each year, constant, next step: allow not constant
# rmale - recruitment probabilities for male, length T (or length 1 for constant)
# rfemale - recruitment probabilities for male, length T (or length 1 for constant)
# smale - male survival, length T
# sfemale - male survival, length T
# # alpha - initial discrete state probability (length R) - seems we don't need it, maybe use again for model with temp emigration
# pmale.sec - capture probability for male, dependent on t, assumed to be constant within primary
# here: p.sec = capt prob for each sec. point k[j] in t, prob of being obs at all in the primary time t
# is then p.prim = 1 - dbinom(x=0, size=K, prob=p.sec)
# pfemale.sec - capture probability for female
# pmale.prim - probability for male of being captured at least once in the primary occassion t, time dept
# pfemale.prim - probability for female
# from p.prim, can derive p.sec = 1 - nthroot(x=1 - p.prim,n=K)
# - next: could allow for additional option. eg trap shyness, or linear increase/decrease within primary
# - however, these would be only to test the general program for robustness
# taumale - probability of temporary emigration for male (length = 2),
# given 1) not temp. emigrated in previous year,
# 2) temp. emigrated in previous year,
# this is now changed to be a factor which is multiplicated (1-tau)*s to the survival
# taufemale - probability of temporary emigration for female
# pclassmal - classification probabilities for true male. vector of 3 values, classified as male/female/unknown given male
# pclassfem - classification probabilities for true female. vector of 3 values, classified as male/female/unknown given female
# pclassmal needs to sum to 1, pclassfem needs to sum to 1, last class unknown can be missing, then = 0
# random - whether to randomly mix together male and female, ie. mix up all observations
# Outputs: attendance - attendance matrix, truth of which years individuals are present at the site
# encounter - encounter matrix, number of times an individuals was seen in each year, dim = N x T
# gencounter - encounter array, number of times an individuals was captured and classified as male [,,1], female [,,2], unknown [,,3] in each year, dim = N x T x 3
# state - state history vector for each year, truth of which state individual was in whilst present at site (0 = not present 1 = male, 2 = female)
# state.laake - state history matrix for each year, truth of which state individual was in whilst present at site,
# style as in Laake paper. 0 = not yet born, 1 = alive, 2 = temp emig, 3 dead
# p.state - yearly true state (gender) proportion | attendance
# capture.full - capture history list with a matrix for each year for all individuals, no of times in t that individuals were seen
# ? capture - capture history matrix for each year, when individuals were or were not seen
# N.attend - actual number of individuals at the site each year - to do: for all + both genders
# N.encounter - number of individuals seen each year (+ gender specific) - to do: for all + both genders
# N.seen - number of individuals seen over entire study (+ gender specific) - to do: for all + both genders
# temp = sim.data.robust.tau.time(N=100, T=10, K=5, r= 0.6, s=rep(0.5,10)-seq(0.01, 0.1, length=10), p.prim=rep(0.5,10)+seq(0.01, 0.1, length=10), tau = c(0.2, 0.3)) ;
# temp$capture.full; temp$N.attend ; temp$N.encounter; temp$N.seen
# temp$state; temp$state.laake; temp$encounter; temp$capture
# 1/11.2019: this is now recoded. survprob = s*(1-tau), emig prob = s*tau, dead prob = 1-s
sim.data.gender <- function(Nmale, Nfemale ,T, K=1, rmale, rfemale, smale,sfemale ,pmale.prim=NULL, pfemale.prim=NULL, pmale.sec=NULL,pfemale.sec=NULL,
taumale , taufemale, pmale, pfemale, pclassmal, pclassfem, random = FALSE) {
sim.data.robust.tau.time.gender <- function(N, T, K=1, r, s, p.prim=NULL, p.sec=NULL, tau) {
if(sum(pclassmal) != 1 ) stop("classification probabilities must sum up to 1!")
if(sum(pclassfem) != 1 ) stop("classification probabilities must sum up to 1!")
if(length(pclassmal) == 2) pclassmal <- c(pclassmal, 0)
if(length(pclassfem) == 2) pclassfem <- c(pclassfem, 0)
if(any(smale < 0) | any(sfemale <0 ) | any(pmale < 0) | any(pfemale < 0) | any(smale >1) | any(sfemale >1) | any(pmale >1) | any(pfemale >1) ) stop(
"probabilities must have values between 0 and 1" )
if(is.null(pfemale.prim)) {
if(is.null(pfemale.sec)) stop("either pfemale.prim or p.sec need to be specified") else {
pfemale.prim = 1 - dbinom(x=0, size=K, prob=pfemale.sec)
}
}
if(is.null(pfemale.sec)) pfemale.sec = 1 - nthroot(1-pfemale.prim,K);
# from here on, we use only p = p.sec for calculations
#p <- pfemale.sec
if(is.null(pmale.prim)) {
if(is.null(pmale.sec)) stop("either pmale.prim or pmale.sec need to be specified") else {
pmale.prim = 1 - dbinom(x=0, size=K, prob=pmale.sec)
}
}
if(is.null(pmale.sec)) pmale.sec = 1 - nthroot(1-pmale.prim,K);
# from here on, we use only p = p.sec for calculations
#p <- p.sec
if(length(rmale)==1) rmale<- rep(rmale, times = T) else if(length(rmale) != T) stop("rmale needs to have length T");
if(length(rfemale)==1) rfemale<- rep(rfemale, times = T) else if(length(rfemale) != T) stop("rfemale needs to have length T");
if(length(smale)==1) smale<- rep(smale, times = T) else if(length(smale) != T) stop("smale needs to have length T");
if(length(sfemale)==1) sfemale<- rep(sfemale, times = T) else if(length(sfemale) != T) stop("sfemale needs to have length T");
if(length(pfemale.sec)==1) pfemale.sec<- rep(pfemale.sec, times = T) else if(length(pfemale.sec) != T) stop("pfemale.sec needs to have length T");
if(length(pmale.sec)==1) pmale.sec<- rep(pmale.sec, times = T) else if(length(pmale.sec) != T) stop("pmale.sec needs to have length T");
if(any(rmale > 1)) {
stop("r must be <= 1") }
if(any(rfemale > 1)) {
stop("r must be <= 1") }
if(any(taumale > 1)) {
stop("taumale must be <= 1") }
if(any(taufemale > 1)) {
stop("taufemale must be <= 1") }
# sp = s + tau[1];
# s <- s/sp;
# tau[1]<- tau[1]/sp
testsimmale = sim.data.robust.tau.time(N=Nmale, T=T, K=K, r=rmale, s=smale, p.sec=pmale.sec, tau = taumale)
testsimfemale = sim.data.robust.tau.time(N=Nfemale, T=T, K=K, r=rfemale, s=sfemale, p.sec=pfemale.sec, tau = taufemale)
# go on here!
# sim.data.robust.tau.time(N, T, K=1, r, s, p.prim=NULL, p.sec=NULL, tau)
# create storage variables
attendance <- matrix(0, nrow=N, ncol=T) # alive an not temp emigrated
encounter <- matrix(0, nrow=N, ncol=T) # encounter is a matrix with T columns
# p.state <- rep(0, times = T)
capture.full <- NULL # capture.full is a list of T matrizes with each K columns
capture <- NULL
# attendance history
# generate recruitment distribution
recruitment <- rmultinom(1, N, r) # produces a matrix with rows = T = lenght r , with the number of elements first recruited in each row
# make vector of arrival times
recruitment.i <- rep(1:T, recruitment) # a number for each individual # adapt for 2-gender version
# now use
state <- matrix(0, nrow=N, ncol=T) # state = 0, and 1 if alive
# instead of state, I now use state.laake. state was in HW a list with attendance vector as elements for each secondary period
state.laake <- matrix(0, nrow=N, ncol=T) # is C_t in Laake for each individual
# state.laake: 0 not yet recruited. 1 recruited . 2 temp. emigrated. 3 departed
# state = 1 means temp. emigrated or alive
# attendance is 1 if alive and not temp emigrated!
# loop over individuals
for (i in 1:N) {
# record first attendance
attendance[i,recruitment.i[i]] <- 1 # recruitment.i[i] is the first atttendance time point
state.laake[i,recruitment.i[i]] <- 1
state[i,recruitment.i[i]] <- 1 # state should be used later to for male/female, here: just one gender
# state.laake: 0 not yet recruited. 1 recruited . 2 temp. emigrated. 3 departed
# if not recruited in final year
if (recruitment.i[i] < T) {
# loop over remaining occasions
for (t in recruitment.i[i]:(T-1)) {
# if present at site
if (attendance[i,t] == 1) {
# work out whether they survive until the next year, or temp emigrate or die
# recoded 1/11/2019: death prob = 1-s[t],emig prob = s[t]*tau[2]
survival <- rmultinom(1,1,c(s[t]*(1-tau[1]),s[t]*tau[1], 1-s[t] ) )
surv <- which(survival == 1) # 1 = alive, 2 = temp. emig, 3 = dead
# store 0 or 1 following year
# state[i,t+1] <- survival;
state.laake[i,t+1] <- surv
if (surv == 3) { # state.laake[i,t+1] <- 3
state[i,t+1] <- 0 # it is defaulted to 0 anyway
} else if(surv == 1) {# state.laake[i,t+1] <- 1;
state[i,t+1] <- 1;
attendance[i,t+1] <- 1
} else if(surv == 2){ # temp. emigrated
# attendance[i,t+1] <- 0 # is anyway the default
state[i,t+1] <- 1; # state: 0 - dead. 1 male or no gender measured
# here: state = 1 means temp. emigrated or alive
}
# attendance is 1 if alive and not temp emigrated!
} else { # is either dead or temp emigrated
if (state.laake[i,t] == 2){ # temp. emigrated
# lets build in a death prob.: recoded 1/11/2019: death prob = 1-s[t],emig prob = s[t]*tau[2]
survival <- rmultinom(1,1,c(s[t]*(1-tau[2]),s[t]*tau[2], 1-s[t] ) )
surv <- which(survival == 1) # 1 = alive, 2 = temp. emig, 3 = dead
# store 0 or 1 following year
# state[i,t+1] <- survival;
state.laake[i,t+1] <- surv
if (surv == 3) { # state.laake[i,t+1] <- 3
state[i,t+1] <- 0 # it is defaulted to 0 anyway
} else if(surv == 1) {# state.laake[i,t+1] <- 1;
state[i,t+1] <- 1;
attendance[i,t+1] <- 1
} else if(surv == 2){ # temp. emigrated
# attendance[i,t+1] <- 0 # is anyway the default
state[i,t+1] <- 1;
# here: state = 1 means temp. emigrated or alive
}
} else { # ie dead -
state.laake[i,t+1] <- 3
state[i,t+1] <- 0;
# since this is developed from gender version, we have states: 0 (unborn)), 1 (alive), 3 (departed)
}
}
}
}
}
# find number that are present each year
N.t <- colSums(attendance) # + add for each gender
# N1.t <- colSums(attendance[state == 1 , ]);
# N2.t <- colSums(attendance[state == 2 , ]);
# p.state <- N1.t / N.t # true state proportion for each primary capture occassion
# state.t <- matrix(0, nrow=N, ncol=1) # needed when we include the temp. emigration
# capture histories for each year
# loop over years
for (t in 1:T) {
# storage variables for this year
capture.t <- matrix(0, nrow=N, ncol=K)
# loop over individuals and check whether they were captured or not
for (i in 1:N) {
# capture.t is defaulted to 0
# find the primary occassions where they were present
if(attendance[i,t]==1) {
# loop over occasions
capture.t[i,] <- rbinom(K,1,p[t]) # outputs K values of 0 and 1
encounter[i,t] <- sum(capture.t[i,]) # i am only interested in no of captures # outputs the number between 0 and K
}
}
# find which rows are all zeros in capture histories
capture.0 <- which(rowSums(capture.t) == 0) # ie for which year are all secondary capt histories = 0
# update encounter histories
for (c in capture.0) { encounter[c,t] <- 0 } # should work anyway
# store state history for year t
# state[[t]] <- state.t - will be needed if temp. emigration is also a state
# store full capture history for year t
capture.full[[t]] <- capture.t # a matrix with N rows and K columns
# store capture history for year t
capture[[t]] <- capture.t[-capture.0,]
}
# count those encountered each year
N.c <- colSums(encounter >= 1) # to do: count for both male and female and all
# count those who are seen at least once
N.seen <- N-length(which(rowSums(encounter >= 1) == 0)) # to do: count for both male and female and all
# return
return(list('attendance'=attendance, 'encounter'=encounter, 'state'=state, 'state.laake' = state.laake, # 'p.state' = p.state,
'capture.full'=capture.full, 'capture'=capture, 'N.attend'=N.t, 'N.encounter'=N.c, 'N.seen'=N.seen))
}
| /simdata_UN_01112019.r | no_license | UlrikeNaumann/CMR_Telfair | R | false | false | 80,608 | r | # HW, - adapted by UN - Estimating Abundance from multiple sampling capture recatpure data via multi-state
# simulating capture recapture data
require(pracma)
# ------------------------------------------------------------------------------
# Code to generate multi-state (multi-period) CRM data for 2 genders
# ------------------------------------------------------------------------------
# Name: sim.data.gender
# Objective: To generate multiple years of multi-state CMR data using the given parameter values
# Inputs: Nmale - total number of male
# Nfemale - total number of female
# T - number of years
# K - number of occasions each year, constant
# r - recruitment probabilities, length T, if not state dept specified, assume constant for genders
# - can be either one value or a vector with the first value for male, second for female
# smale - male survival, constant - next: dependent on t
# sfemale - female survival, constant - next: dependent on t
# # alpha - initial discrete state probability (length R) - seems we don't need it, maybe use again for model with temp emigration
# pmale - capture probability for each state, constant, length R, for male . next: dependent on t
# pfemale - capture probability for each state, constant, length R, for female . next: dependent on t
# # psi - transition probabilities matrix - seems we don't need it, maybe use again for model with temp emigration
# pclassmal - classification probabilities for true male. vector of 3 values, classified as male/female/unknown given male
# pclassfem - classification probabilities for true female. vector of 3 values, classified as male/female/unknown given female
# pclassmal needs to sum to 1, pclassfem needs to sum to 1, last class unknown can be missing, then = 0
# Outputs: attendance - attendance matrix, truth of which years individuals are present at the site
# encounter - encounter matrix, which years individuals were or were not seen
# state - state history matrix for each year, truth of which state individual was in whilst present at site
# state.laake - state history matrix for each year, truth of which state individual was in whilst present at site,
# style as in Laake paper. 0 = not yet born, 1 = male, present, 2 = female, present, 3 dead
# p.state - yearly true state (gender) proportion | attendance
# capture.full - capture history list with a vector for each year for all individuals, when individuals were or were not seen
# capture - capture history matrix for each year, when individuals were or were not seen
# N.attend - actual number of individuals at the site each year - to do: for all + both genders
# N.encounter - number of individuals seen each year (+ gender specific) - to do: for all + both genders
# N.seen - number of individuals seen over entire study (+ gender specific) - to do: for all + both genders
sim.data.gender <- function(Nmale, Nfemale ,T, K=1, r, smale,sfemale ,
pmale, pfemale, pclassmal, pclassfem, random = FALSE, psi = matrix(c(1,0,0,1), ncol=2,nrow=2)) {
if(sum(pclassmal) != 1 ) stop("classification probabilities must sum up to 1!")
if(sum(pclassfem) != 1 ) stop("classification probabilities must sum up to 1!")
if(length(pclassmal) == 2) pclassmal <- c(pclassmal, 0)
if(length(pclassfem) == 2) pclassfem <- c(pclassfem, 0)
if(smale < 0 | sfemale <0 | pmale < 0 | pfemale < 0 |smale >1 | sfemale >1 | pmale >1 | pfemale >1 ) stop(
"probabilities must have values between 0 and 1" )
# now run the simulation for male
# possibly change how N is coded in sim.data! to avoid having to provide 2 values
testsimmale = sim.data(N=c(Nmale,0), T=T, K=K, r=rep(0.2, times=5), s=smale, p = pmale)
# adjust the state for the animals where state was falsely coded
# we need testsimmale$state.laake, testsimmale$encounter, pclassmal
# state.obsm: 0 = not observed. 1 = observed as male, 2 = observed as female, 3 = observed as unknown gender
# get multinomial draws
tmp <- rmultinom(n=sum(testsimmale$attendance), size=1, prob=pclassmal)
# make these into a vector of 1,2, or 3
obsgender <- apply(tmp , MARGIN=2, FUN = function(x) which(x == 1))
state.obsm <- matrix(0, nrow = Nmale, ncol = T)
state.encm <- matrix(0, nrow = Nmale, ncol = 3)
noencounters <- rowSums(testsimmale$encounter)
running <- 1
for(i in 1:length(noencounters)){
if(noencounters[i]!= 0){ # if 0, go to next animal
# get no. of encounters per animal
wh <- which(testsimmale$encounter == 1)
state.obsm[i,wh] <- obsgender[running:(running+noencounters[i] - 1)]
# how many of state.obs[i,wh] are respectively 1, 2 or 3
state.encm[i,] <- c(sum(state.obsm[i,wh]==1) , sum(state.obsm[i,wh]==2), sum(state.obsm[i,wh]==3) )
# code state as 3 numbers for each indiv.: of all obs. times obs as male/female/unknown
running <- running+noencounters[i]
}
}
testsimfemale = sim.data(N=c(0, Nfemale), T=T, K=K, r=rep(0.2, times=5), s=sfemale, p = pfemale)
# adjust the state for the animals where state was falsely coded
# we need testsimmale$state.laake, testsimmale$encounter, pclassmal
# state.obsf: 0 = not observed. 1 = observed as male, 2 = observed as female, 3 = observed as unknown gender
# get multinomial draws
tmp <- rmultinom(n=sum(testsimfemale$attendance), size=1, prob=pclassmal)
# make these into a vector of 1,2, or 3
obsgender <- apply(tmp , MARGIN=2, FUN = function(x) which(x == 1))
state.obsf <- matrix(0, nrow = Nmale, ncol = T)
state.encf <- matrix(0, nrow = Nmale, ncol = 3)
noencounters <- rowSums(testsimfemale$encounter)
running <- 1
for(i in 1:length(noencounters)){
if(noencounters[i]!= 0){ # if 0, go to next animal
# get no. of encounters per animal
wh <- which(testsimfemale$encounter == 1)
state.obsf[i,wh] <- obsgender[running:(running+noencounters[i] - 1)]
# how many of state.obs[i,wh] are respectively 1, 2 or 3
state.encf[i,] <- c(sum(state.obsf[i,wh]==1) , sum(state.obsf[i,wh]==2), sum(state.obsf[i,wh]==3) )
# code state as 3 numbers for each indiv.: of all obs. times obs as male/female/unknown
running <- running+noencounters[i]
}
}
# TO DO
# now combine the results from testsimfemale and testsimmale
# observed gender proportion at each time point. HERE, we ignore whether the same animal is assessed with different gender
# at different time point. we have male, female, uncertain.
p.state.obs <- matrix(0, ncol = T, row = 3)
p.state.obsN <- matrix(0, ncol = T, row = 3)
state.enc <- rbind( state.encm , state.encf )
state.obs <- rbind(state.obsm, state.obsf)
for(t in 1:T){
p.state.obsN[,i] <- c( sum( state.obs[,i] == 1), sum( state.obs[,i] == 2),sum( state.obs[,i] == 3) )
p.state.obs[,i] <- p.state.obsN[,i] / sum( p.state.obsN[,i])
}
# what is the estimated gender proportion after readjusting the gender for animals with uncertain gender assessment
# p.state.obs.corrected # this term will be needed for decoding algorithm!
#TO DO
# eg for each animal where gender is unclear, we could use an extra category: unclear
if(random){
# randomly mix together male and female, ie. mix up all observations
neworder <- order( rnorm(sum(Nmale, Nfemale)) )
# Nmale, Nfemale
# frand = rbinom(sum(Nmale, Nfemale),1,.5) # works only if the same number of male and female
# does not work, the number needs to be exact
# neworder[frand == 0] <- 1:Nmale
# neworder[frand == 1] <-(Nmale+1):(Nmale+Nfemale)
# use neworder to reorder all outputs
# now reorder all outputs
attendance <- attendance[neworder ,]
encounter <- encounter[neworder ,]
state <- state[neworder]
state.laake <- state.laake[neworder ,];
# p.state # true gender proportion
for(j in 1:T){
capture.full[[j]] <- capture.full[[j]][neworder]
capture.0 <- which(capture.full[[j]] == 0)
capture[[j]] <- capture.full[[j]][- capture.0]
}
}
# N.obs = number of individuals seen each year (observed gender)
N.t <- matrix(0, ncol = T, nrow = 3)
N.t[2,] <- testsimmale$N.attend
N.t[3,] <- testsimfemale$N.attend
N.t[1,] <- N.t[3,] + N.t[2,];
# N.c = N.encounter - number of individuals seen each year (true gender)
N.c <- matrix(0, ncol = T, nrow = 3)
N.c[2,] <- testsimmale$N.encounter
N.c[3,] <- testsimfemale$N.encounter
N.c[1,] <- N.c[3,] + N.c[2,];
N.obs <-
nsee <- c(testsimmale$N.seen , testsimfemale$N.seen)
# state.laake: 0 not yet recruited. 1 recruited male. 2 recruited female. 3 departed
# to do: still need to refine this
return(list('attendance'=attendance, 'encounter'=encounter, 'state'=state, 'state.laake' = state.laake, 'p.state' = p.state,
'p.state.obs' = p.state.obs, 'capture.full'=capture.full, 'capture'=capture, 'N.attend'=N.t,
'N.encounter'=N.c, 'N.obs' = N.obs , 'N.seen'= c(sum(nsee),nsee ) ))
}
#head(testsim1$state.laake)
#head(testsim1$encounter)
# dim(testsim1$capture); head(testsim1$capture)
# testsim1$N.encounter
# ------------------------------------------------------------------------------
# Code to generate multi-state (multi-period) CRM data
# ------------------------------------------------------------------------------
# Name: sim.data
# Objective: To generate multiple years of multi-state stopover data using the given parameter values
# Inputs: N - total number of individuals # to do: 2 numbers - male and female
# if only one number specified, assume 1/2 male, half female
# T - number of years
# K - number of occasions each year, constant
# r - recruitment probabilities, length T, if not state dept specified, assume constant for genders - to do: make dependent on gender
# s - survival, constant - to do: make dependent on gender. next: dependent on t
# # alpha - initial discrete state probability (length R) - seems we don't need it, maybe use again for model with temp emigration
# p - capture probability for each state, constant, length R -to do: make dependent on gender. next: dependent on t
# # psi - transition probabilities matrix - seems we don't need it, maybe use again for model with temp emigration
# Outputs: attendance - attendance matrix, truth of which years individuals are present at the site
# encounter - encounter matrix, which years individuals were or were not seen
# state - state history vector for each year, truth of which state individual was in whilst present at site (male/female)
# state.laake - state history matrix for each year, truth of which state individual was in whilst present at site,
# style as in Laake paper. 0 = not yet born, 1 = male, present, 2 = female, present, 3 dead
# p.state - yearly true state (gender) proportion | attendance
# capture.full - capture history list with a vector for each year for all individuals, when individuals were or were not seen
# capture - capture history matrix for each year, when individuals were or were not seen
# N.attend - actual number of individuals at the site each year - to do: for all + both genders
# N.encounter - number of individuals seen each year (+ gender specific) - to do: for all + both genders
# N.seen - number of individuals seen over entire study (+ gender specific) - to do: for all + both genders
sim.data <- function(N, T, K=1, r, s, p, psi = matrix(c(1,0,0,1), ncol=2,nrow=2)) {
if (length(N)==1) Ngender <- c(floor(N/2) , ceiling(N/2)) else if(length(N)==2) Ngender <- N else {
stop("Only 2 different states (gender). Please specifify N correctly.") }
# if N is one number but not even, the first state will have 1 less individuum then the second state
# reassign N
N <- Ngender[1] + Ngender[2] ;
# create storage variables
attendance <- matrix(0, nrow=N, ncol=T) # next: array with gender as dimension
encounter <- matrix(1, nrow=N, ncol=T) # next: array with gender as dimension
p.state <- rep(0, times = T)
capture.full <- NULL
capture <- NULL
if(length(r)==1) r<- rep(r, times = T) else if(length(r) != T) stop("r needs to have length T");
# attendance history
# generate recruitment distribution
# recruitment <- rmultinom(1, N, r) # to do. with N and r as 2dim vector (gender)
recruitment1 <- rmultinom(1, Ngender[1], r)
recruitment2 <- rmultinom(1, Ngender[2], r)
# make vector of arrival times
# recruitment.i <- rep(1:T, recruitment) # adapt for 2-gender version
recruitment1.i <- rep(1:T, recruitment1)
recruitment2.i <- rep(1:T, recruitment2)
recruitment.i <- c(recruitment1.i, recruitment2.i);
# state <- # true state (gender), vector of length N
state <- c(rep(1, times = Ngender[1]), rep(2, times = Ngender[2]) );
state.laake <- matrix(0, nrow=N, ncol=T) # is C_t in Laake for each individual
# loop over individuals
for (i in 1:N) {
# record first attendance
attendance[i,recruitment.i[i]] <- 1 # recruitment.i[i] is the first atttendance time point
state.laake[i,recruitment.i[i]] <- state[i]
# state.laake: 0 not yet recruited. 1 recruited male. 2 recruited female. 3 departed
# if not recruited in final year
if (recruitment.i[i] < T) {
# loop over remaining occasions
for (t in recruitment.i[i]:(T-1)) {
# if present at site
if (attendance[i,t] == 1) {
# work out whether they survive until the next year
survival <- rbinom(1,1,s) # adapt with survival prob s dependent on gender
# store 0 or 1 following year
attendance[i,t+1] <- survival
if (survival == 0) state.laake[i,t+1] <- 3 else state.laake[i,t+1] <- state[i];
} else state.laake[i,t+1] <- 3 # ie departed
}
}
}
# find number that are present each year
N.t <- colSums(attendance) # + add for each gender
N1.t <- colSums(attendance[state == 1 , ]);
N2.t <- colSums(attendance[state == 2 , ]);
p.state <- N1.t / N.t # true state proportion for each primary capture occassion
# state.t <- matrix(0, nrow=N, ncol=1) # needed when we include the temp. emigration
# capture histories for each year
# loop over years
for (t in 1:T) {
# storage variables for this year
capture.t <- matrix(0, nrow=N, ncol=K)
# I will need this when the states are also temporary emigration states - then adapt this
# loop over individuals and assign states
# for (i in 1:N) {
# find the occasions when present
# present <- which(presence.t[i,] == 1)
# assign state at initial capture
# state.init <- 1+rbinom(1,1,alpha[2]) # if necessary, add alpha again as argument, if needed for temp. emigration modelling
# state.t[i,present[1]] <- state.init
# loop over remaining occasions when present and transition between states
# if (length(present) > 1) {
# for (k in present[2]:present[length(present)]) {
# if (state.t[i,k-1] == 1) {
# state.k <- 1+rbinom(1,1,psi[1,2]) # if necessary, add psi again as argument, if needed for temp. emigration modelling
# } else if (state.t[i,k-1] == 2) {
# state.k <- 1+rbinom(1,1,psi[2,2])
# }
# state.t[i,k] <- state.k
# }
# }
# }
# loop over individuals and check whether they were captured or not
for (i in 1:N) {
# capture.t is defaulted to 0
# find the primary occassions where they were present
if(attendance[i,t]==1) {
# loop over occasions
for (k in 1:K) {
# determine whether they were captured or not
# capture.t[i,k] <- state.t[i,1]*rbinom(1,1,p[state.t[i,1]])
capture.t[i,k] <- state[i]*rbinom(1,1,p[state[i] ]) # needs to be adapted if temp emigration possible
} }
}
# find which rows are all zeros in capture histories
capture.0 <- which(rowSums(capture.t) == 0)
# update encounter histories
for (c in capture.0) {
encounter[c,t] <- 0
}
# store state history for year t
# state[[t]] <- state.t - will be needed if temp. emigration is also a state
# store full capture history for year t
capture.full[[t]] <- c( capture.t) # capture.t
# store capture history for year t
capture[[t]] <- capture.t[-capture.0,]
}
# count those encountered each year
N.c <- colSums(encounter) # to do: count for both male and female and all
# count those who are seen at least once
N.seen <- N-length(which(rowSums(encounter) == 0)) # to do: count for both male and female and all
# return
return(list('attendance'=attendance, 'encounter'=encounter, 'state'=state, 'state.laake' = state.laake, 'p.state' = p.state,
'capture.full'=capture.full, 'capture'=capture, 'N.attend'=N.t, 'N.encounter'=N.c, 'N.seen'=N.seen))
}
# example
# testsim1 = sim.data(N=1000, T=5, K=1, r=rep(0.2, times=5), s=0.3, p = c(0.3,0.5))
# testsim = sim.data(N=c(1000,0), T=5, K=1, r=rep(0.2, times=5), s=0.3, p = 0.4) # only male
# testsim1$p.state; head(testsim1$encounter)
# head(testsim1$state); tail(testsim1$state)
# head(testsim1$state.laake); tail(testsim1$state.laake)
# head(testsim1$attendance)
# dim(testsim$attendance);
# head(testsim$state.laake); tail(testsim$state.laake)
# ------------------------------------------------------------------------------
# Code to generate multi-state (multi-period) CRM data WITHOUT gender
# ------------------------------------------------------------------------------
# Name: sim.data.0
# Objective: To generate multiple years of capture recapture data using the given parameter values, constant survival and capture prob
# Inputs: N - total number of individuals
# T - number of years
# K - number of occasions each year, constant
# r - recruitment probabilities, length T, if not state dept specified
# s - survival, constant - . next: dependent on t
# # alpha - initial discrete state probability (length R) - seems we don't need it, maybe use again for model with temp emigration
# p - capture probability for each state, constant, length R -to do: make dependent on gender. next: dependent on t
# Outputs: attendance - attendance matrix, truth of which years individuals are present at the site
# encounter - encounter matrix, which years individuals were or were not seen
# state - state history vector for each year, truth of which state individual was in whilst present at site (male/female)
# state.laake - state history matrix for each year, truth of which state individual was in whilst present at site,
# style as in Laake paper. 0 = not yet born, 1 = present, 3 = dead # not yet: 1 = male, present, 2 = female, present,
# p.state - yearly true state (gender) proportion | attendance
# capture.full - capture history list with a vector for each year for all individuals, when individuals were or were not seen
# capture - capture history matrix for each year, when individuals were or were not seen
# N.attend - actual number of individuals at the site each year - to do: for all + both genders
# N.encounter - number of individuals seen each year (+ gender specific) - to do: for all + both genders
# N.seen - number of individuals seen over entire study (+ gender specific) - to do: for all + both genders
sim.data.0 <- function(N, T, K=1, r, s, p, psi = matrix(c(1,0,0,1), ncol=2,nrow=2)) {
# if (length(N)==1) Ngender <- c(floor(N/2) , ceiling(N/2)) else if(length(N)==2) Ngender <- N else {
# stop("Only 2 different states (gender). Please specifify N correctly.") }
# if N is one number but not even, the first state will have 1 less individuum then the second state
# reassign N
# N <- Ngender[1] + Ngender[2] ;
# create storage variables
attendance <- matrix(0, nrow=N, ncol=T) # next: array with gender as dimension
encounter <- matrix(1, nrow=N, ncol=T) # next: array with gender as dimension
# p.state <- rep(0, times = T)
capture.full <- NULL
capture <- NULL
if(length(r)==1) r<- rep(r, times = T) else if(length(r) != T) stop("r needs to have length T");
# attendance history
# generate recruitment distribution
recruitment <- rmultinom(1, N, r) # produces a matrix wiht rows = T = lenght r , with the number of elements first recruited in each row
# to do. with N and r as 2dim vector (gender)
# recruitment1 <- rmultinom(1, Ngender[1], r)
# recruitment2 <- rmultinom(1, Ngender[2], r)
# make vector of arrival times
recruitment.i <- rep(1:T, recruitment) # a number for each individual # adapt for 2-gender version
# recruitment1.i <- rep(1:T, recruitment1)
# recruitment2.i <- rep(1:T, recruitment2)
# recruitment.i <- c(recruitment1.i, recruitment2.i);
# state <- # true state (gender), vector of length N
# state <- c(rep(1, times = Ngender[1]), rep(2, times = Ngender[2]) );
# state <- rep(1, times = N)
# now use
state <- matrix(0, nrow=N, ncol=T) # state = 0, and 1 if alive
# instead of state, I now use state.laake. state was in HW a list with attendance vector as elements for each secondary period
state.laake <- matrix(0, nrow=N, ncol=T) # is C_t in Laake for each individual
# loop over individuals
for (i in 1:N) {
# record first attendance
attendance[i,recruitment.i[i]] <- 1 # recruitment.i[i] is the first atttendance time point
state.laake[i,recruitment.i[i]] <- 1 # state[i]
state[i,recruitment.i[i]] <- 1
# state.laake: 0 not yet recruited. 1 recruited male. 2 recruited female. 3 departed
# if not recruited in final year
if (recruitment.i[i] < T) {
# loop over remaining occasions
for (t in recruitment.i[i]:(T-1)) {
# if present at site
if (attendance[i,t] == 1) {
# work out whether they survive until the next year
survival <- rbinom(1,1,s) # adapt with survival prob s dependent on gender
# store 0 or 1 following year
attendance[i,t+1] <- survival
state[i,t+1] <- survival;
if (survival == 0) { state.laake[i,t+1] <- 3
# state[i,t+1] <- 0 # it is defaulted to 0 anyway
} else { state.laake[i,t+1] <- 1;
# state[i,t+1] <- 1;
}# state[i];
} else { # ie, between first recruitment and end of study are some time points, but has died now
state.laake[i,t+1] <- 3 # ie departed -
state[i,t+1] <- 0;
# since this is developed from gender version, we have states: 0 (unborn)), 1 (alive), 3 (departed)
}
}
}
}
# find number that are present each year
N.t <- colSums(attendance) # + add for each gender
# N1.t <- colSums(attendance[state == 1 , ]);
# N2.t <- colSums(attendance[state == 2 , ]);
# p.state <- N1.t / N.t # true state proportion for each primary capture occassion
# state.t <- matrix(0, nrow=N, ncol=1) # needed when we include the temp. emigration
# capture histories for each year
# loop over years
for (t in 1:T) {
# storage variables for this year
capture.t <- matrix(0, nrow=N, ncol=K)
# I will need this when the states are also temporary emigration states - then adapt this
# loop over individuals and assign states
# for (i in 1:N) {
# find the occasions when present
# present <- which(presence.t[i,] == 1)
# assign state at initial capture
# state.init <- 1+rbinom(1,1,alpha[2]) # if necessary, add alpha again as argument, if needed for temp. emigration modelling
# state.t[i,present[1]] <- state.init
# loop over remaining occasions when present and transition between states
# if (length(present) > 1) {
# for (k in present[2]:present[length(present)]) {
# if (state.t[i,k-1] == 1) {
# state.k <- 1+rbinom(1,1,psi[1,2]) # if necessary, add psi again as argument, if needed for temp. emigration modelling
# } else if (state.t[i,k-1] == 2) {
# state.k <- 1+rbinom(1,1,psi[2,2])
# }
# state.t[i,k] <- state.k
# }
# }
# }
# loop over individuals and check whether they were captured or not
for (i in 1:N) {
# capture.t is defaulted to 0
# find the primary occassions where they were present
if(attendance[i,t]==1) {
# loop over occasions
capture.t[i,] <- rbinom(K,1,p) # needs to be adapted if temp emigration possible
# next: use time dependent capture prob! in primary time - possible would also be time dept within secondary
# for (k in 1:K) {
# determine whether they were captured or not
## capture.t[i,k] <- state.t[i,1]*rbinom(1,1,p[state.t[i,1]])
## capture.t[i,k] <- state[i]*rbinom(1,1,p[state[i] ]) # needs to be adapted if temp emigration possible
# capture.t[i,k] <- rbinom(1,1,p) # needs to be adapted if temp emigration possible
# next: use time dependent capture prob!
# }
}
}
# find which rows are all zeros in capture histories
capture.0 <- which(rowSums(capture.t) == 0) # ie for which year are all secondary capt histories = 0
# update encounter histories
for (c in capture.0) {
encounter[c,t] <- 0
}
# store state history for year t
# state[[t]] <- state.t - will be needed if temp. emigration is also a state
# store full capture history for year t
capture.full[[t]] <- c( capture.t) # capture.t
# store capture history for year t
capture[[t]] <- capture.t[-capture.0,]
}
# count those encountered each year
N.c <- colSums(encounter) # to do: count for both male and female and all
# count those who are seen at least once
N.seen <- N-length(which(rowSums(encounter) == 0)) # to do: count for both male and female and all
# return
return(list('attendance'=attendance, 'encounter'=encounter, 'state'=state, 'state.laake' = state.laake, # 'p.state' = p.state,
'capture.full'=capture.full, 'capture'=capture, 'N.attend'=N.t, 'N.encounter'=N.c, 'N.seen'=N.seen))
}
# ------------------------------------------------------------------------------
# Code to generate multi-state (multi-period) CRM data WITH temp. emigration
# ------------------------------------------------------------------------------
# this is now out of date, and replaced by sim.data.tau.time
# Name: sim.data.tau
# Objective: To generate multiple years of capture recapture data using the given parameter values, constant survival and capture prob
# Inputs: N - total number of individuals
# T - number of years
# K - number of occasions each year, constant
# r - recruitment probabilities, length T, if not state dept specified
# s - survival, constant - . next: dependent on t
# # alpha - initial discrete state probability (length R) - seems we don't need it, maybe use again for model with temp emigration
# p - capture probability for each state, constant, length R -to do: make dependent on gender. next: dependent on t
# tau - probability of temporary emigration, given 1) not temp. emigrated in previous year,
# 2) temp. emigrated in previous year,
# Outputs: attendance - attendance matrix, truth of which years individuals are present at the site
# encounter - encounter matrix, which years individuals were or were not seen
# state - state history vector for each year, truth of which state individual was in whilst present at site (male/female)
# state.laake - state history matrix for each year, truth of which state individual was in whilst present at site,
# style as in Laake paper. 0 = not yet born, 1 = alive, 2 = temp emig, 3 dead
# p.state - yearly true state (gender) proportion | attendance
# capture.full - capture history list with a vector for each year for all individuals, when individuals were or were not seen
# capture - capture history matrix for each year, when individuals were or were not seen
# N.attend - actual number of individuals at the site each year - to do: for all + both genders
# N.encounter - number of individuals seen each year (+ gender specific) - to do: for all + both genders
# N.seen - number of individuals seen over entire study (+ gender specific) - to do: for all + both genders
# temp = sim.data.tau(N=100, T=10, K=1, r= 0.6, s=0.5, p=0.5, tau = c(0.2, 0.3)) ; temp$capture.full; temp$N.attend ; temp$N.encounter; temp$N.seen
# temp$state; temp$state.laake
sim.data.tau <- function(N, T, K=1, r, s, p, tau) {
# if (length(N)==1) Ngender <- c(floor(N/2) , ceiling(N/2)) else if(length(N)==2) Ngender <- N else {
# stop("Only 2 different states (gender). Please specifify N correctly.") }
# if N is one number but not even, the first state will have 1 less individuum then the second state
# reassign N
# N <- Ngender[1] + Ngender[2] ;
if(s + tau[1] > 1) {
warning("s + tau[1] must be <= 1")
sp = s + tau[1];
s <- s/sp;
tau[1]/sp
}
# create storage variables
attendance <- matrix(0, nrow=N, ncol=T) # alive an not temp emigrated
encounter <- matrix(1, nrow=N, ncol=T) # next: array with gender as dimension
# p.state <- rep(0, times = T)
capture.full <- NULL
capture <- NULL
if(length(r)==1) r<- rep(r, times = T) else if(length(r) != T) stop("r needs to have length T");
# attendance history
# generate recruitment distribution
recruitment <- rmultinom(1, N, r) # produces a matrix with rows = T = lenght r , with the number of elements first recruited in each row
# make vector of arrival times
recruitment.i <- rep(1:T, recruitment) # a number for each individual # adapt for 2-gender version
# now use
state <- matrix(0, nrow=N, ncol=T) # state = 0, and 1 if alive
# instead of state, I now use state.laake. state was in HW a list with attendance vector as elements for each secondary period
state.laake <- matrix(0, nrow=N, ncol=T) # is C_t in Laake for each individual
# state.laake: 0 not yet recruited. 1 recruited . 2 temp. emigrated. 3 departed
# state = 1 means temp. emigrated or alive
# attendance is 1 if alive and not temp emigrated!
# loop over individuals
for (i in 1:N) {
# record first attendance
attendance[i,recruitment.i[i]] <- 1 # recruitment.i[i] is the first atttendance time point
state.laake[i,recruitment.i[i]] <- 1
state[i,recruitment.i[i]] <- 1 # state should be used later to for male/female, here: just one gender
# state.laake: 0 not yet recruited. 1 recruited . 2 temp. emigrated. 3 departed
# if not recruited in final year
if (recruitment.i[i] < T) {
# loop over remaining occasions
for (t in recruitment.i[i]:(T-1)) {
# if present at site
if (attendance[i,t] == 1) {
# work out whether they survive until the next year, or temp emigrate or die
survival <- rmultinom(1,1,c(s,tau[1], 1-s-tau[1] ) ) # adapt with survival prob s dependent on gender
surv <- which(survival == 1) # 1 = alive, 2 = temp. emig, 3 = dead
# store 0 or 1 following year
# state[i,t+1] <- survival;
state.laake[i,t+1] <- surv
if (surv == 3) { # state.laake[i,t+1] <- 3
state[i,t+1] <- 0 # it is defaulted to 0 anyway
} else if(surv == 1) {# state.laake[i,t+1] <- 1;
state[i,t+1] <- 1;
attendance[i,t+1] <- 1
} else if(surv == 2){ # temp. emigrated
# attendance[i,t+1] <- 0 # is anyway the default
state[i,t+1] <- 1; # state: 0 - dead. 1 male or no gender measured
# here: state = 1 means temp. emigrated or alive
}
# attendance is 1 if alive and not temp emigrated!
} else { # is either dead or temp emigrated
if (state.laake[i,t] == 2){ # temp. emigrated
# now probability of emigrationg again is tau[2]
emigagain <- rbinom(1,1, tau[2]) # 1 = emig 0 = alive
state[i,t+1] <- 1 # either way from temp. emig. no death
state.laake[i,t+1] <- emigagain + 1 # 1 = alive, 2 = temp. emig, 3 = dead
attendance[i,t+1] == 1 - emigagain
} else { # ie dead -
state.laake[i,t+1] <- 3
state[i,t+1] <- 0;
# since this is developed from gender version, we have states: 0 (unborn)), 1 (alive), 3 (departed)
}
}
}
}
}
# find number that are present each year
N.t <- colSums(attendance) # + add for each gender
# N1.t <- colSums(attendance[state == 1 , ]);
# N2.t <- colSums(attendance[state == 2 , ]);
# p.state <- N1.t / N.t # true state proportion for each primary capture occassion
# state.t <- matrix(0, nrow=N, ncol=1) # needed when we include the temp. emigration
# capture histories for each year
# loop over years
for (t in 1:T) {
# storage variables for this year
capture.t <- matrix(0, nrow=N, ncol=K)
# I will need this when the states are also temporary emigration states - then adapt this
# loop over individuals and assign states
# for (i in 1:N) {
# find the occasions when present
# present <- which(presence.t[i,] == 1)
# assign state at initial capture
# state.init <- 1+rbinom(1,1,alpha[2]) # if necessary, add alpha again as argument, if needed for temp. emigration modelling
# state.t[i,present[1]] <- state.init
# loop over remaining occasions when present and transition between states
# if (length(present) > 1) {
# for (k in present[2]:present[length(present)]) {
# if (state.t[i,k-1] == 1) {
# state.k <- 1+rbinom(1,1,psi[1,2]) # if necessary, add psi again as argument, if needed for temp. emigration modelling
# } else if (state.t[i,k-1] == 2) {
# state.k <- 1+rbinom(1,1,psi[2,2])
# }
# state.t[i,k] <- state.k
# }
# }
# }
# loop over individuals and check whether they were captured or not
for (i in 1:N) {
# capture.t is defaulted to 0
# find the primary occassions where they were present
if(attendance[i,t]==1) {
# loop over occasions
capture.t[i,] <- rbinom(K,1,p) # needs to be adapted if temp emigration possible
# next: use time dependent capture prob! in primary time - possible would also be time dept within secondary
# for (k in 1:K) {
# determine whether they were captured or not
## capture.t[i,k] <- state.t[i,1]*rbinom(1,1,p[state.t[i,1]])
## capture.t[i,k] <- state[i]*rbinom(1,1,p[state[i] ]) # needs to be adapted if temp emigration possible
# capture.t[i,k] <- rbinom(1,1,p) # needs to be adapted if temp emigration possible
# next: use time dependent capture prob!
# }
}
}
# find which rows are all zeros in capture histories
capture.0 <- which(rowSums(capture.t) == 0) # ie for which year are all secondary capt histories = 0
# update encounter histories
for (c in capture.0) {
encounter[c,t] <- 0
}
# store state history for year t
# state[[t]] <- state.t - will be needed if temp. emigration is also a state
# store full capture history for year t
capture.full[[t]] <- c( capture.t) # capture.t
# store capture history for year t
capture[[t]] <- capture.t[-capture.0,]
}
# count those encountered each year
N.c <- colSums(encounter) # to do: count for both male and female and all
# count those who are seen at least once
N.seen <- N-length(which(rowSums(encounter) == 0)) # to do: count for both male and female and all
# return
return(list('attendance'=attendance, 'encounter'=encounter, 'state'=state, 'state.laake' = state.laake, # 'p.state' = p.state,
'capture.full'=capture.full, 'capture'=capture, 'N.attend'=N.t, 'N.encounter'=N.c, 'N.seen'=N.seen))
}
# to do: should we allow the first time point of attendance, that the animal is already temp. emigrated?
# ------------------------------------------------------------------------------
# Code to generate multi-state (multi-period) CRM data WITH temp. emigration
# ------------------------------------------------------------------------------
# Name: sim.data.tau.t
# Objective: To generate multiple years of capture recapture data using the given parameter values, constant survival and capture prob
# Inputs: N - total number of individuals
# T - number of years
# K - number of occasions each year, constant
# r - recruitment probabilities, length T, if not state dept specified
# s - survival, dependent on t
# # alpha - initial discrete state probability (length R) - seems we don't need it, maybe use again for model with temp emigration
# p - capture probability for each state, dependent on t
# tau - probability of temporary emigration, given 1) not temp. emigrated in previous year,
# 2) temp. emigrated in previous year,
# this is now changed to be a factor which is multiplicated (1-tau)*s to the survival
# Outputs: attendance - attendance matrix, truth of which years individuals are present at the site
# encounter - encounter matrix, which years individuals were or were not seen
# state - state history matrix (vector for each year), truth of which state individual was in whilst present at site (0 = not present, 1 = present)
# state.laake - state history matrix for each year, truth of which state individual was in whilst present at site,
# style as in Laake paper. 0 = not yet born, 1 = alive, 2 = temp emig, 3 dead
# p.state - yearly true state (gender) proportion | attendance
# capture.full - capture history list with a vector for each year for all individuals, when individuals were or were not seen
# capture - capture history matrix for each year, when individuals were or were not seen
# N.attend - actual number of individuals at the site each year - to do: for all + both genders
# N.encounter - number of individuals seen each year (+ gender specific) - to do: for all + both genders
# N.seen - number of individuals seen over entire study (+ gender specific) - to do: for all + both genders
# temp = sim.data.tau.time(N=100, T=10, K=1, r= 0.6, s=rep(0.5,10)-seq(0.01, 0.1, length=10), p=rep(0.5,10)+seq(0.01, 0.1, length=10), tau = c(0.2, 0.3)) ; temp$capture.full; temp$N.attend ; temp$N.encounter; temp$N.seen
# temp$state; temp$state.laake
# 1/11.2019: this is now recoded. survprob = s*(1-tau), emig prob = s*tau, dead prob = 1-s
sim.data.tau.time <- function(N, T, K=1, r, s, p, tau) {
if(length(r)==1) r<- rep(r, times = T) else if(length(r) != T) stop("r needs to have length T");
if(length(s)==1) s<- rep(s, times = T) else if(length(s) != T) stop("s needs to have length T");
if(length(p)==1) p<- rep(p, times = T) else if(length(p) != T) stop("p needs to have length T");
if(any(s > 1)) {
stop("s must be <= 1") }
if(any(p > 1)) {
stop("p must be <= 1") }
if(any(r > 1)) {
stop("r must be <= 1") }
if(any(tau > 1)) {
stop("tau must be <= 1") }
# sp = s + tau[1];
# s <- s/sp;
# tau[1]<- tau[1]/sp
# create storage variables
attendance <- matrix(0, nrow=N, ncol=T) # alive an not temp emigrated
encounter <- matrix(1, nrow=N, ncol=T) # next: array with gender as dimension
# p.state <- rep(0, times = T)
capture.full <- NULL
capture <- NULL
# attendance history
# generate recruitment distribution
recruitment <- rmultinom(1, N, r) # produces a matrix with rows = T = lenght r , with the number of elements first recruited in each row
# make vector of arrival times
recruitment.i <- rep(1:T, recruitment) # a number for each individual # adapt for 2-gender version
# now use
state <- matrix(0, nrow=N, ncol=T) # state = 0, and 1 if alive
# instead of state, I now use state.laake. state was in HW a list with attendance vector as elements for each secondary period
state.laake <- matrix(0, nrow=N, ncol=T) # is C_t in Laake for each individual
# state.laake: 0 not yet recruited. 1 recruited . 2 temp. emigrated. 3 departed
# state = 1 means temp. emigrated or alive
# attendance is 1 if alive and not temp emigrated!
# loop over individuals
for (i in 1:N) {
# record first attendance
attendance[i,recruitment.i[i]] <- 1 # recruitment.i[i] is the first atttendance time point
state.laake[i,recruitment.i[i]] <- 1
state[i,recruitment.i[i]] <- 1 # state should be used later to for male/female, here: just one gender
# state.laake: 0 not yet recruited. 1 recruited . 2 temp. emigrated. 3 departed
# if not recruited in final year
if (recruitment.i[i] < T) {
# loop over remaining occasions
for (t in recruitment.i[i]:(T-1)) {
# if present at site
if (attendance[i,t] == 1) {
# work out whether they survive until the next year, or temp emigrate or die
# survival <- rmultinom(1,1,c(s[t],tau[1], 1-s[t]-tau[1] ) )
# recoded 1/11/2019: death prob = 1-s[t],emig prob = s[t]*tau[2]
survival <- rmultinom(1,1,c(s[t]*(1-tau[1]),s[t]*tau[1], 1-s[t] ) )
surv <- which(survival == 1) # 1 = alive, 2 = temp. emig, 3 = dead
# store 0 or 1 following year
# state[i,t+1] <- survival;
state.laake[i,t+1] <- surv
if (surv == 3) { # state.laake[i,t+1] <- 3
state[i,t+1] <- 0 # it is defaulted to 0 anyway
} else if(surv == 1) {# state.laake[i,t+1] <- 1;
state[i,t+1] <- 1;
attendance[i,t+1] <- 1
} else if(surv == 2){ # temp. emigrated
# attendance[i,t+1] <- 0 # is anyway the default
state[i,t+1] <- 1; # state: 0 - dead. 1 male or no gender measured
# here: state = 1 means temp. emigrated or alive
}
# attendance is 1 if alive and not temp emigrated!
} else { # is either dead or temp emigrated
if (state.laake[i,t] == 2){ # temp. emigrated
# lets build in a death prob.: recoded 1/11/2019: death prob = 1-s[t],emig prob = s[t]*tau[2]
survival <- rmultinom(1,1,c(s[t]*(1-tau[2]),s[t]*tau[2], 1-s[t] ) )
surv <- which(survival == 1) # 1 = alive, 2 = temp. emig, 3 = dead
# store 0 or 1 following year
# state[i,t+1] <- survival;
state.laake[i,t+1] <- surv
if (surv == 3) { # state.laake[i,t+1] <- 3
state[i,t+1] <- 0 # it is defaulted to 0 anyway
} else if(surv == 1) {# state.laake[i,t+1] <- 1;
state[i,t+1] <- 1;
attendance[i,t+1] <- 1
} else if(surv == 2){ # temp. emigrated
# attendance[i,t+1] <- 0 # is anyway the default
state[i,t+1] <- 1; # state: 0 - dead. 1 male or no gender measured
# here: state = 1 means temp. emigrated or alive
}
# now probability of emigrationg again is tau[2]
# emigagain <- rbinom(1,1, tau[2]) # 1 = emig 0 = alive
# state[i,t+1] <- 1 # either way from temp. emig. no death
# assumption here is: no death after temp emig?
# state.laake[i,t+1] <- emigagain + 1 # 1 = alive, 2 = temp. emig, 3 = dead
# attendance[i,t+1] == 1 - emigagain
} else { # ie dead -
state.laake[i,t+1] <- 3
state[i,t+1] <- 0;
# since this is developed from gender version, we have states: 0 (unborn)), 1 (alive), 3 (departed)
}
}
}
}
}
# find number that are present each year
N.t <- colSums(attendance) # + add for each gender
# N1.t <- colSums(attendance[state == 1 , ]);
# N2.t <- colSums(attendance[state == 2 , ]);
# p.state <- N1.t / N.t # true state proportion for each primary capture occassion
# state.t <- matrix(0, nrow=N, ncol=1) # needed when we include the temp. emigration
# capture histories for each year
# loop over years
for (t in 1:T) {
# storage variables for this year
capture.t <- matrix(0, nrow=N, ncol=K)
# I will need this when the states are also temporary emigration states - then adapt this
# loop over individuals and assign states
# for (i in 1:N) {
# find the occasions when present
# present <- which(presence.t[i,] == 1)
# assign state at initial capture
# state.init <- 1+rbinom(1,1,alpha[2]) # if necessary, add alpha again as argument, if needed for temp. emigration modelling
# state.t[i,present[1]] <- state.init
# loop over remaining occasions when present and transition between states
# if (length(present) > 1) {
# for (k in present[2]:present[length(present)]) {
# if (state.t[i,k-1] == 1) {
# state.k <- 1+rbinom(1,1,psi[1,2]) # if necessary, add psi again as argument, if needed for temp. emigration modelling
# } else if (state.t[i,k-1] == 2) {
# state.k <- 1+rbinom(1,1,psi[2,2])
# }
# state.t[i,k] <- state.k
# }
# }
# }
# loop over individuals and check whether they were captured or not
for (i in 1:N) {
# capture.t is defaulted to 0
# find the primary occassions where they were present
if(attendance[i,t]==1) {
# loop over occasions
capture.t[i,] <- rbinom(K,1,p[t]) # needs to be adapted if temp emigration possible
# next: use time dependent capture prob! in primary time - possible would also be time dept within secondary
# for (k in 1:K) {
# determine whether they were captured or not
## capture.t[i,k] <- state.t[i,1]*rbinom(1,1,p[state.t[i,1]])
## capture.t[i,k] <- state[i]*rbinom(1,1,p[state[i] ]) # needs to be adapted if temp emigration possible
# capture.t[i,k] <- rbinom(1,1,p) # needs to be adapted if temp emigration possible
# next: use time dependent capture prob!
# }
}
}
# find which rows are all zeros in capture histories
capture.0 <- which(rowSums(capture.t) == 0) # ie for which year are all secondary capt histories = 0
# update encounter histories
for (c in capture.0) {
encounter[c,t] <- 0
}
# store state history for year t
# state[[t]] <- state.t - will be needed if temp. emigration is also a state
# store full capture history for year t
capture.full[[t]] <- c( capture.t) # capture.t
# store capture history for year t
capture[[t]] <- capture.t[-capture.0,]
}
# count those encountered each year
N.c <- colSums(encounter) # to do: count for both male and female and all
# count those who are seen at least once
N.seen <- N-length(which(rowSums(encounter) == 0)) # to do: count for both male and female and all
# return
return(list('attendance'=attendance, 'encounter'=encounter, 'state'=state, 'state.laake' = state.laake, # 'p.state' = p.state,
'capture.full'=capture.full, 'capture'=capture, 'N.attend'=N.t, 'N.encounter'=N.c, 'N.seen'=N.seen))
}
# to do: should we allow the first time point of attendance, that the animal is already temp. emigrated?
# ------------------------------------------------------------------------------
# Code to generate robust multi-state (multi-period) CRM data WITH temp. emigration
# ------------------------------------------------------------------------------
# Name: sim.data.robust.tau.time
# Objective: To generate multiple years of capture recapture data using the given parameter values, constant survival and capture prob
# Inputs: N - total number of individuals
# T - number of years
# K - number of occasions each year, allow to vary over time, can be length = 1 or T
# r - recruitment probabilities, length T, if not state dept specified
# s - survival, dependent on t
# # alpha - initial discrete state probability (length R) - seems we don't need it, maybe use again for model with temp emigration
# p.sec - capture probability, dependent on t, assumed to be constant within primary
# here: p.sec = capt prob for each sec. point k[j] in t, prob of being obs at all in the primary time t
# is then p.prim = 1 - dbinom(x=0, size=K, prob=p.sec)
# p.prim - probability of being captured at least once in the primary occassion t, time dept
# from p.prim, can derive p.sec = 1 - nthroot(x=1 - p.prim,n=K)
# - next: could allow for additional option. eg trap shyness, or linear increase/decrease within primary
# - however, these would be only to test the general program for robustness
# for specification of p.sec or p.prim: p.sec overwrites p.prim, if both are specified!
# if K differs for each t, the same p.sec for each prim time point, does not correspond to the same p.prim
# tau - probability of temporary emigration, given 1) not temp. emigrated in previous year,
# 2) temp. emigrated in previous year,
# this is now changed to be a factor which is multiplicated (1-tau)*s to the survival
# Outputs: attendance - attendance matrix, truth of which years individuals are present at the site
# encounter - encounter matrix, number of times an individuals was seen in each year
# state - state history vector for each year, truth of which state individual was in whilst present at site (male/female)
# state.laake - state history matrix for each year, truth of which state individual was in whilst present at site,
# style as in Laake paper. 0 = not yet born, 1 = alive, 2 = temp emig, 3 dead
# p.state - yearly true state (gender) proportion | attendance
# capture.full - capture history list with a matrix for each year for all individuals, no of times in t that individuals were seen
# ? capture - capture history matrix for each year, when individuals were or were not seen
# N.attend - actual number of individuals at the site each year - to do: for all + both genders
# N.encounter - number of individuals seen each year (+ gender specific) - to do: for all + both genders
# N.seen - number of individuals seen over entire study (+ gender specific) - to do: for all + both genders
# temp = sim.data.robust.tau.time(N=100, T=10, K=5, r= 0.6, s=rep(0.5,10)-seq(0.01, 0.1, length=10), p.prim=rep(0.5,10)+seq(0.01, 0.1, length=10), tau = c(0.2, 0.3)) ;
# temp = sim.data.robust.tau.time(N=100, T=10, K=c(3,3,3,3,2,2,2,2,2,2), r= 0.6, s=rep(0.5,10)-seq(0.01, 0.1, length=10), p.prim=rep(0.5,10)+seq(0.01, 0.1, length=10), tau = c(0.2, 0.3)) ;
# temp$capture.full; temp$N.attend ; temp$N.encounter; temp$N.seen
# temp$state; temp$state.laake; temp$encounter; temp$capture
# 1/11.2019: this is now recoded. survprob = s*(1-tau), emig prob = s*tau, dead prob = 1-s
sim.data.robust.tau.time <- function(N, T, K=1, r, s, p.prim=NULL, p.sec=NULL, tau) {
if(length(r)==1) r<- rep(r, times = T) else if(length(r) != T) stop("r needs to have length T");
if(length(s)==1) s<- rep(s, times = T) else if(length(s) != T) stop("s needs to have length T");
# if(length(p)==1) p<- rep(p, times = T) else if(length(p) != T) stop("p needs to have length T");
if(length(K)==1) K<- rep(K, times = T) else if(length(K) != T) stop("K needs to have length T");
if(is.null(p.prim)) {
if(is.null(p.sec)) stop("either p.prim or p.sec need to be specified") else {
p.prim = 1 - dbinom(x=0, size=K, prob=p.sec) # returns vector if K is a vector
}
}
if(is.null(p.sec)) p.sec = 1 - nthroot(1-p.prim,K);
# from here on, we use only p = p.sec for calculations
p <- p.sec
if(length(p)==1) p<- rep(p, times = T) else if(length(p) != T) stop("p.prim / p.sec needs to have length T");
if(any(s > 1)) {
stop("s must be <= 1") }
if(any(p > 1)) {
stop("p must be <= 1") }
if(any(r > 1)) {
stop("r must be <= 1") }
if(any(tau > 1)) {
stop("tau must be <= 1") }
# sp = s + tau[1];
# s <- s/sp;
# tau[1]<- tau[1]/sp
# create storage variables
attendance <- matrix(0, nrow=N, ncol=T) # alive an not temp emigrated
encounter <- matrix(0, nrow=N, ncol=T) # encounter is a matrix with T columns
# p.state <- rep(0, times = T)
capture.full <- NULL # capture.full is a list of T matrizes with each K columns
capture <- NULL
# attendance history
# generate recruitment distribution
recruitment <- rmultinom(1, N, r) # produces a matrix with rows = T = lenght r , with the number of elements first recruited in each row
# make vector of arrival times
recruitment.i <- rep(1:T, recruitment) # a number for each individual # adapt for 2-gender version
# now use
state <- matrix(0, nrow=N, ncol=T) # state = 0, and 1 if alive
# instead of state, I now use state.laake. state was in HW a list with attendance vector as elements for each secondary period
state.laake <- matrix(0, nrow=N, ncol=T) # is C_t in Laake for each individual
# state.laake: 0 not yet recruited. 1 recruited . 2 temp. emigrated. 3 departed
# state = 1 means temp. emigrated or alive
# attendance is 1 if alive and not temp emigrated!
# loop over individuals
for (i in 1:N) {
# record first attendance
attendance[i,recruitment.i[i]] <- 1 # recruitment.i[i] is the first atttendance time point
state.laake[i,recruitment.i[i]] <- 1
state[i,recruitment.i[i]] <- 1 # state should be used later to for male/female, here: just one gender
# state.laake: 0 not yet recruited. 1 recruited . 2 temp. emigrated. 3 departed
# if not recruited in final year
if (recruitment.i[i] < T) {
# loop over remaining occasions
for (t in recruitment.i[i]:(T-1)) {
# if present at site
if (attendance[i,t] == 1) {
# work out whether they survive until the next year, or temp emigrate or die
# survival <- rmultinom(1,1,c(s[t],tau[1], 1-s[t]-tau[1] ) )
# recoded 1/11/2019: death prob = 1-s[t],emig prob = s[t]*tau[2]
survival <- rmultinom(1,1,c(s[t]*(1-tau[1]),s[t]*tau[1], 1-s[t] ) )
surv <- which(survival == 1) # 1 = alive, 2 = temp. emig, 3 = dead
# store 0 or 1 following year
# state[i,t+1] <- survival;
state.laake[i,t+1] <- surv
if (surv == 3) { # state.laake[i,t+1] <- 3
state[i,t+1] <- 0 # it is defaulted to 0 anyway
} else if(surv == 1) {# state.laake[i,t+1] <- 1;
state[i,t+1] <- 1;
attendance[i,t+1] <- 1
} else if(surv == 2){ # temp. emigrated
# attendance[i,t+1] <- 0 # is anyway the default
state[i,t+1] <- 1; # state: 0 - dead. 1 male or no gender measured
# here: state = 1 means temp. emigrated or alive
}
# attendance is 1 if alive and not temp emigrated!
} else { # is either dead or temp emigrated
if (state.laake[i,t] == 2){ # temp. emigrated
# lets build in a death prob.: recoded 1/11/2019: death prob = 1-s[t],emig prob = s[t]*tau[2]
survival <- rmultinom(1,1,c(s[t]*(1-tau[2]),s[t]*tau[2], 1-s[t] ) )
surv <- which(survival == 1) # 1 = alive, 2 = temp. emig, 3 = dead
# store 0 or 1 following year
# state[i,t+1] <- survival;
state.laake[i,t+1] <- surv
if (surv == 3) { # state.laake[i,t+1] <- 3
state[i,t+1] <- 0 # it is defaulted to 0 anyway
} else if(surv == 1) {# state.laake[i,t+1] <- 1;
state[i,t+1] <- 1;
attendance[i,t+1] <- 1
} else if(surv == 2){ # temp. emigrated
# attendance[i,t+1] <- 0 # is anyway the default
state[i,t+1] <- 1; # state: 0 - dead. 1 male or no gender measured
# here: state = 1 means temp. emigrated or alive
}
# now probability of emigrationg again is tau[2]
# emigagain <- rbinom(1,1, tau[2]) # 1 = emig 0 = alive
# state[i,t+1] <- 1 # either way from temp. emig. no death
# assumption here is: no death after temp emig?
# state.laake[i,t+1] <- emigagain + 1 # 1 = alive, 2 = temp. emig, 3 = dead
# attendance[i,t+1] == 1 - emigagain
} else { # ie dead -
state.laake[i,t+1] <- 3
state[i,t+1] <- 0;
# since this is developed from gender version, we have states: 0 (unborn)), 1 (alive), 3 (departed)
}
}
}
}
}
# find number that are present each year
N.t <- colSums(attendance) # + add for each gender
# N1.t <- colSums(attendance[state == 1 , ]);
# N2.t <- colSums(attendance[state == 2 , ]);
# p.state <- N1.t / N.t # true state proportion for each primary capture occassion
# state.t <- matrix(0, nrow=N, ncol=1) # needed when we include the temp. emigration
# capture histories for each year
# loop over years
for (t in 1:T) {
# storage variables for this year
capture.t <- matrix(0, nrow=N, ncol=K[t])
#capture.tt <- matrix(0, nrow=N, ncol=1) # i am only interested in no of captures
# I will need this when the states are also temporary emigration states - then adapt this
# loop over individuals and assign states
# for (i in 1:N) {
# find the occasions when present
# present <- which(presence.t[i,] == 1)
# assign state at initial capture
# state.init <- 1+rbinom(1,1,alpha[2]) # if necessary, add alpha again as argument, if needed for temp. emigration modelling
# state.t[i,present[1]] <- state.init
# loop over remaining occasions when present and transition between states
# if (length(present) > 1) {
# for (k in present[2]:present[length(present)]) {
# if (state.t[i,k-1] == 1) {
# state.k <- 1+rbinom(1,1,psi[1,2]) # if necessary, add psi again as argument, if needed for temp. emigration modelling
# } else if (state.t[i,k-1] == 2) {
# state.k <- 1+rbinom(1,1,psi[2,2])
# }
# state.t[i,k] <- state.k
# }
# }
# }
# loop over individuals and check whether they were captured or not
for (i in 1:N) {
# capture.t is defaulted to 0
# find the primary occassions where they were present
if(attendance[i,t]==1) {
# loop over occasions
capture.t[i,] <- rbinom(K[t],1,p[t]) # outputs K values of 0 and 1
# capture.tt[i,] <- sum(capture.ti[i,]) # rbinom(1,K,p[t]) # outputs the number between 0 and K
# next: use time dependent capture prob! in primary time - possible would also be time dept within secondary
# for (k in 1:K) {
# determine whether they were captured or not
## capture.t[i,k] <- state.t[i,1]*rbinom(1,1,p[state.t[i,1]])
## capture.t[i,k] <- state[i]*rbinom(1,1,p[state[i] ]) # needs to be adapted if temp emigration possible
# capture.t[i,k] <- rbinom(1,1,p) # needs to be adapted if temp emigration possible
# next: use time dependent capture prob!
# }
encounter[i,t] <- sum(capture.t[i,]) # i am only interested in no of captures # outputs the number between 0 and K
}
}
# find which rows are all zeros in capture histories
capture.0 <- which(rowSums(capture.t) == 0) # ie for which year are all secondary capt histories = 0
# update encounter histories
for (c in capture.0) { encounter[c,t] <- 0 } # should work anyway
# store state history for year t
# state[[t]] <- state.t - will be needed if temp. emigration is also a state
# store full capture history for year t
capture.full[[t]] <- capture.t # a matrix with N rows and K[t] columns
# store capture history for year t
capture[[t]] <- capture.t[-capture.0,]
}
# count those encountered each year
N.c <- colSums(encounter >= 1) # to do: count for both male and female and all
# count those who are seen at least once
N.seen <- N-length(which(rowSums(encounter >= 1) == 0)) # to do: count for both male and female and all
# return
return(list('attendance'=attendance, 'encounter'=encounter, 'state'=state, 'state.laake' = state.laake, # 'p.state' = p.state,
'capture.full'=capture.full, 'capture'=capture, 'N.attend'=N.t, 'N.encounter'=N.c, 'N.seen'=N.seen))
}
# ------------------------------------------------------------------------------
# Code to generate multi-state (multi-period) CRM data for 2 genders
# ------------------------------------------------------------------------------
# Name: sim.data.gender
# Objective: To generate multiple years of multi-state CMR data using the given parameter values
# Inputs: Nmale - total number of male
# Nfemale - total number of female
# T - number of years
# K - number of occasions each year, constant
# r - recruitment probabilities, length T, if not state dept specified, assume constant for genders
# - can be either one value or a vector with the first value for male, second for female
# smale - male survival, constant - next: dependent on t
# sfemale - female survival, constant - next: dependent on t
# # alpha - initial discrete state probability (length R) - seems we don't need it, maybe use again for model with temp emigration
# pmale - capture probability for each state, constant, length R, for male . next: dependent on t
# pfemale - capture probability for each state, constant, length R, for female . next: dependent on t
# # psi - transition probabilities matrix - seems we don't need it, maybe use again for model with temp emigration
# pclassmal - classification probabilities for true male. vector of 3 values, classified as male/female/unknown given male
# pclassfem - classification probabilities for true female. vector of 3 values, classified as male/female/unknown given female
# pclassmal needs to sum to 1, pclassfem needs to sum to 1, last class unknown can be missing, then = 0
# Outputs: attendance - attendance matrix, truth of which years individuals are present at the site
# encounter - encounter matrix, which years individuals were or were not seen
# state - state history matrix for each year, truth of which state individual was in whilst present at site
# state.laake - state history matrix for each year, truth of which state individual was in whilst present at site,
# style as in Laake paper. 0 = not yet born, 1 = male, present, 2 = female, present, 3 dead
# p.state - yearly true state (gender) proportion | attendance
# capture.full - capture history list with a vector for each year for all individuals, when individuals were or were not seen
# capture - capture history matrix for each year, when individuals were or were not seen
# N.attend - actual number of individuals at the site each year - to do: for all + both genders
# N.encounter - number of individuals seen each year (+ gender specific) - to do: for all + both genders
# N.seen - number of individuals seen over entire study (+ gender specific) - to do: for all + both genders
# to do: should we allow the first time point of attendance, that the animal is already temp. emigrated?
# in preparation
# ------------------------------------------------------------------------------------------------
# Code to generate robust multi-state (multi-period) CRM data WITH temp. emigration for 2 genders
# -------------------------------------------------------------------------------------------------
# Name: sim.data.robust.tau.time.gender
# Objective: To generate multiple years of capture recapture data using the given parameter values, constant survival and capture prob
# Inputs: Nmale - total number of male
# Nfemale - total number of female
# T - number of years
# K - number of occasions each year, constant, next step: allow not constant
# rmale - recruitment probabilities for male, length T (or length 1 for constant)
# rfemale - recruitment probabilities for male, length T (or length 1 for constant)
# smale - male survival, length T
# sfemale - male survival, length T
# # alpha - initial discrete state probability (length R) - seems we don't need it, maybe use again for model with temp emigration
# pmale.sec - capture probability for male, dependent on t, assumed to be constant within primary
# here: p.sec = capt prob for each sec. point k[j] in t, prob of being obs at all in the primary time t
# is then p.prim = 1 - dbinom(x=0, size=K, prob=p.sec)
# pfemale.sec - capture probability for female
# pmale.prim - probability for male of being captured at least once in the primary occassion t, time dept
# pfemale.prim - probability for female
# from p.prim, can derive p.sec = 1 - nthroot(x=1 - p.prim,n=K)
# - next: could allow for additional option. eg trap shyness, or linear increase/decrease within primary
# - however, these would be only to test the general program for robustness
# taumale - probability of temporary emigration for male (length = 2),
# given 1) not temp. emigrated in previous year,
# 2) temp. emigrated in previous year,
# this is now changed to be a factor which is multiplicated (1-tau)*s to the survival
# taufemale - probability of temporary emigration for female
# pclassmal - classification probabilities for true male. vector of 3 values, classified as male/female/unknown given male
# pclassfem - classification probabilities for true female. vector of 3 values, classified as male/female/unknown given female
# pclassmal needs to sum to 1, pclassfem needs to sum to 1, last class unknown can be missing, then = 0
# random - whether to randomly mix together male and female, ie. mix up all observations
# Outputs: attendance - attendance matrix, truth of which years individuals are present at the site
# encounter - encounter matrix, number of times an individuals was seen in each year, dim = N x T
# gencounter - encounter array, number of times an individuals was captured and classified as male [,,1], female [,,2], unknown [,,3] in each year, dim = N x T x 3
# state - state history vector for each year, truth of which state individual was in whilst present at site (0 = not present 1 = male, 2 = female)
# state.laake - state history matrix for each year, truth of which state individual was in whilst present at site,
# style as in Laake paper. 0 = not yet born, 1 = alive, 2 = temp emig, 3 dead
# p.state - yearly true state (gender) proportion | attendance
# capture.full - capture history list with a matrix for each year for all individuals, no of times in t that individuals were seen
# ? capture - capture history matrix for each year, when individuals were or were not seen
# N.attend - actual number of individuals at the site each year - to do: for all + both genders
# N.encounter - number of individuals seen each year (+ gender specific) - to do: for all + both genders
# N.seen - number of individuals seen over entire study (+ gender specific) - to do: for all + both genders
# temp = sim.data.robust.tau.time(N=100, T=10, K=5, r= 0.6, s=rep(0.5,10)-seq(0.01, 0.1, length=10), p.prim=rep(0.5,10)+seq(0.01, 0.1, length=10), tau = c(0.2, 0.3)) ;
# temp$capture.full; temp$N.attend ; temp$N.encounter; temp$N.seen
# temp$state; temp$state.laake; temp$encounter; temp$capture
# 1/11.2019: this is now recoded. survprob = s*(1-tau), emig prob = s*tau, dead prob = 1-s
sim.data.gender <- function(Nmale, Nfemale ,T, K=1, rmale, rfemale, smale,sfemale ,pmale.prim=NULL, pfemale.prim=NULL, pmale.sec=NULL,pfemale.sec=NULL,
taumale , taufemale, pmale, pfemale, pclassmal, pclassfem, random = FALSE) {
sim.data.robust.tau.time.gender <- function(N, T, K=1, r, s, p.prim=NULL, p.sec=NULL, tau) {
if(sum(pclassmal) != 1 ) stop("classification probabilities must sum up to 1!")
if(sum(pclassfem) != 1 ) stop("classification probabilities must sum up to 1!")
if(length(pclassmal) == 2) pclassmal <- c(pclassmal, 0)
if(length(pclassfem) == 2) pclassfem <- c(pclassfem, 0)
if(any(smale < 0) | any(sfemale <0 ) | any(pmale < 0) | any(pfemale < 0) | any(smale >1) | any(sfemale >1) | any(pmale >1) | any(pfemale >1) ) stop(
"probabilities must have values between 0 and 1" )
if(is.null(pfemale.prim)) {
if(is.null(pfemale.sec)) stop("either pfemale.prim or p.sec need to be specified") else {
pfemale.prim = 1 - dbinom(x=0, size=K, prob=pfemale.sec)
}
}
if(is.null(pfemale.sec)) pfemale.sec = 1 - nthroot(1-pfemale.prim,K);
# from here on, we use only p = p.sec for calculations
#p <- pfemale.sec
if(is.null(pmale.prim)) {
if(is.null(pmale.sec)) stop("either pmale.prim or pmale.sec need to be specified") else {
pmale.prim = 1 - dbinom(x=0, size=K, prob=pmale.sec)
}
}
if(is.null(pmale.sec)) pmale.sec = 1 - nthroot(1-pmale.prim,K);
# from here on, we use only p = p.sec for calculations
#p <- p.sec
if(length(rmale)==1) rmale<- rep(rmale, times = T) else if(length(rmale) != T) stop("rmale needs to have length T");
if(length(rfemale)==1) rfemale<- rep(rfemale, times = T) else if(length(rfemale) != T) stop("rfemale needs to have length T");
if(length(smale)==1) smale<- rep(smale, times = T) else if(length(smale) != T) stop("smale needs to have length T");
if(length(sfemale)==1) sfemale<- rep(sfemale, times = T) else if(length(sfemale) != T) stop("sfemale needs to have length T");
if(length(pfemale.sec)==1) pfemale.sec<- rep(pfemale.sec, times = T) else if(length(pfemale.sec) != T) stop("pfemale.sec needs to have length T");
if(length(pmale.sec)==1) pmale.sec<- rep(pmale.sec, times = T) else if(length(pmale.sec) != T) stop("pmale.sec needs to have length T");
if(any(rmale > 1)) {
stop("r must be <= 1") }
if(any(rfemale > 1)) {
stop("r must be <= 1") }
if(any(taumale > 1)) {
stop("taumale must be <= 1") }
if(any(taufemale > 1)) {
stop("taufemale must be <= 1") }
# sp = s + tau[1];
# s <- s/sp;
# tau[1]<- tau[1]/sp
testsimmale = sim.data.robust.tau.time(N=Nmale, T=T, K=K, r=rmale, s=smale, p.sec=pmale.sec, tau = taumale)
testsimfemale = sim.data.robust.tau.time(N=Nfemale, T=T, K=K, r=rfemale, s=sfemale, p.sec=pfemale.sec, tau = taufemale)
# go on here!
# sim.data.robust.tau.time(N, T, K=1, r, s, p.prim=NULL, p.sec=NULL, tau)
# create storage variables
attendance <- matrix(0, nrow=N, ncol=T) # alive an not temp emigrated
encounter <- matrix(0, nrow=N, ncol=T) # encounter is a matrix with T columns
# p.state <- rep(0, times = T)
capture.full <- NULL # capture.full is a list of T matrizes with each K columns
capture <- NULL
# attendance history
# generate recruitment distribution
recruitment <- rmultinom(1, N, r) # produces a matrix with rows = T = lenght r , with the number of elements first recruited in each row
# make vector of arrival times
recruitment.i <- rep(1:T, recruitment) # a number for each individual # adapt for 2-gender version
# now use
state <- matrix(0, nrow=N, ncol=T) # state = 0, and 1 if alive
# instead of state, I now use state.laake. state was in HW a list with attendance vector as elements for each secondary period
state.laake <- matrix(0, nrow=N, ncol=T) # is C_t in Laake for each individual
# state.laake: 0 not yet recruited. 1 recruited . 2 temp. emigrated. 3 departed
# state = 1 means temp. emigrated or alive
# attendance is 1 if alive and not temp emigrated!
# loop over individuals
for (i in 1:N) {
# record first attendance
attendance[i,recruitment.i[i]] <- 1 # recruitment.i[i] is the first atttendance time point
state.laake[i,recruitment.i[i]] <- 1
state[i,recruitment.i[i]] <- 1 # state should be used later to for male/female, here: just one gender
# state.laake: 0 not yet recruited. 1 recruited . 2 temp. emigrated. 3 departed
# if not recruited in final year
if (recruitment.i[i] < T) {
# loop over remaining occasions
for (t in recruitment.i[i]:(T-1)) {
# if present at site
if (attendance[i,t] == 1) {
# work out whether they survive until the next year, or temp emigrate or die
# recoded 1/11/2019: death prob = 1-s[t],emig prob = s[t]*tau[2]
survival <- rmultinom(1,1,c(s[t]*(1-tau[1]),s[t]*tau[1], 1-s[t] ) )
surv <- which(survival == 1) # 1 = alive, 2 = temp. emig, 3 = dead
# store 0 or 1 following year
# state[i,t+1] <- survival;
state.laake[i,t+1] <- surv
if (surv == 3) { # state.laake[i,t+1] <- 3
state[i,t+1] <- 0 # it is defaulted to 0 anyway
} else if(surv == 1) {# state.laake[i,t+1] <- 1;
state[i,t+1] <- 1;
attendance[i,t+1] <- 1
} else if(surv == 2){ # temp. emigrated
# attendance[i,t+1] <- 0 # is anyway the default
state[i,t+1] <- 1; # state: 0 - dead. 1 male or no gender measured
# here: state = 1 means temp. emigrated or alive
}
# attendance is 1 if alive and not temp emigrated!
} else { # is either dead or temp emigrated
if (state.laake[i,t] == 2){ # temp. emigrated
# lets build in a death prob.: recoded 1/11/2019: death prob = 1-s[t],emig prob = s[t]*tau[2]
survival <- rmultinom(1,1,c(s[t]*(1-tau[2]),s[t]*tau[2], 1-s[t] ) )
surv <- which(survival == 1) # 1 = alive, 2 = temp. emig, 3 = dead
# store 0 or 1 following year
# state[i,t+1] <- survival;
state.laake[i,t+1] <- surv
if (surv == 3) { # state.laake[i,t+1] <- 3
state[i,t+1] <- 0 # it is defaulted to 0 anyway
} else if(surv == 1) {# state.laake[i,t+1] <- 1;
state[i,t+1] <- 1;
attendance[i,t+1] <- 1
} else if(surv == 2){ # temp. emigrated
# attendance[i,t+1] <- 0 # is anyway the default
state[i,t+1] <- 1;
# here: state = 1 means temp. emigrated or alive
}
} else { # ie dead -
state.laake[i,t+1] <- 3
state[i,t+1] <- 0;
# since this is developed from gender version, we have states: 0 (unborn)), 1 (alive), 3 (departed)
}
}
}
}
}
# find number that are present each year
N.t <- colSums(attendance) # + add for each gender
# N1.t <- colSums(attendance[state == 1 , ]);
# N2.t <- colSums(attendance[state == 2 , ]);
# p.state <- N1.t / N.t # true state proportion for each primary capture occassion
# state.t <- matrix(0, nrow=N, ncol=1) # needed when we include the temp. emigration
# capture histories for each year
# loop over years
for (t in 1:T) {
# storage variables for this year
capture.t <- matrix(0, nrow=N, ncol=K)
# loop over individuals and check whether they were captured or not
for (i in 1:N) {
# capture.t is defaulted to 0
# find the primary occassions where they were present
if(attendance[i,t]==1) {
# loop over occasions
capture.t[i,] <- rbinom(K,1,p[t]) # outputs K values of 0 and 1
encounter[i,t] <- sum(capture.t[i,]) # i am only interested in no of captures # outputs the number between 0 and K
}
}
# find which rows are all zeros in capture histories
capture.0 <- which(rowSums(capture.t) == 0) # ie for which year are all secondary capt histories = 0
# update encounter histories
for (c in capture.0) { encounter[c,t] <- 0 } # should work anyway
# store state history for year t
# state[[t]] <- state.t - will be needed if temp. emigration is also a state
# store full capture history for year t
capture.full[[t]] <- capture.t # a matrix with N rows and K columns
# store capture history for year t
capture[[t]] <- capture.t[-capture.0,]
}
# count those encountered each year
N.c <- colSums(encounter >= 1) # to do: count for both male and female and all
# count those who are seen at least once
N.seen <- N-length(which(rowSums(encounter >= 1) == 0)) # to do: count for both male and female and all
# return
return(list('attendance'=attendance, 'encounter'=encounter, 'state'=state, 'state.laake' = state.laake, # 'p.state' = p.state,
'capture.full'=capture.full, 'capture'=capture, 'N.attend'=N.t, 'N.encounter'=N.c, 'N.seen'=N.seen))
}
|
library(dplyr)
library(ggplot2)
source('data.R')
# https://dplyr.tidyverse.org/reference/arrange.html
books_by_download <- arrange(books, desc(downloads))
books_refined <- books_by_download %>% select(author, title, words, syllables, sentences)
# guessed, knowing pull from last Proj and how R doesn't chain and head from linux
top_ten_authors <- head(pull(books_refined, author), 10)
# https://www.rdocumentation.org/packages/dplyr/versions/0.7.8/topics/filter search for %in%
authors_books <- arrange(filter(books_refined, author %in% top_ten_authors), desc(author))
# guessed, basically (knowledge of previous R Projects helped)
reading_ease <- mutate(authors_books, flesch_reading_ease = 206.835 - 1.015 * (words / sentences) - 84.6 * (syllables / words))
reading_grade <- mutate(reading_ease, flesch_kincaid_grade_level = 0.39 * (words / sentences) + 11.8 * (syllables / words) - 15.59)
# https://stackoverflow.com/a/28255866
reading_grouped <- group_by(reading_grade, author)
# sort guessed. not quite sure why chained piping didn't work. guessing loses data
# reading_summary <- reading_grouped %>% summarize(flesch_reading_ease = mean(flesch_reading_ease)) %>% summarize(flesch_kincaid_grade_level = mean(flesch_kincaid_grade_level))
reading_summary <- reading_grouped %>% summarize(flesch_reading_ease = mean(flesch_reading_ease), flesch_kincaid_grade_level = mean(flesch_kincaid_grade_level))
reading_long <- gather(reading_summary, type, score, flesch_reading_ease, flesch_kincaid_grade_level)
p <- ggplot(reading_long, aes(author, score)) + geom_bar(stat='identity')
p <- p + facet_grid(rows = vars(type))
# https://stackoverflow.com/questions/1330989/rotating-and-spacing-axis-labels-in-ggplot2
p <- p + theme(axis.text.x = element_text(angle = 45, hjust = 1))
plot(p)
| /reading.R | no_license | snychka/R-ClassicLiteratureReadability | R | false | false | 1,789 | r | library(dplyr)
library(ggplot2)
source('data.R')
# https://dplyr.tidyverse.org/reference/arrange.html
books_by_download <- arrange(books, desc(downloads))
books_refined <- books_by_download %>% select(author, title, words, syllables, sentences)
# guessed, knowing pull from last Proj and how R doesn't chain and head from linux
top_ten_authors <- head(pull(books_refined, author), 10)
# https://www.rdocumentation.org/packages/dplyr/versions/0.7.8/topics/filter search for %in%
authors_books <- arrange(filter(books_refined, author %in% top_ten_authors), desc(author))
# guessed, basically (knowledge of previous R Projects helped)
reading_ease <- mutate(authors_books, flesch_reading_ease = 206.835 - 1.015 * (words / sentences) - 84.6 * (syllables / words))
reading_grade <- mutate(reading_ease, flesch_kincaid_grade_level = 0.39 * (words / sentences) + 11.8 * (syllables / words) - 15.59)
# https://stackoverflow.com/a/28255866
reading_grouped <- group_by(reading_grade, author)
# sort guessed. not quite sure why chained piping didn't work. guessing loses data
# reading_summary <- reading_grouped %>% summarize(flesch_reading_ease = mean(flesch_reading_ease)) %>% summarize(flesch_kincaid_grade_level = mean(flesch_kincaid_grade_level))
reading_summary <- reading_grouped %>% summarize(flesch_reading_ease = mean(flesch_reading_ease), flesch_kincaid_grade_level = mean(flesch_kincaid_grade_level))
reading_long <- gather(reading_summary, type, score, flesch_reading_ease, flesch_kincaid_grade_level)
p <- ggplot(reading_long, aes(author, score)) + geom_bar(stat='identity')
p <- p + facet_grid(rows = vars(type))
# https://stackoverflow.com/questions/1330989/rotating-and-spacing-axis-labels-in-ggplot2
p <- p + theme(axis.text.x = element_text(angle = 45, hjust = 1))
plot(p)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/celda_CG.R
\name{celdaUmap,celda_CG-method}
\alias{celdaUmap,celda_CG-method}
\title{umap for celda_CG}
\usage{
\S4method{celdaUmap}{celda_CG}(
counts,
celdaMod,
maxCells = NULL,
minClusterSize = 100,
modules = NULL,
seed = 12345,
nNeighbors = 30,
minDist = 0.75,
spread = 1,
cores = 1,
...
)
}
\arguments{
\item{counts}{Integer matrix. Rows represent features and columns represent
cells. This matrix should be the same as the one used to generate
`celdaMod`.}
\item{celdaMod}{Celda object of class `celda_CG`.}
\item{maxCells}{Integer. Maximum number of cells to plot. Cells will be
randomly subsampled if ncol(counts) > maxCells. Larger numbers of cells
requires more memory. If NULL, no subsampling will be performed.
Default NULL.}
\item{minClusterSize}{Integer. Do not subsample cell clusters below this
threshold. Default 100.}
\item{modules}{Integer vector. Determines which features modules to use for
UMAP. If NULL, all modules will be used. Default NULL.}
\item{seed}{Integer. Passed to \link[withr]{with_seed}. For reproducibility,
a default value of 12345 is used. If NULL, no calls to
\link[withr]{with_seed} are made.}
\item{nNeighbors}{The size of local neighborhood used for
manifold approximation. Larger values result in more global
views of the manifold, while smaller values result in more
local data being preserved. Default 30.
See `?uwot::umap` for more information.}
\item{minDist}{The effective minimum distance between embedded points.
Smaller values will result in a more clustered/clumped
embedding where nearby points on the manifold are drawn
closer together, while larger values will result on a more
even dispersal of points. Default 0.2.
See `?uwot::umap` for more information.}
\item{spread}{The effective scale of embedded points. In combination with
‘min_dist’, this determines how clustered/clumped the
embedded points are. Default 1.
See `?uwot::umap` for more information.}
\item{cores}{Number of threads to use. Default 1.}
\item{...}{Other parameters to pass to `uwot::umap`.}
}
\value{
A two column matrix of umap coordinates
}
\description{
Embeds cells in two dimensions using umap based on a `celda_CG`
model. umap is run on module probabilities to reduce the number of features
instead of using PCA. Module probabilities square-root trasformed before
applying tSNE.
}
\examples{
data(celdaCGSim, celdaCGMod)
umapRes <- celdaUmap(celdaCGSim$counts, celdaCGMod)
}
\seealso{
`celda_CG()` for clustering features and cells and `celdaHeatmap()`
for displaying expression.
}
| /man/celdaUmap-celda_CG-method.Rd | permissive | AhmedYoussef95/celda | R | false | true | 2,634 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/celda_CG.R
\name{celdaUmap,celda_CG-method}
\alias{celdaUmap,celda_CG-method}
\title{umap for celda_CG}
\usage{
\S4method{celdaUmap}{celda_CG}(
counts,
celdaMod,
maxCells = NULL,
minClusterSize = 100,
modules = NULL,
seed = 12345,
nNeighbors = 30,
minDist = 0.75,
spread = 1,
cores = 1,
...
)
}
\arguments{
\item{counts}{Integer matrix. Rows represent features and columns represent
cells. This matrix should be the same as the one used to generate
`celdaMod`.}
\item{celdaMod}{Celda object of class `celda_CG`.}
\item{maxCells}{Integer. Maximum number of cells to plot. Cells will be
randomly subsampled if ncol(counts) > maxCells. Larger numbers of cells
requires more memory. If NULL, no subsampling will be performed.
Default NULL.}
\item{minClusterSize}{Integer. Do not subsample cell clusters below this
threshold. Default 100.}
\item{modules}{Integer vector. Determines which features modules to use for
UMAP. If NULL, all modules will be used. Default NULL.}
\item{seed}{Integer. Passed to \link[withr]{with_seed}. For reproducibility,
a default value of 12345 is used. If NULL, no calls to
\link[withr]{with_seed} are made.}
\item{nNeighbors}{The size of local neighborhood used for
manifold approximation. Larger values result in more global
views of the manifold, while smaller values result in more
local data being preserved. Default 30.
See `?uwot::umap` for more information.}
\item{minDist}{The effective minimum distance between embedded points.
Smaller values will result in a more clustered/clumped
embedding where nearby points on the manifold are drawn
closer together, while larger values will result on a more
even dispersal of points. Default 0.2.
See `?uwot::umap` for more information.}
\item{spread}{The effective scale of embedded points. In combination with
‘min_dist’, this determines how clustered/clumped the
embedded points are. Default 1.
See `?uwot::umap` for more information.}
\item{cores}{Number of threads to use. Default 1.}
\item{...}{Other parameters to pass to `uwot::umap`.}
}
\value{
A two column matrix of umap coordinates
}
\description{
Embeds cells in two dimensions using umap based on a `celda_CG`
model. umap is run on module probabilities to reduce the number of features
instead of using PCA. Module probabilities square-root trasformed before
applying tSNE.
}
\examples{
data(celdaCGSim, celdaCGMod)
umapRes <- celdaUmap(celdaCGSim$counts, celdaCGMod)
}
\seealso{
`celda_CG()` for clustering features and cells and `celdaHeatmap()`
for displaying expression.
}
|
# The purpose of this project is to demonstrate ability to collect, work with, and clean a data set.
# The goal is to prepare tidy data that can be used for later analysis.
# The data is built from recordings of subjects performing daily activities while carrying smartphone
# The full description of the data set is available at the site where the data was obtained:
# http://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones
# The R script called run_analysis.R does the following.
# 1. Merges the training and the test sets to create one data set.
# 2. Extracts only the measurements on the mean and standard deviation for each measurement.
# 3. Uses descriptive activity names to name the activities in the data set
# 4. Appropriately labels the data set with descriptive variable names.
# 5. From the data set in step 4, creates a second, independent tidy data set with the average of
# each variable for each activity and each subject.
# Set the working directory where the data will be downloaded to
setwd("C:/Users/b02257a/Desktop/coursera/DataCleansing")
# Checks for data directory and creates one if it doesn't exist
if (!file.exists("data")) {
message("Creating data directory")
dir.create("data")
}
# if the sample data file does not exist already, download it
if (!file.exists("data/UCI HAR Dataset")) {
# download the data
fileURL <- "https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip"
zipfile="data/UCI_HAR_data.zip"
message("Downloading data")
download.file(fileURL, destfile=zipfile)
unzip(zipfile, exdir="data")
}
# 1. Merges the training and the test sets to create one data set.
# Load the data from the HAR data set
x_train <- read.table("data/UCI HAR Dataset/train/X_train.txt")
y_train <- read.table("data/UCI HAR Dataset/train/y_train.txt")
subject_train <- read.table("data/UCI HAR Dataset/train/subject_train.txt")
x_test <- read.table("data/UCI HAR Dataset/test/X_test.txt")
y_test <- read.table("data/UCI HAR Dataset/test/y_test.txt")
subject_test <- read.table("data/UCI HAR Dataset/test/subject_test.txt")
activity_labels <- read.table("data/UCI HAR Dataset/activity_labels.txt")
features <- read.table("data/UCI HAR Dataset/features.txt")
# Merge the data into a new, combined data frame
x.df <- rbind(x_test, x_train)
y.df <- rbind(y_test, y_train)
subject.df <- rbind(subject_test, subject_train)
# 4. Appropriately labels the data set with descriptive variable names.
# Clean up the variable names from features, and apply them to x.df
# NB: this could also be done between steps (3) and (5) by limiting
# the cleaned data_labels to the columns selected in (2).
data_labels = sapply(features$V2, function(x) {gsub('[-(),]+','_', x)})
colnames(x.df) <- data_labels
# 2. Extracts only the measurements on the mean and standard deviation for each measurement.
mean_and_std_features <- grep('mean|std', features$V2, ignore.case=TRUE)
x.df <- x.df[,mean_and_std_features]
# 3. Uses descriptive activity names to name the activities in the data set
# Use the activity list in y.df combined with the names in activity_lables
# to update x.df with activity labels
for (i in 1:6) {
x.df$activity[y.df$V1 == i] <- as.character(activity_labels[i,2])
}
# 5. Creates a second, independent tidy data set with the average of each
# variable for each activity and each subject.
# First, append the subjects to x.df
x.df$subject <- as.factor(subject.df$V1)
# Then, groupby activity and subject, aggregate by average (mean)
tidy <- aggregate(. ~ subject+activity, data=x.df, FUN=mean)
# And finally, export the dataset as a txt file
write.table(tidy, "tidy.txt", sep="\t")
| /run_analysis.R | no_license | sragam/data-cleansing | R | false | false | 3,707 | r | # The purpose of this project is to demonstrate ability to collect, work with, and clean a data set.
# The goal is to prepare tidy data that can be used for later analysis.
# The data is built from recordings of subjects performing daily activities while carrying smartphone
# The full description of the data set is available at the site where the data was obtained:
# http://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones
# The R script called run_analysis.R does the following.
# 1. Merges the training and the test sets to create one data set.
# 2. Extracts only the measurements on the mean and standard deviation for each measurement.
# 3. Uses descriptive activity names to name the activities in the data set
# 4. Appropriately labels the data set with descriptive variable names.
# 5. From the data set in step 4, creates a second, independent tidy data set with the average of
# each variable for each activity and each subject.
# Set the working directory where the data will be downloaded to
setwd("C:/Users/b02257a/Desktop/coursera/DataCleansing")
# Checks for data directory and creates one if it doesn't exist
if (!file.exists("data")) {
message("Creating data directory")
dir.create("data")
}
# if the sample data file does not exist already, download it
if (!file.exists("data/UCI HAR Dataset")) {
# download the data
fileURL <- "https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip"
zipfile="data/UCI_HAR_data.zip"
message("Downloading data")
download.file(fileURL, destfile=zipfile)
unzip(zipfile, exdir="data")
}
# 1. Merges the training and the test sets to create one data set.
# Load the data from the HAR data set
x_train <- read.table("data/UCI HAR Dataset/train/X_train.txt")
y_train <- read.table("data/UCI HAR Dataset/train/y_train.txt")
subject_train <- read.table("data/UCI HAR Dataset/train/subject_train.txt")
x_test <- read.table("data/UCI HAR Dataset/test/X_test.txt")
y_test <- read.table("data/UCI HAR Dataset/test/y_test.txt")
subject_test <- read.table("data/UCI HAR Dataset/test/subject_test.txt")
activity_labels <- read.table("data/UCI HAR Dataset/activity_labels.txt")
features <- read.table("data/UCI HAR Dataset/features.txt")
# Merge the data into a new, combined data frame
x.df <- rbind(x_test, x_train)
y.df <- rbind(y_test, y_train)
subject.df <- rbind(subject_test, subject_train)
# 4. Appropriately labels the data set with descriptive variable names.
# Clean up the variable names from features, and apply them to x.df
# NB: this could also be done between steps (3) and (5) by limiting
# the cleaned data_labels to the columns selected in (2).
data_labels = sapply(features$V2, function(x) {gsub('[-(),]+','_', x)})
colnames(x.df) <- data_labels
# 2. Extracts only the measurements on the mean and standard deviation for each measurement.
mean_and_std_features <- grep('mean|std', features$V2, ignore.case=TRUE)
x.df <- x.df[,mean_and_std_features]
# 3. Uses descriptive activity names to name the activities in the data set
# Use the activity list in y.df combined with the names in activity_lables
# to update x.df with activity labels
for (i in 1:6) {
x.df$activity[y.df$V1 == i] <- as.character(activity_labels[i,2])
}
# 5. Creates a second, independent tidy data set with the average of each
# variable for each activity and each subject.
# First, append the subjects to x.df
x.df$subject <- as.factor(subject.df$V1)
# Then, groupby activity and subject, aggregate by average (mean)
tidy <- aggregate(. ~ subject+activity, data=x.df, FUN=mean)
# And finally, export the dataset as a txt file
write.table(tidy, "tidy.txt", sep="\t")
|
% Generated by roxygen2 (4.1.0): do not edit by hand
% Please edit documentation in R/sql.r
\name{insert.sql}
\alias{insert.sql}
\title{generate sql insert statement from dataframe}
\usage{
insert.sql(data, table.name)
}
\arguments{
\item{data}{dataframe to import}
\item{table.name}{name of table in db to insert into}
}
\description{
generate sql insert statement from dataframe
}
\seealso{
Other sql: \code{\link{collapse_char_vec}};
\code{\link{collap}}; \code{\link{get_htbl}};
\code{\link{get_qry}}; \code{\link{get_tbl}}
}
| /man/insert.sql.Rd | no_license | mdelhey/mdutils | R | false | false | 536 | rd | % Generated by roxygen2 (4.1.0): do not edit by hand
% Please edit documentation in R/sql.r
\name{insert.sql}
\alias{insert.sql}
\title{generate sql insert statement from dataframe}
\usage{
insert.sql(data, table.name)
}
\arguments{
\item{data}{dataframe to import}
\item{table.name}{name of table in db to insert into}
}
\description{
generate sql insert statement from dataframe
}
\seealso{
Other sql: \code{\link{collapse_char_vec}};
\code{\link{collap}}; \code{\link{get_htbl}};
\code{\link{get_qry}}; \code{\link{get_tbl}}
}
|
library(logisticRR)
### Name: printnRR
### Title: Print adjusted relative risk under nominal exposure variable.
### Aliases: printnRR
### ** Examples
n <- 500
set.seed(1234)
W <- rbinom(n, 1, 0.3); W[sample(1:n, n/3)] = 2
dat <- as.data.frame(W)
dat$X <- sample( c("low", "medium", "high"), size = n, replace = TRUE)
dat$Y <- ifelse(dat$X == "low", rbinom(n, 1, plogis(W + 0.5)),
ifelse(dat$X == "medium", rbinom(n, 1, plogis(W + 0.2)),
rbinom(n, 1, plogis(W - 0.4)) ))
dat$X <- as.factor(dat$X)
result <- printnRR(Y ~ X + W, basecov = "high", comparecov = "low", data = dat)
| /data/genthat_extracted_code/logisticRR/examples/printnRR.Rd.R | no_license | surayaaramli/typeRrh | R | false | false | 615 | r | library(logisticRR)
### Name: printnRR
### Title: Print adjusted relative risk under nominal exposure variable.
### Aliases: printnRR
### ** Examples
n <- 500
set.seed(1234)
W <- rbinom(n, 1, 0.3); W[sample(1:n, n/3)] = 2
dat <- as.data.frame(W)
dat$X <- sample( c("low", "medium", "high"), size = n, replace = TRUE)
dat$Y <- ifelse(dat$X == "low", rbinom(n, 1, plogis(W + 0.5)),
ifelse(dat$X == "medium", rbinom(n, 1, plogis(W + 0.2)),
rbinom(n, 1, plogis(W - 0.4)) ))
dat$X <- as.factor(dat$X)
result <- printnRR(Y ~ X + W, basecov = "high", comparecov = "low", data = dat)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/apaCorrelationTable.R
\name{apa.cor.table}
\alias{apa.cor.table}
\title{Creates a correlation table in APA style with means and standard deviations}
\usage{
apa.cor.table(
data,
filename = NA,
table.number = NA,
show.conf.interval = TRUE,
show.sig.stars = TRUE,
landscape = TRUE
)
}
\arguments{
\item{data}{Project data frame}
\item{filename}{(optional) Output filename document filename (must end in .rtf or .doc only)}
\item{table.number}{Integer to use in table number output line}
\item{show.conf.interval}{(TRUE/FALSE) Display confidence intervals in table. This argument is deprecated and will be removed from later versions.}
\item{show.sig.stars}{(TRUE/FALSE) Display stars for significance in table.}
\item{landscape}{(TRUE/FALSE) Make RTF file landscape}
}
\value{
APA table object
}
\description{
Creates a correlation table in APA style with means and standard deviations
}
\examples{
\dontrun{
# View top few rows of attitude data set
head(attitude)
# Use apa.cor.table function
apa.cor.table(attitude)
apa.cor.table(attitude, filename="ex.CorTable1.doc")
}
}
| /man/apa.cor.table.Rd | no_license | cran/apaTables | R | false | true | 1,169 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/apaCorrelationTable.R
\name{apa.cor.table}
\alias{apa.cor.table}
\title{Creates a correlation table in APA style with means and standard deviations}
\usage{
apa.cor.table(
data,
filename = NA,
table.number = NA,
show.conf.interval = TRUE,
show.sig.stars = TRUE,
landscape = TRUE
)
}
\arguments{
\item{data}{Project data frame}
\item{filename}{(optional) Output filename document filename (must end in .rtf or .doc only)}
\item{table.number}{Integer to use in table number output line}
\item{show.conf.interval}{(TRUE/FALSE) Display confidence intervals in table. This argument is deprecated and will be removed from later versions.}
\item{show.sig.stars}{(TRUE/FALSE) Display stars for significance in table.}
\item{landscape}{(TRUE/FALSE) Make RTF file landscape}
}
\value{
APA table object
}
\description{
Creates a correlation table in APA style with means and standard deviations
}
\examples{
\dontrun{
# View top few rows of attitude data set
head(attitude)
# Use apa.cor.table function
apa.cor.table(attitude)
apa.cor.table(attitude, filename="ex.CorTable1.doc")
}
}
|
library(fwPackage, lib.loc="package")
library(tikzDevice)
library(lattice)
library(dbframe)
ltheme <- canonical.theme(color = FALSE) ## in-built B&W theme
ltheme$strip.background$col <- "transparent" ## change strip bg
lattice.options(default.theme = ltheme) ## set as default
dbc <- dbConnect(dbDriver("SQLite"), dbname = "data/simulations.db")
d <- dbGetQuery(dbc, "select reject, n, kNull, nulllabel, altlabel, norm
from viewftest where label = 'size'")
dbDisconnect(dbc)
d$nulllabel[d$nulllabel == "K0=2"] <- "$2$"
d$nulllabel[d$nulllabel == "K0=n/50"] <- "$T/50$"
d$altlabel[d$altlabel == "K=3"] <- "$3$"
d$altlabel[d$altlabel == "K=T/10"] <- "$T/10$"
dl <- lapply(unique(d$norm), function(dnorm) d[d$norm == dnorm,])
dd <- dl[[1]][, c("nulllabel", "altlabel", "n", "reject")]
names(dd) <- c("$K_1$", "$K_2$", "$T$", "$| \\theta_2 |_2 = 0$")
dd[,"$| \\theta_2 |_2 = 1$"] <- dl[[2]]$reject
tabscode <- booktabs(dd,
align = c("l", "l", "C", "C", "C"),
digits = c(0, 0, 0, 3, 3),
numberformat = c(FALSE, FALSE, TRUE, TRUE, TRUE))
tabscode <- gsub("\\\\toprule", "\\\\toprule &&&
\\\\multicolumn{2}{c}{Conditional rejection probability (size)} \\\\\\\\
\\\\cmidrule(l){4-5}", tabscode)
cat(file = "floats/mc-ftest.tex", "\\begin{table}[tb]\n", tabscode,
"\\caption{Simulated rejection probabilities for the $F$-test under
the null hypothesis that the benchmark model will forecast better,
$\\E_T \\oosB \\leq 0$. Nominal size is 10\\% and values greater than
10\\% indicate that the test rejects the benchmark model too often.
See Section~\\ref{sec:simulation-design} for a discussion of the
simulation design.}
\\label{fig:ftest}
\\end{table}")
| /R/mc-ftest.R | no_license | grayclhn/oos-overfit | R | false | false | 1,759 | r | library(fwPackage, lib.loc="package")
library(tikzDevice)
library(lattice)
library(dbframe)
ltheme <- canonical.theme(color = FALSE) ## in-built B&W theme
ltheme$strip.background$col <- "transparent" ## change strip bg
lattice.options(default.theme = ltheme) ## set as default
dbc <- dbConnect(dbDriver("SQLite"), dbname = "data/simulations.db")
d <- dbGetQuery(dbc, "select reject, n, kNull, nulllabel, altlabel, norm
from viewftest where label = 'size'")
dbDisconnect(dbc)
d$nulllabel[d$nulllabel == "K0=2"] <- "$2$"
d$nulllabel[d$nulllabel == "K0=n/50"] <- "$T/50$"
d$altlabel[d$altlabel == "K=3"] <- "$3$"
d$altlabel[d$altlabel == "K=T/10"] <- "$T/10$"
dl <- lapply(unique(d$norm), function(dnorm) d[d$norm == dnorm,])
dd <- dl[[1]][, c("nulllabel", "altlabel", "n", "reject")]
names(dd) <- c("$K_1$", "$K_2$", "$T$", "$| \\theta_2 |_2 = 0$")
dd[,"$| \\theta_2 |_2 = 1$"] <- dl[[2]]$reject
tabscode <- booktabs(dd,
align = c("l", "l", "C", "C", "C"),
digits = c(0, 0, 0, 3, 3),
numberformat = c(FALSE, FALSE, TRUE, TRUE, TRUE))
tabscode <- gsub("\\\\toprule", "\\\\toprule &&&
\\\\multicolumn{2}{c}{Conditional rejection probability (size)} \\\\\\\\
\\\\cmidrule(l){4-5}", tabscode)
cat(file = "floats/mc-ftest.tex", "\\begin{table}[tb]\n", tabscode,
"\\caption{Simulated rejection probabilities for the $F$-test under
the null hypothesis that the benchmark model will forecast better,
$\\E_T \\oosB \\leq 0$. Nominal size is 10\\% and values greater than
10\\% indicate that the test rejects the benchmark model too often.
See Section~\\ref{sec:simulation-design} for a discussion of the
simulation design.}
\\label{fig:ftest}
\\end{table}")
|
#Working Directory by default "/home/kartik"
#Change Working Directory
setwd("/home/kartik/Desktop/R-Statistical-Computing/Cars Analysis")
#Reading CSV Data
my_data = read.csv("cars.csv",header = TRUE)
#Display CSV
my_data
| /Cars Analysis/Load_CSV_Data.R | no_license | KartikKannapur/R-Statistical-Computing | R | false | false | 226 | r | #Working Directory by default "/home/kartik"
#Change Working Directory
setwd("/home/kartik/Desktop/R-Statistical-Computing/Cars Analysis")
#Reading CSV Data
my_data = read.csv("cars.csv",header = TRUE)
#Display CSV
my_data
|
#' Denoise an image
#'
#' Denoise an image using a spatially adaptive filter originally described in J. V.
#' Manjon, P. Coupe, Luis Marti-Bonmati, D. L. Collins, and M. Robles. Adaptive
#' Non-Local Means Denoising of MR Images With Spatially Varying Noise Levels,
#' Journal of Magnetic Resonance Imaging, 31:192-203, June 2010.
#'
#' @param img scalar image to denoise.
#' @param mask optional to limit the denoise region.
#' @param shrinkFactor downsampling level performed within the algorithm.
#' @param p patch radius for local sample. can be a vector.
#' @param r search radius from which to choose extra local samples. can be a vector.
#' @param noiseModel either Rician or Gaussian.
#' @param verbose boolean
#' @return antsImage denoised version of image
#' @author N Tustison, B Avants
#' @examples
#'
#' img <- antsImageRead( getANTsRData("rand") ) %>% resampleImage( c(32, 32) )
#' dimg <- denoiseImage( img, img * 0 + 1 )
#' dimg2 <- denoiseImage( img)
#'
#' @export denoiseImage
denoiseImage <- function(
img,
mask,
shrinkFactor = 1,
p = 1,
r = 3,
noiseModel = c("Rician","Gaussian"),
verbose = FALSE )
{
img = check_ants(img)
outimg = antsImageClone( img )
noiseModel = match.arg(noiseModel)
mydim = img@dimension
if ( length( p ) > 1 ) pvar = paste0( p, collapse='x' ) else pvar=p
if ( length( r ) > 1 ) rvar = paste0( r, collapse='x' ) else rvar=r
if ( ! missing( mask ) ) {
mask = check_ants(mask)
mskIn = antsImageClone( mask, 'unsigned char')
mskIn = antsCopyImageInfo( img, mskIn )
myargs <- list(
d = mydim,
i = img,
n = noiseModel[1],
x = mskIn,
s = as.numeric( shrinkFactor ),
p = pvar,
r = rvar,
o = outimg,
v = as.numeric( verbose )
)
} else {
myargs <- list(
d = mydim,
i = img,
n = noiseModel[1],
s = as.numeric( shrinkFactor ),
p = pvar,
r = rvar,
o = outimg,
v = as.numeric( verbose )
)
}
.Call("DenoiseImage", .int_antsProcessArguments( c( myargs ) ), PACKAGE = "ANTsRCore")
return( outimg )
}
| /R/denoiseImage.R | permissive | ANTsX/ANTsRCore | R | false | false | 2,126 | r | #' Denoise an image
#'
#' Denoise an image using a spatially adaptive filter originally described in J. V.
#' Manjon, P. Coupe, Luis Marti-Bonmati, D. L. Collins, and M. Robles. Adaptive
#' Non-Local Means Denoising of MR Images With Spatially Varying Noise Levels,
#' Journal of Magnetic Resonance Imaging, 31:192-203, June 2010.
#'
#' @param img scalar image to denoise.
#' @param mask optional to limit the denoise region.
#' @param shrinkFactor downsampling level performed within the algorithm.
#' @param p patch radius for local sample. can be a vector.
#' @param r search radius from which to choose extra local samples. can be a vector.
#' @param noiseModel either Rician or Gaussian.
#' @param verbose boolean
#' @return antsImage denoised version of image
#' @author N Tustison, B Avants
#' @examples
#'
#' img <- antsImageRead( getANTsRData("rand") ) %>% resampleImage( c(32, 32) )
#' dimg <- denoiseImage( img, img * 0 + 1 )
#' dimg2 <- denoiseImage( img)
#'
#' @export denoiseImage
denoiseImage <- function(
img,
mask,
shrinkFactor = 1,
p = 1,
r = 3,
noiseModel = c("Rician","Gaussian"),
verbose = FALSE )
{
img = check_ants(img)
outimg = antsImageClone( img )
noiseModel = match.arg(noiseModel)
mydim = img@dimension
if ( length( p ) > 1 ) pvar = paste0( p, collapse='x' ) else pvar=p
if ( length( r ) > 1 ) rvar = paste0( r, collapse='x' ) else rvar=r
if ( ! missing( mask ) ) {
mask = check_ants(mask)
mskIn = antsImageClone( mask, 'unsigned char')
mskIn = antsCopyImageInfo( img, mskIn )
myargs <- list(
d = mydim,
i = img,
n = noiseModel[1],
x = mskIn,
s = as.numeric( shrinkFactor ),
p = pvar,
r = rvar,
o = outimg,
v = as.numeric( verbose )
)
} else {
myargs <- list(
d = mydim,
i = img,
n = noiseModel[1],
s = as.numeric( shrinkFactor ),
p = pvar,
r = rvar,
o = outimg,
v = as.numeric( verbose )
)
}
.Call("DenoiseImage", .int_antsProcessArguments( c( myargs ) ), PACKAGE = "ANTsRCore")
return( outimg )
}
|
codes <- c(380,124,818)
country <- c("italy","canada","egypt")
names(codes) <- country | /settingColumnNames.r | no_license | faruqa/ds-homework | R | false | false | 88 | r | codes <- c(380,124,818)
country <- c("italy","canada","egypt")
names(codes) <- country |
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/serach_functions.R
\name{search_function}
\alias{search_function}
\title{Search functions in a package matching a pattern.}
\usage{
search_function(pattern, pkg_nm)
}
\arguments{
\item{pattern}{Argument passed to \code{\link[base:grepl]{base::grepl()}}.}
\item{pkg_nm}{A character string giving the name of the package to search.}
}
\value{
A vector of characters
}
\description{
You may need a function which name you remember only partly. Use this
function to serach all functions which name match whatever you remember.
}
\details{
There are multiple ways to find a function in a package, e.g. with the
autocomplete feature in RStudio; by searching the package's index; and by
searching the function's reference in the package's website. However, there
is no way to do it programmatically. This function provides a \emph{programmatic}
way to search functions in a package, based on a user-defined pattern, and
makes it easy to search multiple patterns at once via \code{lapply()}.
}
\examples{
# R loads a number of packages automatically. See what those packages are:
search()
# Directly search functions in any package already loaded: e.g. "base"
search_function("summary", pkg_nm = "base")
# Case is ignored
search_function("Summary", pkg_nm = "base")
# Easily search multiple patterns with lapply
multiple_patterns <- c("min", "ply")
lapply(multiple_patterns, search_function, pkg_nm = "base")
# If the package you want to search isn't load it, you must load it first.
\dontrun{
library(ggplot2)
search_function("point", pkg_nm = "ggplot2")
}
}
\seealso{
\code{\link[base:grepl]{base::grepl()}}
}
| /man/search_function.Rd | no_license | maurolepore/handy | R | false | true | 1,688 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/serach_functions.R
\name{search_function}
\alias{search_function}
\title{Search functions in a package matching a pattern.}
\usage{
search_function(pattern, pkg_nm)
}
\arguments{
\item{pattern}{Argument passed to \code{\link[base:grepl]{base::grepl()}}.}
\item{pkg_nm}{A character string giving the name of the package to search.}
}
\value{
A vector of characters
}
\description{
You may need a function which name you remember only partly. Use this
function to serach all functions which name match whatever you remember.
}
\details{
There are multiple ways to find a function in a package, e.g. with the
autocomplete feature in RStudio; by searching the package's index; and by
searching the function's reference in the package's website. However, there
is no way to do it programmatically. This function provides a \emph{programmatic}
way to search functions in a package, based on a user-defined pattern, and
makes it easy to search multiple patterns at once via \code{lapply()}.
}
\examples{
# R loads a number of packages automatically. See what those packages are:
search()
# Directly search functions in any package already loaded: e.g. "base"
search_function("summary", pkg_nm = "base")
# Case is ignored
search_function("Summary", pkg_nm = "base")
# Easily search multiple patterns with lapply
multiple_patterns <- c("min", "ply")
lapply(multiple_patterns, search_function, pkg_nm = "base")
# If the package you want to search isn't load it, you must load it first.
\dontrun{
library(ggplot2)
search_function("point", pkg_nm = "ggplot2")
}
}
\seealso{
\code{\link[base:grepl]{base::grepl()}}
}
|
library("MASS")
library("lattice")
# scatterplots of lstat and medv by rad
xyplot(medv~lstat|factor(rad), data=Boston) | /inst/examples/data/mgraphics/example_trellis_xyplot.R | no_license | Kale14/mmstat4 | R | false | false | 118 | r | library("MASS")
library("lattice")
# scatterplots of lstat and medv by rad
xyplot(medv~lstat|factor(rad), data=Boston) |
library(SoilR)
### Name: fW.Century
### Title: Effects of moisture on decomposition rates according to the
### CENTURY model
### Aliases: fW.Century
### ** Examples
PPT=seq(0,1500,by=10)
PET=rep(1500,length(PPT))
PPT.PET=fW.Century(PPT,PET)
plot(PPT/PET,PPT.PET,
ylab="f(PPT, PET) (unitless)",
main="Effects of precipitation and potential evapotranspiration on decomposition rates")
| /data/genthat_extracted_code/SoilR/examples/127.Rd.R | no_license | surayaaramli/typeRrh | R | false | false | 404 | r | library(SoilR)
### Name: fW.Century
### Title: Effects of moisture on decomposition rates according to the
### CENTURY model
### Aliases: fW.Century
### ** Examples
PPT=seq(0,1500,by=10)
PET=rep(1500,length(PPT))
PPT.PET=fW.Century(PPT,PET)
plot(PPT/PET,PPT.PET,
ylab="f(PPT, PET) (unitless)",
main="Effects of precipitation and potential evapotranspiration on decomposition rates")
|
setwd("~/Documents/Dissertation/Writing/manuscripts/Ch1/data/temp/")
getwd()
library(Hmisc)
library(MASS)
library(ggplot2)
library(lme4)
library(multcomp)
library(lubridate)
library(data.table)
require(lsmeans)
library(multcompView)
library(car)
library(dplyr)
library(tidyr)
library(Hmisc)
library(FSA)
#Ofu pool temperatures 2015-2016
#read in hobotemp file
temp<-read.delim("AStemp2016-17_avg2.txt",header=T)
temp<-read.delim(pipe("pbpaste"))
head(temp)
#strip Date and time
temp$DateTime<-strptime(temp$DateTime, format="%m/%d/%y %H:%M")
#make month and year-month column to do summarize stats
temp$year=year(temp$DateTime)
temp$month=month(temp$DateTime)
temp$day=day(temp$DateTime)
temp<-unite(temp, 'date', c('month','year'),remove=F)
temp<-unite(temp, 'd', c('day','month','year'),remove=F)
#temp=mutate(temp,date=factor(date,levels=unique(date)))
str(temp)
tail(temp)
#summarize max, min, mean, etc for each day
temp$d=factor(temp$d,levels=unique(temp$d))
HV<-Summarize(HV~d,data=temp,digits=3)
MV<-Summarize(MV~d,data=temp,digits=3)
LV<-Summarize(LV~d,data=temp,digits=3)
write.table(HV,"ASdailytempsumm2-HV_2016-17.txt",sep = "\t")
write.table(MV,"ASdailytempsumm2-MV_2016-17.txt",sep = "\t")
write.table(LV,"ASdailytempsumm2-LV_2016-17.txt",sep = "\t")
#summarize max, min, mean, etc for each month
HVmo<-Summarize(HV~date,data=temp,digits=3)
MVmo<-Summarize(MV~date,data=temp,digits=3)
LVmo<-Summarize(LV~date,data=temp,digits=3)
#black bgnd plot
pdf("2015-16_AStempplot-blackbg.pdf",11,7)
par(bg="black",fg="white",col.lab="white")
plot(temp$DateTime, temp$HV, type="l", col="red", lwd=1.5, ylab="Temperature (°C)", xlab="2015-2016", main="Ofu HV Pool Temperature",col.main="white",col.axis="white",xaxt='n',ylim=c(25.5,35))
points(temp$DateTime, temp$MV, type="l", col="gold", lwd=1.5)
points(temp$DateTime, temp$LV, type="l", col="blue", lwd=1.5)
abline(h=30.2,lty=2,col="white")
#text(0,30.5,"Bleaching Threshold 30.1 °C",col="black")
#to specify the x-axis by months within the DateTime, and remove tick marks
axis.POSIXct(side=1,at=temp$DateTime,format='%b-%y',col.axis="white",lwd=0,lwd.tick=0)
legend("topright",c("HV","MV","LV"),lty=1,lwd=2.5,col=c("red","gold","blue"),bty="n")
dev.off()
#white background
pdf("2015-16_AStempplot.pdf",11,7)
plot(temp$DateTime, temp$HV, type="l", col="red", lwd=1.5, ylab="Temperature (°C)", xlab="2015-2016", main="Ofu HV Pool Temperature",xaxt='n',ylim=c(25.5,35))
points(temp$DateTime, temp$MV, type="l", col="gold", lwd=1.5)
points(temp$DateTime, temp$LV, type="l", col="blue", lwd=1.5)
abline(h=30.2,lty=2,col="black")
#text(0,30.5,"Bleaching Threshold 30.1 °C",col="black")
#to specify the x-axis by months within the DateTime, and remove tick marks
axis.POSIXct(side=1,at=temp$DateTime,format='%b-%y',col.axis="black",lwd=0,lwd.tick=0)
legend("topright",c("HV","MV","LV"),lty=1,lwd=2.5,col=c("red","gold","blue"),bty="n")
dev.off()
#copied summary stats of each site into one data frame and saved as tempsumday.txt in Excel. Imported here.
temp<-read.delim("~/Documents/Dissertation/Writing/manuscripts/Ch1/data/temp/AS_2015-16_tempsumday.txt",header=T)
str(temp)
summary(temp)
temp$site=factor(temp$site,levels(temp$site)[c(1,3,2)])
#anova of max temp
model=lm(max~site*season,data=temp)
anova(model)
summary(model)
##
lsmeans(model,pairwise~site*season,adjust='tukey')
lsmeans(model,pairwise~season,adjust='tukey')
#anova of mean temp
model=lm(mean~site*season,data=temp)
anova(model)
summary(model)
##
lsmeans(model,pairwise~season,adjust='tukey')
#anova of min temp
model=lm(min~site*season,data=temp)
anova(model)
summary(model)
##
lsmeans(model,pairwise~site,adjust='tukey')
lsmeans(model,pairwise~season,adjust='tukey')
#plotting monthly summary of mean, max, min
summary(temp)
temp$d<-as.Date(strptime(temp$d , "%m/%d/%y"))
temp$month <- as.factor(format(temp$d,'%b'))
class(temp$month)
levels(temp$month)
temp$month=factor(temp$month,levels(temp$month)[c(6,7,3,4,5,1,2,10,9,8,11,12)])
#boxplot of mean
pdf("2015-16_OfuDailyboxplot.pdf",10,8)
p1<-ggplot(temp,aes(x=month, y=mean, fill=site)) + geom_boxplot() +
xlab("Month") + ylab("Temperature (°C)") + ggtitle("A. Mean Daily Temperatures")+ scale_fill_manual(guide=FALSE,values=c("red","gold","blue")) + theme_bw()
p2<-ggplot(temp,aes(x=month, y=max, fill=site)) + geom_boxplot() +
xlab("Month") + ylab("Temperature (°C)") + ggtitle("B. Max Daily Temperatures") + scale_fill_manual(guide=FALSE,values=c("red","gold","blue")) + theme_bw()
p3<-ggplot(temp,aes(x=month, y=range, fill=site)) + geom_boxplot() +
xlab("Month") + ylab("Temperature (°C)") + ggtitle("C. Daily Temperature Range")+ scale_fill_manual(guide=FALSE,values=c("red","gold","blue")) + theme_bw() #+ scale_color_manual(name="Site",values=c("black","black","black")) + theme(legend.position="bottom")
source("http://peterhaschke.com/Code/multiplot.R")
multiplot(p1, p2, p3, cols=1)
dev.off()
#seasonal summary of mean, max, min
#boxplot of mean
library(cowplot)
pdf("20190304_2015-16_OfuSeasonboxplot-outliersmean.pdf",10,8)
p3<-ggplot(temp,aes(x=season, y=mean, fill=site)) + geom_boxplot() + stat_summary(fun.y=mean, geom="point", shape=18, size=3, position = position_dodge(0.75)) +
ylab("Mean Daily Temperature (°C)") + ggtitle("C") + scale_fill_manual(guide=FALSE,values=c("red","gold","blue")) + theme_bw(base_size=14) +theme(axis.title.x=element_blank())
p1<-ggplot(temp,aes(x=season, y=max, fill=site)) + geom_boxplot() + stat_summary(fun.y=mean, geom="point", shape=18, size=3, position = position_dodge(0.75)) +
ylab("Max Daily Temperature (°C)") + ggtitle("A") + scale_fill_manual(guide=FALSE,values=c("red","gold","blue")) + theme_bw(base_size=14) +theme(axis.title.x=element_blank())
p2<-ggplot(temp,aes(x=season, y=range, fill=site)) + geom_boxplot() + stat_summary(fun.y=mean, geom="point", shape=18, size=3, position = position_dodge(0.75)) +
ylab("Daily Temperature Range (°C)") + ggtitle("B")+ scale_fill_manual(guide=FALSE,values=c("red","gold","blue")) + theme_bw(base_size=14) +theme(axis.title.x=element_blank())
plot_grid(p1, p2, p3, nrow=1)
#save_plot("20190221_2015-16_OfuSeasonboxplot-outliers-6.pdf", gg_all, base_height = 6)
dev.off()
#summary of mean, max, min by site
#boxplot of mean
pdf("2015-16_OfuTempSummboxplot-outliers.pdf",10,8)
p3<-ggplot(temp,aes(x=site, y=mean, fill=site)) + geom_boxplot() +
xlab("Site") + ylab("Temperature (°C)") + ggtitle("C. Mean Daily Temperatures")+ scale_fill_manual(guide=FALSE,values=c("red","gold","blue")) + theme_bw()
p1<-ggplot(temp,aes(x=site, y=max, fill=site)) + geom_boxplot() +
xlab("Site") + ylab("Temperature (°C)") + ggtitle("A. Max Daily Temperatures") + scale_fill_manual(guide=FALSE,values=c("red","gold","blue")) + theme_bw()
p2<-ggplot(temp,aes(x=site, y=range, fill=site)) + geom_boxplot() +
xlab("Site") + ylab("Temperature (°C)") + ggtitle("B. Daily Temperature Range")+ scale_fill_manual(guide=FALSE,values=c("red","gold","blue")) + theme_bw() #+ scale_color_manual(name="Site",values=c("black","black","black")) + theme(legend.position="bottom")
source("http://peterhaschke.com/Code/multiplot.R")
multiplot(p1, p2, p3, cols=3)
dev.off()
#######################
#ANOVA of Ofu historical temperatures: DHW,SST,SSTA
noaa<-read.csv("~/Documents/Dissertation/Writing/manuscripts/Ch1/data/temp/NOAACRW5km_2000-2017_OfuIsland.csv")
noaa=mutate(noaa,year=factor(year,levels=unique(year)))
noaa=mutate(noaa,month=factor(month,levels=unique(month)))
noaa=mutate(noaa,day=factor(day,levels=unique(day)))
noaa=mutate(noaa,month=month.abb[month])
str(noaa)
library(tidyr)
noaa<-unite(noaa, date, c(year,month),remove=F)
noaa=mutate(noaa,date=factor(date,levels=unique(date)))
summary(noaa)
#summary of each variable, separated by each month
Summarize(DHW~date,data=noaa,digits=3)
Summarize(SST~date,data=noaa,digits=3)
Summarize(SSTA~date,data=noaa,digits=3)
bartlett.test(DHW~date,data=noaa) #if pval >= 0.05, variance is equal
#anova of DHW
model=lm(DHW~year,data=noaa)
anova(model)
summary(model)
lsmeans(model,pairwise~year,adjust='tukey')
tukey<-cld(leastsquare,alpha=0.05,Letters=letters,adjust='tukey')
plot(tukey,las=1,col="black")
#anova of SST
model=lm(SST~year,data=noaa)
anova(model)
lsmeans(model,pairwise~year,adjust='tukey')
#anova of SSTA
model=lm(SSTA~year,data=noaa)
anova(model)
lsmeans(model,pairwise~year,adjust='tukey')
########################
#line plot of temps from 2010-2012 & 2015-2017
stan<-noaa[noaa$year =='2010' | noaa$year == '2011' | noaa$year == '2012',]
odu<-noaa[noaa$year =='2015' | noaa$year == '2016'| noaa$year == '2017',]
write.csv(stan,"NOAA2010-12.csv")
write.csv(odu,"NOAA2015-17.csv")
dat<-read.csv("~/Documents/Dissertation/Writing/manuscripts/Ch1/data/temp/NOAAstanVme.csv")
summary(dat)
dat=mutate(dat,date=factor(date,levels=unique(date)))
#dat$date <- strptime(dat$date,format="%b-%d")
names(dat)
head(dat)
#Set the Theshold Above Which to Count Temperatures
Threshold=30.2
#plot of 2015-2017 vs. 2010-2012 SST & DHW
pdf("NOAA-stanVSme-SST&DHW.pdf",11,7)
par(mar=c(5,5,3,5))
#plot SST for each year
plot(dat$date, dat$SST10, type='n', cex.lab=1.5,cex.axis=1.5, ylab="Temperature (°C)", xlab="Month",main="Ofu Pool Temperature & DHW",ylim=c(24,32))
points(dat$date, dat$SST10, type="l", col="red", lwd=3)
points(dat$date, dat$SST11, type="l", col="orange", lwd=3)
points(dat$date, dat$SST12, type="l", col="green3", lwd=3)
points(dat$date, dat$SST15, type="l", col="blue", lwd=3)
points(dat$date, dat$SST16, type="l", col="steelblue1", lwd=3)
points(dat$date, dat$SST17, type="l", col="mediumpurple", lwd=3)
abline(h=30.2)
#axis(1,at=dat$date,tick=F,labels=format(as.Date(dat$date), "%b"))
#plot DHW for each year under SST, extend y axis to leave room for DHW
par(new=T)
plot(dat$date,dat[,7],type="l",lty=5, col="blue", lwd=3, xaxt='n',xlab='',yaxt='n',ylab='',ylim=c(0,20))
points(dat$date,dat[,15],type="l",lty=5, col="red", lwd=3)
points(dat$date,dat[,19],type="l",lty=5, col="orange", lwd=3)
points(dat$date,dat[,23],type="l",lty=5, col="green3", lwd=3)
points(dat$date,dat[,11],type="l",lty=5, col="steelblue1", lwd=3)
points(dat$date,dat[,27],type="l",lty=5, col="mediumpurple", lwd=3)
axis(side=4, cex.axis=1.5)
mtext("DHW (°C week)",cex=1.5,side=4,line=3)
legend(c(as.POSIXct("2018-12-26 EST"),5),cex=1.5,c("2010","2011","2012","2015","2016","2017"),lty=1,lwd=4,col=c("red","orange","green3","blue","steelblue1","mediumpurple"),bty="n")
dev.off()
#median box plot of historical DHW
pdf("2000-17_OfuDHW-medianboxplot.pdf",8,8)
ggplot(noaa, aes(x = year, y = DHW, group=year)) +
geom_boxplot(colour = "black", width = 0.5) +
labs(x = "Year",
y = "DHW ") +
## ggtitle("Main title") +
theme_classic() + theme(panel.grid.major.y = element_line( size=.1, color="gray"))
dev.off()
##frequency plot of daily temp ranges
pdf("OfuTempRange.pdf",5,5)
ggplot(temp)+geom_freqpoly(aes(x=range,color=site,linetype=site),size=1)+theme_classic()+xlab("Daily Temperature Range (°C)")+ylab("Frequency of Occurence (%)")+scale_color_manual(guide=FALSE,values=c("red","gold","blue"))
dev.off()
#box plot of median
plot(noaa$DHW,data=noaa)
library(ggplot2)
letters=c("a","bcd","e","f","ab","cde","ab","de","a","abc","de","a","ab","abcd","cde","g","f","h")
pdf("2000-17_OfuDHW-medianboxplot.pdf",8,8)
ggplot(noaa, aes(x = year, y = DHW, group=year)) +
geom_boxplot(colour = "black", width = 0.5) +
labs(x = "Year",
y = "DHW ") +
## ggtitle("Main title") +
theme_classic() + theme(panel.grid.major.y = element_line( size=.1, color="gray"))
dev.off()
#boxplot with the mean instead median
pdf("2000-17_OfuDHW.pdf",8,8)
ggplot(noaa, aes(year)) +
geom_boxplot(aes(ymin = min, lower = Q1, middle=mean, upper=Q3,ymax=max),stat="identity") +
xlab("Year") + ylab("Degree Heating Weeks") +
theme_classic() + #title("Mean Degree Heating Weeks")
theme( # remove the vertical grid lines
panel.grid.major.x = element_blank() ,
# explicitly set the horizontal lines (or they will disappear too)
panel.grid.major.y = element_line( size=.1, color="gray"))
dev.off()
| /temp/AS_Temp-SubsetTest&Plot.R | no_license | BarshisLab/project_reducedtolerance_massivecorals_variablehabitats | R | false | false | 12,345 | r | setwd("~/Documents/Dissertation/Writing/manuscripts/Ch1/data/temp/")
getwd()
library(Hmisc)
library(MASS)
library(ggplot2)
library(lme4)
library(multcomp)
library(lubridate)
library(data.table)
require(lsmeans)
library(multcompView)
library(car)
library(dplyr)
library(tidyr)
library(Hmisc)
library(FSA)
#Ofu pool temperatures 2015-2016
#read in hobotemp file
temp<-read.delim("AStemp2016-17_avg2.txt",header=T)
temp<-read.delim(pipe("pbpaste"))
head(temp)
#strip Date and time
temp$DateTime<-strptime(temp$DateTime, format="%m/%d/%y %H:%M")
#make month and year-month column to do summarize stats
temp$year=year(temp$DateTime)
temp$month=month(temp$DateTime)
temp$day=day(temp$DateTime)
temp<-unite(temp, 'date', c('month','year'),remove=F)
temp<-unite(temp, 'd', c('day','month','year'),remove=F)
#temp=mutate(temp,date=factor(date,levels=unique(date)))
str(temp)
tail(temp)
#summarize max, min, mean, etc for each day
temp$d=factor(temp$d,levels=unique(temp$d))
HV<-Summarize(HV~d,data=temp,digits=3)
MV<-Summarize(MV~d,data=temp,digits=3)
LV<-Summarize(LV~d,data=temp,digits=3)
write.table(HV,"ASdailytempsumm2-HV_2016-17.txt",sep = "\t")
write.table(MV,"ASdailytempsumm2-MV_2016-17.txt",sep = "\t")
write.table(LV,"ASdailytempsumm2-LV_2016-17.txt",sep = "\t")
#summarize max, min, mean, etc for each month
HVmo<-Summarize(HV~date,data=temp,digits=3)
MVmo<-Summarize(MV~date,data=temp,digits=3)
LVmo<-Summarize(LV~date,data=temp,digits=3)
#black bgnd plot
pdf("2015-16_AStempplot-blackbg.pdf",11,7)
par(bg="black",fg="white",col.lab="white")
plot(temp$DateTime, temp$HV, type="l", col="red", lwd=1.5, ylab="Temperature (°C)", xlab="2015-2016", main="Ofu HV Pool Temperature",col.main="white",col.axis="white",xaxt='n',ylim=c(25.5,35))
points(temp$DateTime, temp$MV, type="l", col="gold", lwd=1.5)
points(temp$DateTime, temp$LV, type="l", col="blue", lwd=1.5)
abline(h=30.2,lty=2,col="white")
#text(0,30.5,"Bleaching Threshold 30.1 °C",col="black")
#to specify the x-axis by months within the DateTime, and remove tick marks
axis.POSIXct(side=1,at=temp$DateTime,format='%b-%y',col.axis="white",lwd=0,lwd.tick=0)
legend("topright",c("HV","MV","LV"),lty=1,lwd=2.5,col=c("red","gold","blue"),bty="n")
dev.off()
#white background
pdf("2015-16_AStempplot.pdf",11,7)
plot(temp$DateTime, temp$HV, type="l", col="red", lwd=1.5, ylab="Temperature (°C)", xlab="2015-2016", main="Ofu HV Pool Temperature",xaxt='n',ylim=c(25.5,35))
points(temp$DateTime, temp$MV, type="l", col="gold", lwd=1.5)
points(temp$DateTime, temp$LV, type="l", col="blue", lwd=1.5)
abline(h=30.2,lty=2,col="black")
#text(0,30.5,"Bleaching Threshold 30.1 °C",col="black")
#to specify the x-axis by months within the DateTime, and remove tick marks
axis.POSIXct(side=1,at=temp$DateTime,format='%b-%y',col.axis="black",lwd=0,lwd.tick=0)
legend("topright",c("HV","MV","LV"),lty=1,lwd=2.5,col=c("red","gold","blue"),bty="n")
dev.off()
#copied summary stats of each site into one data frame and saved as tempsumday.txt in Excel. Imported here.
temp<-read.delim("~/Documents/Dissertation/Writing/manuscripts/Ch1/data/temp/AS_2015-16_tempsumday.txt",header=T)
str(temp)
summary(temp)
temp$site=factor(temp$site,levels(temp$site)[c(1,3,2)])
#anova of max temp
model=lm(max~site*season,data=temp)
anova(model)
summary(model)
##
lsmeans(model,pairwise~site*season,adjust='tukey')
lsmeans(model,pairwise~season,adjust='tukey')
#anova of mean temp
model=lm(mean~site*season,data=temp)
anova(model)
summary(model)
##
lsmeans(model,pairwise~season,adjust='tukey')
#anova of min temp
model=lm(min~site*season,data=temp)
anova(model)
summary(model)
##
lsmeans(model,pairwise~site,adjust='tukey')
lsmeans(model,pairwise~season,adjust='tukey')
#plotting monthly summary of mean, max, min
summary(temp)
temp$d<-as.Date(strptime(temp$d , "%m/%d/%y"))
temp$month <- as.factor(format(temp$d,'%b'))
class(temp$month)
levels(temp$month)
temp$month=factor(temp$month,levels(temp$month)[c(6,7,3,4,5,1,2,10,9,8,11,12)])
#boxplot of mean
pdf("2015-16_OfuDailyboxplot.pdf",10,8)
p1<-ggplot(temp,aes(x=month, y=mean, fill=site)) + geom_boxplot() +
xlab("Month") + ylab("Temperature (°C)") + ggtitle("A. Mean Daily Temperatures")+ scale_fill_manual(guide=FALSE,values=c("red","gold","blue")) + theme_bw()
p2<-ggplot(temp,aes(x=month, y=max, fill=site)) + geom_boxplot() +
xlab("Month") + ylab("Temperature (°C)") + ggtitle("B. Max Daily Temperatures") + scale_fill_manual(guide=FALSE,values=c("red","gold","blue")) + theme_bw()
p3<-ggplot(temp,aes(x=month, y=range, fill=site)) + geom_boxplot() +
xlab("Month") + ylab("Temperature (°C)") + ggtitle("C. Daily Temperature Range")+ scale_fill_manual(guide=FALSE,values=c("red","gold","blue")) + theme_bw() #+ scale_color_manual(name="Site",values=c("black","black","black")) + theme(legend.position="bottom")
source("http://peterhaschke.com/Code/multiplot.R")
multiplot(p1, p2, p3, cols=1)
dev.off()
#seasonal summary of mean, max, min
#boxplot of mean
library(cowplot)
pdf("20190304_2015-16_OfuSeasonboxplot-outliersmean.pdf",10,8)
p3<-ggplot(temp,aes(x=season, y=mean, fill=site)) + geom_boxplot() + stat_summary(fun.y=mean, geom="point", shape=18, size=3, position = position_dodge(0.75)) +
ylab("Mean Daily Temperature (°C)") + ggtitle("C") + scale_fill_manual(guide=FALSE,values=c("red","gold","blue")) + theme_bw(base_size=14) +theme(axis.title.x=element_blank())
p1<-ggplot(temp,aes(x=season, y=max, fill=site)) + geom_boxplot() + stat_summary(fun.y=mean, geom="point", shape=18, size=3, position = position_dodge(0.75)) +
ylab("Max Daily Temperature (°C)") + ggtitle("A") + scale_fill_manual(guide=FALSE,values=c("red","gold","blue")) + theme_bw(base_size=14) +theme(axis.title.x=element_blank())
p2<-ggplot(temp,aes(x=season, y=range, fill=site)) + geom_boxplot() + stat_summary(fun.y=mean, geom="point", shape=18, size=3, position = position_dodge(0.75)) +
ylab("Daily Temperature Range (°C)") + ggtitle("B")+ scale_fill_manual(guide=FALSE,values=c("red","gold","blue")) + theme_bw(base_size=14) +theme(axis.title.x=element_blank())
plot_grid(p1, p2, p3, nrow=1)
#save_plot("20190221_2015-16_OfuSeasonboxplot-outliers-6.pdf", gg_all, base_height = 6)
dev.off()
#summary of mean, max, min by site
#boxplot of mean
pdf("2015-16_OfuTempSummboxplot-outliers.pdf",10,8)
p3<-ggplot(temp,aes(x=site, y=mean, fill=site)) + geom_boxplot() +
xlab("Site") + ylab("Temperature (°C)") + ggtitle("C. Mean Daily Temperatures")+ scale_fill_manual(guide=FALSE,values=c("red","gold","blue")) + theme_bw()
p1<-ggplot(temp,aes(x=site, y=max, fill=site)) + geom_boxplot() +
xlab("Site") + ylab("Temperature (°C)") + ggtitle("A. Max Daily Temperatures") + scale_fill_manual(guide=FALSE,values=c("red","gold","blue")) + theme_bw()
p2<-ggplot(temp,aes(x=site, y=range, fill=site)) + geom_boxplot() +
xlab("Site") + ylab("Temperature (°C)") + ggtitle("B. Daily Temperature Range")+ scale_fill_manual(guide=FALSE,values=c("red","gold","blue")) + theme_bw() #+ scale_color_manual(name="Site",values=c("black","black","black")) + theme(legend.position="bottom")
source("http://peterhaschke.com/Code/multiplot.R")
multiplot(p1, p2, p3, cols=3)
dev.off()
#######################
#ANOVA of Ofu historical temperatures: DHW,SST,SSTA
noaa<-read.csv("~/Documents/Dissertation/Writing/manuscripts/Ch1/data/temp/NOAACRW5km_2000-2017_OfuIsland.csv")
noaa=mutate(noaa,year=factor(year,levels=unique(year)))
noaa=mutate(noaa,month=factor(month,levels=unique(month)))
noaa=mutate(noaa,day=factor(day,levels=unique(day)))
noaa=mutate(noaa,month=month.abb[month])
str(noaa)
library(tidyr)
noaa<-unite(noaa, date, c(year,month),remove=F)
noaa=mutate(noaa,date=factor(date,levels=unique(date)))
summary(noaa)
#summary of each variable, separated by each month
Summarize(DHW~date,data=noaa,digits=3)
Summarize(SST~date,data=noaa,digits=3)
Summarize(SSTA~date,data=noaa,digits=3)
bartlett.test(DHW~date,data=noaa) #if pval >= 0.05, variance is equal
#anova of DHW
model=lm(DHW~year,data=noaa)
anova(model)
summary(model)
lsmeans(model,pairwise~year,adjust='tukey')
tukey<-cld(leastsquare,alpha=0.05,Letters=letters,adjust='tukey')
plot(tukey,las=1,col="black")
#anova of SST
model=lm(SST~year,data=noaa)
anova(model)
lsmeans(model,pairwise~year,adjust='tukey')
#anova of SSTA
model=lm(SSTA~year,data=noaa)
anova(model)
lsmeans(model,pairwise~year,adjust='tukey')
########################
#line plot of temps from 2010-2012 & 2015-2017
stan<-noaa[noaa$year =='2010' | noaa$year == '2011' | noaa$year == '2012',]
odu<-noaa[noaa$year =='2015' | noaa$year == '2016'| noaa$year == '2017',]
write.csv(stan,"NOAA2010-12.csv")
write.csv(odu,"NOAA2015-17.csv")
dat<-read.csv("~/Documents/Dissertation/Writing/manuscripts/Ch1/data/temp/NOAAstanVme.csv")
summary(dat)
dat=mutate(dat,date=factor(date,levels=unique(date)))
#dat$date <- strptime(dat$date,format="%b-%d")
names(dat)
head(dat)
#Set the Theshold Above Which to Count Temperatures
Threshold=30.2
#plot of 2015-2017 vs. 2010-2012 SST & DHW
pdf("NOAA-stanVSme-SST&DHW.pdf",11,7)
par(mar=c(5,5,3,5))
#plot SST for each year
plot(dat$date, dat$SST10, type='n', cex.lab=1.5,cex.axis=1.5, ylab="Temperature (°C)", xlab="Month",main="Ofu Pool Temperature & DHW",ylim=c(24,32))
points(dat$date, dat$SST10, type="l", col="red", lwd=3)
points(dat$date, dat$SST11, type="l", col="orange", lwd=3)
points(dat$date, dat$SST12, type="l", col="green3", lwd=3)
points(dat$date, dat$SST15, type="l", col="blue", lwd=3)
points(dat$date, dat$SST16, type="l", col="steelblue1", lwd=3)
points(dat$date, dat$SST17, type="l", col="mediumpurple", lwd=3)
abline(h=30.2)
#axis(1,at=dat$date,tick=F,labels=format(as.Date(dat$date), "%b"))
#plot DHW for each year under SST, extend y axis to leave room for DHW
par(new=T)
plot(dat$date,dat[,7],type="l",lty=5, col="blue", lwd=3, xaxt='n',xlab='',yaxt='n',ylab='',ylim=c(0,20))
points(dat$date,dat[,15],type="l",lty=5, col="red", lwd=3)
points(dat$date,dat[,19],type="l",lty=5, col="orange", lwd=3)
points(dat$date,dat[,23],type="l",lty=5, col="green3", lwd=3)
points(dat$date,dat[,11],type="l",lty=5, col="steelblue1", lwd=3)
points(dat$date,dat[,27],type="l",lty=5, col="mediumpurple", lwd=3)
axis(side=4, cex.axis=1.5)
mtext("DHW (°C week)",cex=1.5,side=4,line=3)
legend(c(as.POSIXct("2018-12-26 EST"),5),cex=1.5,c("2010","2011","2012","2015","2016","2017"),lty=1,lwd=4,col=c("red","orange","green3","blue","steelblue1","mediumpurple"),bty="n")
dev.off()
#median box plot of historical DHW
pdf("2000-17_OfuDHW-medianboxplot.pdf",8,8)
ggplot(noaa, aes(x = year, y = DHW, group=year)) +
geom_boxplot(colour = "black", width = 0.5) +
labs(x = "Year",
y = "DHW ") +
## ggtitle("Main title") +
theme_classic() + theme(panel.grid.major.y = element_line( size=.1, color="gray"))
dev.off()
##frequency plot of daily temp ranges
pdf("OfuTempRange.pdf",5,5)
ggplot(temp)+geom_freqpoly(aes(x=range,color=site,linetype=site),size=1)+theme_classic()+xlab("Daily Temperature Range (°C)")+ylab("Frequency of Occurence (%)")+scale_color_manual(guide=FALSE,values=c("red","gold","blue"))
dev.off()
#box plot of median
plot(noaa$DHW,data=noaa)
library(ggplot2)
letters=c("a","bcd","e","f","ab","cde","ab","de","a","abc","de","a","ab","abcd","cde","g","f","h")
pdf("2000-17_OfuDHW-medianboxplot.pdf",8,8)
ggplot(noaa, aes(x = year, y = DHW, group=year)) +
geom_boxplot(colour = "black", width = 0.5) +
labs(x = "Year",
y = "DHW ") +
## ggtitle("Main title") +
theme_classic() + theme(panel.grid.major.y = element_line( size=.1, color="gray"))
dev.off()
#boxplot with the mean instead median
pdf("2000-17_OfuDHW.pdf",8,8)
ggplot(noaa, aes(year)) +
geom_boxplot(aes(ymin = min, lower = Q1, middle=mean, upper=Q3,ymax=max),stat="identity") +
xlab("Year") + ylab("Degree Heating Weeks") +
theme_classic() + #title("Mean Degree Heating Weeks")
theme( # remove the vertical grid lines
panel.grid.major.x = element_blank() ,
# explicitly set the horizontal lines (or they will disappear too)
panel.grid.major.y = element_line( size=.1, color="gray"))
dev.off()
|
x <- c(1,2,3,4,5)
x
xy <- rnorm(30)
xy
xy
mean(x)
mean(xy)
sort(xy) | /1.R | no_license | whddn5464/R | R | false | false | 68 | r |
x <- c(1,2,3,4,5)
x
xy <- rnorm(30)
xy
xy
mean(x)
mean(xy)
sort(xy) |
library(readr)
plastic <- read.csv('D:/WORK_RSTUDIO/FORECASTING/PlasticSales.csv')
View(plastic)
plot(plastic$Month,plastic$Sales, type = 'b')
#ggplot
library(ggplot2)
ggplot(data = plastic,aes(x =plastic$Month,y =plastic$Sales )) +
geom_point(color='blue') +
geom_line(color='red')
p <- data.frame(outer(rep(month.abb,length=60), month.abb, '==') + 0 )
colnames(p)<-month.abb
View(p)
p1 <- cbind(plastic,p)
p1['t'] <- c(1:60)
p1['log_sal'] <- log(p1['Sales'])
p1['t_saq'] <- p1['t']*p1['t']
train <- p1[1:45,]
test <- p1[46:60,]
########################### LINEAR MODEL #############################
lm <- lm(Sales~t,data = train)
summary(lm)
pred_lm <- data.frame(predict(lm,interval = 'predict',newdata = test))
rmse_lm <- sqrt(mean((test$Sales-pred_lm$fit)^2,na.rm=T))
rmse_lm
######################### Exponential #################################
ex <- lm(log_sal~t,data=train)
summary(ex)
pred_ex <- data.frame(predict(ex,interval = 'predict',newdata = test))
rmse_ex <- sqrt(mean((test$Sales-exp(pred_ex$fit))^2,na.rm = T))
rmse_ex
######################### Quadratic ####################################
qd <- lm(Sales~t+t_saq,data=train)
summary(qd)
pred_qd <- data.frame(predict(qd,interval = 'predict',newdata = test))
rmse_qd <- sqrt(mean((test$Sales-pred_qd$fit)^2,na.rm = T))
rmse_qd
######################### Additive Seasonality #########################
asm <- lm(Sales~Jan+Feb+Mar+Apr+May+Jun+Jul+Aug+Sep+Oct+Nov,data=train)
summary(asm)
pred_asm <- data.frame(predict(asm,interval = 'predict',newdata = test))
rmse_asm <- sqrt(mean((test$Sales-pred_asm$fit)^2,na.rm=T))
rmse_asm
######################## Additive Seasonality with Quadratic #################
asqm <- lm(Sales~t+t_saq+Jan+Feb+Mar+Apr+May+Jun+Jul+Aug+Sep+Oct+Nov,data=train)
summary(asqm)
pred_asqm <- data.frame(predict(asqm,interval = 'predict',newdata = test))
rmse_asqm <- sqrt(mean((test$Sales-pred_asqm$fit)^2,na.rm = T))
rmse_asqm
######################## Multiplicative Seasonality #########################
msm <- lm(log_sal~Jan+Feb+Mar+Apr+May+Jun+Jul+Aug+Sep+Oct+Nov,data=train)
summary(msm)
pred_msm <- data.frame(predict(msm,interval = 'predict',newdata = test))
rmse_msm <- sqrt(mean((test$Sales-exp(pred_msm$fit))^2,na.rm = T))
rmse_msm
######################## Multiplicative Additive Seasonality ##########################
masm <- lm(log_sal~t+Jan+Feb+Mar+Apr+May+Jun+Jul+Aug+Sep+Oct+Nov,data=train)
summary(masm)
pred_masm <- data.frame(predict(masm,interval = 'predict',newdata = test))
rmse_masm <- sqrt(mean((test$Sales-exp(pred_masm$fit))^2,na.rm = T))
rmse_masm
# Preparing table on model and it's RMSE values
table_rmse<-data.frame(c("rmse_lm","rmse_ex","rmse_qd","rmse_asm","rmse_asqm","rmse_msm","rmse_masm"),c(rmse_lm,rmse_ex,rmse_qd,rmse_asm,rmse_asqm,rmse_msm,rmse_masm))
colnames(table_rmse)<-c("model","RMSE")
View(table_rmse)
# Multiplicative Additive Seasonality has least RMSE
write.csv(p1,file="p1.csv",col.names = F,row.names = F)
####################### Predicting new data #############################
setwd('D:/R PRATICE')
test_data <- read.csv('p1.csv')
pred_new <- predict(masm,interval = 'predict',newdata = test_data)
pred_new
| /PlasticSales_modelbased.R | no_license | jayasimha338/Data-Science-2 | R | false | false | 3,255 | r | library(readr)
plastic <- read.csv('D:/WORK_RSTUDIO/FORECASTING/PlasticSales.csv')
View(plastic)
plot(plastic$Month,plastic$Sales, type = 'b')
#ggplot
library(ggplot2)
ggplot(data = plastic,aes(x =plastic$Month,y =plastic$Sales )) +
geom_point(color='blue') +
geom_line(color='red')
p <- data.frame(outer(rep(month.abb,length=60), month.abb, '==') + 0 )
colnames(p)<-month.abb
View(p)
p1 <- cbind(plastic,p)
p1['t'] <- c(1:60)
p1['log_sal'] <- log(p1['Sales'])
p1['t_saq'] <- p1['t']*p1['t']
train <- p1[1:45,]
test <- p1[46:60,]
########################### LINEAR MODEL #############################
lm <- lm(Sales~t,data = train)
summary(lm)
pred_lm <- data.frame(predict(lm,interval = 'predict',newdata = test))
rmse_lm <- sqrt(mean((test$Sales-pred_lm$fit)^2,na.rm=T))
rmse_lm
######################### Exponential #################################
ex <- lm(log_sal~t,data=train)
summary(ex)
pred_ex <- data.frame(predict(ex,interval = 'predict',newdata = test))
rmse_ex <- sqrt(mean((test$Sales-exp(pred_ex$fit))^2,na.rm = T))
rmse_ex
######################### Quadratic ####################################
qd <- lm(Sales~t+t_saq,data=train)
summary(qd)
pred_qd <- data.frame(predict(qd,interval = 'predict',newdata = test))
rmse_qd <- sqrt(mean((test$Sales-pred_qd$fit)^2,na.rm = T))
rmse_qd
######################### Additive Seasonality #########################
asm <- lm(Sales~Jan+Feb+Mar+Apr+May+Jun+Jul+Aug+Sep+Oct+Nov,data=train)
summary(asm)
pred_asm <- data.frame(predict(asm,interval = 'predict',newdata = test))
rmse_asm <- sqrt(mean((test$Sales-pred_asm$fit)^2,na.rm=T))
rmse_asm
######################## Additive Seasonality with Quadratic #################
asqm <- lm(Sales~t+t_saq+Jan+Feb+Mar+Apr+May+Jun+Jul+Aug+Sep+Oct+Nov,data=train)
summary(asqm)
pred_asqm <- data.frame(predict(asqm,interval = 'predict',newdata = test))
rmse_asqm <- sqrt(mean((test$Sales-pred_asqm$fit)^2,na.rm = T))
rmse_asqm
######################## Multiplicative Seasonality #########################
msm <- lm(log_sal~Jan+Feb+Mar+Apr+May+Jun+Jul+Aug+Sep+Oct+Nov,data=train)
summary(msm)
pred_msm <- data.frame(predict(msm,interval = 'predict',newdata = test))
rmse_msm <- sqrt(mean((test$Sales-exp(pred_msm$fit))^2,na.rm = T))
rmse_msm
######################## Multiplicative Additive Seasonality ##########################
masm <- lm(log_sal~t+Jan+Feb+Mar+Apr+May+Jun+Jul+Aug+Sep+Oct+Nov,data=train)
summary(masm)
pred_masm <- data.frame(predict(masm,interval = 'predict',newdata = test))
rmse_masm <- sqrt(mean((test$Sales-exp(pred_masm$fit))^2,na.rm = T))
rmse_masm
# Preparing table on model and it's RMSE values
table_rmse<-data.frame(c("rmse_lm","rmse_ex","rmse_qd","rmse_asm","rmse_asqm","rmse_msm","rmse_masm"),c(rmse_lm,rmse_ex,rmse_qd,rmse_asm,rmse_asqm,rmse_msm,rmse_masm))
colnames(table_rmse)<-c("model","RMSE")
View(table_rmse)
# Multiplicative Additive Seasonality has least RMSE
write.csv(p1,file="p1.csv",col.names = F,row.names = F)
####################### Predicting new data #############################
setwd('D:/R PRATICE')
test_data <- read.csv('p1.csv')
pred_new <- predict(masm,interval = 'predict',newdata = test_data)
pred_new
|
# Generated by using Rcpp::compileAttributes() -> do not edit by hand
# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
test_loss_cpp <- function(x, y, w, c0, lambda) {
.Call(`_riskslimr_cplex_test_loss_cpp`, x, y, w, c0, lambda)
}
test_loss_grad_cpp <- function(x, y, w, c0, lambda) {
.Call(`_riskslimr_cplex_test_loss_grad_cpp`, x, y, w, c0, lambda)
}
lcpa_cpp <- function(x, y, weights, logfile, R_max = 3L, time_limit = 60L) {
.Call(`_riskslimr_cplex_lcpa_cpp`, x, y, weights, logfile, R_max, time_limit)
}
| /R/RcppExports.R | no_license | zamorarr/riskslimr.cplex | R | false | false | 533 | r | # Generated by using Rcpp::compileAttributes() -> do not edit by hand
# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
test_loss_cpp <- function(x, y, w, c0, lambda) {
.Call(`_riskslimr_cplex_test_loss_cpp`, x, y, w, c0, lambda)
}
test_loss_grad_cpp <- function(x, y, w, c0, lambda) {
.Call(`_riskslimr_cplex_test_loss_grad_cpp`, x, y, w, c0, lambda)
}
lcpa_cpp <- function(x, y, weights, logfile, R_max = 3L, time_limit = 60L) {
.Call(`_riskslimr_cplex_lcpa_cpp`, x, y, weights, logfile, R_max, time_limit)
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/dst_correct_url.R
\name{dst_correct_url}
\alias{dst_correct_url}
\title{Corrects url encoding for Danish letters.}
\usage{
dst_correct_url(url)
}
\arguments{
\item{url}{A build url.}
}
\description{
Corrects url encoding for Danish letters.
}
| /man/dst_correct_url.Rd | no_license | rOpenGov/dkstat | R | false | true | 322 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/dst_correct_url.R
\name{dst_correct_url}
\alias{dst_correct_url}
\title{Corrects url encoding for Danish letters.}
\usage{
dst_correct_url(url)
}
\arguments{
\item{url}{A build url.}
}
\description{
Corrects url encoding for Danish letters.
}
|
#' Grafico de residuales de un modelo LM, LMM, GLM, GLMM, GAM, etc
#'
#' Muestra el ajuste del modelo LM, GLM, GLMM, GAM, etc. Esta función crea residuos escalados
#' mediante la simulación del modelo ajustado, 250 simulaciones por default. Los residuos pueden ser extraídos con residuals.DHARMa. Ver
#' testResiduals para una visión general de las pruebas de residuos, plot.DHARMa para una visión general de
#' los gráficos disponibles. Esta función fue creada para explorar el ajuste, normalidad y homogeneidad de
#' varianzas entre los grupos.
#' @param Modelo Un modelo LM, GLM, GLMM, GAM.
#' @param nsim Número de simulaciones. Cuanto menor sea el número, mayor será el error estocástico en los residuales.
#' Además, para n muy pequeño, los artefactos de discretización pueden influir en las pruebas. Por defecto
#' es 250, que es un valor relativamente seguro. Puede considerar aumentar a 1000 para estabilizar
#' los valores simulados.
#'
#' @return Grafica los residuales de un modelo.
#' @export
#'
#' @references
#' \itemize{
#' \item Ali MM, Sharma SC (1996) Robustness to nonnormality of regression F-tests. J Econom71, 175–205.
#'
#' \item Lumley T, Diehr P, Emerson S, Chen L (2002) The importance of the normality assumption in
#' large public health data sets. Annu Rev Public Health23, 151–169.
#' }
#'
#' @examples
#' data(warpbreaks)
#' modelo <- glm(breaks ~ wool + tension, family= poisson("log"), data= warpbreaks)
#' resid_DHARMa(modelo)
#'
#' ### tambien se puede usar en GLMMs:
#' datos <- datasets::ChickWeight
#' library(lme4)
#' modelo <- glmer(weight ~ Diet +(1|Chick), family=gaussian("log"), data = datos)
#' resid_DHARMa2(modelo)
#' @encoding UTF-8
#' @importFrom DHARMa simulateResiduals
resid_DHARMa <- function(Modelo, nsim=NULL){
if(is.null(nsim) ){
options(encoding = "UTF-8")
insight::print_color("Si Kolmogorov-Smirnov test (KS test) p < 0.05, entonces no hay normalidad en los residuales. Sin embargo, esta prueba es muy sensible al tama\u00f1o de muestra, con tama\u00f1o de muestra grande el valor de p tiene a < 0.05, pero la distribuci\u00f3n se aproxima mucho a la normal. Se recomienda ser un poco flexible con esta prueba al momento de examinar los residuales (examinar visualmente). Con tama\u00f1os de muestra grandes mayores a 500 el Teorema del Limite Central garantiza que los coeficientes de regresi\u00f3n se distribuyen normalmente en promedio (Ali & Sharma, 1996, Lumley et al., 2002).", "green")
insight::print_color("Outlier test: p < 0.05, no hay outliers. En caso de haber outliers, usar la funci\u00f3n outliers.DHARMa para saber cu\u00e1les son los datos influyentes.", "green")
insight::print_color("Dispersion test: p < 0.05, Indica problemas de sub/sobredispersi\u00f3n. En caso de haber problemas se recomienda ajustar el par\u00e1metro dispformula, solo para la paqueter\u00eda glmmTMB.", "green")
insight::print_color("Gr\u00e1fico de la derecha muestra la distribuci\u00f3n esperada de los residuales, mediante simulaciones. Esto es \u00fatil cuando no sabemos cu\u00e1l es la distribuci\u00f3n nula de los residuales. El grafico de la derecha muestra los residuales contra los valores esperados (ajustados). Estas l\u00edneas pueden no ajustarse debido a un tama\u00f1o de muestra reducido.", "green")
insight::print_color("Recuerda citar el paquete DHARMa. Usa citation('DHARMa') para ver como citar este paquete.", "red")
res.mod <-DHARMa::simulateResiduals(Modelo,n = 250)
return(plot(res.mod, rank = T))
} else if(is.numeric(nsim)){
options(encoding = "UTF-8")
n.sim<- nsim
insight::print_color("Si Kolmogorov-Smirnov test (KS test) p < 0.05, entonces no hay normalidad en los residuales. Sin embargo, esta prueba es muy sensible al tama\u00f1o de muestra, con tama\u00f1o de muestra grande el valor de p tiene a < 0.05, pero la distribuci\u00f3n se aproxima mucho a la normal. Se recomienda ser un poco flexible con esta prueba al momento de examinar los residuales (examinar visualmente). Con tama\u00f1os de muestra grandes mayores a 500 el Teorema del Limite Central garantiza que los coeficientes de regresi\u00f3n se distribuyen normalmente en promedio (Ali & Sharma, 1996, Lumley et al., 2002).", "green")
insight::print_color("Outlier test: p < 0.05, no hay outliers. En caso de haber outliers, usar la funci\u00f3n outliers.DHARMa para saber cu\u00e1les son los datos influyentes.", "green")
insight::print_color("Dispersion test: p < 0.05, Indica problemas de sub/sobredispersi\u00f3n. En caso de haber problemas se recomienda ajustar el par\u00e1metro dispformula, solo para la paqueter\u00eda glmmTMB.", "green")
insight::print_color("Gr\u00e1fico de la derecha muestra la distribuci\u00f3n esperada de los residuales, mediante simulaciones. Esto es \u00fatil cuando no sabemos cu\u00e1l es la distribuci\u00f3n nula de los residuales. El grafico de la derecha muestra los residuales contra los valores esperados (ajustados). Estas l\u00edneas pueden no ajustarse debido a un tama\u00f1o de muestra reducido.", "green")
insight::print_color("Recuerda citar el paquete DHARMa. Usa citation('DHARMa') para ver como citar este paquete.", "red")
base::message(c(paste("Se usaron ", nsim, "simulaciones.")))
res.mod <-DHARMa::simulateResiduals(Modelo,n = n.sim)
return(plot(res.mod, rank = T))
}
}
| /R/resid_DHARMa.R | permissive | mariosandovalmx/tlamatini | R | false | false | 5,401 | r | #' Grafico de residuales de un modelo LM, LMM, GLM, GLMM, GAM, etc
#'
#' Muestra el ajuste del modelo LM, GLM, GLMM, GAM, etc. Esta función crea residuos escalados
#' mediante la simulación del modelo ajustado, 250 simulaciones por default. Los residuos pueden ser extraídos con residuals.DHARMa. Ver
#' testResiduals para una visión general de las pruebas de residuos, plot.DHARMa para una visión general de
#' los gráficos disponibles. Esta función fue creada para explorar el ajuste, normalidad y homogeneidad de
#' varianzas entre los grupos.
#' @param Modelo Un modelo LM, GLM, GLMM, GAM.
#' @param nsim Número de simulaciones. Cuanto menor sea el número, mayor será el error estocástico en los residuales.
#' Además, para n muy pequeño, los artefactos de discretización pueden influir en las pruebas. Por defecto
#' es 250, que es un valor relativamente seguro. Puede considerar aumentar a 1000 para estabilizar
#' los valores simulados.
#'
#' @return Grafica los residuales de un modelo.
#' @export
#'
#' @references
#' \itemize{
#' \item Ali MM, Sharma SC (1996) Robustness to nonnormality of regression F-tests. J Econom71, 175–205.
#'
#' \item Lumley T, Diehr P, Emerson S, Chen L (2002) The importance of the normality assumption in
#' large public health data sets. Annu Rev Public Health23, 151–169.
#' }
#'
#' @examples
#' data(warpbreaks)
#' modelo <- glm(breaks ~ wool + tension, family= poisson("log"), data= warpbreaks)
#' resid_DHARMa(modelo)
#'
#' ### tambien se puede usar en GLMMs:
#' datos <- datasets::ChickWeight
#' library(lme4)
#' modelo <- glmer(weight ~ Diet +(1|Chick), family=gaussian("log"), data = datos)
#' resid_DHARMa2(modelo)
#' @encoding UTF-8
#' @importFrom DHARMa simulateResiduals
resid_DHARMa <- function(Modelo, nsim=NULL){
if(is.null(nsim) ){
options(encoding = "UTF-8")
insight::print_color("Si Kolmogorov-Smirnov test (KS test) p < 0.05, entonces no hay normalidad en los residuales. Sin embargo, esta prueba es muy sensible al tama\u00f1o de muestra, con tama\u00f1o de muestra grande el valor de p tiene a < 0.05, pero la distribuci\u00f3n se aproxima mucho a la normal. Se recomienda ser un poco flexible con esta prueba al momento de examinar los residuales (examinar visualmente). Con tama\u00f1os de muestra grandes mayores a 500 el Teorema del Limite Central garantiza que los coeficientes de regresi\u00f3n se distribuyen normalmente en promedio (Ali & Sharma, 1996, Lumley et al., 2002).", "green")
insight::print_color("Outlier test: p < 0.05, no hay outliers. En caso de haber outliers, usar la funci\u00f3n outliers.DHARMa para saber cu\u00e1les son los datos influyentes.", "green")
insight::print_color("Dispersion test: p < 0.05, Indica problemas de sub/sobredispersi\u00f3n. En caso de haber problemas se recomienda ajustar el par\u00e1metro dispformula, solo para la paqueter\u00eda glmmTMB.", "green")
insight::print_color("Gr\u00e1fico de la derecha muestra la distribuci\u00f3n esperada de los residuales, mediante simulaciones. Esto es \u00fatil cuando no sabemos cu\u00e1l es la distribuci\u00f3n nula de los residuales. El grafico de la derecha muestra los residuales contra los valores esperados (ajustados). Estas l\u00edneas pueden no ajustarse debido a un tama\u00f1o de muestra reducido.", "green")
insight::print_color("Recuerda citar el paquete DHARMa. Usa citation('DHARMa') para ver como citar este paquete.", "red")
res.mod <-DHARMa::simulateResiduals(Modelo,n = 250)
return(plot(res.mod, rank = T))
} else if(is.numeric(nsim)){
options(encoding = "UTF-8")
n.sim<- nsim
insight::print_color("Si Kolmogorov-Smirnov test (KS test) p < 0.05, entonces no hay normalidad en los residuales. Sin embargo, esta prueba es muy sensible al tama\u00f1o de muestra, con tama\u00f1o de muestra grande el valor de p tiene a < 0.05, pero la distribuci\u00f3n se aproxima mucho a la normal. Se recomienda ser un poco flexible con esta prueba al momento de examinar los residuales (examinar visualmente). Con tama\u00f1os de muestra grandes mayores a 500 el Teorema del Limite Central garantiza que los coeficientes de regresi\u00f3n se distribuyen normalmente en promedio (Ali & Sharma, 1996, Lumley et al., 2002).", "green")
insight::print_color("Outlier test: p < 0.05, no hay outliers. En caso de haber outliers, usar la funci\u00f3n outliers.DHARMa para saber cu\u00e1les son los datos influyentes.", "green")
insight::print_color("Dispersion test: p < 0.05, Indica problemas de sub/sobredispersi\u00f3n. En caso de haber problemas se recomienda ajustar el par\u00e1metro dispformula, solo para la paqueter\u00eda glmmTMB.", "green")
insight::print_color("Gr\u00e1fico de la derecha muestra la distribuci\u00f3n esperada de los residuales, mediante simulaciones. Esto es \u00fatil cuando no sabemos cu\u00e1l es la distribuci\u00f3n nula de los residuales. El grafico de la derecha muestra los residuales contra los valores esperados (ajustados). Estas l\u00edneas pueden no ajustarse debido a un tama\u00f1o de muestra reducido.", "green")
insight::print_color("Recuerda citar el paquete DHARMa. Usa citation('DHARMa') para ver como citar este paquete.", "red")
base::message(c(paste("Se usaron ", nsim, "simulaciones.")))
res.mod <-DHARMa::simulateResiduals(Modelo,n = n.sim)
return(plot(res.mod, rank = T))
}
}
|
# 데이터 불러오기
HR = read.csv('D:\\R-project\\Must Learning with R\\datasets\\HR_comma_sep.csv')
# /로 경로를 구분하거나 \\로 경로를 구분할 수 있다.
# 데이터 윗부분 띄우기
head(HR, 5)
# 데이터의 strings 파악
str(HR)
# 데이터를 요약해서 보기
summary(HR)
# 데이터 strings 변경
summary(HR$left)
HR$Work_accident=as.factor(HR$Work_accident)
HR$left=as.factor(HR$left)
HR$promotion_last_5years=as.factor(HR$promotion_last_5years)
summary(HR$left)
HR$left
# ifelse() 조건에 맞는 값 할당하기
# ifelse(조건, TRUE, FALSE)
HR$satisfaction_level_group_1 = ifelse(HR$satisfaction_level > 0.5, 'High', 'Low')
HR$satisfaction_level_group_1 = as.factor(HR$satisfaction_level_group_1)
summary(HR$satisfaction_level_group_1)
# 조건이 추가가 되었을 경우에는 ifeles문 안에 ifelse문을 쓰면 된다.
HR$satisfaction_level_group_2 = ifelse(HR$satisfaction_level > 0.8,'High',
ifelse(HR$satisfaction_level > 0.5, 'Mid', 'Low'))
HR$satisfaction_level_group_2 = as.factor(HR$satisfaction_level_group_2)
summary(HR$satisfaction_level_group_2)
# 조건에 맞는 데이터 추출 subset
# subset(데이터, 추출 조건)
HR_High = subset(HR, salary=='high')
summary(HR_High$salary)
HR_High_IT = subset(HR, salary == 'high' & last_evaluation > 0.5)
print(xtabs(~ HR_High_IT$last_evaluation + HR_High_IT$salary))
# 집계된 데이터 만들기
# 패키지 설치
install.packages("plyr") # 엑셀의 피벗테이블 같은 용도
library(plyr)
# ddply(데이터, 집계기준, summarise, 요약 변수)
SS = ddply(HR, # SS라는 데이터 셋을 생성
c("sales", "salary"), summarise,
M_SF = mean(satisfaction_level1),
COUNT = length(sales),
M_WH = round(mean(average)))
install.packages('tidyverse')
| /R/기초/step2.R | no_license | sanha9999/Data_analysis | R | false | false | 1,904 | r | # 데이터 불러오기
HR = read.csv('D:\\R-project\\Must Learning with R\\datasets\\HR_comma_sep.csv')
# /로 경로를 구분하거나 \\로 경로를 구분할 수 있다.
# 데이터 윗부분 띄우기
head(HR, 5)
# 데이터의 strings 파악
str(HR)
# 데이터를 요약해서 보기
summary(HR)
# 데이터 strings 변경
summary(HR$left)
HR$Work_accident=as.factor(HR$Work_accident)
HR$left=as.factor(HR$left)
HR$promotion_last_5years=as.factor(HR$promotion_last_5years)
summary(HR$left)
HR$left
# ifelse() 조건에 맞는 값 할당하기
# ifelse(조건, TRUE, FALSE)
HR$satisfaction_level_group_1 = ifelse(HR$satisfaction_level > 0.5, 'High', 'Low')
HR$satisfaction_level_group_1 = as.factor(HR$satisfaction_level_group_1)
summary(HR$satisfaction_level_group_1)
# 조건이 추가가 되었을 경우에는 ifeles문 안에 ifelse문을 쓰면 된다.
HR$satisfaction_level_group_2 = ifelse(HR$satisfaction_level > 0.8,'High',
ifelse(HR$satisfaction_level > 0.5, 'Mid', 'Low'))
HR$satisfaction_level_group_2 = as.factor(HR$satisfaction_level_group_2)
summary(HR$satisfaction_level_group_2)
# 조건에 맞는 데이터 추출 subset
# subset(데이터, 추출 조건)
HR_High = subset(HR, salary=='high')
summary(HR_High$salary)
HR_High_IT = subset(HR, salary == 'high' & last_evaluation > 0.5)
print(xtabs(~ HR_High_IT$last_evaluation + HR_High_IT$salary))
# 집계된 데이터 만들기
# 패키지 설치
install.packages("plyr") # 엑셀의 피벗테이블 같은 용도
library(plyr)
# ddply(데이터, 집계기준, summarise, 요약 변수)
SS = ddply(HR, # SS라는 데이터 셋을 생성
c("sales", "salary"), summarise,
M_SF = mean(satisfaction_level1),
COUNT = length(sales),
M_WH = round(mean(average)))
install.packages('tidyverse')
|
\name{CPSPPOTevents}
\alias{CPSPPOTevents}
\title{Identifying the occurrence points of the indicator processes in the CPSP from a POT approach}
\description{This function calculates the occurrence times and other characteristics (length, maximum and mean intensity) of the extreme events
of the three indicator processes of a bivariate Common Poisson Shock Process (CPSP) obtained from a
Peak Over Threshold (POT) approach.}
\usage{CPSPPOTevents(N1,N2,thres1,thres2, date=NULL, dplot=T, pmfrow=c(2,1),
axispoints=NULL,...)}
\arguments{
\item{N1}{Numeric vector. Series \eqn{(x_i)} whose threshold exceedances define the first CPSP marginal process.}
\item{N2}{Numeric vector. Series \eqn{(y_i)} whose threshold exceedances define the second CPSP marginal process.}
\item{thres1}{Numeric value. Threshold used to define the extreme events in \eqn{(x_i)}.}
\item{thres2}{Numeric value. Threshold used to define the extreme events in \eqn{(y_i)}.}
\item{date}{Optional. A vector or matrix indicating the date of each observation.}
\item{dplot}{Optional. A logical flag. If it is TRUE, the marginal and indicator processes are plotted.}
\item{pmfrow}{Optional. A vector of the form (nr, nc) to be supplied as value of the argument \code{mfrow} in \code{\link{par}}. }
\item{axispoints}{Optional. Numeric vector with the points in the time index where axis ticks and labels (from the first column in \code{date})
have to be drawn.}
\item{...}{Further arguments to be passed to the function \code{\link{plot}}.}
}
\details{
A CPSP \eqn{N} can be decomposed into three independent indicator processes: \eqn{N_{(1)}}, \eqn{N_{(2)}}
and \eqn{N_{(12)}}, the processes of the points occurring
only in the first marginal process, only in the second and in both of them (simultaneous points).
In the CPSP resulting from applying a POT approach, the events in \eqn{N_{(1)}}
are a run of consecutive observations where \eqn{x_i} exceeds its extreme threshold but \eqn{y_i} does not exceed
its extreme threshold. An extreme event in \eqn{N_{(2)}} is defined analogously. A simultaneous event, or event
in \eqn{N_{(12)}}, is a run where both series exceed their thresholds.
For the events defined in each indicator process, three magnitudes (length, maximum intensity and mean intensity)
are calculated together with the initial point and the point of maximum excess of each event. In
\eqn{N_{(12)}}, the maximum and the mean intensity in both series \eqn{(x_i)} and
\eqn{(y_i)} are calculated.
The occurrence point of each event is the time in the run where the maximum of the sum of the excesses of
\eqn{(x_i)} and \eqn{(y_i)} over their threholds occurs; if an observation does not exceed
its corresponding threshold, that excess is 0. According to this definition, the occurrence point in
\eqn{N_{(1)}} is the point with maximum intensity in \eqn{(x_i)} within the run.
The vectors \code{inddat1}, \code{inddat2} and \code{inddat12}, elements of the output list,
mark the observations that should be used in the estimation of each indicator process. The
observations in an extreme event which are not the occurrence point are marked with 0
and treated as non observed in the estimation process. The rest are marked with 1 and
must be included in the likelihood function. See function \code{fitPP.fun} in package NHPoisson
for more details on the use of these indexes in the estiamtion of a point process.
The points in the marginal \eqn{N_{1}}, \eqn{N_{2}} and indicator
\eqn{N_{(1)}}, \eqn{N_{(2)}} and \eqn{N_{(12)}} processes can be optionally plotted.
If \code{date} is NULL, default axis are used. Otherwise, the values in \code{axispoints} are used
as the points in the time index where axis ticks and labels, from the first column in \code{date},
have to be drawn. If \code{axispoints} is NULL, a default grid of points is built using the
function \code{marca}.
}
\value{A list with components
\item{Im1}{Vector of mean excesses (over the threshold) of the extreme events in \eqn{N_{(1)}}.}
\item{Ix1}{Vector of maximum excesses (over the threshold) of the extreme events in \eqn{N_{(1)}}.}
\item{L1}{Vector of lengths of the extreme events in \eqn{N_{(1)}}.}
\item{Px1}{Vector of points of maximum excess of the extreme events in \eqn{N_{(1)}}.}
\item{Pi1}{Vector of initial points of the extreme events in \eqn{N_{(1)}}.}
\item{inddat1 }{Index of the observations to be used in the estimation process of \eqn{N_{(1)}}.}
\item{Im2}{Vector of mean excesses (over the threshold) of the extreme events in \eqn{N_{(2)}}.}
\item{IxY}{Vector of maximum excesses (over the threshold) of the extreme events in \eqn{N_{(2)}}.}
\item{L2}{Vector of lengths of the extreme events in \eqn{N_{(2)}}.}
\item{Px2}{Vector of points of maximum excess of the extreme events in \eqn{N_{(2)}}.}
\item{Pi2}{Vector of initial points of the extreme events in \eqn{N_{(2)}}.}
\item{inddat2 }{Index of the observations to be used in the estimation process of
\eqn{N_{(2)}}.}
\item{Im121}{Vector of mean excesses of the series \eqn{(x_i)} in \eqn{N_{(12)}}.}
\item{Ix121}{Vector of maximum excesses the series \eqn{(x_i)} in \eqn{N_{(12)}}.}
\item{Im122}{Vector of mean excesses of the series \eqn{(y_i)} in \eqn{N_{(12)}}.}
\item{Ix122}{Vector of maximum excesses the series \eqn{(y_i)} in \eqn{N_{(12)}}.}
\item{L12}{Vector of lengths of the extreme events in \eqn{N_{(12)}}.}
\item{Px12}{Vector of points of maximum excess of the extreme events in \eqn{N_{(12)}}.}
\item{Pi12}{Vector of initial points of the extreme events in \eqn{N_{(12)}}.}
\item{inddat12}{Index of the observations to be used in the estimation process of \eqn{N_{(12)}}.}
\item{N1}{Input argument.}
\item{N2}{Input argument.}
\item{thres1}{Input argument.}
\item{thres1}{Input argument.}
\item{date}{Input argument.}
}
\references{
Abaurrea, J. Asin, J. and Cebrian, A.C. (2015). A Bootstrap Test of Independence Between Three Temporal Nonhomogeneous Poisson Processes
and its Application to Heat Wave Modeling. \emph{Environmental and Ecological Statistics}, 22(1), 127-144.
}
\seealso{ \code{\link{CPSPpoints}}, \code{\link{PlotMCPSP}}, \code{\link{PlotICPSP}} }
\examples{
data(TxBHZ)
dateT<-cbind(TxBHZ$year,TxBHZ$month,TxBHZ$day) #year, month and day of the month
marca<- c(1:length(TxBHZ$TxH))[c(1,diff(dateT[,1]))==1] # points at first day of the year
BivEv<-CPSPPOTevents(N1=TxBHZ$TxH,N2=TxBHZ$TxZ,thres1=378,thres2=364, date=dateT,
axispoints=marca)
} | /man/CPSPPOTevents.Rd | no_license | cran/IndTestPP | R | false | false | 6,738 | rd | \name{CPSPPOTevents}
\alias{CPSPPOTevents}
\title{Identifying the occurrence points of the indicator processes in the CPSP from a POT approach}
\description{This function calculates the occurrence times and other characteristics (length, maximum and mean intensity) of the extreme events
of the three indicator processes of a bivariate Common Poisson Shock Process (CPSP) obtained from a
Peak Over Threshold (POT) approach.}
\usage{CPSPPOTevents(N1,N2,thres1,thres2, date=NULL, dplot=T, pmfrow=c(2,1),
axispoints=NULL,...)}
\arguments{
\item{N1}{Numeric vector. Series \eqn{(x_i)} whose threshold exceedances define the first CPSP marginal process.}
\item{N2}{Numeric vector. Series \eqn{(y_i)} whose threshold exceedances define the second CPSP marginal process.}
\item{thres1}{Numeric value. Threshold used to define the extreme events in \eqn{(x_i)}.}
\item{thres2}{Numeric value. Threshold used to define the extreme events in \eqn{(y_i)}.}
\item{date}{Optional. A vector or matrix indicating the date of each observation.}
\item{dplot}{Optional. A logical flag. If it is TRUE, the marginal and indicator processes are plotted.}
\item{pmfrow}{Optional. A vector of the form (nr, nc) to be supplied as value of the argument \code{mfrow} in \code{\link{par}}. }
\item{axispoints}{Optional. Numeric vector with the points in the time index where axis ticks and labels (from the first column in \code{date})
have to be drawn.}
\item{...}{Further arguments to be passed to the function \code{\link{plot}}.}
}
\details{
A CPSP \eqn{N} can be decomposed into three independent indicator processes: \eqn{N_{(1)}}, \eqn{N_{(2)}}
and \eqn{N_{(12)}}, the processes of the points occurring
only in the first marginal process, only in the second and in both of them (simultaneous points).
In the CPSP resulting from applying a POT approach, the events in \eqn{N_{(1)}}
are a run of consecutive observations where \eqn{x_i} exceeds its extreme threshold but \eqn{y_i} does not exceed
its extreme threshold. An extreme event in \eqn{N_{(2)}} is defined analogously. A simultaneous event, or event
in \eqn{N_{(12)}}, is a run where both series exceed their thresholds.
For the events defined in each indicator process, three magnitudes (length, maximum intensity and mean intensity)
are calculated together with the initial point and the point of maximum excess of each event. In
\eqn{N_{(12)}}, the maximum and the mean intensity in both series \eqn{(x_i)} and
\eqn{(y_i)} are calculated.
The occurrence point of each event is the time in the run where the maximum of the sum of the excesses of
\eqn{(x_i)} and \eqn{(y_i)} over their threholds occurs; if an observation does not exceed
its corresponding threshold, that excess is 0. According to this definition, the occurrence point in
\eqn{N_{(1)}} is the point with maximum intensity in \eqn{(x_i)} within the run.
The vectors \code{inddat1}, \code{inddat2} and \code{inddat12}, elements of the output list,
mark the observations that should be used in the estimation of each indicator process. The
observations in an extreme event which are not the occurrence point are marked with 0
and treated as non observed in the estimation process. The rest are marked with 1 and
must be included in the likelihood function. See function \code{fitPP.fun} in package NHPoisson
for more details on the use of these indexes in the estiamtion of a point process.
The points in the marginal \eqn{N_{1}}, \eqn{N_{2}} and indicator
\eqn{N_{(1)}}, \eqn{N_{(2)}} and \eqn{N_{(12)}} processes can be optionally plotted.
If \code{date} is NULL, default axis are used. Otherwise, the values in \code{axispoints} are used
as the points in the time index where axis ticks and labels, from the first column in \code{date},
have to be drawn. If \code{axispoints} is NULL, a default grid of points is built using the
function \code{marca}.
}
\value{A list with components
\item{Im1}{Vector of mean excesses (over the threshold) of the extreme events in \eqn{N_{(1)}}.}
\item{Ix1}{Vector of maximum excesses (over the threshold) of the extreme events in \eqn{N_{(1)}}.}
\item{L1}{Vector of lengths of the extreme events in \eqn{N_{(1)}}.}
\item{Px1}{Vector of points of maximum excess of the extreme events in \eqn{N_{(1)}}.}
\item{Pi1}{Vector of initial points of the extreme events in \eqn{N_{(1)}}.}
\item{inddat1 }{Index of the observations to be used in the estimation process of \eqn{N_{(1)}}.}
\item{Im2}{Vector of mean excesses (over the threshold) of the extreme events in \eqn{N_{(2)}}.}
\item{IxY}{Vector of maximum excesses (over the threshold) of the extreme events in \eqn{N_{(2)}}.}
\item{L2}{Vector of lengths of the extreme events in \eqn{N_{(2)}}.}
\item{Px2}{Vector of points of maximum excess of the extreme events in \eqn{N_{(2)}}.}
\item{Pi2}{Vector of initial points of the extreme events in \eqn{N_{(2)}}.}
\item{inddat2 }{Index of the observations to be used in the estimation process of
\eqn{N_{(2)}}.}
\item{Im121}{Vector of mean excesses of the series \eqn{(x_i)} in \eqn{N_{(12)}}.}
\item{Ix121}{Vector of maximum excesses the series \eqn{(x_i)} in \eqn{N_{(12)}}.}
\item{Im122}{Vector of mean excesses of the series \eqn{(y_i)} in \eqn{N_{(12)}}.}
\item{Ix122}{Vector of maximum excesses the series \eqn{(y_i)} in \eqn{N_{(12)}}.}
\item{L12}{Vector of lengths of the extreme events in \eqn{N_{(12)}}.}
\item{Px12}{Vector of points of maximum excess of the extreme events in \eqn{N_{(12)}}.}
\item{Pi12}{Vector of initial points of the extreme events in \eqn{N_{(12)}}.}
\item{inddat12}{Index of the observations to be used in the estimation process of \eqn{N_{(12)}}.}
\item{N1}{Input argument.}
\item{N2}{Input argument.}
\item{thres1}{Input argument.}
\item{thres1}{Input argument.}
\item{date}{Input argument.}
}
\references{
Abaurrea, J. Asin, J. and Cebrian, A.C. (2015). A Bootstrap Test of Independence Between Three Temporal Nonhomogeneous Poisson Processes
and its Application to Heat Wave Modeling. \emph{Environmental and Ecological Statistics}, 22(1), 127-144.
}
\seealso{ \code{\link{CPSPpoints}}, \code{\link{PlotMCPSP}}, \code{\link{PlotICPSP}} }
\examples{
data(TxBHZ)
dateT<-cbind(TxBHZ$year,TxBHZ$month,TxBHZ$day) #year, month and day of the month
marca<- c(1:length(TxBHZ$TxH))[c(1,diff(dateT[,1]))==1] # points at first day of the year
BivEv<-CPSPPOTevents(N1=TxBHZ$TxH,N2=TxBHZ$TxZ,thres1=378,thres2=364, date=dateT,
axispoints=marca)
} |
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/hmob_funcs.R
\name{calc.prop.remain}
\alias{calc.prop.remain}
\title{Proportion of individuals remaining for full epidemic generation}
\usage{
calc.prop.remain(d, gen.t, max.gen = NULL, sub.samp = NULL)
}
\arguments{
\item{d}{a three- or four-dimensional array containing route- or month-level trip duration counts produced by the \code{\link{mob.data.array}} function.
Note that \code{calc.prop.remain} assumes that the duration data array is NOT aggregated (e.g. \code{mob.data.array} argument \code{agg.int}=1)}
\item{gen.t}{the time interval in days used to define the epidemic generation}
\item{max.gen}{the maximum number of generations to evaluate proportion of individuals remaining}
\item{sub.samp}{scalar indicating the number of generations to subsample, if NULL (default), will use all observed generation times in the data (which will increase computation time for large numbers of locations)}
}
\value{
if \code{d} is a month-level duration data array, then a 4D array with values between 0 and 1 is returned. If \code{d} is a route-level duration data array,
then returns a 3D array is returned.
}
\description{
This function calculates the proportion of individuals that remain in a location for
all of epidemic generation \eqn{n}. The value is represented by the variable \eqn{p_jt}, which
is defined as the effective probability if individuals that stay for a full epidemic generation
when they travel to destination \eqn{j} at time \eqn{t}:\cr
\cr
\eqn{p_ij} = Pr(remaining for all of \eqn{n^th} epidemic generation | generation time \eqn{g})\cr
\cr
Because the Namibia mobility data spans 4 years there are many potential time intervals for which to calculate
the proportion of individuals remaining for full epidemic generation. The \code{sub.samp} argument randomly
selects X number of these generations to reduce computation time.
}
\examples{
# Duration data for the purpose of subsetting districts
load('./data/duration_data_arrays_1day_full.Rdata')
# Proportion travellers remaining for full epidemic generation based on subsample of 10, where the generation time is 14 days (measles)
p1 <- calc.prop.remain(d=y.route, gen.t=14, sub.samp=10)
p2 <- calc.prop.remain(d=y.month, gen.t=14, sub.samp=10)
# Get destination-level mean and variance
p1.mean <- apply(p1, 2, mean, na.rm=TRUE)
p1.var <- apply(p1, 2, var, na.rm=TRUE)
p2.mean <- apply(p2, 2, mean, na.rm=TRUE)
p2.var <- apply(p2, 2, var, na.rm=TRUE)
}
\seealso{
Other simulation:
\code{\link{calc.hpd}()},
\code{\link{calc.prop.inf}()},
\code{\link{calc.timing.magnitude}()},
\code{\link{calc.wait.time}()},
\code{\link{decay.func}()},
\code{\link{get.age.beta}()},
\code{\link{get.beta.params}()},
\code{\link{sim.TSIR.full}()},
\code{\link{sim.TSIR}()},
\code{\link{sim.combine.dual}()},
\code{\link{sim.combine}()},
\code{\link{sim.gravity.duration}()},
\code{\link{sim.gravity}()},
\code{\link{sim.lambda}()},
\code{\link{sim.pi}()},
\code{\link{sim.rho}()},
\code{\link{sim.tau}()}
}
\author{
John Giles
}
\concept{simulation}
| /man/calc.prop.remain.Rd | no_license | gilesjohnr/hmob | R | false | true | 3,105 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/hmob_funcs.R
\name{calc.prop.remain}
\alias{calc.prop.remain}
\title{Proportion of individuals remaining for full epidemic generation}
\usage{
calc.prop.remain(d, gen.t, max.gen = NULL, sub.samp = NULL)
}
\arguments{
\item{d}{a three- or four-dimensional array containing route- or month-level trip duration counts produced by the \code{\link{mob.data.array}} function.
Note that \code{calc.prop.remain} assumes that the duration data array is NOT aggregated (e.g. \code{mob.data.array} argument \code{agg.int}=1)}
\item{gen.t}{the time interval in days used to define the epidemic generation}
\item{max.gen}{the maximum number of generations to evaluate proportion of individuals remaining}
\item{sub.samp}{scalar indicating the number of generations to subsample, if NULL (default), will use all observed generation times in the data (which will increase computation time for large numbers of locations)}
}
\value{
if \code{d} is a month-level duration data array, then a 4D array with values between 0 and 1 is returned. If \code{d} is a route-level duration data array,
then returns a 3D array is returned.
}
\description{
This function calculates the proportion of individuals that remain in a location for
all of epidemic generation \eqn{n}. The value is represented by the variable \eqn{p_jt}, which
is defined as the effective probability if individuals that stay for a full epidemic generation
when they travel to destination \eqn{j} at time \eqn{t}:\cr
\cr
\eqn{p_ij} = Pr(remaining for all of \eqn{n^th} epidemic generation | generation time \eqn{g})\cr
\cr
Because the Namibia mobility data spans 4 years there are many potential time intervals for which to calculate
the proportion of individuals remaining for full epidemic generation. The \code{sub.samp} argument randomly
selects X number of these generations to reduce computation time.
}
\examples{
# Duration data for the purpose of subsetting districts
load('./data/duration_data_arrays_1day_full.Rdata')
# Proportion travellers remaining for full epidemic generation based on subsample of 10, where the generation time is 14 days (measles)
p1 <- calc.prop.remain(d=y.route, gen.t=14, sub.samp=10)
p2 <- calc.prop.remain(d=y.month, gen.t=14, sub.samp=10)
# Get destination-level mean and variance
p1.mean <- apply(p1, 2, mean, na.rm=TRUE)
p1.var <- apply(p1, 2, var, na.rm=TRUE)
p2.mean <- apply(p2, 2, mean, na.rm=TRUE)
p2.var <- apply(p2, 2, var, na.rm=TRUE)
}
\seealso{
Other simulation:
\code{\link{calc.hpd}()},
\code{\link{calc.prop.inf}()},
\code{\link{calc.timing.magnitude}()},
\code{\link{calc.wait.time}()},
\code{\link{decay.func}()},
\code{\link{get.age.beta}()},
\code{\link{get.beta.params}()},
\code{\link{sim.TSIR.full}()},
\code{\link{sim.TSIR}()},
\code{\link{sim.combine.dual}()},
\code{\link{sim.combine}()},
\code{\link{sim.gravity.duration}()},
\code{\link{sim.gravity}()},
\code{\link{sim.lambda}()},
\code{\link{sim.pi}()},
\code{\link{sim.rho}()},
\code{\link{sim.tau}()}
}
\author{
John Giles
}
\concept{simulation}
|
### Course Wrap-up and COmprehensive Assessment: Brexit ###
##PART 1:
#Import the brexit_polls polling data from the dslabs package and set options for the analysis:
library(tidyverse)
options(digits = 3)
library(dslabs)
data(brexit_polls)
#Define p = .481 as the actual percent voting "Remain" and d = 2p-1 = -.038 as the actual spread, with Remain defined
#as the positive outcome
p <- .481
d <- 2*p-1
#Q1: The final proportion of voters choosing to Remain was p = 0.481. Consider a poll with sample size 1500 voters...
#What is the expected total number of voters in the sample choosing Remain?
N <-1500
NX_hat <- N*p
#What is the standard error of the total number of voters in the sample choosing Remain
Nse_hat <- sqrt(N*p * (1-p))
#What is the expected value of X, the proportion of Remain voters?
X_hat <- p
#What is the standard error of X, the proportion of Remain voters?
se_hat <- sqrt(p*(1-p)/N)
#What is the expected value of d, the spread between the proportion of Remain voters and Leave voters?
d_hat <- 2*p -1
#What is the standard error of d, the spread between the proportion of Remain voters and Leave voters?
se_hatd <- 2*sqrt(p*(1-p)/N)
#Q2:Calculate X_hat for each poll in the brexit_polls dataset, the estimate of the proportion of voters choosing
#Remain (p = 0.481), given the observed spread. Use mutate to add a variable X_hat to the data
brexit_polls <- brexit_polls %>%
mutate(X_hat = (spread + 1)/2)
#What is the average of the observed spread?
mean(brexit_polls$spread)
#What is the standard deviation of the observed spreads?
sd(brexit_polls$spread)
#What is the average of X_hat, the estimates of the parameter p ?
mean(brexit_polls$X_hat)
#What is the standard deviation of X_hat?
sd(brexit_polls$X_hat)
#Q3: Confidence interval of a Brexit poll. Consider the first poll in brexit_polls, a YouGov pull run on the same
#day as the referendum
brexit_polls[1,]
#Use qnorm() to compute the 95%CI for X_hat
CI <- brexit_polls[1,] %>%
mutate(lower = X_hat - qnorm(.975)*sqrt(X_hat * (1-X_hat)/samplesize),
upper = X_hat + qnorm(.975)*sqrt(X_hat * (1-X_hat)/samplesize))
#Does the 95%CI predict a winner? Does it cover the true value of p observed during the referendum?
#Answer:The interval predicts a winner but does not cover the true value of p
##PART 2:
#Q4: Confidence intervals for polls in June: Create the data frame june_polls containing only Brexit polls ending
#June 2016, aka (enddate of "2016-06-01" and later). Calculate the CIs for all polls and determine how many
#cover the true value of d
june_polls <- brexit_polls %>%
filter(enddate >= "2016-06-01") %>%
mutate(se_x_hat = sqrt(X_hat * (1-X_hat)/samplesize),
se_spread = 2*se_x_hat,
lower = spread - qnorm(.975)*se_spread,
upper = spread + qnorm(.975)*se_spread,
hit = lower <= d & upper >= d)
#How many polls are in june_polls?
nrow(june_polls)
#What proportion of polls have a CI that covers the value of 0?
june_polls %>%
summarise(cover_zero = mean(lower <= 0 & upper >= 0))
#What porpotion of polls predict Remain (CI above 0)?
june_polls %>%
summarise(remain = mean(lower >= 0 & upper >= 0))
#What poprotion of polls have a CI covering the true value of d?
mean(june_polls$hit)
#Q5: Hit rate by pollster. Group and sumarise the june_polls object by pollster to find the proporiton of hits
#for each pollster and the number of polls per pollster. Use arrange() to sort by hit rate
june_polls %>%
group_by(pollster) %>%
summarise(proportion_hits = mean(hit), n = n()) %>%
arrange(proportion_hits)
#Which of the following are TRUE?
#Unbiased polls and pollsters will theoretically cover the correct value of the spread 50% of the time. (FALSE)
#Only 1 pollster had a 100% success rate in generating CIs that covered the correct value of the spread. (FALSE)
#The pollster w/the highest number of polls covered the correct value of the spread in their CI over
#60% of the time. (FALSE)
#All pollsters produced CIs covering the correct spread in at least 1 of their polls. (FALSE)
#The results are consistent with a large general bias that affects all pollsters. (TRUE)
#Q6:Boxplot of Brexit polls by poll type. Make a boxplot of the spread in june_polls by poll type.
june_polls %>%
ggplot(aes(poll_type, spread)) +
geom_boxplot()
#Which of the following are TRUE?
#Online polls tend to show support for Remain (spread > 0). (FALSE)
#Telephone polls tend to show support Remain (spread > 0). (TRUE)
#Telephone polls tend to show higher support for Remain than online polls (higher spread). (TRUE)
#Online polls have a larger interquartile range for the spread than telephone polls, indicating
#that they are more variable. (TRUE)
#Poll type introduces a bias that affects poll results. (TRUE)
#Q7: Combined spread across poll type. Calculate the confidence intervals of the spread combined across
#all polls in june_polls, grouping by poll type.Use the code below, which determines the total sample
#size per poll type; gives each spread estimate a weight based on the poll's sample size; and adds an
#estimate of p from the combined spread, to begin your analysis
combined_by_type <- june_polls %>%
group_by(poll_type) %>%
summarize(N = sum(samplesize),
spread = sum(spread*samplesize)/N,
p_hat = (spread + 1)/2)
combined_by_type <- combined_by_type %>%
mutate (se_spread = 2 * sqrt(p_hat * (1-p_hat)/N),
lower = spread - qnorm(.975)*se_spread,
upper = spread + qnorm(.975)*se_spread)
#What is the lower bound of the 95% confidence interval for online voters?
combined_by_type[1,6]
#What is the upper bound of the 95% confidence interval for online voters?
combined_by_type[1,7]
#Q8: Interpreting combined spread estimates across poll type. Interpret the CIs for the combined spreads for each
#poll type calculated in the previous problem. Which of the following are TRUE about the CIs of the combined
#spreads for different poll types?
#Neither set of combined polls makes a prediction about the outcome of the Brexit referendum (a prediction is
#possible if a confidence interval does not cover 0). (TRUE)
#The CI for online polls is larger than the confidence interval for telephone polls. (FALSE)
#The CI for telephone polls covers more positive values than the confidence interval for online polls. (TRUE)
#The CIs for different poll types do not overlap. (FALSE)
#Neither CI covers the true value d = -.038. (TRUE)
## PART 3:
#Q9: Chi-squared p-value. Define brexit_hit, with the code below, which computes the CI for all Brexit polls in 2016
#and then calculates whether the CI covers the actual value of the spread d = -.038
brexit_hit <- brexit_polls %>%
mutate(p_hat = (spread + 1)/2,
se_spread = 2*sqrt(p_hat*(1-p_hat)/samplesize),
spread_lower = spread - qnorm(.975)*se_spread,
spread_upper = spread + qnorm(.975)*se_spread,
hit = spread_lower < -0.038 & spread_upper > -0.038) %>%
select(poll_type, hit)
#Use brexit_hit to make a 2x2 table of poll type and hit status. Then use the chisq.test() function to perform a
#chi-squared test to determine whether the difference in hit rate is significant.
table <- brexit_hit %>%
group_by(poll_type, hit) %>%
summarise(n = n()) %>%
spread(poll_type, n)
chi_test <- table %>%
select(-hit) %>%
chisq.test()
#What is the p-value of the chi-squared test comparing the hit rate of online and telephone polls?
chi_test %>% .$p.value
#Determine which poll type has a higher probability of producing a confidence interval that covers the correct
#value of the spread. Also determine whether this difference is statistically significant at a p-value cutoff
#of 0.05. Which of the following is true?
Hit_online <- (table[2,2]/sum(table[,2]))/(table[1,2]/sum(table[,2]))
Hit_telephone <- (table[2,3]/sum(table[,3]))/(table[1,3]/sum(table[,3]))
Hit_online > Hit_telephone
#Answer:Online polls are more likely to cover the correct value of the spread and this difference is
#statistically significant.
#Q10: Odds ratio of online and telephone poll hit rate. Use the table from Q9 to calculate the odds ratio
#between the hit rate of online and telephone polls to determine the magnitude of the difference in
#the performance between poll types.
#Calculate the odds that an online poll generates a CI that covers the actual value of the spread
Hit_online[1,1]
#Calculate the odds that a telephone poll generates a CI that covers the actual value of the spread
Hit_telephone[1,1]
#Determine how many times larger odds are for online polls to hit vs telephone polls
Hit_online[1,1]/Hit_telephone[1,1]
#Q11:Plotting spread over time. Use brexit_polls to make a plot of the spread over time colored by poll type
#Use geom_smooth with method = "less" to plot smoot curves with a span of 0.4. Include the individual
#data points colored by poll type. Add a horizontal line indicating the final value of d = -.038
spread_time <- brexit_polls %>%
ggplot(aes(x = enddate, y = spread, col = poll_type)) +
geom_point() +
geom_smooth(method = "loess", span = 0.4) +
geom_hline(yintercept = d)
#Q12: Plotting raw percentages over time. Use the following code to create the object brexit_long, which has a
#column vote containing the 3 possible votes on a Brexit poll and a column proportion containing the raw
#proportion choosing that vote option on the given poll
brexit_long <- brexit_polls %>%
gather(vote, proportion, "remain":"undecided") %>%
mutate(vote = factor(vote))
#Make a grap of proportion over time colored by vote. Add a smooth trendline with geom_smooth and
#method = "loess" with a span of 0.3
proportion_time <- brexit_long %>%
ggplot(aes(x = enddate, y = proportion, col = vote)) +
geom_point() +
geom_smooth(method = "loess", span = 0.3) +
geom_hline(yintercept = d)
#Which of the following are TRUE?
#The percentage of undecided voters declines over time but is still around 10% throughout June. (TRUE)
#Over most of the date range, the confidence bands for Leave and Remain overlap. (TRUE)
#Over most of the date range, the confidence bands for Leave and Remain are below 50%. (TRUE)
#In the first half of June, Leave was polling higher than Remain, although this difference
#was within the CIs. (TRUE)
#At the time of the election in late June, the percentage voting Leave is trending upwards. (FALSE) | /Section, Course Wrap-up and Comprehensive Assessment, Brexit.R | no_license | vrolo001/Inference-and-modelling | R | false | false | 11,776 | r | ### Course Wrap-up and COmprehensive Assessment: Brexit ###
##PART 1:
#Import the brexit_polls polling data from the dslabs package and set options for the analysis:
library(tidyverse)
options(digits = 3)
library(dslabs)
data(brexit_polls)
#Define p = .481 as the actual percent voting "Remain" and d = 2p-1 = -.038 as the actual spread, with Remain defined
#as the positive outcome
p <- .481
d <- 2*p-1
#Q1: The final proportion of voters choosing to Remain was p = 0.481. Consider a poll with sample size 1500 voters...
#What is the expected total number of voters in the sample choosing Remain?
N <-1500
NX_hat <- N*p
#What is the standard error of the total number of voters in the sample choosing Remain
Nse_hat <- sqrt(N*p * (1-p))
#What is the expected value of X, the proportion of Remain voters?
X_hat <- p
#What is the standard error of X, the proportion of Remain voters?
se_hat <- sqrt(p*(1-p)/N)
#What is the expected value of d, the spread between the proportion of Remain voters and Leave voters?
d_hat <- 2*p -1
#What is the standard error of d, the spread between the proportion of Remain voters and Leave voters?
se_hatd <- 2*sqrt(p*(1-p)/N)
#Q2:Calculate X_hat for each poll in the brexit_polls dataset, the estimate of the proportion of voters choosing
#Remain (p = 0.481), given the observed spread. Use mutate to add a variable X_hat to the data
brexit_polls <- brexit_polls %>%
mutate(X_hat = (spread + 1)/2)
#What is the average of the observed spread?
mean(brexit_polls$spread)
#What is the standard deviation of the observed spreads?
sd(brexit_polls$spread)
#What is the average of X_hat, the estimates of the parameter p ?
mean(brexit_polls$X_hat)
#What is the standard deviation of X_hat?
sd(brexit_polls$X_hat)
#Q3: Confidence interval of a Brexit poll. Consider the first poll in brexit_polls, a YouGov pull run on the same
#day as the referendum
brexit_polls[1,]
#Use qnorm() to compute the 95%CI for X_hat
CI <- brexit_polls[1,] %>%
mutate(lower = X_hat - qnorm(.975)*sqrt(X_hat * (1-X_hat)/samplesize),
upper = X_hat + qnorm(.975)*sqrt(X_hat * (1-X_hat)/samplesize))
#Does the 95%CI predict a winner? Does it cover the true value of p observed during the referendum?
#Answer:The interval predicts a winner but does not cover the true value of p
##PART 2:
#Q4: Confidence intervals for polls in June: Create the data frame june_polls containing only Brexit polls ending
#June 2016, aka (enddate of "2016-06-01" and later). Calculate the CIs for all polls and determine how many
#cover the true value of d
june_polls <- brexit_polls %>%
filter(enddate >= "2016-06-01") %>%
mutate(se_x_hat = sqrt(X_hat * (1-X_hat)/samplesize),
se_spread = 2*se_x_hat,
lower = spread - qnorm(.975)*se_spread,
upper = spread + qnorm(.975)*se_spread,
hit = lower <= d & upper >= d)
#How many polls are in june_polls?
nrow(june_polls)
#What proportion of polls have a CI that covers the value of 0?
june_polls %>%
summarise(cover_zero = mean(lower <= 0 & upper >= 0))
#What porpotion of polls predict Remain (CI above 0)?
june_polls %>%
summarise(remain = mean(lower >= 0 & upper >= 0))
#What poprotion of polls have a CI covering the true value of d?
mean(june_polls$hit)
#Q5: Hit rate by pollster. Group and sumarise the june_polls object by pollster to find the proporiton of hits
#for each pollster and the number of polls per pollster. Use arrange() to sort by hit rate
june_polls %>%
group_by(pollster) %>%
summarise(proportion_hits = mean(hit), n = n()) %>%
arrange(proportion_hits)
#Which of the following are TRUE?
#Unbiased polls and pollsters will theoretically cover the correct value of the spread 50% of the time. (FALSE)
#Only 1 pollster had a 100% success rate in generating CIs that covered the correct value of the spread. (FALSE)
#The pollster w/the highest number of polls covered the correct value of the spread in their CI over
#60% of the time. (FALSE)
#All pollsters produced CIs covering the correct spread in at least 1 of their polls. (FALSE)
#The results are consistent with a large general bias that affects all pollsters. (TRUE)
#Q6:Boxplot of Brexit polls by poll type. Make a boxplot of the spread in june_polls by poll type.
june_polls %>%
ggplot(aes(poll_type, spread)) +
geom_boxplot()
#Which of the following are TRUE?
#Online polls tend to show support for Remain (spread > 0). (FALSE)
#Telephone polls tend to show support Remain (spread > 0). (TRUE)
#Telephone polls tend to show higher support for Remain than online polls (higher spread). (TRUE)
#Online polls have a larger interquartile range for the spread than telephone polls, indicating
#that they are more variable. (TRUE)
#Poll type introduces a bias that affects poll results. (TRUE)
#Q7: Combined spread across poll type. Calculate the confidence intervals of the spread combined across
#all polls in june_polls, grouping by poll type.Use the code below, which determines the total sample
#size per poll type; gives each spread estimate a weight based on the poll's sample size; and adds an
#estimate of p from the combined spread, to begin your analysis
combined_by_type <- june_polls %>%
group_by(poll_type) %>%
summarize(N = sum(samplesize),
spread = sum(spread*samplesize)/N,
p_hat = (spread + 1)/2)
combined_by_type <- combined_by_type %>%
mutate (se_spread = 2 * sqrt(p_hat * (1-p_hat)/N),
lower = spread - qnorm(.975)*se_spread,
upper = spread + qnorm(.975)*se_spread)
#What is the lower bound of the 95% confidence interval for online voters?
combined_by_type[1,6]
#What is the upper bound of the 95% confidence interval for online voters?
combined_by_type[1,7]
#Q8: Interpreting combined spread estimates across poll type. Interpret the CIs for the combined spreads for each
#poll type calculated in the previous problem. Which of the following are TRUE about the CIs of the combined
#spreads for different poll types?
#Neither set of combined polls makes a prediction about the outcome of the Brexit referendum (a prediction is
#possible if a confidence interval does not cover 0). (TRUE)
#The CI for online polls is larger than the confidence interval for telephone polls. (FALSE)
#The CI for telephone polls covers more positive values than the confidence interval for online polls. (TRUE)
#The CIs for different poll types do not overlap. (FALSE)
#Neither CI covers the true value d = -.038. (TRUE)
## PART 3:
#Q9: Chi-squared p-value. Define brexit_hit, with the code below, which computes the CI for all Brexit polls in 2016
#and then calculates whether the CI covers the actual value of the spread d = -.038
brexit_hit <- brexit_polls %>%
mutate(p_hat = (spread + 1)/2,
se_spread = 2*sqrt(p_hat*(1-p_hat)/samplesize),
spread_lower = spread - qnorm(.975)*se_spread,
spread_upper = spread + qnorm(.975)*se_spread,
hit = spread_lower < -0.038 & spread_upper > -0.038) %>%
select(poll_type, hit)
#Use brexit_hit to make a 2x2 table of poll type and hit status. Then use the chisq.test() function to perform a
#chi-squared test to determine whether the difference in hit rate is significant.
table <- brexit_hit %>%
group_by(poll_type, hit) %>%
summarise(n = n()) %>%
spread(poll_type, n)
chi_test <- table %>%
select(-hit) %>%
chisq.test()
#What is the p-value of the chi-squared test comparing the hit rate of online and telephone polls?
chi_test %>% .$p.value
#Determine which poll type has a higher probability of producing a confidence interval that covers the correct
#value of the spread. Also determine whether this difference is statistically significant at a p-value cutoff
#of 0.05. Which of the following is true?
Hit_online <- (table[2,2]/sum(table[,2]))/(table[1,2]/sum(table[,2]))
Hit_telephone <- (table[2,3]/sum(table[,3]))/(table[1,3]/sum(table[,3]))
Hit_online > Hit_telephone
#Answer:Online polls are more likely to cover the correct value of the spread and this difference is
#statistically significant.
#Q10: Odds ratio of online and telephone poll hit rate. Use the table from Q9 to calculate the odds ratio
#between the hit rate of online and telephone polls to determine the magnitude of the difference in
#the performance between poll types.
#Calculate the odds that an online poll generates a CI that covers the actual value of the spread
Hit_online[1,1]
#Calculate the odds that a telephone poll generates a CI that covers the actual value of the spread
Hit_telephone[1,1]
#Determine how many times larger odds are for online polls to hit vs telephone polls
Hit_online[1,1]/Hit_telephone[1,1]
#Q11:Plotting spread over time. Use brexit_polls to make a plot of the spread over time colored by poll type
#Use geom_smooth with method = "less" to plot smoot curves with a span of 0.4. Include the individual
#data points colored by poll type. Add a horizontal line indicating the final value of d = -.038
spread_time <- brexit_polls %>%
ggplot(aes(x = enddate, y = spread, col = poll_type)) +
geom_point() +
geom_smooth(method = "loess", span = 0.4) +
geom_hline(yintercept = d)
#Q12: Plotting raw percentages over time. Use the following code to create the object brexit_long, which has a
#column vote containing the 3 possible votes on a Brexit poll and a column proportion containing the raw
#proportion choosing that vote option on the given poll
brexit_long <- brexit_polls %>%
gather(vote, proportion, "remain":"undecided") %>%
mutate(vote = factor(vote))
#Make a grap of proportion over time colored by vote. Add a smooth trendline with geom_smooth and
#method = "loess" with a span of 0.3
proportion_time <- brexit_long %>%
ggplot(aes(x = enddate, y = proportion, col = vote)) +
geom_point() +
geom_smooth(method = "loess", span = 0.3) +
geom_hline(yintercept = d)
#Which of the following are TRUE?
#The percentage of undecided voters declines over time but is still around 10% throughout June. (TRUE)
#Over most of the date range, the confidence bands for Leave and Remain overlap. (TRUE)
#Over most of the date range, the confidence bands for Leave and Remain are below 50%. (TRUE)
#In the first half of June, Leave was polling higher than Remain, although this difference
#was within the CIs. (TRUE)
#At the time of the election in late June, the percentage voting Leave is trending upwards. (FALSE) |
qqlognorm <- function(x, VarName = "Data", pstyle = 1, MU, SIGMA){
# qqlognorm(x,Name,LineType,MU,SIGMA);
# Quantile/Quantile = QQ-Plot im Vergleich. zur LogNormalverteilung
# INPUT
# x(1:n) data may contain NaN
#
# OPTIONAL
# pstyle bezeichnung der y-achse
# MU,SIGMA parameters of LogNormal distribution
# estimated if not given
#
# OUTPUT
# qqx,qqy die Punkte des qq-plots
#
# AUTHOR
# ALU 2017 (Matlab)
# FP 2017 (R Port)
if (missing(MU)) {
if (nanmedian(x) > 0) {
MU = log(nanmedian(x))
} else {
stop("No MU given and median of input data is 0 or less, so no estimation possible")
}
}
if (missing(SIGMA)) {
if (mean(x, na.rm = T) > 0) {
SIGMA = sqrt(2 * (log(mean(x, na.rm = T)) - MU))
} else {
stop("No SIGMA given and mean of input data is 0 or less, so no estimation possible")
}
}
n = length(x)
RandLogNorm = rlnorm(n, MU, SIGMA)
qqplot(
x = x,
y = RandLogNorm,
xlab = cat("LogNorm(", MU, " , ", SIGMA, " )", sep = ""),
ylab = VarName,
main = "QQplot for LogNormal distribution",
pch = pstyle
)
return(invisible(list(
qqx = x,
qqy = RandLogNorm,
MU = MU,
SIGMA = SIGMA
)))
} | /DbtTools/Plot/R/qqlognorm.R | no_license | markus-flicke/KD_Projekt_1 | R | false | false | 1,340 | r | qqlognorm <- function(x, VarName = "Data", pstyle = 1, MU, SIGMA){
# qqlognorm(x,Name,LineType,MU,SIGMA);
# Quantile/Quantile = QQ-Plot im Vergleich. zur LogNormalverteilung
# INPUT
# x(1:n) data may contain NaN
#
# OPTIONAL
# pstyle bezeichnung der y-achse
# MU,SIGMA parameters of LogNormal distribution
# estimated if not given
#
# OUTPUT
# qqx,qqy die Punkte des qq-plots
#
# AUTHOR
# ALU 2017 (Matlab)
# FP 2017 (R Port)
if (missing(MU)) {
if (nanmedian(x) > 0) {
MU = log(nanmedian(x))
} else {
stop("No MU given and median of input data is 0 or less, so no estimation possible")
}
}
if (missing(SIGMA)) {
if (mean(x, na.rm = T) > 0) {
SIGMA = sqrt(2 * (log(mean(x, na.rm = T)) - MU))
} else {
stop("No SIGMA given and mean of input data is 0 or less, so no estimation possible")
}
}
n = length(x)
RandLogNorm = rlnorm(n, MU, SIGMA)
qqplot(
x = x,
y = RandLogNorm,
xlab = cat("LogNorm(", MU, " , ", SIGMA, " )", sep = ""),
ylab = VarName,
main = "QQplot for LogNormal distribution",
pch = pstyle
)
return(invisible(list(
qqx = x,
qqy = RandLogNorm,
MU = MU,
SIGMA = SIGMA
)))
} |
quakes_v2 <- function(dataFile) {
# rm(list=ls())
# source("quakes_v2.R")
# quakes_v2("usgsQuery_LA_84-14.csv")
browser()
library(ggmap)
## read in data
data <- read.csv(dataFile, sep = ",", stringsAsFactors = FALSE)
## plot histogram
hist(dataFit, breaks = 30 , col = "red", las = 1, xlab = "Earthquake Magnitude", main = "Greater Los Angeles Area Earthquakes, 1984-2014 ")
## map earthquake epicenters
map1 <- qmap(location = "los angeles", zoom = 10, source = "osm") +
geom_point(data = data,aes(x = longitude, y = latitude, size = mag, alpha = 1/40, colour="red"))
## pause execution for further analysis ('c' to continue)
browser()
# geocode("Baylor University", output = "more") ## for coords built on . . .
} | /quakes_v2.R | no_license | mlr7/earthquake_mapping_R | R | false | false | 779 | r | quakes_v2 <- function(dataFile) {
# rm(list=ls())
# source("quakes_v2.R")
# quakes_v2("usgsQuery_LA_84-14.csv")
browser()
library(ggmap)
## read in data
data <- read.csv(dataFile, sep = ",", stringsAsFactors = FALSE)
## plot histogram
hist(dataFit, breaks = 30 , col = "red", las = 1, xlab = "Earthquake Magnitude", main = "Greater Los Angeles Area Earthquakes, 1984-2014 ")
## map earthquake epicenters
map1 <- qmap(location = "los angeles", zoom = 10, source = "osm") +
geom_point(data = data,aes(x = longitude, y = latitude, size = mag, alpha = 1/40, colour="red"))
## pause execution for further analysis ('c' to continue)
browser()
# geocode("Baylor University", output = "more") ## for coords built on . . .
} |
# TODO: Analysis the relationship between sing and r valude distribtuion
#
# Author: xzhou
###############################################################################
source("SHC.R")
rDistVSSign <- function(totalGenotype, it = 100)
{
m <- nrow(totalGenotype)
n <- ncol(totalGenotype)
#number individual sampled
sampleIndividualSize = round(m/10)
#total r values
totalRVs <- calculateRValues(totalGenotype)
nSnps <- n/2
result <- NULL
#iterate through each pair
for(i in 1:(nSnps-1))
{
for(j in (i+1):nSnps)
{
pairGenotype <- totalGenotype[, c(2*i-1, 2*i, 2*j-1, 2*j)]
totalV <- totalRVs[i,j]
aResult <- c(i,j,totalV)
for(k in 1:it)
{
#randomly select sampleIndividualSize people
pool = 1:m
sampleIndex <- sort(sample(pool, sampleIndividualSize))
sampledGenotype <- pairGenotype[sampleIndex, ]
rValue <- calculateRValues(sampledGenotype)
aResult <- c(aResult, rValue[1,2])
}
#print(aResult)
hist(aResult[-1:-3], xlab = paste(aResult[1]), ylab = paste(aResult[2]), breaks = 20)
abline(v = aResult[3], col="blue", lty = 1, lwd = 3)
result <- rbind(result, aResult)
}
}
save(file = "rdist.RData", result)
result
}
rdist <- function(file = "../data/sim_4000seq/80SNP_CEU_sim_4000seq.12encode", popSize = 2000, nSnps = 30 )
{
targetGenotype <- read.table(file)
m <- nrow(targetGenotype)
n <- ncol(targetGenotype)
if(popSize == -1)
{
popSize = m
}
if(nSnps == -1)
{
nSnps = n/2
}
targetGenotype = targetGenotype[1:popSize, 1:(2*nSnps)]
pdf("dist.pdf")
result <- rDistVSSign(targetGenotype)
dev.off()
}
dist2Sign <- function(result = NULL, loadFromFile = F)
{
#DEBUG
#loadFromFile = T
if(result == NULL || loadFromFile == T)
{
load("rdist.RData")
}
nSnps <- max(result[,2])
signMatrix = matrix(0, nSnps, nSnps)
nRec <- nrow(result)
for(k in 1:nRec)
{
aResult <- result[k, ]
i <- aResult[1]
j <- aResult[2]
realR <- aResult[3]
allAvgR <- aResult[-1:-3]
nPositive <- length(allAvgR[allAvgR>0])
nNegative <- length(allAvgR[allAvgR<0])
if(nPositive > nNegative)
{
signMatrix[i,j] <- signMatrix[j,i] <- 1
}
else if(nPositive < nNegative)
{
signMatrix[i,j] <- signMatrix[j,i] <- -1
}
else
{
signMatrix[i,j] <- 0
}
}
signMatrix
}
distPlot <- function(result = NULL, loadFromFile = T)
{
if(loadFromFile == TRUE || result == NULL)
{
load("rdist.RData")
}
m <- nrow(result)
n <- ncol(result)
pdf("adjust_r_dist_2000_10_100__0.05.pdf")
for(i in 1:m)
{
aResult = result[i,]
#hist(aResult[-1:-3], xlab = paste(aResult[1]), ylab = paste(aResult[2]), breaks = 20)
if(abs(aResult[3]) >= 0.05)
{
hist(aResult[-1:-3], xlab = paste(aResult[1]), ylab = paste(aResult[2]), breaks = seq(-1, 1, by = 0.05), xlim = c(-1, 1), main = paste(aResult[1], "-", aResult[2], "r = ", aResult[3]))
abline(v = aResult[3], col="blue", lty = 1, lwd = 3)
abline(v = 0.05, col="red", lty = 3, lwd = 1)
abline(v = -0.05, col="red", lty = 3, lwd = 1)
}
}
dev.off()
}
#rdist()
sign <- dist2Sign()
print(sign)
| /dataAnalysis/rDistVSSign.R | no_license | xzhou/gnome | R | false | false | 3,125 | r | # TODO: Analysis the relationship between sing and r valude distribtuion
#
# Author: xzhou
###############################################################################
source("SHC.R")
rDistVSSign <- function(totalGenotype, it = 100)
{
m <- nrow(totalGenotype)
n <- ncol(totalGenotype)
#number individual sampled
sampleIndividualSize = round(m/10)
#total r values
totalRVs <- calculateRValues(totalGenotype)
nSnps <- n/2
result <- NULL
#iterate through each pair
for(i in 1:(nSnps-1))
{
for(j in (i+1):nSnps)
{
pairGenotype <- totalGenotype[, c(2*i-1, 2*i, 2*j-1, 2*j)]
totalV <- totalRVs[i,j]
aResult <- c(i,j,totalV)
for(k in 1:it)
{
#randomly select sampleIndividualSize people
pool = 1:m
sampleIndex <- sort(sample(pool, sampleIndividualSize))
sampledGenotype <- pairGenotype[sampleIndex, ]
rValue <- calculateRValues(sampledGenotype)
aResult <- c(aResult, rValue[1,2])
}
#print(aResult)
hist(aResult[-1:-3], xlab = paste(aResult[1]), ylab = paste(aResult[2]), breaks = 20)
abline(v = aResult[3], col="blue", lty = 1, lwd = 3)
result <- rbind(result, aResult)
}
}
save(file = "rdist.RData", result)
result
}
rdist <- function(file = "../data/sim_4000seq/80SNP_CEU_sim_4000seq.12encode", popSize = 2000, nSnps = 30 )
{
targetGenotype <- read.table(file)
m <- nrow(targetGenotype)
n <- ncol(targetGenotype)
if(popSize == -1)
{
popSize = m
}
if(nSnps == -1)
{
nSnps = n/2
}
targetGenotype = targetGenotype[1:popSize, 1:(2*nSnps)]
pdf("dist.pdf")
result <- rDistVSSign(targetGenotype)
dev.off()
}
dist2Sign <- function(result = NULL, loadFromFile = F)
{
#DEBUG
#loadFromFile = T
if(result == NULL || loadFromFile == T)
{
load("rdist.RData")
}
nSnps <- max(result[,2])
signMatrix = matrix(0, nSnps, nSnps)
nRec <- nrow(result)
for(k in 1:nRec)
{
aResult <- result[k, ]
i <- aResult[1]
j <- aResult[2]
realR <- aResult[3]
allAvgR <- aResult[-1:-3]
nPositive <- length(allAvgR[allAvgR>0])
nNegative <- length(allAvgR[allAvgR<0])
if(nPositive > nNegative)
{
signMatrix[i,j] <- signMatrix[j,i] <- 1
}
else if(nPositive < nNegative)
{
signMatrix[i,j] <- signMatrix[j,i] <- -1
}
else
{
signMatrix[i,j] <- 0
}
}
signMatrix
}
distPlot <- function(result = NULL, loadFromFile = T)
{
if(loadFromFile == TRUE || result == NULL)
{
load("rdist.RData")
}
m <- nrow(result)
n <- ncol(result)
pdf("adjust_r_dist_2000_10_100__0.05.pdf")
for(i in 1:m)
{
aResult = result[i,]
#hist(aResult[-1:-3], xlab = paste(aResult[1]), ylab = paste(aResult[2]), breaks = 20)
if(abs(aResult[3]) >= 0.05)
{
hist(aResult[-1:-3], xlab = paste(aResult[1]), ylab = paste(aResult[2]), breaks = seq(-1, 1, by = 0.05), xlim = c(-1, 1), main = paste(aResult[1], "-", aResult[2], "r = ", aResult[3]))
abline(v = aResult[3], col="blue", lty = 1, lwd = 3)
abline(v = 0.05, col="red", lty = 3, lwd = 1)
abline(v = -0.05, col="red", lty = 3, lwd = 1)
}
}
dev.off()
}
#rdist()
sign <- dist2Sign()
print(sign)
|
hist(weekly$CHANGES*100,breaks = 30,main = "Histogram for Weekly Returns", xlab = "Returns", col = "Grey", border = "Black",xlim = c(-10, 10), ylim=c(0, 35), plot = TRUE)
| /weekly.r | no_license | glorevenhite/gswcapital-stats-r | R | false | false | 171 | r | hist(weekly$CHANGES*100,breaks = 30,main = "Histogram for Weekly Returns", xlab = "Returns", col = "Grey", border = "Black",xlim = c(-10, 10), ylim=c(0, 35), plot = TRUE)
|
\name{initDisplayWindow}
\title{Device management}
\alias{initDisplayWindow}
\description{
Display the device on which the plot will be displayed. For internal use.
}
\usage{
initDisplayWindow(window, filename, path, width, height, scale, res,
mfrow, bg, pty, mar, mgp, n.contrast = 1)
}
\arguments{
\item{window}{the type of device on which the plot will be displayed. \emph{logical}, \code{NULL} or \emph{character}.}
\item{filename}{the name of the file used to export the plot. \emph{character}.}
\item{path}{the directory where the plot file will be created. \emph{character}.}
\item{width}{the width of the device used to export the plot in inches. \emph{postive numeric}.}
\item{height}{the height of the device used to export the plot. \emph{postive numeric}.}
\item{scale}{the scaling factor to convert \code{height} and \code{height} to standard unit. \emph{numeric}.}
\item{res}{the nominal resolution in ppi which will be recorded in the bitmap file. \emph{positive integer}.}
\item{mfrow}{the division of the device in plot region. \emph{numeric vector of size 2}.}
\item{bg}{the color used for the background. \emph{character}.}
\item{pty}{the type of plot region to be used. Can be \code{"s"} or \code{"m"}.}
\item{mar}{the number of margin lines to be specified on the four sides of the plot. \emph{positive numeric vector of size 4}.}
\item{mgp}{the margin line for the axis title, axis labels and axis line. \emph{positive numeric vector of size 3}.}
\item{n.contrast}{the number of contrast parameters. \emph{postive integer}.}
}
\details{
ARGUMENTS: \cr
Information about the \code{window}, \code{filename}, \code{width}, \code{height}, \code{path}, \code{unit} and \code{res} arguments can be found in the details section of \code{\link{initWindow}}.
Information about the \code{bg}, \code{pty}, \code{mar} and \code{mgp} arguments can be found in \code{\link{par}}.
}
\concept{init.}
\keyword{function,internal}
| /man/MRIaggr-initDisplayWindow.Rd | no_license | cran/MRIaggr | R | false | false | 2,005 | rd | \name{initDisplayWindow}
\title{Device management}
\alias{initDisplayWindow}
\description{
Display the device on which the plot will be displayed. For internal use.
}
\usage{
initDisplayWindow(window, filename, path, width, height, scale, res,
mfrow, bg, pty, mar, mgp, n.contrast = 1)
}
\arguments{
\item{window}{the type of device on which the plot will be displayed. \emph{logical}, \code{NULL} or \emph{character}.}
\item{filename}{the name of the file used to export the plot. \emph{character}.}
\item{path}{the directory where the plot file will be created. \emph{character}.}
\item{width}{the width of the device used to export the plot in inches. \emph{postive numeric}.}
\item{height}{the height of the device used to export the plot. \emph{postive numeric}.}
\item{scale}{the scaling factor to convert \code{height} and \code{height} to standard unit. \emph{numeric}.}
\item{res}{the nominal resolution in ppi which will be recorded in the bitmap file. \emph{positive integer}.}
\item{mfrow}{the division of the device in plot region. \emph{numeric vector of size 2}.}
\item{bg}{the color used for the background. \emph{character}.}
\item{pty}{the type of plot region to be used. Can be \code{"s"} or \code{"m"}.}
\item{mar}{the number of margin lines to be specified on the four sides of the plot. \emph{positive numeric vector of size 4}.}
\item{mgp}{the margin line for the axis title, axis labels and axis line. \emph{positive numeric vector of size 3}.}
\item{n.contrast}{the number of contrast parameters. \emph{postive integer}.}
}
\details{
ARGUMENTS: \cr
Information about the \code{window}, \code{filename}, \code{width}, \code{height}, \code{path}, \code{unit} and \code{res} arguments can be found in the details section of \code{\link{initWindow}}.
Information about the \code{bg}, \code{pty}, \code{mar} and \code{mgp} arguments can be found in \code{\link{par}}.
}
\concept{init.}
\keyword{function,internal}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/basic_functions.R
\name{integrate_trapeze}
\alias{integrate_trapeze}
\title{integrate_trapeze}
\usage{
integrate_trapeze(x, y)
}
\arguments{
\item{x}{a numerical vector, the discretization of the domain.}
\item{y}{a numerical value, the discretization of the function to integrate.}
}
\value{
a numerical value, the approximation.
}
\description{
Trapezoidal rule to approximate an integral.
}
\examples{
x <- seq(0,1,le=1e2)
integrate_trapeze(x,x^2)
integrate_trapeze(data1$grids[[1]],t(data1$x[[1]]))
}
| /bliss/man/integrate_trapeze.Rd | no_license | akhikolla/ClusterTests | R | false | true | 610 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/basic_functions.R
\name{integrate_trapeze}
\alias{integrate_trapeze}
\title{integrate_trapeze}
\usage{
integrate_trapeze(x, y)
}
\arguments{
\item{x}{a numerical vector, the discretization of the domain.}
\item{y}{a numerical value, the discretization of the function to integrate.}
}
\value{
a numerical value, the approximation.
}
\description{
Trapezoidal rule to approximate an integral.
}
\examples{
x <- seq(0,1,le=1e2)
integrate_trapeze(x,x^2)
integrate_trapeze(data1$grids[[1]],t(data1$x[[1]]))
}
|
require(testthat)
#filePathOutcomes <- file.path(base::path.package("Wats"), "extdata", "BirthRatesOk.txt")
# filePathOutcomes <- file.path(devtools::inst(name="Wats"), "extdata", "BirthRatesOk.txt") #This approach accounts for working on developmental box.
# filePathOutcomes <- file.path(devtools::inst(name="Wats"), "extdata", "BirthRatesOk.txt") #This approach accounts for working on developmental box.
###########
context("Augment")
###########
test_that("AugmentYearDataWithMonthResolution", {
dsBirthRate <- CountyMonthBirthRate2005Version[CountyMonthBirthRate2005Version$CountyName=="oklahoma", ]
# dsBirthRate$Date <- as.Date(dsBirthRate$Date)
# changeMonth <- as.Date("1996-02-15") # as.Date(dateBombing + weeks(40))
# dsBirthRate$StageID <- ifelse(dsBirthRate$Date < changeMonth, 1L, 2L)
expectedColumnNames <- c(colnames(dsBirthRate), "CycleTally", "ProportionThroughCycle", "ProportionID"
, "StartingPointInCycle", "TerminalPointInCycle", "StageProgress")
actual <- Wats::AugmentYearDataWithMonthResolution(ds=dsBirthRate, dateName="Date")
expect_equal(mean(actual$ProportionThroughCycle), expected=0.5, label="The mean of the proportion should be 0.5.")
expect_equal(actual$ProportionID, expected=rep(1:12, times=10), label="The `ProportionID` should be correct.")
expect_equal(actual$CycleTally, expected=rep(0:9, each=12), label="There should be 120 Cycle Indicies.")
expect_equal(actual$StartingPointInCycle, expected=rep(c(T,F,F,F,F,F,F,F,F,F,F,F), time=10), label="The `StartingPointInCycle` should be correct.")
expect_equal(actual$TerminalPointInCycle, expected=rep(c(F,F,F,F,F,F,F,F,F,F,F,T), time=10), label="The `TerminalPointInCycle` should be correct.")
expect_equal(colnames(actual), expected=expectedColumnNames, label="The correct columns should be added.")
})
test_that("AugmentYearDataWithSecondResolution", {
dsBirthRate <- CountyMonthBirthRate2005Version
dsBirthRate <- dsBirthRate[dsBirthRate$CountyName=="oklahoma", ]
dsBirthRate$Date <- as.POSIXct(dsBirthRate$Date, tz="GMT")
expectedColumnNames <- c(colnames(dsBirthRate), "CycleTally", "ProportionThroughCycle", "ProportionID"
, "StartingPointInCycle", "TerminalPointInCycle", "StageProgress")
actual <- Wats::AugmentYearDataWithSecondResolution(ds=dsBirthRate, dateName="Date")
expect_equal(mean(actual$ProportionThroughCycle), expected=0.4933366, tolerance=1e-7, label="The mean of the proportion should be a little less than 0.5 (ie, ~.4933366) because the calender's first months are shorter than its last.")
expect_equal(actual$ProportionID, expected=rep(1:12, times=10), label="The `ProportionID` should be correct.")
expect_equal(actual$CycleTally, expected=rep(0:9, each=12), label="There should be 120 Cycle Indicies.")
expect_equal(actual$StartingPointInCycle, expected=rep(c(T,F,F,F,F,F,F,F,F,F,F,F), time=10), label="The `StartingPointInCycle` should be correct.")
expect_equal(actual$TerminalPointInCycle, expected=rep(c(F,F,F,F,F,F,F,F,F,F,F,T), time=10), label="The `TerminalPointInCycle` should be correct.")
expect_equal(colnames(actual), expected=expectedColumnNames, label="The correct columns should be added.")
})
| /tests/testthat/test.Augment.R | no_license | andkov/Wats | R | false | false | 3,239 | r | require(testthat)
#filePathOutcomes <- file.path(base::path.package("Wats"), "extdata", "BirthRatesOk.txt")
# filePathOutcomes <- file.path(devtools::inst(name="Wats"), "extdata", "BirthRatesOk.txt") #This approach accounts for working on developmental box.
# filePathOutcomes <- file.path(devtools::inst(name="Wats"), "extdata", "BirthRatesOk.txt") #This approach accounts for working on developmental box.
###########
context("Augment")
###########
test_that("AugmentYearDataWithMonthResolution", {
dsBirthRate <- CountyMonthBirthRate2005Version[CountyMonthBirthRate2005Version$CountyName=="oklahoma", ]
# dsBirthRate$Date <- as.Date(dsBirthRate$Date)
# changeMonth <- as.Date("1996-02-15") # as.Date(dateBombing + weeks(40))
# dsBirthRate$StageID <- ifelse(dsBirthRate$Date < changeMonth, 1L, 2L)
expectedColumnNames <- c(colnames(dsBirthRate), "CycleTally", "ProportionThroughCycle", "ProportionID"
, "StartingPointInCycle", "TerminalPointInCycle", "StageProgress")
actual <- Wats::AugmentYearDataWithMonthResolution(ds=dsBirthRate, dateName="Date")
expect_equal(mean(actual$ProportionThroughCycle), expected=0.5, label="The mean of the proportion should be 0.5.")
expect_equal(actual$ProportionID, expected=rep(1:12, times=10), label="The `ProportionID` should be correct.")
expect_equal(actual$CycleTally, expected=rep(0:9, each=12), label="There should be 120 Cycle Indicies.")
expect_equal(actual$StartingPointInCycle, expected=rep(c(T,F,F,F,F,F,F,F,F,F,F,F), time=10), label="The `StartingPointInCycle` should be correct.")
expect_equal(actual$TerminalPointInCycle, expected=rep(c(F,F,F,F,F,F,F,F,F,F,F,T), time=10), label="The `TerminalPointInCycle` should be correct.")
expect_equal(colnames(actual), expected=expectedColumnNames, label="The correct columns should be added.")
})
test_that("AugmentYearDataWithSecondResolution", {
dsBirthRate <- CountyMonthBirthRate2005Version
dsBirthRate <- dsBirthRate[dsBirthRate$CountyName=="oklahoma", ]
dsBirthRate$Date <- as.POSIXct(dsBirthRate$Date, tz="GMT")
expectedColumnNames <- c(colnames(dsBirthRate), "CycleTally", "ProportionThroughCycle", "ProportionID"
, "StartingPointInCycle", "TerminalPointInCycle", "StageProgress")
actual <- Wats::AugmentYearDataWithSecondResolution(ds=dsBirthRate, dateName="Date")
expect_equal(mean(actual$ProportionThroughCycle), expected=0.4933366, tolerance=1e-7, label="The mean of the proportion should be a little less than 0.5 (ie, ~.4933366) because the calender's first months are shorter than its last.")
expect_equal(actual$ProportionID, expected=rep(1:12, times=10), label="The `ProportionID` should be correct.")
expect_equal(actual$CycleTally, expected=rep(0:9, each=12), label="There should be 120 Cycle Indicies.")
expect_equal(actual$StartingPointInCycle, expected=rep(c(T,F,F,F,F,F,F,F,F,F,F,F), time=10), label="The `StartingPointInCycle` should be correct.")
expect_equal(actual$TerminalPointInCycle, expected=rep(c(F,F,F,F,F,F,F,F,F,F,F,T), time=10), label="The `TerminalPointInCycle` should be correct.")
expect_equal(colnames(actual), expected=expectedColumnNames, label="The correct columns should be added.")
})
|
#' @title For all points in matrix 1, return the distance to and index of the
#' nearest point in matrix 2.
#'
#' @description
#' Find the shortest distance between each point in one data set and the points
#' in a second set.
#'
#' This function determines the distance between every point in mOne and the
#' nearest point in mTwo.
#'
#' @param mOne A numeric matrix where each row is a localization and each
#' column is a spatial axis.
#' @param mTwo A numeric matrix with the same number of columns as mOne.
#'
#' @author Zach Colburn
#'
#' @examples
#' # Generate random data.
#' set.seed(10)
#'
#' mOne <- as.matrix(data.frame(
#' x = rnorm(10),
#' y = rbinom(10, 100, 0.5),
#' z = runif(10)
#' ))
#'
#' mTwo <- as.matrix(data.frame(
#' x = rnorm(20),
#' y = rbinom(20, 100, 0.5),
#' z = runif(20)
#' ))
#'
#' # Find the minimum distance between each point in mOne and the points in
#' # mTwo.
#' find_min_dists(mOne, mTwo)
#'
#' @export
#'
#' @importFrom assertthat assert_that
find_min_dists <- function(mOne, mTwo) {
# Perform type checking.
assert_that(class(mOne)[1] == "matrix")
assert_that(length(mOne) >= 1)
assert_that(class(mOne[1]) %in% c("integer", "numeric"))
assert_that(nrow(mOne) >= 1)
assert_that(ncol(mOne) > 0)
assert_that(class(mTwo)[1] == "matrix")
assert_that(length(mTwo) >= 1)
assert_that(class(mTwo[1]) %in% c("integer", "numeric"))
assert_that(nrow(mTwo) >= 1)
assert_that(ncol(mTwo) > 0)
# Find the minimum distance between each point in mOne and the points in mTwo.
.find_min_dists_cpp(mOne, mTwo)
}
| /Bioi/R/find_min_dists.R | no_license | akhikolla/ClusterTests | R | false | false | 1,618 | r | #' @title For all points in matrix 1, return the distance to and index of the
#' nearest point in matrix 2.
#'
#' @description
#' Find the shortest distance between each point in one data set and the points
#' in a second set.
#'
#' This function determines the distance between every point in mOne and the
#' nearest point in mTwo.
#'
#' @param mOne A numeric matrix where each row is a localization and each
#' column is a spatial axis.
#' @param mTwo A numeric matrix with the same number of columns as mOne.
#'
#' @author Zach Colburn
#'
#' @examples
#' # Generate random data.
#' set.seed(10)
#'
#' mOne <- as.matrix(data.frame(
#' x = rnorm(10),
#' y = rbinom(10, 100, 0.5),
#' z = runif(10)
#' ))
#'
#' mTwo <- as.matrix(data.frame(
#' x = rnorm(20),
#' y = rbinom(20, 100, 0.5),
#' z = runif(20)
#' ))
#'
#' # Find the minimum distance between each point in mOne and the points in
#' # mTwo.
#' find_min_dists(mOne, mTwo)
#'
#' @export
#'
#' @importFrom assertthat assert_that
find_min_dists <- function(mOne, mTwo) {
# Perform type checking.
assert_that(class(mOne)[1] == "matrix")
assert_that(length(mOne) >= 1)
assert_that(class(mOne[1]) %in% c("integer", "numeric"))
assert_that(nrow(mOne) >= 1)
assert_that(ncol(mOne) > 0)
assert_that(class(mTwo)[1] == "matrix")
assert_that(length(mTwo) >= 1)
assert_that(class(mTwo[1]) %in% c("integer", "numeric"))
assert_that(nrow(mTwo) >= 1)
assert_that(ncol(mTwo) > 0)
# Find the minimum distance between each point in mOne and the points in mTwo.
.find_min_dists_cpp(mOne, mTwo)
}
|
## Get results for each EWAS (corrected for nearby + distant GIs) and inspect bias and inflation using bacon
## EWAS statistics after correction for inflation/bias using bacon are saved
# Libraries
options('stringsAsFactors' = FALSE)
library(BiocParallel)
library(bacon)
library(GenomicRanges)
library(BatchJobs)
library(readr)
library(dplyr)
# Working directory
direc <- ""
# Phenotype file
cvrt <- read.table(sprintf("%scvrt.meth.txt", direc), header = TRUE, sep = "\t")
# Get nr of covariates
genes <- gsub(".txt", "", list.files(sprintf("%soutput.genome.wide/ewas.corrected.distant.gi/nr_covariates/", direc)))
nr.covariates <- unlist(lapply(genes, FUN = function(gene) {
nr_covariate <- read.table(sprintf("%soutput.genome.wide/ewas.corrected.distant.gi/nr_covariates/%s.txt", direc, gene))
nr_covariate$V1
}))
names(nr.covariates) <- genes
save(nr.covariates, file = sprintf("%soutput.genome.wide/ewas.corrected.distant.gi/nr.covariates.RData", direc))
run <- function(gene, direc, nr.covariates, cvrt) {
require(GenomicRanges)
require(bacon)
require(readr)
require(dplyr)
chrs <- paste0("chr",1:22)
# Get results for current gene
files <- lapply(chrs, FUN = function(chr) {
file <- sprintf("%soutput.genome.wide/ewas.corrected.distant.gi/output/%s.%s.txt", direc, chr, gene)
me <- read_tsv(file, col_names=TRUE, progress=FALSE)
})
me <- bind_rows(files)
set.seed(1) # reproducibility
# run bacon
bc <- bacon(effectsizes = cbind(me$estimate), standarderrors = cbind(me$se))
me$estimate <- round(drop(es(bc)), digits = 6) # corrected regression coefficients
me$se <- round(drop(se(bc)), digits = 6) # corrected standard errors
me$tvalue <- drop(tstat(bc)) # corrected t-values
me$pvalue <- 2*pt(abs(me$tvalue), nrow(cvrt) - nr.covariates[gene] - 1, lower.tail = FALSE) # corrected p-values
write_tsv(me, gzfile(sprintf("%soutput.genome.wide/ewas.corrected.distant.gi/output/%s.bacon.txt.gz", direc, gene)))
# return bias and inflation for this EWAS
out <- c("bias" = bias(bc), "inflation" = inflation(bc))
return(out)
}
# Genes
genes <- list.files(sprintf("%soutput.genome.wide/ewas.corrected.distant.gi/output", direc))
genes <- gsub("chr[0-9]{1,}\\.|\\.txt", "", genes)
genes <- unique(genes)
# Run
res <- lapply(genes, FUN = run, direc=direc, nr.covariates=nr.covariates, cvrt=cvrt)
res <- do.call(rbind, res)
res <- as.data.frame(cbind(genes, round(res, digits = 6)))
names(res) <- c("gene", "bias", "inflation")
# Save bias and inflation statistics
write.table(res, row.names = FALSE, col.names = TRUE, quote = FALSE, sep = "\t",
file = sprintf("%soutput.genome.wide/ewas.corrected.distant.gi/bias_inflation_ewas.txt", direc))
| /R/bacon_corrected_distant_GIs.R | no_license | pjhop/DNAmRegulators | R | false | false | 2,759 | r | ## Get results for each EWAS (corrected for nearby + distant GIs) and inspect bias and inflation using bacon
## EWAS statistics after correction for inflation/bias using bacon are saved
# Libraries
options('stringsAsFactors' = FALSE)
library(BiocParallel)
library(bacon)
library(GenomicRanges)
library(BatchJobs)
library(readr)
library(dplyr)
# Working directory
direc <- ""
# Phenotype file
cvrt <- read.table(sprintf("%scvrt.meth.txt", direc), header = TRUE, sep = "\t")
# Get nr of covariates
genes <- gsub(".txt", "", list.files(sprintf("%soutput.genome.wide/ewas.corrected.distant.gi/nr_covariates/", direc)))
nr.covariates <- unlist(lapply(genes, FUN = function(gene) {
nr_covariate <- read.table(sprintf("%soutput.genome.wide/ewas.corrected.distant.gi/nr_covariates/%s.txt", direc, gene))
nr_covariate$V1
}))
names(nr.covariates) <- genes
save(nr.covariates, file = sprintf("%soutput.genome.wide/ewas.corrected.distant.gi/nr.covariates.RData", direc))
run <- function(gene, direc, nr.covariates, cvrt) {
require(GenomicRanges)
require(bacon)
require(readr)
require(dplyr)
chrs <- paste0("chr",1:22)
# Get results for current gene
files <- lapply(chrs, FUN = function(chr) {
file <- sprintf("%soutput.genome.wide/ewas.corrected.distant.gi/output/%s.%s.txt", direc, chr, gene)
me <- read_tsv(file, col_names=TRUE, progress=FALSE)
})
me <- bind_rows(files)
set.seed(1) # reproducibility
# run bacon
bc <- bacon(effectsizes = cbind(me$estimate), standarderrors = cbind(me$se))
me$estimate <- round(drop(es(bc)), digits = 6) # corrected regression coefficients
me$se <- round(drop(se(bc)), digits = 6) # corrected standard errors
me$tvalue <- drop(tstat(bc)) # corrected t-values
me$pvalue <- 2*pt(abs(me$tvalue), nrow(cvrt) - nr.covariates[gene] - 1, lower.tail = FALSE) # corrected p-values
write_tsv(me, gzfile(sprintf("%soutput.genome.wide/ewas.corrected.distant.gi/output/%s.bacon.txt.gz", direc, gene)))
# return bias and inflation for this EWAS
out <- c("bias" = bias(bc), "inflation" = inflation(bc))
return(out)
}
# Genes
genes <- list.files(sprintf("%soutput.genome.wide/ewas.corrected.distant.gi/output", direc))
genes <- gsub("chr[0-9]{1,}\\.|\\.txt", "", genes)
genes <- unique(genes)
# Run
res <- lapply(genes, FUN = run, direc=direc, nr.covariates=nr.covariates, cvrt=cvrt)
res <- do.call(rbind, res)
res <- as.data.frame(cbind(genes, round(res, digits = 6)))
names(res) <- c("gene", "bias", "inflation")
# Save bias and inflation statistics
write.table(res, row.names = FALSE, col.names = TRUE, quote = FALSE, sep = "\t",
file = sprintf("%soutput.genome.wide/ewas.corrected.distant.gi/bias_inflation_ewas.txt", direc))
|
hpd_data <- "./data/household_power_consumption.txt"
hpd <- read.table(hpd_data, header=TRUE, sep=";", stringsAsFactors=FALSE, dec=".")
subSethpd<- hpd[hpd$Date %in% c("1/2/2007","2/2/2007") ,]
datetime <- strptime(paste(subSethpd$Date, subSethpd$Time, sep=" "), "%d/%m/%Y %H:%M:%S")
globalActivePower <- as.numeric(subSetData$Global_active_power)
subMetering1 <- as.numeric(subSethpd$Sub_metering_1)
subMetering2 <- as.numeric(subSethpd$Sub_metering_2)
subMetering3 <- as.numeric(subSethpd$Sub_metering_3)
png("plot3.png", width=480, height=480)
plot(datetime, subMetering1, type="l", ylab="Energy Submetering", xlab="")
lines(datetime, subMetering2, type="l", col="red")
lines(datetime, subMetering3, type="l", col="blue")
legend("topright", c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), lty=1, lwd=2.5, col=c("black", "red", "blue"))
dev.off() | /plot3.R | no_license | Odansereau/ExData_Plotting1 | R | false | false | 875 | r | hpd_data <- "./data/household_power_consumption.txt"
hpd <- read.table(hpd_data, header=TRUE, sep=";", stringsAsFactors=FALSE, dec=".")
subSethpd<- hpd[hpd$Date %in% c("1/2/2007","2/2/2007") ,]
datetime <- strptime(paste(subSethpd$Date, subSethpd$Time, sep=" "), "%d/%m/%Y %H:%M:%S")
globalActivePower <- as.numeric(subSetData$Global_active_power)
subMetering1 <- as.numeric(subSethpd$Sub_metering_1)
subMetering2 <- as.numeric(subSethpd$Sub_metering_2)
subMetering3 <- as.numeric(subSethpd$Sub_metering_3)
png("plot3.png", width=480, height=480)
plot(datetime, subMetering1, type="l", ylab="Energy Submetering", xlab="")
lines(datetime, subMetering2, type="l", col="red")
lines(datetime, subMetering3, type="l", col="blue")
legend("topright", c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), lty=1, lwd=2.5, col=c("black", "red", "blue"))
dev.off() |
## Type-generic list- or vector-processing functions
#' List utilities
#'
#' These functions provide small list- or vector-processing utilities, and in
#' some cases are just aliases for functions in base R. In such cases, the
#' point of the alias is to make the function available under the standard
#' Scheme name.
#'
#' \code{cons} is an alias for base R's \code{\link{c}}, \code{nth} is an alias
#' for \code{\link{[[}}, \code{member} is an alias for \code{\link{\%in\%}},
#' \code{reverse} is an alias for \code{\link{rev}} and \code{is.empty} returns
#' TRUE if and only if its argument is of length 0, returning FALSE otherwise.
#'
#' \code{make.list} returns a list constructed by replicating its expr argument
#' n times. It is equivalent to \code{link{replicate}} with
#' \code{simplify=FALSE}.
#'
#' @param ... Arguments that \code{cons} should pass to \code{c()}.
#' @param x As in \code{\link{\%in\%}} or \code{\link{rev}}.
#' @param table As in \code{\link{\%in\%}}.
#' @param obj An object that is.empty should check the length of.
#' @param n The number of times \code{make.list} should replicate its expr
#' argument in building a list.
#' @param expr An object which \code{make.list} should replicate in building
#' a list.
#'
#' @return
#' \code{make.list} returns the n-length list of replicated expr's. is.empty returns
#' TRUE if its argument is 0-length and FALSE otherwise.
#'
#' @rdname list-utilities
#' @name list-utilities
#' @export
cons <-
function(...)
{
do.call(c, list(...))
}
#' @rdname list-utilities
#' @export
reverse <- rev
#' @rdname list-utilities
#' @export
nth <-
function(obj, n)
{
obj[[n]]
}
#' @rdname list-utilities
#' @export
member <- `%in%`
#' @rdname list-utilities
#' @export
is.empty <- function(obj) length(obj) == 0
#' @rdname list-utilities
#' @export
make.list <-
function(n, expr)
{
#As in base, but with a fixed different value for simplify
sapply(integer(n), eval.parent(substitute(function(...) expr)),
simplify=FALSE)
}
#' List/vector access functions
#'
#' These functions are accessors for various elements and subsequences of lists
#' and vectors. They are written in a type-generic way and will work for any
#' broadly defined sequence type: vectors, lists (aka "generic vectors") and
#' pairlists.
#'
#' Using "sequence" to mean list, other vector or pairlist, the basic functions
#' here are
#' \itemize{
#' \item{car, which returns the first element of a sequence (car(x) is
#' equivalent to x[[1]] for (pair)lists and to x[1] for vectors)}
#' \item{cdr, which returns the sequence consisting of every element but
#' the first, or NULL for a sequence of length 0 or length 1}
#' \item{last, which returns the last element of a sequence}
#' \item{first, which is an alias for car}
#' }
#'
#' There are also a large number of functions of the form cXXXXr, where there
#' are two, three or four "a"'s or "d"'s between the c and r. These functions
#' are compositions of car and cdr: to give one example, \code{caadr(x)} is
#' equivalent to car(car(cdr(x))). All such functions with up to four letters
#' between the c and the r are pre-defined here.
#'
#' @param x The object whose elements or subsequences to access.
#'
#' @return A particular element or subsequence.
#' @rdname list-access
#' @name list-access
#' @export
car <-
function(x)
{
if(length(x) == 0)
NULL
else
x[[1]]
}
#' @rdname list-access
#' @export
cdr <-
function(x)
{
ret <- x[-1]
if(length(ret) == 0)
NULL
else if(is.pairlist(x))
as.pairlist(ret)
else
ret
}
#' @rdname list-access
#' @export
first <- car
#' @rdname list-access
#' @export
last <- compose(car, reverse)
#' @rdname list-access
#' @export
caar <- compose(car, car)
#' @rdname list-access
#' @export
cadr <- compose(car, cdr)
#' @rdname list-access
#' @export
cdar <- compose(cdr, car)
#' @rdname list-access
#' @export
cddr <- compose(cdr, cdr)
#' @rdname list-access
#' @export
caaar <- compose(car, car, car)
#' @rdname list-access
#' @export
caadr <- compose(car, car, cdr)
#' @rdname list-access
#' @export
cadar <- compose(car, cdr, car)
#' @rdname list-access
#' @export
caddr <- compose(car, cdr, cdr)
#' @rdname list-access
#' @export
cdaar <- compose(cdr, car, car)
#' @rdname list-access
#' @export
cdadr <- compose(cdr, car, cdr)
#' @rdname list-access
#' @export
cddar <- compose(cdr, cdr, car)
#' @rdname list-access
#' @export
cdddr <- compose(cdr, cdr, cdr)
#' @rdname list-access
#' @export
caaaar <- compose(car, car, car, car)
#' @rdname list-access
#' @export
caaadr <- compose(car, car, car, cdr)
#' @rdname list-access
#' @export
caadar <- compose(car, car, cdr, car)
#' @rdname list-access
#' @export
caaddr <- compose(car, car, cdr, cdr)
#' @rdname list-access
#' @export
cadaar <- compose(car, cdr, car, car)
#' @rdname list-access
#' @export
cadadr <- compose(car, cdr, car, cdr)
#' @rdname list-access
#' @export
caddar <- compose(car, cdr, cdr, car)
#' @rdname list-access
#' @export
cadddr <- compose(car, cdr, cdr, cdr)
#' @rdname list-access
#' @export
cdaaar <- compose(cdr, car, car, car)
#' @rdname list-access
#' @export
cdaadr <- compose(cdr, car, car, cdr)
#' @rdname list-access
#' @export
cdadar <- compose(cdr, car, cdr, car)
#' @rdname list-access
#' @export
cdaddr <- compose(cdr, car, cdr, cdr)
#' @rdname list-access
#' @export
cddaar <- compose(cdr, cdr, car, car)
#' @rdname list-access
#' @export
cddadr <- compose(cdr, cdr, car, cdr)
#' @rdname list-access
#' @export
cdddar <- compose(cdr, cdr, cdr, car)
#' @rdname list-access
#' @export
cddddr <- compose(cdr, cdr, cdr, cdr)
| /R/list.R | permissive | wwbrannon/schemeR | R | false | false | 5,656 | r | ## Type-generic list- or vector-processing functions
#' List utilities
#'
#' These functions provide small list- or vector-processing utilities, and in
#' some cases are just aliases for functions in base R. In such cases, the
#' point of the alias is to make the function available under the standard
#' Scheme name.
#'
#' \code{cons} is an alias for base R's \code{\link{c}}, \code{nth} is an alias
#' for \code{\link{[[}}, \code{member} is an alias for \code{\link{\%in\%}},
#' \code{reverse} is an alias for \code{\link{rev}} and \code{is.empty} returns
#' TRUE if and only if its argument is of length 0, returning FALSE otherwise.
#'
#' \code{make.list} returns a list constructed by replicating its expr argument
#' n times. It is equivalent to \code{link{replicate}} with
#' \code{simplify=FALSE}.
#'
#' @param ... Arguments that \code{cons} should pass to \code{c()}.
#' @param x As in \code{\link{\%in\%}} or \code{\link{rev}}.
#' @param table As in \code{\link{\%in\%}}.
#' @param obj An object that is.empty should check the length of.
#' @param n The number of times \code{make.list} should replicate its expr
#' argument in building a list.
#' @param expr An object which \code{make.list} should replicate in building
#' a list.
#'
#' @return
#' \code{make.list} returns the n-length list of replicated expr's. is.empty returns
#' TRUE if its argument is 0-length and FALSE otherwise.
#'
#' @rdname list-utilities
#' @name list-utilities
#' @export
cons <-
function(...)
{
do.call(c, list(...))
}
#' @rdname list-utilities
#' @export
reverse <- rev
#' @rdname list-utilities
#' @export
nth <-
function(obj, n)
{
obj[[n]]
}
#' @rdname list-utilities
#' @export
member <- `%in%`
#' @rdname list-utilities
#' @export
is.empty <- function(obj) length(obj) == 0
#' @rdname list-utilities
#' @export
make.list <-
function(n, expr)
{
#As in base, but with a fixed different value for simplify
sapply(integer(n), eval.parent(substitute(function(...) expr)),
simplify=FALSE)
}
#' List/vector access functions
#'
#' These functions are accessors for various elements and subsequences of lists
#' and vectors. They are written in a type-generic way and will work for any
#' broadly defined sequence type: vectors, lists (aka "generic vectors") and
#' pairlists.
#'
#' Using "sequence" to mean list, other vector or pairlist, the basic functions
#' here are
#' \itemize{
#' \item{car, which returns the first element of a sequence (car(x) is
#' equivalent to x[[1]] for (pair)lists and to x[1] for vectors)}
#' \item{cdr, which returns the sequence consisting of every element but
#' the first, or NULL for a sequence of length 0 or length 1}
#' \item{last, which returns the last element of a sequence}
#' \item{first, which is an alias for car}
#' }
#'
#' There are also a large number of functions of the form cXXXXr, where there
#' are two, three or four "a"'s or "d"'s between the c and r. These functions
#' are compositions of car and cdr: to give one example, \code{caadr(x)} is
#' equivalent to car(car(cdr(x))). All such functions with up to four letters
#' between the c and the r are pre-defined here.
#'
#' @param x The object whose elements or subsequences to access.
#'
#' @return A particular element or subsequence.
#' @rdname list-access
#' @name list-access
#' @export
car <-
function(x)
{
if(length(x) == 0)
NULL
else
x[[1]]
}
#' @rdname list-access
#' @export
cdr <-
function(x)
{
ret <- x[-1]
if(length(ret) == 0)
NULL
else if(is.pairlist(x))
as.pairlist(ret)
else
ret
}
#' @rdname list-access
#' @export
first <- car
#' @rdname list-access
#' @export
last <- compose(car, reverse)
#' @rdname list-access
#' @export
caar <- compose(car, car)
#' @rdname list-access
#' @export
cadr <- compose(car, cdr)
#' @rdname list-access
#' @export
cdar <- compose(cdr, car)
#' @rdname list-access
#' @export
cddr <- compose(cdr, cdr)
#' @rdname list-access
#' @export
caaar <- compose(car, car, car)
#' @rdname list-access
#' @export
caadr <- compose(car, car, cdr)
#' @rdname list-access
#' @export
cadar <- compose(car, cdr, car)
#' @rdname list-access
#' @export
caddr <- compose(car, cdr, cdr)
#' @rdname list-access
#' @export
cdaar <- compose(cdr, car, car)
#' @rdname list-access
#' @export
cdadr <- compose(cdr, car, cdr)
#' @rdname list-access
#' @export
cddar <- compose(cdr, cdr, car)
#' @rdname list-access
#' @export
cdddr <- compose(cdr, cdr, cdr)
#' @rdname list-access
#' @export
caaaar <- compose(car, car, car, car)
#' @rdname list-access
#' @export
caaadr <- compose(car, car, car, cdr)
#' @rdname list-access
#' @export
caadar <- compose(car, car, cdr, car)
#' @rdname list-access
#' @export
caaddr <- compose(car, car, cdr, cdr)
#' @rdname list-access
#' @export
cadaar <- compose(car, cdr, car, car)
#' @rdname list-access
#' @export
cadadr <- compose(car, cdr, car, cdr)
#' @rdname list-access
#' @export
caddar <- compose(car, cdr, cdr, car)
#' @rdname list-access
#' @export
cadddr <- compose(car, cdr, cdr, cdr)
#' @rdname list-access
#' @export
cdaaar <- compose(cdr, car, car, car)
#' @rdname list-access
#' @export
cdaadr <- compose(cdr, car, car, cdr)
#' @rdname list-access
#' @export
cdadar <- compose(cdr, car, cdr, car)
#' @rdname list-access
#' @export
cdaddr <- compose(cdr, car, cdr, cdr)
#' @rdname list-access
#' @export
cddaar <- compose(cdr, cdr, car, car)
#' @rdname list-access
#' @export
cddadr <- compose(cdr, cdr, car, cdr)
#' @rdname list-access
#' @export
cdddar <- compose(cdr, cdr, cdr, car)
#' @rdname list-access
#' @export
cddddr <- compose(cdr, cdr, cdr, cdr)
|
gradientDescent <- function(X, y, theta, alpha){
m = length(y)
for (i in 1:10000) {
h <- X %*% theta
theta1 <- c(0,theta[2:length(theta)])
grad <- (t(X) %*% (h-y) + lambda*theta1)/m
theta = theta - alpha * grad
}
theta
} | /4 - Regularized/Linear Regression/gradientDescent.R | no_license | SynStratos/Pizza_ML | R | false | false | 281 | r | gradientDescent <- function(X, y, theta, alpha){
m = length(y)
for (i in 1:10000) {
h <- X %*% theta
theta1 <- c(0,theta[2:length(theta)])
grad <- (t(X) %*% (h-y) + lambda*theta1)/m
theta = theta - alpha * grad
}
theta
} |
####################################################
## ##
## Global climate and population dynamics ##
## ##
## Prior Predictive Simulation ##
## ##
## Mar 18th 2021 ##
## ##
####################################################
## Simple prior simulations for the parameters of our meta-regression on the
## terrestrial mammals
rm(list = ls())
options(width = 100)
library(tidyverse)
library(ape)
library(brms)
library(ggridges)
# colours
temp_colour <- "#990a80"
precip_colour <- "#287f79"
##____________________________________________________________________________________________________________________________________________________________________________________________________________
#### 1. Load data ####
load("data/mammal_analysis_data_GAM.RData")
glimpse(mam_coef)
glimpse(mamMCC_coef)
glimpse(A_coef)
##____________________________________________________________________________________________________________________________________________________________________________________________________________
#### 2. Intercept PPS ####
set.seed(1000)
# simulate intercepts for the coefficients in a tible
tibble(`Normal(0, 10)\nWeak` = rnorm(n = 500, mean = 0, sd = 10),
`Normal(0, 2)\nMid` = rnorm(n = 500, mean = 0, sd = 2),
`Normal(0, 0.5)\nRegularising` = rnorm(n = 500, mean = 0, sd = 0.5),
row = 1:500) %>%
# pivot longer and put them with raw data
pivot_longer(-row) %>%
bind_rows(tibble(row = rep(1:nrow(mam_coef), 2),
name = rep(c("Raw\ntemperature\ncoefficient\ndata",
"Raw\nprecipitation\ncoefficient\ndata"),
each = nrow(mam_coef)),
value = c(mam_coef$coef_temp, mam_coef$coef_precip))) %>%
mutate(name = factor(name, levels = c("Raw\ntemperature\ncoefficient\ndata",
"Raw\nprecipitation\ncoefficient\ndata",
"Normal(0, 10)\nWeak",
"Normal(0, 2)\nMid",
"Normal(0, 0.5)\nRegularising"))) %>%
ggplot(aes(x = value, fill = name, y = name)) +
geom_density_ridges(show.legend = F, size = 0.2) +
labs(x = expression(paste("Weather coefficient - Global intercept value ", bar(alpha))),
y = NULL) +
coord_cartesian(xlim = c(-10,10)) +
theme_bw(base_size = 14) +
theme(panel.grid = element_blank()) +
ggsave("plots/meta_regression/prior_predictive_simulation/weather_coefficient_pps.jpeg",
width = 15, height = 13, units = "cm", dpi = 500)
##____________________________________________________________________________________________________________________________________________________________________________________________________________
#### 3. Beta difference effects ####
# Raw data - pairwise estimates of records as a baseline
raw_dat_diffs <- tibble(name = "Raw\npairwise\ncoefficient\ndifferences",
value = apply(combn(mam_coef$coef_temp,2), 2, diff))
set.seed(1000)
# Prior simulation - normal beta priors
tibble(`Normal(0, 10)\nWeak` = rnorm(n = 500, mean = 0, sd = 10),
`Normal(0, 2)\nMid` = rnorm(n = 500, mean = 0, sd = 2),
`Normal(0, 0.5)\nRegularising` = rnorm(n = 500, mean = 0, sd = 0.5)) %>%
pivot_longer(cols = 1:3) %>%
bind_rows(raw_dat_diffs) %>%
mutate(name = factor(name, levels = c("Raw\npairwise\ncoefficient\ndifferences",
"Normal(0, 10)\nWeak",
"Normal(0, 2)\nMid",
"Normal(0, 0.5)\nRegularising"))) %>%
ggplot(aes(x = name, y = value, fill = name)) +
geom_violin(show.legend = F, size = 0.2) +
coord_cartesian(ylim = c(-10,10)) +
labs(x = NULL, y = "Differences in weather coefficients") +
theme_bw(base_size = 14) +
theme(panel.grid = element_blank()) +
ggsave("plots/meta_regression/prior_predictive_simulation/coefficient_differences_beta.jpeg",
width = 15, height = 13, units = "cm", dpi = 500)
##____________________________________________________________________________________________________________________________________________________________________________________________________________
#### 3. Simulated life-history effects ####
# Simple linear lognormal model
set.seed(1000)
tibble(sim = rep(1:100, each = 50),
life_history = rep(seq(-2,2,length.out = 50), times = 100),
# simulate life-history slopes on linear predictor scale using normal
beta_weak = rep(rnorm(100, 0, 10), each = 50),
beta_mid = rep(rnorm(100, 0, 2), each = 50),
beta_reg = rep(rnorm(100, 0, 0.5), each = 50)) %>%
# predictions with a back-transformation
mutate(`Normal(0, 10)\nWeak` = exp(beta_weak*life_history),
`Normal(0, 2)\nMid` = exp(beta_mid*life_history),
`Normal(0, 0.5)\nRegularising` = exp(beta_reg*life_history)) %>%
dplyr::select(-c(beta_weak, beta_mid, beta_reg)) %>%
pivot_longer(-c(life_history, sim)) %>%
filter(value < 100) %>%
mutate(name = factor(name, levels = c("Normal(0, 10)\nWeak",
"Normal(0, 2)\nMid",
"Normal(0, 0.5)\nRegularising"))) %>%
ggplot(aes(x = life_history, y = value, group = sim, colour = name)) +
geom_line(alpha = 0.5, show.legend = F) +
geom_hline(yintercept = max(mam_coef$abs_temp)) +
geom_hline(yintercept = max(mam_coef$abs_precip, na.rm = TRUE), linetype = "dashed") +
labs(x = "Standardised life-history value", y = "|Weather coefficient|") +
facet_wrap(~name, scales = "free") +
theme_bw(base_size = 14) +
theme(panel.grid = element_blank(),
strip.background = element_blank()) +
ggsave(filename = "plots/meta_regression/prior_predictive_simulation/life_history_effect_pps.jpeg",
width = 26, height = 13, units = "cm", dpi = 500)
##____________________________________________________________________________________________________________________________________________________________________________________________________________
#### 4. Error terms - Exponential priors ####
# Simulate exponentials with different rates
rates <- c(0.5,1,2,5,10,20)
exp_dat <- tibble(rate = rep(rates, each = 500),
value = 0)
for(i in rates){
exp_dat[exp_dat$rate == i,]$value <- rexp(500, rate = i)
}
ggplot(exp_dat, aes(x = value, y = as.factor(rate),
fill = as.factor(rate))) +
geom_density_ridges(show.legend = F, rel_min_height=0.005, size = 0.2) +
geom_vline(xintercept = 1) +
labs(x = "Random effect variance term value", y = "Exponential rate") +
theme_bw(base_size = 14) +
theme(panel.grid = element_blank()) +
ggsave("plots/meta_regression/prior_predictive_simulation/random_effect_variance_pps.jpeg",
width = 17, height = 9, units = "cm", dpi = 500)
| /meta_regression/testing_and_prior_predictive_simulation/prior_predictive_simulation.R | no_license | jjackson-eco/mammal_weather_lifehistory | R | false | false | 7,198 | r | ####################################################
## ##
## Global climate and population dynamics ##
## ##
## Prior Predictive Simulation ##
## ##
## Mar 18th 2021 ##
## ##
####################################################
## Simple prior simulations for the parameters of our meta-regression on the
## terrestrial mammals
rm(list = ls())
options(width = 100)
library(tidyverse)
library(ape)
library(brms)
library(ggridges)
# colours
temp_colour <- "#990a80"
precip_colour <- "#287f79"
##____________________________________________________________________________________________________________________________________________________________________________________________________________
#### 1. Load data ####
load("data/mammal_analysis_data_GAM.RData")
glimpse(mam_coef)
glimpse(mamMCC_coef)
glimpse(A_coef)
##____________________________________________________________________________________________________________________________________________________________________________________________________________
#### 2. Intercept PPS ####
set.seed(1000)
# simulate intercepts for the coefficients in a tible
tibble(`Normal(0, 10)\nWeak` = rnorm(n = 500, mean = 0, sd = 10),
`Normal(0, 2)\nMid` = rnorm(n = 500, mean = 0, sd = 2),
`Normal(0, 0.5)\nRegularising` = rnorm(n = 500, mean = 0, sd = 0.5),
row = 1:500) %>%
# pivot longer and put them with raw data
pivot_longer(-row) %>%
bind_rows(tibble(row = rep(1:nrow(mam_coef), 2),
name = rep(c("Raw\ntemperature\ncoefficient\ndata",
"Raw\nprecipitation\ncoefficient\ndata"),
each = nrow(mam_coef)),
value = c(mam_coef$coef_temp, mam_coef$coef_precip))) %>%
mutate(name = factor(name, levels = c("Raw\ntemperature\ncoefficient\ndata",
"Raw\nprecipitation\ncoefficient\ndata",
"Normal(0, 10)\nWeak",
"Normal(0, 2)\nMid",
"Normal(0, 0.5)\nRegularising"))) %>%
ggplot(aes(x = value, fill = name, y = name)) +
geom_density_ridges(show.legend = F, size = 0.2) +
labs(x = expression(paste("Weather coefficient - Global intercept value ", bar(alpha))),
y = NULL) +
coord_cartesian(xlim = c(-10,10)) +
theme_bw(base_size = 14) +
theme(panel.grid = element_blank()) +
ggsave("plots/meta_regression/prior_predictive_simulation/weather_coefficient_pps.jpeg",
width = 15, height = 13, units = "cm", dpi = 500)
##____________________________________________________________________________________________________________________________________________________________________________________________________________
#### 3. Beta difference effects ####
# Raw data - pairwise estimates of records as a baseline
raw_dat_diffs <- tibble(name = "Raw\npairwise\ncoefficient\ndifferences",
value = apply(combn(mam_coef$coef_temp,2), 2, diff))
set.seed(1000)
# Prior simulation - normal beta priors
tibble(`Normal(0, 10)\nWeak` = rnorm(n = 500, mean = 0, sd = 10),
`Normal(0, 2)\nMid` = rnorm(n = 500, mean = 0, sd = 2),
`Normal(0, 0.5)\nRegularising` = rnorm(n = 500, mean = 0, sd = 0.5)) %>%
pivot_longer(cols = 1:3) %>%
bind_rows(raw_dat_diffs) %>%
mutate(name = factor(name, levels = c("Raw\npairwise\ncoefficient\ndifferences",
"Normal(0, 10)\nWeak",
"Normal(0, 2)\nMid",
"Normal(0, 0.5)\nRegularising"))) %>%
ggplot(aes(x = name, y = value, fill = name)) +
geom_violin(show.legend = F, size = 0.2) +
coord_cartesian(ylim = c(-10,10)) +
labs(x = NULL, y = "Differences in weather coefficients") +
theme_bw(base_size = 14) +
theme(panel.grid = element_blank()) +
ggsave("plots/meta_regression/prior_predictive_simulation/coefficient_differences_beta.jpeg",
width = 15, height = 13, units = "cm", dpi = 500)
##____________________________________________________________________________________________________________________________________________________________________________________________________________
#### 3. Simulated life-history effects ####
# Simple linear lognormal model
set.seed(1000)
tibble(sim = rep(1:100, each = 50),
life_history = rep(seq(-2,2,length.out = 50), times = 100),
# simulate life-history slopes on linear predictor scale using normal
beta_weak = rep(rnorm(100, 0, 10), each = 50),
beta_mid = rep(rnorm(100, 0, 2), each = 50),
beta_reg = rep(rnorm(100, 0, 0.5), each = 50)) %>%
# predictions with a back-transformation
mutate(`Normal(0, 10)\nWeak` = exp(beta_weak*life_history),
`Normal(0, 2)\nMid` = exp(beta_mid*life_history),
`Normal(0, 0.5)\nRegularising` = exp(beta_reg*life_history)) %>%
dplyr::select(-c(beta_weak, beta_mid, beta_reg)) %>%
pivot_longer(-c(life_history, sim)) %>%
filter(value < 100) %>%
mutate(name = factor(name, levels = c("Normal(0, 10)\nWeak",
"Normal(0, 2)\nMid",
"Normal(0, 0.5)\nRegularising"))) %>%
ggplot(aes(x = life_history, y = value, group = sim, colour = name)) +
geom_line(alpha = 0.5, show.legend = F) +
geom_hline(yintercept = max(mam_coef$abs_temp)) +
geom_hline(yintercept = max(mam_coef$abs_precip, na.rm = TRUE), linetype = "dashed") +
labs(x = "Standardised life-history value", y = "|Weather coefficient|") +
facet_wrap(~name, scales = "free") +
theme_bw(base_size = 14) +
theme(panel.grid = element_blank(),
strip.background = element_blank()) +
ggsave(filename = "plots/meta_regression/prior_predictive_simulation/life_history_effect_pps.jpeg",
width = 26, height = 13, units = "cm", dpi = 500)
##____________________________________________________________________________________________________________________________________________________________________________________________________________
#### 4. Error terms - Exponential priors ####
# Simulate exponentials with different rates
rates <- c(0.5,1,2,5,10,20)
exp_dat <- tibble(rate = rep(rates, each = 500),
value = 0)
for(i in rates){
exp_dat[exp_dat$rate == i,]$value <- rexp(500, rate = i)
}
ggplot(exp_dat, aes(x = value, y = as.factor(rate),
fill = as.factor(rate))) +
geom_density_ridges(show.legend = F, rel_min_height=0.005, size = 0.2) +
geom_vline(xintercept = 1) +
labs(x = "Random effect variance term value", y = "Exponential rate") +
theme_bw(base_size = 14) +
theme(panel.grid = element_blank()) +
ggsave("plots/meta_regression/prior_predictive_simulation/random_effect_variance_pps.jpeg",
width = 17, height = 9, units = "cm", dpi = 500)
|
library(dplyr)
library(lubridate)
## English by default
Sys.setlocale("LC_ALL", "English")
data <- read.csv("household_power_consumption.txt", sep=";", stringsAsFactors = FALSE, na.strings="?")
#Convert date column from chr to Date class
data[, c(1)] <- as.Date(data[, c(1)], format="%d/%m/%Y")
##Select only two days in February
february <- filter(data, Date == "2007-02-01" | Date == "2007-02-02")
## complete data frame not needed anymore
rm(data)
## Create new variable with date time
february <- mutate(february, Datetime=paste(as.character(Date), Time))
february[, c(10)] <- ymd_hms(february$Datetime)
##change graphics device to png
png("plot2.png", width=480, height=480, units="px")
## Plot type line
with(february, plot(Datetime,Global_active_power, type="l", xlab="", ylab="Global Active Power (kilowatts)"))
##Close device graphic
dev.off()
| /plot2.R | no_license | RODCAR0/ExData_Plotting1 | R | false | false | 862 | r | library(dplyr)
library(lubridate)
## English by default
Sys.setlocale("LC_ALL", "English")
data <- read.csv("household_power_consumption.txt", sep=";", stringsAsFactors = FALSE, na.strings="?")
#Convert date column from chr to Date class
data[, c(1)] <- as.Date(data[, c(1)], format="%d/%m/%Y")
##Select only two days in February
february <- filter(data, Date == "2007-02-01" | Date == "2007-02-02")
## complete data frame not needed anymore
rm(data)
## Create new variable with date time
february <- mutate(february, Datetime=paste(as.character(Date), Time))
february[, c(10)] <- ymd_hms(february$Datetime)
##change graphics device to png
png("plot2.png", width=480, height=480, units="px")
## Plot type line
with(february, plot(Datetime,Global_active_power, type="l", xlab="", ylab="Global Active Power (kilowatts)"))
##Close device graphic
dev.off()
|
library(micropan)
### Name: plot.Binomix
### Title: Plot and summary of 'Binomix' objects
### Aliases: plot.Binomix summary.Binomix
### ** Examples
# See examples in the Help-file for binomixEstimate.
| /data/genthat_extracted_code/micropan/examples/generic.Binomix.Rd.R | no_license | surayaaramli/typeRrh | R | false | false | 209 | r | library(micropan)
### Name: plot.Binomix
### Title: Plot and summary of 'Binomix' objects
### Aliases: plot.Binomix summary.Binomix
### ** Examples
# See examples in the Help-file for binomixEstimate.
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/lgb.Booster.R
\name{predict.lgb.Booster}
\alias{predict.lgb.Booster}
\title{Predict method for LightGBM model}
\usage{
\method{predict}{lgb.Booster}(
object,
data,
start_iteration = NULL,
num_iteration = NULL,
rawscore = FALSE,
predleaf = FALSE,
predcontrib = FALSE,
header = FALSE,
reshape = FALSE,
params = list(),
...
)
}
\arguments{
\item{object}{Object of class \code{lgb.Booster}}
\item{data}{a \code{matrix} object, a \code{dgCMatrix} object or
a character representing a path to a text file (CSV, TSV, or LibSVM)}
\item{start_iteration}{int or None, optional (default=None)
Start index of the iteration to predict.
If None or <= 0, starts from the first iteration.}
\item{num_iteration}{int or None, optional (default=None)
Limit number of iterations in the prediction.
If None, if the best iteration exists and start_iteration is None or <= 0, the
best iteration is used; otherwise, all iterations from start_iteration are used.
If <= 0, all iterations from start_iteration are used (no limits).}
\item{rawscore}{whether the prediction should be returned in the for of original untransformed
sum of predictions from boosting iterations' results. E.g., setting \code{rawscore=TRUE}
for logistic regression would result in predictions for log-odds instead of probabilities.}
\item{predleaf}{whether predict leaf index instead.}
\item{predcontrib}{return per-feature contributions for each record.}
\item{header}{only used for prediction for text file. True if text file has header}
\item{reshape}{whether to reshape the vector of predictions to a matrix form when there are several
prediction outputs per case.}
\item{params}{a list of additional named parameters. See
\href{https://lightgbm.readthedocs.io/en/latest/Parameters.html#predict-parameters}{
the "Predict Parameters" section of the documentation} for a list of parameters and
valid values.}
\item{...}{Additional prediction parameters. NOTE: deprecated as of v3.3.0. Use \code{params} instead.}
}
\value{
For regression or binary classification, it returns a vector of length \code{nrows(data)}.
For multiclass classification, either a \code{num_class * nrows(data)} vector or
a \code{(nrows(data), num_class)} dimension matrix is returned, depending on
the \code{reshape} value.
When \code{predleaf = TRUE}, the output is a matrix object with the
number of columns corresponding to the number of trees.
}
\description{
Predicted values based on class \code{lgb.Booster}
}
\examples{
\donttest{
data(agaricus.train, package = "lightgbm")
train <- agaricus.train
dtrain <- lgb.Dataset(train$data, label = train$label)
data(agaricus.test, package = "lightgbm")
test <- agaricus.test
dtest <- lgb.Dataset.create.valid(dtrain, test$data, label = test$label)
params <- list(objective = "regression", metric = "l2")
valids <- list(test = dtest)
model <- lgb.train(
params = params
, data = dtrain
, nrounds = 5L
, valids = valids
, min_data = 1L
, learning_rate = 1.0
)
preds <- predict(model, test$data)
# pass other prediction parameters
predict(
model,
test$data,
params = list(
predict_disable_shape_check = TRUE
)
)
}
}
| /R-package/man/predict.lgb.Booster.Rd | permissive | makemebitter/LightGBM | R | false | true | 3,275 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/lgb.Booster.R
\name{predict.lgb.Booster}
\alias{predict.lgb.Booster}
\title{Predict method for LightGBM model}
\usage{
\method{predict}{lgb.Booster}(
object,
data,
start_iteration = NULL,
num_iteration = NULL,
rawscore = FALSE,
predleaf = FALSE,
predcontrib = FALSE,
header = FALSE,
reshape = FALSE,
params = list(),
...
)
}
\arguments{
\item{object}{Object of class \code{lgb.Booster}}
\item{data}{a \code{matrix} object, a \code{dgCMatrix} object or
a character representing a path to a text file (CSV, TSV, or LibSVM)}
\item{start_iteration}{int or None, optional (default=None)
Start index of the iteration to predict.
If None or <= 0, starts from the first iteration.}
\item{num_iteration}{int or None, optional (default=None)
Limit number of iterations in the prediction.
If None, if the best iteration exists and start_iteration is None or <= 0, the
best iteration is used; otherwise, all iterations from start_iteration are used.
If <= 0, all iterations from start_iteration are used (no limits).}
\item{rawscore}{whether the prediction should be returned in the for of original untransformed
sum of predictions from boosting iterations' results. E.g., setting \code{rawscore=TRUE}
for logistic regression would result in predictions for log-odds instead of probabilities.}
\item{predleaf}{whether predict leaf index instead.}
\item{predcontrib}{return per-feature contributions for each record.}
\item{header}{only used for prediction for text file. True if text file has header}
\item{reshape}{whether to reshape the vector of predictions to a matrix form when there are several
prediction outputs per case.}
\item{params}{a list of additional named parameters. See
\href{https://lightgbm.readthedocs.io/en/latest/Parameters.html#predict-parameters}{
the "Predict Parameters" section of the documentation} for a list of parameters and
valid values.}
\item{...}{Additional prediction parameters. NOTE: deprecated as of v3.3.0. Use \code{params} instead.}
}
\value{
For regression or binary classification, it returns a vector of length \code{nrows(data)}.
For multiclass classification, either a \code{num_class * nrows(data)} vector or
a \code{(nrows(data), num_class)} dimension matrix is returned, depending on
the \code{reshape} value.
When \code{predleaf = TRUE}, the output is a matrix object with the
number of columns corresponding to the number of trees.
}
\description{
Predicted values based on class \code{lgb.Booster}
}
\examples{
\donttest{
data(agaricus.train, package = "lightgbm")
train <- agaricus.train
dtrain <- lgb.Dataset(train$data, label = train$label)
data(agaricus.test, package = "lightgbm")
test <- agaricus.test
dtest <- lgb.Dataset.create.valid(dtrain, test$data, label = test$label)
params <- list(objective = "regression", metric = "l2")
valids <- list(test = dtest)
model <- lgb.train(
params = params
, data = dtrain
, nrounds = 5L
, valids = valids
, min_data = 1L
, learning_rate = 1.0
)
preds <- predict(model, test$data)
# pass other prediction parameters
predict(
model,
test$data,
params = list(
predict_disable_shape_check = TRUE
)
)
}
}
|
uBlogSavePlot <- function(widget,
file_name) {
# Summary: A function to specifically be used with
# the u_blog developed by Anala (https://github.com/anala-gossai/u_blog)
# that takes and html widget, saves it to the appropriate
# blog folder, and then resets the working directory.
# Arg:
# widget: the name of the widget object (can also
# be piped using %>%)
# file_name: the name of the file the widget is
# to be saved as (e.g., "plot")
# Output: the HTML widget in Anala's static/figures
# blog directory
# Example:
# please see use cases at
# https://github.com/anala-gossai/u_blog
require(htmlwidgets)
currentWD <- getwd()
setwd("/Users/analagossai/u_blog/static")
if(dir.exists("figures") == FALSE) {
dir.create("figures",
showWarnings = FALSE)
}
setwd("figures")
saveWidget(widget,
paste0(file_name, ".html"),
selfcontained = TRUE)
setwd(currentWD)
}
| /uBlogSavePlot.R | no_license | anala-gossai/fun_ctions | R | false | false | 1,106 | r | uBlogSavePlot <- function(widget,
file_name) {
# Summary: A function to specifically be used with
# the u_blog developed by Anala (https://github.com/anala-gossai/u_blog)
# that takes and html widget, saves it to the appropriate
# blog folder, and then resets the working directory.
# Arg:
# widget: the name of the widget object (can also
# be piped using %>%)
# file_name: the name of the file the widget is
# to be saved as (e.g., "plot")
# Output: the HTML widget in Anala's static/figures
# blog directory
# Example:
# please see use cases at
# https://github.com/anala-gossai/u_blog
require(htmlwidgets)
currentWD <- getwd()
setwd("/Users/analagossai/u_blog/static")
if(dir.exists("figures") == FALSE) {
dir.create("figures",
showWarnings = FALSE)
}
setwd("figures")
saveWidget(widget,
paste0(file_name, ".html"),
selfcontained = TRUE)
setwd(currentWD)
}
|
#' ---
#' title: "Metanálise básio quando os resultados (outcomes) são dados continuos"
#' author: "Geiser Chalco <geiser@alumni.usp.br>"
#' date: "5/14/2021"
#'
#'
#' Prerequisitos:
#'
#' - Instalar R: [https://vps.fmvz.usp.br/CRAN/](https://vps.fmvz.usp.br/CRAN/)
#' - Instalar r-studio: [https://www.rstudio.com/products/rstudio/](https://www.rstudio.com/products/rstudio/)
#' # Instalar e carregar pacotes de R necessários
## ------------------------------------------------------------------------------------------------------
install.packages(setdiff(c('meta','metafor','esc','readxl','devtools'), rownames(installed.packages())))
if (!"dmetar" %in% rownames(installed.packages())) {
devtools::install_github("MathiasHarrer/dmetar")
}
library(readxl)
library(meta)
library(metafor)
library(dmetar)
library(esc)
#' # Step 1: Carregar os dados na variável madata
## ------------------------------------------------------------------------------------------------------
madata <- read_excel("raw-data.xlsx", sheet = "sheet")
#' # Step 2: Condução da metanálises sem remover outlier
## ------------------------------------------------------------------------------------------------------
(m.raw <- metacont(Ne, Me, Se, Nc, Mc, Sc, data = madata
, studlab = paste(Author)
, comb.fixed = F, comb.random = T
, sm = "SMD"))
#' # Step 3: Exclusão de outliers
## ------------------------------------------------------------------------------------------------------
#' ## Identificação de outliers mediante Método GOSH
#' Calculo de tamanho de efeito mediante a função `effsize`
effsize <- esc_mean_sd(madata$Me, madata$Se, madata$Ne,
madata$Mc, madata$Sc, madata$Nc, es.type = "g")
madata["TE"] <- effsize$es
madata["seTE"] <- effsize$se
#' Cálcular a metaregresión
m.rma <- rma(yi = madata$TE, sei = madata$seTE)
#' Empregar a função `gosh`
dat.gosh <- gosh(m.rma)
(gda.out <- gosh.diagnostics(dat.gosh))
plot(gda.out$km.plot)
plot(gda.out$db.plot)
plot(gda.out$gmm.plot)
#' ## Efeituar metanálise sem outliers
(m <- metacont(Ne, Me, Se, Nc, Mc, Sc, data = madata
, studlab = paste(Author)
, exclude = c(15,6,18,4)
, comb.fixed = F, comb.random = T
, sm = "SMD"))
#' # Step 4: Forest plot da metanálise sem outliers
## ------------------------------------------------------------------------------------------------------
forest(m, digits=2, digits.sd = 2, test.overall = T, lab.e = "Intervention")
#' # Step 5: Metanálises usando subgrupos
## ------------------------------------------------------------------------------------------------------
#' ## Metanálises agrupando estudos por: população
(m.sg4p <- update.meta(m, byvar=population, comb.random = T, comb.fixed = F))
forest(m.sg4p, digits=2, digits.sd = 2, test.overall = T, lab.e = "Intervention")
#' ## Metanálises agrupando estudos por: contexto
(m.sg4ctx <- update.meta(m, byvar=context, comb.random = T, comb.fixed = F))
forest(m.sg4ctx, digits=2, digits.sd = 2, test.overall = T, lab.e = "Intervention")
#' ## Metanálises agrupando estudos por: duração
(m.sg4d <- subgroup.analysis.mixed.effects(x = m, subgroups = madata$duration))
forest(m.sg4d, digits=2, digits.sd = 2, test.overall = T, lab.e = "Intervention")
#' ## Metanálises agrupando estudos por: intervention
(m.sg4i <- update.meta(m, byvar=intervention, comb.random = T, comb.fixed = F))
forest(m.sg4i, digits=2, digits.sd = 2, test.overall = T, lab.e = "Intervention")
#' ## Metanálises agrupando estudos por: control
(m.sg4c <- update.meta(m, byvar=control, comb.random = T, comb.fixed = F))
forest(m.sg4c, digits=2, digits.sd = 2, test.overall = T, lab.e = "Intervention")
#' ## Metanálises agrupando estudos por: instrumento (usado para medir)
(m.sg4ins <- update.meta(m, byvar=instrument, comb.random = T, comb.fixed = F))
forest(m.sg4ins, digits=2, digits.sd = 2, test.overall = T, lab.e = "Intervention")
#' # Step 6: Análises de viés de publicação usando Funel plot
## ------------------------------------------------------------------------------------------------------
funnel(m, xlab = "Hedges' g", studlab = T)
summary(eggers.test(x = m))
| /simple-for-continuous-data.R | permissive | geiser/example-meta-analysis | R | false | false | 4,290 | r | #' ---
#' title: "Metanálise básio quando os resultados (outcomes) são dados continuos"
#' author: "Geiser Chalco <geiser@alumni.usp.br>"
#' date: "5/14/2021"
#'
#'
#' Prerequisitos:
#'
#' - Instalar R: [https://vps.fmvz.usp.br/CRAN/](https://vps.fmvz.usp.br/CRAN/)
#' - Instalar r-studio: [https://www.rstudio.com/products/rstudio/](https://www.rstudio.com/products/rstudio/)
#' # Instalar e carregar pacotes de R necessários
## ------------------------------------------------------------------------------------------------------
install.packages(setdiff(c('meta','metafor','esc','readxl','devtools'), rownames(installed.packages())))
if (!"dmetar" %in% rownames(installed.packages())) {
devtools::install_github("MathiasHarrer/dmetar")
}
library(readxl)
library(meta)
library(metafor)
library(dmetar)
library(esc)
#' # Step 1: Carregar os dados na variável madata
## ------------------------------------------------------------------------------------------------------
madata <- read_excel("raw-data.xlsx", sheet = "sheet")
#' # Step 2: Condução da metanálises sem remover outlier
## ------------------------------------------------------------------------------------------------------
(m.raw <- metacont(Ne, Me, Se, Nc, Mc, Sc, data = madata
, studlab = paste(Author)
, comb.fixed = F, comb.random = T
, sm = "SMD"))
#' # Step 3: Exclusão de outliers
## ------------------------------------------------------------------------------------------------------
#' ## Identificação de outliers mediante Método GOSH
#' Calculo de tamanho de efeito mediante a função `effsize`
effsize <- esc_mean_sd(madata$Me, madata$Se, madata$Ne,
madata$Mc, madata$Sc, madata$Nc, es.type = "g")
madata["TE"] <- effsize$es
madata["seTE"] <- effsize$se
#' Cálcular a metaregresión
m.rma <- rma(yi = madata$TE, sei = madata$seTE)
#' Empregar a função `gosh`
dat.gosh <- gosh(m.rma)
(gda.out <- gosh.diagnostics(dat.gosh))
plot(gda.out$km.plot)
plot(gda.out$db.plot)
plot(gda.out$gmm.plot)
#' ## Efeituar metanálise sem outliers
(m <- metacont(Ne, Me, Se, Nc, Mc, Sc, data = madata
, studlab = paste(Author)
, exclude = c(15,6,18,4)
, comb.fixed = F, comb.random = T
, sm = "SMD"))
#' # Step 4: Forest plot da metanálise sem outliers
## ------------------------------------------------------------------------------------------------------
forest(m, digits=2, digits.sd = 2, test.overall = T, lab.e = "Intervention")
#' # Step 5: Metanálises usando subgrupos
## ------------------------------------------------------------------------------------------------------
#' ## Metanálises agrupando estudos por: população
(m.sg4p <- update.meta(m, byvar=population, comb.random = T, comb.fixed = F))
forest(m.sg4p, digits=2, digits.sd = 2, test.overall = T, lab.e = "Intervention")
#' ## Metanálises agrupando estudos por: contexto
(m.sg4ctx <- update.meta(m, byvar=context, comb.random = T, comb.fixed = F))
forest(m.sg4ctx, digits=2, digits.sd = 2, test.overall = T, lab.e = "Intervention")
#' ## Metanálises agrupando estudos por: duração
(m.sg4d <- subgroup.analysis.mixed.effects(x = m, subgroups = madata$duration))
forest(m.sg4d, digits=2, digits.sd = 2, test.overall = T, lab.e = "Intervention")
#' ## Metanálises agrupando estudos por: intervention
(m.sg4i <- update.meta(m, byvar=intervention, comb.random = T, comb.fixed = F))
forest(m.sg4i, digits=2, digits.sd = 2, test.overall = T, lab.e = "Intervention")
#' ## Metanálises agrupando estudos por: control
(m.sg4c <- update.meta(m, byvar=control, comb.random = T, comb.fixed = F))
forest(m.sg4c, digits=2, digits.sd = 2, test.overall = T, lab.e = "Intervention")
#' ## Metanálises agrupando estudos por: instrumento (usado para medir)
(m.sg4ins <- update.meta(m, byvar=instrument, comb.random = T, comb.fixed = F))
forest(m.sg4ins, digits=2, digits.sd = 2, test.overall = T, lab.e = "Intervention")
#' # Step 6: Análises de viés de publicação usando Funel plot
## ------------------------------------------------------------------------------------------------------
funnel(m, xlab = "Hedges' g", studlab = T)
summary(eggers.test(x = m))
|
library(tidyverse)
library(maps)
library(albersusa)#installed via github
library(ggmap)
library(RColorBrewer)
setwd("/Users/aradhyakasat/Documents/DataScience/")
data = read.csv("NewYorkCrimeDataAnalysis2019/Data/ArrestData2.csv")
data2 = read.csv("NewYorkCrimeDataAnalysis2019/Data/ArrestData3.csv")
table(data$PD_DESC)
table(data$OFNS_DESC)
barplot(table(data2$AGE_GROUP),col = rainbow(20),ylim=c(0,50000),xlab="Age Group",ylab="No. of Crimes",main="Age Group vs No. of crimes")
barplot(table(data2$ARREST_BORO),col = rainbow(20),ylim=c(0,50000),xlab="Boro",ylab="No. of Crimes",main="Boro vs No. of crimes")
barplot(table(data2$PERP_SEX),col = rainbow(20),ylim=c(0,80000),xlab="Sex",ylab="No. of Crimes",main="Sex vs No. of crimes")
barplot(table(data2$PERP_RACE),col = rainbow(20),ylim=c(0,50000),xlab="Race",ylab="No. of Crimes",main="Race vs No. of crimes",cex.names = 0.5)
table(data2$AGE_GROUP,data2$OFNS_DESC)
table(data2$PERP_SEX,data2$OFNS_DESC)
table(data2$PERP_RACE,data2$OFNS_DESC)
table(data2$JURISDICTION_CODE)
table(data2$ARREST_PRECINCT)
mosaicplot(table(data$PERP_SEX,data$AGE_GROUP),xlab ='Gender',ylab='Age Group',col=c(2,3,4))
#Please set your google maps api key to use
ggmap::register_google(key = "")
p <- ggmap(get_googlemap(center = c(lon = -74.0060, lat = 40.7128),
zoom = 10, scale = 2,
maptype ='terrain',
color = 'color'))
p + geom_point(aes(x =Longitude , y = Latitude, color=data$ARREST_BORO),data=data, alpha=0.25,size = 0.5) +
theme(legend.position="bottom")
p + geom_point(aes(x =Longitude , y = Latitude, color=data$PERP_SEX),data=data, alpha=0.25,size = 0.5) +
theme(legend.position="bottom")
p + geom_point(aes(x =Longitude , y = Latitude, color=data$OFNS_DESC),data=data, alpha=0.25,size = 0.5) +
theme(legend.position="bottom")
p + geom_point(aes(x =Longitude , y = Latitude, color=data$PERP_RACE),data=data, alpha=0.25,size = 0.5) +
theme(legend.position="bottom")
p + geom_point(aes(x =Longitude , y = Latitude, color=data$AGE_GROUP),data=data, alpha=0.25,size = 0.5) +
theme(legend.position="bottom")
data2_plot = data2
table(data2_plot$ARREST_BORO)
for(i in 1:nrow(data2_plot)){
if(data2_plot$ARREST_BORO[i]==1){
data2_plot$ARREST_BORO[i] = 'B';
}
else if(data2_plot$ARREST_BORO[i]==2){
data2_plot$ARREST_BORO[i] = 'K';
}
else if(data2_plot$ARREST_BORO[i]==3){
data2_plot$ARREST_BORO[i] = 'M';
}
else if(data2_plot$ARREST_BORO[i]==4){
data2_plot$ARREST_BORO[i]='Q';
}
else if(data2_plot$ARREST_BORO[i]==5){
data2_plot$ARREST_BORO[i] = 'S'
}
}
plot_data_2014 = subset(data2_plot,data2_plot$ARREST_YEAR==2014)
plot_data_2015 = subset(data2_plot,data2_plot$ARREST_YEAR==2015)
plot_data_2016 = subset(data2_plot,data2_plot$ARREST_YEAR==2016)
plot_data_2017 = subset(data2_plot,data2_plot$ARREST_YEAR==2017)
p + geom_point(aes(x =Longitude , y = Latitude, color=plot_data_2014$ARREST_BORO),data=plot_data_2014, alpha=0.25,size = 0.5) +
theme(legend.position="bottom")
p + geom_point(aes(x =Longitude , y = Latitude, color=plot_data_2015$ARREST_BORO),data=plot_data_2015, alpha=0.25,size = 0.5) +
theme(legend.position="bottom")
p + geom_point(aes(x =Longitude , y = Latitude, color=plot_data_2016$ARREST_BORO),data=plot_data_2016, alpha=0.25,size = 0.5) +
theme(legend.position="bottom")
p + geom_point(aes(x =Longitude , y = Latitude, color=plot_data_2017$ARREST_BORO),data=plot_data_2017, alpha=0.25,size = 0.5) +
theme(legend.position="bottom")
plot_data_sex = subset(data,data$PERP_SEX=='F')
p + geom_point(aes(x =Longitude , y = Latitude, color=plot_data_sex$ARREST_BORO),data=plot_data_sex, alpha=0.25,size = 0.5) +
theme(legend.position="bottom")
plot_data_sex_male = subset(data,data$PERP_SEX=='M')
p + geom_point(aes(x =Longitude , y = Latitude, color=plot_data_sex_male$ARREST_BORO),data=plot_data_sex_male, alpha=0.25,size = 0.5) +
theme(legend.position="bottom")
res <- revgeocode(lonlat_sample, output="more")
# can then access zip and neighborhood where populated
res$postal_code
res$neighborhood
#Type of crimes bar plot
ggplot(data=data,aes(x=data$OFNS_DESC),fill=interaction(data$PERP_SEX))+geom_bar()+scale_fill_brewer(palette = "Set1") +coord_flip()
ggplot(data=data,aes(x=data$AGE_GROUP),fill=interaction(data$PERP_SEX))+geom_bar()+scale_fill_brewer(palette = "Set1") +coord_flip()
ggplot(data=data,aes(x=data$PERP_SEX))+geom_bar()+scale_fill_brewer(palette = "Set1") +coord_flip()
ggplot(data=data,aes(x=data$PERP_RACE))+geom_bar()+scale_fill_brewer(palette = "Set1") +coord_flip()
year_ts=table(data2$ARREST_YEAR)
year_ts = data.frame(year_ts)
ggplot()+geom_line(data=year_ts,aes(x=year_ts$Var1,y=year_ts$Freq,group=1))
month_ts=data.frame(table(data2$ARREST_MONTH))
ggplot()+geom_line(data=month_ts,aes(x=month_ts$Var1,y=month_ts$Freq,group=1))
day_ts=data.frame(table(data2$ARREST_DAY))
ggplot()+geom_line(data=day_ts,aes(x=day_ts$Var1,y=day_ts$Freq,group=1))
date_ts=data.frame(table(data2$ARREST_DATE))
ggplot()+geom_line(data=date_ts,aes(x=date_ts$Var1,y=date_ts$Freq,group=1))
wordcloud::wordcloud(data2$OFNS_DESC,colors =c("black", "cornflowerblue", "darkred"))
wordcloud::wordcloud(data2$PD_DESC,min.freq = 200,scale=c(4,.5),colors =c("black", "cornflowerblue", "darkred"))
ggplot()+geom_jitter(data=data2,aes(data2$PERP_SEX,data2$OFNS_DESC))
#
##Modelling
train = subset(data2, select = -c(ARREST_KEY,ARREST_DATE,PD_CD,KY_CD,LAW_CODE,X_COORD_CD,Y_COORD_CD,Latitude,Longitude))
kcluster = kmeans(train[4],3)
train = subset(train,select = -c(LAW_CAT_CD))
###################
library(geojsonio)
spdf <- geojson_read("/Users/aradhyakasat/Documents/DataScience/NewYorkCrimeDataAnalysis2019/Data/Borough Boundaries.geojson", what = "sp")
ggplot() +
geom_polygon(data = spdf, aes(fill=data2$ARREST_BORO ,x = shape_area, y = shape_leng), fill="white", color="grey") +
theme_void() +
coord_map()
spdf = data.frame(spdf)
for(i in 1:nrow(spdf)){
if(spdf$boro_name[i]=='Bronx'){
spdf$boro_name[i] = 'B';
}
else if(spdf$boro_name[i]=='Brooklyn'){
spdf$boro_name[i] = 'K';
}
else if(spdf$boro_name[i]=='Staten Island'){
spdf$boro_name[i] = 'S';
}
else if(spdf$boro_name[i]=='Queens'){
spdf$boro_name[i]='Q';
}
else if(spdf$boro_name[i]=='Manhattan'){
spdf$boro_name[i] = 'M'
}
}
ggplot() + geom_map(data = data, aes(map_id = data$ARREST_BORO, fill = data$ARREST_BORO),
map = spdf) + expand_limits(x = shape_area, y = shape_leng)
ggplot() +
geom_polygon(data = spdf, aes( x = lat, y = long), fill="white", color="grey") +
theme_void() +
coord_map()
ggplot() +
geom_polygon(data = spdf, aes(fill = data$ARREST_BORO, x = spdf$boro_name)) +
theme_void() +
coord_map()
| /ExploratoryAnalysis.R | no_license | ITWSDataScience/NewYorkCrimeDataAnalysis2019 | R | false | false | 6,771 | r | library(tidyverse)
library(maps)
library(albersusa)#installed via github
library(ggmap)
library(RColorBrewer)
setwd("/Users/aradhyakasat/Documents/DataScience/")
data = read.csv("NewYorkCrimeDataAnalysis2019/Data/ArrestData2.csv")
data2 = read.csv("NewYorkCrimeDataAnalysis2019/Data/ArrestData3.csv")
table(data$PD_DESC)
table(data$OFNS_DESC)
barplot(table(data2$AGE_GROUP),col = rainbow(20),ylim=c(0,50000),xlab="Age Group",ylab="No. of Crimes",main="Age Group vs No. of crimes")
barplot(table(data2$ARREST_BORO),col = rainbow(20),ylim=c(0,50000),xlab="Boro",ylab="No. of Crimes",main="Boro vs No. of crimes")
barplot(table(data2$PERP_SEX),col = rainbow(20),ylim=c(0,80000),xlab="Sex",ylab="No. of Crimes",main="Sex vs No. of crimes")
barplot(table(data2$PERP_RACE),col = rainbow(20),ylim=c(0,50000),xlab="Race",ylab="No. of Crimes",main="Race vs No. of crimes",cex.names = 0.5)
table(data2$AGE_GROUP,data2$OFNS_DESC)
table(data2$PERP_SEX,data2$OFNS_DESC)
table(data2$PERP_RACE,data2$OFNS_DESC)
table(data2$JURISDICTION_CODE)
table(data2$ARREST_PRECINCT)
mosaicplot(table(data$PERP_SEX,data$AGE_GROUP),xlab ='Gender',ylab='Age Group',col=c(2,3,4))
#Please set your google maps api key to use
ggmap::register_google(key = "")
p <- ggmap(get_googlemap(center = c(lon = -74.0060, lat = 40.7128),
zoom = 10, scale = 2,
maptype ='terrain',
color = 'color'))
p + geom_point(aes(x =Longitude , y = Latitude, color=data$ARREST_BORO),data=data, alpha=0.25,size = 0.5) +
theme(legend.position="bottom")
p + geom_point(aes(x =Longitude , y = Latitude, color=data$PERP_SEX),data=data, alpha=0.25,size = 0.5) +
theme(legend.position="bottom")
p + geom_point(aes(x =Longitude , y = Latitude, color=data$OFNS_DESC),data=data, alpha=0.25,size = 0.5) +
theme(legend.position="bottom")
p + geom_point(aes(x =Longitude , y = Latitude, color=data$PERP_RACE),data=data, alpha=0.25,size = 0.5) +
theme(legend.position="bottom")
p + geom_point(aes(x =Longitude , y = Latitude, color=data$AGE_GROUP),data=data, alpha=0.25,size = 0.5) +
theme(legend.position="bottom")
data2_plot = data2
table(data2_plot$ARREST_BORO)
for(i in 1:nrow(data2_plot)){
if(data2_plot$ARREST_BORO[i]==1){
data2_plot$ARREST_BORO[i] = 'B';
}
else if(data2_plot$ARREST_BORO[i]==2){
data2_plot$ARREST_BORO[i] = 'K';
}
else if(data2_plot$ARREST_BORO[i]==3){
data2_plot$ARREST_BORO[i] = 'M';
}
else if(data2_plot$ARREST_BORO[i]==4){
data2_plot$ARREST_BORO[i]='Q';
}
else if(data2_plot$ARREST_BORO[i]==5){
data2_plot$ARREST_BORO[i] = 'S'
}
}
plot_data_2014 = subset(data2_plot,data2_plot$ARREST_YEAR==2014)
plot_data_2015 = subset(data2_plot,data2_plot$ARREST_YEAR==2015)
plot_data_2016 = subset(data2_plot,data2_plot$ARREST_YEAR==2016)
plot_data_2017 = subset(data2_plot,data2_plot$ARREST_YEAR==2017)
p + geom_point(aes(x =Longitude , y = Latitude, color=plot_data_2014$ARREST_BORO),data=plot_data_2014, alpha=0.25,size = 0.5) +
theme(legend.position="bottom")
p + geom_point(aes(x =Longitude , y = Latitude, color=plot_data_2015$ARREST_BORO),data=plot_data_2015, alpha=0.25,size = 0.5) +
theme(legend.position="bottom")
p + geom_point(aes(x =Longitude , y = Latitude, color=plot_data_2016$ARREST_BORO),data=plot_data_2016, alpha=0.25,size = 0.5) +
theme(legend.position="bottom")
p + geom_point(aes(x =Longitude , y = Latitude, color=plot_data_2017$ARREST_BORO),data=plot_data_2017, alpha=0.25,size = 0.5) +
theme(legend.position="bottom")
plot_data_sex = subset(data,data$PERP_SEX=='F')
p + geom_point(aes(x =Longitude , y = Latitude, color=plot_data_sex$ARREST_BORO),data=plot_data_sex, alpha=0.25,size = 0.5) +
theme(legend.position="bottom")
plot_data_sex_male = subset(data,data$PERP_SEX=='M')
p + geom_point(aes(x =Longitude , y = Latitude, color=plot_data_sex_male$ARREST_BORO),data=plot_data_sex_male, alpha=0.25,size = 0.5) +
theme(legend.position="bottom")
res <- revgeocode(lonlat_sample, output="more")
# can then access zip and neighborhood where populated
res$postal_code
res$neighborhood
#Type of crimes bar plot
ggplot(data=data,aes(x=data$OFNS_DESC),fill=interaction(data$PERP_SEX))+geom_bar()+scale_fill_brewer(palette = "Set1") +coord_flip()
ggplot(data=data,aes(x=data$AGE_GROUP),fill=interaction(data$PERP_SEX))+geom_bar()+scale_fill_brewer(palette = "Set1") +coord_flip()
ggplot(data=data,aes(x=data$PERP_SEX))+geom_bar()+scale_fill_brewer(palette = "Set1") +coord_flip()
ggplot(data=data,aes(x=data$PERP_RACE))+geom_bar()+scale_fill_brewer(palette = "Set1") +coord_flip()
year_ts=table(data2$ARREST_YEAR)
year_ts = data.frame(year_ts)
ggplot()+geom_line(data=year_ts,aes(x=year_ts$Var1,y=year_ts$Freq,group=1))
month_ts=data.frame(table(data2$ARREST_MONTH))
ggplot()+geom_line(data=month_ts,aes(x=month_ts$Var1,y=month_ts$Freq,group=1))
day_ts=data.frame(table(data2$ARREST_DAY))
ggplot()+geom_line(data=day_ts,aes(x=day_ts$Var1,y=day_ts$Freq,group=1))
date_ts=data.frame(table(data2$ARREST_DATE))
ggplot()+geom_line(data=date_ts,aes(x=date_ts$Var1,y=date_ts$Freq,group=1))
wordcloud::wordcloud(data2$OFNS_DESC,colors =c("black", "cornflowerblue", "darkred"))
wordcloud::wordcloud(data2$PD_DESC,min.freq = 200,scale=c(4,.5),colors =c("black", "cornflowerblue", "darkred"))
ggplot()+geom_jitter(data=data2,aes(data2$PERP_SEX,data2$OFNS_DESC))
#
##Modelling
train = subset(data2, select = -c(ARREST_KEY,ARREST_DATE,PD_CD,KY_CD,LAW_CODE,X_COORD_CD,Y_COORD_CD,Latitude,Longitude))
kcluster = kmeans(train[4],3)
train = subset(train,select = -c(LAW_CAT_CD))
###################
library(geojsonio)
spdf <- geojson_read("/Users/aradhyakasat/Documents/DataScience/NewYorkCrimeDataAnalysis2019/Data/Borough Boundaries.geojson", what = "sp")
ggplot() +
geom_polygon(data = spdf, aes(fill=data2$ARREST_BORO ,x = shape_area, y = shape_leng), fill="white", color="grey") +
theme_void() +
coord_map()
spdf = data.frame(spdf)
for(i in 1:nrow(spdf)){
if(spdf$boro_name[i]=='Bronx'){
spdf$boro_name[i] = 'B';
}
else if(spdf$boro_name[i]=='Brooklyn'){
spdf$boro_name[i] = 'K';
}
else if(spdf$boro_name[i]=='Staten Island'){
spdf$boro_name[i] = 'S';
}
else if(spdf$boro_name[i]=='Queens'){
spdf$boro_name[i]='Q';
}
else if(spdf$boro_name[i]=='Manhattan'){
spdf$boro_name[i] = 'M'
}
}
ggplot() + geom_map(data = data, aes(map_id = data$ARREST_BORO, fill = data$ARREST_BORO),
map = spdf) + expand_limits(x = shape_area, y = shape_leng)
ggplot() +
geom_polygon(data = spdf, aes( x = lat, y = long), fill="white", color="grey") +
theme_void() +
coord_map()
ggplot() +
geom_polygon(data = spdf, aes(fill = data$ARREST_BORO, x = spdf$boro_name)) +
theme_void() +
coord_map()
|
library(ggplot2)
library(tidyr)
library(dplyr)
# get the dataset
data <- read.csv("winequality-white.csv")
degrees <- 20 # the number of degrees to test
results.df <- data.frame("degree" = integer(), "train" = double(), "test" = double())
for(i in 1:degrees) {
n <- nrow(data) # get the number of rows
train <- sample(1:n, n/2, rep = F) # get subset of the data for training
test <- setdiff(1:n, train) # and one for testing
train.df <- data[train, c("pH", "alcohol")] # set up the data frame for training
test.df <- data[test, c("pH", "alcohol")] # set up the data frame for testing
mod <- lm(pH~poly(alcohol, i), data = train.df) # build the linear model with degree i
pred.train <- predict(mod, newdata = train.df) # traing the model
train.df <- mutate(train.df, pred = pred.train) # add the training data to the data frame
pred.test <- predict(mod, newdata = test.df) # test the model
test.df <- mutate(test.df, pred = pred.test) # add the test data to the data frame
mse.train <- with(train.df, mean((pH - pred)^2)) # calculate information about the model
mse.test <- with(test.df, mean((pH - pred)^2))
c(mse.train, mse.test) # print the information about the model to the console
results.df <- rbind(results.df, c(i, mse.train, mse.test))
}
head(results.df) | /data_analysis_assignment/regression.R | no_license | elijahverdoorn/MATH384 | R | false | false | 1,308 | r | library(ggplot2)
library(tidyr)
library(dplyr)
# get the dataset
data <- read.csv("winequality-white.csv")
degrees <- 20 # the number of degrees to test
results.df <- data.frame("degree" = integer(), "train" = double(), "test" = double())
for(i in 1:degrees) {
n <- nrow(data) # get the number of rows
train <- sample(1:n, n/2, rep = F) # get subset of the data for training
test <- setdiff(1:n, train) # and one for testing
train.df <- data[train, c("pH", "alcohol")] # set up the data frame for training
test.df <- data[test, c("pH", "alcohol")] # set up the data frame for testing
mod <- lm(pH~poly(alcohol, i), data = train.df) # build the linear model with degree i
pred.train <- predict(mod, newdata = train.df) # traing the model
train.df <- mutate(train.df, pred = pred.train) # add the training data to the data frame
pred.test <- predict(mod, newdata = test.df) # test the model
test.df <- mutate(test.df, pred = pred.test) # add the test data to the data frame
mse.train <- with(train.df, mean((pH - pred)^2)) # calculate information about the model
mse.test <- with(test.df, mean((pH - pred)^2))
c(mse.train, mse.test) # print the information about the model to the console
results.df <- rbind(results.df, c(i, mse.train, mse.test))
}
head(results.df) |
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/greedy_knapsack.R
\name{greedy_knapsack}
\alias{greedy_knapsack}
\title{Greedy}
\usage{
greedy_knapsack(x, W)
}
\arguments{
\item{x}{data.frame}
\item{W}{integer}
}
\value{
list of ideal value and elements that solves the problem
}
\description{
Solving Knapsack problem with Greedy heuristic
}
| /man/greedy_knapsack.Rd | no_license | MartinSmel/Knapsack | R | false | true | 374 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/greedy_knapsack.R
\name{greedy_knapsack}
\alias{greedy_knapsack}
\title{Greedy}
\usage{
greedy_knapsack(x, W)
}
\arguments{
\item{x}{data.frame}
\item{W}{integer}
}
\value{
list of ideal value and elements that solves the problem
}
\description{
Solving Knapsack problem with Greedy heuristic
}
|
library(dplyr)
library(rstan)
options(mc.cores = 3)
library(ggplot2)
library(patchwork)
library(bayesplot)
cd4 <- read.delim("cd4.txt", header = TRUE)
n_obs <- nrow(cd4)
J <- max(cd4$ID)
x <- seq(from = 1, by = 3, length.out = 7)
df <- tibble(id = rep(1:J, each = 7), visit = rep(x, J))
cd4 <- cd4 %>% select(id = ID, visit = Visit, CD4Pct) %>%
right_join(df, by = c('id', 'visit')) %>%
mutate(y = sqrt(CD4Pct))
n <- nrow(cd4)
cd4_data <- list(N = n, N_obs = n_obs, y_obs = cd4$y[1:n_obs], visit = cd4$visit, id = cd4$id, J = J)
fit <- stan(file='cd4.stan', data = cd4_data, chains = 3,
iter = 2500, warmup = 2000, refresh = 1000, save_warmup = FALSE)
# find indices of y_miss correspond to id = 18 for example
idx <- which(cd4$id == 18)
idx[idx > n_obs] - n_obs
param <- c('y_miss[38]', 'y_miss[39]')
y18 <- extract(fit, pars = param)
sigmas <- extract(fit, pars = c('sigma_y', 'sigma_a', 'sigma_b'), permuted = FALSE)
id18 <- tibble(t16 = post_param$`y_miss[38]`, t19 = post_param$`y_miss[39]`)
id18 <- id18 %>% mutate(cd4t16 = t16^2, cd4t19 = t19^2)
mcmc_intervals(
id18,
pars = c('cd4t16', 'cd4t19'),
prob = 0.95, # 80% intervals
prob_outer = 0.95, # 99%
point_est = "mean"
)
mcmc_trace(fit, pars = param)
| /cd4_stan.R | no_license | owenqiz/miscellaneous | R | false | false | 1,317 | r | library(dplyr)
library(rstan)
options(mc.cores = 3)
library(ggplot2)
library(patchwork)
library(bayesplot)
cd4 <- read.delim("cd4.txt", header = TRUE)
n_obs <- nrow(cd4)
J <- max(cd4$ID)
x <- seq(from = 1, by = 3, length.out = 7)
df <- tibble(id = rep(1:J, each = 7), visit = rep(x, J))
cd4 <- cd4 %>% select(id = ID, visit = Visit, CD4Pct) %>%
right_join(df, by = c('id', 'visit')) %>%
mutate(y = sqrt(CD4Pct))
n <- nrow(cd4)
cd4_data <- list(N = n, N_obs = n_obs, y_obs = cd4$y[1:n_obs], visit = cd4$visit, id = cd4$id, J = J)
fit <- stan(file='cd4.stan', data = cd4_data, chains = 3,
iter = 2500, warmup = 2000, refresh = 1000, save_warmup = FALSE)
# find indices of y_miss correspond to id = 18 for example
idx <- which(cd4$id == 18)
idx[idx > n_obs] - n_obs
param <- c('y_miss[38]', 'y_miss[39]')
y18 <- extract(fit, pars = param)
sigmas <- extract(fit, pars = c('sigma_y', 'sigma_a', 'sigma_b'), permuted = FALSE)
id18 <- tibble(t16 = post_param$`y_miss[38]`, t19 = post_param$`y_miss[39]`)
id18 <- id18 %>% mutate(cd4t16 = t16^2, cd4t19 = t19^2)
mcmc_intervals(
id18,
pars = c('cd4t16', 'cd4t19'),
prob = 0.95, # 80% intervals
prob_outer = 0.95, # 99%
point_est = "mean"
)
mcmc_trace(fit, pars = param)
|
#'@name cutRange
#'
#'@title Species on a specific elevation range
#'
#'@description Get species distributed on a specific range of altitude.
#'
#'@param data Vector of characters. Name of the input file.
#'
#'@param rd.frmt Vector of characters. File format to read.
#'By default it will be read as a R object using the
#' \code{'readRDS'} argument, but it can be read as plain text using the
#' \code{'readTXT'} argument. See details.
#'
#'@param path Vector of characters. Path to the input file.
#'
#'@param range.from Numeric vector. Lower bound of the range of the distribution
#'
#'@param range.to Numeric vector. Upper bound of the range of the distribution.
#'
#'@param wrt.frmt Vector of characters. Format to save output
#'file. By default it will be written as a R object using the
#' \code{'saveRDS'} argument, but it can be saved as plain text using the
#' \code{'saveTXT'} argument. See details.
#'
#'@param save.inside.in Vector of characters. Path to the output
#' file with the species whose occurrences are on the range
#' assigned in \code{range.from} to \code{range.to} parameters. Output file
#' will be called <inside.range>.
#'
#'@param save.outside.in Vector of characters. Path to the output
#'file with the species whose occurences are not on the range
#'assigned in \code{range.from} and \code{range.to} parameters. Output file
#'will be called <outside.range>.
#'
#'@details For more details about the formats to read and/or write, see
#'\code{\link{readAndWrite}} function.
#'
#'The headers of the input file must follow the Darwin Core standard [1].
#'The user can see the guide using data('ID_DarwinCore) command.
#'
#'@return A table data.frame class with only the species whose occurences is on range
#'assigned in \code{range.from} and \code{range.to} parameters, and a vector with a table with descriptive quantities.
#'
#'
#'@author R-Alarcon Viviana and Miranda-Esquivel Daniel R.
#'
#'@note See:
#'R-Alarcon V. and Miranda-Esquivel DR.(submitted) geocleaMT: An R package to
#'cleaning geographical data from electronic biodatabases.
#'
#'@seealso \code{\link{readAndWrite}}
#'
#'@references
#' [1] Wieczorek, J. et al. 2012. Darwin core: An evolving community-developed biodiversity data standard.
#' PloS One 7: e29715.
#'
cutRange <- function(data = NULL,
path = NULL,
rd.frmt = 'readRDS',
range.from = 0,
range.to = 1000,
wrt.frmt = 'saveRDS',
save.inside.in = NULL,
save.outside.in = NULL) {
data <- readAndWrite(action = 'read', frmt = rd.frmt,
path = path, name = data)
tab.info <- as.data.frame(matrix(NA, 1, 6))
colnames(tab.info) <- c('Total.Occ','Total.Sp', 'Uniq.Sp.Inside',
'Uniq.Sp.Outside','Sp.In.and.Outside','Total.In.Range')
tab.info$Total.Sp <- length(unique(data$species))
tab.info$Total.Occ <- nrow(data)
data <- as.data.frame(unique(data))
#Select species inside range
inside.range <- subset(data, (as.numeric(as.character(data$elevation))) >
range.from & (as.numeric(as.character(data$elevation)))
< range.to)
#Select species outside range
outside.range <- subset(data, !(as.numeric(as.character(data$elevation)) >
range.from & as.numeric(as.character(data$elevation))
< range.to))
# Write table with species inside the range
readAndWrite(action = 'write', frmt = wrt.frmt, path = save.inside.in,
name = 'inside.range', object = inside.range)
readAndWrite(action = 'write', frmt = wrt.frmt, path = save.outside.in,
name = 'outside.range', object = outside.range)
#Count different items like Total species, total occurrences etc
tab.info$Uniq.Sp.Inside <- length(inside.range$species[which(!unique(inside.range$species) %in%
unique(outside.range$species))])
tab.info$Uniq.Sp.Outside <- as.numeric(length(outside.range$species[which(!unique(outside.range$species) %in%
unique(inside.range$species))]))
tab.info$Sp.In.and.Outside <-as.numeric(tab.info$Total.Sp) - as.numeric(tab.info$Uniq.Sp.Outside) - as.numeric(tab.info$Uniq.Sp.Inside)
tab.info$Total.In.Range <- as.numeric(tab.info$Total.Sp) - as.numeric(tab.info$Uniq.Sp.Outside)
return(tab.info)
}
| /R/cutRange.R | no_license | Dmirandae/geocleaMT | R | false | false | 4,583 | r | #'@name cutRange
#'
#'@title Species on a specific elevation range
#'
#'@description Get species distributed on a specific range of altitude.
#'
#'@param data Vector of characters. Name of the input file.
#'
#'@param rd.frmt Vector of characters. File format to read.
#'By default it will be read as a R object using the
#' \code{'readRDS'} argument, but it can be read as plain text using the
#' \code{'readTXT'} argument. See details.
#'
#'@param path Vector of characters. Path to the input file.
#'
#'@param range.from Numeric vector. Lower bound of the range of the distribution
#'
#'@param range.to Numeric vector. Upper bound of the range of the distribution.
#'
#'@param wrt.frmt Vector of characters. Format to save output
#'file. By default it will be written as a R object using the
#' \code{'saveRDS'} argument, but it can be saved as plain text using the
#' \code{'saveTXT'} argument. See details.
#'
#'@param save.inside.in Vector of characters. Path to the output
#' file with the species whose occurrences are on the range
#' assigned in \code{range.from} to \code{range.to} parameters. Output file
#' will be called <inside.range>.
#'
#'@param save.outside.in Vector of characters. Path to the output
#'file with the species whose occurences are not on the range
#'assigned in \code{range.from} and \code{range.to} parameters. Output file
#'will be called <outside.range>.
#'
#'@details For more details about the formats to read and/or write, see
#'\code{\link{readAndWrite}} function.
#'
#'The headers of the input file must follow the Darwin Core standard [1].
#'The user can see the guide using data('ID_DarwinCore) command.
#'
#'@return A table data.frame class with only the species whose occurences is on range
#'assigned in \code{range.from} and \code{range.to} parameters, and a vector with a table with descriptive quantities.
#'
#'
#'@author R-Alarcon Viviana and Miranda-Esquivel Daniel R.
#'
#'@note See:
#'R-Alarcon V. and Miranda-Esquivel DR.(submitted) geocleaMT: An R package to
#'cleaning geographical data from electronic biodatabases.
#'
#'@seealso \code{\link{readAndWrite}}
#'
#'@references
#' [1] Wieczorek, J. et al. 2012. Darwin core: An evolving community-developed biodiversity data standard.
#' PloS One 7: e29715.
#'
cutRange <- function(data = NULL,
path = NULL,
rd.frmt = 'readRDS',
range.from = 0,
range.to = 1000,
wrt.frmt = 'saveRDS',
save.inside.in = NULL,
save.outside.in = NULL) {
data <- readAndWrite(action = 'read', frmt = rd.frmt,
path = path, name = data)
tab.info <- as.data.frame(matrix(NA, 1, 6))
colnames(tab.info) <- c('Total.Occ','Total.Sp', 'Uniq.Sp.Inside',
'Uniq.Sp.Outside','Sp.In.and.Outside','Total.In.Range')
tab.info$Total.Sp <- length(unique(data$species))
tab.info$Total.Occ <- nrow(data)
data <- as.data.frame(unique(data))
#Select species inside range
inside.range <- subset(data, (as.numeric(as.character(data$elevation))) >
range.from & (as.numeric(as.character(data$elevation)))
< range.to)
#Select species outside range
outside.range <- subset(data, !(as.numeric(as.character(data$elevation)) >
range.from & as.numeric(as.character(data$elevation))
< range.to))
# Write table with species inside the range
readAndWrite(action = 'write', frmt = wrt.frmt, path = save.inside.in,
name = 'inside.range', object = inside.range)
readAndWrite(action = 'write', frmt = wrt.frmt, path = save.outside.in,
name = 'outside.range', object = outside.range)
#Count different items like Total species, total occurrences etc
tab.info$Uniq.Sp.Inside <- length(inside.range$species[which(!unique(inside.range$species) %in%
unique(outside.range$species))])
tab.info$Uniq.Sp.Outside <- as.numeric(length(outside.range$species[which(!unique(outside.range$species) %in%
unique(inside.range$species))]))
tab.info$Sp.In.and.Outside <-as.numeric(tab.info$Total.Sp) - as.numeric(tab.info$Uniq.Sp.Outside) - as.numeric(tab.info$Uniq.Sp.Inside)
tab.info$Total.In.Range <- as.numeric(tab.info$Total.Sp) - as.numeric(tab.info$Uniq.Sp.Outside)
return(tab.info)
}
|
library(cvTools)
library(glmnet)
# Utilize UAMS dataset for training
training <- combine(eval.data$GSE24080UAMS[[1]]$training,eval.data$GSE24080UAMS[[1]]$test)
emc92.features <- rbind(result.data$emc92$GSE24080UAMS[[1]],test.result.data$emc92$GSE24080UAMS[[1]]);
uams70.features <- rbind(result.data$uams.70$GSE24080UAMS[[1]],test.result.data$uams.70$GSE24080UAMS[[1]]);
uams17.features <- rbind(result.data$uams.17$GSE24080UAMS[[1]],test.result.data$uams.17$GSE24080UAMS[[1]]);
uams5.features <- rbind(result.data$uams.5$GSE24080UAMS[[1]],test.result.data$uams.5$GSE24080UAMS[[1]]);
emc92.features <- emc92.features[match(sampleNames(training),emc92.features$ID),]
uams70.features <- uams70.features[match(sampleNames(training),uams70.features$ID),]
uams17.features <- uams17.features[match(sampleNames(training),uams17.features$ID),]
uams5.features <- uams5.features[match(sampleNames(training),uams5.features$ID),]
all.training.uams <- data.frame(PFStimeMonths=pData(training)[['PFStimeMonths']],
Progression=pData(training)[['Progression']],
emc92=emc92.features$raw.score,
uams70.features=uams70.features$raw.score,
uams17.features=uams17.features$raw.score,
uams5.features=uams5.features$raw.score)
all.training.uams <- all.training.uams[all.training.uams$PFStimeMonths > 0,]
folds <- cvFolds(n=nrow(all.training.uams),K=10)
# Function to minimize to identify the best-fit alpha value
train <- function(par,numeric.matrix,folds,classes,mc) {
library(glmnet)
library(doParallel)
registerDoParallel(cl = mc)
model <- cv.glmnet(y=classes,x=numeric.matrix,family = 'cox',foldid = folds$which,parallel = T)
model$cvm[model$lambda == model$lambda.1se]
}
mc <- makeCluster(detectCores())
classes <- as(Surv(time=as.numeric(all.training.uams$PFStimeMonths),event=all.training.uams$Progression),'matrix')
numeric.matrix=as.matrix(all.training.uams[,-c(1,2)])
optimized <- optim(par=0,train,method='Brent',lower=0,upper=1,numeric.matrix=numeric.matrix,folds=folds,classes=classes,mc)
model <- cv.glmnet(x=numeric.matrix,y=classes,family='cox',alpha=optimized$par,foldid = folds$which,parallel = T)
stopCluster(mc)
coef <- predict(model,newx=numeric.matrix,s=model$lambda.1se,type='coefficients') | /publishedClassifiers/lasso.weighted.ensemble/scratch.R | no_license | bswhite/Celgene-Multiple-Myeloma-Challenge-Baseline-Models | R | false | false | 2,363 | r | library(cvTools)
library(glmnet)
# Utilize UAMS dataset for training
training <- combine(eval.data$GSE24080UAMS[[1]]$training,eval.data$GSE24080UAMS[[1]]$test)
emc92.features <- rbind(result.data$emc92$GSE24080UAMS[[1]],test.result.data$emc92$GSE24080UAMS[[1]]);
uams70.features <- rbind(result.data$uams.70$GSE24080UAMS[[1]],test.result.data$uams.70$GSE24080UAMS[[1]]);
uams17.features <- rbind(result.data$uams.17$GSE24080UAMS[[1]],test.result.data$uams.17$GSE24080UAMS[[1]]);
uams5.features <- rbind(result.data$uams.5$GSE24080UAMS[[1]],test.result.data$uams.5$GSE24080UAMS[[1]]);
emc92.features <- emc92.features[match(sampleNames(training),emc92.features$ID),]
uams70.features <- uams70.features[match(sampleNames(training),uams70.features$ID),]
uams17.features <- uams17.features[match(sampleNames(training),uams17.features$ID),]
uams5.features <- uams5.features[match(sampleNames(training),uams5.features$ID),]
all.training.uams <- data.frame(PFStimeMonths=pData(training)[['PFStimeMonths']],
Progression=pData(training)[['Progression']],
emc92=emc92.features$raw.score,
uams70.features=uams70.features$raw.score,
uams17.features=uams17.features$raw.score,
uams5.features=uams5.features$raw.score)
all.training.uams <- all.training.uams[all.training.uams$PFStimeMonths > 0,]
folds <- cvFolds(n=nrow(all.training.uams),K=10)
# Function to minimize to identify the best-fit alpha value
train <- function(par,numeric.matrix,folds,classes,mc) {
library(glmnet)
library(doParallel)
registerDoParallel(cl = mc)
model <- cv.glmnet(y=classes,x=numeric.matrix,family = 'cox',foldid = folds$which,parallel = T)
model$cvm[model$lambda == model$lambda.1se]
}
mc <- makeCluster(detectCores())
classes <- as(Surv(time=as.numeric(all.training.uams$PFStimeMonths),event=all.training.uams$Progression),'matrix')
numeric.matrix=as.matrix(all.training.uams[,-c(1,2)])
optimized <- optim(par=0,train,method='Brent',lower=0,upper=1,numeric.matrix=numeric.matrix,folds=folds,classes=classes,mc)
model <- cv.glmnet(x=numeric.matrix,y=classes,family='cox',alpha=optimized$par,foldid = folds$which,parallel = T)
stopCluster(mc)
coef <- predict(model,newx=numeric.matrix,s=model$lambda.1se,type='coefficients') |
gfmcRaster <- function(input, GFMCold = 85, time.step = 1, roFL = 0.3,
out = "GFMCandMC") {
#############################################################################
# Description: Calculation of the Grass Fuel Moisture Code. This calculates
# the moisture content of both the surface of a fully cured
# matted grass layer and also an equivalent Grass Fuel Moisture
# Code. All equations come from Wotton (2009) as cited below
# unless otherwise specified.
#
# Wotton, B.M. 2009. A grass moisture model for the Canadian
# Forest Fire Danger Rating System. In: Proceedings 8th Fire and
# Forest Meteorology Symposium, Kalispell, MT Oct 13-15, 2009.
# Paper 3-2. https://ams.confex.com/ams/pdfpapers/155930.pdf
#
# Args: input (rasterstack):
# temp (required) Temperature (centigrade)
# rh (required) Relative humidity (%)
# ws (required) 10-m height wind speed (km/h)
# prec (required) 1-hour rainfall (mm)
# isol (required) Solar radiation (kW/m^2)
# GFMCold: GFMC from yesterday (double, default=85)
# time.step: The hourly time steps (integer hour, default=1)
# roFL: Nominal fuel load of the fine fuel layer
# (kg/m^2 double, default=0.3)
# out: Output format (GFMCandMC/MC/GFMC/ALL, default=GFMCandMC)
#
# Returns: Returns a raster stack of either MC, GMFC, All, or GFMCandMC
#
#############################################################################
t0 <- time.step ## Currently locked at 1
names(input) <- tolower(names(input))
#Quite often users will have a data frame called "input" already attached
# to the workspace. To mitigate this, we remove that if it exists, and warn
# the user of this case.
if (!is.na(charmatch("input", search()))) {
warning("Attached dataset 'input' is being detached to use fbp() function.")
detach(input)
}
#set local scope variables
temp <- input$temp
prec <- input$prec
ws <- input$ws
rh <- input$rh
isol <- input$isol
#show warnings when inputs are missing
if (!exists("temp") | is.null(temp))
warning("temperature (temp) is missing!")
if (!exists("prec") | is.null(prec))
warning("precipitation (prec) is missing!")
if (!exists("ws") | is.null(ws))
warning("wind speed (ws) is missing!")
if (!exists("rh") | is.null(rh))
warning("relative humidity (rh) is missing!")
if (!exists("isol") | is.null(isol))
warning("ISOL is missing!")
if (is.numeric(GFMCold) & length(GFMCold) == 1){
warning("Single GFMCold value for grid is applied to the whole grid")
GFMCold <- setValues(temp, GFMCold)
}
validOutTypes = c("GFMCandMC", "MC", "GFMC", "ALL")
if(!(out %in% validOutTypes)){
stop(paste("'",out, "' is an invalid 'out' type.", sep=""))
}
#get the length of the data stream
GFMC <- NULL
MC <- NULL
#iterate through timesteps
#Eq. 13 - Calculate previous moisture code
MCold <- 147.27723 * ((101 - GFMCold) / (59.5 + GFMCold))
#Eq. 11 - Calculate the moisture content of the layer in % after rainfall
MCr <- MCold
MCr[prec>0] <- MCold[prec>0] + 100 * (prec[prec>0] / roFL)
#Constrain to 250
MCr[MCr > 250] <- 250
MCold <- MCr
#Eq. 2 - Calculate Fuel temperature
Tf <- temp + 35.07 * isol * exp(-0.06215 * ws)
#Eq. 3 - Calculate Saturation Vapour Pressure (Baumgartner et a. 1982)
eS.T <- 6.107 * 10^(7.5 * temp / (237 + temp))
#Eq. 3 for Fuel temperature
eS.Tf <- 6.107 * 10^(7.5 * Tf / (237 + Tf))
#Eq. 4 - Calculate Fuel Level Relative Humidity
RH.f <- rh * (eS.T / eS.Tf)
#Eq. 7 - Calculate Equilibrium Moisture Content for Drying phase
EMC.D <- (1.62 * RH.f^0.532 + 13.7 * exp((RH.f - 100) / 13.0)) +
0.27 * (26.7 - Tf) * (1 - exp(-0.115 * RH.f))
#Eq. 7 - Calculate Equilibrium Moisture Content for Wetting phase
EMC.W <- (1.42 * RH.f^0.512 + 12.0 * exp((RH.f - 100) / 18.0)) +
0.27 * (26.7 - Tf) * (1 - exp(-0.115 * RH.f))
#RH in terms of RH/100 for desorption
Rf <- rh
Rf[MCold > EMC.D] <- RH.f[MCold > EMC.D] / 100
#RH in terms of 1-RH/100 for absorption
Rf[MCold < EMC.W] <- (100 - RH.f[MCold < EMC.W]) / 100
#Eq. 10 - Calculate Inverse Response time of grass (hours)
K.GRASS <- 0.389633 * exp(0.0365 * Tf) * (0.424 * (1 - Rf^1.7) + 0.0694 *
sqrt(ws) * (1 - Rf^8))
#Fuel is drying, calculate Moisture Content
MC0 <- MCold
MC0[MCold > EMC.D] <- EMC.D[MCold > EMC.D] + (MCold[MCold > EMC.D] - EMC.D[MCold > EMC.D]) * exp(-1.0 * log(10.0) * K.GRASS[MCold > EMC.D] * t0)
#Fuel is wetting, calculate moisture content
MC0[MCold < EMC.W] <- EMC.W[MCold < EMC.W] + (MCold[MCold < EMC.W] - EMC.W[MCold < EMC.W]) * exp(-1.0 * log(10.0) * K.GRASS[MCold < EMC.W] * t0)
#Eq. 12 - Calculate GFMC
GFMC0 <- 59.5 * ((250 - MC0) / (147.2772 + MC0))
#Keep current and old GFMC
GFMC <- GFMC0
names(GFMC) <- "GFMC"
#Same for moisture content
MC <- MC0
names(MC) <- "MC"
#Reset vars
GFMCold <- GFMC0
MCold <- MC0
#Return requested 'out' type
if (out=="ALL"){
return(raster::stack(input, GFMC, MC))
} else if(out == "GFMC"){
return(GFMC)
} else if (out == "MC"){
return(MC)
} else { #GFMCandMC
return(raster::stack( GFMC, MC))
}
}
| /R/gfmcRaster.R | no_license | cran/cffdrs | R | false | false | 5,563 | r | gfmcRaster <- function(input, GFMCold = 85, time.step = 1, roFL = 0.3,
out = "GFMCandMC") {
#############################################################################
# Description: Calculation of the Grass Fuel Moisture Code. This calculates
# the moisture content of both the surface of a fully cured
# matted grass layer and also an equivalent Grass Fuel Moisture
# Code. All equations come from Wotton (2009) as cited below
# unless otherwise specified.
#
# Wotton, B.M. 2009. A grass moisture model for the Canadian
# Forest Fire Danger Rating System. In: Proceedings 8th Fire and
# Forest Meteorology Symposium, Kalispell, MT Oct 13-15, 2009.
# Paper 3-2. https://ams.confex.com/ams/pdfpapers/155930.pdf
#
# Args: input (rasterstack):
# temp (required) Temperature (centigrade)
# rh (required) Relative humidity (%)
# ws (required) 10-m height wind speed (km/h)
# prec (required) 1-hour rainfall (mm)
# isol (required) Solar radiation (kW/m^2)
# GFMCold: GFMC from yesterday (double, default=85)
# time.step: The hourly time steps (integer hour, default=1)
# roFL: Nominal fuel load of the fine fuel layer
# (kg/m^2 double, default=0.3)
# out: Output format (GFMCandMC/MC/GFMC/ALL, default=GFMCandMC)
#
# Returns: Returns a raster stack of either MC, GMFC, All, or GFMCandMC
#
#############################################################################
t0 <- time.step ## Currently locked at 1
names(input) <- tolower(names(input))
#Quite often users will have a data frame called "input" already attached
# to the workspace. To mitigate this, we remove that if it exists, and warn
# the user of this case.
if (!is.na(charmatch("input", search()))) {
warning("Attached dataset 'input' is being detached to use fbp() function.")
detach(input)
}
#set local scope variables
temp <- input$temp
prec <- input$prec
ws <- input$ws
rh <- input$rh
isol <- input$isol
#show warnings when inputs are missing
if (!exists("temp") | is.null(temp))
warning("temperature (temp) is missing!")
if (!exists("prec") | is.null(prec))
warning("precipitation (prec) is missing!")
if (!exists("ws") | is.null(ws))
warning("wind speed (ws) is missing!")
if (!exists("rh") | is.null(rh))
warning("relative humidity (rh) is missing!")
if (!exists("isol") | is.null(isol))
warning("ISOL is missing!")
if (is.numeric(GFMCold) & length(GFMCold) == 1){
warning("Single GFMCold value for grid is applied to the whole grid")
GFMCold <- setValues(temp, GFMCold)
}
validOutTypes = c("GFMCandMC", "MC", "GFMC", "ALL")
if(!(out %in% validOutTypes)){
stop(paste("'",out, "' is an invalid 'out' type.", sep=""))
}
#get the length of the data stream
GFMC <- NULL
MC <- NULL
#iterate through timesteps
#Eq. 13 - Calculate previous moisture code
MCold <- 147.27723 * ((101 - GFMCold) / (59.5 + GFMCold))
#Eq. 11 - Calculate the moisture content of the layer in % after rainfall
MCr <- MCold
MCr[prec>0] <- MCold[prec>0] + 100 * (prec[prec>0] / roFL)
#Constrain to 250
MCr[MCr > 250] <- 250
MCold <- MCr
#Eq. 2 - Calculate Fuel temperature
Tf <- temp + 35.07 * isol * exp(-0.06215 * ws)
#Eq. 3 - Calculate Saturation Vapour Pressure (Baumgartner et a. 1982)
eS.T <- 6.107 * 10^(7.5 * temp / (237 + temp))
#Eq. 3 for Fuel temperature
eS.Tf <- 6.107 * 10^(7.5 * Tf / (237 + Tf))
#Eq. 4 - Calculate Fuel Level Relative Humidity
RH.f <- rh * (eS.T / eS.Tf)
#Eq. 7 - Calculate Equilibrium Moisture Content for Drying phase
EMC.D <- (1.62 * RH.f^0.532 + 13.7 * exp((RH.f - 100) / 13.0)) +
0.27 * (26.7 - Tf) * (1 - exp(-0.115 * RH.f))
#Eq. 7 - Calculate Equilibrium Moisture Content for Wetting phase
EMC.W <- (1.42 * RH.f^0.512 + 12.0 * exp((RH.f - 100) / 18.0)) +
0.27 * (26.7 - Tf) * (1 - exp(-0.115 * RH.f))
#RH in terms of RH/100 for desorption
Rf <- rh
Rf[MCold > EMC.D] <- RH.f[MCold > EMC.D] / 100
#RH in terms of 1-RH/100 for absorption
Rf[MCold < EMC.W] <- (100 - RH.f[MCold < EMC.W]) / 100
#Eq. 10 - Calculate Inverse Response time of grass (hours)
K.GRASS <- 0.389633 * exp(0.0365 * Tf) * (0.424 * (1 - Rf^1.7) + 0.0694 *
sqrt(ws) * (1 - Rf^8))
#Fuel is drying, calculate Moisture Content
MC0 <- MCold
MC0[MCold > EMC.D] <- EMC.D[MCold > EMC.D] + (MCold[MCold > EMC.D] - EMC.D[MCold > EMC.D]) * exp(-1.0 * log(10.0) * K.GRASS[MCold > EMC.D] * t0)
#Fuel is wetting, calculate moisture content
MC0[MCold < EMC.W] <- EMC.W[MCold < EMC.W] + (MCold[MCold < EMC.W] - EMC.W[MCold < EMC.W]) * exp(-1.0 * log(10.0) * K.GRASS[MCold < EMC.W] * t0)
#Eq. 12 - Calculate GFMC
GFMC0 <- 59.5 * ((250 - MC0) / (147.2772 + MC0))
#Keep current and old GFMC
GFMC <- GFMC0
names(GFMC) <- "GFMC"
#Same for moisture content
MC <- MC0
names(MC) <- "MC"
#Reset vars
GFMCold <- GFMC0
MCold <- MC0
#Return requested 'out' type
if (out=="ALL"){
return(raster::stack(input, GFMC, MC))
} else if(out == "GFMC"){
return(GFMC)
} else if (out == "MC"){
return(MC)
} else { #GFMCandMC
return(raster::stack( GFMC, MC))
}
}
|
# script to process original raw data
# this is based on a number of notes made by Pete Lenaker in
# the file: 'M:/QW Monitoring Team/GLRI toxics/GLRI II/WY2017/Data/GLRI PAH Battelle Data Notes_READ ME'
process_sample_merge <- function(raw_sample, raw_site){
dat.clean <- raw_sample
dat.clean$STAT_ID[dat.clean$STAT_ID == "UJC"] <- "UCJ" # fix wrong site id for Underwood Creek
dat.clean$STAT_ID[dat.clean$STAT_ID == "CRO"] <- "CRP" # fix wrong site id for Underwood Creek
# create just a date (collection) column without time
dat.clean$COLLECTION_DATE_NOTIME <- as.Date(dat.clean$COLLECTION_DATE)
# create two datasets, one where there should be no issue merging by site,
# and the other where STAT_ID is duplicated across states
dat.clean.nodup <- filter(dat.clean, !(STAT_ID %in% c("CRM", "RRS", "RRR", "RRB")))
dat.clean.dup <- filter(dat.clean, (STAT_ID %in% c("CRM", "RRS", "RRR", "RRB")))
dat.clean.nodup <- left_join(dat.clean.nodup, raw_site, by = c("STAT_ID" = "Base.Field.ID"))
# fix spots where a STAT_ID was used by multiple states
#CRM
dat.clean.dup$State <- NA
dat.clean.dup$State[dat.clean.dup$STAT_ID == 'CRM' &
dat.clean.dup$COLLECTION_DATE_NOTIME == as.Date("2017-06-28")] <- "MI"
dat.clean.dup$State[dat.clean.dup$STAT_ID == 'CRM' &
dat.clean.dup$COLLECTION_DATE_NOTIME == as.Date("2017-06-07")] <- "OH"
#RRS
dat.clean.dup$State[dat.clean.dup$STAT_ID == 'RRS' &
dat.clean.dup$COLLECTION_DATE_NOTIME == as.Date("2017-06-28")] <- "MI"
dat.clean.dup$State[dat.clean.dup$STAT_ID == 'RRS' &
dat.clean.dup$COLLECTION_DATE_NOTIME == as.Date("2017-06-06")] <- "OH"
#RRR
dat.clean.dup$State[dat.clean.dup$STAT_ID == 'RRR' &
dat.clean.dup$COLLECTION_DATE_NOTIME == as.Date("2017-06-28")] <- "MI"
dat.clean.dup$State[dat.clean.dup$STAT_ID == 'RRR' &
dat.clean.dup$COLLECTION_DATE_NOTIME == as.Date("2017-06-07")] <- "WI"
#RRB
dat.clean.dup$State[dat.clean.dup$STAT_ID == 'RRB' &
dat.clean.dup$COLLECTION_DATE_NOTIME == as.Date("2017-06-28")] <- "MI"
dat.clean.dup$State[dat.clean.dup$STAT_ID == 'RRB' &
dat.clean.dup$COLLECTION_DATE_NOTIME == as.Date("2017-06-06")] <- "OH"
# now merge the cleaned up duplicates by STATID and state
dat.clean.dup <- left_join(dat.clean.dup, raw_site, by =c("STAT_ID" = "Base.Field.ID", "State"))
# append dat.clean.dup to dat.clean.nodup
dat.clean <- bind_rows(dat.clean.nodup, dat.clean.dup)
# get rid of samples that are "bad"
dat.clean <- filter(dat.clean, LAB_SAMPLE_ID != "K7216") # get rid of first sample taken at SLR
dat.clean <- filter(dat.clean, LAB_SAMPLE_ID != "K1708433-057") # some leftover data from first sample at SLR
dat.clean <- filter(dat.clean, !(STAT_ID == "BRO" & COLLECTION_DATE_NOTIME == as.Date("2017-06-21"))) # get rid of first sample at BRO
# sed sample ID K7135 (IN-CCD) is a duplicate, but marked as a sample, so gets through later filter
# change FIELD_QC_CODE == 'DU'
dat.clean$FIELD_QC_CODE <- ifelse(dat.clean$SAMPLE_ID == 'K7135', 'DU', dat.clean$FIELD_QC_CODE)
# get rid of columns that are unnecessary
dat.clean <- select(dat.clean, -c(1:7, 14:21))
# temporary fix for Benzo(a)anthracene - should have a broader match function
dat.clean$PARAM_SYNONYM[dat.clean$PARAM_SYNONYM %in% "Benzo(a)anthracene"] <- "Benz(a)anthracene"
# merge with compound metadata
dat.clean2 <- get_compound_info(pah_dat = dat.clean, merge_type = 'name', merge_col = 'PARAM_SYNONYM')
# create unique id for each site that combines state and 3-letter site ID
dat.clean2$unique_id <- paste0(dat.clean2$State, "-", dat.clean2$STAT_ID)
# export dat.clean
return(dat.clean2)
}
process_nondetects <- function(processed_sample_merge, detect.decision = "zero",
code.column = "LAB_QUAL", detect.code = "U",
detect.limit.column = "DETECT_LIMIT") {
if (detect.decision == 'zero') {
processed_sample <-
mutate(processed_sample_merge,
RESULT = ifelse(grepl(detect.code, processed_sample_merge[[code.column]]), 0, RESULT))
} else if (detect.decision == 'half'){
processed_sample <-
mutate(processed_sample_merge,
RESULT = ifelse(grepl(detect.code, processed_sample_merge[[code.column]]), 0.5*processed_sample_merge[[detect.limit.column]], RESULT))
}
}
process_mke <- function(raw = raw_5507) {
mke <- raw
# first, handle zeros in mke data by turning values below dl to 0
mke$remark_cd[is.na(mke$remark_cd)] <- "d" # if remark_cd is blank it's a detection
mke$remark_cd <- ifelse(mke$remark_cd == "E", "d", mke$remark_cd) # classify Estimated values as detections
mke$MKE<- ifelse(mke$remark_cd == "d", mke$result_va, 0)
return(mke)
}
process_5433 <- function(raw = raw_5433) {
mod_5433 <- mutate(raw, conc_5433 = ifelse(remark_cd %in% '<', 0, result_va))
return(mod_5433)
}
| /2_process_data/src/process_data.R | no_license | limnoliver/pah_glri | R | false | false | 5,093 | r | # script to process original raw data
# this is based on a number of notes made by Pete Lenaker in
# the file: 'M:/QW Monitoring Team/GLRI toxics/GLRI II/WY2017/Data/GLRI PAH Battelle Data Notes_READ ME'
process_sample_merge <- function(raw_sample, raw_site){
dat.clean <- raw_sample
dat.clean$STAT_ID[dat.clean$STAT_ID == "UJC"] <- "UCJ" # fix wrong site id for Underwood Creek
dat.clean$STAT_ID[dat.clean$STAT_ID == "CRO"] <- "CRP" # fix wrong site id for Underwood Creek
# create just a date (collection) column without time
dat.clean$COLLECTION_DATE_NOTIME <- as.Date(dat.clean$COLLECTION_DATE)
# create two datasets, one where there should be no issue merging by site,
# and the other where STAT_ID is duplicated across states
dat.clean.nodup <- filter(dat.clean, !(STAT_ID %in% c("CRM", "RRS", "RRR", "RRB")))
dat.clean.dup <- filter(dat.clean, (STAT_ID %in% c("CRM", "RRS", "RRR", "RRB")))
dat.clean.nodup <- left_join(dat.clean.nodup, raw_site, by = c("STAT_ID" = "Base.Field.ID"))
# fix spots where a STAT_ID was used by multiple states
#CRM
dat.clean.dup$State <- NA
dat.clean.dup$State[dat.clean.dup$STAT_ID == 'CRM' &
dat.clean.dup$COLLECTION_DATE_NOTIME == as.Date("2017-06-28")] <- "MI"
dat.clean.dup$State[dat.clean.dup$STAT_ID == 'CRM' &
dat.clean.dup$COLLECTION_DATE_NOTIME == as.Date("2017-06-07")] <- "OH"
#RRS
dat.clean.dup$State[dat.clean.dup$STAT_ID == 'RRS' &
dat.clean.dup$COLLECTION_DATE_NOTIME == as.Date("2017-06-28")] <- "MI"
dat.clean.dup$State[dat.clean.dup$STAT_ID == 'RRS' &
dat.clean.dup$COLLECTION_DATE_NOTIME == as.Date("2017-06-06")] <- "OH"
#RRR
dat.clean.dup$State[dat.clean.dup$STAT_ID == 'RRR' &
dat.clean.dup$COLLECTION_DATE_NOTIME == as.Date("2017-06-28")] <- "MI"
dat.clean.dup$State[dat.clean.dup$STAT_ID == 'RRR' &
dat.clean.dup$COLLECTION_DATE_NOTIME == as.Date("2017-06-07")] <- "WI"
#RRB
dat.clean.dup$State[dat.clean.dup$STAT_ID == 'RRB' &
dat.clean.dup$COLLECTION_DATE_NOTIME == as.Date("2017-06-28")] <- "MI"
dat.clean.dup$State[dat.clean.dup$STAT_ID == 'RRB' &
dat.clean.dup$COLLECTION_DATE_NOTIME == as.Date("2017-06-06")] <- "OH"
# now merge the cleaned up duplicates by STATID and state
dat.clean.dup <- left_join(dat.clean.dup, raw_site, by =c("STAT_ID" = "Base.Field.ID", "State"))
# append dat.clean.dup to dat.clean.nodup
dat.clean <- bind_rows(dat.clean.nodup, dat.clean.dup)
# get rid of samples that are "bad"
dat.clean <- filter(dat.clean, LAB_SAMPLE_ID != "K7216") # get rid of first sample taken at SLR
dat.clean <- filter(dat.clean, LAB_SAMPLE_ID != "K1708433-057") # some leftover data from first sample at SLR
dat.clean <- filter(dat.clean, !(STAT_ID == "BRO" & COLLECTION_DATE_NOTIME == as.Date("2017-06-21"))) # get rid of first sample at BRO
# sed sample ID K7135 (IN-CCD) is a duplicate, but marked as a sample, so gets through later filter
# change FIELD_QC_CODE == 'DU'
dat.clean$FIELD_QC_CODE <- ifelse(dat.clean$SAMPLE_ID == 'K7135', 'DU', dat.clean$FIELD_QC_CODE)
# get rid of columns that are unnecessary
dat.clean <- select(dat.clean, -c(1:7, 14:21))
# temporary fix for Benzo(a)anthracene - should have a broader match function
dat.clean$PARAM_SYNONYM[dat.clean$PARAM_SYNONYM %in% "Benzo(a)anthracene"] <- "Benz(a)anthracene"
# merge with compound metadata
dat.clean2 <- get_compound_info(pah_dat = dat.clean, merge_type = 'name', merge_col = 'PARAM_SYNONYM')
# create unique id for each site that combines state and 3-letter site ID
dat.clean2$unique_id <- paste0(dat.clean2$State, "-", dat.clean2$STAT_ID)
# export dat.clean
return(dat.clean2)
}
process_nondetects <- function(processed_sample_merge, detect.decision = "zero",
code.column = "LAB_QUAL", detect.code = "U",
detect.limit.column = "DETECT_LIMIT") {
if (detect.decision == 'zero') {
processed_sample <-
mutate(processed_sample_merge,
RESULT = ifelse(grepl(detect.code, processed_sample_merge[[code.column]]), 0, RESULT))
} else if (detect.decision == 'half'){
processed_sample <-
mutate(processed_sample_merge,
RESULT = ifelse(grepl(detect.code, processed_sample_merge[[code.column]]), 0.5*processed_sample_merge[[detect.limit.column]], RESULT))
}
}
process_mke <- function(raw = raw_5507) {
mke <- raw
# first, handle zeros in mke data by turning values below dl to 0
mke$remark_cd[is.na(mke$remark_cd)] <- "d" # if remark_cd is blank it's a detection
mke$remark_cd <- ifelse(mke$remark_cd == "E", "d", mke$remark_cd) # classify Estimated values as detections
mke$MKE<- ifelse(mke$remark_cd == "d", mke$result_va, 0)
return(mke)
}
process_5433 <- function(raw = raw_5433) {
mod_5433 <- mutate(raw, conc_5433 = ifelse(remark_cd %in% '<', 0, result_va))
return(mod_5433)
}
|
library(shiny)
library(shinyjs)
require(shinyWidgets)
library(shinyModulesTuto)
ui <- fluidPage(
useShinyjs(),
loadModulesCSS("modules_styling.css"),
tags$h1("Application with dynamic module calls"),
tags$br(),
fluidRow(
column(
width = 4,
panel(
heading = "Module : load_data",
status = "info",
load_datasetUI(id = "mod1")
)
)
),
fluidRow(
uiOutput("all_results")
)
)
server <- function(input, output, session) {
# List that contains all output UI from modules data_info dynamically called
rv <- list()
# ReactiveValues that "trick" the output renderUI
trick <- reactiveVal(1)
# Call module load_dataset
data_mod1 <- callModule(module = load_dataset, id = "mod1")
# When a new dataset is loaded, call dynamically the module 'data_info'
# And add an element to the list rv$all_ui that is rendered through a renderUI / tagList
observeEvent(data_mod1$trigger, {
req(data_mod1$trigger>0)
callModule(
module = data_info,
id = data_mod1$trigger,
data = data_mod1$data,
data_name = data_mod1$data_name
)
rv[[trick()]] <<- data_infoUI(id = data_mod1$trigger)
trick(trick() + 1)
})
output$all_results <- renderUI({
fool <- trick()
tagList(rv)
})
}
# Run the application
shinyApp(ui = ui, server = server, options = list(display.mode = "showcase"))
| /inst/applications/dynamic-call2/app.R | no_license | ardata-fr/Shiny-Modules-Tutorials | R | false | false | 1,542 | r | library(shiny)
library(shinyjs)
require(shinyWidgets)
library(shinyModulesTuto)
ui <- fluidPage(
useShinyjs(),
loadModulesCSS("modules_styling.css"),
tags$h1("Application with dynamic module calls"),
tags$br(),
fluidRow(
column(
width = 4,
panel(
heading = "Module : load_data",
status = "info",
load_datasetUI(id = "mod1")
)
)
),
fluidRow(
uiOutput("all_results")
)
)
server <- function(input, output, session) {
# List that contains all output UI from modules data_info dynamically called
rv <- list()
# ReactiveValues that "trick" the output renderUI
trick <- reactiveVal(1)
# Call module load_dataset
data_mod1 <- callModule(module = load_dataset, id = "mod1")
# When a new dataset is loaded, call dynamically the module 'data_info'
# And add an element to the list rv$all_ui that is rendered through a renderUI / tagList
observeEvent(data_mod1$trigger, {
req(data_mod1$trigger>0)
callModule(
module = data_info,
id = data_mod1$trigger,
data = data_mod1$data,
data_name = data_mod1$data_name
)
rv[[trick()]] <<- data_infoUI(id = data_mod1$trigger)
trick(trick() + 1)
})
output$all_results <- renderUI({
fool <- trick()
tagList(rv)
})
}
# Run the application
shinyApp(ui = ui, server = server, options = list(display.mode = "showcase"))
|
#Power Curves#
#n1=n2=6,n=6#
mu=c(0,0.1,0.2,0.5,0.8,0.9,0.95,0.98,1,1.2,1.5)
p=c(0.04559,0.0623,0.08435,0.18236,0.33245,0.38964,0.42036,0.43863,0.45049,0.57184,0.73988)
plot(mu,p,cex.lab=2,col="red",main="Power Curve for 4 different sample sizes",sub="red:curve for n=6,blue:curve for n=10,green:curve for n=15,black:curve for n=20")
par(new=TRUE)
#n1=n2=10,n=10#
mu=c(0,0.1,0.2,0.5,0.8,0.9,0.95,0.98,1,1.2,1.5)
p=c(0.05247,0.07939,0.11471,0.28244,0.52042,0.60289,0.64213,0.66431,0.67912,0.81042,0.93316)
plot(mu,p,cex.lab=2,col="blue")
par(new=TRUE)
#n1=n2=15,n=15#
mu=c(0,0.1,0.2,0.5,0.8,0.9,0.95,0.98,1,1.2,1.5)
p=c(0.04834,0.08092,0.12788,0.36321,0.66349,0.75184,0.79079,0.81251,0.82626,0.9264,0.98658)
plot(mu,p,cex.lab=2,col="green")
par(new=TRUE)
#n1=n2=20,n=20#
mu=c(0,0.1,0.2,0.5,0.8,0.9,0.95,0.98,1,1.2,1.5)
p=c(0.05139,0.09139,0.15183,0.45104,0.78414,0.8621,0.8921,0.90771,0.9174,0.97683,0.99812)
plot(mu,p,cex.lab=2,col="black") | /7.R | no_license | AnupriyaHalder99/Dissertation | R | false | false | 963 | r | #Power Curves#
#n1=n2=6,n=6#
mu=c(0,0.1,0.2,0.5,0.8,0.9,0.95,0.98,1,1.2,1.5)
p=c(0.04559,0.0623,0.08435,0.18236,0.33245,0.38964,0.42036,0.43863,0.45049,0.57184,0.73988)
plot(mu,p,cex.lab=2,col="red",main="Power Curve for 4 different sample sizes",sub="red:curve for n=6,blue:curve for n=10,green:curve for n=15,black:curve for n=20")
par(new=TRUE)
#n1=n2=10,n=10#
mu=c(0,0.1,0.2,0.5,0.8,0.9,0.95,0.98,1,1.2,1.5)
p=c(0.05247,0.07939,0.11471,0.28244,0.52042,0.60289,0.64213,0.66431,0.67912,0.81042,0.93316)
plot(mu,p,cex.lab=2,col="blue")
par(new=TRUE)
#n1=n2=15,n=15#
mu=c(0,0.1,0.2,0.5,0.8,0.9,0.95,0.98,1,1.2,1.5)
p=c(0.04834,0.08092,0.12788,0.36321,0.66349,0.75184,0.79079,0.81251,0.82626,0.9264,0.98658)
plot(mu,p,cex.lab=2,col="green")
par(new=TRUE)
#n1=n2=20,n=20#
mu=c(0,0.1,0.2,0.5,0.8,0.9,0.95,0.98,1,1.2,1.5)
p=c(0.05139,0.09139,0.15183,0.45104,0.78414,0.8621,0.8921,0.90771,0.9174,0.97683,0.99812)
plot(mu,p,cex.lab=2,col="black") |
library(kaphom)
### Name: mlscorehom
### Title: Modified Likelihood Score test for homogeneity of kappa
### statistics
### Aliases: mlscorehom
### ** Examples
library(kaphom)
pp <- c(11,26,22)
pm <- c(6,5,14)
mm <- c(22,10,39)
mlscorehom(pp,pm,mm)
| /data/genthat_extracted_code/kaphom/examples/mlscorehom.Rd.R | no_license | surayaaramli/typeRrh | R | false | false | 279 | r | library(kaphom)
### Name: mlscorehom
### Title: Modified Likelihood Score test for homogeneity of kappa
### statistics
### Aliases: mlscorehom
### ** Examples
library(kaphom)
pp <- c(11,26,22)
pm <- c(6,5,14)
mm <- c(22,10,39)
mlscorehom(pp,pm,mm)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/power_utils.R
\name{PlotPowerProfile}
\alias{PlotPowerProfile}
\title{Plot power profile}
\usage{
PlotPowerProfile(mSetObj=NA, fdr.lvl, smplSize, imgName, format, dpi, width)
}
\arguments{
\item{mSetObj}{Input the name of the created mSetObj (see InitDataObjects)}
\item{fdr.lvl}{Specify the false-discovery rate level.}
\item{smplSize}{Specify the maximum sample size, the number must be between 60-1000.}
\item{imgName}{Specify the name to save the image as.}
\item{format}{Specify the format of the image to save it as, either "png" or "pdf".}
\item{dpi}{Specify the dots-per-inch (dpi). By default it is 72, for publications
the recommended dpi is 300.}
\item{width}{Specify the width of the image. NA specifies a width of 9, 0 specifies a width
of 7, otherwise input a chosen width.}
}
\description{
Plot power profile, specifying FDR level and sample size. It will
return the image as well as the predicted power at various sample sizes.
}
\author{
Jeff Xia \email{jeff.xia@mcgill.ca}
McGill University, Canada
License: GNU GPL (>= 2)
}
| /man/PlotPowerProfile.Rd | permissive | xia-lab/MetaboAnalystR | R | false | true | 1,128 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/power_utils.R
\name{PlotPowerProfile}
\alias{PlotPowerProfile}
\title{Plot power profile}
\usage{
PlotPowerProfile(mSetObj=NA, fdr.lvl, smplSize, imgName, format, dpi, width)
}
\arguments{
\item{mSetObj}{Input the name of the created mSetObj (see InitDataObjects)}
\item{fdr.lvl}{Specify the false-discovery rate level.}
\item{smplSize}{Specify the maximum sample size, the number must be between 60-1000.}
\item{imgName}{Specify the name to save the image as.}
\item{format}{Specify the format of the image to save it as, either "png" or "pdf".}
\item{dpi}{Specify the dots-per-inch (dpi). By default it is 72, for publications
the recommended dpi is 300.}
\item{width}{Specify the width of the image. NA specifies a width of 9, 0 specifies a width
of 7, otherwise input a chosen width.}
}
\description{
Plot power profile, specifying FDR level and sample size. It will
return the image as well as the predicted power at various sample sizes.
}
\author{
Jeff Xia \email{jeff.xia@mcgill.ca}
McGill University, Canada
License: GNU GPL (>= 2)
}
|
context("Rendering a graph object")
test_that("rendering a graph is indeed possible", {
# Create a node data frame
ndf <-
create_node_df(
n = 26,
type = "letter",
shape = sample(c("circle", "rectangle"),
length(1:26),
replace = TRUE),
fillcolor = sample(c("steelblue", "gray80",
"#FFC0CB", "green",
"azure", NA),
length(1:26),
replace = TRUE))
# Create an edge data frame
edf <-
create_edge_df(
from = sample(1:26, replace = TRUE),
to = sample(1:26, replace = TRUE),
relationship = "letter_to_letter")
# Create the graph object using the node and
# edge data frames
graph <-
create_graph(
nodes_df = ndf,
edges_df = edf)
# Render the graph object and create a
# `grViz`/`htmlwidget` object
rendered_graph <- render_graph(graph)
# Expect that the `rendered_graph` object inherits
# from `grViz` & `htmlwidget`
expect_is(rendered_graph, c("grViz", "htmlwidget"))
})
test_that("rendering a graph from a series is also possible", {
# Create a set of graphs for a graph series
graph_1 <-
create_graph() %>%
add_node(1) %>%
add_node(2) %>%
add_node(3) %>%
add_edge(1, 3) %>%
add_edge(1, 2) %>%
add_edge(2, 3)
graph_2 <-
graph_1 %>%
add_node(4) %>%
add_edge(4, 3)
graph_3 <-
graph_2 %>%
add_node(5) %>%
add_edge(5, 2)
# Create an empty graph series
series <-
create_series(series_type = "sequential")
# Add graphs to the graph series
series <- graph_1 %>% add_to_series(series)
series <- graph_2 %>% add_to_series(series)
series <- graph_3 %>% add_to_series(series)
# View the second graph from the graph series in
# the RStudio Viewer
series_graph_2 <-
render_graph_from_series(
graph_series = series,
graph_no = 2)
# Expect error when rendering graph 4 from the
# series (which doesn't exist)
expect_error(
render_graph_from_series(
graph_series = series,
graph_no = 4))
# Expect that each of the graphs is different
expect_true(
render_graph_from_series(
graph_series = series,
graph_no = 1)$x$diagram !=
render_graph_from_series(
graph_series = series,
graph_no = 2)$x$diagram)
expect_true(
render_graph_from_series(
graph_series = series,
graph_no = 2)$x$diagram !=
render_graph_from_series(
graph_series = series,
graph_no = 3)$x$diagram)
expect_true(
render_graph_from_series(
graph_series = series,
graph_no = 1)$x$diagram !=
render_graph_from_series(
graph_series = series,
graph_no = 3)$x$diagram)
# Create an empty graph series
empty_series <-
create_series(series_type = "sequential")
# Expect an error if there are no graphs
# in the series
expect_error(
render_graph_from_series(
graph_series = empty_series))
})
| /tests/testthat/test-render_graph_series.R | no_license | DataXujing/DiagrammeR | R | false | false | 3,043 | r | context("Rendering a graph object")
test_that("rendering a graph is indeed possible", {
# Create a node data frame
ndf <-
create_node_df(
n = 26,
type = "letter",
shape = sample(c("circle", "rectangle"),
length(1:26),
replace = TRUE),
fillcolor = sample(c("steelblue", "gray80",
"#FFC0CB", "green",
"azure", NA),
length(1:26),
replace = TRUE))
# Create an edge data frame
edf <-
create_edge_df(
from = sample(1:26, replace = TRUE),
to = sample(1:26, replace = TRUE),
relationship = "letter_to_letter")
# Create the graph object using the node and
# edge data frames
graph <-
create_graph(
nodes_df = ndf,
edges_df = edf)
# Render the graph object and create a
# `grViz`/`htmlwidget` object
rendered_graph <- render_graph(graph)
# Expect that the `rendered_graph` object inherits
# from `grViz` & `htmlwidget`
expect_is(rendered_graph, c("grViz", "htmlwidget"))
})
test_that("rendering a graph from a series is also possible", {
# Create a set of graphs for a graph series
graph_1 <-
create_graph() %>%
add_node(1) %>%
add_node(2) %>%
add_node(3) %>%
add_edge(1, 3) %>%
add_edge(1, 2) %>%
add_edge(2, 3)
graph_2 <-
graph_1 %>%
add_node(4) %>%
add_edge(4, 3)
graph_3 <-
graph_2 %>%
add_node(5) %>%
add_edge(5, 2)
# Create an empty graph series
series <-
create_series(series_type = "sequential")
# Add graphs to the graph series
series <- graph_1 %>% add_to_series(series)
series <- graph_2 %>% add_to_series(series)
series <- graph_3 %>% add_to_series(series)
# View the second graph from the graph series in
# the RStudio Viewer
series_graph_2 <-
render_graph_from_series(
graph_series = series,
graph_no = 2)
# Expect error when rendering graph 4 from the
# series (which doesn't exist)
expect_error(
render_graph_from_series(
graph_series = series,
graph_no = 4))
# Expect that each of the graphs is different
expect_true(
render_graph_from_series(
graph_series = series,
graph_no = 1)$x$diagram !=
render_graph_from_series(
graph_series = series,
graph_no = 2)$x$diagram)
expect_true(
render_graph_from_series(
graph_series = series,
graph_no = 2)$x$diagram !=
render_graph_from_series(
graph_series = series,
graph_no = 3)$x$diagram)
expect_true(
render_graph_from_series(
graph_series = series,
graph_no = 1)$x$diagram !=
render_graph_from_series(
graph_series = series,
graph_no = 3)$x$diagram)
# Create an empty graph series
empty_series <-
create_series(series_type = "sequential")
# Expect an error if there are no graphs
# in the series
expect_error(
render_graph_from_series(
graph_series = empty_series))
})
|
##### function for calculating the rank-order correlations between two performed MAGMA protocols #####
# author: Juliska E Boer
# date: 04 Nov 2020
calc_rank_cor <- function(kyoko, skene, all){
kyoko$R = rank(kyoko$P)
skene$R = rank(skene$P)
if (all==TRUE){
colnames(kyoko) = c("VARIABLE", "P-kyoko", "Dataset", "Rkyoko")
colnames(skene) = c("VARIABLE", "p-skene", "Rskene")
}
else {
colnames(kyoko) = c("VARIABLE", "P-kyoko", "Rkyoko")
colnames(skene) = c("VARIABLE", "p-skene", "Rskene")
}
both = full_join(kyoko, skene, by="VARIABLE")
both$d = abs(both$`Rkyoko`-both$`Rskene`)
both$d2 = (both$d^2)
sum_d2 = sum(both$d2)
n = dim(both)[1]
rs = (1 - ((6*sum_d2)/(n*((n^2) - 1))))
to.return = list(rs, as.data.frame(both))
return(to.return)
} | /MAGMA/Plots/MAGMA_RankOrderFunct.R | no_license | liekevandehaar/Dev_Hb_mouse | R | false | false | 786 | r | ##### function for calculating the rank-order correlations between two performed MAGMA protocols #####
# author: Juliska E Boer
# date: 04 Nov 2020
calc_rank_cor <- function(kyoko, skene, all){
kyoko$R = rank(kyoko$P)
skene$R = rank(skene$P)
if (all==TRUE){
colnames(kyoko) = c("VARIABLE", "P-kyoko", "Dataset", "Rkyoko")
colnames(skene) = c("VARIABLE", "p-skene", "Rskene")
}
else {
colnames(kyoko) = c("VARIABLE", "P-kyoko", "Rkyoko")
colnames(skene) = c("VARIABLE", "p-skene", "Rskene")
}
both = full_join(kyoko, skene, by="VARIABLE")
both$d = abs(both$`Rkyoko`-both$`Rskene`)
both$d2 = (both$d^2)
sum_d2 = sum(both$d2)
n = dim(both)[1]
rs = (1 - ((6*sum_d2)/(n*((n^2) - 1))))
to.return = list(rs, as.data.frame(both))
return(to.return)
} |
#
# This test file has been generated by kwb.test::create_test_files()
#
test_that("vs2dh.ConfigureBoundaryFluxes() works", {
kwb.vs2dh:::vs2dh.ConfigureBoundaryFluxes()
})
| /tests/testthat/test-function-vs2dh.ConfigureBoundaryFluxes.R | permissive | KWB-R/kwb.vs2dh | R | false | false | 179 | r | #
# This test file has been generated by kwb.test::create_test_files()
#
test_that("vs2dh.ConfigureBoundaryFluxes() works", {
kwb.vs2dh:::vs2dh.ConfigureBoundaryFluxes()
})
|
testlist <- list(x = c(NA, 0L, 0L, 0L), y = integer(0))
result <- do.call(diffrprojects:::dist_mat_absolute,testlist)
str(result) | /diffrprojects/inst/testfiles/dist_mat_absolute/libFuzzer_dist_mat_absolute/dist_mat_absolute_valgrind_files/1609961548-test.R | no_license | akhikolla/updated-only-Issues | R | false | false | 129 | r | testlist <- list(x = c(NA, 0L, 0L, 0L), y = integer(0))
result <- do.call(diffrprojects:::dist_mat_absolute,testlist)
str(result) |
#' Basic function to convert human to mouse gene names
#' @export
convertHumanGeneList <- function(x){
human <- useMart("ensembl", dataset = "hsapiens_gene_ensembl")
mouse <- useMart("ensembl", dataset = "mmusculus_gene_ensembl")
tmp <- getLDS(attributes = c("hgnc_symbol"), filters = "hgnc_symbol", values = x , mart = human, attributesL = c("mgi_symbol"), martL = mouse, uniqueRows=TRUE)
mousex <- unique(tmp[,2])
return(mousex)
}
| /R/humanMouseConversion.R | no_license | vincent-van-hoef/myFunctions | R | false | false | 439 | r | #' Basic function to convert human to mouse gene names
#' @export
convertHumanGeneList <- function(x){
human <- useMart("ensembl", dataset = "hsapiens_gene_ensembl")
mouse <- useMart("ensembl", dataset = "mmusculus_gene_ensembl")
tmp <- getLDS(attributes = c("hgnc_symbol"), filters = "hgnc_symbol", values = x , mart = human, attributesL = c("mgi_symbol"), martL = mouse, uniqueRows=TRUE)
mousex <- unique(tmp[,2])
return(mousex)
}
|
#' rerf-package
#'
#' The rerf package provides an R implementation of the randomer forest
#' algorithm developed by Tomita et al.(2016) <arXiv:1506.03410v2>,
#' along with variants such as Structured Randomer Forest (S-RerF) and
#' Similarity Randomer Forest (SmerF).
#'
#'
#' @section The main function \code{RerF}:
#' The \code{RerF} function is the primary access point to the
#' algorithm. Variants of the algorithm can be controlled by specifying
#' the appropriate set of parameters, explained in the sections below.
#'
#' @section RandMat*:
#' The set of \code{RandMat*} functions specify the distribution of
#' projection weights used to split the data at each node.
#'
#' \describe{
#' \item{RandMatBinary}{samples projection weights from \eqn{{-1,1}}.}
#' \item{RandMatContinuous}{samples projection weights from \eqn{N(0,1)}}
#' \item{RandMatPoisson}{samples projection weights from a \eqn{N(0,1)} with sparsity \eqn{~ Poisson(\lambda)}}
#' }
#'
#' @section RerF variants:
#' \describe{
#' \item{RF}{Use \code{FUN = RandMatRF} in the call to \code{RerF}}
#' \item{RerF}{Use \code{FUN = RandMatBinary} in the call to \code{RerF}}
#' \item{S-RerF}{Use \code{FUN = RandMatImagePatch} in the call to \code{RerF}}
#' \item{SmerF}{Set \code{task = "similarity"} in the call to \code{RerF}}
#' }
#'
#'
"_PACKAGE"
| /R-Project/R/rerf-package.R | permissive | neurodata/SPORF | R | false | false | 1,338 | r | #' rerf-package
#'
#' The rerf package provides an R implementation of the randomer forest
#' algorithm developed by Tomita et al.(2016) <arXiv:1506.03410v2>,
#' along with variants such as Structured Randomer Forest (S-RerF) and
#' Similarity Randomer Forest (SmerF).
#'
#'
#' @section The main function \code{RerF}:
#' The \code{RerF} function is the primary access point to the
#' algorithm. Variants of the algorithm can be controlled by specifying
#' the appropriate set of parameters, explained in the sections below.
#'
#' @section RandMat*:
#' The set of \code{RandMat*} functions specify the distribution of
#' projection weights used to split the data at each node.
#'
#' \describe{
#' \item{RandMatBinary}{samples projection weights from \eqn{{-1,1}}.}
#' \item{RandMatContinuous}{samples projection weights from \eqn{N(0,1)}}
#' \item{RandMatPoisson}{samples projection weights from a \eqn{N(0,1)} with sparsity \eqn{~ Poisson(\lambda)}}
#' }
#'
#' @section RerF variants:
#' \describe{
#' \item{RF}{Use \code{FUN = RandMatRF} in the call to \code{RerF}}
#' \item{RerF}{Use \code{FUN = RandMatBinary} in the call to \code{RerF}}
#' \item{S-RerF}{Use \code{FUN = RandMatImagePatch} in the call to \code{RerF}}
#' \item{SmerF}{Set \code{task = "similarity"} in the call to \code{RerF}}
#' }
#'
#'
"_PACKAGE"
|
\name{add-package}
\alias{add-package}
\docType{package}
\title{
\packageTitle{add}
}
\description{
\packageDescription{add}
}
\details{
The DESCRIPTION file:
\packageDESCRIPTION{add}
\packageIndices{add}
The package is a minimal example including function \code{add()} which
is trivial.
}
\author{
\packageAuthor{add}
Maintainer: \packageMaintainer{add}
}
\keyword{ package }
\examples{
add(2,3)
}
| /man/add-package.Rd | no_license | RobinHankin/add | R | false | false | 402 | rd | \name{add-package}
\alias{add-package}
\docType{package}
\title{
\packageTitle{add}
}
\description{
\packageDescription{add}
}
\details{
The DESCRIPTION file:
\packageDESCRIPTION{add}
\packageIndices{add}
The package is a minimal example including function \code{add()} which
is trivial.
}
\author{
\packageAuthor{add}
Maintainer: \packageMaintainer{add}
}
\keyword{ package }
\examples{
add(2,3)
}
|
## Nothing to Export.
## this is a bit messy. (model, section) picks out the right model in
## the correct section. this model has a default setting for
## 'hyper'. simply replace these entries with given ones, first in
## 'hyper', then in 'initial', 'fixed', 'prior' and 'param'. somewhat
## tricky is that the length in 'param' depends on the argument(s) of
## 'prior' as various priors can have different number of
## parameters. also, if NA or NULL is given, then we use the default
## ones.
## I think its a better strategy to take initial, fixed, prior, param
## and make a hyper-similar structure and then merge these two. the
## current code is messy but does not have to be.
inla.set.hyper = function(
model = NULL,
section = NULL,
hyper = NULL,
initial = NULL,
fixed = NULL,
prior = NULL,
param = NULL,
debug = FALSE,
hyper.default = NULL)
{
## name of the list can be in any CASE, and a longer name is ok,
## like 'list(precision=list(...))' where the 'name="prec"'.
skip.final.check = FALSE
if (is.null(section))
stop("No section given; please fix...")
mm = inla.models()
section = match.arg(section, names(mm))
if (is.null(hyper.default)) {
## default values are given in the inla.models()
hyper.new = inla.model.properties(model, section)$hyper
} else {
## default values are given by the user. process these
hyper.new = inla.set.hyper(model, section, hyper = hyper.default, debug = debug)
}
nhyper = length(hyper.new)
if (debug) {
cat(paste("* Get default hyper from model", model, "in section", section), "\n")
}
if (nhyper == 0L) {
if (!is.null(hyper) && !identical(hyper, list())) {
stop(inla.paste(c("Model", model, "[", section,
"], has none hyperparameters, but 'hyper' is ",
inla.paste(list(hyper))), sep = " "))
}
if (!is.null(initial) && length(initial) > 0L) {
stop(inla.paste(c("Model", model, "[", section, "], has none hyperparameters, but 'initial' is ",
initial), sep=" "))
}
if (!is.null(fixed) && length(fixed) > 0L) {
stop(inla.paste(c("Model", model, "[", section, "], has none hyperparameters, but 'fixed' is",
fixed), sep=" "))
}
if (!is.null(param) && length(param) > 0L) {
stop(inla.paste(c("Model", model, "[", section, "], has none hyperparameters, but 'param' is",
param), sep=" "))
}
if (!is.null(prior) && length(prior) > 0L) {
stop(inla.paste(c("Model", model, "[", section, "], has none hyperparameters, but 'prior' is",
param), sep=" "))
}
return (hyper.new)
}
if (!is.null(hyper)) {
for (nm in names(hyper)) {
if (debug) {
cat(paste("* Check contents of given hyper$", nm, sep=""), "\n")
}
valid.keywords = c(
"theta",
paste("theta", 1L:nhyper, sep=""),
as.character(sapply(hyper.new, function(x) x$short.name)),
as.character(sapply(hyper.new, function(x) x$name)))
if (is.null(nm)) {
stop(paste("Missing name/keyword in `hyper'; must be one of ", inla.paste(valid.keywords), ".",
sep=" "))
}
if (!any(inla.strcasecmp(nm, valid.keywords))) {
stop(paste("Unknown keyword in `hyper' `", nm,
"'. Must be one of ", inla.paste(valid.keywords), ".", sep=" "))
}
}
}
## need `prior' to be before `param'!
keywords = c("initial", "fixed", "prior", "param")
off = list(0L, 0L, 0L, 0L)
names(off) = keywords
## do each hyperparameter one by time. fill into `hyper.new'
for(ih in 1L:nhyper) {
if (debug) {
cat(paste("** Check hyperparameter", ih, "with name", names(hyper.new)[ih]), "\n")
}
## find idx in the new one
idx.new = which(names(hyper.new) == paste("theta", ih, sep=""))
if (ih == 1L && length(idx.new) == 0L) {
idx.new = which(names(hyper.new) == "theta")
}
stopifnot(length(idx.new) > 0L)
name = hyper.new[[idx.new]]$name ## full name
short.name = hyper.new[[idx.new]]$short.name ## short name
stopifnot(!is.null(short.name))
if (debug) {
cat(paste("** idx.new =", idx.new), "\n")
}
if (!is.null(hyper)) {
## find idx in the given one
idx = which(names(hyper) == paste("theta", ih, sep=""))
if (length(idx) == 0L && nhyper == 1L) {
idx = which(names(hyper) == "theta")
}
if (length(idx) == 0L) {
idx = which(inla.strcasecmp(names(hyper), name))
}
if (length(idx) == 0L) {
idx = which(inla.strcasecmp(names(hyper), short.name))
}
if (length(idx) == 0L) {
h = NULL
idx = NULL
} else {
h = hyper[[idx]]
if (!is.list(h)) {
stop(paste("Argument `hyper$theta", ih, "' or `", short.name,
"' or `", name, "', is not a list: ", h, sep=""))
}
}
if (debug) {
cat(paste("** Corresponding idx in given hyper =", idx), "\n")
if (is.null(h)) {
cat(paste("*** h is NULL"), "\n")
} else {
cat(paste("*** h is !NULL"), "\n")
}
}
} else {
h = NULL
idx = NULL
}
for (key in keywords) {
key.val = inla.eval(key)
if (debug) {
cat(paste("*** Process key =", key), "\n")
cat(inla.paste("*** key =", inla.ifelse(is.null(key.val) || (is.numeric(key.val) && length(key.val)==0),
"NULL", as.character(key.val))), "\n")
}
## special case. if attribute is set to 'read only' then refuse to change value
read.only = attr(hyper.new[[idx.new]][[key]], "inla.read.only")
if (!is.null(read.only) && read.only == TRUE) {
if (!is.null(h[[key]]) && h[[key]] != hyper.new[[idx.new]][[key]])
stop(paste("Setting hyperparameter `", name,
"'. Key `", key, "' = '", hyper.new[[idx.new]][[key]],
"' is 'read-only', cannot change to `", h[[key]], "'.", sep=""))
ii = idx.new + off[[key]]
if (!is.null(key.val) && !is.na(key.val[ii])) {
if (key.val[ii] != hyper.new[[idx.new]][[key]]) {
stop(paste("Setting hyperparameter `", name,
"'. Key `", key,"' = '", hyper.new[[idx.new]][[key]],
"' is 'read-only', cannot change to `", key.val[ii], "'.", sep=""))
}
}
}
## start of cmd is here
if (!is.null(key.val)) {
## known length
if (key == "param") {
len = inla.model.properties(hyper.new[[idx.new]]$prior, "prior")$nparameters
if (len < 0L) {
## this is a special case, where the number of
## parameters in the prior vary. first example
## is the spde2/spde3 model. in this case, we just
## eat all the remaining parameters.
skip.final.check = TRUE
} else {
## this is the normal case
if (len <= length(hyper.new[[idx.new]][[key]])) {
if (len > 0L) {
hyper.new[[idx.new]][[key]] = hyper.new[[idx.new]][[key]][1L:len]
} else if (len == 0L) {
hyper.new[[idx.new]][[key]] = numeric(0L)
} else {
stop("SHOULD NOT HAPPEN")
}
} else if (len > length(hyper.new[[idx.new]][[key]])) {
hyper.new[[idx.new]][[key]] = c(hyper.new[[idx.new]][[key]],
rep(NA, len - length(hyper.new[[idx.new]][[key]])))
} else {
stop("SHOULD NOT HAPPEN")
}
}
} else {
len = length(hyper.new[[idx.new]][[key]])
}
## given length
llen = length(key.val) - off[[key]]
if (llen < len) {
key.val = c(key.val, rep(NA, len - llen))
}
if (llen >= 0L) {
if (len < 0L) {
if (debug) {
cat(inla.paste(c("*** Replace hyper.new|", idx.new, "|", key, "|", idxx, " with ", key.val)), "\n")
}
hyper.new[[idx.new]][[key]] = key.val
} else {
if (len > 0L) {
## set those NA's to the default ones
ii = key.val[off[[key]] + 1L:len]
idxx = which(!(is.na(ii) | is.null(ii)))
if (length(idxx) > 0L) {
if (debug) {
cat(inla.paste(c("*** Replace hyper.new|", idx.new, "|", key, "|", idxx, " with ", ii[idxx])), "\n")
}
hyper.new[[idx.new]][[key]][idxx] = ii[idxx]
}
}
}
off[[key]] = off[[key]] + len
}
}
test.val = (!is.null(h) && !is.null(h[[key]]) && !(is.na(h[[key]])))
if (debug) {
cat(paste("*** test.val =", test.val), "\n")
}
if (is.na(test.val) || test.val) {
## known length
if (key == "param") {
len = inla.model.properties(hyper.new[[idx.new]]$prior, "prior")$nparameters
if (debug) {
cat(paste("*** nparam =", len), "\n")
}
if (len < 0L) {
## see explanation above
skip.final.check = TRUE
hyper.new[[idx.new]][[key]] = h[[key]]
} else {
## normal case
if (len < length(hyper.new[[idx.new]][[key]]) && len > 0L) {
hyper.new[[idx.new]][[key]] = hyper.new[[idx.new]][[key]][1L:len]
} else if (len < length(hyper.new[[idx.new]][[key]]) && len == 0L) {
hyper.new[[idx.new]][[key]] = NULL
} else if (len > length(hyper.new[[idx.new]][[key]])) {
hyper.new[[idx.new]][[key]] = c(hyper.new[[idx.new]][[key]],
rep(NA, len - length(hyper.new[[idx.new]][[key]])))
}
}
} else {
len = length(hyper.new[[idx.new]][[key]])
}
## given length
llen = length(h[[key]])
if (len >= 0L) {
if (llen > len) {
stop(paste("model", model, "[", section, "], hyperparam", ih, ", length(hyper[[key]]) =",
llen, ">", len, sep = " "))
} else if (llen < len) {
h[[key]] = c(h[[key]], rep(NA, len - llen))
}
}
if (len != 0L) {
## set those NA's to the default ones
idxx = which(!is.na(h[[key]]) & !is.null(h[[key]]))
if (length(idxx) > 0L) {
if (debug) {
cat(inla.paste(c("*** Replace hyper.new|", idx.new, "|", key, "|", idxx, " with h|", key, "|", idxx,
"=", h[[key]][idxx])), "\n")
}
hyper.new[[idx.new]][[key]][idxx] = h[[key]][idxx]
}
}
}
if (key == "param") {
ans = inla.model.properties(hyper.new[[idx.new]]$prior, "prior", stop.on.error = TRUE)
if (ans$nparameters >= 0L) {
if (length(hyper.new[[idx.new]]$param) != ans$nparameters) {
stop(paste("Wrong length of prior-parameters, prior `", hyper.new[[idx.new]]$prior, "' needs ",
ans$nparameters, " parameters, you have ",
length(hyper.new[[idx.new]]$param), ".", sep=""))
}
}
}
}
}
for (key in keywords) {
key.val = inla.eval(key)
if (key != "param" || (key == "param" && !skip.final.check)) {
if (!is.null(key.val) && (length(key.val) > off[[key]])) {
stop(paste("Length of argument `", key, "' is ", length(key.val),
", does not match the total length of `", key, "' in `hyper' which is ", off[[key]], sep=""))
}
}
}
return (hyper.new)
}
| /rinla/R/hyper.R | no_license | ThierryO/r-inla | R | false | false | 14,096 | r | ## Nothing to Export.
## this is a bit messy. (model, section) picks out the right model in
## the correct section. this model has a default setting for
## 'hyper'. simply replace these entries with given ones, first in
## 'hyper', then in 'initial', 'fixed', 'prior' and 'param'. somewhat
## tricky is that the length in 'param' depends on the argument(s) of
## 'prior' as various priors can have different number of
## parameters. also, if NA or NULL is given, then we use the default
## ones.
## I think its a better strategy to take initial, fixed, prior, param
## and make a hyper-similar structure and then merge these two. the
## current code is messy but does not have to be.
inla.set.hyper = function(
model = NULL,
section = NULL,
hyper = NULL,
initial = NULL,
fixed = NULL,
prior = NULL,
param = NULL,
debug = FALSE,
hyper.default = NULL)
{
## name of the list can be in any CASE, and a longer name is ok,
## like 'list(precision=list(...))' where the 'name="prec"'.
skip.final.check = FALSE
if (is.null(section))
stop("No section given; please fix...")
mm = inla.models()
section = match.arg(section, names(mm))
if (is.null(hyper.default)) {
## default values are given in the inla.models()
hyper.new = inla.model.properties(model, section)$hyper
} else {
## default values are given by the user. process these
hyper.new = inla.set.hyper(model, section, hyper = hyper.default, debug = debug)
}
nhyper = length(hyper.new)
if (debug) {
cat(paste("* Get default hyper from model", model, "in section", section), "\n")
}
if (nhyper == 0L) {
if (!is.null(hyper) && !identical(hyper, list())) {
stop(inla.paste(c("Model", model, "[", section,
"], has none hyperparameters, but 'hyper' is ",
inla.paste(list(hyper))), sep = " "))
}
if (!is.null(initial) && length(initial) > 0L) {
stop(inla.paste(c("Model", model, "[", section, "], has none hyperparameters, but 'initial' is ",
initial), sep=" "))
}
if (!is.null(fixed) && length(fixed) > 0L) {
stop(inla.paste(c("Model", model, "[", section, "], has none hyperparameters, but 'fixed' is",
fixed), sep=" "))
}
if (!is.null(param) && length(param) > 0L) {
stop(inla.paste(c("Model", model, "[", section, "], has none hyperparameters, but 'param' is",
param), sep=" "))
}
if (!is.null(prior) && length(prior) > 0L) {
stop(inla.paste(c("Model", model, "[", section, "], has none hyperparameters, but 'prior' is",
param), sep=" "))
}
return (hyper.new)
}
if (!is.null(hyper)) {
for (nm in names(hyper)) {
if (debug) {
cat(paste("* Check contents of given hyper$", nm, sep=""), "\n")
}
valid.keywords = c(
"theta",
paste("theta", 1L:nhyper, sep=""),
as.character(sapply(hyper.new, function(x) x$short.name)),
as.character(sapply(hyper.new, function(x) x$name)))
if (is.null(nm)) {
stop(paste("Missing name/keyword in `hyper'; must be one of ", inla.paste(valid.keywords), ".",
sep=" "))
}
if (!any(inla.strcasecmp(nm, valid.keywords))) {
stop(paste("Unknown keyword in `hyper' `", nm,
"'. Must be one of ", inla.paste(valid.keywords), ".", sep=" "))
}
}
}
## need `prior' to be before `param'!
keywords = c("initial", "fixed", "prior", "param")
off = list(0L, 0L, 0L, 0L)
names(off) = keywords
## do each hyperparameter one by time. fill into `hyper.new'
for(ih in 1L:nhyper) {
if (debug) {
cat(paste("** Check hyperparameter", ih, "with name", names(hyper.new)[ih]), "\n")
}
## find idx in the new one
idx.new = which(names(hyper.new) == paste("theta", ih, sep=""))
if (ih == 1L && length(idx.new) == 0L) {
idx.new = which(names(hyper.new) == "theta")
}
stopifnot(length(idx.new) > 0L)
name = hyper.new[[idx.new]]$name ## full name
short.name = hyper.new[[idx.new]]$short.name ## short name
stopifnot(!is.null(short.name))
if (debug) {
cat(paste("** idx.new =", idx.new), "\n")
}
if (!is.null(hyper)) {
## find idx in the given one
idx = which(names(hyper) == paste("theta", ih, sep=""))
if (length(idx) == 0L && nhyper == 1L) {
idx = which(names(hyper) == "theta")
}
if (length(idx) == 0L) {
idx = which(inla.strcasecmp(names(hyper), name))
}
if (length(idx) == 0L) {
idx = which(inla.strcasecmp(names(hyper), short.name))
}
if (length(idx) == 0L) {
h = NULL
idx = NULL
} else {
h = hyper[[idx]]
if (!is.list(h)) {
stop(paste("Argument `hyper$theta", ih, "' or `", short.name,
"' or `", name, "', is not a list: ", h, sep=""))
}
}
if (debug) {
cat(paste("** Corresponding idx in given hyper =", idx), "\n")
if (is.null(h)) {
cat(paste("*** h is NULL"), "\n")
} else {
cat(paste("*** h is !NULL"), "\n")
}
}
} else {
h = NULL
idx = NULL
}
for (key in keywords) {
key.val = inla.eval(key)
if (debug) {
cat(paste("*** Process key =", key), "\n")
cat(inla.paste("*** key =", inla.ifelse(is.null(key.val) || (is.numeric(key.val) && length(key.val)==0),
"NULL", as.character(key.val))), "\n")
}
## special case. if attribute is set to 'read only' then refuse to change value
read.only = attr(hyper.new[[idx.new]][[key]], "inla.read.only")
if (!is.null(read.only) && read.only == TRUE) {
if (!is.null(h[[key]]) && h[[key]] != hyper.new[[idx.new]][[key]])
stop(paste("Setting hyperparameter `", name,
"'. Key `", key, "' = '", hyper.new[[idx.new]][[key]],
"' is 'read-only', cannot change to `", h[[key]], "'.", sep=""))
ii = idx.new + off[[key]]
if (!is.null(key.val) && !is.na(key.val[ii])) {
if (key.val[ii] != hyper.new[[idx.new]][[key]]) {
stop(paste("Setting hyperparameter `", name,
"'. Key `", key,"' = '", hyper.new[[idx.new]][[key]],
"' is 'read-only', cannot change to `", key.val[ii], "'.", sep=""))
}
}
}
## start of cmd is here
if (!is.null(key.val)) {
## known length
if (key == "param") {
len = inla.model.properties(hyper.new[[idx.new]]$prior, "prior")$nparameters
if (len < 0L) {
## this is a special case, where the number of
## parameters in the prior vary. first example
## is the spde2/spde3 model. in this case, we just
## eat all the remaining parameters.
skip.final.check = TRUE
} else {
## this is the normal case
if (len <= length(hyper.new[[idx.new]][[key]])) {
if (len > 0L) {
hyper.new[[idx.new]][[key]] = hyper.new[[idx.new]][[key]][1L:len]
} else if (len == 0L) {
hyper.new[[idx.new]][[key]] = numeric(0L)
} else {
stop("SHOULD NOT HAPPEN")
}
} else if (len > length(hyper.new[[idx.new]][[key]])) {
hyper.new[[idx.new]][[key]] = c(hyper.new[[idx.new]][[key]],
rep(NA, len - length(hyper.new[[idx.new]][[key]])))
} else {
stop("SHOULD NOT HAPPEN")
}
}
} else {
len = length(hyper.new[[idx.new]][[key]])
}
## given length
llen = length(key.val) - off[[key]]
if (llen < len) {
key.val = c(key.val, rep(NA, len - llen))
}
if (llen >= 0L) {
if (len < 0L) {
if (debug) {
cat(inla.paste(c("*** Replace hyper.new|", idx.new, "|", key, "|", idxx, " with ", key.val)), "\n")
}
hyper.new[[idx.new]][[key]] = key.val
} else {
if (len > 0L) {
## set those NA's to the default ones
ii = key.val[off[[key]] + 1L:len]
idxx = which(!(is.na(ii) | is.null(ii)))
if (length(idxx) > 0L) {
if (debug) {
cat(inla.paste(c("*** Replace hyper.new|", idx.new, "|", key, "|", idxx, " with ", ii[idxx])), "\n")
}
hyper.new[[idx.new]][[key]][idxx] = ii[idxx]
}
}
}
off[[key]] = off[[key]] + len
}
}
test.val = (!is.null(h) && !is.null(h[[key]]) && !(is.na(h[[key]])))
if (debug) {
cat(paste("*** test.val =", test.val), "\n")
}
if (is.na(test.val) || test.val) {
## known length
if (key == "param") {
len = inla.model.properties(hyper.new[[idx.new]]$prior, "prior")$nparameters
if (debug) {
cat(paste("*** nparam =", len), "\n")
}
if (len < 0L) {
## see explanation above
skip.final.check = TRUE
hyper.new[[idx.new]][[key]] = h[[key]]
} else {
## normal case
if (len < length(hyper.new[[idx.new]][[key]]) && len > 0L) {
hyper.new[[idx.new]][[key]] = hyper.new[[idx.new]][[key]][1L:len]
} else if (len < length(hyper.new[[idx.new]][[key]]) && len == 0L) {
hyper.new[[idx.new]][[key]] = NULL
} else if (len > length(hyper.new[[idx.new]][[key]])) {
hyper.new[[idx.new]][[key]] = c(hyper.new[[idx.new]][[key]],
rep(NA, len - length(hyper.new[[idx.new]][[key]])))
}
}
} else {
len = length(hyper.new[[idx.new]][[key]])
}
## given length
llen = length(h[[key]])
if (len >= 0L) {
if (llen > len) {
stop(paste("model", model, "[", section, "], hyperparam", ih, ", length(hyper[[key]]) =",
llen, ">", len, sep = " "))
} else if (llen < len) {
h[[key]] = c(h[[key]], rep(NA, len - llen))
}
}
if (len != 0L) {
## set those NA's to the default ones
idxx = which(!is.na(h[[key]]) & !is.null(h[[key]]))
if (length(idxx) > 0L) {
if (debug) {
cat(inla.paste(c("*** Replace hyper.new|", idx.new, "|", key, "|", idxx, " with h|", key, "|", idxx,
"=", h[[key]][idxx])), "\n")
}
hyper.new[[idx.new]][[key]][idxx] = h[[key]][idxx]
}
}
}
if (key == "param") {
ans = inla.model.properties(hyper.new[[idx.new]]$prior, "prior", stop.on.error = TRUE)
if (ans$nparameters >= 0L) {
if (length(hyper.new[[idx.new]]$param) != ans$nparameters) {
stop(paste("Wrong length of prior-parameters, prior `", hyper.new[[idx.new]]$prior, "' needs ",
ans$nparameters, " parameters, you have ",
length(hyper.new[[idx.new]]$param), ".", sep=""))
}
}
}
}
}
for (key in keywords) {
key.val = inla.eval(key)
if (key != "param" || (key == "param" && !skip.final.check)) {
if (!is.null(key.val) && (length(key.val) > off[[key]])) {
stop(paste("Length of argument `", key, "' is ", length(key.val),
", does not match the total length of `", key, "' in `hyper' which is ", off[[key]], sep=""))
}
}
}
return (hyper.new)
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/AllGenerics.R, R/cluster.R
\docType{methods}
\name{cluster}
\alias{cluster}
\alias{cluster,daFrame-method}
\title{FlowSOM clustering & ConsensusClusterPlus metaclustering}
\usage{
cluster(x, ...)
\S4method{cluster}{daFrame}(x, cols_to_use, xdim = 10, ydim = 10,
maxK = 20, seed = 1)
}
\arguments{
\item{x}{a \code{\link{daFrame}}.}
\item{...}{optional arguments.}
\item{cols_to_use}{a character vector. Specifies which antigens to use for clustering.}
\item{xdim, ydim}{numeric. Specify the grid size of the self-orginizing map.
The default 10x10 grid will yield 100 clusters.}
\item{maxK}{numeric. Specifies the maximum number of clusters to evaluate
in the metaclustering. For \code{maxK = 20}, for example,
metaclustering will be performed for 2 through 20 clusters.}
\item{seed}{numeric. Sets random seed in \code{ConsensusClusterPlus()}.}
}
\value{
The function will add information to the following slots
of the input \code{daFrame} (and return it):
\itemize{
\item{\code{rowData}\describe{\itemize{
\item{\code{cluster_id}:
each cell's cluster ID as inferred by \code{FlowSOM}.
One of 1, ..., \code{xdim}x\code{ydim}}.}
}}
\item{\code{colData}\describe{\itemize{
\item{\code{marker_class}:
\code{"type"} or \code{"state"}.
Specifies whether an antigen has been used for clustering
or not, respectively.}}
}}
\item{\code{metadata}\describe{\itemize{
\item{\code{SOM_codes}:
a table with dimensions K x (# cell type markers),
where K = \code{xdim} x \code{ydim}. Contains the SOM codes.}
\item{\code{cluster_codes}:
a table with dimensions K x (\code{maxK} + 1).
Contains the cluster codes for all metaclustering.}
\item{\code{delta_area}:
a \code{\link{ggplot}} object. See above for details.}}
}}
}
}
\description{
\code{cluster} will first group cells into \code{xdim}x\code{ydim}
clusters using \pkg{FlowSOM}, and subsequently perform metaclustering
with \pkg{ConsensusClusterPlus} into 2 through \code{maxK} clusters.
In the returned \code{daFrame}, those antigens used for clustering will be
labelled as '\code{type}' markers, and the remainder of antigens as
'\code{state}' markers.
}
\details{
The delta area represents the amount of extra cluster stability gained when
clustering into k groups as compared to k-1 groups. It can be expected that
high stability of clusters can be reached when clustering into the number of
groups that best fits the data. The "natural" number of clusters present in
the data should thus corresponds to the value of k where there is no longer
a considerable increase in stability (pleateau onset).
}
\examples{
data(PBMC_fs, PBMC_panel, PBMC_md)
re <- daFrame(PBMC_fs, PBMC_panel, PBMC_md)
# specify antigens to use for clustering
lineage <- c("CD3", "CD45", "CD4", "CD20", "CD33",
"CD123", "CD14", "IgM", "HLA_DR", "CD7")
(re <- cluster(re, cols_to_use=lineage))
}
\references{
Nowicka M, Krieg C, Weber LM et al.
CyTOF workflow: Differential discovery in
high-throughput high-dimensional cytometry datasets.
\emph{F1000Research} 2017, 6:748 (doi: 10.12688/f1000research.11622.1)
}
\author{
Helena Lucia Crowell \email{crowellh@student.ethz.ch}
}
| /man/cluster.Rd | no_license | lmweber/CATALYST | R | false | true | 3,228 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/AllGenerics.R, R/cluster.R
\docType{methods}
\name{cluster}
\alias{cluster}
\alias{cluster,daFrame-method}
\title{FlowSOM clustering & ConsensusClusterPlus metaclustering}
\usage{
cluster(x, ...)
\S4method{cluster}{daFrame}(x, cols_to_use, xdim = 10, ydim = 10,
maxK = 20, seed = 1)
}
\arguments{
\item{x}{a \code{\link{daFrame}}.}
\item{...}{optional arguments.}
\item{cols_to_use}{a character vector. Specifies which antigens to use for clustering.}
\item{xdim, ydim}{numeric. Specify the grid size of the self-orginizing map.
The default 10x10 grid will yield 100 clusters.}
\item{maxK}{numeric. Specifies the maximum number of clusters to evaluate
in the metaclustering. For \code{maxK = 20}, for example,
metaclustering will be performed for 2 through 20 clusters.}
\item{seed}{numeric. Sets random seed in \code{ConsensusClusterPlus()}.}
}
\value{
The function will add information to the following slots
of the input \code{daFrame} (and return it):
\itemize{
\item{\code{rowData}\describe{\itemize{
\item{\code{cluster_id}:
each cell's cluster ID as inferred by \code{FlowSOM}.
One of 1, ..., \code{xdim}x\code{ydim}}.}
}}
\item{\code{colData}\describe{\itemize{
\item{\code{marker_class}:
\code{"type"} or \code{"state"}.
Specifies whether an antigen has been used for clustering
or not, respectively.}}
}}
\item{\code{metadata}\describe{\itemize{
\item{\code{SOM_codes}:
a table with dimensions K x (# cell type markers),
where K = \code{xdim} x \code{ydim}. Contains the SOM codes.}
\item{\code{cluster_codes}:
a table with dimensions K x (\code{maxK} + 1).
Contains the cluster codes for all metaclustering.}
\item{\code{delta_area}:
a \code{\link{ggplot}} object. See above for details.}}
}}
}
}
\description{
\code{cluster} will first group cells into \code{xdim}x\code{ydim}
clusters using \pkg{FlowSOM}, and subsequently perform metaclustering
with \pkg{ConsensusClusterPlus} into 2 through \code{maxK} clusters.
In the returned \code{daFrame}, those antigens used for clustering will be
labelled as '\code{type}' markers, and the remainder of antigens as
'\code{state}' markers.
}
\details{
The delta area represents the amount of extra cluster stability gained when
clustering into k groups as compared to k-1 groups. It can be expected that
high stability of clusters can be reached when clustering into the number of
groups that best fits the data. The "natural" number of clusters present in
the data should thus corresponds to the value of k where there is no longer
a considerable increase in stability (pleateau onset).
}
\examples{
data(PBMC_fs, PBMC_panel, PBMC_md)
re <- daFrame(PBMC_fs, PBMC_panel, PBMC_md)
# specify antigens to use for clustering
lineage <- c("CD3", "CD45", "CD4", "CD20", "CD33",
"CD123", "CD14", "IgM", "HLA_DR", "CD7")
(re <- cluster(re, cols_to_use=lineage))
}
\references{
Nowicka M, Krieg C, Weber LM et al.
CyTOF workflow: Differential discovery in
high-throughput high-dimensional cytometry datasets.
\emph{F1000Research} 2017, 6:748 (doi: 10.12688/f1000research.11622.1)
}
\author{
Helena Lucia Crowell \email{crowellh@student.ethz.ch}
}
|
#'@title Import a dataset
#'
#'@description
#'The import function can import data from
#'delimited text files, EXCEL spreadsheets, and
#'statistical packages such as SAS, SPSS, and Stata.
#'
#'@param file datafile to import. If missing, the user
#'is prompted to select a file interactively.
#'@param ... parameters passed to the import function. See details below.
#'
#'@return a data frame
#'
#'@details
#'The \code{import} function is wrapper for the
#'\href{https://haven.tidyverse.org/}{haven},
#'\href{https://readxl.tidyverse.org/}{readxl},
#'and \href{https://github.com/r-lib/vroom}{vroom}
#'packages.
#'
#'@seealso
#'\link[haven]{read_sas},
#'\link[haven]{read_dta},
#'\link[haven]{read_spss},
#'\link[readxl]{read_excel},
#'\link[vroom]{}
#'
#'@export
#'
#'@importFrom haven read_sas read_stata read_spss
#'@importFrom tools file_ext
#'@importFrom readxl read_excel
#'@import vroom
#'
#'@examples
#'\dontrun {
#' # import a comma delimited file
#' mydataframe <- import("mydata.csv")
#'
#' # import a SAS binary datafile
#' mydataframe <- import("mydata.sas7dbat")
#'
#' # import the second worksheet of an Excel workbook
#' mydataframe <- import("mydata.xlsx", sheet=2)
#'
#' # prompt for a file to import
#' mydataframe <- import()
#'
#'}
#'
import <- function(file, ...){
# if no file specified, prompt user
if(missing(file))
file <- file.choose()
# get file info
file <- tolower(file)
basename <- basename(file)
extension <- tools::file_ext(file)
# import dataset
df <- switch(extension,
"sas7bdat" = haven::read_sas(file, ...),
"dta" = haven::read_stata(file, ...),
"sav" = haven::read_spss(file, ...),
"xlsx" = readxl::read_excel(file, ...),
"xls" = readxl::read_excel(file, ...),
vroom::vroom(file, ...)
)
# return data frame
return(df)
}
| /R/import.R | permissive | jnguyen01/importR | R | false | false | 1,885 | r | #'@title Import a dataset
#'
#'@description
#'The import function can import data from
#'delimited text files, EXCEL spreadsheets, and
#'statistical packages such as SAS, SPSS, and Stata.
#'
#'@param file datafile to import. If missing, the user
#'is prompted to select a file interactively.
#'@param ... parameters passed to the import function. See details below.
#'
#'@return a data frame
#'
#'@details
#'The \code{import} function is wrapper for the
#'\href{https://haven.tidyverse.org/}{haven},
#'\href{https://readxl.tidyverse.org/}{readxl},
#'and \href{https://github.com/r-lib/vroom}{vroom}
#'packages.
#'
#'@seealso
#'\link[haven]{read_sas},
#'\link[haven]{read_dta},
#'\link[haven]{read_spss},
#'\link[readxl]{read_excel},
#'\link[vroom]{}
#'
#'@export
#'
#'@importFrom haven read_sas read_stata read_spss
#'@importFrom tools file_ext
#'@importFrom readxl read_excel
#'@import vroom
#'
#'@examples
#'\dontrun {
#' # import a comma delimited file
#' mydataframe <- import("mydata.csv")
#'
#' # import a SAS binary datafile
#' mydataframe <- import("mydata.sas7dbat")
#'
#' # import the second worksheet of an Excel workbook
#' mydataframe <- import("mydata.xlsx", sheet=2)
#'
#' # prompt for a file to import
#' mydataframe <- import()
#'
#'}
#'
import <- function(file, ...){
# if no file specified, prompt user
if(missing(file))
file <- file.choose()
# get file info
file <- tolower(file)
basename <- basename(file)
extension <- tools::file_ext(file)
# import dataset
df <- switch(extension,
"sas7bdat" = haven::read_sas(file, ...),
"dta" = haven::read_stata(file, ...),
"sav" = haven::read_spss(file, ...),
"xlsx" = readxl::read_excel(file, ...),
"xls" = readxl::read_excel(file, ...),
vroom::vroom(file, ...)
)
# return data frame
return(df)
}
|
ebic.multinom.bsreg <- function(target, dataset, wei = NULL, gam = NULL) {
dm <- dim(dataset)
if ( is.null(dm) ) {
n <- length(target)
p <- 1
} else {
n <- dm[1] ## sample size
p <- dm[2] ## number of variables
}
if ( p > n ) {
res <- paste("The number of variables is higher than the sample size. No backward procedure was attempted")
} else {
tic <- proc.time()
logn <- log(n)
if ( is.null(gam) ) {
con <- 2 - log(p) / logn
if ( (con) < 0 ) con <- 0
} else con <- 2 * gam
tool <- numeric(p + 1)
ini <- nnet::multinom( target ~., data = dataset, weights = wei, trace = FALSE )
bic0 <- BIC(ini) ## initial bic
tool[1] <- bic0
bic <- numeric(p)
M <- dim(dataset)[2] - 1
if ( M == 0 ) {
mod <- nnet::multinom( target ~ 1, weights = wei, trace = FALSE )
bic <- BIC(mod)
if (bic0 - bic < 0 ) {
info <- matrix( 0, nrow = 0, ncol = 2 )
mat <- matrix( c(1, bic), ncol = 2 )
} else {
info <- matrix( c(1, bic), ncol = 2 )
mat <- matrix(0, nrow = 0, ncol = 2 )
}
runtime <- proc.time() - tic
colnames(info) <- c("Variables", "eBIC")
colnames(mat) <- c("Variables", "eBIC")
res <- list(runtime = runtime, info = info, mat = mat )
} else {
###########
for (j in 1:p) {
mod <- nnet::multinom( target ~., data = dataset[, -j, drop = FALSE], weights = wei, trace = FALSE)
bic[j] <- BIC(mod) + con * lchoose(p, M)
}
mat <- cbind(1:p, bic )
sel <- which.min( mat[, 2] )
info <- matrix( c(0, 0), ncol = 2 )
colnames(info) <- c("Variables", "eBIC")
colnames(mat) <- c("Variables", "eBIC")
if ( bic0 - mat[sel, 2] < 0 ) {
runtime <- proc.time() - tic
res <- list(runtime = runtime, info = info, mat = mat )
} else {
info[1, ] <- mat[sel, ]
mat <- mat[-sel, , drop = FALSE]
dat <- dataset[, -sel, drop = FALSE]
tool[2] <- info[1, 2]
i <- 2
if ( tool[2] > 0 ) {
while ( tool[i - 1] - tool[i ] > 0 & NCOL(dat) > 0 ) {
ini <- nnet::multinom( target ~., data = dat, weights = wei, trace = FALSE )
M <- dim(dat)[2]
bic0 <- BIC(mod) + con * lchoose(p, M)
i <- i + 1
if ( M == 1 ) {
mod <- nnet::multinom(target ~ 1, weights = wei, trace = FALSE )
bic <- - 2 * mod$loglik
tool[i] <- bic
if (bic0 - bic < 0 ) {
runtime <- proc.time() - tic
res <- list(runtime = runtime, info = info, mat = mat )
} else {
runtime <- proc.time() - tic
info <- rbind(info, c(mat[, 1], bic) )
mat <- mat[-1, , drop = FALSE]
res <- list(runtime = runtime, info = info, mat = mat )
dat <- dataset[, -info[, 1], drop = FALSE ]
}
} else {
bic <- numeric(M)
M <- dim(dat)[2] - 1
for ( j in 1:(M + 1) ) {
mod <- nnet::multinom( target ~., data = dat[, -j, drop = FALSE], weights = wei, trace = FALSE )
bic[j] <- BIC(mod) + con * lchoose(p, M)
}
mat[, 2] <- bic
sel <- which.min( mat[, 2] )
tool[i] <- mat[sel, 2]
if ( bic0 - mat[sel, 2] < 0 ) {
runtime <- proc.time() - tic
res <- list(runtime = runtime, info = info, mat = mat )
} else {
info <- rbind(info, mat[sel, ] )
mat <- mat[-sel, , drop = FALSE]
dat <- dataset[, -info[, 1], drop = FALSE ]
} ## end if ( bic0 - mat[sel, 2] < 0 )
} ## end if (M == 1)
} ## end while
} ## end if ( tool[2] > 0 )
} ## end if ( bic0 - mat[sel, 2] < 0 )
} ## end if (M == 0)
runtime <- proc.time() - tic
res <- list(runtime = runtime, info = info, mat = mat )
} ## end if ( p > n )
res
}
| /R/ebic.multinom.bsreg.R | no_license | JokerWhy233/MXM | R | false | false | 4,259 | r | ebic.multinom.bsreg <- function(target, dataset, wei = NULL, gam = NULL) {
dm <- dim(dataset)
if ( is.null(dm) ) {
n <- length(target)
p <- 1
} else {
n <- dm[1] ## sample size
p <- dm[2] ## number of variables
}
if ( p > n ) {
res <- paste("The number of variables is higher than the sample size. No backward procedure was attempted")
} else {
tic <- proc.time()
logn <- log(n)
if ( is.null(gam) ) {
con <- 2 - log(p) / logn
if ( (con) < 0 ) con <- 0
} else con <- 2 * gam
tool <- numeric(p + 1)
ini <- nnet::multinom( target ~., data = dataset, weights = wei, trace = FALSE )
bic0 <- BIC(ini) ## initial bic
tool[1] <- bic0
bic <- numeric(p)
M <- dim(dataset)[2] - 1
if ( M == 0 ) {
mod <- nnet::multinom( target ~ 1, weights = wei, trace = FALSE )
bic <- BIC(mod)
if (bic0 - bic < 0 ) {
info <- matrix( 0, nrow = 0, ncol = 2 )
mat <- matrix( c(1, bic), ncol = 2 )
} else {
info <- matrix( c(1, bic), ncol = 2 )
mat <- matrix(0, nrow = 0, ncol = 2 )
}
runtime <- proc.time() - tic
colnames(info) <- c("Variables", "eBIC")
colnames(mat) <- c("Variables", "eBIC")
res <- list(runtime = runtime, info = info, mat = mat )
} else {
###########
for (j in 1:p) {
mod <- nnet::multinom( target ~., data = dataset[, -j, drop = FALSE], weights = wei, trace = FALSE)
bic[j] <- BIC(mod) + con * lchoose(p, M)
}
mat <- cbind(1:p, bic )
sel <- which.min( mat[, 2] )
info <- matrix( c(0, 0), ncol = 2 )
colnames(info) <- c("Variables", "eBIC")
colnames(mat) <- c("Variables", "eBIC")
if ( bic0 - mat[sel, 2] < 0 ) {
runtime <- proc.time() - tic
res <- list(runtime = runtime, info = info, mat = mat )
} else {
info[1, ] <- mat[sel, ]
mat <- mat[-sel, , drop = FALSE]
dat <- dataset[, -sel, drop = FALSE]
tool[2] <- info[1, 2]
i <- 2
if ( tool[2] > 0 ) {
while ( tool[i - 1] - tool[i ] > 0 & NCOL(dat) > 0 ) {
ini <- nnet::multinom( target ~., data = dat, weights = wei, trace = FALSE )
M <- dim(dat)[2]
bic0 <- BIC(mod) + con * lchoose(p, M)
i <- i + 1
if ( M == 1 ) {
mod <- nnet::multinom(target ~ 1, weights = wei, trace = FALSE )
bic <- - 2 * mod$loglik
tool[i] <- bic
if (bic0 - bic < 0 ) {
runtime <- proc.time() - tic
res <- list(runtime = runtime, info = info, mat = mat )
} else {
runtime <- proc.time() - tic
info <- rbind(info, c(mat[, 1], bic) )
mat <- mat[-1, , drop = FALSE]
res <- list(runtime = runtime, info = info, mat = mat )
dat <- dataset[, -info[, 1], drop = FALSE ]
}
} else {
bic <- numeric(M)
M <- dim(dat)[2] - 1
for ( j in 1:(M + 1) ) {
mod <- nnet::multinom( target ~., data = dat[, -j, drop = FALSE], weights = wei, trace = FALSE )
bic[j] <- BIC(mod) + con * lchoose(p, M)
}
mat[, 2] <- bic
sel <- which.min( mat[, 2] )
tool[i] <- mat[sel, 2]
if ( bic0 - mat[sel, 2] < 0 ) {
runtime <- proc.time() - tic
res <- list(runtime = runtime, info = info, mat = mat )
} else {
info <- rbind(info, mat[sel, ] )
mat <- mat[-sel, , drop = FALSE]
dat <- dataset[, -info[, 1], drop = FALSE ]
} ## end if ( bic0 - mat[sel, 2] < 0 )
} ## end if (M == 1)
} ## end while
} ## end if ( tool[2] > 0 )
} ## end if ( bic0 - mat[sel, 2] < 0 )
} ## end if (M == 0)
runtime <- proc.time() - tic
res <- list(runtime = runtime, info = info, mat = mat )
} ## end if ( p > n )
res
}
|
`hmm.vitFUN.rils` <-
function (geno, position, geno.probability, transitionFUN = phy2get.haldane.rils,
emissionFUN = makeEmissionFUN(errorRate = 0.01), ...)
{
n.obs <- length(geno)
n.state <- length(geno.probability)
psi <- delta <- matrix(0, nrow = n.state, ncol = n.obs)
n.con <- geno.cr <- numeric(n.obs)
geno.dis <- abs(diff(position))
n.con[1] <- 1
g <- geno[1]
for (i in 2:n.obs) {
n.con[i] <- ifelse(geno[i] == g, n.con[i - 1] + 1, 1)
g <- geno[i]
}
for (i in 1:n.state) delta[i, 1] <- log(geno.probability[i]) +
emissionFUN(i, geno[1], n.con[1])
preProb <- numeric(n.state)
for (t in 2:n.obs) {
for (j in 1:n.state) {
for (i in 1:n.state) preProb[i] <- delta[i, t - 1] +
log(transitionFUN(i, j, geno.dis[t - 1]))
psi[j, t] <- which.max(preProb)
delta[j, t] <- max(preProb) + emissionFUN(j, geno[t],
n.con[t])
}
}
geno.cr[n.obs] <- which.max(delta[, n.obs])
for (t in seq(n.obs - 1, 1, by = -1)) geno.cr[t] <- psi[geno.cr[t +
1], t + 1]
geno.cr
}
| /MPR_genotyping/MPR/R/hmm.vitFUN.rils.R | no_license | JinfengChen/MPR_install | R | false | false | 1,144 | r | `hmm.vitFUN.rils` <-
function (geno, position, geno.probability, transitionFUN = phy2get.haldane.rils,
emissionFUN = makeEmissionFUN(errorRate = 0.01), ...)
{
n.obs <- length(geno)
n.state <- length(geno.probability)
psi <- delta <- matrix(0, nrow = n.state, ncol = n.obs)
n.con <- geno.cr <- numeric(n.obs)
geno.dis <- abs(diff(position))
n.con[1] <- 1
g <- geno[1]
for (i in 2:n.obs) {
n.con[i] <- ifelse(geno[i] == g, n.con[i - 1] + 1, 1)
g <- geno[i]
}
for (i in 1:n.state) delta[i, 1] <- log(geno.probability[i]) +
emissionFUN(i, geno[1], n.con[1])
preProb <- numeric(n.state)
for (t in 2:n.obs) {
for (j in 1:n.state) {
for (i in 1:n.state) preProb[i] <- delta[i, t - 1] +
log(transitionFUN(i, j, geno.dis[t - 1]))
psi[j, t] <- which.max(preProb)
delta[j, t] <- max(preProb) + emissionFUN(j, geno[t],
n.con[t])
}
}
geno.cr[n.obs] <- which.max(delta[, n.obs])
for (t in seq(n.obs - 1, 1, by = -1)) geno.cr[t] <- psi[geno.cr[t +
1], t + 1]
geno.cr
}
|
\name{fasttle-methods}
\docType{methods}
\alias{fasttle-methods}
\alias{fasttle,IData-method}
\alias{fasttle}
\title{ Methods for Function fasttle in Package \sQuote{MAINT.Data}}
\description{Performs maximum trimmed likelihood estimation by the fasttle algorithm}
\usage{fasttle(Sdt,
CovCase=1:4,
SelCrit=c("BIC","AIC"),
alpha=control@alpha,
nsamp = control@nsamp,
seed=control@seed,
trace=control@trace,
use.correction=control@use.correction,
ncsteps=control@ncsteps,
getalpha=control@getalpha,
rawMD2Dist=control@rawMD2Dist,
MD2Dist=control@MD2Dist,
eta=control@eta,
multiCmpCor=control@multiCmpCor,
getkdblstar=control@getkdblstar,
outlin=control@outlin,
trialmethod=control@trialmethod,
m=control@m,
reweighted = control@reweighted,
k2max = control@k2max,
otpType=control@otpType,
control=RobEstControl(), \dots)
}
\arguments{
\item{Sdt}{An IData object representing interval-valued units.}
\item{CovCase}{Configuration of the variance-covariance matrix: a set of integers between 1 and 4.}
\item{SelCrit}{The model selection criterion.}
\item{alpha}{Numeric parameter controlling the size of the subsets over which the trimmed likelihood is maximized; roughly alpha*nrow(Sdt) observations are used for computing the trimmed likelihood. Note that when argument \sQuote{getalpha} is set to \dQuote{TwoStep} the final value of \sQuote{alpha} is estimated by a two-step procedure and the value of argument \sQuote{alpha} is only used to specify the size of the samples used in the first step. Allowed values are between 0.5 and 1.}
\item{nsamp}{Number of subsets used for initial estimates.}
\item{seed}{Initial seed for random generator, like \code{\link{.Random.seed}}, see \code{\link{rrcov.control}}.}
\item{trace}{Logical (or integer) indicating if intermediate results should be printed; defaults to \code{FALSE}.}
\item{use.correction}{ whether to use finite sample correction factors; defaults to \code{TRUE}.}
\item{ncsteps}{The maximum number of concentration steps used each iteration of the fasttle algorithm.}
\item{getalpha}{Argument specifying if the \sQuote{alpha} parameter (roughly the percentage of the sample used for computing the trimmed likelihood) should be estimated from the data, or if the value of the argument \sQuote{alpha} should be used instead. When set to \dQuote{TwoStep}, \sQuote{alpha} is estimated by a two-step procedure with the value of argument \sQuote{alpha} specifying the size of the samples used in the first step. Otherwise, the value of argument \sQuote{alpha} is used directly.}
\item{rawMD2Dist}{The assumed reference distribution of the raw MCD squared distances, which is used to find to cutoffs defining the observations kept in one-step reweighted MCD estimates. Alternatives are \sQuote{ChiSq},\sQuote{HardRockeAsF} and \sQuote{HardRockeAdjF}, respectivelly for the usual Chi-square, and the asymptotic and adjusted scaled F distributions proposed by Hardin and Rocke (2005).}
\item{MD2Dist}{The assumed reference distributions used to find cutoffs defining the observations assumed as outliers. Alternatives are \dQuote{ChiSq} and \dQuote{CerioliBetaF} respectivelly for the usual Chi-square, or the Beta and F distributions proposed by Cerioli (2010).}
\item{eta}{Nominal size for the null hypothesis that a given observation is not an outlier. Defines the raw MCD Mahalanobis distances cutoff used to choose the observations kept in the reweightening step.}
\item{multiCmpCor}{Whether a multicomparison correction of the nominal size (eta) for the outliers tests should be performed. Alternatives are: \sQuote{never} -- ignoring the multicomparisons and testing all entities at \sQuote{eta} nominal level. \sQuote{always} -- testing all n entitites at 1.- (1.-\sQuote{eta}^(1/n)); and \sQuote{iterstep} -- use the iterated rule proposed by Cerioli (2010), \emph{i.e.}, make an initial set of tests using the nominal size 1.- (1-\sQuote{eta}^(1/n)), and if no outliers are detected stop. Otherwise, make a second step testing for outliers at the \sQuote{eta} nominal level. }
\item{getkdblstar}{Argument specifying the size of the initial small (in order to minimize the probability of outliers) subsets. If set to the string \dQuote{Twopplusone} (default) the initial sets have twice the number of interval-value variables plus one (i.e., they are the smaller samples that lead to a non-singular covariance estimate). Otherwise, an integer with the size of the initial sets.}
\item{outlin}{The type of outliers to be considered. \dQuote{MidPandLogR} if outliers may be present in both MidPpoints and LogRanges, \dQuote{MidP} if outliers are only present in MidPpoints, or \dQuote{LogR} if outliers are only present in LogRanges.}
\item{trialmethod}{The method to find a trial subset used to initialize each replication of the fasttle algorithm. The current options are \dQuote{simple} (default) that simply selects \sQuote{kdblstar} observations at random, and \dQuote{Poolm} that divides the original sample into \sQuote{m} non-overlaping subsets, applies the \sQuote{simple trial} and the refinement methods to each one of them, and merges the results into a trial subset.}
\item{m}{Number of non-overlaping subsets used by the trial method when the argument of \sQuote{trialmethod} is set to 'Poolm'.}
\item{reweighted}{Should a (Re)weighted estimate of the covariance matrix be used in the computation of the trimmed likelihood or just a \dQuote{raw} covariance estimate; default is (Re)weighting.}
\item{k2max}{Maximal allowed l2-norm condition number for correlation matrices. Correlation matrices with condition number above k2max are considered to be numerically singular, leading to degenerate results.}
\item{otpType}{The amount of output returned by fasttle. Current options are \dQuote{SetMD2andEst} (default) which returns an \sQuote{IdtSngNDRE} object with the fasttle estimates, \cr
a vector with the final trimmed subset elements used to compute these estimates and the corresponding robust squared Mahalanobis distances, and \cr
\dQuote{SetMD2EstandPrfSt} wich returns an \sQuote{IdtSngNDRE} object with the previous slots plust a list of some performance statistics concerning the algorithm execution.}
\item{control}{a list with estimation options - this includes those above provided in the function specification. See
\code{\link{RobEstControl}} for the defaults. If \code{control} is supplied, the parameters from it will be used.
If parameters are passed also in the invocation statement, they will override the corresponding elements of the control object.}
\item{\dots}{Further arguments to be passed to internal functions of \code{fasttle}.}
}
\value{An object of class \code{\linkS4class{IdtE}} with the fasttle estimates, the value of the comparison criterion used to select the covariance configurations, the robust squared Mahalanobis distances, and optionally (if argument \sQuote{otpType} is set to true) performance statistics concerning the algorithm execution.}
\references{
Brito, P., Duarte Silva, A. P. (2012), Modelling Interval Data with Normal and Skew-Normal Distributions. \emph{Journal of Applied Statistics} \bold{39}(1), 3--20.\cr
Cerioli, A. (2010), Multivariate Outlier Detection with High-Breakdown Estimators.
\emph{Journal of the American Statistical Association} \bold{105} (489), 147--156.\cr
Duarte Silva, A.P., Filzmoser, P. and Brito, P. (2017), Outlier detection in interval data. \emph{Advances in Data Analysis and Classification}, 1--38.\cr
Hadi, A. S. and Luceno, A. (1997), Maximum trimmed likelihood estimators: a unified approach, examples, and algorithms.
\emph{Computational Statistics and Data Analysis} \bold{25}(3), 251--272.\cr
Hardin, J. and Rocke, A. (2005), The Distribution of Robust Distances.
\emph{Journal of Computational and Graphical Statistics} \bold{14}, 910--927.\cr
Todorov V. and Filzmoser P. (2009), An Object Oriented Framework for Robust Multivariate Analysis. \emph{Journal of Statistical Software} \bold{32}(3), 1--47.
}
\keyword{methods}
\keyword{trimmed maximum likelihood estimator}
\keyword{interval data}
\seealso{ \code{\link{fulltle}}, \code{\linkS4class{RobEstControl}}, \code{\link{getIdtOutl}}, \code{\linkS4class{IdtSngNDRE}} }
\examples{
\dontrun{
# Create an Interval-Data object containing the intervals of temperatures by quarter
# for 899 Chinese meteorological stations.
ChinaT <- IData(ChinaTemp[1:8])
# Estimate parameters by the fast trimmed maximum likelihood estimator,
# using a two-step procedure to select the trimming parameter, a reweighted
# MCD estimate, and the classical 97.5\% chi-square quantile cut-offs.
Chinafasttle1 <- fasttle(ChinaT)
cat("China maximum trimmed likelihood estimation results =\n")
print(Chinafasttle1)
# Estimate parameters by the fast trimmed maximum likelihood estimator, using
# the triming parameter that maximizes breakdown, and a reweighted MCD estimate
# based on the 97.5\% quantiles of Hardin and Rocke adjusted F distributions.
Chinafasttle2 <- fasttle(ChinaT,alpha=0.5,getalpha=FALSE,rawMD2Dist="HardRockeAdjF")
cat("China maximum trimmed likelihood estimation results =\n")
print(Chinafasttle2)
# Estimate parameters by the fast trimmed maximum likelihood estimator, using a two-step procedure
# to select the triming parameter, a reweighed MCD estimate based on Hardin and Rocke adjusted
# F distributions, and 95\% quantiles, and the Cerioli Beta and F distributions together
# with Cerioli iterated procedure to identify outliers in the first step.
Chinafasttle3 <- fasttle(ChinaT,rawMD2Dist="HardRockeAdjF",eta=0.05,MD2Dist="CerioliBetaF",
multiCmpCor="iterstep")
cat("China maximum trimmed likelihood estimation results =\n")
print(Chinafasttle3)
}
}
| /man/fasttle-methods.Rd | no_license | cran/MAINT.Data | R | false | false | 10,076 | rd | \name{fasttle-methods}
\docType{methods}
\alias{fasttle-methods}
\alias{fasttle,IData-method}
\alias{fasttle}
\title{ Methods for Function fasttle in Package \sQuote{MAINT.Data}}
\description{Performs maximum trimmed likelihood estimation by the fasttle algorithm}
\usage{fasttle(Sdt,
CovCase=1:4,
SelCrit=c("BIC","AIC"),
alpha=control@alpha,
nsamp = control@nsamp,
seed=control@seed,
trace=control@trace,
use.correction=control@use.correction,
ncsteps=control@ncsteps,
getalpha=control@getalpha,
rawMD2Dist=control@rawMD2Dist,
MD2Dist=control@MD2Dist,
eta=control@eta,
multiCmpCor=control@multiCmpCor,
getkdblstar=control@getkdblstar,
outlin=control@outlin,
trialmethod=control@trialmethod,
m=control@m,
reweighted = control@reweighted,
k2max = control@k2max,
otpType=control@otpType,
control=RobEstControl(), \dots)
}
\arguments{
\item{Sdt}{An IData object representing interval-valued units.}
\item{CovCase}{Configuration of the variance-covariance matrix: a set of integers between 1 and 4.}
\item{SelCrit}{The model selection criterion.}
\item{alpha}{Numeric parameter controlling the size of the subsets over which the trimmed likelihood is maximized; roughly alpha*nrow(Sdt) observations are used for computing the trimmed likelihood. Note that when argument \sQuote{getalpha} is set to \dQuote{TwoStep} the final value of \sQuote{alpha} is estimated by a two-step procedure and the value of argument \sQuote{alpha} is only used to specify the size of the samples used in the first step. Allowed values are between 0.5 and 1.}
\item{nsamp}{Number of subsets used for initial estimates.}
\item{seed}{Initial seed for random generator, like \code{\link{.Random.seed}}, see \code{\link{rrcov.control}}.}
\item{trace}{Logical (or integer) indicating if intermediate results should be printed; defaults to \code{FALSE}.}
\item{use.correction}{ whether to use finite sample correction factors; defaults to \code{TRUE}.}
\item{ncsteps}{The maximum number of concentration steps used each iteration of the fasttle algorithm.}
\item{getalpha}{Argument specifying if the \sQuote{alpha} parameter (roughly the percentage of the sample used for computing the trimmed likelihood) should be estimated from the data, or if the value of the argument \sQuote{alpha} should be used instead. When set to \dQuote{TwoStep}, \sQuote{alpha} is estimated by a two-step procedure with the value of argument \sQuote{alpha} specifying the size of the samples used in the first step. Otherwise, the value of argument \sQuote{alpha} is used directly.}
\item{rawMD2Dist}{The assumed reference distribution of the raw MCD squared distances, which is used to find to cutoffs defining the observations kept in one-step reweighted MCD estimates. Alternatives are \sQuote{ChiSq},\sQuote{HardRockeAsF} and \sQuote{HardRockeAdjF}, respectivelly for the usual Chi-square, and the asymptotic and adjusted scaled F distributions proposed by Hardin and Rocke (2005).}
\item{MD2Dist}{The assumed reference distributions used to find cutoffs defining the observations assumed as outliers. Alternatives are \dQuote{ChiSq} and \dQuote{CerioliBetaF} respectivelly for the usual Chi-square, or the Beta and F distributions proposed by Cerioli (2010).}
\item{eta}{Nominal size for the null hypothesis that a given observation is not an outlier. Defines the raw MCD Mahalanobis distances cutoff used to choose the observations kept in the reweightening step.}
\item{multiCmpCor}{Whether a multicomparison correction of the nominal size (eta) for the outliers tests should be performed. Alternatives are: \sQuote{never} -- ignoring the multicomparisons and testing all entities at \sQuote{eta} nominal level. \sQuote{always} -- testing all n entitites at 1.- (1.-\sQuote{eta}^(1/n)); and \sQuote{iterstep} -- use the iterated rule proposed by Cerioli (2010), \emph{i.e.}, make an initial set of tests using the nominal size 1.- (1-\sQuote{eta}^(1/n)), and if no outliers are detected stop. Otherwise, make a second step testing for outliers at the \sQuote{eta} nominal level. }
\item{getkdblstar}{Argument specifying the size of the initial small (in order to minimize the probability of outliers) subsets. If set to the string \dQuote{Twopplusone} (default) the initial sets have twice the number of interval-value variables plus one (i.e., they are the smaller samples that lead to a non-singular covariance estimate). Otherwise, an integer with the size of the initial sets.}
\item{outlin}{The type of outliers to be considered. \dQuote{MidPandLogR} if outliers may be present in both MidPpoints and LogRanges, \dQuote{MidP} if outliers are only present in MidPpoints, or \dQuote{LogR} if outliers are only present in LogRanges.}
\item{trialmethod}{The method to find a trial subset used to initialize each replication of the fasttle algorithm. The current options are \dQuote{simple} (default) that simply selects \sQuote{kdblstar} observations at random, and \dQuote{Poolm} that divides the original sample into \sQuote{m} non-overlaping subsets, applies the \sQuote{simple trial} and the refinement methods to each one of them, and merges the results into a trial subset.}
\item{m}{Number of non-overlaping subsets used by the trial method when the argument of \sQuote{trialmethod} is set to 'Poolm'.}
\item{reweighted}{Should a (Re)weighted estimate of the covariance matrix be used in the computation of the trimmed likelihood or just a \dQuote{raw} covariance estimate; default is (Re)weighting.}
\item{k2max}{Maximal allowed l2-norm condition number for correlation matrices. Correlation matrices with condition number above k2max are considered to be numerically singular, leading to degenerate results.}
\item{otpType}{The amount of output returned by fasttle. Current options are \dQuote{SetMD2andEst} (default) which returns an \sQuote{IdtSngNDRE} object with the fasttle estimates, \cr
a vector with the final trimmed subset elements used to compute these estimates and the corresponding robust squared Mahalanobis distances, and \cr
\dQuote{SetMD2EstandPrfSt} wich returns an \sQuote{IdtSngNDRE} object with the previous slots plust a list of some performance statistics concerning the algorithm execution.}
\item{control}{a list with estimation options - this includes those above provided in the function specification. See
\code{\link{RobEstControl}} for the defaults. If \code{control} is supplied, the parameters from it will be used.
If parameters are passed also in the invocation statement, they will override the corresponding elements of the control object.}
\item{\dots}{Further arguments to be passed to internal functions of \code{fasttle}.}
}
\value{An object of class \code{\linkS4class{IdtE}} with the fasttle estimates, the value of the comparison criterion used to select the covariance configurations, the robust squared Mahalanobis distances, and optionally (if argument \sQuote{otpType} is set to true) performance statistics concerning the algorithm execution.}
\references{
Brito, P., Duarte Silva, A. P. (2012), Modelling Interval Data with Normal and Skew-Normal Distributions. \emph{Journal of Applied Statistics} \bold{39}(1), 3--20.\cr
Cerioli, A. (2010), Multivariate Outlier Detection with High-Breakdown Estimators.
\emph{Journal of the American Statistical Association} \bold{105} (489), 147--156.\cr
Duarte Silva, A.P., Filzmoser, P. and Brito, P. (2017), Outlier detection in interval data. \emph{Advances in Data Analysis and Classification}, 1--38.\cr
Hadi, A. S. and Luceno, A. (1997), Maximum trimmed likelihood estimators: a unified approach, examples, and algorithms.
\emph{Computational Statistics and Data Analysis} \bold{25}(3), 251--272.\cr
Hardin, J. and Rocke, A. (2005), The Distribution of Robust Distances.
\emph{Journal of Computational and Graphical Statistics} \bold{14}, 910--927.\cr
Todorov V. and Filzmoser P. (2009), An Object Oriented Framework for Robust Multivariate Analysis. \emph{Journal of Statistical Software} \bold{32}(3), 1--47.
}
\keyword{methods}
\keyword{trimmed maximum likelihood estimator}
\keyword{interval data}
\seealso{ \code{\link{fulltle}}, \code{\linkS4class{RobEstControl}}, \code{\link{getIdtOutl}}, \code{\linkS4class{IdtSngNDRE}} }
\examples{
\dontrun{
# Create an Interval-Data object containing the intervals of temperatures by quarter
# for 899 Chinese meteorological stations.
ChinaT <- IData(ChinaTemp[1:8])
# Estimate parameters by the fast trimmed maximum likelihood estimator,
# using a two-step procedure to select the trimming parameter, a reweighted
# MCD estimate, and the classical 97.5\% chi-square quantile cut-offs.
Chinafasttle1 <- fasttle(ChinaT)
cat("China maximum trimmed likelihood estimation results =\n")
print(Chinafasttle1)
# Estimate parameters by the fast trimmed maximum likelihood estimator, using
# the triming parameter that maximizes breakdown, and a reweighted MCD estimate
# based on the 97.5\% quantiles of Hardin and Rocke adjusted F distributions.
Chinafasttle2 <- fasttle(ChinaT,alpha=0.5,getalpha=FALSE,rawMD2Dist="HardRockeAdjF")
cat("China maximum trimmed likelihood estimation results =\n")
print(Chinafasttle2)
# Estimate parameters by the fast trimmed maximum likelihood estimator, using a two-step procedure
# to select the triming parameter, a reweighed MCD estimate based on Hardin and Rocke adjusted
# F distributions, and 95\% quantiles, and the Cerioli Beta and F distributions together
# with Cerioli iterated procedure to identify outliers in the first step.
Chinafasttle3 <- fasttle(ChinaT,rawMD2Dist="HardRockeAdjF",eta=0.05,MD2Dist="CerioliBetaF",
multiCmpCor="iterstep")
cat("China maximum trimmed likelihood estimation results =\n")
print(Chinafasttle3)
}
}
|
tally(child ~ parents, data = Smoking, format="prop", margins=TRUE)
diffprop(child ~ parents, data = Smoking)
| /inst/snippets/Figure5.10.R | no_license | rpruim/ISIwithR | R | false | false | 111 | r | tally(child ~ parents, data = Smoking, format="prop", margins=TRUE)
diffprop(child ~ parents, data = Smoking)
|
## Equations For Hill equation
# dS1/dt = (k1 / (1 + ((S2/M2)^n1))) - (k3 * S1)
# dS2/dt = (k2 / (1 + ((S1/M1)^n2))) - (k4 * S2)
library(deSolve)
library(rootSolve)
# Define Hill equation function with t, initial values, parameter
hill = function(t, init, para){
S1 <- init[1]
S2 <- init[2]
n1 <- para[1]
n2<- para[2]
k1 <- para[3]
k2 <- para[4]
M1 <- para[5]
M2 <- para[6]
k3 <- para[7]
k4 <- para[8]
dS1 = (k1 / (1 + ((S2/M2)^n1))) - (k3 * S1) # dS1/dt
dS2 = (k2 / (1 + ((S1/M1)^n2))) - (k4 * S2) # dS2/dt
list(c(dS1, dS2)) # function automatically returns dS1, dS2 as a list
}
# Give initial values - S1(t=0), S2(t=0)
init <- c(3, 1)
# Give parameter value - n1, n2, k1, k2, M1, M2, k3, k4
para <- c(2, 2, 20, 20, 1, 1, 5, 5)
# Time range for solution - till 6.7 - found out when calculated till 100
t <- seq(0, 6.7, 0.01)
# Calling ODE function
out <- ode(y = init, times = t, func = hill, parms = para)
# Plotting solution for S1(t)
plot(out[,1], out[,2], type = "l", xlab = "t", ylab = "S1(t)")
# Plotting solution for S2(t)
plot(out[,1], out[,3], type = "l", xlab = "t", ylab = "S2(t)")
# Plotting S1(t) vs S2(t)
plot(out[,2], out[,3], type = "l", xlab = "S1(t)", ylab = "S2(t)")
#Print summary - top few results
head(out)
# Printing Eigen Values
lambdas <- eigen(jacobian.full(y = init, func = hill,
parms = para))$values
print(lambdas)
if(is.complex(lambdas) == FALSE && lambdas[1] < 0 && lambdas[2] < 0){
print("Stable node - system is stable for given initial conditions.")
} else if(is.complex(lambdas) == FALSE && lambdas[1] > 0 && lambdas[2] > 0){
print("Unstable node - system is unstable for given initial conditions.")
} else if(is.complex(lambdas) == FALSE && lambdas[1] > 0 && lambdas[2] < 0){
print("Unstable node - saddle point - system is unstable for given initial conditions.")
} else if(is.complex(lambdas) == FALSE && lambdas[1] < 0 && lambdas[2] > 0){
print("Unstable node - saddle point - system is unstable for given initial conditions.")
} else if(is.complex(lambdas) == TRUE && Re(lambdas[1]) > 0 && Re(lambdas[2]) > 0){
print("Unstable focus - system is oscillatory and unstable.")
} else if(is.complex(lambdas) == TRUE && Re(lambdas[1]) < 0 && Re(lambdas[2]) < 0){
print("Stable focus - system is oscillatory and stable.")
}
model = function(x){
F1 <- (20 / (1 + ((x[2]/1)^2))) - (5 * x[1])
F2 <- (20 / (1 + ((x[1]/1)^2))) - (5 * x[2])
c(F1 = F1, F2 = F2)
}
ss = multiroot(f=model, start=c(3,1))
print(ss)
| /rootSolve/Hill_Eqn.R | no_license | swetaleena2206/systems_biology | R | false | false | 2,551 | r | ## Equations For Hill equation
# dS1/dt = (k1 / (1 + ((S2/M2)^n1))) - (k3 * S1)
# dS2/dt = (k2 / (1 + ((S1/M1)^n2))) - (k4 * S2)
library(deSolve)
library(rootSolve)
# Define Hill equation function with t, initial values, parameter
hill = function(t, init, para){
S1 <- init[1]
S2 <- init[2]
n1 <- para[1]
n2<- para[2]
k1 <- para[3]
k2 <- para[4]
M1 <- para[5]
M2 <- para[6]
k3 <- para[7]
k4 <- para[8]
dS1 = (k1 / (1 + ((S2/M2)^n1))) - (k3 * S1) # dS1/dt
dS2 = (k2 / (1 + ((S1/M1)^n2))) - (k4 * S2) # dS2/dt
list(c(dS1, dS2)) # function automatically returns dS1, dS2 as a list
}
# Give initial values - S1(t=0), S2(t=0)
init <- c(3, 1)
# Give parameter value - n1, n2, k1, k2, M1, M2, k3, k4
para <- c(2, 2, 20, 20, 1, 1, 5, 5)
# Time range for solution - till 6.7 - found out when calculated till 100
t <- seq(0, 6.7, 0.01)
# Calling ODE function
out <- ode(y = init, times = t, func = hill, parms = para)
# Plotting solution for S1(t)
plot(out[,1], out[,2], type = "l", xlab = "t", ylab = "S1(t)")
# Plotting solution for S2(t)
plot(out[,1], out[,3], type = "l", xlab = "t", ylab = "S2(t)")
# Plotting S1(t) vs S2(t)
plot(out[,2], out[,3], type = "l", xlab = "S1(t)", ylab = "S2(t)")
#Print summary - top few results
head(out)
# Printing Eigen Values
lambdas <- eigen(jacobian.full(y = init, func = hill,
parms = para))$values
print(lambdas)
if(is.complex(lambdas) == FALSE && lambdas[1] < 0 && lambdas[2] < 0){
print("Stable node - system is stable for given initial conditions.")
} else if(is.complex(lambdas) == FALSE && lambdas[1] > 0 && lambdas[2] > 0){
print("Unstable node - system is unstable for given initial conditions.")
} else if(is.complex(lambdas) == FALSE && lambdas[1] > 0 && lambdas[2] < 0){
print("Unstable node - saddle point - system is unstable for given initial conditions.")
} else if(is.complex(lambdas) == FALSE && lambdas[1] < 0 && lambdas[2] > 0){
print("Unstable node - saddle point - system is unstable for given initial conditions.")
} else if(is.complex(lambdas) == TRUE && Re(lambdas[1]) > 0 && Re(lambdas[2]) > 0){
print("Unstable focus - system is oscillatory and unstable.")
} else if(is.complex(lambdas) == TRUE && Re(lambdas[1]) < 0 && Re(lambdas[2]) < 0){
print("Stable focus - system is oscillatory and stable.")
}
model = function(x){
F1 <- (20 / (1 + ((x[2]/1)^2))) - (5 * x[1])
F2 <- (20 / (1 + ((x[1]/1)^2))) - (5 * x[2])
c(F1 = F1, F2 = F2)
}
ss = multiroot(f=model, start=c(3,1))
print(ss)
|
#### Script to create the dataset used by first draft model ####
library(dplyr)
library(reshape)
setwd("~/")
#### Read in raw dataset #######
electionsRaw <- read.csv("midterms/inputData/electionsNew2006_2018.csv", stringsAsFactors = TRUE, na.strings = c("#N/A", "NA"))
#setwd("~/MSPA/590-Thesis") # Work
#electionsRaw <- read.csv("electionsNew2006_2018.csv", stringsAsFactors = TRUE, na.strings = c("#N/A", "NA"))
### Update Sabato Scores and Numbers, re-write data ###
## Last updated: 13 June 2018
sabatoUpdate <- data.frame(ID = c("2018SC1", "2018WV3", "2018CA45", "2018NJ3", "2018NJ2", "2018VA7", "2018VA10", "2018VA2", "2018AR2", "2018FL16", "2018FL13",
"2018IA4", "2018IA3", "2018IL6", "2018IN9", "2018IN2", "2018KY6", "2018MI8", "2018NM2", "2018OH1", "2018PA16", "2018TX31",
"2018TX7", "2018KS3", "2018MI11", "2018NJ11", "2018NY27", "2018PA17", "2018PA7", "2018WA3", "2018WA5"),
Sabato2 = c("Likely R", "R Toss-up", "R Toss-up", "Leans R", "Likely D", "R Toss-up", "Leans D", "R Toss-up", "Leans R", "Leans R", "D",
"Likely R", "R Toss-up", "R Toss-up", "Likely R", "Likely R", "R Toss-up", "R Toss-up", "Leans R", "R Toss-up", "Likely R", "Likely R",
"R Toss-up", "R Toss-up", "Leans D", "Leans D", "Likely R", "Leans D", "Leans D", "Leans R", "R Toss-up"),
SabatoNum2 = c(3, 2, 1, 2, -3, 1, -2, 1, 2, 2, -5,
3, 1, 1, 3, 3, 1, 1, 2, 1, 3, 3,
1, 1, -2, -2, 3, -2, -2, 2, 1))
electionsRaw <- left_join(electionsRaw, sabatoUpdate, by = "ID")
electionsRaw$Sabato[!is.na(electionsRaw$Sabato2)] <- electionsRaw$Sabato2[!is.na(electionsRaw$Sabato2)]
electionsRaw$SabatoNum[!is.na(electionsRaw$SabatoNum2)] <- electionsRaw$SabatoNum2[!is.na(electionsRaw$SabatoNum2)]
electionsRaw$Sabato2 <- NULL
electionsRaw$SabatoNum2 <- NULL
rm(sabatoUpdate)
### Refresh DW_NOMINATE scores
nom_dat <- read.csv("https://voteview.com/static/data/out/members/HSall_members.csv")
nom_dat <- nom_dat[nom_dat$congress == 115 & nom_dat$chamber == "House",]
nom_dat$ID <- paste0("2018", nom_dat$state_abbrev, nom_dat$district_code)
nom_dat <- nom_dat[,c("ID", "nominate_dim1")]
nom_dat <- nom_dat[-which(duplicated(nom_dat$ID)),]
electionsRaw <- left_join(electionsRaw, nom_dat, by = "ID")
electionsRaw$INC_DW_NOM[electionsRaw$year == "2018"] <- electionsRaw$nominate_dim1[electionsRaw$year == "2018"]
electionsRaw$nominate_dim1 <- NULL
rm(nom_dat)
### Refresh Spending
disb <- read.csv("https://classic.fec.gov/data/CandidateSummary.do?format=csv&election_yr=2018&can_nam=&can_off=&can_off_sta=&can_off_dis=&can_par_aff=&can_inc_cha_ope_sea=&tot_rec=&tot_dis=&cas_on_han_clo_of_per=&deb_owe_by_com=&cov_dat=&sortField=can_nam&sortOrder=0")
disb <- subset(disb, can_off == "H")
disb$can_off_dis[disb$can_off_dis == 0] <- 1
disb$ID <- paste0("2018", disb$can_off_sta, disb$can_off_dis)
disb$tot_dis <- sub('\\$','',as.character(disb$tot_dis))
disb$tot_dis <- as.numeric(sub('\\,','',as.character(disb$tot_dis)))
disb$tot_dis[is.na(disb$tot_dis)] <- 0
disb$can_par_aff <- as.character(disb$can_par_aff)
disb$can_par_aff[disb$can_par_aff != "DEM" & disb$can_par_aff != "REP"] <- "OTHER"
disbTable <- cast(disb, ID ~ can_par_aff, sum, value = 'tot_dis')
electionsRaw <- left_join(electionsRaw, disbTable, by = "ID")
electionsRaw$Dcont[electionsRaw$year == "2018"] <- electionsRaw$DEM[electionsRaw$year == "2018"]
electionsRaw$Rcont[electionsRaw$year == "2018"] <- electionsRaw$REP[electionsRaw$year == "2018"]
electionsRaw$Ocont[electionsRaw$year == "2018"] <- electionsRaw$OTHER[electionsRaw$year == "2018"]
electionsRaw$DEM <- NULL
electionsRaw$REP <- NULL
electionsRaw$OTHER <- NULL
rm(disb, disbTable)
#### Subset and create new variables ####
# Incumbent winner indicator
electionsRaw$IncWin <- 0
electionsRaw$IncWin[electionsRaw$INC == electionsRaw$Winner] <- 1
# Incumbent party registration
electionsRaw$IncReg <- 0
electionsRaw$IncReg[electionsRaw$INC == "D"] <- electionsRaw$Dreg[electionsRaw$INC == "D"]
electionsRaw$IncReg[electionsRaw$INC == "R"] <- electionsRaw$Rreg[electionsRaw$INC == "R"]
# Non-Incumbent party registration
electionsRaw$NIncReg <- 0
electionsRaw$NIncReg[electionsRaw$INC == "D"] <- electionsRaw$Rreg[electionsRaw$INC == "D"]
electionsRaw$NIncReg[electionsRaw$INC == "R"] <- electionsRaw$Dreg[electionsRaw$INC == "R"]
# Registration difference
electionsRaw$RegDiff <- electionsRaw$IncReg - electionsRaw$NIncReg
# Existence of third party candidate indicator
electionsRaw$thirdParty <- 0
electionsRaw$thirdParty[electionsRaw$oPct > .01] <- 1
# Create third party effect variable
electionsRaw$thirdPartyEffect <- electionsRaw$Oreg*electionsRaw$thirdParty
# Re-code Pres_Incumbent_SameParty
electionsRaw$Pres_Incumbent_SameParty[electionsRaw$Pres_Incumbent_SameParty == 1] <- 1
electionsRaw$Pres_Incumbent_SameParty[electionsRaw$Pres_Incumbent_SameParty == 0] <- -1
# Create midterm effect variable
electionsRaw$midtermEffect <- electionsRaw$Midterm. * electionsRaw$Pres_Incumbent_SameParty
# Create Ideology Effect variable
electionsRaw$ideologyEffect <- electionsRaw$PVI...100.to.100. * electionsRaw$INC_DW_NOM
# Incumbent campaign spending variable
electionsRaw$IncCont <- 0
electionsRaw$NincCont <- 0
electionsRaw$IncCont[electionsRaw$INC == "R"] <- electionsRaw$Rcont[electionsRaw$INC == "R"]
electionsRaw$NincCont[electionsRaw$INC == "R"] <- electionsRaw$Dcont[electionsRaw$INC == "R"]
electionsRaw$IncCont[electionsRaw$INC == "D"] <- electionsRaw$Dcont[electionsRaw$INC == "D"]
electionsRaw$NincCont[electionsRaw$INC == "D"] <- electionsRaw$Rcont[electionsRaw$INC == "D"]
electionsRaw$IncContDiff <- log(electionsRaw$IncCont + 1) - log(electionsRaw$NincCont + 1)
electionsRaw$dContDiff <- electionsRaw$Dcont - electionsRaw$Rcont
# Log incumbent spending variable
electionsRaw$logIncCont <- log(electionsRaw$IncCont + 1)
# Republican indicator
electionsRaw$Repub <- 1
electionsRaw$Repub[electionsRaw$INC == "D"] <- -1
# PVI effect variable
electionsRaw$PVIeffect <- electionsRaw$PVI...100.to.100. * electionsRaw$Repub
# Two-party vote shares
electionsRaw$dPct2 <- electionsRaw$D/(electionsRaw$D + electionsRaw$R)
electionsRaw$rPct2 <- electionsRaw$R/(electionsRaw$D + electionsRaw$R)
# Dem win?
electionsRaw$dWin <- 0
electionsRaw$dWin[electionsRaw$dPct2 > 0.5] <- 1
### Change variable classes for EDA (e.g. change year to factor instead of integer) ###
electionsRaw$year <- as.factor(electionsRaw$year)
electionsRaw$district <- as.factor(electionsRaw$district)
electionsRaw$IncWin <- as.factor(electionsRaw$IncWin)
electionsRaw$thirdParty <- as.factor(electionsRaw$thirdParty)
electionsRaw$Midterm. <- as.factor(electionsRaw$Midterm.)
electionsRaw$Pres_Incumbent_SameParty <- as.factor(electionsRaw$Pres_Incumbent_SameParty)
electionsRaw$midtermEffect <- as.factor(electionsRaw$midtermEffect)
electionsRaw$Winner <- relevel(electionsRaw$Winner, "R")
electionsRaw$INC <- relevel(electionsRaw$INC, "R")
#Oreg has a lot of 1s because districts that do not require/collect party registration for voters are given 1 under Oreg
electionsRaw[which(electionsRaw$Oreg == 1),"Oreg"] <- NA
#Get rid of "O" factor for INC
electionsRaw$INC <- factor(electionsRaw$INC)
# Log NincCont
electionsRaw$logNincCont <- log(electionsRaw$NincCont + 1)
# Inc 2-party share
electionsRaw$IncPct2 <- electionsRaw$D/(electionsRaw$D + electionsRaw$R)
electionsRaw$IncPct2[electionsRaw$INC == "R"] <- electionsRaw$R[electionsRaw$INC == "R"]/(electionsRaw$D[electionsRaw$INC == "R"] + electionsRaw$R[electionsRaw$INC == "R"])
# Sabato
electionsRaw$SabatoScore <- electionsRaw$SabatoNum * electionsRaw$Repub
#Challenged
electionsRaw$Challenge[electionsRaw$year %in% c("2006", "2008", "2010", "2012", "2014", "2016")] <- 1
electionsRaw$Challenge[electionsRaw$year %in% c("2006", "2008", "2010", "2012", "2014", "2016") & (electionsRaw$dPct2 == 1 | electionsRaw$dPct2 == 0)] <- 0
### Refresh Polls, Open races, and whether races are Challenged ###
#dk <- gs_title("Daily Kos Elections House open seat tracker")
library(gsheet)
open <- gsheet2tbl("https://docs.google.com/spreadsheets/d/12RhR9oZZpyKKceyLO3C5am84abKzu2XqLWjP2LnQDgI/edit#gid=0")
colnames(open) <- open[1,]
open <- open[-1,]
#open2 <- gs_read(ss = dk, ws = "2018 - open seats", skip = 1)
open <- filter(open, Clinton %in% c(as.character(seq(0,100,1))))
open$Dist2 <- gsub("AL","1", substr(open$District,4,6))
open$Dist2[substr(open$Dist2,1,1) == "0"] <- substr(open$Dist2[substr(open$Dist2,1,1) == "0"], 2,2)
open$state <- substr(open$District,1,2)
open$ID <- paste0("2018", open$state, open$Dist2)
open$Open2 <- 1
open <- open[,12:13]
electionsRaw <- left_join(electionsRaw, open, by = "ID")
electionsRaw$Open2[is.na(electionsRaw$Open2)] <- 0
electionsRaw$Open[electionsRaw$year == "2018"] <- electionsRaw$Open2[electionsRaw$year == "2018"]
electionsRaw$Open2 <- NULL
unchallenged <- gsheet2tbl("https://docs.google.com/spreadsheets/d/12RhR9oZZpyKKceyLO3C5am84abKzu2XqLWjP2LnQDgI/edit#gid=195784761")
colnames(unchallenged) <- unchallenged[1,]
unchallenged <- unchallenged[-1,]
#unchallenged <- gs_read(ss = dk, ws = "2018 - uncontested seats", skip = 1)
unchallenged <- filter(unchallenged, Clinton %in% c(as.character(seq(0,100,1))))
unchallenged$Dist2 <- gsub("AL","1", substr(unchallenged$District,4,6))
unchallenged$Dist2[substr(unchallenged$Dist2,1,1) == "0"] <- substr(unchallenged$Dist2[substr(unchallenged$Dist2,1,1) == "0"], 2,2)
unchallenged$state <- substr(unchallenged$District,1,2)
unchallenged$ID <- paste0("2018", unchallenged$state, unchallenged$Dist2)
unchallenged$Challenge2 <- 0
unchallenged <- unchallenged[,10:11]
electionsRaw <- left_join(electionsRaw, unchallenged, by = "ID")
electionsRaw$Challenge2[is.na(electionsRaw$Challenge2)] <- 1
electionsRaw$Challenge[electionsRaw$year == "2018"] <- electionsRaw$Challenge2[electionsRaw$year == "2018"]
electionsRaw$Challenge2 <- NULL
pollYear <- data.frame(year = c("2006", "2008", "2010", "2012", "2014", "2016", "2018"), Polls = c(7.9,10.7,-6.8,1.2,-5.7,-1.1,8.2), dSwing = c(10.5,2.8,-17.4,8,-6.9,4.6,9.3))
polls <- read.csv("https://projects.fivethirtyeight.com/generic-ballot-data/generic_topline.csv")
pollYear$Polls[7] <- round(polls$dem_estimate[3] - polls$rep_estimate[3], digits = 1)
pollYear$dSwing[7] <- pollYear$Polls[7] - pollYear$Polls[6]
electionsRaw <- left_join(electionsRaw, pollYear, by = "year")
rm(open, polls, pollYear, unchallenged)
## Other modeling variables ##
modelData <- electionsRaw
modelData$PrevElectionD2 <- modelData$PrevElectionD./(modelData$PrevElectionD. + modelData$PrevElectionR.)
modelData$Prev2ElectionD2 <- modelData$PrevElection2D./(modelData$PrevElection2D. + modelData$PrevElection2R.)
modelData$Prev2ElectionD2Diff <- (modelData$PrevElection2D./(modelData$PrevElection2D. + modelData$PrevElection2R.)) -.5
modelData$OpenInc <- "Open"
modelData$OpenInc[modelData$Open == 0] <- as.character(modelData$INC[modelData$Open == 0])
modelData$midPres <- "On-cycle"
modelData$midPres[modelData$Midterm. == 1] <- as.character(modelData$PresParty[modelData$Midterm. == 1])
modelData$PrevElectionD2Diff <- modelData$PrevElectionD2 - .5
modelData$PrevElectionD2DiffSwing <- modelData$PrevElectionD2Diff - (modelData$Prev2ElectionD2 - .5)
modelData$Dcont[is.na(modelData$Dcont)] <- 0
modelData$Rcont[is.na(modelData$Rcont)] <- 0
modelData$logDCont <- log(modelData$Dcont + 1)
modelData$logRCont <- log(modelData$Rcont + 1)
modelData$logDContDiff <- modelData$logDCont - modelData$logRCont
#modelData$logDContDiff <- 0
#modelData$logDContDiff[modelData$Dcont >= modelData$Rcont] <- log(modelData$Dcont[modelData$Dcont >= modelData$Rcont] - modelData$Rcont[modelData$Dcont >= modelData$Rcont] + 1)
#modelData$logDContDiff[modelData$Rcont >= modelData$Dcont] <- log(modelData$Rcont[modelData$Rcont >= modelData$Dcont] - modelData$Dcont[modelData$Rcont >= modelData$Dcont] + 1)*-1
modelData$OpenInc <- as.factor(modelData$OpenInc)
modelData$midPres <- as.factor(modelData$midPres)
modelData$ideologyEffect2 <- modelData$ideologyEffect*modelData$Repub
modelData$crossPressure <- 0
modelData$crossPressure[sign(modelData$INC_DW_NOM) != sign(modelData$PVI2) & modelData$INC == "D"] <- -1
modelData$crossPressure[sign(modelData$INC_DW_NOM) != sign(modelData$PVI2) & modelData$INC == "R"] <- 1
## Final model data before subsetting to challenged becomes exploratory dataset
explore <- modelData
# Additional (unchallenged) seats -- we will add this data to our final dataset later
rfTestAdd <- subset(modelData, year == "2018" & Challenge == 0)
# Subset model data -- must be a challenged race
modelData <- subset(modelData, Challenge == 1)
### Fix exploratory dataset
#colnames(explore)
explore <- subset(explore, select = c("year", "state", "district", "oPct", "ID", "INC", "Winner", "Open", "Challenge", "Dcont", "Rcont", "Ocont", "Midterm.", "PVI...100.to.100.",
"PresParty", "Pres_Incumbent_SameParty", "PrevPresR.", "PrevPresD.", "PrevPresImcumb.", "YearsIncumbPartyControl", "TermsDemControl",
"TermsRepControl", "Age.25.to.44", "Age.65.and.over", "Race.White", "Race.Black.or.African.American", "Race.American.Indian.and.Alaska.Native",
"Race.Asian", "Race.Native.Hawaiian.and.Other.Pacific.Islander", "Race.Some.other.race", "Race.Two.or.more.races",
"Race.Hispanic.or.Latino", "Unemployment.Rate", "Delta.unemployment.Rate", "Median.household.income", "PercentDelta.median.household.income",
"Percent.below.poverty.level", "INC_DW_NOM", "Sabato", "SabatoNum", "PVI2", "IncWin", "thirdParty", "midtermEffect", "ideologyEffect",
"IncCont", "NincCont", "IncContDiff", "dContDiff", "logIncCont", "PVIeffect", "dPct2", "rPct2", "dWin", "logNincCont", "IncPct2", "SabatoScore",
"Polls", "dSwing", "PrevElectionD2", "Prev2ElectionD2", "Prev2ElectionD2Diff", "OpenInc", "midPres", "PrevElectionD2Diff", "PrevElectionD2DiffSwing",
"logDCont", "logRCont", "logDContDiff", "ideologyEffect2", "crossPressure"))
colnames(explore) <- c("year", "state", "district", "otherPct", "id", "INC", "winner", "open", "challenged", "demExpenditures", "repExpenditures", "otherExpenditures", "midterm", "cookPVI",
"presParty", "presINCsameParty", "prevPresR", "prevPresD", "prevPresINC", "yrsINCpartyControl", "termsDemControl",
"termsRepControl", "age25to44", "age65andover", "raceWhite", "raceBlackOrAfricanAmerican", "raceAmericanIndianAndAlaskaNative",
"raceAsian", "raceNativeHawaiianAndOtherPacificIslander", "RaceSomeOtherRace", "raceTwoOrMoreRaces",
"raceHispanicOrLatino", "unemploymentRate", "deltaUnemploymentRate", "medianHouseholdIncome", "percentDeltaMedianHouseholdIncome",
"percentBelowPovertyLevel", "INCdwNom", "sabato", "sabatoNum", "weightedPVI", "incWin", "thirdParty", "midtermEffect", "ideologyEffect",
"incExpenditures", "nincExpenditures", "incExpDiff", "dExpDiff", "logIncExp", "PVIeffect", "dPct2", "rPct2", "dWin", "logNincExp", "incPct2", "sabatoScore",
"polls", "dSwing", "prevElectionDem", "Prev2ElectionDem", "Prev2ElectionDemDiff", "OpenInc", "midPres", "prevElectionDemDiff", "prevElectionDemDiffSwing",
"logDemExp", "logRepExp", "logDemContDiff", "ideologyEffectDem", "crossPressure")
explore$dWin[explore$year == "2018"] <- "NA"
explore$incWin[explore$year == "2018"] <- "NA"
explore$thirdParty[explore$year == "2018"] <- "NA"
write.csv(explore, "midterms/outputData/explore.csv", row.names = FALSE)
#########################################################################################################################################################################################################
#########################################################################################################################################################################################################
#########################################################################################################################################################################################################
#########################################################################################################################################################################################################
# Random forest
library(randomForest)
rfData <- subset(modelData, select = -c(Dreg, Rreg, Oreg, RegDiff, IncReg, NIncReg, PVI..0.to.100., PresApprov, PresDisapp, PresApprovDiff, ECI, thirdPartyEffect,
total_votes, D, O, R, dPct, rPct, oPct, IncPct, ID2, Pres_Incumbent_SameParty, PrevElectionR., PrevElectionD., PrevElectionIncumbParty.,
PrevElection2R., PrevElection2D., PrevElection2IncumbParty., PrevPresImcumb., PrevPresSameAsInc., YearsIncumbPartyControl, Sabato,
IncWin, IncCont, NincCont, IncContDiff, logIncCont, PVIeffect, logNincCont, IncPct2, SabatoScore))
rfTrain <- na.omit(subset(rfData, year == "2006" | year == "2008" | year == "2010" | year == "2012" | year == "2014" | year == "2016"))
rfTest <- subset(rfData, year == "2018")
rfTest[is.na(rfTest)] <- 0
levels(rfTest$Winner) <- c("R", "D", "0")
rfTest$Winner[is.na(rfTest$Winner)] <- "0"
#Training data (subset of variables)
X.train <- subset(rfTrain, select = -c(year, state, district, ID, Winner, Repub, rPct2, dWin, logDCont, logRCont, ideologyEffect, ideologyEffect2, Prev2ElectionD2, Dcont, Rcont, PVI...100.to.100., PrevPresD., PrevPresR., midtermEffect, Challenge, PresYrsIncumb, PrevPresParty, PrevElectionD2, demoScore))
#colnames(rfData)
# Random forest generation and prediction
set.seed(1)
rf <- randomForest(x = X.train[,-28], y = X.train[,28], mtry = 10, importance = TRUE, ntree = 500)
yhat.rf <- predict(rf, newdata = rfTest)
#par(pty = "s")
#plot(yhat.rf, rfTest$dPct2, main = "Predicted versus actual", xlab = "Predicted Incumbent Vote Share", ylab = "Actual Incumbent Vote Share", xlim = c(.1,1), ylim = c(.1,1))
#abline(0,1)
#sqrt(mean((yhat.rf - rfTest$dPct2)^2))
#mean(abs(yhat.rf - rfTest$dPct2))
#par(pty = "m")
#varImpPlot(rf, n.var = 36)
#table(yhat.rf >= 0.5, rfTest$dPct2 >= 0.5)
#table(yhat.rf >= 0.5)
#hist(yhat.rf - rfTest$dPct2, breaks = 24, main = "Histogram of errors (predicted - actual)", xlab = "Error", xlim = c(-.15,.15))
########################################################################################
#### Simulation -- counting the number of seats won by each party in each iteration ####
########################################################################################
numSim <- 20000
dfCount <- as.data.frame(seq(1,numSim,1))
colnames(dfCount) <- "sim"
dfCount$dWin <- 0
dfCount$rWin <- 0
# Dataset used for shiny app, which includes the predicted vote shares from rf and number of times the Dem won each seat
rfTestCheck <- rfTest
rfTestCheck$dPctPred <- yhat.rf
rfTestCheck$Pred <- 0
#
wins <- numeric(numSim)
counts <- numeric(nrow(rfTest))
# Might need this package to create distributions
library(statmod)
# Iterate!
start_time <- Sys.time()
for(i in 1:numSim){
rfTest2 <- rfTest
natError <- rnorm(1, mean = 0, sd = 3)
rfTest2$dSwing <- rfTest2$dSwing + natError
rfTest2$Polls <- rfTest2$Polls + natError
#districtError <- rnorm(nrow(rfTest2), mean = natError/100, sd=.05)
districtError <- rnorm(nrow(rfTest2), mean = natError/100, sd=(.5 - abs(yhat.rf-.5))/7)
#districtError <- rinvgauss(nrow(rfTest2), mean = (.5 - abs(yhat.rf-.5))/8, shape = .2) # or should we use inverse normal dist? rinvgauss()
#districtError <- rfTest2$demoScore + natError/100
#districtError <- rfTest2$demoScore + rnorm(nrow(rfTest2), mean = natError/100, sd=.05)
yhat.rf <- predict(rf, newdata = rfTest2)
wins[i] <- sum(yhat.rf + districtError >= 0.5)
counts <- counts + (yhat.rf + districtError >= 0.5)
}
end_time <- Sys.time()
# Count the number of times the Democrats took control of the House, and how many times the Dem candidate won each district
dfCount$dWin <- wins
rfTestCheck$Pred <- counts
# Add the data we removed earlier for races that are unchallenged
rfTestAdd <- subset(rfTestAdd, select = -c(Dreg, Rreg, Oreg, RegDiff, IncReg, NIncReg, PVI..0.to.100., PresApprov, PresDisapp, PresApprovDiff, ECI, thirdPartyEffect,
total_votes, D, O, R, dPct, rPct, oPct, IncPct, ID2, Pres_Incumbent_SameParty, PrevElectionR., PrevElectionD., PrevElectionIncumbParty.,
PrevElection2R., PrevElection2D., PrevElection2IncumbParty., PrevPresImcumb., PrevPresSameAsInc., YearsIncumbPartyControl, Sabato,
IncWin, IncCont, NincCont, IncContDiff, logIncCont, PVIeffect, logNincCont, IncPct2, SabatoScore))
rfTestAdd$Pred <- numSim
rfTestAdd$Pred[rfTestAdd$SabatoNum > 0] <- 0
rfTestAdd$Pred[rfTestAdd$SabatoNum < 0] <- numSim
rfTestAdd$dPctPred <- 1
rfTestAdd$dPctPred[rfTestAdd$SabatoNum > 0] <- 0
rfTestCheck <- rbind(rfTestCheck, rfTestAdd)
# How many seats were unchallenged? We need this number for the shiny app
demUnchallenged <- nrow(subset(electionsRaw, year == "2018" & Challenge == 0 & INC == "D"))
dfCount$demUnchallenged <- demUnchallenged
#hist(dfCount$dWin + demUnchallenged, breaks = seq(0,435,1), xlim = c(150,300), main = "")
#abline(v = 218, lty = "dashed")
#abline(v = median(dfCount$dWin) + demUnchallenged)
#table(dfCount$dWin + demUnchallenged >= 218)
# What are the odds that the Dems take control of the House?
dProb <- table(dfCount$dWin + demUnchallenged >= 218)[2]/numSim
#ggplot(dfCount, aes(dWin + demUnchallenged)) + geom_histogram(binwidth = 1, aes(fill = dWin + demUnchallenged >= 218))
#ggplot(dfCount, aes(dWin + demUnchallenged - 218)) + geom_histogram(binwidth = 5, aes(fill = dWin + demUnchallenged - 218 > 0))
#ggplot(rfTestCheck, aes(round(Pred/numSim, 1))) + geom_dotplot(dotsize = .5)
# Write out the data that tells us the Dems chances AND the individual district data (once to use for the app, and once for archiving in case we need it later)
write.csv(dfCount, "midterms/outputData/dfCount.csv", row.names = FALSE)
write.csv(rfTestCheck, "midterms/outputData/rfTestCheck.csv", row.names = FALSE)
write.csv(rfTestCheck, paste0("midterms/outputData/Archive/rfTestCheck", Sys.Date(), ".csv"), row.names = FALSE)
# Write out the data that shows the Dems chances to take control for every day of the election season
#dWinDf <- data.frame(Date = seq(as.Date('2018-06-14'),as.Date('2018-11-06'),by = 1), dProb = NA)
#write.csv(dWinDf, "dWin.csv", row.names = FALSE)
dWin <- read.csv("midterms/outputData/dWin.csv")
dWin$Date <- as.Date(dWin$Date, format = "%Y-%m-%d")
dWin$dProb[dWin$Date == Sys.Date()] <- dProb
write.csv(dWin, "midterms/outputData/dWin.csv", row.names = FALSE)
#rf2 <- randomForest(as.factor(dWin) ~ . -year -state -district -ID -Winner -Repub -rPct2 -dPct2 -incSwing -logDCont -logRCont -SabatoNum -ideologyEffect -Dcont -Rcont -PrevPresD. -PrevPresR. -midtermEffect, data = rfTrain, mtry = 10, importance = TRUE, ntree = 500)
#yhat.rf2 <- predict(rf2, newdata = rfTest, type = "prob")
#rf2Inspect <- cbind(rfTest, dProb = yhat.rf2[,2])
#plot(rf2Inspect$dProb, rfTestCheck$Pred/10000)
#abline(0,1)
# Refresh the shiny app!
#quit(save = "no")
rsconnect::setAccountInfo(name='pquinn1991', token='74383A64C5E471D7D7F661261D4E08DE', secret='z9OMYbFWp6HYA3mYOy6LeqQM52RdBC/zEVV+/NzW')
library(rsconnect)
setwd("midterms")
deployApp(account = "pquinn1991", launch.browser = FALSE, appName = "midterms")
Y
| /dailyRun.R | no_license | vmandela99/Congressional-Elections-Predictive-Model | R | false | false | 24,040 | r | #### Script to create the dataset used by first draft model ####
library(dplyr)
library(reshape)
setwd("~/")
#### Read in raw dataset #######
electionsRaw <- read.csv("midterms/inputData/electionsNew2006_2018.csv", stringsAsFactors = TRUE, na.strings = c("#N/A", "NA"))
#setwd("~/MSPA/590-Thesis") # Work
#electionsRaw <- read.csv("electionsNew2006_2018.csv", stringsAsFactors = TRUE, na.strings = c("#N/A", "NA"))
### Update Sabato Scores and Numbers, re-write data ###
## Last updated: 13 June 2018
sabatoUpdate <- data.frame(ID = c("2018SC1", "2018WV3", "2018CA45", "2018NJ3", "2018NJ2", "2018VA7", "2018VA10", "2018VA2", "2018AR2", "2018FL16", "2018FL13",
"2018IA4", "2018IA3", "2018IL6", "2018IN9", "2018IN2", "2018KY6", "2018MI8", "2018NM2", "2018OH1", "2018PA16", "2018TX31",
"2018TX7", "2018KS3", "2018MI11", "2018NJ11", "2018NY27", "2018PA17", "2018PA7", "2018WA3", "2018WA5"),
Sabato2 = c("Likely R", "R Toss-up", "R Toss-up", "Leans R", "Likely D", "R Toss-up", "Leans D", "R Toss-up", "Leans R", "Leans R", "D",
"Likely R", "R Toss-up", "R Toss-up", "Likely R", "Likely R", "R Toss-up", "R Toss-up", "Leans R", "R Toss-up", "Likely R", "Likely R",
"R Toss-up", "R Toss-up", "Leans D", "Leans D", "Likely R", "Leans D", "Leans D", "Leans R", "R Toss-up"),
SabatoNum2 = c(3, 2, 1, 2, -3, 1, -2, 1, 2, 2, -5,
3, 1, 1, 3, 3, 1, 1, 2, 1, 3, 3,
1, 1, -2, -2, 3, -2, -2, 2, 1))
electionsRaw <- left_join(electionsRaw, sabatoUpdate, by = "ID")
electionsRaw$Sabato[!is.na(electionsRaw$Sabato2)] <- electionsRaw$Sabato2[!is.na(electionsRaw$Sabato2)]
electionsRaw$SabatoNum[!is.na(electionsRaw$SabatoNum2)] <- electionsRaw$SabatoNum2[!is.na(electionsRaw$SabatoNum2)]
electionsRaw$Sabato2 <- NULL
electionsRaw$SabatoNum2 <- NULL
rm(sabatoUpdate)
### Refresh DW_NOMINATE scores
nom_dat <- read.csv("https://voteview.com/static/data/out/members/HSall_members.csv")
nom_dat <- nom_dat[nom_dat$congress == 115 & nom_dat$chamber == "House",]
nom_dat$ID <- paste0("2018", nom_dat$state_abbrev, nom_dat$district_code)
nom_dat <- nom_dat[,c("ID", "nominate_dim1")]
nom_dat <- nom_dat[-which(duplicated(nom_dat$ID)),]
electionsRaw <- left_join(electionsRaw, nom_dat, by = "ID")
electionsRaw$INC_DW_NOM[electionsRaw$year == "2018"] <- electionsRaw$nominate_dim1[electionsRaw$year == "2018"]
electionsRaw$nominate_dim1 <- NULL
rm(nom_dat)
### Refresh Spending
disb <- read.csv("https://classic.fec.gov/data/CandidateSummary.do?format=csv&election_yr=2018&can_nam=&can_off=&can_off_sta=&can_off_dis=&can_par_aff=&can_inc_cha_ope_sea=&tot_rec=&tot_dis=&cas_on_han_clo_of_per=&deb_owe_by_com=&cov_dat=&sortField=can_nam&sortOrder=0")
disb <- subset(disb, can_off == "H")
disb$can_off_dis[disb$can_off_dis == 0] <- 1
disb$ID <- paste0("2018", disb$can_off_sta, disb$can_off_dis)
disb$tot_dis <- sub('\\$','',as.character(disb$tot_dis))
disb$tot_dis <- as.numeric(sub('\\,','',as.character(disb$tot_dis)))
disb$tot_dis[is.na(disb$tot_dis)] <- 0
disb$can_par_aff <- as.character(disb$can_par_aff)
disb$can_par_aff[disb$can_par_aff != "DEM" & disb$can_par_aff != "REP"] <- "OTHER"
disbTable <- cast(disb, ID ~ can_par_aff, sum, value = 'tot_dis')
electionsRaw <- left_join(electionsRaw, disbTable, by = "ID")
electionsRaw$Dcont[electionsRaw$year == "2018"] <- electionsRaw$DEM[electionsRaw$year == "2018"]
electionsRaw$Rcont[electionsRaw$year == "2018"] <- electionsRaw$REP[electionsRaw$year == "2018"]
electionsRaw$Ocont[electionsRaw$year == "2018"] <- electionsRaw$OTHER[electionsRaw$year == "2018"]
electionsRaw$DEM <- NULL
electionsRaw$REP <- NULL
electionsRaw$OTHER <- NULL
rm(disb, disbTable)
#### Subset and create new variables ####
# Incumbent winner indicator
electionsRaw$IncWin <- 0
electionsRaw$IncWin[electionsRaw$INC == electionsRaw$Winner] <- 1
# Incumbent party registration
electionsRaw$IncReg <- 0
electionsRaw$IncReg[electionsRaw$INC == "D"] <- electionsRaw$Dreg[electionsRaw$INC == "D"]
electionsRaw$IncReg[electionsRaw$INC == "R"] <- electionsRaw$Rreg[electionsRaw$INC == "R"]
# Non-Incumbent party registration
electionsRaw$NIncReg <- 0
electionsRaw$NIncReg[electionsRaw$INC == "D"] <- electionsRaw$Rreg[electionsRaw$INC == "D"]
electionsRaw$NIncReg[electionsRaw$INC == "R"] <- electionsRaw$Dreg[electionsRaw$INC == "R"]
# Registration difference
electionsRaw$RegDiff <- electionsRaw$IncReg - electionsRaw$NIncReg
# Existence of third party candidate indicator
electionsRaw$thirdParty <- 0
electionsRaw$thirdParty[electionsRaw$oPct > .01] <- 1
# Create third party effect variable
electionsRaw$thirdPartyEffect <- electionsRaw$Oreg*electionsRaw$thirdParty
# Re-code Pres_Incumbent_SameParty
electionsRaw$Pres_Incumbent_SameParty[electionsRaw$Pres_Incumbent_SameParty == 1] <- 1
electionsRaw$Pres_Incumbent_SameParty[electionsRaw$Pres_Incumbent_SameParty == 0] <- -1
# Create midterm effect variable
electionsRaw$midtermEffect <- electionsRaw$Midterm. * electionsRaw$Pres_Incumbent_SameParty
# Create Ideology Effect variable
electionsRaw$ideologyEffect <- electionsRaw$PVI...100.to.100. * electionsRaw$INC_DW_NOM
# Incumbent campaign spending variable
electionsRaw$IncCont <- 0
electionsRaw$NincCont <- 0
electionsRaw$IncCont[electionsRaw$INC == "R"] <- electionsRaw$Rcont[electionsRaw$INC == "R"]
electionsRaw$NincCont[electionsRaw$INC == "R"] <- electionsRaw$Dcont[electionsRaw$INC == "R"]
electionsRaw$IncCont[electionsRaw$INC == "D"] <- electionsRaw$Dcont[electionsRaw$INC == "D"]
electionsRaw$NincCont[electionsRaw$INC == "D"] <- electionsRaw$Rcont[electionsRaw$INC == "D"]
electionsRaw$IncContDiff <- log(electionsRaw$IncCont + 1) - log(electionsRaw$NincCont + 1)
electionsRaw$dContDiff <- electionsRaw$Dcont - electionsRaw$Rcont
# Log incumbent spending variable
electionsRaw$logIncCont <- log(electionsRaw$IncCont + 1)
# Republican indicator
electionsRaw$Repub <- 1
electionsRaw$Repub[electionsRaw$INC == "D"] <- -1
# PVI effect variable
electionsRaw$PVIeffect <- electionsRaw$PVI...100.to.100. * electionsRaw$Repub
# Two-party vote shares
electionsRaw$dPct2 <- electionsRaw$D/(electionsRaw$D + electionsRaw$R)
electionsRaw$rPct2 <- electionsRaw$R/(electionsRaw$D + electionsRaw$R)
# Dem win?
electionsRaw$dWin <- 0
electionsRaw$dWin[electionsRaw$dPct2 > 0.5] <- 1
### Change variable classes for EDA (e.g. change year to factor instead of integer) ###
electionsRaw$year <- as.factor(electionsRaw$year)
electionsRaw$district <- as.factor(electionsRaw$district)
electionsRaw$IncWin <- as.factor(electionsRaw$IncWin)
electionsRaw$thirdParty <- as.factor(electionsRaw$thirdParty)
electionsRaw$Midterm. <- as.factor(electionsRaw$Midterm.)
electionsRaw$Pres_Incumbent_SameParty <- as.factor(electionsRaw$Pres_Incumbent_SameParty)
electionsRaw$midtermEffect <- as.factor(electionsRaw$midtermEffect)
electionsRaw$Winner <- relevel(electionsRaw$Winner, "R")
electionsRaw$INC <- relevel(electionsRaw$INC, "R")
#Oreg has a lot of 1s because districts that do not require/collect party registration for voters are given 1 under Oreg
electionsRaw[which(electionsRaw$Oreg == 1),"Oreg"] <- NA
#Get rid of "O" factor for INC
electionsRaw$INC <- factor(electionsRaw$INC)
# Log NincCont
electionsRaw$logNincCont <- log(electionsRaw$NincCont + 1)
# Inc 2-party share
electionsRaw$IncPct2 <- electionsRaw$D/(electionsRaw$D + electionsRaw$R)
electionsRaw$IncPct2[electionsRaw$INC == "R"] <- electionsRaw$R[electionsRaw$INC == "R"]/(electionsRaw$D[electionsRaw$INC == "R"] + electionsRaw$R[electionsRaw$INC == "R"])
# Sabato
electionsRaw$SabatoScore <- electionsRaw$SabatoNum * electionsRaw$Repub
#Challenged
electionsRaw$Challenge[electionsRaw$year %in% c("2006", "2008", "2010", "2012", "2014", "2016")] <- 1
electionsRaw$Challenge[electionsRaw$year %in% c("2006", "2008", "2010", "2012", "2014", "2016") & (electionsRaw$dPct2 == 1 | electionsRaw$dPct2 == 0)] <- 0
### Refresh Polls, Open races, and whether races are Challenged ###
#dk <- gs_title("Daily Kos Elections House open seat tracker")
library(gsheet)
open <- gsheet2tbl("https://docs.google.com/spreadsheets/d/12RhR9oZZpyKKceyLO3C5am84abKzu2XqLWjP2LnQDgI/edit#gid=0")
colnames(open) <- open[1,]
open <- open[-1,]
#open2 <- gs_read(ss = dk, ws = "2018 - open seats", skip = 1)
open <- filter(open, Clinton %in% c(as.character(seq(0,100,1))))
open$Dist2 <- gsub("AL","1", substr(open$District,4,6))
open$Dist2[substr(open$Dist2,1,1) == "0"] <- substr(open$Dist2[substr(open$Dist2,1,1) == "0"], 2,2)
open$state <- substr(open$District,1,2)
open$ID <- paste0("2018", open$state, open$Dist2)
open$Open2 <- 1
open <- open[,12:13]
electionsRaw <- left_join(electionsRaw, open, by = "ID")
electionsRaw$Open2[is.na(electionsRaw$Open2)] <- 0
electionsRaw$Open[electionsRaw$year == "2018"] <- electionsRaw$Open2[electionsRaw$year == "2018"]
electionsRaw$Open2 <- NULL
unchallenged <- gsheet2tbl("https://docs.google.com/spreadsheets/d/12RhR9oZZpyKKceyLO3C5am84abKzu2XqLWjP2LnQDgI/edit#gid=195784761")
colnames(unchallenged) <- unchallenged[1,]
unchallenged <- unchallenged[-1,]
#unchallenged <- gs_read(ss = dk, ws = "2018 - uncontested seats", skip = 1)
unchallenged <- filter(unchallenged, Clinton %in% c(as.character(seq(0,100,1))))
unchallenged$Dist2 <- gsub("AL","1", substr(unchallenged$District,4,6))
unchallenged$Dist2[substr(unchallenged$Dist2,1,1) == "0"] <- substr(unchallenged$Dist2[substr(unchallenged$Dist2,1,1) == "0"], 2,2)
unchallenged$state <- substr(unchallenged$District,1,2)
unchallenged$ID <- paste0("2018", unchallenged$state, unchallenged$Dist2)
unchallenged$Challenge2 <- 0
unchallenged <- unchallenged[,10:11]
electionsRaw <- left_join(electionsRaw, unchallenged, by = "ID")
electionsRaw$Challenge2[is.na(electionsRaw$Challenge2)] <- 1
electionsRaw$Challenge[electionsRaw$year == "2018"] <- electionsRaw$Challenge2[electionsRaw$year == "2018"]
electionsRaw$Challenge2 <- NULL
pollYear <- data.frame(year = c("2006", "2008", "2010", "2012", "2014", "2016", "2018"), Polls = c(7.9,10.7,-6.8,1.2,-5.7,-1.1,8.2), dSwing = c(10.5,2.8,-17.4,8,-6.9,4.6,9.3))
polls <- read.csv("https://projects.fivethirtyeight.com/generic-ballot-data/generic_topline.csv")
pollYear$Polls[7] <- round(polls$dem_estimate[3] - polls$rep_estimate[3], digits = 1)
pollYear$dSwing[7] <- pollYear$Polls[7] - pollYear$Polls[6]
electionsRaw <- left_join(electionsRaw, pollYear, by = "year")
rm(open, polls, pollYear, unchallenged)
## Other modeling variables ##
modelData <- electionsRaw
modelData$PrevElectionD2 <- modelData$PrevElectionD./(modelData$PrevElectionD. + modelData$PrevElectionR.)
modelData$Prev2ElectionD2 <- modelData$PrevElection2D./(modelData$PrevElection2D. + modelData$PrevElection2R.)
modelData$Prev2ElectionD2Diff <- (modelData$PrevElection2D./(modelData$PrevElection2D. + modelData$PrevElection2R.)) -.5
modelData$OpenInc <- "Open"
modelData$OpenInc[modelData$Open == 0] <- as.character(modelData$INC[modelData$Open == 0])
modelData$midPres <- "On-cycle"
modelData$midPres[modelData$Midterm. == 1] <- as.character(modelData$PresParty[modelData$Midterm. == 1])
modelData$PrevElectionD2Diff <- modelData$PrevElectionD2 - .5
modelData$PrevElectionD2DiffSwing <- modelData$PrevElectionD2Diff - (modelData$Prev2ElectionD2 - .5)
modelData$Dcont[is.na(modelData$Dcont)] <- 0
modelData$Rcont[is.na(modelData$Rcont)] <- 0
modelData$logDCont <- log(modelData$Dcont + 1)
modelData$logRCont <- log(modelData$Rcont + 1)
modelData$logDContDiff <- modelData$logDCont - modelData$logRCont
#modelData$logDContDiff <- 0
#modelData$logDContDiff[modelData$Dcont >= modelData$Rcont] <- log(modelData$Dcont[modelData$Dcont >= modelData$Rcont] - modelData$Rcont[modelData$Dcont >= modelData$Rcont] + 1)
#modelData$logDContDiff[modelData$Rcont >= modelData$Dcont] <- log(modelData$Rcont[modelData$Rcont >= modelData$Dcont] - modelData$Dcont[modelData$Rcont >= modelData$Dcont] + 1)*-1
modelData$OpenInc <- as.factor(modelData$OpenInc)
modelData$midPres <- as.factor(modelData$midPres)
modelData$ideologyEffect2 <- modelData$ideologyEffect*modelData$Repub
modelData$crossPressure <- 0
modelData$crossPressure[sign(modelData$INC_DW_NOM) != sign(modelData$PVI2) & modelData$INC == "D"] <- -1
modelData$crossPressure[sign(modelData$INC_DW_NOM) != sign(modelData$PVI2) & modelData$INC == "R"] <- 1
## Final model data before subsetting to challenged becomes exploratory dataset
explore <- modelData
# Additional (unchallenged) seats -- we will add this data to our final dataset later
rfTestAdd <- subset(modelData, year == "2018" & Challenge == 0)
# Subset model data -- must be a challenged race
modelData <- subset(modelData, Challenge == 1)
### Fix exploratory dataset
#colnames(explore)
explore <- subset(explore, select = c("year", "state", "district", "oPct", "ID", "INC", "Winner", "Open", "Challenge", "Dcont", "Rcont", "Ocont", "Midterm.", "PVI...100.to.100.",
"PresParty", "Pres_Incumbent_SameParty", "PrevPresR.", "PrevPresD.", "PrevPresImcumb.", "YearsIncumbPartyControl", "TermsDemControl",
"TermsRepControl", "Age.25.to.44", "Age.65.and.over", "Race.White", "Race.Black.or.African.American", "Race.American.Indian.and.Alaska.Native",
"Race.Asian", "Race.Native.Hawaiian.and.Other.Pacific.Islander", "Race.Some.other.race", "Race.Two.or.more.races",
"Race.Hispanic.or.Latino", "Unemployment.Rate", "Delta.unemployment.Rate", "Median.household.income", "PercentDelta.median.household.income",
"Percent.below.poverty.level", "INC_DW_NOM", "Sabato", "SabatoNum", "PVI2", "IncWin", "thirdParty", "midtermEffect", "ideologyEffect",
"IncCont", "NincCont", "IncContDiff", "dContDiff", "logIncCont", "PVIeffect", "dPct2", "rPct2", "dWin", "logNincCont", "IncPct2", "SabatoScore",
"Polls", "dSwing", "PrevElectionD2", "Prev2ElectionD2", "Prev2ElectionD2Diff", "OpenInc", "midPres", "PrevElectionD2Diff", "PrevElectionD2DiffSwing",
"logDCont", "logRCont", "logDContDiff", "ideologyEffect2", "crossPressure"))
colnames(explore) <- c("year", "state", "district", "otherPct", "id", "INC", "winner", "open", "challenged", "demExpenditures", "repExpenditures", "otherExpenditures", "midterm", "cookPVI",
"presParty", "presINCsameParty", "prevPresR", "prevPresD", "prevPresINC", "yrsINCpartyControl", "termsDemControl",
"termsRepControl", "age25to44", "age65andover", "raceWhite", "raceBlackOrAfricanAmerican", "raceAmericanIndianAndAlaskaNative",
"raceAsian", "raceNativeHawaiianAndOtherPacificIslander", "RaceSomeOtherRace", "raceTwoOrMoreRaces",
"raceHispanicOrLatino", "unemploymentRate", "deltaUnemploymentRate", "medianHouseholdIncome", "percentDeltaMedianHouseholdIncome",
"percentBelowPovertyLevel", "INCdwNom", "sabato", "sabatoNum", "weightedPVI", "incWin", "thirdParty", "midtermEffect", "ideologyEffect",
"incExpenditures", "nincExpenditures", "incExpDiff", "dExpDiff", "logIncExp", "PVIeffect", "dPct2", "rPct2", "dWin", "logNincExp", "incPct2", "sabatoScore",
"polls", "dSwing", "prevElectionDem", "Prev2ElectionDem", "Prev2ElectionDemDiff", "OpenInc", "midPres", "prevElectionDemDiff", "prevElectionDemDiffSwing",
"logDemExp", "logRepExp", "logDemContDiff", "ideologyEffectDem", "crossPressure")
explore$dWin[explore$year == "2018"] <- "NA"
explore$incWin[explore$year == "2018"] <- "NA"
explore$thirdParty[explore$year == "2018"] <- "NA"
write.csv(explore, "midterms/outputData/explore.csv", row.names = FALSE)
#########################################################################################################################################################################################################
#########################################################################################################################################################################################################
#########################################################################################################################################################################################################
#########################################################################################################################################################################################################
# Random forest
library(randomForest)
rfData <- subset(modelData, select = -c(Dreg, Rreg, Oreg, RegDiff, IncReg, NIncReg, PVI..0.to.100., PresApprov, PresDisapp, PresApprovDiff, ECI, thirdPartyEffect,
total_votes, D, O, R, dPct, rPct, oPct, IncPct, ID2, Pres_Incumbent_SameParty, PrevElectionR., PrevElectionD., PrevElectionIncumbParty.,
PrevElection2R., PrevElection2D., PrevElection2IncumbParty., PrevPresImcumb., PrevPresSameAsInc., YearsIncumbPartyControl, Sabato,
IncWin, IncCont, NincCont, IncContDiff, logIncCont, PVIeffect, logNincCont, IncPct2, SabatoScore))
rfTrain <- na.omit(subset(rfData, year == "2006" | year == "2008" | year == "2010" | year == "2012" | year == "2014" | year == "2016"))
rfTest <- subset(rfData, year == "2018")
rfTest[is.na(rfTest)] <- 0
levels(rfTest$Winner) <- c("R", "D", "0")
rfTest$Winner[is.na(rfTest$Winner)] <- "0"
#Training data (subset of variables)
X.train <- subset(rfTrain, select = -c(year, state, district, ID, Winner, Repub, rPct2, dWin, logDCont, logRCont, ideologyEffect, ideologyEffect2, Prev2ElectionD2, Dcont, Rcont, PVI...100.to.100., PrevPresD., PrevPresR., midtermEffect, Challenge, PresYrsIncumb, PrevPresParty, PrevElectionD2, demoScore))
#colnames(rfData)
# Random forest generation and prediction
set.seed(1)
rf <- randomForest(x = X.train[,-28], y = X.train[,28], mtry = 10, importance = TRUE, ntree = 500)
yhat.rf <- predict(rf, newdata = rfTest)
#par(pty = "s")
#plot(yhat.rf, rfTest$dPct2, main = "Predicted versus actual", xlab = "Predicted Incumbent Vote Share", ylab = "Actual Incumbent Vote Share", xlim = c(.1,1), ylim = c(.1,1))
#abline(0,1)
#sqrt(mean((yhat.rf - rfTest$dPct2)^2))
#mean(abs(yhat.rf - rfTest$dPct2))
#par(pty = "m")
#varImpPlot(rf, n.var = 36)
#table(yhat.rf >= 0.5, rfTest$dPct2 >= 0.5)
#table(yhat.rf >= 0.5)
#hist(yhat.rf - rfTest$dPct2, breaks = 24, main = "Histogram of errors (predicted - actual)", xlab = "Error", xlim = c(-.15,.15))
########################################################################################
#### Simulation -- counting the number of seats won by each party in each iteration ####
########################################################################################
numSim <- 20000
dfCount <- as.data.frame(seq(1,numSim,1))
colnames(dfCount) <- "sim"
dfCount$dWin <- 0
dfCount$rWin <- 0
# Dataset used for shiny app, which includes the predicted vote shares from rf and number of times the Dem won each seat
rfTestCheck <- rfTest
rfTestCheck$dPctPred <- yhat.rf
rfTestCheck$Pred <- 0
#
wins <- numeric(numSim)
counts <- numeric(nrow(rfTest))
# Might need this package to create distributions
library(statmod)
# Iterate!
start_time <- Sys.time()
for(i in 1:numSim){
rfTest2 <- rfTest
natError <- rnorm(1, mean = 0, sd = 3)
rfTest2$dSwing <- rfTest2$dSwing + natError
rfTest2$Polls <- rfTest2$Polls + natError
#districtError <- rnorm(nrow(rfTest2), mean = natError/100, sd=.05)
districtError <- rnorm(nrow(rfTest2), mean = natError/100, sd=(.5 - abs(yhat.rf-.5))/7)
#districtError <- rinvgauss(nrow(rfTest2), mean = (.5 - abs(yhat.rf-.5))/8, shape = .2) # or should we use inverse normal dist? rinvgauss()
#districtError <- rfTest2$demoScore + natError/100
#districtError <- rfTest2$demoScore + rnorm(nrow(rfTest2), mean = natError/100, sd=.05)
yhat.rf <- predict(rf, newdata = rfTest2)
wins[i] <- sum(yhat.rf + districtError >= 0.5)
counts <- counts + (yhat.rf + districtError >= 0.5)
}
end_time <- Sys.time()
# Count the number of times the Democrats took control of the House, and how many times the Dem candidate won each district
dfCount$dWin <- wins
rfTestCheck$Pred <- counts
# Add the data we removed earlier for races that are unchallenged
rfTestAdd <- subset(rfTestAdd, select = -c(Dreg, Rreg, Oreg, RegDiff, IncReg, NIncReg, PVI..0.to.100., PresApprov, PresDisapp, PresApprovDiff, ECI, thirdPartyEffect,
total_votes, D, O, R, dPct, rPct, oPct, IncPct, ID2, Pres_Incumbent_SameParty, PrevElectionR., PrevElectionD., PrevElectionIncumbParty.,
PrevElection2R., PrevElection2D., PrevElection2IncumbParty., PrevPresImcumb., PrevPresSameAsInc., YearsIncumbPartyControl, Sabato,
IncWin, IncCont, NincCont, IncContDiff, logIncCont, PVIeffect, logNincCont, IncPct2, SabatoScore))
rfTestAdd$Pred <- numSim
rfTestAdd$Pred[rfTestAdd$SabatoNum > 0] <- 0
rfTestAdd$Pred[rfTestAdd$SabatoNum < 0] <- numSim
rfTestAdd$dPctPred <- 1
rfTestAdd$dPctPred[rfTestAdd$SabatoNum > 0] <- 0
rfTestCheck <- rbind(rfTestCheck, rfTestAdd)
# How many seats were unchallenged? We need this number for the shiny app
demUnchallenged <- nrow(subset(electionsRaw, year == "2018" & Challenge == 0 & INC == "D"))
dfCount$demUnchallenged <- demUnchallenged
#hist(dfCount$dWin + demUnchallenged, breaks = seq(0,435,1), xlim = c(150,300), main = "")
#abline(v = 218, lty = "dashed")
#abline(v = median(dfCount$dWin) + demUnchallenged)
#table(dfCount$dWin + demUnchallenged >= 218)
# What are the odds that the Dems take control of the House?
dProb <- table(dfCount$dWin + demUnchallenged >= 218)[2]/numSim
#ggplot(dfCount, aes(dWin + demUnchallenged)) + geom_histogram(binwidth = 1, aes(fill = dWin + demUnchallenged >= 218))
#ggplot(dfCount, aes(dWin + demUnchallenged - 218)) + geom_histogram(binwidth = 5, aes(fill = dWin + demUnchallenged - 218 > 0))
#ggplot(rfTestCheck, aes(round(Pred/numSim, 1))) + geom_dotplot(dotsize = .5)
# Write out the data that tells us the Dems chances AND the individual district data (once to use for the app, and once for archiving in case we need it later)
write.csv(dfCount, "midterms/outputData/dfCount.csv", row.names = FALSE)
write.csv(rfTestCheck, "midterms/outputData/rfTestCheck.csv", row.names = FALSE)
write.csv(rfTestCheck, paste0("midterms/outputData/Archive/rfTestCheck", Sys.Date(), ".csv"), row.names = FALSE)
# Write out the data that shows the Dems chances to take control for every day of the election season
#dWinDf <- data.frame(Date = seq(as.Date('2018-06-14'),as.Date('2018-11-06'),by = 1), dProb = NA)
#write.csv(dWinDf, "dWin.csv", row.names = FALSE)
dWin <- read.csv("midterms/outputData/dWin.csv")
dWin$Date <- as.Date(dWin$Date, format = "%Y-%m-%d")
dWin$dProb[dWin$Date == Sys.Date()] <- dProb
write.csv(dWin, "midterms/outputData/dWin.csv", row.names = FALSE)
#rf2 <- randomForest(as.factor(dWin) ~ . -year -state -district -ID -Winner -Repub -rPct2 -dPct2 -incSwing -logDCont -logRCont -SabatoNum -ideologyEffect -Dcont -Rcont -PrevPresD. -PrevPresR. -midtermEffect, data = rfTrain, mtry = 10, importance = TRUE, ntree = 500)
#yhat.rf2 <- predict(rf2, newdata = rfTest, type = "prob")
#rf2Inspect <- cbind(rfTest, dProb = yhat.rf2[,2])
#plot(rf2Inspect$dProb, rfTestCheck$Pred/10000)
#abline(0,1)
# Refresh the shiny app!
#quit(save = "no")
rsconnect::setAccountInfo(name='pquinn1991', token='74383A64C5E471D7D7F661261D4E08DE', secret='z9OMYbFWp6HYA3mYOy6LeqQM52RdBC/zEVV+/NzW')
library(rsconnect)
setwd("midterms")
deployApp(account = "pquinn1991", launch.browser = FALSE, appName = "midterms")
Y
|
# This is the user-interface definition of a Shiny web application.
# You can find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com
#
library(shiny)
library(data.table)
shinyUI(
navbarPage("Car fuel consumptions and emissions 2000-2013",
tabPanel("Plot",
sidebarPanel(sliderInput("range", "Engine:", min = 599, max = 8285, value = c(599,3500))
, radioButtons("trans_type", "Transmission Type:", c("Manual"="Manual","Automatic"="Automatic","Both"="Both"), selected = "Both", inline = FALSE, width = NULL)
, checkboxGroupInput("euro_std", "Euro Standard:", c("2"=2,"3"=3,"4"=4,"5"=5,"6"=6), selected = c("3","4","5","6"), inline = FALSE, width = NULL)
),
mainPanel(
tabsetPanel(
tabPanel('Explore Data'
, h4('Emission/Consumptions by year of construction', align = "center"), plotOutput("Emissionbyyear")
, h4('Emission/Consumptions by euro standard', align = "center"), plotOutput("Emissionbyfuel")
),
tabPanel('Emission Density'
, h4('Emission density by fuel type', align = "center"), plotOutput("EmissionDensitybyFuel")
, h4('Emission density by euro standard', align = "center"), plotOutput("EmissionDensitybyEuro")
)
)
)
),
tabPanel("About",mainPanel(includeMarkdown("README.md")))
)
)
| /ui.R | no_license | maolong/DDP_Project | R | false | false | 1,489 | r |
# This is the user-interface definition of a Shiny web application.
# You can find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com
#
library(shiny)
library(data.table)
shinyUI(
navbarPage("Car fuel consumptions and emissions 2000-2013",
tabPanel("Plot",
sidebarPanel(sliderInput("range", "Engine:", min = 599, max = 8285, value = c(599,3500))
, radioButtons("trans_type", "Transmission Type:", c("Manual"="Manual","Automatic"="Automatic","Both"="Both"), selected = "Both", inline = FALSE, width = NULL)
, checkboxGroupInput("euro_std", "Euro Standard:", c("2"=2,"3"=3,"4"=4,"5"=5,"6"=6), selected = c("3","4","5","6"), inline = FALSE, width = NULL)
),
mainPanel(
tabsetPanel(
tabPanel('Explore Data'
, h4('Emission/Consumptions by year of construction', align = "center"), plotOutput("Emissionbyyear")
, h4('Emission/Consumptions by euro standard', align = "center"), plotOutput("Emissionbyfuel")
),
tabPanel('Emission Density'
, h4('Emission density by fuel type', align = "center"), plotOutput("EmissionDensitybyFuel")
, h4('Emission density by euro standard', align = "center"), plotOutput("EmissionDensitybyEuro")
)
)
)
),
tabPanel("About",mainPanel(includeMarkdown("README.md")))
)
)
|
#' Treatment of outliers
#'
#' Takes the COIN object and Winsorises indicators where necessary or specified, or reverts to log transform or similar. This is done
#' one indicator at a time.
#'
#' Outliers are identified according to skewness and kurtosis thresholds. The algorithm attempts to reduce the absolute skew and
#' kurtosis by successively Winsorising points up to a specified limit. If this limit is reached, it applies a nonlinear transformation.
#'
#' The process is detailed in the [COINr online documentation](https://bluefoxr.github.io/COINrDoc/data-treatment.html#data-treatment-in-coinr).
#'
#' @param COIN The COIN object
#' @param dset The data set to treat
#' @param winmax The maximum number of points to Winsorise for each indicator. If `NA`, will keep Winsorising until skewness and kurtosis thresholds
#' achieved (but it is likely this will cause errors).
#' @param winchange Logical: if `TRUE` (default), Winsorisation can change direction from one iteration to the next. Otherwise if `FALSE`, no change.
#' @param deflog The type of transformation to apply if Winsorisation fails. If `"log"`, use simple `log(x)` as log transform
#' (note: indicators containing negative values will be skipped). If `"CTlog"`, will do `log(x-min(x) + a)`, where `a <- 0.01*(max(x)-min(x))`, similar to that used in the COIN Tool.
#' If `"CTlog_orig"`, this is exactly the COIN Tool log transformation, which is `log(x-min(x) + 1)`.
#' If `"GIIlog"`, use GII log transformation.
#' If "`boxcox"`, performs a Box-Cox transformation. In this latter case, you should also specify `boxlam`. Finally, if `"none"`, will
#' return the indicator untreated.
#' @param boxlam The lambda parameter of the Box-Cox transform.
#' @param t_skew Absolute skew threshold (default 2)
#' @param t_kurt Kurtosis threshold (default 3.5)
#' @param individual A data frame specifying individual treatment for each indicator, with each row corresponding to one indicator to be treated. Columns are:
#' * `IndCode` The code of the indicator to be treated.
#' * `Treat` The type of treatment to apply, one of `"win"` (Winsorise), `"log"` (log), `"GIIlog"` (GII log), `"CTlog"` (COIN Tool log),
#' `"boxcox"` (Box Cox), or `"None"` (no treatment).
#' * `Winmax` The maximum number of points to Winsorise. Ignored if the corresponding entry in `"Treat"` is not `"win"`.
#' * `Thresh` Either `NA`, which means that Winsorisation will continue up to `winmax` with no checks on skew and kurtosis, or `"thresh"`,
#' which uses the skew and kurtosis thresholds specified in `t_skew` and `t_kurt`.
#' * `boxlam` Lambda parameter for the Box Cox transformation
#' @param indiv_only Logical: if `TRUE`, only the indicators specified in `"individual"` are treated.
#' If `FALSE`, all indicators are treated: any outside of `individual` will get default treatment.
#' @param bypass_all Logical: if `TRUE`, bypasses all data treatment and returns the original data. This
#' is useful for sensitivity analysis and comparing the effects of turning data treatment on and off.
#'
#' @importFrom dplyr pull
#' @importFrom e1071 skewness kurtosis
#' @importFrom tibble add_column
#'
#' @examples
#' # assemble ASEM COIN
#' ASEM <- assemble(IndData = ASEMIndData, IndMeta = ASEMIndMeta, AggMeta = ASEMAggMeta)
#' # treat raw data set, Winsorise up to a maximum of five points
#' ASEM <- treat(ASEM, dset = "Raw", winmax = 5)
#' # inspect what was done
#' ASEM$Analysis$Treated$TreatSummary
#' # check whether skew and kurtosis now within limits
#' ASEM$Analysis$Treated$StatTable$SK.outlier.flag
#'
#' @seealso
#' * [indDash()] Interactive app for checking indicator distributions. Useful for comparing before/after data treatment.
#'
#' @return If the input is a COIN, outputs an updated COIN with a new treated data set at `.$Data$Treated`, as well as
#' information about the data treatment in `.$Analysis$Treated`. Else if the input is a data frame, outputs both the treated
#' data set and the information about data treatment to a list.
#'
#' @export
treat <- function(COIN, dset = NULL, winmax = NULL, winchange = NULL, deflog = NULL, boxlam = NULL,
t_skew = NULL, t_kurt = NULL, individual = NULL, indiv_only = NULL, bypass_all = NULL){
# Check for dset. If not specified, exit.
if (is.null(dset) & !("data.frame" %in% class(COIN))){
stop("dset is NULL. Please specify which data set to operate on.")
}
##----- SET DEFAULTS -------##
# Done here because otherwise if we use regen, this input could be input as NULL
if(is.null(winchange)){
winchange <- TRUE
}
if(is.null(deflog)){
deflog <- "CTlog"
}
if(is.null(t_skew)){
t_skew <- 2
}
if(is.null(t_kurt)){
t_kurt <- 3.5
}
if(is.null(indiv_only)){
indiv_only <- TRUE
}
if(is.null(bypass_all)){
bypass_all <- FALSE
}
# First check object type and extract
out <- getIn(COIN, dset = dset)
if (out$otype == "COINobj"){
# write function arguments to Method
COIN$Method$treat$dset <- dset
COIN$Method$treat$winmax <- winmax
COIN$Method$treat$winchange <- winchange
COIN$Method$treat$deflog <- deflog
COIN$Method$treat$boxlam <- boxlam
COIN$Method$treat$t_skew <- t_skew
COIN$Method$treat$t_kurt <- t_kurt
COIN$Method$treat$individual <- individual
COIN$Method$treat$indiv_only <- indiv_only
COIN$Method$treat$bypass_all <- bypass_all
}
# if winmax not specified, default to 10% of units, rounded up
if(is.null(winmax)){
winmax <- ceiling((length(out$UnitCodes)*0.1))
}
# get basic data sets
ind_data <- out$ind_data # all indicator data
ind_data_only <- out$ind_data_only
IndCodes <- out$IndCodes
###---- Bypass everything if requested -----##
if(bypass_all){
if (out$otype == "COINobj"){
# write results
COIN$Data$Treated <- ind_data
COIN$Analysis$Treated$TreatSummary <- data.frame(Treatment = "Treatment bypassed")
COIN$Analysis$Treated$TreatFlags <- NULL
return(COIN)
} else {
# if input was a data frame, output a list
fout <- list(
DataTreated = ind_data,
TreatmentSummary = data.frame(Treatment = "Treatment bypassed")
)
return(fout)
}
}
ind_data_treated <- ind_data # make a copy, for treated data
treat_flag <- matrix("No", nrow = nrow(ind_data_only), ncol = ncol(ind_data_only)) # empty matrix for populating
Treatment <- matrix(NA, nrow = ncol(ind_data_only), 1) # this will summarise the data treatment for each indicator
TreatSpec <- matrix(NA, nrow = ncol(ind_data_only), 1) # record of what treatment was specified
###----------- DEFAULT INDICATOR TREATMENT -------------------------
if (is.null(individual)){ # means that all indicators follow the same default treatment process
# looping over indicators (columns)
for (ii in 1:ncol(ind_data_only)){
icol <- dplyr::pull(ind_data_only,ii) # get relevant column
icode <- colnames(ind_data_only)[ii]
w <- coin_win(icol, winmax, winchange, t_skew, t_kurt, icode)
# test skew and kurtosis again
sk <- e1071::skewness(w$icol, na.rm = T, type = 2)
kt <- e1071::kurtosis(w$icol, na.rm = T, type = 2)
# Here, loop may have exited because treatment succeeded, or reached winmax. Let's check
if ( (w$winz >= winmax) & ((abs(sk)>t_skew) & (kt>t_kurt)) ){ # didn't work
# do log-type transformation
params <- list(winmax = winmax, IndCodes = IndCodes, ii = ii, boxlam = boxlam,
forced = FALSE)
logout <- loggish(icol, deflog, params)
# record outputs
icol <- logout$x # the transformed values
treat_flag[,ii] <- logout$Flag
Treatment[ii] <- logout$Treatment
TreatSpec[ii] <- logout$TreatSpec
} else { # Winsorization DID work
treat_flag[w$imax,ii] <- "WHigh" # Flag Winsorisation (if NULL, will not assign anything)
treat_flag[w$imin,ii] <- "WLow"
icol <- w$icol
if (w$winz>0){
Treatment[ii] <- paste0("Winsorised ", w$winz, " points")}
else {Treatment[ii] <- "None"}
TreatSpec[ii] <- paste0("Default, winmax = ", winmax)
}
ind_data_treated[IndCodes[ii]]<-icol # subst treated col into treated data set
}
###------ INDIVIDUAL INDICATOR TREATMENT -----
} else {
# looping over indicators (columns)
for (ii in 1:ncol(ind_data_only)){
icol <- dplyr::pull(ind_data_only,ii) # get relevant column
ind_name <- IndCodes[ii] # get indicator name
# check if this indicator is specified in the "individual" table
# if it is, we treat it as specified in the table
if (ind_name %in% individual$IndCode) {
# INDIVIDUAL TREATMENT
# Now check which kind of treatment to apply using table
if( individual$Treat[individual$IndCode==ind_name] == "win"){
# this indicator should be winsorised
# get the winmax for this indicator from the table
winmaxii <- individual$Winmax[individual$IndCode==ind_name]
# get skew and kurtosis threshold to use
if ( is.na(individual$Thresh[individual$IndCode==ind_name]) ) {
# NA implies to keep Winsorising up to winmax. To do this, set thresholds to zero (cannot be reached)
t_skewi <- 0
t_kurti <- 0
} else if ( individual$Thresh[individual$IndCode==ind_name] == "thresh"){
# use the global threshold
t_skewi <- t_skew
t_kurti <- t_kurt
} else {
warning("Threshold type (in individual$Thresh) not recognised, using global values.")
# use the global threshold
t_skewi <- t_skew
t_kurti <- t_kurt
}
w <- coin_win(icol, winmaxii, winchange, t_skewi, t_kurti, ind_name)
# loop exited, we don't know if we succeeded or not and don't go to log
treat_flag[w$imax,ii] <- "WHigh" # Flag Winsorisation (if NULL, will not assign anything)
treat_flag[w$imin,ii] <- "WLow"
if ( is.na(individual$Thresh[individual$IndCode==ind_name]) ){
TreatSpec[ii] <- paste0("Forced Win (no thresh), winmax = ", winmaxii)
} else {
TreatSpec[ii] <- paste0("Forced Win, winmax = ", winmaxii)
}
TreatSpec[ii] <- paste0("Forced Win, winmax = ", winmaxii)
if (w$winz>0){
Treatment[ii] <- paste0("Winsorised ", w$winz, " points")}
else {Treatment[ii] <- "None"}
ind_data_treated[IndCodes[ii]]<-w$icol # subst treated col into treated data set
} else {
icol <- dplyr::pull(ind_data_only,ii) # get fresh version of column
# do log-type transformation
params <- list(winmax = individual$Winmax[individual$IndCode==ind_name], IndCodes = IndCodes, ii = ii,
boxlam = individual$Boxlam[individual$IndCode==ind_name], forced = TRUE)
logout <- loggish(icol, individual$Treat[individual$IndCode==ind_name], params)
# record outputs
ind_data_treated[IndCodes[ii]] <- logout$x # the transformed values
treat_flag[,ii] <- logout$Flag
Treatment[ii] <- logout$Treatment
TreatSpec[ii] <- logout$TreatSpec
}
} else if (indiv_only == FALSE){
# here means that indicator is NOT specified in the individual table, and
# the indiv_only flag is set so that all other indicators should be treated by default process
# So, applying default process to this one.
w <- coin_win(icol, winmax, winchange, t_skew, t_kurt, ind_name)
sk <- e1071::skewness(w$icol, na.rm = T, type = 2)
kt <- e1071::kurtosis(w$icol, na.rm = T, type = 2)
# Here, loop may have exited because treatment succeeded, or reached winmax. Let's check
if ( (w$winz >= winmax) & ((abs(sk)>t_skew) & (kt>t_kurt)) ){ # didn't work
icol <- dplyr::pull(ind_data_only,ii) # get fresh version of column
# do log-type transformation
params <- list(winmax = winmax, IndCodes = IndCodes, ii = ii, boxlam = boxlam,
forced = FALSE)
logout <- loggish(icol, deflog, params)
# record outputs
icol <- logout$x # the transformed values
treat_flag[,ii] <- logout$Flag
Treatment[ii] <- logout$Treatment
TreatSpec[ii] <- logout$TreatSpec
} else { # Winsorization DID work
treat_flag[w$imax,ii] <- "WHigh" # Flag Winsorisation (if NULL, will not assign anything)
treat_flag[w$imin,ii] <- "WLow"
icol <- w$icol
if (w$winz>0){
Treatment[ii] <- paste0("Winsorised ", w$winz, " points")}
else {Treatment[ii] <- "None"}
TreatSpec[ii] <- paste0("Default, winmax = ", winmax)
}
ind_data_treated[IndCodes[ii]]<-icol # subst treated col into treated data set
} # end of if indicator in individual table
} # end indicator loop
} # end IF indicator individual treatment
# tidy up a bit
Treatment[is.na(Treatment)] <- "None"
TreatSpec[is.na(TreatSpec)] <- "None"
ntreated <- data.frame(
IndCode = IndCodes,
Low = map_dbl(as.data.frame(treat_flag), ~sum(.x=="WLow")),
High = map_dbl(as.data.frame(treat_flag), ~sum(.x=="WHigh")),
TreatSpec = TreatSpec,
Treatment = Treatment
)
colnames(treat_flag) <- colnames(ind_data_only)
treat_flag <- as.data.frame(treat_flag)
treat_flag <- treat_flag %>%
tibble::add_column(UnitCode = out$UnitCodes, .before = 1)
###---- Write results and method -----##
if (out$otype == "COINobj"){
# write results
COIN$Data$Treated <- ind_data_treated
COIN$Analysis$Treated$TreatSummary <- ntreated
COIN$Analysis$Treated$TreatFlags <- treat_flag
return(COIN)
} else {
# if input was a data frame, output a list
fout <- list(
DataTreated <- ind_data_treated,
TreatmentSummary <- ntreated,
TreatmentFlags <- treat_flag
)
return(fout)
}
}
#' Winsorisation helper function
#'
#' To be used inside [treat()] to avoid repetitions. Winsorises a numerical vector of data.
#'
#' Outliers are identified according to skewness and kurtosis thresholds. The algorithm attempts to reduce the absolute skew and
#' kurtosis by successively Winsorising points up to a specified limit.
#'
#' The process is detailed in the [COINr online documentation](https://bluefoxr.github.io/COINrDoc/data-treatment.html#data-treatment-in-coinr).
#'
#' @param icol The vector of data to Winsorise
#' @param winmax The maximum number of points to Winsorise for each indicator. If `NA`, will keep Winsorising until skewness and kurtosis
#' thresholds achieved (but it is likely this will cause errors).
#' @param winchange Logical: if `TRUE`, Winsorisation can change direction from one iteration to the next. Otherwise if `FALSE` (default), no change.
#' @param t_skew Absolute skew threshold (default 2).
#' @param t_kurt Kurtosis threshold (default 3.5).
#' @param icode The indicator name - used for error messages in [treat()].
#'
#' @examples
#' # get a column of data with outliers
#' x <- ASEMIndData$Tariff
#' # Winsorise up to five points
#' winlist <- coin_win(x, winmax = 5)
#' # check the differences
#' data.frame(
#' Orig = x,
#' Treated = winlist$icol,
#' Changes = ifelse(x == winlist$icol, "Same", "Treated"))
#'
#' @seealso
#' * [treat()] Outlier treatment
#'
#' @return A list containing:
#' * `.$icol` the vector of treated data
#' * `.$imax` the indices of elements of the vector that were Winsorised as high values
#' * `.$imax` the indices of elements of the vector that were Winsorised as low values
#' * `.$winz` the total number of Winsorised points
#'
#' @export
coin_win <- function(icol, winmax, winchange = TRUE, t_skew = 2, t_kurt = 3.5, icode = NULL){
# first, check skew and kurtosis
sk <- e1071::skewness(icol, na.rm = T, type = 2)
kt <- e1071::kurtosis(icol, na.rm = T, type = 2)
# now make a flag to either always do high Winsorisation, or always low, depending on sk
if (winchange==F){ # if F, we should always Winsorise from the same direction
if (sk>0){
windir <- 1 # always high
} else {
windir <- -1 # always low
}
} else { windir <- 0} # can change from high to low (winchange == T)
winz<-0 # set counter to 0
imax<-imin<-NULL # reset to NULL
if (is.na(winmax)){winmax <- 1e6}
while ( ((abs(sk)>t_skew) & (kt>t_kurt)) & (winz < winmax) ) { # keep going until sk and kt below thresholds OR reached winsorisation limit
# high winz if high skew AND windir =1, OR windir = 1 (always use high)
if ((sk>=0 & windir==0) | (windir == 1)){ # skew is positive, implies high outliers
imax <- which(icol==max(icol, na.rm = T)) # position(s) of maximum value(s)
icol[imax] <- max(icol[-imax], na.rm = T) # replace imax with max value of indicator if imax value(s) excluded
} else { # skew is negative, implies low outliers
imin <- which(icol==min(icol, na.rm = T)) # ditto, but with min
icol[imin] <- min(icol[-imin], na.rm = T)
}
winz<-winz+1 # add the winsorisation counter
# test skew and kurtosis again
if(length(unique(icol[!is.na(icol)])) < 2){
stop(paste0("Can't Winsorise further because it would imply less than two unique values in the indicator.
This is probably not a good idea. Consider individual settings for this indicator, such as
a lower winmax, using a transformation by default, or excluding from treatment.
**INDICATOR = ",icode,"**"))
} else {
sk <- e1071::skewness(icol, na.rm = T, type = 2)
kt <- e1071::kurtosis(icol, na.rm = T, type = 2)
}
}
# write outputs
w <- list(
icol = icol,
imax = imax,
imin = imin,
winz = winz
)
return(w)
}
#' Box Cox transformation
#'
#' Simple Box Cox, with no optimisation of lambda.
#' See [COINr online documentation](https://bluefoxr.github.io/COINrDoc/data-treatment.html#transformation) for more details.
#'
#' @param x A vector or column of data to transform
#' @param lambda The lambda parameter of the Box Cox transform
#' @param makepos If `TRUE` (default) makes all values positive by subtracting the minimum and adding 1.
#'
#' @examples
#' # get a column of data with outliers
#' x <- ASEMIndData$Tariff
#' # Apply Box Cox
#' xBox <- BoxCox(x, lambda = 2)
#' # plot one against the other
#' plot(x, xBox)
#'
#' @seealso
#' * [treat()] Outlier treatment
#'
#' @return A vector of length `length(x)` with transformed values.
#'
#' @export
BoxCox <- function(x, lambda, makepos = TRUE){
if(makepos){
# make positive using COIN Tool style shift
x <- x - min(x,na.rm = T) + 1
}
# Box Cox
if (lambda==0){
x <- log(x)
} else {
x <- (x^lambda - 1)/lambda
}
return(x)
}
#' Log-type transformation of a vector
#'
#' This applies various simple transformations, to be used by the [treat()] function.
#' This function is probably not very useful on its own because it requires `params`,
#' a list of parameters which are used to output the type and status of treatment applied.
#'
#' @param x A vector or column of data to transform
#' @param ltype The type of log transformation - see `deflog` in [treat()].
#' @param params Some extra parameters to pass. These parameters mostly concern internal messages for [treat()] and this can be
#' left unspecified unless `ltype == "boxcox"`, in which case there should be a parameter `params$boxlam` specified
#' (see [BoxCox()]). However, if you wish to use a Box Cox transformation, it is better to use [BoxCox()] directly.
#'
#' @examples
#' # get a column of data with outliers
#' x <- ASEMIndData$Tariff
#' # apply a GII transformation
#' xdash <- loggish(x, ltype = "GIIlog")
#' # plot one against the other
#' plot(x, xdash$x)
#'
#' @seealso
#' * [treat()] Outlier treatment
#'
#' @return A list with
#' * `.$x` is the transformed vector of data
#' * `.$Flag` is a flag of the type of treatment specified (used inside [treat()])
#' * `.$Treatment` the treatment applied (used inside [treat()])
#' * `.$TreatSpec` the treatment specified (used inside [treat()])
#'
#' @export
loggish <- function(x, ltype, params = NULL){
# some default parameters if this function is used on its own
if(is.null(params)){
params = list(IndCodes = "Indicator",
ii = 1,
forced = FALSE,
winmax = "unspecified",
boxlam = 1)
} else if (!is.null(params$boxlam)){
params$IndCodes = "Indicator"
params$ii = 1
params$forced = FALSE
params$winmax = "unspecified"
}
# prep a list
l <- list(x = NA, Flag = NA, Treatment = NA, TreatSpec = NA)
if ( (sum(x<=0, na.rm=T)>0) & (ltype == "log") ){ # negative values. No can normal log.
l$Flag <- "Err"
# x will be passed through with no treatment
l$x <- x
warning(paste0(params$IndCodes[params$ii],": log transform attempted but failed because negative or zero values. Please check."))
if(params$forced){
l$TreatSpec <- paste0("Forced log")
l$Treatment <- "None: log error"
} else {
l$TreatSpec <- paste0("Default, winmax = ", params$winmax)
l$Treatment <- "None: exceeded winmax but log error"
}
} else if ( (sum(x<=0, na.rm=T)==0) & (ltype == "log") ) { # OK to normal log
l$x <- log(x)
l$Flag <- "Log"
if(params$forced){
l$TreatSpec <- paste0("Forced log")
l$Treatment <- "Log"
} else {
l$TreatSpec <- paste0("Default, winmax = ", params$winmax)
l$Treatment <- "Log (exceeded winmax)"
}
} else if (ltype == "GIIlog"){ # GII log
# get GII log
l$x <- log( (max(x, na.rm = T)-1)*(x-min(x, na.rm = T))/(max(x, na.rm = T)-min(x, na.rm = T)) + 1 )
l$Flag <- "GIILog"
if(params$forced){
l$TreatSpec <- paste0("Forced GIIlog")
l$Treatment <- "GIILog"
} else {
l$TreatSpec <- paste0("Default, winmax = ", params$winmax)
l$Treatment <- "GIILog (exceeded winmax)"
}
} else if (ltype == "CTlog"){
# COIN TOOl style log: subtract min and add fraction of range
l$x <- log(x- min(x,na.rm = T) + 0.01*(max(x, na.rm = T)-min(x, na.rm = T)))
l$Flag <- "CTLog"
if(params$forced){
l$TreatSpec <- paste0("Forced CTlog")
l$Treatment <- "CTLog"
} else {
l$TreatSpec <- paste0("Default, winmax = ", params$winmax)
l$Treatment <- "CTLog (exceeded winmax)"
}
} else if (ltype == "CTlog_orig"){
# COIN TOOl original log: subtract min and add 1
l$x <- log(x- min(x,na.rm = T) + 1)
l$Flag <- "CTlog_orig"
if(params$forced){
l$TreatSpec <- paste0("Forced CTlog_orig")
l$Treatment <- "CTlog_orig"
} else {
l$TreatSpec <- paste0("Default, winmax = ", params$winmax)
l$Treatment <- "CTlog_orig (exceeded winmax)"
}
} else if (ltype == "boxcox"){
# Box Cox transform
l$x <- BoxCox(x,params$boxlam)
l$Flag <- "BoxCox"
if(params$forced){
l$TreatSpec <- paste0("Forced Box-Cox")
l$Treatment <- paste0("Box Cox with lambda = ",params$boxlam)
} else {
l$TreatSpec <- paste0("Default, winmax = ", params$winmax)
l$Treatment <- paste0("Box Cox with lambda = ",params$boxlam," (exceeded winmax)")
}
} else if (ltype == "None"){
# No transform
l$x <- x
# this indicator should be excluded from any treatment
l$Flag <- "ForcedNo"
l$Treatment <- "ForcedNone"
l$TreatSpec <- "None"
}
return(l)
}
| /R/coin_treat.R | permissive | Lucas-OlivCouto/COINr | R | false | false | 23,596 | r | #' Treatment of outliers
#'
#' Takes the COIN object and Winsorises indicators where necessary or specified, or reverts to log transform or similar. This is done
#' one indicator at a time.
#'
#' Outliers are identified according to skewness and kurtosis thresholds. The algorithm attempts to reduce the absolute skew and
#' kurtosis by successively Winsorising points up to a specified limit. If this limit is reached, it applies a nonlinear transformation.
#'
#' The process is detailed in the [COINr online documentation](https://bluefoxr.github.io/COINrDoc/data-treatment.html#data-treatment-in-coinr).
#'
#' @param COIN The COIN object
#' @param dset The data set to treat
#' @param winmax The maximum number of points to Winsorise for each indicator. If `NA`, will keep Winsorising until skewness and kurtosis thresholds
#' achieved (but it is likely this will cause errors).
#' @param winchange Logical: if `TRUE` (default), Winsorisation can change direction from one iteration to the next. Otherwise if `FALSE`, no change.
#' @param deflog The type of transformation to apply if Winsorisation fails. If `"log"`, use simple `log(x)` as log transform
#' (note: indicators containing negative values will be skipped). If `"CTlog"`, will do `log(x-min(x) + a)`, where `a <- 0.01*(max(x)-min(x))`, similar to that used in the COIN Tool.
#' If `"CTlog_orig"`, this is exactly the COIN Tool log transformation, which is `log(x-min(x) + 1)`.
#' If `"GIIlog"`, use GII log transformation.
#' If "`boxcox"`, performs a Box-Cox transformation. In this latter case, you should also specify `boxlam`. Finally, if `"none"`, will
#' return the indicator untreated.
#' @param boxlam The lambda parameter of the Box-Cox transform.
#' @param t_skew Absolute skew threshold (default 2)
#' @param t_kurt Kurtosis threshold (default 3.5)
#' @param individual A data frame specifying individual treatment for each indicator, with each row corresponding to one indicator to be treated. Columns are:
#' * `IndCode` The code of the indicator to be treated.
#' * `Treat` The type of treatment to apply, one of `"win"` (Winsorise), `"log"` (log), `"GIIlog"` (GII log), `"CTlog"` (COIN Tool log),
#' `"boxcox"` (Box Cox), or `"None"` (no treatment).
#' * `Winmax` The maximum number of points to Winsorise. Ignored if the corresponding entry in `"Treat"` is not `"win"`.
#' * `Thresh` Either `NA`, which means that Winsorisation will continue up to `winmax` with no checks on skew and kurtosis, or `"thresh"`,
#' which uses the skew and kurtosis thresholds specified in `t_skew` and `t_kurt`.
#' * `boxlam` Lambda parameter for the Box Cox transformation
#' @param indiv_only Logical: if `TRUE`, only the indicators specified in `"individual"` are treated.
#' If `FALSE`, all indicators are treated: any outside of `individual` will get default treatment.
#' @param bypass_all Logical: if `TRUE`, bypasses all data treatment and returns the original data. This
#' is useful for sensitivity analysis and comparing the effects of turning data treatment on and off.
#'
#' @importFrom dplyr pull
#' @importFrom e1071 skewness kurtosis
#' @importFrom tibble add_column
#'
#' @examples
#' # assemble ASEM COIN
#' ASEM <- assemble(IndData = ASEMIndData, IndMeta = ASEMIndMeta, AggMeta = ASEMAggMeta)
#' # treat raw data set, Winsorise up to a maximum of five points
#' ASEM <- treat(ASEM, dset = "Raw", winmax = 5)
#' # inspect what was done
#' ASEM$Analysis$Treated$TreatSummary
#' # check whether skew and kurtosis now within limits
#' ASEM$Analysis$Treated$StatTable$SK.outlier.flag
#'
#' @seealso
#' * [indDash()] Interactive app for checking indicator distributions. Useful for comparing before/after data treatment.
#'
#' @return If the input is a COIN, outputs an updated COIN with a new treated data set at `.$Data$Treated`, as well as
#' information about the data treatment in `.$Analysis$Treated`. Else if the input is a data frame, outputs both the treated
#' data set and the information about data treatment to a list.
#'
#' @export
treat <- function(COIN, dset = NULL, winmax = NULL, winchange = NULL, deflog = NULL, boxlam = NULL,
t_skew = NULL, t_kurt = NULL, individual = NULL, indiv_only = NULL, bypass_all = NULL){
# Check for dset. If not specified, exit.
if (is.null(dset) & !("data.frame" %in% class(COIN))){
stop("dset is NULL. Please specify which data set to operate on.")
}
##----- SET DEFAULTS -------##
# Done here because otherwise if we use regen, this input could be input as NULL
if(is.null(winchange)){
winchange <- TRUE
}
if(is.null(deflog)){
deflog <- "CTlog"
}
if(is.null(t_skew)){
t_skew <- 2
}
if(is.null(t_kurt)){
t_kurt <- 3.5
}
if(is.null(indiv_only)){
indiv_only <- TRUE
}
if(is.null(bypass_all)){
bypass_all <- FALSE
}
# First check object type and extract
out <- getIn(COIN, dset = dset)
if (out$otype == "COINobj"){
# write function arguments to Method
COIN$Method$treat$dset <- dset
COIN$Method$treat$winmax <- winmax
COIN$Method$treat$winchange <- winchange
COIN$Method$treat$deflog <- deflog
COIN$Method$treat$boxlam <- boxlam
COIN$Method$treat$t_skew <- t_skew
COIN$Method$treat$t_kurt <- t_kurt
COIN$Method$treat$individual <- individual
COIN$Method$treat$indiv_only <- indiv_only
COIN$Method$treat$bypass_all <- bypass_all
}
# if winmax not specified, default to 10% of units, rounded up
if(is.null(winmax)){
winmax <- ceiling((length(out$UnitCodes)*0.1))
}
# get basic data sets
ind_data <- out$ind_data # all indicator data
ind_data_only <- out$ind_data_only
IndCodes <- out$IndCodes
###---- Bypass everything if requested -----##
if(bypass_all){
if (out$otype == "COINobj"){
# write results
COIN$Data$Treated <- ind_data
COIN$Analysis$Treated$TreatSummary <- data.frame(Treatment = "Treatment bypassed")
COIN$Analysis$Treated$TreatFlags <- NULL
return(COIN)
} else {
# if input was a data frame, output a list
fout <- list(
DataTreated = ind_data,
TreatmentSummary = data.frame(Treatment = "Treatment bypassed")
)
return(fout)
}
}
ind_data_treated <- ind_data # make a copy, for treated data
treat_flag <- matrix("No", nrow = nrow(ind_data_only), ncol = ncol(ind_data_only)) # empty matrix for populating
Treatment <- matrix(NA, nrow = ncol(ind_data_only), 1) # this will summarise the data treatment for each indicator
TreatSpec <- matrix(NA, nrow = ncol(ind_data_only), 1) # record of what treatment was specified
###----------- DEFAULT INDICATOR TREATMENT -------------------------
if (is.null(individual)){ # means that all indicators follow the same default treatment process
# looping over indicators (columns)
for (ii in 1:ncol(ind_data_only)){
icol <- dplyr::pull(ind_data_only,ii) # get relevant column
icode <- colnames(ind_data_only)[ii]
w <- coin_win(icol, winmax, winchange, t_skew, t_kurt, icode)
# test skew and kurtosis again
sk <- e1071::skewness(w$icol, na.rm = T, type = 2)
kt <- e1071::kurtosis(w$icol, na.rm = T, type = 2)
# Here, loop may have exited because treatment succeeded, or reached winmax. Let's check
if ( (w$winz >= winmax) & ((abs(sk)>t_skew) & (kt>t_kurt)) ){ # didn't work
# do log-type transformation
params <- list(winmax = winmax, IndCodes = IndCodes, ii = ii, boxlam = boxlam,
forced = FALSE)
logout <- loggish(icol, deflog, params)
# record outputs
icol <- logout$x # the transformed values
treat_flag[,ii] <- logout$Flag
Treatment[ii] <- logout$Treatment
TreatSpec[ii] <- logout$TreatSpec
} else { # Winsorization DID work
treat_flag[w$imax,ii] <- "WHigh" # Flag Winsorisation (if NULL, will not assign anything)
treat_flag[w$imin,ii] <- "WLow"
icol <- w$icol
if (w$winz>0){
Treatment[ii] <- paste0("Winsorised ", w$winz, " points")}
else {Treatment[ii] <- "None"}
TreatSpec[ii] <- paste0("Default, winmax = ", winmax)
}
ind_data_treated[IndCodes[ii]]<-icol # subst treated col into treated data set
}
###------ INDIVIDUAL INDICATOR TREATMENT -----
} else {
# looping over indicators (columns)
for (ii in 1:ncol(ind_data_only)){
icol <- dplyr::pull(ind_data_only,ii) # get relevant column
ind_name <- IndCodes[ii] # get indicator name
# check if this indicator is specified in the "individual" table
# if it is, we treat it as specified in the table
if (ind_name %in% individual$IndCode) {
# INDIVIDUAL TREATMENT
# Now check which kind of treatment to apply using table
if( individual$Treat[individual$IndCode==ind_name] == "win"){
# this indicator should be winsorised
# get the winmax for this indicator from the table
winmaxii <- individual$Winmax[individual$IndCode==ind_name]
# get skew and kurtosis threshold to use
if ( is.na(individual$Thresh[individual$IndCode==ind_name]) ) {
# NA implies to keep Winsorising up to winmax. To do this, set thresholds to zero (cannot be reached)
t_skewi <- 0
t_kurti <- 0
} else if ( individual$Thresh[individual$IndCode==ind_name] == "thresh"){
# use the global threshold
t_skewi <- t_skew
t_kurti <- t_kurt
} else {
warning("Threshold type (in individual$Thresh) not recognised, using global values.")
# use the global threshold
t_skewi <- t_skew
t_kurti <- t_kurt
}
w <- coin_win(icol, winmaxii, winchange, t_skewi, t_kurti, ind_name)
# loop exited, we don't know if we succeeded or not and don't go to log
treat_flag[w$imax,ii] <- "WHigh" # Flag Winsorisation (if NULL, will not assign anything)
treat_flag[w$imin,ii] <- "WLow"
if ( is.na(individual$Thresh[individual$IndCode==ind_name]) ){
TreatSpec[ii] <- paste0("Forced Win (no thresh), winmax = ", winmaxii)
} else {
TreatSpec[ii] <- paste0("Forced Win, winmax = ", winmaxii)
}
TreatSpec[ii] <- paste0("Forced Win, winmax = ", winmaxii)
if (w$winz>0){
Treatment[ii] <- paste0("Winsorised ", w$winz, " points")}
else {Treatment[ii] <- "None"}
ind_data_treated[IndCodes[ii]]<-w$icol # subst treated col into treated data set
} else {
icol <- dplyr::pull(ind_data_only,ii) # get fresh version of column
# do log-type transformation
params <- list(winmax = individual$Winmax[individual$IndCode==ind_name], IndCodes = IndCodes, ii = ii,
boxlam = individual$Boxlam[individual$IndCode==ind_name], forced = TRUE)
logout <- loggish(icol, individual$Treat[individual$IndCode==ind_name], params)
# record outputs
ind_data_treated[IndCodes[ii]] <- logout$x # the transformed values
treat_flag[,ii] <- logout$Flag
Treatment[ii] <- logout$Treatment
TreatSpec[ii] <- logout$TreatSpec
}
} else if (indiv_only == FALSE){
# here means that indicator is NOT specified in the individual table, and
# the indiv_only flag is set so that all other indicators should be treated by default process
# So, applying default process to this one.
w <- coin_win(icol, winmax, winchange, t_skew, t_kurt, ind_name)
sk <- e1071::skewness(w$icol, na.rm = T, type = 2)
kt <- e1071::kurtosis(w$icol, na.rm = T, type = 2)
# Here, loop may have exited because treatment succeeded, or reached winmax. Let's check
if ( (w$winz >= winmax) & ((abs(sk)>t_skew) & (kt>t_kurt)) ){ # didn't work
icol <- dplyr::pull(ind_data_only,ii) # get fresh version of column
# do log-type transformation
params <- list(winmax = winmax, IndCodes = IndCodes, ii = ii, boxlam = boxlam,
forced = FALSE)
logout <- loggish(icol, deflog, params)
# record outputs
icol <- logout$x # the transformed values
treat_flag[,ii] <- logout$Flag
Treatment[ii] <- logout$Treatment
TreatSpec[ii] <- logout$TreatSpec
} else { # Winsorization DID work
treat_flag[w$imax,ii] <- "WHigh" # Flag Winsorisation (if NULL, will not assign anything)
treat_flag[w$imin,ii] <- "WLow"
icol <- w$icol
if (w$winz>0){
Treatment[ii] <- paste0("Winsorised ", w$winz, " points")}
else {Treatment[ii] <- "None"}
TreatSpec[ii] <- paste0("Default, winmax = ", winmax)
}
ind_data_treated[IndCodes[ii]]<-icol # subst treated col into treated data set
} # end of if indicator in individual table
} # end indicator loop
} # end IF indicator individual treatment
# tidy up a bit
Treatment[is.na(Treatment)] <- "None"
TreatSpec[is.na(TreatSpec)] <- "None"
ntreated <- data.frame(
IndCode = IndCodes,
Low = map_dbl(as.data.frame(treat_flag), ~sum(.x=="WLow")),
High = map_dbl(as.data.frame(treat_flag), ~sum(.x=="WHigh")),
TreatSpec = TreatSpec,
Treatment = Treatment
)
colnames(treat_flag) <- colnames(ind_data_only)
treat_flag <- as.data.frame(treat_flag)
treat_flag <- treat_flag %>%
tibble::add_column(UnitCode = out$UnitCodes, .before = 1)
###---- Write results and method -----##
if (out$otype == "COINobj"){
# write results
COIN$Data$Treated <- ind_data_treated
COIN$Analysis$Treated$TreatSummary <- ntreated
COIN$Analysis$Treated$TreatFlags <- treat_flag
return(COIN)
} else {
# if input was a data frame, output a list
fout <- list(
DataTreated <- ind_data_treated,
TreatmentSummary <- ntreated,
TreatmentFlags <- treat_flag
)
return(fout)
}
}
#' Winsorisation helper function
#'
#' To be used inside [treat()] to avoid repetitions. Winsorises a numerical vector of data.
#'
#' Outliers are identified according to skewness and kurtosis thresholds. The algorithm attempts to reduce the absolute skew and
#' kurtosis by successively Winsorising points up to a specified limit.
#'
#' The process is detailed in the [COINr online documentation](https://bluefoxr.github.io/COINrDoc/data-treatment.html#data-treatment-in-coinr).
#'
#' @param icol The vector of data to Winsorise
#' @param winmax The maximum number of points to Winsorise for each indicator. If `NA`, will keep Winsorising until skewness and kurtosis
#' thresholds achieved (but it is likely this will cause errors).
#' @param winchange Logical: if `TRUE`, Winsorisation can change direction from one iteration to the next. Otherwise if `FALSE` (default), no change.
#' @param t_skew Absolute skew threshold (default 2).
#' @param t_kurt Kurtosis threshold (default 3.5).
#' @param icode The indicator name - used for error messages in [treat()].
#'
#' @examples
#' # get a column of data with outliers
#' x <- ASEMIndData$Tariff
#' # Winsorise up to five points
#' winlist <- coin_win(x, winmax = 5)
#' # check the differences
#' data.frame(
#' Orig = x,
#' Treated = winlist$icol,
#' Changes = ifelse(x == winlist$icol, "Same", "Treated"))
#'
#' @seealso
#' * [treat()] Outlier treatment
#'
#' @return A list containing:
#' * `.$icol` the vector of treated data
#' * `.$imax` the indices of elements of the vector that were Winsorised as high values
#' * `.$imax` the indices of elements of the vector that were Winsorised as low values
#' * `.$winz` the total number of Winsorised points
#'
#' @export
coin_win <- function(icol, winmax, winchange = TRUE, t_skew = 2, t_kurt = 3.5, icode = NULL){
# first, check skew and kurtosis
sk <- e1071::skewness(icol, na.rm = T, type = 2)
kt <- e1071::kurtosis(icol, na.rm = T, type = 2)
# now make a flag to either always do high Winsorisation, or always low, depending on sk
if (winchange==F){ # if F, we should always Winsorise from the same direction
if (sk>0){
windir <- 1 # always high
} else {
windir <- -1 # always low
}
} else { windir <- 0} # can change from high to low (winchange == T)
winz<-0 # set counter to 0
imax<-imin<-NULL # reset to NULL
if (is.na(winmax)){winmax <- 1e6}
while ( ((abs(sk)>t_skew) & (kt>t_kurt)) & (winz < winmax) ) { # keep going until sk and kt below thresholds OR reached winsorisation limit
# high winz if high skew AND windir =1, OR windir = 1 (always use high)
if ((sk>=0 & windir==0) | (windir == 1)){ # skew is positive, implies high outliers
imax <- which(icol==max(icol, na.rm = T)) # position(s) of maximum value(s)
icol[imax] <- max(icol[-imax], na.rm = T) # replace imax with max value of indicator if imax value(s) excluded
} else { # skew is negative, implies low outliers
imin <- which(icol==min(icol, na.rm = T)) # ditto, but with min
icol[imin] <- min(icol[-imin], na.rm = T)
}
winz<-winz+1 # add the winsorisation counter
# test skew and kurtosis again
if(length(unique(icol[!is.na(icol)])) < 2){
stop(paste0("Can't Winsorise further because it would imply less than two unique values in the indicator.
This is probably not a good idea. Consider individual settings for this indicator, such as
a lower winmax, using a transformation by default, or excluding from treatment.
**INDICATOR = ",icode,"**"))
} else {
sk <- e1071::skewness(icol, na.rm = T, type = 2)
kt <- e1071::kurtosis(icol, na.rm = T, type = 2)
}
}
# write outputs
w <- list(
icol = icol,
imax = imax,
imin = imin,
winz = winz
)
return(w)
}
#' Box Cox transformation
#'
#' Simple Box Cox, with no optimisation of lambda.
#' See [COINr online documentation](https://bluefoxr.github.io/COINrDoc/data-treatment.html#transformation) for more details.
#'
#' @param x A vector or column of data to transform
#' @param lambda The lambda parameter of the Box Cox transform
#' @param makepos If `TRUE` (default) makes all values positive by subtracting the minimum and adding 1.
#'
#' @examples
#' # get a column of data with outliers
#' x <- ASEMIndData$Tariff
#' # Apply Box Cox
#' xBox <- BoxCox(x, lambda = 2)
#' # plot one against the other
#' plot(x, xBox)
#'
#' @seealso
#' * [treat()] Outlier treatment
#'
#' @return A vector of length `length(x)` with transformed values.
#'
#' @export
BoxCox <- function(x, lambda, makepos = TRUE){
if(makepos){
# make positive using COIN Tool style shift
x <- x - min(x,na.rm = T) + 1
}
# Box Cox
if (lambda==0){
x <- log(x)
} else {
x <- (x^lambda - 1)/lambda
}
return(x)
}
#' Log-type transformation of a vector
#'
#' This applies various simple transformations, to be used by the [treat()] function.
#' This function is probably not very useful on its own because it requires `params`,
#' a list of parameters which are used to output the type and status of treatment applied.
#'
#' @param x A vector or column of data to transform
#' @param ltype The type of log transformation - see `deflog` in [treat()].
#' @param params Some extra parameters to pass. These parameters mostly concern internal messages for [treat()] and this can be
#' left unspecified unless `ltype == "boxcox"`, in which case there should be a parameter `params$boxlam` specified
#' (see [BoxCox()]). However, if you wish to use a Box Cox transformation, it is better to use [BoxCox()] directly.
#'
#' @examples
#' # get a column of data with outliers
#' x <- ASEMIndData$Tariff
#' # apply a GII transformation
#' xdash <- loggish(x, ltype = "GIIlog")
#' # plot one against the other
#' plot(x, xdash$x)
#'
#' @seealso
#' * [treat()] Outlier treatment
#'
#' @return A list with
#' * `.$x` is the transformed vector of data
#' * `.$Flag` is a flag of the type of treatment specified (used inside [treat()])
#' * `.$Treatment` the treatment applied (used inside [treat()])
#' * `.$TreatSpec` the treatment specified (used inside [treat()])
#'
#' @export
loggish <- function(x, ltype, params = NULL){
# some default parameters if this function is used on its own
if(is.null(params)){
params = list(IndCodes = "Indicator",
ii = 1,
forced = FALSE,
winmax = "unspecified",
boxlam = 1)
} else if (!is.null(params$boxlam)){
params$IndCodes = "Indicator"
params$ii = 1
params$forced = FALSE
params$winmax = "unspecified"
}
# prep a list
l <- list(x = NA, Flag = NA, Treatment = NA, TreatSpec = NA)
if ( (sum(x<=0, na.rm=T)>0) & (ltype == "log") ){ # negative values. No can normal log.
l$Flag <- "Err"
# x will be passed through with no treatment
l$x <- x
warning(paste0(params$IndCodes[params$ii],": log transform attempted but failed because negative or zero values. Please check."))
if(params$forced){
l$TreatSpec <- paste0("Forced log")
l$Treatment <- "None: log error"
} else {
l$TreatSpec <- paste0("Default, winmax = ", params$winmax)
l$Treatment <- "None: exceeded winmax but log error"
}
} else if ( (sum(x<=0, na.rm=T)==0) & (ltype == "log") ) { # OK to normal log
l$x <- log(x)
l$Flag <- "Log"
if(params$forced){
l$TreatSpec <- paste0("Forced log")
l$Treatment <- "Log"
} else {
l$TreatSpec <- paste0("Default, winmax = ", params$winmax)
l$Treatment <- "Log (exceeded winmax)"
}
} else if (ltype == "GIIlog"){ # GII log
# get GII log
l$x <- log( (max(x, na.rm = T)-1)*(x-min(x, na.rm = T))/(max(x, na.rm = T)-min(x, na.rm = T)) + 1 )
l$Flag <- "GIILog"
if(params$forced){
l$TreatSpec <- paste0("Forced GIIlog")
l$Treatment <- "GIILog"
} else {
l$TreatSpec <- paste0("Default, winmax = ", params$winmax)
l$Treatment <- "GIILog (exceeded winmax)"
}
} else if (ltype == "CTlog"){
# COIN TOOl style log: subtract min and add fraction of range
l$x <- log(x- min(x,na.rm = T) + 0.01*(max(x, na.rm = T)-min(x, na.rm = T)))
l$Flag <- "CTLog"
if(params$forced){
l$TreatSpec <- paste0("Forced CTlog")
l$Treatment <- "CTLog"
} else {
l$TreatSpec <- paste0("Default, winmax = ", params$winmax)
l$Treatment <- "CTLog (exceeded winmax)"
}
} else if (ltype == "CTlog_orig"){
# COIN TOOl original log: subtract min and add 1
l$x <- log(x- min(x,na.rm = T) + 1)
l$Flag <- "CTlog_orig"
if(params$forced){
l$TreatSpec <- paste0("Forced CTlog_orig")
l$Treatment <- "CTlog_orig"
} else {
l$TreatSpec <- paste0("Default, winmax = ", params$winmax)
l$Treatment <- "CTlog_orig (exceeded winmax)"
}
} else if (ltype == "boxcox"){
# Box Cox transform
l$x <- BoxCox(x,params$boxlam)
l$Flag <- "BoxCox"
if(params$forced){
l$TreatSpec <- paste0("Forced Box-Cox")
l$Treatment <- paste0("Box Cox with lambda = ",params$boxlam)
} else {
l$TreatSpec <- paste0("Default, winmax = ", params$winmax)
l$Treatment <- paste0("Box Cox with lambda = ",params$boxlam," (exceeded winmax)")
}
} else if (ltype == "None"){
# No transform
l$x <- x
# this indicator should be excluded from any treatment
l$Flag <- "ForcedNo"
l$Treatment <- "ForcedNone"
l$TreatSpec <- "None"
}
return(l)
}
|
## ----setup, include=FALSE-------------------------------------------
options(formatR.indent = 4, width = 70)
knitr::opts_chunk$set(tidy = TRUE)
## ----eval=FALSE-----------------------------------------------------
# install.packages('formatR', repos = 'http://cran.rstudio.com')
# # or development version
# options(repos = c(
# yihui = 'https://yihui.r-universe.dev',
# CRAN = 'https://cloud.r-project.org'
# ))
# install.packages('formatR')
## -------------------------------------------------------------------
library(formatR)
sessionInfo()
## ----example, eval=FALSE, tidy=FALSE--------------------------------
# ## comments are retained;
# # a comment block will be reflowed if it contains long comments;
# #' roxygen comments will not be wrapped in any case
# 1+1
#
# if(TRUE){
# x=1 # inline comments
# }else{
# x=2;print('Oh no... ask the right bracket to go away!')}
# 1*3 # one space before this comment will become two!
# 2+2+2 # only 'single quotes' are allowed in comments
#
# lm(y~x1+x2, data=data.frame(y=rnorm(100),x1=rnorm(100),x2=rnorm(100))) ### a linear model
# 1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1 # comment after a long line
# ## here is a long long long long long long long long long long long long long comment that may be wrapped
## ----example, eval=FALSE, tidy.opts=list(width.cutoff=50)-----------
# ## comments are retained;
# # a comment block will be reflowed if it contains long comments;
# #' roxygen comments will not be wrapped in any case
# 1+1
#
# if(TRUE){
# x=1 # inline comments
# }else{
# x=2;print('Oh no... ask the right bracket to go away!')}
# 1*3 # one space before this comment will become two!
# 2+2+2 # only 'single quotes' are allowed in comments
#
# lm(y~x1+x2, data=data.frame(y=rnorm(100),x1=rnorm(100),x2=rnorm(100))) ### a linear model
# 1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1 # comment after a long line
# ## here is a long long long long long long long long long long long long long comment that may be wrapped
## ----collapse=TRUE--------------------------------------------------
library(formatR)
usage(glm, width = 40) # can set arbitrary width here
args(glm)
## ----echo=FALSE, results='asis'-------------------------------------
if (ignore_img <- !is.na(Sys.getenv('_R_CHECK_PACKAGE_NAME_', NA))) cat('<!--')
## ----echo=FALSE, results='asis'-------------------------------------
if (ignore_img) cat('\n-->')
## ----comment=NA-----------------------------------------------------
set.seed(123)
tidy_eval(text = c("a<-1+1;a # print the value", "matrix(rnorm(10),5)"))
## ----eval=FALSE-----------------------------------------------------
# library(formatR)
# tidy_eval()
# # without specifying any arguments, it reads code from clipboard
## ----example, eval=FALSE, echo=5, tidy.opts=list(arrow=TRUE)--------
# ## comments are retained;
# # a comment block will be reflowed if it contains long comments;
# #' roxygen comments will not be wrapped in any case
# 1+1
#
# if(TRUE){
# x=1 # inline comments
# }else{
# x=2;print('Oh no... ask the right bracket to go away!')}
# 1*3 # one space before this comment will become two!
# 2+2+2 # only 'single quotes' are allowed in comments
#
# lm(y~x1+x2, data=data.frame(y=rnorm(100),x1=rnorm(100),x2=rnorm(100))) ### a linear model
# 1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1 # comment after a long line
# ## here is a long long long long long long long long long long long long long comment that may be wrapped
## ----example, eval=FALSE, echo=1:5, tidy.opts=list(blank = FALSE)----
# ## comments are retained;
# # a comment block will be reflowed if it contains long comments;
# #' roxygen comments will not be wrapped in any case
# 1+1
#
# if(TRUE){
# x=1 # inline comments
# }else{
# x=2;print('Oh no... ask the right bracket to go away!')}
# 1*3 # one space before this comment will become two!
# 2+2+2 # only 'single quotes' are allowed in comments
#
# lm(y~x1+x2, data=data.frame(y=rnorm(100),x1=rnorm(100),x2=rnorm(100))) ### a linear model
# 1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1 # comment after a long line
# ## here is a long long long long long long long long long long long long long comment that may be wrapped
## ----example, eval=FALSE, echo=5, tidy.opts=list(indent = 2)--------
# ## comments are retained;
# # a comment block will be reflowed if it contains long comments;
# #' roxygen comments will not be wrapped in any case
# 1+1
#
# if(TRUE){
# x=1 # inline comments
# }else{
# x=2;print('Oh no... ask the right bracket to go away!')}
# 1*3 # one space before this comment will become two!
# 2+2+2 # only 'single quotes' are allowed in comments
#
# lm(y~x1+x2, data=data.frame(y=rnorm(100),x1=rnorm(100),x2=rnorm(100))) ### a linear model
# 1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1 # comment after a long line
# ## here is a long long long long long long long long long long long long long comment that may be wrapped
## ---- args-code, eval=FALSE-----------------------------------------
# shiny::updateSelectizeInput(session, "foo", label = "New Label",
# selected = c("A", "B"), choices = LETTERS,
# server = TRUE)
## ---- args-code, eval=FALSE, tidy.opts=list(args.newline=TRUE)------
# shiny::updateSelectizeInput(session, "foo", label = "New Label",
# selected = c("A", "B"), choices = LETTERS,
# server = TRUE)
## ---- pipe-code, eval=FALSE, tidy=FALSE-----------------------------
# mtcars %>% subset(am == 0) %>% lm(mpg~hp, data=.)
## ---- pipe-code, eval=FALSE, tidy=TRUE------------------------------
# mtcars %>% subset(am == 0) %>% lm(mpg~hp, data=.)
## ----example, eval=FALSE, echo=5, tidy.opts=list(brace.newline = TRUE)----
# ## comments are retained;
# # a comment block will be reflowed if it contains long comments;
# #' roxygen comments will not be wrapped in any case
# 1+1
#
# if(TRUE){
# x=1 # inline comments
# }else{
# x=2;print('Oh no... ask the right bracket to go away!')}
# 1*3 # one space before this comment will become two!
# 2+2+2 # only 'single quotes' are allowed in comments
#
# lm(y~x1+x2, data=data.frame(y=rnorm(100),x1=rnorm(100),x2=rnorm(100))) ### a linear model
# 1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1 # comment after a long line
# ## here is a long long long long long long long long long long long long long comment that may be wrapped
## ----example, eval=FALSE, echo=11:12, tidy.opts=list(wrap = FALSE)----
# ## comments are retained;
# # a comment block will be reflowed if it contains long comments;
# #' roxygen comments will not be wrapped in any case
# 1+1
#
# if(TRUE){
# x=1 # inline comments
# }else{
# x=2;print('Oh no... ask the right bracket to go away!')}
# 1*3 # one space before this comment will become two!
# 2+2+2 # only 'single quotes' are allowed in comments
#
# lm(y~x1+x2, data=data.frame(y=rnorm(100),x1=rnorm(100),x2=rnorm(100))) ### a linear model
# 1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1 # comment after a long line
# ## here is a long long long long long long long long long long long long long comment that may be wrapped
## ----example, eval=FALSE, tidy.opts=list(comment = FALSE, width.cutoff = 50)----
# ## comments are retained;
# # a comment block will be reflowed if it contains long comments;
# #' roxygen comments will not be wrapped in any case
# 1+1
#
# if(TRUE){
# x=1 # inline comments
# }else{
# x=2;print('Oh no... ask the right bracket to go away!')}
# 1*3 # one space before this comment will become two!
# 2+2+2 # only 'single quotes' are allowed in comments
#
# lm(y~x1+x2, data=data.frame(y=rnorm(100),x1=rnorm(100),x2=rnorm(100))) ### a linear model
# 1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1 # comment after a long line
# ## here is a long long long long long long long long long long long long long comment that may be wrapped
## ----comment-brace, tidy=FALSE, eval=FALSE--------------------------
# if (TRUE) {## comments
# }
## ----comment-brace, eval=FALSE--------------------------------------
# if (TRUE) {## comments
# }
## -------------------------------------------------------------------
deparse(parse(text = '1+2-3*4/5 # a comment'))
| /formatR/doc/formatR.R | no_license | r-tutor/libs2 | R | false | false | 8,340 | r | ## ----setup, include=FALSE-------------------------------------------
options(formatR.indent = 4, width = 70)
knitr::opts_chunk$set(tidy = TRUE)
## ----eval=FALSE-----------------------------------------------------
# install.packages('formatR', repos = 'http://cran.rstudio.com')
# # or development version
# options(repos = c(
# yihui = 'https://yihui.r-universe.dev',
# CRAN = 'https://cloud.r-project.org'
# ))
# install.packages('formatR')
## -------------------------------------------------------------------
library(formatR)
sessionInfo()
## ----example, eval=FALSE, tidy=FALSE--------------------------------
# ## comments are retained;
# # a comment block will be reflowed if it contains long comments;
# #' roxygen comments will not be wrapped in any case
# 1+1
#
# if(TRUE){
# x=1 # inline comments
# }else{
# x=2;print('Oh no... ask the right bracket to go away!')}
# 1*3 # one space before this comment will become two!
# 2+2+2 # only 'single quotes' are allowed in comments
#
# lm(y~x1+x2, data=data.frame(y=rnorm(100),x1=rnorm(100),x2=rnorm(100))) ### a linear model
# 1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1 # comment after a long line
# ## here is a long long long long long long long long long long long long long comment that may be wrapped
## ----example, eval=FALSE, tidy.opts=list(width.cutoff=50)-----------
# ## comments are retained;
# # a comment block will be reflowed if it contains long comments;
# #' roxygen comments will not be wrapped in any case
# 1+1
#
# if(TRUE){
# x=1 # inline comments
# }else{
# x=2;print('Oh no... ask the right bracket to go away!')}
# 1*3 # one space before this comment will become two!
# 2+2+2 # only 'single quotes' are allowed in comments
#
# lm(y~x1+x2, data=data.frame(y=rnorm(100),x1=rnorm(100),x2=rnorm(100))) ### a linear model
# 1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1 # comment after a long line
# ## here is a long long long long long long long long long long long long long comment that may be wrapped
## ----collapse=TRUE--------------------------------------------------
library(formatR)
usage(glm, width = 40) # can set arbitrary width here
args(glm)
## ----echo=FALSE, results='asis'-------------------------------------
if (ignore_img <- !is.na(Sys.getenv('_R_CHECK_PACKAGE_NAME_', NA))) cat('<!--')
## ----echo=FALSE, results='asis'-------------------------------------
if (ignore_img) cat('\n-->')
## ----comment=NA-----------------------------------------------------
set.seed(123)
tidy_eval(text = c("a<-1+1;a # print the value", "matrix(rnorm(10),5)"))
## ----eval=FALSE-----------------------------------------------------
# library(formatR)
# tidy_eval()
# # without specifying any arguments, it reads code from clipboard
## ----example, eval=FALSE, echo=5, tidy.opts=list(arrow=TRUE)--------
# ## comments are retained;
# # a comment block will be reflowed if it contains long comments;
# #' roxygen comments will not be wrapped in any case
# 1+1
#
# if(TRUE){
# x=1 # inline comments
# }else{
# x=2;print('Oh no... ask the right bracket to go away!')}
# 1*3 # one space before this comment will become two!
# 2+2+2 # only 'single quotes' are allowed in comments
#
# lm(y~x1+x2, data=data.frame(y=rnorm(100),x1=rnorm(100),x2=rnorm(100))) ### a linear model
# 1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1 # comment after a long line
# ## here is a long long long long long long long long long long long long long comment that may be wrapped
## ----example, eval=FALSE, echo=1:5, tidy.opts=list(blank = FALSE)----
# ## comments are retained;
# # a comment block will be reflowed if it contains long comments;
# #' roxygen comments will not be wrapped in any case
# 1+1
#
# if(TRUE){
# x=1 # inline comments
# }else{
# x=2;print('Oh no... ask the right bracket to go away!')}
# 1*3 # one space before this comment will become two!
# 2+2+2 # only 'single quotes' are allowed in comments
#
# lm(y~x1+x2, data=data.frame(y=rnorm(100),x1=rnorm(100),x2=rnorm(100))) ### a linear model
# 1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1 # comment after a long line
# ## here is a long long long long long long long long long long long long long comment that may be wrapped
## ----example, eval=FALSE, echo=5, tidy.opts=list(indent = 2)--------
# ## comments are retained;
# # a comment block will be reflowed if it contains long comments;
# #' roxygen comments will not be wrapped in any case
# 1+1
#
# if(TRUE){
# x=1 # inline comments
# }else{
# x=2;print('Oh no... ask the right bracket to go away!')}
# 1*3 # one space before this comment will become two!
# 2+2+2 # only 'single quotes' are allowed in comments
#
# lm(y~x1+x2, data=data.frame(y=rnorm(100),x1=rnorm(100),x2=rnorm(100))) ### a linear model
# 1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1 # comment after a long line
# ## here is a long long long long long long long long long long long long long comment that may be wrapped
## ---- args-code, eval=FALSE-----------------------------------------
# shiny::updateSelectizeInput(session, "foo", label = "New Label",
# selected = c("A", "B"), choices = LETTERS,
# server = TRUE)
## ---- args-code, eval=FALSE, tidy.opts=list(args.newline=TRUE)------
# shiny::updateSelectizeInput(session, "foo", label = "New Label",
# selected = c("A", "B"), choices = LETTERS,
# server = TRUE)
## ---- pipe-code, eval=FALSE, tidy=FALSE-----------------------------
# mtcars %>% subset(am == 0) %>% lm(mpg~hp, data=.)
## ---- pipe-code, eval=FALSE, tidy=TRUE------------------------------
# mtcars %>% subset(am == 0) %>% lm(mpg~hp, data=.)
## ----example, eval=FALSE, echo=5, tidy.opts=list(brace.newline = TRUE)----
# ## comments are retained;
# # a comment block will be reflowed if it contains long comments;
# #' roxygen comments will not be wrapped in any case
# 1+1
#
# if(TRUE){
# x=1 # inline comments
# }else{
# x=2;print('Oh no... ask the right bracket to go away!')}
# 1*3 # one space before this comment will become two!
# 2+2+2 # only 'single quotes' are allowed in comments
#
# lm(y~x1+x2, data=data.frame(y=rnorm(100),x1=rnorm(100),x2=rnorm(100))) ### a linear model
# 1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1 # comment after a long line
# ## here is a long long long long long long long long long long long long long comment that may be wrapped
## ----example, eval=FALSE, echo=11:12, tidy.opts=list(wrap = FALSE)----
# ## comments are retained;
# # a comment block will be reflowed if it contains long comments;
# #' roxygen comments will not be wrapped in any case
# 1+1
#
# if(TRUE){
# x=1 # inline comments
# }else{
# x=2;print('Oh no... ask the right bracket to go away!')}
# 1*3 # one space before this comment will become two!
# 2+2+2 # only 'single quotes' are allowed in comments
#
# lm(y~x1+x2, data=data.frame(y=rnorm(100),x1=rnorm(100),x2=rnorm(100))) ### a linear model
# 1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1 # comment after a long line
# ## here is a long long long long long long long long long long long long long comment that may be wrapped
## ----example, eval=FALSE, tidy.opts=list(comment = FALSE, width.cutoff = 50)----
# ## comments are retained;
# # a comment block will be reflowed if it contains long comments;
# #' roxygen comments will not be wrapped in any case
# 1+1
#
# if(TRUE){
# x=1 # inline comments
# }else{
# x=2;print('Oh no... ask the right bracket to go away!')}
# 1*3 # one space before this comment will become two!
# 2+2+2 # only 'single quotes' are allowed in comments
#
# lm(y~x1+x2, data=data.frame(y=rnorm(100),x1=rnorm(100),x2=rnorm(100))) ### a linear model
# 1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1 # comment after a long line
# ## here is a long long long long long long long long long long long long long comment that may be wrapped
## ----comment-brace, tidy=FALSE, eval=FALSE--------------------------
# if (TRUE) {## comments
# }
## ----comment-brace, eval=FALSE--------------------------------------
# if (TRUE) {## comments
# }
## -------------------------------------------------------------------
deparse(parse(text = '1+2-3*4/5 # a comment'))
|
zagreb1 <- function(g,deg=NULL){
if(class(g)[1]!="graphNEL"){
stop("'g' must be a 'graphNEL' object")
}
stopifnot(.validateGraph(g))
if(is.null(deg)){
deg <- graph::degree(g)
}
sum(deg)
}
| /QuACN/R/zagreb1.R | no_license | ingted/R-Examples | R | false | false | 212 | r | zagreb1 <- function(g,deg=NULL){
if(class(g)[1]!="graphNEL"){
stop("'g' must be a 'graphNEL' object")
}
stopifnot(.validateGraph(g))
if(is.null(deg)){
deg <- graph::degree(g)
}
sum(deg)
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tree.HDOM.r
\name{tree.HDOM}
\alias{tree.HDOM}
\title{Calculate dominant height for a plot based on tree-level data.}
\usage{
tree.HDOM(HT, DBH, AREA)
}
\arguments{
\item{HT}{Vector of tree heights (ft) for a given plot (must be complete).}
\item{DBH}{Vector of diameter at breast height (DBH, in). Must be complete and have the same size and order of HT.}
\item{AREA}{Numeric value of area of the inventory plot (ft2).}
}
\value{
A value with Dominant Height (HDOM, ft) for the plot.
}
\description{
\code{tree.HDOM} Calculate the dominant height for a plot based on tree-level data based on the top 25th percentile
of the tree heights. The provided vector of heights should be complete without missing data.
}
\examples{
treedata <- subset(treedata, is.na(DBH)==FALSE)
HT <- treedata$HT
DBH <- treedata$DBH
AREA <- 3240
tree.HDOM(HT=HT, DBH=DBH, AREA=AREA)
}
\author{
Priscila Someda-Dias, Salvador A. Gezan
}
| /Code/man/tree.HDOM.Rd | no_license | carlos-alberto-silva/slashGY | R | false | true | 1,024 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tree.HDOM.r
\name{tree.HDOM}
\alias{tree.HDOM}
\title{Calculate dominant height for a plot based on tree-level data.}
\usage{
tree.HDOM(HT, DBH, AREA)
}
\arguments{
\item{HT}{Vector of tree heights (ft) for a given plot (must be complete).}
\item{DBH}{Vector of diameter at breast height (DBH, in). Must be complete and have the same size and order of HT.}
\item{AREA}{Numeric value of area of the inventory plot (ft2).}
}
\value{
A value with Dominant Height (HDOM, ft) for the plot.
}
\description{
\code{tree.HDOM} Calculate the dominant height for a plot based on tree-level data based on the top 25th percentile
of the tree heights. The provided vector of heights should be complete without missing data.
}
\examples{
treedata <- subset(treedata, is.na(DBH)==FALSE)
HT <- treedata$HT
DBH <- treedata$DBH
AREA <- 3240
tree.HDOM(HT=HT, DBH=DBH, AREA=AREA)
}
\author{
Priscila Someda-Dias, Salvador A. Gezan
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/ModStore.R
\name{ModStore}
\alias{ModStore}
\title{R6 Class Representing a ModStore}
\description{
This class is used to create a storage for tidymodules objects.
}
\details{
Manage applications, sessions and modules.
}
\examples{
## ------------------------------------------------
## Method `ModStore$new`
## ------------------------------------------------
MyModule <- R6::R6Class("MyModule", inherit = tidymodules::TidyModule)
m <- MyModule$new()
s <- m$getStore()
## ------------------------------------------------
## Method `ModStore$isStored`
## ------------------------------------------------
MyModule <- R6::R6Class("MyModule", inherit = tidymodules::TidyModule)
m <- MyModule$new()
s <- m$getStore()
s$isStored(m)
}
\section{Methods}{
\subsection{Public methods}{
\itemize{
\item \href{#method-new}{\code{ModStore$new()}}
\item \href{#method-isStored}{\code{ModStore$isStored()}}
\item \href{#method-getGlobalSession}{\code{ModStore$getGlobalSession()}}
\item \href{#method-getSession}{\code{ModStore$getSession()}}
\item \href{#method-getSessions}{\code{ModStore$getSessions()}}
\item \href{#method-getMods}{\code{ModStore$getMods()}}
\item \href{#method-getEdges}{\code{ModStore$getEdges()}}
\item \href{#method-addEdge}{\code{ModStore$addEdge()}}
\item \href{#method-addMod}{\code{ModStore$addMod()}}
\item \href{#method-delMod}{\code{ModStore$delMod()}}
\item \href{#method-print}{\code{ModStore$print()}}
\item \href{#method-clone}{\code{ModStore$clone()}}
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-new"></a>}}
\subsection{Method \code{new()}}{
Create a new ModStore object.
Should be called once by the TidyModule class.
Not to be called directly outside TidyModule.
The ModStore object can be retrieved from any TidyModule object, see example below.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{ModStore$new()}\if{html}{\out{</div>}}
}
\subsection{Returns}{
A new \code{ModStore} object.
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{MyModule <- R6::R6Class("MyModule", inherit = tidymodules::TidyModule)
m <- MyModule$new()
s <- m$getStore()
}
\if{html}{\out{</div>}}
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-isStored"></a>}}
\subsection{Method \code{isStored()}}{
Check if a module is stored in the current session.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{ModStore$isStored(m)}\if{html}{\out{</div>}}
}
\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{m}}{TidyModule object.}
}
\if{html}{\out{</div>}}
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{MyModule <- R6::R6Class("MyModule", inherit = tidymodules::TidyModule)
m <- MyModule$new()
s <- m$getStore()
s$isStored(m)
}
\if{html}{\out{</div>}}
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-getGlobalSession"></a>}}
\subsection{Method \code{getGlobalSession()}}{
Retrieve the global session 'global_session'.
This is the session that exists outside the application server function
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{ModStore$getGlobalSession()}\if{html}{\out{</div>}}
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-getSession"></a>}}
\subsection{Method \code{getSession()}}{
Retrieve a module session.
This could be the global session or a user session.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{ModStore$getSession(m)}\if{html}{\out{</div>}}
}
\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{m}}{TidyModule object.}
}
\if{html}{\out{</div>}}
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-getSessions"></a>}}
\subsection{Method \code{getSessions()}}{
Retrieve all sessions.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{ModStore$getSessions()}\if{html}{\out{</div>}}
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-getMods"></a>}}
\subsection{Method \code{getMods()}}{
Retrieve all modules.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{ModStore$getMods(m)}\if{html}{\out{</div>}}
}
\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{m}}{TidyModule object.}
}
\if{html}{\out{</div>}}
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-getEdges"></a>}}
\subsection{Method \code{getEdges()}}{
Retrieve modules connections.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{ModStore$getEdges(m)}\if{html}{\out{</div>}}
}
\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{m}}{TidyModule object.}
}
\if{html}{\out{</div>}}
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-addEdge"></a>}}
\subsection{Method \code{addEdge()}}{
Add modules connections into ModStore.
An edge is either a connection between a reactive object and a module
or between two modules.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{ModStore$addEdge(from, to, mode = "direct", comment = NA)}\if{html}{\out{</div>}}
}
\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{from}}{list with three elements: m -> module, type -> input or output, port -> port Id.}
\item{\code{to}}{list with three elements: m -> module, type -> input or output, port -> port Id.}
\item{\code{mode}}{The type of edge, default to 'direct'.}
\item{\code{comment}}{Any additional comment.}
}
\if{html}{\out{</div>}}
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-addMod"></a>}}
\subsection{Method \code{addMod()}}{
Add module into the ModStore.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{ModStore$addMod(m)}\if{html}{\out{</div>}}
}
\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{m}}{TidyModule object.}
}
\if{html}{\out{</div>}}
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-delMod"></a>}}
\subsection{Method \code{delMod()}}{
Delete a module from the ModStore.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{ModStore$delMod(m)}\if{html}{\out{</div>}}
}
\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{m}}{TidyModule object.}
}
\if{html}{\out{</div>}}
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-print"></a>}}
\subsection{Method \code{print()}}{
Print the ModStore object.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{ModStore$print()}\if{html}{\out{</div>}}
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-clone"></a>}}
\subsection{Method \code{clone()}}{
The objects of this class are cloneable with this method.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{ModStore$clone(deep = FALSE)}\if{html}{\out{</div>}}
}
\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{deep}}{Whether to make a deep clone.}
}
\if{html}{\out{</div>}}
}
}
}
| /man/ModStore.Rd | permissive | jonas-hag/tidymodules | R | false | true | 7,004 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/ModStore.R
\name{ModStore}
\alias{ModStore}
\title{R6 Class Representing a ModStore}
\description{
This class is used to create a storage for tidymodules objects.
}
\details{
Manage applications, sessions and modules.
}
\examples{
## ------------------------------------------------
## Method `ModStore$new`
## ------------------------------------------------
MyModule <- R6::R6Class("MyModule", inherit = tidymodules::TidyModule)
m <- MyModule$new()
s <- m$getStore()
## ------------------------------------------------
## Method `ModStore$isStored`
## ------------------------------------------------
MyModule <- R6::R6Class("MyModule", inherit = tidymodules::TidyModule)
m <- MyModule$new()
s <- m$getStore()
s$isStored(m)
}
\section{Methods}{
\subsection{Public methods}{
\itemize{
\item \href{#method-new}{\code{ModStore$new()}}
\item \href{#method-isStored}{\code{ModStore$isStored()}}
\item \href{#method-getGlobalSession}{\code{ModStore$getGlobalSession()}}
\item \href{#method-getSession}{\code{ModStore$getSession()}}
\item \href{#method-getSessions}{\code{ModStore$getSessions()}}
\item \href{#method-getMods}{\code{ModStore$getMods()}}
\item \href{#method-getEdges}{\code{ModStore$getEdges()}}
\item \href{#method-addEdge}{\code{ModStore$addEdge()}}
\item \href{#method-addMod}{\code{ModStore$addMod()}}
\item \href{#method-delMod}{\code{ModStore$delMod()}}
\item \href{#method-print}{\code{ModStore$print()}}
\item \href{#method-clone}{\code{ModStore$clone()}}
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-new"></a>}}
\subsection{Method \code{new()}}{
Create a new ModStore object.
Should be called once by the TidyModule class.
Not to be called directly outside TidyModule.
The ModStore object can be retrieved from any TidyModule object, see example below.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{ModStore$new()}\if{html}{\out{</div>}}
}
\subsection{Returns}{
A new \code{ModStore} object.
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{MyModule <- R6::R6Class("MyModule", inherit = tidymodules::TidyModule)
m <- MyModule$new()
s <- m$getStore()
}
\if{html}{\out{</div>}}
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-isStored"></a>}}
\subsection{Method \code{isStored()}}{
Check if a module is stored in the current session.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{ModStore$isStored(m)}\if{html}{\out{</div>}}
}
\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{m}}{TidyModule object.}
}
\if{html}{\out{</div>}}
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{MyModule <- R6::R6Class("MyModule", inherit = tidymodules::TidyModule)
m <- MyModule$new()
s <- m$getStore()
s$isStored(m)
}
\if{html}{\out{</div>}}
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-getGlobalSession"></a>}}
\subsection{Method \code{getGlobalSession()}}{
Retrieve the global session 'global_session'.
This is the session that exists outside the application server function
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{ModStore$getGlobalSession()}\if{html}{\out{</div>}}
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-getSession"></a>}}
\subsection{Method \code{getSession()}}{
Retrieve a module session.
This could be the global session or a user session.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{ModStore$getSession(m)}\if{html}{\out{</div>}}
}
\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{m}}{TidyModule object.}
}
\if{html}{\out{</div>}}
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-getSessions"></a>}}
\subsection{Method \code{getSessions()}}{
Retrieve all sessions.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{ModStore$getSessions()}\if{html}{\out{</div>}}
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-getMods"></a>}}
\subsection{Method \code{getMods()}}{
Retrieve all modules.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{ModStore$getMods(m)}\if{html}{\out{</div>}}
}
\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{m}}{TidyModule object.}
}
\if{html}{\out{</div>}}
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-getEdges"></a>}}
\subsection{Method \code{getEdges()}}{
Retrieve modules connections.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{ModStore$getEdges(m)}\if{html}{\out{</div>}}
}
\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{m}}{TidyModule object.}
}
\if{html}{\out{</div>}}
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-addEdge"></a>}}
\subsection{Method \code{addEdge()}}{
Add modules connections into ModStore.
An edge is either a connection between a reactive object and a module
or between two modules.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{ModStore$addEdge(from, to, mode = "direct", comment = NA)}\if{html}{\out{</div>}}
}
\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{from}}{list with three elements: m -> module, type -> input or output, port -> port Id.}
\item{\code{to}}{list with three elements: m -> module, type -> input or output, port -> port Id.}
\item{\code{mode}}{The type of edge, default to 'direct'.}
\item{\code{comment}}{Any additional comment.}
}
\if{html}{\out{</div>}}
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-addMod"></a>}}
\subsection{Method \code{addMod()}}{
Add module into the ModStore.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{ModStore$addMod(m)}\if{html}{\out{</div>}}
}
\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{m}}{TidyModule object.}
}
\if{html}{\out{</div>}}
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-delMod"></a>}}
\subsection{Method \code{delMod()}}{
Delete a module from the ModStore.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{ModStore$delMod(m)}\if{html}{\out{</div>}}
}
\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{m}}{TidyModule object.}
}
\if{html}{\out{</div>}}
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-print"></a>}}
\subsection{Method \code{print()}}{
Print the ModStore object.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{ModStore$print()}\if{html}{\out{</div>}}
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-clone"></a>}}
\subsection{Method \code{clone()}}{
The objects of this class are cloneable with this method.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{ModStore$clone(deep = FALSE)}\if{html}{\out{</div>}}
}
\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{deep}}{Whether to make a deep clone.}
}
\if{html}{\out{</div>}}
}
}
}
|
# Ensure that you have working Dataset and BEC Pair Table in your working directory:
# When you start with a new dataset, make sure to follow "When You Have New Dataset" below first:
#set library
.libPaths("E:/R packages")
# Install the following R packages:
install.packages("caret")
install.packages("rattle")
install.packages("rpart")
install.packages("rpart.plot")
install.packages("tcltk")
install.packages("plyr")
install.packages("reshape")
install.packages("reshape2")
install.packages("VSURF")
install.packages("reports")
install.packages("rpart.utils")
install.packages("rfUtilities")
install.packages ("ggplot2")
install.packages ("functional")
install.packages ("plot3D")
install.packages("dplyr")
install.packages("randomForest")
install.packages("ranger")
install.packages("OpenMP")
install.packages ("randomForestSRC")
# Load R packages:
library(rattle)
library(rpart)
library(rpart.plot)
library(plyr)
library(reshape)
library(reshape2)
library(VSURF)
library(reports)
library(rpart.utils)
require(rfUtilities)
library("parallel")
library("foreach")
library("doParallel")
require("ggplot2")
library(functional)
require(plot3D)
library(dplyr)
library(tcltk)
library(caret)
require(randomForest)
require(ranger)
require (OpenMP)
require (randomForestSRC)
require (tools)
######Clear environment and add in dataset############
rm(list=ls())
options(stringsAsFactors = FALSE)
# The codes below need to be run only once when you start with a new dataset #
## Set working directory:
wd=tk_choose.dir()
setwd(wd)
#Use to import multiple datasets
##load 1st climate data set and use file name of dataset as fname
fplot=(file.choose())
Y1=read.csv(fplot,stringsAsFactors=F,na.strings=".")
fname=basename(file_path_sans_ext(fplot))
#Load a second file to merge with Y1, repeat this block with additional files
fplot2=(file.choose())
Y2=read.csv(fplot2,stringsAsFactors=F,na.strings=".")
Y1 <- rbind(Y1, Y2)
X1=Y1
#####Alternate method for import
## Name of ClimateWNA output Model Dataset and Plots to predict Table:
fname="AB2000pts_outputfromWNA"
## Unzip .csv file of a BEC Climate dataset and save and store it in .Rda format:
fpath=paste(wd,"/",fname,".csv",sep="")
X1=read.csv(fpath,stringsAsFactors=FALSE,na.strings=".")
###########################
####modify variable names
colnames(X1)[1]=c("PlotNo")
colnames(X1)[2]=c("BGC")
records <- nrow(X1)
X1$PlotNo <- as.integer(seq(from = 1, to = records, by =1))
attr(X1, "row.names") <- (X1$PlotNo)
X2 <- X1 [, c("PlotNo", "BGC", "Latitude", "Longitude", "Elevation")]
X1=X1[,-c(1,3:5)]
#X1<- as.data.frame(X1)
# Drop
X1$BGC <- as.factor(X1$BGC)
save(X1,file=paste(fname,".Rda",sep=""))
#############################################
############# Reduce to working dataset ######
#############################################
############# Prepare Dataset for Analysis:----
# Load saved RDA Dataset (if .csv not used):
fname="BGCv10_2000Pt_Rnd_Normal_1961_1990MSY"
load(paste(fname,".Rda",sep=""))
#####generate some addtional variables
X1$PPT_MJ <- X1$PPT05 + X1$PPT06 # MaY/June precip
X1$PPT_JAS <- X1$PPT07 + X1$PPT08 + X1$PPT09 # July/Aug/Sept precip
X1$CMDMax <- X1$CMD07
X1$CMD.grow <- X1$CMD05 + X1$CMD06 +X1$CMD07 +X1$CMD08 +X1$CMD09
X1$PPT.dormant <- X1$PPT_at + X1$PPT_wt # for calculating spring deficit
X1$CMD.def <- 500 - (X1$PPT.dormant)# start of growing season deficit original value was 400 but 500 seems better
X1$CMD.def [X1$CMD.def < 0] <- 0 #negative values set to zero = no deficit
X1$CMD.total <- X1$CMD.def + X1$CMD
X1save = X1
model = "Allvariables"
X1=X1save
####################Create reduced datasets - several options
############Reduce variables to match Wang et al. paper
model = "Wang"
TEMP.list = c("Tmin11","Tmax02","Tmin_sm","Tmax_sp","Tmax_wt","Tmax_sm","Tmax11","Tave_sm","Tmax_at",
"Tmax10","Tmin_wt","Tmin_02","Tave_sp","Tmax05","Tmax01","Tmin12","Tmin_at","Tmax07",
"Tmin10","Tmax08","Tmin06","Tmin05","Tmax09","Tmin01")
PPT.list = c("PPT10","PPT06","PPT12","PPT08","PPT_sm","PPT_sp","PPT_05","PPT_09","PPT_at","PPT07",
"PPT_wt","PPT04","PPT11","PPT01","PPT03","PPT02")
OTHER.list = c("SHM","EMT","PAS")
Variables = c(TEMP.list,PPT.list,OTHER.list)
X1save = X1
List = c("BGC")
X1$BGC <- as.factor(X1$BGC)
X1 = X1[, names(X1) %in% c(List,Variables)]
#######
#### "BioFinal Updated"--Biologically Interpretable Variables Reduced to 25 highest GINI (Will's Version)
model = "BioFinalupdated"
TEMP.list=c("Tmax_sp","Tmin_wt","Tmin_sm","DD5_sp", "MCMT", "EMT", "DD5_06", "TD", "Tmin01")#,"Tmin_at","EXT"
PPT.list=c("PPT06", "PPT_sp","MSP","PAS", "PPT_JAS", "PPT06")
OTHER.list=c("AHM","FFP", "CMD.total", "Eref", "eFFP")
ClimateVar=c(TEMP.list,PPT.list,OTHER.list)
List=c("BGC")
X1save = X1
X1$BGC <- as.factor(X1$BGC)
X1=X1[,names(X1) %in% c(List,ClimateVar)]
save(X1,file=paste(fname,"_Dataset", model,".Rda",sep=""))
load(paste(fname,"_Dataset", model,".Rda",sep=""))
#### "BioFinal"--Biologically Interpretable Variables Reduced to 25 highest GINI
model = "BioFinalOld"
TEMP.list=c("Tmax_sp","Tmin_wt","Tmin_sm","Tmin_at",
"DD5_sp", "MCMT", "EMT","EXT", "DD5_06", "TD")
PPT.list=c("PPT06", "PPT_sp", "PPT_sm","MSP", "MAP","PAS", "PPT_MJ", "PPT_JAS")
OTHER.list=c("AHM","SHM","bFFP","FFP","CMD07", "CMD.total", "Eref")
ClimateVar=c(TEMP.list,PPT.list,OTHER.list)
List=c("BGC")
X1save = X1
X1$BGC <- as.factor(X1$BGC)
X1=X1[,names(X1) %in% c(List,ClimateVar)]
####################Kiri Final Model###################
model = "KiriFinal"
VarList = c("AHM", "bFFP","CMD.total","DD5_sp","EMT","Eref_sm","EXT","FFP","MCMT","MSP",
"PPT_JAS","PPT_MJ","PPT06","SHM","TD","Tmax_sp","Tmin_at","Tmin_sm","Tmin_wt",
"PAS","CMD.def","CMDMax","eFFP","Eref09","MAT","PPT07","Tmin_sp")
##VarList <- readLines("Kiri_FinalVars.csv")
List = c("BGC")
X1save = X1
X1$BGC <- as.factor(X1$BGC)
X1=X1[,names(X1) %in% c(List,VarList)]
###############Build RandomForest Model#################
#BGCmodel standard random forest with trace
set.seed(123321)
ptm <- proc.time()
BGCmodel <- randomForest(BGC ~ ., data=X1, nodesize = 5, do.trace = 10, ntree=101, na.action=na.fail, importance=TRUE, proximity=FALSE)
proc.time() - ptm
##Save output
print(BGCmodel$confusion, digits=2)
Novel <-outlier(BGCmodel, X1)
write.csv(BGCmodel$proximity, file= paste(fname,"_Proximity",model,".csv",sep=""))
write.csv(BGCmodel$importance, file= paste(fname,"_Importance",model,".csv",sep=""))
write.csv(BGCmodel$err.rate, file= paste(fname,"_Error",model,".csv",sep=""))
write.csv(BGCmodel$confusion, file= paste(fname,"_ConfusionMatrix",model,".csv",sep=""))
write.csv(BGCmodel$confusion[, 'class.error'], file= paste(fname,"_Confusion",model,".csv",sep=""))
VIP <- varImpPlot(BGCmodel, sort=TRUE)
write.csv(VIP, file= paste(fname,"_OBO",model,".csv",sep=""))
dev.copy(pdf,(paste(model,'VarImpPlot.pdf')))
dev.off()
#### Save random forest model
file=paste(fname,"_RFmodel",model,".Rdata",sep="")
save(BGCmodel,file=file)
##******OPTIONAL*********##
################Do parallel version to increase speed (but miss out on some model metrics)
set.seed(123321)
coreNo <- makeCluster(detectCores() - 1)
registerDoParallel(coreNo, cores = detectCores() - 1)
Cores <- as.numeric(detectCores()-1)
###runs with all cores - does not produce confusion matrix
ptmcore <- proc.time()
BGCmodel2 <- foreach(ntree=rep(round(150/(Cores)), Cores), .combine=combine, .packages='randomForest') %dopar% {
randomForest(X1$BGC ~ ., data=X1, ntree=ntree, na.action=na.fail, do.trace = 10, importance=TRUE)
}
proc.time() - ptmcore
###BGCmodel from rfsrc (different option)
options(rf.cores=detectCores(), mc.cores=detectCores())
ptm <- proc.time()
BGCmodel <- rfsrc(BGC ~ ., data=X1 , ntree=11, na.action=c("na.omit"), importance=TRUE)
proc.time() - ptm
# Save Confusion matrix
print(BGCmodel$confusion, digits=2)
write.csv(BGCmodel$err.rate, file= paste(fname,"_ErrorBio2v1000_53",".csv",sep=""))
write.csv(BGCmodel$confusion, file= paste(fname,"_ConfusionMatrixBio2v1000_53",".csv",sep=""))
write.csv(BGCmodel$confusion[, 'class.error'], file= paste(fname,"_ConfusionBio2v1000_53",".csv",sep=""))
varImpPlot(BGCmodel, sort=TRUE, n.var=nrow(BGCmodel$importance))
###"RFCV"--Runs iterations to determine how many variables are required for accurancy
ptm <- proc.time()
BGCmodelVar <- rfcv(trainx = X1[,-1], trainy = X1[,1], scale = "log", step=0.5)
proc.time() - ptm
###graph of decrease in error with number of variables
with(BGCmodelVar, plot(n.var, error.cv, type="o", lwd=2, xlim = c(0,40)))
print(BGCmodelVar$predicted)
save(BGCmodelVar$predicted,file=paste(fname,"_VarImp",".JPEG",sep=""))
##### run the next line of code iteratively to find best mtry number
BGCmodel2 <- tuneRF(X1[,-1], X1[,1], mtryStart=5, ntreeTry=151, stepFactor=1.5, improve=0.05,trace=TRUE, plot=TRUE, doBest=FALSE)
##output model variable stats
print(BGCmodel)
varUsed (BGCmodel, by.tree=FALSE, count=TRUE)
round(importance(BGCmodel),2)
varImpPlot(BGCmodel,sort=T,n.var=min(50,nrow(BGCmodel$importance)))
plot(margin(BGCmodel))
###output locations file with original and new BGC predicted
X2$BGC.predict <- BGCmodel$predicted
write.csv(X2, file= paste(fname,"_TrainingPtsPredicted",".csv",sep=""))
###OPTION: Updates the original assignment of BGC from predict model
X1$BGC <- factor (BGCmodel$predicted)
print (BGCmodel$confusion, digits=2)
write.csv(BGCmodel$confusion, file= "AlpineSubzZone_ConfusionMatrix501.csv")
write.csv(BGCmodel$confusion[, 'class.error'], file= "AlpineSubzone_OverallConfusion501.csv")
save(BGCmodel,file=paste(fname,".Rdata",sep=""))
load(paste(fname,".Rdata",sep=""))
| /Build_BGC_RndFor_Model_ver8.R | no_license | FLNRO-Smithers-Research/Tree-Species-Selection-Tool | R | false | false | 9,883 | r | # Ensure that you have working Dataset and BEC Pair Table in your working directory:
# When you start with a new dataset, make sure to follow "When You Have New Dataset" below first:
#set library
.libPaths("E:/R packages")
# Install the following R packages:
install.packages("caret")
install.packages("rattle")
install.packages("rpart")
install.packages("rpart.plot")
install.packages("tcltk")
install.packages("plyr")
install.packages("reshape")
install.packages("reshape2")
install.packages("VSURF")
install.packages("reports")
install.packages("rpart.utils")
install.packages("rfUtilities")
install.packages ("ggplot2")
install.packages ("functional")
install.packages ("plot3D")
install.packages("dplyr")
install.packages("randomForest")
install.packages("ranger")
install.packages("OpenMP")
install.packages ("randomForestSRC")
# Load R packages:
library(rattle)
library(rpart)
library(rpart.plot)
library(plyr)
library(reshape)
library(reshape2)
library(VSURF)
library(reports)
library(rpart.utils)
require(rfUtilities)
library("parallel")
library("foreach")
library("doParallel")
require("ggplot2")
library(functional)
require(plot3D)
library(dplyr)
library(tcltk)
library(caret)
require(randomForest)
require(ranger)
require (OpenMP)
require (randomForestSRC)
require (tools)
######Clear environment and add in dataset############
rm(list=ls())
options(stringsAsFactors = FALSE)
# The codes below need to be run only once when you start with a new dataset #
## Set working directory:
wd=tk_choose.dir()
setwd(wd)
#Use to import multiple datasets
##load 1st climate data set and use file name of dataset as fname
fplot=(file.choose())
Y1=read.csv(fplot,stringsAsFactors=F,na.strings=".")
fname=basename(file_path_sans_ext(fplot))
#Load a second file to merge with Y1, repeat this block with additional files
fplot2=(file.choose())
Y2=read.csv(fplot2,stringsAsFactors=F,na.strings=".")
Y1 <- rbind(Y1, Y2)
X1=Y1
#####Alternate method for import
## Name of ClimateWNA output Model Dataset and Plots to predict Table:
fname="AB2000pts_outputfromWNA"
## Unzip .csv file of a BEC Climate dataset and save and store it in .Rda format:
fpath=paste(wd,"/",fname,".csv",sep="")
X1=read.csv(fpath,stringsAsFactors=FALSE,na.strings=".")
###########################
####modify variable names
colnames(X1)[1]=c("PlotNo")
colnames(X1)[2]=c("BGC")
records <- nrow(X1)
X1$PlotNo <- as.integer(seq(from = 1, to = records, by =1))
attr(X1, "row.names") <- (X1$PlotNo)
X2 <- X1 [, c("PlotNo", "BGC", "Latitude", "Longitude", "Elevation")]
X1=X1[,-c(1,3:5)]
#X1<- as.data.frame(X1)
# Drop
X1$BGC <- as.factor(X1$BGC)
save(X1,file=paste(fname,".Rda",sep=""))
#############################################
############# Reduce to working dataset ######
#############################################
############# Prepare Dataset for Analysis:----
# Load saved RDA Dataset (if .csv not used):
fname="BGCv10_2000Pt_Rnd_Normal_1961_1990MSY"
load(paste(fname,".Rda",sep=""))
#####generate some addtional variables
X1$PPT_MJ <- X1$PPT05 + X1$PPT06 # MaY/June precip
X1$PPT_JAS <- X1$PPT07 + X1$PPT08 + X1$PPT09 # July/Aug/Sept precip
X1$CMDMax <- X1$CMD07
X1$CMD.grow <- X1$CMD05 + X1$CMD06 +X1$CMD07 +X1$CMD08 +X1$CMD09
X1$PPT.dormant <- X1$PPT_at + X1$PPT_wt # for calculating spring deficit
X1$CMD.def <- 500 - (X1$PPT.dormant)# start of growing season deficit original value was 400 but 500 seems better
X1$CMD.def [X1$CMD.def < 0] <- 0 #negative values set to zero = no deficit
X1$CMD.total <- X1$CMD.def + X1$CMD
X1save = X1
model = "Allvariables"
X1=X1save
####################Create reduced datasets - several options
############Reduce variables to match Wang et al. paper
model = "Wang"
TEMP.list = c("Tmin11","Tmax02","Tmin_sm","Tmax_sp","Tmax_wt","Tmax_sm","Tmax11","Tave_sm","Tmax_at",
"Tmax10","Tmin_wt","Tmin_02","Tave_sp","Tmax05","Tmax01","Tmin12","Tmin_at","Tmax07",
"Tmin10","Tmax08","Tmin06","Tmin05","Tmax09","Tmin01")
PPT.list = c("PPT10","PPT06","PPT12","PPT08","PPT_sm","PPT_sp","PPT_05","PPT_09","PPT_at","PPT07",
"PPT_wt","PPT04","PPT11","PPT01","PPT03","PPT02")
OTHER.list = c("SHM","EMT","PAS")
Variables = c(TEMP.list,PPT.list,OTHER.list)
X1save = X1
List = c("BGC")
X1$BGC <- as.factor(X1$BGC)
X1 = X1[, names(X1) %in% c(List,Variables)]
#######
#### "BioFinal Updated"--Biologically Interpretable Variables Reduced to 25 highest GINI (Will's Version)
model = "BioFinalupdated"
TEMP.list=c("Tmax_sp","Tmin_wt","Tmin_sm","DD5_sp", "MCMT", "EMT", "DD5_06", "TD", "Tmin01")#,"Tmin_at","EXT"
PPT.list=c("PPT06", "PPT_sp","MSP","PAS", "PPT_JAS", "PPT06")
OTHER.list=c("AHM","FFP", "CMD.total", "Eref", "eFFP")
ClimateVar=c(TEMP.list,PPT.list,OTHER.list)
List=c("BGC")
X1save = X1
X1$BGC <- as.factor(X1$BGC)
X1=X1[,names(X1) %in% c(List,ClimateVar)]
save(X1,file=paste(fname,"_Dataset", model,".Rda",sep=""))
load(paste(fname,"_Dataset", model,".Rda",sep=""))
#### "BioFinal"--Biologically Interpretable Variables Reduced to 25 highest GINI
model = "BioFinalOld"
TEMP.list=c("Tmax_sp","Tmin_wt","Tmin_sm","Tmin_at",
"DD5_sp", "MCMT", "EMT","EXT", "DD5_06", "TD")
PPT.list=c("PPT06", "PPT_sp", "PPT_sm","MSP", "MAP","PAS", "PPT_MJ", "PPT_JAS")
OTHER.list=c("AHM","SHM","bFFP","FFP","CMD07", "CMD.total", "Eref")
ClimateVar=c(TEMP.list,PPT.list,OTHER.list)
List=c("BGC")
X1save = X1
X1$BGC <- as.factor(X1$BGC)
X1=X1[,names(X1) %in% c(List,ClimateVar)]
####################Kiri Final Model###################
model = "KiriFinal"
VarList = c("AHM", "bFFP","CMD.total","DD5_sp","EMT","Eref_sm","EXT","FFP","MCMT","MSP",
"PPT_JAS","PPT_MJ","PPT06","SHM","TD","Tmax_sp","Tmin_at","Tmin_sm","Tmin_wt",
"PAS","CMD.def","CMDMax","eFFP","Eref09","MAT","PPT07","Tmin_sp")
##VarList <- readLines("Kiri_FinalVars.csv")
List = c("BGC")
X1save = X1
X1$BGC <- as.factor(X1$BGC)
X1=X1[,names(X1) %in% c(List,VarList)]
###############Build RandomForest Model#################
#BGCmodel standard random forest with trace
set.seed(123321)
ptm <- proc.time()
BGCmodel <- randomForest(BGC ~ ., data=X1, nodesize = 5, do.trace = 10, ntree=101, na.action=na.fail, importance=TRUE, proximity=FALSE)
proc.time() - ptm
##Save output
print(BGCmodel$confusion, digits=2)
Novel <-outlier(BGCmodel, X1)
write.csv(BGCmodel$proximity, file= paste(fname,"_Proximity",model,".csv",sep=""))
write.csv(BGCmodel$importance, file= paste(fname,"_Importance",model,".csv",sep=""))
write.csv(BGCmodel$err.rate, file= paste(fname,"_Error",model,".csv",sep=""))
write.csv(BGCmodel$confusion, file= paste(fname,"_ConfusionMatrix",model,".csv",sep=""))
write.csv(BGCmodel$confusion[, 'class.error'], file= paste(fname,"_Confusion",model,".csv",sep=""))
VIP <- varImpPlot(BGCmodel, sort=TRUE)
write.csv(VIP, file= paste(fname,"_OBO",model,".csv",sep=""))
dev.copy(pdf,(paste(model,'VarImpPlot.pdf')))
dev.off()
#### Save random forest model
file=paste(fname,"_RFmodel",model,".Rdata",sep="")
save(BGCmodel,file=file)
##******OPTIONAL*********##
################Do parallel version to increase speed (but miss out on some model metrics)
set.seed(123321)
coreNo <- makeCluster(detectCores() - 1)
registerDoParallel(coreNo, cores = detectCores() - 1)
Cores <- as.numeric(detectCores()-1)
###runs with all cores - does not produce confusion matrix
ptmcore <- proc.time()
BGCmodel2 <- foreach(ntree=rep(round(150/(Cores)), Cores), .combine=combine, .packages='randomForest') %dopar% {
randomForest(X1$BGC ~ ., data=X1, ntree=ntree, na.action=na.fail, do.trace = 10, importance=TRUE)
}
proc.time() - ptmcore
###BGCmodel from rfsrc (different option)
options(rf.cores=detectCores(), mc.cores=detectCores())
ptm <- proc.time()
BGCmodel <- rfsrc(BGC ~ ., data=X1 , ntree=11, na.action=c("na.omit"), importance=TRUE)
proc.time() - ptm
# Save Confusion matrix
print(BGCmodel$confusion, digits=2)
write.csv(BGCmodel$err.rate, file= paste(fname,"_ErrorBio2v1000_53",".csv",sep=""))
write.csv(BGCmodel$confusion, file= paste(fname,"_ConfusionMatrixBio2v1000_53",".csv",sep=""))
write.csv(BGCmodel$confusion[, 'class.error'], file= paste(fname,"_ConfusionBio2v1000_53",".csv",sep=""))
varImpPlot(BGCmodel, sort=TRUE, n.var=nrow(BGCmodel$importance))
###"RFCV"--Runs iterations to determine how many variables are required for accurancy
ptm <- proc.time()
BGCmodelVar <- rfcv(trainx = X1[,-1], trainy = X1[,1], scale = "log", step=0.5)
proc.time() - ptm
###graph of decrease in error with number of variables
with(BGCmodelVar, plot(n.var, error.cv, type="o", lwd=2, xlim = c(0,40)))
print(BGCmodelVar$predicted)
save(BGCmodelVar$predicted,file=paste(fname,"_VarImp",".JPEG",sep=""))
##### run the next line of code iteratively to find best mtry number
BGCmodel2 <- tuneRF(X1[,-1], X1[,1], mtryStart=5, ntreeTry=151, stepFactor=1.5, improve=0.05,trace=TRUE, plot=TRUE, doBest=FALSE)
##output model variable stats
print(BGCmodel)
varUsed (BGCmodel, by.tree=FALSE, count=TRUE)
round(importance(BGCmodel),2)
varImpPlot(BGCmodel,sort=T,n.var=min(50,nrow(BGCmodel$importance)))
plot(margin(BGCmodel))
###output locations file with original and new BGC predicted
X2$BGC.predict <- BGCmodel$predicted
write.csv(X2, file= paste(fname,"_TrainingPtsPredicted",".csv",sep=""))
###OPTION: Updates the original assignment of BGC from predict model
X1$BGC <- factor (BGCmodel$predicted)
print (BGCmodel$confusion, digits=2)
write.csv(BGCmodel$confusion, file= "AlpineSubzZone_ConfusionMatrix501.csv")
write.csv(BGCmodel$confusion[, 'class.error'], file= "AlpineSubzone_OverallConfusion501.csv")
save(BGCmodel,file=paste(fname,".Rdata",sep=""))
load(paste(fname,".Rdata",sep=""))
|
# This script converts the raw experimental data into the cleaned files that appear in experiment/data. The raw data aren't included in this repository so it's not possible to actually run this script -- but it's included to document the processing pipeline.
# Use tidyverse
library(dplyr)
library(tidyverse)
library(here)
d <- read.csv(here("experiments", "data", "raw_data", "results_exp_pictographic_ratings_oracle_printedtraditional.csv")) %>%
pull("content") %>% # retain only the content vector
as.character() %>%
stringi::stri_remove_empty() %>% # in case we have an empty entry
map(read_csv, col_types = cols(.default = "c")) %>% # map each element to a tibble
reduce(bind_rows) %>% # take the list of tibbles and collapse to one tibble
mutate(rownum = row_number()) %>%
mutate(imgpair= str_extract_all(stimulus, "(?<=img/).+?(?=.png)")) %>%
mutate(imgpair= map(imgpair, toString)) %>%
separate(imgpair, c("left", "right"), sep=",") %>%
select(turkcode, left, right, button_pressed, trial_type, responses, rownum, endperiod) %>%
group_by(turkcode) %>%
mutate(participantid = cur_group_id()) %>%
ungroup() %>%
select(-turkcode) %>%
filter(! is.na(right) | ! is.na(responses) ) %>%
separate(left, c("character", "leftver", "c1", "c2", "cleftver"), sep="_", extra = "merge", remove=FALSE) %>%
separate(right, c(NA, "rightver", NA, NA, "crightver"), sep="_", extra = "merge", remove=FALSE) %>%
unite(cc, c(c1, c2), remove=FALSE) %>%
mutate(character = if_else(is.na(c1), character, paste("control", cc, sep="_"))) %>%
mutate(leftver = if_else(is.na(c1), leftver, cleftver)) %>%
mutate(rightver = if_else(is.na(c1), rightver, crightver)) %>%
select(-cc, -c1, -c2, -cleftver, -crightver, -left, -right)
responses <- d %>%
filter(trial_type =="survey-text" & responses != '{"Q0":""}') %>%
select(responses)
print(responses$responses)
responses %>% write_csv(here("experiments", "data", "commentsplaceholder.csv"))
ratings <- d %>%
filter(!(is.na(character)) & character != "NA") %>%
select(-trial_type, -responses) %>%
group_by(participantid) %>%
mutate(trialnum = rank(rownum)) %>%
ungroup() %>%
rename(rating=button_pressed) %>%
rename(condition=endperiod) %>%
arrange(participantid, trialnum) %>%
mutate(rating = if_else(leftver != "oracle", 5 - as.numeric(rating), as.numeric(rating))) %>%
mutate(flip = if_else(leftver != "oracle", "flip", "noflip")) %>%
select(-leftver, -rightver) %>%
mutate( controlcorrect = if_else( str_detect(character, "^control_") & rating >= 3, 1, 0) ) %>%
group_by(participantid) %>%
mutate(controlscore = sum(controlcorrect) ) %>%
ungroup() %>%
select(participantid, condition, trialnum, character, rating, flip, controlscore, -controlcorrect, -rownum)
ratings %>% write_csv(here("experiments", "data", "placeholder.csv"))
| /experiment/preprocessing/preprocess_pictographic_ratings.R | permissive | cskemp/chinesecharacters | R | false | false | 2,935 | r | # This script converts the raw experimental data into the cleaned files that appear in experiment/data. The raw data aren't included in this repository so it's not possible to actually run this script -- but it's included to document the processing pipeline.
# Use tidyverse
library(dplyr)
library(tidyverse)
library(here)
d <- read.csv(here("experiments", "data", "raw_data", "results_exp_pictographic_ratings_oracle_printedtraditional.csv")) %>%
pull("content") %>% # retain only the content vector
as.character() %>%
stringi::stri_remove_empty() %>% # in case we have an empty entry
map(read_csv, col_types = cols(.default = "c")) %>% # map each element to a tibble
reduce(bind_rows) %>% # take the list of tibbles and collapse to one tibble
mutate(rownum = row_number()) %>%
mutate(imgpair= str_extract_all(stimulus, "(?<=img/).+?(?=.png)")) %>%
mutate(imgpair= map(imgpair, toString)) %>%
separate(imgpair, c("left", "right"), sep=",") %>%
select(turkcode, left, right, button_pressed, trial_type, responses, rownum, endperiod) %>%
group_by(turkcode) %>%
mutate(participantid = cur_group_id()) %>%
ungroup() %>%
select(-turkcode) %>%
filter(! is.na(right) | ! is.na(responses) ) %>%
separate(left, c("character", "leftver", "c1", "c2", "cleftver"), sep="_", extra = "merge", remove=FALSE) %>%
separate(right, c(NA, "rightver", NA, NA, "crightver"), sep="_", extra = "merge", remove=FALSE) %>%
unite(cc, c(c1, c2), remove=FALSE) %>%
mutate(character = if_else(is.na(c1), character, paste("control", cc, sep="_"))) %>%
mutate(leftver = if_else(is.na(c1), leftver, cleftver)) %>%
mutate(rightver = if_else(is.na(c1), rightver, crightver)) %>%
select(-cc, -c1, -c2, -cleftver, -crightver, -left, -right)
responses <- d %>%
filter(trial_type =="survey-text" & responses != '{"Q0":""}') %>%
select(responses)
print(responses$responses)
responses %>% write_csv(here("experiments", "data", "commentsplaceholder.csv"))
ratings <- d %>%
filter(!(is.na(character)) & character != "NA") %>%
select(-trial_type, -responses) %>%
group_by(participantid) %>%
mutate(trialnum = rank(rownum)) %>%
ungroup() %>%
rename(rating=button_pressed) %>%
rename(condition=endperiod) %>%
arrange(participantid, trialnum) %>%
mutate(rating = if_else(leftver != "oracle", 5 - as.numeric(rating), as.numeric(rating))) %>%
mutate(flip = if_else(leftver != "oracle", "flip", "noflip")) %>%
select(-leftver, -rightver) %>%
mutate( controlcorrect = if_else( str_detect(character, "^control_") & rating >= 3, 1, 0) ) %>%
group_by(participantid) %>%
mutate(controlscore = sum(controlcorrect) ) %>%
ungroup() %>%
select(participantid, condition, trialnum, character, rating, flip, controlscore, -controlcorrect, -rownum)
ratings %>% write_csv(here("experiments", "data", "placeholder.csv"))
|
% Generated by roxygen2 (4.1.1): do not edit by hand
% Please edit documentation in R/JSTOR_clusterbywords.R
\name{JSTOR_clusterbywords}
\alias{JSTOR_clusterbywords}
\title{Cluster documents by similarities in word frequencies}
\usage{
JSTOR_clusterbywords(nouns, word, custom_stopwords = NULL, f = 0.01)
}
\arguments{
\item{nouns}{the object returned by the function JSTOR_dtmofnouns. A corpus containing the documents with stopwords removed.}
\item{word}{The word or vector of words to subset the documents by, ie. use only documents containing this word (or words) in the cluster analysis}
\item{f}{A scalar value to filter the total number of words used in the cluster analyses. For each document, the count of each word is divided by the total number of words in that document, expressing a word's frequency as a proportion of all words in that document. This parameter corresponds to the summed proportions of a word in all documents (ie. the column sum for the document term matrix). If f = 0.01 then only words that constitute at least 1.0 percent of all words in all documents will be used for the cluster analyses.}
}
\value{
Returns plots of clusters of documents, and dataframes of affinity propogation clustering, k-means and PCA outputs
}
\description{
Generates plots visualizing the results of different clustering methods applied to the documents. For use with JSTOR's Data for Research datasets (http://dfr.jstor.org/). For best results, repeat the function several times after adding common words to the stopword list and excluding them using the JSTOR_removestopwords function.
}
\examples{
## cl1 <- JSTOR_clusterbywords(nouns, "pirates")
## cl2 <- JSTOR_clusterbywords(nouns, c("pirates", "privateers"))
}
| /man/JSTOR_clusterbywords.Rd | no_license | brooksambrose/JSTORr | R | false | false | 1,731 | rd | % Generated by roxygen2 (4.1.1): do not edit by hand
% Please edit documentation in R/JSTOR_clusterbywords.R
\name{JSTOR_clusterbywords}
\alias{JSTOR_clusterbywords}
\title{Cluster documents by similarities in word frequencies}
\usage{
JSTOR_clusterbywords(nouns, word, custom_stopwords = NULL, f = 0.01)
}
\arguments{
\item{nouns}{the object returned by the function JSTOR_dtmofnouns. A corpus containing the documents with stopwords removed.}
\item{word}{The word or vector of words to subset the documents by, ie. use only documents containing this word (or words) in the cluster analysis}
\item{f}{A scalar value to filter the total number of words used in the cluster analyses. For each document, the count of each word is divided by the total number of words in that document, expressing a word's frequency as a proportion of all words in that document. This parameter corresponds to the summed proportions of a word in all documents (ie. the column sum for the document term matrix). If f = 0.01 then only words that constitute at least 1.0 percent of all words in all documents will be used for the cluster analyses.}
}
\value{
Returns plots of clusters of documents, and dataframes of affinity propogation clustering, k-means and PCA outputs
}
\description{
Generates plots visualizing the results of different clustering methods applied to the documents. For use with JSTOR's Data for Research datasets (http://dfr.jstor.org/). For best results, repeat the function several times after adding common words to the stopword list and excluding them using the JSTOR_removestopwords function.
}
\examples{
## cl1 <- JSTOR_clusterbywords(nouns, "pirates")
## cl2 <- JSTOR_clusterbywords(nouns, c("pirates", "privateers"))
}
|
context("wflow_build")
# Setup ------------------------------------------------------------------------
library(workflowr)
# start project in a tempdir
site_dir <- tempfile("test-wflow_build-")
suppressMessages(wflow_start(site_dir, change_wd = FALSE, user.name = "Test Name",
user.email = "test@email"))
on.exit(unlink(site_dir, recursive = TRUE, force = TRUE))
site_dir <- workflowr:::absolute(site_dir)
s <- wflow_status(project = site_dir)
rmd <- rownames(s$status)
stopifnot(length(rmd) > 0)
# Expected html files
html <- workflowr:::to_html(rmd, outdir = s$docs)
# Test wflow_build -------------------------------------------------------------
test_that("wflow_build deletes cache when delete_cache = TRUE", {
skip_on_cran()
# Build a file that has cached chunks
file_w_cache <- file.path(s$analysis, "cache.Rmd")
fs::file_copy("cache-all-chunks.Rmd", file_w_cache)
build_v01 <- wflow_build(file_w_cache, view = FALSE, project = site_dir)
dir_cache <- fs::path_ext_remove(file_w_cache)
dir_cache <- glue::glue("{dir_cache}_cache")
expect_true(fs::dir_exists(dir_cache))
# By default, cache directory is not affected
dir_cache_mod_pre <- fs::file_info(dir_cache)$modification_time
expect_message(
build_v02 <- wflow_build(file_w_cache, view = FALSE, project = site_dir),
" - Note: This file has a cache directory"
)
expect_false(build_v02$delete_cache)
expect_true(fs::dir_exists(dir_cache))
dir_cache_mod_post <- fs::file_info(dir_cache)$modification_time
expect_equal(dir_cache_mod_post, dir_cache_mod_pre)
# delete_cache deletes cache directory prior to building (it gets re-created)
# problem <- fs::path(
# dir_cache,
# "html",
# "session-info-chunk-inserted-by-workflowr_dcb4b1f4c87754270381f62dd2d3f529.RData"
# )
expect_true(fs::dir_exists(dir_cache))
expect_true(fs::dir_exists(fs::path(dir_cache, "html")))
session_info_files <- fs::dir_ls(path = fs::path(dir_cache, "html"),
regexp = "session-info")
expect_equal(length(session_info_files), 6)
expect_true(fs::dir_exists(dir_cache))
problem <- fs::path(dir_cache, "html/session-info-chunk-inserted-by-workflowr_dcb4b1f4c87754270381f62dd2d3f529.rdb")
expect_true(fs::file_exists(problem))
dir_cache_mod_pre <- fs::file_info(dir_cache)$modification_time
expect_message(
build_v03 <- wflow_build(file_w_cache, view = FALSE, delete_cache = TRUE,
project = site_dir),
" - Note: Deleted the cache directory before building"
)
expect_true(build_v03$delete_cache)
expect_true(fs::dir_exists(dir_cache))
dir_cache_mod_post <- fs::file_info(dir_cache)$modification_time
expect_true(dir_cache_mod_post > dir_cache_mod_pre)
# Cleanup
wflow_remove(file_w_cache, project = site_dir)
})
| /tests/testthat/test-wflow_build.R | permissive | jdblischak/fsDirDeleteError | R | false | false | 2,842 | r | context("wflow_build")
# Setup ------------------------------------------------------------------------
library(workflowr)
# start project in a tempdir
site_dir <- tempfile("test-wflow_build-")
suppressMessages(wflow_start(site_dir, change_wd = FALSE, user.name = "Test Name",
user.email = "test@email"))
on.exit(unlink(site_dir, recursive = TRUE, force = TRUE))
site_dir <- workflowr:::absolute(site_dir)
s <- wflow_status(project = site_dir)
rmd <- rownames(s$status)
stopifnot(length(rmd) > 0)
# Expected html files
html <- workflowr:::to_html(rmd, outdir = s$docs)
# Test wflow_build -------------------------------------------------------------
test_that("wflow_build deletes cache when delete_cache = TRUE", {
skip_on_cran()
# Build a file that has cached chunks
file_w_cache <- file.path(s$analysis, "cache.Rmd")
fs::file_copy("cache-all-chunks.Rmd", file_w_cache)
build_v01 <- wflow_build(file_w_cache, view = FALSE, project = site_dir)
dir_cache <- fs::path_ext_remove(file_w_cache)
dir_cache <- glue::glue("{dir_cache}_cache")
expect_true(fs::dir_exists(dir_cache))
# By default, cache directory is not affected
dir_cache_mod_pre <- fs::file_info(dir_cache)$modification_time
expect_message(
build_v02 <- wflow_build(file_w_cache, view = FALSE, project = site_dir),
" - Note: This file has a cache directory"
)
expect_false(build_v02$delete_cache)
expect_true(fs::dir_exists(dir_cache))
dir_cache_mod_post <- fs::file_info(dir_cache)$modification_time
expect_equal(dir_cache_mod_post, dir_cache_mod_pre)
# delete_cache deletes cache directory prior to building (it gets re-created)
# problem <- fs::path(
# dir_cache,
# "html",
# "session-info-chunk-inserted-by-workflowr_dcb4b1f4c87754270381f62dd2d3f529.RData"
# )
expect_true(fs::dir_exists(dir_cache))
expect_true(fs::dir_exists(fs::path(dir_cache, "html")))
session_info_files <- fs::dir_ls(path = fs::path(dir_cache, "html"),
regexp = "session-info")
expect_equal(length(session_info_files), 6)
expect_true(fs::dir_exists(dir_cache))
problem <- fs::path(dir_cache, "html/session-info-chunk-inserted-by-workflowr_dcb4b1f4c87754270381f62dd2d3f529.rdb")
expect_true(fs::file_exists(problem))
dir_cache_mod_pre <- fs::file_info(dir_cache)$modification_time
expect_message(
build_v03 <- wflow_build(file_w_cache, view = FALSE, delete_cache = TRUE,
project = site_dir),
" - Note: Deleted the cache directory before building"
)
expect_true(build_v03$delete_cache)
expect_true(fs::dir_exists(dir_cache))
dir_cache_mod_post <- fs::file_info(dir_cache)$modification_time
expect_true(dir_cache_mod_post > dir_cache_mod_pre)
# Cleanup
wflow_remove(file_w_cache, project = site_dir)
})
|
context("Testing pfr's peer()")
test_that("peer with D2 penalty", {
skip_on_cran()
data(DTI)
DTI = DTI[which(DTI$case == 1),]
fit.D2 <- pfr(pasat ~ peer(cca, pentype="D"), data=DTI)
expect_is(fit.D2, "pfr")
})
test_that("peer with structured penalty works", {
skip_on_cran()
data(PEER.Sim, Q)
# Setting k to max possible value
fit.decomp <- pfr(Y ~ peer(W, pentype="Decomp", Q=Q, k=99),
data=subset(PEER.Sim, t==0))
expect_is(fit.decomp, "pfr")
}) | /tests/testthat/test-peer.R | no_license | refunders/refund | R | false | false | 492 | r | context("Testing pfr's peer()")
test_that("peer with D2 penalty", {
skip_on_cran()
data(DTI)
DTI = DTI[which(DTI$case == 1),]
fit.D2 <- pfr(pasat ~ peer(cca, pentype="D"), data=DTI)
expect_is(fit.D2, "pfr")
})
test_that("peer with structured penalty works", {
skip_on_cran()
data(PEER.Sim, Q)
# Setting k to max possible value
fit.decomp <- pfr(Y ~ peer(W, pentype="Decomp", Q=Q, k=99),
data=subset(PEER.Sim, t==0))
expect_is(fit.decomp, "pfr")
}) |
kaptár=dir("méhészet")
# teszt
for (segéd in 1:3) {
kaptár1=read.csv(paste("méhészet",kaptár[segéd],sep="/"),encoding="latin1")
print(summary(kaptár1[,3]))
}
# lista
kaptárlista=list()
for (segéd in 1:3) {
kaptárlista[[segéd]]=read.csv(paste("méhészet",kaptár[segéd],sep="/"),encoding="latin1")
}
(summary(kaptárlista[[2]][,3]))
# lista
for (segéd in 1:length(kaptár)) {
assign(paste0("kaptár",segéd),read.csv(paste("méhészet",kaptár[segéd],sep="/"),encoding="latin1"))
}
| /beolvasás.R | no_license | emese95/kaptar | R | false | false | 511 | r | kaptár=dir("méhészet")
# teszt
for (segéd in 1:3) {
kaptár1=read.csv(paste("méhészet",kaptár[segéd],sep="/"),encoding="latin1")
print(summary(kaptár1[,3]))
}
# lista
kaptárlista=list()
for (segéd in 1:3) {
kaptárlista[[segéd]]=read.csv(paste("méhészet",kaptár[segéd],sep="/"),encoding="latin1")
}
(summary(kaptárlista[[2]][,3]))
# lista
for (segéd in 1:length(kaptár)) {
assign(paste0("kaptár",segéd),read.csv(paste("méhészet",kaptár[segéd],sep="/"),encoding="latin1"))
}
|
# optimisation
# prerun the model with glm to find some parameter values that are not jointly constrained
# use logits
model = function(params, dat, step= 1)
{
st0 = dat$st0
st1 = dat$st1
ET = dat$ET
EB = dat$EB
EM = dat$EM
ENV1 = dat$ENV1
ENV2 = dat$ENV2
itime = dat$itime
names(params) = c("ab0", "ab1", "ab2", "ab3","ab4",
"at0", "at1" , "at2", "at3", "at4",
"bb0", "bb1", "bb2", "bb3", "bb4",
"bt0", "bt1", "bt2", "bt3", "bt4",
"tt0", "tt1", "tt2", "tt3", "tt4",
"th0", "th1", "th2", "th3", "th4",
"e0", "e1", "e2", "e3", "e4")
lik = numeric(length(st0))
alphab = params["ab0"] + params["ab1"]*ENV1 + params["ab2"]*ENV2 + params["ab3"]*ENV1^2 + params["ab4"]*ENV2^2
alphat = params["at0"] + params["at1"]*ENV1 + params["at2"]*ENV2 + params["at3"]*ENV1^2 + params["at4"]*ENV2^2
betab = params["bb0"] + params["bb1"]*ENV1 + params["bb2"]*ENV2 + params["bb3"]*ENV1^2 + params["bb4"]*ENV2^2
betat = params["bt0"] + params["bt1"]*ENV1 + params["bt2"]*ENV2 + params["bt3"]*ENV1^2 + params["bt4"]*ENV2^2
theta = params["th0"] + params["th1"]*ENV1 + params["th2"]*ENV2 + params["th3"]*ENV1^2 + params["th4"]*ENV2^2
thetat = params["tt0"] + params["tt1"]*ENV1 + params["tt2"]*ENV2 + params["tt3"]*ENV1^2 + params["tt4"]*ENV2^2
eps = params["e0"] + params["e1"]*ENV1 + params["e2"]*ENV2 + params["e3"]*ENV1^2 + params["e4"]*ENV2^2
# Compute the likelihood of observations
pBM = (betat*(ET+EM)*(1-eps))
pBR = eps
pBB = (1 - eps - betat*(ET+EM)*(1-eps))
pTT = (1 - eps - betab*(EB+EM)*(1-eps))
pTM = (betab*(EB+EM)*(1-eps))
pTR = eps
pMB = (theta*(1-thetat)*(1-eps))
pMT= (theta*thetat*(1-eps))
pMM = ((1 - eps)*(1 - theta))
pMR = eps
phib = alphab*(EM + EB)*(1-alphat*(ET+EM))
phit = alphat*(EM + ET)*(1-alphab*(EB+EM))
phim = alphab*(EM + EB)*alphat*(EM + ET)
lik[st0 == "R" & st1 == "B"] = phib[st0 == "R" & st1 == "B"]
lik[st0 == "R" & st1 == "T"] = phit[st0 == "R" & st1 == "T"]
lik[st0 == "R" & st1 == "M"] = phim[st0 == "R" & st1 == "M"]
lik[st0 == "R" & st1 == "R"] = (1 - phib - phit - phim)[st0 == "R" & st1 == "R"]
# lik might be <0 !!!!
# for T->T, M->M, B->B and R->R transitions
# it will give NaN when log
# lik might be equal = 0 -> give -Inf at log
# for instance when neighbor (seeds) = 0
#lik[lik == 0] = .Machine$double.xmin
# calculate sum log likelihood
# lik might be <0 (in the 1 - other proba)
# if(sum(lik<0)>0)
# {
# sumLL = -.Machine$double.xmax
# }else{
sumLL = sum(log(lik))
# }
if(is.infinite(sumLL)) sumLL = -.Machine$double.xmax
if(is.nan(sumLL)) sumLL = -.Machine$double.xmax
if(is.na(sumLL)) print("sumLL: na values!")
# print(sumLL)
# return a value to minimize in GenSA
return(-sumLL)
}
#-----------------------------------------------------------------------------
| /5-Validation/model.r | no_license | QUICC-FOR/STModel-CompAnalysis | R | false | false | 2,917 | r | # optimisation
# prerun the model with glm to find some parameter values that are not jointly constrained
# use logits
model = function(params, dat, step= 1)
{
st0 = dat$st0
st1 = dat$st1
ET = dat$ET
EB = dat$EB
EM = dat$EM
ENV1 = dat$ENV1
ENV2 = dat$ENV2
itime = dat$itime
names(params) = c("ab0", "ab1", "ab2", "ab3","ab4",
"at0", "at1" , "at2", "at3", "at4",
"bb0", "bb1", "bb2", "bb3", "bb4",
"bt0", "bt1", "bt2", "bt3", "bt4",
"tt0", "tt1", "tt2", "tt3", "tt4",
"th0", "th1", "th2", "th3", "th4",
"e0", "e1", "e2", "e3", "e4")
lik = numeric(length(st0))
alphab = params["ab0"] + params["ab1"]*ENV1 + params["ab2"]*ENV2 + params["ab3"]*ENV1^2 + params["ab4"]*ENV2^2
alphat = params["at0"] + params["at1"]*ENV1 + params["at2"]*ENV2 + params["at3"]*ENV1^2 + params["at4"]*ENV2^2
betab = params["bb0"] + params["bb1"]*ENV1 + params["bb2"]*ENV2 + params["bb3"]*ENV1^2 + params["bb4"]*ENV2^2
betat = params["bt0"] + params["bt1"]*ENV1 + params["bt2"]*ENV2 + params["bt3"]*ENV1^2 + params["bt4"]*ENV2^2
theta = params["th0"] + params["th1"]*ENV1 + params["th2"]*ENV2 + params["th3"]*ENV1^2 + params["th4"]*ENV2^2
thetat = params["tt0"] + params["tt1"]*ENV1 + params["tt2"]*ENV2 + params["tt3"]*ENV1^2 + params["tt4"]*ENV2^2
eps = params["e0"] + params["e1"]*ENV1 + params["e2"]*ENV2 + params["e3"]*ENV1^2 + params["e4"]*ENV2^2
# Compute the likelihood of observations
pBM = (betat*(ET+EM)*(1-eps))
pBR = eps
pBB = (1 - eps - betat*(ET+EM)*(1-eps))
pTT = (1 - eps - betab*(EB+EM)*(1-eps))
pTM = (betab*(EB+EM)*(1-eps))
pTR = eps
pMB = (theta*(1-thetat)*(1-eps))
pMT= (theta*thetat*(1-eps))
pMM = ((1 - eps)*(1 - theta))
pMR = eps
phib = alphab*(EM + EB)*(1-alphat*(ET+EM))
phit = alphat*(EM + ET)*(1-alphab*(EB+EM))
phim = alphab*(EM + EB)*alphat*(EM + ET)
lik[st0 == "R" & st1 == "B"] = phib[st0 == "R" & st1 == "B"]
lik[st0 == "R" & st1 == "T"] = phit[st0 == "R" & st1 == "T"]
lik[st0 == "R" & st1 == "M"] = phim[st0 == "R" & st1 == "M"]
lik[st0 == "R" & st1 == "R"] = (1 - phib - phit - phim)[st0 == "R" & st1 == "R"]
# lik might be <0 !!!!
# for T->T, M->M, B->B and R->R transitions
# it will give NaN when log
# lik might be equal = 0 -> give -Inf at log
# for instance when neighbor (seeds) = 0
#lik[lik == 0] = .Machine$double.xmin
# calculate sum log likelihood
# lik might be <0 (in the 1 - other proba)
# if(sum(lik<0)>0)
# {
# sumLL = -.Machine$double.xmax
# }else{
sumLL = sum(log(lik))
# }
if(is.infinite(sumLL)) sumLL = -.Machine$double.xmax
if(is.nan(sumLL)) sumLL = -.Machine$double.xmax
if(is.na(sumLL)) print("sumLL: na values!")
# print(sumLL)
# return a value to minimize in GenSA
return(-sumLL)
}
#-----------------------------------------------------------------------------
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/layout.R
\name{add_layout_}
\alias{add_layout_}
\title{Add layout to graph}
\usage{
add_layout_(graph, ..., overwrite = TRUE)
}
\arguments{
\item{graph}{The input graph.}
\item{...}{Additional arguments are passed to \code{\link{layout_}}.}
\item{overwrite}{Whether to overwrite the layout of the graph,
if it already has one.}
}
\value{
The input graph, with the layout added.
}
\description{
Add layout to graph
}
\examples{
(make_star(11) + make_star(11)) \%>\%
add_layout_(as_star(), component_wise()) \%>\%
plot()
}
\seealso{
\code{\link{layout_}} for a description of the layout API.
Other graph layouts:
\code{\link{component_wise}()},
\code{\link{layout_as_bipartite}()},
\code{\link{layout_as_star}()},
\code{\link{layout_as_tree}()},
\code{\link{layout_in_circle}()},
\code{\link{layout_nicely}()},
\code{\link{layout_on_grid}()},
\code{\link{layout_on_sphere}()},
\code{\link{layout_randomly}()},
\code{\link{layout_with_dh}()},
\code{\link{layout_with_fr}()},
\code{\link{layout_with_gem}()},
\code{\link{layout_with_graphopt}()},
\code{\link{layout_with_kk}()},
\code{\link{layout_with_lgl}()},
\code{\link{layout_with_mds}()},
\code{\link{layout_with_sugiyama}()},
\code{\link{layout_}()},
\code{\link{merge_coords}()},
\code{\link{norm_coords}()},
\code{\link{normalize}()}
}
\concept{graph layouts}
| /man/add_layout_.Rd | no_license | DavisVaughan/rigraph | R | false | true | 1,401 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/layout.R
\name{add_layout_}
\alias{add_layout_}
\title{Add layout to graph}
\usage{
add_layout_(graph, ..., overwrite = TRUE)
}
\arguments{
\item{graph}{The input graph.}
\item{...}{Additional arguments are passed to \code{\link{layout_}}.}
\item{overwrite}{Whether to overwrite the layout of the graph,
if it already has one.}
}
\value{
The input graph, with the layout added.
}
\description{
Add layout to graph
}
\examples{
(make_star(11) + make_star(11)) \%>\%
add_layout_(as_star(), component_wise()) \%>\%
plot()
}
\seealso{
\code{\link{layout_}} for a description of the layout API.
Other graph layouts:
\code{\link{component_wise}()},
\code{\link{layout_as_bipartite}()},
\code{\link{layout_as_star}()},
\code{\link{layout_as_tree}()},
\code{\link{layout_in_circle}()},
\code{\link{layout_nicely}()},
\code{\link{layout_on_grid}()},
\code{\link{layout_on_sphere}()},
\code{\link{layout_randomly}()},
\code{\link{layout_with_dh}()},
\code{\link{layout_with_fr}()},
\code{\link{layout_with_gem}()},
\code{\link{layout_with_graphopt}()},
\code{\link{layout_with_kk}()},
\code{\link{layout_with_lgl}()},
\code{\link{layout_with_mds}()},
\code{\link{layout_with_sugiyama}()},
\code{\link{layout_}()},
\code{\link{merge_coords}()},
\code{\link{norm_coords}()},
\code{\link{normalize}()}
}
\concept{graph layouts}
|
rm(list=ls(all=TRUE))
setwd("C:/Users/Hai/Desktop/insofe/Cute3")
library(caret)
library(DMwR)
#bankdata=read.csv("UniversalBank.csv", header=TRUE, sep=",")
data=read.csv("train.csv", header=TRUE, sep=",",na.strings=c("","NA"))
str(data)
dat2 <- read.csv("train.csv", header=T, na.strings=c("","NA"))
str(data)
test=read.csv("test.csv",header=TRUE,sep=",",na.strings=c("","NA"))
str(test)
#OBJECTIVE: Will a person take a personal loan or not?
#Response variable is "Personal.Loan"
# Understanding the data
# summary(bankdata)
# str(bankdata)
# head(bankdata)
dim(data)
#53631*51
head(data)
names(data)
str(data)
summary(data)
#cat_var_1 NA's : 2426,cat_var_3
dim(test)
#53545*50
summary(test)
str(test)
## Remove columns which does not add any information
x=nearZeroVar(data,names=TRUE)
# reduced to 29 variables
data=data[,setdiff(names(data),x)]
dim(data)
str(data)
summary(data)
test=test[,setdiff(names(test),x)]
dim(data)
#53631 29
summary(test)
##Check for Missing Values
sum(is.na(data))
#26126
sum(is.na(test))
#25803
# II. Find Number of missing values and drop a row if it contains more than 20% of columns contains missing values. Impute the remining.
sum(is.na(data))
length(manyNAs(data, 0.2) )
ExcludedMissing= data[!rowSums(is.na(data)) > ncol(data)*.2,]
sum(is.na(ExcludedMissing))
#library(aCRM)
ImputedData=centralImputation(ExcludedMissing)
sum(is.na(ImputedData))
# need to do according to train data mean(numeric) & mode(cat)
sum(is.na(test))
length(manyNAs(test, 0.2) )
ExcludedMissingTest= test[!rowSums(is.na(test)) > ncol(test)*.2,]
sum(is.na(ExcludedMissingTest))
ImputedTest=centralImputation(ExcludedMissingTest)
sum(is.na(ImputedTest))
#28 variables
#drop id
ImputedDataRemovedId=ImputedData
ImputedDataRemovedId$transaction_id=NULL
#ImputedDataRemovedIdandName$Itemname=NULL
sum(is.na(ImputedDataRemovedId))
str(ImputedDataRemovedId)
summary(ImputedDataRemovedId)
ImputedTestRemovedId=ImputedTest
ImputedTestRemovedId$transaction_id=NULL
sum(is.na(ImputedTestRemovedId))
str(ImputedTestRemovedId)
summary(ImputedTestRemovedId)
# # Removing unnecessary columns ID and zipcode
# bankdata=subset(bankdata, select=-c(ID,ZIP.Code))
#
# # Do necessary type conversions
# bankdata$Education=as.factor(as.character(bankdata$Education))
# bankdata$Personal.Loan=as.factor(as.character(bankdata$Personal.Loan))
# Do Train-Test Split
library(caret)
set.seed(125)
rows=createDataPartition(ImputedDataRemovedId$target,p = 0.7,list = FALSE)
train=ImputedDataRemovedId[rows,]
val=ImputedDataRemovedId[-rows,]
# PreProcess the data to standadize the numeric attributes
preProc<-preProcess(train[,setdiff(names(train),"target")],method = c("center", "scale"))
train<-predict(preProc,train)
val<-predict(preProc,val)
###create dummies for factor varibales
dummies <- dummyVars(target~., data = ImputedDataRemovedId)
x.train=predict(dummies, newdata = train)
y.train=train$target
x.val = predict(dummies, newdata = val)
y.val = val$target
####Use Caret package to build adaboost
trctrl <- trainControl(method = "cv", number = 5)
grid <- expand.grid(iter = c(50,100,150,200),maxdepth=7:10,nu=c(0.1,0.5,0.9))
set.seed(3233)
Ada_Model <- train(target~., data=train, method = "ada",
trControl=trctrl,
tuneGrid = grid)
Ada_Model$bestTune
ada_preds <- predict(Ada_Model, val)
confusionMatrix(val$Personal.Loan, ada_preds)
| /Predict_Fradulent_Transactions_Classification/Code/ada.R | no_license | pranakum/DSProjects | R | false | false | 3,406 | r | rm(list=ls(all=TRUE))
setwd("C:/Users/Hai/Desktop/insofe/Cute3")
library(caret)
library(DMwR)
#bankdata=read.csv("UniversalBank.csv", header=TRUE, sep=",")
data=read.csv("train.csv", header=TRUE, sep=",",na.strings=c("","NA"))
str(data)
dat2 <- read.csv("train.csv", header=T, na.strings=c("","NA"))
str(data)
test=read.csv("test.csv",header=TRUE,sep=",",na.strings=c("","NA"))
str(test)
#OBJECTIVE: Will a person take a personal loan or not?
#Response variable is "Personal.Loan"
# Understanding the data
# summary(bankdata)
# str(bankdata)
# head(bankdata)
dim(data)
#53631*51
head(data)
names(data)
str(data)
summary(data)
#cat_var_1 NA's : 2426,cat_var_3
dim(test)
#53545*50
summary(test)
str(test)
## Remove columns which does not add any information
x=nearZeroVar(data,names=TRUE)
# reduced to 29 variables
data=data[,setdiff(names(data),x)]
dim(data)
str(data)
summary(data)
test=test[,setdiff(names(test),x)]
dim(data)
#53631 29
summary(test)
##Check for Missing Values
sum(is.na(data))
#26126
sum(is.na(test))
#25803
# II. Find Number of missing values and drop a row if it contains more than 20% of columns contains missing values. Impute the remining.
sum(is.na(data))
length(manyNAs(data, 0.2) )
ExcludedMissing= data[!rowSums(is.na(data)) > ncol(data)*.2,]
sum(is.na(ExcludedMissing))
#library(aCRM)
ImputedData=centralImputation(ExcludedMissing)
sum(is.na(ImputedData))
# need to do according to train data mean(numeric) & mode(cat)
sum(is.na(test))
length(manyNAs(test, 0.2) )
ExcludedMissingTest= test[!rowSums(is.na(test)) > ncol(test)*.2,]
sum(is.na(ExcludedMissingTest))
ImputedTest=centralImputation(ExcludedMissingTest)
sum(is.na(ImputedTest))
#28 variables
#drop id
ImputedDataRemovedId=ImputedData
ImputedDataRemovedId$transaction_id=NULL
#ImputedDataRemovedIdandName$Itemname=NULL
sum(is.na(ImputedDataRemovedId))
str(ImputedDataRemovedId)
summary(ImputedDataRemovedId)
ImputedTestRemovedId=ImputedTest
ImputedTestRemovedId$transaction_id=NULL
sum(is.na(ImputedTestRemovedId))
str(ImputedTestRemovedId)
summary(ImputedTestRemovedId)
# # Removing unnecessary columns ID and zipcode
# bankdata=subset(bankdata, select=-c(ID,ZIP.Code))
#
# # Do necessary type conversions
# bankdata$Education=as.factor(as.character(bankdata$Education))
# bankdata$Personal.Loan=as.factor(as.character(bankdata$Personal.Loan))
# Do Train-Test Split
library(caret)
set.seed(125)
rows=createDataPartition(ImputedDataRemovedId$target,p = 0.7,list = FALSE)
train=ImputedDataRemovedId[rows,]
val=ImputedDataRemovedId[-rows,]
# PreProcess the data to standadize the numeric attributes
preProc<-preProcess(train[,setdiff(names(train),"target")],method = c("center", "scale"))
train<-predict(preProc,train)
val<-predict(preProc,val)
###create dummies for factor varibales
dummies <- dummyVars(target~., data = ImputedDataRemovedId)
x.train=predict(dummies, newdata = train)
y.train=train$target
x.val = predict(dummies, newdata = val)
y.val = val$target
####Use Caret package to build adaboost
trctrl <- trainControl(method = "cv", number = 5)
grid <- expand.grid(iter = c(50,100,150,200),maxdepth=7:10,nu=c(0.1,0.5,0.9))
set.seed(3233)
Ada_Model <- train(target~., data=train, method = "ada",
trControl=trctrl,
tuneGrid = grid)
Ada_Model$bestTune
ada_preds <- predict(Ada_Model, val)
confusionMatrix(val$Personal.Loan, ada_preds)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.