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 |
|---|---|---|---|---|---|---|---|---|---|
############################ FTS Project R code #############################
#Feature Extraction - Yanchi Liu
login=read.table("login_201511.txt", sep=',', header=F)
length(unique(login$V1))
length(unique(login$V6))
purchase=read.table("pay_201511.txt", sep=',', header=F)
length(unique(purchase$V1))
length(unique(purchase$V6))
ip <- read.table("ip_city.txt", sep=':', header=F, fill=T, quote="", na.strings=c("","None","NA"))
names(ip) = c("ip", "country", "province", "city")
as.factor(ip$country)
as.factor(ip$province)
as.factor(ip$city)
ip <- ip[complete.cases(ip),]
length(is.element(unique(purchase$V1), unique(login$V1)))
print (intersect(unique(purchase$V1), unique(login$V1)))
View(login[login$V1 == '1869414', ])
View(purchase[purchase$V1 == '1869414', ])
#####
## Feature Extraction
user_data=read.table("results.csv", sep=',', header=F, na.strings=c("","NA"))
names(user_data) = c("uid", "date", "ip", "login", "purchase", "amount")
user_data$date <- as.Date(user_data$date)
user_data <- user_data[1:10000, ]
## login in previous 7 days
n = 7
movsum <- function(x,n=7){filter(x,rep(1,n), sides=1)}
user_data$login_7 <- movsum(user_data$login, n) - user_data$login
user_data$purchase_7 <- movsum(user_data$purchase, n) - user_data$purchase
user_data$login_7 <- user_data$login_7 / (n-1)
user_data$purchase_7 <- user_data$purchase_7 / (n-1)
user_data$pur_aft_login_7 <- user_data$purchase_7 / user_data$login_7
## create label
user_data$label <- rep(0, nrow(user_data))
# label of purchase the current day
user_data[which(user_data$purchase>0), "label"] <- rep(1, length(which(user_data$purchase>0)))
# label of purchase the next day
user_data[which(user_data$purchase>0) - 1, "label"] <- rep(1, length(which(user_data$purchase>0)))
user_data$label <- as.factor(user_data$label)
##
user_purchase <- user_data_comp[which(user_data_comp$purchase != 0), ]
# #ts_purchase <- ts(user_purchase[,c("date", "purchase")])
# #plot(ts_purchase)
plot(table(user_purchase$date))
#
# par(mfrow=c(2,1))
# plot(user_data$login)
# plot(user_data$purchase)
# cor(user_data$login, user_data$purchase)
#
# tmp <- user_data_comp[which(user_data_comp$date > '2015-11-06'), ]
# unique(user_data$uid)
## time since last login/purchase
user_data_comp <- user_data[complete.cases(user_data),]
login_diff <- diff(user_data_comp$date)
login_diff[login_diff < 0] <- 0
login_diff <- c(0, login_diff)
length(login_diff)
user_data_comp$login_diff <- login_diff
idx <- user_data_comp$purchase > 0
purchase_diff <- diff(user_data_comp[idx,]$date)
purchase_diff[purchase_diff < 0] <- 0
purchase_diff <- c(0, purchase_diff)
length(purchase_diff)
user_data_comp$purchase_diff <- rep(0, nrow(user_data_comp))
user_data_comp[idx, ]$purchase_diff <- purchase_diff
## user statistics
library(plyr)
user_sum <- ddply(user_data_comp, c("uid"), summarize, login = sum(login), purchase = sum(purchase), amount = sum(amount))
user_avg <- user_sum[, c("login", "purchase", "amount")] / 30
names(user_avg) <- c("avg_login", "avg_purchase", "avg_amount")
user_avg$uid <- user_sum$uid
user_avg$convrate <- user_avg$avg_purchase / user_avg$avg_login
#####
user_data_comp <- merge(user_data_comp, ip, by="ip")
user_data_comp <- merge(user_data_comp, user_avg, by="uid")
user_data_comp <- user_data_comp[, c(1:9,11:19,10)]
write.csv(user_data_comp, file = 'user_data.txt', row.names = FALSE, quote = FALSE)
user_data<- read.table("user_data.txt", sep=',', header=T, fill=T, quote="", na.strings=c("","None","NA"))
user_data$label <- as.factor(user_data$label)
#Logistic Regression and SVM - Yueqing Zhang
## read data
user_data<- read.table("/Users/yueqingzhang/Desktop/2017 FTS project/user_data.txt", sep=',', header=T, fill=T, quote="", na.strings=c("","None","NA"))
user_data$label <- as.factor(user_data$label)
## train and test
set.seed(123)
idx_train <- sample(nrow(user_data), as.integer(nrow(user_data)*0.50))
train_data <- user_data[idx_train,]
test_data <- user_data[-idx_train,]
## Logistic Regression
library(stats)
# m_lr = glm(label~.-login_7-pur_aft_login_7, set.seed(123), data=train_data, family=binomial)
m_lr = glm(label~.-login_7-pur_aft_login_7, set.seed(123), data=train_data[,-c(1:3, 16:18)], family=binomial)
summary(m_lr)
pred_lr = predict(m_lr, test_data)
pred_lr[pred_lr > .5] = 1
pred_lr[pred_lr <= .5] = 0
table(observed = test_data$label,predicted =pred_lr)
accuracy = sum(diag(table(observed = test_data$label,predicted =pred_lr)))/nrow(test_data)
accuracy # 0.9781641
## SVM model
library(e1071)
idx <- sample(nrow(train_data), as.integer(nrow(train_data)*0.05))
obj = best.tune(svm, label~., set.seed(123), data = train_data[idx,-c(1:3, 16:18)], kernel = "linear")
summary(obj) # cost: 1
# gamma: 0.08333333
m_svm <- svm(label~., set.seed(123), data=train_data[idx,-c(1:3, 16:18)], cost = 1, gamma = 0.08333333 ,
kernel = "linear")
summary(m_svm)
pred_svm = predict(m_svm, test_data)
table(observed = test_data$label,predicted =pred_svm)
accuracy = sum(diag(table(observed = test_data$label,predicted =pred_svm)))/nrow(test_data)
accuracy # 0.9795911
obj = best.tune(svm, label~., set.seed(123), data = train_data[idx,-c(1:3, 16:18)], kernel = "radial")
summary(obj)
m_svm <- svm(label~., data=train_data[idx,-c(1:3, 16:18)], cost = 1, gamma = 0.08333333,
kernel = "radial")
pred_svm = predict(m_svm, test_data)
table(observed = test_data$label,predicted =pred_svm)
accuracy = sum(diag(table(observed = test_data$label,predicted =pred_svm)))/nrow(test_data)
accuracy # 0.9796714
obj = best.tune(svm, label~., set.seed(123), data = train_data[idx,-c(1:3, 16:18)], kernel = "sigmoid")
summary(obj)
m_svm <- svm(label~., set.seed(123), data=train_data[idx,-c(1:3, 16:18)], cost = 1, gamma = 0.08333333,
kernel = "sigmoid")
pred_svm = predict(m_svm, test_data)
table(observed = test_data$label,predicted =pred_svm)
accuracy = sum(diag(table(observed = test_data$label,predicted =pred_svm)))/nrow(test_data)
accuracy # 0.9356318
obj = best.tune(svm, label~., set.seed(123), data = train_data[idx,-c(1:3, 16:18)], kernel = "polynomial")
summary(obj)
m_svm <- svm(label~., set.seed(123), data=train_data[idx,-c(1:3, 16:18)], cost = 1, gamma = 0.08333333,
kernel = "polynomial")
pred_svm = predict(m_svm, test_data)
table(observed = test_data$label,predicted =pred_svm)
accuracy = sum(diag(table(observed = test_data$label,predicted =pred_svm)))/nrow(test_data)
accuracy # 0.9791431
#Boosting and Random Forest - Gunjan Batra
setwd("C:/Users/gunjan/Desktop/Spring 2017/Fin Time Series/Project")
## read data
user_data<- read.table("user_data.txt", sep=',', header=T, fill=T, quote="", na.strings=c("","None","NA"))
user_data$label <- as.factor(user_data$label)
## train and test
set.seed(123)
idx_train <- sample(nrow(user_data), as.integer(nrow(user_data)*0.50))
train_data <- user_data[idx_train,]
test_data <- user_data[-idx_train,]
## Random Forest model
library(randomForest)
m_rf <- randomForest(label ~., data=train_data[,-c(1:3, 16:18)], importance=TRUE, ntree = 300)
pred_rf = predict(m_rf, test_data)
table(observed = test_data$label,predicted =pred_rf)
# predicted
# observed 0 1
# 0 370184 1990
# 1 5461 8472
accuracy = sum(diag(table(observed = test_data$label,predicted =pred_rf)))/nrow(test_data)
accuracy
#[1] 0.9807022
#Adaboost Code using function Ada
library("rpart")
library("ada")
control <- rpart.control(cp = -1, maxdepth = 14,maxcompete = 1,xval = 0)
gen1 <- ada(label ~., data=train_data[,-c(1:3, 16:18)],type = "gentle", control = control, iter = 300)
gen1 <- addtest(gen1, test_data[,-c(1:3, 16:18)], test_data$label)
summary(gen1)
# Call:
# ada(label ~ ., data = train_data[, -c(1:3, 16:18)], type = "gentle",
# control = control, iter = 300)
# Loss: exponential Method: gentle Iteration: 300
# Training Results
# Accuracy: 0.988 Kappa: NA
# Testing Results
# Accuracy: 0.981 Kappa: NA
varplot(gen1)
pred_ab = predict(gen1, test_data)
table(observed = test_data$label,predicted =pred_ab)
# predicted
# observed 0 1
# 0 370120 2054
# 1 5432 8501
accuracy = sum(diag(table(observed = test_data$label,predicted =pred_ab)))/nrow(test_data)
accuracy
#[1] 0.9806116
#Adaboost Code using function boosting
library(adabag);
adadata<- read.table("user_data.txt", sep=',', header=T, fill=T, quote="", na.strings=c("","None","NA"))
adaboost<-boosting(label ~.,data=train_data[,-c(1:3, 16:18)], boos=TRUE, mfinal=2,coeflearn='Breiman')
pred_ab = predict(adaboost, test_data)
table(observed = test_data$label,predicted =pred_ab$class)
# predicted
# observed 0 1
# 0 370560 1614
# 1 6091 7842
accuracy = sum(diag(table(observed = test_data$label,predicted =pred_ab$class)))/nrow(test_data)
accuracy
#[1] 0.9800444
summary(adaboost)
# Length Class Mode
# formula 3 formula call
# trees 2 -none- list
# weights 2 -none- numeric
# votes 772214 -none- numeric
# prob 772214 -none- numeric
# class 386107 -none- character
# importance 12 -none- numeric
# terms 3 terms call
# call 6 -none- call
adaboost$trees
#Statitics - Yahui Guo
library(moments)
data=read.table("results.txt",header=F,sep = ",")
sumindividual=function(vec,t){
l=length(vec)/t
x=rep(0,l)
for (i in 1:l){
for (j in 1:t){
x[i]=vec[t*(i-1)+j]+x[i]
}
}
x
}
averagevec=function(vec,k){
l=length(vec)
x=rep(0,l)
for (i in 1:l){
x[i]=vec[i]/k
}
x
}
sumday=function(vec,t){
l=length(vec)/t
x=rep(0,t)
for (i in 1:t){
for(j in 1:l){
x[i]=vec[t*(j-1)+i]+x[i]
}
}
x
}
lt<-sumindividual(data[,4],30)
pt<-sumindividual(data[,5],30)
pamount<-sumindividual(data[,6],30)
avlt<-averagevec(lt,30)
avpt<-averagevec(pt,30)
avpamount<-averagevec(pamount,30)
dailylt<-sumday(data[,4],30)
dailypt<-sumday(data[,5],30)
dailypamount<-sumday(data[,6],30)
hist(lt,breaks = c(20*0:25, 1000,2100))
hist(pt,breaks = c(0:10,120))
hist(pamount,breaks=c(0:50,100,34510))
plot(dailylt,type="l")
plot(dailypt,type="l")
plot(dailypamount,type="l")
skewness(pt)
kurtosis(pt)
summary(lt)
summary(pt)
summary(pamount)
summary(avlt)
summary(avpt)
summary(avpamount)
summary(dailylt)
summary(dailypt)
summary(dailypamount)
mdata<-cbind(avlt,avpt,avpamount)
cov(mdata)
m2data<-cbind(dailylt,dailypt,dailypamount)
cov(m2data)
logdata<-data.frame(loglt=log(avlt+1),
logpt=log(avpt+1),
logpamount=log(avpamount+1))
pairs(logdata[,1:3])
fit<-lm(logpamount~loglt+logpt,data=logdata)
summary(fit)
plot(fit$residuals)
#Time Series Analysis - Cong Shi
library(fGarch)
library(fUnitRoots)
data=read.table("timeline.txt",header=F,sep = ",")
mintohour=function(vec,t){
l=length(vec)/t
x=rep(0,l)
for (i in 1:l){
for (j in 1:t){
x[i]=vec[t*(i-1)+j]+x[i]
}
}
x
}
lt=mintohour(data[,2],12)
pt=mintohour(data[,3],12)
pmt=mintohour(data[,4],12)
ts.plot(lt)
ts.plot(pt)
ts.plot(pmt)
hist(lt)
hist(pt)
hist(pmt)
acf(lt,lag.max=200)
acf(pt,lag.max=200)
acf(pmt,lag.max=200)
dlt=diff(lt,lag=24)
dpt=diff(pt,lag=24)
dpmt=diff(pmt,lag=24)
acf(dlt,lag.max=200)
acf(dpt,lag.max=200)
acf(dpmt,lag.max=200)
pacf(dlt,lag.max=200)
pacf(dpt,lag.max=200)
pacf(dpmt,lag.max=200)
adfTest(dlt,lags=24)
adfTest(dpt,lags=24)
adfTest(dpmt,lags=24)
ar(dpmt)$order
m1=arima(pmt,order=c(7,0,1),seasonal=list(order=c(3,1,1),period=24))
m1
acf(m1$residuals,lag.max=200)
pacf(m1$residuals,lag.max=200)
Box.test(m1$residuals,lag=24,type='Ljung')
tsdiag(m1,gof=24)
m2=arima(pmt,order=c(9,0,1),seasonal=list(order=c(4,1,1),period=24),fixed=c(NA,0,0,0,0,0,NA,0,NA,NA,0,0,NA,NA,NA),transform.pars = FALSE)
m2
acf(m2$residuals,lag.max=200)
pacf(m2$residuals,lag.max=200)
Box.test(m2$residuals,lag=24,type='Ljung')
Box.test(m2$residuals^2,lag=24,type='Ljung')
tsdiag(m2,gof=24)
acf(m2$residuals^2,lag.max=200)
m3=lm(dpmt~dlt+dpt)
summary(m3)
acf(m3$residuals,lag.max=200)
pacf(m3$residuals,lag.max=200)
m4=ar(m3$residuals,method='mle')
m4$order
xmatrix=cbind(dlt,dpt)
m5=arima(dpmt,order=c(9,0,0),seasonal=list(order=c(3,0,1),period=24),fixed=c(NA,NA,0,NA,0,0,NA,0,NA,NA,0,NA,NA,NA,NA),include.mean=F,xreg=xmatrix,transform.pars = FALSE)
m5
acf(m5$residuals,lag.max=200)
pacf(m5$residuals,lag.max=200)
tsdiag(m5,gof=24)
Box.test(m5$residuals,lag=24,type='Ljung')
Box.test(m5$residuals^2,lag=24,type='Ljung')
acf(m5$residuals^2,lag.max=200)
m2test=arima(pmt[1:(length(pmt)-120)],order=c(9,0,1),seasonal=list(order=c(4,1,1),period=24),fixed=c(NA,0,0,0,0,0,NA,0,NA,NA,0,0,NA,NA,NA),transform.pars = FALSE)
p1=predict(m2test,120)
plot(481:length(pmt),pmt[(481:length(pmt))],xlab="Hour", ylab="pmt",type="l")
lines((length(pmt)-119):length(pmt),p1$pred,col="red",lty=5)
lines((length(pmt)-119):length(pmt),p1$pred+0.5*p1$se,col="darkviolet",lty=2)
lines((length(pmt)-119):length(pmt),p1$pred-0.5*p1$se,col="blue",lty=2)
p2=predict(m2,120)
void=rep(-Inf,120)
plot(601:(length(pmt)+120),c(pmt[(601:length(pmt))],void),xlab="Hour", ylab="pmt",type="l")
lines((length(pmt)+1):(length(pmt)+120),p2$pred,col="red",lty=1)
lines((length(pmt)+1):(length(pmt)+120),p2$pred+0.5*p2$se,col="darkviolet",lty=2)
lines((length(pmt)+1):(length(pmt)+120),p2$pred-0.5*p2$se,col="blue",lty=2)
dslt=dlt[1:(length(dlt)-72)]
dspt=dpt[1:(length(dpt)-72)]
dspmt=dpmt[1:(length(dpmt)-72)]
dtlt=dlt[(length(dlt)-71):length(dlt)]
dtpt=dpt[(length(dpt)-71):length(dpt)]
xsmatrix=cbind(dslt,dspt)
xtmatrix=cbind(dtlt,dtpt)
m5test=arima(dspmt,order=c(9,0,0),seasonal=list(order=c(3,0,1),period=24),fixed=c(NA,NA,0,NA,0,0,NA,0,NA,NA,0,NA,NA,NA,NA),include.mean=F,xreg=xsmatrix,transform.pars = FALSE)
p3=predict(m5test,72,newxreg=xtmatrix)
plot(601:length(dpmt),dpmt[(601:length(dpmt))],xlab="Hour", ylab="dpmt",type="l")
lines((length(dpmt)-71):length(dpmt),p3$pred,col="red",lty=5)
lines((length(dpmt)-71):length(dpmt),p3$pred+0.5*p3$se,col="darkviolet",lty=2)
lines((length(dpmt)-71):length(dpmt),p3$pred-0.5*p3$se,col="blue",lty=2)
| /Prediction of future in-app purchases for a mobile app/Final Project R Code.R | no_license | gunjanbatra/Academic-Projects | R | false | false | 14,454 | r | ############################ FTS Project R code #############################
#Feature Extraction - Yanchi Liu
login=read.table("login_201511.txt", sep=',', header=F)
length(unique(login$V1))
length(unique(login$V6))
purchase=read.table("pay_201511.txt", sep=',', header=F)
length(unique(purchase$V1))
length(unique(purchase$V6))
ip <- read.table("ip_city.txt", sep=':', header=F, fill=T, quote="", na.strings=c("","None","NA"))
names(ip) = c("ip", "country", "province", "city")
as.factor(ip$country)
as.factor(ip$province)
as.factor(ip$city)
ip <- ip[complete.cases(ip),]
length(is.element(unique(purchase$V1), unique(login$V1)))
print (intersect(unique(purchase$V1), unique(login$V1)))
View(login[login$V1 == '1869414', ])
View(purchase[purchase$V1 == '1869414', ])
#####
## Feature Extraction
user_data=read.table("results.csv", sep=',', header=F, na.strings=c("","NA"))
names(user_data) = c("uid", "date", "ip", "login", "purchase", "amount")
user_data$date <- as.Date(user_data$date)
user_data <- user_data[1:10000, ]
## login in previous 7 days
n = 7
movsum <- function(x,n=7){filter(x,rep(1,n), sides=1)}
user_data$login_7 <- movsum(user_data$login, n) - user_data$login
user_data$purchase_7 <- movsum(user_data$purchase, n) - user_data$purchase
user_data$login_7 <- user_data$login_7 / (n-1)
user_data$purchase_7 <- user_data$purchase_7 / (n-1)
user_data$pur_aft_login_7 <- user_data$purchase_7 / user_data$login_7
## create label
user_data$label <- rep(0, nrow(user_data))
# label of purchase the current day
user_data[which(user_data$purchase>0), "label"] <- rep(1, length(which(user_data$purchase>0)))
# label of purchase the next day
user_data[which(user_data$purchase>0) - 1, "label"] <- rep(1, length(which(user_data$purchase>0)))
user_data$label <- as.factor(user_data$label)
##
user_purchase <- user_data_comp[which(user_data_comp$purchase != 0), ]
# #ts_purchase <- ts(user_purchase[,c("date", "purchase")])
# #plot(ts_purchase)
plot(table(user_purchase$date))
#
# par(mfrow=c(2,1))
# plot(user_data$login)
# plot(user_data$purchase)
# cor(user_data$login, user_data$purchase)
#
# tmp <- user_data_comp[which(user_data_comp$date > '2015-11-06'), ]
# unique(user_data$uid)
## time since last login/purchase
user_data_comp <- user_data[complete.cases(user_data),]
login_diff <- diff(user_data_comp$date)
login_diff[login_diff < 0] <- 0
login_diff <- c(0, login_diff)
length(login_diff)
user_data_comp$login_diff <- login_diff
idx <- user_data_comp$purchase > 0
purchase_diff <- diff(user_data_comp[idx,]$date)
purchase_diff[purchase_diff < 0] <- 0
purchase_diff <- c(0, purchase_diff)
length(purchase_diff)
user_data_comp$purchase_diff <- rep(0, nrow(user_data_comp))
user_data_comp[idx, ]$purchase_diff <- purchase_diff
## user statistics
library(plyr)
user_sum <- ddply(user_data_comp, c("uid"), summarize, login = sum(login), purchase = sum(purchase), amount = sum(amount))
user_avg <- user_sum[, c("login", "purchase", "amount")] / 30
names(user_avg) <- c("avg_login", "avg_purchase", "avg_amount")
user_avg$uid <- user_sum$uid
user_avg$convrate <- user_avg$avg_purchase / user_avg$avg_login
#####
user_data_comp <- merge(user_data_comp, ip, by="ip")
user_data_comp <- merge(user_data_comp, user_avg, by="uid")
user_data_comp <- user_data_comp[, c(1:9,11:19,10)]
write.csv(user_data_comp, file = 'user_data.txt', row.names = FALSE, quote = FALSE)
user_data<- read.table("user_data.txt", sep=',', header=T, fill=T, quote="", na.strings=c("","None","NA"))
user_data$label <- as.factor(user_data$label)
#Logistic Regression and SVM - Yueqing Zhang
## read data
user_data<- read.table("/Users/yueqingzhang/Desktop/2017 FTS project/user_data.txt", sep=',', header=T, fill=T, quote="", na.strings=c("","None","NA"))
user_data$label <- as.factor(user_data$label)
## train and test
set.seed(123)
idx_train <- sample(nrow(user_data), as.integer(nrow(user_data)*0.50))
train_data <- user_data[idx_train,]
test_data <- user_data[-idx_train,]
## Logistic Regression
library(stats)
# m_lr = glm(label~.-login_7-pur_aft_login_7, set.seed(123), data=train_data, family=binomial)
m_lr = glm(label~.-login_7-pur_aft_login_7, set.seed(123), data=train_data[,-c(1:3, 16:18)], family=binomial)
summary(m_lr)
pred_lr = predict(m_lr, test_data)
pred_lr[pred_lr > .5] = 1
pred_lr[pred_lr <= .5] = 0
table(observed = test_data$label,predicted =pred_lr)
accuracy = sum(diag(table(observed = test_data$label,predicted =pred_lr)))/nrow(test_data)
accuracy # 0.9781641
## SVM model
library(e1071)
idx <- sample(nrow(train_data), as.integer(nrow(train_data)*0.05))
obj = best.tune(svm, label~., set.seed(123), data = train_data[idx,-c(1:3, 16:18)], kernel = "linear")
summary(obj) # cost: 1
# gamma: 0.08333333
m_svm <- svm(label~., set.seed(123), data=train_data[idx,-c(1:3, 16:18)], cost = 1, gamma = 0.08333333 ,
kernel = "linear")
summary(m_svm)
pred_svm = predict(m_svm, test_data)
table(observed = test_data$label,predicted =pred_svm)
accuracy = sum(diag(table(observed = test_data$label,predicted =pred_svm)))/nrow(test_data)
accuracy # 0.9795911
obj = best.tune(svm, label~., set.seed(123), data = train_data[idx,-c(1:3, 16:18)], kernel = "radial")
summary(obj)
m_svm <- svm(label~., data=train_data[idx,-c(1:3, 16:18)], cost = 1, gamma = 0.08333333,
kernel = "radial")
pred_svm = predict(m_svm, test_data)
table(observed = test_data$label,predicted =pred_svm)
accuracy = sum(diag(table(observed = test_data$label,predicted =pred_svm)))/nrow(test_data)
accuracy # 0.9796714
obj = best.tune(svm, label~., set.seed(123), data = train_data[idx,-c(1:3, 16:18)], kernel = "sigmoid")
summary(obj)
m_svm <- svm(label~., set.seed(123), data=train_data[idx,-c(1:3, 16:18)], cost = 1, gamma = 0.08333333,
kernel = "sigmoid")
pred_svm = predict(m_svm, test_data)
table(observed = test_data$label,predicted =pred_svm)
accuracy = sum(diag(table(observed = test_data$label,predicted =pred_svm)))/nrow(test_data)
accuracy # 0.9356318
obj = best.tune(svm, label~., set.seed(123), data = train_data[idx,-c(1:3, 16:18)], kernel = "polynomial")
summary(obj)
m_svm <- svm(label~., set.seed(123), data=train_data[idx,-c(1:3, 16:18)], cost = 1, gamma = 0.08333333,
kernel = "polynomial")
pred_svm = predict(m_svm, test_data)
table(observed = test_data$label,predicted =pred_svm)
accuracy = sum(diag(table(observed = test_data$label,predicted =pred_svm)))/nrow(test_data)
accuracy # 0.9791431
#Boosting and Random Forest - Gunjan Batra
setwd("C:/Users/gunjan/Desktop/Spring 2017/Fin Time Series/Project")
## read data
user_data<- read.table("user_data.txt", sep=',', header=T, fill=T, quote="", na.strings=c("","None","NA"))
user_data$label <- as.factor(user_data$label)
## train and test
set.seed(123)
idx_train <- sample(nrow(user_data), as.integer(nrow(user_data)*0.50))
train_data <- user_data[idx_train,]
test_data <- user_data[-idx_train,]
## Random Forest model
library(randomForest)
m_rf <- randomForest(label ~., data=train_data[,-c(1:3, 16:18)], importance=TRUE, ntree = 300)
pred_rf = predict(m_rf, test_data)
table(observed = test_data$label,predicted =pred_rf)
# predicted
# observed 0 1
# 0 370184 1990
# 1 5461 8472
accuracy = sum(diag(table(observed = test_data$label,predicted =pred_rf)))/nrow(test_data)
accuracy
#[1] 0.9807022
#Adaboost Code using function Ada
library("rpart")
library("ada")
control <- rpart.control(cp = -1, maxdepth = 14,maxcompete = 1,xval = 0)
gen1 <- ada(label ~., data=train_data[,-c(1:3, 16:18)],type = "gentle", control = control, iter = 300)
gen1 <- addtest(gen1, test_data[,-c(1:3, 16:18)], test_data$label)
summary(gen1)
# Call:
# ada(label ~ ., data = train_data[, -c(1:3, 16:18)], type = "gentle",
# control = control, iter = 300)
# Loss: exponential Method: gentle Iteration: 300
# Training Results
# Accuracy: 0.988 Kappa: NA
# Testing Results
# Accuracy: 0.981 Kappa: NA
varplot(gen1)
pred_ab = predict(gen1, test_data)
table(observed = test_data$label,predicted =pred_ab)
# predicted
# observed 0 1
# 0 370120 2054
# 1 5432 8501
accuracy = sum(diag(table(observed = test_data$label,predicted =pred_ab)))/nrow(test_data)
accuracy
#[1] 0.9806116
#Adaboost Code using function boosting
library(adabag);
adadata<- read.table("user_data.txt", sep=',', header=T, fill=T, quote="", na.strings=c("","None","NA"))
adaboost<-boosting(label ~.,data=train_data[,-c(1:3, 16:18)], boos=TRUE, mfinal=2,coeflearn='Breiman')
pred_ab = predict(adaboost, test_data)
table(observed = test_data$label,predicted =pred_ab$class)
# predicted
# observed 0 1
# 0 370560 1614
# 1 6091 7842
accuracy = sum(diag(table(observed = test_data$label,predicted =pred_ab$class)))/nrow(test_data)
accuracy
#[1] 0.9800444
summary(adaboost)
# Length Class Mode
# formula 3 formula call
# trees 2 -none- list
# weights 2 -none- numeric
# votes 772214 -none- numeric
# prob 772214 -none- numeric
# class 386107 -none- character
# importance 12 -none- numeric
# terms 3 terms call
# call 6 -none- call
adaboost$trees
#Statitics - Yahui Guo
library(moments)
data=read.table("results.txt",header=F,sep = ",")
sumindividual=function(vec,t){
l=length(vec)/t
x=rep(0,l)
for (i in 1:l){
for (j in 1:t){
x[i]=vec[t*(i-1)+j]+x[i]
}
}
x
}
averagevec=function(vec,k){
l=length(vec)
x=rep(0,l)
for (i in 1:l){
x[i]=vec[i]/k
}
x
}
sumday=function(vec,t){
l=length(vec)/t
x=rep(0,t)
for (i in 1:t){
for(j in 1:l){
x[i]=vec[t*(j-1)+i]+x[i]
}
}
x
}
lt<-sumindividual(data[,4],30)
pt<-sumindividual(data[,5],30)
pamount<-sumindividual(data[,6],30)
avlt<-averagevec(lt,30)
avpt<-averagevec(pt,30)
avpamount<-averagevec(pamount,30)
dailylt<-sumday(data[,4],30)
dailypt<-sumday(data[,5],30)
dailypamount<-sumday(data[,6],30)
hist(lt,breaks = c(20*0:25, 1000,2100))
hist(pt,breaks = c(0:10,120))
hist(pamount,breaks=c(0:50,100,34510))
plot(dailylt,type="l")
plot(dailypt,type="l")
plot(dailypamount,type="l")
skewness(pt)
kurtosis(pt)
summary(lt)
summary(pt)
summary(pamount)
summary(avlt)
summary(avpt)
summary(avpamount)
summary(dailylt)
summary(dailypt)
summary(dailypamount)
mdata<-cbind(avlt,avpt,avpamount)
cov(mdata)
m2data<-cbind(dailylt,dailypt,dailypamount)
cov(m2data)
logdata<-data.frame(loglt=log(avlt+1),
logpt=log(avpt+1),
logpamount=log(avpamount+1))
pairs(logdata[,1:3])
fit<-lm(logpamount~loglt+logpt,data=logdata)
summary(fit)
plot(fit$residuals)
#Time Series Analysis - Cong Shi
library(fGarch)
library(fUnitRoots)
data=read.table("timeline.txt",header=F,sep = ",")
mintohour=function(vec,t){
l=length(vec)/t
x=rep(0,l)
for (i in 1:l){
for (j in 1:t){
x[i]=vec[t*(i-1)+j]+x[i]
}
}
x
}
lt=mintohour(data[,2],12)
pt=mintohour(data[,3],12)
pmt=mintohour(data[,4],12)
ts.plot(lt)
ts.plot(pt)
ts.plot(pmt)
hist(lt)
hist(pt)
hist(pmt)
acf(lt,lag.max=200)
acf(pt,lag.max=200)
acf(pmt,lag.max=200)
dlt=diff(lt,lag=24)
dpt=diff(pt,lag=24)
dpmt=diff(pmt,lag=24)
acf(dlt,lag.max=200)
acf(dpt,lag.max=200)
acf(dpmt,lag.max=200)
pacf(dlt,lag.max=200)
pacf(dpt,lag.max=200)
pacf(dpmt,lag.max=200)
adfTest(dlt,lags=24)
adfTest(dpt,lags=24)
adfTest(dpmt,lags=24)
ar(dpmt)$order
m1=arima(pmt,order=c(7,0,1),seasonal=list(order=c(3,1,1),period=24))
m1
acf(m1$residuals,lag.max=200)
pacf(m1$residuals,lag.max=200)
Box.test(m1$residuals,lag=24,type='Ljung')
tsdiag(m1,gof=24)
m2=arima(pmt,order=c(9,0,1),seasonal=list(order=c(4,1,1),period=24),fixed=c(NA,0,0,0,0,0,NA,0,NA,NA,0,0,NA,NA,NA),transform.pars = FALSE)
m2
acf(m2$residuals,lag.max=200)
pacf(m2$residuals,lag.max=200)
Box.test(m2$residuals,lag=24,type='Ljung')
Box.test(m2$residuals^2,lag=24,type='Ljung')
tsdiag(m2,gof=24)
acf(m2$residuals^2,lag.max=200)
m3=lm(dpmt~dlt+dpt)
summary(m3)
acf(m3$residuals,lag.max=200)
pacf(m3$residuals,lag.max=200)
m4=ar(m3$residuals,method='mle')
m4$order
xmatrix=cbind(dlt,dpt)
m5=arima(dpmt,order=c(9,0,0),seasonal=list(order=c(3,0,1),period=24),fixed=c(NA,NA,0,NA,0,0,NA,0,NA,NA,0,NA,NA,NA,NA),include.mean=F,xreg=xmatrix,transform.pars = FALSE)
m5
acf(m5$residuals,lag.max=200)
pacf(m5$residuals,lag.max=200)
tsdiag(m5,gof=24)
Box.test(m5$residuals,lag=24,type='Ljung')
Box.test(m5$residuals^2,lag=24,type='Ljung')
acf(m5$residuals^2,lag.max=200)
m2test=arima(pmt[1:(length(pmt)-120)],order=c(9,0,1),seasonal=list(order=c(4,1,1),period=24),fixed=c(NA,0,0,0,0,0,NA,0,NA,NA,0,0,NA,NA,NA),transform.pars = FALSE)
p1=predict(m2test,120)
plot(481:length(pmt),pmt[(481:length(pmt))],xlab="Hour", ylab="pmt",type="l")
lines((length(pmt)-119):length(pmt),p1$pred,col="red",lty=5)
lines((length(pmt)-119):length(pmt),p1$pred+0.5*p1$se,col="darkviolet",lty=2)
lines((length(pmt)-119):length(pmt),p1$pred-0.5*p1$se,col="blue",lty=2)
p2=predict(m2,120)
void=rep(-Inf,120)
plot(601:(length(pmt)+120),c(pmt[(601:length(pmt))],void),xlab="Hour", ylab="pmt",type="l")
lines((length(pmt)+1):(length(pmt)+120),p2$pred,col="red",lty=1)
lines((length(pmt)+1):(length(pmt)+120),p2$pred+0.5*p2$se,col="darkviolet",lty=2)
lines((length(pmt)+1):(length(pmt)+120),p2$pred-0.5*p2$se,col="blue",lty=2)
dslt=dlt[1:(length(dlt)-72)]
dspt=dpt[1:(length(dpt)-72)]
dspmt=dpmt[1:(length(dpmt)-72)]
dtlt=dlt[(length(dlt)-71):length(dlt)]
dtpt=dpt[(length(dpt)-71):length(dpt)]
xsmatrix=cbind(dslt,dspt)
xtmatrix=cbind(dtlt,dtpt)
m5test=arima(dspmt,order=c(9,0,0),seasonal=list(order=c(3,0,1),period=24),fixed=c(NA,NA,0,NA,0,0,NA,0,NA,NA,0,NA,NA,NA,NA),include.mean=F,xreg=xsmatrix,transform.pars = FALSE)
p3=predict(m5test,72,newxreg=xtmatrix)
plot(601:length(dpmt),dpmt[(601:length(dpmt))],xlab="Hour", ylab="dpmt",type="l")
lines((length(dpmt)-71):length(dpmt),p3$pred,col="red",lty=5)
lines((length(dpmt)-71):length(dpmt),p3$pred+0.5*p3$se,col="darkviolet",lty=2)
lines((length(dpmt)-71):length(dpmt),p3$pred-0.5*p3$se,col="blue",lty=2)
|
# gamma
file1="data-simul-chain3/D1001DT0.06T.fasta"
PMST=NULL
ID=str_split(file1,"D")[[1]][2]
time=str_split(file1,"T")[[1]][2]
## example for one fasta file
subdna<-read.dna(file1,format="fasta")
uniqseq <- dna2uniqSequences(subdna)
## get the counts for each sequence
IDcounts<-do.call(rbind, lapply(uniqseq@uniqID, function(x) length(x)))
IDcounts<-as.data.frame(IDcounts[order(-IDcounts[,1]),])
colnames(IDcounts) <- c( 'count')
seqindex<-match(rownames(IDcounts), labels(uniqseq@uniqdna))
## reorder the DNAbin accordingly
ordereddna<-uniqseq@uniqdna[seqindex, ]
uniqdist<-dist.dna(ordereddna,model="raw", as.matrix=TRUE)
mstdist<-mst(uniqdist)
plotcord <- data.frame(gplot.layout.fruchtermanreingold(mstdist, NULL))
X1=X2=Y1=Y2=NULL
colnames(plotcord) = c("X1","X2")
rownames(plotcord) = rownames(uniqdist)
plotcord<-cbind(plotcord,IDcounts)
mstdist[lower.tri(mstdist,diag=TRUE)]<-NA
eList <- NULL
for ( i in 1:nrow(mstdist) ){
for ( j in 1:ncol(mstdist)) {
if (!is.na(mstdist[i,j])){
if (mstdist[i,j]>0){
eList <- rbind(eList,c( rownames(mstdist)[i], colnames(mstdist)[j]))
}
}
}
}
edges <- data.frame(plotcord[eList[,1],1:2], plotcord[eList[,2],1:2])
colnames(edges) <- c("X1","Y1","X2","Y2")
myTheme <- theme(axis.ticks.y = element_blank(), axis.ticks.x = element_blank(),
axis.title.y = element_blank(), panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_blank(), panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(), panel.border = element_blank(),
panel.background = element_blank(), legend.position = "none")
pmst1 <- ggplot()+theme_void()
pmst1 <- pmst1 + geom_segment(data=edges,aes(x=X1,xend=X2,y=Y1,yend=Y2),lineend="round",size=0.5)
pmst1 <- pmst1 + scale_y_continuous("",labels=NULL)+scale_x_continuous("",labels=NULL)
pmst1 <- pmst1 + geom_point(aes(X1, X2, size=count, colour="red"), data=plotcord,colour="turquoise4")
pmst1 <- pmst1 + ggtitle(paste("ID",ID,", t=",time,", With coefficients"))
pmst1
# gamma
file2="data-simul-chain3/D1001DT8.88T.fasta"
PMST=NULL
ID=str_split(file2,"D")[[1]][2]
time=str_split(file2,"T")[[1]][2]
## example for one fasta file
subdna<-read.dna(file2,format="fasta")
uniqseq <- dna2uniqSequences(subdna)
## get the counts for each sequence
IDcounts<-do.call(rbind, lapply(uniqseq@uniqID, function(x) length(x)))
IDcounts<-as.data.frame(IDcounts[order(-IDcounts[,1]),])
colnames(IDcounts) <- c( 'count')
seqindex<-match(rownames(IDcounts), labels(uniqseq@uniqdna))
## reorder the DNAbin accordingly
ordereddna<-uniqseq@uniqdna[seqindex, ]
uniqdist<-dist.dna(ordereddna,model="raw", as.matrix=TRUE)
mstdist<-mst(uniqdist)
plotcord <- data.frame(gplot.layout.fruchtermanreingold(mstdist, NULL))
X1=X2=Y1=Y2=NULL
colnames(plotcord) = c("X1","X2")
rownames(plotcord) = rownames(uniqdist)
plotcord<-cbind(plotcord,IDcounts)
mstdist[lower.tri(mstdist,diag=TRUE)]<-NA
eList <- NULL
for ( i in 1:nrow(mstdist) ){
for ( j in 1:ncol(mstdist)) {
if (!is.na(mstdist[i,j])){
if (mstdist[i,j]>0){
eList <- rbind(eList,c( rownames(mstdist)[i], colnames(mstdist)[j]))
}
}
}
}
edges <- data.frame(plotcord[eList[,1],1:2], plotcord[eList[,2],1:2])
colnames(edges) <- c("X1","Y1","X2","Y2")
myTheme <- theme(axis.ticks.y = element_blank(), axis.ticks.x = element_blank(),
axis.title.y = element_blank(), panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_blank(), panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(), panel.border = element_blank(),
panel.background = element_blank(), legend.position = "none")
pmst2 <- ggplot()+theme_void()
pmst2 <- pmst2 + geom_segment(data=edges,aes(x=X1,xend=X2,y=Y1,yend=Y2),lineend="round",size=0.45)
pmst2 <- pmst2 + scale_y_continuous("",labels=NULL)+scale_x_continuous("",labels=NULL)
pmst2 <- pmst2 + geom_point(aes(X1, X2, size=count, colour="red"), data=plotcord,colour="turquoise4")
pmst2 <- pmst2 + ggtitle(paste("ID",ID,", t=",time,", With coefficients"))
pmst2
# no gamma
file3="data-simul-chain4/D1001DT0.57T.fasta"
PMST=NULL
ID=str_split(file3,"D")[[1]][2]
time=str_split(file3,"T")[[1]][2]
## example for one fasta file
subdna<-read.dna(file3,format="fasta")
uniqseq<- dna2uniqSequences(subdna)
## get the counts for each sequence
IDcounts<-do.call(rbind, lapply(uniqseq@uniqID, function(x) length(x)))
IDcounts<-as.data.frame(IDcounts[order(-IDcounts[,1]),])
colnames(IDcounts) <- c( 'count')
seqindex<-match(rownames(IDcounts), labels(uniqseq@uniqdna))
## reorder the DNAbin accordingly
ordereddna<-uniqseq@uniqdna[seqindex, ]
uniqdist<-dist.dna(ordereddna,model="raw", as.matrix=TRUE)
mstdist<-mst(uniqdist)
plotcord <- data.frame(gplot.layout.fruchtermanreingold(mstdist, NULL))
X1=X2=Y1=Y2=NULL
colnames(plotcord) = c("X1","X2")
rownames(plotcord) = rownames(uniqdist)
plotcord<-cbind(plotcord,IDcounts)
mstdist[lower.tri(mstdist,diag=TRUE)]<-NA
eList <- NULL
for ( i in 1:nrow(mstdist) ){
for ( j in 1:ncol(mstdist)) {
if (!is.na(mstdist[i,j])){
if (mstdist[i,j]>0){
eList <- rbind(eList,c( rownames(mstdist)[i], colnames(mstdist)[j]))
}
}
}
}
edges <- data.frame(plotcord[eList[,1],1:2], plotcord[eList[,2],1:2])
colnames(edges) <- c("X1","Y1","X2","Y2")
myTheme <- theme(axis.ticks.y = element_blank(), axis.ticks.x = element_blank(),
axis.title.y = element_blank(), panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_blank(), panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(), panel.border = element_blank(),
panel.background = element_blank(), legend.position = "none")
pmst3 <- ggplot()+theme_void()
pmst3 <- pmst3 + geom_segment(data=edges,aes(x=X1,xend=X2,y=Y1,yend=Y2),lineend="round",size=0.45)
pmst3 <- pmst3 + scale_y_continuous("",labels=NULL)+scale_x_continuous("",labels=NULL)
pmst3 <- pmst3 + geom_point(aes(X1, X2, size=count, colour="red"), data=plotcord,colour="turquoise4")
pmst3 <- pmst3 + ggtitle(paste("ID",ID,", t=",time,", Without coefficients"))
pmst3
file4="data-simul-chain2/D1001DT8.88T.fasta"
PMST=NULL
ID=str_split(file4,"D")[[1]][2]
time=str_split(file4,"T")[[1]][2]
## example for one fasta file
subdna<-read.dna(file1,format="fasta")
uniqseq <- dna2uniqSequences(subdna)
## get the counts for each sequence
IDcounts<-do.call(rbind, lapply(uniqseq@uniqID, function(x) length(x)))
IDcounts<-as.data.frame(IDcounts[order(-IDcounts[,1]),])
colnames(IDcounts) <- c( 'count')
seqindex<-match(rownames(IDcounts), labels(uniqseq@uniqdna))
## reorder the DNAbin accordingly
ordereddna<-uniqseq@uniqdna[seqindex, ]
uniqdist<-dist.dna(ordereddna,model="raw", as.matrix=TRUE)
mstdist<-mst(uniqdist)
plotcord <- data.frame(gplot.layout.fruchtermanreingold(mstdist, NULL))
X1=X2=Y1=Y2=NULL
colnames(plotcord) = c("X1","X2")
rownames(plotcord) = rownames(uniqdist)
plotcord<-cbind(plotcord,IDcounts)
mstdist[lower.tri(mstdist,diag=TRUE)]<-NA
eList <- NULL
for ( i in 1:nrow(mstdist) ){
for ( j in 1:ncol(mstdist)) {
if (!is.na(mstdist[i,j])){
if (mstdist[i,j]>0){
eList <- rbind(eList,c( rownames(mstdist)[i], colnames(mstdist)[j]))
}
}
}
}
edges <- data.frame(plotcord[eList[,1],1:2], plotcord[eList[,2],1:2])
colnames(edges) <- c("X1","Y1","X2","Y2")
myTheme <- theme(axis.ticks.y = element_blank(), axis.ticks.x = element_blank(),
axis.title.y = element_blank(), panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_blank(), panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(), panel.border = element_blank(),
panel.background = element_blank(), legend.position = "none")
pmst4 <- ggplot()+theme_void()
pmst4 <- pmst4 + geom_segment(data=edges,aes(x=X1,xend=X2,y=Y1,yend=Y2),lineend="round",size=0.45)
pmst4 <- pmst4 + scale_y_continuous("",labels=NULL)+scale_x_continuous("",labels=NULL)
pmst4 <- pmst4 + geom_point(aes(X1, X2, size=count, colour="red"), data=plotcord,colour="turquoise4")
pmst4 <- pmst4 + ggtitle(paste("ID",ID,", t=",time,", Without coefficients"))
pmst4
PMST=c(list(pmst1),list(pmst2))
do.call(grid.arrange,PMST)
PMST2=c(list(pmst1),list(pmst2),list(pmst3),list(pmst4))
do.call(grid.arrange,PMST2)
PMST3=c(list(pmst1),list(pmst3))
do.call(PMST3)
| /CODE/Modèle/OneHost/Figures.R | no_license | MeijeGawinowski/Repertoire_Meije | R | false | false | 8,446 | r | # gamma
file1="data-simul-chain3/D1001DT0.06T.fasta"
PMST=NULL
ID=str_split(file1,"D")[[1]][2]
time=str_split(file1,"T")[[1]][2]
## example for one fasta file
subdna<-read.dna(file1,format="fasta")
uniqseq <- dna2uniqSequences(subdna)
## get the counts for each sequence
IDcounts<-do.call(rbind, lapply(uniqseq@uniqID, function(x) length(x)))
IDcounts<-as.data.frame(IDcounts[order(-IDcounts[,1]),])
colnames(IDcounts) <- c( 'count')
seqindex<-match(rownames(IDcounts), labels(uniqseq@uniqdna))
## reorder the DNAbin accordingly
ordereddna<-uniqseq@uniqdna[seqindex, ]
uniqdist<-dist.dna(ordereddna,model="raw", as.matrix=TRUE)
mstdist<-mst(uniqdist)
plotcord <- data.frame(gplot.layout.fruchtermanreingold(mstdist, NULL))
X1=X2=Y1=Y2=NULL
colnames(plotcord) = c("X1","X2")
rownames(plotcord) = rownames(uniqdist)
plotcord<-cbind(plotcord,IDcounts)
mstdist[lower.tri(mstdist,diag=TRUE)]<-NA
eList <- NULL
for ( i in 1:nrow(mstdist) ){
for ( j in 1:ncol(mstdist)) {
if (!is.na(mstdist[i,j])){
if (mstdist[i,j]>0){
eList <- rbind(eList,c( rownames(mstdist)[i], colnames(mstdist)[j]))
}
}
}
}
edges <- data.frame(plotcord[eList[,1],1:2], plotcord[eList[,2],1:2])
colnames(edges) <- c("X1","Y1","X2","Y2")
myTheme <- theme(axis.ticks.y = element_blank(), axis.ticks.x = element_blank(),
axis.title.y = element_blank(), panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_blank(), panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(), panel.border = element_blank(),
panel.background = element_blank(), legend.position = "none")
pmst1 <- ggplot()+theme_void()
pmst1 <- pmst1 + geom_segment(data=edges,aes(x=X1,xend=X2,y=Y1,yend=Y2),lineend="round",size=0.5)
pmst1 <- pmst1 + scale_y_continuous("",labels=NULL)+scale_x_continuous("",labels=NULL)
pmst1 <- pmst1 + geom_point(aes(X1, X2, size=count, colour="red"), data=plotcord,colour="turquoise4")
pmst1 <- pmst1 + ggtitle(paste("ID",ID,", t=",time,", With coefficients"))
pmst1
# gamma
file2="data-simul-chain3/D1001DT8.88T.fasta"
PMST=NULL
ID=str_split(file2,"D")[[1]][2]
time=str_split(file2,"T")[[1]][2]
## example for one fasta file
subdna<-read.dna(file2,format="fasta")
uniqseq <- dna2uniqSequences(subdna)
## get the counts for each sequence
IDcounts<-do.call(rbind, lapply(uniqseq@uniqID, function(x) length(x)))
IDcounts<-as.data.frame(IDcounts[order(-IDcounts[,1]),])
colnames(IDcounts) <- c( 'count')
seqindex<-match(rownames(IDcounts), labels(uniqseq@uniqdna))
## reorder the DNAbin accordingly
ordereddna<-uniqseq@uniqdna[seqindex, ]
uniqdist<-dist.dna(ordereddna,model="raw", as.matrix=TRUE)
mstdist<-mst(uniqdist)
plotcord <- data.frame(gplot.layout.fruchtermanreingold(mstdist, NULL))
X1=X2=Y1=Y2=NULL
colnames(plotcord) = c("X1","X2")
rownames(plotcord) = rownames(uniqdist)
plotcord<-cbind(plotcord,IDcounts)
mstdist[lower.tri(mstdist,diag=TRUE)]<-NA
eList <- NULL
for ( i in 1:nrow(mstdist) ){
for ( j in 1:ncol(mstdist)) {
if (!is.na(mstdist[i,j])){
if (mstdist[i,j]>0){
eList <- rbind(eList,c( rownames(mstdist)[i], colnames(mstdist)[j]))
}
}
}
}
edges <- data.frame(plotcord[eList[,1],1:2], plotcord[eList[,2],1:2])
colnames(edges) <- c("X1","Y1","X2","Y2")
myTheme <- theme(axis.ticks.y = element_blank(), axis.ticks.x = element_blank(),
axis.title.y = element_blank(), panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_blank(), panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(), panel.border = element_blank(),
panel.background = element_blank(), legend.position = "none")
pmst2 <- ggplot()+theme_void()
pmst2 <- pmst2 + geom_segment(data=edges,aes(x=X1,xend=X2,y=Y1,yend=Y2),lineend="round",size=0.45)
pmst2 <- pmst2 + scale_y_continuous("",labels=NULL)+scale_x_continuous("",labels=NULL)
pmst2 <- pmst2 + geom_point(aes(X1, X2, size=count, colour="red"), data=plotcord,colour="turquoise4")
pmst2 <- pmst2 + ggtitle(paste("ID",ID,", t=",time,", With coefficients"))
pmst2
# no gamma
file3="data-simul-chain4/D1001DT0.57T.fasta"
PMST=NULL
ID=str_split(file3,"D")[[1]][2]
time=str_split(file3,"T")[[1]][2]
## example for one fasta file
subdna<-read.dna(file3,format="fasta")
uniqseq<- dna2uniqSequences(subdna)
## get the counts for each sequence
IDcounts<-do.call(rbind, lapply(uniqseq@uniqID, function(x) length(x)))
IDcounts<-as.data.frame(IDcounts[order(-IDcounts[,1]),])
colnames(IDcounts) <- c( 'count')
seqindex<-match(rownames(IDcounts), labels(uniqseq@uniqdna))
## reorder the DNAbin accordingly
ordereddna<-uniqseq@uniqdna[seqindex, ]
uniqdist<-dist.dna(ordereddna,model="raw", as.matrix=TRUE)
mstdist<-mst(uniqdist)
plotcord <- data.frame(gplot.layout.fruchtermanreingold(mstdist, NULL))
X1=X2=Y1=Y2=NULL
colnames(plotcord) = c("X1","X2")
rownames(plotcord) = rownames(uniqdist)
plotcord<-cbind(plotcord,IDcounts)
mstdist[lower.tri(mstdist,diag=TRUE)]<-NA
eList <- NULL
for ( i in 1:nrow(mstdist) ){
for ( j in 1:ncol(mstdist)) {
if (!is.na(mstdist[i,j])){
if (mstdist[i,j]>0){
eList <- rbind(eList,c( rownames(mstdist)[i], colnames(mstdist)[j]))
}
}
}
}
edges <- data.frame(plotcord[eList[,1],1:2], plotcord[eList[,2],1:2])
colnames(edges) <- c("X1","Y1","X2","Y2")
myTheme <- theme(axis.ticks.y = element_blank(), axis.ticks.x = element_blank(),
axis.title.y = element_blank(), panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_blank(), panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(), panel.border = element_blank(),
panel.background = element_blank(), legend.position = "none")
pmst3 <- ggplot()+theme_void()
pmst3 <- pmst3 + geom_segment(data=edges,aes(x=X1,xend=X2,y=Y1,yend=Y2),lineend="round",size=0.45)
pmst3 <- pmst3 + scale_y_continuous("",labels=NULL)+scale_x_continuous("",labels=NULL)
pmst3 <- pmst3 + geom_point(aes(X1, X2, size=count, colour="red"), data=plotcord,colour="turquoise4")
pmst3 <- pmst3 + ggtitle(paste("ID",ID,", t=",time,", Without coefficients"))
pmst3
file4="data-simul-chain2/D1001DT8.88T.fasta"
PMST=NULL
ID=str_split(file4,"D")[[1]][2]
time=str_split(file4,"T")[[1]][2]
## example for one fasta file
subdna<-read.dna(file1,format="fasta")
uniqseq <- dna2uniqSequences(subdna)
## get the counts for each sequence
IDcounts<-do.call(rbind, lapply(uniqseq@uniqID, function(x) length(x)))
IDcounts<-as.data.frame(IDcounts[order(-IDcounts[,1]),])
colnames(IDcounts) <- c( 'count')
seqindex<-match(rownames(IDcounts), labels(uniqseq@uniqdna))
## reorder the DNAbin accordingly
ordereddna<-uniqseq@uniqdna[seqindex, ]
uniqdist<-dist.dna(ordereddna,model="raw", as.matrix=TRUE)
mstdist<-mst(uniqdist)
plotcord <- data.frame(gplot.layout.fruchtermanreingold(mstdist, NULL))
X1=X2=Y1=Y2=NULL
colnames(plotcord) = c("X1","X2")
rownames(plotcord) = rownames(uniqdist)
plotcord<-cbind(plotcord,IDcounts)
mstdist[lower.tri(mstdist,diag=TRUE)]<-NA
eList <- NULL
for ( i in 1:nrow(mstdist) ){
for ( j in 1:ncol(mstdist)) {
if (!is.na(mstdist[i,j])){
if (mstdist[i,j]>0){
eList <- rbind(eList,c( rownames(mstdist)[i], colnames(mstdist)[j]))
}
}
}
}
edges <- data.frame(plotcord[eList[,1],1:2], plotcord[eList[,2],1:2])
colnames(edges) <- c("X1","Y1","X2","Y2")
myTheme <- theme(axis.ticks.y = element_blank(), axis.ticks.x = element_blank(),
axis.title.y = element_blank(), panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_blank(), panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(), panel.border = element_blank(),
panel.background = element_blank(), legend.position = "none")
pmst4 <- ggplot()+theme_void()
pmst4 <- pmst4 + geom_segment(data=edges,aes(x=X1,xend=X2,y=Y1,yend=Y2),lineend="round",size=0.45)
pmst4 <- pmst4 + scale_y_continuous("",labels=NULL)+scale_x_continuous("",labels=NULL)
pmst4 <- pmst4 + geom_point(aes(X1, X2, size=count, colour="red"), data=plotcord,colour="turquoise4")
pmst4 <- pmst4 + ggtitle(paste("ID",ID,", t=",time,", Without coefficients"))
pmst4
PMST=c(list(pmst1),list(pmst2))
do.call(grid.arrange,PMST)
PMST2=c(list(pmst1),list(pmst2),list(pmst3),list(pmst4))
do.call(grid.arrange,PMST2)
PMST3=c(list(pmst1),list(pmst3))
do.call(PMST3)
|
# Google matrica A s vjv beta
# INIT HERE
# ================================================================
mat <-matrix(c(0, 0.5, 0, 0, 0,
0, 0, 1/3, 0, 0,
0, 0.5, 0, 1, 0,
0, 0, 1/3, 0.0, 1,
1, 0, 1/3, 0, 0), byrow = TRUE, nrow = 5)
#r<-matrix(c(1/9, 1/3, 1/3, 2/9), byrow=TRUE, nrow=5) #vektor ranga
mat
beta = 0.8
r0<-matrix(c(1/5, 1/5, 1/5, 1/5, 1/5),byrow=TRUE, nrow=5)
N = 5 # broj cvorova
matN <- matrix(c(1/N, 1/N, 1/N, 1/N, 1/N,
1/N, 1/N, 1/N, 1/N,1/N,
1/N, 1/N, 1/N, 1/N, 1/N,
1/N, 1/N, 1/N, 1/N, 1/N,
1/N, 1/N, 1/N, 1/N, 1/N), byrow=TRUE, nrow=N, ncol=5)
matN
# ================================================================
A<- beta*mat + (1-beta)*matN
A
res= (A%*%A)%*%A
r3= res%*%r0
r3 | /Meduispit/Link Analysis Google.r | no_license | ardee123/Analysis-of-massive-data-sets | R | false | false | 833 | r | # Google matrica A s vjv beta
# INIT HERE
# ================================================================
mat <-matrix(c(0, 0.5, 0, 0, 0,
0, 0, 1/3, 0, 0,
0, 0.5, 0, 1, 0,
0, 0, 1/3, 0.0, 1,
1, 0, 1/3, 0, 0), byrow = TRUE, nrow = 5)
#r<-matrix(c(1/9, 1/3, 1/3, 2/9), byrow=TRUE, nrow=5) #vektor ranga
mat
beta = 0.8
r0<-matrix(c(1/5, 1/5, 1/5, 1/5, 1/5),byrow=TRUE, nrow=5)
N = 5 # broj cvorova
matN <- matrix(c(1/N, 1/N, 1/N, 1/N, 1/N,
1/N, 1/N, 1/N, 1/N,1/N,
1/N, 1/N, 1/N, 1/N, 1/N,
1/N, 1/N, 1/N, 1/N, 1/N,
1/N, 1/N, 1/N, 1/N, 1/N), byrow=TRUE, nrow=N, ncol=5)
matN
# ================================================================
A<- beta*mat + (1-beta)*matN
A
res= (A%*%A)%*%A
r3= res%*%r0
r3 |
#!/usr/bin/env Rscript
# Author Stephen Coleman
# Student ID 940-309-160-050
# Initial set up of Sleuth - only required once.
# source("http://bioconductor.org/biocLite.R")
# biocLite("rhdf5")
# install.packages("devtools")
# library("devtools")
# devtools::install_github("pachterlab/sleuth")
# biocLite("biomaRt")
library("sleuth")
library("shiny")
# Set current working directory
setwd('.')
args <- commandArgs(trailingOnly=T)
# Ensure at least one input
if(length(args) == 0){
stop("At least one argument (input directory) must be supplied.n", call=F)
}
base_dir <- args[1]
# Want metadata of samples, similar to assignment from DESeq2 tutorial
metadata <- read.csv(args[2], header=T)
metadata <- metadata[order(metadata$run.accession),]
sample_id <- dir(file.path(base_dir))
sample_id <- grep('_quant', sample_id, value=TRUE)
entries <- c()
for(sample in metadata$run.accession){
entry <- grep(sample, sample_id, value=T)
entries <- c(entries, entry)
}
sample_id <- sort(entries)
kal_dirs <- sapply(entries, function(id) file.path(base_dir, id))
s2c <- dplyr::select(metadata, sample = run.accession, Tissue, SRP)
s2c <- dplyr::mutate(s2c, path = kal_dirs)
# Read the Kallisto output files, connect them with metadata,
# and set up a linear model for analyzing the expression data.
so <- sleuth_prep(s2c, ~Tissue+SRP, extra_bootstrap_summary = TRUE)
# Next we fit the linear model and test for one of the model coefficients
# Attempt first a comparison of Tissue vs Experiment, if this fails use
# Tissue vs random
so <- tryCatch({
so <- sleuth_fit(so, ~Tissue+SRP, 'full')
so <- sleuth_fit(so, ~SRP, 'reduced')
},
error=function(cond) {
message("Direct comparison of Tissue and Experiment failed.")
message(cond)
message(": Attempting alternative model.")
so <- sleuth_fit(so, ~Tissue, 'full')
so <- sleuth_fit(so, ~1, 'reduced')
return(so)
}
)
# Test reduced model, full model
so <- sleuth_lrt(so, 'reduced', 'full')
sleuth_table <- sleuth_results(so, 'reduced:full', 'lrt', show_all = FALSE)
sleuth_significant <- dplyr::filter(sleuth_table, qval <= 0.05)
write.csv(sleuth_significant[1:500,], 'significant_isoforms.csv')
so <- sleuth_wt(so, which_beta="TissueLeaf")
# Visualise the results
saveRDS(so, file = './so.rds')
sleuth_live(so, launch.browser=F)
| /Project/scripts/sleuth.R | no_license | stcolema/BIF30806_AdvBioinformatics | R | false | false | 2,385 | r | #!/usr/bin/env Rscript
# Author Stephen Coleman
# Student ID 940-309-160-050
# Initial set up of Sleuth - only required once.
# source("http://bioconductor.org/biocLite.R")
# biocLite("rhdf5")
# install.packages("devtools")
# library("devtools")
# devtools::install_github("pachterlab/sleuth")
# biocLite("biomaRt")
library("sleuth")
library("shiny")
# Set current working directory
setwd('.')
args <- commandArgs(trailingOnly=T)
# Ensure at least one input
if(length(args) == 0){
stop("At least one argument (input directory) must be supplied.n", call=F)
}
base_dir <- args[1]
# Want metadata of samples, similar to assignment from DESeq2 tutorial
metadata <- read.csv(args[2], header=T)
metadata <- metadata[order(metadata$run.accession),]
sample_id <- dir(file.path(base_dir))
sample_id <- grep('_quant', sample_id, value=TRUE)
entries <- c()
for(sample in metadata$run.accession){
entry <- grep(sample, sample_id, value=T)
entries <- c(entries, entry)
}
sample_id <- sort(entries)
kal_dirs <- sapply(entries, function(id) file.path(base_dir, id))
s2c <- dplyr::select(metadata, sample = run.accession, Tissue, SRP)
s2c <- dplyr::mutate(s2c, path = kal_dirs)
# Read the Kallisto output files, connect them with metadata,
# and set up a linear model for analyzing the expression data.
so <- sleuth_prep(s2c, ~Tissue+SRP, extra_bootstrap_summary = TRUE)
# Next we fit the linear model and test for one of the model coefficients
# Attempt first a comparison of Tissue vs Experiment, if this fails use
# Tissue vs random
so <- tryCatch({
so <- sleuth_fit(so, ~Tissue+SRP, 'full')
so <- sleuth_fit(so, ~SRP, 'reduced')
},
error=function(cond) {
message("Direct comparison of Tissue and Experiment failed.")
message(cond)
message(": Attempting alternative model.")
so <- sleuth_fit(so, ~Tissue, 'full')
so <- sleuth_fit(so, ~1, 'reduced')
return(so)
}
)
# Test reduced model, full model
so <- sleuth_lrt(so, 'reduced', 'full')
sleuth_table <- sleuth_results(so, 'reduced:full', 'lrt', show_all = FALSE)
sleuth_significant <- dplyr::filter(sleuth_table, qval <= 0.05)
write.csv(sleuth_significant[1:500,], 'significant_isoforms.csv')
so <- sleuth_wt(so, which_beta="TissueLeaf")
# Visualise the results
saveRDS(so, file = './so.rds')
sleuth_live(so, launch.browser=F)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/server-helpers.R
\name{getQueryYears}
\alias{getQueryYears}
\title{Get the years for which a query is defined}
\usage{
getQueryYears(prj, scenario, query)
}
\arguments{
\item{prj}{Project data structure}
\item{scenario}{Name of the scenario}
\item{query}{Name of the query}
}
\description{
Get the years for which a query is defined
}
| /man/getQueryYears.Rd | no_license | JGCRI/GCAM-LAC-dashboard | R | false | true | 415 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/server-helpers.R
\name{getQueryYears}
\alias{getQueryYears}
\title{Get the years for which a query is defined}
\usage{
getQueryYears(prj, scenario, query)
}
\arguments{
\item{prj}{Project data structure}
\item{scenario}{Name of the scenario}
\item{query}{Name of the query}
}
\description{
Get the years for which a query is defined
}
|
% File rmongodb/man/mongo.gridfs.find.Rd
\name{mongo.gridfs.find}
\alias{mongo.gridfs.find}
\title{Find a GridFS file}
\description{
Find a GridFS file and return a \link{mongo.gridfile} object used for further operations on it}
\usage{
mongo.gridfs.find(gridfs, query)
}
\arguments{
\item{gridfs}{A (\link{mongo.gridfs}) object.}
\item{query}{(string) The name of the GridFS file to locate.
This parameter may also be a \link{mongo.bson} query object and is used to search
the GridFS "files" collection documents for matches. Alternately, \code{query} may be
a list which will be converted to a mongo.bson object by \code{\link{mongo.bson.from.list}()}.}
}
\value{
NULL, if not found; otherwise, a \link{mongo.gridfile} object corresponding to the found GridFS file.
}
\examples{
mongo <- mongo.create()
if (mongo.is.connected(mongo)) {
gridfs <- mongo.gridfs.create(mongo, "grid")
gf <- mongo.gridfs.find(gridfs, "test.dat")
print(mongo.gridfile.get.length(gf))
# find a GridFS file uploaded midnight July 4, 2008
buf <- mongo.bson.buffer.create()
mongo.bson.buffer.append(buf, "uploadDate",
strptime("07-04-2008", "\%m-\%d-\%Y"))
query <- mongo.bson.from.buffer(buf)
gf <- mongo.gridfs.find(gridfs, query)
if (!is.null(gf))
print(mongo.gridfile.get.filename(gf))
mongo.gridfs.destroy(gridfs)
}
}
\seealso{
\link{mongo.gridfile},\cr
\code{\link{mongo.gridfile.get.filename}},\cr
\link{mongo.gridfs}.
}
| /rstuff/rmongodb/rmongodb/man/mongo.gridfs.find.Rd | permissive | BigBlueBox/GoodAndBad | R | false | false | 1,467 | rd | % File rmongodb/man/mongo.gridfs.find.Rd
\name{mongo.gridfs.find}
\alias{mongo.gridfs.find}
\title{Find a GridFS file}
\description{
Find a GridFS file and return a \link{mongo.gridfile} object used for further operations on it}
\usage{
mongo.gridfs.find(gridfs, query)
}
\arguments{
\item{gridfs}{A (\link{mongo.gridfs}) object.}
\item{query}{(string) The name of the GridFS file to locate.
This parameter may also be a \link{mongo.bson} query object and is used to search
the GridFS "files" collection documents for matches. Alternately, \code{query} may be
a list which will be converted to a mongo.bson object by \code{\link{mongo.bson.from.list}()}.}
}
\value{
NULL, if not found; otherwise, a \link{mongo.gridfile} object corresponding to the found GridFS file.
}
\examples{
mongo <- mongo.create()
if (mongo.is.connected(mongo)) {
gridfs <- mongo.gridfs.create(mongo, "grid")
gf <- mongo.gridfs.find(gridfs, "test.dat")
print(mongo.gridfile.get.length(gf))
# find a GridFS file uploaded midnight July 4, 2008
buf <- mongo.bson.buffer.create()
mongo.bson.buffer.append(buf, "uploadDate",
strptime("07-04-2008", "\%m-\%d-\%Y"))
query <- mongo.bson.from.buffer(buf)
gf <- mongo.gridfs.find(gridfs, query)
if (!is.null(gf))
print(mongo.gridfile.get.filename(gf))
mongo.gridfs.destroy(gridfs)
}
}
\seealso{
\link{mongo.gridfile},\cr
\code{\link{mongo.gridfile.get.filename}},\cr
\link{mongo.gridfs}.
}
|
## This R program contains two functions that perform the following functions
## 1. makeCacheMatrix() --> Caches a matrix that is provided as input to its set function.
## Also, defines a set of functions that can be used by the
## thus created matrix
## 2. cacheSolve() --> Takes a matrix as input and returns the inverse of it
## Prepares a Matrix (Square) passed as input to it
makeCacheMatrix <- function(x = matrix()) {
## Reset the value of the variable that holds the inverse of the matrix
inv_mtr <- NULL
set <- function(y) {
## Ensure that the input is a matrix
if ( ! is.matrix(y) ) {
message("ERROR - makeCacheMatrix expects a matrix as input !!")
return
}
x <<- y
inv_mtr <<- NULL
}
get <- function() x
setinvmtr <- function(inv) inv_mtr <<- inv
getinvmtr <- function() inv_mtr
list(set = set, get = get,
setinvmtr = setinvmtr,
getinvmtr = getinvmtr)
}
## Inverts the matrix provided as input to it
### The input matrix must be created using the above makeCacheMatrix function
cacheSolve <- function(x, ...) {
## Ensure that the input is a square matrix since only those have an inverse
if ( dim(x$get())[1] != dim(x$get())[2] ) {
message("ERROR - makeCacheMatrix expects a Square Matrix as input !!")
return()
}
message("Getting the Inverse of the Matrix ")
inv_mtr <- x$getinvmtr()
if (! is.null(inv_mtr)) {
return(inv_mtr)
}
tmp <- x$get()
inv_mtr <- try(solve(tmp))
x$setinvmtr(inv_mtr)
inv_mtr
}
| /cachematrix.R | no_license | valli223/ProgrammingAssignment2 | R | false | false | 1,577 | r | ## This R program contains two functions that perform the following functions
## 1. makeCacheMatrix() --> Caches a matrix that is provided as input to its set function.
## Also, defines a set of functions that can be used by the
## thus created matrix
## 2. cacheSolve() --> Takes a matrix as input and returns the inverse of it
## Prepares a Matrix (Square) passed as input to it
makeCacheMatrix <- function(x = matrix()) {
## Reset the value of the variable that holds the inverse of the matrix
inv_mtr <- NULL
set <- function(y) {
## Ensure that the input is a matrix
if ( ! is.matrix(y) ) {
message("ERROR - makeCacheMatrix expects a matrix as input !!")
return
}
x <<- y
inv_mtr <<- NULL
}
get <- function() x
setinvmtr <- function(inv) inv_mtr <<- inv
getinvmtr <- function() inv_mtr
list(set = set, get = get,
setinvmtr = setinvmtr,
getinvmtr = getinvmtr)
}
## Inverts the matrix provided as input to it
### The input matrix must be created using the above makeCacheMatrix function
cacheSolve <- function(x, ...) {
## Ensure that the input is a square matrix since only those have an inverse
if ( dim(x$get())[1] != dim(x$get())[2] ) {
message("ERROR - makeCacheMatrix expects a Square Matrix as input !!")
return()
}
message("Getting the Inverse of the Matrix ")
inv_mtr <- x$getinvmtr()
if (! is.null(inv_mtr)) {
return(inv_mtr)
}
tmp <- x$get()
inv_mtr <- try(solve(tmp))
x$setinvmtr(inv_mtr)
inv_mtr
}
|
plot3 <- function(){
library(data.table)
## Read file
## I'm considering that the final data are available in the work directory
dt <- fread("household_power_consumption.txt", colClasses = "character")
## Converting to date
dt$Date <- as.Date(dt$Date, format="%d/%m/%Y")
## Getting only the specified data
dt <- dt[(dt$Date >= "2007-02-01" & dt$Date <= "2007-02-02"), ]
## create a new column with date + time
dt[, DateTime := paste(format(dt$Date,"%d/%m/%Y"), dt$Time)]
## put strptime in a new variable, because seems it doesn't works with data.table
auxDateTime <- strptime(dt$DateTime, format = "%d/%m/%Y %H:%M:%S")
## Open PNG device; create 'plot3.png' in my working directory with 480 x 480 pixels
png(file = "plot3.png", width = 480, height = 480, units = "px")
## Create plot and send to a file
plot(auxDateTime, dt$Sub_metering_1, type='l', ylim = c(0, 38), xlab='', ylab='Energy sub Metering')
## plot the lines separately
par(new=T)
plot(auxDateTime, dt$Sub_metering_2, type='l', ylim = c(0, 38), xlab='', ylab='', axes=F, col="red")
par(new=T)
plot(auxDateTime, dt$Sub_metering_3, type='l', ylim = c(0, 38), xlab='', ylab='', axes=F, col="blue")
par(new=F)
## Legend
legend("topright", col=c("black", "red", "blue"), lty=1, lwd=2, bty="n", legend=c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"))
## Close the PNG file device
dev.off()
## Now you can view the file 'plot3.png' on your computer
}
| /plot3.R | no_license | saquarema/ExData_Plotting1 | R | false | false | 1,812 | r | plot3 <- function(){
library(data.table)
## Read file
## I'm considering that the final data are available in the work directory
dt <- fread("household_power_consumption.txt", colClasses = "character")
## Converting to date
dt$Date <- as.Date(dt$Date, format="%d/%m/%Y")
## Getting only the specified data
dt <- dt[(dt$Date >= "2007-02-01" & dt$Date <= "2007-02-02"), ]
## create a new column with date + time
dt[, DateTime := paste(format(dt$Date,"%d/%m/%Y"), dt$Time)]
## put strptime in a new variable, because seems it doesn't works with data.table
auxDateTime <- strptime(dt$DateTime, format = "%d/%m/%Y %H:%M:%S")
## Open PNG device; create 'plot3.png' in my working directory with 480 x 480 pixels
png(file = "plot3.png", width = 480, height = 480, units = "px")
## Create plot and send to a file
plot(auxDateTime, dt$Sub_metering_1, type='l', ylim = c(0, 38), xlab='', ylab='Energy sub Metering')
## plot the lines separately
par(new=T)
plot(auxDateTime, dt$Sub_metering_2, type='l', ylim = c(0, 38), xlab='', ylab='', axes=F, col="red")
par(new=T)
plot(auxDateTime, dt$Sub_metering_3, type='l', ylim = c(0, 38), xlab='', ylab='', axes=F, col="blue")
par(new=F)
## Legend
legend("topright", col=c("black", "red", "blue"), lty=1, lwd=2, bty="n", legend=c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"))
## Close the PNG file device
dev.off()
## Now you can view the file 'plot3.png' on your computer
}
|
library(arules)
groceries<-read.transactions("groceries.csv",sep = ",")
summary(groceries)
itemFrequencyPlot(groceries,topN=20)
#使用image可视化稀疏矩阵,sample随机抽样
#sample for randomly extracting samples, image function for visualing sparse matrix
image(sample(groceries,100))
groceries_rule<-apriori(data = groceries,parameter =list(support=0.006,confidence=0.25,minlen=2))
plotly_arules(groceries_rule)
summary(groceries_rule)
| /AssociationAlgorithm/Apriori.R | permissive | JavierCanon/R | R | false | false | 449 | r | library(arules)
groceries<-read.transactions("groceries.csv",sep = ",")
summary(groceries)
itemFrequencyPlot(groceries,topN=20)
#使用image可视化稀疏矩阵,sample随机抽样
#sample for randomly extracting samples, image function for visualing sparse matrix
image(sample(groceries,100))
groceries_rule<-apriori(data = groceries,parameter =list(support=0.006,confidence=0.25,minlen=2))
plotly_arules(groceries_rule)
summary(groceries_rule)
|
pollutantmean <- function(directory, pollutant, id = 1:332) {
## 'directory' is a character vector of length 1 indicating
## the location of the CSV files
## 'pollutant' is a character vector of length 1 indicating
## the name of the pollutant for which we will calculate the
## mean; either "sulfate" or "nitrate".
## 'id' is an integer vector indicating the monitor ID numbers
## to be used
## Return the mean of the pollutant across all monitors list
## in the 'id' vector (ignoring NA values)
data<-NULL
monitor <- list()
id<-as.character(id)
id[nchar(id)==1]<-paste('00',id[nchar(id)==1],sep='')
id[nchar(id)==2]<-paste('0',id[nchar(id)==2],sep='')
for(i in seq_along(id)){
monitor[[i]] <- read.table(paste(directory,'/',id[i],'.csv',sep=''),header=TRUE,sep=',')
data <- rbind(data,monitor[[i]])
}
m <- mean(data[[pollutant]],na.rm=TRUE)
m
} | /pollutantmean.R | no_license | osmarllq/r-assignments | R | false | false | 961 | r | pollutantmean <- function(directory, pollutant, id = 1:332) {
## 'directory' is a character vector of length 1 indicating
## the location of the CSV files
## 'pollutant' is a character vector of length 1 indicating
## the name of the pollutant for which we will calculate the
## mean; either "sulfate" or "nitrate".
## 'id' is an integer vector indicating the monitor ID numbers
## to be used
## Return the mean of the pollutant across all monitors list
## in the 'id' vector (ignoring NA values)
data<-NULL
monitor <- list()
id<-as.character(id)
id[nchar(id)==1]<-paste('00',id[nchar(id)==1],sep='')
id[nchar(id)==2]<-paste('0',id[nchar(id)==2],sep='')
for(i in seq_along(id)){
monitor[[i]] <- read.table(paste(directory,'/',id[i],'.csv',sep=''),header=TRUE,sep=',')
data <- rbind(data,monitor[[i]])
}
m <- mean(data[[pollutant]],na.rm=TRUE)
m
} |
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/manlysa.R
\name{manlysalpha}
\alias{manlysalpha}
\title{Manly's alpha feeding preference (Chesson 1968).
Returns Manly'as alpha index from vectors of initial and final food item counts.}
\usage{
manlysalpha(initial, consumed, stand = FALSE, perc = FALSE,
deplete = TRUE)
}
\arguments{
\item{initial}{A vector of initial food items counts available to the organism in the environment}
\item{consumed}{A vector of food items consumed by the organism}
\item{stand}{Converts values with highest standardized to "1"? Defaults to FALSE.}
\item{perc}{Converts values to percentages? Defaults to FALSE.}
\item{deplete}{For use in experiments where food sources deplete? Defaults to TRUE.}
}
\description{
Manly's alpha feeding preference (Chesson 1968).
Returns Manly'as alpha index from vectors of initial and final food item counts.
}
\examples{
initial_prey_count <- c(10,10,10,10,10,10)
number_prey_consumed <- c(9,8,1,3,5,9)
manlysalpha(initial = initial_prey_count, consumed = number_prey_consumed,
stand = TRUE, perc = FALSE, deplete = TRUE)
manlysalpha(initial = initial_prey_count, consumed = number_prey_consumed,
stand = TRUE, perc = TRUE, deplete = TRUE)
}
\keyword{Manly's}
\keyword{alpha}
\keyword{preference}
\keyword{selectivity}
| /manlysalpha.Rd | no_license | jcrichardson617/selectapref | R | false | true | 1,363 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/manlysa.R
\name{manlysalpha}
\alias{manlysalpha}
\title{Manly's alpha feeding preference (Chesson 1968).
Returns Manly'as alpha index from vectors of initial and final food item counts.}
\usage{
manlysalpha(initial, consumed, stand = FALSE, perc = FALSE,
deplete = TRUE)
}
\arguments{
\item{initial}{A vector of initial food items counts available to the organism in the environment}
\item{consumed}{A vector of food items consumed by the organism}
\item{stand}{Converts values with highest standardized to "1"? Defaults to FALSE.}
\item{perc}{Converts values to percentages? Defaults to FALSE.}
\item{deplete}{For use in experiments where food sources deplete? Defaults to TRUE.}
}
\description{
Manly's alpha feeding preference (Chesson 1968).
Returns Manly'as alpha index from vectors of initial and final food item counts.
}
\examples{
initial_prey_count <- c(10,10,10,10,10,10)
number_prey_consumed <- c(9,8,1,3,5,9)
manlysalpha(initial = initial_prey_count, consumed = number_prey_consumed,
stand = TRUE, perc = FALSE, deplete = TRUE)
manlysalpha(initial = initial_prey_count, consumed = number_prey_consumed,
stand = TRUE, perc = TRUE, deplete = TRUE)
}
\keyword{Manly's}
\keyword{alpha}
\keyword{preference}
\keyword{selectivity}
|
rm(list=ls())
library(readxl)
MyData1 =read_excel(file.choose())
Mydf1=as.data.frame(MyData1 )
Mydf1
length(Mydf1$Merge)
head(Mydf1)
Action1=unique(Mydf1$Merge)
Action2=c()
j=1
for (i in 1:length(Action1)){
if (length(table(Mydf1$CRA[Mydf1$Merge==Action1[i]]))>2 )
{
Action2[j]=Action1[i]
i=i+1
j=j+1
}
}
Action2
================================
df_one=data.frame(Action2)
names(df_one)[1] <- "Merge"
attach(df_one)
FinalData=merge(x = df_one , y = Mydf1, by = "Merge", all.x = TRUE)
haad(FinalData,30)
length(FinalData$X)
attach(FinalData)
FinalData1=data.frame(X,CRA,Number,CHROM,POS,REF,ALT)
head(FinalData1,30)
library("xlsx")
write.csv(FinalData1, file = "C:/Users/hezardastan/Desktop/Sara/Remove_Unique/FinalCode.csv" , row.names = F)
write.csv(df_one, file = "C:/Users/hezardastan/Desktop/Sara/Remove_Unique/Action2.csv" , row.names = F)
| /ngs1.R | no_license | SaraFarmahiniFarahani/ngs1 | R | false | false | 895 | r | rm(list=ls())
library(readxl)
MyData1 =read_excel(file.choose())
Mydf1=as.data.frame(MyData1 )
Mydf1
length(Mydf1$Merge)
head(Mydf1)
Action1=unique(Mydf1$Merge)
Action2=c()
j=1
for (i in 1:length(Action1)){
if (length(table(Mydf1$CRA[Mydf1$Merge==Action1[i]]))>2 )
{
Action2[j]=Action1[i]
i=i+1
j=j+1
}
}
Action2
================================
df_one=data.frame(Action2)
names(df_one)[1] <- "Merge"
attach(df_one)
FinalData=merge(x = df_one , y = Mydf1, by = "Merge", all.x = TRUE)
haad(FinalData,30)
length(FinalData$X)
attach(FinalData)
FinalData1=data.frame(X,CRA,Number,CHROM,POS,REF,ALT)
head(FinalData1,30)
library("xlsx")
write.csv(FinalData1, file = "C:/Users/hezardastan/Desktop/Sara/Remove_Unique/FinalCode.csv" , row.names = F)
write.csv(df_one, file = "C:/Users/hezardastan/Desktop/Sara/Remove_Unique/Action2.csv" , row.names = F)
|
# Load Libraries and Data
library(tidyverse)
library(modelr)
library(broom)
library(knitr)
gdpreal <- read.csv("gdpreal.csv")
# Part 1
## Tidy data
gdpreal <- slice(gdpreal, 1:4)
gdpreal <- gather(gdpreal, 5:64, key = "year", value = "growth")
colnames(gdpreal)[1:2] <- c("aggregate", "aggregate_code")
gdpreal <- select(gdpreal, 1, 5, 6)
gdpreal$year <- substr(gdpreal$year, 2, 5)
gdpreal$year <- as.Date(gdpreal$year, format = "%Y")
gdpreal$growth <- as.double(gdpreal$growth)
## Plot data
ggplot(gdpreal, mapping = aes(x = year, y = growth, color = aggregate)) +
geom_smooth(se = FALSE)
# Part 2
## Load Data
solow <- read.csv("solow.csv")
## Tidy Data
solow <- select(solow, -2, -4)
solow <- slice(solow, 1:736)
colnames(solow) <- c("country", "series", "value")
solow <- spread(solow, series, value)
colnames(solow) <- c("country", "sav_net_all", "sav_net", "gdp_pc", "cap_form", "dom_sav", "sav_gdp", "sav_gni", "invest")
solow$sav_net_all <- as.numeric(as.character(solow$sav_net_all))
solow$sav_net <- as.numeric(as.character(solow$sav_net))
solow$gdp_pc <- as.numeric(as.character(solow$gdp_pc))
solow$cap_form <- as.numeric(as.character(solow$cap_form))
solow$dom_sav <- as.numeric(as.character(solow$dom_sav))
solow$sav_gdp <- as.numeric(as.character(solow$sav_gdp))
solow$sav_gni <- as.numeric(as.character(solow$sav_gni))
solow$invest <- as.numeric(as.character(solow$invest))
## Plot Data
### Do this one. Net investment in nonfinancial assets and gross savings
ggplot(solow, mapping = aes(x = sav_gdp, y = invest)) +
geom_point(alpha = 0.5) +
geom_smooth(method = 'lm', se = FALSE)
solow_mod_1 <- lm(invest ~ sav_gdp,
data = solow)
tidy(solow_mod_1)
### Oooh. replace investment with Gross Capital Formation and things change
ggplot(solow, mapping = aes(x = sav_gdp, y = cap_form)) +
geom_point(alpha = 0.5) +
geom_smooth(method = 'lm', se = FALSE)
solow_mod_2 <- lm(cap_form ~ sav_gdp,
data = solow)
tidy(solow_mod_2)
view(solow)
# Part 3
solow <- mutate(solow, log_gdp_pc = log(gdp_pc))
ggplot(solow, mapping = aes(x = sav_gdp, y = log_gdp_pc)) +
geom_point(alpha = 0.5) +
geom_smooth(method = 'lm', se = FALSE)
solow_mod_3 <- lm(sav_gdp ~ log_gdp_pc,
data = solow)
tidy(solow_mod_3)
| /question 3.R | no_license | mtlynch4/EDP-Homework-2 | R | false | false | 2,308 | r |
# Load Libraries and Data
library(tidyverse)
library(modelr)
library(broom)
library(knitr)
gdpreal <- read.csv("gdpreal.csv")
# Part 1
## Tidy data
gdpreal <- slice(gdpreal, 1:4)
gdpreal <- gather(gdpreal, 5:64, key = "year", value = "growth")
colnames(gdpreal)[1:2] <- c("aggregate", "aggregate_code")
gdpreal <- select(gdpreal, 1, 5, 6)
gdpreal$year <- substr(gdpreal$year, 2, 5)
gdpreal$year <- as.Date(gdpreal$year, format = "%Y")
gdpreal$growth <- as.double(gdpreal$growth)
## Plot data
ggplot(gdpreal, mapping = aes(x = year, y = growth, color = aggregate)) +
geom_smooth(se = FALSE)
# Part 2
## Load Data
solow <- read.csv("solow.csv")
## Tidy Data
solow <- select(solow, -2, -4)
solow <- slice(solow, 1:736)
colnames(solow) <- c("country", "series", "value")
solow <- spread(solow, series, value)
colnames(solow) <- c("country", "sav_net_all", "sav_net", "gdp_pc", "cap_form", "dom_sav", "sav_gdp", "sav_gni", "invest")
solow$sav_net_all <- as.numeric(as.character(solow$sav_net_all))
solow$sav_net <- as.numeric(as.character(solow$sav_net))
solow$gdp_pc <- as.numeric(as.character(solow$gdp_pc))
solow$cap_form <- as.numeric(as.character(solow$cap_form))
solow$dom_sav <- as.numeric(as.character(solow$dom_sav))
solow$sav_gdp <- as.numeric(as.character(solow$sav_gdp))
solow$sav_gni <- as.numeric(as.character(solow$sav_gni))
solow$invest <- as.numeric(as.character(solow$invest))
## Plot Data
### Do this one. Net investment in nonfinancial assets and gross savings
ggplot(solow, mapping = aes(x = sav_gdp, y = invest)) +
geom_point(alpha = 0.5) +
geom_smooth(method = 'lm', se = FALSE)
solow_mod_1 <- lm(invest ~ sav_gdp,
data = solow)
tidy(solow_mod_1)
### Oooh. replace investment with Gross Capital Formation and things change
ggplot(solow, mapping = aes(x = sav_gdp, y = cap_form)) +
geom_point(alpha = 0.5) +
geom_smooth(method = 'lm', se = FALSE)
solow_mod_2 <- lm(cap_form ~ sav_gdp,
data = solow)
tidy(solow_mod_2)
view(solow)
# Part 3
solow <- mutate(solow, log_gdp_pc = log(gdp_pc))
ggplot(solow, mapping = aes(x = sav_gdp, y = log_gdp_pc)) +
geom_point(alpha = 0.5) +
geom_smooth(method = 'lm', se = FALSE)
solow_mod_3 <- lm(sav_gdp ~ log_gdp_pc,
data = solow)
tidy(solow_mod_3)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/JSTOR_1word.R
\name{JSTOR_1word}
\alias{JSTOR_1word}
\title{Plot the frequency of one word over time in a JSTOR DfR dataset}
\usage{
JSTOR_1word(unpack1grams, oneword, span = 0.5, se = FALSE)
}
\arguments{
\item{unpack1grams}{object returned by the function JSTOR_unpack1grams.}
\item{oneword}{One word, surrounded by standard quote marks, or a vector of words}
\item{span}{span of the lowess line (controls the degree of smoothing). Default is 0.4}
\item{se}{logical, show or hide standard error region of smoother line, Default is TRUE.}
}
\value{
Returns a ggplot object with publication year on the horizontal axis and log relative frequency on the vertical axis. Each point represents a single document.
}
\description{
Function to plot changes in the relative frequency of a word over time. The relative frequency is the frequency of the word in a document divided by the total number of words in a document. For use with JSTOR's Data for Research datasets (http://dfr.jstor.org/).
}
\examples{
## JSTOR_1word(unpack1grams, "diamonds")
## JSTOR_1word(unpack1grams, c("diamonds", "pearls"), span = 0.4, se = FALSE) +
## scale_y_continuous(trans=log2_trans()) # to diminish the effect of a few extreme values
}
| /man/JSTOR_1word.Rd | no_license | elinw/JSTORr | R | false | true | 1,298 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/JSTOR_1word.R
\name{JSTOR_1word}
\alias{JSTOR_1word}
\title{Plot the frequency of one word over time in a JSTOR DfR dataset}
\usage{
JSTOR_1word(unpack1grams, oneword, span = 0.5, se = FALSE)
}
\arguments{
\item{unpack1grams}{object returned by the function JSTOR_unpack1grams.}
\item{oneword}{One word, surrounded by standard quote marks, or a vector of words}
\item{span}{span of the lowess line (controls the degree of smoothing). Default is 0.4}
\item{se}{logical, show or hide standard error region of smoother line, Default is TRUE.}
}
\value{
Returns a ggplot object with publication year on the horizontal axis and log relative frequency on the vertical axis. Each point represents a single document.
}
\description{
Function to plot changes in the relative frequency of a word over time. The relative frequency is the frequency of the word in a document divided by the total number of words in a document. For use with JSTOR's Data for Research datasets (http://dfr.jstor.org/).
}
\examples{
## JSTOR_1word(unpack1grams, "diamonds")
## JSTOR_1word(unpack1grams, c("diamonds", "pearls"), span = 0.4, se = FALSE) +
## scale_y_continuous(trans=log2_trans()) # to diminish the effect of a few extreme values
}
|
#' Create HCL parameter-set
#'
#' This follows the colorspace scheme.
#'
#' @inheritParams colorspace::sequential_hcl
#'
#' @return Object with S3 class `pev_hcl`
#' @examples
#' pev_hcl(h1 = 0, h2 = 360, c1 = 60, l1 = 60)
#' @export
#'
pev_hcl <- function(type = c("qualitative", "sequential", "diverging"),
h1, h2 = NULL, c1, c2 = NULL,
l1, l2 = NULL, p1 = NULL, p2 = NULL, cmax = NULL,
fixup = TRUE) {
`%|na|%` <- function(x, y) {
if (is.null(x) || is.na(x)) {
return(y)
}
x
}
if (identical(type, "qualitative")) {
h2 <- h2 %|na|% (h1 + 360)
c2 <- c2 %|na|% c1
} else {
h2 <- h2 %|na|% h1
c2 <- c2 %|na|% 0
}
l2 <- l2 %|na|% l1
p1 <- p1 %|na|% 1
p2 <- p2 %|na|% p1
if (identical(type, "diverging")) {
c2 <- c2 %|na|% NA_real_
} else {
c2 <- c2 %|na|% c1
l2 <- l2 %|na|% l1
}
# want to permit NA here
cmax <- cmax %||% NA_real_
pev_hcl = structure(
list(
type = match.arg(type),
h1 = h1,
h2 = h2,
c1 = c1,
c2 = c2,
l1 = l1,
l2 = l2,
p1 = p1,
p2 = p2,
cmax = cmax,
fixup = fixup
),
class = "pev_hcl"
)
}
print.pev_hcl <- function(x, ...) {
f <- function(x) {
sprintf("% 7.2f", x)
}
print(
glue::glue(
"HCL Parameters (colorspace)",
"Type:\t\t{x$type}",
"Hue:\t\t[1]: {f(x$h1)}\t[2]: {f(x$h2)}",
"Chroma:\t\t[1]: {f(x$c1)}\t[2]: {f(x$c2)}\tmax: {f(x$cmax)}",
"Luminance:\t[1]: {f(x$l1)}\t[2]: {f(x$l2)}",
"Exponent:\t[1]: {f(x$p1)}\t[2]: {f(x$p2)}",
.sep = "\n"
)
)
invisible(x)
}
#' Create list of HCL parameter-sets
#'
#' For each row in the `hcl_palettes` data frame
#'
#' @param hcl_palettes Object with S3 class `hcl_palettes`,
#' created using [colorspace::hcl_palettes()].
#'
#' @return Named list, elements are objects with S3 class `pev_hcl`
#' @export
#'
pev_map_hcl <- function(hcl_palettes) {
assertthat::assert_that(
inherits(hcl_palettes, "hcl_palettes"),
msg = "Argument `hcl_palettes` must inherit from colorspace `hcl_palettes`."
)
# fix type -> one of "qualitative", "sequential", "diverging"
levels(hcl_palettes$type) <-
c("qualitative", "sequential", "sequential", "diverging")
hcl_palettes$type <- as.character(hcl_palettes$type)
# want to convert to named list of lists: one element for each row
hcl_list <-
stats::setNames(
split(hcl_palettes, seq(nrow(hcl_palettes))),
rownames(hcl_palettes)
)
hcl_list <- purrr::map(hcl_list, as.list)
hcl_list <- purrr::map(hcl_list, ~do.call(pev_hcl, .x))
hcl_list
}
| /R/hcl_param.R | permissive | ijlyttle/paleval | R | false | false | 2,697 | r | #' Create HCL parameter-set
#'
#' This follows the colorspace scheme.
#'
#' @inheritParams colorspace::sequential_hcl
#'
#' @return Object with S3 class `pev_hcl`
#' @examples
#' pev_hcl(h1 = 0, h2 = 360, c1 = 60, l1 = 60)
#' @export
#'
pev_hcl <- function(type = c("qualitative", "sequential", "diverging"),
h1, h2 = NULL, c1, c2 = NULL,
l1, l2 = NULL, p1 = NULL, p2 = NULL, cmax = NULL,
fixup = TRUE) {
`%|na|%` <- function(x, y) {
if (is.null(x) || is.na(x)) {
return(y)
}
x
}
if (identical(type, "qualitative")) {
h2 <- h2 %|na|% (h1 + 360)
c2 <- c2 %|na|% c1
} else {
h2 <- h2 %|na|% h1
c2 <- c2 %|na|% 0
}
l2 <- l2 %|na|% l1
p1 <- p1 %|na|% 1
p2 <- p2 %|na|% p1
if (identical(type, "diverging")) {
c2 <- c2 %|na|% NA_real_
} else {
c2 <- c2 %|na|% c1
l2 <- l2 %|na|% l1
}
# want to permit NA here
cmax <- cmax %||% NA_real_
pev_hcl = structure(
list(
type = match.arg(type),
h1 = h1,
h2 = h2,
c1 = c1,
c2 = c2,
l1 = l1,
l2 = l2,
p1 = p1,
p2 = p2,
cmax = cmax,
fixup = fixup
),
class = "pev_hcl"
)
}
print.pev_hcl <- function(x, ...) {
f <- function(x) {
sprintf("% 7.2f", x)
}
print(
glue::glue(
"HCL Parameters (colorspace)",
"Type:\t\t{x$type}",
"Hue:\t\t[1]: {f(x$h1)}\t[2]: {f(x$h2)}",
"Chroma:\t\t[1]: {f(x$c1)}\t[2]: {f(x$c2)}\tmax: {f(x$cmax)}",
"Luminance:\t[1]: {f(x$l1)}\t[2]: {f(x$l2)}",
"Exponent:\t[1]: {f(x$p1)}\t[2]: {f(x$p2)}",
.sep = "\n"
)
)
invisible(x)
}
#' Create list of HCL parameter-sets
#'
#' For each row in the `hcl_palettes` data frame
#'
#' @param hcl_palettes Object with S3 class `hcl_palettes`,
#' created using [colorspace::hcl_palettes()].
#'
#' @return Named list, elements are objects with S3 class `pev_hcl`
#' @export
#'
pev_map_hcl <- function(hcl_palettes) {
assertthat::assert_that(
inherits(hcl_palettes, "hcl_palettes"),
msg = "Argument `hcl_palettes` must inherit from colorspace `hcl_palettes`."
)
# fix type -> one of "qualitative", "sequential", "diverging"
levels(hcl_palettes$type) <-
c("qualitative", "sequential", "sequential", "diverging")
hcl_palettes$type <- as.character(hcl_palettes$type)
# want to convert to named list of lists: one element for each row
hcl_list <-
stats::setNames(
split(hcl_palettes, seq(nrow(hcl_palettes))),
rownames(hcl_palettes)
)
hcl_list <- purrr::map(hcl_list, as.list)
hcl_list <- purrr::map(hcl_list, ~do.call(pev_hcl, .x))
hcl_list
}
|
# 2D plot based on path FC
# position socre from 9-1
# GO BP for a look
# ------------------------
rm(list = rm())
library(tidyverse)
human_bp <- read.csv("human_bp_fc_ps.txt", sep = "\t", header = T)
mouse_bp <- read.csv("mouse_bp_fc_ps.txt", sep = "\t", header = T)
dat <- inner_join(mouse_bp, human_bp, by = "GO.ID") %>%
dplyr::select(GO.ID, Term.x, ps.x, ps.y,
classicFisher.x, classicFisher.y)
dat$group <- ifelse(dat$ps.x * dat$ps.y > 0,
ifelse(abs(dat$ps.x) >= 0.8 & abs(dat$ps.y) >= 0.8, "corr", "other"),
ifelse(abs(dat$ps.x) >= 0.8 & abs(dat$ps.y) >= 0.8, "anti", "other"))
dat$sig <- ifelse(dat$classicFisher.x < 0.01 & dat$classicFisher.y < 0.01, "bothsig",
ifelse(dat$classicFisher.x < 0.01, "msig",
ifelse(dat$classicFisher.y < 0.01, "hsig", "no")))
### dot plot
## x: moue path position score
## y: human path position score
theme_set(
theme_classic() +
theme(legend.position = "right"))
#png("figs/2dgobp_pathfcps.png", res = 300)
p <- ggplot(dat, #%>% filter(padj.x <= 0.05 | padj.y <= 0.05),
aes(x = ps.x, y = ps.y))
p + geom_point(alpha = .6, size = 1, aes(color = group, shape = sig)) +
#size = dat$size.x/dat$size.y)) + # size are the same
scale_color_manual(values = c("#D43F3A", "#5CB85C", "#7C878E")) +
# geom_text(data = dat %>%
# filter(group == "corr" &
# padj.x <= 0.01 & padj.y <= 0.01),
# mapping = aes(label = pathway), size = 3) +
labs(title = "2D GOBP pathways",
x = "Arrested / 8C pathway FC", y = "Diapause / E4.5 pathway FC")
ggsave(width = 7.6, height = 7.6, filename = "figs/2dgobp_pathfcps.pdf")
#dev.off()
| /cross-species/10-1.2D_pathfc_ps.R | no_license | xscapintime/crspecies_RNAseq-analysis | R | false | false | 1,888 | r | # 2D plot based on path FC
# position socre from 9-1
# GO BP for a look
# ------------------------
rm(list = rm())
library(tidyverse)
human_bp <- read.csv("human_bp_fc_ps.txt", sep = "\t", header = T)
mouse_bp <- read.csv("mouse_bp_fc_ps.txt", sep = "\t", header = T)
dat <- inner_join(mouse_bp, human_bp, by = "GO.ID") %>%
dplyr::select(GO.ID, Term.x, ps.x, ps.y,
classicFisher.x, classicFisher.y)
dat$group <- ifelse(dat$ps.x * dat$ps.y > 0,
ifelse(abs(dat$ps.x) >= 0.8 & abs(dat$ps.y) >= 0.8, "corr", "other"),
ifelse(abs(dat$ps.x) >= 0.8 & abs(dat$ps.y) >= 0.8, "anti", "other"))
dat$sig <- ifelse(dat$classicFisher.x < 0.01 & dat$classicFisher.y < 0.01, "bothsig",
ifelse(dat$classicFisher.x < 0.01, "msig",
ifelse(dat$classicFisher.y < 0.01, "hsig", "no")))
### dot plot
## x: moue path position score
## y: human path position score
theme_set(
theme_classic() +
theme(legend.position = "right"))
#png("figs/2dgobp_pathfcps.png", res = 300)
p <- ggplot(dat, #%>% filter(padj.x <= 0.05 | padj.y <= 0.05),
aes(x = ps.x, y = ps.y))
p + geom_point(alpha = .6, size = 1, aes(color = group, shape = sig)) +
#size = dat$size.x/dat$size.y)) + # size are the same
scale_color_manual(values = c("#D43F3A", "#5CB85C", "#7C878E")) +
# geom_text(data = dat %>%
# filter(group == "corr" &
# padj.x <= 0.01 & padj.y <= 0.01),
# mapping = aes(label = pathway), size = 3) +
labs(title = "2D GOBP pathways",
x = "Arrested / 8C pathway FC", y = "Diapause / E4.5 pathway FC")
ggsave(width = 7.6, height = 7.6, filename = "figs/2dgobp_pathfcps.pdf")
#dev.off()
|
rm(list = ls())
library(nnet)
rm(list = ls())
library(dplyr)
library(tidyr)
load("all_data_with_neighbor_count.Rdata")
all_data <- all_data %>% filter(is.na(Dollar) == FALSE) #Get rid of rows with fewer than 8 neighbors
next_year <- all_data %>% select(X, Y, Status, Treatment, Replicate, Year) #just select the following years data
next_year <- next_year %>% mutate(Year = Year - 1) %>% rename(StatusNext = Status)#rename the status column
all_transitions <- inner_join(all_data, next_year) append using the id columns the next years data to it.
# Here one could subset the data (for example filter(Year == 14) would take only the transitions observed 2014->2015)
model_current_status <- multinom(StatusNext ~ as.factor(Status) + Empty + Dollar + Grass, data = all_transitions)#Multinomial logistic model
stupid_model <- multinom(StatusNext ~ 1, data = all_transitions)#null model
exp(as.numeric(logLik(stupid_model)) / nrow(all_transitions)) #basic structure for testing what proportion of the observations it guesses correctly
model_only_neigh <- multinom(StatusNext ~ Empty + Dollar + Grass, data = all_transitions)#mulitnom model of just neighbors
model_only_sign <- multinom(StatusNext ~ as.factor(Status) + I((Dollar) / (Grass + Dollar)), data = all_transitions) #current best fit based on proportions of neighbors
all_transitions$model_st <- rep(0, nrow(all_transitions)) # this script makes an empty column for the probilities to go
all_transitions$model_ne <- rep(0, nrow(all_transitions))
for(i in 1:nrow(all_transitions)){
my_next <- as.integer(all_transitions$StatusNext[i])
all_transitions$model_st[i] <- model_current_status$fitted.values[i, my_next + 1]
all_transitions$model_ne[i] <- model_only_neigh$fitted.values[i, my_next + 1]
} #this function puts fitted values of those probabilities into those columns
# all possible states
for_simulations_curr_status <- expand.grid(0:2, 0:8, 0:8, 0:8) #make a structure for all possible combinations of starting conditions, neighbor states
# filter those that don't have exactly 8 neighbors
for_simulations_curr_status <- for_simulations_curr_status[rowSums(for_simulations_curr_status[,-1]) == 8, ] #winnow it down
# make into a data frame
for_simulations_curr_status <- data.frame(for_simulations_curr_status)
colnames(for_simulations_curr_status) <- c("Status", "Empty", "Dollar", "Grass")
tmp <- predict(model_current_status, for_simulations_curr_status, "probs")
colnames(tmp) <- c("pEmpty", "pDollar", "pGrass")
for_simulations_curr_status <- cbind(for_simulations_curr_status, tmp)
# # Example from https://www.r-bloggers.com/how-to-multinomial-regression-models-in-r/
# n <- 1000
# df1 <- data.frame(x1=runif(n,0,100),
# x2=runif(n,0,100))
# df1 <- transform(df1,
# y=1+ifelse(100 - x1 - x2 + rnorm(n,sd=10) < 0, 0,
# ifelse(100 - 2*x2 + rnorm(n,sd=10) < 0, 1, 2)),
# set="Original")
#
# mod <- multinom(y ~ x1 + x2, df1)
# get_probability <- function(x){
# predict(mod, x, "probs")
# }
| /code/multinomial.R | no_license | amykhenry/RacetrackData | R | false | false | 3,052 | r | rm(list = ls())
library(nnet)
rm(list = ls())
library(dplyr)
library(tidyr)
load("all_data_with_neighbor_count.Rdata")
all_data <- all_data %>% filter(is.na(Dollar) == FALSE) #Get rid of rows with fewer than 8 neighbors
next_year <- all_data %>% select(X, Y, Status, Treatment, Replicate, Year) #just select the following years data
next_year <- next_year %>% mutate(Year = Year - 1) %>% rename(StatusNext = Status)#rename the status column
all_transitions <- inner_join(all_data, next_year) append using the id columns the next years data to it.
# Here one could subset the data (for example filter(Year == 14) would take only the transitions observed 2014->2015)
model_current_status <- multinom(StatusNext ~ as.factor(Status) + Empty + Dollar + Grass, data = all_transitions)#Multinomial logistic model
stupid_model <- multinom(StatusNext ~ 1, data = all_transitions)#null model
exp(as.numeric(logLik(stupid_model)) / nrow(all_transitions)) #basic structure for testing what proportion of the observations it guesses correctly
model_only_neigh <- multinom(StatusNext ~ Empty + Dollar + Grass, data = all_transitions)#mulitnom model of just neighbors
model_only_sign <- multinom(StatusNext ~ as.factor(Status) + I((Dollar) / (Grass + Dollar)), data = all_transitions) #current best fit based on proportions of neighbors
all_transitions$model_st <- rep(0, nrow(all_transitions)) # this script makes an empty column for the probilities to go
all_transitions$model_ne <- rep(0, nrow(all_transitions))
for(i in 1:nrow(all_transitions)){
my_next <- as.integer(all_transitions$StatusNext[i])
all_transitions$model_st[i] <- model_current_status$fitted.values[i, my_next + 1]
all_transitions$model_ne[i] <- model_only_neigh$fitted.values[i, my_next + 1]
} #this function puts fitted values of those probabilities into those columns
# all possible states
for_simulations_curr_status <- expand.grid(0:2, 0:8, 0:8, 0:8) #make a structure for all possible combinations of starting conditions, neighbor states
# filter those that don't have exactly 8 neighbors
for_simulations_curr_status <- for_simulations_curr_status[rowSums(for_simulations_curr_status[,-1]) == 8, ] #winnow it down
# make into a data frame
for_simulations_curr_status <- data.frame(for_simulations_curr_status)
colnames(for_simulations_curr_status) <- c("Status", "Empty", "Dollar", "Grass")
tmp <- predict(model_current_status, for_simulations_curr_status, "probs")
colnames(tmp) <- c("pEmpty", "pDollar", "pGrass")
for_simulations_curr_status <- cbind(for_simulations_curr_status, tmp)
# # Example from https://www.r-bloggers.com/how-to-multinomial-regression-models-in-r/
# n <- 1000
# df1 <- data.frame(x1=runif(n,0,100),
# x2=runif(n,0,100))
# df1 <- transform(df1,
# y=1+ifelse(100 - x1 - x2 + rnorm(n,sd=10) < 0, 0,
# ifelse(100 - 2*x2 + rnorm(n,sd=10) < 0, 1, 2)),
# set="Original")
#
# mod <- multinom(y ~ x1 + x2, df1)
# get_probability <- function(x){
# predict(mod, x, "probs")
# }
|
setwd("/Users/michael/Documents/r/coursera/ExploratoryDataAnalysis/ExData_Plotting1")
power <- read.table("/Users/michael/Documents/r/coursera/ExploratoryDataAnalysis/household_power_consumption.txt",
header = TRUE, sep = ";", na.strings = "?",
colClasses = c("character", "character", "numeric", "numeric", "numeric", "numeric", "numeric", "numeric", "numeric"))
power$DateTime <- as.POSIXct(paste(power$Date, power$Time), format="%d/%m/%Y %H:%M:%S")
power$Date <- as.Date(power$Date, format = "%d/%m/%Y")
powerslice = subset(power, power$Date == as.Date(c("02/01/2007"), format = "%m/%d/%Y") |
power$Date == as.Date(c("02/02/2007"), format = "%m/%d/%Y"))
# Plot 1
png(filename = "plot1.png", width = 480, height = 480)
hist(powerslice$Global_active_power, col = "red", main = "Global Active Power", xlab = "Global Active Power (kilowatts)")
dev.off()
| /plot1.R | no_license | michaelrstuart/ExData_Plotting1 | R | false | false | 869 | r |
setwd("/Users/michael/Documents/r/coursera/ExploratoryDataAnalysis/ExData_Plotting1")
power <- read.table("/Users/michael/Documents/r/coursera/ExploratoryDataAnalysis/household_power_consumption.txt",
header = TRUE, sep = ";", na.strings = "?",
colClasses = c("character", "character", "numeric", "numeric", "numeric", "numeric", "numeric", "numeric", "numeric"))
power$DateTime <- as.POSIXct(paste(power$Date, power$Time), format="%d/%m/%Y %H:%M:%S")
power$Date <- as.Date(power$Date, format = "%d/%m/%Y")
powerslice = subset(power, power$Date == as.Date(c("02/01/2007"), format = "%m/%d/%Y") |
power$Date == as.Date(c("02/02/2007"), format = "%m/%d/%Y"))
# Plot 1
png(filename = "plot1.png", width = 480, height = 480)
hist(powerslice$Global_active_power, col = "red", main = "Global Active Power", xlab = "Global Active Power (kilowatts)")
dev.off()
|
# Get data from the website and unzip it
fileURL <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip"
download.file(fileURL, destfile="./data.zip")
unzip("data.zip")
# load data for dates between 2007-02-01 and 2007-02-02
require(sqldf)
data <-read.csv.sql("household_power_consumption.txt", sep=";",
"select * from file where Date = '1/2/2007' OR Date = '2/2/2007'",
colClasses=c("Date", "character", "numeric", "numeric", "numeric", "numeric",
"numeric", "numeric", "numeric"))
# create a column with date and time bound together
data$datetime <- strptime(paste(data$Date, data$Time), format='%d/%m/%Y %H:%M:%S')
png(file="plot4.png")
# setup layout
par(mfcol=c(2,2))
# plot all plots
with (data, {
# plot the first plot
plot(data$datetime,data$Global_active_power, type="n",ylab="Global Active Power", xlab="" )
lines(data$datetime,data$Global_active_power, type="l")
# plot the second plot
plot(data$datetime,data$Sub_metering_1, type="n",ylab="Energy sub metering", xlab="" )
lines(data$datetime,data$Sub_metering_1, type="l", col="black")
lines(data$datetime,data$Sub_metering_2, type="l", col="red")
lines(data$datetime,data$Sub_metering_3, type="l", col="blue")
legend("topright", lty=c(1,1,1), col = c("black","red", "blue" ),bty = "n", cex=0.9,
legend = c("Sub_metering_1","Sub_metering_2","Sub_metering_3"))
# plot the third plot
plot(data$datetime,data$Voltage, type="n",ylab="Voltage", xlab="" )
lines(data$datetime,data$Voltage, type="l")
# plot the fourth plot
plot(data$datetime,data$Global_reactive_power, type="n",ylab="Global_reactive_power", xlab="" )
lines(data$datetime,data$Global_reactive_power, type="l")
})
# copy plot to png file
dev.off() | /plot4.R | no_license | tbelorusets/ExData_Plotting1 | R | false | false | 1,795 | r | # Get data from the website and unzip it
fileURL <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip"
download.file(fileURL, destfile="./data.zip")
unzip("data.zip")
# load data for dates between 2007-02-01 and 2007-02-02
require(sqldf)
data <-read.csv.sql("household_power_consumption.txt", sep=";",
"select * from file where Date = '1/2/2007' OR Date = '2/2/2007'",
colClasses=c("Date", "character", "numeric", "numeric", "numeric", "numeric",
"numeric", "numeric", "numeric"))
# create a column with date and time bound together
data$datetime <- strptime(paste(data$Date, data$Time), format='%d/%m/%Y %H:%M:%S')
png(file="plot4.png")
# setup layout
par(mfcol=c(2,2))
# plot all plots
with (data, {
# plot the first plot
plot(data$datetime,data$Global_active_power, type="n",ylab="Global Active Power", xlab="" )
lines(data$datetime,data$Global_active_power, type="l")
# plot the second plot
plot(data$datetime,data$Sub_metering_1, type="n",ylab="Energy sub metering", xlab="" )
lines(data$datetime,data$Sub_metering_1, type="l", col="black")
lines(data$datetime,data$Sub_metering_2, type="l", col="red")
lines(data$datetime,data$Sub_metering_3, type="l", col="blue")
legend("topright", lty=c(1,1,1), col = c("black","red", "blue" ),bty = "n", cex=0.9,
legend = c("Sub_metering_1","Sub_metering_2","Sub_metering_3"))
# plot the third plot
plot(data$datetime,data$Voltage, type="n",ylab="Voltage", xlab="" )
lines(data$datetime,data$Voltage, type="l")
# plot the fourth plot
plot(data$datetime,data$Global_reactive_power, type="n",ylab="Global_reactive_power", xlab="" )
lines(data$datetime,data$Global_reactive_power, type="l")
})
# copy plot to png file
dev.off() |
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/utility_functions.R
\name{print.multiRDPGfit}
\alias{print.multiRDPGfit}
\title{Print object from \code{multiRDPG}}
\usage{
\method{print}{multiRDPGfit}(x, ...)
}
\arguments{
\item{x}{multiRDPGfit object from function \code{multiRDPG}}
\item{...}{further arguments passed to or from other methods}
}
\description{
Print object from \code{multiRDPG}
}
\seealso{
\code{\link{multiRDPG}}
}
\author{
Agnes Martine Nielsen (agni@dtu.dk)
}
| /man/print.multiRDPGfit.Rd | no_license | cran/multiRDPG | R | false | true | 513 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/utility_functions.R
\name{print.multiRDPGfit}
\alias{print.multiRDPGfit}
\title{Print object from \code{multiRDPG}}
\usage{
\method{print}{multiRDPGfit}(x, ...)
}
\arguments{
\item{x}{multiRDPGfit object from function \code{multiRDPG}}
\item{...}{further arguments passed to or from other methods}
}
\description{
Print object from \code{multiRDPG}
}
\seealso{
\code{\link{multiRDPG}}
}
\author{
Agnes Martine Nielsen (agni@dtu.dk)
}
|
## This function creates a matrix that is able to cache it's inverse.
## It seems to be making an object like an object oriented language
makeCacheMatrix <- function(x = matrix()) {
inversedMatrix <- NULL
set <- function(y) {
x <<- y
inversedMatrix <<- NULL
}
get <- function() x
setInversedMatrix <- function(inverse) inversedMatrix <<- inverse
getInversedMatrix <- function() inversedMatrix
list(set=set, get=get, setInversedMatrix=setInversedMatrix, getInversedMatrix=getInversedMatrix)
}
## This function computes the inverse of the matrix object created in the first function
## called makeCacheMatrix. If the inverse has already been calculated (and the matrix
## has not changed), then the cachesolve should retrieve the inverse from the cache.
cacheSolve <- function(x, ...) {
inversedMatrix <- x$getInversedMatrix()
if(!is.null(inversedMatrix)) {
message("getting cached data.")
return(inversedMatrix)
}
data <- x$get()
# Documentation for Solve can be found here: http://www.statmethods.net/advstats/matrix.html
# solve computes the inverse of the matrix.
inversedMatrix <- solve(data)
x$setInversedMatrix(inversedMatrix)
inversedMatrix
}
| /cachematrix.R | no_license | comeaugilles/ProgrammingAssignment2 | R | false | false | 1,478 | r | ## This function creates a matrix that is able to cache it's inverse.
## It seems to be making an object like an object oriented language
makeCacheMatrix <- function(x = matrix()) {
inversedMatrix <- NULL
set <- function(y) {
x <<- y
inversedMatrix <<- NULL
}
get <- function() x
setInversedMatrix <- function(inverse) inversedMatrix <<- inverse
getInversedMatrix <- function() inversedMatrix
list(set=set, get=get, setInversedMatrix=setInversedMatrix, getInversedMatrix=getInversedMatrix)
}
## This function computes the inverse of the matrix object created in the first function
## called makeCacheMatrix. If the inverse has already been calculated (and the matrix
## has not changed), then the cachesolve should retrieve the inverse from the cache.
cacheSolve <- function(x, ...) {
inversedMatrix <- x$getInversedMatrix()
if(!is.null(inversedMatrix)) {
message("getting cached data.")
return(inversedMatrix)
}
data <- x$get()
# Documentation for Solve can be found here: http://www.statmethods.net/advstats/matrix.html
# solve computes the inverse of the matrix.
inversedMatrix <- solve(data)
x$setInversedMatrix(inversedMatrix)
inversedMatrix
}
|
\name{generateBernoulliLDA}
\alias{generateBernoulliLDA}
\alias{generateBernoulliLDA.rlda}
\title{Simulates a Bernoulli LDA.}
\description{
Simulates a Bernoulli LDA.
}
\usage{
\method{generateBernoulliLDA}{rlda}(seed0, community, variables,
observations, alpha0, alpha1, gamma, ...)
}
\arguments{
\item{seed0}{Initial seed to simulate a Bernoulli LDA.}
\item{community}{Total number of latent clusters. Must be greater than 2.}
\item{variables}{Total number of variables. Must be greater than the number of communities.}
\item{observations}{Total number of observations. Must be greater than 1.}
\item{alpha0}{Scalar hyperparameters that must be positive.}
\item{alpha1}{Scalar hyperparameters that must be positive.}
\item{gamma}{Scalar hyperparameters that must be positive.}
\item{...}{ other arguments may be useful.}
}
\details{
Generates a list with the simulated Theta and Phi matrix of parameters,
Z latent matrix of communities and and Data matrix for the Bernoulli LDA.
}
\author{
\itemize{
\item
Pedro Albuquerque.\cr
\email{pedroa@unb.br}\cr
\url{http://pedrounb.blogspot.com/}
\item
Denis Valle.\cr
\email{drvalle@ufl.edu}\cr
\url{http://denisvalle.weebly.com/}
\item
Daijiang Li.\cr
\email{daijianglee@gmail.com}\cr
}
}
\keyword{generateMultinomialLDA}
\keyword{generateBernoulliLDA}
\keyword{generateBinomialLDA}
\keyword{Rlda}
\seealso{\code{\link{generateMultinomialLDA}}, \code{\link{generateBinomialLDA}}}
\examples{
\dontrun{
#Generate fake data
res<- generateBernoulliLDA.rlda(seed0=9292, community=3,
variables=100, observations=1000,
alpha0=0.01, alpha1=0.01, gamma=0.01)
#Show results
res
}
}
| /Rlda/man/generateBernoulliLDA.Rd | no_license | akhikolla/InformationHouse | R | false | false | 1,827 | rd | \name{generateBernoulliLDA}
\alias{generateBernoulliLDA}
\alias{generateBernoulliLDA.rlda}
\title{Simulates a Bernoulli LDA.}
\description{
Simulates a Bernoulli LDA.
}
\usage{
\method{generateBernoulliLDA}{rlda}(seed0, community, variables,
observations, alpha0, alpha1, gamma, ...)
}
\arguments{
\item{seed0}{Initial seed to simulate a Bernoulli LDA.}
\item{community}{Total number of latent clusters. Must be greater than 2.}
\item{variables}{Total number of variables. Must be greater than the number of communities.}
\item{observations}{Total number of observations. Must be greater than 1.}
\item{alpha0}{Scalar hyperparameters that must be positive.}
\item{alpha1}{Scalar hyperparameters that must be positive.}
\item{gamma}{Scalar hyperparameters that must be positive.}
\item{...}{ other arguments may be useful.}
}
\details{
Generates a list with the simulated Theta and Phi matrix of parameters,
Z latent matrix of communities and and Data matrix for the Bernoulli LDA.
}
\author{
\itemize{
\item
Pedro Albuquerque.\cr
\email{pedroa@unb.br}\cr
\url{http://pedrounb.blogspot.com/}
\item
Denis Valle.\cr
\email{drvalle@ufl.edu}\cr
\url{http://denisvalle.weebly.com/}
\item
Daijiang Li.\cr
\email{daijianglee@gmail.com}\cr
}
}
\keyword{generateMultinomialLDA}
\keyword{generateBernoulliLDA}
\keyword{generateBinomialLDA}
\keyword{Rlda}
\seealso{\code{\link{generateMultinomialLDA}}, \code{\link{generateBinomialLDA}}}
\examples{
\dontrun{
#Generate fake data
res<- generateBernoulliLDA.rlda(seed0=9292, community=3,
variables=100, observations=1000,
alpha0=0.01, alpha1=0.01, gamma=0.01)
#Show results
res
}
}
|
fileNames <- as.list(paste0('barkData/meteo_orduna/amurrio/',
list.files('barkData/meteo_orduna/amurrio/')))
allRaw <- dplyr::bind_rows(lapply(fileNames, data.table::fread))
names(allRaw) <- c(as.character(read.csv('barkData/meteo_Orduna/descripcion_datos.csv')[,2]))
valuesL <- strsplit(allRaw$MEDICION, ',')
allRaw$Value1 <- c(unlist(lapply(valuesL, function(L) L[1])))
allRaw$Value2 <- c(unlist(lapply(valuesL, function(L) L[2])))
write.csv(allRaw, file = 'barkData/meteo_Orduna/temp.csv', row.names = F)
clean <- read.csv('barkData/meteo_Orduna/temp.csv')
clean[which(is.na(clean$Value2)), 'Value2'] <- 0
clean$Value2 <- ifelse(clean$Value2 <= 9, clean$Value2 * 10, clean$Value2)
clean$value <- clean$Value1 + clean$Value2*0.01
clean$DateTime <- paste0(clean$FECHA_MEDICION, ' ', clean$HORA_MEDICION)
clean$DateTime <- lubridate::dmy_hm(as.character(clean$DateTime))
clean <- doBy::orderBy(~DateTime, clean)
codes <- read.csv('barkData/meteo_Orduna/codigo_meteoro.csv')[, c('CODIGO_METEORO', 'short')]
clean <- dplyr::left_join(clean, codes, by = 'CODIGO_METEORO')[,c('DateTime', 'short', 'value')]
meteo <- subset(clean, short == 'P_tot')[, c('DateTime', 'value')]
meteo$Date <- as.Date(meteo$DateTime)
amurrio <- summarise(group_by(meteo, Date), Pday_amu = sum(value))
| /barkRead/amurrio.R | no_license | TerefiGimeno/bark | R | false | false | 1,303 | r | fileNames <- as.list(paste0('barkData/meteo_orduna/amurrio/',
list.files('barkData/meteo_orduna/amurrio/')))
allRaw <- dplyr::bind_rows(lapply(fileNames, data.table::fread))
names(allRaw) <- c(as.character(read.csv('barkData/meteo_Orduna/descripcion_datos.csv')[,2]))
valuesL <- strsplit(allRaw$MEDICION, ',')
allRaw$Value1 <- c(unlist(lapply(valuesL, function(L) L[1])))
allRaw$Value2 <- c(unlist(lapply(valuesL, function(L) L[2])))
write.csv(allRaw, file = 'barkData/meteo_Orduna/temp.csv', row.names = F)
clean <- read.csv('barkData/meteo_Orduna/temp.csv')
clean[which(is.na(clean$Value2)), 'Value2'] <- 0
clean$Value2 <- ifelse(clean$Value2 <= 9, clean$Value2 * 10, clean$Value2)
clean$value <- clean$Value1 + clean$Value2*0.01
clean$DateTime <- paste0(clean$FECHA_MEDICION, ' ', clean$HORA_MEDICION)
clean$DateTime <- lubridate::dmy_hm(as.character(clean$DateTime))
clean <- doBy::orderBy(~DateTime, clean)
codes <- read.csv('barkData/meteo_Orduna/codigo_meteoro.csv')[, c('CODIGO_METEORO', 'short')]
clean <- dplyr::left_join(clean, codes, by = 'CODIGO_METEORO')[,c('DateTime', 'short', 'value')]
meteo <- subset(clean, short == 'P_tot')[, c('DateTime', 'value')]
meteo$Date <- as.Date(meteo$DateTime)
amurrio <- summarise(group_by(meteo, Date), Pday_amu = sum(value))
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/dsdata.R
\name{endpoint.segment}
\alias{endpoint.segment}
\title{End points coordinates of segment(s)}
\usage{
\method{endpoint}{segment}(tr, data, keep = FALSE)
}
\arguments{
\item{data}{Data set with $effort}
}
\value{
epoint
}
\description{
End points coordinates of segment(s)
}
\author{
Fabian E. Bachl <\email{f.e.bachl@bath.ac.uk}>
}
| /man/endpoint.segment.Rd | no_license | dill/inlabru | R | false | true | 420 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/dsdata.R
\name{endpoint.segment}
\alias{endpoint.segment}
\title{End points coordinates of segment(s)}
\usage{
\method{endpoint}{segment}(tr, data, keep = FALSE)
}
\arguments{
\item{data}{Data set with $effort}
}
\value{
epoint
}
\description{
End points coordinates of segment(s)
}
\author{
Fabian E. Bachl <\email{f.e.bachl@bath.ac.uk}>
}
|
#'@title Save 3D Print
#'
#'@description Writes a stereolithography (STL) file that can be used in 3D printing.
#'
#'@param filename String with the filename. If `.stl` is not at the end of the string, it will be appended automatically.
#'@param maxwidth Default `125`. Desired maximum width of the 3D print in millimeters. Uses the units set in `unit` argument. Can also pass in a string, "125mm" or "5in".
#'@param unit Default `mm`. Units of the `maxwidth` argument. Can also be set to inches with `in`.
#'@param rotate Default `TRUE`. If `FALSE`, the map will be printing on its side. This may improve resolution for some 3D printing types.
#'@param remove_extras Default `TRUE`. Removes non-topographic features from base: lines, water, labels, and the shadow.
#'@param clear Default `FALSE`. If `TRUE`, the current `rgl` device will be cleared.
#'@return Writes an STL file to `filename`. Regardless of the unit displayed, the output STL is in millimeters.
#'@export
#'@examples
#'filename_stl = tempfile()
#'
#'#Save the STL file into `filename_stl`
#'\donttest{
#'volcano %>%
#' sphere_shade() %>%
#' plot_3d(volcano,zscale=3)
#'render_snapshot()
#'save_3dprint(filename_stl, clear=TRUE)
#'}
#'
#'#Save the STL file into `filename_stl`, setting maximum width to 100 mm
#'\donttest{
#'volcano %>%
#' sphere_shade() %>%
#' plot_3d(volcano,zscale=3)
#'render_snapshot()
#'save_3dprint(filename_stl, maxwidth = 100, clear=TRUE)
#'}
#'
#'#'#Save the STL file into `filename_stl`, setting maximum width to 4 inches
#'\donttest{
#'volcano %>%
#' sphere_shade() %>%
#' plot_3d(volcano,zscale=3)
#'render_snapshot()
#'save_3dprint(filename_stl, maxwidth = 4, unit = "in", clear=TRUE)
#'}
#'#'#'#Save the STL file into `filename_stl`, setting maximum width (character) to 120mm
#'\donttest{
#'volcano %>%
#' sphere_shade() %>%
#' plot_3d(volcano,zscale=3)
#'render_snapshot()
#'save_3dprint(filename_stl, maxwidth = "120mm", clear=TRUE)
#'}
save_3dprint = function(filename,maxwidth=125,unit="mm",rotate=TRUE,remove_extras = TRUE,
clear=FALSE) {
if(remove_extras) {
idlist = get_ids_with_labels()
remove_ids = idlist$id[!(idlist$raytype %in% c("surface","base"))]
rgl::pop3d(id=remove_ids)
}
if(substring(filename, nchar(filename)-3,nchar(filename)) != ".stl") {
filename = paste0(filename,".stl")
}
inch2mm = function(inch) {
inch/0.0393
}
if(class(maxwidth) == "character") {
unit = substr(maxwidth,nchar(maxwidth)-1,nchar(maxwidth))
maxwidth = as.numeric(substr(maxwidth,1,nchar(maxwidth)-2))
}
if(unit == "in") {
maxwidth = inch2mm(maxwidth)
}
if(!(unit %in% c("in", "mm"))) {
stop(paste0("unit: ",unit," not recognized: use `mm` or `in`."))
}
if(rotate) {
zrot = matrix(0,3,3)
zrot[1,1] = 1
zrot[2,2] = 0
zrot[3,3] = 0
zrot[2,3] = 1
zrot[3,2] = -1
} else {
zrot = matrix(0,3,3)
zrot[1,1] = 1
zrot[2,2] = 1
zrot[3,3] = 1
}
rot_z_90 = function(vec) {
vec %*% zrot
}
temp = paste0(tempfile(),".stl")
rgl::writeSTL(temp)
#Read STL file and manipulate
stlfile = file(temp, "rb")
header = readChar(stlfile, nchars = 80)
numbertriangles = readBin(stlfile, integer(),size=4, endian = "little")
vertexmatrix = matrix(0,nrow=numbertriangles*3,ncol=3)
normalmatrix = matrix(0,nrow=numbertriangles,ncol=3)
zeros = list()
for(i in 1:numbertriangles) {
normalmatrix[i,] = readBin(stlfile, "double",size=4,endian = "little", n=3)
vertexmatrix[3*(i-1)+1,] = readBin(stlfile, "double",size=4,endian = "little", n=3)
vertexmatrix[3*(i-1)+2,] = readBin(stlfile, "double",size=4,endian = "little", n=3)
vertexmatrix[3*(i-1)+3,] = readBin(stlfile, "double",size=4,endian = "little", n=3)
zeros[[i]] = readBin(stlfile, "integer",size=2,endian = "little", n=1)
}
close.connection(stlfile)
dim1width = abs(min(vertexmatrix[,1],na.rm = TRUE)-max(vertexmatrix[,1],na.rm = TRUE))
dim2width = abs(min(vertexmatrix[,3],na.rm = TRUE)-max(vertexmatrix[,3],na.rm = TRUE))
dim3width = abs(min(vertexmatrix[,2],na.rm = TRUE)-max(vertexmatrix[,2],na.rm = TRUE))
maxdim = max(dim1width,dim2width)
multiplier = maxwidth/maxdim
stlfilewrite = file(filename, "wb")
writeChar(header,stlfilewrite,nchars = 80,eos=NULL)
adjustednumbertriangles = 0L
for(i in 1:numbertriangles) {
if(all(!is.nan(normalmatrix[i,,drop=FALSE])) && all(!is.nan(vertexmatrix[3*(i-1)+1,,drop=FALSE])) &&
all(!is.nan(vertexmatrix[3*(i-1)+2,,drop=FALSE])) && all(!is.nan(vertexmatrix[3*(i-1)+3,,drop=FALSE]))) {
adjustednumbertriangles = adjustednumbertriangles + 1L
}
}
writeBin(adjustednumbertriangles, stlfilewrite, size=4, endian = "little")
for(i in 1:numbertriangles) {
if(all(!is.nan(normalmatrix[i,,drop=FALSE])) && all(!is.nan(vertexmatrix[3*(i-1)+1,,drop=FALSE])) &&
all(!is.nan(vertexmatrix[3*(i-1)+2,,drop=FALSE])) && all(!is.nan(vertexmatrix[3*(i-1)+3,,drop=FALSE]))) {
writeBin(as.double(rot_z_90(normalmatrix[i,,drop=FALSE])), stlfilewrite,endian = "little",size=4)
writeBin(as.double(rot_z_90(vertexmatrix[3*(i-1)+1,,drop=FALSE])*multiplier), stlfilewrite, endian = "little",size=4)
writeBin(as.double(rot_z_90(vertexmatrix[3*(i-1)+2,,drop=FALSE])*multiplier), stlfilewrite, endian = "little",size=4)
writeBin(as.double(rot_z_90(vertexmatrix[3*(i-1)+3,,drop=FALSE])*multiplier), stlfilewrite, endian = "little",size=4)
writeBin(0L, stlfilewrite,size=2, endian = "little")
}
}
close.connection(stlfilewrite)
if(!rotate) {
temp1 = dim2width
dim2width = dim3width
dim3width = temp1
}
if(unit == "mm") {
message(sprintf("Dimensions of model are: %1.1f mm x %1.1f mm x %1.1f mm",dim1width*multiplier,dim2width*multiplier,dim3width*multiplier))
} else {
message(sprintf("Dimensions of model are: %1.2f in x %1.2f in x %1.2f in",dim1width*0.0393*multiplier,dim2width*0.0393*multiplier,dim3width*0.0393*multiplier))
}
if(clear) {
rgl::rgl.clear()
}
} | /R/save_3dprint.R | no_license | sqjin/rayshader | R | false | false | 6,040 | r | #'@title Save 3D Print
#'
#'@description Writes a stereolithography (STL) file that can be used in 3D printing.
#'
#'@param filename String with the filename. If `.stl` is not at the end of the string, it will be appended automatically.
#'@param maxwidth Default `125`. Desired maximum width of the 3D print in millimeters. Uses the units set in `unit` argument. Can also pass in a string, "125mm" or "5in".
#'@param unit Default `mm`. Units of the `maxwidth` argument. Can also be set to inches with `in`.
#'@param rotate Default `TRUE`. If `FALSE`, the map will be printing on its side. This may improve resolution for some 3D printing types.
#'@param remove_extras Default `TRUE`. Removes non-topographic features from base: lines, water, labels, and the shadow.
#'@param clear Default `FALSE`. If `TRUE`, the current `rgl` device will be cleared.
#'@return Writes an STL file to `filename`. Regardless of the unit displayed, the output STL is in millimeters.
#'@export
#'@examples
#'filename_stl = tempfile()
#'
#'#Save the STL file into `filename_stl`
#'\donttest{
#'volcano %>%
#' sphere_shade() %>%
#' plot_3d(volcano,zscale=3)
#'render_snapshot()
#'save_3dprint(filename_stl, clear=TRUE)
#'}
#'
#'#Save the STL file into `filename_stl`, setting maximum width to 100 mm
#'\donttest{
#'volcano %>%
#' sphere_shade() %>%
#' plot_3d(volcano,zscale=3)
#'render_snapshot()
#'save_3dprint(filename_stl, maxwidth = 100, clear=TRUE)
#'}
#'
#'#'#Save the STL file into `filename_stl`, setting maximum width to 4 inches
#'\donttest{
#'volcano %>%
#' sphere_shade() %>%
#' plot_3d(volcano,zscale=3)
#'render_snapshot()
#'save_3dprint(filename_stl, maxwidth = 4, unit = "in", clear=TRUE)
#'}
#'#'#'#Save the STL file into `filename_stl`, setting maximum width (character) to 120mm
#'\donttest{
#'volcano %>%
#' sphere_shade() %>%
#' plot_3d(volcano,zscale=3)
#'render_snapshot()
#'save_3dprint(filename_stl, maxwidth = "120mm", clear=TRUE)
#'}
save_3dprint = function(filename,maxwidth=125,unit="mm",rotate=TRUE,remove_extras = TRUE,
clear=FALSE) {
if(remove_extras) {
idlist = get_ids_with_labels()
remove_ids = idlist$id[!(idlist$raytype %in% c("surface","base"))]
rgl::pop3d(id=remove_ids)
}
if(substring(filename, nchar(filename)-3,nchar(filename)) != ".stl") {
filename = paste0(filename,".stl")
}
inch2mm = function(inch) {
inch/0.0393
}
if(class(maxwidth) == "character") {
unit = substr(maxwidth,nchar(maxwidth)-1,nchar(maxwidth))
maxwidth = as.numeric(substr(maxwidth,1,nchar(maxwidth)-2))
}
if(unit == "in") {
maxwidth = inch2mm(maxwidth)
}
if(!(unit %in% c("in", "mm"))) {
stop(paste0("unit: ",unit," not recognized: use `mm` or `in`."))
}
if(rotate) {
zrot = matrix(0,3,3)
zrot[1,1] = 1
zrot[2,2] = 0
zrot[3,3] = 0
zrot[2,3] = 1
zrot[3,2] = -1
} else {
zrot = matrix(0,3,3)
zrot[1,1] = 1
zrot[2,2] = 1
zrot[3,3] = 1
}
rot_z_90 = function(vec) {
vec %*% zrot
}
temp = paste0(tempfile(),".stl")
rgl::writeSTL(temp)
#Read STL file and manipulate
stlfile = file(temp, "rb")
header = readChar(stlfile, nchars = 80)
numbertriangles = readBin(stlfile, integer(),size=4, endian = "little")
vertexmatrix = matrix(0,nrow=numbertriangles*3,ncol=3)
normalmatrix = matrix(0,nrow=numbertriangles,ncol=3)
zeros = list()
for(i in 1:numbertriangles) {
normalmatrix[i,] = readBin(stlfile, "double",size=4,endian = "little", n=3)
vertexmatrix[3*(i-1)+1,] = readBin(stlfile, "double",size=4,endian = "little", n=3)
vertexmatrix[3*(i-1)+2,] = readBin(stlfile, "double",size=4,endian = "little", n=3)
vertexmatrix[3*(i-1)+3,] = readBin(stlfile, "double",size=4,endian = "little", n=3)
zeros[[i]] = readBin(stlfile, "integer",size=2,endian = "little", n=1)
}
close.connection(stlfile)
dim1width = abs(min(vertexmatrix[,1],na.rm = TRUE)-max(vertexmatrix[,1],na.rm = TRUE))
dim2width = abs(min(vertexmatrix[,3],na.rm = TRUE)-max(vertexmatrix[,3],na.rm = TRUE))
dim3width = abs(min(vertexmatrix[,2],na.rm = TRUE)-max(vertexmatrix[,2],na.rm = TRUE))
maxdim = max(dim1width,dim2width)
multiplier = maxwidth/maxdim
stlfilewrite = file(filename, "wb")
writeChar(header,stlfilewrite,nchars = 80,eos=NULL)
adjustednumbertriangles = 0L
for(i in 1:numbertriangles) {
if(all(!is.nan(normalmatrix[i,,drop=FALSE])) && all(!is.nan(vertexmatrix[3*(i-1)+1,,drop=FALSE])) &&
all(!is.nan(vertexmatrix[3*(i-1)+2,,drop=FALSE])) && all(!is.nan(vertexmatrix[3*(i-1)+3,,drop=FALSE]))) {
adjustednumbertriangles = adjustednumbertriangles + 1L
}
}
writeBin(adjustednumbertriangles, stlfilewrite, size=4, endian = "little")
for(i in 1:numbertriangles) {
if(all(!is.nan(normalmatrix[i,,drop=FALSE])) && all(!is.nan(vertexmatrix[3*(i-1)+1,,drop=FALSE])) &&
all(!is.nan(vertexmatrix[3*(i-1)+2,,drop=FALSE])) && all(!is.nan(vertexmatrix[3*(i-1)+3,,drop=FALSE]))) {
writeBin(as.double(rot_z_90(normalmatrix[i,,drop=FALSE])), stlfilewrite,endian = "little",size=4)
writeBin(as.double(rot_z_90(vertexmatrix[3*(i-1)+1,,drop=FALSE])*multiplier), stlfilewrite, endian = "little",size=4)
writeBin(as.double(rot_z_90(vertexmatrix[3*(i-1)+2,,drop=FALSE])*multiplier), stlfilewrite, endian = "little",size=4)
writeBin(as.double(rot_z_90(vertexmatrix[3*(i-1)+3,,drop=FALSE])*multiplier), stlfilewrite, endian = "little",size=4)
writeBin(0L, stlfilewrite,size=2, endian = "little")
}
}
close.connection(stlfilewrite)
if(!rotate) {
temp1 = dim2width
dim2width = dim3width
dim3width = temp1
}
if(unit == "mm") {
message(sprintf("Dimensions of model are: %1.1f mm x %1.1f mm x %1.1f mm",dim1width*multiplier,dim2width*multiplier,dim3width*multiplier))
} else {
message(sprintf("Dimensions of model are: %1.2f in x %1.2f in x %1.2f in",dim1width*0.0393*multiplier,dim2width*0.0393*multiplier,dim3width*0.0393*multiplier))
}
if(clear) {
rgl::rgl.clear()
}
} |
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/old_silhouette.wsum.R
\name{silhouette.wsum}
\alias{silhouette.wsum}
\title{Weighted Sum of Multiple Persistence Silhouettes}
\usage{
silhouette.wsum(slist, weight)
}
\description{
Weighted Sum of Multiple Persistence Silhouettes
}
| /man/silhouette.wsum.Rd | permissive | kyound/TDAkit | R | false | true | 310 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/old_silhouette.wsum.R
\name{silhouette.wsum}
\alias{silhouette.wsum}
\title{Weighted Sum of Multiple Persistence Silhouettes}
\usage{
silhouette.wsum(slist, weight)
}
\description{
Weighted Sum of Multiple Persistence Silhouettes
}
|
p_load(plyr,
knitr,
kableExtra,
formattable,
dplyr,
webshot,
qdapRegex,
stringr,
install = TRUE,
update = getOption("pac_update"),
character.only = FALSE)
tgen_lme4 <- as.data.frame(model_gen_IDA_lme4[c(2:4),])
tgen_brms <- as.data.frame(model_gen_IDA[c(9:11),])
tgen_equi <- as.data.frame(equi_gen_IDA)
tneg_lme4 <- as.data.frame(model_neg_IDA_lme4[c(2:4),])
tneg_brms <- as.data.frame(model_neg_IDA[c(9:11),])
tneg_equi <- as.data.frame(equi_neg_IDA)
tpos_lme4 <- as.data.frame(model_pos_IDA_lme4[c(2:4),])
tpos_brms <- as.data.frame(model_pos_IDA[c(9:11),])
tpos_equi <- as.data.frame(equi_pos_IDA)
tgen_lme4$term <- tgen_brms$term
tneg_lme4$term <- tneg_brms$term
tpos_lme4$term <- tpos_brms$term
# general regression ------------------------------------------------------
tgen <- join (tgen_brms, tgen_lme4, by = "term")
tgen <- join (tgen, tgen_equi, by ="term")
tgen$"b [95% HDI]" <- paste (format(tgen$estimate, nsmall = 2), " [", format(tgen$hdi.low, nsmall = 2), ", ",
format(tgen$hdi.high, nsmall = 2), "]", sep = "")
tgen$"b [95% HDI]" <- gsub("\\s+", " ", str_trim(tgen$"b [95% HDI]"))
tgen$"b [95% HDI]" <- gsub("\\[ ", "\\[", str_trim(tgen$"b [95% HDI]"))
ifelse ( grepl( " \\d", tgen$"b [95% HDI]"), " " == " ", tgen$"b [95% HDI]")
tgen$"b [95% CI]" <- paste (format( tgen$Estimate, nsmall = 2), " [", format(tgen$"2.5 %", nsmall = 2), ", ",
format(tgen$"97.5 %", nsmall = 2), "]", sep = "")
tgen$"b [95% CI]" <- gsub("\\s+", " ", str_trim(tgen$"b [95% CI]"))
tgen$"b [95% CI]" <- gsub("\\[ ", "\\[", str_trim(tgen$"b [95% CI]"))
# simple slope RWA in the negative condition ----------
tnegA_lme4 <- format(tneg_lme4[tneg_lme4$term == "b_RWAscore",], nsmall = 2)
tnegA_brms <- format(tneg_brms[tneg_brms$term == "b_RWAscore",], nsmall = 2)
tnegA_equi <- format(tneg_equi[tneg_equi$term == "b_RWAscore",], nsmall = 2)
tnegA <- join (tnegA_brms, tnegA_lme4, by = "term")
tnegA <- join (tnegA, tnegA_equi, by ="term")
tnegA$"b [95% HDI]" <- paste (format(tnegA$estimate, nsmall = 2), " [", format(tnegA$hdi.low, nsmall = 2), ", ",
format(tnegA$hdi.high, nsmall = 2), "]", sep = "")
tnegA$"b [95% CI]" <- paste (format( tnegA$Estimate, nsmall = 2), " [", format(tnegA$"2.5 %", nsmall = 2), ", ",
format(tnegA$"97.5 %", nsmall = 2), "]", sep = "")
# simple slope valence in the warning condition ----------
tposA_lme4 <- format(tpos_lme4[tpos_lme4$term == "b_RWAscore",], nsmall = 2)
tposA_brms <- format(tpos_brms[tpos_brms$term == "b_RWAscore",], nsmall = 2)
tposA_equi <- format(tpos_equi[tpos_equi$term == "b_RWAscore",], nsmall = 2)
tposA <- join (tposA_brms, tposA_lme4, by = "term")
tposA <- join (tposA, tposA_equi, by ="term")
tposA$"b [95% HDI]" <- paste (format(tposA$estimate, nsmall = 2), " [", format(tposA$hdi.low, nsmall = 2), ", ",
format(tposA$hdi.high, nsmall = 2), "]", sep = "")
tposA$"b [95% CI]" <- paste (format( tposA$Estimate, nsmall = 2), " [", format(tposA$"2.5 %", nsmall = 2), ", ",
format(tposA$"97.5 %", nsmall = 2), "]", sep = "")
# join -------------------------------------------------------------------
col2k <- c("term", "b [95% HDI]", "std.error",
"b [95% CI]", "Std. Error", "t value",
"decision", "ROPE", "inside.rope")
tgen <- format(tgen[,col2k], nsmall = 2)
tnegA <- format(tnegA[,col2k], nsmall = 2)
tposA <- format(tposA[,col2k], nsmall = 2)
t_all <- rbind(tgen,
tnegA,
tposA)
t_all$term <- c("Val",
"RWA",
"Val × RWA",
"RWA <sub>neg</sub>",
"RWA <sub>pos</sub>")
t_all$decision <- ifelse(t_all$decision == "reject", "oui",
ifelse(t_all$decision == "accept", "non",
"indécision"))
t_all <- t_all %>%
mutate(inside.rope = color_tile("lightgreen", "orange")(inside.rope))
t_all$"n° β" <- 1:length( t_all$term)
ordc <- c("n° β", "term", "b [95% HDI]", "std.error",
"b [95% CI]", "Std. Error", "t value",
"decision", "ROPE", "inside.rope")
t_all <- t_all[,ordc]
colnames(t_all) <- c("n° β", "Paramètre", "β<sub>Bayes</sub> [95% HDI]",
"SE<sub>Bayes</sub>", "β<sub>freq</sub> [95% CI]",
"SE<sub>freq</sub>", "t",
"β ≠ 0", "ROPE", "% β<sub>Bayes</sub> dans ROPE")
rownames(t_all) <- NULL
| /ida_CE/06_tables_ida.R | permissive | bricebeffara/rwa_evaluative_conditioning_data_analysis | R | false | false | 4,625 | r | p_load(plyr,
knitr,
kableExtra,
formattable,
dplyr,
webshot,
qdapRegex,
stringr,
install = TRUE,
update = getOption("pac_update"),
character.only = FALSE)
tgen_lme4 <- as.data.frame(model_gen_IDA_lme4[c(2:4),])
tgen_brms <- as.data.frame(model_gen_IDA[c(9:11),])
tgen_equi <- as.data.frame(equi_gen_IDA)
tneg_lme4 <- as.data.frame(model_neg_IDA_lme4[c(2:4),])
tneg_brms <- as.data.frame(model_neg_IDA[c(9:11),])
tneg_equi <- as.data.frame(equi_neg_IDA)
tpos_lme4 <- as.data.frame(model_pos_IDA_lme4[c(2:4),])
tpos_brms <- as.data.frame(model_pos_IDA[c(9:11),])
tpos_equi <- as.data.frame(equi_pos_IDA)
tgen_lme4$term <- tgen_brms$term
tneg_lme4$term <- tneg_brms$term
tpos_lme4$term <- tpos_brms$term
# general regression ------------------------------------------------------
tgen <- join (tgen_brms, tgen_lme4, by = "term")
tgen <- join (tgen, tgen_equi, by ="term")
tgen$"b [95% HDI]" <- paste (format(tgen$estimate, nsmall = 2), " [", format(tgen$hdi.low, nsmall = 2), ", ",
format(tgen$hdi.high, nsmall = 2), "]", sep = "")
tgen$"b [95% HDI]" <- gsub("\\s+", " ", str_trim(tgen$"b [95% HDI]"))
tgen$"b [95% HDI]" <- gsub("\\[ ", "\\[", str_trim(tgen$"b [95% HDI]"))
ifelse ( grepl( " \\d", tgen$"b [95% HDI]"), " " == " ", tgen$"b [95% HDI]")
tgen$"b [95% CI]" <- paste (format( tgen$Estimate, nsmall = 2), " [", format(tgen$"2.5 %", nsmall = 2), ", ",
format(tgen$"97.5 %", nsmall = 2), "]", sep = "")
tgen$"b [95% CI]" <- gsub("\\s+", " ", str_trim(tgen$"b [95% CI]"))
tgen$"b [95% CI]" <- gsub("\\[ ", "\\[", str_trim(tgen$"b [95% CI]"))
# simple slope RWA in the negative condition ----------
tnegA_lme4 <- format(tneg_lme4[tneg_lme4$term == "b_RWAscore",], nsmall = 2)
tnegA_brms <- format(tneg_brms[tneg_brms$term == "b_RWAscore",], nsmall = 2)
tnegA_equi <- format(tneg_equi[tneg_equi$term == "b_RWAscore",], nsmall = 2)
tnegA <- join (tnegA_brms, tnegA_lme4, by = "term")
tnegA <- join (tnegA, tnegA_equi, by ="term")
tnegA$"b [95% HDI]" <- paste (format(tnegA$estimate, nsmall = 2), " [", format(tnegA$hdi.low, nsmall = 2), ", ",
format(tnegA$hdi.high, nsmall = 2), "]", sep = "")
tnegA$"b [95% CI]" <- paste (format( tnegA$Estimate, nsmall = 2), " [", format(tnegA$"2.5 %", nsmall = 2), ", ",
format(tnegA$"97.5 %", nsmall = 2), "]", sep = "")
# simple slope valence in the warning condition ----------
tposA_lme4 <- format(tpos_lme4[tpos_lme4$term == "b_RWAscore",], nsmall = 2)
tposA_brms <- format(tpos_brms[tpos_brms$term == "b_RWAscore",], nsmall = 2)
tposA_equi <- format(tpos_equi[tpos_equi$term == "b_RWAscore",], nsmall = 2)
tposA <- join (tposA_brms, tposA_lme4, by = "term")
tposA <- join (tposA, tposA_equi, by ="term")
tposA$"b [95% HDI]" <- paste (format(tposA$estimate, nsmall = 2), " [", format(tposA$hdi.low, nsmall = 2), ", ",
format(tposA$hdi.high, nsmall = 2), "]", sep = "")
tposA$"b [95% CI]" <- paste (format( tposA$Estimate, nsmall = 2), " [", format(tposA$"2.5 %", nsmall = 2), ", ",
format(tposA$"97.5 %", nsmall = 2), "]", sep = "")
# join -------------------------------------------------------------------
col2k <- c("term", "b [95% HDI]", "std.error",
"b [95% CI]", "Std. Error", "t value",
"decision", "ROPE", "inside.rope")
tgen <- format(tgen[,col2k], nsmall = 2)
tnegA <- format(tnegA[,col2k], nsmall = 2)
tposA <- format(tposA[,col2k], nsmall = 2)
t_all <- rbind(tgen,
tnegA,
tposA)
t_all$term <- c("Val",
"RWA",
"Val × RWA",
"RWA <sub>neg</sub>",
"RWA <sub>pos</sub>")
t_all$decision <- ifelse(t_all$decision == "reject", "oui",
ifelse(t_all$decision == "accept", "non",
"indécision"))
t_all <- t_all %>%
mutate(inside.rope = color_tile("lightgreen", "orange")(inside.rope))
t_all$"n° β" <- 1:length( t_all$term)
ordc <- c("n° β", "term", "b [95% HDI]", "std.error",
"b [95% CI]", "Std. Error", "t value",
"decision", "ROPE", "inside.rope")
t_all <- t_all[,ordc]
colnames(t_all) <- c("n° β", "Paramètre", "β<sub>Bayes</sub> [95% HDI]",
"SE<sub>Bayes</sub>", "β<sub>freq</sub> [95% CI]",
"SE<sub>freq</sub>", "t",
"β ≠ 0", "ROPE", "% β<sub>Bayes</sub> dans ROPE")
rownames(t_all) <- NULL
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/knn_imp.R
\name{step_knnimpute}
\alias{step_knnimpute}
\alias{tidy.step_knnimpute}
\title{Imputation via K-Nearest Neighbors}
\usage{
step_knnimpute(
recipe,
...,
role = NA,
trained = FALSE,
neighbors = 5,
impute_with = imp_vars(all_predictors()),
options = list(nthread = 1, eps = 1e-08),
ref_data = NULL,
columns = NULL,
skip = FALSE,
id = rand_id("knnimpute")
)
\method{tidy}{step_knnimpute}(x, ...)
}
\arguments{
\item{recipe}{A recipe object. The step will be added to the
sequence of operations for this recipe.}
\item{...}{One or more selector functions to choose variables. For
\code{step_knnimpute}, this indicates the variables to be imputed. When used with
\code{imp_vars}, the dots indicates which variables are used to predict the
missing data in each variable. See \code{\link[=selections]{selections()}} for more details. For the
\code{tidy} method, these are not currently used.}
\item{role}{Not used by this step since no new variables are created.}
\item{trained}{A logical to indicate if the quantities for
preprocessing have been estimated.}
\item{neighbors}{The number of neighbors.}
\item{impute_with}{A call to \code{imp_vars} to specify which variables are used
to impute the variables that can include specific variable names separated
by commas or different selectors (see \code{\link[=selections]{selections()}}). If a column is
included in both lists to be imputed and to be an imputation predictor, it
will be removed from the latter and not used to impute itself.}
\item{options}{A named list of options to pass to \code{\link[gower:gower_topn]{gower::gower_topn()}}.
Available options are currently \code{nthread} and \code{eps}.}
\item{ref_data}{A tibble of data that will reflect the data preprocessing
done up to the point of this imputation step. This is \code{NULL} until the step
is trained by \code{\link[=prep.recipe]{prep.recipe()}}.}
\item{columns}{The column names that will be imputed and used for
imputation. This is \code{NULL} until the step is trained by \code{\link[=prep.recipe]{prep.recipe()}}.}
\item{skip}{A logical. Should the step be skipped when the
recipe is baked by \code{\link[=bake.recipe]{bake.recipe()}}? While all operations are baked
when \code{\link[=prep.recipe]{prep.recipe()}} is run, some operations may not be able to be
conducted on new data (e.g. processing the outcome variable(s)).
Care should be taken when using \code{skip = TRUE} as it may affect
the computations for subsequent operations}
\item{id}{A character string that is unique to this step to identify it.}
\item{x}{A \code{step_knnimpute} object.}
}
\value{
An updated version of \code{recipe} with the new step added to the
sequence of existing steps (if any). For the \code{tidy} method, a tibble with
columns \code{terms} (the selectors or variables for imputation), \code{predictors}
(those variables used to impute), and \code{neighbors}.
}
\description{
\code{step_knnimpute} creates a \emph{specification} of a recipe step that will
impute missing data using nearest neighbors.
}
\details{
The step uses the training set to impute any other data sets. The
only distance function available is Gower's distance which can be used for
mixtures of nominal and numeric data.
Once the nearest neighbors are determined, the mode is used to predictor
nominal variables and the mean is used for numeric data. Note that, if the
underlying data are integer, the mean will be converted to an integer too.
Note that if a variable that is to be imputed is also in \code{impute_with},
this variable will be ignored.
It is possible that missing values will still occur after imputation if a
large majority (or all) of the imputing variables are also missing.
}
\examples{
library(recipes)
library(modeldata)
data(biomass)
biomass_tr <- biomass[biomass$dataset == "Training", ]
biomass_te <- biomass[biomass$dataset == "Testing", ]
biomass_te_whole <- biomass_te
# induce some missing data at random
set.seed(9039)
carb_missing <- sample(1:nrow(biomass_te), 3)
nitro_missing <- sample(1:nrow(biomass_te), 3)
biomass_te$carbon[carb_missing] <- NA
biomass_te$nitrogen[nitro_missing] <- NA
rec <- recipe(HHV ~ carbon + hydrogen + oxygen + nitrogen + sulfur,
data = biomass_tr)
ratio_recipe <- rec \%>\%
step_knnimpute(all_predictors(), neighbors = 3)
ratio_recipe2 <- prep(ratio_recipe, training = biomass_tr)
imputed <- bake(ratio_recipe2, biomass_te)
# how well did it work?
summary(biomass_te_whole$carbon)
cbind(before = biomass_te_whole$carbon[carb_missing],
after = imputed$carbon[carb_missing])
summary(biomass_te_whole$nitrogen)
cbind(before = biomass_te_whole$nitrogen[nitro_missing],
after = imputed$nitrogen[nitro_missing])
tidy(ratio_recipe, number = 1)
tidy(ratio_recipe2, number = 1)
}
\references{
Gower, C. (1971) "A general coefficient of similarity and some
of its properties," Biometrics, 857-871.
}
\concept{imputation}
\concept{preprocessing}
\keyword{datagen}
| /man/step_knnimpute.Rd | no_license | juliasilge/recipes | R | false | true | 5,055 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/knn_imp.R
\name{step_knnimpute}
\alias{step_knnimpute}
\alias{tidy.step_knnimpute}
\title{Imputation via K-Nearest Neighbors}
\usage{
step_knnimpute(
recipe,
...,
role = NA,
trained = FALSE,
neighbors = 5,
impute_with = imp_vars(all_predictors()),
options = list(nthread = 1, eps = 1e-08),
ref_data = NULL,
columns = NULL,
skip = FALSE,
id = rand_id("knnimpute")
)
\method{tidy}{step_knnimpute}(x, ...)
}
\arguments{
\item{recipe}{A recipe object. The step will be added to the
sequence of operations for this recipe.}
\item{...}{One or more selector functions to choose variables. For
\code{step_knnimpute}, this indicates the variables to be imputed. When used with
\code{imp_vars}, the dots indicates which variables are used to predict the
missing data in each variable. See \code{\link[=selections]{selections()}} for more details. For the
\code{tidy} method, these are not currently used.}
\item{role}{Not used by this step since no new variables are created.}
\item{trained}{A logical to indicate if the quantities for
preprocessing have been estimated.}
\item{neighbors}{The number of neighbors.}
\item{impute_with}{A call to \code{imp_vars} to specify which variables are used
to impute the variables that can include specific variable names separated
by commas or different selectors (see \code{\link[=selections]{selections()}}). If a column is
included in both lists to be imputed and to be an imputation predictor, it
will be removed from the latter and not used to impute itself.}
\item{options}{A named list of options to pass to \code{\link[gower:gower_topn]{gower::gower_topn()}}.
Available options are currently \code{nthread} and \code{eps}.}
\item{ref_data}{A tibble of data that will reflect the data preprocessing
done up to the point of this imputation step. This is \code{NULL} until the step
is trained by \code{\link[=prep.recipe]{prep.recipe()}}.}
\item{columns}{The column names that will be imputed and used for
imputation. This is \code{NULL} until the step is trained by \code{\link[=prep.recipe]{prep.recipe()}}.}
\item{skip}{A logical. Should the step be skipped when the
recipe is baked by \code{\link[=bake.recipe]{bake.recipe()}}? While all operations are baked
when \code{\link[=prep.recipe]{prep.recipe()}} is run, some operations may not be able to be
conducted on new data (e.g. processing the outcome variable(s)).
Care should be taken when using \code{skip = TRUE} as it may affect
the computations for subsequent operations}
\item{id}{A character string that is unique to this step to identify it.}
\item{x}{A \code{step_knnimpute} object.}
}
\value{
An updated version of \code{recipe} with the new step added to the
sequence of existing steps (if any). For the \code{tidy} method, a tibble with
columns \code{terms} (the selectors or variables for imputation), \code{predictors}
(those variables used to impute), and \code{neighbors}.
}
\description{
\code{step_knnimpute} creates a \emph{specification} of a recipe step that will
impute missing data using nearest neighbors.
}
\details{
The step uses the training set to impute any other data sets. The
only distance function available is Gower's distance which can be used for
mixtures of nominal and numeric data.
Once the nearest neighbors are determined, the mode is used to predictor
nominal variables and the mean is used for numeric data. Note that, if the
underlying data are integer, the mean will be converted to an integer too.
Note that if a variable that is to be imputed is also in \code{impute_with},
this variable will be ignored.
It is possible that missing values will still occur after imputation if a
large majority (or all) of the imputing variables are also missing.
}
\examples{
library(recipes)
library(modeldata)
data(biomass)
biomass_tr <- biomass[biomass$dataset == "Training", ]
biomass_te <- biomass[biomass$dataset == "Testing", ]
biomass_te_whole <- biomass_te
# induce some missing data at random
set.seed(9039)
carb_missing <- sample(1:nrow(biomass_te), 3)
nitro_missing <- sample(1:nrow(biomass_te), 3)
biomass_te$carbon[carb_missing] <- NA
biomass_te$nitrogen[nitro_missing] <- NA
rec <- recipe(HHV ~ carbon + hydrogen + oxygen + nitrogen + sulfur,
data = biomass_tr)
ratio_recipe <- rec \%>\%
step_knnimpute(all_predictors(), neighbors = 3)
ratio_recipe2 <- prep(ratio_recipe, training = biomass_tr)
imputed <- bake(ratio_recipe2, biomass_te)
# how well did it work?
summary(biomass_te_whole$carbon)
cbind(before = biomass_te_whole$carbon[carb_missing],
after = imputed$carbon[carb_missing])
summary(biomass_te_whole$nitrogen)
cbind(before = biomass_te_whole$nitrogen[nitro_missing],
after = imputed$nitrogen[nitro_missing])
tidy(ratio_recipe, number = 1)
tidy(ratio_recipe2, number = 1)
}
\references{
Gower, C. (1971) "A general coefficient of similarity and some
of its properties," Biometrics, 857-871.
}
\concept{imputation}
\concept{preprocessing}
\keyword{datagen}
|
#Correlation is Not Causation: Outliers
#Suppose we take measurements from two independent outcomes, x and y, and we standardize the meansurements.
#However, imagine we made a mistake and forgot to standardize entry 23. We can simulate such data using
#this code:
set.seed(1)
x <- rnorm(100,100,1)
y <- rnorm(100,84,1)
x[-23] <- scale(x[-23])
y[-23] <- scale(y[-23])
#The data looks like this
tibble(x,y) %>% ggplot(aes(x,y)) + geom_point(alpha = 0.5)
#Not surprisingly, the correlation is very high
cor(x,y)
#The one loutlier is making the correlation to be as high as 0.99. If we remove this outlier, the
#correlation is greatly reduced to almost 0, which is wha tit should be
cor(x[-23],y[-23])
#We can use the Spearman correlation that is robust to outliers. If we compute the correlation of the ranks,
#we get something much closer to 0.
cor(rank(x), rank(y))
#We can also use the correlation function using the method argument to tell which correlation to compute.
cor(x, y, method = "spearman") | /rda/CorrelationOutlier.R | no_license | vleung5/linear_regression | R | false | false | 1,013 | r |
#Correlation is Not Causation: Outliers
#Suppose we take measurements from two independent outcomes, x and y, and we standardize the meansurements.
#However, imagine we made a mistake and forgot to standardize entry 23. We can simulate such data using
#this code:
set.seed(1)
x <- rnorm(100,100,1)
y <- rnorm(100,84,1)
x[-23] <- scale(x[-23])
y[-23] <- scale(y[-23])
#The data looks like this
tibble(x,y) %>% ggplot(aes(x,y)) + geom_point(alpha = 0.5)
#Not surprisingly, the correlation is very high
cor(x,y)
#The one loutlier is making the correlation to be as high as 0.99. If we remove this outlier, the
#correlation is greatly reduced to almost 0, which is wha tit should be
cor(x[-23],y[-23])
#We can use the Spearman correlation that is robust to outliers. If we compute the correlation of the ranks,
#we get something much closer to 0.
cor(rank(x), rank(y))
#We can also use the correlation function using the method argument to tell which correlation to compute.
cor(x, y, method = "spearman") |
args = commandArgs(trailingOnly=TRUE)
.cran_packages <- c("BiocManager", "rmarkdown", "devtools", "curl","dplyr","reshape2","tidyverse","magrittr","readr","stringr","data.table","svMisc","gtools","igraph","igraphdata","MCL","NetIndices","kernlab","smotefamily","pROC","FNN","ggplot2","gplots","RColorBrewer","vegetarian","vegan","knitr","rstudioapi","Rcpp","RMySQL","RSQLite","foreign","tidyr","lubridate","ggvis","rgl","htmlwidgets","leaflet","dygraphs","googleVis","car","mgcv","lme4","nlme","randomForest","multcomp","vcd","glmnet","survival","caret","shiny","maps","ggmap","zoo","xts","quantmod","parallel","XML","jsonlite","testthat","roxygen2")
.bioc_packages <- c("Biostrings","DESeq2","limma","pcaMethods","phyloseq","dada2","DECIPHER","phangorn")
.inst <- .cran_packages %in% installed.packages()
if(any(!.inst)) {install.packages(.cran_packages[!.inst], lib = args[1], contriburl = contrib.url('http://cran.r-project.org/'))}
.inst <- .bioc_packages %in% installed.packages()
if(any(!.inst)) {BiocManager::install(.bioc_packages[!.inst], ask = F)}
devtools::install_github("benjjneb/dada2")
devtools::install_github("joey711/phyloseq")
sapply(c(.cran_packages, .bioc_packages), require, character.only = TRUE)
| /library_setup.R | no_license | schuyler-smith/hpcc_R_setup | R | false | false | 1,226 | r |
args = commandArgs(trailingOnly=TRUE)
.cran_packages <- c("BiocManager", "rmarkdown", "devtools", "curl","dplyr","reshape2","tidyverse","magrittr","readr","stringr","data.table","svMisc","gtools","igraph","igraphdata","MCL","NetIndices","kernlab","smotefamily","pROC","FNN","ggplot2","gplots","RColorBrewer","vegetarian","vegan","knitr","rstudioapi","Rcpp","RMySQL","RSQLite","foreign","tidyr","lubridate","ggvis","rgl","htmlwidgets","leaflet","dygraphs","googleVis","car","mgcv","lme4","nlme","randomForest","multcomp","vcd","glmnet","survival","caret","shiny","maps","ggmap","zoo","xts","quantmod","parallel","XML","jsonlite","testthat","roxygen2")
.bioc_packages <- c("Biostrings","DESeq2","limma","pcaMethods","phyloseq","dada2","DECIPHER","phangorn")
.inst <- .cran_packages %in% installed.packages()
if(any(!.inst)) {install.packages(.cran_packages[!.inst], lib = args[1], contriburl = contrib.url('http://cran.r-project.org/'))}
.inst <- .bioc_packages %in% installed.packages()
if(any(!.inst)) {BiocManager::install(.bioc_packages[!.inst], ask = F)}
devtools::install_github("benjjneb/dada2")
devtools::install_github("joey711/phyloseq")
sapply(c(.cran_packages, .bioc_packages), require, character.only = TRUE)
|
estadisticos_iniciales_mult <- function(datos){
## esta función regresa una base con la media y varianza para cada
## variable de la base de datos (se toman solo las variables numéricas)
nums <- sapply(datos, is.numeric)
datos[ , nums]
covar<-cov(datos[ ,nums])%>%
melt()%>%
rename(c(X1="variable",X2="O"))%>%
dcast(variable~O)
res <- datos[,nums] %>%
gather(variable, value) %>%
group_by(variable) %>%
summarise(media = mean(value)) %>%
ungroup%>%
data.frame()
resultado<-merge(res,covar)
return(resultado)
}
| /Algoritmo2306/estadisticos_iniciales_mult.R | no_license | montserratvizcayno/Tesis1 | R | false | false | 615 | r | estadisticos_iniciales_mult <- function(datos){
## esta función regresa una base con la media y varianza para cada
## variable de la base de datos (se toman solo las variables numéricas)
nums <- sapply(datos, is.numeric)
datos[ , nums]
covar<-cov(datos[ ,nums])%>%
melt()%>%
rename(c(X1="variable",X2="O"))%>%
dcast(variable~O)
res <- datos[,nums] %>%
gather(variable, value) %>%
group_by(variable) %>%
summarise(media = mean(value)) %>%
ungroup%>%
data.frame()
resultado<-merge(res,covar)
return(resultado)
}
|
# NOTE: This code has been modified from AWS Stepfunctions Python:
# https://github.com/aws/aws-step-functions-data-science-sdk-python/blob/main/src/stepfunctions/workflow/stepfunctions.py
#' @importFrom paws sfn
#' @import R6
#' @import jsonlite
#' @import lgr
#' @include utils.R
#' @include steps_states.R
#' @include workflow_widgets_graph.R
#' @include workflow_widgets_event_table.R
#' @include workflow_widgets_workflows_table.R
#' @include workflow_widgets_utils.R
#' @include workflow_cloudformation.R
EventsList = R6Class("EventsList",
inherit = EventsTableWidget,
public = list(
to_html = function(){
return(self$show())
}
),
lock_objects=F
)
WorkflowList = R6Class("WorkflowList",
inherit = WorkflowsTableWidget,
public = list(
to_html = function(){
return(self$show())
}
),
lock_objects=F
)
ExecutionsList = R6Class("ExecutionsList",
inherit = ExecutionsTableWidget,
public = list(
to_html = function(){
return(self$show())
}
),
lock_objects=F
)
ExecutionStatus = Enum(
Running = 'RUNNING',
Succeeded = 'SUCCEEDED',
Failed = 'FAILED',
TimedOut = 'TIMED_OUT',
Aborted = 'ABORTED'
)
#' @title Workflow Class
#' @description Class for creating and managing a workflow.
#' @export
Workflow = R6Class("Workflow",
public = list(
#' @description Lists all the workflows in the account.
#' @param max_items (int, optional): The maximum number of items to be returned. (default: 100)
#' @param client (SFN.Client, optional): \code{\link[paws]{sfn}} client to use for the query. If
#' not provided, a default \code{\link[paws]{sfn}} client for Step Functions will be
#' automatically created and used. (default: None)
#' @param html (bool, optional): Renders the list as an HTML table (If running in
#' an IRkernel environment). If the parameter is not provided, or set
#' to FALSE, a R list is returned. (default: False)
#' @return list: The list of workflows. Refer to :meth:`.SFN.Client.list_state_machines()`
#' for the response structure.
list_workflows = function(max_items=100,
client=NULL,
html=FALSE){
if (is.null(client)){
LOGGER$debug(paste("The argument 'client' is not provided. Creating a new",
"`paws::sfn()` client instance with default settings."))
client = sfn()
}
LOGGER$debug("Retrieving list of workflows from AWS Step Functions.")
token = NULL
workflows = list()
while(!identical(token, character(0))){
batch_response=client$list_state_machines(
maxResults=1000, # maximum allowed page size
nextToken=token
)
workflows = c(workflows, batch_response[["stateMachines"]])
if(length(workflows) >= max_items){
workflows = workflows[1:max_items]
break
}
token=batch_response[["nextToken"]]
}
if (html){
display_html <- pkg_method("display_html","IRdisplay")
return(display_html(WorkflowList$new(workflows)$to_html()))
} else {
return(workflows)
}
},
#' @description Initialize Workflow Class
#' @param name (str): The name of the workflow. A name must not contain:
#' \itemize{
#' \item{whitespace}
#' \item{brackets ``< > { } [ ]``}
#' \item{wildcard characters ``? *``}
#' \item{special characters ``\" # \% \ ^ | ~ ` $ & , ; : /``}
#' \item{control characters (``U+0000-001F``, ``U+007F-009F``)}
#' }
#' @param definition (State or Chain): The Amazon States Language
#' \url{https://states-language.net/spec.html} definition of the workflow.
#' @param role (str): The Amazon Resource Name (ARN) of the IAM role to use for creating,
#' managing, and running the workflow.
#' @param tags (list): Tags to be added when creating a workflow. Tags are key-value pairs
#' that can be associated with Step Functions workflows and activities. (default: [])
#' @param execution_input (ExecutionInput, optional): Placeholder collection that defines
#' the placeholder variables for the workflow execution. This is also used
#' to validate inputs provided when executing the workflow. (default: None)
#' @param timeout_seconds (int, optional): The maximum number of seconds an execution
#' of the workflow can run. If it runs longer than the specified time,
#' the workflow run fails with a `States.Timeout` Error Name. (default: None)
#' @param comment (str, optional): A human-readable description of the workflow. (default: None)
#' @param version (str, optional): The version of the Amazon States Language used
#' in the workflow. (default: None)
#' @param state_machine_arn (str, optional): The Amazon Resource Name (ARN) of
#' the workflow. (default: None)
#' @param format_json (bool, optional): Boolean flag set to `True` if workflow
#' definition and execution inputs should be prettified for this workflow.
#' `False`, otherwise. (default: True)
#' @param client (SFN.Client, optional): paws client to use for creating, managing,
#' and running the workflow on Step Functions. If not provided, a
#' default \code{\link[paws]{sfn}} client for Step Functions will be automatically created
#' and used. (default: None)
initialize = function(name,
definition,
role,
tags=list(),
execution_input=NULL,
timeout_seconds=NULL,
comment=NULL,
version=NULL,
state_machine_arn=NULL,
format_json=TRUE,
client=NULL){
self$timeout_seconds = timeout_seconds
self$comment = comment
self$version = version
if (inherits(definition, "Graph"))
self$definition = definition
else
self$definition = Graph$new(
definition,
timeout_seconds=self$timeout_seconds,
comment=self$comment,
version=self$version
)
self$name = name
self$role = role
self$tags = tags
self$workflow_input = execution_input
if (!is.null(client))
self$client = client
else
self$client = sfn()
self$format_json = format_json
self$state_machine_arn = state_machine_arn
},
#' @description Factory method to create an instance attached to an exisiting
#' workflow in Step Functions.
#' @param state_machine_arn (str): The Amazon Resource Name (ARN) of the existing workflow.
#' @param client (SFN.Client, optional): \code{\link[paws]{sfn}} client to use for attaching the existing
#' workflow in Step Functions to the Workflow object. If not provided,
#' a default \code{\link[paws]{sfn}} client for Step Functions will be automatically
#' created and used. (default: None)
#' @return Workflow: Workflow object attached to the existing workflow in Step Functions.
attach = function(state_machine_arn,
client=NULL){
if (!is.null(client)){
LOGGER$debug(paste("The argument 'client' is not provided. Creating a new",
"`paws::sfn` client instance with default settings."))
client = sfn()
}
response = client$describe_state_machine(stateMachineArn=state_machine_arn)
return(Workflow$new(
name=response[['name']],
definition=FrozenGraph$public_methods$from_json(response[['definition']]),
role=response[['roleArn']],
state_machine_arn=response[['stateMachineArn']],
client=client)
)
},
#' @description Creates the workflow on Step Functions.
#' @return str: The Amazon Resource Name (ARN) of the workflow created. If the workflow
#' already existed, the ARN of the existing workflow is returned.
create = function(){
if (!is.null(self$state_machine_arn)){
LOGGER$warn("The workflow already exists on AWS Step Functions. No action will be performed.")
return(self$state_machine_arn)
}
tryCatch({
self$state_machine_arn = private$.create()
},
error = function(e){
self$state_machine_arn = private$.extract_state_machine_arn(e)
LOGGER$error(paste("A workflow with the same name already exists on AWS",
"Step Functions. To update a workflow, use Workflow.update()."))
})
return(self$state_machine_arn)
},
#' @description Updates an existing state machine by modifying its definition
#' and/or role. Executions started immediately after calling this
#' method may use the previous definition and role.
#' @param definition (State or Chain, optional): The Amazon States Language
#' \url{https://states-language.net/spec.html} definition to update
#' the workflow with. (default: None)
#' @param role (str, optional): The Amazon Resource Name (ARN) of the IAM role
#' to use for creating, managing, and running the workflow. (default: None)
#' @return str: The state machine definition and/or role updated. If the update fails,
#' None will be returned.
update = function(definition=NULL,
role=NULL){
if (is.null(definition) && is.null(role))
stop("A new definition and/or role must be provided to update an existing workflow.")
if (is.null(self$state_machine_arn))
stop("Local workflow instance does not point to an existing workflow ",
"on AWS StepFunctions. Please consider using Workflow.create(...) ",
"to create a new workflow, or Workflow.attach(...) to attach the ",
"instance to an existing workflow on AWS Step Functions.")
if (!is.null(definition)){
if (inherits(definition, "Graph"))
self$definition = definition
else
self$definition = Graph$new(
definition,
timeout_seconds=self$timeout_seconds,
comment=self$comment,
version=self$version)
}
if(!is.null(role))
self$role = role
response = self$client$update_state_machine(
stateMachineArn=self$state_machine_arn,
definition=self$definition$to_json(pretty=self$format_json),
roleArn=self$role
)
LOGGER$info(paste("Workflow updated successfully on AWS Step Functions.",
"All execute() calls will use the updated definition and role within a few seconds."))
return(self$state_machine_arn)
},
#' @description Starts a single execution of the workflow.
#' @param name (str, optional): The name of the workflow execution. If one is
#' not provided, a workflow execution name will be auto-generated. (default: None)
#' @param inputs (str, list, optional): Input data for the workflow execution. (default: None)
#' @return stepfunctions.workflow.Execution: An execution instance of the workflow.
execute = function(name=NULL, inputs=NULL){
if (!is.null(self$workflow_input)){
validation_result = self$workflow_input$validate(inputs)
if (isFALSE(validation_result$valid))
stop(sprintf(
"Expected run input with the schema: %s",
self$workflow_input$get_schema_as_json()))
}
if (is.null(self$state_machine_arn))
stop("Local workflow instance does not point to an existing workflow on ",
"AWS StepFunctions. Before executing a workflow, call Workflow.create(...) ",
"or Workflow.attach(...).")
params = list(
'stateMachineArn'=self$state_machine_arn)
params[['name']] = name
if (!is.null(inputs))
params[['input']] = toJSON(inputs, pretty=self$format_json, auto_unbox=T)
response = self$client$start_execution(
stateMachineArn=params$stateMachineArn,
name=params$name,
input=params$input)
LOGGER$info("Workflow execution started successfully on AWS Step Functions.")
# name is None because \code{\link[paws]{sfn}} client.start_execution only returns startDate and executionArn
return(Execution$new(
workflow=self,
execution_arn=response[['executionArn']],
start_date=response[['startDate']],
status=ExecutionStatus$Running,
client=self$client)
)
},
#' @description Lists the executions for the workflow.
#' @param max_items (int, optional): The maximum number of items to be returned. (default: 100)
#' @param status_filter (ExecutionStatus, optional): If specified, only list
#' the executions whose current status matches the given filter. (default: None)
#' @param html (bool, optional): Renders the list as an HTML table (If running
#' in an IRKernel environment). If the parameter is not provided, or
#' set to FALSE, a R list is returned. (default: False)
#' @return list: List of workflow run instances.
list_executions = function(max_items=100,
status_filter=NULL,
html=FALSE){
if (is.null(self$state_machine_arn))
return(list())
LOGGER$debug("Retrieving list of executions from AWS Step Functions.")
token=NULL
response = list()
while(!identical(token, character(0))){
batch_response=response=self$client$list_executions(
stateMachineArn=self$state_machine_arn,
statusFilter=if(is.null(status_filter)) status_filter else toupper(status_filter),
maxResults=1000, # maximum allowed page size
nextToken=token)
response = c(response, batch_response["executions"])
if(length(response) >= max_items){
response = response[1:max_items]
break
}
token = batch_response[["nextToken"]]
}
runs = lapply(response$executions, function(execution){
Execution$new(
name=execution[['name']],
workflow=self,
execution_arn=execution[['executionArn']],
start_date=execution[['startDate']],
stop_date=execution[['stopDate']],
status=execution[['status']],
client=self$client
)
})
if (html){
display_html <- pkg_method("display_html","IRdisplay")
return(display_html(ExecutionsList$new(runs)$to_html()))
} else {
return(runs)
}
},
#' @description Deletes the workflow, if it exists.
delete = function(){
if (!is.null(self$state_machine_arn))
self$client$delete_state_machine(stateMachineArn=self$state_machine_arn)
LOGGER$info(paste("Workflow has been marked for deletion. If the workflow has",
"running executions, it will be deleted when all executions are stopped."))
},
#' @description Renders a visualization of the workflow graph.
#' @param portrait (bool, optional): Boolean flag set to `True` if the workflow
#' graph should be rendered in portrait orientation. Set to `False`,
#' if the graph should be rendered in landscape orientation. (default: False)
render_graph = function(portrait = FALSE){
widget = WorkflowGraphWidget$new(self$definition$to_json())
return(widget$show(portrait=portrait))
},
#' @description Returns a CloudFormation template that contains only the StateMachine
#' resource. To reuse the CloudFormation template in a different region,
#' please make sure to update the region specific AWS resources (e.g: Lambda
#' ARN, Training Image) in the StateMachine definition.
get_cloudformation_template = function(){
return(build_cloudformation_template(self))
},
#' @description class formatting
format = function(){
# identify if in Rstudio or not
if (pkg_env$jupyter){
if (!is.null(self$state_machine_arn))
return(sprintf(
'Workflow: <a target="_blank" href="%s">%s</a>',
create_sfn_workflow_url(self$state_machine_arn), self$state_machine_arn))
else
return('Workflow: Does Not Exist.')
} else {
if (!is.null(self$state_machine_arn)){
cls_fmt = "%s(name='%s', role='%s', state_machine_arn='%s')"
return(sprintf(cls_fmt, class(self)[1],
self$name, self$role, self$state_machine_arn))
} else {
cls_fmt = "%s(name='%s', role='%s'): Does Not Exist"
return(sprintf(cls_fmt, class(self)[1],
self$name, self$role))
}
}
},
#' @description print class
print = function(){
if(pkg_env$jupyter){
display_html <- pkg_method("display_html","IRdisplay")
display_html(self$format())
} else {
cat(self$format(), "\n")
}
}
),
private = list(
.create = function(){
response = self$client$create_state_machine(
name=self$name,
definition=self$definition$to_json(pretty=self$format_json),
roleArn=self$role,
tags=self$tags)
LOGGER$info("Workflow created successfully on AWS Step Functions.")
return(response[['stateMachineArn']])
},
.extract_state_machine_arn = function(exception){
message = attributes(exception)$error_response$message
return(unlist(strsplit(message, "'"))[2])
}
),
lock_objects=F
)
#' @title Execution class
#' @description Class for managing a workflow execution.
#' @export
Execution = R6Class("Execution",
public = list(
#' @description Initialize Execution class
#' @param workflow (Workflow): Step Functions workflow instance.
#' @param execution_arn (str): The Amazon Resource Name (ARN) of the workflow execution.
#' @param start_date (datetime.datetime): The date the workflow execution was started.
#' @param status (RunStatus): Status of the workflow execution.
#' @param client (SFN.Client, optional): \code{\link[paws]{sfn}} client to use for running and
#' managing the workflow executions on Step Functions. If no client
#' is provided, the \code{\link[paws]{sfn}} client from the parent workflow will be used. (default: None)
#' @param name (str, optional): Name for the workflow execution. (default: None)
#' @param stop_date (datetime.datetime, optional): The date the workflow execution
#' was stopped, if applicable. (default: None)
initialize = function(workflow,
execution_arn,
start_date,
status,
client=NULL,
name=NULL,
stop_date=NULL){
self$name = name
self$workflow = workflow
self$execution_arn = execution_arn
self$start_date = start_date
self$stop_date = stop_date
self$status = status
if (!is.null(client))
self$client = client
else
self$client = self$workflow$client
},
#' @description Stops a workflow execution.
#' @param error (str, optional): The error code of the failure. (default: None)
#' @param cause (str, optional): A more detailed explanation of the cause of the failure. (default: None)
#' @return list: Datetime of when the workflow execution was stopped. Example below::
#' \code{
#' list(
#' stopDate = as.POSIXct(
#' "2015-01-01"
#' )
#' )
#' }
#' **Response structure**:
#' \itemize{
#' \item{(list)}
#' \item{stopDate (datetime): The date the workflow execution is stopped}
#' }
stop = function(cause=NULL,
error=NULL){
response = self$client$stop_execution(
executionArn=self$execution_arn,
cause=cause,
error=error
)
return(response)
},
#' @description Lists the events in the workflow execution.
#' @param max_items (int, optional): The maximum number of items to be returned.
#' (default: 100)
#' @param reverse_order (bool, optional): Boolean flag set to `True` if the events
#' should be listed in reverse chronological order. Set to `False`,
#' if the order should be in chronological order. (default: False)
#' @param html (bool, optional): Renders the list as an HTML table (If running in
#' an IRKernel environment). If the parameter is not provided, or set
#' to FALSE, a R list is returned. (default: False)
#' @return list: Object containing the list of workflow execution events. Refer
#' to :meth:`.SFN.Client.get_execution_history()` for the response structure.
list_events = function(max_items=100,
reverse_order=FALSE,
html=FALSE){
LOGGER$debug("Retrieving list of history events for your execution from AWS Step Functions.")
events=list()
token=NULL
while(!identical(token, character(0))){
batch_response = self$client$get_execution_history(
executionArn=self$execution_arn,
maxResults=1000, # maximum allowed page size
reverseOrder=reverse_order,
nextToken=token
)
events=c(events, batch_response[["events"]])
if(length(events) >= max_items){
events = events[1:max_items]
break
}
token=batch_response[["nextToken"]]
}
if (html){
display_html <- pkg_method("display_html","IRdisplay")
return(display_html(EventsList$new(events)$to_html()))
} else {
return(events)
}
},
#' @description Describes a workflow execution.
#' @return list: Details of the workflow execution.
#' **Response structure**:
#' \itemize{
#' \item{executionArn (string): The Amazon Resource Name (ARN) that identifies the workflow execution.}
#' \item{stateMachineArn (string): The Amazon Resource Name (ARN) of the workflow that was executed.}
#' \item{name (string): The name of the workflow execution.}
#' \item{status (string): The current status of the workflow execution.}
#' \item{startDate (datetime): The date the workflow execution is started.}
#' \item{stopDate (datetime): If the workflow execution has already ended, the date the execution stopped.}
#' \item{input (string): The string that contains the JSON input data of the workflow execution.}
#' \item{output (string): The JSON output data of the workflow execution.}
#' }
describe = function(){
return(self$client$describe_execution(executionArn=self$execution_arn))
},
#' @description Renders a visualization of the workflow execution graph.
#' @param portrait (bool, optional): Boolean flag set to `True` if the workflow
#' execution graph should be rendered in portrait orientation. Set
#' to `False`, if the graph should be rendered in landscape orientation. (default: False)
#' @param max_events (int, optional): Specifies the number of events to be visualized
#' in the workflow execution graph. (default: 25000)
render_progress = function(portrait=FALSE,
max_events=25000){
events = self$list_events(max_items=max_events)
widget = ExecutionGraphWidget$new(
self$workflow$definition$to_json(),
toJSON(events, auto_unbox = T),
execution_arn=self$execution_arn)
return(widget$show(portrait=portrait))
},
#' @description Get the input for the workflow execution.
#' @return list: Workflow execution input.
get_input = function(){
run_input = self$describe()[['input']]
if(is.null(run_input))
return(run_input)
return(fromJSON(run_input))
},
#' @description Get the output for the workflow execution.
#' @param wait (bool, optional): Boolean flag set to `True` if the call should
#' wait for a running workflow execution to end before returning
#' the output. Set to `False`, otherwise. Note that if the status
#' is running, and `wait` is set to `True`, this will be a blocking
#' call. (default: False)
#' @return list: Workflow execution output.
get_output = function(wait=FALSE){
while(wait && self$describe()[['status']] == 'RUNNING'){
Sys.sleep(1)
}
output = self$describe()[["output"]]
if (is.null(outpu))
return(output)
return(fromJSON(output))
},
#' @description format class
format = function(){
if(pkg_env$jupyter){
return(sprintf('Execution: <a target="_blank" href="%s">%s</a>',
create_sfn_execution_url(self$execution_arn), self$execution_arn))
} else {
return(sprintf("%s(execution_arn='%s', name='%s', status='%s', start_date='%s')",
class(self)[1], self$execution_arn, self$name, self$status, self$start_date))
}
},
#' @description print class
print = function(){
if(pkg_env$jupyter){
display_html <- pkg_method("display_html","IRdisplay")
display_html(self$format())
} else {
cat(self$format(), "\n")
}
}
),
lock_objects=F
)
| /R/workflow_stepfunctions.R | permissive | DyfanJones/aws-step-functions-data-science-sdk-r | R | false | false | 25,922 | r | # NOTE: This code has been modified from AWS Stepfunctions Python:
# https://github.com/aws/aws-step-functions-data-science-sdk-python/blob/main/src/stepfunctions/workflow/stepfunctions.py
#' @importFrom paws sfn
#' @import R6
#' @import jsonlite
#' @import lgr
#' @include utils.R
#' @include steps_states.R
#' @include workflow_widgets_graph.R
#' @include workflow_widgets_event_table.R
#' @include workflow_widgets_workflows_table.R
#' @include workflow_widgets_utils.R
#' @include workflow_cloudformation.R
EventsList = R6Class("EventsList",
inherit = EventsTableWidget,
public = list(
to_html = function(){
return(self$show())
}
),
lock_objects=F
)
WorkflowList = R6Class("WorkflowList",
inherit = WorkflowsTableWidget,
public = list(
to_html = function(){
return(self$show())
}
),
lock_objects=F
)
ExecutionsList = R6Class("ExecutionsList",
inherit = ExecutionsTableWidget,
public = list(
to_html = function(){
return(self$show())
}
),
lock_objects=F
)
ExecutionStatus = Enum(
Running = 'RUNNING',
Succeeded = 'SUCCEEDED',
Failed = 'FAILED',
TimedOut = 'TIMED_OUT',
Aborted = 'ABORTED'
)
#' @title Workflow Class
#' @description Class for creating and managing a workflow.
#' @export
Workflow = R6Class("Workflow",
public = list(
#' @description Lists all the workflows in the account.
#' @param max_items (int, optional): The maximum number of items to be returned. (default: 100)
#' @param client (SFN.Client, optional): \code{\link[paws]{sfn}} client to use for the query. If
#' not provided, a default \code{\link[paws]{sfn}} client for Step Functions will be
#' automatically created and used. (default: None)
#' @param html (bool, optional): Renders the list as an HTML table (If running in
#' an IRkernel environment). If the parameter is not provided, or set
#' to FALSE, a R list is returned. (default: False)
#' @return list: The list of workflows. Refer to :meth:`.SFN.Client.list_state_machines()`
#' for the response structure.
list_workflows = function(max_items=100,
client=NULL,
html=FALSE){
if (is.null(client)){
LOGGER$debug(paste("The argument 'client' is not provided. Creating a new",
"`paws::sfn()` client instance with default settings."))
client = sfn()
}
LOGGER$debug("Retrieving list of workflows from AWS Step Functions.")
token = NULL
workflows = list()
while(!identical(token, character(0))){
batch_response=client$list_state_machines(
maxResults=1000, # maximum allowed page size
nextToken=token
)
workflows = c(workflows, batch_response[["stateMachines"]])
if(length(workflows) >= max_items){
workflows = workflows[1:max_items]
break
}
token=batch_response[["nextToken"]]
}
if (html){
display_html <- pkg_method("display_html","IRdisplay")
return(display_html(WorkflowList$new(workflows)$to_html()))
} else {
return(workflows)
}
},
#' @description Initialize Workflow Class
#' @param name (str): The name of the workflow. A name must not contain:
#' \itemize{
#' \item{whitespace}
#' \item{brackets ``< > { } [ ]``}
#' \item{wildcard characters ``? *``}
#' \item{special characters ``\" # \% \ ^ | ~ ` $ & , ; : /``}
#' \item{control characters (``U+0000-001F``, ``U+007F-009F``)}
#' }
#' @param definition (State or Chain): The Amazon States Language
#' \url{https://states-language.net/spec.html} definition of the workflow.
#' @param role (str): The Amazon Resource Name (ARN) of the IAM role to use for creating,
#' managing, and running the workflow.
#' @param tags (list): Tags to be added when creating a workflow. Tags are key-value pairs
#' that can be associated with Step Functions workflows and activities. (default: [])
#' @param execution_input (ExecutionInput, optional): Placeholder collection that defines
#' the placeholder variables for the workflow execution. This is also used
#' to validate inputs provided when executing the workflow. (default: None)
#' @param timeout_seconds (int, optional): The maximum number of seconds an execution
#' of the workflow can run. If it runs longer than the specified time,
#' the workflow run fails with a `States.Timeout` Error Name. (default: None)
#' @param comment (str, optional): A human-readable description of the workflow. (default: None)
#' @param version (str, optional): The version of the Amazon States Language used
#' in the workflow. (default: None)
#' @param state_machine_arn (str, optional): The Amazon Resource Name (ARN) of
#' the workflow. (default: None)
#' @param format_json (bool, optional): Boolean flag set to `True` if workflow
#' definition and execution inputs should be prettified for this workflow.
#' `False`, otherwise. (default: True)
#' @param client (SFN.Client, optional): paws client to use for creating, managing,
#' and running the workflow on Step Functions. If not provided, a
#' default \code{\link[paws]{sfn}} client for Step Functions will be automatically created
#' and used. (default: None)
initialize = function(name,
definition,
role,
tags=list(),
execution_input=NULL,
timeout_seconds=NULL,
comment=NULL,
version=NULL,
state_machine_arn=NULL,
format_json=TRUE,
client=NULL){
self$timeout_seconds = timeout_seconds
self$comment = comment
self$version = version
if (inherits(definition, "Graph"))
self$definition = definition
else
self$definition = Graph$new(
definition,
timeout_seconds=self$timeout_seconds,
comment=self$comment,
version=self$version
)
self$name = name
self$role = role
self$tags = tags
self$workflow_input = execution_input
if (!is.null(client))
self$client = client
else
self$client = sfn()
self$format_json = format_json
self$state_machine_arn = state_machine_arn
},
#' @description Factory method to create an instance attached to an exisiting
#' workflow in Step Functions.
#' @param state_machine_arn (str): The Amazon Resource Name (ARN) of the existing workflow.
#' @param client (SFN.Client, optional): \code{\link[paws]{sfn}} client to use for attaching the existing
#' workflow in Step Functions to the Workflow object. If not provided,
#' a default \code{\link[paws]{sfn}} client for Step Functions will be automatically
#' created and used. (default: None)
#' @return Workflow: Workflow object attached to the existing workflow in Step Functions.
attach = function(state_machine_arn,
client=NULL){
if (!is.null(client)){
LOGGER$debug(paste("The argument 'client' is not provided. Creating a new",
"`paws::sfn` client instance with default settings."))
client = sfn()
}
response = client$describe_state_machine(stateMachineArn=state_machine_arn)
return(Workflow$new(
name=response[['name']],
definition=FrozenGraph$public_methods$from_json(response[['definition']]),
role=response[['roleArn']],
state_machine_arn=response[['stateMachineArn']],
client=client)
)
},
#' @description Creates the workflow on Step Functions.
#' @return str: The Amazon Resource Name (ARN) of the workflow created. If the workflow
#' already existed, the ARN of the existing workflow is returned.
create = function(){
if (!is.null(self$state_machine_arn)){
LOGGER$warn("The workflow already exists on AWS Step Functions. No action will be performed.")
return(self$state_machine_arn)
}
tryCatch({
self$state_machine_arn = private$.create()
},
error = function(e){
self$state_machine_arn = private$.extract_state_machine_arn(e)
LOGGER$error(paste("A workflow with the same name already exists on AWS",
"Step Functions. To update a workflow, use Workflow.update()."))
})
return(self$state_machine_arn)
},
#' @description Updates an existing state machine by modifying its definition
#' and/or role. Executions started immediately after calling this
#' method may use the previous definition and role.
#' @param definition (State or Chain, optional): The Amazon States Language
#' \url{https://states-language.net/spec.html} definition to update
#' the workflow with. (default: None)
#' @param role (str, optional): The Amazon Resource Name (ARN) of the IAM role
#' to use for creating, managing, and running the workflow. (default: None)
#' @return str: The state machine definition and/or role updated. If the update fails,
#' None will be returned.
update = function(definition=NULL,
role=NULL){
if (is.null(definition) && is.null(role))
stop("A new definition and/or role must be provided to update an existing workflow.")
if (is.null(self$state_machine_arn))
stop("Local workflow instance does not point to an existing workflow ",
"on AWS StepFunctions. Please consider using Workflow.create(...) ",
"to create a new workflow, or Workflow.attach(...) to attach the ",
"instance to an existing workflow on AWS Step Functions.")
if (!is.null(definition)){
if (inherits(definition, "Graph"))
self$definition = definition
else
self$definition = Graph$new(
definition,
timeout_seconds=self$timeout_seconds,
comment=self$comment,
version=self$version)
}
if(!is.null(role))
self$role = role
response = self$client$update_state_machine(
stateMachineArn=self$state_machine_arn,
definition=self$definition$to_json(pretty=self$format_json),
roleArn=self$role
)
LOGGER$info(paste("Workflow updated successfully on AWS Step Functions.",
"All execute() calls will use the updated definition and role within a few seconds."))
return(self$state_machine_arn)
},
#' @description Starts a single execution of the workflow.
#' @param name (str, optional): The name of the workflow execution. If one is
#' not provided, a workflow execution name will be auto-generated. (default: None)
#' @param inputs (str, list, optional): Input data for the workflow execution. (default: None)
#' @return stepfunctions.workflow.Execution: An execution instance of the workflow.
execute = function(name=NULL, inputs=NULL){
if (!is.null(self$workflow_input)){
validation_result = self$workflow_input$validate(inputs)
if (isFALSE(validation_result$valid))
stop(sprintf(
"Expected run input with the schema: %s",
self$workflow_input$get_schema_as_json()))
}
if (is.null(self$state_machine_arn))
stop("Local workflow instance does not point to an existing workflow on ",
"AWS StepFunctions. Before executing a workflow, call Workflow.create(...) ",
"or Workflow.attach(...).")
params = list(
'stateMachineArn'=self$state_machine_arn)
params[['name']] = name
if (!is.null(inputs))
params[['input']] = toJSON(inputs, pretty=self$format_json, auto_unbox=T)
response = self$client$start_execution(
stateMachineArn=params$stateMachineArn,
name=params$name,
input=params$input)
LOGGER$info("Workflow execution started successfully on AWS Step Functions.")
# name is None because \code{\link[paws]{sfn}} client.start_execution only returns startDate and executionArn
return(Execution$new(
workflow=self,
execution_arn=response[['executionArn']],
start_date=response[['startDate']],
status=ExecutionStatus$Running,
client=self$client)
)
},
#' @description Lists the executions for the workflow.
#' @param max_items (int, optional): The maximum number of items to be returned. (default: 100)
#' @param status_filter (ExecutionStatus, optional): If specified, only list
#' the executions whose current status matches the given filter. (default: None)
#' @param html (bool, optional): Renders the list as an HTML table (If running
#' in an IRKernel environment). If the parameter is not provided, or
#' set to FALSE, a R list is returned. (default: False)
#' @return list: List of workflow run instances.
list_executions = function(max_items=100,
status_filter=NULL,
html=FALSE){
if (is.null(self$state_machine_arn))
return(list())
LOGGER$debug("Retrieving list of executions from AWS Step Functions.")
token=NULL
response = list()
while(!identical(token, character(0))){
batch_response=response=self$client$list_executions(
stateMachineArn=self$state_machine_arn,
statusFilter=if(is.null(status_filter)) status_filter else toupper(status_filter),
maxResults=1000, # maximum allowed page size
nextToken=token)
response = c(response, batch_response["executions"])
if(length(response) >= max_items){
response = response[1:max_items]
break
}
token = batch_response[["nextToken"]]
}
runs = lapply(response$executions, function(execution){
Execution$new(
name=execution[['name']],
workflow=self,
execution_arn=execution[['executionArn']],
start_date=execution[['startDate']],
stop_date=execution[['stopDate']],
status=execution[['status']],
client=self$client
)
})
if (html){
display_html <- pkg_method("display_html","IRdisplay")
return(display_html(ExecutionsList$new(runs)$to_html()))
} else {
return(runs)
}
},
#' @description Deletes the workflow, if it exists.
delete = function(){
if (!is.null(self$state_machine_arn))
self$client$delete_state_machine(stateMachineArn=self$state_machine_arn)
LOGGER$info(paste("Workflow has been marked for deletion. If the workflow has",
"running executions, it will be deleted when all executions are stopped."))
},
#' @description Renders a visualization of the workflow graph.
#' @param portrait (bool, optional): Boolean flag set to `True` if the workflow
#' graph should be rendered in portrait orientation. Set to `False`,
#' if the graph should be rendered in landscape orientation. (default: False)
render_graph = function(portrait = FALSE){
widget = WorkflowGraphWidget$new(self$definition$to_json())
return(widget$show(portrait=portrait))
},
#' @description Returns a CloudFormation template that contains only the StateMachine
#' resource. To reuse the CloudFormation template in a different region,
#' please make sure to update the region specific AWS resources (e.g: Lambda
#' ARN, Training Image) in the StateMachine definition.
get_cloudformation_template = function(){
return(build_cloudformation_template(self))
},
#' @description class formatting
format = function(){
# identify if in Rstudio or not
if (pkg_env$jupyter){
if (!is.null(self$state_machine_arn))
return(sprintf(
'Workflow: <a target="_blank" href="%s">%s</a>',
create_sfn_workflow_url(self$state_machine_arn), self$state_machine_arn))
else
return('Workflow: Does Not Exist.')
} else {
if (!is.null(self$state_machine_arn)){
cls_fmt = "%s(name='%s', role='%s', state_machine_arn='%s')"
return(sprintf(cls_fmt, class(self)[1],
self$name, self$role, self$state_machine_arn))
} else {
cls_fmt = "%s(name='%s', role='%s'): Does Not Exist"
return(sprintf(cls_fmt, class(self)[1],
self$name, self$role))
}
}
},
#' @description print class
print = function(){
if(pkg_env$jupyter){
display_html <- pkg_method("display_html","IRdisplay")
display_html(self$format())
} else {
cat(self$format(), "\n")
}
}
),
private = list(
.create = function(){
response = self$client$create_state_machine(
name=self$name,
definition=self$definition$to_json(pretty=self$format_json),
roleArn=self$role,
tags=self$tags)
LOGGER$info("Workflow created successfully on AWS Step Functions.")
return(response[['stateMachineArn']])
},
.extract_state_machine_arn = function(exception){
message = attributes(exception)$error_response$message
return(unlist(strsplit(message, "'"))[2])
}
),
lock_objects=F
)
#' @title Execution class
#' @description Class for managing a workflow execution.
#' @export
Execution = R6Class("Execution",
public = list(
#' @description Initialize Execution class
#' @param workflow (Workflow): Step Functions workflow instance.
#' @param execution_arn (str): The Amazon Resource Name (ARN) of the workflow execution.
#' @param start_date (datetime.datetime): The date the workflow execution was started.
#' @param status (RunStatus): Status of the workflow execution.
#' @param client (SFN.Client, optional): \code{\link[paws]{sfn}} client to use for running and
#' managing the workflow executions on Step Functions. If no client
#' is provided, the \code{\link[paws]{sfn}} client from the parent workflow will be used. (default: None)
#' @param name (str, optional): Name for the workflow execution. (default: None)
#' @param stop_date (datetime.datetime, optional): The date the workflow execution
#' was stopped, if applicable. (default: None)
initialize = function(workflow,
execution_arn,
start_date,
status,
client=NULL,
name=NULL,
stop_date=NULL){
self$name = name
self$workflow = workflow
self$execution_arn = execution_arn
self$start_date = start_date
self$stop_date = stop_date
self$status = status
if (!is.null(client))
self$client = client
else
self$client = self$workflow$client
},
#' @description Stops a workflow execution.
#' @param error (str, optional): The error code of the failure. (default: None)
#' @param cause (str, optional): A more detailed explanation of the cause of the failure. (default: None)
#' @return list: Datetime of when the workflow execution was stopped. Example below::
#' \code{
#' list(
#' stopDate = as.POSIXct(
#' "2015-01-01"
#' )
#' )
#' }
#' **Response structure**:
#' \itemize{
#' \item{(list)}
#' \item{stopDate (datetime): The date the workflow execution is stopped}
#' }
stop = function(cause=NULL,
error=NULL){
response = self$client$stop_execution(
executionArn=self$execution_arn,
cause=cause,
error=error
)
return(response)
},
#' @description Lists the events in the workflow execution.
#' @param max_items (int, optional): The maximum number of items to be returned.
#' (default: 100)
#' @param reverse_order (bool, optional): Boolean flag set to `True` if the events
#' should be listed in reverse chronological order. Set to `False`,
#' if the order should be in chronological order. (default: False)
#' @param html (bool, optional): Renders the list as an HTML table (If running in
#' an IRKernel environment). If the parameter is not provided, or set
#' to FALSE, a R list is returned. (default: False)
#' @return list: Object containing the list of workflow execution events. Refer
#' to :meth:`.SFN.Client.get_execution_history()` for the response structure.
list_events = function(max_items=100,
reverse_order=FALSE,
html=FALSE){
LOGGER$debug("Retrieving list of history events for your execution from AWS Step Functions.")
events=list()
token=NULL
while(!identical(token, character(0))){
batch_response = self$client$get_execution_history(
executionArn=self$execution_arn,
maxResults=1000, # maximum allowed page size
reverseOrder=reverse_order,
nextToken=token
)
events=c(events, batch_response[["events"]])
if(length(events) >= max_items){
events = events[1:max_items]
break
}
token=batch_response[["nextToken"]]
}
if (html){
display_html <- pkg_method("display_html","IRdisplay")
return(display_html(EventsList$new(events)$to_html()))
} else {
return(events)
}
},
#' @description Describes a workflow execution.
#' @return list: Details of the workflow execution.
#' **Response structure**:
#' \itemize{
#' \item{executionArn (string): The Amazon Resource Name (ARN) that identifies the workflow execution.}
#' \item{stateMachineArn (string): The Amazon Resource Name (ARN) of the workflow that was executed.}
#' \item{name (string): The name of the workflow execution.}
#' \item{status (string): The current status of the workflow execution.}
#' \item{startDate (datetime): The date the workflow execution is started.}
#' \item{stopDate (datetime): If the workflow execution has already ended, the date the execution stopped.}
#' \item{input (string): The string that contains the JSON input data of the workflow execution.}
#' \item{output (string): The JSON output data of the workflow execution.}
#' }
describe = function(){
return(self$client$describe_execution(executionArn=self$execution_arn))
},
#' @description Renders a visualization of the workflow execution graph.
#' @param portrait (bool, optional): Boolean flag set to `True` if the workflow
#' execution graph should be rendered in portrait orientation. Set
#' to `False`, if the graph should be rendered in landscape orientation. (default: False)
#' @param max_events (int, optional): Specifies the number of events to be visualized
#' in the workflow execution graph. (default: 25000)
render_progress = function(portrait=FALSE,
max_events=25000){
events = self$list_events(max_items=max_events)
widget = ExecutionGraphWidget$new(
self$workflow$definition$to_json(),
toJSON(events, auto_unbox = T),
execution_arn=self$execution_arn)
return(widget$show(portrait=portrait))
},
#' @description Get the input for the workflow execution.
#' @return list: Workflow execution input.
get_input = function(){
run_input = self$describe()[['input']]
if(is.null(run_input))
return(run_input)
return(fromJSON(run_input))
},
#' @description Get the output for the workflow execution.
#' @param wait (bool, optional): Boolean flag set to `True` if the call should
#' wait for a running workflow execution to end before returning
#' the output. Set to `False`, otherwise. Note that if the status
#' is running, and `wait` is set to `True`, this will be a blocking
#' call. (default: False)
#' @return list: Workflow execution output.
get_output = function(wait=FALSE){
while(wait && self$describe()[['status']] == 'RUNNING'){
Sys.sleep(1)
}
output = self$describe()[["output"]]
if (is.null(outpu))
return(output)
return(fromJSON(output))
},
#' @description format class
format = function(){
if(pkg_env$jupyter){
return(sprintf('Execution: <a target="_blank" href="%s">%s</a>',
create_sfn_execution_url(self$execution_arn), self$execution_arn))
} else {
return(sprintf("%s(execution_arn='%s', name='%s', status='%s', start_date='%s')",
class(self)[1], self$execution_arn, self$name, self$status, self$start_date))
}
},
#' @description print class
print = function(){
if(pkg_env$jupyter){
display_html <- pkg_method("display_html","IRdisplay")
display_html(self$format())
} else {
cat(self$format(), "\n")
}
}
),
lock_objects=F
)
|
testlist <- list(A = structure(c(1.38997190089718e-309, 3.81575932257023e-236, 3.82003335597149e-236), .Dim = c(1L, 3L)), B = structure(0, .Dim = c(1L, 1L)))
result <- do.call(multivariance:::match_rows,testlist)
str(result) | /multivariance/inst/testfiles/match_rows/AFL_match_rows/match_rows_valgrind_files/1613127362-test.R | no_license | akhikolla/updatedatatype-list3 | R | false | false | 226 | r | testlist <- list(A = structure(c(1.38997190089718e-309, 3.81575932257023e-236, 3.82003335597149e-236), .Dim = c(1L, 3L)), B = structure(0, .Dim = c(1L, 1L)))
result <- do.call(multivariance:::match_rows,testlist)
str(result) |
tblsLoad <-
function(connection, table.schematic = NULL, unlist = FALSE) {
require(RODBC)
require(dplyr)
if(is.logical(unlist) == FALSE) {
stop('Unlist must be of class logical')
}
if(is.character(table.schematic) == FALSE & is.null(table.schematic) == FALSE) {
stop('Table schematic input must be text or left NULL')
}
tbls <- # load all table details into a df
sqlTables(odbc.textio)
if(is.null(table.schematic) == FALSE) {
tbls <-
tbls %>% filter(TABLE_SCHEM %in% table.schematic)
}
list.tbls <-
Map(
function(tbl)
sqlQuery(odbc.textio,
paste0(
'SELECT * FROM ['
, tbl
, ']'
)
),
tbls$TABLE_NAME
)
if(unlist == TRUE) {
list.tbls %>% list2env(.GlobalEnv) %>% return()
} else if(unlist == FALSE) {
return(list.tbls)
}
# to unlist the tables in returned list use list2env(list.tbls, .GlobalEnv)
} | /R/tblsLoad.R | no_license | avant-gardED/TextIO | R | false | false | 1,096 | r | tblsLoad <-
function(connection, table.schematic = NULL, unlist = FALSE) {
require(RODBC)
require(dplyr)
if(is.logical(unlist) == FALSE) {
stop('Unlist must be of class logical')
}
if(is.character(table.schematic) == FALSE & is.null(table.schematic) == FALSE) {
stop('Table schematic input must be text or left NULL')
}
tbls <- # load all table details into a df
sqlTables(odbc.textio)
if(is.null(table.schematic) == FALSE) {
tbls <-
tbls %>% filter(TABLE_SCHEM %in% table.schematic)
}
list.tbls <-
Map(
function(tbl)
sqlQuery(odbc.textio,
paste0(
'SELECT * FROM ['
, tbl
, ']'
)
),
tbls$TABLE_NAME
)
if(unlist == TRUE) {
list.tbls %>% list2env(.GlobalEnv) %>% return()
} else if(unlist == FALSE) {
return(list.tbls)
}
# to unlist the tables in returned list use list2env(list.tbls, .GlobalEnv)
} |
# 主分析程序
options(stringsAsFactors = F)
# 以一般分詞方式確認詞庫的效果 實際分析或許用關鍵字取得方式比較好
library(readr)
library(text2vec)
library(jiebaR)
library(stats)
library(stringr)
# init jieba segment
seg = worker(bylines = TRUE, dict = "./dict/dict_zhtw.txt", stop_word = "./dict/stop_words.utf8.txt")
# set user dictionary
new_user_word(seg, '場次名')
new_user_word(seg, '工商')
new_user_word(seg, '手滑')
data = read_csv('csv/data.csv')
contents = data$content
rm(data)
# clear data
# clear html tag
contents = gsub("<.*?>", " ", contents)
# 清除 wwwww 這個特殊詞
contents = gsub("w{2,}", "", contents, ignore.case = TRUE)
# 清除 xd 這個特殊詞
contents = gsub("xd+", "", contents, ignore.case = TRUE)
# 清除從頭到尾都沒有中文的內容
contents = gsub("^[^\u4E00-\u9FA5]*$", "", contents)
# 清理掉被篩選掉完全為空的條目
contents = contents[contents!=""]
# try just get content has 'FF' or 'CWT'
contents = contents[grepl('FF', contents, ignore.case = TRUE) | grepl('CWT', contents, ignore.case = TRUE)]
# TODO: 分詞前處理
# 將場次名的標準結構取代為「場次名」這個字 以統一場次名混亂的問題
# FFK\d{2}
# FF\d{2}
# FFK
# FF
# CWTT\d{2}
# CWTK\d{2}
# CWT\d{2}
# CWTT
# CWTK
contents = gsub("\bFFK\d*\b", "場次名", contents)
contents = gsub("\bFF\d*\b", "場次名", contents)
contents = gsub("\bCWTT\d*\b", "場次名", contents)
contents = gsub("\bCWTK\d*\b", "場次名", contents)
contents = gsub("\bCWT\d*\b", "場次名", contents)
# 將英文部份先拋出去 避免jieba的英文分詞問題
eng_cut = str_match_all(contents, '[A-z]{2,}')
contents = gsub("[A-z]{2,}", "", contents, ignore.case = TRUE)
# 分詞
seg_results = segment(contents, seg)
# TODO: 把英文部份塞回去
q = list()
for(index in 1:length(seg_results)) {
q[[index]] = c(seg_results[[index]], eng_cut[[index]][,1])
}
seg_results = q
rm(q)
rm(eng_cut)
# TRY: 或許這邊試試看進行提取關鍵字?
token = itoken(seg_results)
vocab = create_vocabulary(token)
vectorizer = vocab_vectorizer(vocab)
dtm_train = create_dtm(token, vectorizer)
# kms <- kmeans(dtm_train, centers = 3, nstart = 1)
# ratio <- kms$tot.withinss / (kms$tot.withinss + kms$betweenss)
| /main.R | no_license | windthunder/plurk_analysis | R | false | false | 2,299 | r | # 主分析程序
options(stringsAsFactors = F)
# 以一般分詞方式確認詞庫的效果 實際分析或許用關鍵字取得方式比較好
library(readr)
library(text2vec)
library(jiebaR)
library(stats)
library(stringr)
# init jieba segment
seg = worker(bylines = TRUE, dict = "./dict/dict_zhtw.txt", stop_word = "./dict/stop_words.utf8.txt")
# set user dictionary
new_user_word(seg, '場次名')
new_user_word(seg, '工商')
new_user_word(seg, '手滑')
data = read_csv('csv/data.csv')
contents = data$content
rm(data)
# clear data
# clear html tag
contents = gsub("<.*?>", " ", contents)
# 清除 wwwww 這個特殊詞
contents = gsub("w{2,}", "", contents, ignore.case = TRUE)
# 清除 xd 這個特殊詞
contents = gsub("xd+", "", contents, ignore.case = TRUE)
# 清除從頭到尾都沒有中文的內容
contents = gsub("^[^\u4E00-\u9FA5]*$", "", contents)
# 清理掉被篩選掉完全為空的條目
contents = contents[contents!=""]
# try just get content has 'FF' or 'CWT'
contents = contents[grepl('FF', contents, ignore.case = TRUE) | grepl('CWT', contents, ignore.case = TRUE)]
# TODO: 分詞前處理
# 將場次名的標準結構取代為「場次名」這個字 以統一場次名混亂的問題
# FFK\d{2}
# FF\d{2}
# FFK
# FF
# CWTT\d{2}
# CWTK\d{2}
# CWT\d{2}
# CWTT
# CWTK
contents = gsub("\bFFK\d*\b", "場次名", contents)
contents = gsub("\bFF\d*\b", "場次名", contents)
contents = gsub("\bCWTT\d*\b", "場次名", contents)
contents = gsub("\bCWTK\d*\b", "場次名", contents)
contents = gsub("\bCWT\d*\b", "場次名", contents)
# 將英文部份先拋出去 避免jieba的英文分詞問題
eng_cut = str_match_all(contents, '[A-z]{2,}')
contents = gsub("[A-z]{2,}", "", contents, ignore.case = TRUE)
# 分詞
seg_results = segment(contents, seg)
# TODO: 把英文部份塞回去
q = list()
for(index in 1:length(seg_results)) {
q[[index]] = c(seg_results[[index]], eng_cut[[index]][,1])
}
seg_results = q
rm(q)
rm(eng_cut)
# TRY: 或許這邊試試看進行提取關鍵字?
token = itoken(seg_results)
vocab = create_vocabulary(token)
vectorizer = vocab_vectorizer(vocab)
dtm_train = create_dtm(token, vectorizer)
# kms <- kmeans(dtm_train, centers = 3, nstart = 1)
# ratio <- kms$tot.withinss / (kms$tot.withinss + kms$betweenss)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/Stat_test_Delta_AUC_Group_Specific.R
\name{Stat_test_Delta_AUC_Group_Specific}
\alias{Stat_test_Delta_AUC_Group_Specific}
\title{T-statistic of the Difference of AUC of Two Group-Specific Polynomial Marginal Dynamics}
\usage{
Stat_test_Delta_AUC_Group_Specific(
MEM_Pol_group,Group1,Group2,
time.G1,time.G2,common.interval = TRUE,
method = "trapezoid",Group.dependence = TRUE,
Averaged = FALSE,conf_level = 0.95,
alternative = "two.sided"
)
}
\arguments{
\item{MEM_Pol_group}{A list with similar structure than the output provided by the function \link[AUCcomparison]{MEM_Polynomial_Group_structure}.
A list containing:
\itemize{
\item \code{Model_estimation}: a list containing at least 2 elements: \enumerate{
\item the vector of the marginal (fixed) parameters estimates (at least for the groups whose AUC is to estimate), labeled \emph{'beta'}.
\item the variance-covariance matrix of these parameters, labeled \emph{'varFix'} (see \link[AUCcomparison]{MEM_Polynomial_Group_structure} for details about the parameter order).
}
\item \code{Model_features}: a list of at least 2 elements: \enumerate{
\item \code{Groups}: a vector indicating the names of the groups whose fixed parameters are given.
\item \code{Marginal.dyn.feature}: a list summarizing the features of the marginal dynamics defined in the model:
\itemize{
\item \code{dynamic.type}: a character scalar indicating the chosen type of marginal dynamics. Options are 'polynomial' or 'spline'.
\item \code{intercept}: a logical vector summarizing choices about global and group-specific intercepts (Number of groups + 1) elements whose elements are named as ('global.intercept','group.intercept1', ..., 'group.interceptG') if G Groups are defined in \code{MEM_Pol_group}. For each element of the vector, if TRUE, the considered intercept is considered as included in the model (see \emph{Examples}).
}
If \code{dynamic.type} is defined as 'polynomial':\itemize{
\item \code{polynomial.degree}: an integer vector indicating the degree of polynomial functions, one value for each group.
}
If \code{dynamic.type} is defined as 'spline':\itemize{
\item \code{spline.degree}: an integer vector indicating the degree of B-spline curves, one for each group.
\item \code{knots}: a list of group-specific internal knots used to build B-spline basis (one numerical vector for each group) (see \link[splines]{bs} for more details).
\item \code{df}: a numerical vector of group-specific degrees of freedom used to build B-spline basis, (one for each group).
\item \code{boundary.knots}: a list of group-specific boundary knots used to build B-spline basis (one vector for each group) (see \link[splines]{bs} for more details).
}
}
}}
\item{Group1}{a character scalar indicating the name of the first group whose marginal dynamics must be considered. This group name must belong to the set of groups involved in the MEM (see \code{Groups} vector in \code{MEM_Pol_group}).}
\item{Group2}{a character scalar indicating the name of the second group whose marginal dynamics must be considered. This group name must belong to the set of groups involved in the MEM (see \code{Groups} vector in \code{MEM_Pol_group}).}
\item{time.G1}{a numerical vector of time points (x-axis coordinates) to use for the Group1 AUC calculation.}
\item{time.G2}{a numerical vector of time points (x-axis coordinates) to use for the Group2 AUC calculation.}
\item{common.interval}{a logical scalar. If FALSE, the difference of AUC is calculated as the difference of AUCs where the AUC of each group is calculated on its specific interval of time. If TRUE (default), the difference of AUC is estimated on a common interval of time defined as the intersect of the two group-specific interval (see \link[AUCcomparison]{Group_specific_Delta_AUC_estimation} for more details about calculation).}
\item{method}{a character scalar indicating the interpolation method to use to estimate the AUC. Options are 'trapezoid' (default), 'lagrange' and 'spline'. In this version, the 'spline' interpolation is implemented with "not-a-knot" spline boundary conditions.}
\item{Group.dependence}{a logical scalar indicating whether the two groups, whose the difference of AUC (\eqn{\Delta}AUC) is studied, are considered as dependent. By default, this variable is defined as TRUE.}
\item{Averaged}{a logical scalar. If TRUE, the function return the difference of normalized AUC (nAUC) where nAUC is computated as the AUC divided by the range of time of calculation. If FALSE (default), the classic AUC is calculated.}
\item{conf_level}{a numerical value (between 0 and 1) indicating the confidence level of the interval. By default, this variable is fixed at 0.95}
\item{alternative}{a character scalar specifying the alternative hypothesis. Options are 'two.sided' (default), 'greater' or 'less'.}
}
\value{
A list containing:\itemize{
\item \code{Tstat}: the value of the t-statistic.
\item \code{Pvalue}: the P-value.
\item \code{Conf.int}: the confidence interval.
\item \code{Delta_AUC}: the estimated value of the difference of AUC between the two groups (nAUC2 - nAUC1) (see \code{\link[AUCcomparison]{Group_specific_Delta_AUC_estimation}} for more details).
\item \code{AUCs}: the estimated values of the Group-specific AUC (AUC1 and AUC 2)
(see \code{\link[AUCcomparison]{Group_specific_AUC_estimation}} for more details).
}
}
\description{
This function performs the t-test evaluating whether the difference of area under the curve of two marginal dynamics, modeled by group-structured polynomials or B-spline curve in Mixed-Effects model, is null.
}
\examples{
\donttest{# Download of data
data("HIV_Simu_Dataset_Delta01_cens")
data <- HIV_Simu_Dataset_Delta01_cens
# Change factors in character vectors
data$id <- as.character(data$id) ; data$Group <- as.character(data$Group)
MEM_estimation <- MEM_Polynomial_Group_structure(y=data$VL,x=data$time,Group=data$Group,
Id=data$id,Cens=data$cens)
time_group1 <- unique(data$time[which(data$Group=="Group1")])
time_group2 <- unique(data$time[which(data$Group=="Group2")])
Test <- Stat_test_Delta_AUC_Group_Specific(MEM_Pol_group=MEM_estimation,
Group1="Group1",Group2="Group2",
time.G1=time_group1,time.G2=time_group2)
}
}
\seealso{
\code{\link[AUCcomparison]{MEM_Polynomial_Group_structure}},
\code{\link[AUCcomparison]{Group_specific_Delta_AUC_estimation}},
\code{\link[AUCcomparison]{Group_specific_AUC_estimation}}
}
| /man/Stat_test_Delta_AUC_Group_Specific.Rd | permissive | marie-alexandre/AUCcomparison | R | false | true | 6,676 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/Stat_test_Delta_AUC_Group_Specific.R
\name{Stat_test_Delta_AUC_Group_Specific}
\alias{Stat_test_Delta_AUC_Group_Specific}
\title{T-statistic of the Difference of AUC of Two Group-Specific Polynomial Marginal Dynamics}
\usage{
Stat_test_Delta_AUC_Group_Specific(
MEM_Pol_group,Group1,Group2,
time.G1,time.G2,common.interval = TRUE,
method = "trapezoid",Group.dependence = TRUE,
Averaged = FALSE,conf_level = 0.95,
alternative = "two.sided"
)
}
\arguments{
\item{MEM_Pol_group}{A list with similar structure than the output provided by the function \link[AUCcomparison]{MEM_Polynomial_Group_structure}.
A list containing:
\itemize{
\item \code{Model_estimation}: a list containing at least 2 elements: \enumerate{
\item the vector of the marginal (fixed) parameters estimates (at least for the groups whose AUC is to estimate), labeled \emph{'beta'}.
\item the variance-covariance matrix of these parameters, labeled \emph{'varFix'} (see \link[AUCcomparison]{MEM_Polynomial_Group_structure} for details about the parameter order).
}
\item \code{Model_features}: a list of at least 2 elements: \enumerate{
\item \code{Groups}: a vector indicating the names of the groups whose fixed parameters are given.
\item \code{Marginal.dyn.feature}: a list summarizing the features of the marginal dynamics defined in the model:
\itemize{
\item \code{dynamic.type}: a character scalar indicating the chosen type of marginal dynamics. Options are 'polynomial' or 'spline'.
\item \code{intercept}: a logical vector summarizing choices about global and group-specific intercepts (Number of groups + 1) elements whose elements are named as ('global.intercept','group.intercept1', ..., 'group.interceptG') if G Groups are defined in \code{MEM_Pol_group}. For each element of the vector, if TRUE, the considered intercept is considered as included in the model (see \emph{Examples}).
}
If \code{dynamic.type} is defined as 'polynomial':\itemize{
\item \code{polynomial.degree}: an integer vector indicating the degree of polynomial functions, one value for each group.
}
If \code{dynamic.type} is defined as 'spline':\itemize{
\item \code{spline.degree}: an integer vector indicating the degree of B-spline curves, one for each group.
\item \code{knots}: a list of group-specific internal knots used to build B-spline basis (one numerical vector for each group) (see \link[splines]{bs} for more details).
\item \code{df}: a numerical vector of group-specific degrees of freedom used to build B-spline basis, (one for each group).
\item \code{boundary.knots}: a list of group-specific boundary knots used to build B-spline basis (one vector for each group) (see \link[splines]{bs} for more details).
}
}
}}
\item{Group1}{a character scalar indicating the name of the first group whose marginal dynamics must be considered. This group name must belong to the set of groups involved in the MEM (see \code{Groups} vector in \code{MEM_Pol_group}).}
\item{Group2}{a character scalar indicating the name of the second group whose marginal dynamics must be considered. This group name must belong to the set of groups involved in the MEM (see \code{Groups} vector in \code{MEM_Pol_group}).}
\item{time.G1}{a numerical vector of time points (x-axis coordinates) to use for the Group1 AUC calculation.}
\item{time.G2}{a numerical vector of time points (x-axis coordinates) to use for the Group2 AUC calculation.}
\item{common.interval}{a logical scalar. If FALSE, the difference of AUC is calculated as the difference of AUCs where the AUC of each group is calculated on its specific interval of time. If TRUE (default), the difference of AUC is estimated on a common interval of time defined as the intersect of the two group-specific interval (see \link[AUCcomparison]{Group_specific_Delta_AUC_estimation} for more details about calculation).}
\item{method}{a character scalar indicating the interpolation method to use to estimate the AUC. Options are 'trapezoid' (default), 'lagrange' and 'spline'. In this version, the 'spline' interpolation is implemented with "not-a-knot" spline boundary conditions.}
\item{Group.dependence}{a logical scalar indicating whether the two groups, whose the difference of AUC (\eqn{\Delta}AUC) is studied, are considered as dependent. By default, this variable is defined as TRUE.}
\item{Averaged}{a logical scalar. If TRUE, the function return the difference of normalized AUC (nAUC) where nAUC is computated as the AUC divided by the range of time of calculation. If FALSE (default), the classic AUC is calculated.}
\item{conf_level}{a numerical value (between 0 and 1) indicating the confidence level of the interval. By default, this variable is fixed at 0.95}
\item{alternative}{a character scalar specifying the alternative hypothesis. Options are 'two.sided' (default), 'greater' or 'less'.}
}
\value{
A list containing:\itemize{
\item \code{Tstat}: the value of the t-statistic.
\item \code{Pvalue}: the P-value.
\item \code{Conf.int}: the confidence interval.
\item \code{Delta_AUC}: the estimated value of the difference of AUC between the two groups (nAUC2 - nAUC1) (see \code{\link[AUCcomparison]{Group_specific_Delta_AUC_estimation}} for more details).
\item \code{AUCs}: the estimated values of the Group-specific AUC (AUC1 and AUC 2)
(see \code{\link[AUCcomparison]{Group_specific_AUC_estimation}} for more details).
}
}
\description{
This function performs the t-test evaluating whether the difference of area under the curve of two marginal dynamics, modeled by group-structured polynomials or B-spline curve in Mixed-Effects model, is null.
}
\examples{
\donttest{# Download of data
data("HIV_Simu_Dataset_Delta01_cens")
data <- HIV_Simu_Dataset_Delta01_cens
# Change factors in character vectors
data$id <- as.character(data$id) ; data$Group <- as.character(data$Group)
MEM_estimation <- MEM_Polynomial_Group_structure(y=data$VL,x=data$time,Group=data$Group,
Id=data$id,Cens=data$cens)
time_group1 <- unique(data$time[which(data$Group=="Group1")])
time_group2 <- unique(data$time[which(data$Group=="Group2")])
Test <- Stat_test_Delta_AUC_Group_Specific(MEM_Pol_group=MEM_estimation,
Group1="Group1",Group2="Group2",
time.G1=time_group1,time.G2=time_group2)
}
}
\seealso{
\code{\link[AUCcomparison]{MEM_Polynomial_Group_structure}},
\code{\link[AUCcomparison]{Group_specific_Delta_AUC_estimation}},
\code{\link[AUCcomparison]{Group_specific_AUC_estimation}}
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/roxy.R
\name{dense}
\alias{dense}
\title{Dense colour palette}
\arguments{
\item{n}{integer giving the number of colours (>= 1) to be produced;
currently it does not make sense to ask for more than 256}
}
\value{
Vector of R colours (\code{'#RRGGBB'} strings) of length \code{n}.
}
\description{
The dense colormap is sequential with whitish-blue for low values and increasing in purple with increasing value, which could be used to represent an increase in water density.
}
\examples{
z <- xtabs(weight~Time+Chick, ChickWeight)
x <- sort(as.numeric(rownames(z)))
y <- sort(as.numeric(colnames(z)))
image(
x = x, y = y, z = z, col = dense(100),
xlab = 'Time', ylab = 'Chick'
)
}
\keyword{color}
| /man/dense.Rd | no_license | richardsc/cmocean | R | false | true | 775 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/roxy.R
\name{dense}
\alias{dense}
\title{Dense colour palette}
\arguments{
\item{n}{integer giving the number of colours (>= 1) to be produced;
currently it does not make sense to ask for more than 256}
}
\value{
Vector of R colours (\code{'#RRGGBB'} strings) of length \code{n}.
}
\description{
The dense colormap is sequential with whitish-blue for low values and increasing in purple with increasing value, which could be used to represent an increase in water density.
}
\examples{
z <- xtabs(weight~Time+Chick, ChickWeight)
x <- sort(as.numeric(rownames(z)))
y <- sort(as.numeric(colnames(z)))
image(
x = x, y = y, z = z, col = dense(100),
xlab = 'Time', ylab = 'Chick'
)
}
\keyword{color}
|
#' Prepares data for model fitting (fe.prov)
#'
#' \code{fe.data.prep} prepares the data for model fitting with \code{fe.prov} by
#' taking the data with missing values imputed. Go to
#' \href{https://github.com/umich-biostatistics/FEprovideR}{Github} for a tutorial.
#'
#' @param data a \code{data.frame} including response, provider ID, and covariates, with missing values imputed
#' @param Y.char name of the response variable from \code{data} as a character string
#' @param Z.char names of covariates from \code{data} as vector of character strings
#' @param prov.char name of provider IDs variable as a character string
#' @param cutoff cutoff of provider size as an interger, default value is 10
#'
#' @seealso \code{\link{fe.prov}}, \code{\link{test.fe.prov}},
#' \code{\link{funnel.SRR}}, \code{\link{confint.fe.prov}}
#'
#' @references He, K., Kalbfleisch, J.D., Li, Y. and Li, Y., 2013. Evaluating hospital
#' readmission rates in dialysis facilities; adjusting for hospital effects. Lifetime data
#' analysis, 19(4), pp.490-512.
#'
#' @return \code{data.frame}: a data frame sorted by provider IDs with additional
#' variables 'included', 'no.readm', 'all.readm' and missing values imputed.
#'
#' @examples
#' data(hospital) # build in data set
#' # Name input variables and other parameters
#' cutoff <- 10 # an integer as cutoff of facility (or provider) size with 10 as default
#' alpha <- 0.05 # significance level
#' Y.char <- 'Y'
#' prov.char <- 'prov.ID'
#' Z.char <- paste0('z', 1:3)
#'
#' hospital_prepared <- fe.data.prep(hospital, Y.char, Z.char, prov.char, cutoff) # data preparation
#'
#' @export fe.data.prep
#'
#' @importFrom Matrix rankMatrix
fe.data.prep <- function(data, Y.char, Z.char, prov.char, cutoff=10) {
# data: a data frame including response, provider ID, and
# covariates, with missing values imputed
# Y.char: a character string as name of response variable
# Z.char: a vector of character strings as names of covariates
# prov.char: a character string as name of variable consisting of provider IDs
# cutoff: an integer as cutoff of provider size with 10 as default
## check absence of variables
# message("Checking absence of variables ... ") # fewer warning messages for CRAN
Y.ind <- match(Y.char, names(data))
if (is.na(Y.ind)) {
stop(paste("Response variable '", Y.char, "' NOT found!", sep=""),call.=F)
}
Z.ind <- match(Z.char, names(data))
if (sum(is.na(Z.ind)) > 0) {
stop(paste("Covariate(s) '", paste(Z.char[is.na(Z.ind)], collapse="', '"), "' NOT found!", sep=""),call.=F)
}
prov.ind <- match(prov.char, names(data))
if (is.na(prov.ind)) {
stop(paste("Provider ID '", prov.char, "' NOT found!", sep=""),call.=F)
}
# message("Checking absence of variables completed!") # fewer warning messages for CRAN
## check missingness of variables
# message("Checking missingness of variables ... ")
if (sum(is.na(data[,Y.ind])) > 0) {
warning(sum(is.na(data[,Y.ind]))," out of ",NROW(data[,Y.ind])," in '",Y.char,"' missing!",immediate.=T,call.=F)
}
for (i in 1:length(Z.ind)) {
if (sum(is.na(data[,Z.ind[i]])) > 0) {
warning(sum(is.na(data[,Z.ind[i]]))," out of ",NROW(data[,Z.ind[i]])," in '",Z.char[i],"' missing!",immediate.=T,call.=F)
}
}
if (sum(is.na(data[,prov.ind])) > 0) {
warning(sum(is.na(data[,prov.ind]))," out of ",NROW(data[,prov.ind])," in '",prov.char,"' missing!",immediate.=T,call.=F)
}
if (sum(complete.cases(data[,c(Y.ind,Z.ind,prov.ind)]))==NROW(data)) {
# message("Missing values NOT found. Checking missingness of variables completed!") # fewer warnings
} else {
missingness <- (1 - sum(complete.cases(data[,c(Y.ind,Z.ind,prov.ind)])) / NROW(data)) * 100
stop(paste(round(missingness,2), "% of all observations are missing!",sep=""),call.=F)
}
## check variation in covariates
# message("Checking variation in covariates ... ") # fewer messages
ind.novariation <- which(apply(data[, Z.char], 2, var)==0)
if(length(ind.novariation) > 0){
stop(paste0("Covariate(s) '", paste(Z.char[ind.novariation], collapse="', '"), "' is/are discharge-invariant!"))
}
# message("Checking variation in covariates completed!")
## check singularity of design matrix
# message("Checking sigularity of design matrix ... ")
for (i in 2:length(Z.char)) {
if (rankMatrix(as.matrix(data[,Z.char[1:i]]))[1] < i)
stop(paste0("Covariate '", Z.char[i], "' is perfectly collinear with the rest!",sep=""),call.=F)
}
# message("NO multicollinearity in design matrix. Checking sigularity of design matrix completed!")
data <- data[order(factor(data[,prov.ind])),] # sort data by provider ID
prov.size <- as.integer(table(data[,prov.ind])) # provider sizes
prov.size.long <- rep(prov.size,prov.size) # provider sizes assigned to patients
data$included <- 1 * (prov.size.long > cutoff) # create variable 'included' as an indicator
# warning(sum(prov.size<=cutoff)," out of ",length(prov.size),
# " providers considered small and filtered out!",immediate.=T,call.=F)
prov.list <- unique(data[data$included==1,prov.ind]) # a reduced list of provider IDs
prov.no.readm <- # providers with no readmission within 30 days
prov.list[sapply(split(data[data$included==1,Y.ind], factor(data[data$included==1,prov.ind])),sum)==0]
data$no.readm <- 0
data$no.readm[data[,prov.ind]%in%c(prov.no.readm)] <- 1
# message(paste(length(prov.no.readm),"out of",length(prov.list),
# "remaining providers with no readmission within 30 days."))
prov.all.readm <- # providers with all readmissions within 30 days
prov.list[sapply(split(1-data[data$included==1,Y.ind],factor(data[data$included==1,prov.ind])),sum)==0]
data$all.readm <- 0
data$all.readm[data[,prov.ind]%in%c(prov.all.readm)] <- 1
# message(paste(length(prov.all.readm),"out of",length(prov.list),
# "remaining providers with all readmissions within 30 days."))
# message(paste0("After screening, ", round(sum(data[data$included==1,Y.ind])/length(data[data$included==1,Y.ind])*100,2),
# "% of all discharges were readmitted within 30 days."))
return(data)
# data: a data frame sorted by provider IDs with additional variables 'included', 'no.readm', 'all.readm'
# and missing values imputed
}
| /R/fe.data.prep.R | no_license | GlafiraM/FEprovideR | R | false | false | 6,404 | r |
#' Prepares data for model fitting (fe.prov)
#'
#' \code{fe.data.prep} prepares the data for model fitting with \code{fe.prov} by
#' taking the data with missing values imputed. Go to
#' \href{https://github.com/umich-biostatistics/FEprovideR}{Github} for a tutorial.
#'
#' @param data a \code{data.frame} including response, provider ID, and covariates, with missing values imputed
#' @param Y.char name of the response variable from \code{data} as a character string
#' @param Z.char names of covariates from \code{data} as vector of character strings
#' @param prov.char name of provider IDs variable as a character string
#' @param cutoff cutoff of provider size as an interger, default value is 10
#'
#' @seealso \code{\link{fe.prov}}, \code{\link{test.fe.prov}},
#' \code{\link{funnel.SRR}}, \code{\link{confint.fe.prov}}
#'
#' @references He, K., Kalbfleisch, J.D., Li, Y. and Li, Y., 2013. Evaluating hospital
#' readmission rates in dialysis facilities; adjusting for hospital effects. Lifetime data
#' analysis, 19(4), pp.490-512.
#'
#' @return \code{data.frame}: a data frame sorted by provider IDs with additional
#' variables 'included', 'no.readm', 'all.readm' and missing values imputed.
#'
#' @examples
#' data(hospital) # build in data set
#' # Name input variables and other parameters
#' cutoff <- 10 # an integer as cutoff of facility (or provider) size with 10 as default
#' alpha <- 0.05 # significance level
#' Y.char <- 'Y'
#' prov.char <- 'prov.ID'
#' Z.char <- paste0('z', 1:3)
#'
#' hospital_prepared <- fe.data.prep(hospital, Y.char, Z.char, prov.char, cutoff) # data preparation
#'
#' @export fe.data.prep
#'
#' @importFrom Matrix rankMatrix
fe.data.prep <- function(data, Y.char, Z.char, prov.char, cutoff=10) {
# data: a data frame including response, provider ID, and
# covariates, with missing values imputed
# Y.char: a character string as name of response variable
# Z.char: a vector of character strings as names of covariates
# prov.char: a character string as name of variable consisting of provider IDs
# cutoff: an integer as cutoff of provider size with 10 as default
## check absence of variables
# message("Checking absence of variables ... ") # fewer warning messages for CRAN
Y.ind <- match(Y.char, names(data))
if (is.na(Y.ind)) {
stop(paste("Response variable '", Y.char, "' NOT found!", sep=""),call.=F)
}
Z.ind <- match(Z.char, names(data))
if (sum(is.na(Z.ind)) > 0) {
stop(paste("Covariate(s) '", paste(Z.char[is.na(Z.ind)], collapse="', '"), "' NOT found!", sep=""),call.=F)
}
prov.ind <- match(prov.char, names(data))
if (is.na(prov.ind)) {
stop(paste("Provider ID '", prov.char, "' NOT found!", sep=""),call.=F)
}
# message("Checking absence of variables completed!") # fewer warning messages for CRAN
## check missingness of variables
# message("Checking missingness of variables ... ")
if (sum(is.na(data[,Y.ind])) > 0) {
warning(sum(is.na(data[,Y.ind]))," out of ",NROW(data[,Y.ind])," in '",Y.char,"' missing!",immediate.=T,call.=F)
}
for (i in 1:length(Z.ind)) {
if (sum(is.na(data[,Z.ind[i]])) > 0) {
warning(sum(is.na(data[,Z.ind[i]]))," out of ",NROW(data[,Z.ind[i]])," in '",Z.char[i],"' missing!",immediate.=T,call.=F)
}
}
if (sum(is.na(data[,prov.ind])) > 0) {
warning(sum(is.na(data[,prov.ind]))," out of ",NROW(data[,prov.ind])," in '",prov.char,"' missing!",immediate.=T,call.=F)
}
if (sum(complete.cases(data[,c(Y.ind,Z.ind,prov.ind)]))==NROW(data)) {
# message("Missing values NOT found. Checking missingness of variables completed!") # fewer warnings
} else {
missingness <- (1 - sum(complete.cases(data[,c(Y.ind,Z.ind,prov.ind)])) / NROW(data)) * 100
stop(paste(round(missingness,2), "% of all observations are missing!",sep=""),call.=F)
}
## check variation in covariates
# message("Checking variation in covariates ... ") # fewer messages
ind.novariation <- which(apply(data[, Z.char], 2, var)==0)
if(length(ind.novariation) > 0){
stop(paste0("Covariate(s) '", paste(Z.char[ind.novariation], collapse="', '"), "' is/are discharge-invariant!"))
}
# message("Checking variation in covariates completed!")
## check singularity of design matrix
# message("Checking sigularity of design matrix ... ")
for (i in 2:length(Z.char)) {
if (rankMatrix(as.matrix(data[,Z.char[1:i]]))[1] < i)
stop(paste0("Covariate '", Z.char[i], "' is perfectly collinear with the rest!",sep=""),call.=F)
}
# message("NO multicollinearity in design matrix. Checking sigularity of design matrix completed!")
data <- data[order(factor(data[,prov.ind])),] # sort data by provider ID
prov.size <- as.integer(table(data[,prov.ind])) # provider sizes
prov.size.long <- rep(prov.size,prov.size) # provider sizes assigned to patients
data$included <- 1 * (prov.size.long > cutoff) # create variable 'included' as an indicator
# warning(sum(prov.size<=cutoff)," out of ",length(prov.size),
# " providers considered small and filtered out!",immediate.=T,call.=F)
prov.list <- unique(data[data$included==1,prov.ind]) # a reduced list of provider IDs
prov.no.readm <- # providers with no readmission within 30 days
prov.list[sapply(split(data[data$included==1,Y.ind], factor(data[data$included==1,prov.ind])),sum)==0]
data$no.readm <- 0
data$no.readm[data[,prov.ind]%in%c(prov.no.readm)] <- 1
# message(paste(length(prov.no.readm),"out of",length(prov.list),
# "remaining providers with no readmission within 30 days."))
prov.all.readm <- # providers with all readmissions within 30 days
prov.list[sapply(split(1-data[data$included==1,Y.ind],factor(data[data$included==1,prov.ind])),sum)==0]
data$all.readm <- 0
data$all.readm[data[,prov.ind]%in%c(prov.all.readm)] <- 1
# message(paste(length(prov.all.readm),"out of",length(prov.list),
# "remaining providers with all readmissions within 30 days."))
# message(paste0("After screening, ", round(sum(data[data$included==1,Y.ind])/length(data[data$included==1,Y.ind])*100,2),
# "% of all discharges were readmitted within 30 days."))
return(data)
# data: a data frame sorted by provider IDs with additional variables 'included', 'no.readm', 'all.readm'
# and missing values imputed
}
|
/cachematrix.R | no_license | Culligan/ProgrammingAssignment2 | R | false | false | 2,002 | r | ||
context("plotT")
library(visualTest)
library(ggplot2)
data(iris)
# save plots as png image
png("tests/testthat/test1.png")
plotT(iris,"Sepal.Length","Sepal.Width")
dev.off()
png("tests/testthat/test2.png")
plotT(iris[-c(1:50),],"Sepal.Length","Sepal.Width")
dev.off()
# get numeric print of graphics
getFingerprint(file = "tests/testthat/test1.png")
getFingerprint(file = "tests/testthat/test2.png")
test_that("#5 - Test similarité des graphics ",{
expect_true(isSimilar(file="tests/testthat/test1.png", # graphic 1
fingerprint = getFingerprint(file = "tests/testthat/test2.png"), # Fingerprint du graphic 2
threshold =0.05) # degrée de similarité
)
})
| /tests/testthat/test-plotT.R | no_license | alimanager/test2git | R | false | false | 698 | r | context("plotT")
library(visualTest)
library(ggplot2)
data(iris)
# save plots as png image
png("tests/testthat/test1.png")
plotT(iris,"Sepal.Length","Sepal.Width")
dev.off()
png("tests/testthat/test2.png")
plotT(iris[-c(1:50),],"Sepal.Length","Sepal.Width")
dev.off()
# get numeric print of graphics
getFingerprint(file = "tests/testthat/test1.png")
getFingerprint(file = "tests/testthat/test2.png")
test_that("#5 - Test similarité des graphics ",{
expect_true(isSimilar(file="tests/testthat/test1.png", # graphic 1
fingerprint = getFingerprint(file = "tests/testthat/test2.png"), # Fingerprint du graphic 2
threshold =0.05) # degrée de similarité
)
})
|
## Main script to compute and plot PCA of various data preprocessing methods
generate_single_random_partition.cpp_var <- function(input_labels_cell_lines, input_labels_patient, training_amount) {
## Copied and adjusted from Bortezomib/Script/generate_random_partition.R function generate_random_partition.cpp_var
stopifnot(input_labels_patient < training_amount)
temp.cell_lines <- 1:length(input_labels_cell_lines)
temp.patients <- length(input_labels_cell_lines) + 1:length(input_labels_patient)
input_combined_labels <- c(input_labels_cell_lines, input_labels_patient)
temp.patients_in_training <- sample(temp.patients, training_amount)
temp.training_index.single <- c(temp.cell_lines, temp.patients_in_training)
temp.test_index <- setdiff(temp.patients, temp.patients_in_training)
while ((length(table(input_combined_labels[temp.training_index.single])) != 2) || (length(table(input_combined_labels[temp.test_index])) != 2)) {
temp.patients_in_training <- sample(temp.patients, training_amount)
temp.training_index.single <- c(temp.cell_lines, temp.patients_in_training)
temp.test_index <- setdiff(temp.patients, temp.patients_in_training)
}
# flags to denote: cell lines in training; patients in training; patients in test
cell.line.name = "GDSC "
if (length(input_labels_cell_lines) == 38) { # hack to change name in the legened in case of Epirubicin
cell.line.name = "GRAY "
}
if (length(input_labels_cell_lines) == 489) { # hack to change name in the legened in case of Erlotinib CCLE
cell.line.name = "CCLE "
}
cpp_flags <- rep(cell.line.name, length(input_combined_labels))
cpp_flags[temp.patients_in_training] <- "Patients 70% " # a hack to make this be before the "patients 30%"
cpp_flags[temp.test_index] <- "Patients 30%"
cpp_source <- rep("gdsc", length(input_combined_labels))
cpp_source[temp.patients] <- "patient"
stopifnot(length(temp.test_index) > 0)
stopifnot(length(temp.training_index.single) > 0)
stopifnot(length(intersect(temp.test_index, temp.training_index.single)) == 0)
stopifnot(temp.test_index %in% temp.patients)
cpp.partition <- list(
test_index = temp.test_index
, training_index = temp.training_index.single
, cpp_flags = cpp_flags
, cpp_source = cpp_source
)
return(cpp.partition)
}
compute_preprocessing <- function(data, label, sampleinfo, n.sv, preprocessCLsva = 0, baselinePlot = c('AUC', 'IC50', 'Slope')){
## Split to training set and patient-only test set
labels_cell_lines <- label$AUC
cl.len <- length(label$AUC)
labels_patient <- label$patient
training_amount <- round(length(labels_patient) * 0.7) #30% test set
cpp.partition <- generate_single_random_partition.cpp_var(labels_cell_lines, labels_patient, training_amount)
#print(length(cpp.partition$test_index))
#print(length(cpp.partition$training_index))
print("preprocessing cell lines only")
data.raw <- list()
labels.combined <- list()
## Pool AUC, IC50, Slope data and labels together, preprocess cell lines with SVA first
if (preprocessCLsva != 0) {
cl_AUC.sva <- sva_combine(batch = sampleinfo$tissue.type[label$AUC_ind],
label = label$AUC, input_data = scale(data$cl_AUC), n.sv=preprocessCLsva)
temp.data <- comGENE(scale(cl_AUC.sva), scale(data$patient))
} else {
temp.data <- comGENE(scale(data$cl_AUC), scale(data$patient))
}
data.raw[[1]] <- rbind(temp.data[[1]], temp.data[[2]])
labels.combined[[1]] <- c(label$AUC, label$patient)
#IC50
if (preprocessCLsva != 0) {
cl_IC50.sva <- sva_combine(batch = sampleinfo$tissue.type[label$IC50_ind],
label = label$IC50, input_data = scale(data$cl_IC50), n.sv=preprocessCLsva)
temp.data <- comGENE(scale(cl_IC50.sva), scale(data$patient))
} else {
temp.data <- comGENE(scale(data$cl_IC50), scale(data$patient))
}
data.raw[[2]] <- rbind(temp.data[[1]], temp.data[[2]])
labels.combined[[2]] <- c(label$IC50, label$patient)
#Slope
if (preprocessCLsva != 0) {
cl_slope.sva <- sva_combine(batch = sampleinfo$tissue.type[label$slope_ind],
label = label$slope, input_data = scale(data$cl_slope), n.sv=preprocessCLsva)
temp.data <- comGENE(scale(cl_slope.sva), scale(data$patient))
} else {
temp.data <- comGENE(scale(data$cl_slope), scale(data$patient))
}
data.raw[[3]] <- rbind(temp.data[[1]], temp.data[[2]])
labels.combined[[3]] <- c(label$slope, label$patient)
pID <- 1
data.all <- list()
plabel.all <- list()
ptitle.all <- list()
## Store raw data as is
if (baselinePlot == 'AUC'){
temp.data <- comGENE(scale(data$cl_AUC), scale(data$patient))
} else if (baselinePlot == 'IC50'){
temp.data <- comGENE(scale(data$cl_IC50), scale(data$patient))
} else if (baselinePlot == 'slope'){
temp.data <- comGENE(scale(data$cl_slope), scale(data$patient))
}
temp.data.raw <- rbind(temp.data[[1]], temp.data[[2]])
temp.label.combined <- c(label$slope, label$patient)
## Compensate for different number of cell lines with AUC/IC50/Slope labels
temp.ddiff <- length(labels.combined[[1]]) - length(temp.label.combined)
print(paste("adjusting", temp.ddiff))
temp.plot_label <- cpp.partition$cpp_flags[(temp.ddiff+1) : length(cpp.partition$cpp_flags)]
data.all[[pID]] <- temp.data.raw
plabel.all[[pID]] <- temp.plot_label
ptitle.all[[pID]] <- paste(baselinePlot, "labels before cell lines vs patients homogenization")
pID <- pID + 1
print("processing CL + patients")
for(outcomeID in 1:3) {
## Get data and labels
temp.data.raw <- data.raw[[outcomeID]]
temp.labels.combined <- labels.combined[[outcomeID]]
# print(paste("len", length(temp.data.raw), length(temp.labels.combined)))
## Compensate for different number of cell lines with AUC/IC50/Slope labels
temp.ddiff <- length(labels.combined[[1]]) - length(labels.combined[[outcomeID]])
print(paste("adjusting", temp.ddiff))
temp.plot_label <- cpp.partition$cpp_flags[(temp.ddiff+1) : length(cpp.partition$cpp_flags)]
temp.cpp_source <- cpp.partition$cpp_source[(temp.ddiff+1) : length(cpp.partition$cpp_source)]
# print(paste("len2", length(temp.plot_label), length(temp.cpp_source)))
# print(paste("len22", length(cpp.partition$cpp_flags), length(cpp.partition$cpp_source)))
temp.train_index <- cpp.partition$training_index[cpp.partition$training_index <= cl.len - temp.ddiff]
temp.train_index <- c(temp.train_index, cpp.partition$training_index[cpp.partition$training_index > cl.len] - temp.ddiff)
temp.test_index <- cpp.partition$test_index - temp.ddiff
# print(paste("len3", length(temp.train_index), length(temp.test_index)))
## Store Combat processed data
temp.data.ComBat <- ComBat_combine(batch = temp.cpp_source,
label = temp.labels.combined,
input_data = temp.data.raw)
data.all[[pID]] <- temp.data.ComBat
plabel.all[[pID]] <- temp.plot_label
ptitle.all[[pID]] <- paste(c('AUC', 'IC50', 'Slope')[outcomeID], "labels after ComBat homogenization of entire data set")
pID <- pID + 1
## Store SVA processed data
temp.data.sva <- sva_combine(batch = temp.cpp_source,
label = temp.labels.combined,
input_data = temp.data.raw,
n.sv = n.sv)
data.all[[pID]] <- temp.data.sva
plabel.all[[pID]] <- temp.plot_label
ptitle.all[[pID]] <- paste(c('AUC', 'IC50', 'Slope')[outcomeID], "labels after SVA homogenization of entire data set")
pID <- pID + 1
## Store frozen SVA processed data
temp.data.fsva <- fsva_combine(batch = temp.cpp_source,
label = temp.labels.combined,
input_data = temp.data.raw,
training_ind = temp.train_index,
test_ind = temp.test_index,
n.sv = n.sv)
#num_sv_method = "leek"
data.all[[pID]] <- temp.data.fsva
plabel.all[[pID]] <- temp.plot_label
ptitle.all[[pID]] <- paste(c('AUC', 'IC50', 'Slope')[outcomeID], "labels after frozen SVA homogenization")
pID <- pID + 1
}
return(list(data.all, plabel.all, ptitle.all))
}
format_PCAplot <- function (plt, plot_label, pOrder) {
# The color-blind friendly palette with grey
# cbPalette <- c("#B3B3B3", "#DE9900", "#48A6DB", "#00996F", "#F0E442", "#0072B2", "#D55E00", "#CC79A7")
cbPalette <- c("#B3B3B3", "#0D5DE0", "#E6374F")
plot_label <<- plot_label
plt <- plt + theme(legend.direction = 'horizontal',
legend.position = 'top', plot.margin = unit(c(5.1,7,4.5,3.5)/2, "lines"),
text = element_text(size=15), axis.title.x=element_text(vjust=-1.5))
plt <- plt + guides(colour = guide_legend(override.aes = list(size=2.5, linetype=0, shape = c(16, 17, 15))))
plt <- plt + geom_point(aes(shape = factor(plot_label), colour = factor(plot_label)), show.legend = FALSE)
# plt <- plt + ggtitle(LETTERS[pOrder]) + theme(plot.title=element_text(hjust=-0.12, size = rel(1.75), face='bold'))
plt <- plt + scale_colour_manual(name = 'Dataset: ', values=cbPalette)
return(eval(ggplotGrob(plt)))
}
#### Plot PCA of all given data
plot_processed_data_all <- function(data.all, plabel.all, ptitle.all, name="drugX"){
library(ggplot2)
library(grid)
library(RColorBrewer)
require(gtable)
require(gridExtra)
print("running PCA of the all data for plotting")
lplots <- list() # list to keep all plots in
for(pID in 1:length(data.all)) { #length(data.all)
## Plot PCA of the data as is
p1 <- show_pca(input_data = data.all[[pID]], label = plabel.all[[pID]], pca_line_plot = FALSE, print = FALSE, useColorBlindScheme = TRUE)
p1 <- p1 + ggtitle(ptitle.all[[pID]]) + theme(plot.title=element_text(hjust=0.5, size = rel(1.15)))
g1 <- format_PCAplot(p1, plabel.all[[pID]], pID)
g2 <- arrangeGrob(g1, top = textGrob(LETTERS[pID], x = unit(0.05, "npc"), y = unit(0.0, "npc"),
just = c("left", "top"),
gp = gpar(col="black", fontsize=22, fontface="bold")))
lplots <- c(lplots, list(g2))
}
## Extract Grobs
# g1 <- ggplotGrob(p1)
blank <- grid.rect(gp=gpar(col="white"))
row1 <- list(blank, lplots[[1]], blank)
gs <- lplots[2:length(lplots)]
gs <- c(row1, gs)
print("plotting")
pdf(paste0(name, "_all.pdf"), width = 20, height = 25)#, onefile=FALSE)
#grid.arrange(blank, g1, blank, g2, g3, g4, nrow=2, ncol=3)
grid.arrange(grobs=gs, nrow=4, ncol=3)
dev.off()
}
###################### MAIN #######################
args <- commandArgs(TRUE)
ENV <- args[1]
stopifnot(ENV %in% c('dp', 'cb'))
DRUG2RUN <- args[2]
stopifnot(DRUG2RUN %in% c('bor', 'doc', 'epir', 'erl-gdsc', 'erl-ccle'))
if (ENV == 'dp'){
rootdir <- "~/Dropbox/CP2P"
setwd(rootdir)
source("Common/preparing_data_helper.R")
source("Common/comGENE.R")
rdata_prefix_bor <- "../Bortezomib/WS/"
rdata_prefix_doc <- "../Docetaxel/WS/"
rdata_prefix_epir <- "../Epirubicin/WS/"
rdata_prefix_erl <- "../Erlotinib/WS/"
}
if (ENV == 'cb'){
rootdir <- "/dupa-filer/laci/CP2P/"
setwd(rootdir)
source("SVA_plots/preparing_data_helper.R")
source("SVA_plots/comGENE.R")
rdata_prefix_bor <- ""
rdata_prefix_doc <- ""
rdata_prefix_epir <- ""
rdata_prefix_erl <- ""
}
#### Bortezomib
if (DRUG2RUN == 'bor'){
load(paste0(rdata_prefix_bor, "bortezomib_data.RData")); bortezomib$patient <- bortezomib$patient.combat
bortezomib$cl_IC50 <- bortezomib$gdsc_IC50
bortezomib$cl_AUC <- bortezomib$gdsc_AUC
bortezomib$cl_slope <- bortezomib$gdsc_slope
bor.processed.data <- compute_preprocessing(bortezomib, bortezomib.labels, sampleinfo.gdsc, n.sv = 2, preprocessCLsva = 3, baselinePlot = 'Slope')
save(bor.processed.data, file = "bor.processed.data.RData")
plot_processed_data_all(bor.processed.data[[1]], bor.processed.data[[2]], bor.processed.data[[3]], name="bortezomib_2sva")
}
#### Docetaxel
if (DRUG2RUN == 'doc'){
load(paste0(rdata_prefix_doc, "docetaxel_data.RData"))
docetaxel$cl_IC50 <- docetaxel$gdsc_IC50
docetaxel$cl_AUC <- docetaxel$gdsc_AUC
docetaxel$cl_slope <- docetaxel$gdsc_slope
doc.processed.data <- compute_preprocessing(docetaxel, docetaxel.labels, sampleinfo.gdsc, n.sv = 2, preprocessCLsva = 0, baselinePlot = 'Slope')
save(doc.processed.data, file = "doc.processed.data.RData")
plot_processed_data_all(doc.processed.data[[1]], doc.processed.data[[2]], doc.processed.data[[3]], name="docetaxel_2sva")
}
#### Epirubicin
if (DRUG2RUN == 'epir'){
load(paste0(rdata_prefix_epir, "epirubicin_data.RData"))
epirubicin$cl_IC50 <- epirubicin$gray_IC50
epirubicin$cl_AUC <- epirubicin$gray_AUC
epirubicin$cl_slope <- epirubicin$gray_slope
epir.processed.data <- compute_preprocessing(epirubicin, epirubicin.labels, sampleinfo.gray, n.sv = 3, preprocessCLsva = 0, baselinePlot = 'Slope')
save(epir.processed.data, file = "epir.processed.data.RData")
# load("epir.processed.data.RData")
plot_processed_data_all(epir.processed.data[[1]], epir.processed.data[[2]], epir.processed.data[[3]], name="epirubicin_3sva")
}
#### Erlotinib
if (DRUG2RUN == 'erl-gdsc'){
load(paste0(rdata_prefix_erl, "erlotinib_homogenized_data_gdsc.RData"))
erlotinib$cl_IC50 <- erlotinib$gdsc_IC50
erlotinib$cl_AUC <- erlotinib$gdsc_AUC
erlotinib$cl_slope <- erlotinib$gdsc_slope
colnames(erlotinib$cl_AUC) <- colnames(erlotinib$cl_IC50) # fix gene names
erl.processed.data <- compute_preprocessing(erlotinib, erlotinib.labels, sampleinfo.gdsc, n.sv = 2, preprocessCLsva = 0, baselinePlot = 'Slope')
save(erl.processed.data, file = "erl.gdsc.processed.data.RData")
# load("erl.gdsc.processed.data.RData")
plot_processed_data_all(erl.processed.data[[1]], erl.processed.data[[2]], erl.processed.data[[3]], name="erlotinibGDSC_2sva")
}
if (DRUG2RUN == 'erl-ccle'){
load(paste0(rdata_prefix_erl, "erlotinib_homogenized_data_ccle.RData"))
erlotinib$cl_IC50 <- erlotinib$ccle_IC50
erlotinib$cl_AUC <- erlotinib$ccle_AUC
erlotinib$cl_slope <- erlotinib$ccle_slope
colnames(erlotinib$cl_AUC) <- colnames(erlotinib$cl_IC50) # fix gene names
erl.processed.data <- compute_preprocessing(erlotinib, erlotinib.labels, sampleinfo.ccle, n.sv = 2, preprocessCLsva = 0, baselinePlot = 'Slope')
save(erl.processed.data, file = "erl.ccle.processed.data.RData")
# load("erl.ccle.processed.data.RData")
plot_processed_data_all(erl.processed.data[[1]], erl.processed.data[[2]], erl.processed.data[[3]], name="erlotinibCCLE_2sva")
}
| /SVA_plots/data_processing_plots.R | no_license | chengzhao41/CP2P | R | false | false | 14,816 | r | ## Main script to compute and plot PCA of various data preprocessing methods
generate_single_random_partition.cpp_var <- function(input_labels_cell_lines, input_labels_patient, training_amount) {
## Copied and adjusted from Bortezomib/Script/generate_random_partition.R function generate_random_partition.cpp_var
stopifnot(input_labels_patient < training_amount)
temp.cell_lines <- 1:length(input_labels_cell_lines)
temp.patients <- length(input_labels_cell_lines) + 1:length(input_labels_patient)
input_combined_labels <- c(input_labels_cell_lines, input_labels_patient)
temp.patients_in_training <- sample(temp.patients, training_amount)
temp.training_index.single <- c(temp.cell_lines, temp.patients_in_training)
temp.test_index <- setdiff(temp.patients, temp.patients_in_training)
while ((length(table(input_combined_labels[temp.training_index.single])) != 2) || (length(table(input_combined_labels[temp.test_index])) != 2)) {
temp.patients_in_training <- sample(temp.patients, training_amount)
temp.training_index.single <- c(temp.cell_lines, temp.patients_in_training)
temp.test_index <- setdiff(temp.patients, temp.patients_in_training)
}
# flags to denote: cell lines in training; patients in training; patients in test
cell.line.name = "GDSC "
if (length(input_labels_cell_lines) == 38) { # hack to change name in the legened in case of Epirubicin
cell.line.name = "GRAY "
}
if (length(input_labels_cell_lines) == 489) { # hack to change name in the legened in case of Erlotinib CCLE
cell.line.name = "CCLE "
}
cpp_flags <- rep(cell.line.name, length(input_combined_labels))
cpp_flags[temp.patients_in_training] <- "Patients 70% " # a hack to make this be before the "patients 30%"
cpp_flags[temp.test_index] <- "Patients 30%"
cpp_source <- rep("gdsc", length(input_combined_labels))
cpp_source[temp.patients] <- "patient"
stopifnot(length(temp.test_index) > 0)
stopifnot(length(temp.training_index.single) > 0)
stopifnot(length(intersect(temp.test_index, temp.training_index.single)) == 0)
stopifnot(temp.test_index %in% temp.patients)
cpp.partition <- list(
test_index = temp.test_index
, training_index = temp.training_index.single
, cpp_flags = cpp_flags
, cpp_source = cpp_source
)
return(cpp.partition)
}
compute_preprocessing <- function(data, label, sampleinfo, n.sv, preprocessCLsva = 0, baselinePlot = c('AUC', 'IC50', 'Slope')){
## Split to training set and patient-only test set
labels_cell_lines <- label$AUC
cl.len <- length(label$AUC)
labels_patient <- label$patient
training_amount <- round(length(labels_patient) * 0.7) #30% test set
cpp.partition <- generate_single_random_partition.cpp_var(labels_cell_lines, labels_patient, training_amount)
#print(length(cpp.partition$test_index))
#print(length(cpp.partition$training_index))
print("preprocessing cell lines only")
data.raw <- list()
labels.combined <- list()
## Pool AUC, IC50, Slope data and labels together, preprocess cell lines with SVA first
if (preprocessCLsva != 0) {
cl_AUC.sva <- sva_combine(batch = sampleinfo$tissue.type[label$AUC_ind],
label = label$AUC, input_data = scale(data$cl_AUC), n.sv=preprocessCLsva)
temp.data <- comGENE(scale(cl_AUC.sva), scale(data$patient))
} else {
temp.data <- comGENE(scale(data$cl_AUC), scale(data$patient))
}
data.raw[[1]] <- rbind(temp.data[[1]], temp.data[[2]])
labels.combined[[1]] <- c(label$AUC, label$patient)
#IC50
if (preprocessCLsva != 0) {
cl_IC50.sva <- sva_combine(batch = sampleinfo$tissue.type[label$IC50_ind],
label = label$IC50, input_data = scale(data$cl_IC50), n.sv=preprocessCLsva)
temp.data <- comGENE(scale(cl_IC50.sva), scale(data$patient))
} else {
temp.data <- comGENE(scale(data$cl_IC50), scale(data$patient))
}
data.raw[[2]] <- rbind(temp.data[[1]], temp.data[[2]])
labels.combined[[2]] <- c(label$IC50, label$patient)
#Slope
if (preprocessCLsva != 0) {
cl_slope.sva <- sva_combine(batch = sampleinfo$tissue.type[label$slope_ind],
label = label$slope, input_data = scale(data$cl_slope), n.sv=preprocessCLsva)
temp.data <- comGENE(scale(cl_slope.sva), scale(data$patient))
} else {
temp.data <- comGENE(scale(data$cl_slope), scale(data$patient))
}
data.raw[[3]] <- rbind(temp.data[[1]], temp.data[[2]])
labels.combined[[3]] <- c(label$slope, label$patient)
pID <- 1
data.all <- list()
plabel.all <- list()
ptitle.all <- list()
## Store raw data as is
if (baselinePlot == 'AUC'){
temp.data <- comGENE(scale(data$cl_AUC), scale(data$patient))
} else if (baselinePlot == 'IC50'){
temp.data <- comGENE(scale(data$cl_IC50), scale(data$patient))
} else if (baselinePlot == 'slope'){
temp.data <- comGENE(scale(data$cl_slope), scale(data$patient))
}
temp.data.raw <- rbind(temp.data[[1]], temp.data[[2]])
temp.label.combined <- c(label$slope, label$patient)
## Compensate for different number of cell lines with AUC/IC50/Slope labels
temp.ddiff <- length(labels.combined[[1]]) - length(temp.label.combined)
print(paste("adjusting", temp.ddiff))
temp.plot_label <- cpp.partition$cpp_flags[(temp.ddiff+1) : length(cpp.partition$cpp_flags)]
data.all[[pID]] <- temp.data.raw
plabel.all[[pID]] <- temp.plot_label
ptitle.all[[pID]] <- paste(baselinePlot, "labels before cell lines vs patients homogenization")
pID <- pID + 1
print("processing CL + patients")
for(outcomeID in 1:3) {
## Get data and labels
temp.data.raw <- data.raw[[outcomeID]]
temp.labels.combined <- labels.combined[[outcomeID]]
# print(paste("len", length(temp.data.raw), length(temp.labels.combined)))
## Compensate for different number of cell lines with AUC/IC50/Slope labels
temp.ddiff <- length(labels.combined[[1]]) - length(labels.combined[[outcomeID]])
print(paste("adjusting", temp.ddiff))
temp.plot_label <- cpp.partition$cpp_flags[(temp.ddiff+1) : length(cpp.partition$cpp_flags)]
temp.cpp_source <- cpp.partition$cpp_source[(temp.ddiff+1) : length(cpp.partition$cpp_source)]
# print(paste("len2", length(temp.plot_label), length(temp.cpp_source)))
# print(paste("len22", length(cpp.partition$cpp_flags), length(cpp.partition$cpp_source)))
temp.train_index <- cpp.partition$training_index[cpp.partition$training_index <= cl.len - temp.ddiff]
temp.train_index <- c(temp.train_index, cpp.partition$training_index[cpp.partition$training_index > cl.len] - temp.ddiff)
temp.test_index <- cpp.partition$test_index - temp.ddiff
# print(paste("len3", length(temp.train_index), length(temp.test_index)))
## Store Combat processed data
temp.data.ComBat <- ComBat_combine(batch = temp.cpp_source,
label = temp.labels.combined,
input_data = temp.data.raw)
data.all[[pID]] <- temp.data.ComBat
plabel.all[[pID]] <- temp.plot_label
ptitle.all[[pID]] <- paste(c('AUC', 'IC50', 'Slope')[outcomeID], "labels after ComBat homogenization of entire data set")
pID <- pID + 1
## Store SVA processed data
temp.data.sva <- sva_combine(batch = temp.cpp_source,
label = temp.labels.combined,
input_data = temp.data.raw,
n.sv = n.sv)
data.all[[pID]] <- temp.data.sva
plabel.all[[pID]] <- temp.plot_label
ptitle.all[[pID]] <- paste(c('AUC', 'IC50', 'Slope')[outcomeID], "labels after SVA homogenization of entire data set")
pID <- pID + 1
## Store frozen SVA processed data
temp.data.fsva <- fsva_combine(batch = temp.cpp_source,
label = temp.labels.combined,
input_data = temp.data.raw,
training_ind = temp.train_index,
test_ind = temp.test_index,
n.sv = n.sv)
#num_sv_method = "leek"
data.all[[pID]] <- temp.data.fsva
plabel.all[[pID]] <- temp.plot_label
ptitle.all[[pID]] <- paste(c('AUC', 'IC50', 'Slope')[outcomeID], "labels after frozen SVA homogenization")
pID <- pID + 1
}
return(list(data.all, plabel.all, ptitle.all))
}
format_PCAplot <- function (plt, plot_label, pOrder) {
# The color-blind friendly palette with grey
# cbPalette <- c("#B3B3B3", "#DE9900", "#48A6DB", "#00996F", "#F0E442", "#0072B2", "#D55E00", "#CC79A7")
cbPalette <- c("#B3B3B3", "#0D5DE0", "#E6374F")
plot_label <<- plot_label
plt <- plt + theme(legend.direction = 'horizontal',
legend.position = 'top', plot.margin = unit(c(5.1,7,4.5,3.5)/2, "lines"),
text = element_text(size=15), axis.title.x=element_text(vjust=-1.5))
plt <- plt + guides(colour = guide_legend(override.aes = list(size=2.5, linetype=0, shape = c(16, 17, 15))))
plt <- plt + geom_point(aes(shape = factor(plot_label), colour = factor(plot_label)), show.legend = FALSE)
# plt <- plt + ggtitle(LETTERS[pOrder]) + theme(plot.title=element_text(hjust=-0.12, size = rel(1.75), face='bold'))
plt <- plt + scale_colour_manual(name = 'Dataset: ', values=cbPalette)
return(eval(ggplotGrob(plt)))
}
#### Plot PCA of all given data
plot_processed_data_all <- function(data.all, plabel.all, ptitle.all, name="drugX"){
library(ggplot2)
library(grid)
library(RColorBrewer)
require(gtable)
require(gridExtra)
print("running PCA of the all data for plotting")
lplots <- list() # list to keep all plots in
for(pID in 1:length(data.all)) { #length(data.all)
## Plot PCA of the data as is
p1 <- show_pca(input_data = data.all[[pID]], label = plabel.all[[pID]], pca_line_plot = FALSE, print = FALSE, useColorBlindScheme = TRUE)
p1 <- p1 + ggtitle(ptitle.all[[pID]]) + theme(plot.title=element_text(hjust=0.5, size = rel(1.15)))
g1 <- format_PCAplot(p1, plabel.all[[pID]], pID)
g2 <- arrangeGrob(g1, top = textGrob(LETTERS[pID], x = unit(0.05, "npc"), y = unit(0.0, "npc"),
just = c("left", "top"),
gp = gpar(col="black", fontsize=22, fontface="bold")))
lplots <- c(lplots, list(g2))
}
## Extract Grobs
# g1 <- ggplotGrob(p1)
blank <- grid.rect(gp=gpar(col="white"))
row1 <- list(blank, lplots[[1]], blank)
gs <- lplots[2:length(lplots)]
gs <- c(row1, gs)
print("plotting")
pdf(paste0(name, "_all.pdf"), width = 20, height = 25)#, onefile=FALSE)
#grid.arrange(blank, g1, blank, g2, g3, g4, nrow=2, ncol=3)
grid.arrange(grobs=gs, nrow=4, ncol=3)
dev.off()
}
###################### MAIN #######################
args <- commandArgs(TRUE)
ENV <- args[1]
stopifnot(ENV %in% c('dp', 'cb'))
DRUG2RUN <- args[2]
stopifnot(DRUG2RUN %in% c('bor', 'doc', 'epir', 'erl-gdsc', 'erl-ccle'))
if (ENV == 'dp'){
rootdir <- "~/Dropbox/CP2P"
setwd(rootdir)
source("Common/preparing_data_helper.R")
source("Common/comGENE.R")
rdata_prefix_bor <- "../Bortezomib/WS/"
rdata_prefix_doc <- "../Docetaxel/WS/"
rdata_prefix_epir <- "../Epirubicin/WS/"
rdata_prefix_erl <- "../Erlotinib/WS/"
}
if (ENV == 'cb'){
rootdir <- "/dupa-filer/laci/CP2P/"
setwd(rootdir)
source("SVA_plots/preparing_data_helper.R")
source("SVA_plots/comGENE.R")
rdata_prefix_bor <- ""
rdata_prefix_doc <- ""
rdata_prefix_epir <- ""
rdata_prefix_erl <- ""
}
#### Bortezomib
if (DRUG2RUN == 'bor'){
load(paste0(rdata_prefix_bor, "bortezomib_data.RData")); bortezomib$patient <- bortezomib$patient.combat
bortezomib$cl_IC50 <- bortezomib$gdsc_IC50
bortezomib$cl_AUC <- bortezomib$gdsc_AUC
bortezomib$cl_slope <- bortezomib$gdsc_slope
bor.processed.data <- compute_preprocessing(bortezomib, bortezomib.labels, sampleinfo.gdsc, n.sv = 2, preprocessCLsva = 3, baselinePlot = 'Slope')
save(bor.processed.data, file = "bor.processed.data.RData")
plot_processed_data_all(bor.processed.data[[1]], bor.processed.data[[2]], bor.processed.data[[3]], name="bortezomib_2sva")
}
#### Docetaxel
if (DRUG2RUN == 'doc'){
load(paste0(rdata_prefix_doc, "docetaxel_data.RData"))
docetaxel$cl_IC50 <- docetaxel$gdsc_IC50
docetaxel$cl_AUC <- docetaxel$gdsc_AUC
docetaxel$cl_slope <- docetaxel$gdsc_slope
doc.processed.data <- compute_preprocessing(docetaxel, docetaxel.labels, sampleinfo.gdsc, n.sv = 2, preprocessCLsva = 0, baselinePlot = 'Slope')
save(doc.processed.data, file = "doc.processed.data.RData")
plot_processed_data_all(doc.processed.data[[1]], doc.processed.data[[2]], doc.processed.data[[3]], name="docetaxel_2sva")
}
#### Epirubicin
if (DRUG2RUN == 'epir'){
load(paste0(rdata_prefix_epir, "epirubicin_data.RData"))
epirubicin$cl_IC50 <- epirubicin$gray_IC50
epirubicin$cl_AUC <- epirubicin$gray_AUC
epirubicin$cl_slope <- epirubicin$gray_slope
epir.processed.data <- compute_preprocessing(epirubicin, epirubicin.labels, sampleinfo.gray, n.sv = 3, preprocessCLsva = 0, baselinePlot = 'Slope')
save(epir.processed.data, file = "epir.processed.data.RData")
# load("epir.processed.data.RData")
plot_processed_data_all(epir.processed.data[[1]], epir.processed.data[[2]], epir.processed.data[[3]], name="epirubicin_3sva")
}
#### Erlotinib
if (DRUG2RUN == 'erl-gdsc'){
load(paste0(rdata_prefix_erl, "erlotinib_homogenized_data_gdsc.RData"))
erlotinib$cl_IC50 <- erlotinib$gdsc_IC50
erlotinib$cl_AUC <- erlotinib$gdsc_AUC
erlotinib$cl_slope <- erlotinib$gdsc_slope
colnames(erlotinib$cl_AUC) <- colnames(erlotinib$cl_IC50) # fix gene names
erl.processed.data <- compute_preprocessing(erlotinib, erlotinib.labels, sampleinfo.gdsc, n.sv = 2, preprocessCLsva = 0, baselinePlot = 'Slope')
save(erl.processed.data, file = "erl.gdsc.processed.data.RData")
# load("erl.gdsc.processed.data.RData")
plot_processed_data_all(erl.processed.data[[1]], erl.processed.data[[2]], erl.processed.data[[3]], name="erlotinibGDSC_2sva")
}
if (DRUG2RUN == 'erl-ccle'){
load(paste0(rdata_prefix_erl, "erlotinib_homogenized_data_ccle.RData"))
erlotinib$cl_IC50 <- erlotinib$ccle_IC50
erlotinib$cl_AUC <- erlotinib$ccle_AUC
erlotinib$cl_slope <- erlotinib$ccle_slope
colnames(erlotinib$cl_AUC) <- colnames(erlotinib$cl_IC50) # fix gene names
erl.processed.data <- compute_preprocessing(erlotinib, erlotinib.labels, sampleinfo.ccle, n.sv = 2, preprocessCLsva = 0, baselinePlot = 'Slope')
save(erl.processed.data, file = "erl.ccle.processed.data.RData")
# load("erl.ccle.processed.data.RData")
plot_processed_data_all(erl.processed.data[[1]], erl.processed.data[[2]], erl.processed.data[[3]], name="erlotinibCCLE_2sva")
}
|
library(car)
library(nlme)
# ----------------------------------------------------------------------------------------------------------------#
# R is rooted in object-oriented programming #
# You create 'objects' that for all intents and purposes are your datasets or elements of your data. #
# It takes the form of object <- what you want to put in your object. #
# The arrow assigns whatever you want to your object name. #
# You can also use an = to assign objects, but it's not recommended. People do it, though. #
# ----------------------------------------------------------------------------------------------------------------#
# My general approach to make code more consistent is to freely use carriage returns/enter between lines of code.
# I always assign my object on the top line, and then enter the commands below that line, like this:
# object <-
# what_i_want_in_my_object.
# -------------------- #
# QUESTION 1 BEGINNING #
# -------------------- #
# Read in the file.
base <-
read.csv(
# specify file in your local directory.
file = "./cilia-r-help/aggregate-by-state-with-rurality-treatment-flags.csv", # put the directory to your file here. note that R does not like backslashes.
# base R converts strings to factors which isn't recommended.
stringsAsFactors = FALSE
)
# Examine the contents. head() looks at the first 10 observations.
head(base)
# Examine the contents. tail() looks at the last 10 observations.
tail(base)
# Remove the suppression records.
baseNoSuppression <-
base[base$suppression_used == "FALSE", ]
baseNoSuppression
# Aggregate your file.
baseAgg <-
# with tells R that you want to take an object you've already created and use it in the following calculation
with(
# this is your object that you want to conduct calculations on.
baseNoSuppression,
# The 'aggregate' function is one way of aggregating in R
aggregate(
# Since we're creating two summed up variables, we need to enclose these variables in a list. Lists can hold multiple elements.
list(
chipMedicaidEnroll_agg = chipMedicaidEnroll, # Here we're creating aggregate variables based on the old variables.
total_prescriptions_agg = total_prescriptions # Here we're creating aggregate variables based on the old variables.
),
# now we want to split these summations by groups of year, half-year, and group. Specify a list again.
by = list(
year = year,
half_year = half_year,
group = group
),
# Then call on how we want to aggregate - we want to sum the chipMedicaidEnroll and total_prescription variables.
FUN = sum
)
)
# Create the rx_rate variable.
baseAgg$rx_rate_per_hundred <-
(baseAgg$total_prescriptions_agg / baseAgg$chipMedicaidEnroll_agg) * 100
# View the file
baseAgg
# Ordering dataset is necessary at this point.
baseAgg <-
baseAgg[order(-baseAgg$group, baseAgg$year), ]
# We need to add our flags: "halfYear' time', 'level', 'trend', 'grouptime', 'grouplevel', and 'grouptrend'.
# First, we'll remove those records for 2014,1
# Notice the exclamation point before the statement - it means to remove those records.
baseAggFlags <-
baseAgg
# baseAggFlags <-
# baseAgg[!(baseAgg$year == "2014" & baseAgg$half_year == "1"), ]
# Create yearHalfYear flag
baseAggFlags$yearHalfYear <-
# Paste0 concatenates or pieces together elements without spaces. Here we want '2011,1'.
paste0(
baseAggFlags$year, # first element we want is year
",", # then our comma
baseAggFlags$half_year # then our half year.
)
# See it in the output.
baseAggFlags
# Create the time flag.
baseAggFlags$time <-
# 'ave' is a function that allows you to do sequence operations
ave(
baseAggFlags$year, #First group variable, our year
baseAggFlags$group, # Second group variable, our group
FUN = seq_along # seq_along() then creates a sequence pattern based on these groupings.
)
# Create the level flag.
baseAggFlags$level <-
ifelse( #ifelse is a pretty useful tool in R
baseAggFlags$year >= 2014, # This says, if baseAggFlags$year is greater than or equal to 2014,
1, # Then set it to 1.
0 # otherwise set it to 0.
)
# Create trend flag. This isn't a very programmatic way to do it, but other usual functions struggled.
baseAggFlags$trend <-
ifelse(
baseAggFlags$level == 1,
baseAggFlags$time - 6, # Here I'm just subtracting from another sequence to get the numbers that were needed.
0
)
# Create the group time variable.
baseAggFlags$grouptime <-
ifelse(
baseAggFlags$group == 1,
baseAggFlags$time,
0
)
# Create group level variable.
baseAggFlags$grouplevel <-
ifelse(
baseAggFlags$group == 1,
baseAggFlags$level,
0
)
# Create group trend variable.
baseAggFlags$grouptrend <-
ifelse(
baseAggFlags$group == 1,
baseAggFlags$trend,
0
)
# Put treatment group into their own object.
baseAggFlagsTreat <-
baseAggFlags[baseAggFlags$group == 1, ]
# Put control group into their own object.
baseAggFlagsControl <-
baseAggFlags[baseAggFlags$group == 0, ]
# Make plotting area have space for 1 row and 2 columns.
par(mfrow=c(1, 2))
# Make the plot of the treatment group.
plot(baseAggFlagsTreat$time,
baseAggFlagsTreat$rx_rate_per_hundred,
ylab="COPD Rx Rate: per 100",
ylim=c(0,5),
xlab="Year HalfYear",
type="l",
col="red",
xaxt="n")
abline(v=6.5,lty=2)
points(
baseAggFlagsTreat$time,
baseAggFlagsTreat$rx_rate_per_hundred,
col = "red"
)
# Give it a title.
title("Treatment Group")
# Make the plot of the control group.
plot(baseAggFlagsControl$time,
baseAggFlagsControl$rx_rate_per_hundred,
ylab="COPD Rx Rate: per 100",
ylim=c(0,5),
xlab="Year HalfYear",
type="l",
col="blue",
xaxt="n")
abline(v=6.5,lty=2)
axis(1, at=1:12, labels=baseAggFlagsControl$yearHalfYear, )
points(
baseAggFlagsControl$time,
baseAggFlagsControl$rx_rate_per_hundred,
col = "blue"
)
# Give it a title.
title("Control Group")
# Putting them in the same plot and saving them out.
png("./cilia-r-help/one-plot.png")
plot(baseAggFlagsTreat$time,
baseAggFlagsTreat$rx_rate_per_hundred,
ylab="COPD Rx Rate: per 100",
ylim=c(0,5),
xlab="Year HalfYear",
type="l",
col="red",
xaxt="n")
points(
baseAggFlagsTreat$time,
baseAggFlagsTreat$rx_rate_per_hundred,
col = "red"
)
par(new = TRUE)
plot(baseAggFlagsControl$time,
baseAggFlagsControl$rx_rate_per_hundred,
ylab="COPD Rx Rate: per 100",
ylim=c(0,5),
xlab="Year HalfYear",
type="l",
col="blue",
xaxt="n")
points(
baseAggFlagsControl$time,
baseAggFlagsControl$rx_rate_per_hundred,
col = "blue"
)
dev.off()
# End of plotting and file is saved out.
model <-
lm(
formula = rx_rate_per_hundred ~ time + group + grouptime + level + trend + grouplevel + grouptrend,
data = baseAggFlags
)
summary(model)
# -------------------- #
# QUESTION 1 END #
# -------------------- #
# -------------------- #
# QUESTION 2 BEGINNING #
# -------------------- #
## Remove those with 2014,1.
## You have to re-run all your computations, here. There are more efficient ways to do this, but I think it's not worth delving into it now.
baseAggFlagsRm20141 <-
baseAggFlags[baseAggFlags$yearHalfYear != "2014,1", ]
baseAggFlagsRm20141$yearHalfYear <-
# Paste0 concatenates or pieces together elements without spaces. Here we want '2011,1'.
paste0(
baseAggFlagsRm20141$year, # first element we want is year
",", # then our comma
baseAggFlagsRm20141$half_year # then our half year.
)
# Create the time flag.
baseAggFlagsRm20141$time <-
# 'ave' is a function that allows you to do sequence operations
ave(
baseAggFlagsRm20141$year, #First group variable, our year
baseAggFlagsRm20141$group, # Second group variable, our group
FUN = seq_along # seq_along() then creates a sequence pattern based on these groupings.
)
# Create the level flag.
baseAggFlagsRm20141$level <-
ifelse( #ifelse is a pretty useful tool in R
baseAggFlagsRm20141$year >= 2014, # This says, if baseAggFlags$year is greater than or equal to 2014,
1, # Then set it to 1.
0 # otherwise set it to 0.
)
# Create trend flag. This isn't a very programmatic way to do it, but other usual functions struggled.
baseAggFlagsRm20141$trend <-
ifelse(
baseAggFlagsRm20141$level == 1,
baseAggFlagsRm20141$time - 6, # Here I'm just subtracting from another sequence to get the numbers that were needed.
0
)
# Create the group time variable.
baseAggFlagsRm20141$grouptime <-
ifelse(
baseAggFlagsRm20141$group == 1,
baseAggFlagsRm20141$time,
0
)
# Create group level variable.
baseAggFlagsRm20141$grouplevel <-
ifelse(
baseAggFlagsRm20141$group == 1,
baseAggFlagsRm20141$level,
0
)
# Create group trend variable.
baseAggFlagsRm20141$grouptrend <-
ifelse(
baseAggFlagsRm20141$group == 1,
baseAggFlagsRm20141$trend,
0
)
# Put treatment group into their own object.
baseAggFlagsTreatRm20141 <-
baseAggFlagsRm20141[baseAggFlagsRm20141$group == 1, ]
# Put control group into their own object.
baseAggFlagsControlRm20141 <-
baseAggFlagsRm20141[baseAggFlagsRm20141$group == 0, ]
# Make plotting area have space for 1 row and 2 columns.
par(mfrow=c(1, 2))
# Make the plot of the treatment group.
plot(baseAggFlagsTreatRm20141$time,
baseAggFlagsTreatRm20141$rx_rate_per_hundred,
ylab="COPD Rx Rate: per 100",
ylim=c(0,5),
xlab="Year HalfYear",
type="l",
col="red",
xaxt="n")
points(
baseAggFlagsTreatRm20141$time,
baseAggFlagsTreatRm20141$rx_rate_per_hundred,
col = "red"
)
# Give it a title.
title("Treatment Group")
# Make the plot of the control group.
plot(baseAggFlagsControlRm20141$time,
baseAggFlagsControlRm20141$rx_rate_per_hundred,
ylab="COPD Rx Rate: per 100",
ylim=c(0,5),
xlab="Year HalfYear",
type="l",
col="blue",
xaxt="n")
points(
baseAggFlagsControlRm20141$time,
baseAggFlagsControlRm20141$rx_rate_per_hundred,
col = "blue"
)
# Give it a title.
title("Control Group")
# Putting them in the same plot and saving them out.
png("./cilia-r-help/one-plot.png")
plot(baseAggFlagsTreatRm20141$time,
baseAggFlagsTreatRm20141$rx_rate_per_hundred,
ylab="COPD Rx Rate: per 100",
ylim=c(0,5),
xlab="Year HalfYear",
type="l",
col="red",
xaxt="n")
points(
baseAggFlagsTreatRm20141$time,
baseAggFlagsTreatRm20141$rx_rate_per_hundred,
col = "red"
)
par(new = TRUE)
plot(baseAggFlagsControlRm20141$time,
baseAggFlagsControlRm20141$rx_rate_per_hundred,
ylab="COPD Rx Rate: per 100",
ylim=c(0,5),
xlab="Year HalfYear",
type="l",
col="blue",
xaxt="n")
points(
baseAggFlagsControlRm20141$time,
baseAggFlagsControlRm20141$rx_rate_per_hundred,
col = "blue"
)
dev.off()
# End of plotting and file is saved out.
model_rm20141 <-
lm(
formula = rx_rate_per_hundred ~ time + group + grouptime + level + trend + grouplevel + grouptrend,
data = baseAggFlagsRm20141
)
summary(model_rm20141)
| /cilia-r-help/01_import-and-clean.R | no_license | michaelqmaguire/sdud-copd-expansion | R | false | false | 11,490 | r | library(car)
library(nlme)
# ----------------------------------------------------------------------------------------------------------------#
# R is rooted in object-oriented programming #
# You create 'objects' that for all intents and purposes are your datasets or elements of your data. #
# It takes the form of object <- what you want to put in your object. #
# The arrow assigns whatever you want to your object name. #
# You can also use an = to assign objects, but it's not recommended. People do it, though. #
# ----------------------------------------------------------------------------------------------------------------#
# My general approach to make code more consistent is to freely use carriage returns/enter between lines of code.
# I always assign my object on the top line, and then enter the commands below that line, like this:
# object <-
# what_i_want_in_my_object.
# -------------------- #
# QUESTION 1 BEGINNING #
# -------------------- #
# Read in the file.
base <-
read.csv(
# specify file in your local directory.
file = "./cilia-r-help/aggregate-by-state-with-rurality-treatment-flags.csv", # put the directory to your file here. note that R does not like backslashes.
# base R converts strings to factors which isn't recommended.
stringsAsFactors = FALSE
)
# Examine the contents. head() looks at the first 10 observations.
head(base)
# Examine the contents. tail() looks at the last 10 observations.
tail(base)
# Remove the suppression records.
baseNoSuppression <-
base[base$suppression_used == "FALSE", ]
baseNoSuppression
# Aggregate your file.
baseAgg <-
# with tells R that you want to take an object you've already created and use it in the following calculation
with(
# this is your object that you want to conduct calculations on.
baseNoSuppression,
# The 'aggregate' function is one way of aggregating in R
aggregate(
# Since we're creating two summed up variables, we need to enclose these variables in a list. Lists can hold multiple elements.
list(
chipMedicaidEnroll_agg = chipMedicaidEnroll, # Here we're creating aggregate variables based on the old variables.
total_prescriptions_agg = total_prescriptions # Here we're creating aggregate variables based on the old variables.
),
# now we want to split these summations by groups of year, half-year, and group. Specify a list again.
by = list(
year = year,
half_year = half_year,
group = group
),
# Then call on how we want to aggregate - we want to sum the chipMedicaidEnroll and total_prescription variables.
FUN = sum
)
)
# Create the rx_rate variable.
baseAgg$rx_rate_per_hundred <-
(baseAgg$total_prescriptions_agg / baseAgg$chipMedicaidEnroll_agg) * 100
# View the file
baseAgg
# Ordering dataset is necessary at this point.
baseAgg <-
baseAgg[order(-baseAgg$group, baseAgg$year), ]
# We need to add our flags: "halfYear' time', 'level', 'trend', 'grouptime', 'grouplevel', and 'grouptrend'.
# First, we'll remove those records for 2014,1
# Notice the exclamation point before the statement - it means to remove those records.
baseAggFlags <-
baseAgg
# baseAggFlags <-
# baseAgg[!(baseAgg$year == "2014" & baseAgg$half_year == "1"), ]
# Create yearHalfYear flag
baseAggFlags$yearHalfYear <-
# Paste0 concatenates or pieces together elements without spaces. Here we want '2011,1'.
paste0(
baseAggFlags$year, # first element we want is year
",", # then our comma
baseAggFlags$half_year # then our half year.
)
# See it in the output.
baseAggFlags
# Create the time flag.
baseAggFlags$time <-
# 'ave' is a function that allows you to do sequence operations
ave(
baseAggFlags$year, #First group variable, our year
baseAggFlags$group, # Second group variable, our group
FUN = seq_along # seq_along() then creates a sequence pattern based on these groupings.
)
# Create the level flag.
baseAggFlags$level <-
ifelse( #ifelse is a pretty useful tool in R
baseAggFlags$year >= 2014, # This says, if baseAggFlags$year is greater than or equal to 2014,
1, # Then set it to 1.
0 # otherwise set it to 0.
)
# Create trend flag. This isn't a very programmatic way to do it, but other usual functions struggled.
baseAggFlags$trend <-
ifelse(
baseAggFlags$level == 1,
baseAggFlags$time - 6, # Here I'm just subtracting from another sequence to get the numbers that were needed.
0
)
# Create the group time variable.
baseAggFlags$grouptime <-
ifelse(
baseAggFlags$group == 1,
baseAggFlags$time,
0
)
# Create group level variable.
baseAggFlags$grouplevel <-
ifelse(
baseAggFlags$group == 1,
baseAggFlags$level,
0
)
# Create group trend variable.
baseAggFlags$grouptrend <-
ifelse(
baseAggFlags$group == 1,
baseAggFlags$trend,
0
)
# Put treatment group into their own object.
baseAggFlagsTreat <-
baseAggFlags[baseAggFlags$group == 1, ]
# Put control group into their own object.
baseAggFlagsControl <-
baseAggFlags[baseAggFlags$group == 0, ]
# Make plotting area have space for 1 row and 2 columns.
par(mfrow=c(1, 2))
# Make the plot of the treatment group.
plot(baseAggFlagsTreat$time,
baseAggFlagsTreat$rx_rate_per_hundred,
ylab="COPD Rx Rate: per 100",
ylim=c(0,5),
xlab="Year HalfYear",
type="l",
col="red",
xaxt="n")
abline(v=6.5,lty=2)
points(
baseAggFlagsTreat$time,
baseAggFlagsTreat$rx_rate_per_hundred,
col = "red"
)
# Give it a title.
title("Treatment Group")
# Make the plot of the control group.
plot(baseAggFlagsControl$time,
baseAggFlagsControl$rx_rate_per_hundred,
ylab="COPD Rx Rate: per 100",
ylim=c(0,5),
xlab="Year HalfYear",
type="l",
col="blue",
xaxt="n")
abline(v=6.5,lty=2)
axis(1, at=1:12, labels=baseAggFlagsControl$yearHalfYear, )
points(
baseAggFlagsControl$time,
baseAggFlagsControl$rx_rate_per_hundred,
col = "blue"
)
# Give it a title.
title("Control Group")
# Putting them in the same plot and saving them out.
png("./cilia-r-help/one-plot.png")
plot(baseAggFlagsTreat$time,
baseAggFlagsTreat$rx_rate_per_hundred,
ylab="COPD Rx Rate: per 100",
ylim=c(0,5),
xlab="Year HalfYear",
type="l",
col="red",
xaxt="n")
points(
baseAggFlagsTreat$time,
baseAggFlagsTreat$rx_rate_per_hundred,
col = "red"
)
par(new = TRUE)
plot(baseAggFlagsControl$time,
baseAggFlagsControl$rx_rate_per_hundred,
ylab="COPD Rx Rate: per 100",
ylim=c(0,5),
xlab="Year HalfYear",
type="l",
col="blue",
xaxt="n")
points(
baseAggFlagsControl$time,
baseAggFlagsControl$rx_rate_per_hundred,
col = "blue"
)
dev.off()
# End of plotting and file is saved out.
model <-
lm(
formula = rx_rate_per_hundred ~ time + group + grouptime + level + trend + grouplevel + grouptrend,
data = baseAggFlags
)
summary(model)
# -------------------- #
# QUESTION 1 END #
# -------------------- #
# -------------------- #
# QUESTION 2 BEGINNING #
# -------------------- #
## Remove those with 2014,1.
## You have to re-run all your computations, here. There are more efficient ways to do this, but I think it's not worth delving into it now.
baseAggFlagsRm20141 <-
baseAggFlags[baseAggFlags$yearHalfYear != "2014,1", ]
baseAggFlagsRm20141$yearHalfYear <-
# Paste0 concatenates or pieces together elements without spaces. Here we want '2011,1'.
paste0(
baseAggFlagsRm20141$year, # first element we want is year
",", # then our comma
baseAggFlagsRm20141$half_year # then our half year.
)
# Create the time flag.
baseAggFlagsRm20141$time <-
# 'ave' is a function that allows you to do sequence operations
ave(
baseAggFlagsRm20141$year, #First group variable, our year
baseAggFlagsRm20141$group, # Second group variable, our group
FUN = seq_along # seq_along() then creates a sequence pattern based on these groupings.
)
# Create the level flag.
baseAggFlagsRm20141$level <-
ifelse( #ifelse is a pretty useful tool in R
baseAggFlagsRm20141$year >= 2014, # This says, if baseAggFlags$year is greater than or equal to 2014,
1, # Then set it to 1.
0 # otherwise set it to 0.
)
# Create trend flag. This isn't a very programmatic way to do it, but other usual functions struggled.
baseAggFlagsRm20141$trend <-
ifelse(
baseAggFlagsRm20141$level == 1,
baseAggFlagsRm20141$time - 6, # Here I'm just subtracting from another sequence to get the numbers that were needed.
0
)
# Create the group time variable.
baseAggFlagsRm20141$grouptime <-
ifelse(
baseAggFlagsRm20141$group == 1,
baseAggFlagsRm20141$time,
0
)
# Create group level variable.
baseAggFlagsRm20141$grouplevel <-
ifelse(
baseAggFlagsRm20141$group == 1,
baseAggFlagsRm20141$level,
0
)
# Create group trend variable.
baseAggFlagsRm20141$grouptrend <-
ifelse(
baseAggFlagsRm20141$group == 1,
baseAggFlagsRm20141$trend,
0
)
# Put treatment group into their own object.
baseAggFlagsTreatRm20141 <-
baseAggFlagsRm20141[baseAggFlagsRm20141$group == 1, ]
# Put control group into their own object.
baseAggFlagsControlRm20141 <-
baseAggFlagsRm20141[baseAggFlagsRm20141$group == 0, ]
# Make plotting area have space for 1 row and 2 columns.
par(mfrow=c(1, 2))
# Make the plot of the treatment group.
plot(baseAggFlagsTreatRm20141$time,
baseAggFlagsTreatRm20141$rx_rate_per_hundred,
ylab="COPD Rx Rate: per 100",
ylim=c(0,5),
xlab="Year HalfYear",
type="l",
col="red",
xaxt="n")
points(
baseAggFlagsTreatRm20141$time,
baseAggFlagsTreatRm20141$rx_rate_per_hundred,
col = "red"
)
# Give it a title.
title("Treatment Group")
# Make the plot of the control group.
plot(baseAggFlagsControlRm20141$time,
baseAggFlagsControlRm20141$rx_rate_per_hundred,
ylab="COPD Rx Rate: per 100",
ylim=c(0,5),
xlab="Year HalfYear",
type="l",
col="blue",
xaxt="n")
points(
baseAggFlagsControlRm20141$time,
baseAggFlagsControlRm20141$rx_rate_per_hundred,
col = "blue"
)
# Give it a title.
title("Control Group")
# Putting them in the same plot and saving them out.
png("./cilia-r-help/one-plot.png")
plot(baseAggFlagsTreatRm20141$time,
baseAggFlagsTreatRm20141$rx_rate_per_hundred,
ylab="COPD Rx Rate: per 100",
ylim=c(0,5),
xlab="Year HalfYear",
type="l",
col="red",
xaxt="n")
points(
baseAggFlagsTreatRm20141$time,
baseAggFlagsTreatRm20141$rx_rate_per_hundred,
col = "red"
)
par(new = TRUE)
plot(baseAggFlagsControlRm20141$time,
baseAggFlagsControlRm20141$rx_rate_per_hundred,
ylab="COPD Rx Rate: per 100",
ylim=c(0,5),
xlab="Year HalfYear",
type="l",
col="blue",
xaxt="n")
points(
baseAggFlagsControlRm20141$time,
baseAggFlagsControlRm20141$rx_rate_per_hundred,
col = "blue"
)
dev.off()
# End of plotting and file is saved out.
model_rm20141 <-
lm(
formula = rx_rate_per_hundred ~ time + group + grouptime + level + trend + grouplevel + grouptrend,
data = baseAggFlagsRm20141
)
summary(model_rm20141)
|
# Question 5
# How have emissions from motor vehicle sources changed from 1999-2008 in Baltimore City?
# read the dataset
emissions <- readRDS("summarySCC_PM25.rds")
# read scc dateset
scc <- readRDS("Source_Classification_Code.rds")
baltimoreMotorEmissions <- emissions[emissions$type == 'ON-ROAD' & emissions$fips == '24510', ]
baltimoreMotorEmissionsByYear <- aggregate(Emissions ~ year, data = baltimoreMotorEmissions, FUN = sum)
png(filename='plot5.png', width=480, height=480, units='px')
with(baltimoreMotorEmissionsByYear, {
plot(year, Emissions, type = 'b',
xlab="Year",
ylab='PM2.5 Emissions (tons)',
main='PM2.5 Emissions from motor vehicle sources in Baltimore City')
})
dev.off()
| /plot5.R | no_license | rmy0005/exploratory-data-analysis-course-project-2 | R | false | false | 767 | r | # Question 5
# How have emissions from motor vehicle sources changed from 1999-2008 in Baltimore City?
# read the dataset
emissions <- readRDS("summarySCC_PM25.rds")
# read scc dateset
scc <- readRDS("Source_Classification_Code.rds")
baltimoreMotorEmissions <- emissions[emissions$type == 'ON-ROAD' & emissions$fips == '24510', ]
baltimoreMotorEmissionsByYear <- aggregate(Emissions ~ year, data = baltimoreMotorEmissions, FUN = sum)
png(filename='plot5.png', width=480, height=480, units='px')
with(baltimoreMotorEmissionsByYear, {
plot(year, Emissions, type = 'b',
xlab="Year",
ylab='PM2.5 Emissions (tons)',
main='PM2.5 Emissions from motor vehicle sources in Baltimore City')
})
dev.off()
|
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
# Using evolutionary theory to predict microbes’ effect on host health
# Camille Simonet & Luke McNally
#
# SCRIPT: Statistical analyses
# last edit: 21/08/2021
#
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
#local_project_dir="path/to/repo"
#local_project_dir="/Users/s1687811/Documents/PhD/Research/MicrobiomeHamiltonianMedicine/MicrobiomeHamiltonianMedicine_repo"
# SETUP ----
# Sourcing packages ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
setwd(local_project_dir)
source('./scripts/sourced_packages.R')
library(ape)
library(MCMCglmm)
library(vegan)
library(lme4)
library(lmerTest)
library(irr)
library(effects)
library(jtools)
library(ROCR)
library(ggrepel)
# Load environment preped by script 4.1_data_prep.R
load('./output/stats_runs/data_preps_23062021.RData')
# Data overview
table(dat.rescaled$caseControl)
nrow(dat.rescaled)
# MICROBIOME ANALYSIS ----
# Binomial regressions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# We put disease as random effect allowing both intercepts and slope to vary per disease
# Let the model estimate ful;l covariance matrix
m.glmm.disease <- glmer(caseControl ~ 1+ NR + NRSPO + (1 + NR + NRSPO|disease_type),
family = binomial(link = "logit"),
data = dat.rescaled,
control = glmerControl(optimizer = "bobyqa", optCtrl = list(maxfun=5e5)))
summary(m.glmm.disease)
# Not enough cohort per disease to distinguish the two effect, so partly confounded
# re-run analysis with cohort as random effect
# find similar result
m.glmm.cohort <- glmer(caseControl ~ 1+ NR + NRSPO + (1 + NR + NRSPO|cohortNew),
family = binomial(link = "logit"),
data = dat.rescaled,
control = glmerControl(optimizer = "bobyqa", optCtrl = list(maxfun=2e5)))
summary(m.glmm.cohort)
# Test random slopes (LRT) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Re-run model with the random slopes
# use LRT tests to verify if indeed allowing random slopes give a better fit
m.glmm.disease.fixedSlopes <- glmer(caseControl ~ 1+ NR + NRSPO + (1 |disease_type),
family = binomial(link = "logit"),
data = dat.rescaled,
control = glmerControl(optimizer = "bobyqa", optCtrl = list(maxfun=5e5)))
summary(m.glmm.disease.fixedSlopes) # same results for NR, NRSPO comes out significant too
m.glmm.cohort.fixedSlopes <- glmer(caseControl ~ 1+ NR + NRSPO + (1 |cohortNew),
family = binomial(link = "logit"),
data = dat.rescaled,
control = glmerControl(optimizer = "bobyqa", optCtrl = list(maxfun=5e5)))
summary(m.glmm.cohort.fixedSlopes) # same results
anova(m.glmm.disease.fixedSlopes, m.glmm.disease) # model with random slopes gives sig. better fit
anova(m.glmm.cohort.fixedSlopes, m.glmm.cohort) # model with random slopes gives sig. better fit
# Check with MCMC ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Verify with MCMCglmm if I get the same result for the choosen model (per disease, with random slopes)
prior.0<-list(R=list(V=1, fix=1),
G=list(G1=list(V=diag(3), nu=3, alpha.mu=c(0,0,0), alpha.V=diag(3)*1000))) # variance in fixed effect across diseases
mcmc.disease<- MCMCglmm(caseControl ~ 1+ NR+NRSPO,
random = ~us(1+NR+NRSPO):disease_type,
data = dat.rescaled,
family = 'threshold',
prior = prior.0,
nitt = 150000, burnin = 50000, thin = 100)
summary(mcmc.disease) # MCMCglmm gives similar results
# MAKE SUPPLEMENTARY TABLES ----
source('./scripts/5.1_suppMat_make_modelSummaries.R')
# PLOT MICROBIOME MODEL ----
# Boxplots NR/NRSPO ----
mygrey<- colorRampPalette(c('white', 'lightgrey'))(10)[4]
theme.bp<-
theme_bw()+
theme(axis.title = element_text(size = 6),
axis.text = element_text(size = 5, colour = 'black'),
panel.grid = element_blank(),
#legend.position = 'top', #c(0.9, 0.1),
legend.key.size = unit(0.3, "cm"),
legend.text = element_text(size = 3),
legend.title = element_blank(),
panel.border = element_blank(),
axis.line = element_line(size = 0.4))
dat.rescaled$cohortNewPlot<- factor(dat.rescaled$cohortNew,
levels = (c('YeZ2018_BD', 'LiJ2017_HYPER', 'Zhang2015_RA','JieZ2017_ACVD', 'Karlsson2012_ACVD',
'QinN2014_LC', 'QinJ2012_T2D', 'Karlsson2013_T2D&IGT',
'FengQ2015_CRC', 'YuJ2015_CRC', 'ZellerG2014_CRC', 'ThomasAM2018_CRC', 'VogtmannE2016_CRC',
'He2017_IBD', 'NielsenH2014_IBD', 'iHMP_IBD', 'Costea2017_MetS', 'LeChatelierE2013_OBE', 'Liu2017_OBE')))
dat.rescaled$cohortNewPlot2<- do.call('rbind', strsplit(dat.rescaled$cohortNew, '_'))[,1]
dat.rescaled$cohortNewPlot2<- factor(dat.rescaled$cohortNewPlot2,
levels = (c('YeZ2018', 'LiJ2017', 'Zhang2015','JieZ2017', 'Karlsson2012',
'QinN2014', 'QinJ2012', 'Karlsson2013',
'FengQ2015', 'YuJ2015', 'ZellerG2014', 'ThomasAM2018', 'VogtmannE2016',
'He2017', 'NielsenH2014', 'iHMP', 'Costea2017', 'LeChatelierE2013', 'Liu2017')))
# Add samples sizes under cohort names on y-axis ticks
nsizes<- dat.rescaled %>%
group_by(cohortNewPlot2, caseControl) %>%
summarise(n = n()) %>%
as.data.frame() %>%
ungroup() %>%
spread(key = caseControl, value = n) %>%
as.data.frame() %>%
rename(case = `0`,
control = `1`)
dat.rescaled<- left_join(dat.rescaled, nsizes, by = 'cohortNewPlot2')
dat.rescaled<- dat.rescaled %>%
mutate(cohortNewPlot3 = paste0(cohortNewPlot2, '\n(c:', case, ', h:', control, ')'))
dat.rescaled$cohortNewPlot3<- factor(dat.rescaled$cohortNewPlot3,
levels = rev(c("Liu2017\n(c:104, h:101)",
"LeChatelierE2013\n(c:130, h:79)",
"Costea2017\n(c:60, h:26)",
"iHMP\n(c:89, h:26)",
"NielsenH2014\n(c:60, h:41)",
"He2017\n(c:47, h:41)",
"VogtmannE2016\n(c:24, h:19)",
"ThomasAM2018\n(c:84, h:45)",
"ZellerG2014\n(c:111, h:45)",
"YuJ2015\n(c:74, h:53)",
"FengQ2015\n(c:93, h:43)",
"Karlsson2013\n(c:98, h:33)",
"QinJ2012\n(c:182, h:182)",
"QinN2014\n(c:118, h:111)",
"Karlsson2012\n(c:12, h:10)",
"JieZ2017\n(c:202, h:159)" ,
"Zhang2015\n(c:88, h:89)",
"LiJ2017\n(c:155, h:41)",
"YeZ2018\n(c:19, h:40)")))
p.NR.boxes<- ggplot(dat.rescaled, aes(x = cohortNewPlot3, y = NR, fill = as.factor(caseControl)))+
ylab('Gut average relatedness')+xlab('Cohort')+
scale_y_continuous(limits = c(0.35, 1), expand = c(0, 0))+
geom_boxplot(width = 0.5, outlier.size = 0.05, lwd = 0.2)+
#scale_fill_manual(values = c('lightgrey', 'white'))+
scale_fill_manual(values = c('firebrick', 'dodgerblue'))+
coord_flip()+
theme.bp+
theme(legend.position = 'none')
ymin.rect.NR = 0.35
ymax.rect.NR = 1
text.pos = 0.38
p.NR<- p.NR.boxes +
annotate("rect", xmin = 17.5, xmax = 19.5, ymin = ymin.rect.NR, ymax = ymax.rect.NR,fill = mygrey)+
annotate("rect", xmin = 16.5, xmax = 17.5, ymin = ymin.rect.NR, ymax = ymax.rect.NR,fill = 'white')+
annotate("rect", xmin = 14.5, xmax = 16.5, ymin = ymin.rect.NR, ymax = ymax.rect.NR, fill = mygrey)+
annotate("rect", xmin = 13.5, xmax = 14.5, ymin = ymin.rect.NR, ymax = ymax.rect.NR, fill = mygrey)+
annotate("rect", xmin = 8.5, xmax = 13.5, ymin = ymin.rect.NR, ymax = ymax.rect.NR, fill = 'white')+
annotate("rect", xmin = 7.5, xmax = 8.5, ymin = ymin.rect.NR, ymax = ymax.rect.NR, fill = mygrey)+
annotate("rect", xmin = 6.5, xmax = 7.5, ymin = ymin.rect.NR, ymax = ymax.rect.NR, fill = mygrey)+
annotate("rect", xmin = 5.5, xmax = 6.5, ymin = ymin.rect.NR, ymax = ymax.rect.NR, fill = 'white')+
annotate("rect", xmin = 3.5, xmax = 5.5, ymin = ymin.rect.NR, ymax = ymax.rect.NR, fill = mygrey)+
annotate("rect", xmin = 2.5, xmax = 3.5, ymin = ymin.rect.NR, ymax = ymax.rect.NR, fill = 'white')+
annotate("rect", xmin = 1.5, xmax = 2.5, ymin = ymin.rect.NR, ymax = ymax.rect.NR, fill = mygrey)+
annotate("rect", xmin = 0.5, xmax = 1.5, ymin = ymin.rect.NR, ymax = ymax.rect.NR, fill = 'white')+
geom_boxplot(width = 0.5, outlier.size = 0.05, lwd = 0.2)+
annotate('text', x = 18.5, y = text.pos, label = 'Obesity', angle = 90, size = 2)+
annotate('text', x = 17, y = text.pos, label = 'MetS', angle = 90, size = 2)+
#annotate('text', x = 15.5, y = text.pos, label = "CD", angle = 90, size = 2)+
#annotate('text', x = 14, y = text.pos, label = 'UC', angle = 90, size = 2)+
annotate('text', x = 15, y = text.pos, label = 'IBD', angle = 90, size = 2)+
annotate('text', x = 11, y = text.pos, label = 'Colorectal Cancer', angle = 90, size = 2)+
#annotate('text', x = 8, y = text.pos, label = 'IGT', angle = 90, size = 2)+
#annotate('text', x = 7, y = text.pos, label = 'T2D', angle = 90, size = 2)+
annotate('text', x = 7.5, y = text.pos, label = 'T2D & IGT', angle = 90, size = 2)+
annotate('text', x = 6, y = text.pos, label = 'LC', angle = 90, size = 2)+
annotate('text', x = 4.5, y = text.pos, label = 'ACVD', angle = 90, size = 2)+
annotate('text', x = 3, y = text.pos, label = 'RA', angle = 90, size = 2)+
annotate('text', x = 2, y = text.pos, label = 'HypT', angle = 90, size = 2)+
annotate('text', x = 1, y = text.pos, label = 'BD', angle = 90, size = 2)
p.NR
p.NRSPO.boxes<- ggplot(dat.rescaled, aes(x = cohortNewPlot3, y = NRSPO, fill = as.factor(caseControl)))+
xlab(' \ ')+ylab('Relatedness weighed mean\nsporulation score')+
scale_y_continuous(limits = c(0, 0.5), expand = c(0, 0))+
geom_boxplot(width = 0.5, outlier.size = 0.05, lwd = 0.2)+
#scale_fill_manual(values = c('lightgrey', 'white'))+
scale_fill_manual(values = c('firebrick', 'dodgerblue'))+
coord_flip()+
theme.bp+
theme(legend.position = 'none',
axis.text.y = element_blank(),
axis.line.y = element_blank(),
axis.ticks.y = element_blank())
ymin.rect.NRSPO = 0
ymax.rect.NRSPO = 0.5
p.NRSPO<- p.NRSPO.boxes +
annotate("rect", xmin = 17.5, xmax = 19.5, ymin = ymin.rect.NRSPO, ymax = ymax.rect.NRSPO, fill = mygrey)+
annotate("rect", xmin = 16.5, xmax = 17.5, ymin = ymin.rect.NRSPO, ymax = ymax.rect.NRSPO, fill = 'white')+
annotate("rect", xmin = 14.5, xmax = 16.5, ymin = ymin.rect.NRSPO, ymax = ymax.rect.NRSPO, fill = mygrey)+
annotate("rect", xmin = 13.5, xmax = 14.5, ymin = ymin.rect.NRSPO, ymax = ymax.rect.NRSPO, fill = mygrey)+
annotate("rect", xmin = 8.5, xmax = 13.5, ymin = ymin.rect.NRSPO, ymax = ymax.rect.NRSPO, fill = 'white')+
annotate("rect", xmin = 7.5, xmax = 8.5, ymin = ymin.rect.NRSPO, ymax = ymax.rect.NRSPO, fill = mygrey)+
annotate("rect", xmin = 6.5, xmax = 7.5, ymin = ymin.rect.NRSPO, ymax = ymax.rect.NRSPO, fill = mygrey)+
annotate("rect", xmin = 5.5, xmax = 6.5, ymin = ymin.rect.NRSPO, ymax = ymax.rect.NRSPO, fill = 'white')+
annotate("rect", xmin = 3.5, xmax = 5.5, ymin = ymin.rect.NRSPO, ymax = ymax.rect.NRSPO, fill = mygrey)+
annotate("rect", xmin = 2.5, xmax = 3.5, ymin = ymin.rect.NRSPO, ymax = ymax.rect.NRSPO, fill = 'white')+
annotate("rect", xmin = 1.5, xmax = 2.5, ymin = ymin.rect.NRSPO, ymax = ymax.rect.NRSPO, fill = mygrey)+
annotate("rect", xmin = 0.5, xmax = 1.5, ymin = ymin.rect.NRSPO, ymax = ymax.rect.NRSPO, fill = 'white')+
geom_boxplot(width = 0.5, outlier.size = 0.05, lwd = 0.2)
# Effect plots ----
# *** To run this part need to run the models in script 4.2 ***
fm1 <- m.glmm.disease # store whatever model I want to use in fm1 variable and use this in code below
newdat <- expand.grid( # Make a new dataframe for predictions
NR=seq(0.38, 0.94, 0.01), # Make range of NR within range of observed values
NRSPO = mean(dat.rescaled$NRSPO), # condition on typical (i.e. mean) value of NRSPO
caseControl = NA
)
newdat$caseControl <- predict(fm1,newdat,re.form=NA) # Make predictions
plot(newdat$caseControl~ newdat$NR, type = 'l', ylim = c(-4, 1)) # Ok, what I get corresponds to what allEffect() wrapper gives
plot(allEffects(fm1), type = 'link')
# Ok now doing this manually (following Ben Bolkers tutorial on it) to customise plot
mm <- model.matrix(terms(fm1),newdat)
## or newdat$distance <- mm %*% fixef(fm1)
pvar1 <- diag(mm %*% tcrossprod(vcov(fm1),mm)) # Thus is to produce CI based on fixed-effects uncertainty ONLY
tvar1 <- pvar1+VarCorr(fm1)$disease_type[1]+VarCorr(fm1)$disease_type[5]+VarCorr(fm1)$disease_type[9] # This adds the variance of random effects. Adapted from Ben Bolker's code but here for more complex model. Because we let the model estimate variance in intercept, NR slope and NRSPO slope with disease_type, we must add those three sources of variance.
cmult <- 1.96 ## could use 1.96
newdat <- data.frame(
newdat
, plo = newdat$caseControl-cmult*sqrt(pvar1)
, phi = newdat$caseControl+cmult*sqrt(pvar1)
, tlo = newdat$caseControl-cmult*sqrt(tvar1)
, thi = newdat$caseControl+cmult*sqrt(tvar1)
)
#plot confidence
g0 <- ggplot(newdat, aes(x=NR, y=plogis(caseControl)))+geom_point()
g0 + geom_pointrange(aes(ymin = plogis(plo), ymax = plogis(phi)))+
labs(title="CI based on fixed-effects uncertainty ONLY")
#plot prediction
g0 + geom_pointrange(aes(ymin = plogis(tlo), ymax = plogis(thi)))+
labs(title="CI based on FE uncertainty + RE variance")
plot(allEffects(fm1), type = 'response') # ok, what I get manually looks similar to what allEffects() wrapper gives
funFormat<- function(x, digits){ifelse(x<0.01,
formatC(x, digit = digits, format = 'e'),
formatC(x, digit = digits, format = 'f'))}
out.fix.format<- summary(m.glmm.disease)[[10]] %>%
as.data.frame() %>%
add_rownames('Effect') %>%
as.data.frame() %>%
mutate_if(is.numeric, funs(funFormat(., 2)))
b1 = out.fix.format[2,2]
pvalb1 = out.fix.format[2,5]
p.predict.NR<- ggplot(newdat, aes(x=NR, y=plogis(caseControl)))+
#geom_segment(data = dat.rescaled, aes(x = NR, xend = NR, y = 0, yend = 0.02))+
geom_segment(data = dat.rescaled[dat.rescaled$caseControl == '0',], aes(x = NR, xend = NR, y = 0, yend = 0.02), alpha = .2, col = 'firebrick')+
geom_segment(data = dat.rescaled[dat.rescaled$caseControl == '1',], aes(x = NR, xend = NR, y = 0.02, yend = 0.04), alpha = .2, col = 'dodgerblue')+
geom_ribbon(aes(NR, ymin = plogis(plo), ymax = plogis(phi)), fill = 'lightgrey')+
geom_line()+
ylab('Probability of healthy')+xlab('Mean gut relatedness')+
theme_bw()+
theme(axis.title = element_text(size = 6),
axis.text = element_text(size = 5),
panel.grid = element_blank(),
#legend.position = 'top', #c(0.9, 0.1),
legend.key.size = unit(0.3, "cm"),
legend.text = element_text(size = 3),
legend.title = element_blank(),
panel.border = element_blank(),
axis.line = element_line(size = 0.3))+
annotate('text', x = 0.4, y = 0.75, label = paste0('slope = ', b1, ', pval = ', pvalb1, '***'), size = 1.8, hjust = 0)+
ylim(c(0,0.75))
p.predict.NR
# Let's do the same for NRSPO now
newdat.2 <- expand.grid( # Make a new dataframe for predictions
NRSPO=seq(0.08, 0.5, 0.01), # Make range of NRSPO within range of observed values
NR = mean(dat.rescaled$NR), # condition on typical (i.e. mean) value of NR
caseControl = NA
)
newdat.2$caseControl <- predict(fm1,newdat.2,re.form=NA) # Make predictions
plot(newdat.2$caseControl~ newdat.2$NRSPO, type = 'l', ylim = c(-2, 0.5)) # Ok, what I get corresponds to what allEffect() wrapper gives
plot(allEffects(fm1), type = 'link')
mm.2 <- model.matrix(terms(fm1),newdat.2)
## or newdat$distance <- mm %*% fixef(fm1)
pvar1.2 <- diag(mm.2 %*% tcrossprod(vcov(fm1),mm.2)) # Thus is to produce CI based on fixed-effects uncertainty ONLY
tvar1.2 <- pvar1.2+VarCorr(fm1)$disease_type[1]+VarCorr(fm1)$disease_type[5]+VarCorr(fm1)$disease_type[9] # This adds the variance of random effects. Adapted from Ben Bolker's code but here for more complex model. Because we let the model estimate variance in intercept, NR slope and NRSPO slope with disease_type, we must add those three sources of variance.
cmult <- 1.96 ## could use 1.96
newdat.2 <- data.frame(
newdat.2
, plo = newdat.2$caseControl-cmult*sqrt(pvar1.2)
, phi = newdat.2$caseControl+cmult*sqrt(pvar1.2)
, tlo = newdat.2$caseControl-cmult*sqrt(tvar1.2)
, thi = newdat.2$caseControl+cmult*sqrt(tvar1.2)
)
#plot confidence
g0 <- ggplot(newdat.2, aes(x=NRSPO, y=plogis(caseControl)))+geom_point()
g0 + geom_pointrange(aes(ymin = plogis(plo), ymax = plogis(phi)))+
labs(title="CI based on fixed-effects uncertainty ONLY")
#plot prediction
g0 + geom_pointrange(aes(ymin = plogis(tlo), ymax = plogis(thi)))+
labs(title="CI based on FE uncertainty + RE variance")
plot(allEffects(fm1), type = 'response') # ok, what I get manually looks similar to what allEffects() wrapper gives
out.fix.format<- summary(m.glmm.disease)[[10]] %>%
as.data.frame() %>%
add_rownames('Effect') %>%
as.data.frame()
b1 = round(out.fix.format[3,2],2)
pvalb1 = round(out.fix.format[3,5],2)
p.predict.NRSPO<- ggplot(newdat.2, aes(x=NRSPO, y=plogis(caseControl)))+
#geom_segment(data = dat.rescaled, aes(x = NRSPO, xend = NRSPO, y = 0.1, yend = 0.116), alpha = .2)+
geom_segment(data = dat.rescaled[dat.rescaled$caseControl == '0',], aes(x = NRSPO, xend = NRSPO, y = 0, yend = 0.02), alpha = .2, col = 'firebrick')+
geom_segment(data = dat.rescaled[dat.rescaled$caseControl == '1',], aes(x = NRSPO, xend = NRSPO, y = 0.02, yend = 0.04), alpha = .2, col = 'dodgerblue')+
geom_ribbon(aes(NRSPO, ymin = plogis(plo), ymax = plogis(phi)), fill = 'lightgrey')+
geom_line()+
ylab('Probability of healthy')+xlab('Relatedness weighed mean\nsporulation score')+
theme_bw()+
theme(axis.title = element_text(size = 6),
axis.text = element_text(size = 5),
panel.grid = element_blank(),
#legend.position = 'top', #c(0.9, 0.1),
legend.key.size = unit(0.3, "cm"),
legend.text = element_text(size = 3),
legend.title = element_blank(),
panel.border = element_blank(),
axis.line = element_line(size = 0.3))+
annotate('text', x = 0.1, y = 0.62, label = paste0('slope = ', b1, ', pval = ', pvalb1), size = 1.8, hjust = 0)
p.predict.NRSPO
# Assemble ----
library(patchwork)
#pdf('./output/figures/Figure2_microbiome.pdf', width = 16/2.55, height = 13/2.55)
#(p.NR | p.NRSPO | (p.all.NR|p.all.NRSPO)/p.predict.NR / p.predict.NRSPO) +
# plot_annotation(tag_levels = 'A') &
# theme(plot.tag = element_text(size = 7, face = 'bold'))
#dev.off()
pdf('./output/figures/Figure2_microbiome.pdf', width = 14/2.55, height = 11.5/2.55)
(p.NR | p.NRSPO | (p.predict.NR / p.predict.NRSPO/plot_spacer())) +
plot_annotation(tag_levels = 'A') &
theme(plot.tag = element_text(size = 7, face = 'bold'))
dev.off()
library(cowplot)
leg<- get_legend(
p.NR+
theme(legend.position = 'right',
legend.text = element_text(size = 7),
legend.key.size = unit(0.5, "cm"))+
scale_fill_manual(values = c('firebrick', 'dodgerblue'),
labels = c('case (sick)', 'control (healthy)'))
)
pdf('./output/figures/legend_microbiomePlot.pdf', width = 3/2.55, height = 1.8/2.55)
plot(leg)
dev.off()
# AUC (cvAUC package analysis) ----
library(pROC)
library(caret)
library(metRology)
# USING cvAUC PACKAGE, WITH FUNCTION ci.cvAUC() TO COMPUTE A CONFIDENCE INTERVAL ON THE AUC
# Package has a useful documentation page to understand exactly what they are doing:
# https://www.rdocumentation.org/packages/cvAUC/versions/1.1.0/topics/ci.cvAUC
# What they do is:
# 1) define the folds (as in: select the row ids to be used in each fold). Ideal is to stratify the folds by outcome, to keep balance of 1/0 cases in each fold
# 2) fit the model on all folds but one
# 3) using that model fit, predict values in the left-out fold, on response scale
# do for each fold in turn
# then in the ci.cvAUC() function:
# predictions is the vector of all predictions, on response scale (probability)
# label is the true observed value (on 1/0 scale)
# fold is the list of row ids for each fold
# Let's use their demo code wrappers. Works for any dataset as long as
# input dataset has a first 'Y' variables of 1/0 outcome
# other variables are those to use in the model
# so if want only 'NR', subset dataset to get only the Y and NR columns
# and of course everytime, subset to keep all or specific disease
# in the code wrapper below, utility functons to get the folds and train/test are defined within the code wrapper
# then the cross validated AUC is passed through ci.cvAUC() to get the mean AUC and confidence intervals
cvAUC_demoWrapper <- function(data, V=10){
.cvFolds <- function(Y, V){ #Create CV folds (stratify by outcome)
Y0 <- split(sample(which(Y==0)), rep(1:V, length=length(which(Y==0))))
Y1 <- split(sample(which(Y==1)), rep(1:V, length=length(which(Y==1))))
folds <- vector("list", length=V)
for (v in seq(V)) {folds[[v]] <- c(Y0[[v]], Y1[[v]])}
return(folds)
}
.doFit <- function(v, folds, data){ #Train/test glm for each fold
fit <- glm(Y~., data=data[-folds[[v]],], family=binomial)
pred <- predict(fit, newdata=data[folds[[v]],], type="response")
return(pred)
}
folds <- .cvFolds(Y=data$Y, V=V) #Create folds
predictions <- unlist(sapply(seq(V), .doFit, folds=folds, data=data)) #CV train/predict
predictions[unlist(folds)] <- predictions #Re-order pred values
# Get CV AUC and confidence interval
out <- ci.cvAUC(predictions=predictions, labels=data$Y, folds=folds, confidence=0.95)
return(out)
}
# data here must be dat.rescaled, which has the caseControl variable (0 = sick, 1 = healthy), and the disease_type variable which specific which disease the "cases" were
# in principle could modify the wrapper to select specific cohorts instead
# focal.predictor must be a vector of the predictors you want to use for the glm model fit
# focal.disease must be a vector of disease you want to subset the dataset for (it will select the cases and controls only from the studies focusing on those specific disease)
# V is number of folds to use for the k-fold cross validation, if set V = nrow(data), then that's a leave-one-out analysis
# Note: I'm setting set.seed(42) in the code wrapper, just before computing the folds
# that means that the output will be reproducible because that will reselect the same folds for a given dataset
# so when re-running the cvAUC (or running it with a different predictor), the folds are the same, so the AUC can be compared
# as in, the difference in AUC is NOT due to sampling, it's due to the different predictor
run.cvAUC_demoWrapper<- function(data, focal.predictor, focal.disease , V=10){
d.focal<- data[data$disease_type %in% focal.disease, c('caseControl', focal.predictor)] %>%
rename(Y = caseControl)
set.seed(42) # by setting the seed, the folds selection will be the same. MUST set it everytime running the AUCcv for a different predictor, so that the AUC computed are comparable, i.e. computed over the same data split
out<- cvAUC_demoWrapper(d.focal, V = V)
out.df<- data.frame(predictor = paste(focal.predictor, collapse = '_'),
disease = paste(focal.disease, collapse = '_'),
cvAUC = out$cvAUC,
se = out$se,
ci.low = out$ci[1],
ci.up = out$ci[2])
return(out.df)
}
# example
run.cvAUC_demoWrapper(dat.rescaled, c('NR', 'NRSPO'), 'MetS', V = 10)
# Ok, now, just have to run it for each of my four predictors (NR/NRSPO, or Shannon, invSimpson, Richness)
# And for each disease as well as all diseases together
# that's 44 runs
unique(dat.rescaled$disease_type) # 10 diseases
(10*4)+4
ls.diseases<- as.list(unique(dat.rescaled$disease_type))
ls.diseases[[11]]<- unique(dat.rescaled$disease_type)
ls.predictors<- as.list(c('NR', 'Shannon', 'invSimpson', 'Richness'))
#ls.predictors[[5]]<- c('NR', 'NRSPO')
ls.cvAUC.out<- list()
counter = 0
for(i in 1:length(ls.diseases)){
for(j in 1:length(ls.predictors)){
counter = counter + 1
run.out<- run.cvAUC_demoWrapper(dat.rescaled, ls.predictors[[j]], ls.diseases[[i]], V = 10)
print(counter)
ls.cvAUC.out[[counter]] = run.out
}
}
ls.cvAUC.out<- do.call('rbind', ls.cvAUC.out)
ls.cvAUC.out$disease[ls.cvAUC.out$disease == 'CRC_HYPER_IBD_ACVD_LC_OBE_T2D_IGC_RA_BD_MetS']<- 'All diseases'
#ls.cvAUC.out<- ls.cvAUC.out[ls.cvAUC.out$predictor != 'NR_NRSPO',]
ls.cvAUC.out$disease<- factor(ls.cvAUC.out$disease,
levels = rev(c('All diseases', 'OBE', 'MetS', 'IBD', 'CRC', 'T2D_IGC', 'LC', 'ACVD', 'RA', 'HYPER', 'BD')))
# Add samples sizes under disease names on y-axis ticks
nsizes.diseases<- dat.rescaled %>%
group_by(disease_type, caseControl) %>%
summarise(n = n()) %>%
as.data.frame() %>%
ungroup() %>%
spread(key = caseControl, value = n) %>%
as.data.frame() %>%
rename(case = `0`,
control = `1`) %>%
rename(disease = disease_type)
nsizes.diseases<- rbind(nsizes.diseases,
data.frame(disease = 'All diseases',
case = table(dat.rescaled$caseControl)[[1]],
control = table(dat.rescaled$caseControl)[[2]]))
ls.cvAUC.out2<- left_join(ls.cvAUC.out, nsizes.diseases, by = 'disease')
ls.cvAUC.out2<- ls.cvAUC.out2 %>%
mutate(diseasePlot2 = paste0(disease, '\n(c:', case, ', h:', control, ')'))
ls.cvAUC.out2$diseasePlot2[ls.cvAUC.out2$diseasePlot2 == 'T2D_IGC\n(c:280, h:215)']<- "T2D & IGT\n(c:280, h:215)"
unique(ls.cvAUC.out2$diseasePlot2)
ls.cvAUC.out2$diseasePlot2<- factor(ls.cvAUC.out2$diseasePlot2,
levels = rev(c("All diseases\n(c:1750, h:1184)",
"OBE\n(c:234, h:180)",
"MetS\n(c:60, h:26)",
"IBD\n(c:196, h:108)",
"CRC\n(c:386, h:205)",
"T2D & IGT\n(c:280, h:215)",
"LC\n(c:118, h:111)",
"ACVD\n(c:214, h:169)",
"RA\n(c:88, h:89)",
"HYPER\n(c:155, h:41)",
"BD\n(c:19, h:40)")))
# by definition, a 10-fold will split it in 10, meaning 90% of data goes to training and 10% goes to testing set
# So by knowing the sample size of the cohorts, the size of train/test sets is known
# redefining predictors as factor to have them in right orders on plot
ls.cvAUC.out2$predictor[ls.cvAUC.out2$predictor == 'NR']<- 'Mean Relatedness'
ls.cvAUC.out2$predictor<- factor(ls.cvAUC.out2$predictor,
levels = rev(c('Mean Relatedness', 'Shannon', 'invSimpson', 'Richness')))
# Setting pallette for background coloring area
pal<- c(piratepal('basel', trans = 0.4), piratepal('pony', trans = .5)[9], piratepal('info2', trans = .5)[14])
# Redfining that 'pal' palette with colors that do not rely on transparency settings (for correct pdf conversion)
cols<- NULL
for(i in 1:length(piratepal('basel'))){
cols<- c(cols, colorRampPalette(c("white", piratepal('basel')[i]))(10)[3])
}
cols<- c(cols, colorRampPalette(c("white", piratepal('pony')[9]))(10)[3])
cols<- c(cols, colorRampPalette(c("white", piratepal('info2')[14]))(10)[3])
pal<- cols
brewer.pal(9, 'BrBG')[9] # seablue
brewer.pal(2, 'BrBG')[2] # marron
brewer.pal(10, 'Paired')[10] # purple
brewer.pal(5, 'Paired')[5] # salmon
# plot it
p.auc<- ggplot(ls.cvAUC.out2, aes(x = cvAUC, y = diseasePlot2, col = predictor, xmin = ci.low, xmax = ci.up))+
geom_point(position = position_dodge(.8))+
geom_errorbarh(position = position_dodge(.8), height = 0.2)+
#scale_color_manual(values = rev(c('darkred','firebrick', 'dodgerblue', 'purple', 'goldenrod')))+
scale_color_manual(values = rev(c(brewer.pal(9, 'BrBG')[9], # seablue
brewer.pal(7, 'Accent')[7], # marron
brewer.pal(10, 'Paired')[10], # purple
brewer.pal(5, 'Paired')[5])))+ # salmon
#annotate("rect", ymin = 0.5, ymax = 1.5, xmin = -Inf, xmax = +Inf,fill = pal[12])+
#annotate("rect", ymin = 1.5, ymax = 2.5, xmin = -Inf, xmax = +Inf,fill = pal[7])+
#annotate("rect", ymin = 2.5, ymax = 3.5, xmin = -Inf, xmax = +Inf,fill = pal[10])+
#annotate("rect", ymin = 3.5, ymax = 4.5, xmin = -Inf, xmax = +Inf,fill = pal[9])+
#annotate("rect", ymin = 4.5, ymax = 5.5, xmin = -Inf, xmax = +Inf,fill = pal[8])+
#annotate("rect", ymin = 5.5, ymax = 6.5, xmin = -Inf, xmax = +Inf,fill = pal[11])+
#annotate("rect", ymin = 6.5, ymax = 7.5, xmin = -Inf, xmax = +Inf,fill = pal[5])+
#annotate("rect", ymin = 7.5, ymax = 8.5, xmin = -Inf, xmax = +Inf,fill = pal[3])+
#annotate("rect", ymin = 8.5, ymax = 9.5, xmin = -Inf, xmax = +Inf,fill = pal[2])+
#annotate("rect", ymin = 9.5, ymax = 10.5, xmin = -Inf, xmax = +Inf,fill = pal[1])+
#annotate("rect", ymin = 10.5, ymax = 11.5, xmin = -Inf, xmax = +Inf,fill = 'white', colour = 'black')+
# for grey/white shaded background
annotate("rect", ymin = 0.5, ymax = 1.5, xmin = -Inf, xmax = +Inf,fill = 'white')+
annotate("rect", ymin = 1.5, ymax = 2.5, xmin = -Inf, xmax = +Inf,fill = mygrey)+
annotate("rect", ymin = 2.5, ymax = 3.5, xmin = -Inf, xmax = +Inf,fill = 'white')+
annotate("rect", ymin = 3.5, ymax = 4.5, xmin = -Inf, xmax = +Inf,fill = mygrey)+
annotate("rect", ymin = 4.5, ymax = 5.5, xmin = -Inf, xmax = +Inf,fill = 'white')+
annotate("rect", ymin = 5.5, ymax = 6.5, xmin = -Inf, xmax = +Inf,fill = mygrey)+
annotate("rect", ymin = 6.5, ymax = 7.5, xmin = -Inf, xmax = +Inf,fill = 'white')+
annotate("rect", ymin = 7.5, ymax = 8.5, xmin = -Inf, xmax = +Inf,fill = mygrey)+
annotate("rect", ymin = 8.5, ymax = 9.5, xmin = -Inf, xmax = +Inf,fill = 'white')+
annotate("rect", ymin = 9.5, ymax = 10.5, xmin = -Inf, xmax = +Inf,fill = mygrey)+
annotate("rect", ymin = 10.5, ymax = 11.5, xmin = -Inf, xmax = +Inf,fill = 'white', colour = 'black')+
geom_point(position = position_dodge(.8), size = 1)+
geom_errorbarh(position = position_dodge(.8), height = 0.3, size = 0.4)+
ylab('Disease')+xlab('AUC')+
theme_bw()+
geom_vline(xintercept = c(0.5, 0.7), linetype = 'dashed')+
theme(axis.title = element_text(size = 8),
axis.text = element_text(size = 6, colour = 'black'),
panel.grid = element_blank(),
legend.position = 'right',
legend.justification = 'top',
legend.key.size = unit(0.3, "cm"),
legend.text = element_text(size = 6),
legend.title = element_blank(),
panel.border = element_blank(),
axis.line = element_line(size = 0.4))
p.auc
pdf('./output/figures/Figure3_AUC_CrossValidation.pdf', width = 10/2.55, height = (15/2.55))
p.auc
dev.off()
# THEORY PLOT ----
r = seq(0, 1, 0.01)
v = seq(0, 1, 0.01)
b = -0.5
c = 1
v_effect = 1
df<- expand.grid(r, v, b, c) %>%
rename(r = Var1, v = Var2, b = Var3, c = Var4) %>%
mutate(x = r*((b+(v_effect*v))/(2*c)))
# Basic theory plot
p.map.theory<- ggplot(df, aes(x = v, y = r))+
geom_tile(aes(fill = x, col = x), size = 0.2)+
scale_fill_gradient2('Predicted effect\non host',low = 'firebrick', mid = 'white', high='dodgerblue', midpoint = 0)+
scale_colour_gradient2('Predicted effect\non host',low = 'firebrick', mid = 'white', high='dodgerblue', midpoint = 0)+
ylab('Relatedness')+xlab('Probability of vertical transmission')+
scale_y_continuous(expand = c(0, 0))+
scale_x_continuous(expand = c(0, 0))+
theme_bw()+
theme(axis.title = element_text(size = 6),
axis.text = element_text(size = 5),
axis.ticks = element_line(size = 0.2, color = 'black'),
panel.grid = element_line(size = 0.1),
legend.position = 'right', #c(0.9, 0.1),
legend.justification = 'top',
legend.key.size = unit(0.3, "cm"),
legend.text = element_text(size = 3),
legend.title = element_text(size = 4),
panel.border = element_blank(),
axis.line = element_line(size = 0.3))
p.map.theory
# Plot of observed data
r.df<- read.table('./data/relatedness_sporulation.txt', header = TRUE, sep = '\t')
p.map.obs<- ggplot(r.df, aes(x = (1-sporulation_score), y = mean_relatedness))+
geom_point(size = 0.3)+
#geom_tile(aes(fill = x))+
#scale_fill_gradient2('Predicted effect\non host',low = 'firebrick', mid = 'white', high='springgreen4', midpoint = 0)+
ylab('Relatedness estimates')+xlab('(1 - sporulation score)')+
#scale_y_continuous(expand = c(0, 0))+
#scale_x_continuous(expand = c(0, 0))+
theme_bw()+
theme(axis.title = element_text(size = 6),
axis.text = element_text(size = 5),
axis.ticks = element_line(size = 0.2, color = 'black'),
panel.grid = element_blank(),
legend.position = 'right', #c(0.9, 0.1),
legend.justification = 'top',
legend.key.size = unit(0.3, "cm"),
legend.text = element_text(size = 3),
legend.title = element_text(size = 4),
panel.border = element_blank(),
axis.line = element_line(size = 0.3))
library(patchwork)
# adding different colors to point for better plotting
keep<- c("Ruminococcus_bromii_62047",
"Clostridium_sp_61482",
"Eubacterium_eligens_61678",
"Guyana_massiliensis_60772",
"Faecalibacterium_prausnitzii_61481",
"Roseburia_intestinalis_56239",
"Coprococcus_comes_61587",
"Dorea_longicatena_61473",
"Lachnospiraceae_bacterium_56833",
"Erysipelotrichaceae_bacterium_55770",
"Escherichia_coli_58110",
"Akkermansia_muciniphila_55290",
"Bacteroides_intestinalis_61596",
"Alistipes_onderdonkii_55464",
"Bacteroides_finegoldii_57739",
"Parabacteroides_goldsteinii_56831",
"Parabacteroides_merdae_56972",
"Bacteroides_fragilis_54507",
"Odoribacter_laneus_62216",
"Acidaminococcus_intestini_54097",
"Clostridium_leptum_61499")
r.df$cat<- 'a'
r.df[which(r.df$species_id%in% keep),'cat']<- 'b'
r.df$names<- ''
r.df<- r.df %>% mutate(names = ifelse(species_id %in% keep, species_id, ''))
r.df$names<- gsub('_', ' ', substr(r.df$names,1,nchar(r.df$name)-6))
p.map.obs<- ggplot(r.df, aes(x = (1-sporulation_score), y = mean_relatedness, col = cat))+
geom_point(size = 0.3)+
#geom_tile(aes(fill = x))+
#scale_fill_gradient2('Predicted effect\non host',low = 'firebrick', mid = 'white', high='springgreen4', midpoint = 0)+
#geom_text(aes(label = names), size = 1)+
#geom_text_repel(aes(label = names), box.padding = unit(0.1, 'line'), segment.colour = 'black', size = 0.9, segment.size = 0.5)+
ylab('Relatedness estimates')+xlab('(1 - sporulation score)')+
scale_color_manual(values = c('darkgrey', 'black'))+
theme_bw()+
theme(axis.title = element_text(size = 6),
axis.text = element_text(size = 5),
axis.ticks = element_line(size = 0.2, color = 'black'),
panel.grid = element_blank(),
legend.position = 'none', #c(0.9, 0.1),
legend.justification = 'top',
legend.key.size = unit(0.3, "cm"),
legend.text = element_text(size = 3),
legend.title = element_text(size = 4),
panel.border = element_blank(),
axis.line = element_line(size = 0.3))
pdf('./output/figures/Figure1_heatmap.pdf', width = 12/2.55, height = 5/2.55)
(p.map.theory | p.map.obs) +
plot_annotation(tag_levels = 'A') &
theme(plot.tag = element_text(size = 7, face = 'bold'))
dev.off()
# Version with all names on plot
p.heatmap.obs.names<- ggplot(r.df, aes(x = (1-sporulation_score), y = mean_relatedness, label = species_id))+
#geom_point(size = 0.1)+
#geom_text_repel(aes(label = species_id), box.padding = unit(0.1, 'line'), fontface = 'bold', segment.colour = 'black', size = 1.5, segment.size = 0.2)+
geom_text_repel(aes(label = species_id), box.padding = unit(0.1, 'line'), segment.colour = 'black', size = 1.3, segment.size = 0.2)+
#geom_tile(aes(fill = x))+
#scale_fill_gradient2('Predicted effect\non host',low = 'firebrick', mid = 'white', high='springgreen4', midpoint = 0)+
ylab('Relatedness')+xlab('(1 - sporulation score)')+
#scale_y_continuous(expand = c(0, 0))+
#scale_x_continuous(expand = c(0, 0))+
#scale_color_manual(values = rep('black', nrow(r.df)))+
theme_bw()+
theme(axis.title = element_text(face = 'bold', size = 9),
axis.text = element_text(size = 9, color = 'black'),
axis.ticks = element_line(size = 0.6, color = 'black'),
panel.grid = element_blank(),
legend.position = 'right', #c(0.9, 0.1),
legend.justification = 'top',
legend.key.size = unit(0.3, "cm"),
legend.text = element_text(size = 3),
legend.title = element_text(size = 4),
panel.border = element_blank(),
axis.line = element_line(size = 0.6))
#library(ggplot2)
#library(plotly)
#library(gapminder)
#install.packages('plotly') # if you haven't installed the package
#library(plotly)
#py <- plotly(username="r_user_guide", key="mw5isa4yqp")
#ggplotly(p.heatmap.obs.names)
#py$ggplotly(p.heatmap.obs.names)
#l <- plotly::ggplotly(p.heatmap.obs.names)
#htmlwidgets::saveWidget(l, file = "./output/figures/index.html")
pdf('./output/figures/Supp_heatmap_names.pdf', width = 15/2.55, height = 20/2.55)
p.heatmap.obs.names
dev.off()
# Map species on theory plot & other versions
r.df<- read.table('./data/relatedness_sporulation.txt', header = TRUE, sep = '\t')
r.df$revSporulation<- 1- r.df$sporulation_score
r.df$spoRescaled = 0.01 + ((0.99 - 0.01) / (max(r.df$revSporulation) - min(r.df$revSporulation))) * (r.df$revSporulation - min(r.df$revSporulation))
p.map.theory+
geom_point(data = r.df, aes(x = revSporulation, y = mean_relatedness))#+
#geom_text_repel(data = r.df, aes(x = spoRescaled, y = mean_relatedness, label = species_id), box.padding = unit(0.45, 'line'), fontface = 'bold', segment.colour = 'black')
ggplot(r.df, aes(x = revSporulation, y = mean_relatedness))+
geom_point()
#geom_text_repel(data = r.df, aes(x = spoRescaled, y = mean_relatedness, label = species_id), box.padding = unit(0.45, 'line'), fontface = 'bold', segment.colour = 'black')
leg <- get_legend(p.hm.leg) # library(ggpubr)
p.legend<- as_ggplot(leg)
p.legend
p.fan.theory<- ggplot(df, aes(x = r, y = x, col = v))+
geom_point()+
scale_color_gradient2(low = 'firebrick', mid = 'white', high='springgreen4', midpoint = 0.5)+
geom_point(data = r.df, aes(x = mean_relatedness, y = pred_x), col = 'black')+
geom_text_repel(data = r.df[r.df$species_id %in% keep,], aes(x = mean_relatedness, y = pred_x, label = species_id), box.padding = unit(0.45, 'line'), fontface = 'bold', segment.colour = 'black', col = 'black')
p.fan.theory
# MCMC general MMMC model ----
# Not included in MS. Another possible approach to analyse the data, using Multimembership model.
load('./output/stats_runs/data_preps_23062021.RData')
mf = 100
prior.1<-list(R=list(V=1, fix=1),
G=list(G1=list(V=1, nu=1, alpha.mu=0, alpha.V=100),
G2=list(V=1, nu=1, alpha.mu=0, alpha.V=100)))
m_1<-MCMCglmm(caseControl~NR,
random=~idv(prob)+idv(probr),
data=dat.rescaled,
family="threshold",
prior=prior.1,
nitt = 13000*mf,
thin = 10*mf,burnin=3000*mf)
summary(m_2)
prior.2<-list(R=list(V=1, fix=1),
G=list(G1=list(V=1, nu=1, alpha.mu=0, alpha.V=100)))
m_2<-MCMCglmm(caseControl~NR,
random=~idv(prob),
data=dat.rescaled,
family="threshold",
prior=prior.2,
nitt = 13000*mf,
thin = 10*mf,burnin=3000*mf)
save.image('./output/stats_runs/MMMC_HM2_run_July2021.RData')
# ARCHIVED CODE ----
# [deprecated] AllData boxplots ----
p.all.NR<- ggplot(dat.rescaled, aes(x = as.factor(caseControl), y = NR, fill = as.factor(caseControl)))+
geom_boxplot(width = 0.5, outlier.size = 0.1, lwd = 0.3)+
ylab('Mean gut relatedness')+xlab('')+
scale_fill_manual(values = c('lightgrey', 'white'))+
scale_x_discrete(labels = c('Sick', 'Healthy'))+
theme_bw()+
theme(axis.title = element_text(size = 6),
axis.text = element_text(size = 5),
axis.text.x = element_text(size = 5, angle = 45, hjust = 1), panel.grid = element_line(size = 0.1),
legend.position = 'none', #c(0.9, 0.1),
legend.key.size = unit(0.3, "cm"),
legend.text = element_text(size = 3),
legend.title = element_blank(),
panel.border = element_blank(),
axis.line = element_line(size = 0.3))
p.all.NRSPO<- ggplot(dat.rescaled, aes(x = as.factor(caseControl), y = NRSPO, fill = as.factor(caseControl)))+
geom_boxplot(width = 0.5, outlier.size = 0.1, lwd = 0.3)+
ylab('Relatedness weighed mean\nsporulation score')+xlab('')+
scale_x_discrete(labels = c('Sick', 'Healthy'))+
scale_fill_manual(values = c('lightgrey', 'white'))+
theme_bw()+
theme(axis.title = element_text(size = 6),
axis.text = element_text(size = 5),
axis.text.x = element_text(size = 5, angle = 45, hjust = 1),
panel.grid = element_line(size = 0.1),
legend.position = 'none', #c(0.9, 0.1),
legend.key.size = unit(0.3, "cm"),
legend.text = element_text(size = 3),
legend.title = element_blank(),
panel.border = element_blank(),
axis.line = element_line(size = 0.3))
# [deprecated] ROC/AUC analysis ----
library(pROC)
library(caret)
library(metRology)
# Using caret package to run cross-validation analysis
# Example to see how it works
# Code wrapper to run the cross validation
rocCV<- function(data, nb.k, reps, focal.disease, focal.predictor){
# Defining the cross validation algorithm parameters
fit.control <- trainControl(method = "repeatedcv", # repeated k-fold validation
number = nb.k, repeats = reps, # use: 10 folds, repeat: 10 times
summaryFunction = twoClassSummary, classProbs = TRUE) # Use AUC summary stat
#fit.control <- trainControl(method = "LOOCV", # for leave-one-out analysis
# summaryFunction = twoClassSummary, classProbs = TRUE)
d2<- data %>%
filter(disease_type %in% focal.disease) %>%
select(caseControl, NR, Shannon, invSimpson, Richness) %>%
rename(focal.predictor = focal.predictor)
d2$caseControl<- ifelse(d2$caseControl == 0, 'sick', 'healthy')
set.seed(42)
fit<- train(caseControl ~ focal.predictor, data = d2, method = "glm", family = "binomial", trControl = fit.control)
#fit$results # ROC corresponds to mean(fit$resample[,'ROC]), and ROCSD = sd(fit$resample[,'ROC])
return(fit)
}
# run it
out<- rocCV(dat.rescaled, 10, 10, 'MetS', 'NR')
out$results # ROC = 0.53, ROCSD = 0.2328
mean(out$resample[,'ROC']) # this is an emprical sampling distribution of the AUC
sd(out$resample[,'ROC']) # and this is the standard deviation of the sampling distribution of our mean estimate of the AUC, i.e.the standard error
# then taking the 0.025 and 97.5 percentiles of this empirical distribution gives as the confidence interval
# So as far as I understand, the k-fold cross validation is a way to obtain a mean estimate of the AUC
# and the vector of AUC obtained from each fold/repeat sample of the data is essentially an empirical sampling distribution
# So the standard deviation of that is the standard error of the mean AUC
# and the percentiles of that is the confidence interval.
# Here the CI would be ~ 1.96*0.2328 = 0.456, so the mean AUC would be [0.074-0.986]
quantile(out$resample[,'ROC'], c(0.025, 0.975))
mean(out$resample[,'ROC'])-(1.96*sd(out$resample[,'ROC']))
mean(out$resample[,'ROC'])+(1.96*sd(out$resample[,'ROC']))
# Ok so don't find exactly the same, probably because the exact normal approximation here is not the best
# Like for certain case the t-distribution (= a slightly flattened) normal is better
#
qt.scaled(c(0.025, 0.975),
mean = mean(out$resample[,'ROC']),
sd = sd(out$resample[,'ROC']),
df = length(out$resample[,'ROC']))
# Yep, what I get there is similar to what I get with mean +/- 1.96 SD, but a tad different due to qt.scaled being a t distribution
# The empirical quantiles are a bit shifted towards lower estimates
# Quick sensitivity analysis test for k and reps values, see with MetS which is a small dataset
df.run.rocCV<- data.frame(nb.k = rep(seq(3,10,1), each = 4),
reps = rep(c(10, 50, 100, 1000), 8),
focal.disease = 'MetS',
ROC = NA,
ROCSD = NA)
for(i in 1:nrow(df.run.rocCV)){
print(i)
t<- rocCV(dat.rescaled, nb.k = df.run.rocCV$nb.k[i], reps = df.run.rocCV$reps[i], focal.disease = df.run.rocCV$focal.disease[i])$results[,c('ROC', 'ROCSD')]
df.run.rocCV$ROC[i] = t[,'ROC']
df.run.rocCV$ROCSD[i] = t[,'ROCSD']
}
# Not much effect, variance goes larger as k increases, which is expected
ggplot(df.run.rocCV, aes(x = nb.k, y = ROC, ymin = ROC-ROCSD, ymax = ROC+ROCSD, col = as.factor(reps)))+
geom_point(position = position_dodge(.8))+
geom_errorbar(position = position_dodge(.8), width = 0.2)+
scale_color_manual(values = c('red', 'dodgerblue', 'green', 'goldenrod'))
# actual run
# keep k = 10, reps = 1000
nb.k = 10
reps = 1000
df.run.rocCV.fin<- data.frame(nb.k = nb.k,
reps = reps,
focal.disease = unique(dat.rescaled$disease_type),
ROC = NA,
ROCSD = NA)
# Make dataframe smaller (faster run?)
d.clean = dat.rescaled %>%
select(caseControl, NR, Shannon, invSimpson, Richness, disease_type) %>%
mutate(caseControl = ifelse(caseControl == 0, 'sick', 'healthy'))
head(d.clean)
fit.control <- trainControl(method = "repeatedcv", number = nb.k, repeats = reps,
summaryFunction = twoClassSummary, classProbs = TRUE)
# re-define code wrappers to work with actual run
rocCV<- function(data, focal.predictor, focal.disease, trainControl){
data<- rename(data, focal.predictor = focal.predictor)
set.seed(42) # re-setting the seed everytime ensures that the dataset is split the same way when running the ROCcv for the different predictors
fit<- train(caseControl ~ focal.predictor, data = data[data$disease_type %in% focal.disease,], method = "glm", family = "binomial", trControl = trainControl)
d.out<- data.frame(disease = focal.disease,
predictor = focal.predictor,
ROC = fit$results[,'ROC'],
ROCSD = fit$results[,'ROCSD'],
mean.train.n = round(mean(lengths(fit$control$index)),0), # mean training set size
mean.test.n = round(mean(lengths(fit$control$indexOut)),0)) # mean test set size
return(list(d.out, fit))
}
rocCV.severalDiseases<- function(data, focal.predictor, focal.disease, disease.tag = 'several', trainControl){
data<- rename(data, focal.predictor = focal.predictor)
set.seed(42) # re-setting the seed everytime ensures that the dataset is split the same way when running the ROCcv for the different predictors
fit<- train(caseControl ~ focal.predictor, data = data[data$disease_type %in% focal.disease,], method = "glm", family = "binomial", trControl = trainControl)
d.out<- data.frame(disease = disease.tag,
predictor = focal.predictor,
ROC = fit$results[,'ROC'],
ROCSD = fit$results[,'ROCSD'],
mean.train.n = round(mean(lengths(fit$control$index)),0), # mean training set size
mean.test.n = round(mean(lengths(fit$control$indexOut)),0)) # mean test set size
return(list(d.out, fit))
}
preds = c('NR', 'Shannon', 'invSimpson', 'Richness') # four predictors to run the cross-validation over
dis = unique(d.clean$disease_type) # 19 diseases to run the cross validation over
# to store results
dfin<- data.frame(disease = character(),
predictor = character(),
ROC = numeric(),
ROCSD = numeric(),
mean.train.n = numeric(),
mean.test.n = numeric())
dfin.list<- vector('list')
# In the loop, redefine the set.seed() everytime ensures the same fold split is done for each test over each predictor
# can be verified when looking within $result output, can see the seeds of the out/in rows are the same
counter = 0
for(p in 1:length(preds)){
foc.predictor = preds[p]
for(d in 1:length(dis)){
counter = counter + 1
print(counter)
foc.disease = dis[d]
roc.cv<- rocCV(d.clean, focal.predictor = foc.predictor, focal.disease = foc.disease, trainControl = fit.control)
dfin<- rbind(dfin, roc.cv[[1]])
dfin.list[[counter]]<- roc.cv[[2]]$resample
}
}
# Finally, add the cross validation when pooling all diseases
roc.cv.all_NR<- rocCV.severalDiseases(d.clean, focal.predictor = 'NR', focal.disease = dis, disease.tag = 'All diseases', trainControl = fit.control)
roc.cv.all_Shannon<- rocCV.severalDiseases(d.clean, focal.predictor = 'Shannon', focal.disease = dis, disease.tag = 'All diseases', trainControl = fit.control)
roc.cv.all_invSimpson<- rocCV.severalDiseases(d.clean, focal.predictor = 'invSimpson', focal.disease = dis, disease.tag = 'All diseases', trainControl = fit.control)
roc.cv.all_Richness<- rocCV.severalDiseases(d.clean, focal.predictor = 'Richness', focal.disease = dis, disease.tag = 'All diseases', trainControl = fit.control)
dfin2<- rbind(dfin,
roc.cv.all_NR[[1]],
roc.cv.all_Shannon[[1]],
roc.cv.all_invSimpson[[1]],
roc.cv.all_Richness[[1]])
dfin.list2<- dfin.list
dfin.list2[[41]]<- roc.cv.all_NR[[2]]$resample
dfin.list2[[42]]<- roc.cv.all_Shannon[[2]]$resample
dfin.list2[[43]]<- roc.cv.all_invSimpson[[2]]$resample
dfin.list2[[44]]<- roc.cv.all_Richness[[2]]$resample
hist(dfin.list2[[11]][,'ROC'])
rm(dfin.list)
rm(dat.rescaled) # need only d.clean for the AUC analysis
rm(prob)
rm(prob.rescaled)
rm(roc.cv.all_invSimpson)
rm(roc.cv.all_NR)
rm(roc.cv.all_Richness)
rm(roc.cv.all_Shannon)
save.image('./output/stats_runs/AUC_crossValidation_runClean.RData')
load('./output/stats_runs/AUC_crossValidation_runClean.RData')
# looking at an example of resampling distribution
quantile(dfin.list2[[41]][,'ROC'], c(0.025, 0.975))
hist(dfin.list2[[41]][,'ROC'])
qt.scaled(c(0.025), mean = roc.cv.all_NR[[1]]$ROC, sd = roc.cv.all_NR[[1]]$ROCSD, df = 999)
qt.scaled(c(0.975), mean = roc.cv.all_NR[[1]]$ROC, sd = roc.cv.all_NR[[1]]$ROCSD, df = 999)
# Ok, those are super close, and the resampling distribution looks very well normal on this example
# so think should be fine, use the "empricial 95%CI", that is, the percentile distribution of the resampling distribution
# this way what this is is transparent
# Plot it
dfin2$disease<- factor(dfin2$disease,
levels = rev(c('All diseases', 'OBE', 'MetS', 'IBD', 'CRC', 'T2D_IGC', 'LC', 'ACVD', 'RA', 'HYPER', 'BD')))
dfin2$predictor[dfin2$predictor == 'NR']<- 'Mean Relatedness'
dfin2$predictor<- factor(dfin2$predictor,
levels = rev(c('Mean Relatedness', 'Shannon', 'invSimpson', 'Richness')))
dfin3<- dfin2
head(dfin3)
dfin3$cilower.t<- qt.scaled(c(0.025), mean = dfin3$ROC, sd = dfin3$ROCSD, df = 999)
dfin3$ciupper.t<- qt.scaled(c(0.975), mean = dfin3$ROC, sd = dfin3$ROCSD, df = 999)
getci.emp<- function(x){quantile(x[,'ROC'], c(0.025, 0.975))}
cis.emp<- as.data.frame(do.call('rbind', lapply(dfin.list2, getci.emp))) %>%
rename(cilower.emp = `2.5%`,
ciupper.emp = `97.5%`)
dfin3<- cbind(dfin3, cis.emp)
# Using percentile intervals of the resampling distribution rather than the qt.scaled quantiles
# because not 100% sure about the statistical property of the repeated k-fold resampling
# the percentile interval will be 100% clear and transparent about the method
# The two correlate so not worried about it anyway
plot(cilower.emp ~ cilower.t, data = dfin3)
# Add samples sizes under disease names on y-axis ticks
nsizes.diseases<- dat.rescaled %>%
group_by(disease_type, caseControl) %>%
summarise(n = n()) %>%
as.data.frame() %>%
ungroup() %>%
spread(key = caseControl, value = n) %>%
as.data.frame() %>%
rename(case = `0`,
control = `1`) %>%
rename(disease = disease_type)
nsizes.diseases<- rbind(nsizes.diseases,
data.frame(disease = 'All diseases',
case = table(dat.rescaled$caseControl)[[1]],
control = table(dat.rescaled$caseControl)[[2]]))
dfin3<- left_join(dfin3, nsizes.diseases, by = 'disease')
dfin3<- dfin3 %>%
mutate(diseasePlot2 = paste0(disease, '\n(sick:', case, ', healthy:', control, ')'))
dfin3$diseasePlot2[dfin3$diseasePlot2 == 'T2D_IGC\n(sick:280, healthy:215)']<- "T2D & IGT\n(sick:280, healthy:215)"
dfin3$diseasePlot2<- factor(dfin3$diseasePlot2,
levels = rev(c("All diseases\n(sick:1750, healthy:1184)",
"OBE\n(sick:234, healthy:180)",
"MetS\n(sick:60, healthy:26)",
"IBD\n(sick:196, healthy:108)",
"CRC\n(sick:386, healthy:205)",
"T2D & IGT\n(sick:280, healthy:215)",
"LC\n(sick:118, healthy:111)",
"ACVD\n(sick:214, healthy:169)",
"RA\n(sick:88, healthy:89)",
"HYPER\n(sick:155, healthy:41)",
"BD\n(sick:19, healthy:40)")))
# by definition, a 10-fold will split it in 10, meaning 90% of data goes to training and 10% goes to testing set
# So by knowing the sample size of the cohorts, the size of train/test sets is known
library(yarrr)
pal<- c(piratepal('basel', trans = 0.4), piratepal('pony', trans = .5)[9], piratepal('info2', trans = .5)[14])
# Plot
p.auc<- ggplot(dfin3, aes(x = ROC, y = diseasePlot2, col = predictor, xmin = cilower.emp, xmax = ciupper.emp))+
geom_point(position = position_dodge(.8))+
geom_errorbarh(position = position_dodge(.8), height = 0.2)+
scale_color_manual(values = rev(c('firebrick', 'dodgerblue', 'purple', 'goldenrod')))+
annotate("rect", ymin = 0.5, ymax = 1.5, xmin = -Inf, xmax = +Inf, alpha = .2,fill = pal[12])+
annotate("rect", ymin = 1.5, ymax = 2.5, xmin = -Inf, xmax = +Inf, alpha = .2,fill = pal[7])+
annotate("rect", ymin = 2.5, ymax = 3.5, xmin = -Inf, xmax = +Inf, alpha = .2,fill = pal[10])+
annotate("rect", ymin = 3.5, ymax = 4.5, xmin = -Inf, xmax = +Inf, alpha = .2,fill = pal[9])+
annotate("rect", ymin = 4.5, ymax = 5.5, xmin = -Inf, xmax = +Inf, alpha = .2,fill = pal[8])+
annotate("rect", ymin = 5.5, ymax = 6.5, xmin = -Inf, xmax = +Inf, alpha = .2,fill = pal[11])+
annotate("rect", ymin = 6.5, ymax = 7.5, xmin = -Inf, xmax = +Inf, alpha = .2,fill = pal[5])+
annotate("rect", ymin = 7.5, ymax = 8.5, xmin = -Inf, xmax = +Inf, alpha = .2,fill = pal[3])+
annotate("rect", ymin = 8.5, ymax = 9.5, xmin = -Inf, xmax = +Inf, alpha = .2,fill = pal[2])+
annotate("rect", ymin = 9.5, ymax = 10.5, xmin = -Inf, xmax = +Inf, alpha = .2,fill = pal[1])+
annotate("rect", ymin = 10.5, ymax = 11.5, xmin = -Inf, xmax = +Inf, alpha = .2,fill = 'white', colour = 'black')+
geom_point(position = position_dodge(.8))+
geom_errorbarh(position = position_dodge(.8), height = 0.3)+
ylab('Disease')+
theme_bw()+
geom_vline(xintercept = c(0.5, 0.7), linetype = 'dashed')+
theme(axis.title = element_text(size = 8),
axis.text = element_text(size = 6),
panel.grid = element_line(size = 0.1),
legend.position = 'right',
legend.justification = 'top',
legend.key.size = unit(0.3, "cm"),
legend.text = element_text(size = 6),
legend.title = element_blank(),
panel.border = element_blank(),
axis.line = element_line(size = 0.35))
p.auc
pdf('./output/figures/Figure3_AUC_CrossValidation.pdf', width = 10/2.55, height = (15/2.55))
p.auc
dev.off()
| /scripts/4.2_statisticals_analyses.R | no_license | CamilleAnna/MicrobiomeHamiltonianMedicine_repo | R | false | false | 58,632 | r | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
# Using evolutionary theory to predict microbes’ effect on host health
# Camille Simonet & Luke McNally
#
# SCRIPT: Statistical analyses
# last edit: 21/08/2021
#
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
#local_project_dir="path/to/repo"
#local_project_dir="/Users/s1687811/Documents/PhD/Research/MicrobiomeHamiltonianMedicine/MicrobiomeHamiltonianMedicine_repo"
# SETUP ----
# Sourcing packages ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
setwd(local_project_dir)
source('./scripts/sourced_packages.R')
library(ape)
library(MCMCglmm)
library(vegan)
library(lme4)
library(lmerTest)
library(irr)
library(effects)
library(jtools)
library(ROCR)
library(ggrepel)
# Load environment preped by script 4.1_data_prep.R
load('./output/stats_runs/data_preps_23062021.RData')
# Data overview
table(dat.rescaled$caseControl)
nrow(dat.rescaled)
# MICROBIOME ANALYSIS ----
# Binomial regressions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# We put disease as random effect allowing both intercepts and slope to vary per disease
# Let the model estimate ful;l covariance matrix
m.glmm.disease <- glmer(caseControl ~ 1+ NR + NRSPO + (1 + NR + NRSPO|disease_type),
family = binomial(link = "logit"),
data = dat.rescaled,
control = glmerControl(optimizer = "bobyqa", optCtrl = list(maxfun=5e5)))
summary(m.glmm.disease)
# Not enough cohort per disease to distinguish the two effect, so partly confounded
# re-run analysis with cohort as random effect
# find similar result
m.glmm.cohort <- glmer(caseControl ~ 1+ NR + NRSPO + (1 + NR + NRSPO|cohortNew),
family = binomial(link = "logit"),
data = dat.rescaled,
control = glmerControl(optimizer = "bobyqa", optCtrl = list(maxfun=2e5)))
summary(m.glmm.cohort)
# Test random slopes (LRT) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Re-run model with the random slopes
# use LRT tests to verify if indeed allowing random slopes give a better fit
m.glmm.disease.fixedSlopes <- glmer(caseControl ~ 1+ NR + NRSPO + (1 |disease_type),
family = binomial(link = "logit"),
data = dat.rescaled,
control = glmerControl(optimizer = "bobyqa", optCtrl = list(maxfun=5e5)))
summary(m.glmm.disease.fixedSlopes) # same results for NR, NRSPO comes out significant too
m.glmm.cohort.fixedSlopes <- glmer(caseControl ~ 1+ NR + NRSPO + (1 |cohortNew),
family = binomial(link = "logit"),
data = dat.rescaled,
control = glmerControl(optimizer = "bobyqa", optCtrl = list(maxfun=5e5)))
summary(m.glmm.cohort.fixedSlopes) # same results
anova(m.glmm.disease.fixedSlopes, m.glmm.disease) # model with random slopes gives sig. better fit
anova(m.glmm.cohort.fixedSlopes, m.glmm.cohort) # model with random slopes gives sig. better fit
# Check with MCMC ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Verify with MCMCglmm if I get the same result for the choosen model (per disease, with random slopes)
prior.0<-list(R=list(V=1, fix=1),
G=list(G1=list(V=diag(3), nu=3, alpha.mu=c(0,0,0), alpha.V=diag(3)*1000))) # variance in fixed effect across diseases
mcmc.disease<- MCMCglmm(caseControl ~ 1+ NR+NRSPO,
random = ~us(1+NR+NRSPO):disease_type,
data = dat.rescaled,
family = 'threshold',
prior = prior.0,
nitt = 150000, burnin = 50000, thin = 100)
summary(mcmc.disease) # MCMCglmm gives similar results
# MAKE SUPPLEMENTARY TABLES ----
source('./scripts/5.1_suppMat_make_modelSummaries.R')
# PLOT MICROBIOME MODEL ----
# Boxplots NR/NRSPO ----
mygrey<- colorRampPalette(c('white', 'lightgrey'))(10)[4]
theme.bp<-
theme_bw()+
theme(axis.title = element_text(size = 6),
axis.text = element_text(size = 5, colour = 'black'),
panel.grid = element_blank(),
#legend.position = 'top', #c(0.9, 0.1),
legend.key.size = unit(0.3, "cm"),
legend.text = element_text(size = 3),
legend.title = element_blank(),
panel.border = element_blank(),
axis.line = element_line(size = 0.4))
dat.rescaled$cohortNewPlot<- factor(dat.rescaled$cohortNew,
levels = (c('YeZ2018_BD', 'LiJ2017_HYPER', 'Zhang2015_RA','JieZ2017_ACVD', 'Karlsson2012_ACVD',
'QinN2014_LC', 'QinJ2012_T2D', 'Karlsson2013_T2D&IGT',
'FengQ2015_CRC', 'YuJ2015_CRC', 'ZellerG2014_CRC', 'ThomasAM2018_CRC', 'VogtmannE2016_CRC',
'He2017_IBD', 'NielsenH2014_IBD', 'iHMP_IBD', 'Costea2017_MetS', 'LeChatelierE2013_OBE', 'Liu2017_OBE')))
dat.rescaled$cohortNewPlot2<- do.call('rbind', strsplit(dat.rescaled$cohortNew, '_'))[,1]
dat.rescaled$cohortNewPlot2<- factor(dat.rescaled$cohortNewPlot2,
levels = (c('YeZ2018', 'LiJ2017', 'Zhang2015','JieZ2017', 'Karlsson2012',
'QinN2014', 'QinJ2012', 'Karlsson2013',
'FengQ2015', 'YuJ2015', 'ZellerG2014', 'ThomasAM2018', 'VogtmannE2016',
'He2017', 'NielsenH2014', 'iHMP', 'Costea2017', 'LeChatelierE2013', 'Liu2017')))
# Add samples sizes under cohort names on y-axis ticks
nsizes<- dat.rescaled %>%
group_by(cohortNewPlot2, caseControl) %>%
summarise(n = n()) %>%
as.data.frame() %>%
ungroup() %>%
spread(key = caseControl, value = n) %>%
as.data.frame() %>%
rename(case = `0`,
control = `1`)
dat.rescaled<- left_join(dat.rescaled, nsizes, by = 'cohortNewPlot2')
dat.rescaled<- dat.rescaled %>%
mutate(cohortNewPlot3 = paste0(cohortNewPlot2, '\n(c:', case, ', h:', control, ')'))
dat.rescaled$cohortNewPlot3<- factor(dat.rescaled$cohortNewPlot3,
levels = rev(c("Liu2017\n(c:104, h:101)",
"LeChatelierE2013\n(c:130, h:79)",
"Costea2017\n(c:60, h:26)",
"iHMP\n(c:89, h:26)",
"NielsenH2014\n(c:60, h:41)",
"He2017\n(c:47, h:41)",
"VogtmannE2016\n(c:24, h:19)",
"ThomasAM2018\n(c:84, h:45)",
"ZellerG2014\n(c:111, h:45)",
"YuJ2015\n(c:74, h:53)",
"FengQ2015\n(c:93, h:43)",
"Karlsson2013\n(c:98, h:33)",
"QinJ2012\n(c:182, h:182)",
"QinN2014\n(c:118, h:111)",
"Karlsson2012\n(c:12, h:10)",
"JieZ2017\n(c:202, h:159)" ,
"Zhang2015\n(c:88, h:89)",
"LiJ2017\n(c:155, h:41)",
"YeZ2018\n(c:19, h:40)")))
p.NR.boxes<- ggplot(dat.rescaled, aes(x = cohortNewPlot3, y = NR, fill = as.factor(caseControl)))+
ylab('Gut average relatedness')+xlab('Cohort')+
scale_y_continuous(limits = c(0.35, 1), expand = c(0, 0))+
geom_boxplot(width = 0.5, outlier.size = 0.05, lwd = 0.2)+
#scale_fill_manual(values = c('lightgrey', 'white'))+
scale_fill_manual(values = c('firebrick', 'dodgerblue'))+
coord_flip()+
theme.bp+
theme(legend.position = 'none')
ymin.rect.NR = 0.35
ymax.rect.NR = 1
text.pos = 0.38
p.NR<- p.NR.boxes +
annotate("rect", xmin = 17.5, xmax = 19.5, ymin = ymin.rect.NR, ymax = ymax.rect.NR,fill = mygrey)+
annotate("rect", xmin = 16.5, xmax = 17.5, ymin = ymin.rect.NR, ymax = ymax.rect.NR,fill = 'white')+
annotate("rect", xmin = 14.5, xmax = 16.5, ymin = ymin.rect.NR, ymax = ymax.rect.NR, fill = mygrey)+
annotate("rect", xmin = 13.5, xmax = 14.5, ymin = ymin.rect.NR, ymax = ymax.rect.NR, fill = mygrey)+
annotate("rect", xmin = 8.5, xmax = 13.5, ymin = ymin.rect.NR, ymax = ymax.rect.NR, fill = 'white')+
annotate("rect", xmin = 7.5, xmax = 8.5, ymin = ymin.rect.NR, ymax = ymax.rect.NR, fill = mygrey)+
annotate("rect", xmin = 6.5, xmax = 7.5, ymin = ymin.rect.NR, ymax = ymax.rect.NR, fill = mygrey)+
annotate("rect", xmin = 5.5, xmax = 6.5, ymin = ymin.rect.NR, ymax = ymax.rect.NR, fill = 'white')+
annotate("rect", xmin = 3.5, xmax = 5.5, ymin = ymin.rect.NR, ymax = ymax.rect.NR, fill = mygrey)+
annotate("rect", xmin = 2.5, xmax = 3.5, ymin = ymin.rect.NR, ymax = ymax.rect.NR, fill = 'white')+
annotate("rect", xmin = 1.5, xmax = 2.5, ymin = ymin.rect.NR, ymax = ymax.rect.NR, fill = mygrey)+
annotate("rect", xmin = 0.5, xmax = 1.5, ymin = ymin.rect.NR, ymax = ymax.rect.NR, fill = 'white')+
geom_boxplot(width = 0.5, outlier.size = 0.05, lwd = 0.2)+
annotate('text', x = 18.5, y = text.pos, label = 'Obesity', angle = 90, size = 2)+
annotate('text', x = 17, y = text.pos, label = 'MetS', angle = 90, size = 2)+
#annotate('text', x = 15.5, y = text.pos, label = "CD", angle = 90, size = 2)+
#annotate('text', x = 14, y = text.pos, label = 'UC', angle = 90, size = 2)+
annotate('text', x = 15, y = text.pos, label = 'IBD', angle = 90, size = 2)+
annotate('text', x = 11, y = text.pos, label = 'Colorectal Cancer', angle = 90, size = 2)+
#annotate('text', x = 8, y = text.pos, label = 'IGT', angle = 90, size = 2)+
#annotate('text', x = 7, y = text.pos, label = 'T2D', angle = 90, size = 2)+
annotate('text', x = 7.5, y = text.pos, label = 'T2D & IGT', angle = 90, size = 2)+
annotate('text', x = 6, y = text.pos, label = 'LC', angle = 90, size = 2)+
annotate('text', x = 4.5, y = text.pos, label = 'ACVD', angle = 90, size = 2)+
annotate('text', x = 3, y = text.pos, label = 'RA', angle = 90, size = 2)+
annotate('text', x = 2, y = text.pos, label = 'HypT', angle = 90, size = 2)+
annotate('text', x = 1, y = text.pos, label = 'BD', angle = 90, size = 2)
p.NR
p.NRSPO.boxes<- ggplot(dat.rescaled, aes(x = cohortNewPlot3, y = NRSPO, fill = as.factor(caseControl)))+
xlab(' \ ')+ylab('Relatedness weighed mean\nsporulation score')+
scale_y_continuous(limits = c(0, 0.5), expand = c(0, 0))+
geom_boxplot(width = 0.5, outlier.size = 0.05, lwd = 0.2)+
#scale_fill_manual(values = c('lightgrey', 'white'))+
scale_fill_manual(values = c('firebrick', 'dodgerblue'))+
coord_flip()+
theme.bp+
theme(legend.position = 'none',
axis.text.y = element_blank(),
axis.line.y = element_blank(),
axis.ticks.y = element_blank())
ymin.rect.NRSPO = 0
ymax.rect.NRSPO = 0.5
p.NRSPO<- p.NRSPO.boxes +
annotate("rect", xmin = 17.5, xmax = 19.5, ymin = ymin.rect.NRSPO, ymax = ymax.rect.NRSPO, fill = mygrey)+
annotate("rect", xmin = 16.5, xmax = 17.5, ymin = ymin.rect.NRSPO, ymax = ymax.rect.NRSPO, fill = 'white')+
annotate("rect", xmin = 14.5, xmax = 16.5, ymin = ymin.rect.NRSPO, ymax = ymax.rect.NRSPO, fill = mygrey)+
annotate("rect", xmin = 13.5, xmax = 14.5, ymin = ymin.rect.NRSPO, ymax = ymax.rect.NRSPO, fill = mygrey)+
annotate("rect", xmin = 8.5, xmax = 13.5, ymin = ymin.rect.NRSPO, ymax = ymax.rect.NRSPO, fill = 'white')+
annotate("rect", xmin = 7.5, xmax = 8.5, ymin = ymin.rect.NRSPO, ymax = ymax.rect.NRSPO, fill = mygrey)+
annotate("rect", xmin = 6.5, xmax = 7.5, ymin = ymin.rect.NRSPO, ymax = ymax.rect.NRSPO, fill = mygrey)+
annotate("rect", xmin = 5.5, xmax = 6.5, ymin = ymin.rect.NRSPO, ymax = ymax.rect.NRSPO, fill = 'white')+
annotate("rect", xmin = 3.5, xmax = 5.5, ymin = ymin.rect.NRSPO, ymax = ymax.rect.NRSPO, fill = mygrey)+
annotate("rect", xmin = 2.5, xmax = 3.5, ymin = ymin.rect.NRSPO, ymax = ymax.rect.NRSPO, fill = 'white')+
annotate("rect", xmin = 1.5, xmax = 2.5, ymin = ymin.rect.NRSPO, ymax = ymax.rect.NRSPO, fill = mygrey)+
annotate("rect", xmin = 0.5, xmax = 1.5, ymin = ymin.rect.NRSPO, ymax = ymax.rect.NRSPO, fill = 'white')+
geom_boxplot(width = 0.5, outlier.size = 0.05, lwd = 0.2)
# Effect plots ----
# *** To run this part need to run the models in script 4.2 ***
fm1 <- m.glmm.disease # store whatever model I want to use in fm1 variable and use this in code below
newdat <- expand.grid( # Make a new dataframe for predictions
NR=seq(0.38, 0.94, 0.01), # Make range of NR within range of observed values
NRSPO = mean(dat.rescaled$NRSPO), # condition on typical (i.e. mean) value of NRSPO
caseControl = NA
)
newdat$caseControl <- predict(fm1,newdat,re.form=NA) # Make predictions
plot(newdat$caseControl~ newdat$NR, type = 'l', ylim = c(-4, 1)) # Ok, what I get corresponds to what allEffect() wrapper gives
plot(allEffects(fm1), type = 'link')
# Ok now doing this manually (following Ben Bolkers tutorial on it) to customise plot
mm <- model.matrix(terms(fm1),newdat)
## or newdat$distance <- mm %*% fixef(fm1)
pvar1 <- diag(mm %*% tcrossprod(vcov(fm1),mm)) # Thus is to produce CI based on fixed-effects uncertainty ONLY
tvar1 <- pvar1+VarCorr(fm1)$disease_type[1]+VarCorr(fm1)$disease_type[5]+VarCorr(fm1)$disease_type[9] # This adds the variance of random effects. Adapted from Ben Bolker's code but here for more complex model. Because we let the model estimate variance in intercept, NR slope and NRSPO slope with disease_type, we must add those three sources of variance.
cmult <- 1.96 ## could use 1.96
newdat <- data.frame(
newdat
, plo = newdat$caseControl-cmult*sqrt(pvar1)
, phi = newdat$caseControl+cmult*sqrt(pvar1)
, tlo = newdat$caseControl-cmult*sqrt(tvar1)
, thi = newdat$caseControl+cmult*sqrt(tvar1)
)
#plot confidence
g0 <- ggplot(newdat, aes(x=NR, y=plogis(caseControl)))+geom_point()
g0 + geom_pointrange(aes(ymin = plogis(plo), ymax = plogis(phi)))+
labs(title="CI based on fixed-effects uncertainty ONLY")
#plot prediction
g0 + geom_pointrange(aes(ymin = plogis(tlo), ymax = plogis(thi)))+
labs(title="CI based on FE uncertainty + RE variance")
plot(allEffects(fm1), type = 'response') # ok, what I get manually looks similar to what allEffects() wrapper gives
funFormat<- function(x, digits){ifelse(x<0.01,
formatC(x, digit = digits, format = 'e'),
formatC(x, digit = digits, format = 'f'))}
out.fix.format<- summary(m.glmm.disease)[[10]] %>%
as.data.frame() %>%
add_rownames('Effect') %>%
as.data.frame() %>%
mutate_if(is.numeric, funs(funFormat(., 2)))
b1 = out.fix.format[2,2]
pvalb1 = out.fix.format[2,5]
p.predict.NR<- ggplot(newdat, aes(x=NR, y=plogis(caseControl)))+
#geom_segment(data = dat.rescaled, aes(x = NR, xend = NR, y = 0, yend = 0.02))+
geom_segment(data = dat.rescaled[dat.rescaled$caseControl == '0',], aes(x = NR, xend = NR, y = 0, yend = 0.02), alpha = .2, col = 'firebrick')+
geom_segment(data = dat.rescaled[dat.rescaled$caseControl == '1',], aes(x = NR, xend = NR, y = 0.02, yend = 0.04), alpha = .2, col = 'dodgerblue')+
geom_ribbon(aes(NR, ymin = plogis(plo), ymax = plogis(phi)), fill = 'lightgrey')+
geom_line()+
ylab('Probability of healthy')+xlab('Mean gut relatedness')+
theme_bw()+
theme(axis.title = element_text(size = 6),
axis.text = element_text(size = 5),
panel.grid = element_blank(),
#legend.position = 'top', #c(0.9, 0.1),
legend.key.size = unit(0.3, "cm"),
legend.text = element_text(size = 3),
legend.title = element_blank(),
panel.border = element_blank(),
axis.line = element_line(size = 0.3))+
annotate('text', x = 0.4, y = 0.75, label = paste0('slope = ', b1, ', pval = ', pvalb1, '***'), size = 1.8, hjust = 0)+
ylim(c(0,0.75))
p.predict.NR
# Let's do the same for NRSPO now
newdat.2 <- expand.grid( # Make a new dataframe for predictions
NRSPO=seq(0.08, 0.5, 0.01), # Make range of NRSPO within range of observed values
NR = mean(dat.rescaled$NR), # condition on typical (i.e. mean) value of NR
caseControl = NA
)
newdat.2$caseControl <- predict(fm1,newdat.2,re.form=NA) # Make predictions
plot(newdat.2$caseControl~ newdat.2$NRSPO, type = 'l', ylim = c(-2, 0.5)) # Ok, what I get corresponds to what allEffect() wrapper gives
plot(allEffects(fm1), type = 'link')
mm.2 <- model.matrix(terms(fm1),newdat.2)
## or newdat$distance <- mm %*% fixef(fm1)
pvar1.2 <- diag(mm.2 %*% tcrossprod(vcov(fm1),mm.2)) # Thus is to produce CI based on fixed-effects uncertainty ONLY
tvar1.2 <- pvar1.2+VarCorr(fm1)$disease_type[1]+VarCorr(fm1)$disease_type[5]+VarCorr(fm1)$disease_type[9] # This adds the variance of random effects. Adapted from Ben Bolker's code but here for more complex model. Because we let the model estimate variance in intercept, NR slope and NRSPO slope with disease_type, we must add those three sources of variance.
cmult <- 1.96 ## could use 1.96
newdat.2 <- data.frame(
newdat.2
, plo = newdat.2$caseControl-cmult*sqrt(pvar1.2)
, phi = newdat.2$caseControl+cmult*sqrt(pvar1.2)
, tlo = newdat.2$caseControl-cmult*sqrt(tvar1.2)
, thi = newdat.2$caseControl+cmult*sqrt(tvar1.2)
)
#plot confidence
g0 <- ggplot(newdat.2, aes(x=NRSPO, y=plogis(caseControl)))+geom_point()
g0 + geom_pointrange(aes(ymin = plogis(plo), ymax = plogis(phi)))+
labs(title="CI based on fixed-effects uncertainty ONLY")
#plot prediction
g0 + geom_pointrange(aes(ymin = plogis(tlo), ymax = plogis(thi)))+
labs(title="CI based on FE uncertainty + RE variance")
plot(allEffects(fm1), type = 'response') # ok, what I get manually looks similar to what allEffects() wrapper gives
out.fix.format<- summary(m.glmm.disease)[[10]] %>%
as.data.frame() %>%
add_rownames('Effect') %>%
as.data.frame()
b1 = round(out.fix.format[3,2],2)
pvalb1 = round(out.fix.format[3,5],2)
p.predict.NRSPO<- ggplot(newdat.2, aes(x=NRSPO, y=plogis(caseControl)))+
#geom_segment(data = dat.rescaled, aes(x = NRSPO, xend = NRSPO, y = 0.1, yend = 0.116), alpha = .2)+
geom_segment(data = dat.rescaled[dat.rescaled$caseControl == '0',], aes(x = NRSPO, xend = NRSPO, y = 0, yend = 0.02), alpha = .2, col = 'firebrick')+
geom_segment(data = dat.rescaled[dat.rescaled$caseControl == '1',], aes(x = NRSPO, xend = NRSPO, y = 0.02, yend = 0.04), alpha = .2, col = 'dodgerblue')+
geom_ribbon(aes(NRSPO, ymin = plogis(plo), ymax = plogis(phi)), fill = 'lightgrey')+
geom_line()+
ylab('Probability of healthy')+xlab('Relatedness weighed mean\nsporulation score')+
theme_bw()+
theme(axis.title = element_text(size = 6),
axis.text = element_text(size = 5),
panel.grid = element_blank(),
#legend.position = 'top', #c(0.9, 0.1),
legend.key.size = unit(0.3, "cm"),
legend.text = element_text(size = 3),
legend.title = element_blank(),
panel.border = element_blank(),
axis.line = element_line(size = 0.3))+
annotate('text', x = 0.1, y = 0.62, label = paste0('slope = ', b1, ', pval = ', pvalb1), size = 1.8, hjust = 0)
p.predict.NRSPO
# Assemble ----
library(patchwork)
#pdf('./output/figures/Figure2_microbiome.pdf', width = 16/2.55, height = 13/2.55)
#(p.NR | p.NRSPO | (p.all.NR|p.all.NRSPO)/p.predict.NR / p.predict.NRSPO) +
# plot_annotation(tag_levels = 'A') &
# theme(plot.tag = element_text(size = 7, face = 'bold'))
#dev.off()
pdf('./output/figures/Figure2_microbiome.pdf', width = 14/2.55, height = 11.5/2.55)
(p.NR | p.NRSPO | (p.predict.NR / p.predict.NRSPO/plot_spacer())) +
plot_annotation(tag_levels = 'A') &
theme(plot.tag = element_text(size = 7, face = 'bold'))
dev.off()
library(cowplot)
leg<- get_legend(
p.NR+
theme(legend.position = 'right',
legend.text = element_text(size = 7),
legend.key.size = unit(0.5, "cm"))+
scale_fill_manual(values = c('firebrick', 'dodgerblue'),
labels = c('case (sick)', 'control (healthy)'))
)
pdf('./output/figures/legend_microbiomePlot.pdf', width = 3/2.55, height = 1.8/2.55)
plot(leg)
dev.off()
# AUC (cvAUC package analysis) ----
library(pROC)
library(caret)
library(metRology)
# USING cvAUC PACKAGE, WITH FUNCTION ci.cvAUC() TO COMPUTE A CONFIDENCE INTERVAL ON THE AUC
# Package has a useful documentation page to understand exactly what they are doing:
# https://www.rdocumentation.org/packages/cvAUC/versions/1.1.0/topics/ci.cvAUC
# What they do is:
# 1) define the folds (as in: select the row ids to be used in each fold). Ideal is to stratify the folds by outcome, to keep balance of 1/0 cases in each fold
# 2) fit the model on all folds but one
# 3) using that model fit, predict values in the left-out fold, on response scale
# do for each fold in turn
# then in the ci.cvAUC() function:
# predictions is the vector of all predictions, on response scale (probability)
# label is the true observed value (on 1/0 scale)
# fold is the list of row ids for each fold
# Let's use their demo code wrappers. Works for any dataset as long as
# input dataset has a first 'Y' variables of 1/0 outcome
# other variables are those to use in the model
# so if want only 'NR', subset dataset to get only the Y and NR columns
# and of course everytime, subset to keep all or specific disease
# in the code wrapper below, utility functons to get the folds and train/test are defined within the code wrapper
# then the cross validated AUC is passed through ci.cvAUC() to get the mean AUC and confidence intervals
cvAUC_demoWrapper <- function(data, V=10){
.cvFolds <- function(Y, V){ #Create CV folds (stratify by outcome)
Y0 <- split(sample(which(Y==0)), rep(1:V, length=length(which(Y==0))))
Y1 <- split(sample(which(Y==1)), rep(1:V, length=length(which(Y==1))))
folds <- vector("list", length=V)
for (v in seq(V)) {folds[[v]] <- c(Y0[[v]], Y1[[v]])}
return(folds)
}
.doFit <- function(v, folds, data){ #Train/test glm for each fold
fit <- glm(Y~., data=data[-folds[[v]],], family=binomial)
pred <- predict(fit, newdata=data[folds[[v]],], type="response")
return(pred)
}
folds <- .cvFolds(Y=data$Y, V=V) #Create folds
predictions <- unlist(sapply(seq(V), .doFit, folds=folds, data=data)) #CV train/predict
predictions[unlist(folds)] <- predictions #Re-order pred values
# Get CV AUC and confidence interval
out <- ci.cvAUC(predictions=predictions, labels=data$Y, folds=folds, confidence=0.95)
return(out)
}
# data here must be dat.rescaled, which has the caseControl variable (0 = sick, 1 = healthy), and the disease_type variable which specific which disease the "cases" were
# in principle could modify the wrapper to select specific cohorts instead
# focal.predictor must be a vector of the predictors you want to use for the glm model fit
# focal.disease must be a vector of disease you want to subset the dataset for (it will select the cases and controls only from the studies focusing on those specific disease)
# V is number of folds to use for the k-fold cross validation, if set V = nrow(data), then that's a leave-one-out analysis
# Note: I'm setting set.seed(42) in the code wrapper, just before computing the folds
# that means that the output will be reproducible because that will reselect the same folds for a given dataset
# so when re-running the cvAUC (or running it with a different predictor), the folds are the same, so the AUC can be compared
# as in, the difference in AUC is NOT due to sampling, it's due to the different predictor
run.cvAUC_demoWrapper<- function(data, focal.predictor, focal.disease , V=10){
d.focal<- data[data$disease_type %in% focal.disease, c('caseControl', focal.predictor)] %>%
rename(Y = caseControl)
set.seed(42) # by setting the seed, the folds selection will be the same. MUST set it everytime running the AUCcv for a different predictor, so that the AUC computed are comparable, i.e. computed over the same data split
out<- cvAUC_demoWrapper(d.focal, V = V)
out.df<- data.frame(predictor = paste(focal.predictor, collapse = '_'),
disease = paste(focal.disease, collapse = '_'),
cvAUC = out$cvAUC,
se = out$se,
ci.low = out$ci[1],
ci.up = out$ci[2])
return(out.df)
}
# example
run.cvAUC_demoWrapper(dat.rescaled, c('NR', 'NRSPO'), 'MetS', V = 10)
# Ok, now, just have to run it for each of my four predictors (NR/NRSPO, or Shannon, invSimpson, Richness)
# And for each disease as well as all diseases together
# that's 44 runs
unique(dat.rescaled$disease_type) # 10 diseases
(10*4)+4
ls.diseases<- as.list(unique(dat.rescaled$disease_type))
ls.diseases[[11]]<- unique(dat.rescaled$disease_type)
ls.predictors<- as.list(c('NR', 'Shannon', 'invSimpson', 'Richness'))
#ls.predictors[[5]]<- c('NR', 'NRSPO')
ls.cvAUC.out<- list()
counter = 0
for(i in 1:length(ls.diseases)){
for(j in 1:length(ls.predictors)){
counter = counter + 1
run.out<- run.cvAUC_demoWrapper(dat.rescaled, ls.predictors[[j]], ls.diseases[[i]], V = 10)
print(counter)
ls.cvAUC.out[[counter]] = run.out
}
}
ls.cvAUC.out<- do.call('rbind', ls.cvAUC.out)
ls.cvAUC.out$disease[ls.cvAUC.out$disease == 'CRC_HYPER_IBD_ACVD_LC_OBE_T2D_IGC_RA_BD_MetS']<- 'All diseases'
#ls.cvAUC.out<- ls.cvAUC.out[ls.cvAUC.out$predictor != 'NR_NRSPO',]
ls.cvAUC.out$disease<- factor(ls.cvAUC.out$disease,
levels = rev(c('All diseases', 'OBE', 'MetS', 'IBD', 'CRC', 'T2D_IGC', 'LC', 'ACVD', 'RA', 'HYPER', 'BD')))
# Add samples sizes under disease names on y-axis ticks
nsizes.diseases<- dat.rescaled %>%
group_by(disease_type, caseControl) %>%
summarise(n = n()) %>%
as.data.frame() %>%
ungroup() %>%
spread(key = caseControl, value = n) %>%
as.data.frame() %>%
rename(case = `0`,
control = `1`) %>%
rename(disease = disease_type)
nsizes.diseases<- rbind(nsizes.diseases,
data.frame(disease = 'All diseases',
case = table(dat.rescaled$caseControl)[[1]],
control = table(dat.rescaled$caseControl)[[2]]))
ls.cvAUC.out2<- left_join(ls.cvAUC.out, nsizes.diseases, by = 'disease')
ls.cvAUC.out2<- ls.cvAUC.out2 %>%
mutate(diseasePlot2 = paste0(disease, '\n(c:', case, ', h:', control, ')'))
ls.cvAUC.out2$diseasePlot2[ls.cvAUC.out2$diseasePlot2 == 'T2D_IGC\n(c:280, h:215)']<- "T2D & IGT\n(c:280, h:215)"
unique(ls.cvAUC.out2$diseasePlot2)
ls.cvAUC.out2$diseasePlot2<- factor(ls.cvAUC.out2$diseasePlot2,
levels = rev(c("All diseases\n(c:1750, h:1184)",
"OBE\n(c:234, h:180)",
"MetS\n(c:60, h:26)",
"IBD\n(c:196, h:108)",
"CRC\n(c:386, h:205)",
"T2D & IGT\n(c:280, h:215)",
"LC\n(c:118, h:111)",
"ACVD\n(c:214, h:169)",
"RA\n(c:88, h:89)",
"HYPER\n(c:155, h:41)",
"BD\n(c:19, h:40)")))
# by definition, a 10-fold will split it in 10, meaning 90% of data goes to training and 10% goes to testing set
# So by knowing the sample size of the cohorts, the size of train/test sets is known
# redefining predictors as factor to have them in right orders on plot
ls.cvAUC.out2$predictor[ls.cvAUC.out2$predictor == 'NR']<- 'Mean Relatedness'
ls.cvAUC.out2$predictor<- factor(ls.cvAUC.out2$predictor,
levels = rev(c('Mean Relatedness', 'Shannon', 'invSimpson', 'Richness')))
# Setting pallette for background coloring area
pal<- c(piratepal('basel', trans = 0.4), piratepal('pony', trans = .5)[9], piratepal('info2', trans = .5)[14])
# Redfining that 'pal' palette with colors that do not rely on transparency settings (for correct pdf conversion)
cols<- NULL
for(i in 1:length(piratepal('basel'))){
cols<- c(cols, colorRampPalette(c("white", piratepal('basel')[i]))(10)[3])
}
cols<- c(cols, colorRampPalette(c("white", piratepal('pony')[9]))(10)[3])
cols<- c(cols, colorRampPalette(c("white", piratepal('info2')[14]))(10)[3])
pal<- cols
brewer.pal(9, 'BrBG')[9] # seablue
brewer.pal(2, 'BrBG')[2] # marron
brewer.pal(10, 'Paired')[10] # purple
brewer.pal(5, 'Paired')[5] # salmon
# plot it
p.auc<- ggplot(ls.cvAUC.out2, aes(x = cvAUC, y = diseasePlot2, col = predictor, xmin = ci.low, xmax = ci.up))+
geom_point(position = position_dodge(.8))+
geom_errorbarh(position = position_dodge(.8), height = 0.2)+
#scale_color_manual(values = rev(c('darkred','firebrick', 'dodgerblue', 'purple', 'goldenrod')))+
scale_color_manual(values = rev(c(brewer.pal(9, 'BrBG')[9], # seablue
brewer.pal(7, 'Accent')[7], # marron
brewer.pal(10, 'Paired')[10], # purple
brewer.pal(5, 'Paired')[5])))+ # salmon
#annotate("rect", ymin = 0.5, ymax = 1.5, xmin = -Inf, xmax = +Inf,fill = pal[12])+
#annotate("rect", ymin = 1.5, ymax = 2.5, xmin = -Inf, xmax = +Inf,fill = pal[7])+
#annotate("rect", ymin = 2.5, ymax = 3.5, xmin = -Inf, xmax = +Inf,fill = pal[10])+
#annotate("rect", ymin = 3.5, ymax = 4.5, xmin = -Inf, xmax = +Inf,fill = pal[9])+
#annotate("rect", ymin = 4.5, ymax = 5.5, xmin = -Inf, xmax = +Inf,fill = pal[8])+
#annotate("rect", ymin = 5.5, ymax = 6.5, xmin = -Inf, xmax = +Inf,fill = pal[11])+
#annotate("rect", ymin = 6.5, ymax = 7.5, xmin = -Inf, xmax = +Inf,fill = pal[5])+
#annotate("rect", ymin = 7.5, ymax = 8.5, xmin = -Inf, xmax = +Inf,fill = pal[3])+
#annotate("rect", ymin = 8.5, ymax = 9.5, xmin = -Inf, xmax = +Inf,fill = pal[2])+
#annotate("rect", ymin = 9.5, ymax = 10.5, xmin = -Inf, xmax = +Inf,fill = pal[1])+
#annotate("rect", ymin = 10.5, ymax = 11.5, xmin = -Inf, xmax = +Inf,fill = 'white', colour = 'black')+
# for grey/white shaded background
annotate("rect", ymin = 0.5, ymax = 1.5, xmin = -Inf, xmax = +Inf,fill = 'white')+
annotate("rect", ymin = 1.5, ymax = 2.5, xmin = -Inf, xmax = +Inf,fill = mygrey)+
annotate("rect", ymin = 2.5, ymax = 3.5, xmin = -Inf, xmax = +Inf,fill = 'white')+
annotate("rect", ymin = 3.5, ymax = 4.5, xmin = -Inf, xmax = +Inf,fill = mygrey)+
annotate("rect", ymin = 4.5, ymax = 5.5, xmin = -Inf, xmax = +Inf,fill = 'white')+
annotate("rect", ymin = 5.5, ymax = 6.5, xmin = -Inf, xmax = +Inf,fill = mygrey)+
annotate("rect", ymin = 6.5, ymax = 7.5, xmin = -Inf, xmax = +Inf,fill = 'white')+
annotate("rect", ymin = 7.5, ymax = 8.5, xmin = -Inf, xmax = +Inf,fill = mygrey)+
annotate("rect", ymin = 8.5, ymax = 9.5, xmin = -Inf, xmax = +Inf,fill = 'white')+
annotate("rect", ymin = 9.5, ymax = 10.5, xmin = -Inf, xmax = +Inf,fill = mygrey)+
annotate("rect", ymin = 10.5, ymax = 11.5, xmin = -Inf, xmax = +Inf,fill = 'white', colour = 'black')+
geom_point(position = position_dodge(.8), size = 1)+
geom_errorbarh(position = position_dodge(.8), height = 0.3, size = 0.4)+
ylab('Disease')+xlab('AUC')+
theme_bw()+
geom_vline(xintercept = c(0.5, 0.7), linetype = 'dashed')+
theme(axis.title = element_text(size = 8),
axis.text = element_text(size = 6, colour = 'black'),
panel.grid = element_blank(),
legend.position = 'right',
legend.justification = 'top',
legend.key.size = unit(0.3, "cm"),
legend.text = element_text(size = 6),
legend.title = element_blank(),
panel.border = element_blank(),
axis.line = element_line(size = 0.4))
p.auc
pdf('./output/figures/Figure3_AUC_CrossValidation.pdf', width = 10/2.55, height = (15/2.55))
p.auc
dev.off()
# THEORY PLOT ----
r = seq(0, 1, 0.01)
v = seq(0, 1, 0.01)
b = -0.5
c = 1
v_effect = 1
df<- expand.grid(r, v, b, c) %>%
rename(r = Var1, v = Var2, b = Var3, c = Var4) %>%
mutate(x = r*((b+(v_effect*v))/(2*c)))
# Basic theory plot
p.map.theory<- ggplot(df, aes(x = v, y = r))+
geom_tile(aes(fill = x, col = x), size = 0.2)+
scale_fill_gradient2('Predicted effect\non host',low = 'firebrick', mid = 'white', high='dodgerblue', midpoint = 0)+
scale_colour_gradient2('Predicted effect\non host',low = 'firebrick', mid = 'white', high='dodgerblue', midpoint = 0)+
ylab('Relatedness')+xlab('Probability of vertical transmission')+
scale_y_continuous(expand = c(0, 0))+
scale_x_continuous(expand = c(0, 0))+
theme_bw()+
theme(axis.title = element_text(size = 6),
axis.text = element_text(size = 5),
axis.ticks = element_line(size = 0.2, color = 'black'),
panel.grid = element_line(size = 0.1),
legend.position = 'right', #c(0.9, 0.1),
legend.justification = 'top',
legend.key.size = unit(0.3, "cm"),
legend.text = element_text(size = 3),
legend.title = element_text(size = 4),
panel.border = element_blank(),
axis.line = element_line(size = 0.3))
p.map.theory
# Plot of observed data
r.df<- read.table('./data/relatedness_sporulation.txt', header = TRUE, sep = '\t')
p.map.obs<- ggplot(r.df, aes(x = (1-sporulation_score), y = mean_relatedness))+
geom_point(size = 0.3)+
#geom_tile(aes(fill = x))+
#scale_fill_gradient2('Predicted effect\non host',low = 'firebrick', mid = 'white', high='springgreen4', midpoint = 0)+
ylab('Relatedness estimates')+xlab('(1 - sporulation score)')+
#scale_y_continuous(expand = c(0, 0))+
#scale_x_continuous(expand = c(0, 0))+
theme_bw()+
theme(axis.title = element_text(size = 6),
axis.text = element_text(size = 5),
axis.ticks = element_line(size = 0.2, color = 'black'),
panel.grid = element_blank(),
legend.position = 'right', #c(0.9, 0.1),
legend.justification = 'top',
legend.key.size = unit(0.3, "cm"),
legend.text = element_text(size = 3),
legend.title = element_text(size = 4),
panel.border = element_blank(),
axis.line = element_line(size = 0.3))
library(patchwork)
# adding different colors to point for better plotting
keep<- c("Ruminococcus_bromii_62047",
"Clostridium_sp_61482",
"Eubacterium_eligens_61678",
"Guyana_massiliensis_60772",
"Faecalibacterium_prausnitzii_61481",
"Roseburia_intestinalis_56239",
"Coprococcus_comes_61587",
"Dorea_longicatena_61473",
"Lachnospiraceae_bacterium_56833",
"Erysipelotrichaceae_bacterium_55770",
"Escherichia_coli_58110",
"Akkermansia_muciniphila_55290",
"Bacteroides_intestinalis_61596",
"Alistipes_onderdonkii_55464",
"Bacteroides_finegoldii_57739",
"Parabacteroides_goldsteinii_56831",
"Parabacteroides_merdae_56972",
"Bacteroides_fragilis_54507",
"Odoribacter_laneus_62216",
"Acidaminococcus_intestini_54097",
"Clostridium_leptum_61499")
r.df$cat<- 'a'
r.df[which(r.df$species_id%in% keep),'cat']<- 'b'
r.df$names<- ''
r.df<- r.df %>% mutate(names = ifelse(species_id %in% keep, species_id, ''))
r.df$names<- gsub('_', ' ', substr(r.df$names,1,nchar(r.df$name)-6))
p.map.obs<- ggplot(r.df, aes(x = (1-sporulation_score), y = mean_relatedness, col = cat))+
geom_point(size = 0.3)+
#geom_tile(aes(fill = x))+
#scale_fill_gradient2('Predicted effect\non host',low = 'firebrick', mid = 'white', high='springgreen4', midpoint = 0)+
#geom_text(aes(label = names), size = 1)+
#geom_text_repel(aes(label = names), box.padding = unit(0.1, 'line'), segment.colour = 'black', size = 0.9, segment.size = 0.5)+
ylab('Relatedness estimates')+xlab('(1 - sporulation score)')+
scale_color_manual(values = c('darkgrey', 'black'))+
theme_bw()+
theme(axis.title = element_text(size = 6),
axis.text = element_text(size = 5),
axis.ticks = element_line(size = 0.2, color = 'black'),
panel.grid = element_blank(),
legend.position = 'none', #c(0.9, 0.1),
legend.justification = 'top',
legend.key.size = unit(0.3, "cm"),
legend.text = element_text(size = 3),
legend.title = element_text(size = 4),
panel.border = element_blank(),
axis.line = element_line(size = 0.3))
pdf('./output/figures/Figure1_heatmap.pdf', width = 12/2.55, height = 5/2.55)
(p.map.theory | p.map.obs) +
plot_annotation(tag_levels = 'A') &
theme(plot.tag = element_text(size = 7, face = 'bold'))
dev.off()
# Version with all names on plot
p.heatmap.obs.names<- ggplot(r.df, aes(x = (1-sporulation_score), y = mean_relatedness, label = species_id))+
#geom_point(size = 0.1)+
#geom_text_repel(aes(label = species_id), box.padding = unit(0.1, 'line'), fontface = 'bold', segment.colour = 'black', size = 1.5, segment.size = 0.2)+
geom_text_repel(aes(label = species_id), box.padding = unit(0.1, 'line'), segment.colour = 'black', size = 1.3, segment.size = 0.2)+
#geom_tile(aes(fill = x))+
#scale_fill_gradient2('Predicted effect\non host',low = 'firebrick', mid = 'white', high='springgreen4', midpoint = 0)+
ylab('Relatedness')+xlab('(1 - sporulation score)')+
#scale_y_continuous(expand = c(0, 0))+
#scale_x_continuous(expand = c(0, 0))+
#scale_color_manual(values = rep('black', nrow(r.df)))+
theme_bw()+
theme(axis.title = element_text(face = 'bold', size = 9),
axis.text = element_text(size = 9, color = 'black'),
axis.ticks = element_line(size = 0.6, color = 'black'),
panel.grid = element_blank(),
legend.position = 'right', #c(0.9, 0.1),
legend.justification = 'top',
legend.key.size = unit(0.3, "cm"),
legend.text = element_text(size = 3),
legend.title = element_text(size = 4),
panel.border = element_blank(),
axis.line = element_line(size = 0.6))
#library(ggplot2)
#library(plotly)
#library(gapminder)
#install.packages('plotly') # if you haven't installed the package
#library(plotly)
#py <- plotly(username="r_user_guide", key="mw5isa4yqp")
#ggplotly(p.heatmap.obs.names)
#py$ggplotly(p.heatmap.obs.names)
#l <- plotly::ggplotly(p.heatmap.obs.names)
#htmlwidgets::saveWidget(l, file = "./output/figures/index.html")
pdf('./output/figures/Supp_heatmap_names.pdf', width = 15/2.55, height = 20/2.55)
p.heatmap.obs.names
dev.off()
# Map species on theory plot & other versions
r.df<- read.table('./data/relatedness_sporulation.txt', header = TRUE, sep = '\t')
r.df$revSporulation<- 1- r.df$sporulation_score
r.df$spoRescaled = 0.01 + ((0.99 - 0.01) / (max(r.df$revSporulation) - min(r.df$revSporulation))) * (r.df$revSporulation - min(r.df$revSporulation))
p.map.theory+
geom_point(data = r.df, aes(x = revSporulation, y = mean_relatedness))#+
#geom_text_repel(data = r.df, aes(x = spoRescaled, y = mean_relatedness, label = species_id), box.padding = unit(0.45, 'line'), fontface = 'bold', segment.colour = 'black')
ggplot(r.df, aes(x = revSporulation, y = mean_relatedness))+
geom_point()
#geom_text_repel(data = r.df, aes(x = spoRescaled, y = mean_relatedness, label = species_id), box.padding = unit(0.45, 'line'), fontface = 'bold', segment.colour = 'black')
leg <- get_legend(p.hm.leg) # library(ggpubr)
p.legend<- as_ggplot(leg)
p.legend
p.fan.theory<- ggplot(df, aes(x = r, y = x, col = v))+
geom_point()+
scale_color_gradient2(low = 'firebrick', mid = 'white', high='springgreen4', midpoint = 0.5)+
geom_point(data = r.df, aes(x = mean_relatedness, y = pred_x), col = 'black')+
geom_text_repel(data = r.df[r.df$species_id %in% keep,], aes(x = mean_relatedness, y = pred_x, label = species_id), box.padding = unit(0.45, 'line'), fontface = 'bold', segment.colour = 'black', col = 'black')
p.fan.theory
# MCMC general MMMC model ----
# Not included in MS. Another possible approach to analyse the data, using Multimembership model.
load('./output/stats_runs/data_preps_23062021.RData')
mf = 100
prior.1<-list(R=list(V=1, fix=1),
G=list(G1=list(V=1, nu=1, alpha.mu=0, alpha.V=100),
G2=list(V=1, nu=1, alpha.mu=0, alpha.V=100)))
m_1<-MCMCglmm(caseControl~NR,
random=~idv(prob)+idv(probr),
data=dat.rescaled,
family="threshold",
prior=prior.1,
nitt = 13000*mf,
thin = 10*mf,burnin=3000*mf)
summary(m_2)
prior.2<-list(R=list(V=1, fix=1),
G=list(G1=list(V=1, nu=1, alpha.mu=0, alpha.V=100)))
m_2<-MCMCglmm(caseControl~NR,
random=~idv(prob),
data=dat.rescaled,
family="threshold",
prior=prior.2,
nitt = 13000*mf,
thin = 10*mf,burnin=3000*mf)
save.image('./output/stats_runs/MMMC_HM2_run_July2021.RData')
# ARCHIVED CODE ----
# [deprecated] AllData boxplots ----
p.all.NR<- ggplot(dat.rescaled, aes(x = as.factor(caseControl), y = NR, fill = as.factor(caseControl)))+
geom_boxplot(width = 0.5, outlier.size = 0.1, lwd = 0.3)+
ylab('Mean gut relatedness')+xlab('')+
scale_fill_manual(values = c('lightgrey', 'white'))+
scale_x_discrete(labels = c('Sick', 'Healthy'))+
theme_bw()+
theme(axis.title = element_text(size = 6),
axis.text = element_text(size = 5),
axis.text.x = element_text(size = 5, angle = 45, hjust = 1), panel.grid = element_line(size = 0.1),
legend.position = 'none', #c(0.9, 0.1),
legend.key.size = unit(0.3, "cm"),
legend.text = element_text(size = 3),
legend.title = element_blank(),
panel.border = element_blank(),
axis.line = element_line(size = 0.3))
p.all.NRSPO<- ggplot(dat.rescaled, aes(x = as.factor(caseControl), y = NRSPO, fill = as.factor(caseControl)))+
geom_boxplot(width = 0.5, outlier.size = 0.1, lwd = 0.3)+
ylab('Relatedness weighed mean\nsporulation score')+xlab('')+
scale_x_discrete(labels = c('Sick', 'Healthy'))+
scale_fill_manual(values = c('lightgrey', 'white'))+
theme_bw()+
theme(axis.title = element_text(size = 6),
axis.text = element_text(size = 5),
axis.text.x = element_text(size = 5, angle = 45, hjust = 1),
panel.grid = element_line(size = 0.1),
legend.position = 'none', #c(0.9, 0.1),
legend.key.size = unit(0.3, "cm"),
legend.text = element_text(size = 3),
legend.title = element_blank(),
panel.border = element_blank(),
axis.line = element_line(size = 0.3))
# [deprecated] ROC/AUC analysis ----
library(pROC)
library(caret)
library(metRology)
# Using caret package to run cross-validation analysis
# Example to see how it works
# Code wrapper to run the cross validation
rocCV<- function(data, nb.k, reps, focal.disease, focal.predictor){
# Defining the cross validation algorithm parameters
fit.control <- trainControl(method = "repeatedcv", # repeated k-fold validation
number = nb.k, repeats = reps, # use: 10 folds, repeat: 10 times
summaryFunction = twoClassSummary, classProbs = TRUE) # Use AUC summary stat
#fit.control <- trainControl(method = "LOOCV", # for leave-one-out analysis
# summaryFunction = twoClassSummary, classProbs = TRUE)
d2<- data %>%
filter(disease_type %in% focal.disease) %>%
select(caseControl, NR, Shannon, invSimpson, Richness) %>%
rename(focal.predictor = focal.predictor)
d2$caseControl<- ifelse(d2$caseControl == 0, 'sick', 'healthy')
set.seed(42)
fit<- train(caseControl ~ focal.predictor, data = d2, method = "glm", family = "binomial", trControl = fit.control)
#fit$results # ROC corresponds to mean(fit$resample[,'ROC]), and ROCSD = sd(fit$resample[,'ROC])
return(fit)
}
# run it
out<- rocCV(dat.rescaled, 10, 10, 'MetS', 'NR')
out$results # ROC = 0.53, ROCSD = 0.2328
mean(out$resample[,'ROC']) # this is an emprical sampling distribution of the AUC
sd(out$resample[,'ROC']) # and this is the standard deviation of the sampling distribution of our mean estimate of the AUC, i.e.the standard error
# then taking the 0.025 and 97.5 percentiles of this empirical distribution gives as the confidence interval
# So as far as I understand, the k-fold cross validation is a way to obtain a mean estimate of the AUC
# and the vector of AUC obtained from each fold/repeat sample of the data is essentially an empirical sampling distribution
# So the standard deviation of that is the standard error of the mean AUC
# and the percentiles of that is the confidence interval.
# Here the CI would be ~ 1.96*0.2328 = 0.456, so the mean AUC would be [0.074-0.986]
quantile(out$resample[,'ROC'], c(0.025, 0.975))
mean(out$resample[,'ROC'])-(1.96*sd(out$resample[,'ROC']))
mean(out$resample[,'ROC'])+(1.96*sd(out$resample[,'ROC']))
# Ok so don't find exactly the same, probably because the exact normal approximation here is not the best
# Like for certain case the t-distribution (= a slightly flattened) normal is better
#
qt.scaled(c(0.025, 0.975),
mean = mean(out$resample[,'ROC']),
sd = sd(out$resample[,'ROC']),
df = length(out$resample[,'ROC']))
# Yep, what I get there is similar to what I get with mean +/- 1.96 SD, but a tad different due to qt.scaled being a t distribution
# The empirical quantiles are a bit shifted towards lower estimates
# Quick sensitivity analysis test for k and reps values, see with MetS which is a small dataset
df.run.rocCV<- data.frame(nb.k = rep(seq(3,10,1), each = 4),
reps = rep(c(10, 50, 100, 1000), 8),
focal.disease = 'MetS',
ROC = NA,
ROCSD = NA)
for(i in 1:nrow(df.run.rocCV)){
print(i)
t<- rocCV(dat.rescaled, nb.k = df.run.rocCV$nb.k[i], reps = df.run.rocCV$reps[i], focal.disease = df.run.rocCV$focal.disease[i])$results[,c('ROC', 'ROCSD')]
df.run.rocCV$ROC[i] = t[,'ROC']
df.run.rocCV$ROCSD[i] = t[,'ROCSD']
}
# Not much effect, variance goes larger as k increases, which is expected
ggplot(df.run.rocCV, aes(x = nb.k, y = ROC, ymin = ROC-ROCSD, ymax = ROC+ROCSD, col = as.factor(reps)))+
geom_point(position = position_dodge(.8))+
geom_errorbar(position = position_dodge(.8), width = 0.2)+
scale_color_manual(values = c('red', 'dodgerblue', 'green', 'goldenrod'))
# actual run
# keep k = 10, reps = 1000
nb.k = 10
reps = 1000
df.run.rocCV.fin<- data.frame(nb.k = nb.k,
reps = reps,
focal.disease = unique(dat.rescaled$disease_type),
ROC = NA,
ROCSD = NA)
# Make dataframe smaller (faster run?)
d.clean = dat.rescaled %>%
select(caseControl, NR, Shannon, invSimpson, Richness, disease_type) %>%
mutate(caseControl = ifelse(caseControl == 0, 'sick', 'healthy'))
head(d.clean)
fit.control <- trainControl(method = "repeatedcv", number = nb.k, repeats = reps,
summaryFunction = twoClassSummary, classProbs = TRUE)
# re-define code wrappers to work with actual run
rocCV<- function(data, focal.predictor, focal.disease, trainControl){
data<- rename(data, focal.predictor = focal.predictor)
set.seed(42) # re-setting the seed everytime ensures that the dataset is split the same way when running the ROCcv for the different predictors
fit<- train(caseControl ~ focal.predictor, data = data[data$disease_type %in% focal.disease,], method = "glm", family = "binomial", trControl = trainControl)
d.out<- data.frame(disease = focal.disease,
predictor = focal.predictor,
ROC = fit$results[,'ROC'],
ROCSD = fit$results[,'ROCSD'],
mean.train.n = round(mean(lengths(fit$control$index)),0), # mean training set size
mean.test.n = round(mean(lengths(fit$control$indexOut)),0)) # mean test set size
return(list(d.out, fit))
}
rocCV.severalDiseases<- function(data, focal.predictor, focal.disease, disease.tag = 'several', trainControl){
data<- rename(data, focal.predictor = focal.predictor)
set.seed(42) # re-setting the seed everytime ensures that the dataset is split the same way when running the ROCcv for the different predictors
fit<- train(caseControl ~ focal.predictor, data = data[data$disease_type %in% focal.disease,], method = "glm", family = "binomial", trControl = trainControl)
d.out<- data.frame(disease = disease.tag,
predictor = focal.predictor,
ROC = fit$results[,'ROC'],
ROCSD = fit$results[,'ROCSD'],
mean.train.n = round(mean(lengths(fit$control$index)),0), # mean training set size
mean.test.n = round(mean(lengths(fit$control$indexOut)),0)) # mean test set size
return(list(d.out, fit))
}
preds = c('NR', 'Shannon', 'invSimpson', 'Richness') # four predictors to run the cross-validation over
dis = unique(d.clean$disease_type) # 19 diseases to run the cross validation over
# to store results
dfin<- data.frame(disease = character(),
predictor = character(),
ROC = numeric(),
ROCSD = numeric(),
mean.train.n = numeric(),
mean.test.n = numeric())
dfin.list<- vector('list')
# In the loop, redefine the set.seed() everytime ensures the same fold split is done for each test over each predictor
# can be verified when looking within $result output, can see the seeds of the out/in rows are the same
counter = 0
for(p in 1:length(preds)){
foc.predictor = preds[p]
for(d in 1:length(dis)){
counter = counter + 1
print(counter)
foc.disease = dis[d]
roc.cv<- rocCV(d.clean, focal.predictor = foc.predictor, focal.disease = foc.disease, trainControl = fit.control)
dfin<- rbind(dfin, roc.cv[[1]])
dfin.list[[counter]]<- roc.cv[[2]]$resample
}
}
# Finally, add the cross validation when pooling all diseases
roc.cv.all_NR<- rocCV.severalDiseases(d.clean, focal.predictor = 'NR', focal.disease = dis, disease.tag = 'All diseases', trainControl = fit.control)
roc.cv.all_Shannon<- rocCV.severalDiseases(d.clean, focal.predictor = 'Shannon', focal.disease = dis, disease.tag = 'All diseases', trainControl = fit.control)
roc.cv.all_invSimpson<- rocCV.severalDiseases(d.clean, focal.predictor = 'invSimpson', focal.disease = dis, disease.tag = 'All diseases', trainControl = fit.control)
roc.cv.all_Richness<- rocCV.severalDiseases(d.clean, focal.predictor = 'Richness', focal.disease = dis, disease.tag = 'All diseases', trainControl = fit.control)
dfin2<- rbind(dfin,
roc.cv.all_NR[[1]],
roc.cv.all_Shannon[[1]],
roc.cv.all_invSimpson[[1]],
roc.cv.all_Richness[[1]])
dfin.list2<- dfin.list
dfin.list2[[41]]<- roc.cv.all_NR[[2]]$resample
dfin.list2[[42]]<- roc.cv.all_Shannon[[2]]$resample
dfin.list2[[43]]<- roc.cv.all_invSimpson[[2]]$resample
dfin.list2[[44]]<- roc.cv.all_Richness[[2]]$resample
hist(dfin.list2[[11]][,'ROC'])
rm(dfin.list)
rm(dat.rescaled) # need only d.clean for the AUC analysis
rm(prob)
rm(prob.rescaled)
rm(roc.cv.all_invSimpson)
rm(roc.cv.all_NR)
rm(roc.cv.all_Richness)
rm(roc.cv.all_Shannon)
save.image('./output/stats_runs/AUC_crossValidation_runClean.RData')
load('./output/stats_runs/AUC_crossValidation_runClean.RData')
# looking at an example of resampling distribution
quantile(dfin.list2[[41]][,'ROC'], c(0.025, 0.975))
hist(dfin.list2[[41]][,'ROC'])
qt.scaled(c(0.025), mean = roc.cv.all_NR[[1]]$ROC, sd = roc.cv.all_NR[[1]]$ROCSD, df = 999)
qt.scaled(c(0.975), mean = roc.cv.all_NR[[1]]$ROC, sd = roc.cv.all_NR[[1]]$ROCSD, df = 999)
# Ok, those are super close, and the resampling distribution looks very well normal on this example
# so think should be fine, use the "empricial 95%CI", that is, the percentile distribution of the resampling distribution
# this way what this is is transparent
# Plot it
dfin2$disease<- factor(dfin2$disease,
levels = rev(c('All diseases', 'OBE', 'MetS', 'IBD', 'CRC', 'T2D_IGC', 'LC', 'ACVD', 'RA', 'HYPER', 'BD')))
dfin2$predictor[dfin2$predictor == 'NR']<- 'Mean Relatedness'
dfin2$predictor<- factor(dfin2$predictor,
levels = rev(c('Mean Relatedness', 'Shannon', 'invSimpson', 'Richness')))
dfin3<- dfin2
head(dfin3)
dfin3$cilower.t<- qt.scaled(c(0.025), mean = dfin3$ROC, sd = dfin3$ROCSD, df = 999)
dfin3$ciupper.t<- qt.scaled(c(0.975), mean = dfin3$ROC, sd = dfin3$ROCSD, df = 999)
getci.emp<- function(x){quantile(x[,'ROC'], c(0.025, 0.975))}
cis.emp<- as.data.frame(do.call('rbind', lapply(dfin.list2, getci.emp))) %>%
rename(cilower.emp = `2.5%`,
ciupper.emp = `97.5%`)
dfin3<- cbind(dfin3, cis.emp)
# Using percentile intervals of the resampling distribution rather than the qt.scaled quantiles
# because not 100% sure about the statistical property of the repeated k-fold resampling
# the percentile interval will be 100% clear and transparent about the method
# The two correlate so not worried about it anyway
plot(cilower.emp ~ cilower.t, data = dfin3)
# Add samples sizes under disease names on y-axis ticks
nsizes.diseases<- dat.rescaled %>%
group_by(disease_type, caseControl) %>%
summarise(n = n()) %>%
as.data.frame() %>%
ungroup() %>%
spread(key = caseControl, value = n) %>%
as.data.frame() %>%
rename(case = `0`,
control = `1`) %>%
rename(disease = disease_type)
nsizes.diseases<- rbind(nsizes.diseases,
data.frame(disease = 'All diseases',
case = table(dat.rescaled$caseControl)[[1]],
control = table(dat.rescaled$caseControl)[[2]]))
dfin3<- left_join(dfin3, nsizes.diseases, by = 'disease')
dfin3<- dfin3 %>%
mutate(diseasePlot2 = paste0(disease, '\n(sick:', case, ', healthy:', control, ')'))
dfin3$diseasePlot2[dfin3$diseasePlot2 == 'T2D_IGC\n(sick:280, healthy:215)']<- "T2D & IGT\n(sick:280, healthy:215)"
dfin3$diseasePlot2<- factor(dfin3$diseasePlot2,
levels = rev(c("All diseases\n(sick:1750, healthy:1184)",
"OBE\n(sick:234, healthy:180)",
"MetS\n(sick:60, healthy:26)",
"IBD\n(sick:196, healthy:108)",
"CRC\n(sick:386, healthy:205)",
"T2D & IGT\n(sick:280, healthy:215)",
"LC\n(sick:118, healthy:111)",
"ACVD\n(sick:214, healthy:169)",
"RA\n(sick:88, healthy:89)",
"HYPER\n(sick:155, healthy:41)",
"BD\n(sick:19, healthy:40)")))
# by definition, a 10-fold will split it in 10, meaning 90% of data goes to training and 10% goes to testing set
# So by knowing the sample size of the cohorts, the size of train/test sets is known
library(yarrr)
pal<- c(piratepal('basel', trans = 0.4), piratepal('pony', trans = .5)[9], piratepal('info2', trans = .5)[14])
# Plot
p.auc<- ggplot(dfin3, aes(x = ROC, y = diseasePlot2, col = predictor, xmin = cilower.emp, xmax = ciupper.emp))+
geom_point(position = position_dodge(.8))+
geom_errorbarh(position = position_dodge(.8), height = 0.2)+
scale_color_manual(values = rev(c('firebrick', 'dodgerblue', 'purple', 'goldenrod')))+
annotate("rect", ymin = 0.5, ymax = 1.5, xmin = -Inf, xmax = +Inf, alpha = .2,fill = pal[12])+
annotate("rect", ymin = 1.5, ymax = 2.5, xmin = -Inf, xmax = +Inf, alpha = .2,fill = pal[7])+
annotate("rect", ymin = 2.5, ymax = 3.5, xmin = -Inf, xmax = +Inf, alpha = .2,fill = pal[10])+
annotate("rect", ymin = 3.5, ymax = 4.5, xmin = -Inf, xmax = +Inf, alpha = .2,fill = pal[9])+
annotate("rect", ymin = 4.5, ymax = 5.5, xmin = -Inf, xmax = +Inf, alpha = .2,fill = pal[8])+
annotate("rect", ymin = 5.5, ymax = 6.5, xmin = -Inf, xmax = +Inf, alpha = .2,fill = pal[11])+
annotate("rect", ymin = 6.5, ymax = 7.5, xmin = -Inf, xmax = +Inf, alpha = .2,fill = pal[5])+
annotate("rect", ymin = 7.5, ymax = 8.5, xmin = -Inf, xmax = +Inf, alpha = .2,fill = pal[3])+
annotate("rect", ymin = 8.5, ymax = 9.5, xmin = -Inf, xmax = +Inf, alpha = .2,fill = pal[2])+
annotate("rect", ymin = 9.5, ymax = 10.5, xmin = -Inf, xmax = +Inf, alpha = .2,fill = pal[1])+
annotate("rect", ymin = 10.5, ymax = 11.5, xmin = -Inf, xmax = +Inf, alpha = .2,fill = 'white', colour = 'black')+
geom_point(position = position_dodge(.8))+
geom_errorbarh(position = position_dodge(.8), height = 0.3)+
ylab('Disease')+
theme_bw()+
geom_vline(xintercept = c(0.5, 0.7), linetype = 'dashed')+
theme(axis.title = element_text(size = 8),
axis.text = element_text(size = 6),
panel.grid = element_line(size = 0.1),
legend.position = 'right',
legend.justification = 'top',
legend.key.size = unit(0.3, "cm"),
legend.text = element_text(size = 6),
legend.title = element_blank(),
panel.border = element_blank(),
axis.line = element_line(size = 0.35))
p.auc
pdf('./output/figures/Figure3_AUC_CrossValidation.pdf', width = 10/2.55, height = (15/2.55))
p.auc
dev.off()
|
library(zoo)
### Name: make.par.list
### Title: Make a List from a Parameter Specification
### Aliases: make.par.list
### Keywords: ts
### ** Examples
make.par.list(letters[1:5], 1:5, 3, 5)
suppressWarnings( make.par.list(letters[1:5], 1:4, 3, 5, 99) )
make.par.list(letters[1:5], c(d=3), 3, 5, 99)
make.par.list(letters[1:5], list(d=1:2, 99), 3, 5)
make.par.list(letters[1:5], list(d=1:2, 99, 100), 3, 5)
| /data/genthat_extracted_code/zoo/examples/make.par.list.Rd.R | no_license | surayaaramli/typeRrh | R | false | false | 413 | r | library(zoo)
### Name: make.par.list
### Title: Make a List from a Parameter Specification
### Aliases: make.par.list
### Keywords: ts
### ** Examples
make.par.list(letters[1:5], 1:5, 3, 5)
suppressWarnings( make.par.list(letters[1:5], 1:4, 3, 5, 99) )
make.par.list(letters[1:5], c(d=3), 3, 5, 99)
make.par.list(letters[1:5], list(d=1:2, 99), 3, 5)
make.par.list(letters[1:5], list(d=1:2, 99, 100), 3, 5)
|
library(ggplot2)
df <- mtcars
pl <- ggplot(df,aes(x=wt,y=mpg))
#pl <- pl + geom_point(size=5,alpha=0.2,color='red',fill='pink' )
#pl <- pl + geom_point(aes(size=hp),color = 'red',alpha =0.2,fill = 'light pink' )
#pl <- pl + geom_point(aes(shape=factor(cyl),color = factor(cyl),size = hp),alpha = '0.4')
pl <- pl + geom_point(aes(shape=factor(cyl),color =hp),alpha = '0.4',size=5)
pl <- pl + scale_color_gradient(low='green',high ='red')
print(pl)
| /scatterplot.R | no_license | obaidM/Advance-R-programming-DataVisulization | R | false | false | 476 | r | library(ggplot2)
df <- mtcars
pl <- ggplot(df,aes(x=wt,y=mpg))
#pl <- pl + geom_point(size=5,alpha=0.2,color='red',fill='pink' )
#pl <- pl + geom_point(aes(size=hp),color = 'red',alpha =0.2,fill = 'light pink' )
#pl <- pl + geom_point(aes(shape=factor(cyl),color = factor(cyl),size = hp),alpha = '0.4')
pl <- pl + geom_point(aes(shape=factor(cyl),color =hp),alpha = '0.4',size=5)
pl <- pl + scale_color_gradient(low='green',high ='red')
print(pl)
|
## This code aims to save computation time by caching the inverse of
## a given matrix so that if it is required again, it does not need
## to be computed again, instead being retrieved directly from the
## cache.
## This function creates a special matrix object that can cache its
## inverse.
makeCacheMatrix <- function(x = matrix()) {
v <- NULL
set <- function(y) {
x <<- y
v <<- NULL
}
get <- function() x
setinv <- function(solve) v <<- solve
getinv <- function() v
list(set = set, get = get, setinv = setinv,
getinv = getinv)
}
## This function will compute the inverse of the special matrix
## object created above. If the inverse has already been calculated,
## then this function will retrieve it directly from the cache.
cacheSolve <- function(x, ...) {
## This code checks if the inverse has already been calculated
## and returns it if it has.
v <- x$getinv()
if(!is.null(v)){
print("Getting cached inverse...")
return(v)
}
## If no inverse has already been calculated, this code returns
## the inverse of the supplied matrix object.
data <- x$get()
m <- solve(data,...)
x$setinv(m)
m
} | /cachematrix.R | no_license | astefa/ProgrammingAssignment2 | R | false | false | 1,231 | r | ## This code aims to save computation time by caching the inverse of
## a given matrix so that if it is required again, it does not need
## to be computed again, instead being retrieved directly from the
## cache.
## This function creates a special matrix object that can cache its
## inverse.
makeCacheMatrix <- function(x = matrix()) {
v <- NULL
set <- function(y) {
x <<- y
v <<- NULL
}
get <- function() x
setinv <- function(solve) v <<- solve
getinv <- function() v
list(set = set, get = get, setinv = setinv,
getinv = getinv)
}
## This function will compute the inverse of the special matrix
## object created above. If the inverse has already been calculated,
## then this function will retrieve it directly from the cache.
cacheSolve <- function(x, ...) {
## This code checks if the inverse has already been calculated
## and returns it if it has.
v <- x$getinv()
if(!is.null(v)){
print("Getting cached inverse...")
return(v)
}
## If no inverse has already been calculated, this code returns
## the inverse of the supplied matrix object.
data <- x$get()
m <- solve(data,...)
x$setinv(m)
m
} |
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/F018.run.umap.R
\name{run.umap}
\alias{run.umap}
\title{Run UMAP on PCA Data (Computes a manifold approximation and projection)}
\usage{
run.umap(
x = NULL,
dims = 1:10,
n_neighbors = 15,
n_components = 2,
metric = "euclidean",
n_epochs = NULL,
learning_rate = 1,
scale = FALSE,
init = "spectral",
init_sdev = NULL,
spread = 1,
min_dist = 0.01,
set_op_mix_ratio = 1,
local_connectivity = 1,
bandwidth = 1,
repulsion_strength = 1,
negative_sample_rate = 5,
a = NULL,
b = NULL,
nn_method = NULL,
n_trees = 50,
search_k = 2 * n_neighbors * n_trees,
approx_pow = FALSE,
y = NULL,
target_n_neighbors = n_neighbors,
target_metric = "euclidean",
target_weight = 0.5,
pca = NULL,
pca_center = TRUE,
pcg_rand = TRUE,
fast_sgd = FALSE,
ret_model = FALSE,
ret_nn = FALSE,
n_threads = 1,
n_sgd_threads = 0,
grain_size = 1,
tmpdir = tempdir(),
verbose = getOption("verbose", TRUE)
)
}
\arguments{
\item{x}{An object of class iCellR.}
\item{dims}{PC dimentions to be used for UMAP analysis.}
\item{n_neighbors}{The size of local neighborhood (in terms of number of
neighboring sample points) used for manifold approximation. Larger values
result in more global views of the manifold, while smaller values result in
more local data being preserved. In general values should be in the range
\code{2} to \code{100}.}
\item{n_components}{The dimension of the space to embed into. This defaults
to \code{2} to provide easy visualization, but can reasonably be set to any
integer value in the range \code{2} to \code{100}.}
\item{metric}{Type of distance metric to use to find nearest neighbors. One
of:
\itemize{
\item \code{"euclidean"} (the default)
\item \code{"cosine"}
\item \code{"manhattan"}
\item \code{"hamming"}
\item \code{"categorical"} (see below)
}
Only applies if \code{nn_method = "annoy"} (for \code{nn_method = "fnn"}, the
distance metric is always "euclidean").
If \code{X} is a data frame or matrix, then multiple metrics can be
specified, by passing a list to this argument, where the name of each item in
the list is one of the metric names above. The value of each list item should
be a vector giving the names or integer ids of the columns to be included in
a calculation, e.g. \code{metric = list(euclidean = 1:4, manhattan = 5:10)}.
Each metric calculation results in a separate fuzzy simplicial set, which are
intersected together to produce the final set. Metric names can be repeated.
Because non-numeric columns are removed from the data frame, it is safer to
use column names than integer ids.
Factor columns can also be used by specifying the metric name
\code{"categorical"}. Factor columns are treated different from numeric
columns and although multiple factor columns can be specified in a vector,
each factor column specified is processed individually. If you specify
a non-factor column, it will be coerced to a factor.
For a given data block, you may override the \code{pca} and \code{pca_center}
arguments for that block, by providing a list with one unnamed item
containing the column names or ids, and then any of the \code{pca} or
\code{pca_center} overrides as named items, e.g. \code{metric =
list(euclidean = 1:4, manhattan = list(5:10, pca_center = FALSE))}. This
exists to allow mixed binary and real-valued data to be included and to have
PCA applied to both, but with centering applied only to the real-valued data
(it is typical not to apply centering to binary data before PCA is applied).}
\item{n_epochs}{Number of epochs to use during the optimization of the
embedded coordinates. By default, this value is set to \code{500} for datasets
containing 10,000 vertices or less, and \code{200} otherwise.}
\item{learning_rate}{Initial learning rate used in optimization of the
coordinates.}
\item{scale}{Scaling to apply to \code{X} if it is a data frame or matrix:
\itemize{
\item{\code{"none"} or \code{FALSE} or \code{NULL}} No scaling.
\item{\code{"Z"} or \code{"scale"} or \code{TRUE}} Scale each column to
zero mean and variance 1.
\item{\code{"maxabs"}} Center each column to mean 0, then divide each
element by the maximum absolute value over the entire matrix.
\item{\code{"range"}} Range scale the entire matrix, so the smallest
element is 0 and the largest is 1.
\item{\code{"colrange"}} Scale each column in the range (0,1).
}
For UMAP, the default is \code{"none"}.}
\item{init}{Type of initialization for the coordinates. Options are:
\itemize{
\item \code{"spectral"} Spectral embedding using the normalized Laplacian
of the fuzzy 1-skeleton, with Gaussian noise added.
\item \code{"normlaplacian"}. Spectral embedding using the normalized
Laplacian of the fuzzy 1-skeleton, without noise.
\item \code{"random"}. Coordinates assigned using a uniform random
distribution between -10 and 10.
\item \code{"lvrandom"}. Coordinates assigned using a Gaussian
distribution with standard deviation 1e-4, as used in LargeVis
(Tang et al., 2016) and t-SNE.
\item \code{"laplacian"}. Spectral embedding using the Laplacian Eigenmap
(Belkin and Niyogi, 2002).
\item \code{"pca"}. The first two principal components from PCA of
\code{X} if \code{X} is a data frame, and from a 2-dimensional classical
MDS if \code{X} is of class \code{"dist"}.
\item \code{"spca"}. Like \code{"pca"}, but each dimension is then scaled
so the standard deviation is 1e-4, to give a distribution similar to that
used in t-SNE. This is an alias for \code{init = "pca", init_sdev =
1e-4}.
\item \code{"agspectral"} An "approximate global" modification of
\code{"spectral"} which all edges in the graph to a value of 1, and then
sets a random number of edges (\code{negative_sample_rate} edges per
vertex) to 0.1, to approximate the effect of non-local affinities.
\item A matrix of initial coordinates.
}
For spectral initializations, (\code{"spectral"}, \code{"normlaplacian"},
\code{"laplacian"}), if more than one connected component is identified,
each connected component is initialized separately and the results are
merged. If \code{verbose = TRUE} the number of connected components are
logged to the console. The existence of multiple connected components
implies that a global view of the data cannot be attained with this
initialization. Either a PCA-based initialization or increasing the value of
\code{n_neighbors} may be more appropriate.}
\item{init_sdev}{If non-\code{NULL}, scales each dimension of the initialized
coordinates (including any user-supplied matrix) to this standard
deviation. By default no scaling is carried out, except when \code{init =
"spca"}, in which case the value is \code{0.0001}. Scaling the input may
help if the unscaled versions result in initial coordinates with large
inter-point distances or outliers. This usually results in small gradients
during optimization and very little progress being made to the layout.
Shrinking the initial embedding by rescaling can help under these
circumstances. Scaling the result of \code{init = "pca"} is usually
recommended and \code{init = "spca"} as an alias for \code{init = "pca",
init_sdev = 1e-4} but for the spectral initializations the scaled versions
usually aren't necessary unless you are using a large value of
\code{n_neighbors} (e.g. \code{n_neighbors = 150} or higher).}
\item{spread}{The effective scale of embedded points. In combination with
\code{min_dist}, this determines how clustered/clumped the embedded points
are.}
\item{min_dist}{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. The value should be
set relative to the \code{spread} value, which determines the scale at
which embedded points will be spread out.}
\item{set_op_mix_ratio}{Interpolate between (fuzzy) union and intersection as
the set operation used to combine local fuzzy simplicial sets to obtain a
global fuzzy simplicial sets. Both fuzzy set operations use the product
t-norm. The value of this parameter should be between \code{0.0} and
\code{1.0}; a value of \code{1.0} will use a pure fuzzy union, while
\code{0.0} will use a pure fuzzy intersection.}
\item{local_connectivity}{The local connectivity required -- i.e. the number
of nearest neighbors that should be assumed to be connected at a local
level. The higher this value the more connected the manifold becomes
locally. In practice this should be not more than the local intrinsic
dimension of the manifold.}
\item{bandwidth}{The effective bandwidth of the kernel if we view the
algorithm as similar to Laplacian Eigenmaps. Larger values induce more
connectivity and a more global view of the data, smaller values concentrate
more locally.}
\item{repulsion_strength}{Weighting applied to negative samples in low
dimensional embedding optimization. Values higher than one will result in
greater weight being given to negative samples.}
\item{negative_sample_rate}{The number of negative edge/1-simplex samples to
use per positive edge/1-simplex sample in optimizing the low dimensional
embedding.}
\item{a}{More specific parameters controlling the embedding. If \code{NULL}
these values are set automatically as determined by \code{min_dist} and
\code{spread}.}
\item{b}{More specific parameters controlling the embedding. If \code{NULL}
these values are set automatically as determined by \code{min_dist} and
\code{spread}.}
\item{nn_method}{Method for finding nearest neighbors. Options are:
\itemize{
\item \code{"fnn"}. Use exact nearest neighbors via the
\href{https://cran.r-project.org/package=FNN}{FNN} package.
\item \code{"annoy"} Use approximate nearest neighbors via the
\href{https://cran.r-project.org/package=RcppAnnoy}{RcppAnnoy} package.
}
By default, if \code{X} has less than 4,096 vertices, the exact nearest
neighbors are found. Otherwise, approximate nearest neighbors are used.
You may also pass precalculated nearest neighbor data to this argument. It
must be a list consisting of two elements:
\itemize{
\item \code{"idx"}. A \code{n_vertices x n_neighbors} matrix
containing the integer indexes of the nearest neighbors in \code{X}. Each
vertex is considered to be its own nearest neighbor, i.e.
\code{idx[, 1] == 1:n_vertices}.
\item \code{"dist"}. A \code{n_vertices x n_neighbors} matrix
containing the distances of the nearest neighbors.
}
Multiple nearest neighbor data (e.g. from two different precomputed
metrics) can be passed by passing a list containing the nearest neighbor
data lists as items.
The \code{n_neighbors} parameter is ignored when using precomputed
nearest neighbor data.}
\item{n_trees}{Number of trees to build when constructing the nearest
neighbor index. The more trees specified, the larger the index, but the
better the results. With \code{search_k}, determines the accuracy of the
Annoy nearest neighbor search. Only used if the \code{nn_method} is
\code{"annoy"}. Sensible values are between \code{10} to \code{100}.}
\item{search_k}{Number of nodes to search during the neighbor retrieval. The
larger k, the more the accurate results, but the longer the search takes.
With \code{n_trees}, determines the accuracy of the Annoy nearest neighbor
search. Only used if the \code{nn_method} is \code{"annoy"}.}
\item{approx_pow}{If \code{TRUE}, use an approximation to the power function
in the UMAP gradient, from
\url{https://martin.ankerl.com/2012/01/25/optimized-approximative-pow-in-c-and-cpp/}.}
\item{y}{Optional target data for supervised dimension reduction. Can be a
vector, matrix or data frame. Use the \code{target_metric} parameter to
specify the metrics to use, using the same syntax as \code{metric}. Usually
either a single numeric or factor column is used, but more complex formats
are possible. The following types are allowed:
\itemize{
\item Factor columns with the same length as \code{X}. \code{NA} is
allowed for any observation with an unknown level, in which case
UMAP operates as a form of semi-supervised learning. Each column is
treated separately.
\item Numeric data. \code{NA} is \emph{not} allowed in this case. Use the
parameter \code{target_n_neighbors} to set the number of neighbors used
with \code{y}. If unset, \code{n_neighbors} is used. Unlike factors,
numeric columns are grouped into one block unless \code{target_metric}
specifies otherwise. For example, if you wish columns \code{a} and
\code{b} to be treated separately, specify
\code{target_metric = list(euclidean = "a", euclidean = "b")}. Otherwise,
the data will be effectively treated as a matrix with two columns.
\item Nearest neighbor data, consisting of a list of two matrices,
\code{idx} and \code{dist}. These represent the precalculated nearest
neighbor indices and distances, respectively. This
is the same format as that expected for precalculated data in
\code{nn_method}. This format assumes that the underlying data was a
numeric vector. Any user-supplied value of the \code{target_n_neighbors}
parameter is ignored in this case, because the the number of columns in
the matrices is used for the value. Multiple nearest neighbor data using
different metrics can be supplied by passing a list of these lists.
}
Unlike \code{X}, all factor columns included in \code{y} are automatically
used.}
\item{target_n_neighbors}{Number of nearest neighbors to use to construct the
target simplicial set. Default value is \code{n_neighbors}. Applies only if
\code{y} is non-\code{NULL} and \code{numeric}.}
\item{target_metric}{The metric used to measure distance for \code{y} if
using supervised dimension reduction. Used only if \code{y} is numeric.}
\item{target_weight}{Weighting factor between data topology and target
topology. A value of 0.0 weights entirely on data, a value of 1.0 weights
entirely on target. The default of 0.5 balances the weighting equally
between data and target. Only applies if \code{y} is non-\code{NULL}.}
\item{pca}{If set to a positive integer value, reduce data to this number of
columns using PCA. Doesn't applied if the distance \code{metric} is
\code{"hamming"}, or the dimensions of the data is larger than the
number specified (i.e. number of rows and columns must be larger than the
value of this parameter). If you have > 100 columns in a data frame or
matrix, reducing the number of columns in this way may substantially
increase the performance of the nearest neighbor search at the cost of a
potential decrease in accuracy. In many t-SNE applications, a value of 50
is recommended, although there's no guarantee that this is appropriate for
all settings.}
\item{pca_center}{If \code{TRUE}, center the columns of \code{X} before
carrying out PCA. For binary data, it's recommended to set this to
\code{FALSE}.}
\item{pcg_rand}{If \code{TRUE}, use the PCG random number generator (O'Neill,
2014) during optimization. Otherwise, use the faster (but probably less
statistically good) Tausworthe "taus88" generator. The default is
\code{TRUE}.}
\item{fast_sgd}{If \code{TRUE}, then the following combination of parameters
is set: \code{pcg_rand = TRUE}, \code{n_sgd_threads = "auto"} and
\code{approx_pow = TRUE}. The default is \code{FALSE}. Setting this to
\code{TRUE} will speed up the stochastic optimization phase, but give a
potentially less accurate embedding, and which will not be exactly
reproducible even with a fixed seed. For visualization, \code{fast_sgd =
TRUE} will give perfectly good results. For more generic dimensionality
reduction, it's safer to leave \code{fast_sgd = FALSE}. If \code{fast_sgd =
TRUE}, then user-supplied values of \code{pcg_rand}, \code{n_sgd_threads},
and \code{approx_pow} are ignored.}
\item{ret_model}{If \code{TRUE}, then return extra data that can be used to
add new data to an existing embedding via \code{\link{umap_transform}}. The
embedded coordinates are returned as the list item \code{embedding}. If
\code{FALSE}, just return the coordinates. This parameter can be used in
conjunction with \code{ret_nn}. Note that some settings are incompatible
with the production of a UMAP model: external neighbor data (passed via a
list to \code{nn_method}), and factor columns that were included
via the \code{metric} parameter. In the latter case, the model produced is
based only on the numeric data. A transformation using new data is
possible, but the factor columns in the new data are ignored.}
\item{ret_nn}{If \code{TRUE}, then in addition to the embedding, also return
nearest neighbor data that can be used as input to \code{nn_method} to
avoid the overhead of repeatedly calculating the nearest neighbors when
manipulating unrelated parameters (e.g. \code{min_dist}, \code{n_epochs},
\code{init}). See the "Value" section for the names of the list items. If
\code{FALSE}, just return the coordinates. Note that the nearest neighbors
could be sensitive to data scaling, so be wary of reusing nearest neighbor
data if modifying the \code{scale} parameter. This parameter can be used in
conjunction with \code{ret_model}.}
\item{n_threads}{Number of threads to use.}
\item{n_sgd_threads}{Number of threads to use during stochastic gradient
descent. If set to > 1, then results will not be reproducible, even if
`set.seed` is called with a fixed seed before running. Set to
\code{"auto"} go use the same value as \code{n_threads}.}
\item{grain_size}{Minimum batch size for multithreading. If the number of
items to process in a thread falls below this number, then no threads will
be used. Used in conjunction with \code{n_threads} and
\code{n_sgd_threads}.}
\item{tmpdir}{Temporary directory to store nearest neighbor indexes during
nearest neighbor search. Default is \code{\link{tempdir}}. The index is
only written to disk if \code{n_threads > 1} and
\code{nn_method = "annoy"}; otherwise, this parameter is ignored.}
\item{verbose}{If \code{TRUE}, log details to the console.}
}
\value{
An object of class iCellR.
}
\description{
This function takes an object of class iCellR and runs UMAP on PCA data.
}
\examples{
demo.obj <- run.umap(demo.obj, dims = 1:10)
head(demo.obj@umap.data)
}
| /man/run.umap.Rd | no_license | Derming123/iCellR | R | false | true | 18,398 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/F018.run.umap.R
\name{run.umap}
\alias{run.umap}
\title{Run UMAP on PCA Data (Computes a manifold approximation and projection)}
\usage{
run.umap(
x = NULL,
dims = 1:10,
n_neighbors = 15,
n_components = 2,
metric = "euclidean",
n_epochs = NULL,
learning_rate = 1,
scale = FALSE,
init = "spectral",
init_sdev = NULL,
spread = 1,
min_dist = 0.01,
set_op_mix_ratio = 1,
local_connectivity = 1,
bandwidth = 1,
repulsion_strength = 1,
negative_sample_rate = 5,
a = NULL,
b = NULL,
nn_method = NULL,
n_trees = 50,
search_k = 2 * n_neighbors * n_trees,
approx_pow = FALSE,
y = NULL,
target_n_neighbors = n_neighbors,
target_metric = "euclidean",
target_weight = 0.5,
pca = NULL,
pca_center = TRUE,
pcg_rand = TRUE,
fast_sgd = FALSE,
ret_model = FALSE,
ret_nn = FALSE,
n_threads = 1,
n_sgd_threads = 0,
grain_size = 1,
tmpdir = tempdir(),
verbose = getOption("verbose", TRUE)
)
}
\arguments{
\item{x}{An object of class iCellR.}
\item{dims}{PC dimentions to be used for UMAP analysis.}
\item{n_neighbors}{The size of local neighborhood (in terms of number of
neighboring sample points) used for manifold approximation. Larger values
result in more global views of the manifold, while smaller values result in
more local data being preserved. In general values should be in the range
\code{2} to \code{100}.}
\item{n_components}{The dimension of the space to embed into. This defaults
to \code{2} to provide easy visualization, but can reasonably be set to any
integer value in the range \code{2} to \code{100}.}
\item{metric}{Type of distance metric to use to find nearest neighbors. One
of:
\itemize{
\item \code{"euclidean"} (the default)
\item \code{"cosine"}
\item \code{"manhattan"}
\item \code{"hamming"}
\item \code{"categorical"} (see below)
}
Only applies if \code{nn_method = "annoy"} (for \code{nn_method = "fnn"}, the
distance metric is always "euclidean").
If \code{X} is a data frame or matrix, then multiple metrics can be
specified, by passing a list to this argument, where the name of each item in
the list is one of the metric names above. The value of each list item should
be a vector giving the names or integer ids of the columns to be included in
a calculation, e.g. \code{metric = list(euclidean = 1:4, manhattan = 5:10)}.
Each metric calculation results in a separate fuzzy simplicial set, which are
intersected together to produce the final set. Metric names can be repeated.
Because non-numeric columns are removed from the data frame, it is safer to
use column names than integer ids.
Factor columns can also be used by specifying the metric name
\code{"categorical"}. Factor columns are treated different from numeric
columns and although multiple factor columns can be specified in a vector,
each factor column specified is processed individually. If you specify
a non-factor column, it will be coerced to a factor.
For a given data block, you may override the \code{pca} and \code{pca_center}
arguments for that block, by providing a list with one unnamed item
containing the column names or ids, and then any of the \code{pca} or
\code{pca_center} overrides as named items, e.g. \code{metric =
list(euclidean = 1:4, manhattan = list(5:10, pca_center = FALSE))}. This
exists to allow mixed binary and real-valued data to be included and to have
PCA applied to both, but with centering applied only to the real-valued data
(it is typical not to apply centering to binary data before PCA is applied).}
\item{n_epochs}{Number of epochs to use during the optimization of the
embedded coordinates. By default, this value is set to \code{500} for datasets
containing 10,000 vertices or less, and \code{200} otherwise.}
\item{learning_rate}{Initial learning rate used in optimization of the
coordinates.}
\item{scale}{Scaling to apply to \code{X} if it is a data frame or matrix:
\itemize{
\item{\code{"none"} or \code{FALSE} or \code{NULL}} No scaling.
\item{\code{"Z"} or \code{"scale"} or \code{TRUE}} Scale each column to
zero mean and variance 1.
\item{\code{"maxabs"}} Center each column to mean 0, then divide each
element by the maximum absolute value over the entire matrix.
\item{\code{"range"}} Range scale the entire matrix, so the smallest
element is 0 and the largest is 1.
\item{\code{"colrange"}} Scale each column in the range (0,1).
}
For UMAP, the default is \code{"none"}.}
\item{init}{Type of initialization for the coordinates. Options are:
\itemize{
\item \code{"spectral"} Spectral embedding using the normalized Laplacian
of the fuzzy 1-skeleton, with Gaussian noise added.
\item \code{"normlaplacian"}. Spectral embedding using the normalized
Laplacian of the fuzzy 1-skeleton, without noise.
\item \code{"random"}. Coordinates assigned using a uniform random
distribution between -10 and 10.
\item \code{"lvrandom"}. Coordinates assigned using a Gaussian
distribution with standard deviation 1e-4, as used in LargeVis
(Tang et al., 2016) and t-SNE.
\item \code{"laplacian"}. Spectral embedding using the Laplacian Eigenmap
(Belkin and Niyogi, 2002).
\item \code{"pca"}. The first two principal components from PCA of
\code{X} if \code{X} is a data frame, and from a 2-dimensional classical
MDS if \code{X} is of class \code{"dist"}.
\item \code{"spca"}. Like \code{"pca"}, but each dimension is then scaled
so the standard deviation is 1e-4, to give a distribution similar to that
used in t-SNE. This is an alias for \code{init = "pca", init_sdev =
1e-4}.
\item \code{"agspectral"} An "approximate global" modification of
\code{"spectral"} which all edges in the graph to a value of 1, and then
sets a random number of edges (\code{negative_sample_rate} edges per
vertex) to 0.1, to approximate the effect of non-local affinities.
\item A matrix of initial coordinates.
}
For spectral initializations, (\code{"spectral"}, \code{"normlaplacian"},
\code{"laplacian"}), if more than one connected component is identified,
each connected component is initialized separately and the results are
merged. If \code{verbose = TRUE} the number of connected components are
logged to the console. The existence of multiple connected components
implies that a global view of the data cannot be attained with this
initialization. Either a PCA-based initialization or increasing the value of
\code{n_neighbors} may be more appropriate.}
\item{init_sdev}{If non-\code{NULL}, scales each dimension of the initialized
coordinates (including any user-supplied matrix) to this standard
deviation. By default no scaling is carried out, except when \code{init =
"spca"}, in which case the value is \code{0.0001}. Scaling the input may
help if the unscaled versions result in initial coordinates with large
inter-point distances or outliers. This usually results in small gradients
during optimization and very little progress being made to the layout.
Shrinking the initial embedding by rescaling can help under these
circumstances. Scaling the result of \code{init = "pca"} is usually
recommended and \code{init = "spca"} as an alias for \code{init = "pca",
init_sdev = 1e-4} but for the spectral initializations the scaled versions
usually aren't necessary unless you are using a large value of
\code{n_neighbors} (e.g. \code{n_neighbors = 150} or higher).}
\item{spread}{The effective scale of embedded points. In combination with
\code{min_dist}, this determines how clustered/clumped the embedded points
are.}
\item{min_dist}{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. The value should be
set relative to the \code{spread} value, which determines the scale at
which embedded points will be spread out.}
\item{set_op_mix_ratio}{Interpolate between (fuzzy) union and intersection as
the set operation used to combine local fuzzy simplicial sets to obtain a
global fuzzy simplicial sets. Both fuzzy set operations use the product
t-norm. The value of this parameter should be between \code{0.0} and
\code{1.0}; a value of \code{1.0} will use a pure fuzzy union, while
\code{0.0} will use a pure fuzzy intersection.}
\item{local_connectivity}{The local connectivity required -- i.e. the number
of nearest neighbors that should be assumed to be connected at a local
level. The higher this value the more connected the manifold becomes
locally. In practice this should be not more than the local intrinsic
dimension of the manifold.}
\item{bandwidth}{The effective bandwidth of the kernel if we view the
algorithm as similar to Laplacian Eigenmaps. Larger values induce more
connectivity and a more global view of the data, smaller values concentrate
more locally.}
\item{repulsion_strength}{Weighting applied to negative samples in low
dimensional embedding optimization. Values higher than one will result in
greater weight being given to negative samples.}
\item{negative_sample_rate}{The number of negative edge/1-simplex samples to
use per positive edge/1-simplex sample in optimizing the low dimensional
embedding.}
\item{a}{More specific parameters controlling the embedding. If \code{NULL}
these values are set automatically as determined by \code{min_dist} and
\code{spread}.}
\item{b}{More specific parameters controlling the embedding. If \code{NULL}
these values are set automatically as determined by \code{min_dist} and
\code{spread}.}
\item{nn_method}{Method for finding nearest neighbors. Options are:
\itemize{
\item \code{"fnn"}. Use exact nearest neighbors via the
\href{https://cran.r-project.org/package=FNN}{FNN} package.
\item \code{"annoy"} Use approximate nearest neighbors via the
\href{https://cran.r-project.org/package=RcppAnnoy}{RcppAnnoy} package.
}
By default, if \code{X} has less than 4,096 vertices, the exact nearest
neighbors are found. Otherwise, approximate nearest neighbors are used.
You may also pass precalculated nearest neighbor data to this argument. It
must be a list consisting of two elements:
\itemize{
\item \code{"idx"}. A \code{n_vertices x n_neighbors} matrix
containing the integer indexes of the nearest neighbors in \code{X}. Each
vertex is considered to be its own nearest neighbor, i.e.
\code{idx[, 1] == 1:n_vertices}.
\item \code{"dist"}. A \code{n_vertices x n_neighbors} matrix
containing the distances of the nearest neighbors.
}
Multiple nearest neighbor data (e.g. from two different precomputed
metrics) can be passed by passing a list containing the nearest neighbor
data lists as items.
The \code{n_neighbors} parameter is ignored when using precomputed
nearest neighbor data.}
\item{n_trees}{Number of trees to build when constructing the nearest
neighbor index. The more trees specified, the larger the index, but the
better the results. With \code{search_k}, determines the accuracy of the
Annoy nearest neighbor search. Only used if the \code{nn_method} is
\code{"annoy"}. Sensible values are between \code{10} to \code{100}.}
\item{search_k}{Number of nodes to search during the neighbor retrieval. The
larger k, the more the accurate results, but the longer the search takes.
With \code{n_trees}, determines the accuracy of the Annoy nearest neighbor
search. Only used if the \code{nn_method} is \code{"annoy"}.}
\item{approx_pow}{If \code{TRUE}, use an approximation to the power function
in the UMAP gradient, from
\url{https://martin.ankerl.com/2012/01/25/optimized-approximative-pow-in-c-and-cpp/}.}
\item{y}{Optional target data for supervised dimension reduction. Can be a
vector, matrix or data frame. Use the \code{target_metric} parameter to
specify the metrics to use, using the same syntax as \code{metric}. Usually
either a single numeric or factor column is used, but more complex formats
are possible. The following types are allowed:
\itemize{
\item Factor columns with the same length as \code{X}. \code{NA} is
allowed for any observation with an unknown level, in which case
UMAP operates as a form of semi-supervised learning. Each column is
treated separately.
\item Numeric data. \code{NA} is \emph{not} allowed in this case. Use the
parameter \code{target_n_neighbors} to set the number of neighbors used
with \code{y}. If unset, \code{n_neighbors} is used. Unlike factors,
numeric columns are grouped into one block unless \code{target_metric}
specifies otherwise. For example, if you wish columns \code{a} and
\code{b} to be treated separately, specify
\code{target_metric = list(euclidean = "a", euclidean = "b")}. Otherwise,
the data will be effectively treated as a matrix with two columns.
\item Nearest neighbor data, consisting of a list of two matrices,
\code{idx} and \code{dist}. These represent the precalculated nearest
neighbor indices and distances, respectively. This
is the same format as that expected for precalculated data in
\code{nn_method}. This format assumes that the underlying data was a
numeric vector. Any user-supplied value of the \code{target_n_neighbors}
parameter is ignored in this case, because the the number of columns in
the matrices is used for the value. Multiple nearest neighbor data using
different metrics can be supplied by passing a list of these lists.
}
Unlike \code{X}, all factor columns included in \code{y} are automatically
used.}
\item{target_n_neighbors}{Number of nearest neighbors to use to construct the
target simplicial set. Default value is \code{n_neighbors}. Applies only if
\code{y} is non-\code{NULL} and \code{numeric}.}
\item{target_metric}{The metric used to measure distance for \code{y} if
using supervised dimension reduction. Used only if \code{y} is numeric.}
\item{target_weight}{Weighting factor between data topology and target
topology. A value of 0.0 weights entirely on data, a value of 1.0 weights
entirely on target. The default of 0.5 balances the weighting equally
between data and target. Only applies if \code{y} is non-\code{NULL}.}
\item{pca}{If set to a positive integer value, reduce data to this number of
columns using PCA. Doesn't applied if the distance \code{metric} is
\code{"hamming"}, or the dimensions of the data is larger than the
number specified (i.e. number of rows and columns must be larger than the
value of this parameter). If you have > 100 columns in a data frame or
matrix, reducing the number of columns in this way may substantially
increase the performance of the nearest neighbor search at the cost of a
potential decrease in accuracy. In many t-SNE applications, a value of 50
is recommended, although there's no guarantee that this is appropriate for
all settings.}
\item{pca_center}{If \code{TRUE}, center the columns of \code{X} before
carrying out PCA. For binary data, it's recommended to set this to
\code{FALSE}.}
\item{pcg_rand}{If \code{TRUE}, use the PCG random number generator (O'Neill,
2014) during optimization. Otherwise, use the faster (but probably less
statistically good) Tausworthe "taus88" generator. The default is
\code{TRUE}.}
\item{fast_sgd}{If \code{TRUE}, then the following combination of parameters
is set: \code{pcg_rand = TRUE}, \code{n_sgd_threads = "auto"} and
\code{approx_pow = TRUE}. The default is \code{FALSE}. Setting this to
\code{TRUE} will speed up the stochastic optimization phase, but give a
potentially less accurate embedding, and which will not be exactly
reproducible even with a fixed seed. For visualization, \code{fast_sgd =
TRUE} will give perfectly good results. For more generic dimensionality
reduction, it's safer to leave \code{fast_sgd = FALSE}. If \code{fast_sgd =
TRUE}, then user-supplied values of \code{pcg_rand}, \code{n_sgd_threads},
and \code{approx_pow} are ignored.}
\item{ret_model}{If \code{TRUE}, then return extra data that can be used to
add new data to an existing embedding via \code{\link{umap_transform}}. The
embedded coordinates are returned as the list item \code{embedding}. If
\code{FALSE}, just return the coordinates. This parameter can be used in
conjunction with \code{ret_nn}. Note that some settings are incompatible
with the production of a UMAP model: external neighbor data (passed via a
list to \code{nn_method}), and factor columns that were included
via the \code{metric} parameter. In the latter case, the model produced is
based only on the numeric data. A transformation using new data is
possible, but the factor columns in the new data are ignored.}
\item{ret_nn}{If \code{TRUE}, then in addition to the embedding, also return
nearest neighbor data that can be used as input to \code{nn_method} to
avoid the overhead of repeatedly calculating the nearest neighbors when
manipulating unrelated parameters (e.g. \code{min_dist}, \code{n_epochs},
\code{init}). See the "Value" section for the names of the list items. If
\code{FALSE}, just return the coordinates. Note that the nearest neighbors
could be sensitive to data scaling, so be wary of reusing nearest neighbor
data if modifying the \code{scale} parameter. This parameter can be used in
conjunction with \code{ret_model}.}
\item{n_threads}{Number of threads to use.}
\item{n_sgd_threads}{Number of threads to use during stochastic gradient
descent. If set to > 1, then results will not be reproducible, even if
`set.seed` is called with a fixed seed before running. Set to
\code{"auto"} go use the same value as \code{n_threads}.}
\item{grain_size}{Minimum batch size for multithreading. If the number of
items to process in a thread falls below this number, then no threads will
be used. Used in conjunction with \code{n_threads} and
\code{n_sgd_threads}.}
\item{tmpdir}{Temporary directory to store nearest neighbor indexes during
nearest neighbor search. Default is \code{\link{tempdir}}. The index is
only written to disk if \code{n_threads > 1} and
\code{nn_method = "annoy"}; otherwise, this parameter is ignored.}
\item{verbose}{If \code{TRUE}, log details to the console.}
}
\value{
An object of class iCellR.
}
\description{
This function takes an object of class iCellR and runs UMAP on PCA data.
}
\examples{
demo.obj <- run.umap(demo.obj, dims = 1:10)
head(demo.obj@umap.data)
}
|
library(datasets)
data(iris)
# Q1
s <- split(iris, iris$Species)
mean(s$virginica$Sepal.Length)
# Q2
rowMeans(iris[,1:4])
colMeans(iris[,1:4])
apply(iris[,1:4], 2, mean)
# Q3
data(mtcars)
lapply(split(mtcars$mpg, mtcars$cyl), mean)
# Q4
means <- lapply(split(mtcars$hp, mtcars$cyl), mean)
abs(means$`4` - means$`8`)
| /rprog/quiz2/quiz2.R | no_license | geraudster/datasciencecoursera | R | false | false | 320 | r | library(datasets)
data(iris)
# Q1
s <- split(iris, iris$Species)
mean(s$virginica$Sepal.Length)
# Q2
rowMeans(iris[,1:4])
colMeans(iris[,1:4])
apply(iris[,1:4], 2, mean)
# Q3
data(mtcars)
lapply(split(mtcars$mpg, mtcars$cyl), mean)
# Q4
means <- lapply(split(mtcars$hp, mtcars$cyl), mean)
abs(means$`4` - means$`8`)
|
## In order to avoid unnecessary repetitions of cumbersome computation,
## "makeCacheMatrix" function will create the list of functions whose
## environmet includes a cache "m" for an inverse matrix.
## "cacheSolve" computes the inverse, but bypasses the computation if
## the inverse matrix is already stored in m.
## makeChacheMatrix creates a "matrix", which carries the list of functions.
makeCacheMatrix <- function(x = matrix()) { # x is the argument matrix.
m <- NULL # m is the storage for the inverse matrix.
set <- function(y) { # "set" function substitutes a new matrix into x.
x <<- y # x is in the parent environment, thus <<- is used here.
m <<- NULL # The old cache is cleared out when the old matrix is replaced.
}
get <- function() x # Get the current matrix.
setsolve <- function(solve) m <<- solve # Store "solve" matrix into m. "solve" will be given by cacheSolveMatrix function.
getsolve <- function() m # Get the cached inverse matrix.
list(set = set, get = get, # Return the list of functions.
setsolve = setsolve,
getsolve = getsolve)
}
## CacheSolve computes the inverse of the data matrix of x.
## However it avoids computation if the inverse matrix is already stored in x.
cacheSolve <- function(x, ...) {
m <- x$getsolve() # Get the currently-cached inverse matrix in x.
if(!is.null(m)) { # See if any matrix is stored in m.
message("getting cached data") # If an inverse matrix is already cached,
return(m) # then cacheSolve just returns the cache without computing again.
}
data <- x$get() # If an inverse matrix is not cached in m, then cacheSolve needs to compute it again.
m <- solve(data, ...) # The inverse matrix is computed here.
x$setsolve(m) # Using "setsolve" function, the computed inverse matrix is stored into x.
m # Return the freshly calculated inverse matrix.
}
# TEST RUNNING ------------------------------------------------------------
Test <- makeCacheMatrix() # Test is the list of functions.
randMatrix <- matrix(runif(16),nrow=4,ncol=4) # make an example 4*4 random matrix.
Test$set(randMatrix) # set the data into Test
cacheSolve(Test) # Cache an inverse matrix.
# Since this is the 1st time to calcuate randMatrix's inverse,
# this should just return the inverse matrix
# without the "getting cached data" message.
cacheSolve(Test) # Attempting to caching again.
# Since this is the 2nd time, this should results in
# "getting chached data" message, meaning that the
# function bypassed the cumbersome computation.
round(randMatrix %*% cacheSolve(Test)) # Check the cached m is really the inverse matrix.
# (I rounded the matrix to make it clear.)
| /cachematrix.R | no_license | satoshi-harashima/Coursera_R_Programming_Week2 | R | false | false | 3,515 | r | ## In order to avoid unnecessary repetitions of cumbersome computation,
## "makeCacheMatrix" function will create the list of functions whose
## environmet includes a cache "m" for an inverse matrix.
## "cacheSolve" computes the inverse, but bypasses the computation if
## the inverse matrix is already stored in m.
## makeChacheMatrix creates a "matrix", which carries the list of functions.
makeCacheMatrix <- function(x = matrix()) { # x is the argument matrix.
m <- NULL # m is the storage for the inverse matrix.
set <- function(y) { # "set" function substitutes a new matrix into x.
x <<- y # x is in the parent environment, thus <<- is used here.
m <<- NULL # The old cache is cleared out when the old matrix is replaced.
}
get <- function() x # Get the current matrix.
setsolve <- function(solve) m <<- solve # Store "solve" matrix into m. "solve" will be given by cacheSolveMatrix function.
getsolve <- function() m # Get the cached inverse matrix.
list(set = set, get = get, # Return the list of functions.
setsolve = setsolve,
getsolve = getsolve)
}
## CacheSolve computes the inverse of the data matrix of x.
## However it avoids computation if the inverse matrix is already stored in x.
cacheSolve <- function(x, ...) {
m <- x$getsolve() # Get the currently-cached inverse matrix in x.
if(!is.null(m)) { # See if any matrix is stored in m.
message("getting cached data") # If an inverse matrix is already cached,
return(m) # then cacheSolve just returns the cache without computing again.
}
data <- x$get() # If an inverse matrix is not cached in m, then cacheSolve needs to compute it again.
m <- solve(data, ...) # The inverse matrix is computed here.
x$setsolve(m) # Using "setsolve" function, the computed inverse matrix is stored into x.
m # Return the freshly calculated inverse matrix.
}
# TEST RUNNING ------------------------------------------------------------
Test <- makeCacheMatrix() # Test is the list of functions.
randMatrix <- matrix(runif(16),nrow=4,ncol=4) # make an example 4*4 random matrix.
Test$set(randMatrix) # set the data into Test
cacheSolve(Test) # Cache an inverse matrix.
# Since this is the 1st time to calcuate randMatrix's inverse,
# this should just return the inverse matrix
# without the "getting cached data" message.
cacheSolve(Test) # Attempting to caching again.
# Since this is the 2nd time, this should results in
# "getting chached data" message, meaning that the
# function bypassed the cumbersome computation.
round(randMatrix %*% cacheSolve(Test)) # Check the cached m is really the inverse matrix.
# (I rounded the matrix to make it clear.)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/functions.R
\name{get_uid_info}
\alias{get_uid_info}
\title{Get subject info}
\usage{
get_uid_info(uid, ADSL)
}
\value{
A \code{list} with subject level information for \code{uid}.
}
\description{
Get subject level info for a participant
}
| /man/get_uid_info.Rd | permissive | vineetrepository/patprofile | R | false | true | 318 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/functions.R
\name{get_uid_info}
\alias{get_uid_info}
\title{Get subject info}
\usage{
get_uid_info(uid, ADSL)
}
\value{
A \code{list} with subject level information for \code{uid}.
}
\description{
Get subject level info for a participant
}
|
#Workshop 13: Imputing missing values
#Uncomment the following if you need to install the following packages
#install.packages("mice")
#install.packages("VIM")
#install.packages("NHANES")
library(mice)
library(VIM)
#Exercise 2
#(a)
data(tao) #in VIM package
?tao
table(tao$Year)
#there are only two years and we do not need the numeric value of Year in the regression model,
# so convert it to a factor
tao$Year<-as.factor(tao$Year)
plot(tao$Air.Temp,tao$Sea.Surface.Temp,col=tao$Year)
#(b)
startMar<-par()$mar #store the current margin settings
par(mar=c(0,0,0,0)+0.1)
md.pattern(tao, rotate.names=TRUE)
summary(tao)
aggr(tao)
any.missing<-!complete.cases(tao)
par(mar=startMar)
marginplot(tao[,c("Air.Temp", "Humidity")])
marginplot(tao[,c("Air.Temp","Sea.Surface.Temp")])
#Notice that the missing values appear not to be random
#(c)
#You will use the same longish model specification several times in Exercise 3, so let's give the "formula" a short name.
tao.model<-formula(Sea.Surface.Temp~Year+Longitude+Latitude+Air.Temp+ Humidity+UWind+VWind)
#fit a linear regression model to the "fully known" observations
lm.knowns<-lm(tao.model,data=tao)
summary(lm.knowns)
#(d) Question in worksheet
#Exercise 3
#univariate imputation
#(a) Mean imputation
mean.replace<-function(x)
{
idx<-which(is.na(x)) #returns the row nubers with a missing value in x
known.mean<-mean(x,na.rm=T)
x[idx]<-known.mean
return(x)
}
#check using a test variable
tt<-c(1:10,NA,NA,95)
tt
mean.replace(tt)
hist(tao$Air.Temp)
#impute the Air.Temp using mean replacement
mrep.Air.Temp<-mean.replace(tao$Air.Temp)
hist(mrep.Air.Temp)
tao.mrep<-tao
tao.mrep$Air.Temp<-mrep.Air.Temp
tao.mrep$Sea.Surface.Temp<-mean.replace(???)
tao.mrep$Humidity<-mean.replace(???)
with(tao.mrep,plot(Air.Temp,Sea.Surface.Temp,col=Year))
###NB with(data.frame,command(...)) runs command(...) knowing that variable names are to be found in data.frame
with(???,plot(Air.Temp,Sea.Surface.Temp,col=1+any.missing)) #colour the imputed vales red.
lm.mrep<-lm(tao.model,data=tao.mrep)
summary(lm.mrep)
#(b)
mean.sd.replace<-function(x)
{
idx<-which(is.na(x))
known.mean<-mean(x,na.rm=T)
known.sd<-sd(???,???)
x[idx]<-rnorm(length(idx),known.mean,known.sd)
return(x)
}
tt<-c(1:10,NA,NA,95)
tt
mean.sd.replace(tt)
hist(tao$Air.Temp)
#impute the Air.Temp using mean replacement
msdrep.Air.Temp<-mean.sd.replace(???)
hist(msdrep.Air.Temp)
tao.msdrep<-tao
tao.msdrep$Air.Temp<-???
tao.msdrep$Sea.Surface.Temp<-???
tao.msdrep$Humidity<-???
with(tao.??,plot(Air.Temp,Sea.Surface.Temp,col=Year))
with(???,plot(??,???,col=1+any.missing))
lm.msdrep<-lm(tao.model,data=???)
summary(???)
#(c)
dir.rand.samp<-function(x)
{ ##direct random sampling of x
idx<-which(is.na(x))
x[idx]<-sample(x[-idx],length(idx),replace=???)
return(x)
}
#check
tt
dir.rand.samp(tt)
#and again
dir.rand.samp(tt)
tao.drs<-tao
tao.drs$Air.Temp<-dir.rand.samp(tao$Air.Temp)
tao.drs$Sea.Surface.Temp<-dir.rand.samp(tao$Sea.Surface.Temp)
tao.drs$Humidity<-dir.rand.samp(tao$Humidity)
hist(tao.drs$Air.Temp)
plot(tao.drs$Air.Temp,tao.drs$Sea.Surface.Temp,col=tao.drs$Year)
with(tao.drs,plot(???))
with(???,plot(???))
lm.drs<-lm(tao.model,data=tao.drs)
summary(lm.drs)
#compare the coefficients from all four univariate methods
cbind(lm.knowns$coefficients,lm.mrep$coefficients,lm.msdrep$coefficients,lm.drs$coefficients)
#Exercise 4 Multivariate imputation using Gibbs sampling
#(a)
GibbsData <- mice(tao,m=5,maxit=50,meth='pmm',seed=600)
#(b)
Gibbsdata1<-complete(GibbsData,1)
#plot with missing values in red
with(Gibbsdata1,plot(Air.Temp,Sea.Surface.Temp,col=1+any.missing))
lm.Gibbs1<-lm(tao.model,data=Gibbsdata1)
summary(lm.Gibbs1)
cbind(lm.knowns$coefficients,lm.mrep$coefficients,lm.msdrep$coefficients,lm.drs$coefficients,lm.Gibbs1$coefficients)
#(c)
#run lm on all 5 complete data sets
lm.Gibbs.all<-with(GibbsData,lm(Sea.Surface.Temp~Year+Longitude+Latitude+Air.Temp+ Humidity+UWind+VWind))
#the resulst of each on
lm.Gibbs.all$analyses
#summary(lm.obj) for each of the 5 lms.
lapply(lm.Gibbs.all$analyses,summary)
sapply(lm.Gibbs.all$analyses,coefficients)
#(d)
summary(pool(lm.Gibbs.all))
# final model
lm.Gibbs.all.final<-with(GibbsData,lm(Sea.Surface.Temp~Year+Longitude+Latitude+Air.Temp+Humidity+VWind))
summary(pool(lm.Gibbs.all.final))
#Exercise 5: Imputing missing data for the Diabetes data set
#(a)
library(NHANES)
Diabetes2<-data.frame(NHANES[,c("Diabetes","Gender","Race1","BMI","Age","Pulse","BPSysAve","BPDiaAve","HealthGen","DaysPhysHlthBad","DaysMentHlthBad","LittleInterest","Depressed")])
table(Diabetes2$Diabetes)
#convert Diabetes vaiable to be a binary outcome for logistic regression
Diabetes2$Diabetes<-as.numeric(Diabetes2$Diabetes)-1
par(mar=c(0,0,0,0)+0.1)
md.pattern(Diabetes2,rotate.names = TRUE)
#reset the margins
par(mar=startMar)
summary(Diabetes2)
aggr(Diabetes2)
any.missing<-!complete.cases(Diabetes2)
#(b)Multivariate imputation
#this takes a while!
GibbsDiabetes <- mice(???,m=5,maxit=10,meth='pmm',seed=700)
##obtain the first complete data set
Gibbs1Diabetes<-???;
Gibbs1Diabetes<-complete(GibbsDiabetes,1)
#output a cat!
md.pattern(Gibbs1Diabetes)
#(c) glm() with family="binomial" specifies a logistic regression
#first the logistic regression on the original known data, throwing away the missings
logreg.known<-glm(Diabetes~.,data=???,family="binomial")
logreg.known<-glm(Diabetes~.,data=Diabetes2,family="binomial")
summary(logreg.known)
logreg.Gibbs1<-glm(Diabetes~.,???)
summary(???)
logreg.full<-with(GibbsDiabetes,glm(Diabetes~Gender+Race1+BMI+Age+Pulse+BPSysAve+BPDiaAve+HealthGen+
DaysPhysHlthBad+DaysMentHlthBad+LittleInterest+Depressed,family="binomial"))
summary(pool(???))
#remove the variable Depressed as it seems not to be significant at 5% level
logreg.final<-with(GibbsDiabetes,glm(Diabetes~Gender+Race1+BMI+Age+Pulse+BPSysAve+BPDiaAve+HealthGen+
DaysPhysHlthBad+DaysMentHlthBad,family="binomial"))
summary(pool(????))
#predictions from the logistic regression model
pr.logreg<-predict(logreg.Gibbs1,type="response")>0.5
table(pr.logreg,Diabetes2$Diabetes)
#e)
library(rpart)
library(rpart.plot)
tree.known<-rpart(Diabetes~.,data=Diabetes2)
rpart.plot(tree.known)
tree.Gibbs1<-rpart(Diabetes~.,data=Gibbs1Diabetes)
rpart.plot(tree.Gibbs1)
Gibbs.full<-with(GibbsDiabetes,rpart(Diabetes~Gender+Race1+BMI+Age))
pool(Gibbs.full) ###Damn!
for(i in 1:5){
tree.Gibbsfull<-rpart(Diabetes~Gender+Race1+BMI+Age+Pulse+BPSysAve+BPDiaAve+HealthGen+DaysPhysHlthBad+DaysMentHlthBad+LittleInterest+Depressed,
data=complete(GibbsDiabetes,i))
rpart.plot(tree.Gibbs1,main=i)
}
##Notice that the 5 Tree models are exactly the same, which tells that the model is insensitive to the imputation.
| /R_Maschine_learning_II/01/ML2_Workshop1_Wksp1MissingData.R | no_license | torstenschenk/BeuthDevML | R | false | false | 6,887 | r | #Workshop 13: Imputing missing values
#Uncomment the following if you need to install the following packages
#install.packages("mice")
#install.packages("VIM")
#install.packages("NHANES")
library(mice)
library(VIM)
#Exercise 2
#(a)
data(tao) #in VIM package
?tao
table(tao$Year)
#there are only two years and we do not need the numeric value of Year in the regression model,
# so convert it to a factor
tao$Year<-as.factor(tao$Year)
plot(tao$Air.Temp,tao$Sea.Surface.Temp,col=tao$Year)
#(b)
startMar<-par()$mar #store the current margin settings
par(mar=c(0,0,0,0)+0.1)
md.pattern(tao, rotate.names=TRUE)
summary(tao)
aggr(tao)
any.missing<-!complete.cases(tao)
par(mar=startMar)
marginplot(tao[,c("Air.Temp", "Humidity")])
marginplot(tao[,c("Air.Temp","Sea.Surface.Temp")])
#Notice that the missing values appear not to be random
#(c)
#You will use the same longish model specification several times in Exercise 3, so let's give the "formula" a short name.
tao.model<-formula(Sea.Surface.Temp~Year+Longitude+Latitude+Air.Temp+ Humidity+UWind+VWind)
#fit a linear regression model to the "fully known" observations
lm.knowns<-lm(tao.model,data=tao)
summary(lm.knowns)
#(d) Question in worksheet
#Exercise 3
#univariate imputation
#(a) Mean imputation
mean.replace<-function(x)
{
idx<-which(is.na(x)) #returns the row nubers with a missing value in x
known.mean<-mean(x,na.rm=T)
x[idx]<-known.mean
return(x)
}
#check using a test variable
tt<-c(1:10,NA,NA,95)
tt
mean.replace(tt)
hist(tao$Air.Temp)
#impute the Air.Temp using mean replacement
mrep.Air.Temp<-mean.replace(tao$Air.Temp)
hist(mrep.Air.Temp)
tao.mrep<-tao
tao.mrep$Air.Temp<-mrep.Air.Temp
tao.mrep$Sea.Surface.Temp<-mean.replace(???)
tao.mrep$Humidity<-mean.replace(???)
with(tao.mrep,plot(Air.Temp,Sea.Surface.Temp,col=Year))
###NB with(data.frame,command(...)) runs command(...) knowing that variable names are to be found in data.frame
with(???,plot(Air.Temp,Sea.Surface.Temp,col=1+any.missing)) #colour the imputed vales red.
lm.mrep<-lm(tao.model,data=tao.mrep)
summary(lm.mrep)
#(b)
mean.sd.replace<-function(x)
{
idx<-which(is.na(x))
known.mean<-mean(x,na.rm=T)
known.sd<-sd(???,???)
x[idx]<-rnorm(length(idx),known.mean,known.sd)
return(x)
}
tt<-c(1:10,NA,NA,95)
tt
mean.sd.replace(tt)
hist(tao$Air.Temp)
#impute the Air.Temp using mean replacement
msdrep.Air.Temp<-mean.sd.replace(???)
hist(msdrep.Air.Temp)
tao.msdrep<-tao
tao.msdrep$Air.Temp<-???
tao.msdrep$Sea.Surface.Temp<-???
tao.msdrep$Humidity<-???
with(tao.??,plot(Air.Temp,Sea.Surface.Temp,col=Year))
with(???,plot(??,???,col=1+any.missing))
lm.msdrep<-lm(tao.model,data=???)
summary(???)
#(c)
dir.rand.samp<-function(x)
{ ##direct random sampling of x
idx<-which(is.na(x))
x[idx]<-sample(x[-idx],length(idx),replace=???)
return(x)
}
#check
tt
dir.rand.samp(tt)
#and again
dir.rand.samp(tt)
tao.drs<-tao
tao.drs$Air.Temp<-dir.rand.samp(tao$Air.Temp)
tao.drs$Sea.Surface.Temp<-dir.rand.samp(tao$Sea.Surface.Temp)
tao.drs$Humidity<-dir.rand.samp(tao$Humidity)
hist(tao.drs$Air.Temp)
plot(tao.drs$Air.Temp,tao.drs$Sea.Surface.Temp,col=tao.drs$Year)
with(tao.drs,plot(???))
with(???,plot(???))
lm.drs<-lm(tao.model,data=tao.drs)
summary(lm.drs)
#compare the coefficients from all four univariate methods
cbind(lm.knowns$coefficients,lm.mrep$coefficients,lm.msdrep$coefficients,lm.drs$coefficients)
#Exercise 4 Multivariate imputation using Gibbs sampling
#(a)
GibbsData <- mice(tao,m=5,maxit=50,meth='pmm',seed=600)
#(b)
Gibbsdata1<-complete(GibbsData,1)
#plot with missing values in red
with(Gibbsdata1,plot(Air.Temp,Sea.Surface.Temp,col=1+any.missing))
lm.Gibbs1<-lm(tao.model,data=Gibbsdata1)
summary(lm.Gibbs1)
cbind(lm.knowns$coefficients,lm.mrep$coefficients,lm.msdrep$coefficients,lm.drs$coefficients,lm.Gibbs1$coefficients)
#(c)
#run lm on all 5 complete data sets
lm.Gibbs.all<-with(GibbsData,lm(Sea.Surface.Temp~Year+Longitude+Latitude+Air.Temp+ Humidity+UWind+VWind))
#the resulst of each on
lm.Gibbs.all$analyses
#summary(lm.obj) for each of the 5 lms.
lapply(lm.Gibbs.all$analyses,summary)
sapply(lm.Gibbs.all$analyses,coefficients)
#(d)
summary(pool(lm.Gibbs.all))
# final model
lm.Gibbs.all.final<-with(GibbsData,lm(Sea.Surface.Temp~Year+Longitude+Latitude+Air.Temp+Humidity+VWind))
summary(pool(lm.Gibbs.all.final))
#Exercise 5: Imputing missing data for the Diabetes data set
#(a)
library(NHANES)
Diabetes2<-data.frame(NHANES[,c("Diabetes","Gender","Race1","BMI","Age","Pulse","BPSysAve","BPDiaAve","HealthGen","DaysPhysHlthBad","DaysMentHlthBad","LittleInterest","Depressed")])
table(Diabetes2$Diabetes)
#convert Diabetes vaiable to be a binary outcome for logistic regression
Diabetes2$Diabetes<-as.numeric(Diabetes2$Diabetes)-1
par(mar=c(0,0,0,0)+0.1)
md.pattern(Diabetes2,rotate.names = TRUE)
#reset the margins
par(mar=startMar)
summary(Diabetes2)
aggr(Diabetes2)
any.missing<-!complete.cases(Diabetes2)
#(b)Multivariate imputation
#this takes a while!
GibbsDiabetes <- mice(???,m=5,maxit=10,meth='pmm',seed=700)
##obtain the first complete data set
Gibbs1Diabetes<-???;
Gibbs1Diabetes<-complete(GibbsDiabetes,1)
#output a cat!
md.pattern(Gibbs1Diabetes)
#(c) glm() with family="binomial" specifies a logistic regression
#first the logistic regression on the original known data, throwing away the missings
logreg.known<-glm(Diabetes~.,data=???,family="binomial")
logreg.known<-glm(Diabetes~.,data=Diabetes2,family="binomial")
summary(logreg.known)
logreg.Gibbs1<-glm(Diabetes~.,???)
summary(???)
logreg.full<-with(GibbsDiabetes,glm(Diabetes~Gender+Race1+BMI+Age+Pulse+BPSysAve+BPDiaAve+HealthGen+
DaysPhysHlthBad+DaysMentHlthBad+LittleInterest+Depressed,family="binomial"))
summary(pool(???))
#remove the variable Depressed as it seems not to be significant at 5% level
logreg.final<-with(GibbsDiabetes,glm(Diabetes~Gender+Race1+BMI+Age+Pulse+BPSysAve+BPDiaAve+HealthGen+
DaysPhysHlthBad+DaysMentHlthBad,family="binomial"))
summary(pool(????))
#predictions from the logistic regression model
pr.logreg<-predict(logreg.Gibbs1,type="response")>0.5
table(pr.logreg,Diabetes2$Diabetes)
#e)
library(rpart)
library(rpart.plot)
tree.known<-rpart(Diabetes~.,data=Diabetes2)
rpart.plot(tree.known)
tree.Gibbs1<-rpart(Diabetes~.,data=Gibbs1Diabetes)
rpart.plot(tree.Gibbs1)
Gibbs.full<-with(GibbsDiabetes,rpart(Diabetes~Gender+Race1+BMI+Age))
pool(Gibbs.full) ###Damn!
for(i in 1:5){
tree.Gibbsfull<-rpart(Diabetes~Gender+Race1+BMI+Age+Pulse+BPSysAve+BPDiaAve+HealthGen+DaysPhysHlthBad+DaysMentHlthBad+LittleInterest+Depressed,
data=complete(GibbsDiabetes,i))
rpart.plot(tree.Gibbs1,main=i)
}
##Notice that the 5 Tree models are exactly the same, which tells that the model is insensitive to the imputation.
|
testlist <- list(mat = NULL, pi_mat = structure(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(9L, 3L)))
result <- do.call(NetMix:::getZ,testlist)
str(result) | /NetMix/inst/testfiles/getZ/libFuzzer_getZ/getZ_valgrind_files/1612742793-test.R | no_license | akhikolla/updatedatatype-list1 | R | false | false | 206 | r | testlist <- list(mat = NULL, pi_mat = structure(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(9L, 3L)))
result <- do.call(NetMix:::getZ,testlist)
str(result) |
#' ---
#' title: Mixed models - socioeconomic predictors of forest cover
#' author: Matt Nuttall
#' date: 23/06/20
#' output:
#' html_document:
#' toc: true
#' highlight: zenburn
#' ---
#+ include=FALSE
library(sjPlot)
library(DHARMa)
library(lme4)
library(patchwork)
library(pbkrtest)
library(MuMIn)
library(RColorBrewer)
library(tidyverse)
# load data
dat <- read.csv("Data/commune/dat_use.csv", header = TRUE, stringsAsFactors = TRUE)
dat <- dat[ ,-1]
# re-classify the variables
dat$year <- as.numeric(dat$year)
dat$elc <- as.factor(dat$elc)
dat$PA <- as.factor(dat$PA)
dat1 <- dat %>%
mutate_at(c("year","tot_pop","prop_ind","pop_den","M6_24_sch","propPrimSec","propSecSec","Les1_R_Land",
"pig_fam","dist_sch","garbage","KM_Comm","land_confl","crim_case","Pax_migt_in",
"Pax_migt_out","mean_elev","dist_border","dist_provCap"), ~(scale(.) %>% as.vector))
# merge Province and Commune into a new unique variable (to remove issue of communes with the same name)
dat1 <- dat1 %>% mutate(Provcomm = paste(dat1$Province, dat1$Commune, sep = "_"))
# add original year (i.e. not scaled)
dat1$year.orig <- dat$year
#' This document is a summary of the ongoing analysis into predictors of forest cover/loss at the commune level across Cambodia.
#'
#' Currently the response variable is raw count of forest pixels, and there are 9 predictor variable sets with varying numbers of predictors in each set. All predictor variables have been scaled and centered prior to analysis. A GLMM framework has been used, with a Poisson distribution and the following random effects structure:
#'
#' **(year|Province/Commune)**
#'
#' The logged area (KM) of each commune has been used as an offset term in each model.
#'
#' The variable sets are as follows:
#'
#' * POPULATION DEMOGRAPHICS - population density, total population, proportion of commune that are indigenous
#' * EDUCATION - proportion of males aged 6-24 in school
#' * EMPLOYMENT - proportion of people employed in the Primary sector, proportion of people emplyed in the Secondary sector
#' * ECONOMIC SECURITY - proportion of population with less than 1ha of farming land, proportion of families with pigs
#' * ACCESS TO SERVICES - median distance to nearest school (of all the villages within the commune), median distance to the Commune Office (of all the villages within the commune), proportion of families with access to waste collection services
#' * SOCIAL JUSTICE - total number of land conflict cases, number of criminal cases per capita
#' * MIGRATION - total number of in-migrants, total number of out-migrants
#' * ENVIRONMENTAL (CONTROL) - mean elevation, habitat
#' * HUMAN (CONTROL) - distance to international border, distance to Provincial Capital, PA presence, PA category, economic land concession presence
#'
#' ## summary of results
#'
#' Unfortunately, none of the socioeconomic predictors appear to have any predictive power! The only exception is population density. The "control" variables (Environmental, Human, see above) however, do have some predictive power. Below I will show the results of the initial models for each set.
#'
#' My general conclusion thus far however is that with this response, I still don't think I am asking the question I want to. I think the models below are telling us which variables can predict forest cover (i.e. where is the forest? Which communes have lots of forest and which ones have little forest?). I don't think the below models can really tell me anything about forest ***loss***, or which variables are able to predict forest cover loss/change. I feel like I need to go further and look at forest cover change as a response (e.g. rate of change / difference in forest pixels). That's not to say that what I have done so far is not useful - I think in combination with further analysis we can build up a wider picture of forest cover and forest cover dynamics. For example, the overall analysis and our results could be made up of the following:
#'
#' * Which variables predict where forest cover is greatest / lowest across the country? (this is what I have done. Although at the moment the question is really "...where forest cover is greatest/lowest given there is SOME forest. This is because I removed all communes with 0 forest cover right at the start, as at that stage I was planning on useing rate of change as a response and so communes with no forest were false 0's)
#' * Which variables predict where forest is likely to be lost? (Presumably I could use binomial logistic model here: forest lost/not lost)
#' * Then subset the communes to only those that have lost some forest, and then model rate of change / magnitude of change. (Initially this is what I was going to do, either manually i.e. two steps, or via a hurdle model)
#'
#' I keep having to remind myself of what the purpose of this analysis is. The purpose is to use the resulting model(s) to predict where in the country forest is likely to be lost under various potential scenarios. I want to be able to highlight communes where forest cover is likely to be lost if, say, population density in rural areas goes up, or if the number of land conflicts in communes with land concessions spike. The aim WAS then to use these predictions to assess the robustness of the national wildlife corridor network to future changes. But in theory I could do a number of things, e.g. identifiy which PAs are most vulnerable to certain future scenarios etc.
#' The main point being though, is that I don't think I can use the below models to do that.
#'
#' Unless I am mis-understanding the usefulness of the models below. Please feel free to correct me if you think I am interpreting this incorrectly. The only way I can think to use these models to do what I want, is using the below approach:
#'
#' * Ignore the "global" model (i.e. the model with RE's set to means)
#' * Pull out the individual communes of interest, e.g. the ones within the wildlife corridor, or the ones in/around the PAs
#' * run the commune-specific models (i.e. with RE's specific to that commune) with varying ranges of the predictors, e.g. increasing population density.
#'
#' That approach above though, doesn't feel right to me. This is because at the moment, if I adjusted model parameters to simulate a particular commune increasing, say, its population density, I don't feel like the result would reflect forest cover dynamics in that commune. I feel like it would be more llike saying - "if this commune happened to have a higher population density, it would probably have this amount of forest", which I think is subtley but importantly different from saying - "if population density increased in this communes, this commune would likely lose xx amount of forest".
#'
#' The other obvious problem with the above approach is that I don't really have any socioeconomic predictors (apart from population density) to play with as they're all a bit shit! The other predictor variables that have some predictive power are mostly unchangeable i.e. elevation, distance to Provincial capital etc.
#'
#' So I am currently unsure how best to proceed, and I would very much appreciate some guidance! Below I will summarise the models, the diagnostics, and the predictions.
#'
#' # Model results
#'
#' ## Population demographics
#'
#' Full population demographics model below. `tot_pop` = total population, `pop_den` = population density, `prop_ind` = proporition indigneous.
#+ popdem.m1
popdem.m1 <- glmer(ForPix ~ tot_pop + pop_den + prop_ind + offset(log(areaKM)) + (year|Province/Provcomm),
data=dat1, family="poisson")
summary(popdem.m1)
#' Variance for Province and commune are similar. Variance for year at both levels is small, but an order of magnitude smaller for the Province level. Approximate p values are significant for pop_den only. tot_pop is positive effect, pop_den and prop_ind are negative. No real correlation between fixed effects.Note: I did run the model without offset and the variance for Province and Provcomm:Province were double what they are now that offset is included.
#'
#' Plot the random effects. First plot is Commune and year, second plot is Province and year
#+ popdem.m1 RE plots, echo=FALSE, results=TRUE
plot_model(popdem.m1, type="re")
#' The model summary and likelihood ratio tests suggested proportion indigneous was contributing little, and so that variable was dropped. There was evidence of an interaction between population density and total population, and likelihood ratio tests suggested the model with both terms in was better than the model with only population density, but these two variables are intrinsically linked, and so I dropped total population, as it had the weaker effect. As a note on LRT's - my protocol was to begin with simple 'anova(test="Chisq")' and if there was a variable/model that had a p-value that was hovering around 0.05, then I would progress to another test (e.g. profiled CI's, bootstrapping, but this was never really necessary).
#'
#' Therefore the final population demographics model is:
#'
#+ popdem.m6,
popdem.m6 <- glmer(ForPix ~ pop_den + offset(log(areaKM)) + (year|Province/Provcomm),
data = dat1, family = "poisson")
summary(popdem.m6)
#' ### Diagnostics
#'
#+ popdem.m6 predictions and residuals, include=FALSE
# copy data
m6.diag.dat <- dat1
m6.diag.dat$Provcomm <- as.factor(m6.diag.dat$Provcomm)
# Make "fitted" predictions, i.e. fully conditional:
m6.diag.dat$m6pred <- predict(popdem.m6, type = "response")
# attach residuals
m6.diag.dat$m6res <- resid(popdem.m6)
#' Plot of predicted values vs observed values
#+ popdem.m6 fitted vs observed plot, echo=FALSE, results=TRUE
plot(m6.diag.dat$ForPix, m6.diag.dat$m6pred, ylab = "Predicted ForPix", xlab = "Observed ForPix")
#' This plot looks good.
#'
#' Below is a plot of residuals vs fitted values
#'
#+ popdem.m6 plot fitted vs residuals, echo=FALSE,results=TRUE
plot(m6.diag.dat$m6pred, m6.diag.dat$m6res)
#' Quite bad heterogeneity here. Jeroen suggested this could be due to missing predictors, however this was also the case for previous models that had the other 2 predictors. At low predicted values, error is greater. As Jeroren said - given the structure in the data, this is almost inevitable given the extent of variation across communes. As we will see, this is an issues with all of the models.
#'
#' Exploration of the residuals over the predictors, and between provinces and communes:
#'
#+ popdem.m6 residual plots, echo=FALSE,results=TRUE, fig.width=10, fig.height=10, dpi=100
par(mfrow=c(2,2))
plot(m6.diag.dat$pop_den, m6.diag.dat$m6res, ylab = "residuals", xlab = "pop density")
boxplot(m6res ~ factor(Province), data = m6.diag.dat, outline = T, xlab = "Province", ylab = "Residuals w/i Province")
boxplot(m6res ~ factor(Provcomm), data = m6.diag.dat, outline = T, xlab = "Commune", ylab = "Residuals w/i Commune")
#' A lot of the heterogeneity is driven by relatively few communes/provinces. I investigated further. If you look at the map (in GIS), the provinces with the smallest residuals are the smaller provinces in the south surrounding the capital Phnom Penh. These are provinces that generally have very little forest. But they are not the only provinces with no forest cover, so I am not sure that is the (only) reason. I think I need to look at the communes within the provinces.
#'
#+ popdem.m6 extract problem residuals, include=FALSE
provs <- c("Battambang","Kampong Chhnang","Kampong Thom","Kracheh","Pursat","Ratanak Kiri","Siem Reap",
"Stung Treng")
# extract all original data from those provinces
prov.dat <- dat %>% filter(Province %in% provs)
prov.dat$type <- "problem"
# create subset of all data NOT including the above
prov.excl <- dat %>% filter(!Province %in% provs)
prov.excl$type <- "other"
prov.all <- rbind(prov.dat,prov.excl)
#' Here I plot forest pixels for each commune, separated by the communes with high residuals in the model ("problem"), and the rest ("other"):
#'
#+ popdem.m6 plot problem communes ForPix, echo=FALSE, results=TRUE, warnings=FALSE
ggplot(prov.all, aes(Commune,y=ForPix, colour=type))+
geom_point()+
theme(element_blank())+
ylab("Forest pixels")
#' I would say that the provinces that are causing the issues tend to have higher ForPix than the others. It also look potentially like the provinces causing issues are almost always losing forest cover over time (lots of vertical lines of dots).
#'
#' Plot of population density (the predictor) against forest pixels, split by the problem communes again. I have zoomed in on both axes so we can see what is going on a bit better:
#'
#+ popdem.m6 plot problem communes ForPix ~ pop_den, echo=FALSE, results=TRUE, warning=FALSE
ggplot(prov.all, aes(x=pop_den, y=ForPix, colour=type))+
geom_point()+
ylim(0,10000)+
xlim(0,1000)+
theme(element_blank())+
ylab("Forest pixels")+
xlab("population density")
#' This plot makes it also look like the problem provinces tend to have communes with higher ForPix (although this is clearly not true for all communes). There is a chunk of blue with no pink where pop_den has increased to about 100 but ForPix has not decreased (whereas almost all the pink dots are lower, i.e. in the other provinces/communes at that population density forest cover is lower).
#'
#' The plot below shows the forest pixels by province (rather than commune), split by the problem provinces.
#'
#+ popdem.m6 plot problem provinces and ForPix, echo=FALSE, results=TRUE, warning=FALSE
ggplot()+
geom_boxplot(data=prov.dat, aes(x=Province, y=ForPix,colour="Problem provinces"))+
geom_boxplot(data=prov.excl, aes(x=Province, y=ForPix, colour="Other provinces"))+
ylim(0,10000)+
theme(element_blank())+
ylab("Forest pixels")
#' This plot suggests that the problem provinces don't necessarily have more (mean) forest cover, but they do tend to have more outliers (individual communes) that are very high forest cover.
#'
#' The plot below shows the population density by province, split by the problem provinces.
#'
#+ popdem.m6 plot problem provinces and pop_den, echo=FALSE, results=TRUE, warning=FALSE
ggplot()+
geom_boxplot(data=prov.dat, aes(x=Province, y=pop_den,colour="Problem provinces"))+
geom_boxplot(data=prov.excl, aes(x=Province, y=pop_den, colour="Other provinces"))+
theme(element_blank())+
ylab("Population density")
#' This plot suggests that overall, the problem provinces tend to have lower median pop_den value compared to the other provinces, but they again tend to have more outliers. This is what I would expect - the communes with lower population density will also likely be the communes with higher forest cover (as we saw in the above plots).
#'
#' The plot below shows the same as above but by communes, rather than province
#'
#+ popdem.m6 plot problem communes and pop_den, echo=FALSE, results=TRUE, warning=FALSE
ggplot()+
geom_boxplot(data=prov.dat, aes(x=Commune, y=pop_den,colour="Problem provinces"))+
geom_boxplot(data=prov.excl, aes(x=Commune, y=pop_den, colour="Other provinces"))+
ylim(0,1000)+
theme(element_blank())+
ylab("Population density")
#' Although slightly difficult to interpret, again this looks like there are more communes with higher pop_den values in the non-problematic provinces. And in the problem communes with higher population density values, they also tend to have much more variation in population density (i.e. the pop_den changes a lot over time)
#'
#' The plot below shows the problem communes and their forest pixels:
#'
#+ popdem.m6 plot problem communes and ForPix, echo=FALSE, results=TRUE, warning=FALSE
ggplot()+
geom_boxplot(data=prov.dat, aes(x=Commune, y=ForPix,colour="Problem provinces"))+
geom_boxplot(data=prov.excl, aes(x=Commune, y=ForPix, colour="Other provinces"))+
ylim(0,10000)+
theme(element_blank())+
ylab("Forest pixels")
#' Again, difficult to see a huge amount, however I would say that it looks like the problem provinces in general have more variation in ForPix, both within communes and between communes.
#'
#' If you look at the plot of the main effect below, the line is pretty flat, even at low pop_den and ForPix values. This is where the model is not predicitng well for communes with low population density but higher forest cover. This is because there is so much variation in the communes - i.e. there are so many that have low pop_den but low ForPix, which is dragging the model down. So the communes with large residuals are going to be the commune with low pop_den values and higher ForPix values I think. I do not think there is much I can do about this? Would including year as a fixed effect perhaps help account for the variation within communes across years?
#'
#' ### Predict main (global) effects
#'
#+ popdem.m6 predict & plot main effects, echo=FALSE, results=TRUE
# create new data
m6.newdat <- data.frame(pop_den = seq(from=min(dat1$pop_den), to=max(dat1$pop_den), length.out = 100),
areaKM = mean(dat1$areaKM))
# add predictions
m6.newdat$pred <- as.vector(predict(popdem.m6, type="response", newdata=m6.newdat, re.form=NA))
# plot with free y axis
popdem.m6.p1 <- ggplot(m6.newdat, aes(x=pop_den, y=pred))+
geom_line()+
theme(element_blank())+
xlab("Population density (scaled and centered)")+
ylab("Predicted forest pixels")
# plot with large y axis
popdem.m6.p2 <-ggplot(m6.newdat, aes(x=pop_den, y=pred))+
geom_line()+
ylim(0,5000)+
theme(element_blank())+
xlab("Population density (scaled and centered)")+
ylab("Predicted forest pixels")
popdem.m6.p1 + popdem.m6.p2
#' We can see in the plots above that the effect is there (left plot), but it is small when you look at it with a more realistic y-axis, i.e. with forest pixel values more like those that are actually seen (right plot)
#'
#' ### Predict for specific communes
#'
#' Here I want to plot grids of different communes with the overall predicted effect, plus the commune-specific effect. I want to do this for communes with commune-level intercepts close to the mean, and communes with commune-level intercepts at the extremes. I will also do this for a random sample of communes.
#'
#+ popdem.m6 commune predictions, echo=FALSE, results=T,fig.width=10, fig.height=10, dpi=100
# save the popdem.m4 commune-level random effects
m6.re.com <- ranef(popdem.m6)[[1]]
# re-order
m6.re.com <- m6.re.com[order(m6.re.com[ ,"(Intercept)"], decreasing = FALSE),]
# which communes
coms <- c("Pursat_Ansa Chambak","Kampong Cham_Kraek", "Ratanak Kiri_Pak Nhai","Kampong Speu_Tang Samraong",
"Kampong Chhnang_Chieb","Kampot_Preaek Tnaot","Battambang_Chhnal Moan","Phnom Penh_Chak Angrae Kraom",
"Kampong Thom_Chaeung Daeung","Kracheh_Han Chey","Siem Reap_Nokor Pheas","Kampong Thom_Tang Krasang")
# which provinces
provs <- c("Pursat","Kampong Cham","Ratanak Kiri","Kampong Speu",
"Kampong Chhnang","Kampot","Battambang","Phnom Penh",
"Kampong Thom","Kracheh","Siem Reap","Kampong Thom")
### I am making commune-specific predictions, so should customise the range of population densities I am predicting for, on the basis of each commune.
### Easiest to define the range of pop_den to predict for, first. Min/max per commune:
pop_den_min <- tapply(dat1$pop_den, dat1$Provcomm, min)
pop_den_max <- tapply(dat1$pop_den, dat1$Provcomm, max)
### Min/max within your selection of communes:
pop_den_min <- min(pop_den_min[names(pop_den_min) %in% coms])
pop_den_max <- max(pop_den_max[names(pop_den_max) %in% coms])
### Not really any different from the overall min and max
# create new prediction grid for specific communes with varying pop_den
m6_newdat_com <- data.frame(Provcomm = rep(coms, each=100),
Province = rep(provs, each=100),
pop_den = seq(from=pop_den_min, to=pop_den_max, length.out = 100),
year = mean(dat1$year))
# add commune-specific areaKM offset
m6_newdat_com$areaKM <- dat1$areaKM[match(m6_newdat_com$Provcomm, dat1$Provcomm)]
# re-order levels so they plot in the correct sets
m6_newdat_com$Provcomm <- factor(m6_newdat_com$Provcomm,
levels = c("Pursat_Ansa Chambak","Kampong Cham_Kraek", "Ratanak Kiri_Pak Nhai",
"Kampong Speu_Tang Samraong","Kampong Chhnang_Chieb","Kampot_Preaek Tnaot",
"Battambang_Chhnal Moan","Phnom Penh_Chak Angrae Kraom",
"Kampong Thom_Chaeung Daeung","Kracheh_Han Chey","Siem Reap_Nokor Pheas",
"Kampong Thom_Tang Krasang"))
# attach commune-specific predictions
m6_newdat_com$pred.com <- as.vector(predict(popdem.m6, type="response", newdata=m6_newdat_com,
re.form=~(year|Province/Provcomm)))
# attach global predictions
m6_newdat_com$pred.glo <- rep(m6.newdat$pred, times=12)
### The following plot can either "overlay" the observed ForPix count against observed population densities for the communes, or I can split by commune. comment out the if(i==1) statement and set par() if you want a grid
### Pick some colours using RColorBrewer using a completely overelaborate piece of crap code... Anyway this is just to
#try to help see the differences between communes more clearly in the observed points in particular (you can comment the
#following lines out if you want)
require(RColorBrewer)
com_colours <- brewer.pal(11, "RdYlBu")
com_colours <- c(head(com_colours,4),tail(com_colours,4))
com_colours_greys <- tail(brewer.pal(9, "Greys"),4)
com_colours <- c(com_colours, com_colours_greys)
com_colours <- com_colours[sample(1:length(com_colours),12,replace=F)]
### This is just to check if you have commented tbe above out: :)
if(!exists("com_colours")) {
com_colours <- rep("black", 12)
}
provcomm_lvls <- levels(m6_newdat_com$Provcomm)
par(mfrow = c(3,4))
### Note the scales are important here - we need to set a scale that encompasses all the communes and the full
### population density range across all communes, so we need to do this overall:
ylo <- min(m6_newdat_com$pred.com)*0.9
yhi <- max(m6_newdat_com$pred.com)*1.1
xlo <- min(dat1[dat1$Provcomm %in% levels(m6_newdat_com$Provcomm),"pop_den"])
xhi <- max(dat1[dat1$Provcomm %in% levels(m6_newdat_com$Provcomm),"pop_den"])
### Iterate through the communes (levels in m6_newdat_com$Provcomm):
for(i in 1:length(provcomm_lvls)) {
### Pick commune i data from the predictions:
preddat_i <- m6_newdat_com[m6_newdat_com$Provcomm==provcomm_lvls[i],]
### Pick commune i data from observed data:
dat_i <- dat1[dat1$Provcomm==provcomm_lvls[i],]
## If this is the first plot, use plot(), otherwise lines() to add to an existing plot:
# if(i == 1) {
# Plot predicted ForPix as function of pop_den; as "line" type. Note this is where you set axis limits.
plot(preddat_i$pop_den,preddat_i$pred.com,
type = "l",
col = com_colours[i],
ylim = c(ylo,yhi), xlim = c(xlo,xhi),
xlab = "Population density (scaled & standardised",
ylab = "Predicted forest cover pixels")
# } else {
lines(preddat_i$pop_den,preddat_i$pred.com, col = com_colours[i])
lines(preddat_i$pop_den,preddat_i$pred.glo, lty=2)
#}
## Add points for "observed" ForPix for commune i across all observed pop_den across communes.
points(dat_i$pop_den, dat_i$ForPix, pch = 21, bg = com_colours[i], col = com_colours[i])
}
#' In the above plots, the top row are communes with intercepts closest to the mean, the middle row are communes with intercepts furthest above the mean, and the bottom row are communes with intercepts furthest below the mean. The coloured solid lines are the commune-specific predictions, i.e. those made using all RE's specific to that commune. The dashed black line is the global model (i.e. for an "average" commune). The points are the actual pop_den ~ ForPix values for that commune. The plots support the diagnostics in the section above - the global model does not predict well for communes with high forest cover - because the global model always predicts low forest cover, even for communes with low population density. Essentially there are too many communes with low forest cover, and so the global model is dragged down, meaning that the communes with high forest cover get poor predictions. This does suggest though that the global model predicts well at high population density values, as these communes tend to have low forest cover.
#'
#' Now I will do the same but for 9 random selections of 9 communes.
#'
#+ popdem.m6 commune predictions from random selection, echo=FALSE,results=TRUE, fig.width=10, fig.height=10, dpi=100
# randomly sample communes
par(mfrow = c(3,3))
set.seed(123)
runs <- c(1:9)
for(i in 1:length(runs)){
rand.com <- sample(dat1$Provcomm,9, replace = FALSE)
rand.prov <- unlist(strsplit(rand.com, "_"))
rand.prov <- rand.prov[c(1,3,5,7,9,11,13,15,17)]
# define the range of pop_den to predict for, first. Min/max per commune:
pop_den_min <- tapply(dat1$pop_den, dat1$Provcomm, min)
pop_den_max <- tapply(dat1$pop_den, dat1$Provcomm, max)
# Min/max within your selection of communes:
pop_den_min <- min(pop_den_min[names(pop_den_min) %in% rand.com])
pop_den_max <- max(pop_den_max[names(pop_den_max) %in% rand.com])
# create new prediction grid for specific communes with varying pop_den
m6_newdat_com_ran <- data.frame(Provcomm = rep(rand.com, each=100),
Province = rep(rand.prov, each=100),
pop_den = seq(from=pop_den_min, to=pop_den_max, length.out = 100),
year = mean(dat1$year))
# add commune-specific areaKM offset
m6_newdat_com_ran$areaKM <- dat1$areaKM[match(m6_newdat_com_ran$Provcomm, dat1$Provcomm)]
# attach commune-specific predictions
m6_newdat_com_ran$pred.com <- as.vector(predict(popdem.m6, type="response", newdata=m6_newdat_com_ran,
re.form=~(year|Province/Provcomm)))
# attach global predictions
m6_newdat_com_ran$pred.glo <- rep(m6.newdat$pred, times=9)
# set levels
m6_newdat_com_ran$Provcomm <- as.factor(m6_newdat_com_ran$Provcomm)
provcomm_lvls <- levels(m6_newdat_com_ran$Provcomm)
# set scales
ylo <- min(m6_newdat_com_ran$pred.com)*0.9
yhi <- max(m6_newdat_com_ran$pred.com)*1.1
xlo <- pop_den_min
xhi <- pop_den_max
# Iterate through the communes (levels in m6_newdat_com$Provcomm):
for(i in 1:length(provcomm_lvls)) {
### Pick commune i data from the predictions:
preddat_i <- m6_newdat_com_ran[m6_newdat_com_ran$Provcomm==provcomm_lvls[i],]
### Pick commune i data from observed data:
dat_i <- dat1[dat1$Provcomm==provcomm_lvls[i],]
## If this is the first plot, use plot(), otherwise lines() to add to an existing plot:
if(i == 1) {
# Plot predicted ForPix as function of pop_den; as "line" type. Note this is where you set axis limits.
plot(preddat_i$pop_den,preddat_i$pred.com,
type = "l",
col = com_colours[i],
ylim = c(ylo,yhi), xlim = c(xlo,xhi),
xlab = "Population density (scaled & standardised",
ylab = "Predicted forest cover (forest pixel count)")
} else {
lines(preddat_i$pop_den,preddat_i$pred.com, col = com_colours[i])
lines(preddat_i$pop_den,preddat_i$pred.glo, lty=2)
}
## Add points for "observed" ForPix for commune i across all observed pop_den across communes.
points(dat_i$pop_den, dat_i$ForPix, pch = 21, bg = com_colours[i], col = com_colours[i])
}
}
#'
#' The above plots I think support the assessment that the global model predicts poorly for most communes, but I would expect this as there is so much variation between communes, it would be impossible to get a single model that predicted well. The above plots suggest that the commune-specific models predict better for communes where population density changes over time, but they predict poorly for communes when forest pixels change over time (i.e. forest is lost). Communes with more forest are, in general, more likely to lose forest (see plot below), which I think exacerbates the problem of the global model predicting poorly for communes with high forest cover i.e. it's a double whammy of poor predictions due to high forest cover, and poor predictions due to forest loss.
#'
#+ plot forest loss comparison between high and low forested communes, echo=FALSE,results=TRUE
## check whether communes with more forest are more likely to lose forest
# separate dat1 into the quarter with the most forest and then the rest
com.for <- dat1[dat1$ForPix>982,] # 982 is the 3rd quantile
com.for1 <- dat1[!(dat1$Provcomm %in% com.for$Provcomm),]
# summarise forest loss
com.for <- com.for %>% group_by(Provcomm) %>%
summarise(diffPix_sum = sum(diffPix))
com.for$type <- "high forest"
com.for1 <- com.for1 %>% group_by(Provcomm) %>%
summarise(diffPix_sum = sum(diffPix))
com.for1$type <- "low forest"
com.for.all <- rbind(com.for,com.for1)
ggplot(com.for.all, aes(x=type, y=diffPix_sum, colour=type))+
geom_boxplot()+
xlab("Commune")+
ylab("Forest pixels lost over study period")+
theme(element_blank())
#' The above plot splits the communes by forest cover - communes in the top 3rd quarter of most forested are in the "high forest" category, and the rest are in the "low forest" category. I have then summed the difference in pixels within each commune across the study period (i.e. if a commune loses 10 pixels each year it would have a y-axis value of 50). We can see that the communes with more forest, are more likely to lose forest.
#'
#'
#' ## Education
#'
#' There is only one variable in this set - the number of males aged 6-24 in school. There were more raw variables, but they were all highly correlated and so this one was taken forward as I think it is the most relevant to forest cover. This is because young men are the most likely to be engaging in agriculture, forest clearance, logging etc.
#'
#+ edu.m1, include=TRUE
edu.m1 <- glmer(ForPix ~ M6_24_sch + offset(log(areaKM)) + (year|Province/Provcomm), family="poisson", data=dat1)
summary(edu.m1)
#' The model output suggests there is nothing going on here. I can use 'plot_model' from the sjPlot package to quickly plot a prediction. It basically does exactly what I would do - create newdata with the variable of interest varying from the min to the max, and holding all others at their mean. You can specify whether you want it to plot conditional on the fixed effects only (i.e. "average" comune / global model), or on the random effects. The below is conditionl on fixed effects only.
#'
#+ edu.m1 plot_model, echo=FALSE, results=TRUE
plot_model(edu.m1, type="pred", terms="M6_24_sch")
#' Flat as a pancake.
#'
#' Below are some commune-specific predictions from another random selection of communes
#'
#+ edu.m1 commune predictions, echo=FALSE,results=T, fig.width=10, fig.height=10, dpi=100
par(mfrow = c(3,3))
set.seed(123)
runs <- c(1:9)
for(i in 1:length(runs)){
# randomly sample communes
rand.com <- sample(dat1$Provcomm, 9, replace = FALSE)
rand.prov <- unlist(strsplit(rand.com, "_"))
rand.prov <- rand.prov[c(1,3,5,7,9,11,13,15,17)]
# define the range of pop_den to predict for, first. Min/max per commune:
M6_24_sch_min <- tapply(dat1$M6_24_sch, dat1$Provcomm, min)
M6_24_sch_max <- tapply(dat1$M6_24_sch, dat1$Provcomm, max)
# Min/max within your selection of communes:
M6_24_sch_min <- min(M6_24_sch_min[names(M6_24_sch_min) %in% rand.com])
M6_24_sch_max <- max(M6_24_sch_max[names(M6_24_sch_max) %in% rand.com])
# create new prediction grid for specific communes with varying pop_den
edu.m1_newdat_com_ran <- data.frame(Provcomm = rep(rand.com, each=100),
Province = rep(rand.prov, each=100),
M6_24_sch = seq(from=M6_24_sch_min, to=M6_24_sch_max, length.out = 100),
year = mean(dat1$year))
# add commune-specific areaKM offset
edu.m1_newdat_com_ran$areaKM <- dat1$areaKM[match(edu.m1_newdat_com_ran$Provcomm, dat1$Provcomm)]
# attach commune-specific predictions
edu.m1_newdat_com_ran$pred.com <- as.vector(predict(edu.m1, type="response",
newdata=edu.m1_newdat_com_ran,
re.form=~(year|Province/Provcomm)))
# global predictions
edu.m1_glo_pred <- data.frame(M6_24_sch = rep(min(dat1$M6_24_sch),max(dat1$M6_24_sch), length.out=100),
areaKM = mean(dat1$areaKM))
edu.m1_glo_pred$pred <- as.vector(predict(edu.m1, type="response", newdata=edu.m1_glo_pred,re.form=NA))
# attach global predictions
edu.m1_newdat_com_ran$pred.glo <- rep(edu.m1_glo_pred$pred, times=9)
# set levels
edu.m1_newdat_com_ran$Provcomm <- as.factor(edu.m1_newdat_com_ran$Provcomm)
provcomm_lvls <- levels(edu.m1_newdat_com_ran$Provcomm)
# set scales
ylo <- min(edu.m1_newdat_com_ran$pred.com)*0.9
yhi <- max(edu.m1_newdat_com_ran$pred.com)*1.1
xlo <- M6_24_sch_min
xhi <- M6_24_sch_max
# Iterate through the communes
for(i in 1:length(provcomm_lvls)) {
### Pick commune i data from the predictions:
preddat_i <- edu.m1_newdat_com_ran[edu.m1_newdat_com_ran$Provcomm==provcomm_lvls[i],]
### Pick commune i data from observed data:
dat_i <- dat1[dat1$Provcomm==provcomm_lvls[i],]
## If this is the first plot, use plot(), otherwise lines() to add to an existing plot:
if(i == 1) {
# Plot predicted ForPix as function of pop_den; as "line" type. Note this is where you set axis limits.
plot(preddat_i$M6_24_sch,preddat_i$pred.com,
type = "l",
col = com_colours[i],
ylim = c(ylo,yhi), xlim = c(xlo,xhi),
xlab = "Proportion of males aged 6-24 in school (scaled & standardised",
ylab = "Predicted forest pixels")
} else {
lines(preddat_i$M6_24_sch,preddat_i$pred.com, col = com_colours[i])
lines(preddat_i$M6_24_sch,preddat_i$pred.glo, lty=2)
}
## Add points for "observed" ForPix for commune i across all observed pop_den across communes.
points(dat_i$M6_24_sch, dat_i$ForPix, pch = 21, bg = com_colours[i], col = com_colours[i])
}
}
#' I think it is fair to say that there is no relationship between forest cover and males in school.
#'
#' ## Employment
#'
#' There are two variables in this set - the proportion of the population engaged in the Primary Sector and the proportion engaged in the Secondary Sector. The primary sector includes sectors of the economy that extracts or harvests products from the earth such as raw materials and basic foods, and includes farming, fishing, mining etc. The secondary sector includes the production of finished goods from raw materials, and includes manufacturing, processing, and construction.
#'
#' I have no *a priori* hypothesis about an interaction between these two variables, and so I have not tested one. It is also plausible that although these two are not correlated (-0.2), they may well be related as they are both proportions drawn from the same population, therefore including an interaction might be misleading.
#'
#' The model:
#'
#+ emp.m1, include=TRUE
emp.m1 <- glmer(ForPix ~ propPrimSec + propSecSec + offset(log(areaKM)) + (year|Province/Provcomm),
family="poisson", data=dat1)
summary(emp.m1)
#' Province and commune variance similar to other model sets. Year variance for commune is an order of magnitude larger than for province, but both very small. propPrimSec has positive effect, propSecSec has negative, but both very small and approximate p values > 0.5. The model produces a warning about large eigenvalues. The variables are already scaled so I guess this just suggests a poor model fit.
#'
#' Quick plot of the effects
#'
#+ plot_model emp.m1, echo=FALSE, results=TRUE
plot_model(emp.m1, type="re")
plot_model(emp.m1, type="pred", terms=c("propPrimSec"))
plot_model(emp.m1, type="pred", terms=c("propSecSec"))
#' These two variables do not appear to be important. I will try and remove propSecSec
#'
#+ emp.m2, include=TRUE
emp.m2 <- glmer(ForPix ~ propPrimSec + offset(log(areaKM)) + (year|Province/Provcomm), family="poisson", data=dat1)
summary(emp.m2)
#' Compare the two models:
#'
#+ anova emp.m1 and emp.m2, include=TRUE
anova(emp.m1, emp.m2, test="Chisq")
#' The simpler model is better, but is still pretty uninteresting
#'
#' ## Economic Security
#'
#' In this set there are two variables - the proportion of families who have less than 1 hectare of agricultural land, and the proportion of families who keep pigs. Both of these things are fairly good proxies for a family's economic security, especially the farming land variable.
#'
#+ econ.m1, include=TRUE
econ.m1 <- glmer(ForPix ~ Les1_R_Land + pig_fam + offset(log(areaKM)) + (year|Province/Provcomm),
family="poisson", data=dat1)
summary(econ.m1)
#' Very small effects with large approximate p values. Random effects similar to previous models. Les1_R_Land has a tiny negative effect, pig_fam has a small positive effect.
#'
#' Quick plot of the main effects:
#'
#+ plot_model econ.m1, echo=FALSE, results=TRUE
plot_model(econ.m1, type="pred", terms="Les1_R_Land")
plot_model(econ.m1, type="pred", terms="pig_fam")
#' Again, these variables do not look like they can provide much. I did run model selection, and the simpler models (i.e. with just one of the vars) were better than model 1 with both variables, but the effects were similarly tiny.
#'
#' ## Access to Services
#'
#' This model set has three variables - median distance to the nearest school, median distance to the Commune office, and the proportion of families with access to waste collection.
#'
#+ acc.m1, include=TRUE
acc.m1 <- glmer(ForPix ~ dist_sch + garbage + KM_Comm + offset(log(areaKM)) +
(year|Province/Provcomm),family="poisson", data=dat1)
summary(acc.m1)
#' Also produces warning about large eigenvalues. All three variables have tiny effects with large approximate p values.
#'
#' Quick plots of the main effects
#'
#+ plot_model acc.m1, echo=FALSE, results=TRUE
plot_model(acc.m1, type="pred", terms="dist_sch")
plot_model(acc.m1, type="pred", terms="garbage")
plot_model(acc.m1, type="pred", terms="KM_Comm")
#' These variables do not appear to be useful. I completed model selection using a combination of LRT's and AICc comparison, and all of the models with only an individual predictor were better than any model with more than one predictor. The top three models were therefore models with each of the single predictors, and there was virtually no difference between them (dAICc < 0.1). But they were equally as useless as the acc.m1 i.e. tiny effects, large approximate p values, flat main effect.
#'
#' ## Social Justice
#'
#' This set includes two predictor variables - the raw number of land conflict cases, and the per capita number of criminal cases. I had no *a priori* hypothesis about an interaction between these two variables, and so I did not test one.
#'
#+ just.m1, include=TRUE
jus.m1 <- glmer(ForPix ~ crim_case + land_confl + offset(log(areaKM)) + (year|Province/Provcomm),
family="poisson", data=dat1)
summary(jus.m1)
#' Very small effects with large approximate p values. Similar RE variances to previous model sets.
#'
#' Quick plots of main effects:
#'
#+ plot_model jus.m1, echo=FALSE, results=TRUE
plot_model(jus.m1, type="pred", terms="crim_case")
plot_model(jus.m1, type="pred", terms="land_confl")
#' I removed land_confl for jus.m2, and LRT suggested the simpler model was better, but the resulting model still had tiny effect for crim_case, with large approximate p value. The plot was just as flat as jus.m1.
#'
#' ## Migration
#'
#' There are two predictors in this set - raw number of in-migrants and out-migrants. For these variables, I thought there was cause to test an interaction, as the relationship between migration in and out of a commune is potentially complex, and intertwined with various aspects of the local economy and natural resource use.
#'
#+ mig.m1, include=TRUE
mig.m1 <- glmer(ForPix ~ Pax_migt_in*Pax_migt_out + offset(log(areaKM)) + (year|Province/Provcomm),
family="poisson", data=dat1)
summary(mig.m1)
#' Very small effects and large approximate p values. No change in the RE variances
#'
#' Quick plots of the marginal effects of interaction terms:
#'
#+ plot_model mig.m1, echo=FALSE, results=TRUE
plot_model(mig.m1, type="pred", terms=c("Pax_migt_in","Pax_migt_out[-0.47,0,16.7]"))
plot_model(mig.m1, type="pred", terms=c("Pax_migt_out","Pax_migt_in[-0.53,0,11.1]"))
#' There appears to be a small interaction. When out-migration from a commune is large, then the effect of in-migration is positive, whereas there is no effect when out-migration is low or at its mean. Similarly, when in-migration to a commune is large, then there is a small positive effect of out-migration. There is no effect of out-migration when in-migration is low or at its mean. Nevertheless, neither term, nor the interaction are particularly convincing. Model selection using LRT suggested that a model with just Pax_migt_out was significantly better than the model with both terms. And the resulting model has as equally unimpressive effect.
#'
#+ mig.m2, include=TRUE
mig.m2 <- glmer(ForPix ~ Pax_migt_out + offset(log(areaKM)) + (year|Province/Provcomm),
family="poisson", data=dat1)
summary(mig.m2)
anova(mig.m1,mig.m2,test="Chisq")
# simpler model is better
plot_model(mig.m2, type="pred", terms="Pax_migt_out")
#' ## Environmental variables
#'
#' This set initially had two predictor variables - mean elevation and habitat. These variables were intially supposed to be "control" variables, i.e. ensuring that other, non-socioeconomic predictors that would be likely to affect forest cover, were taken into account. I did run some models, diagnostics, and predictions using both variables, but I have decided to drop habitat altogether. This is because the layer I was using for the habitat was the same layer that produced the response - i.e. to get the "forest pixel" layer used in the response, I simply aggregated all of the forest habitat types. Therefore I don't think it is appropriate to use the same layer as a predictor! That leaves me with mean elevation.
#'
#+ env.m2 elevation only, include=TRUE
env.m2 <- glmer(ForPix ~ mean_elev + offset(log(areaKM)) + (year|Province/Provcomm),
family = "poisson", data=dat1)
summary(env.m2)
#' The RE variances have decreased slightly compared to previous model sets, suggesting that the elevation predictor is explaning more of the total variance. Elevation appears to have a positive effect on forest pixels and appears significant (very small approximate p value).
#'
#' ### Diagnostics
#'
#+ env.m2 diagnostics 1, include=FALSE
# copy data
env.m2.diag <- dat1
env.m2.diag$Provcomm <- as.factor(env.m2.diag$Provcomm)
# attach residuals
env.m2.diag$m2res <- resid(env.m2)
# attach conditional predictions
env.m2.diag$m2pred <- as.vector(predict(env.m2, type="response"))
#+ env.m2 predicted vs observed plot, echo=FALSE, results=TRUE
plot(env.m2.diag$m2pred, env.m2.diag$ForPix)
#' The above plot is the predicted versus observed values, which looks good.
#+ env.m2 residuals vs fitted plot, echo=FALSE, results=TRUE
plot(env.m2.diag$m2pred, env.m2.diag$m2res)
#' The above plot is the predicted values versus model residuals. Again heteroskedasicity is an issues here - particularly bad a low predicted forest cover. Similar to the popdem models.
#'
#' Bit more exploration of residuals, but now over the explanatory variable:
#+ env.m2 residual plots, echo=FALSE, results=TRUE, fig.width=10, fig.height=10, dpi=100
par(mfrow=c(2,2))
plot(env.m2.diag$mean_elev, env.m2.diag$m2res, ylab = "residuals", xlab = "mean elevation")
boxplot(m2res ~ factor(Province), data = env.m2.diag, outline = T, xlab = "Province",
ylab = "Residuals w/i Province")
boxplot(m2res ~ factor(Provcomm), data = env.m2.diag, outline = T, xlab = "Commune",
ylab = "Residuals w/i Commune")
#' There seems to be a slightly odd pattern in the first plot - it looks like there are certain elevation values that produce large residuals. Zoom in:
#+ env.m2 elevation vs residuals, echo=FALSE, results=TRUE
plot(env.m2.diag$mean_elev, env.m2.diag$m2res, xlim = c(-1,2),ylab = "residuals", xlab = "mean elevation")
#' Looks like elevation values of approx -0.6, -0.4, -0.1, 0.2, 0.8.
#'
#' I will take a closer look at the Provinces that have the communes that appear to produce the largest residuals.
#'
#+ env.m2 provinces with largest residuals, echo=FALSE, results=TRUE
provs <- c("Battambang","Kampong Cham","Kampong Chhnang","Kampong Thom","Koh Kong","Kracheh",
"Mondul Kiri","Otdar Meanchey","Preah Sihanouk","Pursat","Ratanak Kiri","Siem Reap",
"Stung Treng")
prob.provs <- dat %>% filter(Province %in% provs)
prob.provs$type <- "problem"
other.provs <- dat %>% filter(!Province %in% provs)
other.provs$type <- "other"
all.provs <- rbind(prob.provs,other.provs)
# get provincial means
prov.elev.mean <- all.provs %>% group_by(Province) %>% summarise(mean = mean(mean_elev))
prov.elev.mean$type <- ifelse(prov.elev.mean$Province %in% provs, "problem", "other")
# plot mean elevation by province
ggplot(prov.elev.mean, aes(x=Province, y=mean, colour=type))+
geom_point(size=4)+
theme(element_blank())+
ylab("Mean elevation")
#' The above plot shows the mean elevation (on the original scale) for each Province, with the "problem" provinces (i.e. the ones with the largest residuals) coloured blue. There is not a striking trend, but the 4 provinces with the lowest mean elevation are all *not* problematic ones.
#'
#' Now I will pull out the individual communes that have residual values that match the weird pattern and see if there is any other pattern that might explain it.
#+ env.m2 prob.com, echo=FALSE, results=TRUE
par(mfrow=c(1,1))
prob.coms <- env.m2.diag %>% filter(m2res > 0.5 | m2res < -0.5)
plot(prob.coms$mean_elev, prob.coms$m2res)
#' The above plot are the "problem" residuals. These are now the communes with the weird shape. Let's have a look that these communes and their mean elevation (on the original scale), compared with all other communes:
#'
#+ env.m2 prob.coms, echo=FALSE, results=TRUE
coms <- prob.coms$Commune
prob.coms.orig <- dat[dat$Commune %in% coms,]
other.coms.orig <- dat %>% filter(!Commune %in% coms)
ggplot()+
geom_point(data=other.coms.orig, aes(x=Commune, y=mean_elev, colour="other"))+
geom_point(data=prob.coms.orig, aes(x=Commune, y=mean_elev, colour="problem"))+
theme(element_blank())+
ylab("Mean elevation")
#' I can't see an obvious pattern here. The other fixed effect is the offset - areaKM. Perhaps this is the source of the issue:
#'
#+ env.m2 prob.com - areaKM plot, echo=F, results=T
ggplot()+
geom_point(data=other.coms.orig, aes(x=Commune, y=areaKM, colour="other"))+
geom_point(data=prob.coms.orig, aes(x=Commune, y=areaKM, colour="problem"))+
theme(element_blank())+
ylab("Area (KM)")
#' No obvious pattern. Let's look at the response (ForPix):
#'
#+ env.m2 prob.com ForPix plot, echo=F, results=T
ggplot()+
geom_point(data=other.coms.orig, aes(x=Commune, y=ForPix, colour="other"))+
geom_point(data=prob.coms.orig, aes(x=Commune, y=ForPix, colour="problem"))+
theme(element_blank())+
ylab("Forest pixels")
#' Ok so there is an obvious difference here. The problem communes clearly mostly lose forest over time (vertical lines of dots), whereas the others generally do not (single points). This is the same issue as highlighted in the population demographics model. So the global model does not fit well when communes lose forest over time.
#'
#' ### Predict main effects
#'
#+ env.m2 predict main effects, echo=FALSE, results=TRUE
env_m2_newdata <- data.frame(mean_elev = seq(from=min(dat1$mean_elev), to=max(dat1$mean_elev),
length.out = 100),
areaKM = mean(dat1$areaKM))
# predict
env_m2_newdata$pred <- as.vector(predict(env.m2, type="response", newdata=env_m2_newdata,
re.form=NA))
# plot with free y axis
env.m2.main.plot <- ggplot(env_m2_newdata, aes(x=mean_elev, y=pred))+
geom_line()+
theme(element_blank())+
xlab("Mean elevation (scaled)")+
ylab("Predicted forest cover (pixels)")
# plot
env.m2.main.plot2 <- ggplot(env_m2_newdata, aes(x=mean_elev, y=pred))+
geom_line()+
theme(element_blank())+
ylim(0,20000)+
xlab("Mean elevation (scaled)")+
ylab("Predicted forest cover (pixels)")
env.m2.main.plot + env.m2.main.plot2
#' The above two plots show the predicted effects of mean elevation for an "average" commune (i.e. not commune-specific RE's), with a free y-axis (left) and with a realistic y axis (right). We can see that mean elevation has a positive effect on forest cover. I was expecting this relationship. Most of the highly forested areas in Cambodia are in the provinces with higher elevation.
#'
#' ### Predict for specific commmunes
#'
#' I will start by predicting for the 4 communes with intercepts closest to 0, the 4 communes with intercepts furthest above 0, and the communes with intercepts furthest below 0.
#'
#+ env.m2 commune predictions, echo=FALSE, results=TRUE, fig.width=8, fig.height=8, dpi=100
env.m2.com <- ranef(env.m2)[[1]]
# re-order
env.m2.com <- env.m2.com[order(env.m2.com[ ,"(Intercept)"], decreasing = FALSE),]
# which communes
coms <- c("Koh Kong_Bak Khlang","Kracheh_Bos Leav","Preah Vihear_Kuleaen Tboung","Ratanak Kiri_Saom Thum",
"Kampong Cham_Tuol Snuol","Banteay Meanchey_Paoy Char","Kampong Cham_Khpob Ta Nguon","Kampong Chhnang_Dar",
"Kampong Thom_Chaeung Daeung","Kracheh_Han Chey","Kampong Thom_Tang Krasang","Siem Reap_Nokor Pheas")
# which provinces
provs <- c("Koh Kong","Kracheh","Preah Vihear","Ratanak Kiri",
"Kampong Cham","Banteay Meanchey","Kampong Cham","Kampong Chhnang",
"Kampong Thom","Kracheh","Kampong Thom","Siem Reap")
# customise the range of elevations I am predicting for, on the basis of each commune.
### Easiest to define the range of mean_elev to predict for, first. Min/max per commune:
mean_elev_min <- tapply(dat1$mean_elev, dat1$Provcomm, min)
mean_elev_max <- tapply(dat1$mean_elev, dat1$Provcomm, max)
### Min/max within your selection of communes:
mean_elev_min <- min(mean_elev_min[names(mean_elev_min) %in% coms])
mean_elev_max <- max(mean_elev_max[names(mean_elev_max) %in% coms])
# create new prediction grid for specific communes with varying mean_elev
env_m2_newdat_com <- data.frame(Provcomm = rep(coms, each=100),
Province = as.factor(rep(provs, each=100)),
mean_elev = seq(from=mean_elev_min, to=mean_elev_max, length.out = 100),
year = mean(dat1$year))
# add commune-specific areaKM offset
env_m2_newdat_com$areaKM <- dat1$areaKM[match(env_m2_newdat_com$Provcomm, dat1$Provcomm)]
# re-order levels so they plot in the correct sets
env_m2_newdat_com$Provcomm <- factor(env_m2_newdat_com$Provcomm,
levels = c("Koh Kong_Bak Khlang",
"Kracheh_Bos Leav",
"Preah Vihear_Kuleaen Tboung",
"Ratanak Kiri_Saom Thum",
"Kampong Cham_Tuol Snuol",
"Banteay Meanchey_Paoy Char",
"Kampong Cham_Khpob Ta Nguon",
"Kampong Chhnang_Dar",
"Kampong Thom_Chaeung Daeung",
"Kracheh_Han Chey",
"Kampong Thom_Tang Krasang",
"Siem Reap_Nokor Pheas"))
# attach commune-specific predictions
env_m2_newdat_com$pred.com <- as.vector(predict(env.m2, type="response", newdata=env_m2_newdat_com,
re.form=~(year|Province/Provcomm)))
# attach global predictions
env_m2_newdat_com$pred.glo <- rep(env_m2_newdata$pred, times=12)
# colours
require(RColorBrewer)
com_colours <- brewer.pal(11, "RdYlBu")
com_colours <- c(head(com_colours,4),tail(com_colours,4))
com_colours_greys <- tail(brewer.pal(9, "Greys"),4)
com_colours <- c(com_colours, com_colours_greys)
com_colours <- com_colours[sample(1:length(com_colours),12,replace=F)]
### This is just to check if you have commented tbe above out: :)
if(!exists("com_colours")) {
com_colours <- rep("black", 12)
}
provcomm_lvls <- levels(env_m2_newdat_com$Provcomm)
par(mfrow = c(3,4))
### Note the scales are important here - we need to set a scale that encompasses all the communes and the full
### population density range across all communes, so we need to do this overall:
ylo <- min(env_m2_newdat_com$pred.com)*0.9
yhi <- max(env_m2_newdat_com$pred.com)*1.1
xlo <- min(dat1[dat1$Provcomm %in% levels(env_m2_newdat_com$Provcomm),"mean_elev"])
xhi <- max(dat1[dat1$Provcomm %in% levels(env_m2_newdat_com$Provcomm),"mean_elev"])
### Iterate through the communes (levels in m6_newdat_com$Provcomm):
for(i in 1:length(provcomm_lvls)) {
### Pick commune i data from the predictions:
preddat_i <- env_m2_newdat_com[env_m2_newdat_com$Provcomm==provcomm_lvls[i],]
### Pick commune i data from observed data:
dat_i <- dat1[dat1$Provcomm==provcomm_lvls[i],]
## If this is the first plot, use plot(), otherwise lines() to add to an existing plot:
# if(i == 1) {
# Plot predicted ForPix as function of pop_den; as "line" type. Note this is where you set axis limits.
plot(preddat_i$mean_elev,preddat_i$pred.com,
type = "l",
col = com_colours[i],
ylim = c(ylo,yhi), xlim = c(xlo,xhi),
xlab = "Mean elevation (scaled & standardised",
ylab = "Predicted forest pixels",
main = unique(preddat_i$Provcomm))
# } else {
lines(preddat_i$mean_elev,preddat_i$pred.com, col = com_colours[i])
lines(preddat_i$mean_elev,preddat_i$pred.glo, lty=2)
#}
## Add points for "observed" ForPix for commune i across all observed pop_den across communes.
points(dat_i$mean_elev, dat_i$ForPix, pch = 21, bg = com_colours[i], col = com_colours[i])
}
#' In the above plots, the top row are the communes with intercepts clsoest to 0, middle row are those with intercepts furthest above 0, and bottom row are those with intercepts furthest below 0. The dashed black line is the global model, and the coloured solid lines are the commune-specific predictions. The dots are the actual ForPix ~ mean elevation points for that commune.
#' We can see that as for the population demographics model, the global model predicts poorly for communes with high forest cover, regardless of mean elevation. If a commune has low forest cover, then the global model predicts well for increasing values of elevation, until elevation reaches a scaled value of ~1, after which the model predicts poorly (becasue a commune can't increase in elevation).
#'
#' Let's do the same predictions but for a random set of communes:
#'
#+ env.m2 commune predictions - random, echo=FALSE, results=TRUE,fig.width=8, fig.height=8, dpi=100
par(mfrow = c(3,3))
set.seed(123)
runs <- c(1:9)
for(i in 1:length(runs)){
# randomly sample communes
rand.com <- sample(dat1$Provcomm, 9, replace = FALSE)
rand.prov <- unlist(strsplit(rand.com, "_"))
rand.prov <- rand.prov[c(1,3,5,7,9,11,13,15,17)]
# define the range of pop_den to predict for, first. Min/max per commune:
mean_elev_min <- tapply(dat1$mean_elev, dat1$Provcomm, min)
mean_elev_max <- tapply(dat1$mean_elev, dat1$Provcomm, max)
# Min/max within your selection of communes:
mean_elev_min <- min(mean_elev_min[names(mean_elev_min) %in% rand.com])
mean_elev_max <- max(mean_elev_max[names(mean_elev_max) %in% rand.com])
# min not really different but max very different
# create new prediction grid for specific communes with varying pop_den
env.m2_newdat_com_ran <- data.frame(Provcomm = rep(rand.com, each=100),
Province = rep(rand.prov, each=100),
mean_elev = seq(from=mean_elev_min, to=mean_elev_max, length.out = 100),
year = mean(dat1$year))
# add commune-specific areaKM offset
env.m2_newdat_com_ran$areaKM <- dat1$areaKM[match(env.m2_newdat_com_ran$Provcomm, dat1$Provcomm)]
# attach commune-specific predictions
env.m2_newdat_com_ran$pred.com <- as.vector(predict(env.m2, type="response",
newdata=env.m2_newdat_com_ran,
re.form=~(year|Province/Provcomm)))
# attach global predictions
env.m2_newdat_com_ran$pred.glo <- rep(env_m2_newdata$pred, times=9)
# set levels
env.m2_newdat_com_ran$Provcomm <- as.factor(env.m2_newdat_com_ran$Provcomm)
provcomm_lvls <- levels(env.m2_newdat_com_ran$Provcomm)
# set scales
ylo <- min(env.m2_newdat_com_ran$pred.com)*0.9
yhi <- max(env.m2_newdat_com_ran$pred.com)*1.1
xlo <- mean_elev_min
xhi <- mean_elev_max
# Iterate through the communes (levels in m6_newdat_com$Provcomm):
for(i in 1:length(provcomm_lvls)) {
### Pick commune i data from the predictions:
preddat_i <- env.m2_newdat_com_ran[env.m2_newdat_com_ran$Provcomm==provcomm_lvls[i],]
### Pick commune i data from observed data:
dat_i <- dat1[dat1$Provcomm==provcomm_lvls[i],]
## If this is the first plot, use plot(), otherwise lines() to add to an existing plot:
if(i == 1) {
# Plot predicted ForPix as function of pop_den; as "line" type. Note this is where you set axis limits.
plot(preddat_i$mean_elev,preddat_i$pred.com,
type = "l",
col = com_colours[i],
ylim = c(ylo,yhi), xlim = c(xlo,xhi),
xlab = "Mean elevation (scaled & standardised",
ylab = "Predicted forest pixels",
main = unique(preddat_i$Provcomm))
} else {
lines(preddat_i$mean_elev,preddat_i$pred.com, col = com_colours[i])
lines(preddat_i$mean_elev,preddat_i$pred.glo, lty=2)
}
## Add points for "observed" ForPix for commune i across all observed pop_den across communes.
points(dat_i$mean_elev, dat_i$ForPix, pch = 21, bg = com_colours[i], col = com_colours[i])
}
}
#' Each plot contains a random sample of 9 communes. Again the black dashed line is the global model. Note the varying y-axes. After running the above random sampling code a few times, it looks as though the global model is good at predicting at low forest cover and low elevation (as with the population density model), as this is where most of the communes sit on the spectrum. It performs ok for communes with higher elevation provided they don't have too much forest! As soon as the commune has lots of forest or very high elevation, the global model performs badly. It looks as though the commune-specific models predict quite well, provided the communes does not lose forest (as with the population density model).
#'
#' ## Additional human predictor variables
#'
#' As with the environmental predictor above, these variables were supposed to be "control" variables. The variables included in this set are distance to border (from the centre of the commune), distance to the Provincial Capital (from the centre of the commune), presence of economic land concessions ("elc", binary), presence of a PA (any kind of PA, binary), PA category (7 levels, including "none").
#'
#+ hum.m1, include=TRUE
hum.m1 <- glmer(ForPix ~ dist_border+dist_provCap+elc+PA+PA_cat+offset(log(areaKM)) +
(year|Province/Provcomm), family = "poisson", data=dat1)
summary(hum.m1)
#' Model produces a rank deficiency warning. Interestingly, PA doesn't appear to look important. This surprises me as you would assume that PAs would be placed in areas with high forest cover. elc doesn't appear to be important, which is also surprising because I could imagine two scenarios 1) it would have a postive relationship because elc's were often placed in forested areas, and 2) a negative relationship because the elc's would have cleared a lot of forest in the areas they were placed. However, during this time period, perhaps not much forest clearing had happened yet. dist_border and dst_provCap appear to be important, with both having a positive effect. dist_provCap I can understand - communes further away from urban centres are likely to be more forested. Not sure yet about dist_border. I think all vars require further investigation.
#'
#' I will do some quick plots below:
#'
#+ hum.m1 plot_models, echo=FALSE, results=TRUE, warning=F, fig.width=8, fig.height=8, dpi=100
# quick plots
hum.p1 <- plot_model(hum.m1, type="pred", terms="dist_border")
hum.p2 <- plot_model(hum.m1, type="pred", terms="dist_provCap")
hum.p3 <- plot_model(hum.m1, type="pred", terms="elc")
hum.p4 <- plot_model(hum.m1, type="pred", terms="PA")
hum.p5 <- plot_model(hum.m1, type="pred", terms="PA_cat") # surprised RMS level is not sig given the coefficient
hum.p1+hum.p2+hum.p3+hum.p4+hum.p5
#' From the quick plots above, it looks like both dist_border and dist_provCap do have a relationship with forest cover. elc does not look promising (note the y axis - difference is tiny), and neither really does PA. Not much difference in predicted forest cover for the different PA categories, apart from the RMS (RAMSAR) level.
#'
#' I conducted LRT's and AICc comparisons, and moved forward with predictions and plotting for models with dist_border, dist_provCap, PA and elc. But it became clear that PA and elc did very little, and so I have settled on a model with just dist_border and dist_provCap.
#'
#' ### Diagnostics
#'
#+ hum.m5 pred and res and plot observerd vs predicted, echo=FALSE, results=TRUE
# copy data for diagnostics
hum.m5 <- glmer(ForPix ~ dist_border+dist_provCap+offset(log(areaKM)) +
(year|Province/Provcomm), family = "poisson", data=dat1)
hum.diag.dat <- dat1
# residuals
hum.diag.dat$m5res <- resid(hum.m5)
# conditional predictions
hum.diag.dat$m5.pred <- as.vector(predict(hum.m5, type="response", re.form=NA))
plot(hum.diag.dat$m5.pred, hum.diag.dat$ForPix)
#' The above plot is the observed values versus the predicted values (from a fully conditional model). This plot is not great - worse than the previous model sets, and it looks like the model is under-predicting by quite a long way.
#'
#+ hum.m5 plot residuals versus predicted, echo=FALSE, results=TRUE
plot(hum.diag.dat$m5.pred, hum.diag.dat$m5res)
#' The above plot is the predicted values versus the model residuals. This doesn't look great. Some outlier large predictions which have small residuals, but a lot of heterogeneity at smaller predicted values. There's an odd line of residuals just below 2000 (x axis) which suggests there's one predicted value that is appearing quite a few times? Below I look more closely at the residuals.
#'
#+ hum.m5 residual plots, echo=FALSE, results=TRUE, fig.width=10, fig.height=10, dpi=100
par(mfrow=c(2,2))
plot(hum.diag.dat$dist_border, hum.diag.dat$m5res, ylab = "residuals", xlab = "distance to border")
plot(hum.diag.dat$dist_provCap, hum.diag.dat$m5res, ylab = "residuals", xlab = "distance to Prov Cap")
boxplot(m5res ~ factor(Province), data = hum.diag.dat, outline = T, xlab = "Province",
ylab = "Residuals w/i Province")
boxplot(m5res ~ factor(Provcomm), data = hum.diag.dat, outline = T, xlab = "Commune",
ylab = "Residuals w/i Commune")
#' Based on the first two plots, it looks like there's only a relatively small number of communes that have really large residuals (and there seems to be patterns in these).
#'
#' Zoom in:
#'
#+ hum.m5 residual plots zoom, echo=FALSE, results=TRUE, fig.width=10, fig.height=10, dpi=100
par(mfrow=c(2,1))
plot(hum.diag.dat$dist_border, hum.diag.dat$m5res, ylim=c(-3,3),
ylab = "residuals", xlab = "distance to border")
plot(hum.diag.dat$dist_provCap, hum.diag.dat$m5res, ylim=c(-3,3),
ylab = "residuals", xlab = "distance to Prov Cap")
#' The slightly odd patterns are smaller residuals between 0 and 1 dist_border, and between probably 0 and 0.3 for dist_provCap.
#'
#' I had a look at which provinces have the larger residuals to see if they match with the problem provinces from the previous model sets. They are Battambang, Kampong Cham, Kampong Chhnanhg, Kampong Thom, Koh Kong, Kracheh, Mondul Kiri, Otdar Meanchey, Pursat, Ratanak Kiri, Siem Reap, Stung Treng. These are the same provinces that are causing issues in the other model sets.
#'
#' As I have mentioned before, I think these problem communes are the ones that are losing forest over time. I used the raw data to assess which Provinces contain communes that lose some forest over the study period.
#'
#+ hum.m5 Provinces that lose forest, echo=FALSE, results=TRUE
diffPix <- dat1 %>% group_by(Provcomm) %>% summarise(sum = sum(diffPix))
provs <- unlist(strsplit(diffPix$Provcomm, "_"))
provs1 <- provs[seq(1, length(provs), 2)]
diffPix$Province <- provs1
unique(diffPix$Province[diffPix$sum > 0])
#' So this may go some way towards explaining the issues. However, there are still Provinces that lose no forest but are still causing issues, such as Kampong Chhnang and Kampong Thom. I looked more closely at some of the individual communes that had very large residuals.
#'
#+ hum.m5 communes larege residusals, echo=FALSE, results=TRUE
prob.coms <- hum.diag.dat[hum.diag.dat$m5res > 1 | hum.diag.dat$m5res < -1,]
prob.coms$type <- "problem"
other.coms <- hum.diag.dat %>% filter(!Provcomm %in% prob.coms$Provcomm)
other.coms$type <- "other"
all.coms <- rbind(prob.coms, other.coms)
plot(prob.coms$m5.pred, prob.coms$m5res)
#' The residuals above are the largest ones. Below, I have split all of the communes into the ones that produced the residuals above, and the rest:
#'
#+ hum.m5 prob coms vs ForPix, echo=F, results=T, fig.width=10, fig.height=10, dpi=100
hum.plot1 <- ggplot(all.coms, aes(x=Provcomm, y=ForPix, colour=type))+
geom_point()+
theme(element_blank())+
labs(x="Commune", y="Forest pixels")
hum.plot2 <- ggplot(all.coms, aes(x=Provcomm, y=areaKM, colour=type))+
geom_point()+
theme(element_blank())+
labs(x="Commune", y="Commune area (KM)")
hum.plot3 <- ggplot(all.coms, aes(x=Provcomm, y=dist_border, colour=type))+
geom_point()+
theme(element_blank())+
labs(x="Commune", y="Distance to border")
hum.plot4 <- ggplot(all.coms, aes(x=Provcomm, y=dist_provCap, colour=type))+
geom_point()+
theme(element_blank())+
labs(x="Commune", y="Distance to Provincial Captital")
hum.plot1+hum.plot2+hum.plot3+hum.plot4
#' The top left plot is forest pixels per commune, the top right plot is the area (KM) of the communes, the bottom left plot is distance to border, and the bottom right is distance to provincial capital. None of these show an obvious pattern to me - and in fact in the top left plot (forest pixels) the loss of forest over time doesn't look unique to the problem communes, as it did in the previous sets. The only pattern I can see in these plots is that the problem communes are spatially relatively close and clumped (they are grouped by Province in the dataframe and so if they are plotted near one another on the x axis they are probably in the same Province). But the issues are certainly not unique to a single province, or to a set of communes all with similar characteristics (that I can think of anyway!). So am not sure exactly what the other reasons are for the large residuals in those communes.
#'
#' ### Predict main effects
#'
#' Below are the predictions for dist_border and dist_provCap from the 'global' model.
#'
#+ hum.m5 main effects predictions, echo=F, results=T
# create new data for dist_border
dist_border_newdat <- expand.grid(dist_border = seq(min(dat1$dist_border), max(dat1$dist_border),
length.out = 100),
dist_provCap = mean(dat1$dist_provCap),
areaKM = mean(dat1$areaKM))
# predict
dist_border_newdat$pred <- as.vector(predict(hum.m5, type="response", newdata=dist_border_newdat, re.form=NA))
# create new data for dist_provCap
dist_provCap_newdat <- expand.grid(dist_provCap = seq(min(dat1$dist_provCap), max(dat1$dist_provCap),
length.out = 100),
dist_border = mean(dat1$dist_border),
areaKM = mean(dat1$areaKM))
# predict
dist_provCap_newdat$pred <- as.vector(predict(hum.m5, type="response", newdata=dist_provCap_newdat,
re.form=NA))
# plot
hum.p6 <- ggplot(dist_border_newdat, aes(x=dist_border, y=pred))+
geom_line(size=1)+
theme(element_blank())+
ylim(0,2000)+
xlab("Distance to international border (scaled and centered)")+
ylab("Predicted forest cover (pixels)")+
ggtitle("Distance to border")
hum.p7 <-ggplot(dist_provCap_newdat, aes(x=dist_provCap, y=pred))+
geom_line(size=1)+
theme(element_blank())+
ylim(0,2000)+
xlab("Distance to provincial capital (scaled and centered)")+
ylab("Predicted forest cover (pixels)")+
ggtitle("Distance to provincial capital")
hum.p6 + hum.p7
#' We can see that both predictors have a positive effect on forest cover, and that distance to provincial capital is the stronger effect. The relationship with dist_provCap makes sense - the more rural/remote a communes is, the more likely it is to be forested. Communes that are in or around large urban centres, are unlikely to be heavily forested. The dist_border relationship is more difficult to explain easily. Based on my knowledge of the country I was expecting the opposite - lots of the large PAs are near international borders, whereas much of the central part of the country is farmland. I will need to investigate this further.
#'
#' ### Predict for specific communes
#'
#' Below I have run predictions for 12 communes - the four with intercepts closest to 0, four with intercepts furthest above 0, and the four with intercepts furthest below 0.
#'
#' First for dist_border
#'
#+ hum.m5 commune predictions dist_border, echo=F, results=T, fig.width=8, fig.height=8, dpi=100
hum.m5.com <- ranef(hum.m5)[[1]]
# re-order
hum.m5.com <- hum.m5.com[order(hum.m5.com[ ,"(Intercept)"], decreasing = TRUE),]
# which communes
coms <- c("Stung Treng_Kbal Romeas","Preah Vihear_Chhaeb Pir","Kampong Cham_Kampoan","Preah Vihear_Kuleaen Tboung",
"Kampot_Preaek Tnaot","Kampot_Kaoh Touch","Kampong Chhnang_Chieb","Kampong Cham_Pongro",
"Kampong Thom_Chaeung Daeung","Kracheh_Han Chey","Preah Vihear_Reaksmei","Siem Reap_Nokor Pheas")
# which provinces
provs <- c("Stung Treng","Preah Vihear","Kampong Cham","Preah Vihear",
"Kampot","Kampot","Kampong Chhnang","Kampong Cham",
"Kampong Thom","Kracheh","Preah Vihear","Siem Reap")
### define the range of dist_border to predict for. Min/max per commune:
dist_border_min <- tapply(dat1$dist_border, dat1$Provcomm, min)
dist_border_max <- tapply(dat1$dist_border, dat1$Provcomm, max)
### Min/max within your selection of communes:
dist_border_min <- min(dist_border_min[names(dist_border_min) %in% coms])
dist_border_max <- max(dist_border_max[names(dist_border_max) %in% coms])
# create new prediction grid for specific communes with varying dist_border
hum_m5_newdat_bord <- data.frame(Provcomm = rep(coms, each=100),
Province = rep(provs, each=100),
dist_border = seq(dist_border_min, dist_border_max, length.out = 100),
year = mean(dat1$year))
# add dist_provCap
hum_m5_newdat_bord$dist_provCap <- dat1$dist_provCap[match(hum_m5_newdat_bord$Provcomm, dat1$Provcomm)]
# add commune-specific areaKM offset
hum_m5_newdat_bord$areaKM <- dat1$areaKM[match(hum_m5_newdat_bord$Provcomm, dat1$Provcomm)]
# re-order levels so they plot in the correct sets
hum_m5_newdat_bord$Provcomm <- factor(hum_m5_newdat_bord$Provcomm,
levels = c("Stung Treng_Kbal Romeas","Preah Vihear_Chhaeb Pir",
"Kampong Cham_Kampoan","Preah Vihear_Kuleaen Tboung",
"Kampot_Preaek Tnaot","Kampot_Kaoh Touch","Kampong Chhnang_Chieb",
"Kampong Cham_Pongro","Kampong Thom_Chaeung Daeung",
"Kracheh_Han Chey","Preah Vihear_Reaksmei","Siem Reap_Nokor Pheas"))
# attach commune-specific predictions
hum_m5_newdat_bord$pred.com <- as.vector(predict(hum.m5, type="response", newdata=hum_m5_newdat_bord,
re.form=~(year|Province/Provcomm)))
# attach global predictions. need to alter areaKM below so that the global model has only the mean areakM rather than the commune-specific one. This is fine as pred.com is already done
hum_m5_newdat_bord <- hum_m5_newdat_bord %>% rename(areaKM_com = areaKM)
hum_m5_newdat_bord$areaKM <- mean(dat1$areaKM)
hum_m5_newdat_bord$pred.glo <- as.vector(predict(hum.m5,type="response",newdata=hum_m5_newdat_bord,re.form=NA))
require(RColorBrewer)
com_colours <- brewer.pal(11, "RdYlBu")
com_colours <- c(head(com_colours,4),tail(com_colours,4))
com_colours_greys <- tail(brewer.pal(9, "Greys"),4)
com_colours <- c(com_colours, com_colours_greys)
com_colours <- com_colours[sample(1:length(com_colours),12,replace=F)]
### This is just to check if you have commented tbe above out: :)
if(!exists("com_colours")) {
com_colours <- rep("black", 12)
}
provcomm_lvls <- levels(hum_m5_newdat_bord$Provcomm)
par(mfrow = c(3,4))
### Note the scales are important here - we need to set a scale that encompasses all the communes and the full
### dist_border range across all communes, so we need to do this overall:
ylo <- min(hum_m5_newdat_bord$pred.com)*0.9
yhi <- max(hum_m5_newdat_bord$pred.com)*1.1
xlo <- min(dat1[dat1$Provcomm %in% levels(hum_m5_newdat_bord$Provcomm),"dist_border"])
xhi <- max(dat1[dat1$Provcomm %in% levels(hum_m5_newdat_bord$Provcomm),"dist_border"])
### Iterate through the communes (levels in hum_m5_newdat_bord$Provcomm):
for(i in 1:length(provcomm_lvls)) {
### Pick commune i data from the predictions:
preddat_i <- hum_m5_newdat_bord[hum_m5_newdat_bord$Provcomm==provcomm_lvls[i],]
### Pick commune i data from observed data:
dat_i <- dat1[dat1$Provcomm==provcomm_lvls[i],]
## If this is the first plot, use plot(), otherwise lines() to add to an existing plot:
#if(i == 1) {
# Plot predicted ForPix as function of dist_border; as "line" type. Note this is where you set axis limits.
plot(preddat_i$dist_border,preddat_i$pred.com,
type = "l",
col = com_colours[i],
ylim = c(ylo,yhi), xlim = c(xlo,xhi),
xlab = "Distance to intl border (scaled & standardised)",
ylab = "Predicted forest pixels",
main = unique(preddat_i$Provcomm))
#} else {
lines(preddat_i$dist_border,preddat_i$pred.com, col = com_colours[i])
lines(preddat_i$dist_border,preddat_i$pred.glo, lty=2)
#}
## Add points for "observed" ForPix for commune i across all observed pop_den across communes.
points(dat_i$dist_border, dat_i$ForPix, pch = 21, bg = com_colours[i], col = com_colours[i])
}
#' These plots suggest the global model fits poorly for communes with higher forest cover, but fits better for communes with low forest cover, regardless of dist_border, which is much the same as previous models. The global model is better at predicting for communes with intercepts around the global mean, or below it.
#'
#' Now I will do the same plots but for a random subset of communes.
#'
#+ hum.m5 random commune predictions dist_border, echo=F, results=T, fig.width=8, fig.height=8, dpi=100
par(mfrow = c(3,3))
set.seed(123)
runs <- c(1:9)
for(i in 1:length(runs)){
# randomly sample communes
rand.com <- sample(dat1$Provcomm, 9, replace = FALSE)
rand.prov <- unlist(strsplit(rand.com, "_"))
rand.prov <- rand.prov[c(1,3,5,7,9,11,13,15,17)]
# define the range of pop_den to predict for, first. Min/max per commune:
dist_border_min <- tapply(dat1$dist_border, dat1$Provcomm, min)
dist_border_max <- tapply(dat1$dist_border, dat1$Provcomm, max)
# Min/max within your selection of communes:
dist_border_min <- min(dist_border_min[names(dist_border_min) %in% rand.com])
dist_border_max <- max(dist_border_max[names(dist_border_max) %in% rand.com])
# min not really different but max very different
# create new prediction grid for random communes with varying dist_border
hum_m5_newdat_bord_ran <- data.frame(Provcomm = rep(rand.com, each=100),
Province = rep(rand.prov, each=100),
dist_border = seq(dist_border_min, dist_border_max, length.out = 100),
year = mean(dat1$year))
hum_m5_newdat_bord_ran$Provcomm <- as.factor(hum_m5_newdat_bord_ran$Provcomm)
# add dist_provCap
hum_m5_newdat_bord_ran$dist_provCap <- dat1$dist_provCap[match(hum_m5_newdat_bord_ran$Provcomm, dat1$Provcomm)]
# add commune-specific areaKM offset
hum_m5_newdat_bord_ran$areaKM <- dat1$areaKM[match(hum_m5_newdat_bord_ran$Provcomm, dat1$Provcomm)]
# attach commune-specific predictions
hum_m5_newdat_bord_ran$pred.com <- as.vector(predict(hum.m5, type="response", newdata=hum_m5_newdat_bord_ran,
re.form=~(year|Province/Provcomm)))
# attach global predictions. need to alter areaKM below so that the global model has only the mean areakM rather than the commune-specific one. This is fine as pred.com is already done
hum_m5_newdat_bord_ran <- hum_m5_newdat_bord_ran %>% rename(areaKM_com = areaKM)
hum_m5_newdat_bord_ran$areaKM <- mean(dat1$areaKM)
hum_m5_newdat_bord_ran$pred.glo <- as.vector(predict(hum.m5,type="response",
newdata=hum_m5_newdat_bord_ran,re.form=NA))
require(RColorBrewer)
com_colours <- brewer.pal(11, "RdYlBu")
com_colours <- c(head(com_colours,4),tail(com_colours,4))
com_colours_greys <- tail(brewer.pal(9, "Greys"),4)
com_colours <- c(com_colours, com_colours_greys)
com_colours <- com_colours[sample(1:length(com_colours),12,replace=F)]
### This is just to check if you have commented tbe above out: :)
if(!exists("com_colours")) {
com_colours <- rep("black", 12)
}
provcomm_lvls <- levels(hum_m5_newdat_bord_ran$Provcomm)
### Note the scales are important here - we need to set a scale that encompasses all the communes and the full
### dist_border range across all communes, so we need to do this overall:
ylo <- min(hum_m5_newdat_bord_ran$pred.com)*0.9
yhi <- max(hum_m5_newdat_bord_ran$pred.com)*1.1
xlo <- min(dat1[dat1$Provcomm %in% levels(hum_m5_newdat_bord_ran$Provcomm),"dist_border"])
xhi <- max(dat1[dat1$Provcomm %in% levels(hum_m5_newdat_bord_ran$Provcomm),"dist_border"])
### Iterate through the communes (levels in hum_m5_newdat_bord$Provcomm):
for(i in 1:length(provcomm_lvls)) {
### Pick commune i data from the predictions:
preddat_i <- hum_m5_newdat_bord_ran[hum_m5_newdat_bord_ran$Provcomm==provcomm_lvls[i],]
### Pick commune i data from observed data:
dat_i <- dat1[dat1$Provcomm==provcomm_lvls[i],]
## If this is the first plot, use plot(), otherwise lines() to add to an existing plot:
if(i == 1) {
# Plot predicted ForPix as function of dist_border; as "line" type. Note this is where you set axis limits.
plot(preddat_i$dist_border,preddat_i$pred.com,
type = "l",
col = com_colours[i],
ylim = c(ylo,yhi), xlim = c(xlo,xhi),
xlab = "Distance to intl border (scaled & standardised)",
ylab = "Predicted forest pixels",
main = unique(preddat_i$Provcomm))
} else {
lines(preddat_i$dist_border,preddat_i$pred.com, col = com_colours[i])
lines(preddat_i$dist_border,preddat_i$pred.glo, lty=2)
}
## Add points for "observed" ForPix for commune i across all observed pop_den across communes.
points(dat_i$dist_border, dat_i$ForPix, pch = 21, bg = com_colours[i], col = com_colours[i])
}
}
#' The above plots I think show that again, the commune-specific models are fitting well, provided forest cover doesn't change.
#'
#' Below I will do the same predictions and plotting, but for varying dist_provCap. First, I will plot the 12 communes above, below, and around the mean intercept.
#'
#+ hum.m5 commune predictions dist_provCap, echo=F, results=T, fig.width=8, fig.height=8, dpi=100
### define the range of dist_provCap to predict for. Min/max per commune:
dist_provCap_min <- tapply(dat1$dist_provCap, dat1$Provcomm, min)
dist_provCap_max <- tapply(dat1$dist_provCap, dat1$Provcomm, max)
### Min/max within your selection of communes:
dist_provCap_min <- min(dist_provCap_min[names(dist_provCap_min) %in% coms])
dist_provCap_max <- max(dist_provCap_max[names(dist_provCap_max) %in% coms])
# create new prediction grid for specific communes with varying dist_border
hum_m5_newdat_provCap <- data.frame(Provcomm = rep(coms, each=100),
Province = rep(provs, each=100),
dist_provCap = seq(dist_provCap_min, dist_provCap_max, length.out = 100),
dist_border = dat1$dist_border[match(hum_m5_newdat_bord$Provcomm, dat1$Provcomm)],
year = mean(dat1$year))
# add commune-specific areaKM offset
hum_m5_newdat_provCap$areaKM <- dat1$areaKM[match(hum_m5_newdat_provCap$Provcomm, dat1$Provcomm)]
# re-order levels so they plot in the correct sets
hum_m5_newdat_provCap$Provcomm <- factor(hum_m5_newdat_provCap$Provcomm,
levels = c("Stung Treng_Kbal Romeas","Preah Vihear_Chhaeb Pir",
"Kampong Cham_Kampoan","Preah Vihear_Kuleaen Tboung",
"Kampot_Preaek Tnaot","Kampot_Kaoh Touch","Kampong Chhnang_Chieb",
"Kampong Cham_Pongro","Kampong Thom_Chaeung Daeung",
"Kracheh_Han Chey","Preah Vihear_Reaksmei","Siem Reap_Nokor Pheas"))
# attach commune-specific predictions
hum_m5_newdat_provCap$pred.com <- as.vector(predict(hum.m5, type="response", newdata=hum_m5_newdat_provCap,
re.form=~(year|Province/Provcomm)))
# attach global predictions. need to alter areaKM below so that the global model has only the mean areakM rather than the commune-specific one. This is fine as pred.com is already done
hum_m5_newdat_provCap <- hum_m5_newdat_provCap %>% rename(areaKM_com = areaKM)
hum_m5_newdat_provCap$areaKM <- mean(dat1$areaKM)
hum_m5_newdat_provCap$pred.glo <- as.vector(predict(hum.m5,type="response",newdata=hum_m5_newdat_provCap,re.form=NA))
### The following plot can either "overlay" the observed ForPix count against observed dist_provCap for the communes, or I can split by commune. comment out the if(i==1) statement and set par() if you want a grid
### Pick some colours using RColorBrewer using a completely overelaborate piece of crap code... Anyway this is just to
#try to help see the differences between communes more clearly in the observed points in particular (you can comment the
#following lines out if you want)
require(RColorBrewer)
com_colours <- brewer.pal(11, "RdYlBu")
com_colours <- c(head(com_colours,4),tail(com_colours,4))
com_colours_greys <- tail(brewer.pal(9, "Greys"),4)
com_colours <- c(com_colours, com_colours_greys)
com_colours <- com_colours[sample(1:length(com_colours),12,replace=F)]
### This is just to check if you have commented tbe above out: :)
if(!exists("com_colours")) {
com_colours <- rep("black", 12)
}
provcomm_lvls <- levels(hum_m5_newdat_provCap$Provcomm)
par(mfrow = c(3,4))
### Note the scales are important here - we need to set a scale that encompasses all the communes and the full
### dist_provCap range across all communes, so we need to do this overall:
ylo <- min(hum_m5_newdat_provCap$pred.com)*0.9
yhi <- max(hum_m5_newdat_provCap$pred.com)*1.1
xlo <- min(dat1[dat1$Provcomm %in% levels(hum_m5_newdat_provCap$Provcomm),"dist_border"])
xhi <- max(dat1[dat1$Provcomm %in% levels(hum_m5_newdat_provCap$Provcomm),"dist_border"])
### Iterate through the communes (levels in hum_m5_newdat_bord$Provcomm):
for(i in 1:length(provcomm_lvls)) {
### Pick commune i data from the predictions:
preddat_i <- hum_m5_newdat_provCap[hum_m5_newdat_provCap$Provcomm==provcomm_lvls[i],]
### Pick commune i data from observed data:
dat_i <- dat1[dat1$Provcomm==provcomm_lvls[i],]
## If this is the first plot, use plot(), otherwise lines() to add to an existing plot:
#if(i == 1) {
# Plot predicted ForPix as function of dist_border; as "line" type. Note this is where you set axis limits.
plot(preddat_i$dist_provCap,preddat_i$pred.com,
type = "l",
col = com_colours[i],
ylim = c(ylo,yhi), xlim = c(xlo,xhi),
xlab = "Distance to provincial capital (scaled & standardised)",
ylab = "Predicted forest pixels",
main = unique(preddat_i$Provcomm))
#} else {
lines(preddat_i$dist_provCap,preddat_i$pred.com, col = com_colours[i])
lines(preddat_i$dist_provCap,preddat_i$pred.glo, lty=2)
#}
## Add points for "observed" ForPix for commune i across all observed pop_den across communes.
points(dat_i$dist_provCap, dat_i$ForPix, pch = 21, bg = com_colours[i], col = com_colours[i])
}
#' The above plots paint a similar picture to the dist_border plots. Below I will predict and plot for a random subset of communes.
#'
#+ hum.m5 random commune predictions dist_provCap, echo=F, results=T, fig.width=8, fig.height=8, dpi=100
par(mfrow = c(3,3))
set.seed(123)
runs <- c(1:9)
for(i in 1:length(runs)){
# randomly sample communes
rand.com <- sample(dat1$Provcomm, 9, replace = FALSE)
rand.prov <- unlist(strsplit(rand.com, "_"))
rand.prov <- rand.prov[c(1,3,5,7,9,11,13,15,17)]
# define the range of pop_den to predict for, first. Min/max per commune:
dist_provCap_min <- tapply(dat1$dist_provCap, dat1$Provcomm, min)
dist_provCap_max <- tapply(dat1$dist_provCap, dat1$Provcomm, max)
# Min/max within your selection of communes:
dist_provCap_min <- min(dist_provCap_min[names(dist_provCap_min) %in% rand.com])
dist_provCap_max <- max(dist_provCap_max[names(dist_provCap_max) %in% rand.com])
# min not really different but max very different
# create new prediction grid for random communes with varying dist_border
hum_m5_newdat_provCap_ran <- data.frame(Provcomm = rep(rand.com, each=100),
Province = rep(rand.prov, each=100),
dist_provCap = seq(dist_provCap_min, dist_provCap_max, length.out = 100),
year = mean(dat1$year))
hum_m5_newdat_provCap_ran$Provcomm <- as.factor(hum_m5_newdat_provCap_ran$Provcomm)
# add dist_border
hum_m5_newdat_provCap_ran$dist_border <- dat1$dist_border[match(hum_m5_newdat_provCap_ran$Provcomm, dat1$Provcomm)]
# add commune-specific areaKM offset
hum_m5_newdat_provCap_ran$areaKM <- dat1$areaKM[match(hum_m5_newdat_provCap_ran$Provcomm, dat1$Provcomm)]
# attach commune-specific predictions
hum_m5_newdat_provCap_ran$pred.com <- as.vector(predict(hum.m5, type="response",
newdata=hum_m5_newdat_provCap_ran,
re.form=~(year|Province/Provcomm)))
# attach global predictions. need to alter areaKM below so that the global model has only the mean areakM rather than the commune-specific one. This is fine as pred.com is already done
hum_m5_newdat_provCap_ran <- hum_m5_newdat_provCap_ran %>% rename(areaKM_com = areaKM)
hum_m5_newdat_provCap_ran$areaKM <- mean(dat1$areaKM)
hum_m5_newdat_provCap_ran$pred.glo <- as.vector(predict(hum.m5,type="response",
newdata=hum_m5_newdat_provCap_ran,re.form=NA))
require(RColorBrewer)
com_colours <- brewer.pal(11, "RdYlBu")
com_colours <- c(head(com_colours,4),tail(com_colours,4))
com_colours_greys <- tail(brewer.pal(9, "Greys"),4)
com_colours <- c(com_colours, com_colours_greys)
com_colours <- com_colours[sample(1:length(com_colours),12,replace=F)]
### This is just to check if you have commented tbe above out: :)
if(!exists("com_colours")) {
com_colours <- rep("black", 12)
}
provcomm_lvls <- levels(hum_m5_newdat_provCap_ran$Provcomm)
### Note the scales are important here - we need to set a scale that encompasses all the communes and the full
### dist_border range across all communes, so we need to do this overall:
ylo <- min(hum_m5_newdat_provCap_ran$pred.com)*0.9
yhi <- max(hum_m5_newdat_provCap_ran$pred.com)*1.1
xlo <- min(dat1[dat1$Provcomm %in% levels(hum_m5_newdat_provCap_ran$Provcomm),"dist_provCap"])
xhi <- max(dat1[dat1$Provcomm %in% levels(hum_m5_newdat_provCap_ran$Provcomm),"dist_provCap"])
### Iterate through the communes (levels in hum_m5_newdat_bord$Provcomm):
for(i in 1:length(provcomm_lvls)) {
### Pick commune i data from the predictions:
preddat_i <- hum_m5_newdat_provCap_ran[hum_m5_newdat_provCap_ran$Provcomm==provcomm_lvls[i],]
### Pick commune i data from observed data:
dat_i <- dat1[dat1$Provcomm==provcomm_lvls[i],]
## If this is the first plot, use plot(), otherwise lines() to add to an existing plot:
if(i == 1) {
# Plot predicted ForPix as function of dist_provCap; as "line" type. Note this is where you set axis limits.
plot(preddat_i$dist_provCap,preddat_i$pred.com,
type = "l",
col = com_colours[i],
ylim = c(ylo,yhi), xlim = c(xlo,xhi),
xlab = "Distance to Provincial capital (scaled & standardised)",
ylab = "Predicted forest pixels",
main = unique(preddat_i$Provcomm))
} else {
lines(preddat_i$dist_provCap,preddat_i$pred.com, col = com_colours[i])
lines(preddat_i$dist_provCap,preddat_i$pred.glo, lty=2)
}
## Add points for "observed" ForPix for commune i across all observed pop_den across communes.
points(dat_i$dist_provCap, dat_i$ForPix, pch = 21, bg = com_colours[i], col = com_colours[i])
}
}
| /ongoing_analysis.R | no_license | mattnuttall00/PhD_Chapter1 | R | false | false | 91,403 | r | #' ---
#' title: Mixed models - socioeconomic predictors of forest cover
#' author: Matt Nuttall
#' date: 23/06/20
#' output:
#' html_document:
#' toc: true
#' highlight: zenburn
#' ---
#+ include=FALSE
library(sjPlot)
library(DHARMa)
library(lme4)
library(patchwork)
library(pbkrtest)
library(MuMIn)
library(RColorBrewer)
library(tidyverse)
# load data
dat <- read.csv("Data/commune/dat_use.csv", header = TRUE, stringsAsFactors = TRUE)
dat <- dat[ ,-1]
# re-classify the variables
dat$year <- as.numeric(dat$year)
dat$elc <- as.factor(dat$elc)
dat$PA <- as.factor(dat$PA)
dat1 <- dat %>%
mutate_at(c("year","tot_pop","prop_ind","pop_den","M6_24_sch","propPrimSec","propSecSec","Les1_R_Land",
"pig_fam","dist_sch","garbage","KM_Comm","land_confl","crim_case","Pax_migt_in",
"Pax_migt_out","mean_elev","dist_border","dist_provCap"), ~(scale(.) %>% as.vector))
# merge Province and Commune into a new unique variable (to remove issue of communes with the same name)
dat1 <- dat1 %>% mutate(Provcomm = paste(dat1$Province, dat1$Commune, sep = "_"))
# add original year (i.e. not scaled)
dat1$year.orig <- dat$year
#' This document is a summary of the ongoing analysis into predictors of forest cover/loss at the commune level across Cambodia.
#'
#' Currently the response variable is raw count of forest pixels, and there are 9 predictor variable sets with varying numbers of predictors in each set. All predictor variables have been scaled and centered prior to analysis. A GLMM framework has been used, with a Poisson distribution and the following random effects structure:
#'
#' **(year|Province/Commune)**
#'
#' The logged area (KM) of each commune has been used as an offset term in each model.
#'
#' The variable sets are as follows:
#'
#' * POPULATION DEMOGRAPHICS - population density, total population, proportion of commune that are indigenous
#' * EDUCATION - proportion of males aged 6-24 in school
#' * EMPLOYMENT - proportion of people employed in the Primary sector, proportion of people emplyed in the Secondary sector
#' * ECONOMIC SECURITY - proportion of population with less than 1ha of farming land, proportion of families with pigs
#' * ACCESS TO SERVICES - median distance to nearest school (of all the villages within the commune), median distance to the Commune Office (of all the villages within the commune), proportion of families with access to waste collection services
#' * SOCIAL JUSTICE - total number of land conflict cases, number of criminal cases per capita
#' * MIGRATION - total number of in-migrants, total number of out-migrants
#' * ENVIRONMENTAL (CONTROL) - mean elevation, habitat
#' * HUMAN (CONTROL) - distance to international border, distance to Provincial Capital, PA presence, PA category, economic land concession presence
#'
#' ## summary of results
#'
#' Unfortunately, none of the socioeconomic predictors appear to have any predictive power! The only exception is population density. The "control" variables (Environmental, Human, see above) however, do have some predictive power. Below I will show the results of the initial models for each set.
#'
#' My general conclusion thus far however is that with this response, I still don't think I am asking the question I want to. I think the models below are telling us which variables can predict forest cover (i.e. where is the forest? Which communes have lots of forest and which ones have little forest?). I don't think the below models can really tell me anything about forest ***loss***, or which variables are able to predict forest cover loss/change. I feel like I need to go further and look at forest cover change as a response (e.g. rate of change / difference in forest pixels). That's not to say that what I have done so far is not useful - I think in combination with further analysis we can build up a wider picture of forest cover and forest cover dynamics. For example, the overall analysis and our results could be made up of the following:
#'
#' * Which variables predict where forest cover is greatest / lowest across the country? (this is what I have done. Although at the moment the question is really "...where forest cover is greatest/lowest given there is SOME forest. This is because I removed all communes with 0 forest cover right at the start, as at that stage I was planning on useing rate of change as a response and so communes with no forest were false 0's)
#' * Which variables predict where forest is likely to be lost? (Presumably I could use binomial logistic model here: forest lost/not lost)
#' * Then subset the communes to only those that have lost some forest, and then model rate of change / magnitude of change. (Initially this is what I was going to do, either manually i.e. two steps, or via a hurdle model)
#'
#' I keep having to remind myself of what the purpose of this analysis is. The purpose is to use the resulting model(s) to predict where in the country forest is likely to be lost under various potential scenarios. I want to be able to highlight communes where forest cover is likely to be lost if, say, population density in rural areas goes up, or if the number of land conflicts in communes with land concessions spike. The aim WAS then to use these predictions to assess the robustness of the national wildlife corridor network to future changes. But in theory I could do a number of things, e.g. identifiy which PAs are most vulnerable to certain future scenarios etc.
#' The main point being though, is that I don't think I can use the below models to do that.
#'
#' Unless I am mis-understanding the usefulness of the models below. Please feel free to correct me if you think I am interpreting this incorrectly. The only way I can think to use these models to do what I want, is using the below approach:
#'
#' * Ignore the "global" model (i.e. the model with RE's set to means)
#' * Pull out the individual communes of interest, e.g. the ones within the wildlife corridor, or the ones in/around the PAs
#' * run the commune-specific models (i.e. with RE's specific to that commune) with varying ranges of the predictors, e.g. increasing population density.
#'
#' That approach above though, doesn't feel right to me. This is because at the moment, if I adjusted model parameters to simulate a particular commune increasing, say, its population density, I don't feel like the result would reflect forest cover dynamics in that commune. I feel like it would be more llike saying - "if this commune happened to have a higher population density, it would probably have this amount of forest", which I think is subtley but importantly different from saying - "if population density increased in this communes, this commune would likely lose xx amount of forest".
#'
#' The other obvious problem with the above approach is that I don't really have any socioeconomic predictors (apart from population density) to play with as they're all a bit shit! The other predictor variables that have some predictive power are mostly unchangeable i.e. elevation, distance to Provincial capital etc.
#'
#' So I am currently unsure how best to proceed, and I would very much appreciate some guidance! Below I will summarise the models, the diagnostics, and the predictions.
#'
#' # Model results
#'
#' ## Population demographics
#'
#' Full population demographics model below. `tot_pop` = total population, `pop_den` = population density, `prop_ind` = proporition indigneous.
#+ popdem.m1
popdem.m1 <- glmer(ForPix ~ tot_pop + pop_den + prop_ind + offset(log(areaKM)) + (year|Province/Provcomm),
data=dat1, family="poisson")
summary(popdem.m1)
#' Variance for Province and commune are similar. Variance for year at both levels is small, but an order of magnitude smaller for the Province level. Approximate p values are significant for pop_den only. tot_pop is positive effect, pop_den and prop_ind are negative. No real correlation between fixed effects.Note: I did run the model without offset and the variance for Province and Provcomm:Province were double what they are now that offset is included.
#'
#' Plot the random effects. First plot is Commune and year, second plot is Province and year
#+ popdem.m1 RE plots, echo=FALSE, results=TRUE
plot_model(popdem.m1, type="re")
#' The model summary and likelihood ratio tests suggested proportion indigneous was contributing little, and so that variable was dropped. There was evidence of an interaction between population density and total population, and likelihood ratio tests suggested the model with both terms in was better than the model with only population density, but these two variables are intrinsically linked, and so I dropped total population, as it had the weaker effect. As a note on LRT's - my protocol was to begin with simple 'anova(test="Chisq")' and if there was a variable/model that had a p-value that was hovering around 0.05, then I would progress to another test (e.g. profiled CI's, bootstrapping, but this was never really necessary).
#'
#' Therefore the final population demographics model is:
#'
#+ popdem.m6,
popdem.m6 <- glmer(ForPix ~ pop_den + offset(log(areaKM)) + (year|Province/Provcomm),
data = dat1, family = "poisson")
summary(popdem.m6)
#' ### Diagnostics
#'
#+ popdem.m6 predictions and residuals, include=FALSE
# copy data
m6.diag.dat <- dat1
m6.diag.dat$Provcomm <- as.factor(m6.diag.dat$Provcomm)
# Make "fitted" predictions, i.e. fully conditional:
m6.diag.dat$m6pred <- predict(popdem.m6, type = "response")
# attach residuals
m6.diag.dat$m6res <- resid(popdem.m6)
#' Plot of predicted values vs observed values
#+ popdem.m6 fitted vs observed plot, echo=FALSE, results=TRUE
plot(m6.diag.dat$ForPix, m6.diag.dat$m6pred, ylab = "Predicted ForPix", xlab = "Observed ForPix")
#' This plot looks good.
#'
#' Below is a plot of residuals vs fitted values
#'
#+ popdem.m6 plot fitted vs residuals, echo=FALSE,results=TRUE
plot(m6.diag.dat$m6pred, m6.diag.dat$m6res)
#' Quite bad heterogeneity here. Jeroen suggested this could be due to missing predictors, however this was also the case for previous models that had the other 2 predictors. At low predicted values, error is greater. As Jeroren said - given the structure in the data, this is almost inevitable given the extent of variation across communes. As we will see, this is an issues with all of the models.
#'
#' Exploration of the residuals over the predictors, and between provinces and communes:
#'
#+ popdem.m6 residual plots, echo=FALSE,results=TRUE, fig.width=10, fig.height=10, dpi=100
par(mfrow=c(2,2))
plot(m6.diag.dat$pop_den, m6.diag.dat$m6res, ylab = "residuals", xlab = "pop density")
boxplot(m6res ~ factor(Province), data = m6.diag.dat, outline = T, xlab = "Province", ylab = "Residuals w/i Province")
boxplot(m6res ~ factor(Provcomm), data = m6.diag.dat, outline = T, xlab = "Commune", ylab = "Residuals w/i Commune")
#' A lot of the heterogeneity is driven by relatively few communes/provinces. I investigated further. If you look at the map (in GIS), the provinces with the smallest residuals are the smaller provinces in the south surrounding the capital Phnom Penh. These are provinces that generally have very little forest. But they are not the only provinces with no forest cover, so I am not sure that is the (only) reason. I think I need to look at the communes within the provinces.
#'
#+ popdem.m6 extract problem residuals, include=FALSE
provs <- c("Battambang","Kampong Chhnang","Kampong Thom","Kracheh","Pursat","Ratanak Kiri","Siem Reap",
"Stung Treng")
# extract all original data from those provinces
prov.dat <- dat %>% filter(Province %in% provs)
prov.dat$type <- "problem"
# create subset of all data NOT including the above
prov.excl <- dat %>% filter(!Province %in% provs)
prov.excl$type <- "other"
prov.all <- rbind(prov.dat,prov.excl)
#' Here I plot forest pixels for each commune, separated by the communes with high residuals in the model ("problem"), and the rest ("other"):
#'
#+ popdem.m6 plot problem communes ForPix, echo=FALSE, results=TRUE, warnings=FALSE
ggplot(prov.all, aes(Commune,y=ForPix, colour=type))+
geom_point()+
theme(element_blank())+
ylab("Forest pixels")
#' I would say that the provinces that are causing the issues tend to have higher ForPix than the others. It also look potentially like the provinces causing issues are almost always losing forest cover over time (lots of vertical lines of dots).
#'
#' Plot of population density (the predictor) against forest pixels, split by the problem communes again. I have zoomed in on both axes so we can see what is going on a bit better:
#'
#+ popdem.m6 plot problem communes ForPix ~ pop_den, echo=FALSE, results=TRUE, warning=FALSE
ggplot(prov.all, aes(x=pop_den, y=ForPix, colour=type))+
geom_point()+
ylim(0,10000)+
xlim(0,1000)+
theme(element_blank())+
ylab("Forest pixels")+
xlab("population density")
#' This plot makes it also look like the problem provinces tend to have communes with higher ForPix (although this is clearly not true for all communes). There is a chunk of blue with no pink where pop_den has increased to about 100 but ForPix has not decreased (whereas almost all the pink dots are lower, i.e. in the other provinces/communes at that population density forest cover is lower).
#'
#' The plot below shows the forest pixels by province (rather than commune), split by the problem provinces.
#'
#+ popdem.m6 plot problem provinces and ForPix, echo=FALSE, results=TRUE, warning=FALSE
ggplot()+
geom_boxplot(data=prov.dat, aes(x=Province, y=ForPix,colour="Problem provinces"))+
geom_boxplot(data=prov.excl, aes(x=Province, y=ForPix, colour="Other provinces"))+
ylim(0,10000)+
theme(element_blank())+
ylab("Forest pixels")
#' This plot suggests that the problem provinces don't necessarily have more (mean) forest cover, but they do tend to have more outliers (individual communes) that are very high forest cover.
#'
#' The plot below shows the population density by province, split by the problem provinces.
#'
#+ popdem.m6 plot problem provinces and pop_den, echo=FALSE, results=TRUE, warning=FALSE
ggplot()+
geom_boxplot(data=prov.dat, aes(x=Province, y=pop_den,colour="Problem provinces"))+
geom_boxplot(data=prov.excl, aes(x=Province, y=pop_den, colour="Other provinces"))+
theme(element_blank())+
ylab("Population density")
#' This plot suggests that overall, the problem provinces tend to have lower median pop_den value compared to the other provinces, but they again tend to have more outliers. This is what I would expect - the communes with lower population density will also likely be the communes with higher forest cover (as we saw in the above plots).
#'
#' The plot below shows the same as above but by communes, rather than province
#'
#+ popdem.m6 plot problem communes and pop_den, echo=FALSE, results=TRUE, warning=FALSE
ggplot()+
geom_boxplot(data=prov.dat, aes(x=Commune, y=pop_den,colour="Problem provinces"))+
geom_boxplot(data=prov.excl, aes(x=Commune, y=pop_den, colour="Other provinces"))+
ylim(0,1000)+
theme(element_blank())+
ylab("Population density")
#' Although slightly difficult to interpret, again this looks like there are more communes with higher pop_den values in the non-problematic provinces. And in the problem communes with higher population density values, they also tend to have much more variation in population density (i.e. the pop_den changes a lot over time)
#'
#' The plot below shows the problem communes and their forest pixels:
#'
#+ popdem.m6 plot problem communes and ForPix, echo=FALSE, results=TRUE, warning=FALSE
ggplot()+
geom_boxplot(data=prov.dat, aes(x=Commune, y=ForPix,colour="Problem provinces"))+
geom_boxplot(data=prov.excl, aes(x=Commune, y=ForPix, colour="Other provinces"))+
ylim(0,10000)+
theme(element_blank())+
ylab("Forest pixels")
#' Again, difficult to see a huge amount, however I would say that it looks like the problem provinces in general have more variation in ForPix, both within communes and between communes.
#'
#' If you look at the plot of the main effect below, the line is pretty flat, even at low pop_den and ForPix values. This is where the model is not predicitng well for communes with low population density but higher forest cover. This is because there is so much variation in the communes - i.e. there are so many that have low pop_den but low ForPix, which is dragging the model down. So the communes with large residuals are going to be the commune with low pop_den values and higher ForPix values I think. I do not think there is much I can do about this? Would including year as a fixed effect perhaps help account for the variation within communes across years?
#'
#' ### Predict main (global) effects
#'
#+ popdem.m6 predict & plot main effects, echo=FALSE, results=TRUE
# create new data
m6.newdat <- data.frame(pop_den = seq(from=min(dat1$pop_den), to=max(dat1$pop_den), length.out = 100),
areaKM = mean(dat1$areaKM))
# add predictions
m6.newdat$pred <- as.vector(predict(popdem.m6, type="response", newdata=m6.newdat, re.form=NA))
# plot with free y axis
popdem.m6.p1 <- ggplot(m6.newdat, aes(x=pop_den, y=pred))+
geom_line()+
theme(element_blank())+
xlab("Population density (scaled and centered)")+
ylab("Predicted forest pixels")
# plot with large y axis
popdem.m6.p2 <-ggplot(m6.newdat, aes(x=pop_den, y=pred))+
geom_line()+
ylim(0,5000)+
theme(element_blank())+
xlab("Population density (scaled and centered)")+
ylab("Predicted forest pixels")
popdem.m6.p1 + popdem.m6.p2
#' We can see in the plots above that the effect is there (left plot), but it is small when you look at it with a more realistic y-axis, i.e. with forest pixel values more like those that are actually seen (right plot)
#'
#' ### Predict for specific communes
#'
#' Here I want to plot grids of different communes with the overall predicted effect, plus the commune-specific effect. I want to do this for communes with commune-level intercepts close to the mean, and communes with commune-level intercepts at the extremes. I will also do this for a random sample of communes.
#'
#+ popdem.m6 commune predictions, echo=FALSE, results=T,fig.width=10, fig.height=10, dpi=100
# save the popdem.m4 commune-level random effects
m6.re.com <- ranef(popdem.m6)[[1]]
# re-order
m6.re.com <- m6.re.com[order(m6.re.com[ ,"(Intercept)"], decreasing = FALSE),]
# which communes
coms <- c("Pursat_Ansa Chambak","Kampong Cham_Kraek", "Ratanak Kiri_Pak Nhai","Kampong Speu_Tang Samraong",
"Kampong Chhnang_Chieb","Kampot_Preaek Tnaot","Battambang_Chhnal Moan","Phnom Penh_Chak Angrae Kraom",
"Kampong Thom_Chaeung Daeung","Kracheh_Han Chey","Siem Reap_Nokor Pheas","Kampong Thom_Tang Krasang")
# which provinces
provs <- c("Pursat","Kampong Cham","Ratanak Kiri","Kampong Speu",
"Kampong Chhnang","Kampot","Battambang","Phnom Penh",
"Kampong Thom","Kracheh","Siem Reap","Kampong Thom")
### I am making commune-specific predictions, so should customise the range of population densities I am predicting for, on the basis of each commune.
### Easiest to define the range of pop_den to predict for, first. Min/max per commune:
pop_den_min <- tapply(dat1$pop_den, dat1$Provcomm, min)
pop_den_max <- tapply(dat1$pop_den, dat1$Provcomm, max)
### Min/max within your selection of communes:
pop_den_min <- min(pop_den_min[names(pop_den_min) %in% coms])
pop_den_max <- max(pop_den_max[names(pop_den_max) %in% coms])
### Not really any different from the overall min and max
# create new prediction grid for specific communes with varying pop_den
m6_newdat_com <- data.frame(Provcomm = rep(coms, each=100),
Province = rep(provs, each=100),
pop_den = seq(from=pop_den_min, to=pop_den_max, length.out = 100),
year = mean(dat1$year))
# add commune-specific areaKM offset
m6_newdat_com$areaKM <- dat1$areaKM[match(m6_newdat_com$Provcomm, dat1$Provcomm)]
# re-order levels so they plot in the correct sets
m6_newdat_com$Provcomm <- factor(m6_newdat_com$Provcomm,
levels = c("Pursat_Ansa Chambak","Kampong Cham_Kraek", "Ratanak Kiri_Pak Nhai",
"Kampong Speu_Tang Samraong","Kampong Chhnang_Chieb","Kampot_Preaek Tnaot",
"Battambang_Chhnal Moan","Phnom Penh_Chak Angrae Kraom",
"Kampong Thom_Chaeung Daeung","Kracheh_Han Chey","Siem Reap_Nokor Pheas",
"Kampong Thom_Tang Krasang"))
# attach commune-specific predictions
m6_newdat_com$pred.com <- as.vector(predict(popdem.m6, type="response", newdata=m6_newdat_com,
re.form=~(year|Province/Provcomm)))
# attach global predictions
m6_newdat_com$pred.glo <- rep(m6.newdat$pred, times=12)
### The following plot can either "overlay" the observed ForPix count against observed population densities for the communes, or I can split by commune. comment out the if(i==1) statement and set par() if you want a grid
### Pick some colours using RColorBrewer using a completely overelaborate piece of crap code... Anyway this is just to
#try to help see the differences between communes more clearly in the observed points in particular (you can comment the
#following lines out if you want)
require(RColorBrewer)
com_colours <- brewer.pal(11, "RdYlBu")
com_colours <- c(head(com_colours,4),tail(com_colours,4))
com_colours_greys <- tail(brewer.pal(9, "Greys"),4)
com_colours <- c(com_colours, com_colours_greys)
com_colours <- com_colours[sample(1:length(com_colours),12,replace=F)]
### This is just to check if you have commented tbe above out: :)
if(!exists("com_colours")) {
com_colours <- rep("black", 12)
}
provcomm_lvls <- levels(m6_newdat_com$Provcomm)
par(mfrow = c(3,4))
### Note the scales are important here - we need to set a scale that encompasses all the communes and the full
### population density range across all communes, so we need to do this overall:
ylo <- min(m6_newdat_com$pred.com)*0.9
yhi <- max(m6_newdat_com$pred.com)*1.1
xlo <- min(dat1[dat1$Provcomm %in% levels(m6_newdat_com$Provcomm),"pop_den"])
xhi <- max(dat1[dat1$Provcomm %in% levels(m6_newdat_com$Provcomm),"pop_den"])
### Iterate through the communes (levels in m6_newdat_com$Provcomm):
for(i in 1:length(provcomm_lvls)) {
### Pick commune i data from the predictions:
preddat_i <- m6_newdat_com[m6_newdat_com$Provcomm==provcomm_lvls[i],]
### Pick commune i data from observed data:
dat_i <- dat1[dat1$Provcomm==provcomm_lvls[i],]
## If this is the first plot, use plot(), otherwise lines() to add to an existing plot:
# if(i == 1) {
# Plot predicted ForPix as function of pop_den; as "line" type. Note this is where you set axis limits.
plot(preddat_i$pop_den,preddat_i$pred.com,
type = "l",
col = com_colours[i],
ylim = c(ylo,yhi), xlim = c(xlo,xhi),
xlab = "Population density (scaled & standardised",
ylab = "Predicted forest cover pixels")
# } else {
lines(preddat_i$pop_den,preddat_i$pred.com, col = com_colours[i])
lines(preddat_i$pop_den,preddat_i$pred.glo, lty=2)
#}
## Add points for "observed" ForPix for commune i across all observed pop_den across communes.
points(dat_i$pop_den, dat_i$ForPix, pch = 21, bg = com_colours[i], col = com_colours[i])
}
#' In the above plots, the top row are communes with intercepts closest to the mean, the middle row are communes with intercepts furthest above the mean, and the bottom row are communes with intercepts furthest below the mean. The coloured solid lines are the commune-specific predictions, i.e. those made using all RE's specific to that commune. The dashed black line is the global model (i.e. for an "average" commune). The points are the actual pop_den ~ ForPix values for that commune. The plots support the diagnostics in the section above - the global model does not predict well for communes with high forest cover - because the global model always predicts low forest cover, even for communes with low population density. Essentially there are too many communes with low forest cover, and so the global model is dragged down, meaning that the communes with high forest cover get poor predictions. This does suggest though that the global model predicts well at high population density values, as these communes tend to have low forest cover.
#'
#' Now I will do the same but for 9 random selections of 9 communes.
#'
#+ popdem.m6 commune predictions from random selection, echo=FALSE,results=TRUE, fig.width=10, fig.height=10, dpi=100
# randomly sample communes
par(mfrow = c(3,3))
set.seed(123)
runs <- c(1:9)
for(i in 1:length(runs)){
rand.com <- sample(dat1$Provcomm,9, replace = FALSE)
rand.prov <- unlist(strsplit(rand.com, "_"))
rand.prov <- rand.prov[c(1,3,5,7,9,11,13,15,17)]
# define the range of pop_den to predict for, first. Min/max per commune:
pop_den_min <- tapply(dat1$pop_den, dat1$Provcomm, min)
pop_den_max <- tapply(dat1$pop_den, dat1$Provcomm, max)
# Min/max within your selection of communes:
pop_den_min <- min(pop_den_min[names(pop_den_min) %in% rand.com])
pop_den_max <- max(pop_den_max[names(pop_den_max) %in% rand.com])
# create new prediction grid for specific communes with varying pop_den
m6_newdat_com_ran <- data.frame(Provcomm = rep(rand.com, each=100),
Province = rep(rand.prov, each=100),
pop_den = seq(from=pop_den_min, to=pop_den_max, length.out = 100),
year = mean(dat1$year))
# add commune-specific areaKM offset
m6_newdat_com_ran$areaKM <- dat1$areaKM[match(m6_newdat_com_ran$Provcomm, dat1$Provcomm)]
# attach commune-specific predictions
m6_newdat_com_ran$pred.com <- as.vector(predict(popdem.m6, type="response", newdata=m6_newdat_com_ran,
re.form=~(year|Province/Provcomm)))
# attach global predictions
m6_newdat_com_ran$pred.glo <- rep(m6.newdat$pred, times=9)
# set levels
m6_newdat_com_ran$Provcomm <- as.factor(m6_newdat_com_ran$Provcomm)
provcomm_lvls <- levels(m6_newdat_com_ran$Provcomm)
# set scales
ylo <- min(m6_newdat_com_ran$pred.com)*0.9
yhi <- max(m6_newdat_com_ran$pred.com)*1.1
xlo <- pop_den_min
xhi <- pop_den_max
# Iterate through the communes (levels in m6_newdat_com$Provcomm):
for(i in 1:length(provcomm_lvls)) {
### Pick commune i data from the predictions:
preddat_i <- m6_newdat_com_ran[m6_newdat_com_ran$Provcomm==provcomm_lvls[i],]
### Pick commune i data from observed data:
dat_i <- dat1[dat1$Provcomm==provcomm_lvls[i],]
## If this is the first plot, use plot(), otherwise lines() to add to an existing plot:
if(i == 1) {
# Plot predicted ForPix as function of pop_den; as "line" type. Note this is where you set axis limits.
plot(preddat_i$pop_den,preddat_i$pred.com,
type = "l",
col = com_colours[i],
ylim = c(ylo,yhi), xlim = c(xlo,xhi),
xlab = "Population density (scaled & standardised",
ylab = "Predicted forest cover (forest pixel count)")
} else {
lines(preddat_i$pop_den,preddat_i$pred.com, col = com_colours[i])
lines(preddat_i$pop_den,preddat_i$pred.glo, lty=2)
}
## Add points for "observed" ForPix for commune i across all observed pop_den across communes.
points(dat_i$pop_den, dat_i$ForPix, pch = 21, bg = com_colours[i], col = com_colours[i])
}
}
#'
#' The above plots I think support the assessment that the global model predicts poorly for most communes, but I would expect this as there is so much variation between communes, it would be impossible to get a single model that predicted well. The above plots suggest that the commune-specific models predict better for communes where population density changes over time, but they predict poorly for communes when forest pixels change over time (i.e. forest is lost). Communes with more forest are, in general, more likely to lose forest (see plot below), which I think exacerbates the problem of the global model predicting poorly for communes with high forest cover i.e. it's a double whammy of poor predictions due to high forest cover, and poor predictions due to forest loss.
#'
#+ plot forest loss comparison between high and low forested communes, echo=FALSE,results=TRUE
## check whether communes with more forest are more likely to lose forest
# separate dat1 into the quarter with the most forest and then the rest
com.for <- dat1[dat1$ForPix>982,] # 982 is the 3rd quantile
com.for1 <- dat1[!(dat1$Provcomm %in% com.for$Provcomm),]
# summarise forest loss
com.for <- com.for %>% group_by(Provcomm) %>%
summarise(diffPix_sum = sum(diffPix))
com.for$type <- "high forest"
com.for1 <- com.for1 %>% group_by(Provcomm) %>%
summarise(diffPix_sum = sum(diffPix))
com.for1$type <- "low forest"
com.for.all <- rbind(com.for,com.for1)
ggplot(com.for.all, aes(x=type, y=diffPix_sum, colour=type))+
geom_boxplot()+
xlab("Commune")+
ylab("Forest pixels lost over study period")+
theme(element_blank())
#' The above plot splits the communes by forest cover - communes in the top 3rd quarter of most forested are in the "high forest" category, and the rest are in the "low forest" category. I have then summed the difference in pixels within each commune across the study period (i.e. if a commune loses 10 pixels each year it would have a y-axis value of 50). We can see that the communes with more forest, are more likely to lose forest.
#'
#'
#' ## Education
#'
#' There is only one variable in this set - the number of males aged 6-24 in school. There were more raw variables, but they were all highly correlated and so this one was taken forward as I think it is the most relevant to forest cover. This is because young men are the most likely to be engaging in agriculture, forest clearance, logging etc.
#'
#+ edu.m1, include=TRUE
edu.m1 <- glmer(ForPix ~ M6_24_sch + offset(log(areaKM)) + (year|Province/Provcomm), family="poisson", data=dat1)
summary(edu.m1)
#' The model output suggests there is nothing going on here. I can use 'plot_model' from the sjPlot package to quickly plot a prediction. It basically does exactly what I would do - create newdata with the variable of interest varying from the min to the max, and holding all others at their mean. You can specify whether you want it to plot conditional on the fixed effects only (i.e. "average" comune / global model), or on the random effects. The below is conditionl on fixed effects only.
#'
#+ edu.m1 plot_model, echo=FALSE, results=TRUE
plot_model(edu.m1, type="pred", terms="M6_24_sch")
#' Flat as a pancake.
#'
#' Below are some commune-specific predictions from another random selection of communes
#'
#+ edu.m1 commune predictions, echo=FALSE,results=T, fig.width=10, fig.height=10, dpi=100
par(mfrow = c(3,3))
set.seed(123)
runs <- c(1:9)
for(i in 1:length(runs)){
# randomly sample communes
rand.com <- sample(dat1$Provcomm, 9, replace = FALSE)
rand.prov <- unlist(strsplit(rand.com, "_"))
rand.prov <- rand.prov[c(1,3,5,7,9,11,13,15,17)]
# define the range of pop_den to predict for, first. Min/max per commune:
M6_24_sch_min <- tapply(dat1$M6_24_sch, dat1$Provcomm, min)
M6_24_sch_max <- tapply(dat1$M6_24_sch, dat1$Provcomm, max)
# Min/max within your selection of communes:
M6_24_sch_min <- min(M6_24_sch_min[names(M6_24_sch_min) %in% rand.com])
M6_24_sch_max <- max(M6_24_sch_max[names(M6_24_sch_max) %in% rand.com])
# create new prediction grid for specific communes with varying pop_den
edu.m1_newdat_com_ran <- data.frame(Provcomm = rep(rand.com, each=100),
Province = rep(rand.prov, each=100),
M6_24_sch = seq(from=M6_24_sch_min, to=M6_24_sch_max, length.out = 100),
year = mean(dat1$year))
# add commune-specific areaKM offset
edu.m1_newdat_com_ran$areaKM <- dat1$areaKM[match(edu.m1_newdat_com_ran$Provcomm, dat1$Provcomm)]
# attach commune-specific predictions
edu.m1_newdat_com_ran$pred.com <- as.vector(predict(edu.m1, type="response",
newdata=edu.m1_newdat_com_ran,
re.form=~(year|Province/Provcomm)))
# global predictions
edu.m1_glo_pred <- data.frame(M6_24_sch = rep(min(dat1$M6_24_sch),max(dat1$M6_24_sch), length.out=100),
areaKM = mean(dat1$areaKM))
edu.m1_glo_pred$pred <- as.vector(predict(edu.m1, type="response", newdata=edu.m1_glo_pred,re.form=NA))
# attach global predictions
edu.m1_newdat_com_ran$pred.glo <- rep(edu.m1_glo_pred$pred, times=9)
# set levels
edu.m1_newdat_com_ran$Provcomm <- as.factor(edu.m1_newdat_com_ran$Provcomm)
provcomm_lvls <- levels(edu.m1_newdat_com_ran$Provcomm)
# set scales
ylo <- min(edu.m1_newdat_com_ran$pred.com)*0.9
yhi <- max(edu.m1_newdat_com_ran$pred.com)*1.1
xlo <- M6_24_sch_min
xhi <- M6_24_sch_max
# Iterate through the communes
for(i in 1:length(provcomm_lvls)) {
### Pick commune i data from the predictions:
preddat_i <- edu.m1_newdat_com_ran[edu.m1_newdat_com_ran$Provcomm==provcomm_lvls[i],]
### Pick commune i data from observed data:
dat_i <- dat1[dat1$Provcomm==provcomm_lvls[i],]
## If this is the first plot, use plot(), otherwise lines() to add to an existing plot:
if(i == 1) {
# Plot predicted ForPix as function of pop_den; as "line" type. Note this is where you set axis limits.
plot(preddat_i$M6_24_sch,preddat_i$pred.com,
type = "l",
col = com_colours[i],
ylim = c(ylo,yhi), xlim = c(xlo,xhi),
xlab = "Proportion of males aged 6-24 in school (scaled & standardised",
ylab = "Predicted forest pixels")
} else {
lines(preddat_i$M6_24_sch,preddat_i$pred.com, col = com_colours[i])
lines(preddat_i$M6_24_sch,preddat_i$pred.glo, lty=2)
}
## Add points for "observed" ForPix for commune i across all observed pop_den across communes.
points(dat_i$M6_24_sch, dat_i$ForPix, pch = 21, bg = com_colours[i], col = com_colours[i])
}
}
#' I think it is fair to say that there is no relationship between forest cover and males in school.
#'
#' ## Employment
#'
#' There are two variables in this set - the proportion of the population engaged in the Primary Sector and the proportion engaged in the Secondary Sector. The primary sector includes sectors of the economy that extracts or harvests products from the earth such as raw materials and basic foods, and includes farming, fishing, mining etc. The secondary sector includes the production of finished goods from raw materials, and includes manufacturing, processing, and construction.
#'
#' I have no *a priori* hypothesis about an interaction between these two variables, and so I have not tested one. It is also plausible that although these two are not correlated (-0.2), they may well be related as they are both proportions drawn from the same population, therefore including an interaction might be misleading.
#'
#' The model:
#'
#+ emp.m1, include=TRUE
emp.m1 <- glmer(ForPix ~ propPrimSec + propSecSec + offset(log(areaKM)) + (year|Province/Provcomm),
family="poisson", data=dat1)
summary(emp.m1)
#' Province and commune variance similar to other model sets. Year variance for commune is an order of magnitude larger than for province, but both very small. propPrimSec has positive effect, propSecSec has negative, but both very small and approximate p values > 0.5. The model produces a warning about large eigenvalues. The variables are already scaled so I guess this just suggests a poor model fit.
#'
#' Quick plot of the effects
#'
#+ plot_model emp.m1, echo=FALSE, results=TRUE
plot_model(emp.m1, type="re")
plot_model(emp.m1, type="pred", terms=c("propPrimSec"))
plot_model(emp.m1, type="pred", terms=c("propSecSec"))
#' These two variables do not appear to be important. I will try and remove propSecSec
#'
#+ emp.m2, include=TRUE
emp.m2 <- glmer(ForPix ~ propPrimSec + offset(log(areaKM)) + (year|Province/Provcomm), family="poisson", data=dat1)
summary(emp.m2)
#' Compare the two models:
#'
#+ anova emp.m1 and emp.m2, include=TRUE
anova(emp.m1, emp.m2, test="Chisq")
#' The simpler model is better, but is still pretty uninteresting
#'
#' ## Economic Security
#'
#' In this set there are two variables - the proportion of families who have less than 1 hectare of agricultural land, and the proportion of families who keep pigs. Both of these things are fairly good proxies for a family's economic security, especially the farming land variable.
#'
#+ econ.m1, include=TRUE
econ.m1 <- glmer(ForPix ~ Les1_R_Land + pig_fam + offset(log(areaKM)) + (year|Province/Provcomm),
family="poisson", data=dat1)
summary(econ.m1)
#' Very small effects with large approximate p values. Random effects similar to previous models. Les1_R_Land has a tiny negative effect, pig_fam has a small positive effect.
#'
#' Quick plot of the main effects:
#'
#+ plot_model econ.m1, echo=FALSE, results=TRUE
plot_model(econ.m1, type="pred", terms="Les1_R_Land")
plot_model(econ.m1, type="pred", terms="pig_fam")
#' Again, these variables do not look like they can provide much. I did run model selection, and the simpler models (i.e. with just one of the vars) were better than model 1 with both variables, but the effects were similarly tiny.
#'
#' ## Access to Services
#'
#' This model set has three variables - median distance to the nearest school, median distance to the Commune office, and the proportion of families with access to waste collection.
#'
#+ acc.m1, include=TRUE
acc.m1 <- glmer(ForPix ~ dist_sch + garbage + KM_Comm + offset(log(areaKM)) +
(year|Province/Provcomm),family="poisson", data=dat1)
summary(acc.m1)
#' Also produces warning about large eigenvalues. All three variables have tiny effects with large approximate p values.
#'
#' Quick plots of the main effects
#'
#+ plot_model acc.m1, echo=FALSE, results=TRUE
plot_model(acc.m1, type="pred", terms="dist_sch")
plot_model(acc.m1, type="pred", terms="garbage")
plot_model(acc.m1, type="pred", terms="KM_Comm")
#' These variables do not appear to be useful. I completed model selection using a combination of LRT's and AICc comparison, and all of the models with only an individual predictor were better than any model with more than one predictor. The top three models were therefore models with each of the single predictors, and there was virtually no difference between them (dAICc < 0.1). But they were equally as useless as the acc.m1 i.e. tiny effects, large approximate p values, flat main effect.
#'
#' ## Social Justice
#'
#' This set includes two predictor variables - the raw number of land conflict cases, and the per capita number of criminal cases. I had no *a priori* hypothesis about an interaction between these two variables, and so I did not test one.
#'
#+ just.m1, include=TRUE
jus.m1 <- glmer(ForPix ~ crim_case + land_confl + offset(log(areaKM)) + (year|Province/Provcomm),
family="poisson", data=dat1)
summary(jus.m1)
#' Very small effects with large approximate p values. Similar RE variances to previous model sets.
#'
#' Quick plots of main effects:
#'
#+ plot_model jus.m1, echo=FALSE, results=TRUE
plot_model(jus.m1, type="pred", terms="crim_case")
plot_model(jus.m1, type="pred", terms="land_confl")
#' I removed land_confl for jus.m2, and LRT suggested the simpler model was better, but the resulting model still had tiny effect for crim_case, with large approximate p value. The plot was just as flat as jus.m1.
#'
#' ## Migration
#'
#' There are two predictors in this set - raw number of in-migrants and out-migrants. For these variables, I thought there was cause to test an interaction, as the relationship between migration in and out of a commune is potentially complex, and intertwined with various aspects of the local economy and natural resource use.
#'
#+ mig.m1, include=TRUE
mig.m1 <- glmer(ForPix ~ Pax_migt_in*Pax_migt_out + offset(log(areaKM)) + (year|Province/Provcomm),
family="poisson", data=dat1)
summary(mig.m1)
#' Very small effects and large approximate p values. No change in the RE variances
#'
#' Quick plots of the marginal effects of interaction terms:
#'
#+ plot_model mig.m1, echo=FALSE, results=TRUE
plot_model(mig.m1, type="pred", terms=c("Pax_migt_in","Pax_migt_out[-0.47,0,16.7]"))
plot_model(mig.m1, type="pred", terms=c("Pax_migt_out","Pax_migt_in[-0.53,0,11.1]"))
#' There appears to be a small interaction. When out-migration from a commune is large, then the effect of in-migration is positive, whereas there is no effect when out-migration is low or at its mean. Similarly, when in-migration to a commune is large, then there is a small positive effect of out-migration. There is no effect of out-migration when in-migration is low or at its mean. Nevertheless, neither term, nor the interaction are particularly convincing. Model selection using LRT suggested that a model with just Pax_migt_out was significantly better than the model with both terms. And the resulting model has as equally unimpressive effect.
#'
#+ mig.m2, include=TRUE
mig.m2 <- glmer(ForPix ~ Pax_migt_out + offset(log(areaKM)) + (year|Province/Provcomm),
family="poisson", data=dat1)
summary(mig.m2)
anova(mig.m1,mig.m2,test="Chisq")
# simpler model is better
plot_model(mig.m2, type="pred", terms="Pax_migt_out")
#' ## Environmental variables
#'
#' This set initially had two predictor variables - mean elevation and habitat. These variables were intially supposed to be "control" variables, i.e. ensuring that other, non-socioeconomic predictors that would be likely to affect forest cover, were taken into account. I did run some models, diagnostics, and predictions using both variables, but I have decided to drop habitat altogether. This is because the layer I was using for the habitat was the same layer that produced the response - i.e. to get the "forest pixel" layer used in the response, I simply aggregated all of the forest habitat types. Therefore I don't think it is appropriate to use the same layer as a predictor! That leaves me with mean elevation.
#'
#+ env.m2 elevation only, include=TRUE
env.m2 <- glmer(ForPix ~ mean_elev + offset(log(areaKM)) + (year|Province/Provcomm),
family = "poisson", data=dat1)
summary(env.m2)
#' The RE variances have decreased slightly compared to previous model sets, suggesting that the elevation predictor is explaning more of the total variance. Elevation appears to have a positive effect on forest pixels and appears significant (very small approximate p value).
#'
#' ### Diagnostics
#'
#+ env.m2 diagnostics 1, include=FALSE
# copy data
env.m2.diag <- dat1
env.m2.diag$Provcomm <- as.factor(env.m2.diag$Provcomm)
# attach residuals
env.m2.diag$m2res <- resid(env.m2)
# attach conditional predictions
env.m2.diag$m2pred <- as.vector(predict(env.m2, type="response"))
#+ env.m2 predicted vs observed plot, echo=FALSE, results=TRUE
plot(env.m2.diag$m2pred, env.m2.diag$ForPix)
#' The above plot is the predicted versus observed values, which looks good.
#+ env.m2 residuals vs fitted plot, echo=FALSE, results=TRUE
plot(env.m2.diag$m2pred, env.m2.diag$m2res)
#' The above plot is the predicted values versus model residuals. Again heteroskedasicity is an issues here - particularly bad a low predicted forest cover. Similar to the popdem models.
#'
#' Bit more exploration of residuals, but now over the explanatory variable:
#+ env.m2 residual plots, echo=FALSE, results=TRUE, fig.width=10, fig.height=10, dpi=100
par(mfrow=c(2,2))
plot(env.m2.diag$mean_elev, env.m2.diag$m2res, ylab = "residuals", xlab = "mean elevation")
boxplot(m2res ~ factor(Province), data = env.m2.diag, outline = T, xlab = "Province",
ylab = "Residuals w/i Province")
boxplot(m2res ~ factor(Provcomm), data = env.m2.diag, outline = T, xlab = "Commune",
ylab = "Residuals w/i Commune")
#' There seems to be a slightly odd pattern in the first plot - it looks like there are certain elevation values that produce large residuals. Zoom in:
#+ env.m2 elevation vs residuals, echo=FALSE, results=TRUE
plot(env.m2.diag$mean_elev, env.m2.diag$m2res, xlim = c(-1,2),ylab = "residuals", xlab = "mean elevation")
#' Looks like elevation values of approx -0.6, -0.4, -0.1, 0.2, 0.8.
#'
#' I will take a closer look at the Provinces that have the communes that appear to produce the largest residuals.
#'
#+ env.m2 provinces with largest residuals, echo=FALSE, results=TRUE
provs <- c("Battambang","Kampong Cham","Kampong Chhnang","Kampong Thom","Koh Kong","Kracheh",
"Mondul Kiri","Otdar Meanchey","Preah Sihanouk","Pursat","Ratanak Kiri","Siem Reap",
"Stung Treng")
prob.provs <- dat %>% filter(Province %in% provs)
prob.provs$type <- "problem"
other.provs <- dat %>% filter(!Province %in% provs)
other.provs$type <- "other"
all.provs <- rbind(prob.provs,other.provs)
# get provincial means
prov.elev.mean <- all.provs %>% group_by(Province) %>% summarise(mean = mean(mean_elev))
prov.elev.mean$type <- ifelse(prov.elev.mean$Province %in% provs, "problem", "other")
# plot mean elevation by province
ggplot(prov.elev.mean, aes(x=Province, y=mean, colour=type))+
geom_point(size=4)+
theme(element_blank())+
ylab("Mean elevation")
#' The above plot shows the mean elevation (on the original scale) for each Province, with the "problem" provinces (i.e. the ones with the largest residuals) coloured blue. There is not a striking trend, but the 4 provinces with the lowest mean elevation are all *not* problematic ones.
#'
#' Now I will pull out the individual communes that have residual values that match the weird pattern and see if there is any other pattern that might explain it.
#+ env.m2 prob.com, echo=FALSE, results=TRUE
par(mfrow=c(1,1))
prob.coms <- env.m2.diag %>% filter(m2res > 0.5 | m2res < -0.5)
plot(prob.coms$mean_elev, prob.coms$m2res)
#' The above plot are the "problem" residuals. These are now the communes with the weird shape. Let's have a look that these communes and their mean elevation (on the original scale), compared with all other communes:
#'
#+ env.m2 prob.coms, echo=FALSE, results=TRUE
coms <- prob.coms$Commune
prob.coms.orig <- dat[dat$Commune %in% coms,]
other.coms.orig <- dat %>% filter(!Commune %in% coms)
ggplot()+
geom_point(data=other.coms.orig, aes(x=Commune, y=mean_elev, colour="other"))+
geom_point(data=prob.coms.orig, aes(x=Commune, y=mean_elev, colour="problem"))+
theme(element_blank())+
ylab("Mean elevation")
#' I can't see an obvious pattern here. The other fixed effect is the offset - areaKM. Perhaps this is the source of the issue:
#'
#+ env.m2 prob.com - areaKM plot, echo=F, results=T
ggplot()+
geom_point(data=other.coms.orig, aes(x=Commune, y=areaKM, colour="other"))+
geom_point(data=prob.coms.orig, aes(x=Commune, y=areaKM, colour="problem"))+
theme(element_blank())+
ylab("Area (KM)")
#' No obvious pattern. Let's look at the response (ForPix):
#'
#+ env.m2 prob.com ForPix plot, echo=F, results=T
ggplot()+
geom_point(data=other.coms.orig, aes(x=Commune, y=ForPix, colour="other"))+
geom_point(data=prob.coms.orig, aes(x=Commune, y=ForPix, colour="problem"))+
theme(element_blank())+
ylab("Forest pixels")
#' Ok so there is an obvious difference here. The problem communes clearly mostly lose forest over time (vertical lines of dots), whereas the others generally do not (single points). This is the same issue as highlighted in the population demographics model. So the global model does not fit well when communes lose forest over time.
#'
#' ### Predict main effects
#'
#+ env.m2 predict main effects, echo=FALSE, results=TRUE
env_m2_newdata <- data.frame(mean_elev = seq(from=min(dat1$mean_elev), to=max(dat1$mean_elev),
length.out = 100),
areaKM = mean(dat1$areaKM))
# predict
env_m2_newdata$pred <- as.vector(predict(env.m2, type="response", newdata=env_m2_newdata,
re.form=NA))
# plot with free y axis
env.m2.main.plot <- ggplot(env_m2_newdata, aes(x=mean_elev, y=pred))+
geom_line()+
theme(element_blank())+
xlab("Mean elevation (scaled)")+
ylab("Predicted forest cover (pixels)")
# plot
env.m2.main.plot2 <- ggplot(env_m2_newdata, aes(x=mean_elev, y=pred))+
geom_line()+
theme(element_blank())+
ylim(0,20000)+
xlab("Mean elevation (scaled)")+
ylab("Predicted forest cover (pixels)")
env.m2.main.plot + env.m2.main.plot2
#' The above two plots show the predicted effects of mean elevation for an "average" commune (i.e. not commune-specific RE's), with a free y-axis (left) and with a realistic y axis (right). We can see that mean elevation has a positive effect on forest cover. I was expecting this relationship. Most of the highly forested areas in Cambodia are in the provinces with higher elevation.
#'
#' ### Predict for specific commmunes
#'
#' I will start by predicting for the 4 communes with intercepts closest to 0, the 4 communes with intercepts furthest above 0, and the communes with intercepts furthest below 0.
#'
#+ env.m2 commune predictions, echo=FALSE, results=TRUE, fig.width=8, fig.height=8, dpi=100
env.m2.com <- ranef(env.m2)[[1]]
# re-order
env.m2.com <- env.m2.com[order(env.m2.com[ ,"(Intercept)"], decreasing = FALSE),]
# which communes
coms <- c("Koh Kong_Bak Khlang","Kracheh_Bos Leav","Preah Vihear_Kuleaen Tboung","Ratanak Kiri_Saom Thum",
"Kampong Cham_Tuol Snuol","Banteay Meanchey_Paoy Char","Kampong Cham_Khpob Ta Nguon","Kampong Chhnang_Dar",
"Kampong Thom_Chaeung Daeung","Kracheh_Han Chey","Kampong Thom_Tang Krasang","Siem Reap_Nokor Pheas")
# which provinces
provs <- c("Koh Kong","Kracheh","Preah Vihear","Ratanak Kiri",
"Kampong Cham","Banteay Meanchey","Kampong Cham","Kampong Chhnang",
"Kampong Thom","Kracheh","Kampong Thom","Siem Reap")
# customise the range of elevations I am predicting for, on the basis of each commune.
### Easiest to define the range of mean_elev to predict for, first. Min/max per commune:
mean_elev_min <- tapply(dat1$mean_elev, dat1$Provcomm, min)
mean_elev_max <- tapply(dat1$mean_elev, dat1$Provcomm, max)
### Min/max within your selection of communes:
mean_elev_min <- min(mean_elev_min[names(mean_elev_min) %in% coms])
mean_elev_max <- max(mean_elev_max[names(mean_elev_max) %in% coms])
# create new prediction grid for specific communes with varying mean_elev
env_m2_newdat_com <- data.frame(Provcomm = rep(coms, each=100),
Province = as.factor(rep(provs, each=100)),
mean_elev = seq(from=mean_elev_min, to=mean_elev_max, length.out = 100),
year = mean(dat1$year))
# add commune-specific areaKM offset
env_m2_newdat_com$areaKM <- dat1$areaKM[match(env_m2_newdat_com$Provcomm, dat1$Provcomm)]
# re-order levels so they plot in the correct sets
env_m2_newdat_com$Provcomm <- factor(env_m2_newdat_com$Provcomm,
levels = c("Koh Kong_Bak Khlang",
"Kracheh_Bos Leav",
"Preah Vihear_Kuleaen Tboung",
"Ratanak Kiri_Saom Thum",
"Kampong Cham_Tuol Snuol",
"Banteay Meanchey_Paoy Char",
"Kampong Cham_Khpob Ta Nguon",
"Kampong Chhnang_Dar",
"Kampong Thom_Chaeung Daeung",
"Kracheh_Han Chey",
"Kampong Thom_Tang Krasang",
"Siem Reap_Nokor Pheas"))
# attach commune-specific predictions
env_m2_newdat_com$pred.com <- as.vector(predict(env.m2, type="response", newdata=env_m2_newdat_com,
re.form=~(year|Province/Provcomm)))
# attach global predictions
env_m2_newdat_com$pred.glo <- rep(env_m2_newdata$pred, times=12)
# colours
require(RColorBrewer)
com_colours <- brewer.pal(11, "RdYlBu")
com_colours <- c(head(com_colours,4),tail(com_colours,4))
com_colours_greys <- tail(brewer.pal(9, "Greys"),4)
com_colours <- c(com_colours, com_colours_greys)
com_colours <- com_colours[sample(1:length(com_colours),12,replace=F)]
### This is just to check if you have commented tbe above out: :)
if(!exists("com_colours")) {
com_colours <- rep("black", 12)
}
provcomm_lvls <- levels(env_m2_newdat_com$Provcomm)
par(mfrow = c(3,4))
### Note the scales are important here - we need to set a scale that encompasses all the communes and the full
### population density range across all communes, so we need to do this overall:
ylo <- min(env_m2_newdat_com$pred.com)*0.9
yhi <- max(env_m2_newdat_com$pred.com)*1.1
xlo <- min(dat1[dat1$Provcomm %in% levels(env_m2_newdat_com$Provcomm),"mean_elev"])
xhi <- max(dat1[dat1$Provcomm %in% levels(env_m2_newdat_com$Provcomm),"mean_elev"])
### Iterate through the communes (levels in m6_newdat_com$Provcomm):
for(i in 1:length(provcomm_lvls)) {
### Pick commune i data from the predictions:
preddat_i <- env_m2_newdat_com[env_m2_newdat_com$Provcomm==provcomm_lvls[i],]
### Pick commune i data from observed data:
dat_i <- dat1[dat1$Provcomm==provcomm_lvls[i],]
## If this is the first plot, use plot(), otherwise lines() to add to an existing plot:
# if(i == 1) {
# Plot predicted ForPix as function of pop_den; as "line" type. Note this is where you set axis limits.
plot(preddat_i$mean_elev,preddat_i$pred.com,
type = "l",
col = com_colours[i],
ylim = c(ylo,yhi), xlim = c(xlo,xhi),
xlab = "Mean elevation (scaled & standardised",
ylab = "Predicted forest pixels",
main = unique(preddat_i$Provcomm))
# } else {
lines(preddat_i$mean_elev,preddat_i$pred.com, col = com_colours[i])
lines(preddat_i$mean_elev,preddat_i$pred.glo, lty=2)
#}
## Add points for "observed" ForPix for commune i across all observed pop_den across communes.
points(dat_i$mean_elev, dat_i$ForPix, pch = 21, bg = com_colours[i], col = com_colours[i])
}
#' In the above plots, the top row are the communes with intercepts clsoest to 0, middle row are those with intercepts furthest above 0, and bottom row are those with intercepts furthest below 0. The dashed black line is the global model, and the coloured solid lines are the commune-specific predictions. The dots are the actual ForPix ~ mean elevation points for that commune.
#' We can see that as for the population demographics model, the global model predicts poorly for communes with high forest cover, regardless of mean elevation. If a commune has low forest cover, then the global model predicts well for increasing values of elevation, until elevation reaches a scaled value of ~1, after which the model predicts poorly (becasue a commune can't increase in elevation).
#'
#' Let's do the same predictions but for a random set of communes:
#'
#+ env.m2 commune predictions - random, echo=FALSE, results=TRUE,fig.width=8, fig.height=8, dpi=100
par(mfrow = c(3,3))
set.seed(123)
runs <- c(1:9)
for(i in 1:length(runs)){
# randomly sample communes
rand.com <- sample(dat1$Provcomm, 9, replace = FALSE)
rand.prov <- unlist(strsplit(rand.com, "_"))
rand.prov <- rand.prov[c(1,3,5,7,9,11,13,15,17)]
# define the range of pop_den to predict for, first. Min/max per commune:
mean_elev_min <- tapply(dat1$mean_elev, dat1$Provcomm, min)
mean_elev_max <- tapply(dat1$mean_elev, dat1$Provcomm, max)
# Min/max within your selection of communes:
mean_elev_min <- min(mean_elev_min[names(mean_elev_min) %in% rand.com])
mean_elev_max <- max(mean_elev_max[names(mean_elev_max) %in% rand.com])
# min not really different but max very different
# create new prediction grid for specific communes with varying pop_den
env.m2_newdat_com_ran <- data.frame(Provcomm = rep(rand.com, each=100),
Province = rep(rand.prov, each=100),
mean_elev = seq(from=mean_elev_min, to=mean_elev_max, length.out = 100),
year = mean(dat1$year))
# add commune-specific areaKM offset
env.m2_newdat_com_ran$areaKM <- dat1$areaKM[match(env.m2_newdat_com_ran$Provcomm, dat1$Provcomm)]
# attach commune-specific predictions
env.m2_newdat_com_ran$pred.com <- as.vector(predict(env.m2, type="response",
newdata=env.m2_newdat_com_ran,
re.form=~(year|Province/Provcomm)))
# attach global predictions
env.m2_newdat_com_ran$pred.glo <- rep(env_m2_newdata$pred, times=9)
# set levels
env.m2_newdat_com_ran$Provcomm <- as.factor(env.m2_newdat_com_ran$Provcomm)
provcomm_lvls <- levels(env.m2_newdat_com_ran$Provcomm)
# set scales
ylo <- min(env.m2_newdat_com_ran$pred.com)*0.9
yhi <- max(env.m2_newdat_com_ran$pred.com)*1.1
xlo <- mean_elev_min
xhi <- mean_elev_max
# Iterate through the communes (levels in m6_newdat_com$Provcomm):
for(i in 1:length(provcomm_lvls)) {
### Pick commune i data from the predictions:
preddat_i <- env.m2_newdat_com_ran[env.m2_newdat_com_ran$Provcomm==provcomm_lvls[i],]
### Pick commune i data from observed data:
dat_i <- dat1[dat1$Provcomm==provcomm_lvls[i],]
## If this is the first plot, use plot(), otherwise lines() to add to an existing plot:
if(i == 1) {
# Plot predicted ForPix as function of pop_den; as "line" type. Note this is where you set axis limits.
plot(preddat_i$mean_elev,preddat_i$pred.com,
type = "l",
col = com_colours[i],
ylim = c(ylo,yhi), xlim = c(xlo,xhi),
xlab = "Mean elevation (scaled & standardised",
ylab = "Predicted forest pixels",
main = unique(preddat_i$Provcomm))
} else {
lines(preddat_i$mean_elev,preddat_i$pred.com, col = com_colours[i])
lines(preddat_i$mean_elev,preddat_i$pred.glo, lty=2)
}
## Add points for "observed" ForPix for commune i across all observed pop_den across communes.
points(dat_i$mean_elev, dat_i$ForPix, pch = 21, bg = com_colours[i], col = com_colours[i])
}
}
#' Each plot contains a random sample of 9 communes. Again the black dashed line is the global model. Note the varying y-axes. After running the above random sampling code a few times, it looks as though the global model is good at predicting at low forest cover and low elevation (as with the population density model), as this is where most of the communes sit on the spectrum. It performs ok for communes with higher elevation provided they don't have too much forest! As soon as the commune has lots of forest or very high elevation, the global model performs badly. It looks as though the commune-specific models predict quite well, provided the communes does not lose forest (as with the population density model).
#'
#' ## Additional human predictor variables
#'
#' As with the environmental predictor above, these variables were supposed to be "control" variables. The variables included in this set are distance to border (from the centre of the commune), distance to the Provincial Capital (from the centre of the commune), presence of economic land concessions ("elc", binary), presence of a PA (any kind of PA, binary), PA category (7 levels, including "none").
#'
#+ hum.m1, include=TRUE
hum.m1 <- glmer(ForPix ~ dist_border+dist_provCap+elc+PA+PA_cat+offset(log(areaKM)) +
(year|Province/Provcomm), family = "poisson", data=dat1)
summary(hum.m1)
#' Model produces a rank deficiency warning. Interestingly, PA doesn't appear to look important. This surprises me as you would assume that PAs would be placed in areas with high forest cover. elc doesn't appear to be important, which is also surprising because I could imagine two scenarios 1) it would have a postive relationship because elc's were often placed in forested areas, and 2) a negative relationship because the elc's would have cleared a lot of forest in the areas they were placed. However, during this time period, perhaps not much forest clearing had happened yet. dist_border and dst_provCap appear to be important, with both having a positive effect. dist_provCap I can understand - communes further away from urban centres are likely to be more forested. Not sure yet about dist_border. I think all vars require further investigation.
#'
#' I will do some quick plots below:
#'
#+ hum.m1 plot_models, echo=FALSE, results=TRUE, warning=F, fig.width=8, fig.height=8, dpi=100
# quick plots
hum.p1 <- plot_model(hum.m1, type="pred", terms="dist_border")
hum.p2 <- plot_model(hum.m1, type="pred", terms="dist_provCap")
hum.p3 <- plot_model(hum.m1, type="pred", terms="elc")
hum.p4 <- plot_model(hum.m1, type="pred", terms="PA")
hum.p5 <- plot_model(hum.m1, type="pred", terms="PA_cat") # surprised RMS level is not sig given the coefficient
hum.p1+hum.p2+hum.p3+hum.p4+hum.p5
#' From the quick plots above, it looks like both dist_border and dist_provCap do have a relationship with forest cover. elc does not look promising (note the y axis - difference is tiny), and neither really does PA. Not much difference in predicted forest cover for the different PA categories, apart from the RMS (RAMSAR) level.
#'
#' I conducted LRT's and AICc comparisons, and moved forward with predictions and plotting for models with dist_border, dist_provCap, PA and elc. But it became clear that PA and elc did very little, and so I have settled on a model with just dist_border and dist_provCap.
#'
#' ### Diagnostics
#'
#+ hum.m5 pred and res and plot observerd vs predicted, echo=FALSE, results=TRUE
# copy data for diagnostics
hum.m5 <- glmer(ForPix ~ dist_border+dist_provCap+offset(log(areaKM)) +
(year|Province/Provcomm), family = "poisson", data=dat1)
hum.diag.dat <- dat1
# residuals
hum.diag.dat$m5res <- resid(hum.m5)
# conditional predictions
hum.diag.dat$m5.pred <- as.vector(predict(hum.m5, type="response", re.form=NA))
plot(hum.diag.dat$m5.pred, hum.diag.dat$ForPix)
#' The above plot is the observed values versus the predicted values (from a fully conditional model). This plot is not great - worse than the previous model sets, and it looks like the model is under-predicting by quite a long way.
#'
#+ hum.m5 plot residuals versus predicted, echo=FALSE, results=TRUE
plot(hum.diag.dat$m5.pred, hum.diag.dat$m5res)
#' The above plot is the predicted values versus the model residuals. This doesn't look great. Some outlier large predictions which have small residuals, but a lot of heterogeneity at smaller predicted values. There's an odd line of residuals just below 2000 (x axis) which suggests there's one predicted value that is appearing quite a few times? Below I look more closely at the residuals.
#'
#+ hum.m5 residual plots, echo=FALSE, results=TRUE, fig.width=10, fig.height=10, dpi=100
par(mfrow=c(2,2))
plot(hum.diag.dat$dist_border, hum.diag.dat$m5res, ylab = "residuals", xlab = "distance to border")
plot(hum.diag.dat$dist_provCap, hum.diag.dat$m5res, ylab = "residuals", xlab = "distance to Prov Cap")
boxplot(m5res ~ factor(Province), data = hum.diag.dat, outline = T, xlab = "Province",
ylab = "Residuals w/i Province")
boxplot(m5res ~ factor(Provcomm), data = hum.diag.dat, outline = T, xlab = "Commune",
ylab = "Residuals w/i Commune")
#' Based on the first two plots, it looks like there's only a relatively small number of communes that have really large residuals (and there seems to be patterns in these).
#'
#' Zoom in:
#'
#+ hum.m5 residual plots zoom, echo=FALSE, results=TRUE, fig.width=10, fig.height=10, dpi=100
par(mfrow=c(2,1))
plot(hum.diag.dat$dist_border, hum.diag.dat$m5res, ylim=c(-3,3),
ylab = "residuals", xlab = "distance to border")
plot(hum.diag.dat$dist_provCap, hum.diag.dat$m5res, ylim=c(-3,3),
ylab = "residuals", xlab = "distance to Prov Cap")
#' The slightly odd patterns are smaller residuals between 0 and 1 dist_border, and between probably 0 and 0.3 for dist_provCap.
#'
#' I had a look at which provinces have the larger residuals to see if they match with the problem provinces from the previous model sets. They are Battambang, Kampong Cham, Kampong Chhnanhg, Kampong Thom, Koh Kong, Kracheh, Mondul Kiri, Otdar Meanchey, Pursat, Ratanak Kiri, Siem Reap, Stung Treng. These are the same provinces that are causing issues in the other model sets.
#'
#' As I have mentioned before, I think these problem communes are the ones that are losing forest over time. I used the raw data to assess which Provinces contain communes that lose some forest over the study period.
#'
#+ hum.m5 Provinces that lose forest, echo=FALSE, results=TRUE
diffPix <- dat1 %>% group_by(Provcomm) %>% summarise(sum = sum(diffPix))
provs <- unlist(strsplit(diffPix$Provcomm, "_"))
provs1 <- provs[seq(1, length(provs), 2)]
diffPix$Province <- provs1
unique(diffPix$Province[diffPix$sum > 0])
#' So this may go some way towards explaining the issues. However, there are still Provinces that lose no forest but are still causing issues, such as Kampong Chhnang and Kampong Thom. I looked more closely at some of the individual communes that had very large residuals.
#'
#+ hum.m5 communes larege residusals, echo=FALSE, results=TRUE
prob.coms <- hum.diag.dat[hum.diag.dat$m5res > 1 | hum.diag.dat$m5res < -1,]
prob.coms$type <- "problem"
other.coms <- hum.diag.dat %>% filter(!Provcomm %in% prob.coms$Provcomm)
other.coms$type <- "other"
all.coms <- rbind(prob.coms, other.coms)
plot(prob.coms$m5.pred, prob.coms$m5res)
#' The residuals above are the largest ones. Below, I have split all of the communes into the ones that produced the residuals above, and the rest:
#'
#+ hum.m5 prob coms vs ForPix, echo=F, results=T, fig.width=10, fig.height=10, dpi=100
hum.plot1 <- ggplot(all.coms, aes(x=Provcomm, y=ForPix, colour=type))+
geom_point()+
theme(element_blank())+
labs(x="Commune", y="Forest pixels")
hum.plot2 <- ggplot(all.coms, aes(x=Provcomm, y=areaKM, colour=type))+
geom_point()+
theme(element_blank())+
labs(x="Commune", y="Commune area (KM)")
hum.plot3 <- ggplot(all.coms, aes(x=Provcomm, y=dist_border, colour=type))+
geom_point()+
theme(element_blank())+
labs(x="Commune", y="Distance to border")
hum.plot4 <- ggplot(all.coms, aes(x=Provcomm, y=dist_provCap, colour=type))+
geom_point()+
theme(element_blank())+
labs(x="Commune", y="Distance to Provincial Captital")
hum.plot1+hum.plot2+hum.plot3+hum.plot4
#' The top left plot is forest pixels per commune, the top right plot is the area (KM) of the communes, the bottom left plot is distance to border, and the bottom right is distance to provincial capital. None of these show an obvious pattern to me - and in fact in the top left plot (forest pixels) the loss of forest over time doesn't look unique to the problem communes, as it did in the previous sets. The only pattern I can see in these plots is that the problem communes are spatially relatively close and clumped (they are grouped by Province in the dataframe and so if they are plotted near one another on the x axis they are probably in the same Province). But the issues are certainly not unique to a single province, or to a set of communes all with similar characteristics (that I can think of anyway!). So am not sure exactly what the other reasons are for the large residuals in those communes.
#'
#' ### Predict main effects
#'
#' Below are the predictions for dist_border and dist_provCap from the 'global' model.
#'
#+ hum.m5 main effects predictions, echo=F, results=T
# create new data for dist_border
dist_border_newdat <- expand.grid(dist_border = seq(min(dat1$dist_border), max(dat1$dist_border),
length.out = 100),
dist_provCap = mean(dat1$dist_provCap),
areaKM = mean(dat1$areaKM))
# predict
dist_border_newdat$pred <- as.vector(predict(hum.m5, type="response", newdata=dist_border_newdat, re.form=NA))
# create new data for dist_provCap
dist_provCap_newdat <- expand.grid(dist_provCap = seq(min(dat1$dist_provCap), max(dat1$dist_provCap),
length.out = 100),
dist_border = mean(dat1$dist_border),
areaKM = mean(dat1$areaKM))
# predict
dist_provCap_newdat$pred <- as.vector(predict(hum.m5, type="response", newdata=dist_provCap_newdat,
re.form=NA))
# plot
hum.p6 <- ggplot(dist_border_newdat, aes(x=dist_border, y=pred))+
geom_line(size=1)+
theme(element_blank())+
ylim(0,2000)+
xlab("Distance to international border (scaled and centered)")+
ylab("Predicted forest cover (pixels)")+
ggtitle("Distance to border")
hum.p7 <-ggplot(dist_provCap_newdat, aes(x=dist_provCap, y=pred))+
geom_line(size=1)+
theme(element_blank())+
ylim(0,2000)+
xlab("Distance to provincial capital (scaled and centered)")+
ylab("Predicted forest cover (pixels)")+
ggtitle("Distance to provincial capital")
hum.p6 + hum.p7
#' We can see that both predictors have a positive effect on forest cover, and that distance to provincial capital is the stronger effect. The relationship with dist_provCap makes sense - the more rural/remote a communes is, the more likely it is to be forested. Communes that are in or around large urban centres, are unlikely to be heavily forested. The dist_border relationship is more difficult to explain easily. Based on my knowledge of the country I was expecting the opposite - lots of the large PAs are near international borders, whereas much of the central part of the country is farmland. I will need to investigate this further.
#'
#' ### Predict for specific communes
#'
#' Below I have run predictions for 12 communes - the four with intercepts closest to 0, four with intercepts furthest above 0, and the four with intercepts furthest below 0.
#'
#' First for dist_border
#'
#+ hum.m5 commune predictions dist_border, echo=F, results=T, fig.width=8, fig.height=8, dpi=100
hum.m5.com <- ranef(hum.m5)[[1]]
# re-order
hum.m5.com <- hum.m5.com[order(hum.m5.com[ ,"(Intercept)"], decreasing = TRUE),]
# which communes
coms <- c("Stung Treng_Kbal Romeas","Preah Vihear_Chhaeb Pir","Kampong Cham_Kampoan","Preah Vihear_Kuleaen Tboung",
"Kampot_Preaek Tnaot","Kampot_Kaoh Touch","Kampong Chhnang_Chieb","Kampong Cham_Pongro",
"Kampong Thom_Chaeung Daeung","Kracheh_Han Chey","Preah Vihear_Reaksmei","Siem Reap_Nokor Pheas")
# which provinces
provs <- c("Stung Treng","Preah Vihear","Kampong Cham","Preah Vihear",
"Kampot","Kampot","Kampong Chhnang","Kampong Cham",
"Kampong Thom","Kracheh","Preah Vihear","Siem Reap")
### define the range of dist_border to predict for. Min/max per commune:
dist_border_min <- tapply(dat1$dist_border, dat1$Provcomm, min)
dist_border_max <- tapply(dat1$dist_border, dat1$Provcomm, max)
### Min/max within your selection of communes:
dist_border_min <- min(dist_border_min[names(dist_border_min) %in% coms])
dist_border_max <- max(dist_border_max[names(dist_border_max) %in% coms])
# create new prediction grid for specific communes with varying dist_border
hum_m5_newdat_bord <- data.frame(Provcomm = rep(coms, each=100),
Province = rep(provs, each=100),
dist_border = seq(dist_border_min, dist_border_max, length.out = 100),
year = mean(dat1$year))
# add dist_provCap
hum_m5_newdat_bord$dist_provCap <- dat1$dist_provCap[match(hum_m5_newdat_bord$Provcomm, dat1$Provcomm)]
# add commune-specific areaKM offset
hum_m5_newdat_bord$areaKM <- dat1$areaKM[match(hum_m5_newdat_bord$Provcomm, dat1$Provcomm)]
# re-order levels so they plot in the correct sets
hum_m5_newdat_bord$Provcomm <- factor(hum_m5_newdat_bord$Provcomm,
levels = c("Stung Treng_Kbal Romeas","Preah Vihear_Chhaeb Pir",
"Kampong Cham_Kampoan","Preah Vihear_Kuleaen Tboung",
"Kampot_Preaek Tnaot","Kampot_Kaoh Touch","Kampong Chhnang_Chieb",
"Kampong Cham_Pongro","Kampong Thom_Chaeung Daeung",
"Kracheh_Han Chey","Preah Vihear_Reaksmei","Siem Reap_Nokor Pheas"))
# attach commune-specific predictions
hum_m5_newdat_bord$pred.com <- as.vector(predict(hum.m5, type="response", newdata=hum_m5_newdat_bord,
re.form=~(year|Province/Provcomm)))
# attach global predictions. need to alter areaKM below so that the global model has only the mean areakM rather than the commune-specific one. This is fine as pred.com is already done
hum_m5_newdat_bord <- hum_m5_newdat_bord %>% rename(areaKM_com = areaKM)
hum_m5_newdat_bord$areaKM <- mean(dat1$areaKM)
hum_m5_newdat_bord$pred.glo <- as.vector(predict(hum.m5,type="response",newdata=hum_m5_newdat_bord,re.form=NA))
require(RColorBrewer)
com_colours <- brewer.pal(11, "RdYlBu")
com_colours <- c(head(com_colours,4),tail(com_colours,4))
com_colours_greys <- tail(brewer.pal(9, "Greys"),4)
com_colours <- c(com_colours, com_colours_greys)
com_colours <- com_colours[sample(1:length(com_colours),12,replace=F)]
### This is just to check if you have commented tbe above out: :)
if(!exists("com_colours")) {
com_colours <- rep("black", 12)
}
provcomm_lvls <- levels(hum_m5_newdat_bord$Provcomm)
par(mfrow = c(3,4))
### Note the scales are important here - we need to set a scale that encompasses all the communes and the full
### dist_border range across all communes, so we need to do this overall:
ylo <- min(hum_m5_newdat_bord$pred.com)*0.9
yhi <- max(hum_m5_newdat_bord$pred.com)*1.1
xlo <- min(dat1[dat1$Provcomm %in% levels(hum_m5_newdat_bord$Provcomm),"dist_border"])
xhi <- max(dat1[dat1$Provcomm %in% levels(hum_m5_newdat_bord$Provcomm),"dist_border"])
### Iterate through the communes (levels in hum_m5_newdat_bord$Provcomm):
for(i in 1:length(provcomm_lvls)) {
### Pick commune i data from the predictions:
preddat_i <- hum_m5_newdat_bord[hum_m5_newdat_bord$Provcomm==provcomm_lvls[i],]
### Pick commune i data from observed data:
dat_i <- dat1[dat1$Provcomm==provcomm_lvls[i],]
## If this is the first plot, use plot(), otherwise lines() to add to an existing plot:
#if(i == 1) {
# Plot predicted ForPix as function of dist_border; as "line" type. Note this is where you set axis limits.
plot(preddat_i$dist_border,preddat_i$pred.com,
type = "l",
col = com_colours[i],
ylim = c(ylo,yhi), xlim = c(xlo,xhi),
xlab = "Distance to intl border (scaled & standardised)",
ylab = "Predicted forest pixels",
main = unique(preddat_i$Provcomm))
#} else {
lines(preddat_i$dist_border,preddat_i$pred.com, col = com_colours[i])
lines(preddat_i$dist_border,preddat_i$pred.glo, lty=2)
#}
## Add points for "observed" ForPix for commune i across all observed pop_den across communes.
points(dat_i$dist_border, dat_i$ForPix, pch = 21, bg = com_colours[i], col = com_colours[i])
}
#' These plots suggest the global model fits poorly for communes with higher forest cover, but fits better for communes with low forest cover, regardless of dist_border, which is much the same as previous models. The global model is better at predicting for communes with intercepts around the global mean, or below it.
#'
#' Now I will do the same plots but for a random subset of communes.
#'
#+ hum.m5 random commune predictions dist_border, echo=F, results=T, fig.width=8, fig.height=8, dpi=100
par(mfrow = c(3,3))
set.seed(123)
runs <- c(1:9)
for(i in 1:length(runs)){
# randomly sample communes
rand.com <- sample(dat1$Provcomm, 9, replace = FALSE)
rand.prov <- unlist(strsplit(rand.com, "_"))
rand.prov <- rand.prov[c(1,3,5,7,9,11,13,15,17)]
# define the range of pop_den to predict for, first. Min/max per commune:
dist_border_min <- tapply(dat1$dist_border, dat1$Provcomm, min)
dist_border_max <- tapply(dat1$dist_border, dat1$Provcomm, max)
# Min/max within your selection of communes:
dist_border_min <- min(dist_border_min[names(dist_border_min) %in% rand.com])
dist_border_max <- max(dist_border_max[names(dist_border_max) %in% rand.com])
# min not really different but max very different
# create new prediction grid for random communes with varying dist_border
hum_m5_newdat_bord_ran <- data.frame(Provcomm = rep(rand.com, each=100),
Province = rep(rand.prov, each=100),
dist_border = seq(dist_border_min, dist_border_max, length.out = 100),
year = mean(dat1$year))
hum_m5_newdat_bord_ran$Provcomm <- as.factor(hum_m5_newdat_bord_ran$Provcomm)
# add dist_provCap
hum_m5_newdat_bord_ran$dist_provCap <- dat1$dist_provCap[match(hum_m5_newdat_bord_ran$Provcomm, dat1$Provcomm)]
# add commune-specific areaKM offset
hum_m5_newdat_bord_ran$areaKM <- dat1$areaKM[match(hum_m5_newdat_bord_ran$Provcomm, dat1$Provcomm)]
# attach commune-specific predictions
hum_m5_newdat_bord_ran$pred.com <- as.vector(predict(hum.m5, type="response", newdata=hum_m5_newdat_bord_ran,
re.form=~(year|Province/Provcomm)))
# attach global predictions. need to alter areaKM below so that the global model has only the mean areakM rather than the commune-specific one. This is fine as pred.com is already done
hum_m5_newdat_bord_ran <- hum_m5_newdat_bord_ran %>% rename(areaKM_com = areaKM)
hum_m5_newdat_bord_ran$areaKM <- mean(dat1$areaKM)
hum_m5_newdat_bord_ran$pred.glo <- as.vector(predict(hum.m5,type="response",
newdata=hum_m5_newdat_bord_ran,re.form=NA))
require(RColorBrewer)
com_colours <- brewer.pal(11, "RdYlBu")
com_colours <- c(head(com_colours,4),tail(com_colours,4))
com_colours_greys <- tail(brewer.pal(9, "Greys"),4)
com_colours <- c(com_colours, com_colours_greys)
com_colours <- com_colours[sample(1:length(com_colours),12,replace=F)]
### This is just to check if you have commented tbe above out: :)
if(!exists("com_colours")) {
com_colours <- rep("black", 12)
}
provcomm_lvls <- levels(hum_m5_newdat_bord_ran$Provcomm)
### Note the scales are important here - we need to set a scale that encompasses all the communes and the full
### dist_border range across all communes, so we need to do this overall:
ylo <- min(hum_m5_newdat_bord_ran$pred.com)*0.9
yhi <- max(hum_m5_newdat_bord_ran$pred.com)*1.1
xlo <- min(dat1[dat1$Provcomm %in% levels(hum_m5_newdat_bord_ran$Provcomm),"dist_border"])
xhi <- max(dat1[dat1$Provcomm %in% levels(hum_m5_newdat_bord_ran$Provcomm),"dist_border"])
### Iterate through the communes (levels in hum_m5_newdat_bord$Provcomm):
for(i in 1:length(provcomm_lvls)) {
### Pick commune i data from the predictions:
preddat_i <- hum_m5_newdat_bord_ran[hum_m5_newdat_bord_ran$Provcomm==provcomm_lvls[i],]
### Pick commune i data from observed data:
dat_i <- dat1[dat1$Provcomm==provcomm_lvls[i],]
## If this is the first plot, use plot(), otherwise lines() to add to an existing plot:
if(i == 1) {
# Plot predicted ForPix as function of dist_border; as "line" type. Note this is where you set axis limits.
plot(preddat_i$dist_border,preddat_i$pred.com,
type = "l",
col = com_colours[i],
ylim = c(ylo,yhi), xlim = c(xlo,xhi),
xlab = "Distance to intl border (scaled & standardised)",
ylab = "Predicted forest pixels",
main = unique(preddat_i$Provcomm))
} else {
lines(preddat_i$dist_border,preddat_i$pred.com, col = com_colours[i])
lines(preddat_i$dist_border,preddat_i$pred.glo, lty=2)
}
## Add points for "observed" ForPix for commune i across all observed pop_den across communes.
points(dat_i$dist_border, dat_i$ForPix, pch = 21, bg = com_colours[i], col = com_colours[i])
}
}
#' The above plots I think show that again, the commune-specific models are fitting well, provided forest cover doesn't change.
#'
#' Below I will do the same predictions and plotting, but for varying dist_provCap. First, I will plot the 12 communes above, below, and around the mean intercept.
#'
#+ hum.m5 commune predictions dist_provCap, echo=F, results=T, fig.width=8, fig.height=8, dpi=100
### define the range of dist_provCap to predict for. Min/max per commune:
dist_provCap_min <- tapply(dat1$dist_provCap, dat1$Provcomm, min)
dist_provCap_max <- tapply(dat1$dist_provCap, dat1$Provcomm, max)
### Min/max within your selection of communes:
dist_provCap_min <- min(dist_provCap_min[names(dist_provCap_min) %in% coms])
dist_provCap_max <- max(dist_provCap_max[names(dist_provCap_max) %in% coms])
# create new prediction grid for specific communes with varying dist_border
hum_m5_newdat_provCap <- data.frame(Provcomm = rep(coms, each=100),
Province = rep(provs, each=100),
dist_provCap = seq(dist_provCap_min, dist_provCap_max, length.out = 100),
dist_border = dat1$dist_border[match(hum_m5_newdat_bord$Provcomm, dat1$Provcomm)],
year = mean(dat1$year))
# add commune-specific areaKM offset
hum_m5_newdat_provCap$areaKM <- dat1$areaKM[match(hum_m5_newdat_provCap$Provcomm, dat1$Provcomm)]
# re-order levels so they plot in the correct sets
hum_m5_newdat_provCap$Provcomm <- factor(hum_m5_newdat_provCap$Provcomm,
levels = c("Stung Treng_Kbal Romeas","Preah Vihear_Chhaeb Pir",
"Kampong Cham_Kampoan","Preah Vihear_Kuleaen Tboung",
"Kampot_Preaek Tnaot","Kampot_Kaoh Touch","Kampong Chhnang_Chieb",
"Kampong Cham_Pongro","Kampong Thom_Chaeung Daeung",
"Kracheh_Han Chey","Preah Vihear_Reaksmei","Siem Reap_Nokor Pheas"))
# attach commune-specific predictions
hum_m5_newdat_provCap$pred.com <- as.vector(predict(hum.m5, type="response", newdata=hum_m5_newdat_provCap,
re.form=~(year|Province/Provcomm)))
# attach global predictions. need to alter areaKM below so that the global model has only the mean areakM rather than the commune-specific one. This is fine as pred.com is already done
hum_m5_newdat_provCap <- hum_m5_newdat_provCap %>% rename(areaKM_com = areaKM)
hum_m5_newdat_provCap$areaKM <- mean(dat1$areaKM)
hum_m5_newdat_provCap$pred.glo <- as.vector(predict(hum.m5,type="response",newdata=hum_m5_newdat_provCap,re.form=NA))
### The following plot can either "overlay" the observed ForPix count against observed dist_provCap for the communes, or I can split by commune. comment out the if(i==1) statement and set par() if you want a grid
### Pick some colours using RColorBrewer using a completely overelaborate piece of crap code... Anyway this is just to
#try to help see the differences between communes more clearly in the observed points in particular (you can comment the
#following lines out if you want)
require(RColorBrewer)
com_colours <- brewer.pal(11, "RdYlBu")
com_colours <- c(head(com_colours,4),tail(com_colours,4))
com_colours_greys <- tail(brewer.pal(9, "Greys"),4)
com_colours <- c(com_colours, com_colours_greys)
com_colours <- com_colours[sample(1:length(com_colours),12,replace=F)]
### This is just to check if you have commented tbe above out: :)
if(!exists("com_colours")) {
com_colours <- rep("black", 12)
}
provcomm_lvls <- levels(hum_m5_newdat_provCap$Provcomm)
par(mfrow = c(3,4))
### Note the scales are important here - we need to set a scale that encompasses all the communes and the full
### dist_provCap range across all communes, so we need to do this overall:
ylo <- min(hum_m5_newdat_provCap$pred.com)*0.9
yhi <- max(hum_m5_newdat_provCap$pred.com)*1.1
xlo <- min(dat1[dat1$Provcomm %in% levels(hum_m5_newdat_provCap$Provcomm),"dist_border"])
xhi <- max(dat1[dat1$Provcomm %in% levels(hum_m5_newdat_provCap$Provcomm),"dist_border"])
### Iterate through the communes (levels in hum_m5_newdat_bord$Provcomm):
for(i in 1:length(provcomm_lvls)) {
### Pick commune i data from the predictions:
preddat_i <- hum_m5_newdat_provCap[hum_m5_newdat_provCap$Provcomm==provcomm_lvls[i],]
### Pick commune i data from observed data:
dat_i <- dat1[dat1$Provcomm==provcomm_lvls[i],]
## If this is the first plot, use plot(), otherwise lines() to add to an existing plot:
#if(i == 1) {
# Plot predicted ForPix as function of dist_border; as "line" type. Note this is where you set axis limits.
plot(preddat_i$dist_provCap,preddat_i$pred.com,
type = "l",
col = com_colours[i],
ylim = c(ylo,yhi), xlim = c(xlo,xhi),
xlab = "Distance to provincial capital (scaled & standardised)",
ylab = "Predicted forest pixels",
main = unique(preddat_i$Provcomm))
#} else {
lines(preddat_i$dist_provCap,preddat_i$pred.com, col = com_colours[i])
lines(preddat_i$dist_provCap,preddat_i$pred.glo, lty=2)
#}
## Add points for "observed" ForPix for commune i across all observed pop_den across communes.
points(dat_i$dist_provCap, dat_i$ForPix, pch = 21, bg = com_colours[i], col = com_colours[i])
}
#' The above plots paint a similar picture to the dist_border plots. Below I will predict and plot for a random subset of communes.
#'
#+ hum.m5 random commune predictions dist_provCap, echo=F, results=T, fig.width=8, fig.height=8, dpi=100
par(mfrow = c(3,3))
set.seed(123)
runs <- c(1:9)
for(i in 1:length(runs)){
# randomly sample communes
rand.com <- sample(dat1$Provcomm, 9, replace = FALSE)
rand.prov <- unlist(strsplit(rand.com, "_"))
rand.prov <- rand.prov[c(1,3,5,7,9,11,13,15,17)]
# define the range of pop_den to predict for, first. Min/max per commune:
dist_provCap_min <- tapply(dat1$dist_provCap, dat1$Provcomm, min)
dist_provCap_max <- tapply(dat1$dist_provCap, dat1$Provcomm, max)
# Min/max within your selection of communes:
dist_provCap_min <- min(dist_provCap_min[names(dist_provCap_min) %in% rand.com])
dist_provCap_max <- max(dist_provCap_max[names(dist_provCap_max) %in% rand.com])
# min not really different but max very different
# create new prediction grid for random communes with varying dist_border
hum_m5_newdat_provCap_ran <- data.frame(Provcomm = rep(rand.com, each=100),
Province = rep(rand.prov, each=100),
dist_provCap = seq(dist_provCap_min, dist_provCap_max, length.out = 100),
year = mean(dat1$year))
hum_m5_newdat_provCap_ran$Provcomm <- as.factor(hum_m5_newdat_provCap_ran$Provcomm)
# add dist_border
hum_m5_newdat_provCap_ran$dist_border <- dat1$dist_border[match(hum_m5_newdat_provCap_ran$Provcomm, dat1$Provcomm)]
# add commune-specific areaKM offset
hum_m5_newdat_provCap_ran$areaKM <- dat1$areaKM[match(hum_m5_newdat_provCap_ran$Provcomm, dat1$Provcomm)]
# attach commune-specific predictions
hum_m5_newdat_provCap_ran$pred.com <- as.vector(predict(hum.m5, type="response",
newdata=hum_m5_newdat_provCap_ran,
re.form=~(year|Province/Provcomm)))
# attach global predictions. need to alter areaKM below so that the global model has only the mean areakM rather than the commune-specific one. This is fine as pred.com is already done
hum_m5_newdat_provCap_ran <- hum_m5_newdat_provCap_ran %>% rename(areaKM_com = areaKM)
hum_m5_newdat_provCap_ran$areaKM <- mean(dat1$areaKM)
hum_m5_newdat_provCap_ran$pred.glo <- as.vector(predict(hum.m5,type="response",
newdata=hum_m5_newdat_provCap_ran,re.form=NA))
require(RColorBrewer)
com_colours <- brewer.pal(11, "RdYlBu")
com_colours <- c(head(com_colours,4),tail(com_colours,4))
com_colours_greys <- tail(brewer.pal(9, "Greys"),4)
com_colours <- c(com_colours, com_colours_greys)
com_colours <- com_colours[sample(1:length(com_colours),12,replace=F)]
### This is just to check if you have commented tbe above out: :)
if(!exists("com_colours")) {
com_colours <- rep("black", 12)
}
provcomm_lvls <- levels(hum_m5_newdat_provCap_ran$Provcomm)
### Note the scales are important here - we need to set a scale that encompasses all the communes and the full
### dist_border range across all communes, so we need to do this overall:
ylo <- min(hum_m5_newdat_provCap_ran$pred.com)*0.9
yhi <- max(hum_m5_newdat_provCap_ran$pred.com)*1.1
xlo <- min(dat1[dat1$Provcomm %in% levels(hum_m5_newdat_provCap_ran$Provcomm),"dist_provCap"])
xhi <- max(dat1[dat1$Provcomm %in% levels(hum_m5_newdat_provCap_ran$Provcomm),"dist_provCap"])
### Iterate through the communes (levels in hum_m5_newdat_bord$Provcomm):
for(i in 1:length(provcomm_lvls)) {
### Pick commune i data from the predictions:
preddat_i <- hum_m5_newdat_provCap_ran[hum_m5_newdat_provCap_ran$Provcomm==provcomm_lvls[i],]
### Pick commune i data from observed data:
dat_i <- dat1[dat1$Provcomm==provcomm_lvls[i],]
## If this is the first plot, use plot(), otherwise lines() to add to an existing plot:
if(i == 1) {
# Plot predicted ForPix as function of dist_provCap; as "line" type. Note this is where you set axis limits.
plot(preddat_i$dist_provCap,preddat_i$pred.com,
type = "l",
col = com_colours[i],
ylim = c(ylo,yhi), xlim = c(xlo,xhi),
xlab = "Distance to Provincial capital (scaled & standardised)",
ylab = "Predicted forest pixels",
main = unique(preddat_i$Provcomm))
} else {
lines(preddat_i$dist_provCap,preddat_i$pred.com, col = com_colours[i])
lines(preddat_i$dist_provCap,preddat_i$pred.glo, lty=2)
}
## Add points for "observed" ForPix for commune i across all observed pop_den across communes.
points(dat_i$dist_provCap, dat_i$ForPix, pch = 21, bg = com_colours[i], col = com_colours[i])
}
}
|
% Generated by roxygen2 (4.1.1): do not edit by hand
% Please edit documentation in R/plotOrd.R
\name{plotOrd}
\alias{plotOrd}
\title{Plot of either PCA or MDS coordinates for the distances of normalized or unnormalized counts.}
\usage{
plotOrd(obj, tran = TRUE, comp = 1:2, norm = TRUE, log = TRUE,
usePCA = TRUE, useDist = FALSE, distfun = stats::dist,
dist.method = "euclidian", n = NULL, ...)
}
\arguments{
\item{obj}{A MRexperiment object or count matrix.}
\item{tran}{Transpose the matrix.}
\item{comp}{Which components to display}
\item{norm}{Whether or not to normalize the counts - if MRexperiment object.}
\item{log}{Whether or not to log2 the counts - if MRexperiment object.}
\item{usePCA}{TRUE/FALSE whether to use PCA or MDS coordinates (TRUE is PCA).}
\item{useDist}{TRUE/FALSE whether to calculate distances.}
\item{distfun}{Distance function, default is stats::dist}
\item{dist.method}{If useDist==TRUE, what method to calculate distances.}
\item{n}{Number of features to make use of in calculating your distances.}
\item{...}{Additional plot arguments.}
}
\value{
coordinates
}
\description{
This function plots the PCA / MDS coordinates for the "n" features of interest. Potentially uncovering batch
effects or feature relationships.
}
\examples{
data(mouseData)
cl = pData(mouseData)[,3]
plotOrd(mouseData,tran=TRUE,useDist=TRUE,pch=21,bg=factor(cl),usePCA=FALSE)
}
\seealso{
\code{\link{cumNormMat}}
}
| /man/plotOrd.Rd | no_license | emcgi/metagenomeSeq-1 | R | false | false | 1,439 | rd | % Generated by roxygen2 (4.1.1): do not edit by hand
% Please edit documentation in R/plotOrd.R
\name{plotOrd}
\alias{plotOrd}
\title{Plot of either PCA or MDS coordinates for the distances of normalized or unnormalized counts.}
\usage{
plotOrd(obj, tran = TRUE, comp = 1:2, norm = TRUE, log = TRUE,
usePCA = TRUE, useDist = FALSE, distfun = stats::dist,
dist.method = "euclidian", n = NULL, ...)
}
\arguments{
\item{obj}{A MRexperiment object or count matrix.}
\item{tran}{Transpose the matrix.}
\item{comp}{Which components to display}
\item{norm}{Whether or not to normalize the counts - if MRexperiment object.}
\item{log}{Whether or not to log2 the counts - if MRexperiment object.}
\item{usePCA}{TRUE/FALSE whether to use PCA or MDS coordinates (TRUE is PCA).}
\item{useDist}{TRUE/FALSE whether to calculate distances.}
\item{distfun}{Distance function, default is stats::dist}
\item{dist.method}{If useDist==TRUE, what method to calculate distances.}
\item{n}{Number of features to make use of in calculating your distances.}
\item{...}{Additional plot arguments.}
}
\value{
coordinates
}
\description{
This function plots the PCA / MDS coordinates for the "n" features of interest. Potentially uncovering batch
effects or feature relationships.
}
\examples{
data(mouseData)
cl = pData(mouseData)[,3]
plotOrd(mouseData,tran=TRUE,useDist=TRUE,pch=21,bg=factor(cl),usePCA=FALSE)
}
\seealso{
\code{\link{cumNormMat}}
}
|
c DCNF-Autarky [version 0.0.1].
c Copyright (c) 2018-2019 Swansea University.
c
c Input Clause Count: 41652
c Performing E1-Autarky iteration.
c Remaining clauses count after E-Reduction: 41652
c
c Input Parameter (command line, file):
c input filename QBFLIB/Jordan-Kaiser/reduction-finding-full-set-params-k1c3n4/query44_query25_1344n.qdimacs
c output filename /tmp/dcnfAutarky.dimacs
c autarky level 1
c conformity level 0
c encoding type 2
c no.of var 5533
c no.of clauses 41652
c no.of taut cls 0
c
c Output Parameters:
c remaining no.of clauses 41652
c
c QBFLIB/Jordan-Kaiser/reduction-finding-full-set-params-k1c3n4/query44_query25_1344n.qdimacs 5533 41652 E1 [] 0 168 5365 41652 NONE
| /code/dcnf-ankit-optimized/Results/QBFLIB-2018/E1/Experiments/Jordan-Kaiser/reduction-finding-full-set-params-k1c3n4/query44_query25_1344n/query44_query25_1344n.R | no_license | arey0pushpa/dcnf-autarky | R | false | false | 720 | r | c DCNF-Autarky [version 0.0.1].
c Copyright (c) 2018-2019 Swansea University.
c
c Input Clause Count: 41652
c Performing E1-Autarky iteration.
c Remaining clauses count after E-Reduction: 41652
c
c Input Parameter (command line, file):
c input filename QBFLIB/Jordan-Kaiser/reduction-finding-full-set-params-k1c3n4/query44_query25_1344n.qdimacs
c output filename /tmp/dcnfAutarky.dimacs
c autarky level 1
c conformity level 0
c encoding type 2
c no.of var 5533
c no.of clauses 41652
c no.of taut cls 0
c
c Output Parameters:
c remaining no.of clauses 41652
c
c QBFLIB/Jordan-Kaiser/reduction-finding-full-set-params-k1c3n4/query44_query25_1344n.qdimacs 5533 41652 E1 [] 0 168 5365 41652 NONE
|
# The data from household_power_consumption.txt was inserted into the SQLite
# database to be easy to extract only the data we need. see transform_csv_to_sqlite.R
db <- "data/household_power_consumption.db"
library(RSQLite)
library(grDevices)
con <- dbConnect(dbDriver("SQLite"), dbname=db)
data <- dbGetQuery(con, "select * from household_power_consumption a where a.Date == '1/2/2007' OR a.Date == '2/2/2007';")
dbDisconnect(con)
# Generate the plot
png(filename = "plot1.png")
par(bg="transparent", mar=c(5, 4, 2, 2))
hist(data$Global_active_power, col="red", main="Global Active Power", axes=FALSE,
xlab="Global Active Power (kilowatts)", ylab="Frequency", xlim=c(0, 7))
axis(1, at=seq(0, 6, by=2))
axis(2, at=seq(0, 1200, by=200))
dev.off()
| /plot1.R | no_license | phaser/ExData_Plotting1 | R | false | false | 754 | r | # The data from household_power_consumption.txt was inserted into the SQLite
# database to be easy to extract only the data we need. see transform_csv_to_sqlite.R
db <- "data/household_power_consumption.db"
library(RSQLite)
library(grDevices)
con <- dbConnect(dbDriver("SQLite"), dbname=db)
data <- dbGetQuery(con, "select * from household_power_consumption a where a.Date == '1/2/2007' OR a.Date == '2/2/2007';")
dbDisconnect(con)
# Generate the plot
png(filename = "plot1.png")
par(bg="transparent", mar=c(5, 4, 2, 2))
hist(data$Global_active_power, col="red", main="Global Active Power", axes=FALSE,
xlab="Global Active Power (kilowatts)", ylab="Frequency", xlim=c(0, 7))
axis(1, at=seq(0, 6, by=2))
axis(2, at=seq(0, 1200, by=200))
dev.off()
|
\name{coefficientsplot2D}
\alias{coefficientsplot2D}
\title{2-Dimensionsl Graphical Summary Information Pertaining to the Coefficients of a PLS}
\description{Functions to extract 2D graphical coefficients information from \code{mvdalab} objects.}
\usage{
coefficientsplot2D(object, comps = c(1, 2))
}
\arguments{
\item{object}{ an \code{mvdareg} object. }
\item{comps}{ a vector of length 2 corresponding to the number of components to include. }
}
\details{
\code{coefficientsplot2D} is used to extract a graphical summary of the coefficients of a PLS model.
If \code{comp} is \code{missing} (or is \code{NULL}), a graphical summary for the 1st and 2nd components is returned.
}
\author{Nelson Lee Afanador (\email{nelson.afanador@mvdalab.com})}
\seealso{\code{\link{loadingsplot2D}}, \code{\link{weightsplot2D}}}
\examples{
data(Penta)
mod1 <- plsFit(log.RAI ~., scale = TRUE, data = Penta[, -1],
ncomp = 3, contr = "contr.none", method = "bidiagpls",
validation = "oob")
coefficientsplot2D(mod1, comp = c(1, 2))
} | /man/coefficientsplot2D.Rd | no_license | cwmiller21/mvdalab | R | false | false | 1,036 | rd | \name{coefficientsplot2D}
\alias{coefficientsplot2D}
\title{2-Dimensionsl Graphical Summary Information Pertaining to the Coefficients of a PLS}
\description{Functions to extract 2D graphical coefficients information from \code{mvdalab} objects.}
\usage{
coefficientsplot2D(object, comps = c(1, 2))
}
\arguments{
\item{object}{ an \code{mvdareg} object. }
\item{comps}{ a vector of length 2 corresponding to the number of components to include. }
}
\details{
\code{coefficientsplot2D} is used to extract a graphical summary of the coefficients of a PLS model.
If \code{comp} is \code{missing} (or is \code{NULL}), a graphical summary for the 1st and 2nd components is returned.
}
\author{Nelson Lee Afanador (\email{nelson.afanador@mvdalab.com})}
\seealso{\code{\link{loadingsplot2D}}, \code{\link{weightsplot2D}}}
\examples{
data(Penta)
mod1 <- plsFit(log.RAI ~., scale = TRUE, data = Penta[, -1],
ncomp = 3, contr = "contr.none", method = "bidiagpls",
validation = "oob")
coefficientsplot2D(mod1, comp = c(1, 2))
} |
#Import dataset (code below only works if file is in working directory)
med <- read.csv('MedicalData.csv')
#Confirm normality assumption
boxplot(med$BP~med$Age,main='Blood Pressure by Age Group',ylab='Blood Pressure (mmHg)')
boxplot(med$BP~med$Edema,main='Blood Pressure by Edema Status',ylab='Blood Pressure (mmHg)')
#Define "Edema" as a factor (categorical) variable
med$Edema <- as.factor(med$Edema)
#Confirm equal variance assumption
install.packages(car)
library(car)
leveneTest(med$BP~med$Age)
leveneTest(med$BP~med$Edema)
#Build Two-way ANOVA model with interaction and view results
my2aov <- aov(BP~Age*Edema, data=med, contrasts=list(Age=contr.sum, Edema=contr.sum))
Anova(my2aov, type=3)
#Calculate R-squared
summary.lm(my2aov)$adj.r.squared
#Pairwise comparisons with Tukey adjustment
TukeyHSD(my2aov)
| /sphinx/datascience/source/staging/SOS_MultiANOVA.R | permissive | oneoffcoder/books | R | false | false | 844 | r | #Import dataset (code below only works if file is in working directory)
med <- read.csv('MedicalData.csv')
#Confirm normality assumption
boxplot(med$BP~med$Age,main='Blood Pressure by Age Group',ylab='Blood Pressure (mmHg)')
boxplot(med$BP~med$Edema,main='Blood Pressure by Edema Status',ylab='Blood Pressure (mmHg)')
#Define "Edema" as a factor (categorical) variable
med$Edema <- as.factor(med$Edema)
#Confirm equal variance assumption
install.packages(car)
library(car)
leveneTest(med$BP~med$Age)
leveneTest(med$BP~med$Edema)
#Build Two-way ANOVA model with interaction and view results
my2aov <- aov(BP~Age*Edema, data=med, contrasts=list(Age=contr.sum, Edema=contr.sum))
Anova(my2aov, type=3)
#Calculate R-squared
summary.lm(my2aov)$adj.r.squared
#Pairwise comparisons with Tukey adjustment
TukeyHSD(my2aov)
|
library(utils)
library(R2HTML)
#setwd("C:/Users/Aaron/Documents/JH/Problem Sets for John/")
question.set <- data.frame(name = c("Question1","Question2"), number = c(20,20),source.file = c("generate_questions_1plot","generate_questions_5plot"))
dir.create("PracticeQuestions")
file.copy("printChoices.js","PracticeQuestions/printChoices.js")
setwd("PracticeQuestions")
for(q in 1:nrow(question.set)){
ticker<-1
question.name <- as.character(question.set$name[q])
q.file <- paste("../",paste(question.set[q,"source.file"],".r",sep=""),sep="")
n.q1 <- question.set[q,"number"]
for(i in 1:n.q1){
#Clean up to make sure there aren't any leftover true
#or false statements or questions
rm("question")
if(length(which(ls() == "q.output")) > 0){ rm("q.output")}
if(length(which(ls() == "q.table")) > 0){ rm("q.table")}
rm(list=grep("true.statement",ls(),value=TRUE))
rm(list=grep("true.reason",ls(),value=TRUE))
rm(list=grep("false.statement",ls(),value=TRUE))
rm(list=grep("false.reason",ls(),value=TRUE))
#create names for figures, javascript file, html file
v <- i
q.figure.name <- paste(question.name, "-QFigure-",v,
".png",sep="")
s.figure.name <- paste(question.name, "-SFigure-",v,
".png",sep="")
q.name <- paste(question.name,"-",v,".html",sep="")
js.name <- paste(question.name,"-",v,".js",sep="")
#run sweave on the template file
Sweave("../HTMLTemplate.Rnw",
driver = RweaveHTML)
#Combine all true statements into one vector
true.stats <- c()
for(i in grep("true.statement",ls(),value=TRUE)){
true.stats <- c(true.stats, get(i))
}
#Combine all true reasons into one vector
true.reas <- c()
for(i in grep("true.reason",ls(),value=TRUE)){
true.reas <- c(true.reas, get(i))
}
#Combine all false statements into one vector
false.stats <- c()
for(i in grep("false.statement",ls(),value=TRUE)){
false.stats <- c(false.stats, get(i))
}
#Combine all false reasons into one vector
false.reas <- c()
for(i in grep("false.reason",ls(),value=TRUE)){
false.reas <- c(false.reas, get(i))
}
#write true and false statements to the javascript file
cat("var trueStatements = new Array (","\n",file="javascript.js",
append=FALSE)
cat(paste("\"", true.stats, "\"",collapse=",",sep=""),"\n",
file="javascript.js",append=TRUE)
cat(");","\n",file="javascript.js",append=TRUE)
#
cat("var trueReasons = new Array (","\n",file="javascript.js",
append=TRUE)
cat(paste("\"", true.reas, "\"",collapse=",",sep=""),"\n",
file="javascript.js",append=TRUE)
cat(");","\n",file="javascript.js",append=TRUE)
#
cat("var falseStatements = new Array (","\n",file="javascript.js",
append=TRUE)
cat(paste("\"", false.stats, "\"",collapse=",",sep=""),"\n",
file="javascript.js",append=TRUE)
cat(")","\n",file="javascript.js",append=TRUE)
#
cat("var falseReasons = new Array (","\n",file="javascript.js",
append=TRUE)
cat(paste("\"", false.reas, "\"",collapse=",",sep=""),"\n",
file="javascript.js",append=TRUE)
cat(");","\n",file="javascript.js",append=TRUE)
#rename files
file.rename("FigureQuestion.png", q.figure.name)
file.rename("FigureSolution.png", s.figure.name)
file.rename("javascript.js", js.name)
file.rename("HTMLTemplate.html",
q.name)
}
}
setwd("../")
| /Aaron's General Workspace/outdated stuff/GenerateGame.r | no_license | Adamyazori/EDA-Project | R | false | false | 3,536 | r | library(utils)
library(R2HTML)
#setwd("C:/Users/Aaron/Documents/JH/Problem Sets for John/")
question.set <- data.frame(name = c("Question1","Question2"), number = c(20,20),source.file = c("generate_questions_1plot","generate_questions_5plot"))
dir.create("PracticeQuestions")
file.copy("printChoices.js","PracticeQuestions/printChoices.js")
setwd("PracticeQuestions")
for(q in 1:nrow(question.set)){
ticker<-1
question.name <- as.character(question.set$name[q])
q.file <- paste("../",paste(question.set[q,"source.file"],".r",sep=""),sep="")
n.q1 <- question.set[q,"number"]
for(i in 1:n.q1){
#Clean up to make sure there aren't any leftover true
#or false statements or questions
rm("question")
if(length(which(ls() == "q.output")) > 0){ rm("q.output")}
if(length(which(ls() == "q.table")) > 0){ rm("q.table")}
rm(list=grep("true.statement",ls(),value=TRUE))
rm(list=grep("true.reason",ls(),value=TRUE))
rm(list=grep("false.statement",ls(),value=TRUE))
rm(list=grep("false.reason",ls(),value=TRUE))
#create names for figures, javascript file, html file
v <- i
q.figure.name <- paste(question.name, "-QFigure-",v,
".png",sep="")
s.figure.name <- paste(question.name, "-SFigure-",v,
".png",sep="")
q.name <- paste(question.name,"-",v,".html",sep="")
js.name <- paste(question.name,"-",v,".js",sep="")
#run sweave on the template file
Sweave("../HTMLTemplate.Rnw",
driver = RweaveHTML)
#Combine all true statements into one vector
true.stats <- c()
for(i in grep("true.statement",ls(),value=TRUE)){
true.stats <- c(true.stats, get(i))
}
#Combine all true reasons into one vector
true.reas <- c()
for(i in grep("true.reason",ls(),value=TRUE)){
true.reas <- c(true.reas, get(i))
}
#Combine all false statements into one vector
false.stats <- c()
for(i in grep("false.statement",ls(),value=TRUE)){
false.stats <- c(false.stats, get(i))
}
#Combine all false reasons into one vector
false.reas <- c()
for(i in grep("false.reason",ls(),value=TRUE)){
false.reas <- c(false.reas, get(i))
}
#write true and false statements to the javascript file
cat("var trueStatements = new Array (","\n",file="javascript.js",
append=FALSE)
cat(paste("\"", true.stats, "\"",collapse=",",sep=""),"\n",
file="javascript.js",append=TRUE)
cat(");","\n",file="javascript.js",append=TRUE)
#
cat("var trueReasons = new Array (","\n",file="javascript.js",
append=TRUE)
cat(paste("\"", true.reas, "\"",collapse=",",sep=""),"\n",
file="javascript.js",append=TRUE)
cat(");","\n",file="javascript.js",append=TRUE)
#
cat("var falseStatements = new Array (","\n",file="javascript.js",
append=TRUE)
cat(paste("\"", false.stats, "\"",collapse=",",sep=""),"\n",
file="javascript.js",append=TRUE)
cat(")","\n",file="javascript.js",append=TRUE)
#
cat("var falseReasons = new Array (","\n",file="javascript.js",
append=TRUE)
cat(paste("\"", false.reas, "\"",collapse=",",sep=""),"\n",
file="javascript.js",append=TRUE)
cat(");","\n",file="javascript.js",append=TRUE)
#rename files
file.rename("FigureQuestion.png", q.figure.name)
file.rename("FigureSolution.png", s.figure.name)
file.rename("javascript.js", js.name)
file.rename("HTMLTemplate.html",
q.name)
}
}
setwd("../")
|
plot2 <- function() {
downloadedZipFile = "data.zip"
downloadFolder = "tmp"
# get path for tmp folder
pTmp <- function(fn) {
return (paste(downloadFolder, fn, sep = "/"))
}
# function to download the zip file from the given URL
unzipFile <- function(zipFileUrl) {
if (!file.exists(downloadFolder)) {
print("creating tmp folder and downloading the zip file.")
# create a tmp folder
dir.create(downloadFolder)
# download the file file into tmp folder
download.file(zipFileUrl, pTmp(downloadedZipFile), method = "curl")
# unzip the file
unzip(pTmp(downloadedZipFile), exdir=downloadFolder)
}
}
# function to delete tmp folder
deleteTmpFolder <- function() {
if (file.exists(downloadFolder)) {
print("deleting tmp folder")
unlink(downloadFolder, recursive = TRUE)
}
}
print("into plot2 > calling unzipFile")
# download the zip file from the given URL
unzipFile("https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip");
print("into plot2 > loading powerData")
# read the file content
powerData = read.table(
pTmp("household_power_consumption.txt"),
header=TRUE,
sep = ";",
na.strings = "?",
colClasses = c("character", "character", "numeric", "numeric", "numeric", "numeric", "numeric", "numeric", "numeric"))
#print(head(powerData))
# subset data for date between 2007-02-01 and 2007-02-02
subPowerData = powerData[powerData$Date %in% c("1/2/2007","2/2/2007") ,]
print(head(subPowerData))
# create a png file
png("plot2.png", width=480, height=480)
# plot chart using subPowerData data
plot(subPowerData$Global_active_power~as.POSIXct(paste(as.Date(subPowerData$Date, "%d/%m/%Y"), subPowerData$Time)),
xlab = "",
ylab = "Global Active Power (kilowatts)",
#main = "Global Active Power",
type="l")
dev.off()
# delete tmp folder
deleteTmpFolder()
} | /plot2.R | no_license | lpisapati/ExData_Plotting1 | R | false | false | 1,977 | r | plot2 <- function() {
downloadedZipFile = "data.zip"
downloadFolder = "tmp"
# get path for tmp folder
pTmp <- function(fn) {
return (paste(downloadFolder, fn, sep = "/"))
}
# function to download the zip file from the given URL
unzipFile <- function(zipFileUrl) {
if (!file.exists(downloadFolder)) {
print("creating tmp folder and downloading the zip file.")
# create a tmp folder
dir.create(downloadFolder)
# download the file file into tmp folder
download.file(zipFileUrl, pTmp(downloadedZipFile), method = "curl")
# unzip the file
unzip(pTmp(downloadedZipFile), exdir=downloadFolder)
}
}
# function to delete tmp folder
deleteTmpFolder <- function() {
if (file.exists(downloadFolder)) {
print("deleting tmp folder")
unlink(downloadFolder, recursive = TRUE)
}
}
print("into plot2 > calling unzipFile")
# download the zip file from the given URL
unzipFile("https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip");
print("into plot2 > loading powerData")
# read the file content
powerData = read.table(
pTmp("household_power_consumption.txt"),
header=TRUE,
sep = ";",
na.strings = "?",
colClasses = c("character", "character", "numeric", "numeric", "numeric", "numeric", "numeric", "numeric", "numeric"))
#print(head(powerData))
# subset data for date between 2007-02-01 and 2007-02-02
subPowerData = powerData[powerData$Date %in% c("1/2/2007","2/2/2007") ,]
print(head(subPowerData))
# create a png file
png("plot2.png", width=480, height=480)
# plot chart using subPowerData data
plot(subPowerData$Global_active_power~as.POSIXct(paste(as.Date(subPowerData$Date, "%d/%m/%Y"), subPowerData$Time)),
xlab = "",
ylab = "Global Active Power (kilowatts)",
#main = "Global Active Power",
type="l")
dev.off()
# delete tmp folder
deleteTmpFolder()
} |
testlist <- list(Beta = 0, CVLinf = 86341236051411296, FM = 1.53632495265886e-311, L50 = 0, L95 = 0, LenBins = c(2.0975686864138e+162, -2.68131210337361e-144, -1.11215735981244e+199, -4.48649879577108e+143, 1.6611802228813e+218, 900371.947279558, 1.07063092954708e+238, 2.88003257377011e-142, 1.29554141202795e-89, -1.87294312860528e-75, 3.04319010211815e+31, 191.463561345044, 1.58785813294449e+217, 1.90326589719466e-118, -3.75494418025505e-296, -2.63346094087863e+200, -5.15510035957975e+44, 2.59028521048192e+149, 1.60517426337473e+72, 1.74851929178852e+35, 1.32201752290843e-186, -1.29599553894715e-227, 3.20314220604904e+207, 584155875718587, 1.71017833066717e-283, -3.96505607598107e+51, 5.04440990041945e-163, -5.09127626480085e+268, 2.88137633290038e+175, 6.22724404181897e-256, 4.94195713773372e-295, 5.80049493946414e+160, -5612008.23597089, -2.68347267272935e-262, 1.28861520348431e-305, -5.05455182157157e-136, 4.44386438170367e+50, -2.07294901774837e+254, -3.56325845332496e+62, -1.38575911145229e-262, -1.19026551334786e-217, -3.54406233509625e-43, -4.15938611724176e-209, -3.06799941292011e-106, 1.78044357763692e+244, -1.24657398993838e+190, 1.14089212334828e-90, 136766.715673668, -1.47333345730049e-67, -2.92763930406321e+21 ), LenMids = c(-1.121210344879e+131, -1.121210344879e+131, NaN), Linf = 2.81991272491703e-308, MK = -2.08633459786369e-239, Ml = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), Prob = structure(c(4.48157192325537e-103, 2.43305969276274e+59, 6.5730975202806e-96, 2.03987918888949e-104, 4.61871336464985e-39, 1.10811931066926e+139), .Dim = c(1L, 6L)), SL50 = 9.97941197291525e-316, SL95 = 2.12248160522076e-314, nage = 682962941L, nlen = 1623851345L, rLens = c(4.74956174024781e+199, -7.42049538387034e+278, -5.82966399158032e-71, -6.07988133887702e-34, 4.62037926128924e-295, -8.48833146280612e+43, 2.71954993859316e-126 ))
result <- do.call(DLMtool::LBSPRgen,testlist)
str(result) | /DLMtool/inst/testfiles/LBSPRgen/AFL_LBSPRgen/LBSPRgen_valgrind_files/1615833634-test.R | no_license | akhikolla/updatedatatype-list2 | R | false | false | 2,048 | r | testlist <- list(Beta = 0, CVLinf = 86341236051411296, FM = 1.53632495265886e-311, L50 = 0, L95 = 0, LenBins = c(2.0975686864138e+162, -2.68131210337361e-144, -1.11215735981244e+199, -4.48649879577108e+143, 1.6611802228813e+218, 900371.947279558, 1.07063092954708e+238, 2.88003257377011e-142, 1.29554141202795e-89, -1.87294312860528e-75, 3.04319010211815e+31, 191.463561345044, 1.58785813294449e+217, 1.90326589719466e-118, -3.75494418025505e-296, -2.63346094087863e+200, -5.15510035957975e+44, 2.59028521048192e+149, 1.60517426337473e+72, 1.74851929178852e+35, 1.32201752290843e-186, -1.29599553894715e-227, 3.20314220604904e+207, 584155875718587, 1.71017833066717e-283, -3.96505607598107e+51, 5.04440990041945e-163, -5.09127626480085e+268, 2.88137633290038e+175, 6.22724404181897e-256, 4.94195713773372e-295, 5.80049493946414e+160, -5612008.23597089, -2.68347267272935e-262, 1.28861520348431e-305, -5.05455182157157e-136, 4.44386438170367e+50, -2.07294901774837e+254, -3.56325845332496e+62, -1.38575911145229e-262, -1.19026551334786e-217, -3.54406233509625e-43, -4.15938611724176e-209, -3.06799941292011e-106, 1.78044357763692e+244, -1.24657398993838e+190, 1.14089212334828e-90, 136766.715673668, -1.47333345730049e-67, -2.92763930406321e+21 ), LenMids = c(-1.121210344879e+131, -1.121210344879e+131, NaN), Linf = 2.81991272491703e-308, MK = -2.08633459786369e-239, Ml = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), Prob = structure(c(4.48157192325537e-103, 2.43305969276274e+59, 6.5730975202806e-96, 2.03987918888949e-104, 4.61871336464985e-39, 1.10811931066926e+139), .Dim = c(1L, 6L)), SL50 = 9.97941197291525e-316, SL95 = 2.12248160522076e-314, nage = 682962941L, nlen = 1623851345L, rLens = c(4.74956174024781e+199, -7.42049538387034e+278, -5.82966399158032e-71, -6.07988133887702e-34, 4.62037926128924e-295, -8.48833146280612e+43, 2.71954993859316e-126 ))
result <- do.call(DLMtool::LBSPRgen,testlist)
str(result) |
p1data <- read.table('household_power_consumption.txt',sep = ';',col.names = name,colClasses = rep('character',9),skip = 1)
p1data$Date = as.Date(p1data$Date,'%d/%m/%Y')
ind <- which(p1data$Date >=" 2007-02-01" & p1data$Date <="2007-02-02")
p1 <- p1data[ind,]
p1$Global_active_power <- as.numeric(p1$Global_active_power)
p1$Date <- strptime(paste(p1$Date, p1$Time), format = "%Y-%m-%d %H:%M:%S")
names(p1)[1]="Time"
png(file = "./plot2.png", width = 480, height = 480, units = "px")
plot(p1$Time,p1$Global_active_power,type = 'l',xlab = '',ylab = 'Global Active Power')
dev.off() | /plot2.R | no_license | bzvew/ExData_Plotting1 | R | false | false | 581 | r | p1data <- read.table('household_power_consumption.txt',sep = ';',col.names = name,colClasses = rep('character',9),skip = 1)
p1data$Date = as.Date(p1data$Date,'%d/%m/%Y')
ind <- which(p1data$Date >=" 2007-02-01" & p1data$Date <="2007-02-02")
p1 <- p1data[ind,]
p1$Global_active_power <- as.numeric(p1$Global_active_power)
p1$Date <- strptime(paste(p1$Date, p1$Time), format = "%Y-%m-%d %H:%M:%S")
names(p1)[1]="Time"
png(file = "./plot2.png", width = 480, height = 480, units = "px")
plot(p1$Time,p1$Global_active_power,type = 'l',xlab = '',ylab = 'Global Active Power')
dev.off() |
## Script to generate plot 2 of course project 1
## Exploratory Data Analysis
##
##Importing the dataset
fileUrl <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip"
download.file(fileUrl,destfile="./power_consumption.zip",method="curl")
unzip("power_consumption.zip")
# Reading dataset
power_c <- read.csv("household_power_consumption.txt")
#Initializing Tidyr Library
library(tidyr)
# Split columns in dataset
power_c2 <- separate(power_c, 'Date.Time.Global_active_power.Global_reactive_power.Voltage.Global_intensity.Sub_metering_1.Sub_metering_2.Sub_metering_3', paste("var", 1:9, sep = "_"), sep = ";", extra = "drop")
# Rename columns in dataset
colnames(power_c2) <- c("Date", "Time", "Global_active_power", "Global_reactive_power", "Voltage", "Global_intensity", "Sub_metering_1", "Sub_metering_2", "Sub_metering_3")
# subsetting by specific dates
power_cf1 <- subset(power_c2, grepl("^1/2/2007", power_c2$Date))
power_cf2 <- subset(power_c2, grepl("^2/2/2007", power_c2$Date))
power_cf <- rbind(power_cf1, power_cf2)
# Specifying the types of variables
#power_cf$Date <- as.Date(power_cf$Date)
#power_cf$Time <- strptime(power_cf$Time, "%hh:%mm:%ss")
power_cf$Global_active_power <- as.numeric(power_cf$Global_active_power)
power_cf$Global_reactive_power <- as.numeric(power_cf$Global_reactive_power)
power_cf$Voltage <- as.numeric(power_cf$Voltage)
power_cf$Global_intensity <- as.numeric(power_cf$Global_intensity)
power_cf$Sub_metering_1 <- as.numeric(power_cf$Sub_metering_1)
power_cf$Sub_metering_2 <- as.numeric(power_cf$Sub_metering_2)
power_cf$Sub_metering_2 <- as.numeric(power_cf$Sub_metering_2)
power_cf$Sub_metering_3 <- as.numeric(power_cf$Sub_metering_3)
# Making the plot
# font size
par(cex.main = 0.85) # title
par(cex.lab = 0.65) # labels x,y
par(cex.axis = 0.75) # axis
# Setting my R for English
Sys.setlocale("LC_ALL", 'en_US.UTF-8')
# Using lubridate to work with Date and Time
library(lubridate)
dt <- dmy_hms(paste(power_cf$Date, power_cf$Time))
plot(dt, power_cf$Global_active_power, ylab = "Global Active Power (kilowatts)", xlab = "", type='l')
# Saving the plot in .png format
dev.copy(png, file = "plot2.png", width = 480, height = 480)
dev.off()
## the end | /plot2.R | no_license | leonardo01e/ead_cp1 | R | false | false | 2,250 | r | ## Script to generate plot 2 of course project 1
## Exploratory Data Analysis
##
##Importing the dataset
fileUrl <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip"
download.file(fileUrl,destfile="./power_consumption.zip",method="curl")
unzip("power_consumption.zip")
# Reading dataset
power_c <- read.csv("household_power_consumption.txt")
#Initializing Tidyr Library
library(tidyr)
# Split columns in dataset
power_c2 <- separate(power_c, 'Date.Time.Global_active_power.Global_reactive_power.Voltage.Global_intensity.Sub_metering_1.Sub_metering_2.Sub_metering_3', paste("var", 1:9, sep = "_"), sep = ";", extra = "drop")
# Rename columns in dataset
colnames(power_c2) <- c("Date", "Time", "Global_active_power", "Global_reactive_power", "Voltage", "Global_intensity", "Sub_metering_1", "Sub_metering_2", "Sub_metering_3")
# subsetting by specific dates
power_cf1 <- subset(power_c2, grepl("^1/2/2007", power_c2$Date))
power_cf2 <- subset(power_c2, grepl("^2/2/2007", power_c2$Date))
power_cf <- rbind(power_cf1, power_cf2)
# Specifying the types of variables
#power_cf$Date <- as.Date(power_cf$Date)
#power_cf$Time <- strptime(power_cf$Time, "%hh:%mm:%ss")
power_cf$Global_active_power <- as.numeric(power_cf$Global_active_power)
power_cf$Global_reactive_power <- as.numeric(power_cf$Global_reactive_power)
power_cf$Voltage <- as.numeric(power_cf$Voltage)
power_cf$Global_intensity <- as.numeric(power_cf$Global_intensity)
power_cf$Sub_metering_1 <- as.numeric(power_cf$Sub_metering_1)
power_cf$Sub_metering_2 <- as.numeric(power_cf$Sub_metering_2)
power_cf$Sub_metering_2 <- as.numeric(power_cf$Sub_metering_2)
power_cf$Sub_metering_3 <- as.numeric(power_cf$Sub_metering_3)
# Making the plot
# font size
par(cex.main = 0.85) # title
par(cex.lab = 0.65) # labels x,y
par(cex.axis = 0.75) # axis
# Setting my R for English
Sys.setlocale("LC_ALL", 'en_US.UTF-8')
# Using lubridate to work with Date and Time
library(lubridate)
dt <- dmy_hms(paste(power_cf$Date, power_cf$Time))
plot(dt, power_cf$Global_active_power, ylab = "Global Active Power (kilowatts)", xlab = "", type='l')
# Saving the plot in .png format
dev.copy(png, file = "plot2.png", width = 480, height = 480)
dev.off()
## the end |
BiCopSelect <- function(u1, u2, familyset = NA, selectioncrit = "AIC", indeptest = FALSE, level = 0.05, weights = NA, rotations = TRUE) {
## sanity checks
if (is.null(u1) == TRUE || is.null(u2) == TRUE)
stop("u1 and/or u2 are not set or have length zero.")
if (length(u1) != length(u2))
stop("Lengths of 'u1' and 'u2' do not match.")
if (length(u1) < 2)
stop("Number of observations has to be at least 2.")
if (any(u1 > 1) || any(u1 < 0))
stop("Data has to be in the interval [0,1].")
if (any(u2 > 1) || any(u2 < 0))
stop("Data has to be in the interval [0,1].")
if (!is.na(familyset[1]))
for (i in 1:length(familyset)) {
if (!(familyset[i] %in% c(0:10, 13, 14, 16:20,
23, 24, 26:30,
33, 34, 36, 37, 38, 39, 40,
104, 114, 124, 134,
204, 214, 224, 234)))
stop("Copula family not implemented.")
}
if (selectioncrit != "AIC" && selectioncrit != "BIC")
stop("Selection criterion not implemented.")
if (level < 0 & level > 1)
stop("Significance level has to be between 0 and 1.")
## prepare objects
out <- list()
data1 <- u1
data2 <- u2
## adjust familyset if rotations = TRUE
if (rotations)
familyset <- with_rotations(familyset)
if (!is.na(familyset[1]) & any(familyset == 0)) {
# select independence if allowed
out$p.value.indeptest <- NA
out$family <- 0
out$par <- c(0, 0)
} else {
if (!is.na(familyset[1]) && (!any(c(1, 2, 5, 23, 24, 26:30, 33, 34, 36:40, 104, 114, 204, 214) %in% familyset) || !any(c(1:10, 13, 14, 16:20, 124, 134, 224, 234) %in% familyset)))
stop("'familyset' has to include at least one bivariate copula family for positive and one for negative dependence.")
if (is.na(familyset[1]))
familyset <- c(1:10, 13, 14, 16:20, 23, 24, 26:30, 33, 34, 36:40, 104, 114, 124, 134, 204, 214, 224, 234)
# calculate empirical kendall's tau
emp_tau <- fasttau(data1, data2, weights)
## perform independence test (if asked for)
if (indeptest == TRUE) {
out$p.value.indeptest <- BiCopIndTest(data1, data2)$p.value
} else {
out$p.value.indeptest <- NA
}
if (!is.na(out$p.value.indeptest) & out$p.value.indeptest >= level) {
# select independence copula, if not rejected
out$family <- 0
out$par <- c(0, 0)
} else {
## initial values for parameter optimization
start <- list()
start[[1]] <- sin(pi * emp_tau/2)
start[[2]] <- c(sin(emp_tau * pi/2), 10)
start[[3]] <- start[[13]] <- 2 * abs(emp_tau)/(1 - abs(emp_tau))
start[[4]] <- start[[14]] <- 1/(1 - abs(emp_tau))
if (5 %in% familyset)
start[[5]] <- Frank.itau.JJ(emp_tau) else start[[5]] <- 0
if (any(c(6, 16) %in% familyset))
start[[6]] <- start[[16]] <- Joe.itau.JJ(abs(emp_tau)) else start[[6]] <- start[[16]] <- 0
start[[7]] <- start[[17]] <- c(0.5, 1.5)
start[[8]] <- start[[18]] <- c(1.5, 1.5)
start[[9]] <- start[[19]] <- c(1.5, 0.5)
start[[10]] <- start[[20]] <- c(1.5, 0.5)
start[[23]] <- start[[33]] <- -2 * abs(emp_tau)/(1 - abs(emp_tau))
start[[24]] <- start[[34]] <- -1/(1 - abs(emp_tau))
if (any(c(26, 36) %in% familyset))
start[[26]] <- start[[36]] <- -Joe.itau.JJ(abs(emp_tau)) else start[[26]] <- start[[36]] <- 0
start[[27]] <- start[[37]] <- c(-0.5, -1.5)
start[[28]] <- start[[38]] <- c(-1.5, -1.5)
start[[29]] <- start[[39]] <- c(-1.5, -0.5)
start[[30]] <- start[[40]] <- c(-1.5, -0.5)
# start[[41]] = start[[51]] = ipsA.tau2cpar(emp_tau) start[[61]] = start[[71]] =
# -ipsA.tau2cpar(emp_tau)
delta <- min(abs(emp_tau) + 0.1, 0.999)
theta1 <- 1 + 6 * abs(emp_tau)
start[[104]] <- start[[204]] <- start[[114]] <- start[[214]] <- c(theta1, delta)
start[[124]] <- start[[224]] <- start[[134]] <- start[[234]] <- c(-theta1, delta)
## find families for which estimation is required (only families that allow for
## the empirical kendall's tau)
if (emp_tau < 0) {
todo <- c(1, 2, 5, 23, 24, 26:30, 33, 34, 36:40, 124, 134, 224, 234)
} else {
todo <- c(1:10, 13, 14, 16:20, 104, 114, 204, 214)
}
todo <- todo[which(todo %in% familyset)]
## estimate parameters for each of the families (in 'todo')
optiout <- list()
if (any(todo == 2)) {
optiout[[2]] <- suppressWarnings(BiCopEst(data1,
data2,
family = 2,
max.df = 30,
weights = weights))
optiout[[2]]$par <- c(optiout[[2]]$par, optiout[[2]]$par2)
if (optiout[[2]]$par[2] >= 30) {
todo[todo == 2] <- 1
todo <- unique(todo)
optiout[[2]] <- list()
}
}
if (any(todo == 7)) {
optiout[[7]] <- MLE_intern(cbind(data1, data2),
start[[7]],
7,
weights = weights)
if (optiout[[7]]$par[1] <= 0.1 | optiout[[7]]$par[2] <= 1.1) {
if (optiout[[7]]$par[1] <= 0.1) {
todo[todo == 7] <- 4
todo <- unique(todo)
} else if (optiout[[7]]$par[2] <= 1.1) {
todo[todo == 7] <- 3
todo <- unique(todo)
}
optiout[[7]] <- list()
}
}
if (any(todo == 8)) {
optiout[[8]] <- MLE_intern(cbind(data1, data2),
start[[8]],
8,
weights = weights)
if (optiout[[8]]$par[1] <= 1.1 | optiout[[8]]$par[2] <= 1.1) {
if (optiout[[8]]$par[1] <= 1.1) {
todo[todo == 8] <- 4
todo <- unique(todo)
} else if (optiout[[8]]$par[2] <= 1.1) {
todo[todo == 8] <- 6
todo <- unique(todo)
}
optiout[[8]] <- list()
}
}
if (any(todo == 9)) {
optiout[[9]] <- MLE_intern(cbind(data1, data2),
start[[9]],
9,
weights = weights)
if (optiout[[9]]$par[1] <= 1.1 | optiout[[9]]$par[2] <= 0.1) {
if (optiout[[9]]$par[1] <= 1.1) {
todo[todo == 9] <- 3
todo <- unique(todo)
} else if (optiout[[9]]$par[2] <= 0.1) {
todo[todo == 9] <- 6
todo <- unique(todo)
}
optiout[[9]] <- list()
}
}
if (any(todo == 10)) {
optiout[[10]] <- MLE_intern(cbind(data1, data2),
start[[10]],
10,
weights = weights)
if (optiout[[10]]$par[2] >= 0.99) {
todo[todo == 10] <- 6
todo <- unique(todo)
optiout[[10]] <- list()
}
}
if (any(todo == 17)) {
optiout[[17]] <- MLE_intern(cbind(data1, data2),
start[[17]],
17,
weights = weights)
if (optiout[[17]]$par[1] <= 0.1 | optiout[[17]]$par[2] <= 1.1) {
if (optiout[[17]]$par[1] <= 0.1) {
todo[todo == 17] <- 14
todo <- unique(todo)
} else if (optiout[[17]]$par[2] <= 1.1) {
todo[todo == 17] <- 13
todo <- unique(todo)
}
optiout[[17]] <- list()
}
}
if (any(todo == 18)) {
optiout[[18]] <- MLE_intern(cbind(data1, data2),
start[[18]],
18,
weights = weights)
if (optiout[[18]]$par[1] <= 1.1 | optiout[[18]]$par[2] <= 1.1) {
if (optiout[[18]]$par[1] <= 1.1) {
todo[todo == 18] <- 14
todo <- unique(todo)
} else if (optiout[[18]]$par[2] <= 1.1) {
todo[todo == 18] <- 16
todo <- unique(todo)
}
optiout[[18]] <- list()
}
}
if (any(todo == 19)) {
optiout[[19]] <- MLE_intern(cbind(data1, data2),
start[[19]],
19,
weights = weights)
if (optiout[[19]]$par[1] <= 1.1 | optiout[[19]]$par[2] <= 0.1) {
if (optiout[[19]]$par[1] <= 1.1) {
todo[todo == 19] <- 13
todo <- unique(todo)
} else if (optiout[[19]]$par[2] <= 0.1) {
todo[todo == 19] <- 16
todo <- unique(todo)
}
optiout[[19]] <- list()
}
}
if (any(todo == 20)) {
optiout[[20]] <- MLE_intern(cbind(data1, data2),
start[[20]],
20,
weights = weights)
if (optiout[[20]]$par[2] >= 0.99) {
todo[todo == 20] <- 16
todo <- unique(todo)
optiout[[20]] <- list()
}
}
if (any(todo == 27)) {
optiout[[27]] <- MLE_intern(cbind(data1, data2),
start[[27]],
27,
weights = weights)
if (optiout[[27]]$par[1] >= -0.1 | optiout[[27]]$par[2] >= -1.1) {
if (optiout[[27]]$par[1] >= -0.1) {
todo[todo == 27] <- 24
todo <- unique(todo)
} else if (optiout[[27]]$par[2] >= -1.1) {
todo[todo == 27] <- 23
todo <- unique(todo)
}
optiout[[27]] <- list()
}
}
if (any(todo == 28)) {
optiout[[28]] <- MLE_intern(cbind(data1, data2),
start[[28]],
28,
weights = weights)
if (optiout[[28]]$par[1] >= -1.1 | optiout[[28]]$par[2] >= -1.1) {
if (optiout[[28]]$par[1] >= -1.1) {
todo[todo == 28] <- 24
todo <- unique(todo)
} else if (optiout[[28]]$par[2] >= -1.1) {
todo[todo == 28] <- 26
todo <- unique(todo)
}
optiout[[28]] <- list()
}
}
if (any(todo == 29)) {
optiout[[29]] <- MLE_intern(cbind(data1, data2),
start[[29]],
29,
weights = weights)
if (optiout[[29]]$par[1] >= -1.1 | optiout[[29]]$par[2] >= -0.1) {
if (optiout[[29]]$par[1] >= -1.1) {
todo[todo == 29] <- 23
todo <- unique(todo)
} else if (optiout[[29]]$par[2] >= -0.1) {
todo[todo == 29] <- 26
todo <- unique(todo)
}
optiout[[29]] <- list()
}
}
if (any(todo == 30)) {
optiout[[30]] <- MLE_intern(cbind(data1, data2),
start[[30]],
30,
weights = weights)
if (optiout[[30]]$par[2] <= -0.99) {
todo[todo == 30] <- 26
todo <- unique(todo)
optiout[[30]] <- list()
}
}
if (any(todo == 37)) {
optiout[[37]] <- MLE_intern(cbind(data1, data2),
start[[37]],
37,
weights = weights)
if (optiout[[37]]$par[1] >= -0.1 | optiout[[37]]$par[2] >= -1.1) {
if (optiout[[37]]$par[1] >= -0.1) {
todo[todo == 37] <- 34
todo <- unique(todo)
} else if (optiout[[37]]$par[2] >= -1.1) {
todo[todo == 37] <- 33
todo <- unique(todo)
}
optiout[[37]] <- list()
}
}
if (any(todo == 38)) {
optiout[[38]] <- MLE_intern(cbind(data1, data2),
start[[38]],
38,
weights = weights)
if (optiout[[38]]$par[1] >= -1.1 | optiout[[38]]$par[2] >= -1.1) {
if (optiout[[38]]$par[1] >= -1.1) {
todo[todo == 38] <- 34
todo <- unique(todo)
} else if (optiout[[38]]$par[2] >= -1.1) {
todo[todo == 38] <- 36
todo <- unique(todo)
}
optiout[[38]] <- list()
}
}
if (any(todo == 39)) {
optiout[[39]] <- MLE_intern(cbind(data1, data2),
start[[39]],
39,
weights = weights)
if (optiout[[39]]$par[1] >= -1.1 | optiout[[39]]$par[2] >= -0.1) {
if (optiout[[39]]$par[1] >= -1.1) {
todo[todo == 39] <- 33
todo <- unique(todo)
} else if (optiout[[39]]$par[2] >= -0.1) {
todo[todo == 39] <- 36
todo <- unique(todo)
}
optiout[[39]] <- list()
}
}
if (any(todo == 40)) {
optiout[[40]] <- MLE_intern(cbind(data1, data2),
start[[40]],
40,
weights = weights)
if (optiout[[40]]$par[2] <= -0.99) {
todo[todo == 40] <- 36
todo <- unique(todo)
optiout[[40]] <- list()
}
}
for (i in todo[!(todo %in% c(2, 7:10, 17:20, 27:30, 37:40, 104, 114, 124, 134, 204, 214, 224, 234))]) {
optiout[[i]] <- MLE_intern(cbind(data1, data2),
start[[i]],
i,
weights = weights)
}
for (i in todo[(todo %in% c(104, 114, 124, 134, 204, 214, 224, 234))]) {
optiout[[i]] <- MLE_intern_Tawn(cbind(data1, data2),
start[[i]],
i)
}
## select the best model
if (selectioncrit == "AIC") {
AICs <- rep(Inf, max(todo))
for (i in todo) {
if (i %in% c(2, 7:10, 17:20, 27:30, 37:40, 104, 114, 124, 134, 204, 214, 224, 234)) {
if (any(is.na(weights))) {
ll <- sum(log(BiCopPDF(data1,
data2,
i,
optiout[[i]]$par[1],
optiout[[i]]$par[2])))
} else {
ll <- sum(log(BiCopPDF(data1,
data2,
i,
optiout[[i]]$par[1],
optiout[[i]]$par[2])) %*% weights)
}
AICs[i] <- -2 * ll + 4
} else {
if (any(is.na(weights))) {
ll <- sum(log(BiCopPDF(data1,
data2,
i,
optiout[[i]]$par)))
} else {
ll <- sum(log(BiCopPDF(data1,
data2,
i,
optiout[[i]]$par)) %*% weights)
}
AICs[i] <- -2 * ll + 2
}
}
out$family <- todo[which.min(AICs[todo])]
} else {
if (selectioncrit == "BIC") {
BICs <- rep(Inf, max(todo))
for (i in todo) {
if (i %in% c(2, 7:10, 17:20, 27:30, 37:40, 104, 114, 124, 134, 204, 214, 224, 234)) {
if (any(is.na(weights))) {
ll <- sum(log(BiCopPDF(data1,
data2,
i,
optiout[[i]]$par[1],
optiout[[i]]$par[2])))
} else {
ll <- sum(log(BiCopPDF(data1,
data2,
i,
optiout[[i]]$par[1],
optiout[[i]]$par[2])) %*% weights)
}
BICs[i] <- -2 * ll + 2 * log(length(data1))
} else {
if (any(is.na(weights))) {
ll <- sum(log(BiCopPDF(data1,
data2,
i,
optiout[[i]]$par)))
} else {
ll <- sum(log(BiCopPDF(data1,
data2,
i,
optiout[[i]]$par)) %*% weights)
}
BICs[i] <- -2 * ll + log(length(data1))
}
}
out$family <- todo[which.min(BICs[todo])]
}
}
out$par <- optiout[[out$family]]$par
if (!(out$family %in% c(2, 7:10, 17:20, 27:30, 37:40, 104, 114, 124, 134, 204, 214, 224, 234)))
out$par[2] <- 0
}
}
## store and return results
out$par2 <- out$par[2]
out$par <- out$par[1]
class(out) <- "BiCop"
out
}
##### ----------------------------------------------------------------------
## function for augmenting a familyset with rotations
with_rotations <- function(nums) {
unique(unlist(lapply(nums, get_rotations)))
}
get_rotations <- function(i) {
# no roations for independence, gaussian, student and frank copulas
out <- i
## rotations for other families
if(i %in% c(3, 13, 23, 33)) out <- c(3, 13, 23, 33)
if(i %in% c(4, 14, 24, 34)) out <- c(4, 14, 24, 34)
if(i %in% c(6, 16, 26, 36)) out <- c(6, 16, 26, 36)
if(i %in% c(7, 17, 27, 37)) out <- c(7, 17, 27, 37)
if(i %in% c(8, 18, 28, 38)) out <- c(8, 18, 28, 38)
if(i %in% c(9, 19, 29, 39)) out <- c(9, 19, 29, 39)
if(i %in% c(10, 20, 30, 40)) out <- c(10, 20, 30, 40)
if(i %in% c(104, 114, 124, 134)) out <- c(104, 114, 124, 134)
if(i %in% c(204, 214, 224, 234)) out <- c(204, 214, 224, 234)
out
}
| /VineCopula/R/BiCopSelect.r | no_license | ingted/R-Examples | R | false | false | 22,723 | r | BiCopSelect <- function(u1, u2, familyset = NA, selectioncrit = "AIC", indeptest = FALSE, level = 0.05, weights = NA, rotations = TRUE) {
## sanity checks
if (is.null(u1) == TRUE || is.null(u2) == TRUE)
stop("u1 and/or u2 are not set or have length zero.")
if (length(u1) != length(u2))
stop("Lengths of 'u1' and 'u2' do not match.")
if (length(u1) < 2)
stop("Number of observations has to be at least 2.")
if (any(u1 > 1) || any(u1 < 0))
stop("Data has to be in the interval [0,1].")
if (any(u2 > 1) || any(u2 < 0))
stop("Data has to be in the interval [0,1].")
if (!is.na(familyset[1]))
for (i in 1:length(familyset)) {
if (!(familyset[i] %in% c(0:10, 13, 14, 16:20,
23, 24, 26:30,
33, 34, 36, 37, 38, 39, 40,
104, 114, 124, 134,
204, 214, 224, 234)))
stop("Copula family not implemented.")
}
if (selectioncrit != "AIC" && selectioncrit != "BIC")
stop("Selection criterion not implemented.")
if (level < 0 & level > 1)
stop("Significance level has to be between 0 and 1.")
## prepare objects
out <- list()
data1 <- u1
data2 <- u2
## adjust familyset if rotations = TRUE
if (rotations)
familyset <- with_rotations(familyset)
if (!is.na(familyset[1]) & any(familyset == 0)) {
# select independence if allowed
out$p.value.indeptest <- NA
out$family <- 0
out$par <- c(0, 0)
} else {
if (!is.na(familyset[1]) && (!any(c(1, 2, 5, 23, 24, 26:30, 33, 34, 36:40, 104, 114, 204, 214) %in% familyset) || !any(c(1:10, 13, 14, 16:20, 124, 134, 224, 234) %in% familyset)))
stop("'familyset' has to include at least one bivariate copula family for positive and one for negative dependence.")
if (is.na(familyset[1]))
familyset <- c(1:10, 13, 14, 16:20, 23, 24, 26:30, 33, 34, 36:40, 104, 114, 124, 134, 204, 214, 224, 234)
# calculate empirical kendall's tau
emp_tau <- fasttau(data1, data2, weights)
## perform independence test (if asked for)
if (indeptest == TRUE) {
out$p.value.indeptest <- BiCopIndTest(data1, data2)$p.value
} else {
out$p.value.indeptest <- NA
}
if (!is.na(out$p.value.indeptest) & out$p.value.indeptest >= level) {
# select independence copula, if not rejected
out$family <- 0
out$par <- c(0, 0)
} else {
## initial values for parameter optimization
start <- list()
start[[1]] <- sin(pi * emp_tau/2)
start[[2]] <- c(sin(emp_tau * pi/2), 10)
start[[3]] <- start[[13]] <- 2 * abs(emp_tau)/(1 - abs(emp_tau))
start[[4]] <- start[[14]] <- 1/(1 - abs(emp_tau))
if (5 %in% familyset)
start[[5]] <- Frank.itau.JJ(emp_tau) else start[[5]] <- 0
if (any(c(6, 16) %in% familyset))
start[[6]] <- start[[16]] <- Joe.itau.JJ(abs(emp_tau)) else start[[6]] <- start[[16]] <- 0
start[[7]] <- start[[17]] <- c(0.5, 1.5)
start[[8]] <- start[[18]] <- c(1.5, 1.5)
start[[9]] <- start[[19]] <- c(1.5, 0.5)
start[[10]] <- start[[20]] <- c(1.5, 0.5)
start[[23]] <- start[[33]] <- -2 * abs(emp_tau)/(1 - abs(emp_tau))
start[[24]] <- start[[34]] <- -1/(1 - abs(emp_tau))
if (any(c(26, 36) %in% familyset))
start[[26]] <- start[[36]] <- -Joe.itau.JJ(abs(emp_tau)) else start[[26]] <- start[[36]] <- 0
start[[27]] <- start[[37]] <- c(-0.5, -1.5)
start[[28]] <- start[[38]] <- c(-1.5, -1.5)
start[[29]] <- start[[39]] <- c(-1.5, -0.5)
start[[30]] <- start[[40]] <- c(-1.5, -0.5)
# start[[41]] = start[[51]] = ipsA.tau2cpar(emp_tau) start[[61]] = start[[71]] =
# -ipsA.tau2cpar(emp_tau)
delta <- min(abs(emp_tau) + 0.1, 0.999)
theta1 <- 1 + 6 * abs(emp_tau)
start[[104]] <- start[[204]] <- start[[114]] <- start[[214]] <- c(theta1, delta)
start[[124]] <- start[[224]] <- start[[134]] <- start[[234]] <- c(-theta1, delta)
## find families for which estimation is required (only families that allow for
## the empirical kendall's tau)
if (emp_tau < 0) {
todo <- c(1, 2, 5, 23, 24, 26:30, 33, 34, 36:40, 124, 134, 224, 234)
} else {
todo <- c(1:10, 13, 14, 16:20, 104, 114, 204, 214)
}
todo <- todo[which(todo %in% familyset)]
## estimate parameters for each of the families (in 'todo')
optiout <- list()
if (any(todo == 2)) {
optiout[[2]] <- suppressWarnings(BiCopEst(data1,
data2,
family = 2,
max.df = 30,
weights = weights))
optiout[[2]]$par <- c(optiout[[2]]$par, optiout[[2]]$par2)
if (optiout[[2]]$par[2] >= 30) {
todo[todo == 2] <- 1
todo <- unique(todo)
optiout[[2]] <- list()
}
}
if (any(todo == 7)) {
optiout[[7]] <- MLE_intern(cbind(data1, data2),
start[[7]],
7,
weights = weights)
if (optiout[[7]]$par[1] <= 0.1 | optiout[[7]]$par[2] <= 1.1) {
if (optiout[[7]]$par[1] <= 0.1) {
todo[todo == 7] <- 4
todo <- unique(todo)
} else if (optiout[[7]]$par[2] <= 1.1) {
todo[todo == 7] <- 3
todo <- unique(todo)
}
optiout[[7]] <- list()
}
}
if (any(todo == 8)) {
optiout[[8]] <- MLE_intern(cbind(data1, data2),
start[[8]],
8,
weights = weights)
if (optiout[[8]]$par[1] <= 1.1 | optiout[[8]]$par[2] <= 1.1) {
if (optiout[[8]]$par[1] <= 1.1) {
todo[todo == 8] <- 4
todo <- unique(todo)
} else if (optiout[[8]]$par[2] <= 1.1) {
todo[todo == 8] <- 6
todo <- unique(todo)
}
optiout[[8]] <- list()
}
}
if (any(todo == 9)) {
optiout[[9]] <- MLE_intern(cbind(data1, data2),
start[[9]],
9,
weights = weights)
if (optiout[[9]]$par[1] <= 1.1 | optiout[[9]]$par[2] <= 0.1) {
if (optiout[[9]]$par[1] <= 1.1) {
todo[todo == 9] <- 3
todo <- unique(todo)
} else if (optiout[[9]]$par[2] <= 0.1) {
todo[todo == 9] <- 6
todo <- unique(todo)
}
optiout[[9]] <- list()
}
}
if (any(todo == 10)) {
optiout[[10]] <- MLE_intern(cbind(data1, data2),
start[[10]],
10,
weights = weights)
if (optiout[[10]]$par[2] >= 0.99) {
todo[todo == 10] <- 6
todo <- unique(todo)
optiout[[10]] <- list()
}
}
if (any(todo == 17)) {
optiout[[17]] <- MLE_intern(cbind(data1, data2),
start[[17]],
17,
weights = weights)
if (optiout[[17]]$par[1] <= 0.1 | optiout[[17]]$par[2] <= 1.1) {
if (optiout[[17]]$par[1] <= 0.1) {
todo[todo == 17] <- 14
todo <- unique(todo)
} else if (optiout[[17]]$par[2] <= 1.1) {
todo[todo == 17] <- 13
todo <- unique(todo)
}
optiout[[17]] <- list()
}
}
if (any(todo == 18)) {
optiout[[18]] <- MLE_intern(cbind(data1, data2),
start[[18]],
18,
weights = weights)
if (optiout[[18]]$par[1] <= 1.1 | optiout[[18]]$par[2] <= 1.1) {
if (optiout[[18]]$par[1] <= 1.1) {
todo[todo == 18] <- 14
todo <- unique(todo)
} else if (optiout[[18]]$par[2] <= 1.1) {
todo[todo == 18] <- 16
todo <- unique(todo)
}
optiout[[18]] <- list()
}
}
if (any(todo == 19)) {
optiout[[19]] <- MLE_intern(cbind(data1, data2),
start[[19]],
19,
weights = weights)
if (optiout[[19]]$par[1] <= 1.1 | optiout[[19]]$par[2] <= 0.1) {
if (optiout[[19]]$par[1] <= 1.1) {
todo[todo == 19] <- 13
todo <- unique(todo)
} else if (optiout[[19]]$par[2] <= 0.1) {
todo[todo == 19] <- 16
todo <- unique(todo)
}
optiout[[19]] <- list()
}
}
if (any(todo == 20)) {
optiout[[20]] <- MLE_intern(cbind(data1, data2),
start[[20]],
20,
weights = weights)
if (optiout[[20]]$par[2] >= 0.99) {
todo[todo == 20] <- 16
todo <- unique(todo)
optiout[[20]] <- list()
}
}
if (any(todo == 27)) {
optiout[[27]] <- MLE_intern(cbind(data1, data2),
start[[27]],
27,
weights = weights)
if (optiout[[27]]$par[1] >= -0.1 | optiout[[27]]$par[2] >= -1.1) {
if (optiout[[27]]$par[1] >= -0.1) {
todo[todo == 27] <- 24
todo <- unique(todo)
} else if (optiout[[27]]$par[2] >= -1.1) {
todo[todo == 27] <- 23
todo <- unique(todo)
}
optiout[[27]] <- list()
}
}
if (any(todo == 28)) {
optiout[[28]] <- MLE_intern(cbind(data1, data2),
start[[28]],
28,
weights = weights)
if (optiout[[28]]$par[1] >= -1.1 | optiout[[28]]$par[2] >= -1.1) {
if (optiout[[28]]$par[1] >= -1.1) {
todo[todo == 28] <- 24
todo <- unique(todo)
} else if (optiout[[28]]$par[2] >= -1.1) {
todo[todo == 28] <- 26
todo <- unique(todo)
}
optiout[[28]] <- list()
}
}
if (any(todo == 29)) {
optiout[[29]] <- MLE_intern(cbind(data1, data2),
start[[29]],
29,
weights = weights)
if (optiout[[29]]$par[1] >= -1.1 | optiout[[29]]$par[2] >= -0.1) {
if (optiout[[29]]$par[1] >= -1.1) {
todo[todo == 29] <- 23
todo <- unique(todo)
} else if (optiout[[29]]$par[2] >= -0.1) {
todo[todo == 29] <- 26
todo <- unique(todo)
}
optiout[[29]] <- list()
}
}
if (any(todo == 30)) {
optiout[[30]] <- MLE_intern(cbind(data1, data2),
start[[30]],
30,
weights = weights)
if (optiout[[30]]$par[2] <= -0.99) {
todo[todo == 30] <- 26
todo <- unique(todo)
optiout[[30]] <- list()
}
}
if (any(todo == 37)) {
optiout[[37]] <- MLE_intern(cbind(data1, data2),
start[[37]],
37,
weights = weights)
if (optiout[[37]]$par[1] >= -0.1 | optiout[[37]]$par[2] >= -1.1) {
if (optiout[[37]]$par[1] >= -0.1) {
todo[todo == 37] <- 34
todo <- unique(todo)
} else if (optiout[[37]]$par[2] >= -1.1) {
todo[todo == 37] <- 33
todo <- unique(todo)
}
optiout[[37]] <- list()
}
}
if (any(todo == 38)) {
optiout[[38]] <- MLE_intern(cbind(data1, data2),
start[[38]],
38,
weights = weights)
if (optiout[[38]]$par[1] >= -1.1 | optiout[[38]]$par[2] >= -1.1) {
if (optiout[[38]]$par[1] >= -1.1) {
todo[todo == 38] <- 34
todo <- unique(todo)
} else if (optiout[[38]]$par[2] >= -1.1) {
todo[todo == 38] <- 36
todo <- unique(todo)
}
optiout[[38]] <- list()
}
}
if (any(todo == 39)) {
optiout[[39]] <- MLE_intern(cbind(data1, data2),
start[[39]],
39,
weights = weights)
if (optiout[[39]]$par[1] >= -1.1 | optiout[[39]]$par[2] >= -0.1) {
if (optiout[[39]]$par[1] >= -1.1) {
todo[todo == 39] <- 33
todo <- unique(todo)
} else if (optiout[[39]]$par[2] >= -0.1) {
todo[todo == 39] <- 36
todo <- unique(todo)
}
optiout[[39]] <- list()
}
}
if (any(todo == 40)) {
optiout[[40]] <- MLE_intern(cbind(data1, data2),
start[[40]],
40,
weights = weights)
if (optiout[[40]]$par[2] <= -0.99) {
todo[todo == 40] <- 36
todo <- unique(todo)
optiout[[40]] <- list()
}
}
for (i in todo[!(todo %in% c(2, 7:10, 17:20, 27:30, 37:40, 104, 114, 124, 134, 204, 214, 224, 234))]) {
optiout[[i]] <- MLE_intern(cbind(data1, data2),
start[[i]],
i,
weights = weights)
}
for (i in todo[(todo %in% c(104, 114, 124, 134, 204, 214, 224, 234))]) {
optiout[[i]] <- MLE_intern_Tawn(cbind(data1, data2),
start[[i]],
i)
}
## select the best model
if (selectioncrit == "AIC") {
AICs <- rep(Inf, max(todo))
for (i in todo) {
if (i %in% c(2, 7:10, 17:20, 27:30, 37:40, 104, 114, 124, 134, 204, 214, 224, 234)) {
if (any(is.na(weights))) {
ll <- sum(log(BiCopPDF(data1,
data2,
i,
optiout[[i]]$par[1],
optiout[[i]]$par[2])))
} else {
ll <- sum(log(BiCopPDF(data1,
data2,
i,
optiout[[i]]$par[1],
optiout[[i]]$par[2])) %*% weights)
}
AICs[i] <- -2 * ll + 4
} else {
if (any(is.na(weights))) {
ll <- sum(log(BiCopPDF(data1,
data2,
i,
optiout[[i]]$par)))
} else {
ll <- sum(log(BiCopPDF(data1,
data2,
i,
optiout[[i]]$par)) %*% weights)
}
AICs[i] <- -2 * ll + 2
}
}
out$family <- todo[which.min(AICs[todo])]
} else {
if (selectioncrit == "BIC") {
BICs <- rep(Inf, max(todo))
for (i in todo) {
if (i %in% c(2, 7:10, 17:20, 27:30, 37:40, 104, 114, 124, 134, 204, 214, 224, 234)) {
if (any(is.na(weights))) {
ll <- sum(log(BiCopPDF(data1,
data2,
i,
optiout[[i]]$par[1],
optiout[[i]]$par[2])))
} else {
ll <- sum(log(BiCopPDF(data1,
data2,
i,
optiout[[i]]$par[1],
optiout[[i]]$par[2])) %*% weights)
}
BICs[i] <- -2 * ll + 2 * log(length(data1))
} else {
if (any(is.na(weights))) {
ll <- sum(log(BiCopPDF(data1,
data2,
i,
optiout[[i]]$par)))
} else {
ll <- sum(log(BiCopPDF(data1,
data2,
i,
optiout[[i]]$par)) %*% weights)
}
BICs[i] <- -2 * ll + log(length(data1))
}
}
out$family <- todo[which.min(BICs[todo])]
}
}
out$par <- optiout[[out$family]]$par
if (!(out$family %in% c(2, 7:10, 17:20, 27:30, 37:40, 104, 114, 124, 134, 204, 214, 224, 234)))
out$par[2] <- 0
}
}
## store and return results
out$par2 <- out$par[2]
out$par <- out$par[1]
class(out) <- "BiCop"
out
}
##### ----------------------------------------------------------------------
## function for augmenting a familyset with rotations
with_rotations <- function(nums) {
unique(unlist(lapply(nums, get_rotations)))
}
get_rotations <- function(i) {
# no roations for independence, gaussian, student and frank copulas
out <- i
## rotations for other families
if(i %in% c(3, 13, 23, 33)) out <- c(3, 13, 23, 33)
if(i %in% c(4, 14, 24, 34)) out <- c(4, 14, 24, 34)
if(i %in% c(6, 16, 26, 36)) out <- c(6, 16, 26, 36)
if(i %in% c(7, 17, 27, 37)) out <- c(7, 17, 27, 37)
if(i %in% c(8, 18, 28, 38)) out <- c(8, 18, 28, 38)
if(i %in% c(9, 19, 29, 39)) out <- c(9, 19, 29, 39)
if(i %in% c(10, 20, 30, 40)) out <- c(10, 20, 30, 40)
if(i %in% c(104, 114, 124, 134)) out <- c(104, 114, 124, 134)
if(i %in% c(204, 214, 224, 234)) out <- c(204, 214, 224, 234)
out
}
|
# FUNCTION: Reading a CONS file -------------------------------------------
readConsFile <- function(path,fileName){
data <- read_table2(file = file.path(path,fileName),col_names = F,skip = 2)
data <- data[-which(rowSums(is.na(data)) == ncol(data)),]
colnames(data) <- paste0('VL',1:ncol(data))
data <- rbind(data,data[23,])
data <- cbind(LineLayer = 1:23,HL = 1,data) %>%
mutate(
RN = row_number()
,HL = as.integer(RN/23) + 1
,IsHeader = LineLayer%%2) %>%
filter(
LineLayer < 23
,IsHeader == 0)
data <- cbind(EyeLayer = c('ILM','NFL','GCL','IPL','INL','OPL','ELM','PR1','PR2','RPE','BM'),data) %>%
select(-c(RN,IsHeader,LineLayer)) %>%
mutate_at(vars(matches("VL")), as.integer) %>%
as_tibble()
return(data)
} | /reference code/Joos-Updates 20191218/readConsFile.R | no_license | hansvomkreuz/CONS | R | false | false | 843 | r | # FUNCTION: Reading a CONS file -------------------------------------------
readConsFile <- function(path,fileName){
data <- read_table2(file = file.path(path,fileName),col_names = F,skip = 2)
data <- data[-which(rowSums(is.na(data)) == ncol(data)),]
colnames(data) <- paste0('VL',1:ncol(data))
data <- rbind(data,data[23,])
data <- cbind(LineLayer = 1:23,HL = 1,data) %>%
mutate(
RN = row_number()
,HL = as.integer(RN/23) + 1
,IsHeader = LineLayer%%2) %>%
filter(
LineLayer < 23
,IsHeader == 0)
data <- cbind(EyeLayer = c('ILM','NFL','GCL','IPL','INL','OPL','ELM','PR1','PR2','RPE','BM'),data) %>%
select(-c(RN,IsHeader,LineLayer)) %>%
mutate_at(vars(matches("VL")), as.integer) %>%
as_tibble()
return(data)
} |
#**Import the data set**
#**set the working directory**
setwd("C:/Pradeep/Project/Learning/ML A-Z/P1 Data Preprocessing/Machine-Learning-A-Z/Part 1 - Data Preprocessing")
#**Import the data set**
dataset=read.csv("data.csv")
#**print the data set**
print(dataset)
#**Matrix creation is not required in R**
## Take care of missing data
dataset$Age = ifelse(is.na(dataset$Age),
ave((dataset$Age),FUN = function(x) mean(x,na.rm = TRUE))
,dataset$Age)
dataset$Salary = ifelse(is.na(dataset$Salary),
ave((dataset$Salary),FUN = function(x) mean(x,na.rm = TRUE))
,dataset$Salary)
## Encoding the categorical data
dataset$Country=factor(dataset$Country,levels = c("France","Spain","Germany"),labels = c(1,2,3))
print(dataset$Country)
dataset$Purchased=factor(dataset$Purchased,levels = c("Yes","No"),labels = c(0,1))
print(dataset$Purchased)
#Splitting the data in to training and test set
#install a catools
#install.packages("caTools")
library(caTools)
set.seed(123)
split = sample.split(dataset$Purchased,SplitRatio = 0.2)
test_set=subset(dataset,split=TRUE)
training_Set=subset(dataset,split=FALSE)
# Feature Scaling
training_set[, 2:3] = scale(training_set[, 2:3])
test_set[, 2:3] = scale(test_set[, 2:3]) | /Part 1 - Data Preprocessing/Section 2 -------------------- Part 1 - Data Preprocessing --------------------/feature_scaling.R | no_license | pradeeppadmarajaiah/machine_learning | R | false | false | 1,324 | r |
#**Import the data set**
#**set the working directory**
setwd("C:/Pradeep/Project/Learning/ML A-Z/P1 Data Preprocessing/Machine-Learning-A-Z/Part 1 - Data Preprocessing")
#**Import the data set**
dataset=read.csv("data.csv")
#**print the data set**
print(dataset)
#**Matrix creation is not required in R**
## Take care of missing data
dataset$Age = ifelse(is.na(dataset$Age),
ave((dataset$Age),FUN = function(x) mean(x,na.rm = TRUE))
,dataset$Age)
dataset$Salary = ifelse(is.na(dataset$Salary),
ave((dataset$Salary),FUN = function(x) mean(x,na.rm = TRUE))
,dataset$Salary)
## Encoding the categorical data
dataset$Country=factor(dataset$Country,levels = c("France","Spain","Germany"),labels = c(1,2,3))
print(dataset$Country)
dataset$Purchased=factor(dataset$Purchased,levels = c("Yes","No"),labels = c(0,1))
print(dataset$Purchased)
#Splitting the data in to training and test set
#install a catools
#install.packages("caTools")
library(caTools)
set.seed(123)
split = sample.split(dataset$Purchased,SplitRatio = 0.2)
test_set=subset(dataset,split=TRUE)
training_Set=subset(dataset,split=FALSE)
# Feature Scaling
training_set[, 2:3] = scale(training_set[, 2:3])
test_set[, 2:3] = scale(test_set[, 2:3]) |
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/methods.R
\name{plot.vsel}
\alias{plot.vsel}
\title{Plot summary statistics related to variable selection}
\usage{
\method{plot}{vsel}(
x,
nterms_max = NULL,
stats = "elpd",
deltas = FALSE,
alpha = 0.32,
baseline = NULL,
...
)
}
\arguments{
\item{x}{The object returned by \link[=varsel]{varsel} or
\link[=cv_varsel]{cv_varsel}.}
\item{nterms_max}{Maximum submodel size for which the statistics are
calculated. For \code{plot.vsel} it must be at least 1.}
\item{stats}{One or several strings determining which statistics to
calculate. Available statistics are:
\itemize{
\item{elpd:} {(Expected) sum of log predictive densities}
\item{mlpd:} {Mean log predictive density, that is, elpd divided by the
number of datapoints.} \item{mse:} {Mean squared error (gaussian family
only)}
\item{rmse:} {Root mean squared error (gaussian family only)}
\item{acc/pctcorr:} {Classification accuracy (binomial family only)}
\item{auc:} {Area under the ROC curve (binomial family only)}
}
Default is \code{"elpd"}.}
\item{deltas}{If \code{TRUE}, the submodel statistics are estimated relative
to the baseline model (see argument \code{baseline}) instead of estimating
the actual values of the statistics. Defaults to \code{FALSE}.}
\item{alpha}{A number indicating the desired coverage of the credible
intervals. For example \code{alpha=0.32} corresponds to 68\% probability
mass within the intervals, that is, one standard error intervals.}
\item{baseline}{Either 'ref' or 'best' indicating whether the baseline is the
reference model or the best submodel found. Default is 'ref' when the
reference model exists, and 'best' otherwise.}
\item{...}{Currently ignored.}
}
\description{
Plot summary statistics related to variable selection
}
\examples{
\donttest{
### Usage with stanreg objects
if (requireNamespace('rstanarm', quietly=TRUE)) {
n <- 30
d <- 5
x <- matrix(rnorm(n*d), nrow=n)
y <- x[,1] + 0.5*rnorm(n)
data <- data.frame(x,y)
fit <- rstanarm::stan_glm(y ~ X1 + X2 + X3 + X4 + X5, gaussian(),
data=data, chains=2, iter=500)
vs <- cv_varsel(fit)
plot(vs)
}
}
}
| /man/plot.vsel.Rd | no_license | topipa/projpred-1 | R | false | true | 2,190 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/methods.R
\name{plot.vsel}
\alias{plot.vsel}
\title{Plot summary statistics related to variable selection}
\usage{
\method{plot}{vsel}(
x,
nterms_max = NULL,
stats = "elpd",
deltas = FALSE,
alpha = 0.32,
baseline = NULL,
...
)
}
\arguments{
\item{x}{The object returned by \link[=varsel]{varsel} or
\link[=cv_varsel]{cv_varsel}.}
\item{nterms_max}{Maximum submodel size for which the statistics are
calculated. For \code{plot.vsel} it must be at least 1.}
\item{stats}{One or several strings determining which statistics to
calculate. Available statistics are:
\itemize{
\item{elpd:} {(Expected) sum of log predictive densities}
\item{mlpd:} {Mean log predictive density, that is, elpd divided by the
number of datapoints.} \item{mse:} {Mean squared error (gaussian family
only)}
\item{rmse:} {Root mean squared error (gaussian family only)}
\item{acc/pctcorr:} {Classification accuracy (binomial family only)}
\item{auc:} {Area under the ROC curve (binomial family only)}
}
Default is \code{"elpd"}.}
\item{deltas}{If \code{TRUE}, the submodel statistics are estimated relative
to the baseline model (see argument \code{baseline}) instead of estimating
the actual values of the statistics. Defaults to \code{FALSE}.}
\item{alpha}{A number indicating the desired coverage of the credible
intervals. For example \code{alpha=0.32} corresponds to 68\% probability
mass within the intervals, that is, one standard error intervals.}
\item{baseline}{Either 'ref' or 'best' indicating whether the baseline is the
reference model or the best submodel found. Default is 'ref' when the
reference model exists, and 'best' otherwise.}
\item{...}{Currently ignored.}
}
\description{
Plot summary statistics related to variable selection
}
\examples{
\donttest{
### Usage with stanreg objects
if (requireNamespace('rstanarm', quietly=TRUE)) {
n <- 30
d <- 5
x <- matrix(rnorm(n*d), nrow=n)
y <- x[,1] + 0.5*rnorm(n)
data <- data.frame(x,y)
fit <- rstanarm::stan_glm(y ~ X1 + X2 + X3 + X4 + X5, gaussian(),
data=data, chains=2, iter=500)
vs <- cv_varsel(fit)
plot(vs)
}
}
}
|
#ui.R
library(shiny)
library(leaflet)
#library(shinydashboard)
# Rely on the 'WorldPhones' dataset in the datasets
# package (which generally comes preloaded).
# Define the overall UI
shinyUI(
# Use a fluid Bootstrap layout
bootstrapPage(
# Give the page a title
titlePanel(
title=h1("NYC Complaints by Borough, Jan. 2010 to Apr. 2016 (Sample Data)", align="center", style = "color: Darkblue")),
tags$style(type='text/css', ".selectize-input { font-size: 15px; line-height: 15px;} .selectize-dropdown { font-size: 15px; line-height: 15px; }"),
# Generate a row with a sidebar
selectInput(inputId = "boro",
label = "Select a Borough:",
choices = c("BROOKLYN", "QUEENS", "MANHATTAN", "BRONX", "STATEN ISLAND"),
selected = pre_selected),
#
mainPanel(
tags$head(
tags$style(type='text/css',
".nav-tabs {font-size: 20px} ")),
tabsetPanel(
tabPanel("Welcome",
#column(6, offset = 3,
p(h2(
br(),
"
New York City...", style = "font-family: 'times'; font-si16pt; color: Darkgreen"),
br(),
h3(em("
'If I can make it there, I'll make it anywhere.' ~ Frank Sinatra
"), style = "font-family: 'times'; font-si16pt"),
br(),
h3("
When I think of New York City I think of noise, sirens, taxis, the constant battle of suitable heat with the landlord,
and the scent of a sanitation truck on a hot summer day. There is no place like home.", style = "font-family: 'times'; font-si16pt"
),
h3(
"Using the 311 dataset provided by NYC Open Data I crafted an interactive user application to assist
residents and visitors who are in search of an area with an appropriate sound and style to their
liking. NYC Complaints by Borough (N.C.B.) is a quick reference tool to aid users with their planning, grounded
on the complaints reported in NYC.
", style = "font-family: 'times'; font-si16pt")
)
),
tabPanel("About the Dataset",
p(h2(
br(),
"
The Dataset", style = "font-family: 'times'; font-si16pt; color: Darkgreen"),
h3(
"The dataset is a daily collection of complaints made directly to 311 by the public. 311 is a NYC customer service center,
launched by Mayor Michael Bloomberg in March 2003. Providing the public with easy access to NYC government services, while
assisting agency improvement through consistent measurements. 311 is a huge success, with annual year-on-year usage growth
since its launch. Here are some facts on 311:
", style = "font-family: 'times'; font-si16pt"),
h3("
- Open 24 hours a day, 365 days’ year", style = "font-family: 'times'; font-si16pt"),
h3("
- Access to 180 languages", style = "font-family: 'times'; font-si16pt"),
h3("
- Receive 51,000 calls per day on average", style = "font-family: 'times'; font-si16pt"),
h3("
- Annual call volumes to 911 have decreased since the inception of 311", style = "font-family: 'times'; font-si16pt"),
h3("
- 311 online was launched in March 2009", style = "font-family: 'times'; font-si16pt")
)
),
tabPanel("Complaints", plotOutput(outputId = "wordCloud1", height = "700", width="1500")),
tabPanel("Frequency", plotOutput(outputId = "barPlot", height = "600", width="1300"),
selectInput(inputId = "Fre_q",
label = "Select the Frequency:",
choices = c("ANNUAL", "MONTH", "DAY"),
selected = "MONTH")),
tabPanel("Top Ten Complaints", dataTableOutput("table"), height = "1500", width="1500"),
tabPanel("Map", leafletOutput(outputId="map", height = "900", width="1500"))
#tabPanel("Next Steps",
#p(h2(
# br(),
# "
# Next steps", style = "font-family: 'times'; font-si16pt; color: Darkgreen"),
#h3("
# Allow the user to sort by:
# Complaint type
# Specific neighborhoods
# Time period
# Option to enter longitude and latitude coordinates
# Automate application to update live with the latest data available
# Upload the full data set to the application.", style = "font-family: 'times'; font-si16pt")
# )
# )
)
)
)
)
| /Project2-Shiny/kellymejiabreton/ui.R | no_license | jeperez/bootcamp005_project | R | false | false | 10,808 | r | #ui.R
library(shiny)
library(leaflet)
#library(shinydashboard)
# Rely on the 'WorldPhones' dataset in the datasets
# package (which generally comes preloaded).
# Define the overall UI
shinyUI(
# Use a fluid Bootstrap layout
bootstrapPage(
# Give the page a title
titlePanel(
title=h1("NYC Complaints by Borough, Jan. 2010 to Apr. 2016 (Sample Data)", align="center", style = "color: Darkblue")),
tags$style(type='text/css', ".selectize-input { font-size: 15px; line-height: 15px;} .selectize-dropdown { font-size: 15px; line-height: 15px; }"),
# Generate a row with a sidebar
selectInput(inputId = "boro",
label = "Select a Borough:",
choices = c("BROOKLYN", "QUEENS", "MANHATTAN", "BRONX", "STATEN ISLAND"),
selected = pre_selected),
#
mainPanel(
tags$head(
tags$style(type='text/css',
".nav-tabs {font-size: 20px} ")),
tabsetPanel(
tabPanel("Welcome",
#column(6, offset = 3,
p(h2(
br(),
"
New York City...", style = "font-family: 'times'; font-si16pt; color: Darkgreen"),
br(),
h3(em("
'If I can make it there, I'll make it anywhere.' ~ Frank Sinatra
"), style = "font-family: 'times'; font-si16pt"),
br(),
h3("
When I think of New York City I think of noise, sirens, taxis, the constant battle of suitable heat with the landlord,
and the scent of a sanitation truck on a hot summer day. There is no place like home.", style = "font-family: 'times'; font-si16pt"
),
h3(
"Using the 311 dataset provided by NYC Open Data I crafted an interactive user application to assist
residents and visitors who are in search of an area with an appropriate sound and style to their
liking. NYC Complaints by Borough (N.C.B.) is a quick reference tool to aid users with their planning, grounded
on the complaints reported in NYC.
", style = "font-family: 'times'; font-si16pt")
)
),
tabPanel("About the Dataset",
p(h2(
br(),
"
The Dataset", style = "font-family: 'times'; font-si16pt; color: Darkgreen"),
h3(
"The dataset is a daily collection of complaints made directly to 311 by the public. 311 is a NYC customer service center,
launched by Mayor Michael Bloomberg in March 2003. Providing the public with easy access to NYC government services, while
assisting agency improvement through consistent measurements. 311 is a huge success, with annual year-on-year usage growth
since its launch. Here are some facts on 311:
", style = "font-family: 'times'; font-si16pt"),
h3("
- Open 24 hours a day, 365 days’ year", style = "font-family: 'times'; font-si16pt"),
h3("
- Access to 180 languages", style = "font-family: 'times'; font-si16pt"),
h3("
- Receive 51,000 calls per day on average", style = "font-family: 'times'; font-si16pt"),
h3("
- Annual call volumes to 911 have decreased since the inception of 311", style = "font-family: 'times'; font-si16pt"),
h3("
- 311 online was launched in March 2009", style = "font-family: 'times'; font-si16pt")
)
),
tabPanel("Complaints", plotOutput(outputId = "wordCloud1", height = "700", width="1500")),
tabPanel("Frequency", plotOutput(outputId = "barPlot", height = "600", width="1300"),
selectInput(inputId = "Fre_q",
label = "Select the Frequency:",
choices = c("ANNUAL", "MONTH", "DAY"),
selected = "MONTH")),
tabPanel("Top Ten Complaints", dataTableOutput("table"), height = "1500", width="1500"),
tabPanel("Map", leafletOutput(outputId="map", height = "900", width="1500"))
#tabPanel("Next Steps",
#p(h2(
# br(),
# "
# Next steps", style = "font-family: 'times'; font-si16pt; color: Darkgreen"),
#h3("
# Allow the user to sort by:
# Complaint type
# Specific neighborhoods
# Time period
# Option to enter longitude and latitude coordinates
# Automate application to update live with the latest data available
# Upload the full data set to the application.", style = "font-family: 'times'; font-si16pt")
# )
# )
)
)
)
)
|
library(arfima)
### Name: sim_from_fitted
### Title: Simulate an ARFIMA time series from a fitted arfima object.
### Aliases: sim_from_fitted
### Keywords: fit ts
### ** Examples
set.seed(6533)
sim <- arfima.sim(1000, model = list(phi = .2, dfrac = .3, dint = 2))
fit <- arfima(sim, order = c(1, 2, 0))
fit
sim2 <- sim_from_fitted(100, fit)
fit2 <- arfima(sim2, order = c(1, 2, 0))
fit2
## No test:
set.seed(2266)
#Fairly pathological series to fit for this package
series = arfima.sim(500, model=list(phi = 0.98, dfrac = 0.46))
X = matrix(rnorm(1000), ncol = 2)
colnames(X) <- c('c1', 'c2')
series_added <- series + X%*%c(2, 5)
fit <- arfima(series, order = c(1, 0, 0), numeach = c(2, 2))
fit_X <- arfima(series_added, order=c(1, 0, 0), xreg=X, numeach = c(2, 2))
from_series <- sim_from_fitted(1000, fit)
fit1a <- arfima(from_series[[1]], order = c(1, 0, 0), numeach = c(2, 2))
fit1a
fit1 <- arfima(from_series[[1]], order = c(1, 0, 0))
fit1
fit2 <- arfima(from_series[[1]], order = c(1, 0, 0))
fit2
fit3 <- arfima(from_series[[1]], order = c(1, 0, 0))
fit3
fit4 <- arfima(from_series[[1]], order = c(1, 0, 0))
fit4
Xnew = matrix(rnorm(2000), ncol = 2)
from_series_X <- sim_from_fitted(1000, fit_X, X=Xnew)
fit_X1a <- arfima(from_series_X[[1]], order=c(1, 0, 0), xreg=Xnew, numeach = c(2, 2))
fit_X1a
fit_X1 <- arfima(from_series_X[[1]], order=c(1, 0, 0), xreg=Xnew)
fit_X1
fit_X2 <- arfima(from_series_X[[2]], order=c(1, 0, 0), xreg=Xnew)
fit_X2
fit_X3 <- arfima(from_series_X[[3]], order=c(1, 0, 0), xreg=Xnew)
fit_X3
fit_X4 <- arfima(from_series_X[[4]], order=c(1, 0, 0), xreg=Xnew)
fit_X4
## End(No test)
| /data/genthat_extracted_code/arfima/examples/sim_from_fitted.Rd.R | no_license | surayaaramli/typeRrh | R | false | false | 1,631 | r | library(arfima)
### Name: sim_from_fitted
### Title: Simulate an ARFIMA time series from a fitted arfima object.
### Aliases: sim_from_fitted
### Keywords: fit ts
### ** Examples
set.seed(6533)
sim <- arfima.sim(1000, model = list(phi = .2, dfrac = .3, dint = 2))
fit <- arfima(sim, order = c(1, 2, 0))
fit
sim2 <- sim_from_fitted(100, fit)
fit2 <- arfima(sim2, order = c(1, 2, 0))
fit2
## No test:
set.seed(2266)
#Fairly pathological series to fit for this package
series = arfima.sim(500, model=list(phi = 0.98, dfrac = 0.46))
X = matrix(rnorm(1000), ncol = 2)
colnames(X) <- c('c1', 'c2')
series_added <- series + X%*%c(2, 5)
fit <- arfima(series, order = c(1, 0, 0), numeach = c(2, 2))
fit_X <- arfima(series_added, order=c(1, 0, 0), xreg=X, numeach = c(2, 2))
from_series <- sim_from_fitted(1000, fit)
fit1a <- arfima(from_series[[1]], order = c(1, 0, 0), numeach = c(2, 2))
fit1a
fit1 <- arfima(from_series[[1]], order = c(1, 0, 0))
fit1
fit2 <- arfima(from_series[[1]], order = c(1, 0, 0))
fit2
fit3 <- arfima(from_series[[1]], order = c(1, 0, 0))
fit3
fit4 <- arfima(from_series[[1]], order = c(1, 0, 0))
fit4
Xnew = matrix(rnorm(2000), ncol = 2)
from_series_X <- sim_from_fitted(1000, fit_X, X=Xnew)
fit_X1a <- arfima(from_series_X[[1]], order=c(1, 0, 0), xreg=Xnew, numeach = c(2, 2))
fit_X1a
fit_X1 <- arfima(from_series_X[[1]], order=c(1, 0, 0), xreg=Xnew)
fit_X1
fit_X2 <- arfima(from_series_X[[2]], order=c(1, 0, 0), xreg=Xnew)
fit_X2
fit_X3 <- arfima(from_series_X[[3]], order=c(1, 0, 0), xreg=Xnew)
fit_X3
fit_X4 <- arfima(from_series_X[[4]], order=c(1, 0, 0), xreg=Xnew)
fit_X4
## End(No test)
|
source('tex/simulations/aux_.R')
n <- 50
p <- 24
ARMA <- 0.5
percent_alpha <- 0.8
range_alpha <- c(0.6, 0.95)
create_variance_estimates_different_link <- function(n_sim, simulate_link, name_sim, estimate_link, name_est){
if (ARMA == 0) ARMA <- NULL
n_s <- ceiling(0.5*n)
n_h <- n - n_s
samples <- create_samples(n_sim = n_sim, n_h = n_h, n_s = n_s, p = p, Tlength = 115,
percent_alpha = percent_alpha, range_alpha = range_alpha, linkFun = simulate_link,
ARsick = ARMA, ARhealth = ARMA, MAsick = ARMA, MAhealth = ARMA)
results <- lapply(
1:n_sim, function(i) estimate_model(
control_arr = samples$samples[[i]]$healthy,
diagnosed_arr = samples$samples[[i]]$sick,
LinkFunc = estimate_link, verbose = FALSE)
)
gee_vars <- sapply(1:n_sim, function(i) compute_gee_variance(
mod = results[[i]],
control_arr = samples$samples[[i]]$healthy,
diagnosed_arr = samples$samples[[i]]$sick
), simplify = 'array')
sds <- lapply(1:n_sim, function(i) sqrt_diag(gee_vars[,,i]))
out <- data.table(
sims_num = rep(1:n_sim, each = p),
real = as.vector(samples$alpha),
estimate = as.vector(sapply(transpose(results)$alpha, as.vector)),
sd = do.call(c, sds)
)
out[,`:=`(
simulate_link = name_sim,
estimae_link = name_est,
z_value = (estimate - estimate_link$null_value)/sd,
is_null = real == simulate_link$null_value
)]
return(out)
}
res <- create_variance_estimates_different_link(
20,
LinkFunctions$multiplicative_identity, 'additive',
LinkFunctions$additive_quotent, 'quotent'
)
res[,`:=`(
p_value = 2*pnorm(abs(z_value), lower.tail = F),
is_null_char = ifelse(is_null, 'Null Value', 'Non Null Value')
)]
r_squared <- round(summary(lm(estimate ~ 0 + factor(real), res))$r.squared, 3)
estimates_plot <- ggplot(res, aes(x = real, y = estimate)) +
geom_point(shape = 17, position = 'jitter') +
annotate('label', x = min(res$real)*1.1, y = 0, label = TeX(paste0('$R^2$: ', r_squared), 'expression')) +
labs(
# title = 'Bias of Alpha Estimate',
# subtitle = 'Showing Box Plot for Null Values (\u03B1 = 1)',
x = 'Real Value (Multiplicative)',
y = 'Estimate (Quotent)'
) +
theme_bw()
inference_plot <- ggplot(res, aes(x = z_value, y = ..density.., fill = is_null_char)) +
geom_histogram(bins = 8*sqrt(length(res)), alpha = .5, position = 'identity', col = 'white') +
# facet_grid(is_null_char~.) +
geom_hline(yintercept = 0) +
labs(
x = 'Z scores \n of misspecified link function',
y = 'Density',
fill = ''
) +
theme_user() +
theme(
axis.text.y = element_blank(),
axis.ticks.y = element_blank(),
legend.position = c(.8,.75),
legend.background = element_blank(),
legend.title = element_blank(),
legend.box.background = element_rect(colour = "black")
) +
scale_fill_manual(
values = c('Null Value' = '#A6ACAF', 'Non Null Value' = '#212F3D')
)
out <- arrangeGrob(estimates_plot, inference_plot, nrow = 2)
custom_ggsave('robustness_link.png', out, width = 2, height = 1.1)
| /tex/simulations/robustness.R | no_license | itamarfaran/correlation_glm | R | false | false | 3,132 | r | source('tex/simulations/aux_.R')
n <- 50
p <- 24
ARMA <- 0.5
percent_alpha <- 0.8
range_alpha <- c(0.6, 0.95)
create_variance_estimates_different_link <- function(n_sim, simulate_link, name_sim, estimate_link, name_est){
if (ARMA == 0) ARMA <- NULL
n_s <- ceiling(0.5*n)
n_h <- n - n_s
samples <- create_samples(n_sim = n_sim, n_h = n_h, n_s = n_s, p = p, Tlength = 115,
percent_alpha = percent_alpha, range_alpha = range_alpha, linkFun = simulate_link,
ARsick = ARMA, ARhealth = ARMA, MAsick = ARMA, MAhealth = ARMA)
results <- lapply(
1:n_sim, function(i) estimate_model(
control_arr = samples$samples[[i]]$healthy,
diagnosed_arr = samples$samples[[i]]$sick,
LinkFunc = estimate_link, verbose = FALSE)
)
gee_vars <- sapply(1:n_sim, function(i) compute_gee_variance(
mod = results[[i]],
control_arr = samples$samples[[i]]$healthy,
diagnosed_arr = samples$samples[[i]]$sick
), simplify = 'array')
sds <- lapply(1:n_sim, function(i) sqrt_diag(gee_vars[,,i]))
out <- data.table(
sims_num = rep(1:n_sim, each = p),
real = as.vector(samples$alpha),
estimate = as.vector(sapply(transpose(results)$alpha, as.vector)),
sd = do.call(c, sds)
)
out[,`:=`(
simulate_link = name_sim,
estimae_link = name_est,
z_value = (estimate - estimate_link$null_value)/sd,
is_null = real == simulate_link$null_value
)]
return(out)
}
res <- create_variance_estimates_different_link(
20,
LinkFunctions$multiplicative_identity, 'additive',
LinkFunctions$additive_quotent, 'quotent'
)
res[,`:=`(
p_value = 2*pnorm(abs(z_value), lower.tail = F),
is_null_char = ifelse(is_null, 'Null Value', 'Non Null Value')
)]
r_squared <- round(summary(lm(estimate ~ 0 + factor(real), res))$r.squared, 3)
estimates_plot <- ggplot(res, aes(x = real, y = estimate)) +
geom_point(shape = 17, position = 'jitter') +
annotate('label', x = min(res$real)*1.1, y = 0, label = TeX(paste0('$R^2$: ', r_squared), 'expression')) +
labs(
# title = 'Bias of Alpha Estimate',
# subtitle = 'Showing Box Plot for Null Values (\u03B1 = 1)',
x = 'Real Value (Multiplicative)',
y = 'Estimate (Quotent)'
) +
theme_bw()
inference_plot <- ggplot(res, aes(x = z_value, y = ..density.., fill = is_null_char)) +
geom_histogram(bins = 8*sqrt(length(res)), alpha = .5, position = 'identity', col = 'white') +
# facet_grid(is_null_char~.) +
geom_hline(yintercept = 0) +
labs(
x = 'Z scores \n of misspecified link function',
y = 'Density',
fill = ''
) +
theme_user() +
theme(
axis.text.y = element_blank(),
axis.ticks.y = element_blank(),
legend.position = c(.8,.75),
legend.background = element_blank(),
legend.title = element_blank(),
legend.box.background = element_rect(colour = "black")
) +
scale_fill_manual(
values = c('Null Value' = '#A6ACAF', 'Non Null Value' = '#212F3D')
)
out <- arrangeGrob(estimates_plot, inference_plot, nrow = 2)
custom_ggsave('robustness_link.png', out, width = 2, height = 1.1)
|
% File man/getInteractions.Rd
\name{getInteractions}
\alias{getInteractions.path}
\alias{getInteractions.proteincomplex}
\alias{getInteractions.domains}
\alias{getInteractions.GO}
\title{Retrieve Biological Interaction Network Data}
\description{
A collection of functions to download or calculate network data for biological interaction (or relatedness, co-occurence etc). The getInteractions.GO function uses functionality from the GOSim source code by Holger Froehlich (see references). Parts of that code have been included and adapted for parallelization.
}
\usage{
getInteractions.path(
filter.ids = "",
biomart.config = biomartConfigs$hsapiens,
ds = bm.init.path(biomart.config),
toFile = "postgwas.interaction.download"
)
getInteractions.proteincomplex(
filter.ids = "",
biomart.config = biomartConfigs$hsapiens,
ds = bm.init.proteincomplex(biomart.config),
toFile = "postgwas.interaction.download"
)
getInteractions.domains(
filter.ids = "",
biomart.config = biomartConfigs$hsapiens,
filter.type = biomartConfigs$hsapiens$gene$filter$name,
ds = bm.init.genes(biomart.config),
min.occurence = NULL,
max.occurence = if(length(filter.ids) < 20)
NULL
else
length(filter.ids) / (logb(length(filter.ids), 3) +1),
toFile = "postgwas.interaction.download"
)
getInteractions.GO(
filter.ids,
GOpackagename = "org.Hs.eg.db",
ontology = "BP",
toFile = "postgwas.interaction.download",
cores = 1,
...
)
}
\arguments{
\item{filter.ids}{vector. A list of identifiers that that are used to retrieve network data. The type of IDs is specified by additional parameters (can also be symbols). See details.}
\item{biomart.config}{list. Specifies field names for biomart data retrieval. See \code{\link{biomartConfigs}}.}
\item{filter.type}{character. A biomart filter field name, that specifies the type of IDs listed in the argument \code{filter.ids}.}
\item{ds}{object. Biomart dataset to use. Is initialized automatically, but can also be explicitely passed to reduce runtime and network load in multiple calls.}
\item{min.occurence}{numeric(1). Specifies the minimum total number of occurences for a domain to be considered for interaction. This can occasionally be useful to reduce the specifity of modules and complexity of the network., i.e. only domains with common functions will form modules. When NULL, this is deactivated (default). }
\item{max.occurence}{numeric(1). Specifies the maximal total number of occurences for a domain to be considered for interaction. This can be used to avoid very common domains to create giant modules while increasing the functional specifity of modules. When NULL, this is deactivated. Is by default a log fraction of the number of vertices.}
\item{GOpackagename }{character(1). Has to be the package name of an installed GO annotation package (e.g. org.Hs.eg.db, see also \url{http://www.bioconductor.org/packages/2.10/data/annotation/}). GO term information from this package will be used for similarity calculation. }
\item{ontology}{character(1). Can be "BP", "MF" and "CC". Is passed to the \code{setOntology} function in GOSim, see the corresponding documentation.}
\item{toFile}{character(1). A file/pathname where the downloaded interaction data is saved in tab-delimited format. When NULL, does not write a resultfile.}
\item{cores}{integer. The number of parallel processes to use (cores = 1 uses no parallelization). }
\item{...}{Optional arguments that are passed to the \code{getGeneSim} function of the GOSim package. Could be in particular the \code{similarity} argument from that function. }
}
\details{
\describe{
\item{getInteractions.path}{Uses biomart (REACTOME) to determine pathway annotations for each gene. Common pathways between genes form interactions. Uses Entrez gene IDs by default.}
\item{getInteractions.proteincomplex}{Uses biomart (REACTOME) to determine protein interactions (from known complexes) between query genes. Uses Entrez gene IDs by default.}
\item{getInteractions.domains}{Uses biomart to annotate (superfamily) domains to each gene. The edges are formed by common domains between proteins. Uses gene symbols by default.}
\item{getInteractions.GO}{Calculates relations between the query genes based on similarity of their GO term architecture (using the GOSim package). This is time-intensive and takes seveal hours for ~1000 genes. Note that interactions at arbitrary strength are returned (consider 'weight' column), these should manually be filtered for a minimum similarity of e.g. weight > 0.75. GO term retrieval depends on bioconductor annotation packages. The human (org.Hs.eg.db) package is installed by default. When switching to a different organism by installing the appropriate package (\url{http://www.bioconductor.org/packages/2.10/data/annotation/}), the type of IDs used may change. The IDs used are then specified by the annotation package. See the example section of \link{gwas2network} how to overcome such an ID problem exemplified with yeast.}
}
}
\value{
A data frame with columns
\describe{
\item{getInteractions.path:}{"geneid.x", "geneid.y" and "label". The first two columns contain Entrez gene IDs by default, and the third the shared pathway names. }
\item{getInteractions.proteincomplex:}{"geneid.x", "geneid.y" and "label". The first two columns contain Entrez gene IDs by default, and the third the shared protein complex names. }
\item{getInteractions.GO:}{"geneid.x", "geneid.y" and "weight". The first two columns contain gene IDs / names according to the annotation package configuration, currently entrez gene IDs for the human package org.Hs.eg.db. The weight column contains the similarity measure between the genes calculated by GOSim. }
\item{getInteractions.domains:}{returns columns "genename.x", "genename.y", "geneid.x", "geneid.y", "domain.name", the latter specifying the shared domain that defines the edge, and IDs and names according to the biomartConfig used.}
}
}
\seealso{
\code{\link{biomartConfigs}}
}
\references{
The GOSim source code used by the getInteractions.GO function is described in the following publication: Holger Froehlich, N. Speer, A. Poustka, Tim Beissbarth (2007). GOSim - An R-Package for Computation of Information Theoretic GO Similarities Between Terms and Gene Products. BMC Bioinformatics, 8:166
The Reactome database used by the getInteractions.path function can be accessed at \url{http://www.reactome.org}
}
| /man/getInteractions.Rd | no_license | Katospiegel/postgwas | R | false | false | 6,574 | rd | % File man/getInteractions.Rd
\name{getInteractions}
\alias{getInteractions.path}
\alias{getInteractions.proteincomplex}
\alias{getInteractions.domains}
\alias{getInteractions.GO}
\title{Retrieve Biological Interaction Network Data}
\description{
A collection of functions to download or calculate network data for biological interaction (or relatedness, co-occurence etc). The getInteractions.GO function uses functionality from the GOSim source code by Holger Froehlich (see references). Parts of that code have been included and adapted for parallelization.
}
\usage{
getInteractions.path(
filter.ids = "",
biomart.config = biomartConfigs$hsapiens,
ds = bm.init.path(biomart.config),
toFile = "postgwas.interaction.download"
)
getInteractions.proteincomplex(
filter.ids = "",
biomart.config = biomartConfigs$hsapiens,
ds = bm.init.proteincomplex(biomart.config),
toFile = "postgwas.interaction.download"
)
getInteractions.domains(
filter.ids = "",
biomart.config = biomartConfigs$hsapiens,
filter.type = biomartConfigs$hsapiens$gene$filter$name,
ds = bm.init.genes(biomart.config),
min.occurence = NULL,
max.occurence = if(length(filter.ids) < 20)
NULL
else
length(filter.ids) / (logb(length(filter.ids), 3) +1),
toFile = "postgwas.interaction.download"
)
getInteractions.GO(
filter.ids,
GOpackagename = "org.Hs.eg.db",
ontology = "BP",
toFile = "postgwas.interaction.download",
cores = 1,
...
)
}
\arguments{
\item{filter.ids}{vector. A list of identifiers that that are used to retrieve network data. The type of IDs is specified by additional parameters (can also be symbols). See details.}
\item{biomart.config}{list. Specifies field names for biomart data retrieval. See \code{\link{biomartConfigs}}.}
\item{filter.type}{character. A biomart filter field name, that specifies the type of IDs listed in the argument \code{filter.ids}.}
\item{ds}{object. Biomart dataset to use. Is initialized automatically, but can also be explicitely passed to reduce runtime and network load in multiple calls.}
\item{min.occurence}{numeric(1). Specifies the minimum total number of occurences for a domain to be considered for interaction. This can occasionally be useful to reduce the specifity of modules and complexity of the network., i.e. only domains with common functions will form modules. When NULL, this is deactivated (default). }
\item{max.occurence}{numeric(1). Specifies the maximal total number of occurences for a domain to be considered for interaction. This can be used to avoid very common domains to create giant modules while increasing the functional specifity of modules. When NULL, this is deactivated. Is by default a log fraction of the number of vertices.}
\item{GOpackagename }{character(1). Has to be the package name of an installed GO annotation package (e.g. org.Hs.eg.db, see also \url{http://www.bioconductor.org/packages/2.10/data/annotation/}). GO term information from this package will be used for similarity calculation. }
\item{ontology}{character(1). Can be "BP", "MF" and "CC". Is passed to the \code{setOntology} function in GOSim, see the corresponding documentation.}
\item{toFile}{character(1). A file/pathname where the downloaded interaction data is saved in tab-delimited format. When NULL, does not write a resultfile.}
\item{cores}{integer. The number of parallel processes to use (cores = 1 uses no parallelization). }
\item{...}{Optional arguments that are passed to the \code{getGeneSim} function of the GOSim package. Could be in particular the \code{similarity} argument from that function. }
}
\details{
\describe{
\item{getInteractions.path}{Uses biomart (REACTOME) to determine pathway annotations for each gene. Common pathways between genes form interactions. Uses Entrez gene IDs by default.}
\item{getInteractions.proteincomplex}{Uses biomart (REACTOME) to determine protein interactions (from known complexes) between query genes. Uses Entrez gene IDs by default.}
\item{getInteractions.domains}{Uses biomart to annotate (superfamily) domains to each gene. The edges are formed by common domains between proteins. Uses gene symbols by default.}
\item{getInteractions.GO}{Calculates relations between the query genes based on similarity of their GO term architecture (using the GOSim package). This is time-intensive and takes seveal hours for ~1000 genes. Note that interactions at arbitrary strength are returned (consider 'weight' column), these should manually be filtered for a minimum similarity of e.g. weight > 0.75. GO term retrieval depends on bioconductor annotation packages. The human (org.Hs.eg.db) package is installed by default. When switching to a different organism by installing the appropriate package (\url{http://www.bioconductor.org/packages/2.10/data/annotation/}), the type of IDs used may change. The IDs used are then specified by the annotation package. See the example section of \link{gwas2network} how to overcome such an ID problem exemplified with yeast.}
}
}
\value{
A data frame with columns
\describe{
\item{getInteractions.path:}{"geneid.x", "geneid.y" and "label". The first two columns contain Entrez gene IDs by default, and the third the shared pathway names. }
\item{getInteractions.proteincomplex:}{"geneid.x", "geneid.y" and "label". The first two columns contain Entrez gene IDs by default, and the third the shared protein complex names. }
\item{getInteractions.GO:}{"geneid.x", "geneid.y" and "weight". The first two columns contain gene IDs / names according to the annotation package configuration, currently entrez gene IDs for the human package org.Hs.eg.db. The weight column contains the similarity measure between the genes calculated by GOSim. }
\item{getInteractions.domains:}{returns columns "genename.x", "genename.y", "geneid.x", "geneid.y", "domain.name", the latter specifying the shared domain that defines the edge, and IDs and names according to the biomartConfig used.}
}
}
\seealso{
\code{\link{biomartConfigs}}
}
\references{
The GOSim source code used by the getInteractions.GO function is described in the following publication: Holger Froehlich, N. Speer, A. Poustka, Tim Beissbarth (2007). GOSim - An R-Package for Computation of Information Theoretic GO Similarities Between Terms and Gene Products. BMC Bioinformatics, 8:166
The Reactome database used by the getInteractions.path function can be accessed at \url{http://www.reactome.org}
}
|
% Generated by roxygen2 (4.1.0): do not edit by hand
% Please edit documentation in R/trakt.show.summary.R
\name{trakt.show.summary}
\alias{trakt.show.summary}
\title{Get show summary info}
\usage{
trakt.show.summary(target, extended = "min")
}
\arguments{
\item{target}{The \code{id} of the show requested. Either the \code{slug}
(e.g. \code{"game-of-thrones"}), \code{trakt id} or \code{IMDb id}}
\item{extended}{Whether extended info should be provided.
Defaults to \code{"min"}, can either be \code{"min"} or \code{"full"}}
}
\value{
A \code{list} containing summary info
}
\description{
\code{trakt.show.summary} pulls show summary data and returns it compactly.
}
\details{
Note that setting \code{extended} to \code{min} makes this function
return about as much informations as \link[tRakt]{trakt.search}
}
\note{
See \href{http://docs.trakt.apiary.io/reference/shows/summary}{the trakt API docs for further info}
}
\examples{
\dontrun{
get_trakt_credentials() # Set required API data/headers
breakingbad.summary <- trakt.show.summary("breaking-bad")
}
}
\seealso{
Other show: \code{\link{trakt.getEpisodeData}};
\code{\link{trakt.getFullShowData}};
\code{\link{trakt.seasons.season}};
\code{\link{trakt.seasons.summary}};
\code{\link{trakt.show.people}};
\code{\link{trakt.show.ratings}};
\code{\link{trakt.show.stats}};
\code{\link{trakt.shows.popular}};
\code{\link{trakt.shows.related}};
\code{\link{trakt.shows.trending}}
}
| /man/trakt.show.summary.Rd | no_license | arturochian/tRakt | R | false | false | 1,456 | rd | % Generated by roxygen2 (4.1.0): do not edit by hand
% Please edit documentation in R/trakt.show.summary.R
\name{trakt.show.summary}
\alias{trakt.show.summary}
\title{Get show summary info}
\usage{
trakt.show.summary(target, extended = "min")
}
\arguments{
\item{target}{The \code{id} of the show requested. Either the \code{slug}
(e.g. \code{"game-of-thrones"}), \code{trakt id} or \code{IMDb id}}
\item{extended}{Whether extended info should be provided.
Defaults to \code{"min"}, can either be \code{"min"} or \code{"full"}}
}
\value{
A \code{list} containing summary info
}
\description{
\code{trakt.show.summary} pulls show summary data and returns it compactly.
}
\details{
Note that setting \code{extended} to \code{min} makes this function
return about as much informations as \link[tRakt]{trakt.search}
}
\note{
See \href{http://docs.trakt.apiary.io/reference/shows/summary}{the trakt API docs for further info}
}
\examples{
\dontrun{
get_trakt_credentials() # Set required API data/headers
breakingbad.summary <- trakt.show.summary("breaking-bad")
}
}
\seealso{
Other show: \code{\link{trakt.getEpisodeData}};
\code{\link{trakt.getFullShowData}};
\code{\link{trakt.seasons.season}};
\code{\link{trakt.seasons.summary}};
\code{\link{trakt.show.people}};
\code{\link{trakt.show.ratings}};
\code{\link{trakt.show.stats}};
\code{\link{trakt.shows.popular}};
\code{\link{trakt.shows.related}};
\code{\link{trakt.shows.trending}}
}
|
#Run cellSNP on cluster, for each lane
#cellSNP -s outs/possorted_genome_bam.bam -b outs/filtered_gene_bc_matrices/GRCh38/barcodes.tsv -o s3.cellsnp_out.vcf -R common_SNP_files/genome1K.commonSNPsLiftedOver.hg38.vcf.gz -p 10 --minMAF 0.1 --minCOUNT 20
library(cardelino)
library(Seurat, lib.loc="/Library/Frameworks/R.framework/Versions/3.5/Resources/library/v2")
cell_data <- load_cellSNP_vcf("orgs1-6.vcf.gz",
max_other_allele = NULL,
min_count = 0, min_MAF = 0)
summary(cell_data)
ids <- vireo(cell_data = cell_data, n_donor = 2)
table(ids$assigned$donor_id)
saveRDS(ids, "orgs1-6.vireo.ids.rds")
seur = readRDS("clusteredSeur.rds")
seur = SetAllIdent(seur, "orig.ident")
#org2 = SubsetData(seur, ident.use =2)
ids_new = ids$assigned
#rownames(ids_new) = paste0("2_",substr(ids$assigned$cell,1,nchar(ids$assigned$cell)-2))
#get cell names - merge vcf has a different way to solve cell name conflicts than Seurat does
cellnames = ids_new$cell
for (index in 1:length(cellnames)) {
cell = cellnames[index]
f = substr(cell,1,1)
if (f %in% c("A","G","C","T")) {
for (i in 1:6) {
new = paste0(i, "_", substr(cell,1,nchar(cell)-2))
if (paste0(gsub("_",":",new),"-1") %in% cellnames) { break }
if (new %in% seur@cell.names) {
cellnames[index] = new
break
}
}
} else {
new = paste0(f, "_", substr(cell,3,nchar(cell)-2))
if (new %in% seur@cell.names) {
cellnames[index] = new
}
}
}
rownames(ids_new) = cellnames
ids_new_sub = ids_new[seur@cell.names,] #there are 80k in vireo, only 63k in Seurat due to filtering
seur@meta.data$donor_id = NA
seur@meta.data[rownames(ids_new_sub),"donor_id"] = ids_new_sub$donor_id
save.image("seur.org1-6assignments.RData")
seur = SetAllIdent(seur, "donor_id")
pdf("vireo_org1-6_assignments.pdf")
TSNEPlot(seur, do.label=T)
dev.off()
line1 = SubsetData(seur, cells.use = seur@cell.names[seur@meta.data$donor_id=="donor1"])
saveRDS(line1, "line1.rds")
line2 = SubsetData(seur, cells.use = seur@cell.names[seur@meta.data$donor_id=="donor2"])
saveRDS(line2, "line2.rds")
| /demux_vireo.R | no_license | AmandaKedaigle/ASD-mutated-brain-organoids | R | false | false | 2,142 | r | #Run cellSNP on cluster, for each lane
#cellSNP -s outs/possorted_genome_bam.bam -b outs/filtered_gene_bc_matrices/GRCh38/barcodes.tsv -o s3.cellsnp_out.vcf -R common_SNP_files/genome1K.commonSNPsLiftedOver.hg38.vcf.gz -p 10 --minMAF 0.1 --minCOUNT 20
library(cardelino)
library(Seurat, lib.loc="/Library/Frameworks/R.framework/Versions/3.5/Resources/library/v2")
cell_data <- load_cellSNP_vcf("orgs1-6.vcf.gz",
max_other_allele = NULL,
min_count = 0, min_MAF = 0)
summary(cell_data)
ids <- vireo(cell_data = cell_data, n_donor = 2)
table(ids$assigned$donor_id)
saveRDS(ids, "orgs1-6.vireo.ids.rds")
seur = readRDS("clusteredSeur.rds")
seur = SetAllIdent(seur, "orig.ident")
#org2 = SubsetData(seur, ident.use =2)
ids_new = ids$assigned
#rownames(ids_new) = paste0("2_",substr(ids$assigned$cell,1,nchar(ids$assigned$cell)-2))
#get cell names - merge vcf has a different way to solve cell name conflicts than Seurat does
cellnames = ids_new$cell
for (index in 1:length(cellnames)) {
cell = cellnames[index]
f = substr(cell,1,1)
if (f %in% c("A","G","C","T")) {
for (i in 1:6) {
new = paste0(i, "_", substr(cell,1,nchar(cell)-2))
if (paste0(gsub("_",":",new),"-1") %in% cellnames) { break }
if (new %in% seur@cell.names) {
cellnames[index] = new
break
}
}
} else {
new = paste0(f, "_", substr(cell,3,nchar(cell)-2))
if (new %in% seur@cell.names) {
cellnames[index] = new
}
}
}
rownames(ids_new) = cellnames
ids_new_sub = ids_new[seur@cell.names,] #there are 80k in vireo, only 63k in Seurat due to filtering
seur@meta.data$donor_id = NA
seur@meta.data[rownames(ids_new_sub),"donor_id"] = ids_new_sub$donor_id
save.image("seur.org1-6assignments.RData")
seur = SetAllIdent(seur, "donor_id")
pdf("vireo_org1-6_assignments.pdf")
TSNEPlot(seur, do.label=T)
dev.off()
line1 = SubsetData(seur, cells.use = seur@cell.names[seur@meta.data$donor_id=="donor1"])
saveRDS(line1, "line1.rds")
line2 = SubsetData(seur, cells.use = seur@cell.names[seur@meta.data$donor_id=="donor2"])
saveRDS(line2, "line2.rds")
|
library(ape)
testtree <- read.tree("5765_0.txt")
unrooted_tr <- unroot(testtree)
write.tree(unrooted_tr, file="5765_0_unrooted.txt") | /codeml_files/newick_trees_processed/5765_0/rinput.R | no_license | DaniBoo/cyanobacteria_project | R | false | false | 135 | r | library(ape)
testtree <- read.tree("5765_0.txt")
unrooted_tr <- unroot(testtree)
write.tree(unrooted_tr, file="5765_0_unrooted.txt") |
# Generated by using Rcpp::compileAttributes() -> do not edit by hand
# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
cb <- function(m1, m2, m3, d, e) {
.Call('_trackdem_cb', PACKAGE = 'trackdem', m1, m2, m3, d, e)
}
getCoords <- function(m, d) {
.Call('_trackdem_getCoords', PACKAGE = 'trackdem', m, d)
}
muP <- function(m, id, cm1, cm2, cm3, d) {
.Call('_trackdem_muP', PACKAGE = 'trackdem', m, id, cm1, cm2, cm3, d)
}
sb2 <- function(m1, bg, d, e) {
.Call('_trackdem_sb2', PACKAGE = 'trackdem', m1, bg, d, e)
}
sb <- function(m1, bg, d, e) {
.Call('_trackdem_sb', PACKAGE = 'trackdem', m1, bg, d, e)
}
sdP <- function(m, id, cm1, cm2, cm3, d) {
.Call('_trackdem_sdP', PACKAGE = 'trackdem', m, id, cm1, cm2, cm3, d)
}
| /trackBees/src/trackdem_R_Commits/RcppExports.R | no_license | alvarovegahd/trackdem-single-particle-GUI | R | false | false | 759 | r | # Generated by using Rcpp::compileAttributes() -> do not edit by hand
# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
cb <- function(m1, m2, m3, d, e) {
.Call('_trackdem_cb', PACKAGE = 'trackdem', m1, m2, m3, d, e)
}
getCoords <- function(m, d) {
.Call('_trackdem_getCoords', PACKAGE = 'trackdem', m, d)
}
muP <- function(m, id, cm1, cm2, cm3, d) {
.Call('_trackdem_muP', PACKAGE = 'trackdem', m, id, cm1, cm2, cm3, d)
}
sb2 <- function(m1, bg, d, e) {
.Call('_trackdem_sb2', PACKAGE = 'trackdem', m1, bg, d, e)
}
sb <- function(m1, bg, d, e) {
.Call('_trackdem_sb', PACKAGE = 'trackdem', m1, bg, d, e)
}
sdP <- function(m, id, cm1, cm2, cm3, d) {
.Call('_trackdem_sdP', PACKAGE = 'trackdem', m, id, cm1, cm2, cm3, d)
}
|
library(ggplot2)
library(RColorBrewer)
library(reshape2)
measurements = read.csv("~/git/paper-tecs-2021-rt-queries-modelgen/tables/random-model-runtimes.csv", header=T)
maxvals <- data.frame(variable=levels(measurements$Query),
max=c(18.6,15,10,3.68))
histogram_exectimes <- ggplot(measurements, aes(Exectime)) +
geom_histogram(aes(y = ..count.., fill = ..count..), bins = 10) +
scale_fill_gradient(low= "#007BFF", high = "#89EBFF") +
geom_vline(data=maxvals, aes(xintercept = max), colour="red") +
xlab("Execution time (micro seconds)") +
ggtitle("Histogram of Execution Time") +
theme(plot.title = element_text(hjust = 0.5)) +
facet_wrap(~Query, scales = "free_y")+
theme(legend.position = "none")
histogram_exectimes
ggsave(file="~/git/paper-tecs-2021-rt-queries-modelgen/figs/histogram.pdf", plot = histogram_exectimes, width = 65, height = 65, units="mm")
| /tecs/plot_histogram.r | no_license | imbur/paper-utility-scripts | R | false | false | 903 | r | library(ggplot2)
library(RColorBrewer)
library(reshape2)
measurements = read.csv("~/git/paper-tecs-2021-rt-queries-modelgen/tables/random-model-runtimes.csv", header=T)
maxvals <- data.frame(variable=levels(measurements$Query),
max=c(18.6,15,10,3.68))
histogram_exectimes <- ggplot(measurements, aes(Exectime)) +
geom_histogram(aes(y = ..count.., fill = ..count..), bins = 10) +
scale_fill_gradient(low= "#007BFF", high = "#89EBFF") +
geom_vline(data=maxvals, aes(xintercept = max), colour="red") +
xlab("Execution time (micro seconds)") +
ggtitle("Histogram of Execution Time") +
theme(plot.title = element_text(hjust = 0.5)) +
facet_wrap(~Query, scales = "free_y")+
theme(legend.position = "none")
histogram_exectimes
ggsave(file="~/git/paper-tecs-2021-rt-queries-modelgen/figs/histogram.pdf", plot = histogram_exectimes, width = 65, height = 65, units="mm")
|
library(ape)
testtree <- read.tree("6401_0.txt")
unrooted_tr <- unroot(testtree)
write.tree(unrooted_tr, file="6401_0_unrooted.txt") | /codeml_files/newick_trees_processed/6401_0/rinput.R | no_license | DaniBoo/cyanobacteria_project | R | false | false | 135 | r | library(ape)
testtree <- read.tree("6401_0.txt")
unrooted_tr <- unroot(testtree)
write.tree(unrooted_tr, file="6401_0_unrooted.txt") |
#' Internal function for making molaR plot legends
#'
#' Function properly scales legends and prints them to the background of rgl
#' devices
#' @param expression it knows what to do...
#'
#'
#' molaR_bgplot()
molaR_bgplot <- function(expression){
filename <- tempfile(fileext = ".png")
png(filename = filename, width = 800, height = 800)
value <- expression
dev.off()
result <- bg3d(texture = filename, col = "white", lit = FALSE)
invisible(structure(result, value = value))
} | /molaR/R/molaR_bgplot.R | no_license | ingted/R-Examples | R | false | false | 511 | r | #' Internal function for making molaR plot legends
#'
#' Function properly scales legends and prints them to the background of rgl
#' devices
#' @param expression it knows what to do...
#'
#'
#' molaR_bgplot()
molaR_bgplot <- function(expression){
filename <- tempfile(fileext = ".png")
png(filename = filename, width = 800, height = 800)
value <- expression
dev.off()
result <- bg3d(texture = filename, col = "white", lit = FALSE)
invisible(structure(result, value = value))
} |
test_that("survData replicate is factor", {
data("propiconazole")
class(propiconazole$replicate)
expect_s3_class(survData(propiconazole), "data.frame")
expect_s3_class(survData(propiconazole)$replicate, "factor")
propiconazole$replicate = as.character(propiconazole$replicate)
expect_type(propiconazole$replicate, "character")
expect_s3_class(survData(propiconazole)$replicate, "factor")
expect_type(survData(propiconazole)$replicate, "integer")
data("cadmium1")
class(cadmium1$replicate)
expect_s3_class(survData(cadmium1)$replicate, "factor")
cadmium1$replicate = as.character(cadmium1$replicate)
expect_type(cadmium1$replicate, "character")
expect_s3_class(survData(cadmium1)$replicate, "factor")
expect_type(survData(cadmium1)$replicate, "integer")
})
| /tests/testthat/test-read.R | no_license | cran/morse | R | false | false | 802 | r | test_that("survData replicate is factor", {
data("propiconazole")
class(propiconazole$replicate)
expect_s3_class(survData(propiconazole), "data.frame")
expect_s3_class(survData(propiconazole)$replicate, "factor")
propiconazole$replicate = as.character(propiconazole$replicate)
expect_type(propiconazole$replicate, "character")
expect_s3_class(survData(propiconazole)$replicate, "factor")
expect_type(survData(propiconazole)$replicate, "integer")
data("cadmium1")
class(cadmium1$replicate)
expect_s3_class(survData(cadmium1)$replicate, "factor")
cadmium1$replicate = as.character(cadmium1$replicate)
expect_type(cadmium1$replicate, "character")
expect_s3_class(survData(cadmium1)$replicate, "factor")
expect_type(survData(cadmium1)$replicate, "integer")
})
|
# functions
calc_subpop_cases_base <- function(num_cases, risk_group){
subpop_cases_base <- num_cases * risk_group
return(subpop_cases_base)
}
calc_subpop_cases_intv <- function(cases_after_vax, risk_group){
subpop_cases_intv <- cases_after_vax * risk_group
return(subpop_cases_intv)
}
# total cost of vaccination program
calc_vaccination_cost <- function(vax_comp){
total_cost_vax = vax_cost * pop * risk_group * vax_comp
#total_cost_vax = vax_cost * pop * vax_comp
return(total_cost_vax)
}
# adjusted cost per health outcome
cost_cpi_outcome <- function(death, hosp, out, rest){
cost_per_death <- death * cpi
cost_per_hosp <- hosp * cpi
cost_per_out <- out * cpi
cost_per_rest <- rest * cpi
# returns cost per health outcome case
cost_outcome = c(cost_per_death, cost_per_hosp, cost_per_out, cost_per_rest)
return(cost_outcome)
}
# number of cases for each health outcome (base)
calc_num_outcomes_base <- function(p_death, p_hosp, p_out, p_rest){
subpop_cases_base = calc_subpop_cases_base(num_cases, risk_group)
num_death = p_death * subpop_cases_base
num_hosp = p_hosp * subpop_cases_base
num_out = p_out * subpop_cases_base
num_rest = p_rest * subpop_cases_base
num_outcome_total = num_death + num_hosp + num_out + num_rest
num_outcomes_base = c(num_death, num_hosp, num_out, num_rest)
#print(sprintf("base num: deaths = %f, hosps = %f, outps = %f, rest = %f",
# num_death, num_hosp, num_out, num_rest))
#print(sprintf("base total outcomes = %f", num_outcome_total))
return(num_outcomes_base)
}
# number of cases for each health outcome (intervention)
calc_num_outcomes_intv <- function(p_death, p_hosp, p_out, p_rest){
subpop_cases_intv = calc_subpop_cases_intv(cases_after_vax, risk_group)
num_death = p_death * subpop_cases_intv
num_hosp = p_hosp * subpop_cases_intv
num_out = p_out * subpop_cases_intv
num_rest = p_rest * subpop_cases_intv
num_outcome_total = num_death + num_hosp + num_out + num_rest
num_outcomes_intv = c(num_death, num_hosp, num_out, num_rest)
print(sprintf("intv num: deaths = %f, hosps = %f, outps = %f, rest = %f",
num_death, num_hosp, num_out, num_rest))
#print(sprintf("intv total outcomes = %f", num_outcome_total))
return(num_outcomes_intv)
}
# total costs of each health outcome (base)
calc_total_cost_base <- function(death, hosp, out, rest){
cost_outcome = cost_cpi_outcome(death, hosp, out, rest)
total_cost_death = cost_outcome[1] * num_outcomes_base[1]
total_cost_hosp = cost_outcome[2] * num_outcomes_base[2]
total_cost_out = cost_outcome[3] * num_outcomes_base[3]
total_cost_rest = cost_outcome[4] * num_outcomes_base[4]
total_costs = total_cost_death + total_cost_hosp + total_cost_out + total_cost_rest
#print(sprintf("base cc: deaths = %f, hosps = %f, outps = %f, rest = %f",
# total_cost_death, total_cost_hosp, total_cost_out, total_cost_rest))
#print(sprintf("base total clin costs = %f", total_costs))
return(c(total_cost_death, total_cost_hosp, total_cost_out, total_cost_rest, total_costs))
}
# total costs of each health outcome (intervention)
calc_total_cost_intv <- function(death, hosp, out, rest){
cost_outcome = cost_cpi_outcome(death, hosp, out, rest)
total_cost_death = cost_outcome[1] * num_outcomes_intv[1]
total_cost_hosp = cost_outcome[2] * num_outcomes_intv[2]
total_cost_out = cost_outcome[3] * num_outcomes_intv[3]
total_cost_rest = cost_outcome[4] * num_outcomes_intv[4]
total_costs = total_cost_death + total_cost_hosp + total_cost_out + total_cost_rest
print(sprintf("intv cc: deaths = %f, hosps = %f, outps = %f, rest = %f",
total_cost_death, total_cost_hosp, total_cost_out, total_cost_rest))
print(sprintf("intv total clin costs = %f", total_costs))
return(c(total_cost_death, total_cost_hosp, total_cost_out, total_cost_rest, total_costs))
}
# ICER CASES
calc_icer <- function(){
cases_averted <- b_cases - i_cases
net_costs_b = cc_base[5]+total_cost_vax_b
net_costs_i = cc_intv[5]+total_cost_vax_i
cost_diff = net_costs_b - net_costs_i
icer = cost_diff / cases_averted
print(sprintf("base vax costs = %f", total_cost_vax_b))
print(sprintf("intv vax costs = %f", total_cost_vax_i))
print(sprintf("intv net costs = %f", net_costs_i))
print(sprintf("cost difference = %f", cost_diff))
print(sprintf("cases averted = %f", cases_averted))
print(sprintf("icer = %s", icer))
return(c(cost_diff, cases_averted, icer, total_cost_vax_i))
}
# DEATHS
calc_deaths_b <- function(){
deaths_averted = num_outcomes_base[1]-num_outcomes_intv[1]
# death_cost_b = cc_base[1]
# death_cost_i = cc_intv[1]
# cost_diff_d = death_cost_b - death_cost_i
num_deaths_i = num_outcomes_intv[1]
net_costs_b = cc_base[5]+total_cost_vax_b
net_costs_i = cc_intv[5]+total_cost_vax_i
cost_diff_d = net_costs_b - net_costs_i
cost_per_death_averted = cost_diff_d / deaths_averted
print(sprintf("deaths averted = %f", deaths_averted))
print(sprintf("cost per death averted = %f", cost_per_death_averted))
return(c(deaths_averted, cost_per_death_averted, num_deaths_i))
}
### for results
summarize <- function(){
total_cost_vax_b <- calc_vaccination_cost(vax_comp_b)
total_cost_vax_i <- calc_vaccination_cost(vax_comp_i)
costs <- cost_cpi_outcome(r_cost[1], r_cost[2], r_cost[3], r_cost[4])
# base
b_cases <- calc_subpop_cases_base(num_cases, risk_group)
num_outcomes_base <- calc_num_outcomes_base(prob[1], prob[2], prob[3], prob[4])
cc_base <- calc_total_cost_base(r_cost[1],r_cost[2],r_cost[3],r_cost[4])
# intv
i_cases <- calc_subpop_cases_intv(cases_after_vax, risk_group)
num_outcomes_intv <- calc_num_outcomes_intv(prob[1], prob[2], prob[3], prob[4])
cc_intv <- calc_total_cost_intv(r_cost[1],r_cost[2],r_cost[3],r_cost[4])
print(sprintf("total vax costs = %f", total_cost_vax_i))
print(sprintf("base cases = %f", b_cases))
print(sprintf("intv cases = %f", i_cases))
}
# DALY
# calc_daly <- function(){
# dalys_averted =
# net_costs_b = cc_base[5]+total_cost_vax_b
# net_costs_i = cc_intv[5]+total_cost_vax_i
# cost_diff = net_costs_b - net_costs_i
# daly = cost_diff / dalys_averted
# return(daly)
# }
| /code/functions.R | no_license | gloriakang/economic-influenza | R | false | false | 6,215 | r | # functions
calc_subpop_cases_base <- function(num_cases, risk_group){
subpop_cases_base <- num_cases * risk_group
return(subpop_cases_base)
}
calc_subpop_cases_intv <- function(cases_after_vax, risk_group){
subpop_cases_intv <- cases_after_vax * risk_group
return(subpop_cases_intv)
}
# total cost of vaccination program
calc_vaccination_cost <- function(vax_comp){
total_cost_vax = vax_cost * pop * risk_group * vax_comp
#total_cost_vax = vax_cost * pop * vax_comp
return(total_cost_vax)
}
# adjusted cost per health outcome
cost_cpi_outcome <- function(death, hosp, out, rest){
cost_per_death <- death * cpi
cost_per_hosp <- hosp * cpi
cost_per_out <- out * cpi
cost_per_rest <- rest * cpi
# returns cost per health outcome case
cost_outcome = c(cost_per_death, cost_per_hosp, cost_per_out, cost_per_rest)
return(cost_outcome)
}
# number of cases for each health outcome (base)
calc_num_outcomes_base <- function(p_death, p_hosp, p_out, p_rest){
subpop_cases_base = calc_subpop_cases_base(num_cases, risk_group)
num_death = p_death * subpop_cases_base
num_hosp = p_hosp * subpop_cases_base
num_out = p_out * subpop_cases_base
num_rest = p_rest * subpop_cases_base
num_outcome_total = num_death + num_hosp + num_out + num_rest
num_outcomes_base = c(num_death, num_hosp, num_out, num_rest)
#print(sprintf("base num: deaths = %f, hosps = %f, outps = %f, rest = %f",
# num_death, num_hosp, num_out, num_rest))
#print(sprintf("base total outcomes = %f", num_outcome_total))
return(num_outcomes_base)
}
# number of cases for each health outcome (intervention)
calc_num_outcomes_intv <- function(p_death, p_hosp, p_out, p_rest){
subpop_cases_intv = calc_subpop_cases_intv(cases_after_vax, risk_group)
num_death = p_death * subpop_cases_intv
num_hosp = p_hosp * subpop_cases_intv
num_out = p_out * subpop_cases_intv
num_rest = p_rest * subpop_cases_intv
num_outcome_total = num_death + num_hosp + num_out + num_rest
num_outcomes_intv = c(num_death, num_hosp, num_out, num_rest)
print(sprintf("intv num: deaths = %f, hosps = %f, outps = %f, rest = %f",
num_death, num_hosp, num_out, num_rest))
#print(sprintf("intv total outcomes = %f", num_outcome_total))
return(num_outcomes_intv)
}
# total costs of each health outcome (base)
calc_total_cost_base <- function(death, hosp, out, rest){
cost_outcome = cost_cpi_outcome(death, hosp, out, rest)
total_cost_death = cost_outcome[1] * num_outcomes_base[1]
total_cost_hosp = cost_outcome[2] * num_outcomes_base[2]
total_cost_out = cost_outcome[3] * num_outcomes_base[3]
total_cost_rest = cost_outcome[4] * num_outcomes_base[4]
total_costs = total_cost_death + total_cost_hosp + total_cost_out + total_cost_rest
#print(sprintf("base cc: deaths = %f, hosps = %f, outps = %f, rest = %f",
# total_cost_death, total_cost_hosp, total_cost_out, total_cost_rest))
#print(sprintf("base total clin costs = %f", total_costs))
return(c(total_cost_death, total_cost_hosp, total_cost_out, total_cost_rest, total_costs))
}
# total costs of each health outcome (intervention)
calc_total_cost_intv <- function(death, hosp, out, rest){
cost_outcome = cost_cpi_outcome(death, hosp, out, rest)
total_cost_death = cost_outcome[1] * num_outcomes_intv[1]
total_cost_hosp = cost_outcome[2] * num_outcomes_intv[2]
total_cost_out = cost_outcome[3] * num_outcomes_intv[3]
total_cost_rest = cost_outcome[4] * num_outcomes_intv[4]
total_costs = total_cost_death + total_cost_hosp + total_cost_out + total_cost_rest
print(sprintf("intv cc: deaths = %f, hosps = %f, outps = %f, rest = %f",
total_cost_death, total_cost_hosp, total_cost_out, total_cost_rest))
print(sprintf("intv total clin costs = %f", total_costs))
return(c(total_cost_death, total_cost_hosp, total_cost_out, total_cost_rest, total_costs))
}
# ICER CASES
calc_icer <- function(){
cases_averted <- b_cases - i_cases
net_costs_b = cc_base[5]+total_cost_vax_b
net_costs_i = cc_intv[5]+total_cost_vax_i
cost_diff = net_costs_b - net_costs_i
icer = cost_diff / cases_averted
print(sprintf("base vax costs = %f", total_cost_vax_b))
print(sprintf("intv vax costs = %f", total_cost_vax_i))
print(sprintf("intv net costs = %f", net_costs_i))
print(sprintf("cost difference = %f", cost_diff))
print(sprintf("cases averted = %f", cases_averted))
print(sprintf("icer = %s", icer))
return(c(cost_diff, cases_averted, icer, total_cost_vax_i))
}
# DEATHS
calc_deaths_b <- function(){
deaths_averted = num_outcomes_base[1]-num_outcomes_intv[1]
# death_cost_b = cc_base[1]
# death_cost_i = cc_intv[1]
# cost_diff_d = death_cost_b - death_cost_i
num_deaths_i = num_outcomes_intv[1]
net_costs_b = cc_base[5]+total_cost_vax_b
net_costs_i = cc_intv[5]+total_cost_vax_i
cost_diff_d = net_costs_b - net_costs_i
cost_per_death_averted = cost_diff_d / deaths_averted
print(sprintf("deaths averted = %f", deaths_averted))
print(sprintf("cost per death averted = %f", cost_per_death_averted))
return(c(deaths_averted, cost_per_death_averted, num_deaths_i))
}
### for results
summarize <- function(){
total_cost_vax_b <- calc_vaccination_cost(vax_comp_b)
total_cost_vax_i <- calc_vaccination_cost(vax_comp_i)
costs <- cost_cpi_outcome(r_cost[1], r_cost[2], r_cost[3], r_cost[4])
# base
b_cases <- calc_subpop_cases_base(num_cases, risk_group)
num_outcomes_base <- calc_num_outcomes_base(prob[1], prob[2], prob[3], prob[4])
cc_base <- calc_total_cost_base(r_cost[1],r_cost[2],r_cost[3],r_cost[4])
# intv
i_cases <- calc_subpop_cases_intv(cases_after_vax, risk_group)
num_outcomes_intv <- calc_num_outcomes_intv(prob[1], prob[2], prob[3], prob[4])
cc_intv <- calc_total_cost_intv(r_cost[1],r_cost[2],r_cost[3],r_cost[4])
print(sprintf("total vax costs = %f", total_cost_vax_i))
print(sprintf("base cases = %f", b_cases))
print(sprintf("intv cases = %f", i_cases))
}
# DALY
# calc_daly <- function(){
# dalys_averted =
# net_costs_b = cc_base[5]+total_cost_vax_b
# net_costs_i = cc_intv[5]+total_cost_vax_i
# cost_diff = net_costs_b - net_costs_i
# daly = cost_diff / dalys_averted
# return(daly)
# }
|
context("Get Area")
test_that("input cannot be in lonlat crs",{
r.crs <- raster(nrows=10, ncols=10)
expect_error(getArea(r.crs), "Input raster has a longitude/latitude CRS.\nPlease reproject to a projected coordinate system")
})
test_that("accepts different input rasters", {
# Dummy rasters for testing
r <- raster(nrows=10, ncols=10)
crs(r) <- "+proj=utm +zone=55 +south +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0"
r.bin <- r
values(r.bin) <- 1
r.multiple <- r
values(r.multiple) <- rep(c(1:10), 10)
expect_equal(getArea(r.bin), 0.1296)
expect_warning(getArea(r.multiple), "The input raster is not binary, counting ALL non NA cells\n")
expect_equal(getArea(r.multiple, 1), 0.01296)
})
test_that("output is a single value", {
# Dummy raster
r <- raster(nrows=10, ncols=10)
crs(r) <- "+proj=utm +zone=55 +south +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0"
values(r) <- rep(c(1, NA), 50)
expect_equal(length(getArea(r)), 1)
})
test_that("accepts SpatialPolygons", {
# Dummy rectangle
x1 = 0
x2 = 1000
y1 = 0
y2 = 1000
my_polygon = Polygon(cbind(c(x1,x1,x2,x2,x1),c(y1,y2,y2,y1,y1)))
my_polygons = Polygons(list(my_polygon), ID = "A")
dummy_polygon = SpatialPolygons(list(my_polygons))
expect_equal(getArea(dummy_polygon), 1)
})
context("Change functions")
test_that("decline stats work", {
# Dummy areas and years
A.t1 <- 100
A.t2 <- 50
year.t1 <- 2010
year.t2 <- 2015
dummy.decline.df <- getDeclineStats(A.t1, A.t2, year.t1, year.t2,
methods = c('ARD', 'PRD', 'ARC'))
expect_equal(dummy.decline.df$ARD, 10)
expect_equal(dummy.decline.df$PRD, 12.94494, tolerance=1e-5)
expect_equal(dummy.decline.df$ARC, -13.86294, tolerance=1e-5)
expect_error(getDeclineStats(A.t1, A.t2, year.t1, year.t2))
})
| /tests/testthat/test_areaAndChange.R | no_license | dondealban/redlistr | R | false | false | 1,843 | r | context("Get Area")
test_that("input cannot be in lonlat crs",{
r.crs <- raster(nrows=10, ncols=10)
expect_error(getArea(r.crs), "Input raster has a longitude/latitude CRS.\nPlease reproject to a projected coordinate system")
})
test_that("accepts different input rasters", {
# Dummy rasters for testing
r <- raster(nrows=10, ncols=10)
crs(r) <- "+proj=utm +zone=55 +south +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0"
r.bin <- r
values(r.bin) <- 1
r.multiple <- r
values(r.multiple) <- rep(c(1:10), 10)
expect_equal(getArea(r.bin), 0.1296)
expect_warning(getArea(r.multiple), "The input raster is not binary, counting ALL non NA cells\n")
expect_equal(getArea(r.multiple, 1), 0.01296)
})
test_that("output is a single value", {
# Dummy raster
r <- raster(nrows=10, ncols=10)
crs(r) <- "+proj=utm +zone=55 +south +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0"
values(r) <- rep(c(1, NA), 50)
expect_equal(length(getArea(r)), 1)
})
test_that("accepts SpatialPolygons", {
# Dummy rectangle
x1 = 0
x2 = 1000
y1 = 0
y2 = 1000
my_polygon = Polygon(cbind(c(x1,x1,x2,x2,x1),c(y1,y2,y2,y1,y1)))
my_polygons = Polygons(list(my_polygon), ID = "A")
dummy_polygon = SpatialPolygons(list(my_polygons))
expect_equal(getArea(dummy_polygon), 1)
})
context("Change functions")
test_that("decline stats work", {
# Dummy areas and years
A.t1 <- 100
A.t2 <- 50
year.t1 <- 2010
year.t2 <- 2015
dummy.decline.df <- getDeclineStats(A.t1, A.t2, year.t1, year.t2,
methods = c('ARD', 'PRD', 'ARC'))
expect_equal(dummy.decline.df$ARD, 10)
expect_equal(dummy.decline.df$PRD, 12.94494, tolerance=1e-5)
expect_equal(dummy.decline.df$ARC, -13.86294, tolerance=1e-5)
expect_error(getDeclineStats(A.t1, A.t2, year.t1, year.t2))
})
|
rankhospital <- function(state, outcome, num="best") {
## Read outcome data
data<-read.csv("outcome-of-care-measures.csv", colClasses = "character")
if(outcome=="heart attack"){x<-11}
if(outcome=="heart failure"){x<-17}
if(outcome=="pneumonia"){x<-23}
data<-data[which(data$State==state),c(2,7,x)]
data[,3]<-as.numeric(data[,3])
valid<-!is.na(data[,c(3)])
data<-data[valid,]
data[,4]<-numeric()
colnames(data)<-c("Hospital.Name","State","Rate","Rank")
## Check that state and outcome are valid
validOutcome = c("heart attack","heart failure","pneumonia")
if (!outcome %in% validOutcome) { stop("invalid outcome")}
validState = sort(unique(data[,2]))
if (!state %in% validState) stop("invalid state")
## Return hospital name in that state with the given rank
data<-data[order(data$Rate,data$Hospital.Name),]
data[,4]<-1:nrow(data)
if(num=="best"){num<-1}
if(num=="worst"){num<-nrow(data)}
final<-data[which(data$Rank==num),1]
if(num>nrow(data)){final<-NA}
## 30-day death rate
final
} | /rankhospital.R | no_license | lifangya/R-programming-assignment-3 | R | false | false | 1,059 | r | rankhospital <- function(state, outcome, num="best") {
## Read outcome data
data<-read.csv("outcome-of-care-measures.csv", colClasses = "character")
if(outcome=="heart attack"){x<-11}
if(outcome=="heart failure"){x<-17}
if(outcome=="pneumonia"){x<-23}
data<-data[which(data$State==state),c(2,7,x)]
data[,3]<-as.numeric(data[,3])
valid<-!is.na(data[,c(3)])
data<-data[valid,]
data[,4]<-numeric()
colnames(data)<-c("Hospital.Name","State","Rate","Rank")
## Check that state and outcome are valid
validOutcome = c("heart attack","heart failure","pneumonia")
if (!outcome %in% validOutcome) { stop("invalid outcome")}
validState = sort(unique(data[,2]))
if (!state %in% validState) stop("invalid state")
## Return hospital name in that state with the given rank
data<-data[order(data$Rate,data$Hospital.Name),]
data[,4]<-1:nrow(data)
if(num=="best"){num<-1}
if(num=="worst"){num<-nrow(data)}
final<-data[which(data$Rank==num),1]
if(num>nrow(data)){final<-NA}
## 30-day death rate
final
} |
source('scripts/input.R', encoding = 'UTF-8')
library(tableone)
tab1.base <- CreateTableOne(data = dados[, .(
Sexo,
Idade,
Escolaridade,
`Estado civil`,
Trabalho,
Evolução,
Tratamento,
ASC,
Fototipo,
`Casos na família`,
Classificação,
`Tempo de evolução`
)])
tab1.escores <- CreateTableOne(data = dados[, .(
`Escore DLQI - Máx 30`,
DLQI,
`Escore VitiQoL - Máx 90`)])
tab1.base.df <- print(tab1.base, showAllLevels = TRUE, printToggle = FALSE)
tab1.escores.df <- print(tab1.escores, showAllLevels = TRUE, nonnormal = TRUE, printToggle = FALSE)
# protótipos obsoletos ----------------------------------------------------
# ## Tabela 1 completa
#
# tab1 <- rbind(tab1.base.df, tab1.escores.df)
# tab1 <- tab1[-39, ] # remover segunda ocorrência de "n = 131"
| /scripts/descritiva.R | no_license | philsf-biostat/SAR-2019-002-FC | R | false | false | 806 | r | source('scripts/input.R', encoding = 'UTF-8')
library(tableone)
tab1.base <- CreateTableOne(data = dados[, .(
Sexo,
Idade,
Escolaridade,
`Estado civil`,
Trabalho,
Evolução,
Tratamento,
ASC,
Fototipo,
`Casos na família`,
Classificação,
`Tempo de evolução`
)])
tab1.escores <- CreateTableOne(data = dados[, .(
`Escore DLQI - Máx 30`,
DLQI,
`Escore VitiQoL - Máx 90`)])
tab1.base.df <- print(tab1.base, showAllLevels = TRUE, printToggle = FALSE)
tab1.escores.df <- print(tab1.escores, showAllLevels = TRUE, nonnormal = TRUE, printToggle = FALSE)
# protótipos obsoletos ----------------------------------------------------
# ## Tabela 1 completa
#
# tab1 <- rbind(tab1.base.df, tab1.escores.df)
# tab1 <- tab1[-39, ] # remover segunda ocorrência de "n = 131"
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/helpers.R
\name{mkmod}
\alias{mkmod}
\title{helper: create a model based on generic terms}
\usage{
mkmod(coef, terms, start = 1, catmod = FALSE)
}
\arguments{
\item{coef}{ipsum}
\item{terms}{ipsum}
\item{start}{ipsum}
\item{catmod}{ipsum}
}
\description{
not used by user, typically
}
\details{
(mkmodidx probably better)
}
\examples{
runif(1)
}
| /man/mkmod.Rd | no_license | alexpkeil1/wellwise | R | false | true | 427 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/helpers.R
\name{mkmod}
\alias{mkmod}
\title{helper: create a model based on generic terms}
\usage{
mkmod(coef, terms, start = 1, catmod = FALSE)
}
\arguments{
\item{coef}{ipsum}
\item{terms}{ipsum}
\item{start}{ipsum}
\item{catmod}{ipsum}
}
\description{
not used by user, typically
}
\details{
(mkmodidx probably better)
}
\examples{
runif(1)
}
|
#Load the data
Scat<-read.csv(file="DNAid.csv",sep=",",header=TRUE)
#Subset data to exclude mixed, missing and spotted skunk
Scat2<-subset(Scat, Species!="spotted skunk")
Scat2<-subset(Scat2, Species!="mixed")
Scat2<-subset(Scat2, Species!="failed")
Scat2<-subset(Scat2,select=-c(18:19)) #drop out the isotope data for now
Scat2<-subset(Scat2,select=-c(13)) #drop out the C:N ratio for now
Scat2<-subset(Scat2,select=-c(1,3:4)) #drop out the sample id, month and site columns for now
#Reset the Species variable such that it doesn't retain the removed subset labels
Scat2$Species<-factor(Scat2$Species)
#Before we can do any modeling, it's important that any categorical variables are seen as factors, not as numeric variables. check the encoding with:
str(Scat2) #if categorical variables are not factors, use as.factor() to change.
Scat2$Age<-factor(Scat2$Age)
#Now we'll try building a conditional inference tree using the package "Party".
library(party)
speciesID<-ctree(Scat2$Species ~ ., data = Scat2)
speciesID #outputs a description of the model
plot(speciesID) #shows the tree
#to test the fit of the model, plot a table of the prediction errors
table(predict(speciesID), Scat2$Species)
#Estimated class probabilities
tr.pred<-predict(speciesID, type="prob")
tr.pred
## what if we change the tree control type to "MonteCarlo"?
Scat3<-na.omit(Scat2)
speciesID<-ctree(Scat3$Species ~ ., data = Scat3, controls = ctree_control(testtype = c("MonteCarlo"), nresample=9999))
plot(speciesID)
table(predict(speciesID), Scat3$Species)
##Now change the control type to "Bonferroni"
speciesID<-ctree(Scat2$Species ~ ., data = Scat2, controls = ctree_control(testtype = c("Univariate"), mincriterion = 0.95, minbucket = 11, savesplitstats = TRUE))
plot(speciesID)
table(predict(speciesID), Scat2$Species)
#Now let's try creating a Random Forest Model
#start by checking out the data structure, be sure that categorical variables are listed as factors and binary variables are listed as integers.
str(Scat2)
#Then split the data into a training and a test set
ind<-sample(2,nrow(Scat3), replace=TRUE, prob=c(0.7,0.3))
trainData<-Scat3[ind==1,]
testData<-Scat3[ind==2,]
#Generate random forest learning trees
library(randomForest)
set.seed(1385)
Scat_rf<-randomForest(Species~.,data=trainData,ntree=1000,proximity=TRUE)
table(predict(Scat_rf),trainData$Species)
print(Scat_rf)
attributes(Scat_rf)
plot(Scat_rf)
importance(Scat_rf)
varImpPlot(Scat_rf)
#extract the predicted classes from the random forest model
rfTrainPred <- predict(Scat_rf, trainData, type = "prob")
head(rfTrainPred)
trainData$RFprobCoy <- rfTrainPred[,"coyote"]
trainData$RFprobBob <- rfTrainPred[,"bobcat"]
trainData$RFprobFox <- rfTrainPred[,"gray fox"]
trainData$RFclass <- predict(Scat_rf, trainData)
#extract the confusion matrix
confusionMatrix(data = trainData$RFclass, reference = trainData$Species)
#Test the built random forest for the test data
ScatPred<-predict(Scat_rf,newdata=testData)
table(ScatPred, testData$Species)
plot(margin(Scat_rf,testData$Species))
outlier(Scat_rf)
plot(outlier(Scat_rf), type="h",
col=c("red", "green", "blue")[as.numeric(Scat$Species)])
#extract the predicted classes from the random forest model
rfTestPred <- predict(Scat_rf, testData, type = "prob")
head(rfTestPred)
testData$RFprobCoy <- rfTestPred[,"coyote"]
testData$RFprobBob <- rfTestPred[,"bobcat"]
testData$RFprobFox <- rfTestPred[,"gray fox"]
testData$RFclass <- predict(Scat_rf, testData)
#extract the confusion matrix
confusionMatrix(data = testData$RFclass, reference = testData$Species)
#Plot probability distributions of scat ids by species
library(ggplot2)
require(gridExtra)
bobcat<-testData$RFprobBob
coyote<-testData$RFprobCoy
grayfox<-testData$RFprobFox
predictions<-data.frame(testData$Species,bobcat,coyote,grayfox)
colnames(predictions)<-c("Species","Bobcat","Coyote","Fox")
plot1<-ggplot(predictions, aes(x=Bobcat, fill=Species)) + geom_density(alpha=0.2) + xlab("Probability - Bobcat")
plot2<-ggplot(predictions, aes(x=Coyote, fill=Species)) + geom_density(alpha=0.2) + xlab("Probability - Coyote")
plot3<-ggplot(predictions, aes(x=Fox, fill=Species)) + geom_density(alpha=0.2) + xlab("Probability - Gray Fox")
grid.arrange(plot1,plot2,plot3, ncol=3)
###Try the same thing, but using a different R package:
### This is the same type of model, just using a different package to execute it.
#begin by setting the controls for the random forest
data.controls<-cforest_unbiased(ntree=2000, mtry=3.5) #the ntree argument controls the overall number of trees in the forest, the mtry argument controls the number of randomly preselected predictor variables for each split. The square root of the number of variables is the suggested default value for mtry in the literature, we have 9 variables, so 3 is an appropriate choice.
#set a random seed for the forest run, any random number will do:
set.seed(894)
mycforest<-cforest(Species~., data=trainData, controls=data.controls, savesplitstats=TRUE)
mycforest
#Look at some trees in the forest (code from Strobl et al. 2009 supplementary material)
xgr <- 2
grid.newpage()
cgrid <- viewport(layout = grid.layout(xgr, xgr), name = "cgrid")
pushViewport(cgrid)
for (j in 1:xgr) {
pushViewport(viewport(layout.pos.col = i, layout.pos.row = j))
tr <- party:::prettytree(mycforest@ensemble[[i + j * xgr]], names(mycforest@data@get("input")))
plot(new("BinaryTree", tree = tr, data = mycforest@data, responses = mycforest@responses), newpage = FALSE, pop = FALSE, type="simple")
upViewport()
}
#compute and plot the permutation importance of each predictor variable
set.seed(560)
myvarimp<-varimp(mycforest)
myvarimp
dotchart(sort(myvarimp))
#conditional = true
myvarimp<-varimp(mycforest, conditional=TRUE)
dotchart(sort(myvarimp))
###
| /RandomForest.R | no_license | rebreid/Scat-ID-Models | R | false | false | 5,799 | r | #Load the data
Scat<-read.csv(file="DNAid.csv",sep=",",header=TRUE)
#Subset data to exclude mixed, missing and spotted skunk
Scat2<-subset(Scat, Species!="spotted skunk")
Scat2<-subset(Scat2, Species!="mixed")
Scat2<-subset(Scat2, Species!="failed")
Scat2<-subset(Scat2,select=-c(18:19)) #drop out the isotope data for now
Scat2<-subset(Scat2,select=-c(13)) #drop out the C:N ratio for now
Scat2<-subset(Scat2,select=-c(1,3:4)) #drop out the sample id, month and site columns for now
#Reset the Species variable such that it doesn't retain the removed subset labels
Scat2$Species<-factor(Scat2$Species)
#Before we can do any modeling, it's important that any categorical variables are seen as factors, not as numeric variables. check the encoding with:
str(Scat2) #if categorical variables are not factors, use as.factor() to change.
Scat2$Age<-factor(Scat2$Age)
#Now we'll try building a conditional inference tree using the package "Party".
library(party)
speciesID<-ctree(Scat2$Species ~ ., data = Scat2)
speciesID #outputs a description of the model
plot(speciesID) #shows the tree
#to test the fit of the model, plot a table of the prediction errors
table(predict(speciesID), Scat2$Species)
#Estimated class probabilities
tr.pred<-predict(speciesID, type="prob")
tr.pred
## what if we change the tree control type to "MonteCarlo"?
Scat3<-na.omit(Scat2)
speciesID<-ctree(Scat3$Species ~ ., data = Scat3, controls = ctree_control(testtype = c("MonteCarlo"), nresample=9999))
plot(speciesID)
table(predict(speciesID), Scat3$Species)
##Now change the control type to "Bonferroni"
speciesID<-ctree(Scat2$Species ~ ., data = Scat2, controls = ctree_control(testtype = c("Univariate"), mincriterion = 0.95, minbucket = 11, savesplitstats = TRUE))
plot(speciesID)
table(predict(speciesID), Scat2$Species)
#Now let's try creating a Random Forest Model
#start by checking out the data structure, be sure that categorical variables are listed as factors and binary variables are listed as integers.
str(Scat2)
#Then split the data into a training and a test set
ind<-sample(2,nrow(Scat3), replace=TRUE, prob=c(0.7,0.3))
trainData<-Scat3[ind==1,]
testData<-Scat3[ind==2,]
#Generate random forest learning trees
library(randomForest)
set.seed(1385)
Scat_rf<-randomForest(Species~.,data=trainData,ntree=1000,proximity=TRUE)
table(predict(Scat_rf),trainData$Species)
print(Scat_rf)
attributes(Scat_rf)
plot(Scat_rf)
importance(Scat_rf)
varImpPlot(Scat_rf)
#extract the predicted classes from the random forest model
rfTrainPred <- predict(Scat_rf, trainData, type = "prob")
head(rfTrainPred)
trainData$RFprobCoy <- rfTrainPred[,"coyote"]
trainData$RFprobBob <- rfTrainPred[,"bobcat"]
trainData$RFprobFox <- rfTrainPred[,"gray fox"]
trainData$RFclass <- predict(Scat_rf, trainData)
#extract the confusion matrix
confusionMatrix(data = trainData$RFclass, reference = trainData$Species)
#Test the built random forest for the test data
ScatPred<-predict(Scat_rf,newdata=testData)
table(ScatPred, testData$Species)
plot(margin(Scat_rf,testData$Species))
outlier(Scat_rf)
plot(outlier(Scat_rf), type="h",
col=c("red", "green", "blue")[as.numeric(Scat$Species)])
#extract the predicted classes from the random forest model
rfTestPred <- predict(Scat_rf, testData, type = "prob")
head(rfTestPred)
testData$RFprobCoy <- rfTestPred[,"coyote"]
testData$RFprobBob <- rfTestPred[,"bobcat"]
testData$RFprobFox <- rfTestPred[,"gray fox"]
testData$RFclass <- predict(Scat_rf, testData)
#extract the confusion matrix
confusionMatrix(data = testData$RFclass, reference = testData$Species)
#Plot probability distributions of scat ids by species
library(ggplot2)
require(gridExtra)
bobcat<-testData$RFprobBob
coyote<-testData$RFprobCoy
grayfox<-testData$RFprobFox
predictions<-data.frame(testData$Species,bobcat,coyote,grayfox)
colnames(predictions)<-c("Species","Bobcat","Coyote","Fox")
plot1<-ggplot(predictions, aes(x=Bobcat, fill=Species)) + geom_density(alpha=0.2) + xlab("Probability - Bobcat")
plot2<-ggplot(predictions, aes(x=Coyote, fill=Species)) + geom_density(alpha=0.2) + xlab("Probability - Coyote")
plot3<-ggplot(predictions, aes(x=Fox, fill=Species)) + geom_density(alpha=0.2) + xlab("Probability - Gray Fox")
grid.arrange(plot1,plot2,plot3, ncol=3)
###Try the same thing, but using a different R package:
### This is the same type of model, just using a different package to execute it.
#begin by setting the controls for the random forest
data.controls<-cforest_unbiased(ntree=2000, mtry=3.5) #the ntree argument controls the overall number of trees in the forest, the mtry argument controls the number of randomly preselected predictor variables for each split. The square root of the number of variables is the suggested default value for mtry in the literature, we have 9 variables, so 3 is an appropriate choice.
#set a random seed for the forest run, any random number will do:
set.seed(894)
mycforest<-cforest(Species~., data=trainData, controls=data.controls, savesplitstats=TRUE)
mycforest
#Look at some trees in the forest (code from Strobl et al. 2009 supplementary material)
xgr <- 2
grid.newpage()
cgrid <- viewport(layout = grid.layout(xgr, xgr), name = "cgrid")
pushViewport(cgrid)
for (j in 1:xgr) {
pushViewport(viewport(layout.pos.col = i, layout.pos.row = j))
tr <- party:::prettytree(mycforest@ensemble[[i + j * xgr]], names(mycforest@data@get("input")))
plot(new("BinaryTree", tree = tr, data = mycforest@data, responses = mycforest@responses), newpage = FALSE, pop = FALSE, type="simple")
upViewport()
}
#compute and plot the permutation importance of each predictor variable
set.seed(560)
myvarimp<-varimp(mycforest)
myvarimp
dotchart(sort(myvarimp))
#conditional = true
myvarimp<-varimp(mycforest, conditional=TRUE)
dotchart(sort(myvarimp))
###
|
#####################################################
# Figure 4.8. Sediment mineralization model
#####################################################
#General settings
library(deSolve)
# Function to calculate model cost
costf <- function(params){
with(as.list(params), {
Carbon <- meanDepo * mult / k
outtimes <- as.vector(oxcon$time)
outmin <- ode(Carbon, outtimes, minmod, params)
sqdiff <- (outmin[,3] - oxcon$cons)^2
sum(sqdiff)
})
}
# Function to calculate derivative of state variable
minmod <- function(t,Carbon,parameters){
with (as.list(c(Carbon,parameters)),{
minrate <- k*Carbon
Depo <- approx(Flux[,1],Flux[,2], xout=t)$y
dCarbon <- mult*Depo - minrate
list(dCarbon,minrate)
})
}
# initial par estimates
# minimal parameter values
# maximal parameter values
# function to minimise
# nr elements in population
# number of iterations
# number of points in centroid
# relative variation upon stopping
pricefit <- function (par, minpar=rep(-1e8,length(par)),
maxpar=rep(1e8,length(par)), func, npop=max(5*length(par),50),
numiter=10000, centroid = 3, varleft = 1e-8, ...){
# Initialization
cost <- function (par) func(par,...)
npar <- length(par)
tiny <- 1e-8
varleft <- max(tiny,varleft)
populationpar <- matrix(nrow=npop,ncol=npar,byrow=TRUE,
data= minpar+runif(npar*npop)*rep((maxpar-minpar),npop))
colnames(populationpar)<-names(par)
populationpar[1,]<-par
populationcost <- apply(populationpar,FUN=cost,MARGIN=1)
iworst <- which.max(populationcost)
worstcost <- populationcost[iworst]
# Hybridization phase
iter<-0
while(iter < numiter &
(max(populationcost)-min(populationcost)) > (min(populationcost)*varleft)){
iter<-iter+1
selectpar <- sample(1:npop,size=centroid)
# for cross-fertilization
mirrorpar <- sample(1:npop,size=1)
# for mirroring
newpar <- colMeans(populationpar[selectpar,]) # centroid
newpar <- 2*newpar - populationpar[mirrorpar,] # mirroring
newpar <- pmin( pmax(newpar,minpar) ,maxpar)
newcost <- cost(newpar)
if(newcost < worstcost){
populationcost[iworst] <-newcost
populationpar [iworst,]<-newpar
iworst <- which.max(populationcost) # new worst member
worstcost <- populationcost[iworst]
}
} # end j loop
ibest <- which.min(populationcost)
bestpar <- populationpar[ibest,]
bestcost <- populationcost[ibest]
return (list(par = bestpar, cost = bestcost,
poppar = populationpar, popcost=populationcost))
}
# Define problem and data
Flux <- matrix(ncol=2,byrow=TRUE,data=c(
1,
0.654, 11, 0.167, 21, 0.060, 41, 0.070,
73,
0.277, 83, 0.186, 93, 0.140,103, 0.255,
113,
0.231,123, 0.309,133, 1.127,143, 1.923,
153,
1.091,163, 1.001,173, 1.691,183, 1.404,
194,
1.226,204, 0.767,214, 0.893,224, 0.737,
234,
0.772,244, 0.726,254, 0.624,264, 0.439,
274,
0.168,284, 0.280,294, 0.202,304, 0.193,
315,
0.286,325, 0.599,335, 1.889,345, 0.996,
355,
0.681,365, 1.135))
meanDepo <- mean(approx(Flux[,1],Flux[,2], xout=seq(1,365,by=1))$y)
oxcon<-as.data.frame(matrix(ncol=2,byrow=TRUE,data=c(
68, 0.387, 69, 0.447, 71, 0.473, 72, 0.515,
189, 1.210,190, 1.056,192, 0.953,193, 1.133,
220, 1.259,221, 1.291,222, 1.204,230, 1.272,
231, 1.168,232, 1.168,311, 0.963,312, 1.075,
313, 1.023)))
names(oxcon)<-c("time","cons")
plot(oxcon)
multser <- seq(1,1.5,by=.05)
numms <- length(multser)
kseries <- seq(0.001,0.05,by=0.002)
numks <- length(kseries)
outcost <- matrix(nrow = numms, ncol = numks)
for (m in 1:numms){
for (i in 1:numks){
pars <- c(k = kseries[i], mult = multser[m])
outcost[m,i] <- costf(pars)
}
}
minpos <- which(outcost==min(outcost),arr.ind=TRUE)
multm <- multser[minpos[1]]
ki <- kseries[minpos[2]]
optpar <- pricefit(par=c(k=ki,mult=multm),minpar=c(0.001,1),
maxpar=c(0.05,1.5),func=costf,npop=50,numiter=500,
centroid=3,varleft=1e-8)
optpar20 <- pricefit(par=optpar$par,minpar=c(0.001,1),
maxpar=c(0.05,1.5),func=costf,npop=50,numiter=500,
centroid=3,varleft=0.2)
optpar25 <- pricefit(par=optpar$par,minpar=c(0.001,1),
maxpar=c(0.05,1.5),func=costf,npop=50,numiter=500,
centroid=3,varleft=0.025)
outtimes <- seq(1,365,by=1)
Carbon <- meanDepo*optpar$par[2]/optpar$par[1]
names(Carbon) <-"Carbon"
out <- as.data.frame(ode(Carbon,outtimes,minmod, optpar$par))
names(out) <- c("time","Carbon","minrate")
par (oma=c(0,0,0,2))
plot(Flux,type="l",xlab="daynr",ylab="mmol/m2/d",
main="Sediment-detritus model",lwd=2)
lines(out$time,out$minrate,lwd=2,col="darkgrey")
points(oxcon$time,oxcon$cons,pch=25,col="black", bg="darkgray",cex=2)
par(new=TRUE)
plot(out$time,out$Carbon,axes=FALSE,xlab="",ylab="",
type="l",lty=2)
axis(4)
mtext(side=4,"mmolC/m2",outer=TRUE)
legend("topleft",col=c("black","darkgrey","black"),
leg=c("C flux","C mineralization","C concentration"),
lwd=c(2,2,1),lty=c(1,1,2))
| /04_8.R | no_license | jsta/practical_ecomod | R | false | false | 4,937 | r | #####################################################
# Figure 4.8. Sediment mineralization model
#####################################################
#General settings
library(deSolve)
# Function to calculate model cost
costf <- function(params){
with(as.list(params), {
Carbon <- meanDepo * mult / k
outtimes <- as.vector(oxcon$time)
outmin <- ode(Carbon, outtimes, minmod, params)
sqdiff <- (outmin[,3] - oxcon$cons)^2
sum(sqdiff)
})
}
# Function to calculate derivative of state variable
minmod <- function(t,Carbon,parameters){
with (as.list(c(Carbon,parameters)),{
minrate <- k*Carbon
Depo <- approx(Flux[,1],Flux[,2], xout=t)$y
dCarbon <- mult*Depo - minrate
list(dCarbon,minrate)
})
}
# initial par estimates
# minimal parameter values
# maximal parameter values
# function to minimise
# nr elements in population
# number of iterations
# number of points in centroid
# relative variation upon stopping
pricefit <- function (par, minpar=rep(-1e8,length(par)),
maxpar=rep(1e8,length(par)), func, npop=max(5*length(par),50),
numiter=10000, centroid = 3, varleft = 1e-8, ...){
# Initialization
cost <- function (par) func(par,...)
npar <- length(par)
tiny <- 1e-8
varleft <- max(tiny,varleft)
populationpar <- matrix(nrow=npop,ncol=npar,byrow=TRUE,
data= minpar+runif(npar*npop)*rep((maxpar-minpar),npop))
colnames(populationpar)<-names(par)
populationpar[1,]<-par
populationcost <- apply(populationpar,FUN=cost,MARGIN=1)
iworst <- which.max(populationcost)
worstcost <- populationcost[iworst]
# Hybridization phase
iter<-0
while(iter < numiter &
(max(populationcost)-min(populationcost)) > (min(populationcost)*varleft)){
iter<-iter+1
selectpar <- sample(1:npop,size=centroid)
# for cross-fertilization
mirrorpar <- sample(1:npop,size=1)
# for mirroring
newpar <- colMeans(populationpar[selectpar,]) # centroid
newpar <- 2*newpar - populationpar[mirrorpar,] # mirroring
newpar <- pmin( pmax(newpar,minpar) ,maxpar)
newcost <- cost(newpar)
if(newcost < worstcost){
populationcost[iworst] <-newcost
populationpar [iworst,]<-newpar
iworst <- which.max(populationcost) # new worst member
worstcost <- populationcost[iworst]
}
} # end j loop
ibest <- which.min(populationcost)
bestpar <- populationpar[ibest,]
bestcost <- populationcost[ibest]
return (list(par = bestpar, cost = bestcost,
poppar = populationpar, popcost=populationcost))
}
# Define problem and data
Flux <- matrix(ncol=2,byrow=TRUE,data=c(
1,
0.654, 11, 0.167, 21, 0.060, 41, 0.070,
73,
0.277, 83, 0.186, 93, 0.140,103, 0.255,
113,
0.231,123, 0.309,133, 1.127,143, 1.923,
153,
1.091,163, 1.001,173, 1.691,183, 1.404,
194,
1.226,204, 0.767,214, 0.893,224, 0.737,
234,
0.772,244, 0.726,254, 0.624,264, 0.439,
274,
0.168,284, 0.280,294, 0.202,304, 0.193,
315,
0.286,325, 0.599,335, 1.889,345, 0.996,
355,
0.681,365, 1.135))
meanDepo <- mean(approx(Flux[,1],Flux[,2], xout=seq(1,365,by=1))$y)
oxcon<-as.data.frame(matrix(ncol=2,byrow=TRUE,data=c(
68, 0.387, 69, 0.447, 71, 0.473, 72, 0.515,
189, 1.210,190, 1.056,192, 0.953,193, 1.133,
220, 1.259,221, 1.291,222, 1.204,230, 1.272,
231, 1.168,232, 1.168,311, 0.963,312, 1.075,
313, 1.023)))
names(oxcon)<-c("time","cons")
plot(oxcon)
multser <- seq(1,1.5,by=.05)
numms <- length(multser)
kseries <- seq(0.001,0.05,by=0.002)
numks <- length(kseries)
outcost <- matrix(nrow = numms, ncol = numks)
for (m in 1:numms){
for (i in 1:numks){
pars <- c(k = kseries[i], mult = multser[m])
outcost[m,i] <- costf(pars)
}
}
minpos <- which(outcost==min(outcost),arr.ind=TRUE)
multm <- multser[minpos[1]]
ki <- kseries[minpos[2]]
optpar <- pricefit(par=c(k=ki,mult=multm),minpar=c(0.001,1),
maxpar=c(0.05,1.5),func=costf,npop=50,numiter=500,
centroid=3,varleft=1e-8)
optpar20 <- pricefit(par=optpar$par,minpar=c(0.001,1),
maxpar=c(0.05,1.5),func=costf,npop=50,numiter=500,
centroid=3,varleft=0.2)
optpar25 <- pricefit(par=optpar$par,minpar=c(0.001,1),
maxpar=c(0.05,1.5),func=costf,npop=50,numiter=500,
centroid=3,varleft=0.025)
outtimes <- seq(1,365,by=1)
Carbon <- meanDepo*optpar$par[2]/optpar$par[1]
names(Carbon) <-"Carbon"
out <- as.data.frame(ode(Carbon,outtimes,minmod, optpar$par))
names(out) <- c("time","Carbon","minrate")
par (oma=c(0,0,0,2))
plot(Flux,type="l",xlab="daynr",ylab="mmol/m2/d",
main="Sediment-detritus model",lwd=2)
lines(out$time,out$minrate,lwd=2,col="darkgrey")
points(oxcon$time,oxcon$cons,pch=25,col="black", bg="darkgray",cex=2)
par(new=TRUE)
plot(out$time,out$Carbon,axes=FALSE,xlab="",ylab="",
type="l",lty=2)
axis(4)
mtext(side=4,"mmolC/m2",outer=TRUE)
legend("topleft",col=c("black","darkgrey","black"),
leg=c("C flux","C mineralization","C concentration"),
lwd=c(2,2,1),lty=c(1,1,2))
|
#### Preamble ####
# Purpose: Prepare and clean the survey data downloaded from https://hodgettsp.github.io/cesR/
# Author: Wen Wang
# Data: 18 December 2020
# Contact: we.wang@mail.utoronto.ca
# License: MIT
# Pre-requisites:
# - Comment out the lines 10 and 11 if you already have them installed in your computer
# install.packages("devtools")
# devtools::install_github("hodgettsp/cesR")
library(cesR)
library(labelled)
library(tidyverse)
#web survey
get_ces("ces2019_web")
ces2019_web <- to_factor(ces2019_web)
survey_data <- ces2019_web %>%
select(cps19_age,
cps19_gender,
cps19_income_number,
cps19_province,
cps19_votechoice)
#match age
survey_data <- survey_data %>%
mutate(age_group = case_when(cps19_age >=18 & cps19_age < 30 ~ 'Age 18 to 29',
cps19_age >= 30 & cps19_age < 45 ~ 'Age 30 to 44',
cps19_age >= 45 & cps19_age < 60 ~ '45 to 59',
cps19_age >= 60 ~ '60+'))
#match sex
survey_data <- survey_data %>%
mutate(sex = case_when(
cps19_gender =="A man" ~ "Male",
cps19_gender =="A woman" ~ "Female"))
#match income
survey_data <- survey_data %>%
mutate(household_income = case_when(
cps19_income_number < 25000 ~ "Less than $25,000",
cps19_income_number >= 25000 & cps19_income_number < 49999 ~ "$25,000 to $49,999",
cps19_income_number >= 50000 & cps19_income_number < 74999 ~ "$50,000 to $74,999",
cps19_income_number >= 75000 & cps19_income_number < 99999 ~ "$75,000 to $99,999",
cps19_income_number >= 100000 & cps19_income_number < 123999 ~ "$100,000 to $ 124,999",
cps19_income_number >= 125000 ~ "$125,000 and more"))
survey_data <- survey_data %>%
mutate(province = cps19_province)
survey_data <- survey_data %>%
mutate(voteLib = ifelse(cps19_votechoice =="Liberal Party", 1, 0))
survey_data <- survey_data %>%
mutate(voteCon = ifelse(cps19_votechoice =="Conservative Party", 1, 0))
survey_data <- survey_data %>%
select(age_group,
sex,
household_income,
province,
voteLib,
voteCon,
cps19_votechoice)
survey_data$age_group = as.factor(survey_data$age_group)
survey_data$sex = as.factor(survey_data$sex)
survey_data$household_income = as.factor(survey_data$household_income)
survey_data$voteLib = as.factor(survey_data$voteLib)
survey_data$voteCon = as.factor(survey_data$voteCon)
write_csv(survey_data, "./outputs/survey_data.csv")
| /scripts/survery_data.R | permissive | wangw218/STA304_FinalProject | R | false | false | 2,526 | r | #### Preamble ####
# Purpose: Prepare and clean the survey data downloaded from https://hodgettsp.github.io/cesR/
# Author: Wen Wang
# Data: 18 December 2020
# Contact: we.wang@mail.utoronto.ca
# License: MIT
# Pre-requisites:
# - Comment out the lines 10 and 11 if you already have them installed in your computer
# install.packages("devtools")
# devtools::install_github("hodgettsp/cesR")
library(cesR)
library(labelled)
library(tidyverse)
#web survey
get_ces("ces2019_web")
ces2019_web <- to_factor(ces2019_web)
survey_data <- ces2019_web %>%
select(cps19_age,
cps19_gender,
cps19_income_number,
cps19_province,
cps19_votechoice)
#match age
survey_data <- survey_data %>%
mutate(age_group = case_when(cps19_age >=18 & cps19_age < 30 ~ 'Age 18 to 29',
cps19_age >= 30 & cps19_age < 45 ~ 'Age 30 to 44',
cps19_age >= 45 & cps19_age < 60 ~ '45 to 59',
cps19_age >= 60 ~ '60+'))
#match sex
survey_data <- survey_data %>%
mutate(sex = case_when(
cps19_gender =="A man" ~ "Male",
cps19_gender =="A woman" ~ "Female"))
#match income
survey_data <- survey_data %>%
mutate(household_income = case_when(
cps19_income_number < 25000 ~ "Less than $25,000",
cps19_income_number >= 25000 & cps19_income_number < 49999 ~ "$25,000 to $49,999",
cps19_income_number >= 50000 & cps19_income_number < 74999 ~ "$50,000 to $74,999",
cps19_income_number >= 75000 & cps19_income_number < 99999 ~ "$75,000 to $99,999",
cps19_income_number >= 100000 & cps19_income_number < 123999 ~ "$100,000 to $ 124,999",
cps19_income_number >= 125000 ~ "$125,000 and more"))
survey_data <- survey_data %>%
mutate(province = cps19_province)
survey_data <- survey_data %>%
mutate(voteLib = ifelse(cps19_votechoice =="Liberal Party", 1, 0))
survey_data <- survey_data %>%
mutate(voteCon = ifelse(cps19_votechoice =="Conservative Party", 1, 0))
survey_data <- survey_data %>%
select(age_group,
sex,
household_income,
province,
voteLib,
voteCon,
cps19_votechoice)
survey_data$age_group = as.factor(survey_data$age_group)
survey_data$sex = as.factor(survey_data$sex)
survey_data$household_income = as.factor(survey_data$household_income)
survey_data$voteLib = as.factor(survey_data$voteLib)
survey_data$voteCon = as.factor(survey_data$voteCon)
write_csv(survey_data, "./outputs/survey_data.csv")
|
formatear_tabla <- function(x_tbl, scroll = FALSE){
tabla <- knitr::kable(x_tbl) %>%
kableExtra::kable_styling(bootstrap_options = c("striped", "hover", "condensed", "responsive"),
full_width = FALSE, font_size = 15, fixed_thead = TRUE)
if(scroll) tabla <- tabla %>% scroll_box(width = "780px")
tabla
}
cuantil <- function(x, probs = c(0,0.25, 0.5, 0.75,1), ...){
x_quo <- enquo(x)
valores <- quantile(x, probs = probs, names = FALSE, ...)
cuantil_nom <- probs
tibble(cuantil = cuantil_nom, valor = valores)
}
grafica_cuantiles <- function(datos, grupo, valor){
if(!(".sample" %in% names(datos))){
datos$.sample <- 1
}
cuantiles_tbl <- datos %>% group_by({{ grupo }}, .sample) %>%
summarise(
num = n(),
cuantiles = list(cuantil({{ valor }}, c(0.1, 0.25, 0.5, 0.75, 0.9)))) %>%
unnest(cols = c(cuantiles))
grafica <- ggplot(cuantiles_tbl %>% spread(cuantil, valor),
aes(x = {{ grupo }}, y = `0.5`)) +
#geom_linerange(aes(ymin= `0.1`, ymax = `0.9`), colour = "gray40") +
geom_linerange(aes(ymin= `0.25`, ymax = `0.75`), size = 2, colour = "gray") +
geom_point(colour = "salmon", size = 2)
grafica
}
marcar_tabla_fun <- function(corte, color_1 = "darkgreen", color_2 = "red"){
fun_marcar <- function(x){
kableExtra::cell_spec(x, "html",
color = ifelse(x <= -corte, color_1, ifelse(x>= corte, color_2, "lightgray")))
}
fun_marcar
}
marcar_tabla_fun_doble <- function(corte_1, corte_2, color_1 = "darkgreen", color_2 = "red"){
fun_marcar <- function(x){
kableExtra::cell_spec(x, "html",
color = ifelse(x <= corte_1, color_1, ifelse(x>= corte_2, color_2, "lightgray")),
bold = ifelse(x <= 3*corte_1, TRUE, ifelse(x>= 3*corte_2, TRUE, FALSE)))
}
fun_marcar
}
| /R/funciones_auxiliares.R | permissive | Acturio/fundamentos | R | false | false | 1,875 | r |
formatear_tabla <- function(x_tbl, scroll = FALSE){
tabla <- knitr::kable(x_tbl) %>%
kableExtra::kable_styling(bootstrap_options = c("striped", "hover", "condensed", "responsive"),
full_width = FALSE, font_size = 15, fixed_thead = TRUE)
if(scroll) tabla <- tabla %>% scroll_box(width = "780px")
tabla
}
cuantil <- function(x, probs = c(0,0.25, 0.5, 0.75,1), ...){
x_quo <- enquo(x)
valores <- quantile(x, probs = probs, names = FALSE, ...)
cuantil_nom <- probs
tibble(cuantil = cuantil_nom, valor = valores)
}
grafica_cuantiles <- function(datos, grupo, valor){
if(!(".sample" %in% names(datos))){
datos$.sample <- 1
}
cuantiles_tbl <- datos %>% group_by({{ grupo }}, .sample) %>%
summarise(
num = n(),
cuantiles = list(cuantil({{ valor }}, c(0.1, 0.25, 0.5, 0.75, 0.9)))) %>%
unnest(cols = c(cuantiles))
grafica <- ggplot(cuantiles_tbl %>% spread(cuantil, valor),
aes(x = {{ grupo }}, y = `0.5`)) +
#geom_linerange(aes(ymin= `0.1`, ymax = `0.9`), colour = "gray40") +
geom_linerange(aes(ymin= `0.25`, ymax = `0.75`), size = 2, colour = "gray") +
geom_point(colour = "salmon", size = 2)
grafica
}
marcar_tabla_fun <- function(corte, color_1 = "darkgreen", color_2 = "red"){
fun_marcar <- function(x){
kableExtra::cell_spec(x, "html",
color = ifelse(x <= -corte, color_1, ifelse(x>= corte, color_2, "lightgray")))
}
fun_marcar
}
marcar_tabla_fun_doble <- function(corte_1, corte_2, color_1 = "darkgreen", color_2 = "red"){
fun_marcar <- function(x){
kableExtra::cell_spec(x, "html",
color = ifelse(x <= corte_1, color_1, ifelse(x>= corte_2, color_2, "lightgray")),
bold = ifelse(x <= 3*corte_1, TRUE, ifelse(x>= 3*corte_2, TRUE, FALSE)))
}
fun_marcar
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/fars_functions.R
\name{fars_read}
\alias{fars_read}
\title{Reading a csv file into R}
\usage{
fars_read(filename)
}
\arguments{
\item{filename}{A string containing the path for the file}
}
\value{
A tibble dataframe containing the information of the csv file
}
\description{
The function \code{fars_read} gets as input the path of the file name to load
into R. It checks whether the file exists and if not, stops.
If the file exists, with correct format, it is loaded into R with the
\code{read_csv} function from the \code{readr} package and messages,which
type each column is, are suppressed.
At least, the function uses the \code{tbl_df} function from the \code{dplyr}
package, although there is no need to do that.
}
\details{
Erros occur by files which exist but are not in (zipped) csv format, or files
which are in csv format but do not have the default delimiters.
Error occurs if more than one filename is passed.
}
\examples{
# filename <- make_filename(2013)
# accident_2013 <- fars_read(filename)
}
| /man/fars_read.Rd | no_license | alex2905/coursera | R | false | true | 1,089 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/fars_functions.R
\name{fars_read}
\alias{fars_read}
\title{Reading a csv file into R}
\usage{
fars_read(filename)
}
\arguments{
\item{filename}{A string containing the path for the file}
}
\value{
A tibble dataframe containing the information of the csv file
}
\description{
The function \code{fars_read} gets as input the path of the file name to load
into R. It checks whether the file exists and if not, stops.
If the file exists, with correct format, it is loaded into R with the
\code{read_csv} function from the \code{readr} package and messages,which
type each column is, are suppressed.
At least, the function uses the \code{tbl_df} function from the \code{dplyr}
package, although there is no need to do that.
}
\details{
Erros occur by files which exist but are not in (zipped) csv format, or files
which are in csv format but do not have the default delimiters.
Error occurs if more than one filename is passed.
}
\examples{
# filename <- make_filename(2013)
# accident_2013 <- fars_read(filename)
}
|
testlist <- list(data = structure(c(-2.74897634139097e+304, 0), .Dim = 1:2), q = 0)
result <- do.call(biwavelet:::rcpp_row_quantile,testlist)
str(result) | /biwavelet/inst/testfiles/rcpp_row_quantile/libFuzzer_rcpp_row_quantile/rcpp_row_quantile_valgrind_files/1610554352-test.R | no_license | akhikolla/updated-only-Issues | R | false | false | 158 | r | testlist <- list(data = structure(c(-2.74897634139097e+304, 0), .Dim = 1:2), q = 0)
result <- do.call(biwavelet:::rcpp_row_quantile,testlist)
str(result) |
\name{resf}
\alias{resf}
\title{Spatial regression with random effects eigenvector spatial filtering}
\usage{
resf( y, x = NULL, meig, method = "reml" )
}
\description{
This function estimates the random effects eigenvector spatial filtering (RE-ESF) model.
}
\arguments{
\item{y}{Vector of explained variables (N x 1)}
\item{x}{Matrix of explanatory variables (N x K). Default is NULL}
\item{meig}{Moran's eigenvectors and eigenvalues. Output from \code{\link{meigen}} or \code{\link{meigen_f}}}
\item{method}{Estimation method. Restricted maximum likelihood method ("reml") and maximum likelihood method ("ml") are available. Default is "reml"}
}
\value{
\item{b}{Matrix with columns for the estimated coefficients on x, their standard errors, t-values, and p-values (K x 4)}
\item{s}{Vector of estimated shrinkage parameters (2 x 1). The first and the second elements denote the standard error and the spatial scale of the estimated spatial dependent component, respectively (see Murakami and Griffith, 2015)}
\item{e}{Vector whose elements are residual standard error (resid_SE), adjusted conditional R2 (adjR2(cond)), restricted log-likelihood (rlogLik), Akaike information criterion (AIC), and Bayesian information criterion (BIC). When method = "ml", restricted log-likelihood (rlogLik) is replaced with log-likelihood (logLik)}
\item{r}{Vector of estimated random coefficients on Moran's eigenvectors (L x 1)}
\item{sf}{Vector of estimated spatial dependent component (N x 1)}
\item{pred}{Vector of predicted values (N x 1)}
\item{resid}{Vector of residuals (N x 1)}
\item{other}{List of other outcomes, which are internally used}
}
\references{
Murakami, D. and Griffith, D.A. (2015) Random effects specifications in eigenvector spatial filtering: a simulation study. Journal of Geographical Systems, 17 (4), 311-331.
}
\author{
Daisuke Murakami
}
\seealso{
\code{\link{meigen}}, \code{\link{meigen_f}}
}
\examples{
require(spdep)
data(boston)
y <- boston.c[, "CMEDV" ]
x <- boston.c[,c("CRIM","ZN","INDUS", "CHAS", "NOX","RM", "AGE",
"DIS" ,"RAD", "TAX", "PTRATIO", "B", "LSTAT")]
coords <- boston.c[,c("LAT","LON")]
meig <- meigen(coords=coords)
res <- resf(y=y,x=x,meig=meig)
res$b
res$s
res$e
#########Fast approximation
meig_f <- meigen_f(coords=coords)
res <- resf(y=y,x=x,meig=meig_f)
}
| /man/resf.Rd | no_license | ryansar/spmoran | R | false | false | 2,331 | rd | \name{resf}
\alias{resf}
\title{Spatial regression with random effects eigenvector spatial filtering}
\usage{
resf( y, x = NULL, meig, method = "reml" )
}
\description{
This function estimates the random effects eigenvector spatial filtering (RE-ESF) model.
}
\arguments{
\item{y}{Vector of explained variables (N x 1)}
\item{x}{Matrix of explanatory variables (N x K). Default is NULL}
\item{meig}{Moran's eigenvectors and eigenvalues. Output from \code{\link{meigen}} or \code{\link{meigen_f}}}
\item{method}{Estimation method. Restricted maximum likelihood method ("reml") and maximum likelihood method ("ml") are available. Default is "reml"}
}
\value{
\item{b}{Matrix with columns for the estimated coefficients on x, their standard errors, t-values, and p-values (K x 4)}
\item{s}{Vector of estimated shrinkage parameters (2 x 1). The first and the second elements denote the standard error and the spatial scale of the estimated spatial dependent component, respectively (see Murakami and Griffith, 2015)}
\item{e}{Vector whose elements are residual standard error (resid_SE), adjusted conditional R2 (adjR2(cond)), restricted log-likelihood (rlogLik), Akaike information criterion (AIC), and Bayesian information criterion (BIC). When method = "ml", restricted log-likelihood (rlogLik) is replaced with log-likelihood (logLik)}
\item{r}{Vector of estimated random coefficients on Moran's eigenvectors (L x 1)}
\item{sf}{Vector of estimated spatial dependent component (N x 1)}
\item{pred}{Vector of predicted values (N x 1)}
\item{resid}{Vector of residuals (N x 1)}
\item{other}{List of other outcomes, which are internally used}
}
\references{
Murakami, D. and Griffith, D.A. (2015) Random effects specifications in eigenvector spatial filtering: a simulation study. Journal of Geographical Systems, 17 (4), 311-331.
}
\author{
Daisuke Murakami
}
\seealso{
\code{\link{meigen}}, \code{\link{meigen_f}}
}
\examples{
require(spdep)
data(boston)
y <- boston.c[, "CMEDV" ]
x <- boston.c[,c("CRIM","ZN","INDUS", "CHAS", "NOX","RM", "AGE",
"DIS" ,"RAD", "TAX", "PTRATIO", "B", "LSTAT")]
coords <- boston.c[,c("LAT","LON")]
meig <- meigen(coords=coords)
res <- resf(y=y,x=x,meig=meig)
res$b
res$s
res$e
#########Fast approximation
meig_f <- meigen_f(coords=coords)
res <- resf(y=y,x=x,meig=meig_f)
}
|
c DCNF-Autarky [version 0.0.1].
c Copyright (c) 2018-2019 Swansea University.
c
c Input Clause Count: 24682
c Performing E1-Autarky iteration.
c Remaining clauses count after E-Reduction: 24350
c
c Performing E1-Autarky iteration.
c Remaining clauses count after E-Reduction: 24350
c
c Input Parameter (command line, file):
c input filename QBFLIB/Herbstritt/blackbox-01X-QBF/biu.mv.xl_ao.bb-b003-p020-MIF02-c01.blif-biu.inv.prop.bb-bmc.conf02.01X-QBF.BB1-01X.BB2-Zi.BB3-01X.with-IOC.unfold-006.qdimacs
c output filename /tmp/dcnfAutarky.dimacs
c autarky level 1
c conformity level 0
c encoding type 2
c no.of var 11776
c no.of clauses 24682
c no.of taut cls 0
c
c Output Parameters:
c remaining no.of clauses 24350
c
c QBFLIB/Herbstritt/blackbox-01X-QBF/biu.mv.xl_ao.bb-b003-p020-MIF02-c01.blif-biu.inv.prop.bb-bmc.conf02.01X-QBF.BB1-01X.BB2-Zi.BB3-01X.with-IOC.unfold-006.qdimacs 11776 24682 E1 [994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3707 3709 3713 3715 3717 3719 3721 3723 3725 3727 3729 3731 3735 3739 3743 3747 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767] 0 116 8669 24350 RED
| /code/dcnf-ankit-optimized/Results/QBFLIB-2018/E1/Experiments/Herbstritt/blackbox-01X-QBF/biu.mv.xl_ao.bb-b003-p020-MIF02-c01.blif-biu.inv.prop.bb-bmc.conf02.01X-QBF.BB1-01X.BB2-Zi.BB3-01X.with-IOC.unfold-006/biu.mv.xl_ao.bb-b003-p020-MIF02-c01.blif-biu.inv.prop.bb-bmc.conf02.01X-QBF.BB1-01X.BB2-Zi.BB3-01X.with-IOC.unfold-006.R | no_license | arey0pushpa/dcnf-autarky | R | false | false | 2,522 | r | c DCNF-Autarky [version 0.0.1].
c Copyright (c) 2018-2019 Swansea University.
c
c Input Clause Count: 24682
c Performing E1-Autarky iteration.
c Remaining clauses count after E-Reduction: 24350
c
c Performing E1-Autarky iteration.
c Remaining clauses count after E-Reduction: 24350
c
c Input Parameter (command line, file):
c input filename QBFLIB/Herbstritt/blackbox-01X-QBF/biu.mv.xl_ao.bb-b003-p020-MIF02-c01.blif-biu.inv.prop.bb-bmc.conf02.01X-QBF.BB1-01X.BB2-Zi.BB3-01X.with-IOC.unfold-006.qdimacs
c output filename /tmp/dcnfAutarky.dimacs
c autarky level 1
c conformity level 0
c encoding type 2
c no.of var 11776
c no.of clauses 24682
c no.of taut cls 0
c
c Output Parameters:
c remaining no.of clauses 24350
c
c QBFLIB/Herbstritt/blackbox-01X-QBF/biu.mv.xl_ao.bb-b003-p020-MIF02-c01.blif-biu.inv.prop.bb-bmc.conf02.01X-QBF.BB1-01X.BB2-Zi.BB3-01X.with-IOC.unfold-006.qdimacs 11776 24682 E1 [994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3707 3709 3713 3715 3717 3719 3721 3723 3725 3727 3729 3731 3735 3739 3743 3747 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767] 0 116 8669 24350 RED
|
\name{makeModelMatrixFromDataFrame}
\title{Make Model Matrix From Data Frame}
\alias{makeModelMatrixFromDataFrame}
\alias{makeind}
\description{
Converts a data frame with numeric and factor contents into a matrix,
suitable for use with \code{\link{bart}}. Unlike in linear regression,
factors containing more than two levels result in dummy variables being
created for each level.
}
\usage{
makeModelMatrixFromDataFrame(x)
makeind(x, all = TRUE)
}
\arguments{
\item{x}{Data frame of explanatory variables.}
\item{all}{Not currently implemented.
%If all=TRUE, a factor with p levels will be replaced by all p dummies.
%If all=FALSE, the pth dummy is dropped.
}
}
\details{
Note that if you have train and test data frames, it may be best
to \code{\link{rbind}} the two together, apply \code{makeModelMatrixFromDataFrame}
to the result, and then pull them back apart.
}
\value{
A matrix with columns corresponding to the elements of the data frame.
}
\author{
Vincent Dorie: \email{vjd4@nyu.edu}.
}
\examples{
x1 <- 1:10
x2 <- as.factor(c(rep(1, 5), rep(2, 5)))
x3 <- as.factor(rep(c(1, 2, 4), c(3, 3, 4)))
levels(x3) <- c('alice', 'bob', 'charlie')
x <- data.frame(x1, x2, x3)
ignored <- makeModelMatrixFromDataFrame(x)
}
\keyword{factor}
| /man/makeind.Rd | no_license | jmurray1022/dbarts | R | false | false | 1,277 | rd | \name{makeModelMatrixFromDataFrame}
\title{Make Model Matrix From Data Frame}
\alias{makeModelMatrixFromDataFrame}
\alias{makeind}
\description{
Converts a data frame with numeric and factor contents into a matrix,
suitable for use with \code{\link{bart}}. Unlike in linear regression,
factors containing more than two levels result in dummy variables being
created for each level.
}
\usage{
makeModelMatrixFromDataFrame(x)
makeind(x, all = TRUE)
}
\arguments{
\item{x}{Data frame of explanatory variables.}
\item{all}{Not currently implemented.
%If all=TRUE, a factor with p levels will be replaced by all p dummies.
%If all=FALSE, the pth dummy is dropped.
}
}
\details{
Note that if you have train and test data frames, it may be best
to \code{\link{rbind}} the two together, apply \code{makeModelMatrixFromDataFrame}
to the result, and then pull them back apart.
}
\value{
A matrix with columns corresponding to the elements of the data frame.
}
\author{
Vincent Dorie: \email{vjd4@nyu.edu}.
}
\examples{
x1 <- 1:10
x2 <- as.factor(c(rep(1, 5), rep(2, 5)))
x3 <- as.factor(rep(c(1, 2, 4), c(3, 3, 4)))
levels(x3) <- c('alice', 'bob', 'charlie')
x <- data.frame(x1, x2, x3)
ignored <- makeModelMatrixFromDataFrame(x)
}
\keyword{factor}
|
library(textrecipes)
### Name: step_tf
### Title: Term frequency of tokens
### Aliases: step_tf tidy.step_tf
### ** Examples
## No test:
library(recipes)
data(okc_text)
okc_rec <- recipe(~ ., data = okc_text) %>%
step_tokenize(essay0) %>%
step_tf(essay0)
okc_obj <- okc_rec %>%
prep(training = okc_text, retain = TRUE)
bake(okc_obj, okc_text)
tidy(okc_rec, number = 2)
tidy(okc_obj, number = 2)
## End(No test)
| /data/genthat_extracted_code/textrecipes/examples/step_tf.Rd.R | no_license | surayaaramli/typeRrh | R | false | false | 434 | r | library(textrecipes)
### Name: step_tf
### Title: Term frequency of tokens
### Aliases: step_tf tidy.step_tf
### ** Examples
## No test:
library(recipes)
data(okc_text)
okc_rec <- recipe(~ ., data = okc_text) %>%
step_tokenize(essay0) %>%
step_tf(essay0)
okc_obj <- okc_rec %>%
prep(training = okc_text, retain = TRUE)
bake(okc_obj, okc_text)
tidy(okc_rec, number = 2)
tidy(okc_obj, number = 2)
## End(No test)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/data.R
\docType{data}
\name{decom_result}
\alias{decom_result}
\title{Results of decomposition using Gaussian model}
\format{
A data frame with 1000 rows and 7 variables
\describe{
\item{index}{index of waveform, which can tell which rows or results belongs to specific waveform}
\item{A}{the amplitude of one waveform componment (A)}
\item{u}{the time location corresponds to the amplitude for one waveform componment}
\item{sigma}{the echo width of one waveform componment}
\item{A_std}{the standard error of A, which can be used for uncertainty analysis}
\item{u_std}{the standard error of u, which can be used for uncertainty analysis}
\item{sig_std}{the standard error of sigma, which can be used for uncertainty analysis}
}
}
\usage{
decom_result
}
\description{
This dataset contained the result from the Gaussian decompositon.
}
\keyword{datasets}
| /man/decom_result.Rd | no_license | cran/waveformlidar | R | false | true | 973 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/data.R
\docType{data}
\name{decom_result}
\alias{decom_result}
\title{Results of decomposition using Gaussian model}
\format{
A data frame with 1000 rows and 7 variables
\describe{
\item{index}{index of waveform, which can tell which rows or results belongs to specific waveform}
\item{A}{the amplitude of one waveform componment (A)}
\item{u}{the time location corresponds to the amplitude for one waveform componment}
\item{sigma}{the echo width of one waveform componment}
\item{A_std}{the standard error of A, which can be used for uncertainty analysis}
\item{u_std}{the standard error of u, which can be used for uncertainty analysis}
\item{sig_std}{the standard error of sigma, which can be used for uncertainty analysis}
}
}
\usage{
decom_result
}
\description{
This dataset contained the result from the Gaussian decompositon.
}
\keyword{datasets}
|
#' Converts between different measures of humidity
#'
#' @description `humidityconvert` is used to convert between different measures of humidity, namely relative, absolute or specific. Vapour pressure is also returned.
#'
#' @param h humidity value(s). Units as follows: specific humidity (\ifelse{html}{\out{kg kg<sup>-1</sup>}}{\eqn{kg kg^{-1}}}), absolute humidity (\ifelse{html}{\out{kg m<sup>-3</sup> }}{\eqn{kg m^{-3}}}), relative humidity (\%), vapour pressure (kPa).
#' @param intype a character string description of the humidity type of `h`. One of "relative", "absolute" or "specific".
#' @param tc A numeric value specifying the temperature (ºC).
#' @param p An optional numeric value specifying the atmospheric pressure (Pa).
#'
#' @details This function converts between vapour pressure and specific,
#' relative and absolute humidity, based on sea-level pressure and
#' temperature. It returns a list of relative, absolute and specific
#' humidity and vapour pressure. If `intype` is unspecified, then `h` is
#' assumed to be relative humidity. If `p` is unspecified, pressure assumed
#' to be 101300, a typical value for sea-level pressure. If one or more of the
#' relative humidity values exceeds 100\% a warning is given.
#'
#' @return a list of numeric humidity values with the following components:
#' @return `relative` relative humidity (\%).
#' @return `absolute` absolute humidity (\ifelse{html}{\out{kg m<sup>-3</sup> }}{\eqn{kg m^{-3}}}).
#' @return `specific` specific humidity (\ifelse{html}{\out{kg kg<sup>-1</sup> }}{\eqn{kg kg^{-1}}}).
#' @return `vapour_pressure` vapour pressure (kPa).
#' @export
#'
#' @examples
#' humidityconvert(90, 'relative', 20)
#' humidityconvert(0.01555486, 'absolute', 20)
#' humidityconvert(0.01292172, 'specific', 20)
humidityconvert <- function(h, intype = "relative", tc = 20, p = 101300) {
tk <- tc + 273.15
pk <- p / 1000
if (intype != "specific" & intype != "relative" & intype != "absolute") {
warning ("No valid input humidity specified. Humidity assumed to be
relative")
intype <- "relative"
}
e0 <- 0.6108 * exp(17.27 * tc / (tc + 237.3))
ws <- 0.622 * e0 / pk
if (intype == "specific") {
e0 <- 0.6108 * exp(17.27 * tc / (tc + 237.3))
hr <- (h / ws) * 100
}
if (intype == "absolute") {
ea <- (tk * h) / 2.16679
hr <- (ea / e0) * 100
}
if (intype == "relative") hr <- h
if (max(hr, na.rm = T) > 100) warning(paste("Some relative humidity values > 100%",
max(hr, na.rm = T)))
ea <- e0 * (hr / 100)
hs <- (hr / 100) * ws
ha <- 2.16679 * (ea / tk)
return(list(relative = hr, absolute = ha, specific = hs,
vapour_pressure = ea))
}
#' Calculates land to sea ratio in upwind direction
#'
#' @description `invls` is used to calculate an inverse distance\ifelse{html}{\out{<sup>2</sup>}}{\eqn{^2}} weighted ratio of land to sea in a specified upwind direction.
#'
#' @param landsea A raster object with NAs (representing sea) or any non-NA value (representing land). The object should have a larger extent than that for which land-sea ratio values are needed, as the calculation requires land / sea coverage to be assessed upwind outside the target area.
#' @param e an extent object indicating the region for which land-sea ratios are required.
#' @param direction an optional single numeric value specifying the direction (decimal degrees) from which the wind is blowing.
#'
#' @details This function calculates a coefficient of the ratio of land to
#' sea pixels in a specified upwind direction, across all elements of a
#' raster object, weighted using an inverse distance squared function,
#' such that nearby pixels have a greater influence on the coefficient.
#' It returns a raster object representing values ranging between zero
#' (all upwind pixels sea) to one (all upwind pixels land). Upwind
#' direction is randomly varied by ± `jitter.amount` degrees.
#'
#' @return a raster object with distance-weighted proportions of upwind land pixels
#' @import raster rgdal
#' @importFrom sp coordinates
#' @useDynLib microclima, .registration = TRUE
#' @importFrom Rcpp sourceCpp
#' @export
#'
#' @examples
#' library(raster)
#' ls1 <- invls(dtm100m, extent(dtm1m), 180)
#' ls2 <- invls(dtm100m, extent(dtm1m), 270)
#' par(mfrow=c(2,1))
#' plot(ls1, main = "Land to sea weighting, southerly wind")
#' plot(ls2, main = "Land to sea weighting, westerly wind")
invls <- function(landsea, e, direction) {
e2 <- extent(landsea)
maxdist <- sqrt(xres(landsea) * (e2@xmax - e2@xmin) +
yres(landsea) * (e2@ymax - e2@ymin))
resolution <- xres(landsea)
slr <- landsea * 0 + 1
m <- is_raster(slr)
m[is.na(m)] <- 0
slr <- if_raster(m, slr)
s <- c(0, (8:1000) / 8) ^ 2 * resolution
s <- s[s <= maxdist]
lss <- crop(slr, e, snap = 'out')
lsm <- getValues(lss, format = "matrix")
lsw <- array(NA, dim = dim(lsm))
lsw <- invls_calc(lsm, resolution, e@xmin, e@ymax, s, direction, raster::as.matrix(slr),
raster::xmin(slr),raster::xmax(slr),raster::ymin(slr),raster::ymax(slr))
lsr <- raster(lsw, template = lss)
lsr
}
#' Calculates coastal effects using thin-plate spline
#'
#' @description `coastalTps` uses thin-plate spline interpolation to estimate
#' the effects of coastal buffering of land-temperatures by the sea.
#'
#' @param dT a coarse-resolution raster of sea - land temperatures (ºC).
#' @param lsw a fine-resolution raster of coastal exposure upwind, as produced by [invls()].
#' @param lsa a fine-resolution raster of mean coastal exposure in all directions.
#' @return a fine-resolution raster of sea - land temperature differences (ºC).
#' @export
#' @importFrom rgcvpack fitTps
#' @importFrom rgcvpack predict.Tps
#'
#' @examples
#' library(raster)
#' # =========================================
#' # Calculate land-sea temperature difference
#' # =========================================
#' temp <- tas[,,1]
#' sst <- 10.665
#' dT <- if_raster(sst - temp, dtm1km)
#' # ============================
#' # Obtain coastal exposure data
#' # ============================
#' lsw <- landsearatios[,,7] # upwind
#' lsa <- apply(landsearatios, c(1, 2), mean) # mean, all directions
#' lsw <- if_raster(lsw, dtm100m)
#' lsa <- if_raster(lsa, dtm100m)
#' # ==========================================================
#' # Calculate coastal effects using thin-plate spline and plot
#' # ==========================================================
#' dTf <- coastalTps(dT, lsw, lsa)
#' par(mfrow = c(2, 1))
#' plot(sst - dT, main = expression(paste("Temperature ",(~degree~C))))
#' plot(sst - dTf, main = expression(paste("Temperature ",(~degree~C))))
coastalTps <- function(dT, lsw, lsa) {
lswc <- resample(lsw, dT)
lsac <- resample(lsa, dT)
xy <- data.frame(xyFromCell(lswc, 1:ncell(dT)))
z1 <- extract(lswc, xy)
z2 <- extract(lsac, xy)
v <- extract(dT, xy)
xyz <- cbind(xy, z1, z2)
sel <- which(is.na(v) == F)
v <- v[is.na(v) == F]
xyz <- xyz[sel, ]
tps <- fitTps(xyz, v, m = 3)
xy <- data.frame(xyFromCell(lsw, 1:ncell(lsw)))
z1 <- extract(lsw, xy)
z2 <- extract(lsa, xy)
xyz <- cbind(xy, z1, z2)
sel <- which(is.na(z1) == FALSE)
xyz <- xyz[sel, ]
xy$z <- NA
xy$z[sel] <- predict.Tps(tps, xyz)
r <- rasterFromXYZ(xy)
r
}
#' Calculates the moist adiabatic lapse rate
#'
#' @description `lapserate` is used to calculate changes in temperature with height.
#'
#' @param tc a single numeric value, raster object, two-dimensional array or matrix of temperature (ºC).
#' @param h a single numeric value, raster object, two-dimensional array or matrix of specific humidity (\ifelse{html}{\out{kg kg<sup>-1</sup> }}{\eqn{kg kg^{-1}}}).
#' @param p an optional single numeric value, raster object, two-dimensional array or matrix of atmospheric pressure (Pa).
#'
#' @return the lapse rate (\ifelse{html}{\out{º m<sup>-1</sup> }}{\eqn{ º m^{-1}}}).
#' @export
#' @import raster
#'
#' @details if tc is a raster, a raster object is returned. This function calculates the
#' theoretical lapse rate. Environmental lapse rates can vary due to winds.
#'
#' @examples
#' lapserate(20, 0) * 1000 # dry lapse rate per km
#' h <- humidityconvert(100, intype = "relative", 20)
#' lapserate(20, h$specific) * 1000 # lapse rate per km when relative humidity is 100%
lapserate <- function(tc, h, p = 101300) {
r <- tc
tc <- is_raster(tc)
h <- is_raster(h)
p <- is_raster(p)
pk <- p / 1000
e0 <- 0.6108 * exp(17.27 * tc / (tc + 237.3))
ws <- 0.622 * e0 / pk
rh <- (h / ws) * 100
rh[rh > 100] <- 100
ea <- e0 * (rh / 100)
rv <- 0.622 * ea / (pk - ea)
lr <- 9.8076 * (1 + (2501000 * rv) / (287 * (tc + 273.15))) / (1003.5 +
(0.622 * 2501000 ^ 2 * rv) / (287 * (tc + 273.15) ^ 2))
lr <- lr * -1
if_raster(lr, r)
}
#' Applies height correction to wind speed measurements
#'
#' @description `windheight` is used to to apply a height correction to wind speed measured at a specified height above ground level to obtain estimates of wind speed at a desired height above the ground.
#'
#' @param ui numeric value(s) of measured wind speed (\ifelse{html}{\out{m s<sup>-1</sup> }}{\eqn{ m s^{-1}}}) at height `zi` (m).
#' @param zi a numeric value idicating the height (m) above the ground at which `ui` was measured.
#' @param zo a numeric value indicating the height (m) above ground level at which wind speed is desired.
#'
#' @details Thus function assumes a logarithmic height profile to convert
#' wind speeds. It performs innacurately when `uo` is lower than 0.2
#' and a warning is given. If `uo` is below ~0.08 then the logairthmic height
#' profile cannot be used, and `uo` is converted to 0.1 and a warning given.
#'
#' @seealso The function [windcoef()] calculates a topographic or vegetation sheltering effect.
#'
#' @return numeric values(s) of wind speed at height specified by `zo` (\ifelse{html}{\out{m s<sup>-1</sup> }}{\eqn{m s^{-1}}}).
#' @export
#'
#' @examples
#' windheight(3, 10, 1) # good
#' windheight(3, 10, 0.15) # performs poorly. Warning given
#' windheight(3, 10, 0.05) # cannot calculate. ui converted and warning given
#'
windheight <- function(ui, zi, zo) {
if (zo < 0.2 & zo > (5.42 / 67.8)) {
warning("Wind-height profile function performs poorly when wind
height is below 20 cm")
}
if (zo <= (5.42 / 67.8)) {
warning(paste("wind-height profile cannot be calculated for height ",
zo * 100, " cm"))
print("Height converted to 10 cm")
zo <- 0.1
}
uo <- ui * log(67.8 * zo - 5.42) / log(67.8 * zi - 5.42)
uo
}
#' Calculates wind shelter coefficient
#'
#' @description `windcoef` is used to apply a topographic shelter coefficient to wind data.
#'
#' @param dsm raster object, two-dimensional array or matrix of elevations (m) derived either from a digital terrain or digital surface model, and orientated as if derived using [is_raster()]. I.e. `[1, 1]` is the NW corner.
#' @param direction a single numeric value specifying the direction from which the wind is blowing (º).
#' @param hgt a single numeric value specifying the height (m) at which wind speed is derived or measured. The wind speeds returned are also for this height, and account for the fact topography affords less shelter to wind at greater heights.
#' @param res a single numeric value specifying the the resolution (m) of `dsm`.
#'
#' @details If dsm is a raster object, then a raster object is returned.
#' If elevations are derived from a digital terrain model, then
#' the sheltering effects of vegetation are ignored. If derived from a
#' digital surface model, then the sheltering effects of vegetation are
#' accounted for. If `res` is unspecified `dtm` is assumed to have a resolution of one m.
#'
#' @seealso The function [windheight()] converts measured wind heights to a standard reference height.
#'
#' @return a raster object, or two-dimensional array of shelter coefficients. E.g. a shelter coefficient of 0.5 indicates that wind speed at that location is 0.5 times that measured at an unobscured location.
#' @import raster
#' @export
#'
#' @examples
#' library(raster)
#' dsm <- dtm1m + veg_hgt
#' wc <- windcoef(dsm, 0)
#' plot(mask(wc, dtm1m), main ="Northerly wind shelter coefficient")
windcoef <- function(dsm, direction, hgt = 1, res = 1) {
r <- dsm
dsm <- is_raster(dsm)
dsm[is.na(dsm)] <- 0
dtm <- dsm / res
hgt <- hgt / res
direction <- direction - 90
azi <- direction * (pi / 180)
horizon <- array(0, dim(dtm))
dtm3 <- array(0, dim(dtm) + 200)
x <- dim(dtm)[1]
y <- dim(dtm)[2]
dtm3[101:(x + 100), 101:(y + 100)] <- dtm
for (step in 1:10) {
horizon[1:x, 1:y] <- pmax(horizon[1:x, 1:y], (dtm3[(101 + sin(azi) *
step ^ 2):(x + 100 + sin(azi) * step ^ 2),
(101 + cos(azi) * step ^ 2 ):(y + 100 + cos(azi) *
step ^ 2)] - dtm3[101:(x + 100), 101 : (y + 100)]) /
step ^ 2)
horizon[1:x, 1:y] <- ifelse(horizon[1:x, 1:y] < (hgt / step ^ 2), 0,
horizon[1:x, 1:y])
}
index <- 1 - atan(0.17 * 100 * horizon) / 1.65
index <- if_raster(index, r)
index
}
#' Calculates sunrise, sunset and daylength
#'
#' @description `suntimes` is used to calculate, sunrise, sunset and daylength on any given data at a specified location.
#'
#' @param julian the Julian day as returned by [julday()].
#' @param lat latitude of the location for which `suntime` is required (decimal degrees, -ve south of equator).
#' @param long longitude of the location for which `suntime` is required (decimal degrees, -ve west of Greenwich meridian).
#' @param merid an optional numeric value representing the longitude (decimal degrees) of the local time zone meridian (0 for GMT). Default is `round(long / 15, 0) * 15`
#' @param dst an optional numeric value representing the time difference from the timezone meridian (hours, e.g. +1 for BST if `merid` = 0).
#'
#' @return a data.frame with three components:
#' @return `sunrise` a vector of sunrise (hours in 24 hour clock).
#' @return `sunrise` a vector of sunset (hours in 24 hour clock).
#' @return `sunrise` a vector of daylengths (hours).
#' @export
#'
#' @details if the sun is above or below the horizon for 24 hours on any
#' days, a warning is given, and the sunrise and sunset returned are the
#' appoximate times at which that the sun is closest to the horizon.
#'
#' @examples
#' jd <- julday(2018, 1, 16)
#' suntimes(jd, 50.17, -5.12) # Cornwall, UK
#' suntimes(jd, 78.22, 15.64) # Longyearbyen, Svalbad
#' suntimes(jd, -54.94, -67.61, merid = -60, dst = 1) # Puerto Williams, Cabo de Hornos, Chile
suntimes <- function(julian, lat, long, merid = round(long / 15, 0) * 15, dst = 0) {
lw <- (long - merid) * -1
n <- julian - 2451545 - 0.0009 - (lw / 360)
n <- floor (n) + 0.5
sn <- 2451545 + 0.0009 + (lw / 360) + n
msa <- (357.5291 + 0.98560028 * (sn - 2451545))%%360
eoc <- 1.9148 * sin(msa * pi / 180) + 0.02 * sin(2 * msa * pi / 180) +
0.0003 * sin(3 * msa * pi / 180)
ecl <- (msa + 102.9372 + eoc + 180)%%360
st <- sn + (0.0053 * sin(msa * pi / 180)) - (0.0069 *
sin(2 * ecl * pi / 180))
d <- asin(sin(ecl * pi / 180) * sin(23.45 * pi / 180))
coshas <- (sin(-0.83 * pi / 180) - sin(lat * pi / 180) * sin(d)) /
(cos(lat * pi / 180) * cos(d))
if (max(coshas) > 1) {
coshas <- ifelse(coshas > 1, 1, coshas)
warning("sun below horizon for 24 hours on some days")
}
if (min(coshas) < -1) {
coshas <- ifelse(coshas < -1, -1, coshas)
warning("sun above horizon for 24 hours on some days")
}
has <- acos(coshas)
jset <- 2451545 + 0.0009 + (((has * 180 / pi + lw) / 360) + n +
0.0053 * sin(msa * pi / 180)) - 0.0069 *
sin(2 * ecl * pi / 180)
jrise <- st - (jset - st)
hset <- jset%%1 * 24 + dst
hrise <- jrise%%1 * 24 + dst
dl <- round((jset - jrise) * 24, 5)
sunvars <- data.frame(sunrise = hrise, sunset = hset, daylight = dl)
sunvars
}
#' derived fraction of solar day
.solarday <- function(julian, localtime, lat, long, merid, dst = 0) {
src <- suntimes(julian, lat, long, merid, dst)$sunrise
ssc <- suntimes(julian, lat, long, merid, dst)$sunset
ssp <- suntimes(julian - 1, lat, long, merid, dst)$sunset
srn <- suntimes(julian + 1, lat, long, merid, dst)$sunrise
st <- ifelse(localtime >= src & localtime <= ssc,
((localtime - src) / (ssc - src)) * 12 + 6, localtime)
st <- ifelse(localtime > ssc, ((localtime - ssc) / (srn + 24 - ssc)) *
12 + 18, st)
st <- ifelse(localtime < src, ((localtime + 24 - ssp) / (src + 24 - ssp)) *
12 - 6, st)
st <- (st / 24)%%1
st
}
#' derived proportion of maximum radiation
.propmaxrad <- function(dif, dct, am) {
theta <- 1.1 * (0.7 ^ (am ^ 0.678))
mxr <- 4.87 * theta
pr <- (dif + dct) / mxr
pr <- ifelse(pr > 1, 1, pr)
pr
}
#' calculates emmisivity from humidity etc
.emissivity <- function(h, tc, n, p = 100346.13, co = 1.24) {
pk <- p / 1000
e0 <- 0.6108 * exp(17.27 * tc / (tc + 237.3))
ws <- 0.622 * e0 / pk
rh <- (h / ws) * 100
rh[rh > 100] <- 100
ea <- e0 * rh / 100
eo <- co * (0.1 * ea / (tc + 273.15)) ^ (1/7)
em <- (1 - n) + n * eo
em
}
#' Derives hourly temperatures from daily data
#'
#' @description `hourlytemp` is used to derive hourly temperatures from daily maxima and minima.
#'
#' @param julian vector of julian days expressed as integers for every day for which `mintemp` and `maxtemp` are provided, as returned by function [julday()].
#' @param em an optional vector of hourly emissivities. If not provided, calculated from `h`, `n` and `p`.
#' @param h a vector of hourly specific humidities (\ifelse{html}{\out{kg kg<sup>-1</sup> }}{\eqn{kg kg^{-1}}}). Ignored if `em` provided.
#' @param n a vector of hourly fractional cloud cover values (range 0 - 1). Ignored if `em` provided.
#' @param p an optional vector of hourly atmospheric pressure values (Pa). Ignored if `em` provided.
#' @param dni a vector of hourly direct radiation values normal to the solar beam (\ifelse{html}{\out{MJ m<sup>-2</sup> hr<sup>-1</sup>}}{\eqn{MJ m^-2 hr^{-1}}}).
#' @param dif a vector of hourly diffuse radiation values (\ifelse{html}{\out{MJ m<sup>-2</sup> hr<sup>-1</sup>}}{\eqn{MJ m^-2 hr^{-1}}}).
#' @param mintemp a vector of daily minimum temperatures (ºC).
#' @param maxtemp a bector of daily maximum temperatures (ºC).
#' @param lat a single numeric value representing the latitude of the location for which hourly temperatures are required (decimal degrees, -ve south of equator).
#' @param long a single numeric value representing the longitude of the location for which hourly temperatures are required (decimal degrees, -ve west of Greenwich meridian).
#' @param merid an optional numeric value representing the longitude (decimal degrees) of the local time zone meridian (0 for GMT). Default is `round(long / 15, 0) * 15`
#' @param dst an optional numeric value representing the time difference from the timezone meridian (hours, e.g. +1 for BST if `merid` = 0).
#'
#' @return a vector of hourly temperatures (ºC).
#' @export
#'
#' @details A warning is returned if any of following conditions are not
#' met. (1) `h`, `n`, `dif` and `dct` differ in length.
#' (2) `julian`, `mintemp` and `maxtemp` differ in length. (3) E.g. `h` / 24 is not
#' an integer. (4) the length of e.g. `h` is not equal to the length of
#' e.g. `mintemp` x 24.
#'
#' @examples
#' jd <- julday(2010, 5 , c(1,2))
#' ht <- hourlytemp(jd, NA, microvars$humidity[1:48], microvars$cloudcover[1:48],
#' microvars$pressure[1:48], dni = microvars$dni[1:48],
#' dif = microvars$dif[1:48], c(7.5, 7.2), c(14.6, 15.2),
#' 49.968, -5.216)
#' plot(ht ~ c(0:47),type="l", xlab = "Hour", ylab = "Temperature",
#' main = paste("tmins:", 7.2, 7.5, "tmaxs:", 14.6, 15.2))
hourlytemp <- function(julian, em = NA, h, n, p = 100346.13, dni, dif,
mintemp, maxtemp, lat, long, merid = round(long / 15, 0) * 15, dst=0) {
l1 <- unlist(lapply(list(dni, dif), length))
l2 <- unlist(lapply(list(julian, mintemp, maxtemp), length))
if (length(unique(l1)) != 1) {
warning("Number of hourly values not identical")
}
if (length(unique(l2)) != 1) {
warning("Number of daily values not identical")
}
if (length(dni)%%24 != 0) warning ("Hourly values must be multiple of 24")
if (l1[1] != l2[1] * 24) {
warning("Number of hourly values not 24 times number of daily values")
}
o <- order(rep(c(1:length(julian)), 24))
jd <- rep(julian, 24)[o]
localtime <- rep(c(0:23), length(mintemp))
solfrac <- .solarday(julian, localtime, lat, long, merid, dst)
am <- airmasscoef(localtime, lat, long, julian, merid, dst)
dct <- dni * siflat(localtime, lat, long, jd, merid, dst)
pr <- .propmaxrad(dif, dct, am)
tfrac <- 110.42201 * sin(solfrac) - 38.64802 * cos(solfrac) - 79.82963 *
sin(2 * solfrac) + 65.39122 * cos(2 * solfrac) + 15.54387 *
sin(3 * solfrac) - 26.30047 * cos(3 * solfrac)
mns <- rep(mintemp, 24)[o]
mxs <- rep(maxtemp, 24)[o]
tc <- (mxs - mns) * tfrac + mns
if (is.na(em[1]))
em <- .emissivity(h, tc, n, p)
day <- which(is.na(pr) == F)
ngt <- which(is.na(pr))
tfrac[day] <- -0.30516 + 0.78414 * tfrac[day] + 0.89086 *
pr[day] + 0.34062 * tfrac[day] * pr[day]
tfrac[ngt] <- -0.6562 + 1.0277 * tfrac[ngt] + 0.8981 *
em[ngt] -0.5262 * tfrac[ngt] * em[ngt]
tfrac <- 1 / (1 + exp(-1 * tfrac))
td <- array(tfrac, dim = c(24, length(tfrac) / 24))
tmns <- apply(td, 2, min)
tmxs <- apply(td, 2, max)
for (i in 1:dim(td)[2]) {
td[, i] <- (td[, i] - tmns[i]) / (tmxs[i] - tmns[i])
}
tfrac <- as.vector(td)
tc <- (mxs - mns) * tfrac + mns
tc
}
#' Applies a spline function to an array of values
#'
#' @description `arrayspline` is used to derive e.g. hourly climate data from e.g. daily values.
#'
#' @param a a three-dimensional array (row, column, time)
#' @param tme an object of class POSIXct of times for `a`. I.e. `length(tme) = dim(a)[3]`
#' @param nfact indicates the time interval for which outputs are required. E.g to derive hourly from daily data `nfact = 24`, or derive six-hourly from daily data `nfact = 4`
#' @param out an optional character vector indicating the time for which the output is required. Format must be as for `tme`.
#'
#' @return
#' If out is unspecified, a three dimensional array of size `c(a[1], a[2], (length(tme) - 1) * nfact + 1)` is returned.
#' If out is specified, a three dimensional array of size `c(a[1], a[2], length(out))` is returned.
#'
#' @importFrom stats splinefun
#' @export
#'
#' @details
#' `arrayspline` uses the Forsythe, Malcolm and Moler method of splining, as specified by
#' `"fmm"` in [spline()]. If `a[i, j, ]` is a vector of NAs, then tthe corresponding vector in
#' the output array is also a vector of NAs. It is assumed that all spatial data within `a` have
#' equivelent times. I.e. the time of both `a[1, 1, 1]` and `a[1000, 1000, 1]` is identical and
#' equal to `tme[1]`.
#'
#' @examples
#' library(raster)
#' tme <- as.POSIXct(c(0:364) * 24 * 3600, origin="2010-01-01", tz = "GMT")
#' h <- arrayspline(huss, tme, out = "2010-05-01 11:00")
#' plot(raster(h, template = dtm1km),
#' main = "Specific humidity 2010-05-01 11:00")
arrayspline <- function(a, tme, nfact = 24, out = NA) {
n <- (length(tme) - 1) * nfact + 1
sf <- function(y, tme, nfact) {
n <- (length(tme) - 1) * nfact + 1
if (is.na(mean(y)) == FALSE) {
xy <- spline(as.numeric(tme), y, n = n)
xy$y
}
else rep(NA, n)
}
ao <- aperm(apply(a, c(1, 2), sf, tme, nfact), c(2, 3, 1))
if (is.na(out[1]) == FALSE) {
out <- as.POSIXct(out, tz = format(tme[1], "%Z"))
tout <- spline(as.numeric(tme), c(1:length(tme)), n)$x
tout <- as.POSIXct(tout, origin = "1970-01-01 00:00",
tz = format(tme[1], "%Z"))
s <- 0
for (i in 1:length(out)) {
s[i] <- which(tout == out[i])
}
ao <- ao[,,s]
}
ao
}
#' Fits micro- or mesoclimate model
#'
#' @description
#' `fitmicro` is used to fit a micro- or mesoclimate model using field temperature readings, and estimates of reference temperature, net radiation
#' and wind speed at the locations of those readings.
#'
#' @param microfitdata a data.frame with at least the following columns (see, for example, microfit data):
#' \describe{
#' \item{temperature}{microclimate temperature readings}
#' \item{reftemp}{Reference (e.g. coarse-scale or weather station) temperatures}
#' \item{wind}{Wind speeds}
#' \item{netrad}{Net radiation values}
#' }
#' @param alldata an optional logical value indicating whether to fit the model using all data (TRUE) or using a randomization procedure (FALSE). See details.
#' @param windthresh an optional single numeric value indicating the threshold wind speed above which an alternative linear relationship between net radiation the microclimate temperature anomoly is fitted. See details.
#' @param continious an optional logical value indicating whether to treat wind speed as a continious variable.
#' @param iter a single integer specifying the iterations to perform during randomization. Ignored if `alldata` = TRUE.
#'
#' @return a data,frame with the following columns:
#' \describe{
#' \item{Estimate}{parameter estimates and `windthresh`}
#' \item{Std.Dev}{Standard deviation of parameter estimates}
#' \item{P}{Two-tailed p-value}
#' }
#' @export
#' @importFrom stats lm
#' @importFrom stats median
#' @details
#' If modelling mesoclimate, it is assumed that altitudinal, coastal and cold-air
#' drainage effects have already been accounted for in the calculation of `reftemp`.
#' It is therefore assumed that the most important energy fluxes determining near-surface
#' temperature are those due to the radiation flux and convection that occurs at
#' the surface-atmosphere boundary. Heat fluxes into the soil and latent heat
#' exchange are considered to be small and proportional to the net radiation
#' flux, and the heat capacity of the vegetation is considered to be small so
#' that, compared to the time-scale of the model, surface temperature rapidly
#' reach equilibrium. In consequence, the difference between the near-ground
#' temperature and the ambient temperature is a linear function of `netrad`.
#' The gradient of this linear relationship is a measure of the thermal
#' coupling of the surface to the atmosphere. If this relationship is applied
#' to vegetation, assuming the canopy to act like a surface, while air density
#' and the specific heat of air at constant pressure are constant, the slope
#' varies as a function of a wind speed factor, such that different slope values
#' are assumed under high and low wind conditions. Hence, as a default, `fitmicro`
#' fits a linear model of the form `lm((temperature - reftemp) ~ netrad * windfact)`
#' where windfact is given by `ifelse(wind > windthresh, 1, 0)` If `continious` is
#' set to TRUE, then a linear model of the form `lm((temperature - reftemp) ~ netrad * log(wind + 1)`
#' is fitted. If `alldata` is FALSE, random subsets of the data are selected and the analyses repeated
#' `iter` times to reduce the effects of of temporal autocorrelation. Parameter
#' estimates are derived as the median of all runs. If `continious` is set to FALSE
#' and no value is provided for `windthresh`, it is derived by iteratively trying out
#' different values, and selecting that which yields the best fit. The gradient of
#' the relationship is also dependent on vegetation structure, and in some
#' circumstances it may therefore be advisable to fit seperate models for each
#' vegetation type.
#'
#' @examples
#' fitmicro(microfitdata)
#' fitmicro(mesofitdata, alldata = TRUE)
#' fitmicro(mesofitdata, alldata = TRUE, continious = TRUE)
fitmicro <- function(microfitdata, alldata = FALSE, windthresh = NA,
continious = FALSE, iter = 999) {
pvals <- function(x) {
iter <- length(x)
d <- floor(log(iter, 10))
p <- length(x > 0) / iter
p <- ifelse(p > 0.5, 1 - p, p)
p <- round(p * 2, d)
p
}
wthresh <- NA
microfitdata$anom <- microfitdata$temperature - microfitdata$reftemp
if (is.na(windthresh) & continious == FALSE) {
wrange <- floor(max(microfitdata$wind) - min(microfitdata$wind))
rsq <- 0
for (i in 1:100 * wrange) {
wind.fact <- ifelse(microfitdata$wind > (i / 100), 1, 0)
m <- lm(microfitdata$anom ~ microfitdata$netrad * wind.fact)
rsq[i] <- summary(m)$r.squared
}
wthresh <- which(rsq == max(rsq, na.rm = TRUE)) / 100
}
if (alldata) {
if (continious) {
m1 <- summary(lm(anom ~ log(wind + 1) * netrad, data = microfitdata))
} else {
wf <- ifelse(microfitdata$wind > wthresh, 1, 0)
m1 <- summary(lm(microfitdata$anom ~ wf * microfitdata$netrad))
}
mdns <- as.vector(m1$coef[, 1])
sds <- as.vector(m1$coef[, 2]) * sqrt(dim(microfitdata)[1])
pvs <- as.vector(m1$coef[, 4])
} else {
ln <- round(dim(microfitdata)[1] / 100, 0) * 10
pint <- 0
pwf <-0
pnr <- 0
pnrwf <- 0
for (i in 1:iter) {
u <- round(runif(ln, 1, dim(microfitdata)[1]), 0)
one.iter <- microfitdata[u, ]
if (continious == F) {
wf <- ifelse(one.iter$wind > wthresh, 1, 0)
m1 <- lm(one.iter$anom ~ wf * one.iter$netrad)
} else {
lw <- log(one.iter$wind + 1)
m1 <- lm(one.iter$anom ~ lw * one.iter$netrad)
}
pint[i] <- m1$coef[1]
pwf[i] <- m1$coef[2]
pnr[i] <- m1$coef[3]
pnrwf[i] <- m1$coef[4]
}
mdns <- c(median(pint, na.rm = T), median(pwf, na.rm = T),
median(pnr, na.rm = T), median(pnrwf, na.rm = T))
sds <- c(sd(pint, na.rm = T), sd(pwf, na.rm = T), sd(pnr, na.rm = T),
sd(pnrwf, na.rm = T))
pvs <- c(pvals(pint), pvals(pwf), pvals(pnr), pvals(pnrwf))
}
params <- data.frame(Estimate = c(mdns, wthresh), Std.Dev = c(sds, ""),
P = c(pvs, ""))
row.names(params) <- c("Intercept", "Wind factor", "Net radiation",
"Wind factor:Net radiation", "Wind threshold")
if (continious) {
row.names(params)[2] <- "wind"
row.names(params)[5] <- ""
params$Estimate[5] <- ""
}
params$Estimate <- as.numeric(params$Estimate)
params
}
#' Runs micro- or mesoclimate model
#'
#' @description `runmicro` produces a high-resolution dataset of downscaled
#' temperatures for one time interval
#'
#' @param params a data.frame of parameter estimates as produced by [fitmicro()]
#' @param netrad a raster object, two-dimensional array or matrix of downscaled net radiation as produced by [shortwaveveg()] - [longwaveveg()] or [shortwavetopo()] - [longwavetopo()].
#' @param wind a raster object, two-dimensional array or matrix of downscaled wind speed, as produced by reference wind speed x the output of [windcoef()].
#' @param continious an optional logical value indicating whether the model was fitted by treating wind speed as a continious variable.
#' @return a raster object, two-dimensional array or matrix of temperature anomolies from reference temperature, normally in ºC, but units depend on those used in [fitmicro()].
#' @import raster
#' @export
#' @seealso [fitmicro()]
#'
#' @details
#' If `netrad` is a raster object, a raster object is returned.
#' If modelling mesoclimate, it is assumed that altitudinal, coastal and cold-air
#' drainage effects have already been accounted for in the calculation of reference
#' temperature (see example). It is assumed that the most important energy fluxes
#' determining near-surface temperature are those due to the radiation flux and convection
#' that occurs at the surface–atmosphere boundary. Heat fluxes into the soil and latent heat
#' exchange are considered to be small and proportional to the net radiation
#' flux, and the heat capacity of the vegetation is considered to be small so
#' that, compared to the time-scale of the model, surface temperature rapidly
#' reach equilibrium. In consequence, the difference between the near-ground
#' temperature and the ambient temperature is a linear function of `netrad`.
#' The gradient of this linear relationship is a measure of the thermal
#' coupling of the surface to the atmosphere. If this relationship is applied
#' to vegetation, assuming the canopy to act like a surface, while air density
#' and the specific heat of air at constant pressure are constant, the slope
#' varies as a function of a wind speed factor, such that different slope values
#' are assumed under high and low wind conditions.
#'
#' @examples
#' library(raster)
#' # =======================================================================
#' # Run microclimate model for 2010-05-24 11:00 (one of the warmest hours)
#' # =======================================================================
#' params <- fitmicro(microfitdata)
#' netrad <- netshort1m - netlong1m
#' tempanom <- runmicro(params, netrad, wind1m)
#' reftemp <- raster(temp100[,,564])
#' extent(reftemp) <- extent(dtm1m)
#' reftemp <- resample(reftemp, dtm1m)
#' temps <- tempanom + getValues(reftemp, format = "matrix")
#' plot(if_raster(temps, dtm1m), main =
#' expression(paste("Temperature ",(~degree~C))))
#'
#' # ======================================================================
#' # Run mesoclimate model for 2010-05-01 11:00 from first principles
#' # ======================================================================
#'
#' # -------------------------
#' # Resample raster function
#' # -------------------------
#' resampleraster <- function(a, ro) {
#' r <- raster(a)
#' extent(r) <- c(-5.40, -5.00, 49.90, 50.15)
#' crs(r) <- "+init=epsg:4326"
#' r <- projectRaster(r, crs = "+init=epsg:27700")
#' r <- resample(r, ro)
#' as.matrix(r)
#' }
#'
#' # --------------------------
#' # Resample raster: 24 hours
#' # --------------------------
#' get24 <- function(a) {
#' ao <- array(NA, dim = c(dim(dtm1km)[1:2], 24))
#' for (i in 1:24) {
#' ai <- a[,,2880 + i]
#' ao[,,i] <- resampleraster(ai, dtm1km)
#' }
#' ao
#' }
#'
#' # ----------------------------
#' # Derive hourly temperatures
#' # ----------------------------
#' tmax <- tas[,,121] + dtr[,,121] / 2
#' tmin <- tas[,,121] - dtr[,,121] / 2
#' tme <- as.POSIXct(c(0:364) * 24 * 3600, origin="2010-01-01", tz = "GMT")
#' out <- as.POSIXct(c(0:23) * 3600, origin="2010-05-01", tz = "GMT")
#' h <- arrayspline(huss, tme, out = out)
#' p <- arrayspline(pres, tme, out = out)
#' n <- get24(cfc)
#' dni <- get24(dnirad)
#' dif <- get24(difrad)
#' jd <- julday(2010, 5 , 1)
#' tc <- h[,,1] * NA
#' lr <- h[,,1] * NA # Also calculates lapse rate
#' for (i in 1:19) {
#' for (j in 1:22) {
#' if (is.na(tmax[i,j]) == F)
#' {
#' ht <- hourlytemp(jd, em = NA, h[i, j, ], n[i, j, ], p[i, j, ], dni[i, j, ],
#' dif[i, j, ], tmin[i,j], tmax[i,j], 50.02, -5.20)
#' tc[i, j]<- ht[12]
#' lr[i, j] <- lapserate(tc[i, j], h[i, j, 12], p[i, j, 12])
#' }
#' }
#' }
#' # ----------------------------
#' # Calculate coastal effects
#' # ----------------------------
#' sst <- 10.771
#' dT <- if_raster(sst - tc, dtm1km)
#' lsw <- if_raster(landsearatios[,,28], dtm100m) # upwind
#' lsa <- if_raster(apply(landsearatios, c(1, 2), mean), dtm100m) # mean, all directions
#' dTf <- coastalTps(dT, lsw, lsa)
#'
#' # ------------------------------
#' # Calculate altitudinal effects
#' # ------------------------------
#' lrr <- if_raster(lr, dtm1km)
#' lrr <- resample (lrr, dtm100m)
#' tc <- sst - dTf + lrr * dtm100m
#'
#' # ------------------------------
#' # Downscale radiation
#' # ------------------------------
#' dni <- resampleraster(dnirad[,,2891], dtm100m)
#' dif <- resampleraster(difrad[,,2891], dtm100m)
#' n <- resampleraster(cfc[,,2891], dtm100m)
#' h <- resample(if_raster(h[,,12], dtm1km), dtm100m)
#' p <- resample(if_raster(p[,,12], dtm1km), dtm100m)
#' sv <- skyviewtopo(dtm100m)
#' netshort <- shortwavetopo(dni, dif, jd, 11, dtm = dtm100m, svf = sv)
#' netlong <- longwavetopo(h, tc, p, n, sv)
#' netrad <- netshort - netlong
#'
#' # ------------------
#' # Downscale wind
#' # ------------------
#' ws <- array(windheight(wind2010$wind10m, 10, 1), dim = c(1, 1, 8760))
#' wh <- arrayspline(ws, as.POSIXct(wind2010$obs_time), 6, "2010-05-01 11:00")
#' ws <- windcoef(dtm100m, 270, res = 100) * wh
#'
#' # ------------------
#' # Fit and run model
#' # ------------------
#' params <- fitmicro(mesofitdata)
#' anom <- runmicro(params, netrad, ws)
#' tc <- tc + anom
#' plot(mask(tc, dtm100m), main =
#' expression(paste("Mesoclimate temperature ",(~degree~C))))
runmicro <- function(params, netrad, wind, continious = FALSE) {
r <- netrad
netrad <- is_raster(netrad)
wind <- is_raster(wind)
if (continious) {
temp <- params[1, 1] + params[2, 1] * log(wind + 1) + params[3, 1] * netrad +
params[4, 1] * log(wind + 1) * netrad
} else {
wf <- ifelse(wind > params[5, 1], 1, 0)
temp <- params[1, 1] + params[2, 1] * wf + params[3, 1] * netrad +
params[4, 1] * wf * netrad
}
if_raster(temp, r)
}
#' Derives parameters for fitting soil temperatures
#' @export
.fitsoil <- function(soil0, soil200, nmrsoil) {
fitsoilone <- function(soil0, soil200, nmrsoil, x1, x2) {
pred <- nmrsoil[1]
for (i in 2:length(nmrsoil)) {
heatdown <- (soil0[i - 1] - pred[i - 1])
heatup <- (soil200 - pred[i -1])
pred[i] <- pred[i-1] + x1 * heatdown + x2 * heatup
}
difs <- abs(nmrsoil - pred)
sum(difs)
}
fitloop <- function(xs1, xs2, x1add, x2add) {
dfa <- data.frame(x1 = 0, x2 = 0, dif = 0)
for (ii in 1:length(xs1)) {
for (jj in 1:length(xs2)) {
x1 <- xs1[ii] + x1add
x2 <- xs2[jj] + x2add
dif <- fitsoilone(soil0, soil200, nmrsoil, x1, x2)
df1 <- data.frame(x1 = x1, x2 = x2, dif = dif)
dfa <- rbind(dfa, df1)
}
}
dfa <- dfa[-1,]
sel <- which(dfa$dif == min(dfa$dif, na.rm = T))
dfa[sel,]
}
xs1 <- c(0:10)
xs2 <- c(0:10)
dfo <- fitloop(xs1, xs2, 0, 0)
if (dfo$x1 > 0 ) {
xs1 <- c(-10:10) / 10
} else xs1 <- c(0:10) / 10
if (dfo$x2 > 0 ) {
xs2 <- c(-10:10) / 10
} else xs2 <- c(0:10) / 10
dfo <- fitloop(xs1, xs2, dfo$x1, dfo$x2)
if (dfo$x1 > 0 ) {
xs1 <- c(-10:10) / 100
} else xs1 <- c(0:10) / 100
if (dfo$x2 > 0 ) {
xs2 <- c(-10:10) / 100
} else xs2 <- c(0:10) / 100
dfo <- fitloop(xs1, xs2, dfo$x1, dfo$x2)
if (dfo$x1 > 0 ) {
xs1 <- c(-10:10) / 1000
} else xs1 <- c(0:10) / 1000
if (dfo$x2 > 0 ) {
xs2 <- c(-10:10) / 1000
} else xs2 <- c(0:10) / 1000
dfo <- fitloop(xs1, xs2, dfo$x1, dfo$x2)
if (dfo$x1 > 0 ) {
xs1 <- c(-10:10) / 10000
} else xs1 <- c(0:10) / 10000
if (dfo$x2 > 0 ) {
xs2 <- c(-10:10) / 10000
} else xs2 <- c(0:10) / 10000
dfo <- fitloop(xs1, xs2, dfo$x1, dfo$x2)
if (dfo$x1 > 0 ) {
xs1 <- c(-10:10) / 100000
} else xs1 <- c(0:10) / 100000
if (dfo$x2 > 0 ) {
xs2 <- c(-10:10) / 100000
} else xs2 <- c(0:10) / 100000
dfo <- fitloop(xs1, xs2, dfo$x1, dfo$x2)
dfo
}
#' Derives leaf area index, leaf geometry and canopy height from habitat
#'
#' @description `laifromhabitat` generates an hourly dataset for an entire year of
#' leaf area index values, the ratio of vertical to horizontal projections of leaf
#' foliage and canopy height from habitat.
#'
#' @param habitat a character string or numeric value indicating the habitat type. See [habitats()]
#' @param lat a single numeric value representing the mean latitude of the location for which the solar index is required (decimal degrees, -ve south of the equator).
#' @param long a single numeric value representing the mean longitude of the location for which the solar index is required (decimal degrees, -ve west of Greenwich meridian).
#' @param meantemp an optional numeric value of mean annual temperature (ºC) at reference height.
#' @param cvtemp an optional numeric value of the coefficient of variation in temperature (K per 0.25 days) at reference height.
#' @param rainfall an optional numeric value mean annual rainfall (mm per year)
#' @param cvrain an optional numeric value of the coefficient of variation in raifall (mm per 0.25 days) at reference height.
#' @param wetmonth an optional numeric value indicating which month is wettest (1-12).
#' @param year the year for which data are required.
#' @return a list with the following items, (1) lai: hourly leaf area index values,
#' (2) x: the ratio of vertical to horizontal projections of leaf foliage,
#' (3) height: the heigbht of the canopy in metres and (4) obs_time: an object of
#' class POSIXlt of dates and times coressponding to each value of lai.
#' @export
#' @seealso [lai()], [leaf_geometry()]
#'
#' @details
#' If no values of `meantemp`, `cvtemp`, `rainfall`, `cvrain` or `wetmonth` are
#' provided, values are obtained from [globalclimate()]. Variable `lai` is derived by fitting
#' a Gaussian curve parameters of which are climate and location-dependent. Functional
#' fits were calibrated using MODIS data (see https://modis.gsfc.nasa.gov/data/).
#'
#' @examples
#' lxh <- laifromhabitat("Deciduous broadleaf forest", 50, -5.2, 2015)
#' lxh$height
#' lxh$x
#' plot(lxh$lai ~ as.POSIXct(lxh$obs_time), type = "l", xlab = "Month",
#' ylab = "LAI", ylim = c(0, 6))
laifromhabitat <- function(habitat, lat, long, year, meantemp = NA, cvtemp = NA,
rainfall = NA, cvrain = NA, wetmonth = NA) {
laigaus <- function(minlai, maxlai, pkday, dhalf, yr) {
diy <- 365
sdev <- 0.0082 * dhalf^2 + 0.0717 * dhalf + 13.285
difv <- maxlai - minlai
x<-c(-diy:diy)
y <- 1 / (sdev * sqrt(2 * pi)) * exp(-0.5 * (((x - 0) / sdev) ^ 2))
y[(diy + ceiling(0.5 * diy)):(2 * diy + 1)] <- y[(diy - ceiling(0.5 * diy)):diy]
st <- diy + 1 - pkday
y <- y[st:(st + diy - 1)]
x <- c(1:diy)
x <- c(0, x, c(366:375))
y <- c(y[diy], y, y[1:10])
sel <-c(0:15) * 25 + 1
x<-x[sel]
y<-y[sel]
tme <- as.POSIXct((x * 24 * 3600), origin = paste0(yr - 1,"-12-31 12:00"), tz = "GMT")
xy <- spline(tme, y, n = diy * 24 + 241)
tme2 <- as.POSIXlt(xy$x, origin = "1970-01-01 00:00", tz = "GMT")
sel <- which(tme2$year + 1900 == yr)
y <- xy$y[sel]
dify <- max(y) - min(y)
y <- y * (difv / dify)
y <- y + minlai - min(y)
return(y)
}
long <- ifelse(long > 180.9375, long - 360, long)
long <- ifelse(long < -179.0625, long + 360, long)
ll <- SpatialPoints(data.frame(x = long, y = lat))
diy <- 366
if (year%%4 == 0) diy <- 366
if (year%%100 == 0 & year%%400 != 0) diy <- 365
mmonth <-c(16, 45.5, 75, 105.5, 136, 166.5, 197, 228, 258.5, 289, 319.5, 350)
if (diy == 365) mmonth[2:12] <- mmonth[2:12] + 0.5
e <- extent(c(-179.0625, 180.9375, -89.49406, 89.49406))
clim <- c(meantemp, cvtemp, rainfall, cvrain, wetmonth)
for (i in 1:5) {
if (is.na(clim[i])) {
r <- raster(globalclimate[,,i])
extent(r) <- e
clim[i] <- extract(r, ll)
}
}
wgts <- function(x1, x2, ll, lmn, lmx) {
ll <- ifelse(ll < lmn, lmn, lat)
ll <- ifelse(ll > lmx, lmx, lat)
w <- 1 - (abs(ll - lmn) / (abs(ll - lmn) + abs(ll - lmx)))
y <- w * x1 + (1 - w) * x2
y
}
# By habitat type
if (habitat == "Evergreen needleleaf forest" | habitat == 1) {
h2 <- 74.02 + 5.35 * clim[1]
h1 <- 203.22 - 35.63 * clim[4]
hperiod <- wgts(h1, h2, abs(lat), 0, 20)
hperiod <- ifelse(hperiod < 50, 50, hperiod)
p2 <- 216.71 - 2.65 * clim[1]
p2 <- ifelse(p2 > 244, 244, p2)
if (lat < 0) p2 <- (p2 + diy / 2)%%diy
p1 <- mmonth[round(clim[5], 0)]
peakdoy <- wgts(p1, p2, abs(lat), 0, 30)
if (clim[1] <= 20) {
maxlai <- 2.33 + 0.0132 * clim[1]
} else maxlai <- 2.33 + 0.0132 * 20
minlai <- 1.01
x <- 0.4
hgt <- 10
}
if (habitat == "Evergreen Broadleaf forest" | habitat == 2) {
hperiod <- 154.505 + 2.040 * clim[1]
hperiod <- ifelse(hperiod < 50, 50, hperiod)
peakdoy <- peakdoy <- mmonth[round(clim[5], 0)]
maxlai <- 1.83 + 0.22 * log(clim[3])
minlai <- (-1.09) + 0.4030 * log(clim[3])
minlai <- ifelse(minlai < 1, 1, minlai)
x <- 1.2
hgt <- 20
}
if (habitat == "Deciduous needleleaf forest" | habitat == 3) {
h2 <- 51.18 + 3.77 * clim[1]
h1 <- 152
hperiod <- wgts(h1, h2, abs(lat), 0, 20)
p2 <- 204.97 - 1.08 * clim[1]
p2 <- ifelse(p2 > 244, 244, p2)
if (lat < 0) p2 <- (p2 + diy / 2)%%diy
p1 <- mmonth[round(clim[5], 0)]
peakdoy <- wgts(p1, p2, abs(lat), 0, 30)
if (clim[1] <= 20) {
maxlai <- 2.62 + 0.05 * clim[1]
} else maxlai <- 2.62 + 0.05 * 20
minlai <- 0.39
x <- 0.4
hgt <- 10
}
if (habitat == "Deciduous broadleaf forest" | habitat == 4) {
h2 <- 47.6380 + 2.9232 * clim[1]
h1 <- 220.06 - 79.19 * clim[4]
hperiod <- wgts(h1, h2, abs(lat), 0, 20)
hperiod <- ifelse(hperiod < 32.5, 32.5, hperiod)
p2 <- 209.760 - 1.208 * clim[1]
p2 <- ifelse(p2 > 244, 244, p2)
if (lat < 0) p2 <- (p2 + diy / 2)%%diy
p1 <- mmonth[round(clim[5], 0)]
peakdoy <- wgts(p1, p2, abs(lat), 0, 30)
if (clim[1] <= 20) {
maxlai <- 3.98795 + 0.03330 * clim[1]
} else maxlai <- 3.98795 * 0.03330 * 20
minlai <- 0.4808
x <- 1.2
hgt <- 15
}
if (habitat == "Mixed forest" | habitat == 5) {
warning("Results highly sensitive to forest composition. Suggest running
seperately for constituent forest types and weighting output")
h2 <- 74.02 + 5.35 * clim[1]
h1 <- 203.22 - 35.63 * clim[4]
hperiod1 <- wgts(h1, h2, abs(lat), 0, 20)
h2 <- 51.18 + 3.77 * clim[1]
h1 <- 152
hperiod2 <- wgts(h1, h2, abs(lat), 0, 20)
hperiod <- (hperiod1 + hperiod2) / 2
hperiod <- ifelse(hperiod < 30.5, 30.5, hperiod)
p2 <- 216.71 - 2.65 * clim[1]
p2 <- ifelse(p2 > 244, 244, p2)
if (lat < 0) p2 <- (p2 + diy / 2)%%diy
p1 <- mmonth[round(clim[5], 0)]
peakdoy1 <- wgts(p1, p2, abs(lat), 0, 30)
p2 <- 204.97 - -1.08 * clim[1]
p2 <- ifelse(p2 > 244, 244, p2)
if (lat < 0) p2 <- (p2 + diy / 2)%%diy
peakdoy2 <- wgts(p1, p2, abs(lat), 0, 30)
peakdoy <- (peakdoy1 + peakdoy2) / 2
if (clim[1] <= 20) {
maxlai1 <- 2.33 + 0.0132 * clim[1]
maxlai2 <- 2.62 + 0.05 * clim[1]
maxlai <- (maxlai1 + maxlai2) / 2
} else maxlai <- 3.107
minlai <- 0.7
x <- 0.8
hgt <- 10
}
if (habitat == "Closed shrublands" | habitat == 6) {
h2 <- 33.867 + 6.324 * clim[1]
h1 <- 284.20 - 102.51 * clim[4]
hperiod <- wgts(h1, h2, abs(lat), 0, 20)
hperiod <- ifelse(hperiod < 30.5, 30.5, hperiod)
p2 <- 223.55 - 3.125 * clim[1]
p2 <- ifelse(p2 > 244, 244, p2)
if (lat < 0) p2 <- (p2 + diy / 2)%%diy
p1 <- mmonth[round(clim[5], 0)]
peakdoy <- wgts(p1, p2, abs(lat), 0, 30)
maxlai <- 2.34
minlai <- -0.4790 + 0.1450 * log(clim[3])
minlai <- ifelse(minlai < 0.001, 0.001, minlai)
x <- 1
hgt <- 2
}
if (habitat == "Open shrublands" | habitat == 7) {
h2 <- 8.908 + 4.907 * clim[1]
h1 <- 210.09 - 28.62 * clim[4]
hperiod <- wgts(h1, h2, abs(lat), 0, 20)
hperiod <- ifelse(hperiod < 38.3, 38.3, hperiod)
p2 <- 211.7 - 4.085 * clim[1]
p2 <- ifelse(p2 > 244, 244, p2)
if (lat < 0) p2 <- (p2 + diy / 2)%%diy
p1 <- mmonth[round(clim[5], 0)]
peakdoy <- wgts(p1, p2, abs(lat), 0, 30)
maxlai <- -0.7206 + 0.272 * log(clim[3])
minlai <- -0.146 + 0.059 * log(clim[3])
minlai <- ifelse(minlai < 0.001, 0.001, minlai)
x <- 0.7
hgt <- 1.5
}
if (habitat == "Woody savannas" | habitat == 8) {
hperiod1 <- 47.6380 + 2.9232 * clim[1]
hperiod1 <- ifelse(hperiod1 < 32.5, 32.5, hperiod1)
hperiod2 <- 71.72 + 3.012 * clim[1]
h1 <- (hperiod1 + hperiod2) / 2
h2 <- 282.04 - 92.28 * clim[4]
h2 <- ifelse(hperiod1 < 31.9, 31.9, hperiod1)
hperiod <- wgts(h1, h2, abs(lat), 25, 35)
peakdoy1 <- 209.760 - 1.208 * clim[1]
peakdoy1 <- ifelse(peakdoy1 > 244, 244, peakdoy1)
if (lat < 0) peakdoy1 <- ( peakdoy1 + diy / 2)%%diy
peakdoy2 <- 211.98 - 3.4371 * clim[1]
peakdoy2 <- ifelse(peakdoy2 > 244, 244, peakdoy2)
if (lat < 0) peakdoy2 <- (peakdoy2 + diy / 2)%%diy
p2 <- (peakdoy1 + peakdoy2) / 2
p1 <- mmonth[round(clim[5], 0)]
peakdoy <- wgts(p1, p2, abs(lat), 10, 40)
if (clim[1] <= 20) {
maxlai1 <- 3.98795 + 0.03330 * clim[1]
maxlai2 <- 1.0532 * 0.016 * clim[1]
} else {
maxlai1 <- 3.98795 + 0.03330 * 20
maxlai2 <- 1.0532 * 0.016 * 20
}
mx2 <- (maxlai1 + maxlai2) / 2
minlai1 <- 0.4808
minlai2 <- 0.0725 * 0.011 * clim[1]
mn2 <- (minlai1 + minlai2) / 2
mx1 <- 1.298 + 0.171 * log(clim[3])
mn1 <- -2.9458 + 0.5889 * log(clim[3])
maxlai <- wgts(mx1, mx2, abs(lat), 10, 40)
minlai <- wgts(mn1, mn2, abs(lat), 10, 40)
minlai <- ifelse(minlai < 0.0362, 0.0362, minlai)
x <- 0.7
hgt <- 3
}
if (habitat == "Savannas" | habitat == 9 |
habitat == "Short grasslands" | habitat == 10 |
habitat == "Tall grasslands" | habitat == 11) {
h2 <- 71.72 + 3.012 * clim[1]
h1 <- 269.22 - 89.79 * clim[4]
hperiod <- wgts(h1, h2, abs(lat), 0, 20)
hperiod <- ifelse(hperiod < 31.9, 31.9, hperiod)
p2 <- 211.98 - 3.4371 * clim[1]
p2 <- ifelse(p2 > 244, 244, p2)
if (lat < 0) p2 <- (p2 + diy / 2)%%diy
p1 <- mmonth[round(clim[5], 0)]
peakdoy <- wgts(p1, p2, abs(lat), 0, 30)
mx2 <- 1.48
mn2 <- 0.0725 * 0.011 * clim[1]
mx1 <- 0.1215 + 0.2662 * log(clim[3])
mn1 <- 0.331 + 0.0575 * log(clim[3])
maxlai <- wgts(mx1, mx2, abs(lat), 10, 40)
minlai <- wgts(mn1, mn2, abs(lat), 10, 40)
minlai <- ifelse(minlai < 0.762, 0.762, minlai)
x <- 0.15
if (habitat == "Savannas" | habitat == 9) hgt <- 1.5
if (habitat == "Short grasslands" | habitat == 10) hgt <- 0.25
if (habitat == "Tall grasslands" | habitat == 11) hgt <- 1.5
}
if (habitat == "Permanent wetlands" | habitat == 12) {
h2 <- 76 + 4.617 * clim[1]
h1 <- 246.68 - 66.82 * clim[4]
hperiod <- wgts(h1, h2, abs(lat), 0, 20)
hperiod <- ifelse(hperiod < 40, 40, hperiod)
p2 <- 219.64 - 2.793 * clim[1]
p2 <- ifelse(p2 > 244, 244, p2)
if (lat < 0) p2 <- (p2 + diy / 2)%%diy
p1 <- mmonth[round(clim[5], 0)]
peakdoy <- wgts(p1, p2, abs(lat), 0, 30)
maxlai <- -0.1782 + 0.2608 * log(clim[3])
maxlai <- ifelse(maxlai < 1.12, 1.12, maxlai)
minlai <- -0.1450 + 0.1440 * log(clim[3])
minlai <- ifelse(minlai < 0.001, 0.001, minlai)
x <- 1.4
hgt <- 0.5
}
if (habitat == "Croplands" | habitat == 13) {
h2 <- 54.893 + 1.785 * clim[1]
h1 <- 243 - 112.18 * clim[4]
hperiod <- wgts(h1, h2, abs(lat), 10, 30)
hperiod <- ifelse(hperiod < 43.5, 43.5, hperiod)
p2 <- 212.95 - 5.627 * clim[1]
p2 <- ifelse(p2 > 244, 244, p2)
if (lat < 0) p2 <- (p2 + diy / 2)%%diy
p1 <- mmonth[round(clim[5], 0)]
peakdoy <- wgts(p1, p2, abs(lat), 0, 30)
if (clim[1] <= 20) {
maxlai <- 3.124 - 0.0886 * clim[1]
} else maxlai <- 3.124 - 0.0886 * 20
maxlai <- ifelse(maxlai > 3.14, 3.14, maxlai)
minlai <- 0.13
x <- 0.2
hgt <- 0.5
}
if (habitat == "Urban and built-up" | habitat == 14) {
h2 <- 66.669 + 5.618 * clim[1]
h1 <- 283.44 - 86.11 * clim[4]
hperiod <- wgts(h1, h2, abs(lat), 0, 20)
hperiod <- ifelse(hperiod < 43.5, 43.5, hperiod)
p2 <- 215.998 - 4.2806 * clim[1]
p2 <- ifelse(p2 > 244, 244, p2)
if (lat < 0) p2 <- (p2 + diy / 2)%%diy
p1 <- mmonth[round(clim[5], 0)]
peakdoy <- wgts(p1, p2, abs(lat), 10, 30)
if (clim[1] <= 20) {
maxlai <- 1.135 - 0.0244 * clim[1]
} else maxlai <- 1.135 - 0.0244 * 20
maxlai <- ifelse(maxlai > 1.15, 1.15, maxlai)
minlai <- 0.28
x <- 1
hgt <- 0.8
}
if (habitat == "Cropland/Natural vegetation mosaic" | habitat == 15) {
warning("Results highly sensitive to habitat composition. Suggest running
seperately for constituent habitat types and weighting output")
h2 <- 29.490 + 8.260 * clim[1]
h1 <- 326.46 - 161.70 * clim[4]
hperiod <- wgts(h1, h2, abs(lat), 10, 30)
hperiod <- ifelse(hperiod < 43.5, 43.5, hperiod)
p2 <- 210.867 - 3.5464 * clim[1]
p2 <- ifelse(p2 > 244, 244, p2)
if (lat < 0) p2 <- (p2 + diy / 2)%%diy
p1 <- mmonth[round(clim[5], 0)]
peakdoy <- wgts(p1, p2, abs(lat), 10, 30)
if (clim[1] <= 20) {
maxlai <- 3.5485 - 0.09481 * clim[1]
} else maxlai <- 3.5485 - 0.09481 * 20
maxlai <- ifelse(maxlai > 3.14, 3.14, maxlai)
if (clim[1] <= 20) {
minlai <- -0.072815 - 0.044546 * clim[1]
} else minlai <- -0.072815 - 0.044546 * 20
minlai <- ifelse(minlai < 0.001, 0.001, minlai)
x <- 0.5
hgt <- 1
}
if (habitat == "Barren or sparsely vegetated" | habitat == 16) {
h2 <- 80.557 + 6.440 * clim[1]
h1 <- 344.65 - -191.94 * clim[4]
hperiod <- wgts(h1, h2, abs(lat), 0, 20)
hperiod <- ifelse(hperiod < 43.5, 43.5, hperiod)
p2 <- 236.0143 - 3.4726 * clim[1]
p2 <- ifelse(p2 > 244, 244, p2)
if (lat < 0) p2 <- (p2 + diy / 2)%%diy
p1 <- mmonth[round(clim[5], 0)]
peakdoy <- wgts(p1, p2, abs(lat), 10, 30)
maxlai <- -0.05491 + 0.05991 * log(clim[4])
maxlai <- ifelse(maxlai < 0.81, 0.81, maxlai)
minlai <- 0.08
x <- 0.6
hgt <- 0.15
}
if (habitat == "Open water" | habitat == 17) {
hperiod <- 100
peakdoy <- 50
maxlai <- 0
minlai <- 0
hgt <- 0
}
lai <- laigaus(minlai, maxlai, peakdoy, hperiod, year)
if (habitat == "Short grasslands" | habitat == 10) lai <- lai / 2
tme <- c(1:length(lai)) - 1
tme <- as.POSIXlt(tme * 3600, origin = paste0(year,"-01-01 00:00"), tz = "UTC")
return(list(lai = lai, x = x, height = hgt, obs_time = tme))
}
| /R/othertools.R | no_license | Ran-Zhang/microclima | R | false | false | 54,054 | r | #' Converts between different measures of humidity
#'
#' @description `humidityconvert` is used to convert between different measures of humidity, namely relative, absolute or specific. Vapour pressure is also returned.
#'
#' @param h humidity value(s). Units as follows: specific humidity (\ifelse{html}{\out{kg kg<sup>-1</sup>}}{\eqn{kg kg^{-1}}}), absolute humidity (\ifelse{html}{\out{kg m<sup>-3</sup> }}{\eqn{kg m^{-3}}}), relative humidity (\%), vapour pressure (kPa).
#' @param intype a character string description of the humidity type of `h`. One of "relative", "absolute" or "specific".
#' @param tc A numeric value specifying the temperature (ºC).
#' @param p An optional numeric value specifying the atmospheric pressure (Pa).
#'
#' @details This function converts between vapour pressure and specific,
#' relative and absolute humidity, based on sea-level pressure and
#' temperature. It returns a list of relative, absolute and specific
#' humidity and vapour pressure. If `intype` is unspecified, then `h` is
#' assumed to be relative humidity. If `p` is unspecified, pressure assumed
#' to be 101300, a typical value for sea-level pressure. If one or more of the
#' relative humidity values exceeds 100\% a warning is given.
#'
#' @return a list of numeric humidity values with the following components:
#' @return `relative` relative humidity (\%).
#' @return `absolute` absolute humidity (\ifelse{html}{\out{kg m<sup>-3</sup> }}{\eqn{kg m^{-3}}}).
#' @return `specific` specific humidity (\ifelse{html}{\out{kg kg<sup>-1</sup> }}{\eqn{kg kg^{-1}}}).
#' @return `vapour_pressure` vapour pressure (kPa).
#' @export
#'
#' @examples
#' humidityconvert(90, 'relative', 20)
#' humidityconvert(0.01555486, 'absolute', 20)
#' humidityconvert(0.01292172, 'specific', 20)
humidityconvert <- function(h, intype = "relative", tc = 20, p = 101300) {
tk <- tc + 273.15
pk <- p / 1000
if (intype != "specific" & intype != "relative" & intype != "absolute") {
warning ("No valid input humidity specified. Humidity assumed to be
relative")
intype <- "relative"
}
e0 <- 0.6108 * exp(17.27 * tc / (tc + 237.3))
ws <- 0.622 * e0 / pk
if (intype == "specific") {
e0 <- 0.6108 * exp(17.27 * tc / (tc + 237.3))
hr <- (h / ws) * 100
}
if (intype == "absolute") {
ea <- (tk * h) / 2.16679
hr <- (ea / e0) * 100
}
if (intype == "relative") hr <- h
if (max(hr, na.rm = T) > 100) warning(paste("Some relative humidity values > 100%",
max(hr, na.rm = T)))
ea <- e0 * (hr / 100)
hs <- (hr / 100) * ws
ha <- 2.16679 * (ea / tk)
return(list(relative = hr, absolute = ha, specific = hs,
vapour_pressure = ea))
}
#' Calculates land to sea ratio in upwind direction
#'
#' @description `invls` is used to calculate an inverse distance\ifelse{html}{\out{<sup>2</sup>}}{\eqn{^2}} weighted ratio of land to sea in a specified upwind direction.
#'
#' @param landsea A raster object with NAs (representing sea) or any non-NA value (representing land). The object should have a larger extent than that for which land-sea ratio values are needed, as the calculation requires land / sea coverage to be assessed upwind outside the target area.
#' @param e an extent object indicating the region for which land-sea ratios are required.
#' @param direction an optional single numeric value specifying the direction (decimal degrees) from which the wind is blowing.
#'
#' @details This function calculates a coefficient of the ratio of land to
#' sea pixels in a specified upwind direction, across all elements of a
#' raster object, weighted using an inverse distance squared function,
#' such that nearby pixels have a greater influence on the coefficient.
#' It returns a raster object representing values ranging between zero
#' (all upwind pixels sea) to one (all upwind pixels land). Upwind
#' direction is randomly varied by ± `jitter.amount` degrees.
#'
#' @return a raster object with distance-weighted proportions of upwind land pixels
#' @import raster rgdal
#' @importFrom sp coordinates
#' @useDynLib microclima, .registration = TRUE
#' @importFrom Rcpp sourceCpp
#' @export
#'
#' @examples
#' library(raster)
#' ls1 <- invls(dtm100m, extent(dtm1m), 180)
#' ls2 <- invls(dtm100m, extent(dtm1m), 270)
#' par(mfrow=c(2,1))
#' plot(ls1, main = "Land to sea weighting, southerly wind")
#' plot(ls2, main = "Land to sea weighting, westerly wind")
invls <- function(landsea, e, direction) {
e2 <- extent(landsea)
maxdist <- sqrt(xres(landsea) * (e2@xmax - e2@xmin) +
yres(landsea) * (e2@ymax - e2@ymin))
resolution <- xres(landsea)
slr <- landsea * 0 + 1
m <- is_raster(slr)
m[is.na(m)] <- 0
slr <- if_raster(m, slr)
s <- c(0, (8:1000) / 8) ^ 2 * resolution
s <- s[s <= maxdist]
lss <- crop(slr, e, snap = 'out')
lsm <- getValues(lss, format = "matrix")
lsw <- array(NA, dim = dim(lsm))
lsw <- invls_calc(lsm, resolution, e@xmin, e@ymax, s, direction, raster::as.matrix(slr),
raster::xmin(slr),raster::xmax(slr),raster::ymin(slr),raster::ymax(slr))
lsr <- raster(lsw, template = lss)
lsr
}
#' Calculates coastal effects using thin-plate spline
#'
#' @description `coastalTps` uses thin-plate spline interpolation to estimate
#' the effects of coastal buffering of land-temperatures by the sea.
#'
#' @param dT a coarse-resolution raster of sea - land temperatures (ºC).
#' @param lsw a fine-resolution raster of coastal exposure upwind, as produced by [invls()].
#' @param lsa a fine-resolution raster of mean coastal exposure in all directions.
#' @return a fine-resolution raster of sea - land temperature differences (ºC).
#' @export
#' @importFrom rgcvpack fitTps
#' @importFrom rgcvpack predict.Tps
#'
#' @examples
#' library(raster)
#' # =========================================
#' # Calculate land-sea temperature difference
#' # =========================================
#' temp <- tas[,,1]
#' sst <- 10.665
#' dT <- if_raster(sst - temp, dtm1km)
#' # ============================
#' # Obtain coastal exposure data
#' # ============================
#' lsw <- landsearatios[,,7] # upwind
#' lsa <- apply(landsearatios, c(1, 2), mean) # mean, all directions
#' lsw <- if_raster(lsw, dtm100m)
#' lsa <- if_raster(lsa, dtm100m)
#' # ==========================================================
#' # Calculate coastal effects using thin-plate spline and plot
#' # ==========================================================
#' dTf <- coastalTps(dT, lsw, lsa)
#' par(mfrow = c(2, 1))
#' plot(sst - dT, main = expression(paste("Temperature ",(~degree~C))))
#' plot(sst - dTf, main = expression(paste("Temperature ",(~degree~C))))
coastalTps <- function(dT, lsw, lsa) {
lswc <- resample(lsw, dT)
lsac <- resample(lsa, dT)
xy <- data.frame(xyFromCell(lswc, 1:ncell(dT)))
z1 <- extract(lswc, xy)
z2 <- extract(lsac, xy)
v <- extract(dT, xy)
xyz <- cbind(xy, z1, z2)
sel <- which(is.na(v) == F)
v <- v[is.na(v) == F]
xyz <- xyz[sel, ]
tps <- fitTps(xyz, v, m = 3)
xy <- data.frame(xyFromCell(lsw, 1:ncell(lsw)))
z1 <- extract(lsw, xy)
z2 <- extract(lsa, xy)
xyz <- cbind(xy, z1, z2)
sel <- which(is.na(z1) == FALSE)
xyz <- xyz[sel, ]
xy$z <- NA
xy$z[sel] <- predict.Tps(tps, xyz)
r <- rasterFromXYZ(xy)
r
}
#' Calculates the moist adiabatic lapse rate
#'
#' @description `lapserate` is used to calculate changes in temperature with height.
#'
#' @param tc a single numeric value, raster object, two-dimensional array or matrix of temperature (ºC).
#' @param h a single numeric value, raster object, two-dimensional array or matrix of specific humidity (\ifelse{html}{\out{kg kg<sup>-1</sup> }}{\eqn{kg kg^{-1}}}).
#' @param p an optional single numeric value, raster object, two-dimensional array or matrix of atmospheric pressure (Pa).
#'
#' @return the lapse rate (\ifelse{html}{\out{º m<sup>-1</sup> }}{\eqn{ º m^{-1}}}).
#' @export
#' @import raster
#'
#' @details if tc is a raster, a raster object is returned. This function calculates the
#' theoretical lapse rate. Environmental lapse rates can vary due to winds.
#'
#' @examples
#' lapserate(20, 0) * 1000 # dry lapse rate per km
#' h <- humidityconvert(100, intype = "relative", 20)
#' lapserate(20, h$specific) * 1000 # lapse rate per km when relative humidity is 100%
lapserate <- function(tc, h, p = 101300) {
r <- tc
tc <- is_raster(tc)
h <- is_raster(h)
p <- is_raster(p)
pk <- p / 1000
e0 <- 0.6108 * exp(17.27 * tc / (tc + 237.3))
ws <- 0.622 * e0 / pk
rh <- (h / ws) * 100
rh[rh > 100] <- 100
ea <- e0 * (rh / 100)
rv <- 0.622 * ea / (pk - ea)
lr <- 9.8076 * (1 + (2501000 * rv) / (287 * (tc + 273.15))) / (1003.5 +
(0.622 * 2501000 ^ 2 * rv) / (287 * (tc + 273.15) ^ 2))
lr <- lr * -1
if_raster(lr, r)
}
#' Applies height correction to wind speed measurements
#'
#' @description `windheight` is used to to apply a height correction to wind speed measured at a specified height above ground level to obtain estimates of wind speed at a desired height above the ground.
#'
#' @param ui numeric value(s) of measured wind speed (\ifelse{html}{\out{m s<sup>-1</sup> }}{\eqn{ m s^{-1}}}) at height `zi` (m).
#' @param zi a numeric value idicating the height (m) above the ground at which `ui` was measured.
#' @param zo a numeric value indicating the height (m) above ground level at which wind speed is desired.
#'
#' @details Thus function assumes a logarithmic height profile to convert
#' wind speeds. It performs innacurately when `uo` is lower than 0.2
#' and a warning is given. If `uo` is below ~0.08 then the logairthmic height
#' profile cannot be used, and `uo` is converted to 0.1 and a warning given.
#'
#' @seealso The function [windcoef()] calculates a topographic or vegetation sheltering effect.
#'
#' @return numeric values(s) of wind speed at height specified by `zo` (\ifelse{html}{\out{m s<sup>-1</sup> }}{\eqn{m s^{-1}}}).
#' @export
#'
#' @examples
#' windheight(3, 10, 1) # good
#' windheight(3, 10, 0.15) # performs poorly. Warning given
#' windheight(3, 10, 0.05) # cannot calculate. ui converted and warning given
#'
windheight <- function(ui, zi, zo) {
if (zo < 0.2 & zo > (5.42 / 67.8)) {
warning("Wind-height profile function performs poorly when wind
height is below 20 cm")
}
if (zo <= (5.42 / 67.8)) {
warning(paste("wind-height profile cannot be calculated for height ",
zo * 100, " cm"))
print("Height converted to 10 cm")
zo <- 0.1
}
uo <- ui * log(67.8 * zo - 5.42) / log(67.8 * zi - 5.42)
uo
}
#' Calculates wind shelter coefficient
#'
#' @description `windcoef` is used to apply a topographic shelter coefficient to wind data.
#'
#' @param dsm raster object, two-dimensional array or matrix of elevations (m) derived either from a digital terrain or digital surface model, and orientated as if derived using [is_raster()]. I.e. `[1, 1]` is the NW corner.
#' @param direction a single numeric value specifying the direction from which the wind is blowing (º).
#' @param hgt a single numeric value specifying the height (m) at which wind speed is derived or measured. The wind speeds returned are also for this height, and account for the fact topography affords less shelter to wind at greater heights.
#' @param res a single numeric value specifying the the resolution (m) of `dsm`.
#'
#' @details If dsm is a raster object, then a raster object is returned.
#' If elevations are derived from a digital terrain model, then
#' the sheltering effects of vegetation are ignored. If derived from a
#' digital surface model, then the sheltering effects of vegetation are
#' accounted for. If `res` is unspecified `dtm` is assumed to have a resolution of one m.
#'
#' @seealso The function [windheight()] converts measured wind heights to a standard reference height.
#'
#' @return a raster object, or two-dimensional array of shelter coefficients. E.g. a shelter coefficient of 0.5 indicates that wind speed at that location is 0.5 times that measured at an unobscured location.
#' @import raster
#' @export
#'
#' @examples
#' library(raster)
#' dsm <- dtm1m + veg_hgt
#' wc <- windcoef(dsm, 0)
#' plot(mask(wc, dtm1m), main ="Northerly wind shelter coefficient")
windcoef <- function(dsm, direction, hgt = 1, res = 1) {
r <- dsm
dsm <- is_raster(dsm)
dsm[is.na(dsm)] <- 0
dtm <- dsm / res
hgt <- hgt / res
direction <- direction - 90
azi <- direction * (pi / 180)
horizon <- array(0, dim(dtm))
dtm3 <- array(0, dim(dtm) + 200)
x <- dim(dtm)[1]
y <- dim(dtm)[2]
dtm3[101:(x + 100), 101:(y + 100)] <- dtm
for (step in 1:10) {
horizon[1:x, 1:y] <- pmax(horizon[1:x, 1:y], (dtm3[(101 + sin(azi) *
step ^ 2):(x + 100 + sin(azi) * step ^ 2),
(101 + cos(azi) * step ^ 2 ):(y + 100 + cos(azi) *
step ^ 2)] - dtm3[101:(x + 100), 101 : (y + 100)]) /
step ^ 2)
horizon[1:x, 1:y] <- ifelse(horizon[1:x, 1:y] < (hgt / step ^ 2), 0,
horizon[1:x, 1:y])
}
index <- 1 - atan(0.17 * 100 * horizon) / 1.65
index <- if_raster(index, r)
index
}
#' Calculates sunrise, sunset and daylength
#'
#' @description `suntimes` is used to calculate, sunrise, sunset and daylength on any given data at a specified location.
#'
#' @param julian the Julian day as returned by [julday()].
#' @param lat latitude of the location for which `suntime` is required (decimal degrees, -ve south of equator).
#' @param long longitude of the location for which `suntime` is required (decimal degrees, -ve west of Greenwich meridian).
#' @param merid an optional numeric value representing the longitude (decimal degrees) of the local time zone meridian (0 for GMT). Default is `round(long / 15, 0) * 15`
#' @param dst an optional numeric value representing the time difference from the timezone meridian (hours, e.g. +1 for BST if `merid` = 0).
#'
#' @return a data.frame with three components:
#' @return `sunrise` a vector of sunrise (hours in 24 hour clock).
#' @return `sunrise` a vector of sunset (hours in 24 hour clock).
#' @return `sunrise` a vector of daylengths (hours).
#' @export
#'
#' @details if the sun is above or below the horizon for 24 hours on any
#' days, a warning is given, and the sunrise and sunset returned are the
#' appoximate times at which that the sun is closest to the horizon.
#'
#' @examples
#' jd <- julday(2018, 1, 16)
#' suntimes(jd, 50.17, -5.12) # Cornwall, UK
#' suntimes(jd, 78.22, 15.64) # Longyearbyen, Svalbad
#' suntimes(jd, -54.94, -67.61, merid = -60, dst = 1) # Puerto Williams, Cabo de Hornos, Chile
suntimes <- function(julian, lat, long, merid = round(long / 15, 0) * 15, dst = 0) {
lw <- (long - merid) * -1
n <- julian - 2451545 - 0.0009 - (lw / 360)
n <- floor (n) + 0.5
sn <- 2451545 + 0.0009 + (lw / 360) + n
msa <- (357.5291 + 0.98560028 * (sn - 2451545))%%360
eoc <- 1.9148 * sin(msa * pi / 180) + 0.02 * sin(2 * msa * pi / 180) +
0.0003 * sin(3 * msa * pi / 180)
ecl <- (msa + 102.9372 + eoc + 180)%%360
st <- sn + (0.0053 * sin(msa * pi / 180)) - (0.0069 *
sin(2 * ecl * pi / 180))
d <- asin(sin(ecl * pi / 180) * sin(23.45 * pi / 180))
coshas <- (sin(-0.83 * pi / 180) - sin(lat * pi / 180) * sin(d)) /
(cos(lat * pi / 180) * cos(d))
if (max(coshas) > 1) {
coshas <- ifelse(coshas > 1, 1, coshas)
warning("sun below horizon for 24 hours on some days")
}
if (min(coshas) < -1) {
coshas <- ifelse(coshas < -1, -1, coshas)
warning("sun above horizon for 24 hours on some days")
}
has <- acos(coshas)
jset <- 2451545 + 0.0009 + (((has * 180 / pi + lw) / 360) + n +
0.0053 * sin(msa * pi / 180)) - 0.0069 *
sin(2 * ecl * pi / 180)
jrise <- st - (jset - st)
hset <- jset%%1 * 24 + dst
hrise <- jrise%%1 * 24 + dst
dl <- round((jset - jrise) * 24, 5)
sunvars <- data.frame(sunrise = hrise, sunset = hset, daylight = dl)
sunvars
}
#' derived fraction of solar day
.solarday <- function(julian, localtime, lat, long, merid, dst = 0) {
src <- suntimes(julian, lat, long, merid, dst)$sunrise
ssc <- suntimes(julian, lat, long, merid, dst)$sunset
ssp <- suntimes(julian - 1, lat, long, merid, dst)$sunset
srn <- suntimes(julian + 1, lat, long, merid, dst)$sunrise
st <- ifelse(localtime >= src & localtime <= ssc,
((localtime - src) / (ssc - src)) * 12 + 6, localtime)
st <- ifelse(localtime > ssc, ((localtime - ssc) / (srn + 24 - ssc)) *
12 + 18, st)
st <- ifelse(localtime < src, ((localtime + 24 - ssp) / (src + 24 - ssp)) *
12 - 6, st)
st <- (st / 24)%%1
st
}
#' derived proportion of maximum radiation
.propmaxrad <- function(dif, dct, am) {
theta <- 1.1 * (0.7 ^ (am ^ 0.678))
mxr <- 4.87 * theta
pr <- (dif + dct) / mxr
pr <- ifelse(pr > 1, 1, pr)
pr
}
#' calculates emmisivity from humidity etc
.emissivity <- function(h, tc, n, p = 100346.13, co = 1.24) {
pk <- p / 1000
e0 <- 0.6108 * exp(17.27 * tc / (tc + 237.3))
ws <- 0.622 * e0 / pk
rh <- (h / ws) * 100
rh[rh > 100] <- 100
ea <- e0 * rh / 100
eo <- co * (0.1 * ea / (tc + 273.15)) ^ (1/7)
em <- (1 - n) + n * eo
em
}
#' Derives hourly temperatures from daily data
#'
#' @description `hourlytemp` is used to derive hourly temperatures from daily maxima and minima.
#'
#' @param julian vector of julian days expressed as integers for every day for which `mintemp` and `maxtemp` are provided, as returned by function [julday()].
#' @param em an optional vector of hourly emissivities. If not provided, calculated from `h`, `n` and `p`.
#' @param h a vector of hourly specific humidities (\ifelse{html}{\out{kg kg<sup>-1</sup> }}{\eqn{kg kg^{-1}}}). Ignored if `em` provided.
#' @param n a vector of hourly fractional cloud cover values (range 0 - 1). Ignored if `em` provided.
#' @param p an optional vector of hourly atmospheric pressure values (Pa). Ignored if `em` provided.
#' @param dni a vector of hourly direct radiation values normal to the solar beam (\ifelse{html}{\out{MJ m<sup>-2</sup> hr<sup>-1</sup>}}{\eqn{MJ m^-2 hr^{-1}}}).
#' @param dif a vector of hourly diffuse radiation values (\ifelse{html}{\out{MJ m<sup>-2</sup> hr<sup>-1</sup>}}{\eqn{MJ m^-2 hr^{-1}}}).
#' @param mintemp a vector of daily minimum temperatures (ºC).
#' @param maxtemp a bector of daily maximum temperatures (ºC).
#' @param lat a single numeric value representing the latitude of the location for which hourly temperatures are required (decimal degrees, -ve south of equator).
#' @param long a single numeric value representing the longitude of the location for which hourly temperatures are required (decimal degrees, -ve west of Greenwich meridian).
#' @param merid an optional numeric value representing the longitude (decimal degrees) of the local time zone meridian (0 for GMT). Default is `round(long / 15, 0) * 15`
#' @param dst an optional numeric value representing the time difference from the timezone meridian (hours, e.g. +1 for BST if `merid` = 0).
#'
#' @return a vector of hourly temperatures (ºC).
#' @export
#'
#' @details A warning is returned if any of following conditions are not
#' met. (1) `h`, `n`, `dif` and `dct` differ in length.
#' (2) `julian`, `mintemp` and `maxtemp` differ in length. (3) E.g. `h` / 24 is not
#' an integer. (4) the length of e.g. `h` is not equal to the length of
#' e.g. `mintemp` x 24.
#'
#' @examples
#' jd <- julday(2010, 5 , c(1,2))
#' ht <- hourlytemp(jd, NA, microvars$humidity[1:48], microvars$cloudcover[1:48],
#' microvars$pressure[1:48], dni = microvars$dni[1:48],
#' dif = microvars$dif[1:48], c(7.5, 7.2), c(14.6, 15.2),
#' 49.968, -5.216)
#' plot(ht ~ c(0:47),type="l", xlab = "Hour", ylab = "Temperature",
#' main = paste("tmins:", 7.2, 7.5, "tmaxs:", 14.6, 15.2))
hourlytemp <- function(julian, em = NA, h, n, p = 100346.13, dni, dif,
mintemp, maxtemp, lat, long, merid = round(long / 15, 0) * 15, dst=0) {
l1 <- unlist(lapply(list(dni, dif), length))
l2 <- unlist(lapply(list(julian, mintemp, maxtemp), length))
if (length(unique(l1)) != 1) {
warning("Number of hourly values not identical")
}
if (length(unique(l2)) != 1) {
warning("Number of daily values not identical")
}
if (length(dni)%%24 != 0) warning ("Hourly values must be multiple of 24")
if (l1[1] != l2[1] * 24) {
warning("Number of hourly values not 24 times number of daily values")
}
o <- order(rep(c(1:length(julian)), 24))
jd <- rep(julian, 24)[o]
localtime <- rep(c(0:23), length(mintemp))
solfrac <- .solarday(julian, localtime, lat, long, merid, dst)
am <- airmasscoef(localtime, lat, long, julian, merid, dst)
dct <- dni * siflat(localtime, lat, long, jd, merid, dst)
pr <- .propmaxrad(dif, dct, am)
tfrac <- 110.42201 * sin(solfrac) - 38.64802 * cos(solfrac) - 79.82963 *
sin(2 * solfrac) + 65.39122 * cos(2 * solfrac) + 15.54387 *
sin(3 * solfrac) - 26.30047 * cos(3 * solfrac)
mns <- rep(mintemp, 24)[o]
mxs <- rep(maxtemp, 24)[o]
tc <- (mxs - mns) * tfrac + mns
if (is.na(em[1]))
em <- .emissivity(h, tc, n, p)
day <- which(is.na(pr) == F)
ngt <- which(is.na(pr))
tfrac[day] <- -0.30516 + 0.78414 * tfrac[day] + 0.89086 *
pr[day] + 0.34062 * tfrac[day] * pr[day]
tfrac[ngt] <- -0.6562 + 1.0277 * tfrac[ngt] + 0.8981 *
em[ngt] -0.5262 * tfrac[ngt] * em[ngt]
tfrac <- 1 / (1 + exp(-1 * tfrac))
td <- array(tfrac, dim = c(24, length(tfrac) / 24))
tmns <- apply(td, 2, min)
tmxs <- apply(td, 2, max)
for (i in 1:dim(td)[2]) {
td[, i] <- (td[, i] - tmns[i]) / (tmxs[i] - tmns[i])
}
tfrac <- as.vector(td)
tc <- (mxs - mns) * tfrac + mns
tc
}
#' Applies a spline function to an array of values
#'
#' @description `arrayspline` is used to derive e.g. hourly climate data from e.g. daily values.
#'
#' @param a a three-dimensional array (row, column, time)
#' @param tme an object of class POSIXct of times for `a`. I.e. `length(tme) = dim(a)[3]`
#' @param nfact indicates the time interval for which outputs are required. E.g to derive hourly from daily data `nfact = 24`, or derive six-hourly from daily data `nfact = 4`
#' @param out an optional character vector indicating the time for which the output is required. Format must be as for `tme`.
#'
#' @return
#' If out is unspecified, a three dimensional array of size `c(a[1], a[2], (length(tme) - 1) * nfact + 1)` is returned.
#' If out is specified, a three dimensional array of size `c(a[1], a[2], length(out))` is returned.
#'
#' @importFrom stats splinefun
#' @export
#'
#' @details
#' `arrayspline` uses the Forsythe, Malcolm and Moler method of splining, as specified by
#' `"fmm"` in [spline()]. If `a[i, j, ]` is a vector of NAs, then tthe corresponding vector in
#' the output array is also a vector of NAs. It is assumed that all spatial data within `a` have
#' equivelent times. I.e. the time of both `a[1, 1, 1]` and `a[1000, 1000, 1]` is identical and
#' equal to `tme[1]`.
#'
#' @examples
#' library(raster)
#' tme <- as.POSIXct(c(0:364) * 24 * 3600, origin="2010-01-01", tz = "GMT")
#' h <- arrayspline(huss, tme, out = "2010-05-01 11:00")
#' plot(raster(h, template = dtm1km),
#' main = "Specific humidity 2010-05-01 11:00")
arrayspline <- function(a, tme, nfact = 24, out = NA) {
n <- (length(tme) - 1) * nfact + 1
sf <- function(y, tme, nfact) {
n <- (length(tme) - 1) * nfact + 1
if (is.na(mean(y)) == FALSE) {
xy <- spline(as.numeric(tme), y, n = n)
xy$y
}
else rep(NA, n)
}
ao <- aperm(apply(a, c(1, 2), sf, tme, nfact), c(2, 3, 1))
if (is.na(out[1]) == FALSE) {
out <- as.POSIXct(out, tz = format(tme[1], "%Z"))
tout <- spline(as.numeric(tme), c(1:length(tme)), n)$x
tout <- as.POSIXct(tout, origin = "1970-01-01 00:00",
tz = format(tme[1], "%Z"))
s <- 0
for (i in 1:length(out)) {
s[i] <- which(tout == out[i])
}
ao <- ao[,,s]
}
ao
}
#' Fits micro- or mesoclimate model
#'
#' @description
#' `fitmicro` is used to fit a micro- or mesoclimate model using field temperature readings, and estimates of reference temperature, net radiation
#' and wind speed at the locations of those readings.
#'
#' @param microfitdata a data.frame with at least the following columns (see, for example, microfit data):
#' \describe{
#' \item{temperature}{microclimate temperature readings}
#' \item{reftemp}{Reference (e.g. coarse-scale or weather station) temperatures}
#' \item{wind}{Wind speeds}
#' \item{netrad}{Net radiation values}
#' }
#' @param alldata an optional logical value indicating whether to fit the model using all data (TRUE) or using a randomization procedure (FALSE). See details.
#' @param windthresh an optional single numeric value indicating the threshold wind speed above which an alternative linear relationship between net radiation the microclimate temperature anomoly is fitted. See details.
#' @param continious an optional logical value indicating whether to treat wind speed as a continious variable.
#' @param iter a single integer specifying the iterations to perform during randomization. Ignored if `alldata` = TRUE.
#'
#' @return a data,frame with the following columns:
#' \describe{
#' \item{Estimate}{parameter estimates and `windthresh`}
#' \item{Std.Dev}{Standard deviation of parameter estimates}
#' \item{P}{Two-tailed p-value}
#' }
#' @export
#' @importFrom stats lm
#' @importFrom stats median
#' @details
#' If modelling mesoclimate, it is assumed that altitudinal, coastal and cold-air
#' drainage effects have already been accounted for in the calculation of `reftemp`.
#' It is therefore assumed that the most important energy fluxes determining near-surface
#' temperature are those due to the radiation flux and convection that occurs at
#' the surface-atmosphere boundary. Heat fluxes into the soil and latent heat
#' exchange are considered to be small and proportional to the net radiation
#' flux, and the heat capacity of the vegetation is considered to be small so
#' that, compared to the time-scale of the model, surface temperature rapidly
#' reach equilibrium. In consequence, the difference between the near-ground
#' temperature and the ambient temperature is a linear function of `netrad`.
#' The gradient of this linear relationship is a measure of the thermal
#' coupling of the surface to the atmosphere. If this relationship is applied
#' to vegetation, assuming the canopy to act like a surface, while air density
#' and the specific heat of air at constant pressure are constant, the slope
#' varies as a function of a wind speed factor, such that different slope values
#' are assumed under high and low wind conditions. Hence, as a default, `fitmicro`
#' fits a linear model of the form `lm((temperature - reftemp) ~ netrad * windfact)`
#' where windfact is given by `ifelse(wind > windthresh, 1, 0)` If `continious` is
#' set to TRUE, then a linear model of the form `lm((temperature - reftemp) ~ netrad * log(wind + 1)`
#' is fitted. If `alldata` is FALSE, random subsets of the data are selected and the analyses repeated
#' `iter` times to reduce the effects of of temporal autocorrelation. Parameter
#' estimates are derived as the median of all runs. If `continious` is set to FALSE
#' and no value is provided for `windthresh`, it is derived by iteratively trying out
#' different values, and selecting that which yields the best fit. The gradient of
#' the relationship is also dependent on vegetation structure, and in some
#' circumstances it may therefore be advisable to fit seperate models for each
#' vegetation type.
#'
#' @examples
#' fitmicro(microfitdata)
#' fitmicro(mesofitdata, alldata = TRUE)
#' fitmicro(mesofitdata, alldata = TRUE, continious = TRUE)
fitmicro <- function(microfitdata, alldata = FALSE, windthresh = NA,
continious = FALSE, iter = 999) {
pvals <- function(x) {
iter <- length(x)
d <- floor(log(iter, 10))
p <- length(x > 0) / iter
p <- ifelse(p > 0.5, 1 - p, p)
p <- round(p * 2, d)
p
}
wthresh <- NA
microfitdata$anom <- microfitdata$temperature - microfitdata$reftemp
if (is.na(windthresh) & continious == FALSE) {
wrange <- floor(max(microfitdata$wind) - min(microfitdata$wind))
rsq <- 0
for (i in 1:100 * wrange) {
wind.fact <- ifelse(microfitdata$wind > (i / 100), 1, 0)
m <- lm(microfitdata$anom ~ microfitdata$netrad * wind.fact)
rsq[i] <- summary(m)$r.squared
}
wthresh <- which(rsq == max(rsq, na.rm = TRUE)) / 100
}
if (alldata) {
if (continious) {
m1 <- summary(lm(anom ~ log(wind + 1) * netrad, data = microfitdata))
} else {
wf <- ifelse(microfitdata$wind > wthresh, 1, 0)
m1 <- summary(lm(microfitdata$anom ~ wf * microfitdata$netrad))
}
mdns <- as.vector(m1$coef[, 1])
sds <- as.vector(m1$coef[, 2]) * sqrt(dim(microfitdata)[1])
pvs <- as.vector(m1$coef[, 4])
} else {
ln <- round(dim(microfitdata)[1] / 100, 0) * 10
pint <- 0
pwf <-0
pnr <- 0
pnrwf <- 0
for (i in 1:iter) {
u <- round(runif(ln, 1, dim(microfitdata)[1]), 0)
one.iter <- microfitdata[u, ]
if (continious == F) {
wf <- ifelse(one.iter$wind > wthresh, 1, 0)
m1 <- lm(one.iter$anom ~ wf * one.iter$netrad)
} else {
lw <- log(one.iter$wind + 1)
m1 <- lm(one.iter$anom ~ lw * one.iter$netrad)
}
pint[i] <- m1$coef[1]
pwf[i] <- m1$coef[2]
pnr[i] <- m1$coef[3]
pnrwf[i] <- m1$coef[4]
}
mdns <- c(median(pint, na.rm = T), median(pwf, na.rm = T),
median(pnr, na.rm = T), median(pnrwf, na.rm = T))
sds <- c(sd(pint, na.rm = T), sd(pwf, na.rm = T), sd(pnr, na.rm = T),
sd(pnrwf, na.rm = T))
pvs <- c(pvals(pint), pvals(pwf), pvals(pnr), pvals(pnrwf))
}
params <- data.frame(Estimate = c(mdns, wthresh), Std.Dev = c(sds, ""),
P = c(pvs, ""))
row.names(params) <- c("Intercept", "Wind factor", "Net radiation",
"Wind factor:Net radiation", "Wind threshold")
if (continious) {
row.names(params)[2] <- "wind"
row.names(params)[5] <- ""
params$Estimate[5] <- ""
}
params$Estimate <- as.numeric(params$Estimate)
params
}
#' Runs micro- or mesoclimate model
#'
#' @description `runmicro` produces a high-resolution dataset of downscaled
#' temperatures for one time interval
#'
#' @param params a data.frame of parameter estimates as produced by [fitmicro()]
#' @param netrad a raster object, two-dimensional array or matrix of downscaled net radiation as produced by [shortwaveveg()] - [longwaveveg()] or [shortwavetopo()] - [longwavetopo()].
#' @param wind a raster object, two-dimensional array or matrix of downscaled wind speed, as produced by reference wind speed x the output of [windcoef()].
#' @param continious an optional logical value indicating whether the model was fitted by treating wind speed as a continious variable.
#' @return a raster object, two-dimensional array or matrix of temperature anomolies from reference temperature, normally in ºC, but units depend on those used in [fitmicro()].
#' @import raster
#' @export
#' @seealso [fitmicro()]
#'
#' @details
#' If `netrad` is a raster object, a raster object is returned.
#' If modelling mesoclimate, it is assumed that altitudinal, coastal and cold-air
#' drainage effects have already been accounted for in the calculation of reference
#' temperature (see example). It is assumed that the most important energy fluxes
#' determining near-surface temperature are those due to the radiation flux and convection
#' that occurs at the surface–atmosphere boundary. Heat fluxes into the soil and latent heat
#' exchange are considered to be small and proportional to the net radiation
#' flux, and the heat capacity of the vegetation is considered to be small so
#' that, compared to the time-scale of the model, surface temperature rapidly
#' reach equilibrium. In consequence, the difference between the near-ground
#' temperature and the ambient temperature is a linear function of `netrad`.
#' The gradient of this linear relationship is a measure of the thermal
#' coupling of the surface to the atmosphere. If this relationship is applied
#' to vegetation, assuming the canopy to act like a surface, while air density
#' and the specific heat of air at constant pressure are constant, the slope
#' varies as a function of a wind speed factor, such that different slope values
#' are assumed under high and low wind conditions.
#'
#' @examples
#' library(raster)
#' # =======================================================================
#' # Run microclimate model for 2010-05-24 11:00 (one of the warmest hours)
#' # =======================================================================
#' params <- fitmicro(microfitdata)
#' netrad <- netshort1m - netlong1m
#' tempanom <- runmicro(params, netrad, wind1m)
#' reftemp <- raster(temp100[,,564])
#' extent(reftemp) <- extent(dtm1m)
#' reftemp <- resample(reftemp, dtm1m)
#' temps <- tempanom + getValues(reftemp, format = "matrix")
#' plot(if_raster(temps, dtm1m), main =
#' expression(paste("Temperature ",(~degree~C))))
#'
#' # ======================================================================
#' # Run mesoclimate model for 2010-05-01 11:00 from first principles
#' # ======================================================================
#'
#' # -------------------------
#' # Resample raster function
#' # -------------------------
#' resampleraster <- function(a, ro) {
#' r <- raster(a)
#' extent(r) <- c(-5.40, -5.00, 49.90, 50.15)
#' crs(r) <- "+init=epsg:4326"
#' r <- projectRaster(r, crs = "+init=epsg:27700")
#' r <- resample(r, ro)
#' as.matrix(r)
#' }
#'
#' # --------------------------
#' # Resample raster: 24 hours
#' # --------------------------
#' get24 <- function(a) {
#' ao <- array(NA, dim = c(dim(dtm1km)[1:2], 24))
#' for (i in 1:24) {
#' ai <- a[,,2880 + i]
#' ao[,,i] <- resampleraster(ai, dtm1km)
#' }
#' ao
#' }
#'
#' # ----------------------------
#' # Derive hourly temperatures
#' # ----------------------------
#' tmax <- tas[,,121] + dtr[,,121] / 2
#' tmin <- tas[,,121] - dtr[,,121] / 2
#' tme <- as.POSIXct(c(0:364) * 24 * 3600, origin="2010-01-01", tz = "GMT")
#' out <- as.POSIXct(c(0:23) * 3600, origin="2010-05-01", tz = "GMT")
#' h <- arrayspline(huss, tme, out = out)
#' p <- arrayspline(pres, tme, out = out)
#' n <- get24(cfc)
#' dni <- get24(dnirad)
#' dif <- get24(difrad)
#' jd <- julday(2010, 5 , 1)
#' tc <- h[,,1] * NA
#' lr <- h[,,1] * NA # Also calculates lapse rate
#' for (i in 1:19) {
#' for (j in 1:22) {
#' if (is.na(tmax[i,j]) == F)
#' {
#' ht <- hourlytemp(jd, em = NA, h[i, j, ], n[i, j, ], p[i, j, ], dni[i, j, ],
#' dif[i, j, ], tmin[i,j], tmax[i,j], 50.02, -5.20)
#' tc[i, j]<- ht[12]
#' lr[i, j] <- lapserate(tc[i, j], h[i, j, 12], p[i, j, 12])
#' }
#' }
#' }
#' # ----------------------------
#' # Calculate coastal effects
#' # ----------------------------
#' sst <- 10.771
#' dT <- if_raster(sst - tc, dtm1km)
#' lsw <- if_raster(landsearatios[,,28], dtm100m) # upwind
#' lsa <- if_raster(apply(landsearatios, c(1, 2), mean), dtm100m) # mean, all directions
#' dTf <- coastalTps(dT, lsw, lsa)
#'
#' # ------------------------------
#' # Calculate altitudinal effects
#' # ------------------------------
#' lrr <- if_raster(lr, dtm1km)
#' lrr <- resample (lrr, dtm100m)
#' tc <- sst - dTf + lrr * dtm100m
#'
#' # ------------------------------
#' # Downscale radiation
#' # ------------------------------
#' dni <- resampleraster(dnirad[,,2891], dtm100m)
#' dif <- resampleraster(difrad[,,2891], dtm100m)
#' n <- resampleraster(cfc[,,2891], dtm100m)
#' h <- resample(if_raster(h[,,12], dtm1km), dtm100m)
#' p <- resample(if_raster(p[,,12], dtm1km), dtm100m)
#' sv <- skyviewtopo(dtm100m)
#' netshort <- shortwavetopo(dni, dif, jd, 11, dtm = dtm100m, svf = sv)
#' netlong <- longwavetopo(h, tc, p, n, sv)
#' netrad <- netshort - netlong
#'
#' # ------------------
#' # Downscale wind
#' # ------------------
#' ws <- array(windheight(wind2010$wind10m, 10, 1), dim = c(1, 1, 8760))
#' wh <- arrayspline(ws, as.POSIXct(wind2010$obs_time), 6, "2010-05-01 11:00")
#' ws <- windcoef(dtm100m, 270, res = 100) * wh
#'
#' # ------------------
#' # Fit and run model
#' # ------------------
#' params <- fitmicro(mesofitdata)
#' anom <- runmicro(params, netrad, ws)
#' tc <- tc + anom
#' plot(mask(tc, dtm100m), main =
#' expression(paste("Mesoclimate temperature ",(~degree~C))))
runmicro <- function(params, netrad, wind, continious = FALSE) {
r <- netrad
netrad <- is_raster(netrad)
wind <- is_raster(wind)
if (continious) {
temp <- params[1, 1] + params[2, 1] * log(wind + 1) + params[3, 1] * netrad +
params[4, 1] * log(wind + 1) * netrad
} else {
wf <- ifelse(wind > params[5, 1], 1, 0)
temp <- params[1, 1] + params[2, 1] * wf + params[3, 1] * netrad +
params[4, 1] * wf * netrad
}
if_raster(temp, r)
}
#' Derives parameters for fitting soil temperatures
#' @export
.fitsoil <- function(soil0, soil200, nmrsoil) {
fitsoilone <- function(soil0, soil200, nmrsoil, x1, x2) {
pred <- nmrsoil[1]
for (i in 2:length(nmrsoil)) {
heatdown <- (soil0[i - 1] - pred[i - 1])
heatup <- (soil200 - pred[i -1])
pred[i] <- pred[i-1] + x1 * heatdown + x2 * heatup
}
difs <- abs(nmrsoil - pred)
sum(difs)
}
fitloop <- function(xs1, xs2, x1add, x2add) {
dfa <- data.frame(x1 = 0, x2 = 0, dif = 0)
for (ii in 1:length(xs1)) {
for (jj in 1:length(xs2)) {
x1 <- xs1[ii] + x1add
x2 <- xs2[jj] + x2add
dif <- fitsoilone(soil0, soil200, nmrsoil, x1, x2)
df1 <- data.frame(x1 = x1, x2 = x2, dif = dif)
dfa <- rbind(dfa, df1)
}
}
dfa <- dfa[-1,]
sel <- which(dfa$dif == min(dfa$dif, na.rm = T))
dfa[sel,]
}
xs1 <- c(0:10)
xs2 <- c(0:10)
dfo <- fitloop(xs1, xs2, 0, 0)
if (dfo$x1 > 0 ) {
xs1 <- c(-10:10) / 10
} else xs1 <- c(0:10) / 10
if (dfo$x2 > 0 ) {
xs2 <- c(-10:10) / 10
} else xs2 <- c(0:10) / 10
dfo <- fitloop(xs1, xs2, dfo$x1, dfo$x2)
if (dfo$x1 > 0 ) {
xs1 <- c(-10:10) / 100
} else xs1 <- c(0:10) / 100
if (dfo$x2 > 0 ) {
xs2 <- c(-10:10) / 100
} else xs2 <- c(0:10) / 100
dfo <- fitloop(xs1, xs2, dfo$x1, dfo$x2)
if (dfo$x1 > 0 ) {
xs1 <- c(-10:10) / 1000
} else xs1 <- c(0:10) / 1000
if (dfo$x2 > 0 ) {
xs2 <- c(-10:10) / 1000
} else xs2 <- c(0:10) / 1000
dfo <- fitloop(xs1, xs2, dfo$x1, dfo$x2)
if (dfo$x1 > 0 ) {
xs1 <- c(-10:10) / 10000
} else xs1 <- c(0:10) / 10000
if (dfo$x2 > 0 ) {
xs2 <- c(-10:10) / 10000
} else xs2 <- c(0:10) / 10000
dfo <- fitloop(xs1, xs2, dfo$x1, dfo$x2)
if (dfo$x1 > 0 ) {
xs1 <- c(-10:10) / 100000
} else xs1 <- c(0:10) / 100000
if (dfo$x2 > 0 ) {
xs2 <- c(-10:10) / 100000
} else xs2 <- c(0:10) / 100000
dfo <- fitloop(xs1, xs2, dfo$x1, dfo$x2)
dfo
}
#' Derives leaf area index, leaf geometry and canopy height from habitat
#'
#' @description `laifromhabitat` generates an hourly dataset for an entire year of
#' leaf area index values, the ratio of vertical to horizontal projections of leaf
#' foliage and canopy height from habitat.
#'
#' @param habitat a character string or numeric value indicating the habitat type. See [habitats()]
#' @param lat a single numeric value representing the mean latitude of the location for which the solar index is required (decimal degrees, -ve south of the equator).
#' @param long a single numeric value representing the mean longitude of the location for which the solar index is required (decimal degrees, -ve west of Greenwich meridian).
#' @param meantemp an optional numeric value of mean annual temperature (ºC) at reference height.
#' @param cvtemp an optional numeric value of the coefficient of variation in temperature (K per 0.25 days) at reference height.
#' @param rainfall an optional numeric value mean annual rainfall (mm per year)
#' @param cvrain an optional numeric value of the coefficient of variation in raifall (mm per 0.25 days) at reference height.
#' @param wetmonth an optional numeric value indicating which month is wettest (1-12).
#' @param year the year for which data are required.
#' @return a list with the following items, (1) lai: hourly leaf area index values,
#' (2) x: the ratio of vertical to horizontal projections of leaf foliage,
#' (3) height: the heigbht of the canopy in metres and (4) obs_time: an object of
#' class POSIXlt of dates and times coressponding to each value of lai.
#' @export
#' @seealso [lai()], [leaf_geometry()]
#'
#' @details
#' If no values of `meantemp`, `cvtemp`, `rainfall`, `cvrain` or `wetmonth` are
#' provided, values are obtained from [globalclimate()]. Variable `lai` is derived by fitting
#' a Gaussian curve parameters of which are climate and location-dependent. Functional
#' fits were calibrated using MODIS data (see https://modis.gsfc.nasa.gov/data/).
#'
#' @examples
#' lxh <- laifromhabitat("Deciduous broadleaf forest", 50, -5.2, 2015)
#' lxh$height
#' lxh$x
#' plot(lxh$lai ~ as.POSIXct(lxh$obs_time), type = "l", xlab = "Month",
#' ylab = "LAI", ylim = c(0, 6))
laifromhabitat <- function(habitat, lat, long, year, meantemp = NA, cvtemp = NA,
rainfall = NA, cvrain = NA, wetmonth = NA) {
laigaus <- function(minlai, maxlai, pkday, dhalf, yr) {
diy <- 365
sdev <- 0.0082 * dhalf^2 + 0.0717 * dhalf + 13.285
difv <- maxlai - minlai
x<-c(-diy:diy)
y <- 1 / (sdev * sqrt(2 * pi)) * exp(-0.5 * (((x - 0) / sdev) ^ 2))
y[(diy + ceiling(0.5 * diy)):(2 * diy + 1)] <- y[(diy - ceiling(0.5 * diy)):diy]
st <- diy + 1 - pkday
y <- y[st:(st + diy - 1)]
x <- c(1:diy)
x <- c(0, x, c(366:375))
y <- c(y[diy], y, y[1:10])
sel <-c(0:15) * 25 + 1
x<-x[sel]
y<-y[sel]
tme <- as.POSIXct((x * 24 * 3600), origin = paste0(yr - 1,"-12-31 12:00"), tz = "GMT")
xy <- spline(tme, y, n = diy * 24 + 241)
tme2 <- as.POSIXlt(xy$x, origin = "1970-01-01 00:00", tz = "GMT")
sel <- which(tme2$year + 1900 == yr)
y <- xy$y[sel]
dify <- max(y) - min(y)
y <- y * (difv / dify)
y <- y + minlai - min(y)
return(y)
}
long <- ifelse(long > 180.9375, long - 360, long)
long <- ifelse(long < -179.0625, long + 360, long)
ll <- SpatialPoints(data.frame(x = long, y = lat))
diy <- 366
if (year%%4 == 0) diy <- 366
if (year%%100 == 0 & year%%400 != 0) diy <- 365
mmonth <-c(16, 45.5, 75, 105.5, 136, 166.5, 197, 228, 258.5, 289, 319.5, 350)
if (diy == 365) mmonth[2:12] <- mmonth[2:12] + 0.5
e <- extent(c(-179.0625, 180.9375, -89.49406, 89.49406))
clim <- c(meantemp, cvtemp, rainfall, cvrain, wetmonth)
for (i in 1:5) {
if (is.na(clim[i])) {
r <- raster(globalclimate[,,i])
extent(r) <- e
clim[i] <- extract(r, ll)
}
}
wgts <- function(x1, x2, ll, lmn, lmx) {
ll <- ifelse(ll < lmn, lmn, lat)
ll <- ifelse(ll > lmx, lmx, lat)
w <- 1 - (abs(ll - lmn) / (abs(ll - lmn) + abs(ll - lmx)))
y <- w * x1 + (1 - w) * x2
y
}
# By habitat type
if (habitat == "Evergreen needleleaf forest" | habitat == 1) {
h2 <- 74.02 + 5.35 * clim[1]
h1 <- 203.22 - 35.63 * clim[4]
hperiod <- wgts(h1, h2, abs(lat), 0, 20)
hperiod <- ifelse(hperiod < 50, 50, hperiod)
p2 <- 216.71 - 2.65 * clim[1]
p2 <- ifelse(p2 > 244, 244, p2)
if (lat < 0) p2 <- (p2 + diy / 2)%%diy
p1 <- mmonth[round(clim[5], 0)]
peakdoy <- wgts(p1, p2, abs(lat), 0, 30)
if (clim[1] <= 20) {
maxlai <- 2.33 + 0.0132 * clim[1]
} else maxlai <- 2.33 + 0.0132 * 20
minlai <- 1.01
x <- 0.4
hgt <- 10
}
if (habitat == "Evergreen Broadleaf forest" | habitat == 2) {
hperiod <- 154.505 + 2.040 * clim[1]
hperiod <- ifelse(hperiod < 50, 50, hperiod)
peakdoy <- peakdoy <- mmonth[round(clim[5], 0)]
maxlai <- 1.83 + 0.22 * log(clim[3])
minlai <- (-1.09) + 0.4030 * log(clim[3])
minlai <- ifelse(minlai < 1, 1, minlai)
x <- 1.2
hgt <- 20
}
if (habitat == "Deciduous needleleaf forest" | habitat == 3) {
h2 <- 51.18 + 3.77 * clim[1]
h1 <- 152
hperiod <- wgts(h1, h2, abs(lat), 0, 20)
p2 <- 204.97 - 1.08 * clim[1]
p2 <- ifelse(p2 > 244, 244, p2)
if (lat < 0) p2 <- (p2 + diy / 2)%%diy
p1 <- mmonth[round(clim[5], 0)]
peakdoy <- wgts(p1, p2, abs(lat), 0, 30)
if (clim[1] <= 20) {
maxlai <- 2.62 + 0.05 * clim[1]
} else maxlai <- 2.62 + 0.05 * 20
minlai <- 0.39
x <- 0.4
hgt <- 10
}
if (habitat == "Deciduous broadleaf forest" | habitat == 4) {
h2 <- 47.6380 + 2.9232 * clim[1]
h1 <- 220.06 - 79.19 * clim[4]
hperiod <- wgts(h1, h2, abs(lat), 0, 20)
hperiod <- ifelse(hperiod < 32.5, 32.5, hperiod)
p2 <- 209.760 - 1.208 * clim[1]
p2 <- ifelse(p2 > 244, 244, p2)
if (lat < 0) p2 <- (p2 + diy / 2)%%diy
p1 <- mmonth[round(clim[5], 0)]
peakdoy <- wgts(p1, p2, abs(lat), 0, 30)
if (clim[1] <= 20) {
maxlai <- 3.98795 + 0.03330 * clim[1]
} else maxlai <- 3.98795 * 0.03330 * 20
minlai <- 0.4808
x <- 1.2
hgt <- 15
}
if (habitat == "Mixed forest" | habitat == 5) {
warning("Results highly sensitive to forest composition. Suggest running
seperately for constituent forest types and weighting output")
h2 <- 74.02 + 5.35 * clim[1]
h1 <- 203.22 - 35.63 * clim[4]
hperiod1 <- wgts(h1, h2, abs(lat), 0, 20)
h2 <- 51.18 + 3.77 * clim[1]
h1 <- 152
hperiod2 <- wgts(h1, h2, abs(lat), 0, 20)
hperiod <- (hperiod1 + hperiod2) / 2
hperiod <- ifelse(hperiod < 30.5, 30.5, hperiod)
p2 <- 216.71 - 2.65 * clim[1]
p2 <- ifelse(p2 > 244, 244, p2)
if (lat < 0) p2 <- (p2 + diy / 2)%%diy
p1 <- mmonth[round(clim[5], 0)]
peakdoy1 <- wgts(p1, p2, abs(lat), 0, 30)
p2 <- 204.97 - -1.08 * clim[1]
p2 <- ifelse(p2 > 244, 244, p2)
if (lat < 0) p2 <- (p2 + diy / 2)%%diy
peakdoy2 <- wgts(p1, p2, abs(lat), 0, 30)
peakdoy <- (peakdoy1 + peakdoy2) / 2
if (clim[1] <= 20) {
maxlai1 <- 2.33 + 0.0132 * clim[1]
maxlai2 <- 2.62 + 0.05 * clim[1]
maxlai <- (maxlai1 + maxlai2) / 2
} else maxlai <- 3.107
minlai <- 0.7
x <- 0.8
hgt <- 10
}
if (habitat == "Closed shrublands" | habitat == 6) {
h2 <- 33.867 + 6.324 * clim[1]
h1 <- 284.20 - 102.51 * clim[4]
hperiod <- wgts(h1, h2, abs(lat), 0, 20)
hperiod <- ifelse(hperiod < 30.5, 30.5, hperiod)
p2 <- 223.55 - 3.125 * clim[1]
p2 <- ifelse(p2 > 244, 244, p2)
if (lat < 0) p2 <- (p2 + diy / 2)%%diy
p1 <- mmonth[round(clim[5], 0)]
peakdoy <- wgts(p1, p2, abs(lat), 0, 30)
maxlai <- 2.34
minlai <- -0.4790 + 0.1450 * log(clim[3])
minlai <- ifelse(minlai < 0.001, 0.001, minlai)
x <- 1
hgt <- 2
}
if (habitat == "Open shrublands" | habitat == 7) {
h2 <- 8.908 + 4.907 * clim[1]
h1 <- 210.09 - 28.62 * clim[4]
hperiod <- wgts(h1, h2, abs(lat), 0, 20)
hperiod <- ifelse(hperiod < 38.3, 38.3, hperiod)
p2 <- 211.7 - 4.085 * clim[1]
p2 <- ifelse(p2 > 244, 244, p2)
if (lat < 0) p2 <- (p2 + diy / 2)%%diy
p1 <- mmonth[round(clim[5], 0)]
peakdoy <- wgts(p1, p2, abs(lat), 0, 30)
maxlai <- -0.7206 + 0.272 * log(clim[3])
minlai <- -0.146 + 0.059 * log(clim[3])
minlai <- ifelse(minlai < 0.001, 0.001, minlai)
x <- 0.7
hgt <- 1.5
}
if (habitat == "Woody savannas" | habitat == 8) {
hperiod1 <- 47.6380 + 2.9232 * clim[1]
hperiod1 <- ifelse(hperiod1 < 32.5, 32.5, hperiod1)
hperiod2 <- 71.72 + 3.012 * clim[1]
h1 <- (hperiod1 + hperiod2) / 2
h2 <- 282.04 - 92.28 * clim[4]
h2 <- ifelse(hperiod1 < 31.9, 31.9, hperiod1)
hperiod <- wgts(h1, h2, abs(lat), 25, 35)
peakdoy1 <- 209.760 - 1.208 * clim[1]
peakdoy1 <- ifelse(peakdoy1 > 244, 244, peakdoy1)
if (lat < 0) peakdoy1 <- ( peakdoy1 + diy / 2)%%diy
peakdoy2 <- 211.98 - 3.4371 * clim[1]
peakdoy2 <- ifelse(peakdoy2 > 244, 244, peakdoy2)
if (lat < 0) peakdoy2 <- (peakdoy2 + diy / 2)%%diy
p2 <- (peakdoy1 + peakdoy2) / 2
p1 <- mmonth[round(clim[5], 0)]
peakdoy <- wgts(p1, p2, abs(lat), 10, 40)
if (clim[1] <= 20) {
maxlai1 <- 3.98795 + 0.03330 * clim[1]
maxlai2 <- 1.0532 * 0.016 * clim[1]
} else {
maxlai1 <- 3.98795 + 0.03330 * 20
maxlai2 <- 1.0532 * 0.016 * 20
}
mx2 <- (maxlai1 + maxlai2) / 2
minlai1 <- 0.4808
minlai2 <- 0.0725 * 0.011 * clim[1]
mn2 <- (minlai1 + minlai2) / 2
mx1 <- 1.298 + 0.171 * log(clim[3])
mn1 <- -2.9458 + 0.5889 * log(clim[3])
maxlai <- wgts(mx1, mx2, abs(lat), 10, 40)
minlai <- wgts(mn1, mn2, abs(lat), 10, 40)
minlai <- ifelse(minlai < 0.0362, 0.0362, minlai)
x <- 0.7
hgt <- 3
}
if (habitat == "Savannas" | habitat == 9 |
habitat == "Short grasslands" | habitat == 10 |
habitat == "Tall grasslands" | habitat == 11) {
h2 <- 71.72 + 3.012 * clim[1]
h1 <- 269.22 - 89.79 * clim[4]
hperiod <- wgts(h1, h2, abs(lat), 0, 20)
hperiod <- ifelse(hperiod < 31.9, 31.9, hperiod)
p2 <- 211.98 - 3.4371 * clim[1]
p2 <- ifelse(p2 > 244, 244, p2)
if (lat < 0) p2 <- (p2 + diy / 2)%%diy
p1 <- mmonth[round(clim[5], 0)]
peakdoy <- wgts(p1, p2, abs(lat), 0, 30)
mx2 <- 1.48
mn2 <- 0.0725 * 0.011 * clim[1]
mx1 <- 0.1215 + 0.2662 * log(clim[3])
mn1 <- 0.331 + 0.0575 * log(clim[3])
maxlai <- wgts(mx1, mx2, abs(lat), 10, 40)
minlai <- wgts(mn1, mn2, abs(lat), 10, 40)
minlai <- ifelse(minlai < 0.762, 0.762, minlai)
x <- 0.15
if (habitat == "Savannas" | habitat == 9) hgt <- 1.5
if (habitat == "Short grasslands" | habitat == 10) hgt <- 0.25
if (habitat == "Tall grasslands" | habitat == 11) hgt <- 1.5
}
if (habitat == "Permanent wetlands" | habitat == 12) {
h2 <- 76 + 4.617 * clim[1]
h1 <- 246.68 - 66.82 * clim[4]
hperiod <- wgts(h1, h2, abs(lat), 0, 20)
hperiod <- ifelse(hperiod < 40, 40, hperiod)
p2 <- 219.64 - 2.793 * clim[1]
p2 <- ifelse(p2 > 244, 244, p2)
if (lat < 0) p2 <- (p2 + diy / 2)%%diy
p1 <- mmonth[round(clim[5], 0)]
peakdoy <- wgts(p1, p2, abs(lat), 0, 30)
maxlai <- -0.1782 + 0.2608 * log(clim[3])
maxlai <- ifelse(maxlai < 1.12, 1.12, maxlai)
minlai <- -0.1450 + 0.1440 * log(clim[3])
minlai <- ifelse(minlai < 0.001, 0.001, minlai)
x <- 1.4
hgt <- 0.5
}
if (habitat == "Croplands" | habitat == 13) {
h2 <- 54.893 + 1.785 * clim[1]
h1 <- 243 - 112.18 * clim[4]
hperiod <- wgts(h1, h2, abs(lat), 10, 30)
hperiod <- ifelse(hperiod < 43.5, 43.5, hperiod)
p2 <- 212.95 - 5.627 * clim[1]
p2 <- ifelse(p2 > 244, 244, p2)
if (lat < 0) p2 <- (p2 + diy / 2)%%diy
p1 <- mmonth[round(clim[5], 0)]
peakdoy <- wgts(p1, p2, abs(lat), 0, 30)
if (clim[1] <= 20) {
maxlai <- 3.124 - 0.0886 * clim[1]
} else maxlai <- 3.124 - 0.0886 * 20
maxlai <- ifelse(maxlai > 3.14, 3.14, maxlai)
minlai <- 0.13
x <- 0.2
hgt <- 0.5
}
if (habitat == "Urban and built-up" | habitat == 14) {
h2 <- 66.669 + 5.618 * clim[1]
h1 <- 283.44 - 86.11 * clim[4]
hperiod <- wgts(h1, h2, abs(lat), 0, 20)
hperiod <- ifelse(hperiod < 43.5, 43.5, hperiod)
p2 <- 215.998 - 4.2806 * clim[1]
p2 <- ifelse(p2 > 244, 244, p2)
if (lat < 0) p2 <- (p2 + diy / 2)%%diy
p1 <- mmonth[round(clim[5], 0)]
peakdoy <- wgts(p1, p2, abs(lat), 10, 30)
if (clim[1] <= 20) {
maxlai <- 1.135 - 0.0244 * clim[1]
} else maxlai <- 1.135 - 0.0244 * 20
maxlai <- ifelse(maxlai > 1.15, 1.15, maxlai)
minlai <- 0.28
x <- 1
hgt <- 0.8
}
if (habitat == "Cropland/Natural vegetation mosaic" | habitat == 15) {
warning("Results highly sensitive to habitat composition. Suggest running
seperately for constituent habitat types and weighting output")
h2 <- 29.490 + 8.260 * clim[1]
h1 <- 326.46 - 161.70 * clim[4]
hperiod <- wgts(h1, h2, abs(lat), 10, 30)
hperiod <- ifelse(hperiod < 43.5, 43.5, hperiod)
p2 <- 210.867 - 3.5464 * clim[1]
p2 <- ifelse(p2 > 244, 244, p2)
if (lat < 0) p2 <- (p2 + diy / 2)%%diy
p1 <- mmonth[round(clim[5], 0)]
peakdoy <- wgts(p1, p2, abs(lat), 10, 30)
if (clim[1] <= 20) {
maxlai <- 3.5485 - 0.09481 * clim[1]
} else maxlai <- 3.5485 - 0.09481 * 20
maxlai <- ifelse(maxlai > 3.14, 3.14, maxlai)
if (clim[1] <= 20) {
minlai <- -0.072815 - 0.044546 * clim[1]
} else minlai <- -0.072815 - 0.044546 * 20
minlai <- ifelse(minlai < 0.001, 0.001, minlai)
x <- 0.5
hgt <- 1
}
if (habitat == "Barren or sparsely vegetated" | habitat == 16) {
h2 <- 80.557 + 6.440 * clim[1]
h1 <- 344.65 - -191.94 * clim[4]
hperiod <- wgts(h1, h2, abs(lat), 0, 20)
hperiod <- ifelse(hperiod < 43.5, 43.5, hperiod)
p2 <- 236.0143 - 3.4726 * clim[1]
p2 <- ifelse(p2 > 244, 244, p2)
if (lat < 0) p2 <- (p2 + diy / 2)%%diy
p1 <- mmonth[round(clim[5], 0)]
peakdoy <- wgts(p1, p2, abs(lat), 10, 30)
maxlai <- -0.05491 + 0.05991 * log(clim[4])
maxlai <- ifelse(maxlai < 0.81, 0.81, maxlai)
minlai <- 0.08
x <- 0.6
hgt <- 0.15
}
if (habitat == "Open water" | habitat == 17) {
hperiod <- 100
peakdoy <- 50
maxlai <- 0
minlai <- 0
hgt <- 0
}
lai <- laigaus(minlai, maxlai, peakdoy, hperiod, year)
if (habitat == "Short grasslands" | habitat == 10) lai <- lai / 2
tme <- c(1:length(lai)) - 1
tme <- as.POSIXlt(tme * 3600, origin = paste0(year,"-01-01 00:00"), tz = "UTC")
return(list(lai = lai, x = x, height = hgt, obs_time = tme))
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/getFasta.R
\name{getFasta}
\alias{getFasta}
\title{Extract fasta sequence given a set of genomic intervals and a reference
genome.}
\usage{
getFasta(GR, BSgenome, width = 1e3, filename = 'tmp.fa')
}
\arguments{
\item{GR}{A GRanges object indicating genomic coordinates}
\item{BSgenome}{A BSgenome object indicating the genome of interest}
\item{width}{A number indicating a fixed width of sequences}
\item{filename}{The Name of the input fasta format file, including
full path to file if it is located outside the current working directory}
}
\value{
writes a fasta file
}
\description{
DNAshapeR can predict DNA shape features from custom FASTA files or directly
from genomic coordinates in the form of a GRanges object within BioConductor
(see
<https://bioconductor.org/packages/release/bioc/html/GenomicRanges.html>
for more information).
}
\examples{
gr <- GRanges(seqnames = c("chrI"),
strand = c("+", "-", "+"),
ranges = IRanges(start = c(100, 200, 300), width = 100))
library(BSgenome.Scerevisiae.UCSC.sacCer3)
getFasta(gr, BSgenome = Scerevisiae, width = 100, filename = "tmp.fa")
fn <- "tmp.fa"
pred <- getShape(fn)
}
\author{
Federico Comoglio
}
\keyword{core}
| /Shape Information/DNAshapeR-2nd-order/man/getFasta.Rd | permissive | felixekn/MuANN | R | false | true | 1,255 | rd | % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/getFasta.R
\name{getFasta}
\alias{getFasta}
\title{Extract fasta sequence given a set of genomic intervals and a reference
genome.}
\usage{
getFasta(GR, BSgenome, width = 1e3, filename = 'tmp.fa')
}
\arguments{
\item{GR}{A GRanges object indicating genomic coordinates}
\item{BSgenome}{A BSgenome object indicating the genome of interest}
\item{width}{A number indicating a fixed width of sequences}
\item{filename}{The Name of the input fasta format file, including
full path to file if it is located outside the current working directory}
}
\value{
writes a fasta file
}
\description{
DNAshapeR can predict DNA shape features from custom FASTA files or directly
from genomic coordinates in the form of a GRanges object within BioConductor
(see
<https://bioconductor.org/packages/release/bioc/html/GenomicRanges.html>
for more information).
}
\examples{
gr <- GRanges(seqnames = c("chrI"),
strand = c("+", "-", "+"),
ranges = IRanges(start = c(100, 200, 300), width = 100))
library(BSgenome.Scerevisiae.UCSC.sacCer3)
getFasta(gr, BSgenome = Scerevisiae, width = 100, filename = "tmp.fa")
fn <- "tmp.fa"
pred <- getShape(fn)
}
\author{
Federico Comoglio
}
\keyword{core}
|
\docType{data}
\name{dat}
\alias{dat}
\title{dat: Four random walks}
\format{Four random walks of length 100, described by:
\describe{
\item{time}{The time points (1--100)}
\item{variable}{The identifier for each random walk (A, B, C, D)}
\item{value}{The value of the time series}
}}
\usage{
data(dat)
}
\description{
Four random walks, generated with independent N(0, 1) errors. Used to illustrate ggplot2 vs base graphics.
}
| /man/dat.Rd | no_license | lukketotte/StatProg | R | false | false | 433 | rd | \docType{data}
\name{dat}
\alias{dat}
\title{dat: Four random walks}
\format{Four random walks of length 100, described by:
\describe{
\item{time}{The time points (1--100)}
\item{variable}{The identifier for each random walk (A, B, C, D)}
\item{value}{The value of the time series}
}}
\usage{
data(dat)
}
\description{
Four random walks, generated with independent N(0, 1) errors. Used to illustrate ggplot2 vs base graphics.
}
|
library(shiny)
# Define UI for slider demo application
shinyUI(pageWithSidebar(
# Application title
headerPanel("Random Testing"),
# Sidebar with sliders that demonstrate various available options
sidebarPanel(
sliderInput("pop_size", h3("Population Size"),
min = 5000, max = 50000, value = 50000, step=1000),
sliderInput("tests", h3("Daily tests"),
min = 200, max = 2000, value = 1000, step=100),
sliderInput("ppn_sympt", h3("Proportion of cases symptomatic"),
min = 0, max = .5, value = .05, step=.05),
sliderInput("care_seeking_delay", h3("Days to seeking care"),
min = 0, max = 5, value = 2, round=TRUE),
sliderInput("R0", h3("R0"),
min = 1.5, max = 4, value = 2, step=0.25),
sliderInput("ppn_immune", h3("Proportion Immune"),
min = 0, max = .5, value = .15, step=0.05),
sliderInput("sensitivity", h3("Testing sensitivity"),
min = .9, max = 1, value = .99, step=0.05),
sliderInput("specificity", h3("Testing specificity"),
min = .9, max = 1, value = .99, step=0.05)
),
# plot output
mainPanel(
tabsetPanel(
tabPanel("Time to Detection",plotOutput("Time_to_detection_plot")),
tabPanel("False Positives",plotOutput("False_positives_plot"))
)
)
))
| /testing_shiny/ui.R | no_license | matthewferrari/COVIDstuff | R | false | false | 1,353 | r |
library(shiny)
# Define UI for slider demo application
shinyUI(pageWithSidebar(
# Application title
headerPanel("Random Testing"),
# Sidebar with sliders that demonstrate various available options
sidebarPanel(
sliderInput("pop_size", h3("Population Size"),
min = 5000, max = 50000, value = 50000, step=1000),
sliderInput("tests", h3("Daily tests"),
min = 200, max = 2000, value = 1000, step=100),
sliderInput("ppn_sympt", h3("Proportion of cases symptomatic"),
min = 0, max = .5, value = .05, step=.05),
sliderInput("care_seeking_delay", h3("Days to seeking care"),
min = 0, max = 5, value = 2, round=TRUE),
sliderInput("R0", h3("R0"),
min = 1.5, max = 4, value = 2, step=0.25),
sliderInput("ppn_immune", h3("Proportion Immune"),
min = 0, max = .5, value = .15, step=0.05),
sliderInput("sensitivity", h3("Testing sensitivity"),
min = .9, max = 1, value = .99, step=0.05),
sliderInput("specificity", h3("Testing specificity"),
min = .9, max = 1, value = .99, step=0.05)
),
# plot output
mainPanel(
tabsetPanel(
tabPanel("Time to Detection",plotOutput("Time_to_detection_plot")),
tabPanel("False Positives",plotOutput("False_positives_plot"))
)
)
))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.