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
##This section downloads, unzips, and reads the data install.packages("downloader") library(downloader) download("https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip", dest="dataset.zip", mode="wb") unzip("dataset.zip", exdir = "./") dfHPC <- read.table("household_power_consumption.txt", sep = ";", header = TRUE, na.strings = "?", stringsAsFactors = FALSE) ##This section formats date column and subsets by date dfHPC$Date <- as.Date(dfHPC$Date, "%d/%m/%Y") Date1 <- as.Date("2007-02-01") Date2 <- as.Date("2007-02-02") dfSubset <- dfHPC[dfHPC$Date %in% Date1:Date2, ] ##This section creates a new column that is properly formatted date/time for later use z <- paste(dfSubset$Date, dfSubset$Time) dfSubset$DT <- strptime(z, "%Y-%m-%d %H:%M:%S") ##Begin Plot 1 par(mfrow = c(1,1)) with(dfSubset, hist(Global_active_power, col = "red", xlab = "Global Active Power (kilowatts)", main = "Global Active Power")) dev.copy(png, file = "plot1.png", width = 480, height = 480, units = "px") dev.off()
/plot1.R
no_license
emlaughlin/ExData_Plotting1
R
false
false
1,130
r
##This section downloads, unzips, and reads the data install.packages("downloader") library(downloader) download("https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip", dest="dataset.zip", mode="wb") unzip("dataset.zip", exdir = "./") dfHPC <- read.table("household_power_consumption.txt", sep = ";", header = TRUE, na.strings = "?", stringsAsFactors = FALSE) ##This section formats date column and subsets by date dfHPC$Date <- as.Date(dfHPC$Date, "%d/%m/%Y") Date1 <- as.Date("2007-02-01") Date2 <- as.Date("2007-02-02") dfSubset <- dfHPC[dfHPC$Date %in% Date1:Date2, ] ##This section creates a new column that is properly formatted date/time for later use z <- paste(dfSubset$Date, dfSubset$Time) dfSubset$DT <- strptime(z, "%Y-%m-%d %H:%M:%S") ##Begin Plot 1 par(mfrow = c(1,1)) with(dfSubset, hist(Global_active_power, col = "red", xlab = "Global Active Power (kilowatts)", main = "Global Active Power")) dev.copy(png, file = "plot1.png", width = 480, height = 480, units = "px") dev.off()
# calculate the root mean square error of a model's predictions rmse_calc = function(true_value, predictions) { rmse = sqrt(mean((predictions - true_value)^2)) return(rmse) }
/general_functions/general_utils.R
no_license
marccgrau/dml_estimator_plm
R
false
false
178
r
# calculate the root mean square error of a model's predictions rmse_calc = function(true_value, predictions) { rmse = sqrt(mean((predictions - true_value)^2)) return(rmse) }
library(qmethod) ### Name: make.distribution ### Title: Q methodology: create Q normal distribution ### Aliases: make.distribution ### ** Examples ## Make Q distribution make.distribution(nstat=76, max.bin=7)
/data/genthat_extracted_code/qmethod/examples/make.distribution.Rd.R
no_license
surayaaramli/typeRrh
R
false
false
220
r
library(qmethod) ### Name: make.distribution ### Title: Q methodology: create Q normal distribution ### Aliases: make.distribution ### ** Examples ## Make Q distribution make.distribution(nstat=76, max.bin=7)
testlist <- list(data = structure(0, .Dim = c(1L, 1L)), x = structure(c(0, 1.33091576009481e-309, 5.00368698948671e-304, 1.3545163781073e+248, 2.02822087722601e-110, 7.80639368600506e+115, 2.84878894080431e-306, 5.66569438147973e-217, 4.94433309099852e-312, 2.48588604007856e-265, 1.79809443502751e-309, 0, 2.50632319422251e-304, 0, 1.25205814058912e-312, 1.60553053506776e-306, 0, 0, 3.95252516672997e-323, 8.12983395216297e-261, 0, 6.84076707059454e-304, 0, 8.70026139148914e-316, 2.08882847642057e-314, 4.10547562541273e+62, 1.62916584656708e-260, 2.6425885427944e-260, 1.23055912552855e-269, 5.26246667113329e-312, 0, 0, 4.88059031922013e-312, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8.4886982972039e-314, 2.81776900841821e-202, 2.81772601270452e-202, 7.80639044993566e+115, 1.46942191467086e-105, 5.50828115013509e+125, 7.3055433066634e-304), .Dim = c(10L, 5L ))) result <- do.call(distr6:::C_EmpiricalMVPdf,testlist) str(result)
/distr6/inst/testfiles/C_EmpiricalMVPdf/libFuzzer_C_EmpiricalMVPdf/C_EmpiricalMVPdf_valgrind_files/1610035707-test.R
no_license
akhikolla/updated-only-Issues
R
false
false
935
r
testlist <- list(data = structure(0, .Dim = c(1L, 1L)), x = structure(c(0, 1.33091576009481e-309, 5.00368698948671e-304, 1.3545163781073e+248, 2.02822087722601e-110, 7.80639368600506e+115, 2.84878894080431e-306, 5.66569438147973e-217, 4.94433309099852e-312, 2.48588604007856e-265, 1.79809443502751e-309, 0, 2.50632319422251e-304, 0, 1.25205814058912e-312, 1.60553053506776e-306, 0, 0, 3.95252516672997e-323, 8.12983395216297e-261, 0, 6.84076707059454e-304, 0, 8.70026139148914e-316, 2.08882847642057e-314, 4.10547562541273e+62, 1.62916584656708e-260, 2.6425885427944e-260, 1.23055912552855e-269, 5.26246667113329e-312, 0, 0, 4.88059031922013e-312, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8.4886982972039e-314, 2.81776900841821e-202, 2.81772601270452e-202, 7.80639044993566e+115, 1.46942191467086e-105, 5.50828115013509e+125, 7.3055433066634e-304), .Dim = c(10L, 5L ))) result <- do.call(distr6:::C_EmpiricalMVPdf,testlist) str(result)
###### # Reproducible Research # This is the raw working file where script was developed to complete Project 1 # ####### # Loading and preprocessing the data # # Show any code that is needed to # # 1. Load the data (i.e. read.csv()) if(!exists("activity")){ activity<-read.csv("activity.csv") } # # 2. Process/transform the data (if necessary) into a format suitable for your analysis #seems fine as is # # What is mean total number of steps taken per day? # # For this part of the assignment, you can ignore the missing values in the dataset. # # 1. Calculate the total number of steps taken per day total_steps_daily <- aggregate(steps ~ date, activity, sum) # 2. If you do not understand the difference between a histogram and a barplot, research the difference between them. Make a histogram of the total number of steps taken each day #http://stackoverflow.com/questions/10770698/understanding-dates-and-plotting-a-histogram-with-ggplot2-in-r #total_steps_daily$date <- as.Date(total_steps_daily$date) # format the date field as a Date # hist(total_steps_daily$steps, # col=1, # breaks = 53, # main="Distribution of steps per day", # # axes = FALSE, # xlab="number of steps", # ylab="number of days", # angle = 45) # # 3. Calculate and report the mean and median of the total number of steps taken per day #mean(total_steps_daily$steps, na.rm = TRUE) # 10766.19 #median(total_steps_daily$steps, na.rm = TRUE) # 10765 #sum(total_steps_daily$steps, na.rm = TRUE) # 570608 # # What is the average daily activity pattern? # # 1. Make a time series plot (i.e. type = "l") of the 5-minute interval (x-axis) and the average number of steps taken, averaged across all days (y-axis) # calculate the mean number of steps per interval as a numeric vector mean_steps <- tapply(activity$steps, activity$interval, mean, na.rm = TRUE) # # calculate the x values intervals <- strptime(sprintf("%04d", as.numeric(names(mean_steps))), format="%H%M") # # plot the mean number of steps per day # plot(intervals, mean_steps, # type="l", # main="Mean steps per interval across days", # xlab="5 minute intervals", # ylab="Mean steps per interval" # ) #abline(v=round(max(mean_steps)), lty=3, col="blue") # # # 2. Which 5-minute interval, on average across all the days in the dataset, contains the maximum number of steps? # max_steps<-which.max(time_series) # max_steps[1] # # Imputing missing values # # Note that there are a number of days/intervals where there are missing values (coded as NA). The presence of missing days may introduce bias into some calculations or summaries of the data. # # 1. Calculate and report the total number of missing values in the dataset (i.e. the total number of rows with NAs) # originalValue <- complete.cases(activity) # missingValues <- length(originalValue[originalValue==FALSE]) # number of records with NA # missingValues # nComplete <- length(originalValue[originalValue==TRUE]) # number of complete records # title="Missing vs. Complete Cases" # barplot(table(originalValue),main=title,xaxt='n') # render Complete Cases barplot # axis(side=1,at=c(.7,1.9),labels=c("Missing","Complete"),tick=FALSE) # render axis # text(.7,0,labels=nMissing, pos=3) # label the NA's bar # text(1.9,0,labels=nComplete, pos=3) # # 2. Devise a strategy for filling in all of the missing values in the dataset. The strategy does not need to be sophisticated. For example, you could use the mean/median for that day, or the mean for that 5-minute interval, etc. activity2 <- activity # copy original df into a new one for (i in 1:nrow(activity2)){ # loop through the new df if (is.na(activity2$steps[i])){ # if a value is missing (NA) activity2$steps[i] <- mean_steps[i] # replace it with the value previously # calculated in mean_steps for the given } # interval } # # 3. Create a new dataset that is equal to the original dataset but with the missing data filled in. #already did above # # 4. Make a histogram of the total number of steps taken each day and Calculate and report the mean and median total number of steps taken per day. Do these values differ from the estimates from the first part of the assignment? What is the impact of imputing missing data on the estimates of the total daily number of steps? total_steps_daily2 <- aggregate(strtoi(steps) ~ date, activity2, sum) # mean(strtoi(total_steps_daily2$steps), na.rm = TRUE) # 10766.19 # median(total_steps_daily2$steps, na.rm = TRUE) # 10765 # sum(total_steps_daily2$steps, na.rm = TRUE) # 570608 # # Are there differences in activity patterns between weekdays and weekends? # # For this part the weekdays() function may be of some help here. Use the dataset with the filled-in missing values for this part. # # 1. Create a new factor variable in the dataset with two levels – “weekday” and “weekend” indicating whether a given date is a weekday or weekend day. weekdays(as.Date(total_steps_daily2$date), abbreviate=TRUE) daytype <- function(date) { if (weekdays(as.Date(date)) %in% c("Saturday", "Sunday")) { "weekend" } else { "weekday" } } activity2$daytype <- as.factor(sapply(activity2$date, daytype)) # # 2. Make a panel plot containing a time series plot (i.e. type = "l") of the 5-minute interval (x-axis) and the average number of steps taken, averaged across all weekday days or weekend days (y-axis). See the README file in the GitHub repository to see an example of what this plot should look like using simulated data. par(mfrow = c(2, 1)) for (type in c("weekend", "weekday")) { steps.type <- aggregate(steps ~ interval, data = activity2, subset = activity2$daytype == type, FUN = mean) plot(steps.type, type = "l", main = type) }
/project1.R
no_license
gregrgay/RepData_PeerAssessment1
R
false
false
6,021
r
###### # Reproducible Research # This is the raw working file where script was developed to complete Project 1 # ####### # Loading and preprocessing the data # # Show any code that is needed to # # 1. Load the data (i.e. read.csv()) if(!exists("activity")){ activity<-read.csv("activity.csv") } # # 2. Process/transform the data (if necessary) into a format suitable for your analysis #seems fine as is # # What is mean total number of steps taken per day? # # For this part of the assignment, you can ignore the missing values in the dataset. # # 1. Calculate the total number of steps taken per day total_steps_daily <- aggregate(steps ~ date, activity, sum) # 2. If you do not understand the difference between a histogram and a barplot, research the difference between them. Make a histogram of the total number of steps taken each day #http://stackoverflow.com/questions/10770698/understanding-dates-and-plotting-a-histogram-with-ggplot2-in-r #total_steps_daily$date <- as.Date(total_steps_daily$date) # format the date field as a Date # hist(total_steps_daily$steps, # col=1, # breaks = 53, # main="Distribution of steps per day", # # axes = FALSE, # xlab="number of steps", # ylab="number of days", # angle = 45) # # 3. Calculate and report the mean and median of the total number of steps taken per day #mean(total_steps_daily$steps, na.rm = TRUE) # 10766.19 #median(total_steps_daily$steps, na.rm = TRUE) # 10765 #sum(total_steps_daily$steps, na.rm = TRUE) # 570608 # # What is the average daily activity pattern? # # 1. Make a time series plot (i.e. type = "l") of the 5-minute interval (x-axis) and the average number of steps taken, averaged across all days (y-axis) # calculate the mean number of steps per interval as a numeric vector mean_steps <- tapply(activity$steps, activity$interval, mean, na.rm = TRUE) # # calculate the x values intervals <- strptime(sprintf("%04d", as.numeric(names(mean_steps))), format="%H%M") # # plot the mean number of steps per day # plot(intervals, mean_steps, # type="l", # main="Mean steps per interval across days", # xlab="5 minute intervals", # ylab="Mean steps per interval" # ) #abline(v=round(max(mean_steps)), lty=3, col="blue") # # # 2. Which 5-minute interval, on average across all the days in the dataset, contains the maximum number of steps? # max_steps<-which.max(time_series) # max_steps[1] # # Imputing missing values # # Note that there are a number of days/intervals where there are missing values (coded as NA). The presence of missing days may introduce bias into some calculations or summaries of the data. # # 1. Calculate and report the total number of missing values in the dataset (i.e. the total number of rows with NAs) # originalValue <- complete.cases(activity) # missingValues <- length(originalValue[originalValue==FALSE]) # number of records with NA # missingValues # nComplete <- length(originalValue[originalValue==TRUE]) # number of complete records # title="Missing vs. Complete Cases" # barplot(table(originalValue),main=title,xaxt='n') # render Complete Cases barplot # axis(side=1,at=c(.7,1.9),labels=c("Missing","Complete"),tick=FALSE) # render axis # text(.7,0,labels=nMissing, pos=3) # label the NA's bar # text(1.9,0,labels=nComplete, pos=3) # # 2. Devise a strategy for filling in all of the missing values in the dataset. The strategy does not need to be sophisticated. For example, you could use the mean/median for that day, or the mean for that 5-minute interval, etc. activity2 <- activity # copy original df into a new one for (i in 1:nrow(activity2)){ # loop through the new df if (is.na(activity2$steps[i])){ # if a value is missing (NA) activity2$steps[i] <- mean_steps[i] # replace it with the value previously # calculated in mean_steps for the given } # interval } # # 3. Create a new dataset that is equal to the original dataset but with the missing data filled in. #already did above # # 4. Make a histogram of the total number of steps taken each day and Calculate and report the mean and median total number of steps taken per day. Do these values differ from the estimates from the first part of the assignment? What is the impact of imputing missing data on the estimates of the total daily number of steps? total_steps_daily2 <- aggregate(strtoi(steps) ~ date, activity2, sum) # mean(strtoi(total_steps_daily2$steps), na.rm = TRUE) # 10766.19 # median(total_steps_daily2$steps, na.rm = TRUE) # 10765 # sum(total_steps_daily2$steps, na.rm = TRUE) # 570608 # # Are there differences in activity patterns between weekdays and weekends? # # For this part the weekdays() function may be of some help here. Use the dataset with the filled-in missing values for this part. # # 1. Create a new factor variable in the dataset with two levels – “weekday” and “weekend” indicating whether a given date is a weekday or weekend day. weekdays(as.Date(total_steps_daily2$date), abbreviate=TRUE) daytype <- function(date) { if (weekdays(as.Date(date)) %in% c("Saturday", "Sunday")) { "weekend" } else { "weekday" } } activity2$daytype <- as.factor(sapply(activity2$date, daytype)) # # 2. Make a panel plot containing a time series plot (i.e. type = "l") of the 5-minute interval (x-axis) and the average number of steps taken, averaged across all weekday days or weekend days (y-axis). See the README file in the GitHub repository to see an example of what this plot should look like using simulated data. par(mfrow = c(2, 1)) for (type in c("weekend", "weekday")) { steps.type <- aggregate(steps ~ interval, data = activity2, subset = activity2$daytype == type, FUN = mean) plot(steps.type, type = "l", main = type) }
Get2dBIRObj <- function(X, Y, theta, W.est, lambda){ W.est <- as.matrix(W.est) LS <- (1/(2*nrow(X)))*sum((Y%*%Rot(theta) - as.matrix(X)%*%W.est)^2) L0 <- (sum(sign(abs(W.est[,1])))+sum(sign(abs(W.est[,2])))) LS + lambda*L0 }
/Functions/get_2d_BIR_obj.R
permissive
AdrienBibal/BIR
R
false
false
235
r
Get2dBIRObj <- function(X, Y, theta, W.est, lambda){ W.est <- as.matrix(W.est) LS <- (1/(2*nrow(X)))*sum((Y%*%Rot(theta) - as.matrix(X)%*%W.est)^2) L0 <- (sum(sign(abs(W.est[,1])))+sum(sign(abs(W.est[,2])))) LS + lambda*L0 }
# Set working directory setwd("C:/Users/jess_chen/Dropbox/Jess-LISA/Simulations/Data/") ###################### Read Files ###################### data5 = read.csv("DATA_Local cluster_05_heter.csv") data10 = read.csv("DATA_Local cluster_10_heter.csv") data15 = read.csv("DATA_Local cluster_15_heter.csv") data20 = read.csv("DATA_Local cluster_20_heter.csv") data30 = read.csv("DATA_Local cluster_30_heter.csv") ###################### Test Plots ###################### # Get the mean count generated for each county # County is red if it exceeds the nth percentile # Where n is based on cluster size sum_5=rowMeans(data5[,6:1005]) sum_10=rowMeans(data10[,6:1005]) sum_15=rowMeans(data15[,6:1005]) sum_20=rowMeans(data20[,6:1005]) sum_30=rowMeans(data30[,6:1005]) par(mfrow=c(3,2)) plot(data5$longitude, data5$latitude, main = "5% Cluster", xlab = "Longitude", ylab = "Latitude", col = ifelse(sum_5> quantile(sum_5, 0.95),'red','green')) plot(data5$longitude, data5$latitude, main = "10% Cluster", xlab = "Longitude", ylab = "Latitude", col = ifelse(sum_10> quantile(sum_10, 0.9),'red','green')) plot(data5$longitude, data5$latitude, main = "15% Cluster", xlab = "Longitude", ylab = "Latitude", col = ifelse(sum_15> quantile(sum_15, 0.85),'red','green')) plot(data5$longitude, data5$latitude, main = "20% Cluster", xlab = "Longitude", ylab = "Latitude", col = ifelse(sum_20> quantile(sum_20, 0.8),'red','green')) plot(data5$longitude, data5$latitude, main = "30% Cluster", xlab = "Longitude", ylab = "Latitude", col = ifelse(sum_30> quantile(sum_30, 0.7),'red','green')) ###################### Output for ArcGIS ###################### sum_5[sum_5>quantile(sum_5, 0.95)]<-1 sum_5[sum_5<=quantile(sum_5, 0.95)]<-0 sum_10[sum_10>quantile(sum_10, 0.95)]<-1 sum_10[sum_10<=quantile(sum_10, 0.95)]<-0 sum_15[sum_15>quantile(sum_15, 0.95)]<-1 sum_15[sum_15<=quantile(sum_15, 0.95)]<-0 sum_20[sum_20>quantile(sum_20, 0.95)]<-1 sum_20[sum_20<=quantile(sum_20, 0.95)]<-0 sum_30[sum_30>quantile(sum_30, 0.95)]<-1 sum_30[sum_30<=quantile(sum_30, 0.95)]<-0 cluster5 = cbind(data5[,1:5], sum_5) cluster10 = cbind(data10[,1:5], sum_10) cluster15 = cbind(data15[,1:5], sum_15) cluster20 = cbind(data20[,1:5], sum_20) cluster30 = cbind(data30[,1:5], sum_30) write.table(countypop[closest,], file = filename, sep = ",", row.names = FALSE)
/CODE_Plot_Clusters.R
no_license
jesschen32/LISA
R
false
false
2,348
r
# Set working directory setwd("C:/Users/jess_chen/Dropbox/Jess-LISA/Simulations/Data/") ###################### Read Files ###################### data5 = read.csv("DATA_Local cluster_05_heter.csv") data10 = read.csv("DATA_Local cluster_10_heter.csv") data15 = read.csv("DATA_Local cluster_15_heter.csv") data20 = read.csv("DATA_Local cluster_20_heter.csv") data30 = read.csv("DATA_Local cluster_30_heter.csv") ###################### Test Plots ###################### # Get the mean count generated for each county # County is red if it exceeds the nth percentile # Where n is based on cluster size sum_5=rowMeans(data5[,6:1005]) sum_10=rowMeans(data10[,6:1005]) sum_15=rowMeans(data15[,6:1005]) sum_20=rowMeans(data20[,6:1005]) sum_30=rowMeans(data30[,6:1005]) par(mfrow=c(3,2)) plot(data5$longitude, data5$latitude, main = "5% Cluster", xlab = "Longitude", ylab = "Latitude", col = ifelse(sum_5> quantile(sum_5, 0.95),'red','green')) plot(data5$longitude, data5$latitude, main = "10% Cluster", xlab = "Longitude", ylab = "Latitude", col = ifelse(sum_10> quantile(sum_10, 0.9),'red','green')) plot(data5$longitude, data5$latitude, main = "15% Cluster", xlab = "Longitude", ylab = "Latitude", col = ifelse(sum_15> quantile(sum_15, 0.85),'red','green')) plot(data5$longitude, data5$latitude, main = "20% Cluster", xlab = "Longitude", ylab = "Latitude", col = ifelse(sum_20> quantile(sum_20, 0.8),'red','green')) plot(data5$longitude, data5$latitude, main = "30% Cluster", xlab = "Longitude", ylab = "Latitude", col = ifelse(sum_30> quantile(sum_30, 0.7),'red','green')) ###################### Output for ArcGIS ###################### sum_5[sum_5>quantile(sum_5, 0.95)]<-1 sum_5[sum_5<=quantile(sum_5, 0.95)]<-0 sum_10[sum_10>quantile(sum_10, 0.95)]<-1 sum_10[sum_10<=quantile(sum_10, 0.95)]<-0 sum_15[sum_15>quantile(sum_15, 0.95)]<-1 sum_15[sum_15<=quantile(sum_15, 0.95)]<-0 sum_20[sum_20>quantile(sum_20, 0.95)]<-1 sum_20[sum_20<=quantile(sum_20, 0.95)]<-0 sum_30[sum_30>quantile(sum_30, 0.95)]<-1 sum_30[sum_30<=quantile(sum_30, 0.95)]<-0 cluster5 = cbind(data5[,1:5], sum_5) cluster10 = cbind(data10[,1:5], sum_10) cluster15 = cbind(data15[,1:5], sum_15) cluster20 = cbind(data20[,1:5], sum_20) cluster30 = cbind(data30[,1:5], sum_30) write.table(countypop[closest,], file = filename, sep = ",", row.names = FALSE)
#### UBER ASSIGNMENT #### #Loading the required packages library(lubridate) library(stringr) library(ggplot2) library(dplyr) #Getting uber request data into R Uber.Request<-read.csv("Uber Request Data.csv",stringsAsFactors = FALSE) #Observing the structure of dataframe Uber.Requests str(Uber.Request) #or you can also have a glimpse of data frame using Uber.Requests glimpse(Uber.Request) ####Handling data quality issues/Data Cleaning#### #checking for any duplicate rows cat ('there are',(nrow(Uber.Request)-nrow(Uber.Request %>% unique)),'duplicate rows') #there are 0 duplicate rows # checking for any NA values in all columns, one after other # checking for any NA values in column Request.id anyNA(Uber.Request$Request.id) # no NA's # checking for any NA values in column anyNA(Uber.Request$Driver.id) # NA's present(2650) # checking for any NA values in column anyNA(Uber.Request$Pickup.point) # no NA's # checking for any NA values in column anyNA(Uber.Request$Status) # no NA's # checking for any NA values in column anyNA(Uber.Request$Request.timestamp) # no NA's # checking for any NA values in column anyNA(Uber.Request$Drop.timestamp) # NA's present(3914) # It looks appropriate to leave the NA's untouched as they # look valid in the columns Driver.id and Drop.timestamp the NA's # in the respective columns are present when there is a value # "no cars available" in column status #checking for any spelling mistakes in categorical columns #In column Pickup.point unique(Uber.Request$Pickup.point) # there are only two unique values "Airport" "City" in column Pickup.point.There are no spelling mistakes #In column Status unique(Uber.Request$Status) #there are only three unique values Trip Completed,Cancelled,No Cars Available in column Status.There are no spelling mistakes ###########DATA PREPERATION#################### ####Handling date and time columns Request.timestamp and Drop.timestamp which are read as type character#### ##Request.timestamp## #Parsing Request.timestamp and storing it in the column Request_Date Uber.Request$Request_Date<- lubridate::parse_date_time(Uber.Request$Request.timestamp,orders = c("d/m/Y H:M","d-m-Y H-M-S")) # checking if there are any NA's coerced because of invalid data values (Uber.Request$Request.timestamp %>% is.na %>% sum) == (Uber.Request$Request_Date %>% is.na %>% sum) #It gives TRUE means NA's are not coerced.This also means there are no invalid data values in Request.timestamp #spliting date from Request_Date and storing it in column Request.Date Uber.Request$Request.Date<- as.Date(Uber.Request$Request_Date) #Extracting Day of the week from Request.Date and storing it in Request.Day column Uber.Request$Request.Day<- weekdays(Uber.Request$Request_Date) #spliting date form Request_Date and storing it in column Request.Time Uber.Request$Request.Time<-format(Uber.Request$Request_Date,"%H:%M:%S") #Extracting hours mins and sec from column Request.timestamp Uber.Request$Request.hour<-lubridate::hour(Uber.Request$Request_Date) Uber.Request$Request.minute<-lubridate::minute(Uber.Request$Request_Date) Uber.Request$Request.second<-lubridate::second(Uber.Request$Request_Date) #grouping the data into different time slots morning,noon,evening and night #based on values in request.hour #defineing a timeslot function timeslot<-function(request.hour){ if(request.hour>=4 & request.hour<10){ return("Morning Slot") }else if(request.hour>=10 & request.hour<16){ return("Noon Slot") }else if(request.hour>=16 & request.hour<22){ return("Evening Slot") }else if(request.hour>=22 | request.hour<4){ return("Night Slot") }else{ return(NA) } } #creating timeslot column using timeslot function Uber.Request$Request.TimeSlot<-sapply(Uber.Request$Request.hour,timeslot) %>% unlist #checking for any coerced NA values in column Request.TimeSlot anyNA(Uber.Request$Request.TimeSlot)#FALSE no NA's #Dropping request_date column Uber.Request$Request.timestamp<-NULL #####Drop.timestamp##### #Parsing Drop.timestamp and storing it in the column Drop_Date Uber.Request$Drop_Date<- parse_date_time(Uber.Request$Drop.timestamp,orders = c("d/m/Y H:M","d-m-Y H-M-S")) # checking if there are any NA's coerced because of invalid data values (Uber.Request$Drop.timestamp %>% is.na %>% sum) == (Uber.Request$Drop_Date%>% is.na %>% sum) #It gives TRUE means NA's are not coerced. This also means there are no invalid data values in Drop.timestamp #spliting date form Drop_Date and storing it in column Drop.Date Uber.Request$Drop.Date<- as.Date(Uber.Request$Drop_Date) #spliting date form Drop_Date and storing it in column Drop.Time Uber.Request$Drop.Time<-format(Uber.Request$Drop_Date,"%T") #Extracting hours mins and sec from column Drop.timestamp Uber.Request$Drop.hour<-lubridate::hour(Uber.Request$Drop_Date) Uber.Request$Drop.minute<-lubridate::minute(Uber.Request$Drop_Date) Uber.Request$Drop.second<-lubridate::second(Uber.Request$Drop_Date) #Dropping request_date column Uber.Request$Drop.timestamp<-NULL #checking for the time duration of data present data.interval<-as.interval(min(Uber.Request$Request_Date),max(Uber.Request$Request_Date)) #checking the duration of the interval as.duration(data.interval) #Total 5 Days of data is present ######DATA ANALYSIS##### # Since Request.id and Driver.id are id or unique values there isn't much sense analysing them #Defining the Pickup.point variable as factor and ordering it's levels in a particuler order Uber.Request$Pickup.point<-factor(Uber.Request$Pickup.point,levels=c("City","Airport")) #Analysing variable Pickup.point by plotting a bar chart on it (and looking for some insights) ggplot(Uber.Request,aes(Pickup.point,fill=Pickup.point))+geom_bar(col="black")+annotate("text",x=c("Airport","City"),y=c(3450,3700),label=c("48%","51%"))+theme_bw() #The above plot shows that ,there isn't much difference between Airport and city pickup requests #Analysing variable Status by plotting a bar chart on it (and looking for some insights) ggplot(Uber.Request,aes(Status,fill=Status))+geom_bar(col="black")+annotate("text",x=c("Cancelled","No Cars Available","Trip Completed"),y=c(1400,2800,2950),label=c("19%","39%","41%"))+theme_bw() #The above plot clearly depicts that only 41% of the requests from city and #airport gets completed and the remaining 59% trips either get cancelled or #there is no car availability ########################################################################## #The proportions of above plot can be obtained from the following code prop.table(table(Uber.Request$Pickup.point)) prop.table(table(Uber.Request$Status)) ########################################################################## #segemnting pickup.point over status ggplot(Uber.Request,aes(x=Pickup.point,fill=Status))+geom_bar(position = "dodge",col="black")+geom_text(stat='count',aes(label=..count..),vjust=-1,position = position_dodge(width = 1))+theme_bw() #The above plot shows that for most of the Airport pickup requests there are #no cars available and most requests that get cancelled are city pickup requests #Analysing variable Request.hour by plotting a bar chart on it (and looking for #some insights) ggplot(Uber.Request,aes(Request.hour))+geom_bar(fill="royalblue1",col="black")+annotate("text",x=c(7.2,19),y=c(500,550),label=("High Request Rate"))+theme_bw() #The above plot clearly depicts that there are high request rates from 5AM TO 10AM #and 5pm to 10 pm #To get a better understanding of requests raised at different hours of the day #lets plot a chart on variable timeslot(which contains hours grouped into #different timeslots) #Defining the timeslot variable as factor and ordering it's levels in a particuler order Uber.Request$Request.TimeSlot<-factor(Uber.Request$Request.TimeSlot,levels=c("Morning Slot","Noon Slot","Evening Slot","Night Slot")) #plotting a bargraph on time slots ggplot(Uber.Request,aes(x=Request.TimeSlot,fill=Request.TimeSlot))+xlab("TimeSlot")+geom_bar(col="black")+annotate("text",x=c("Evening Slot","Morning Slot","Night Slot","Noon Slot"),y=c(2590,2400,975,1150),label=c("37%","34%","13%","16%"))+theme_bw() #the proportions can be obtained from the following code prop.table(table(Uber.Request$Request.TimeSlot)) #From the above plot it is clear that most of the requests are raised in #morning(34%) and evening(37%) slots #segmenting the timeslot variable by pickup point may give some more information ggplot(Uber.Request,aes(x=Request.TimeSlot,fill=Pickup.point))+xlab("Timeslot")+geom_bar(position = "dodge",col="black")+ geom_text(stat='count',aes(label=..count..),vjust=-1,position = position_dodge(width = 1))+theme_bw() #During morning slot city pickup requests are high #and during evening slot airport pickup requests are high #segmenting the timeslot variable by Status may give some information ggplot(Uber.Request,aes(x=Request.TimeSlot,fill=Status))+xlab("Timeslot")+geom_bar(position = "dodge",col="black")+ geom_text(stat='count',aes(label=..count..),vjust=-1,position = position_dodge(width = 1))+theme_bw() #segmenting the timeslot variable by both Status and pickup point may give some more information ggplot(Uber.Request,aes(x=Request.TimeSlot,fill=Status))+xlab("Timeslot")+geom_bar(col="black")+theme_bw()+facet_grid(Pickup.point~Status)+stat_count(aes(label = ..count..), geom = "text",vjust=-0.5,size=2)+theme(axis.text.x = element_text(face="bold", color = "#993333",size = 10,angle=90))+theme_bw() #From the above plot it is clear that most city requests get cancelled in the #morningslot(during which there is high city request rate) and for most of the #airport requests during the evening slot(during which there is high airport request rate) #there are no cars available #From the above plots it can be assumed that although there is not much difference city requests and airport requests , #city requests are problametic requests because most of city requests gets cancelled by drivers. #Most Uber drivers are not ready to drive to airport because they may have to wait long before they get a trip back to city #This is the same reason for most airport requests cars are not available ###############SUPPLY AND DEMAND GAP CALCULATION####################### demandd<-function(status){ if (status=="Cancelled"|status=="No Cars Available"|status=="Trip Completed"){ return("demand") }else{ return(NA) } } supply<-function(status){ if (status=="Cancelled"|status=="No Cars Available"){ return( "gap") }else{ return("supply") } } #creating supply column using supply function Uber.Request$supply<-sapply(Uber.Request$Status,supply) %>% unlist #checking for NA values in Uber.Request$supply anyNA(Uber.Request$supply) #No NA's #creating demand column using demand function Uber.Request$demand<-sapply(Uber.Request$Status,demandd) %>% unlist #checking for NA values in Uber.Request$demand anyNA(Uber.Request$demand) #No NA's #Finding supply and demand gap demand<-sum addmargins(table(Uber.Request$supply),FUN = demand) #so overall gap is 2831,it would be better if we look at this values in propotions addmargins(prop.table(table(Uber.Request$supply)),FUN = demand) # gap is 58% of demand #Demand And Supply plot ggplot(Uber.Request,aes(x=supply,fill=supply))+geom_bar(col="black")+geom_bar(aes(x=demand),col="black",fill="royalblue2")+geom_text(stat='count',aes(label=..count..),vjust=-1,position = position_dodge(width = 1))+theme_bw()+annotate("text",x="demand",y=6970,label="6745") #Finding supply and demand gap for each time slot seperately #morning slot addmargins(table(Uber.Request$supply[Uber.Request$Request.TimeSlot=="Morning Slot"]),FUN = demand) #proportions addmargins(prop.table(table(Uber.Request$supply[Uber.Request$Request.TimeSlot=="Morning Slot"])),FUN=demand) #For morning slot the gap is about 59% #noon slot addmargins(table(Uber.Request$supply[Uber.Request$Request.TimeSlot=="Noon Slot"]),FUN=demand) #proportions addmargins(prop.table(table(Uber.Request$supply[Uber.Request$Request.TimeSlot=="Noon Slot"])),FUN=demand) #For noon slot the gap is about 40% #evening slot addmargins(table(Uber.Request$supply[Uber.Request$Request.TimeSlot=="Evening Slot"]),FUN=demand) #proportion addmargins(prop.table(table(Uber.Request$supply[Uber.Request$Request.TimeSlot=="Evening Slot"])),FUN=demand) #For evening slot the gap is about 65% #night slot addmargins(table(Uber.Request$supply[Uber.Request$Request.TimeSlot=="Night Slot"]),FUN=demand) #proportion addmargins(prop.table(table(Uber.Request$supply[Uber.Request$Request.TimeSlot=="Night Slot"])),FUN = demand) #For night slot the gap is about 54% #From the above calculations the gap for evening slot(4pm to 10pm) is high(65%) #Demand And Supply plot for each time slot ggplot(Uber.Request,aes(x=supply,fill=supply))+geom_bar(col="black")+ theme_bw()+facet_wrap(~Request.TimeSlot)+geom_text(stat='count',aes(label=..count..),vjust=1,position = position_dodge(width = 1)) #or ggplot(Uber.Request,aes(x=supply,fill=supply))+theme_bw()+geom_bar(col="black")+geom_bar(aes(x=demand),col="black",fill="royalblue2")+geom_text(stat='count',aes(label=..count..),vjust=-1,position = position_dodge(width = 1))+facet_grid(~Uber.Request$Request.TimeSlot) #From the above graph the gap for evening slot(4pm to 10pm) is high #Finding Gap for each pickup point seperately #City addmargins(table(Uber.Request$supply[Uber.Request$Pickup.point=="City"]),FUN=demand) #proportions addmargins(prop.table(table(Uber.Request$supply[Uber.Request$Pickup.point=="City"])),FUN=demand) #gap for city pickup requests is 57% #city pickup requests demand and supply gap on diffrent time slots #morning slot addmargins(table(Uber.Request$supply[Uber.Request$Pickup.point=="City"& Uber.Request$Request.TimeSlot=="Morning Slot"]),FUN=demand) #proportions addmargins(prop.table(table(Uber.Request$supply[Uber.Request$Pickup.point=="City"& Uber.Request$Request.TimeSlot=="Morning Slot"])),FUN=demand) #gap for city pickup requests on morning slots is 71% #noon slot addmargins(table(Uber.Request$supply[Uber.Request$Pickup.point=="City"& Uber.Request$Request.TimeSlot=="Noon Slot"]),FUN=demand) #proportions addmargins(prop.table(table(Uber.Request$supply[Uber.Request$Pickup.point=="City"& Uber.Request$Request.TimeSlot=="Noon Slot"])),FUN=demand) #gap for city pickup requests on noon slots is 47 % #evening slot addmargins(table(Uber.Request$supply[Uber.Request$Pickup.point=="City"& Uber.Request$Request.TimeSlot=="Evening Slot"]),FUN=demand) #proportions addmargins(prop.table(table(Uber.Request$supply[Uber.Request$Pickup.point=="City"& Uber.Request$Request.TimeSlot=="Evening Slot"])),FUN=demand) #gap for city pickup requests on evening slots is 27% #night slot addmargins(table(Uber.Request$supply[Uber.Request$Pickup.point=="City"& Uber.Request$Request.TimeSlot=="Night Slot"]),FUN=demand) #proportions addmargins(prop.table(table(Uber.Request$supply[Uber.Request$Pickup.point=="City"& Uber.Request$Request.TimeSlot=="Night Slot"])),FUN=demand) #gap for city pickup requests on night slots is 55% #From the above calculations the gap for city pickup requests is high on morning slots i.e 71% #Airport addmargins(table(Uber.Request$supply[Uber.Request$Pickup.point=="Airport"]),FUN=demand) #proportions addmargins(prop.table(table(Uber.Request$supply[Uber.Request$Pickup.point=="Airport"])),FUN=demand) #gap for airport pickup requests is 59% #Airport pickup requests demand and supply gap on diffrent time slots #morning slot addmargins(table(Uber.Request$supply[Uber.Request$Pickup.point=="Airport"& Uber.Request$Request.TimeSlot=="Morning Slot"]),FUN=demand) #proportions addmargins(prop.table(table(Uber.Request$supply[Uber.Request$Pickup.point=="Airport"& Uber.Request$Request.TimeSlot=="Morning Slot"])),FUN=demand) #gap for airport pickup requests on morning slots is 16% #noon slot addmargins(table(Uber.Request$supply[Uber.Request$Pickup.point=="Airport"& Uber.Request$Request.TimeSlot=="Noon Slot"]),FUN=demand) #proportions addmargins(prop.table(table(Uber.Request$supply[Uber.Request$Pickup.point=="Airport"& Uber.Request$Request.TimeSlot=="Noon Slot"])),FUN=demand) #gap for airport pickup requests on noon slots is 30% #evening slot addmargins(table(Uber.Request$supply[Uber.Request$Pickup.point=="Airport"& Uber.Request$Request.TimeSlot=="Evening Slot"]),FUN=demand) #proportions addmargins(prop.table(table(Uber.Request$supply[Uber.Request$Pickup.point=="Airport"& Uber.Request$Request.TimeSlot=="Evening Slot"])),FUN=demand) #gap for airport pickup requests on evening slots is 77% #night slot addmargins(table(Uber.Request$supply[Uber.Request$Pickup.point=="Airport"& Uber.Request$Request.TimeSlot=="Night Slot"]),FUN=demand) #proportions addmargins(prop.table(table(Uber.Request$supply[Uber.Request$Pickup.point=="Airport"& Uber.Request$Request.TimeSlot=="Night Slot"])),FUN=demand) #gap for airport pickup requests on night slots is 54% #From the above calculations the gap for Airport pickup requests is high on evening slots i.e 77% #If we consider all time slots the gap for airport pickup request is high which is 59% than city pickup requests 54% #Plot showing demand and supply gap for different pickup requests on various timeslots ggplot(Uber.Request,aes(x=supply,fill=supply))+geom_bar(col="black")+theme_bw()+geom_bar(aes(x=demand),col="black",fill="royalblue3")+facet_grid(Pickup.point~Request.TimeSlot)+geom_text(stat='count',aes(label=..count..),vjust=-1,position = position_dodge(width = 1)) #In my opinion the reason for the supply demand gap is mainly due to drivers not being ready to take airport trips from city pickups #because of this there is a huge gap of demand and supply in the morning slot for city pickup requests.As drivers are not ready #to take airport trips from city there will be shortage of vehicles at airport.Hence customers who want to book uber will get no cars available as indication #so there is a high gap for airport pickup requests in the evening slot. #Possible suggestions to fill the supply demand gap #1) Increasing trip rates for airport pickups and drops.Which may make drivers interested to take up the trips with out cancelling . #2)Making drivers work on shift basis,where one shift starts in the morning at city and the other start at the airport during evening and so on #3)A fixed number of cars should be specially assigned for airport trips and they should accept only airport pickups and drops #4)Keeping drivers updated with the flight schedule details on a reguler basis,will also help them plan their work productively
/Uber Assignment new.R
no_license
warthineha/DataScienceProjects
R
false
false
19,083
r
#### UBER ASSIGNMENT #### #Loading the required packages library(lubridate) library(stringr) library(ggplot2) library(dplyr) #Getting uber request data into R Uber.Request<-read.csv("Uber Request Data.csv",stringsAsFactors = FALSE) #Observing the structure of dataframe Uber.Requests str(Uber.Request) #or you can also have a glimpse of data frame using Uber.Requests glimpse(Uber.Request) ####Handling data quality issues/Data Cleaning#### #checking for any duplicate rows cat ('there are',(nrow(Uber.Request)-nrow(Uber.Request %>% unique)),'duplicate rows') #there are 0 duplicate rows # checking for any NA values in all columns, one after other # checking for any NA values in column Request.id anyNA(Uber.Request$Request.id) # no NA's # checking for any NA values in column anyNA(Uber.Request$Driver.id) # NA's present(2650) # checking for any NA values in column anyNA(Uber.Request$Pickup.point) # no NA's # checking for any NA values in column anyNA(Uber.Request$Status) # no NA's # checking for any NA values in column anyNA(Uber.Request$Request.timestamp) # no NA's # checking for any NA values in column anyNA(Uber.Request$Drop.timestamp) # NA's present(3914) # It looks appropriate to leave the NA's untouched as they # look valid in the columns Driver.id and Drop.timestamp the NA's # in the respective columns are present when there is a value # "no cars available" in column status #checking for any spelling mistakes in categorical columns #In column Pickup.point unique(Uber.Request$Pickup.point) # there are only two unique values "Airport" "City" in column Pickup.point.There are no spelling mistakes #In column Status unique(Uber.Request$Status) #there are only three unique values Trip Completed,Cancelled,No Cars Available in column Status.There are no spelling mistakes ###########DATA PREPERATION#################### ####Handling date and time columns Request.timestamp and Drop.timestamp which are read as type character#### ##Request.timestamp## #Parsing Request.timestamp and storing it in the column Request_Date Uber.Request$Request_Date<- lubridate::parse_date_time(Uber.Request$Request.timestamp,orders = c("d/m/Y H:M","d-m-Y H-M-S")) # checking if there are any NA's coerced because of invalid data values (Uber.Request$Request.timestamp %>% is.na %>% sum) == (Uber.Request$Request_Date %>% is.na %>% sum) #It gives TRUE means NA's are not coerced.This also means there are no invalid data values in Request.timestamp #spliting date from Request_Date and storing it in column Request.Date Uber.Request$Request.Date<- as.Date(Uber.Request$Request_Date) #Extracting Day of the week from Request.Date and storing it in Request.Day column Uber.Request$Request.Day<- weekdays(Uber.Request$Request_Date) #spliting date form Request_Date and storing it in column Request.Time Uber.Request$Request.Time<-format(Uber.Request$Request_Date,"%H:%M:%S") #Extracting hours mins and sec from column Request.timestamp Uber.Request$Request.hour<-lubridate::hour(Uber.Request$Request_Date) Uber.Request$Request.minute<-lubridate::minute(Uber.Request$Request_Date) Uber.Request$Request.second<-lubridate::second(Uber.Request$Request_Date) #grouping the data into different time slots morning,noon,evening and night #based on values in request.hour #defineing a timeslot function timeslot<-function(request.hour){ if(request.hour>=4 & request.hour<10){ return("Morning Slot") }else if(request.hour>=10 & request.hour<16){ return("Noon Slot") }else if(request.hour>=16 & request.hour<22){ return("Evening Slot") }else if(request.hour>=22 | request.hour<4){ return("Night Slot") }else{ return(NA) } } #creating timeslot column using timeslot function Uber.Request$Request.TimeSlot<-sapply(Uber.Request$Request.hour,timeslot) %>% unlist #checking for any coerced NA values in column Request.TimeSlot anyNA(Uber.Request$Request.TimeSlot)#FALSE no NA's #Dropping request_date column Uber.Request$Request.timestamp<-NULL #####Drop.timestamp##### #Parsing Drop.timestamp and storing it in the column Drop_Date Uber.Request$Drop_Date<- parse_date_time(Uber.Request$Drop.timestamp,orders = c("d/m/Y H:M","d-m-Y H-M-S")) # checking if there are any NA's coerced because of invalid data values (Uber.Request$Drop.timestamp %>% is.na %>% sum) == (Uber.Request$Drop_Date%>% is.na %>% sum) #It gives TRUE means NA's are not coerced. This also means there are no invalid data values in Drop.timestamp #spliting date form Drop_Date and storing it in column Drop.Date Uber.Request$Drop.Date<- as.Date(Uber.Request$Drop_Date) #spliting date form Drop_Date and storing it in column Drop.Time Uber.Request$Drop.Time<-format(Uber.Request$Drop_Date,"%T") #Extracting hours mins and sec from column Drop.timestamp Uber.Request$Drop.hour<-lubridate::hour(Uber.Request$Drop_Date) Uber.Request$Drop.minute<-lubridate::minute(Uber.Request$Drop_Date) Uber.Request$Drop.second<-lubridate::second(Uber.Request$Drop_Date) #Dropping request_date column Uber.Request$Drop.timestamp<-NULL #checking for the time duration of data present data.interval<-as.interval(min(Uber.Request$Request_Date),max(Uber.Request$Request_Date)) #checking the duration of the interval as.duration(data.interval) #Total 5 Days of data is present ######DATA ANALYSIS##### # Since Request.id and Driver.id are id or unique values there isn't much sense analysing them #Defining the Pickup.point variable as factor and ordering it's levels in a particuler order Uber.Request$Pickup.point<-factor(Uber.Request$Pickup.point,levels=c("City","Airport")) #Analysing variable Pickup.point by plotting a bar chart on it (and looking for some insights) ggplot(Uber.Request,aes(Pickup.point,fill=Pickup.point))+geom_bar(col="black")+annotate("text",x=c("Airport","City"),y=c(3450,3700),label=c("48%","51%"))+theme_bw() #The above plot shows that ,there isn't much difference between Airport and city pickup requests #Analysing variable Status by plotting a bar chart on it (and looking for some insights) ggplot(Uber.Request,aes(Status,fill=Status))+geom_bar(col="black")+annotate("text",x=c("Cancelled","No Cars Available","Trip Completed"),y=c(1400,2800,2950),label=c("19%","39%","41%"))+theme_bw() #The above plot clearly depicts that only 41% of the requests from city and #airport gets completed and the remaining 59% trips either get cancelled or #there is no car availability ########################################################################## #The proportions of above plot can be obtained from the following code prop.table(table(Uber.Request$Pickup.point)) prop.table(table(Uber.Request$Status)) ########################################################################## #segemnting pickup.point over status ggplot(Uber.Request,aes(x=Pickup.point,fill=Status))+geom_bar(position = "dodge",col="black")+geom_text(stat='count',aes(label=..count..),vjust=-1,position = position_dodge(width = 1))+theme_bw() #The above plot shows that for most of the Airport pickup requests there are #no cars available and most requests that get cancelled are city pickup requests #Analysing variable Request.hour by plotting a bar chart on it (and looking for #some insights) ggplot(Uber.Request,aes(Request.hour))+geom_bar(fill="royalblue1",col="black")+annotate("text",x=c(7.2,19),y=c(500,550),label=("High Request Rate"))+theme_bw() #The above plot clearly depicts that there are high request rates from 5AM TO 10AM #and 5pm to 10 pm #To get a better understanding of requests raised at different hours of the day #lets plot a chart on variable timeslot(which contains hours grouped into #different timeslots) #Defining the timeslot variable as factor and ordering it's levels in a particuler order Uber.Request$Request.TimeSlot<-factor(Uber.Request$Request.TimeSlot,levels=c("Morning Slot","Noon Slot","Evening Slot","Night Slot")) #plotting a bargraph on time slots ggplot(Uber.Request,aes(x=Request.TimeSlot,fill=Request.TimeSlot))+xlab("TimeSlot")+geom_bar(col="black")+annotate("text",x=c("Evening Slot","Morning Slot","Night Slot","Noon Slot"),y=c(2590,2400,975,1150),label=c("37%","34%","13%","16%"))+theme_bw() #the proportions can be obtained from the following code prop.table(table(Uber.Request$Request.TimeSlot)) #From the above plot it is clear that most of the requests are raised in #morning(34%) and evening(37%) slots #segmenting the timeslot variable by pickup point may give some more information ggplot(Uber.Request,aes(x=Request.TimeSlot,fill=Pickup.point))+xlab("Timeslot")+geom_bar(position = "dodge",col="black")+ geom_text(stat='count',aes(label=..count..),vjust=-1,position = position_dodge(width = 1))+theme_bw() #During morning slot city pickup requests are high #and during evening slot airport pickup requests are high #segmenting the timeslot variable by Status may give some information ggplot(Uber.Request,aes(x=Request.TimeSlot,fill=Status))+xlab("Timeslot")+geom_bar(position = "dodge",col="black")+ geom_text(stat='count',aes(label=..count..),vjust=-1,position = position_dodge(width = 1))+theme_bw() #segmenting the timeslot variable by both Status and pickup point may give some more information ggplot(Uber.Request,aes(x=Request.TimeSlot,fill=Status))+xlab("Timeslot")+geom_bar(col="black")+theme_bw()+facet_grid(Pickup.point~Status)+stat_count(aes(label = ..count..), geom = "text",vjust=-0.5,size=2)+theme(axis.text.x = element_text(face="bold", color = "#993333",size = 10,angle=90))+theme_bw() #From the above plot it is clear that most city requests get cancelled in the #morningslot(during which there is high city request rate) and for most of the #airport requests during the evening slot(during which there is high airport request rate) #there are no cars available #From the above plots it can be assumed that although there is not much difference city requests and airport requests , #city requests are problametic requests because most of city requests gets cancelled by drivers. #Most Uber drivers are not ready to drive to airport because they may have to wait long before they get a trip back to city #This is the same reason for most airport requests cars are not available ###############SUPPLY AND DEMAND GAP CALCULATION####################### demandd<-function(status){ if (status=="Cancelled"|status=="No Cars Available"|status=="Trip Completed"){ return("demand") }else{ return(NA) } } supply<-function(status){ if (status=="Cancelled"|status=="No Cars Available"){ return( "gap") }else{ return("supply") } } #creating supply column using supply function Uber.Request$supply<-sapply(Uber.Request$Status,supply) %>% unlist #checking for NA values in Uber.Request$supply anyNA(Uber.Request$supply) #No NA's #creating demand column using demand function Uber.Request$demand<-sapply(Uber.Request$Status,demandd) %>% unlist #checking for NA values in Uber.Request$demand anyNA(Uber.Request$demand) #No NA's #Finding supply and demand gap demand<-sum addmargins(table(Uber.Request$supply),FUN = demand) #so overall gap is 2831,it would be better if we look at this values in propotions addmargins(prop.table(table(Uber.Request$supply)),FUN = demand) # gap is 58% of demand #Demand And Supply plot ggplot(Uber.Request,aes(x=supply,fill=supply))+geom_bar(col="black")+geom_bar(aes(x=demand),col="black",fill="royalblue2")+geom_text(stat='count',aes(label=..count..),vjust=-1,position = position_dodge(width = 1))+theme_bw()+annotate("text",x="demand",y=6970,label="6745") #Finding supply and demand gap for each time slot seperately #morning slot addmargins(table(Uber.Request$supply[Uber.Request$Request.TimeSlot=="Morning Slot"]),FUN = demand) #proportions addmargins(prop.table(table(Uber.Request$supply[Uber.Request$Request.TimeSlot=="Morning Slot"])),FUN=demand) #For morning slot the gap is about 59% #noon slot addmargins(table(Uber.Request$supply[Uber.Request$Request.TimeSlot=="Noon Slot"]),FUN=demand) #proportions addmargins(prop.table(table(Uber.Request$supply[Uber.Request$Request.TimeSlot=="Noon Slot"])),FUN=demand) #For noon slot the gap is about 40% #evening slot addmargins(table(Uber.Request$supply[Uber.Request$Request.TimeSlot=="Evening Slot"]),FUN=demand) #proportion addmargins(prop.table(table(Uber.Request$supply[Uber.Request$Request.TimeSlot=="Evening Slot"])),FUN=demand) #For evening slot the gap is about 65% #night slot addmargins(table(Uber.Request$supply[Uber.Request$Request.TimeSlot=="Night Slot"]),FUN=demand) #proportion addmargins(prop.table(table(Uber.Request$supply[Uber.Request$Request.TimeSlot=="Night Slot"])),FUN = demand) #For night slot the gap is about 54% #From the above calculations the gap for evening slot(4pm to 10pm) is high(65%) #Demand And Supply plot for each time slot ggplot(Uber.Request,aes(x=supply,fill=supply))+geom_bar(col="black")+ theme_bw()+facet_wrap(~Request.TimeSlot)+geom_text(stat='count',aes(label=..count..),vjust=1,position = position_dodge(width = 1)) #or ggplot(Uber.Request,aes(x=supply,fill=supply))+theme_bw()+geom_bar(col="black")+geom_bar(aes(x=demand),col="black",fill="royalblue2")+geom_text(stat='count',aes(label=..count..),vjust=-1,position = position_dodge(width = 1))+facet_grid(~Uber.Request$Request.TimeSlot) #From the above graph the gap for evening slot(4pm to 10pm) is high #Finding Gap for each pickup point seperately #City addmargins(table(Uber.Request$supply[Uber.Request$Pickup.point=="City"]),FUN=demand) #proportions addmargins(prop.table(table(Uber.Request$supply[Uber.Request$Pickup.point=="City"])),FUN=demand) #gap for city pickup requests is 57% #city pickup requests demand and supply gap on diffrent time slots #morning slot addmargins(table(Uber.Request$supply[Uber.Request$Pickup.point=="City"& Uber.Request$Request.TimeSlot=="Morning Slot"]),FUN=demand) #proportions addmargins(prop.table(table(Uber.Request$supply[Uber.Request$Pickup.point=="City"& Uber.Request$Request.TimeSlot=="Morning Slot"])),FUN=demand) #gap for city pickup requests on morning slots is 71% #noon slot addmargins(table(Uber.Request$supply[Uber.Request$Pickup.point=="City"& Uber.Request$Request.TimeSlot=="Noon Slot"]),FUN=demand) #proportions addmargins(prop.table(table(Uber.Request$supply[Uber.Request$Pickup.point=="City"& Uber.Request$Request.TimeSlot=="Noon Slot"])),FUN=demand) #gap for city pickup requests on noon slots is 47 % #evening slot addmargins(table(Uber.Request$supply[Uber.Request$Pickup.point=="City"& Uber.Request$Request.TimeSlot=="Evening Slot"]),FUN=demand) #proportions addmargins(prop.table(table(Uber.Request$supply[Uber.Request$Pickup.point=="City"& Uber.Request$Request.TimeSlot=="Evening Slot"])),FUN=demand) #gap for city pickup requests on evening slots is 27% #night slot addmargins(table(Uber.Request$supply[Uber.Request$Pickup.point=="City"& Uber.Request$Request.TimeSlot=="Night Slot"]),FUN=demand) #proportions addmargins(prop.table(table(Uber.Request$supply[Uber.Request$Pickup.point=="City"& Uber.Request$Request.TimeSlot=="Night Slot"])),FUN=demand) #gap for city pickup requests on night slots is 55% #From the above calculations the gap for city pickup requests is high on morning slots i.e 71% #Airport addmargins(table(Uber.Request$supply[Uber.Request$Pickup.point=="Airport"]),FUN=demand) #proportions addmargins(prop.table(table(Uber.Request$supply[Uber.Request$Pickup.point=="Airport"])),FUN=demand) #gap for airport pickup requests is 59% #Airport pickup requests demand and supply gap on diffrent time slots #morning slot addmargins(table(Uber.Request$supply[Uber.Request$Pickup.point=="Airport"& Uber.Request$Request.TimeSlot=="Morning Slot"]),FUN=demand) #proportions addmargins(prop.table(table(Uber.Request$supply[Uber.Request$Pickup.point=="Airport"& Uber.Request$Request.TimeSlot=="Morning Slot"])),FUN=demand) #gap for airport pickup requests on morning slots is 16% #noon slot addmargins(table(Uber.Request$supply[Uber.Request$Pickup.point=="Airport"& Uber.Request$Request.TimeSlot=="Noon Slot"]),FUN=demand) #proportions addmargins(prop.table(table(Uber.Request$supply[Uber.Request$Pickup.point=="Airport"& Uber.Request$Request.TimeSlot=="Noon Slot"])),FUN=demand) #gap for airport pickup requests on noon slots is 30% #evening slot addmargins(table(Uber.Request$supply[Uber.Request$Pickup.point=="Airport"& Uber.Request$Request.TimeSlot=="Evening Slot"]),FUN=demand) #proportions addmargins(prop.table(table(Uber.Request$supply[Uber.Request$Pickup.point=="Airport"& Uber.Request$Request.TimeSlot=="Evening Slot"])),FUN=demand) #gap for airport pickup requests on evening slots is 77% #night slot addmargins(table(Uber.Request$supply[Uber.Request$Pickup.point=="Airport"& Uber.Request$Request.TimeSlot=="Night Slot"]),FUN=demand) #proportions addmargins(prop.table(table(Uber.Request$supply[Uber.Request$Pickup.point=="Airport"& Uber.Request$Request.TimeSlot=="Night Slot"])),FUN=demand) #gap for airport pickup requests on night slots is 54% #From the above calculations the gap for Airport pickup requests is high on evening slots i.e 77% #If we consider all time slots the gap for airport pickup request is high which is 59% than city pickup requests 54% #Plot showing demand and supply gap for different pickup requests on various timeslots ggplot(Uber.Request,aes(x=supply,fill=supply))+geom_bar(col="black")+theme_bw()+geom_bar(aes(x=demand),col="black",fill="royalblue3")+facet_grid(Pickup.point~Request.TimeSlot)+geom_text(stat='count',aes(label=..count..),vjust=-1,position = position_dodge(width = 1)) #In my opinion the reason for the supply demand gap is mainly due to drivers not being ready to take airport trips from city pickups #because of this there is a huge gap of demand and supply in the morning slot for city pickup requests.As drivers are not ready #to take airport trips from city there will be shortage of vehicles at airport.Hence customers who want to book uber will get no cars available as indication #so there is a high gap for airport pickup requests in the evening slot. #Possible suggestions to fill the supply demand gap #1) Increasing trip rates for airport pickups and drops.Which may make drivers interested to take up the trips with out cancelling . #2)Making drivers work on shift basis,where one shift starts in the morning at city and the other start at the airport during evening and so on #3)A fixed number of cars should be specially assigned for airport trips and they should accept only airport pickups and drops #4)Keeping drivers updated with the flight schedule details on a reguler basis,will also help them plan their work productively
#The file gene_expression.tsv downloaded from the github repository. download.file("https://raw.githubusercontent.com/markziemann/SLE712_files/master/bioinfo_asst3_part1_files/gene_expression.tsv", destfile = "try.tsv") #Read the file with gene accession numbers as row numbers a <- read.table("try.tsv", header = TRUE, row.names = 1) #Displaying the values of the first six genes head(a) #Making a new column which contains the mean of other columns a$Mean <- rowMeans(a) #Displaying the values of the first six genes head(a) #Listing the 10 genes with highest mean expression list <- a[order(-a$Mean),] head(list,10) #Number of genes with a mean>10 nrow( subset(a, a$Mean<10)) #histogram plot of the means a$Mean <- as.matrix(a) range(a$Mean) hist(a$Mean) hist(as.matrix(a$Mean),10, xlab = "Mean", breaks = 50, col = "blue", xlim = c(0,75000)) #download file download.file("https://raw.githubusercontent.com/markziemann/SLE712_files/master/bioinfo_asst3_part1_files/growth_data.csv", destfile = "try2.csv") y <- read.table("try2.csv", header = TRUE, sep = ",",stringsAsFactors = FALSE) colnames(y) #subset y[1:50,] northeast <- y[1:50, ] #calculate mean and sd mean(northeast$Circumf_2004_cm) sd(northeast$Circumf_2004_cm) mean(northeast$Circumf_2019_cm) sd(northeast$Circumf_2019_cm) #subset y[51:100,] southwest <- y[51:100, ] #calculate mean and sd mean(southwest$Circumf_2004_cm) sd(southwest$Circumf_2004_cm) mean(southwest$Circumf_2019_cm) sd(southwest$Circumf_2019_cm) #boxplot boxplot(southwest$Circumf_2004_cm,southwest$Circumf_2019_cm,northeast$Circumf_2004_cm,northeast$Circumf_2019_cm, names = c("SW2004","SW2019","NE2004","NE2019"),ylab="Cirumference (cm)", main="Growth at Two Plantation Sites") #mean growth for 10 years GrowthSW <- (southwest$Circumf_2019_cm-southwest$Circumf_2009_cm) GrowthNE <- (northeast$Circumf_2019_cm-northeast$Circumf_2009_cm) mean(GrowthSW) mean(GrowthNE) head(y) #t.test res <- t.test(GrowthSW,GrowthNE, var.equal = FALSE) res #part 2 #libraries that are required library("seqinr") library("rBLAST") library("R.utils") #Download the E.coli CDS sequence from the Ensembl FTP page download.file("ftp://ftp.ensemblgenomes.org/pub/bacteria/release-42/fasta/bacteria_0_collection/escherichia_coli_str_k_12_substr_mg1655/cds/Escherichia_coli_str_k_12_substr_mg1655.ASM584v2.cds.all.fa.gz", destfile = "ecoli.fa.gz") # uncompress the file gunzip("ecoli.fa.gz") # create the blast DB makeblastdb("ecoli.fa",dbtype="nucl", "-parse_seqids") #Download the sample file download.file("https://raw.githubusercontent.com/markziemann/SLE712_files/master/bioinfo_asst3_part2_files/sample.fa", destfile = "sample.fa") #Read the sample file into R d <- read.fasta("sample.fa") mygene <- d[[3]] mygene #Length of sequence in bp str(mygene) length(mygene) #Proportion of GC content seqinr::GC(mygene) #function to create blast download.file("https://raw.githubusercontent.com/markziemann/SLE712_files/master/bioinfo_asst3_part2_files/mutblast_functions.R", destfile = "mutblast.R") source("mutblast.R") #Blast search for E. coli genes that matches best res <- myblastn_tab(myseq = mygene, db = "ecoli.fa") #Blast results res View(res) str(res) head(res) #making mutations to mygene mygene_mutation <- mutator(mygene,20) res <- myblastn_tab(myseq = mygene_mutation, db = "ecoli.fa") res #first need to write a blast index write.fasta(mygene,names="mygene",file.out = "mygene.fa") makeblastdb(file = "mygene.fa",dbtype = "nucl") # test with 100 mismatches mygene_mutation <- mutator(myseq=mygene,100) res <- myblastn_tab(myseq = mygene_mutation, db = "mygene.fa") res cointoss <- function(mygene_mutation) { sample(c(0,1),1,replace = TRUE) } mean(replicate(100,cointoss(mygene_mutation))) #test with 150 mismatches mygene_mutation <- mutator(myseq=mygene,150) res <- myblastn_tab(myseq = mygene_mutation, db = "mygene.fa") res cointoss <- function(mygene_mutation) { sample(c(0,1),1,replace = TRUE) } mean(replicate(100,cointoss(mygene_mutation))) #test with 200 mismatches mygene_mutation <- mutator(myseq=mygene,200) res <- myblastn_tab(myseq = mygene_mutation, db = "mygene.fa") res cointoss <- function(mygene_mutation) { sample(c(0,1),1,replace = TRUE) } mean(replicate(100,cointoss(mygene_mutation))) #test with 250 mismatches mygene_mutation <- mutator(myseq=mygene,250) res <- myblastn_tab(myseq = mygene_mutation, db = "mygene.fa") res cointoss <- function(mygene_mutation) { sample(c(0,1),1,replace = TRUE) } mean(replicate(100,cointoss(mygene_mutation))) #test with 300 mismatches mygene_mutation <- mutator(myseq=mygene,450) res <- myblastn_tab(myseq = mygene_mutation, db = "mygene.fa") res cointoss <- function(mygene_mutation) { sample(c(0,1),1,replace = TRUE) } mean(replicate(100,cointoss(mygene_mutation))) plot(res$bitscore)
/Assignment.R
no_license
nvdesilva/Assignment-Three
R
false
false
4,914
r
#The file gene_expression.tsv downloaded from the github repository. download.file("https://raw.githubusercontent.com/markziemann/SLE712_files/master/bioinfo_asst3_part1_files/gene_expression.tsv", destfile = "try.tsv") #Read the file with gene accession numbers as row numbers a <- read.table("try.tsv", header = TRUE, row.names = 1) #Displaying the values of the first six genes head(a) #Making a new column which contains the mean of other columns a$Mean <- rowMeans(a) #Displaying the values of the first six genes head(a) #Listing the 10 genes with highest mean expression list <- a[order(-a$Mean),] head(list,10) #Number of genes with a mean>10 nrow( subset(a, a$Mean<10)) #histogram plot of the means a$Mean <- as.matrix(a) range(a$Mean) hist(a$Mean) hist(as.matrix(a$Mean),10, xlab = "Mean", breaks = 50, col = "blue", xlim = c(0,75000)) #download file download.file("https://raw.githubusercontent.com/markziemann/SLE712_files/master/bioinfo_asst3_part1_files/growth_data.csv", destfile = "try2.csv") y <- read.table("try2.csv", header = TRUE, sep = ",",stringsAsFactors = FALSE) colnames(y) #subset y[1:50,] northeast <- y[1:50, ] #calculate mean and sd mean(northeast$Circumf_2004_cm) sd(northeast$Circumf_2004_cm) mean(northeast$Circumf_2019_cm) sd(northeast$Circumf_2019_cm) #subset y[51:100,] southwest <- y[51:100, ] #calculate mean and sd mean(southwest$Circumf_2004_cm) sd(southwest$Circumf_2004_cm) mean(southwest$Circumf_2019_cm) sd(southwest$Circumf_2019_cm) #boxplot boxplot(southwest$Circumf_2004_cm,southwest$Circumf_2019_cm,northeast$Circumf_2004_cm,northeast$Circumf_2019_cm, names = c("SW2004","SW2019","NE2004","NE2019"),ylab="Cirumference (cm)", main="Growth at Two Plantation Sites") #mean growth for 10 years GrowthSW <- (southwest$Circumf_2019_cm-southwest$Circumf_2009_cm) GrowthNE <- (northeast$Circumf_2019_cm-northeast$Circumf_2009_cm) mean(GrowthSW) mean(GrowthNE) head(y) #t.test res <- t.test(GrowthSW,GrowthNE, var.equal = FALSE) res #part 2 #libraries that are required library("seqinr") library("rBLAST") library("R.utils") #Download the E.coli CDS sequence from the Ensembl FTP page download.file("ftp://ftp.ensemblgenomes.org/pub/bacteria/release-42/fasta/bacteria_0_collection/escherichia_coli_str_k_12_substr_mg1655/cds/Escherichia_coli_str_k_12_substr_mg1655.ASM584v2.cds.all.fa.gz", destfile = "ecoli.fa.gz") # uncompress the file gunzip("ecoli.fa.gz") # create the blast DB makeblastdb("ecoli.fa",dbtype="nucl", "-parse_seqids") #Download the sample file download.file("https://raw.githubusercontent.com/markziemann/SLE712_files/master/bioinfo_asst3_part2_files/sample.fa", destfile = "sample.fa") #Read the sample file into R d <- read.fasta("sample.fa") mygene <- d[[3]] mygene #Length of sequence in bp str(mygene) length(mygene) #Proportion of GC content seqinr::GC(mygene) #function to create blast download.file("https://raw.githubusercontent.com/markziemann/SLE712_files/master/bioinfo_asst3_part2_files/mutblast_functions.R", destfile = "mutblast.R") source("mutblast.R") #Blast search for E. coli genes that matches best res <- myblastn_tab(myseq = mygene, db = "ecoli.fa") #Blast results res View(res) str(res) head(res) #making mutations to mygene mygene_mutation <- mutator(mygene,20) res <- myblastn_tab(myseq = mygene_mutation, db = "ecoli.fa") res #first need to write a blast index write.fasta(mygene,names="mygene",file.out = "mygene.fa") makeblastdb(file = "mygene.fa",dbtype = "nucl") # test with 100 mismatches mygene_mutation <- mutator(myseq=mygene,100) res <- myblastn_tab(myseq = mygene_mutation, db = "mygene.fa") res cointoss <- function(mygene_mutation) { sample(c(0,1),1,replace = TRUE) } mean(replicate(100,cointoss(mygene_mutation))) #test with 150 mismatches mygene_mutation <- mutator(myseq=mygene,150) res <- myblastn_tab(myseq = mygene_mutation, db = "mygene.fa") res cointoss <- function(mygene_mutation) { sample(c(0,1),1,replace = TRUE) } mean(replicate(100,cointoss(mygene_mutation))) #test with 200 mismatches mygene_mutation <- mutator(myseq=mygene,200) res <- myblastn_tab(myseq = mygene_mutation, db = "mygene.fa") res cointoss <- function(mygene_mutation) { sample(c(0,1),1,replace = TRUE) } mean(replicate(100,cointoss(mygene_mutation))) #test with 250 mismatches mygene_mutation <- mutator(myseq=mygene,250) res <- myblastn_tab(myseq = mygene_mutation, db = "mygene.fa") res cointoss <- function(mygene_mutation) { sample(c(0,1),1,replace = TRUE) } mean(replicate(100,cointoss(mygene_mutation))) #test with 300 mismatches mygene_mutation <- mutator(myseq=mygene,450) res <- myblastn_tab(myseq = mygene_mutation, db = "mygene.fa") res cointoss <- function(mygene_mutation) { sample(c(0,1),1,replace = TRUE) } mean(replicate(100,cointoss(mygene_mutation))) plot(res$bitscore)
par(mfrow=c(2,2), mar=c(4,4,2,1)) with(epc, { plot(Global_active_power~dateTime, type="l", ylab="Global Active Power (kilowatts)") plot(Voltage~dateTime, type="l", ylab="Voltage (volt)", xlab="") plot(Sub_metering_1~dateTime, type="l", ylab="Global Active Power (kilowatts)") lines(Sub_metering_2~dateTime,col='Red') lines(Sub_metering_3~dateTime,col='Blue') legend("topright", col=c("black", "red", "blue"), lty=1, lwd=2, legend=c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3")) plot(Global_reactive_power~dateTime, type="l", ylab="Global Rective Power (kilowatts)") }) dev.copy(png, file="plot4.png", height=480, width=480) dev.off()
/plot4.R
no_license
anupkumarsahu/ExData_Plotting1
R
false
false
700
r
par(mfrow=c(2,2), mar=c(4,4,2,1)) with(epc, { plot(Global_active_power~dateTime, type="l", ylab="Global Active Power (kilowatts)") plot(Voltage~dateTime, type="l", ylab="Voltage (volt)", xlab="") plot(Sub_metering_1~dateTime, type="l", ylab="Global Active Power (kilowatts)") lines(Sub_metering_2~dateTime,col='Red') lines(Sub_metering_3~dateTime,col='Blue') legend("topright", col=c("black", "red", "blue"), lty=1, lwd=2, legend=c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3")) plot(Global_reactive_power~dateTime, type="l", ylab="Global Rective Power (kilowatts)") }) dev.copy(png, file="plot4.png", height=480, width=480) dev.off()
# Unit tests test_that("calckl calculates KL correctly", { temp <- 25 sal <- 35 atemp <- 25 wspd <- 5 bp <- 1013 height <- 10 expected_KL <- 1.177 result <- round(calckl(temp, sal, atemp, wspd, bp, height), 3) # Check if the result is equal to the expected value expect_equal(result, expected_KL) })
/tests/testthat/test-calckl.R
no_license
cran/SWMPr
R
false
false
341
r
# Unit tests test_that("calckl calculates KL correctly", { temp <- 25 sal <- 35 atemp <- 25 wspd <- 5 bp <- 1013 height <- 10 expected_KL <- 1.177 result <- round(calckl(temp, sal, atemp, wspd, bp, height), 3) # Check if the result is equal to the expected value expect_equal(result, expected_KL) })
function(input, output, session) { # Define a reactive expression for the document term matrix terms <- reactive({ # Change when the "update" button is pressed... input$update # ...but not for anything else isolate({ withProgress({ setProgress(message = "Processing corpus...") getTermMatrix(input$city) }) }) }) terms2 <- reactive({ # Change when the "update" button is pressed... input$update # ...but not for anything else isolate({ withProgress({ setProgress(message = "Processing Emotion") getbanana(input$city) }) }) }) terms3 <- reactive({ # Change when the "update" button is pressed... input$update # ...but not for anything else isolate({ withProgress({ setProgress(message = "Calculating a score!") getGrape(input$city) }) }) }) terms4 <- reactive({ # Change when the "update" button is pressed... input$update # ...but not for anything else isolate({ withProgress({ setProgress(message = "Show me a histogram") getPickle(input$city) }) }) }) output$plot1 <- renderPlot({ v <- terms() wordcloud(names(v), v, scale=c(5,0.5), min.freq = input$freq, max.words=input$max, colors=brewer.pal(8, "Dark2")) }) output$plot2 <- renderPlot({ b <- terms2() comparison.cloud(b, random.order=FALSE, colors = c("#00B2FF", "red", "#FF0099", "#6600CC", "green", "orange", "blue", "brown"), title.size=2, max.words=input$max, scale=c(5, 0.5),rot.per=0.4) }) output$plot3 <- renderText({ value = terms3() value = round(value,digits = 2) if (value > 1) { print(paste0('Everyone is loving this weather! Score: ', value)) } else if (value < -1){ print(paste0('Weather potentially unsafe! Score: ', value)) } else if (value > 0 & value < .5){ print(paste0('People are not real happy about the weather. Score: ', value)) } else if (value < 0 & value > -1){ print(paste0('The weather is bad, be cautious. Score: ', value)) } else if (value > 0.5 & value < 1){ print(paste0('Nice weather today! Score: ', value)) } else { print("Something has happened to earth :(") } }) output$plot4 <- renderPlot({ df = terms4() ggplot(df, aes(x=syuzhet_emotion.df)) + geom_histogram(aes(y=..density..), colour="black", fill="white", bins = 15)+ geom_density(alpha=.2, fill="#64c651") }) }
/server.R
no_license
JeremyWhittier/MIS510
R
false
false
2,721
r
function(input, output, session) { # Define a reactive expression for the document term matrix terms <- reactive({ # Change when the "update" button is pressed... input$update # ...but not for anything else isolate({ withProgress({ setProgress(message = "Processing corpus...") getTermMatrix(input$city) }) }) }) terms2 <- reactive({ # Change when the "update" button is pressed... input$update # ...but not for anything else isolate({ withProgress({ setProgress(message = "Processing Emotion") getbanana(input$city) }) }) }) terms3 <- reactive({ # Change when the "update" button is pressed... input$update # ...but not for anything else isolate({ withProgress({ setProgress(message = "Calculating a score!") getGrape(input$city) }) }) }) terms4 <- reactive({ # Change when the "update" button is pressed... input$update # ...but not for anything else isolate({ withProgress({ setProgress(message = "Show me a histogram") getPickle(input$city) }) }) }) output$plot1 <- renderPlot({ v <- terms() wordcloud(names(v), v, scale=c(5,0.5), min.freq = input$freq, max.words=input$max, colors=brewer.pal(8, "Dark2")) }) output$plot2 <- renderPlot({ b <- terms2() comparison.cloud(b, random.order=FALSE, colors = c("#00B2FF", "red", "#FF0099", "#6600CC", "green", "orange", "blue", "brown"), title.size=2, max.words=input$max, scale=c(5, 0.5),rot.per=0.4) }) output$plot3 <- renderText({ value = terms3() value = round(value,digits = 2) if (value > 1) { print(paste0('Everyone is loving this weather! Score: ', value)) } else if (value < -1){ print(paste0('Weather potentially unsafe! Score: ', value)) } else if (value > 0 & value < .5){ print(paste0('People are not real happy about the weather. Score: ', value)) } else if (value < 0 & value > -1){ print(paste0('The weather is bad, be cautious. Score: ', value)) } else if (value > 0.5 & value < 1){ print(paste0('Nice weather today! Score: ', value)) } else { print("Something has happened to earth :(") } }) output$plot4 <- renderPlot({ df = terms4() ggplot(df, aes(x=syuzhet_emotion.df)) + geom_histogram(aes(y=..density..), colour="black", fill="white", bins = 15)+ geom_density(alpha=.2, fill="#64c651") }) }
source("../../../src/config") library(cowplot) load("tft-glasso.RData") ## Read files theme_set(theme_cowplot(font_size=12)) # reduce default font size plot.thyroid <- ggplot(plot.thyroid, aes(x = recall, y = precision, colour = type)) + geom_point(size = 0.3) + # theme(text = element_text(size=7))+ xlab("Recall") + ylab("Precision")+ggtitle("Thyroid") plot.muscle <- ggplot(plot.muscle, aes(x = recall, y = precision, colour = type)) + geom_point(size = 0.3) + # theme(text = element_text(size=7)) + xlab("Recall") + ylab("Precision")+ggtitle("Muscle - Skeletal") plot.lung <- ggplot(plot.lung, aes(x = recall, y = precision, colour = type)) + geom_point(size = 0.3) + theme(legend.title=element_blank())+ xlab("Recall") + ylab("Precision")+ggtitle("Lung") plot.blood <- ggplot(plot.blood, aes(x = recall, y = precision, colour = type)) + geom_point(size = 0.3) + # theme(text = element_text(size=7))+ xlab("Recall") + ylab("Precision")+ggtitle("Whole Blood") plot.sub <- ggplot(plot.sub, aes(x = recall, y = precision, colour = type)) + geom_point(size = 0.3) + # theme(text = element_text(size=7))+ xlab("Recall") + ylab("Precision")+ggtitle("Adipose - Subcutaneous") legend <- get_legend(plot.lung + theme(legend.key = element_rect(color = "black", linetype = "solid", size = 0.5), legend.key.size = unit(0.3, "cm"), legend.key.height=unit(1.5,"line")) + guides(colour = guide_legend(override.aes = list(size= 1)))) fig2 <- plot_grid(plot.sub + xlim(0,0.015) + ylim(0, 0.015) + theme(legend.position="none"), plot.thyroid + xlim(0,0.015) + ylim(0, 0.015) + theme(legend.position="none"), plot.lung + xlim(0,0.015) + ylim(0, 0.015) + theme(legend.position="none"), plot.muscle + xlim(0,0.015) + ylim(0, 0.015) + theme(legend.position="none"), plot.blood + xlim(0,0.015) + ylim(0, 0.015) + theme(legend.position="none"), legend, # align = 'vh', labels = c("a", "b", "c", "d", "e", ""), hjust = -1, nrow = 3 ) pdf("supp_fig10.pdf", height = 7.2, width = 7.2) print(fig2) dev.off()
/publication_figures/supp_figs/suppfig9_10/fig_tft_glasso.R
no_license
MMesbahU/networks_correction
R
false
false
2,134
r
source("../../../src/config") library(cowplot) load("tft-glasso.RData") ## Read files theme_set(theme_cowplot(font_size=12)) # reduce default font size plot.thyroid <- ggplot(plot.thyroid, aes(x = recall, y = precision, colour = type)) + geom_point(size = 0.3) + # theme(text = element_text(size=7))+ xlab("Recall") + ylab("Precision")+ggtitle("Thyroid") plot.muscle <- ggplot(plot.muscle, aes(x = recall, y = precision, colour = type)) + geom_point(size = 0.3) + # theme(text = element_text(size=7)) + xlab("Recall") + ylab("Precision")+ggtitle("Muscle - Skeletal") plot.lung <- ggplot(plot.lung, aes(x = recall, y = precision, colour = type)) + geom_point(size = 0.3) + theme(legend.title=element_blank())+ xlab("Recall") + ylab("Precision")+ggtitle("Lung") plot.blood <- ggplot(plot.blood, aes(x = recall, y = precision, colour = type)) + geom_point(size = 0.3) + # theme(text = element_text(size=7))+ xlab("Recall") + ylab("Precision")+ggtitle("Whole Blood") plot.sub <- ggplot(plot.sub, aes(x = recall, y = precision, colour = type)) + geom_point(size = 0.3) + # theme(text = element_text(size=7))+ xlab("Recall") + ylab("Precision")+ggtitle("Adipose - Subcutaneous") legend <- get_legend(plot.lung + theme(legend.key = element_rect(color = "black", linetype = "solid", size = 0.5), legend.key.size = unit(0.3, "cm"), legend.key.height=unit(1.5,"line")) + guides(colour = guide_legend(override.aes = list(size= 1)))) fig2 <- plot_grid(plot.sub + xlim(0,0.015) + ylim(0, 0.015) + theme(legend.position="none"), plot.thyroid + xlim(0,0.015) + ylim(0, 0.015) + theme(legend.position="none"), plot.lung + xlim(0,0.015) + ylim(0, 0.015) + theme(legend.position="none"), plot.muscle + xlim(0,0.015) + ylim(0, 0.015) + theme(legend.position="none"), plot.blood + xlim(0,0.015) + ylim(0, 0.015) + theme(legend.position="none"), legend, # align = 'vh', labels = c("a", "b", "c", "d", "e", ""), hjust = -1, nrow = 3 ) pdf("supp_fig10.pdf", height = 7.2, width = 7.2) print(fig2) dev.off()
\name{ESummary} \alias{ESummary} \title{New ESummary Object} \usage{ESummary(NCBIObject)} \description{This function creates an object of the ESummary class and returns it.} \value{An object of the ESummary class.} \seealso{\code{\link[=ESummaryClass-class]{ESummaryClass}}} \author{Martin Schumann} \arguments{\item{NCBIObject}{The current instance of the NCBIClass.}}
/RNCBI-0.9/R-Source/man/ESummary.Rd
no_license
MartinUndDerWolf/rncbi
R
false
false
370
rd
\name{ESummary} \alias{ESummary} \title{New ESummary Object} \usage{ESummary(NCBIObject)} \description{This function creates an object of the ESummary class and returns it.} \value{An object of the ESummary class.} \seealso{\code{\link[=ESummaryClass-class]{ESummaryClass}}} \author{Martin Schumann} \arguments{\item{NCBIObject}{The current instance of the NCBIClass.}}
#' Building a null hypothesis data #' #' Create a null sampling data (N times) and write them to a file #' #' #' @param X The spectral dataset in the matrix format in which each row contains a single sample #' @param groupLabel Group label of samples in the dataset #' @param N The number of iteration for creating null sample distribution #' @param verbose A boolean value to allow print out process information #' #' @return A matrix with N rows containing the null distribution. #' #' #' @author Trung Nghia Vu #' #' @examples #' res=makeSimulatedData(); #' X=res$data; #' groupLabel=res$label; #' peakList <- detectSpecPeaks(X, #' nDivRange = c(128), #' scales = seq(1, 16, 2), #' baselineThresh = 50000, #' SNR.Th = -1, #' verbose=FALSE #' ); #' resFindRef<- findRef(peakList); #' refInd <- resFindRef$refInd; #' maxShift = 50; #' Y <- dohCluster(X, #' peakList = peakList, #' refInd = refInd, #' maxShift = maxShift, #' acceptLostPeak = TRUE, verbose=FALSE); #' # find the BW-statistic #' BW = BWR(Y, groupLabel); #' H0 = createNullSampling(Y, groupLabel, N = 100,verbose=FALSE) #' #' @export #' #' createNullSampling <-function(X, groupLabel, N=100, verbose=TRUE){ groupNum=length(levels(groupLabel)); samplePool=X; groupMean=list(); for (i in 1:groupNum){ groupLabeli=which(groupLabel==levels(groupLabel)[i]); Xi=X[groupLabeli,] mi=colMeans(Xi); groupMean[[i]]=mi; } for (i in 1:nrow(samplePool)){ samplePool[i,]= X[i,]-groupMean[[which(levels(groupLabel)==groupLabel[i])]]; } L=nrow(X); H0=matrix(data=0,nrow=N,ncol=ncol(X)); for(i in 1 : N){ if (verbose) cat("\n Permutation th",i); index=sample(L); H0[i,]=BWR(samplePool[index,],groupLabel); } return(H0); }
/R/createNullSampling.R
permissive
fenglb/speaq
R
false
false
2,073
r
#' Building a null hypothesis data #' #' Create a null sampling data (N times) and write them to a file #' #' #' @param X The spectral dataset in the matrix format in which each row contains a single sample #' @param groupLabel Group label of samples in the dataset #' @param N The number of iteration for creating null sample distribution #' @param verbose A boolean value to allow print out process information #' #' @return A matrix with N rows containing the null distribution. #' #' #' @author Trung Nghia Vu #' #' @examples #' res=makeSimulatedData(); #' X=res$data; #' groupLabel=res$label; #' peakList <- detectSpecPeaks(X, #' nDivRange = c(128), #' scales = seq(1, 16, 2), #' baselineThresh = 50000, #' SNR.Th = -1, #' verbose=FALSE #' ); #' resFindRef<- findRef(peakList); #' refInd <- resFindRef$refInd; #' maxShift = 50; #' Y <- dohCluster(X, #' peakList = peakList, #' refInd = refInd, #' maxShift = maxShift, #' acceptLostPeak = TRUE, verbose=FALSE); #' # find the BW-statistic #' BW = BWR(Y, groupLabel); #' H0 = createNullSampling(Y, groupLabel, N = 100,verbose=FALSE) #' #' @export #' #' createNullSampling <-function(X, groupLabel, N=100, verbose=TRUE){ groupNum=length(levels(groupLabel)); samplePool=X; groupMean=list(); for (i in 1:groupNum){ groupLabeli=which(groupLabel==levels(groupLabel)[i]); Xi=X[groupLabeli,] mi=colMeans(Xi); groupMean[[i]]=mi; } for (i in 1:nrow(samplePool)){ samplePool[i,]= X[i,]-groupMean[[which(levels(groupLabel)==groupLabel[i])]]; } L=nrow(X); H0=matrix(data=0,nrow=N,ncol=ncol(X)); for(i in 1 : N){ if (verbose) cat("\n Permutation th",i); index=sample(L); H0[i,]=BWR(samplePool[index,],groupLabel); } return(H0); }
Read.wRef <- function(ibase, iref, MissingValue) { # read-in data from base_data_file and ref_data_file, put MissingValue as NA set several global variables as output: Nt -- total numbers of seasonal factors, # say, monthly=12, daily=365 Icy -- catelog of seasonal factors, say, monthly 1:12 Y0 -- data vector of base - ref, take common period for both non-missing IY0 # -- cor-responding seasonal vector of Y0 IY0flg -- flg(integer, 0 or 1) for IY0, 1 -- continouse, 0 -- not continouse for autocorrelation calculation bdata -- # matrix of non-missing base data, 4 columns, yyyy,mm,dd,data ori.bdata -- original base data matrix, also 4 columns, same as bdata # ErrorMSG<-NA assign('ErrorMSG',ErrorMSG,envir=.GlobalEnv) # if(!file.exists(ibase)) { ErrorMSG<<-paste('Input basefile',ibase,'does not exist!', get('ErrorMSG',env=.GlobalEnv),'\n') return(-1) } if(!file.exists(iref)) # { ErrorMSG<<-paste('Input ref file',iref,'does not exist!', get('ErrorMSG',env=.GlobalEnv),'\n') return(-1) } if(is.csv(ibase)){ # itmp<-try(read.table(ibase,sep=',',header=F,na.strings=MissingValue, colClasses='real'),silent=T) if(inherits(itmp,'try-error')){ ErrorMSG<<-geterrmessage() # return(-1) } else itable<-itmp } else{ itmp<-try(read.table(ibase,sep='',header=F,na.strings=MissingValue, colClasses='real'),silent=T) # if(inherits(itmp,'try-error')){ ErrorMSG<<-geterrmessage() return(-1) } else itable<-itmp } if(is.csv(iref)){ # itmp<-try(read.table(iref,sep=',',header=F,na.strings=MissingValue, colClasses='real'),silent=T) if(inherits(itmp,'try-error')){ ErrorMSG<<-geterrmessage() # return(-1) } else rtable<-itmp } else{ itmp<-try(read.table(iref,sep='',header=F,na.strings=MissingValue, colClasses='real'),silent=T) # if(inherits(itmp,'try-error')){ ErrorMSG<<-geterrmessage() return(-1) } else rtable<-itmp } check input data (both base and ref), if column!=4, return error # if(dim(itable)[2]!=4){ ErrorMSG<-paste('Input base data column number error', get('ErrorMSG',env=.GlobalEnv),'\n') return(-1) } # colnames(itable)<-c('id1','id2','id3','data') itable <- as.data.frame(ibase) itable[which(itable[, 4] == MissingValue), 4] <- NA names(itable) <- c("id1", "id2", "id3", "data") # if(dim(rtable)[2]!=4){ ErrorMSG<-paste('Input reference data column number error', get('ErrorMSG',env=.GlobalEnv),'\n') return(-1) } # colnames(rtable)<-c('id1','id2','id3','data') rtable <- as.data.frame(iref) # rtable[rtable==MissingValue,4]<-NA names(rtable) <- c("id1", "id2", "id3", "data") # keep input base data as ori.itable ori.itable <- itable owflg <- is.na(ori.itable[, 4]) == F & ((itable[, 2] * 100 + itable[, 3]) != 229) # get rid of Feb 29th data itable <- itable[!(itable[, 2] == 2 & itable[, 3] == 29), ] rtable <- rtable[!(rtable[, 2] == 2 & rtable[, 3] == 29), ] # check input data (both base and ref), no jump with begin and end Icy <- sort(unique(itable[, 2] * 100 + itable[, 3])) Nt <- length(Icy) # construct YYYYMMDD for base series imdbegin <- itable[1, 2] * 100 + itable[1, 3] # begin MMDD for base series iyrbegin <- itable[1, 1] # begin year for base series Nx1 <- dim(itable)[1] imdend <- itable[Nx1, 2] * 100 + itable[Nx1, 3] # end MMDD for base series iyrend <- itable[Nx1, 1] # end year for base series Ind1 <- iyrbegin * 10000 + Icy[Icy >= imdbegin] # first year if (iyrend > (iyrbegin + 1)) for (i in (iyrbegin + 1):(iyrend - 1)) Ind1 <- c(Ind1, i * 10000 + Icy) Ind1 <- c(Ind1, iyrend * 10000 + Icy[Icy <= imdend]) YMD.base <- itable[, 1] * 10000 + itable[, 2] * 100 + itable[, 3] for (i in 1:length(Ind1)) { if (Ind1[i] != YMD.base[i] | is.na(YMD.base[i])) { InsertMessagesTxt(main.txt.out, paste("input base series not continuous at:", Ind1[i], YMD.base[i]), format = TRUE) return(-1) # stop(paste('input base series not continuous at:',Ind1[i],YMD.base[i])) } } # construct YYYYMMDD for ref series imdbegin <- rtable[1, 2] * 100 + rtable[1, 3] # begin MMDD for ref series iyrbegin <- rtable[1, 1] # begin year for base series Nx2 <- dim(rtable)[1] imdend <- rtable[Nx2, 2] * 100 + rtable[Nx2, 3] # end MMDD for ref series iyrend <- rtable[Nx2, 1] # end year for ref series Ind2 <- iyrbegin * 10000 + Icy[Icy >= imdbegin] # first year if (iyrend > (iyrbegin + 1)) for (i in (iyrbegin + 1):(iyrend - 1)) Ind2 <- c(Ind2, i * 10000 + Icy) Ind2 <- c(Ind2, iyrend * 10000 + Icy[Icy <= imdend]) YMD.ref <- rtable[, 1] * 10000 + rtable[, 2] * 100 + rtable[, 3] for (i in 1:length(Ind2)) if (Ind2[i] != YMD.ref[i] | is.na(YMD.ref[i])) { InsertMessagesTxt(main.txt.out, paste("input ref series not continuous at:", Ind2[i], YMD.base[i]), format = TRUE) # cat(paste('input ref series not continuous at:',Ind2[i],YMD.base[i]),'\n') ErrorMSG<-paste('input ref series not continuous at:',Ind2[i],YMD.base[i], # '\n',get('ErrorMSG',env=.GlobalEnv)) return(-1) } # take non-missing data only icol.nmbase <- itable[, 1] * 10000 + itable[, 2] * 100 + itable[, 3] itable <- itable[is.na(itable[, 4]) == F, ] # itable.nm<-itable itable.nmb <- merge(itable, rtable, by.x = c(1:3), by.y = c(1:3), all.x = T, all.y = F, sort = F) colnames(itable.nmb) <- c(colnames(itable), "data.ref") rtable <- rtable[is.na(rtable[, 4]) == F, ] Nx1 <- dim(itable)[1] Nx2 <- dim(rtable)[1] icol.base <- itable[, 1] * 10000 + itable[, 2] * 100 + itable[, 3] icol.ref <- rtable[, 1] * 10000 + rtable[, 2] * 100 + rtable[, 3] ind.base <- cbind(icol.base, seq(1, Nx1)) ind.ref <- cbind(icol.ref, seq(1, Nx2)) ind.base <- ind.base[is.na(itable[, 4]) == F, ] ind.ref <- ind.ref[is.na(rtable[, 4]) == F, ] colnames(ind.base) <- c("IY0", "ind") colnames(ind.ref) <- c("IY0", "ind") cind <- merge(ind.base, ind.ref, by.x = "IY0", by.y = "IY0", suffixes = c(".base", ".ref")) IY0 <- cind[, "IY0"] IY0flg <- rep(0, length(IY0)) # construct flag vector for autocor calculation Iyr <- floor(IY0/10000) Imd <- IY0 - Iyr * 10000 Ti <- IY0 for (i in 1:length(IY0)) { ith <- match(Imd[i], Icy) Ti[i] <- (Iyr[i] - iyrbegin) * Nt + ith } IyrB <- floor(icol.base/10000) ImdB <- icol.base - IyrB * 10000 TiB <- rep(0, Nx1) for (i in 1:Nx1) { ith <- match(ImdB[i], Icy) TiB[i] <- (IyrB[i] - iyrbegin) * Nt + ith } for (i in 1:(length(IY0) - 1)) { if (Ti[i + 1] - Ti[i] == 1) IY0flg[i] <- 1 } IYBflg <- rep(0, length(TiB)) for (i in 1:(length(TiB) - 1)) if (TiB[i + 1] - TiB[i] == 1) IYBflg[i] <- 1 ind.base <- cind[, "ind.base"] ind.ref <- cind[, "ind.ref"] # check data qualification itmp <- cbind(itable[, 2] * 100 + itable[, 3], rep(NA, dim(itable)[1])) itmp[ind.base, 2] <- itable[ind.base, 4] idenind <- unique(itmp[, 1]) for (i in 1:Nt) { if (sum(is.na(itmp[itmp[, 1] == Icy[i]]) == F) < 10) { InsertMessagesTxt(main.txt.out, paste("input data too few at:", Icy[i]), format = TRUE) # cat(paste('input data too few at:',Icy[i]),'\n') # ErrorMSG<<-paste('input data too few at:',Icy[i], '\n',get('ErrorMSG',env=.GlobalEnv)) return(-1) } } itmp1 <- 0 for (i in 1:(dim(itmp)[1] - 1)) if (is.na(itmp[i, 2]) == F & is.na(itmp[(i + 1), 2]) == F) itmp1 <- itmp1 + 1 if (itmp1 < 10) { InsertMessagesTxt(main.txt.out, "input data too few for autocorrelation calculating", format = TRUE) # cat(paste('input data too few for autocorrelation calculating','\n')) # ErrorMSG<<-paste('input data too few for autocorrelation calculating', '\n',get('ErrorMSG',env=.GlobalEnv)) return(-1) } # finish checking Y0 <- itable[ind.base, 4] - rtable[ind.ref, 4] rtmp <- itable[ind.base, ] otmp <- rmCycle(rtmp) EBb <- otmp$EB rtmp <- rtable[ind.ref, ] otmp <- rmCycle(rtmp) EBr <- otmp$EB itmp <- itable[ind.base, 2] * 100 + itable[ind.base, 3] for (i in 1:length(Y0)) { indd <- itmp[i] # mmdd for Y0[i] indf <- NULL for (j in 1:Nt) if (Icy[j] == indd) indf <- j Y0[i] <- Y0[i] + EBr[indf] - EBb[indf] } assign("Ti", Ti, envir = .GlobalEnv) # Time index for LS fitting assign("TiB", TiB, envir = .GlobalEnv) assign("Y0", Y0, envir = .GlobalEnv) # Data series for Base-Ref assign("IY0", IY0, envir = .GlobalEnv) # Cycle index for Base-Ref assign("IY0flg", IY0flg, envir = .GlobalEnv) # continuous flag for Base-Ref assign("IYBflg", IYBflg, envir = .GlobalEnv) # continuous flag for Base-Ref assign("bdata", itable.nmb, envir = .GlobalEnv) # non-missing table for base data assign("ori.bdata", ori.itable, envir = .GlobalEnv) # original base data assign("owflg", owflg, envir = .GlobalEnv) assign("Icy", Icy, envir = .GlobalEnv) # Cycle index assign("Nt", Nt, envir = .GlobalEnv) # Cycle length }
/RHtestsV4/Read.wRef.R
no_license
rijaf/CDT
R
false
false
9,296
r
Read.wRef <- function(ibase, iref, MissingValue) { # read-in data from base_data_file and ref_data_file, put MissingValue as NA set several global variables as output: Nt -- total numbers of seasonal factors, # say, monthly=12, daily=365 Icy -- catelog of seasonal factors, say, monthly 1:12 Y0 -- data vector of base - ref, take common period for both non-missing IY0 # -- cor-responding seasonal vector of Y0 IY0flg -- flg(integer, 0 or 1) for IY0, 1 -- continouse, 0 -- not continouse for autocorrelation calculation bdata -- # matrix of non-missing base data, 4 columns, yyyy,mm,dd,data ori.bdata -- original base data matrix, also 4 columns, same as bdata # ErrorMSG<-NA assign('ErrorMSG',ErrorMSG,envir=.GlobalEnv) # if(!file.exists(ibase)) { ErrorMSG<<-paste('Input basefile',ibase,'does not exist!', get('ErrorMSG',env=.GlobalEnv),'\n') return(-1) } if(!file.exists(iref)) # { ErrorMSG<<-paste('Input ref file',iref,'does not exist!', get('ErrorMSG',env=.GlobalEnv),'\n') return(-1) } if(is.csv(ibase)){ # itmp<-try(read.table(ibase,sep=',',header=F,na.strings=MissingValue, colClasses='real'),silent=T) if(inherits(itmp,'try-error')){ ErrorMSG<<-geterrmessage() # return(-1) } else itable<-itmp } else{ itmp<-try(read.table(ibase,sep='',header=F,na.strings=MissingValue, colClasses='real'),silent=T) # if(inherits(itmp,'try-error')){ ErrorMSG<<-geterrmessage() return(-1) } else itable<-itmp } if(is.csv(iref)){ # itmp<-try(read.table(iref,sep=',',header=F,na.strings=MissingValue, colClasses='real'),silent=T) if(inherits(itmp,'try-error')){ ErrorMSG<<-geterrmessage() # return(-1) } else rtable<-itmp } else{ itmp<-try(read.table(iref,sep='',header=F,na.strings=MissingValue, colClasses='real'),silent=T) # if(inherits(itmp,'try-error')){ ErrorMSG<<-geterrmessage() return(-1) } else rtable<-itmp } check input data (both base and ref), if column!=4, return error # if(dim(itable)[2]!=4){ ErrorMSG<-paste('Input base data column number error', get('ErrorMSG',env=.GlobalEnv),'\n') return(-1) } # colnames(itable)<-c('id1','id2','id3','data') itable <- as.data.frame(ibase) itable[which(itable[, 4] == MissingValue), 4] <- NA names(itable) <- c("id1", "id2", "id3", "data") # if(dim(rtable)[2]!=4){ ErrorMSG<-paste('Input reference data column number error', get('ErrorMSG',env=.GlobalEnv),'\n') return(-1) } # colnames(rtable)<-c('id1','id2','id3','data') rtable <- as.data.frame(iref) # rtable[rtable==MissingValue,4]<-NA names(rtable) <- c("id1", "id2", "id3", "data") # keep input base data as ori.itable ori.itable <- itable owflg <- is.na(ori.itable[, 4]) == F & ((itable[, 2] * 100 + itable[, 3]) != 229) # get rid of Feb 29th data itable <- itable[!(itable[, 2] == 2 & itable[, 3] == 29), ] rtable <- rtable[!(rtable[, 2] == 2 & rtable[, 3] == 29), ] # check input data (both base and ref), no jump with begin and end Icy <- sort(unique(itable[, 2] * 100 + itable[, 3])) Nt <- length(Icy) # construct YYYYMMDD for base series imdbegin <- itable[1, 2] * 100 + itable[1, 3] # begin MMDD for base series iyrbegin <- itable[1, 1] # begin year for base series Nx1 <- dim(itable)[1] imdend <- itable[Nx1, 2] * 100 + itable[Nx1, 3] # end MMDD for base series iyrend <- itable[Nx1, 1] # end year for base series Ind1 <- iyrbegin * 10000 + Icy[Icy >= imdbegin] # first year if (iyrend > (iyrbegin + 1)) for (i in (iyrbegin + 1):(iyrend - 1)) Ind1 <- c(Ind1, i * 10000 + Icy) Ind1 <- c(Ind1, iyrend * 10000 + Icy[Icy <= imdend]) YMD.base <- itable[, 1] * 10000 + itable[, 2] * 100 + itable[, 3] for (i in 1:length(Ind1)) { if (Ind1[i] != YMD.base[i] | is.na(YMD.base[i])) { InsertMessagesTxt(main.txt.out, paste("input base series not continuous at:", Ind1[i], YMD.base[i]), format = TRUE) return(-1) # stop(paste('input base series not continuous at:',Ind1[i],YMD.base[i])) } } # construct YYYYMMDD for ref series imdbegin <- rtable[1, 2] * 100 + rtable[1, 3] # begin MMDD for ref series iyrbegin <- rtable[1, 1] # begin year for base series Nx2 <- dim(rtable)[1] imdend <- rtable[Nx2, 2] * 100 + rtable[Nx2, 3] # end MMDD for ref series iyrend <- rtable[Nx2, 1] # end year for ref series Ind2 <- iyrbegin * 10000 + Icy[Icy >= imdbegin] # first year if (iyrend > (iyrbegin + 1)) for (i in (iyrbegin + 1):(iyrend - 1)) Ind2 <- c(Ind2, i * 10000 + Icy) Ind2 <- c(Ind2, iyrend * 10000 + Icy[Icy <= imdend]) YMD.ref <- rtable[, 1] * 10000 + rtable[, 2] * 100 + rtable[, 3] for (i in 1:length(Ind2)) if (Ind2[i] != YMD.ref[i] | is.na(YMD.ref[i])) { InsertMessagesTxt(main.txt.out, paste("input ref series not continuous at:", Ind2[i], YMD.base[i]), format = TRUE) # cat(paste('input ref series not continuous at:',Ind2[i],YMD.base[i]),'\n') ErrorMSG<-paste('input ref series not continuous at:',Ind2[i],YMD.base[i], # '\n',get('ErrorMSG',env=.GlobalEnv)) return(-1) } # take non-missing data only icol.nmbase <- itable[, 1] * 10000 + itable[, 2] * 100 + itable[, 3] itable <- itable[is.na(itable[, 4]) == F, ] # itable.nm<-itable itable.nmb <- merge(itable, rtable, by.x = c(1:3), by.y = c(1:3), all.x = T, all.y = F, sort = F) colnames(itable.nmb) <- c(colnames(itable), "data.ref") rtable <- rtable[is.na(rtable[, 4]) == F, ] Nx1 <- dim(itable)[1] Nx2 <- dim(rtable)[1] icol.base <- itable[, 1] * 10000 + itable[, 2] * 100 + itable[, 3] icol.ref <- rtable[, 1] * 10000 + rtable[, 2] * 100 + rtable[, 3] ind.base <- cbind(icol.base, seq(1, Nx1)) ind.ref <- cbind(icol.ref, seq(1, Nx2)) ind.base <- ind.base[is.na(itable[, 4]) == F, ] ind.ref <- ind.ref[is.na(rtable[, 4]) == F, ] colnames(ind.base) <- c("IY0", "ind") colnames(ind.ref) <- c("IY0", "ind") cind <- merge(ind.base, ind.ref, by.x = "IY0", by.y = "IY0", suffixes = c(".base", ".ref")) IY0 <- cind[, "IY0"] IY0flg <- rep(0, length(IY0)) # construct flag vector for autocor calculation Iyr <- floor(IY0/10000) Imd <- IY0 - Iyr * 10000 Ti <- IY0 for (i in 1:length(IY0)) { ith <- match(Imd[i], Icy) Ti[i] <- (Iyr[i] - iyrbegin) * Nt + ith } IyrB <- floor(icol.base/10000) ImdB <- icol.base - IyrB * 10000 TiB <- rep(0, Nx1) for (i in 1:Nx1) { ith <- match(ImdB[i], Icy) TiB[i] <- (IyrB[i] - iyrbegin) * Nt + ith } for (i in 1:(length(IY0) - 1)) { if (Ti[i + 1] - Ti[i] == 1) IY0flg[i] <- 1 } IYBflg <- rep(0, length(TiB)) for (i in 1:(length(TiB) - 1)) if (TiB[i + 1] - TiB[i] == 1) IYBflg[i] <- 1 ind.base <- cind[, "ind.base"] ind.ref <- cind[, "ind.ref"] # check data qualification itmp <- cbind(itable[, 2] * 100 + itable[, 3], rep(NA, dim(itable)[1])) itmp[ind.base, 2] <- itable[ind.base, 4] idenind <- unique(itmp[, 1]) for (i in 1:Nt) { if (sum(is.na(itmp[itmp[, 1] == Icy[i]]) == F) < 10) { InsertMessagesTxt(main.txt.out, paste("input data too few at:", Icy[i]), format = TRUE) # cat(paste('input data too few at:',Icy[i]),'\n') # ErrorMSG<<-paste('input data too few at:',Icy[i], '\n',get('ErrorMSG',env=.GlobalEnv)) return(-1) } } itmp1 <- 0 for (i in 1:(dim(itmp)[1] - 1)) if (is.na(itmp[i, 2]) == F & is.na(itmp[(i + 1), 2]) == F) itmp1 <- itmp1 + 1 if (itmp1 < 10) { InsertMessagesTxt(main.txt.out, "input data too few for autocorrelation calculating", format = TRUE) # cat(paste('input data too few for autocorrelation calculating','\n')) # ErrorMSG<<-paste('input data too few for autocorrelation calculating', '\n',get('ErrorMSG',env=.GlobalEnv)) return(-1) } # finish checking Y0 <- itable[ind.base, 4] - rtable[ind.ref, 4] rtmp <- itable[ind.base, ] otmp <- rmCycle(rtmp) EBb <- otmp$EB rtmp <- rtable[ind.ref, ] otmp <- rmCycle(rtmp) EBr <- otmp$EB itmp <- itable[ind.base, 2] * 100 + itable[ind.base, 3] for (i in 1:length(Y0)) { indd <- itmp[i] # mmdd for Y0[i] indf <- NULL for (j in 1:Nt) if (Icy[j] == indd) indf <- j Y0[i] <- Y0[i] + EBr[indf] - EBb[indf] } assign("Ti", Ti, envir = .GlobalEnv) # Time index for LS fitting assign("TiB", TiB, envir = .GlobalEnv) assign("Y0", Y0, envir = .GlobalEnv) # Data series for Base-Ref assign("IY0", IY0, envir = .GlobalEnv) # Cycle index for Base-Ref assign("IY0flg", IY0flg, envir = .GlobalEnv) # continuous flag for Base-Ref assign("IYBflg", IYBflg, envir = .GlobalEnv) # continuous flag for Base-Ref assign("bdata", itable.nmb, envir = .GlobalEnv) # non-missing table for base data assign("ori.bdata", ori.itable, envir = .GlobalEnv) # original base data assign("owflg", owflg, envir = .GlobalEnv) assign("Icy", Icy, envir = .GlobalEnv) # Cycle index assign("Nt", Nt, envir = .GlobalEnv) # Cycle length }
samp.default <- function(x, summaries=FALSE, ...) { if (inherits(x, "Mefa")) return(x@xtab) if (inherits(x, "mefa")) { if (is.null(x$samp)) return(NULL) else if (summaries) return(as.data.frame(x, fun=mss, ...)) else return(x$samp) } stop("not mefa class") }
/mefa/R/samp.default.R
no_license
ingted/R-Examples
R
false
false
322
r
samp.default <- function(x, summaries=FALSE, ...) { if (inherits(x, "Mefa")) return(x@xtab) if (inherits(x, "mefa")) { if (is.null(x$samp)) return(NULL) else if (summaries) return(as.data.frame(x, fun=mss, ...)) else return(x$samp) } stop("not mefa class") }
#' Drop a node attribute column #' @description Within a graph's internal NDF, remove #' an existing node attribute. #' @param graph a graph object of class #' @param node_attr the name of the node attribute #' column to drop. #' @return a graph object of class #' \code{dgr_graph}. #' @examples #' # Create a random graph #' graph <- #' create_random_graph( #' 5, 10, set_seed = 3) #' #' # Get the graph's internal ndf to show which #' # node attributes are available #' get_node_df(graph) #' #> nodes type label value #' #> 1 1 1 2 #' #> 2 2 2 8.5 #' #> 3 3 3 4 #' #> 4 4 4 3.5 #' #> 5 5 5 6.5 #' #' # Drop the `value` node attribute #' graph <- #' graph %>% #' drop_node_attrs("value") #' #' # Get the graph's internal ndf to show that the #' # node attribute had been removed #' get_node_df(graph) #' #> nodes type label #' #> 1 1 1 #' #> 2 2 2 #' #> 3 3 3 #' #> 4 4 4 #' #> 5 5 5 #' @export drop_node_attrs drop_node_attrs <- function(graph, node_attr) { # Stop function if length of `node_attr` is # greater than one if (length(node_attr) > 1) { stop("You can only provide a single column.") } # Stop function if `node_attr` is any of # `nodes`, `node`, `type`, or `label` if (any(c("nodes", "node", "type", "label") %in% node_attr)) { stop("You cannot drop this column.") } # Get the number of nodes ever created for # this graph nodes_created <- graph$last_node # Extract the graph's ndf nodes <- get_node_df(graph) # Get column names from the graph's ndf column_names_graph <- colnames(nodes) # Stop function if `node_attr` is not one # of the graph's column if (!any(column_names_graph %in% node_attr)) { stop("The node attribute to drop is not in the ndf.") } # Get the column number for the node attr to drop col_num_drop <- which(colnames(nodes) %in% node_attr) # Remove the column nodes <- nodes[, -col_num_drop] # Create a new graph object dgr_graph <- create_graph( nodes_df = nodes, edges_df = graph$edges_df, graph_attrs = graph$graph_attrs, node_attrs = graph$node_attrs, edge_attrs = graph$edge_attrs, directed = graph$directed, graph_name = graph$graph_name, graph_time = graph$graph_time, graph_tz = graph$graph_tz) # Update the `last_node` counter dgr_graph$last_node <- nodes_created return(dgr_graph) }
/R/drop_node_attrs.R
no_license
timelyportfolio/DiagrammeR
R
false
false
2,566
r
#' Drop a node attribute column #' @description Within a graph's internal NDF, remove #' an existing node attribute. #' @param graph a graph object of class #' @param node_attr the name of the node attribute #' column to drop. #' @return a graph object of class #' \code{dgr_graph}. #' @examples #' # Create a random graph #' graph <- #' create_random_graph( #' 5, 10, set_seed = 3) #' #' # Get the graph's internal ndf to show which #' # node attributes are available #' get_node_df(graph) #' #> nodes type label value #' #> 1 1 1 2 #' #> 2 2 2 8.5 #' #> 3 3 3 4 #' #> 4 4 4 3.5 #' #> 5 5 5 6.5 #' #' # Drop the `value` node attribute #' graph <- #' graph %>% #' drop_node_attrs("value") #' #' # Get the graph's internal ndf to show that the #' # node attribute had been removed #' get_node_df(graph) #' #> nodes type label #' #> 1 1 1 #' #> 2 2 2 #' #> 3 3 3 #' #> 4 4 4 #' #> 5 5 5 #' @export drop_node_attrs drop_node_attrs <- function(graph, node_attr) { # Stop function if length of `node_attr` is # greater than one if (length(node_attr) > 1) { stop("You can only provide a single column.") } # Stop function if `node_attr` is any of # `nodes`, `node`, `type`, or `label` if (any(c("nodes", "node", "type", "label") %in% node_attr)) { stop("You cannot drop this column.") } # Get the number of nodes ever created for # this graph nodes_created <- graph$last_node # Extract the graph's ndf nodes <- get_node_df(graph) # Get column names from the graph's ndf column_names_graph <- colnames(nodes) # Stop function if `node_attr` is not one # of the graph's column if (!any(column_names_graph %in% node_attr)) { stop("The node attribute to drop is not in the ndf.") } # Get the column number for the node attr to drop col_num_drop <- which(colnames(nodes) %in% node_attr) # Remove the column nodes <- nodes[, -col_num_drop] # Create a new graph object dgr_graph <- create_graph( nodes_df = nodes, edges_df = graph$edges_df, graph_attrs = graph$graph_attrs, node_attrs = graph$node_attrs, edge_attrs = graph$edge_attrs, directed = graph$directed, graph_name = graph$graph_name, graph_time = graph$graph_time, graph_tz = graph$graph_tz) # Update the `last_node` counter dgr_graph$last_node <- nodes_created return(dgr_graph) }
#' Raw mass spectrum proteomics log abundance for 4 pairs of technical replicates. #' @format A data frame of 85 rows and 8 columns with missing peaks' abundance as NA. #' 'replicates'
/R/replicates.R
no_license
cran/GMSimpute
R
false
false
192
r
#' Raw mass spectrum proteomics log abundance for 4 pairs of technical replicates. #' @format A data frame of 85 rows and 8 columns with missing peaks' abundance as NA. #' 'replicates'
# # RUnit tests TTR moving averages # # test reclass works and throws error # test xtsAttributes, both CLASS and USER # test all.equal(CLASS) and !all.equal(CLASS) cases # Create input data data(ttrc) rownames(ttrc) <- ttrc$Date ttrc$Date <- NULL input <- list( all=ttrc[1:250,], top=ttrc[1:250,], mid=ttrc[1:250,] ) input$top[1:10,] <- NA input$mid[9:20,] <- NA # Load output data load('unitTests/output.overlays.rda') ################################################# # Bollinger Bands test.BBands <- function() { ia <- input$all[,c('High','Low','Close')] it <- input$top[,c('High','Low','Close')] im <- input$mid[,c('High','Low')] rownames(ia) <- rownames(it) <- NULL oa <- BBands(ia) ot <- BBands(it) rownames(oa) <- rownames(ot) <- rownames(input$all) checkEqualsNumeric( oa, output$allBBands ) checkEquals( attributes(oa), attributes(output$allBBands) ) checkEqualsNumeric( ot, output$topBBands ) checkEquals( attributes(ot), attributes(output$topBBands) ) checkException( BBands(im) ) } # SAR test.SAR <- function() { ia <- input$all[,c('High','Low')] it <- input$top[,c('High','Low')] im <- input$mid[,c('High','Low')] rownames(ia) <- rownames(it) <- rownames(im) <- NULL checkEqualsNumeric( SAR(ia), output$allSAR ) checkEquals( attributes(SAR(ia)), attributes(output$allSAR) ) checkEqualsNumeric( SAR(it), output$topSAR ) checkEquals( attributes(SAR(it)), attributes(output$topSAR) ) checkException( SAR(im) ) } # Zig Zag test.ZigZag <- function() { ia <- input$all[,c('High','Low')] it <- input$top[,c('High','Low')] im <- input$mid[,c('High','Low')] rownames(ia) <- rownames(it) <- rownames(im) <- NULL checkEqualsNumeric( ZigZag(ia), output$allZZ ) checkEquals( attributes(ZigZag(ia)), attributes(output$allZZ) ) checkEqualsNumeric( ZigZag(it), output$topZZ ) checkEquals( attributes(ZigZag(it)), attributes(output$topZZ) ) checkException( ZigZag(im) ) }
/TTR/tests/unitTests/runit.TTR.Overlays.R
no_license
codeview2/codeview
R
false
false
1,937
r
# # RUnit tests TTR moving averages # # test reclass works and throws error # test xtsAttributes, both CLASS and USER # test all.equal(CLASS) and !all.equal(CLASS) cases # Create input data data(ttrc) rownames(ttrc) <- ttrc$Date ttrc$Date <- NULL input <- list( all=ttrc[1:250,], top=ttrc[1:250,], mid=ttrc[1:250,] ) input$top[1:10,] <- NA input$mid[9:20,] <- NA # Load output data load('unitTests/output.overlays.rda') ################################################# # Bollinger Bands test.BBands <- function() { ia <- input$all[,c('High','Low','Close')] it <- input$top[,c('High','Low','Close')] im <- input$mid[,c('High','Low')] rownames(ia) <- rownames(it) <- NULL oa <- BBands(ia) ot <- BBands(it) rownames(oa) <- rownames(ot) <- rownames(input$all) checkEqualsNumeric( oa, output$allBBands ) checkEquals( attributes(oa), attributes(output$allBBands) ) checkEqualsNumeric( ot, output$topBBands ) checkEquals( attributes(ot), attributes(output$topBBands) ) checkException( BBands(im) ) } # SAR test.SAR <- function() { ia <- input$all[,c('High','Low')] it <- input$top[,c('High','Low')] im <- input$mid[,c('High','Low')] rownames(ia) <- rownames(it) <- rownames(im) <- NULL checkEqualsNumeric( SAR(ia), output$allSAR ) checkEquals( attributes(SAR(ia)), attributes(output$allSAR) ) checkEqualsNumeric( SAR(it), output$topSAR ) checkEquals( attributes(SAR(it)), attributes(output$topSAR) ) checkException( SAR(im) ) } # Zig Zag test.ZigZag <- function() { ia <- input$all[,c('High','Low')] it <- input$top[,c('High','Low')] im <- input$mid[,c('High','Low')] rownames(ia) <- rownames(it) <- rownames(im) <- NULL checkEqualsNumeric( ZigZag(ia), output$allZZ ) checkEquals( attributes(ZigZag(ia)), attributes(output$allZZ) ) checkEqualsNumeric( ZigZag(it), output$topZZ ) checkEquals( attributes(ZigZag(it)), attributes(output$topZZ) ) checkException( ZigZag(im) ) }
# plot number of strokes per character vs year of learning the kanji # from list on wikipedia # https://en.wikipedia.org/wiki/Ky%C5%8Diku_kanji library(ggplot2) kanjidata_file = "~/git/misc-analyses/language_difficulty/data/kanji_by_school_year_1-6.txt" kanjidata = read.table(kanjidata_file, header=TRUE, sep="\t", encoding="UTF-8", stringsAsFactors=FALSE) strokejitter=jitter(kanjidata$Strokes, factor=0.5) gradejitter=jitter(kanjidata$grade) replace_numbers = c(116, 120, 237, 436, 241, 582, 608, 613, 629, 635, 636, 640, 769, 774, 792, 793, 824, 946, 963, 964, 989, 1003 ) replace_xjitters = c(1.9, 2.1, 2.0, 3.0, 3.0, 3.9, 3.8, 4.1, 3.9, 4.1, 4.0, 4.2, 4.8, 5.0, 5.0, 5.0, 5.2, 5.8, 5.9, 6.0, 6.1, 6.2 ) gradejitter_fixed = replace(gradejitter, replace_numbers, replace_xjitters) has_many_strokes = kanjidata$Strokes >= 18 kanjidata[has_many_strokes,2] p = ggplot(data=kanjidata , aes(x = grade, y = Strokes, group=grade) ) + theme(text = element_text(family="Japan1"), axis.text.y=element_text(size=16), axis.text.x=element_text(size=13), axis.title=element_text(size=18)) + labs(x="Grade", y="Strokes", title="Number of strokes per character for Kyouiku Kanji", subtitle="for primary school") + scale_x_continuous(breaks=1:6) + geom_boxplot( outlier.size = 5, outlier.shape = NA) + #geom_jitter( width=0.25, height=0.2, color="#086a33", size=5, alpha=0.5) geom_point(data=kanjidata, aes(x = gradejitter_fixed, y=strokejitter), size=5, alpha=0.5, color="#fe9929") + geom_text(data=kanjidata, aes( x = gradejitter_fixed, y=strokejitter, label=ifelse(Strokes >= 18 , as.character(Kanji), '' ) ) , vjust=0.5, size=5 ) p pdf("~/git/misc-analyses/language_difficulty/images/kanji_by_school_year_w_outliers.pdf", height=7, width=8, family="Japan1" ) print(p) dev.off() #ggsave("~/git/misc-analyses/language_difficulty/images/kanji_by_school_year_w_outliers.pdf", p, device="pdf", encoding="default", height=7, width=8, fonts="Japan1") #
/language_difficulty/kanji_difficulty.R
no_license
wrf/misc-analyses
R
false
false
2,171
r
# plot number of strokes per character vs year of learning the kanji # from list on wikipedia # https://en.wikipedia.org/wiki/Ky%C5%8Diku_kanji library(ggplot2) kanjidata_file = "~/git/misc-analyses/language_difficulty/data/kanji_by_school_year_1-6.txt" kanjidata = read.table(kanjidata_file, header=TRUE, sep="\t", encoding="UTF-8", stringsAsFactors=FALSE) strokejitter=jitter(kanjidata$Strokes, factor=0.5) gradejitter=jitter(kanjidata$grade) replace_numbers = c(116, 120, 237, 436, 241, 582, 608, 613, 629, 635, 636, 640, 769, 774, 792, 793, 824, 946, 963, 964, 989, 1003 ) replace_xjitters = c(1.9, 2.1, 2.0, 3.0, 3.0, 3.9, 3.8, 4.1, 3.9, 4.1, 4.0, 4.2, 4.8, 5.0, 5.0, 5.0, 5.2, 5.8, 5.9, 6.0, 6.1, 6.2 ) gradejitter_fixed = replace(gradejitter, replace_numbers, replace_xjitters) has_many_strokes = kanjidata$Strokes >= 18 kanjidata[has_many_strokes,2] p = ggplot(data=kanjidata , aes(x = grade, y = Strokes, group=grade) ) + theme(text = element_text(family="Japan1"), axis.text.y=element_text(size=16), axis.text.x=element_text(size=13), axis.title=element_text(size=18)) + labs(x="Grade", y="Strokes", title="Number of strokes per character for Kyouiku Kanji", subtitle="for primary school") + scale_x_continuous(breaks=1:6) + geom_boxplot( outlier.size = 5, outlier.shape = NA) + #geom_jitter( width=0.25, height=0.2, color="#086a33", size=5, alpha=0.5) geom_point(data=kanjidata, aes(x = gradejitter_fixed, y=strokejitter), size=5, alpha=0.5, color="#fe9929") + geom_text(data=kanjidata, aes( x = gradejitter_fixed, y=strokejitter, label=ifelse(Strokes >= 18 , as.character(Kanji), '' ) ) , vjust=0.5, size=5 ) p pdf("~/git/misc-analyses/language_difficulty/images/kanji_by_school_year_w_outliers.pdf", height=7, width=8, family="Japan1" ) print(p) dev.off() #ggsave("~/git/misc-analyses/language_difficulty/images/kanji_by_school_year_w_outliers.pdf", p, device="pdf", encoding="default", height=7, width=8, fonts="Japan1") #
library(glmnet) mydata = read.table("./TrainingSet/ReliefF/stomach.csv",head=T,sep=",") x = as.matrix(mydata[,4:ncol(mydata)]) y = as.matrix(mydata[,1]) set.seed(123) glm = cv.glmnet(x,y,nfolds=10,type.measure="mae",alpha=0.25,family="gaussian",standardize=FALSE) sink('./Model/EN/ReliefF/stomach/stomach_040.txt',append=TRUE) print(glm$glmnet.fit) sink()
/Model/EN/ReliefF/stomach/stomach_040.R
no_license
leon1003/QSMART
R
false
false
356
r
library(glmnet) mydata = read.table("./TrainingSet/ReliefF/stomach.csv",head=T,sep=",") x = as.matrix(mydata[,4:ncol(mydata)]) y = as.matrix(mydata[,1]) set.seed(123) glm = cv.glmnet(x,y,nfolds=10,type.measure="mae",alpha=0.25,family="gaussian",standardize=FALSE) sink('./Model/EN/ReliefF/stomach/stomach_040.txt',append=TRUE) print(glm$glmnet.fit) sink()
## The functions herein cache the inverse of a matrix. ## Matrix inversion is usually a costly computation. ## Caching matrix inversions stores the data produced by the ## matrix inversion so that we can refer to that data repeatedly without ## having to compute the inversion over and over again. makeCacheMatrix <- function(x = matrix(), ...) { ## This function creates a special "matrix" object that can ## cache its inverse: m <- NULL ## This initializes "m", the variable within which the function caches set <- function(y) { ## This enables user to reset m as NULL, as well as x. x <<- y m <<- NULL } get <- function() x ## This allows $get() to take on the value of argument x. setinverse <- function(solve) m <<- solve ## This allows the inverse to be reset. getinverse <- function() m ## This receives the inverse matrix from cacheSolve. list(set = set, get = get, ## This coerces the functions above to list form. setinverse = setinverse, getinverse = getinverse) } cacheSolve <- function(x, ...) { ## This function then computes the inverse of the special matrix ## which was created by the makeCacheMatrix function above. If the inverse ## has already been calculated (and the matrix has not changed), then ## the function below will just retrieve the data from the cache. ## Ultimately, it returns a matrix that is the inverse of 'x'. m <- x$getinverse() ## This makes the local "m" become getinverse() if(!is.null(m)) { ## If the local m is not NULL, then global m is returned. message("getting cached data...") return(m) } data <- x$get() ## Else, the original matrix from makeCacheMatrix is stored in "data". m <- solve(data, ...) ## And "data" is used to store the inverse value into local m x$setinverse(m) ## This sets global m as the local m here m ## This returns local m }
/cachematrix.R
no_license
ericchoi53/ProgrammingAssignment2
R
false
false
2,057
r
## The functions herein cache the inverse of a matrix. ## Matrix inversion is usually a costly computation. ## Caching matrix inversions stores the data produced by the ## matrix inversion so that we can refer to that data repeatedly without ## having to compute the inversion over and over again. makeCacheMatrix <- function(x = matrix(), ...) { ## This function creates a special "matrix" object that can ## cache its inverse: m <- NULL ## This initializes "m", the variable within which the function caches set <- function(y) { ## This enables user to reset m as NULL, as well as x. x <<- y m <<- NULL } get <- function() x ## This allows $get() to take on the value of argument x. setinverse <- function(solve) m <<- solve ## This allows the inverse to be reset. getinverse <- function() m ## This receives the inverse matrix from cacheSolve. list(set = set, get = get, ## This coerces the functions above to list form. setinverse = setinverse, getinverse = getinverse) } cacheSolve <- function(x, ...) { ## This function then computes the inverse of the special matrix ## which was created by the makeCacheMatrix function above. If the inverse ## has already been calculated (and the matrix has not changed), then ## the function below will just retrieve the data from the cache. ## Ultimately, it returns a matrix that is the inverse of 'x'. m <- x$getinverse() ## This makes the local "m" become getinverse() if(!is.null(m)) { ## If the local m is not NULL, then global m is returned. message("getting cached data...") return(m) } data <- x$get() ## Else, the original matrix from makeCacheMatrix is stored in "data". m <- solve(data, ...) ## And "data" is used to store the inverse value into local m x$setinverse(m) ## This sets global m as the local m here m ## This returns local m }
library(fitdistrplus) # (1) fit of two distributions by maximum likelihood estimation # to the serving size data # and comparison of goodness-of-fit statistics # data(groundbeef) serving <- groundbeef$serving (fitg <- fitdist(serving, "gamma")) gg <- gofstat(fitg) (fitln <- fitdist(serving, "lnorm")) gn <- gofstat(fitln) gofstat(list(fitg, fitln)) # (2) fit of two discrete distributions to toxocara data # and comparison of goodness-of-fit statistics # data(toxocara) number <- toxocara$number fitp <- fitdist(number, "pois") summary(fitp) plot(fitp) gp <- gofstat(fitp) gp fitnb <- fitdist(number, "nbinom") summary(fitnb) plot(fitnb) gnb <- gofstat(fitnb) gnb gofstat(list(fitp, fitnb)) attributes(gofstat(list(fitp, fitnb))) # (3) Use of Chi-squared results in addition to # recommended statistics for continuous distributions # set.seed(1234) x4 <- rweibull(n=10,shape=2,scale=1) # fit of the good distribution f4 <- fitdist(x4, "weibull") g4 <- gofstat(f4, meancount=10) print(g4) # fit of a bad distribution f4b <- fitdist(x4, "cauchy") g4b <- gofstat(f4b, meancount=10) print(g4b) # (4) estimation of the standard deviation of a normal distribution # by maximum likelihood with the mean fixed at 10 using the argument fix.arg # f1b <- fitdist(serving, "norm", start=list(sd=5), fix.arg=list(mean=10), lower=0) gofstat(f1b)
/tests/t-gofstat.R
no_license
frontierkodiak/fitdistrplusExperimental
R
false
false
1,357
r
library(fitdistrplus) # (1) fit of two distributions by maximum likelihood estimation # to the serving size data # and comparison of goodness-of-fit statistics # data(groundbeef) serving <- groundbeef$serving (fitg <- fitdist(serving, "gamma")) gg <- gofstat(fitg) (fitln <- fitdist(serving, "lnorm")) gn <- gofstat(fitln) gofstat(list(fitg, fitln)) # (2) fit of two discrete distributions to toxocara data # and comparison of goodness-of-fit statistics # data(toxocara) number <- toxocara$number fitp <- fitdist(number, "pois") summary(fitp) plot(fitp) gp <- gofstat(fitp) gp fitnb <- fitdist(number, "nbinom") summary(fitnb) plot(fitnb) gnb <- gofstat(fitnb) gnb gofstat(list(fitp, fitnb)) attributes(gofstat(list(fitp, fitnb))) # (3) Use of Chi-squared results in addition to # recommended statistics for continuous distributions # set.seed(1234) x4 <- rweibull(n=10,shape=2,scale=1) # fit of the good distribution f4 <- fitdist(x4, "weibull") g4 <- gofstat(f4, meancount=10) print(g4) # fit of a bad distribution f4b <- fitdist(x4, "cauchy") g4b <- gofstat(f4b, meancount=10) print(g4b) # (4) estimation of the standard deviation of a normal distribution # by maximum likelihood with the mean fixed at 10 using the argument fix.arg # f1b <- fitdist(serving, "norm", start=list(sd=5), fix.arg=list(mean=10), lower=0) gofstat(f1b)
## Put comments here that give an overall description of what your ## functions do ## Write a short comment describing this function makeCacheMatrix <- function(x = matrix()) { #this is defineed to set a value to the matrix and c #inverse from the cache i <- NULL set <- function(y) { x <<- y # setting the value i <<- NULL # clear the cache } get <- function() x # Define function to set the inverse. This is only used by getinverse() when # there is no cached inverse setInverse <- function(inverse) i <<- inverse getInverse <- function() i list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) } ## Write a short comment describing this function cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' i <- x$getInverse() if (!is.null(i)) { message("getting cached data") return(i) } mat <- x$get() i <- solve(mat, ...) x$setInverse(i) i }
/cachematrix.R
no_license
kgpavan/ProgrammingAssignment2
R
false
false
984
r
## Put comments here that give an overall description of what your ## functions do ## Write a short comment describing this function makeCacheMatrix <- function(x = matrix()) { #this is defineed to set a value to the matrix and c #inverse from the cache i <- NULL set <- function(y) { x <<- y # setting the value i <<- NULL # clear the cache } get <- function() x # Define function to set the inverse. This is only used by getinverse() when # there is no cached inverse setInverse <- function(inverse) i <<- inverse getInverse <- function() i list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) } ## Write a short comment describing this function cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' i <- x$getInverse() if (!is.null(i)) { message("getting cached data") return(i) } mat <- x$get() i <- solve(mat, ...) x$setInverse(i) i }
#' @title durumWC #' @description 200 sites from durum wheat collection and their world clim data. #' @docType data #' @usage data(durumWC) #' @format The data includes the site unique identifier, longitude, latitude and 55 worldclim data \href{https://www.worldclim.org}{worldclim} #' #' @examples #' if(interactive()){ #' # Load durum wheat data with world climatic variables obtained from WorldClim database #' data(durumWC) #' } "durumWC" #' @title durumDaily #' @description 200 sites from durum wheat collection and their daily climatic data. #' @docType data #' @usage data(durumDaily) #' @format The data includes the site unique identifier and daily data for 4 climatic variables (tmin, tmax, precipitation and relative humidity) #' #' @examples #' if(interactive()){ #' # Load durum wheat data with their daily climatic variables obtained from ICARDA database #' data(durumDaily) #' } "durumDaily" #' @title septoriaDurumWC #' @description A sample data including daily data for 4 climatic variables (tmin, tmax, precipitation and relative humidity) and evaluation for Septoria Tritici #' @docType data #' @usage data(septoriaDurumWC) #' @format 200 sites from durum wheat collection and their daily climatic data and evaluation for Septoria Tritici. #' #' @examples #' if(interactive()){ #' #Load durum wheat data with septoria scores and climatic variables obtained from WorldClim database #' data(septoriaDurumWC) #' } "septoriaDurumWC" #' @title FIGS subset for wheat sodicity resistance #' #' @description FIGS subset for wheat sodicity resistance #' constructed using the harmonized world soil database HWSD #' #' @docType data #' #' @usage data(FIGS) #' #' @format A data frame with 201 rows and 15 variables #' #' #' @references #' \href{http://www.fao.org/3/aq361e/aq361e.pdf}{HWSD} #' #' #' @examples #' if(interactive()){ #' data(FIGS) #' } "FIGS"
/R/data.R
no_license
khadijaaziz/icardaFIGSr
R
false
false
1,887
r
#' @title durumWC #' @description 200 sites from durum wheat collection and their world clim data. #' @docType data #' @usage data(durumWC) #' @format The data includes the site unique identifier, longitude, latitude and 55 worldclim data \href{https://www.worldclim.org}{worldclim} #' #' @examples #' if(interactive()){ #' # Load durum wheat data with world climatic variables obtained from WorldClim database #' data(durumWC) #' } "durumWC" #' @title durumDaily #' @description 200 sites from durum wheat collection and their daily climatic data. #' @docType data #' @usage data(durumDaily) #' @format The data includes the site unique identifier and daily data for 4 climatic variables (tmin, tmax, precipitation and relative humidity) #' #' @examples #' if(interactive()){ #' # Load durum wheat data with their daily climatic variables obtained from ICARDA database #' data(durumDaily) #' } "durumDaily" #' @title septoriaDurumWC #' @description A sample data including daily data for 4 climatic variables (tmin, tmax, precipitation and relative humidity) and evaluation for Septoria Tritici #' @docType data #' @usage data(septoriaDurumWC) #' @format 200 sites from durum wheat collection and their daily climatic data and evaluation for Septoria Tritici. #' #' @examples #' if(interactive()){ #' #Load durum wheat data with septoria scores and climatic variables obtained from WorldClim database #' data(septoriaDurumWC) #' } "septoriaDurumWC" #' @title FIGS subset for wheat sodicity resistance #' #' @description FIGS subset for wheat sodicity resistance #' constructed using the harmonized world soil database HWSD #' #' @docType data #' #' @usage data(FIGS) #' #' @format A data frame with 201 rows and 15 variables #' #' #' @references #' \href{http://www.fao.org/3/aq361e/aq361e.pdf}{HWSD} #' #' #' @examples #' if(interactive()){ #' data(FIGS) #' } "FIGS"
###########################################################################/** # @RdocClass Arguments # # @title "Static class to validate and process arguments" # # \description{ # @classhierarchy # } # # \section{Fields and Methods}{ # @allmethods # } # # @author # # @keyword programming #*/########################################################################### setConstructorS3("Arguments", function(...) { extend(Object(), "Arguments"); }) #########################################################################/** # @RdocMethod getFilename # # @title "Gets and validates a filename" # # \description{ # @get "title". # } # # @synopsis # # \arguments{ # \item{filename}{A @character string.} # \item{nchar}{An @integer @vector of length two specifying the range # of valid filename lengths.} # \item{class}{A @character string specifying the class of valid # filenames.} # \item{.name}{The name of the argument validated.} # \item{.type}{Not used.} # \item{...}{Not used.} # } # # \value{ # Returns a @character string if filename is valid, # otherwise an exception is thrown. # } # # \section{Missing values}{ # If \code{filename} is a missing value, then an exception is thrown. # } # # \details{ # When argument \code{class="safe"}, the following 86 ASCII characters # are allowed in filenames: # \preformatted{ # #$%&'()+,-.0123456789;= (24 including initial space) # @ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_ (31) # `abcdefghijklmnopqrstuvwxyz{|}~ (31) # } # This class of filenames has been extensively tested on for # cross-platform support on Microsoft Windows, OSX and various # Unix flavors. # } # # \references{ # [1] Microsoft, \emph{Naming Files, Paths, and Namespaces} (Section 'Windows Naming Conventions'), 2012. \url{http://msdn.microsoft.com/en-us/library/aa365247.aspx#naming_conventions}. # } # # @author # # \seealso{ # @seeclass # } #*/######################################################################### setMethodS3("getFilename", "Arguments", function(static, filename, nchar=c(1,128), class=c("safe"), .name=NULL, .type="filename", ...) { ## ## OLD NOTES: ## Valid filename characters: ## * The FTP RFCs require (7-bit) ASCII characters (and presumably not control ## characters either). The 95 printable ASCII characters are (note initial ## space): ## ## !"#$%&'()*+,-./0123456789:;<=>? (32) ## @ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_ (32) ## `abcdefghijklmnopqrstuvwxyz{|}~ (31) ## ## * On Windows the following 9 characters aren't allowed: \ / : * ? " < > !. ## This leaves us with: ## ## #$%&'()+,-.0123456789;= (24) ## @ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_ (31) ## `abcdefghijklmnopqrstuvwxyz{|}~ (31) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Validate arguments # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Argument '.name': if (is.null(.name)) { .name <- as.character(deparse(substitute(filename))); } # Argument 'filename': if (is.na(filename)) { throw("Argument 'filename' cannot be a missing value: ", filename) } filename <- getCharacter(static, filename, nchar=nchar, .name=.name); # Argument 'class': class <- match.arg(class); # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Filter out valid characters # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - chars <- filename; # Always valid characters chars <- gsub("[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0-9_.,]", "", chars); chars <- gsub("[-]", "", chars); chars <- gsub("[+]", "", chars); # Filter out according to classes. if ("safe" %in% class) { chars <- gsub("[ ]", "", chars); chars <- gsub("[\\[\\]]", "", chars); chars <- gsub("[#$%&'()`{|}~]", "", chars); chars <- gsub("[=]", "", chars); } # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Check for remaining (=invalid) characters # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if (nchar(chars, type="chars") > 0L) { chars <- unlist(strsplit(chars, split="")); chars <- sort(unique(chars)); chars <- sprintf("'%s'", chars); chars <- paste(chars, collapse=", "); throw(sprintf("Not a valid %s. Argument '%s' contains non-valid %s characters (%s): %s", .type, .name, .type, chars, filename)); } filename; }, static=TRUE, private=TRUE) #########################################################################/** # @RdocMethod getReadablePathname # # @title "Gets a readable pathname" # # \description{ # @get "title". # } # # @synopsis # # \arguments{ # \item{file}{A @character string specifying the file.} # \item{path}{A @character string specifying the path.} # \item{mustExist}{If @TRUE, the pathname must exists and be readable, # otherwise an exception is thrown. If @FALSE, no such test is # performed.} # \item{absolutePath}{If @TRUE, the absolute pathname is returned.} # \item{...}{Not used.} # } # # \value{ # Returns a @character string of the absolute pathname of the file. # } # # \section{Missing values}{ # If \code{file} or \code{path} is @NA and \code{mustExist} is @FALSE, # then (character) @NA is returned, otherwise an exception is thrown. # } # # \section{Windows}{ # If a too long pathname is detected on Windows, an informative warning # is given. # The maximum number of symbols in a Windows pathname is 256, including # file separators '/' or '\', but excluding the drive letter, and initial # file separator (e.g. 'C:/'), and the string terminator ('\\0'), cf. # 'MSDN - Naming a File or Directory', Microsoft. In R, the limit is # one symbol less, i.e. 255. # } # # @author # # \seealso{ # @seemethod "getWritablePathname" # @see "R.utils::filePath". # @seeclass # } # # @keyword IO #*/######################################################################### setMethodS3("getReadablePathname", "Arguments", function(static, file=NULL, path=NULL, mustExist=TRUE, absolutePath=FALSE, adjust=c("none", "url"), ...) { # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Validate arguments # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Argument 'file': if (!is.null(file)) { if (inherits(file, "connection")) { throw("In this context, argument 'file' cannot be a connection."); } file <- getCharacter(static, file, length=c(1,1)); } # Ignore 'path'? if (isAbsolutePath(file)) path <- NULL # Argument 'path': if (!is.null(path)) { path <- getCharacter(static, path, length=c(1,1)); } if (is.null(file) && is.null(path)) { throw("Both argument 'file' and 'path' are NULL."); } # Argument 'mustExist': mustExist <- getLogical(static, mustExist); # Argument 'absolutePath': absolutePath <- getLogical(static, absolutePath); # Argument 'adjust': adjust <- match.arg(adjust); # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Process arguments # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if (mustExist) { if (!is.null(file) && is.na(file)) { throw("No such file/directory because argument 'file' is NA."); } if (!is.null(path) && is.na(path)) { throw("No such file/directory because argument 'path' is NA."); } } # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Make sure <path>/<file> is properly split up # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if (is.null(path)) { pathname <- file; } else if (is.null(file)) { pathname <- path; } else { pathname <- file.path(path, file); } # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Windows: The maximum number of symbols in a Windows pathname is 256, # in R it's 255. For more details, see: # https://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if (.Platform$OS.type == "windows") { if (!is.na(pathname) && nchar(pathname, type="chars") > 255L) { msg <- sprintf("A too long pathname (%d characters) was detected on Windows, where maximum number of symbols is 256 and in R it is one less: %s", nchar(pathname, type="chars"), pathname); warning(msg); } } path <- dirname(pathname); file <- basename(pathname); pathname <- NULL; # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Adjust filename? # FIXME: Adjust also directory names. /HB 2014-05-04 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if (adjust == "url") { # Decode non-problematic filename characters, e.g. '%20' -> ' ' file <- URLdecode(file); # But encode problematic ones, e.g. ':', '*' file <- gsub(":", "%3A", file, fixed=TRUE) file <- gsub("*", "%2A", file, fixed=TRUE) file <- gsub("\\", "%5C", file, fixed=TRUE) # Encode tilde (~) unless first character # FIX ME: Needed or not? /HB 2014-05-04 } # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Expand links # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # NB: Here 'mustExist=TRUE' means that filePath() will always return # a pathname, not that it will give an error if file does not exist. pathname <- filePath(path, file, expandLinks="any", mustExist=TRUE); if (absolutePath) { pathname <- getAbsolutePath(pathname); } # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Windows: The maximum number of symbols in a Windows pathname is 256, # in R it's 255. For more details, see: # https://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if (.Platform$OS.type == "windows") { if (!is.na(pathname) && nchar(pathname, type="chars") > 255L) { msg <- sprintf("A too long pathname (%d characters) was detected on Windows, where maximum number of symbols is 256 and in R it is one less: %s", nchar(pathname, type="chars"), pathname); warning(msg); } } if (mustExist) { # Check if file exists if (!file.exists(pathname)) { # Locate the first parent directory that does not exist depth <- 1; while(TRUE) { parent <- getParent(pathname, depth=depth); if (is.na(parent) || is.null(parent) || isDirectory(parent)) break; depth <- depth + 1; } # while() reason <- NULL; if (is.na(parent) || is.null(parent)) { parent <- getParent(pathname); if (is.na(parent) || is.null(parent)) { reason <- "no such file in the current working directory"; } else { reason <- sprintf("none of the parent directories [%s/] exist", parent); } } else { reason <- sprintf("%s/ exists, but nothing beyond", parent); } if (!is.null(reason) && !isAbsolutePath(pathname)) { reason <- sprintf("%s; current directory is '%s'", reason, getwd()); } reason <- sprintf(" (%s)", reason); throw("Pathname not found: ", pathname, reason); } # Check if file permissions allow reading if (fileAccess(pathname, mode=4) == -1) { throw("Pathname exists, but there is no permission to read file: ", pathname); } } # if (mustExist) pathname; }, static=TRUE) setMethodS3("getReadablePath", "Arguments", function(static, path=NULL, mustExist=TRUE, ...) { if (is.null(path)) return(NULL); path <- getReadablePathname(static, path=path, mustExist=mustExist, ...); if (mustExist && !is.na(path) && !isDirectory(path)) { throw("Argument 'path' is not a directory: ", path); } path; }, static=TRUE, protected=TRUE) #########################################################################/** # @RdocMethod getReadablePathnames # # @title "Gets a readable pathname" # # \description{ # @get "title". # } # # @synopsis # # \arguments{ # \item{files}{A @character @vector of filenames.} # \item{paths}{A @character @vector of paths.} # \item{...}{Arguments passed to @seemethod "getReadablePathname".} # } # # \value{ # Returns a @character @vector of the pathnames for the files. # } # # @author # # \seealso{ # @seemethod "getReadablePathname" # @see "R.utils::filePath". # @seeclass # } # # @keyword IO #*/######################################################################### setMethodS3("getReadablePathnames", "Arguments", function(static, files=NULL, paths=NULL, ...) { nbrOfFiles <- length(files); # Argument 'paths': if (length(paths) > nbrOfFiles) { throw("Argument 'paths' is longer than argument 'files': ", length(paths), " > ", nbrOfFiles); } # Expand argument 'paths' to be of same length as 'files' if (!is.null(paths)) { paths <- rep(paths, length.out=nbrOfFiles); } pathnames <- list(); for (kk in seq(length=nbrOfFiles)) { pathnames[[kk]] <- getReadablePathname(static, files[kk], path=paths[kk], ...); } unlist(pathnames); }, static=TRUE) #########################################################################/** # @RdocMethod getWritablePathname # # @title "Gets a writable pathname" # # \description{ # @get "title". # } # # @synopsis # # \arguments{ # \item{...}{Arguments passed to @seemethod "getReadablePathname".} # \item{mustExist}{If @TRUE and the pathname does not exists, # an Exception is thrown, otherwise not.} # \item{mustNotExist}{If the file exists, and \code{mustNotExist} is # @TRUE, an Exception is thrown. If the file exists, and # \code{mustNotExist} is @FALSE, or the file does not exists, the # pathname is accepted.} # \item{mkdirs}{If @TRUE, \code{mustNotExist} is @FALSE, and the path to # the file does not exist, it is (recursively) created.} # \item{maxTries}{A positive @integer specifying how many times the # method should try to create a missing directory before giving up. # For more details, see @see "R.utils::mkdirs".} # } # # \value{ # Returns a @character string of the pathname of the file. # If the argument was invalid an @see "R.oo::Exception" is thrown. # } # # \section{Missing values}{ # If any argument in \code{...} is @NA, an exception is thrown. # } # # @author # # \seealso{ # @seemethod "getReadablePathname". # @see "R.utils::filePath". # @see "R.utils::mkdirs". # @seeclass # } # # @keyword IO #*/######################################################################### setMethodS3("getWritablePathname", "Arguments", function(static, ..., mustExist=FALSE, mustNotExist=FALSE, mkdirs=TRUE, maxTries=5L) { # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Validate arguments # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Argument 'mustExist': mustExist <- getLogical(static, mustExist); # Argument 'mustNotExist': mustNotExist <- getLogical(static, mustNotExist); # Argument 'mkdirs': mkdirs <- getLogical(static, mkdirs); # Create pathname pathname <- getReadablePathname(static, ..., mustExist=mustExist); if (is.na(pathname)) { throw("Cannot retrieve writable file/directory because it is NA."); } if (isFile(pathname)) { # Check if it is ok that the file already exists if (mustNotExist) { throw("File already exists: ", pathname); } # Check if file permissions allow to modify existing if (fileAccess(pathname, mode=2) == -1) { throw("No permission to modify existing file: ", pathname); } } else { # Check if directory exists path <- getParent(pathname); if (!isDirectory(path)) { # Does the directory have to exists (mkdirs=FALSE)? if (!mkdirs) { path <- getReadablePath(static, path, mustExist=TRUE); } # If not, first try to create the parent directory, iff missing. # This should give a more informative error message, if it fails. pathP <- getParent(path); createParent <- !isDirectory(pathP); if (createParent) { pathnameP <- getWritablePathname(static, file="dummy-not-tested", path=pathP, mustExist=FALSE, mustNotExist=FALSE, mkdirs=TRUE, maxTries=maxTries); } # Try to create the directory mkdirs(path, mustWork=TRUE, maxTries=maxTries) } filename <- basename(pathname); if (filename != "dummy-not-tested") { # Check if file permissions allow to create a file in the directory pathT <- ifelse(is.null(path), ".", path); if (fileAccess(pathT, mode=2) == -1) { throw("No write permission for directory: ", path); } # Try to create a file filenameT <- basename(tempfile()); pathnameT <- filePath(path, filenameT); on.exit({ if (isFile(pathnameT)) { # Try to remove the temporary file res <- FALSE; suppressWarnings({ for (tt in 1:maxTries) { res <- file.remove(pathnameT); if (res) break; # If not, wait a bit and try again... Sys.sleep(0.5); } }) if (!res) { warning("Failed to remove temporary file: ", sQuote(pathnameT)); } } }, add=TRUE); tryCatch({ cat(file=pathnameT, Sys.time()); }, error = function(ex) { throw("No permission to create a new file in directory: ", path); }); } # if (filename != "dummy-not-tested") } # if (isFile(pathname)) pathname; }, static=TRUE) setMethodS3("getWritablePath", "Arguments", function(static, path=NULL, ...) { # Special case: If path == NULL, the skip if (is.null(path)) return(NULL); pathname <- getWritablePathname(static, file="dummy-not-created", path=path, ...); getParent(pathname); }, static=TRUE, protected=TRUE) setMethodS3("getDirectory", "Arguments", function(static, path=NULL, ..., mustExist=FALSE, mkdirs=TRUE) { # Argument 'mustExist': mustExist <- getLogical(static, mustExist); # Argument 'mkdirs': mkdirs <- getLogical(static, mkdirs); # Create pathname pathname <- getReadablePathname(static, path=path, ..., mustExist=mustExist); if (is.na(pathname)) { throw("Cannot retrieve directory because it is NA."); } # Nothing to do? if (isDirectory(pathname)) { return(pathname); } if (!mkdirs) { throw("Directory does not exist: ", pathname); } mkdirs(pathname, mustWork=TRUE) pathname; }, static=TRUE, protected=TRUE) #########################################################################/** # @RdocMethod getVector # # @title "Validates a vector" # # \description{ # @get "title" by checking its length (number of elements). # } # # @synopsis # # \arguments{ # \item{x}{A single @vector.} # \item{length}{A @numeric @vector of length two or more. If two, it # is the minimum and maximum length of \code{x}. Elsewise it is the # set of possible lengths of \code{x}.} # \item{.name}{A @character string for name used in error messages.} # \item{...}{Not used.} # } # # \value{ # Returns the same @vector, if it is valid. Otherwise an exception is # thrown. # } # # @author # # \seealso{ # @seeclass # } # # @keyword IO #*/######################################################################### setMethodS3("getVector", "Arguments", function(static, x, length=NULL, .name=NULL, ...) { if (length(length) == 0) return(x); if (is.null(.name)) .name <- as.character(deparse(substitute(x))); # See ?is.vector for how it is defined. /HB 2009-05-19 attrs <- attributes(x); attributes(x) <- attrs[intersect(names(attrs), c("names", "dim"))]; if (length[1] > 0 && !is.vector(x)) { throw(sprintf("Argument '%s' is not a vector: %s", .name, storage.mode(x))); } xlen <- length(x); if (length(length) == 1) length <- c(1,length); if (length(length) == 2) { if (xlen < length[1] || xlen > length[2]) { if (length[1] == length[2] && length[1] == 1) { throw(sprintf("Argument '%s' should be a single value not %d values.", .name, xlen)); } else if (length[1] == length[2]) { throw(sprintf("Number of elements in argument '%s' should be exactly %d not %d value(s).", .name, length[1], xlen)); } else { throw(sprintf("Number of elements in argument '%s' is out of range [%d,%d]: %d", .name, length[1], length[2], xlen)); } } } else { if (!is.element(xlen, length)) { throw(sprintf("Number of elements in argument '%s' is not in {%s}: %d", .name, seqToHumanReadable(length), xlen, )); } } attributes(x) <- attrs; x; }, static=TRUE, private=TRUE) #########################################################################/** # @RdocMethod getCharacters # @aliasmethod getCharacter # # @title "Coerces to a character vector and validates" # # \description{ # @get "title". # } # # @synopsis # # \arguments{ # \item{s}{A @vector.} # \item{nchar}{A @numeric @vector of length one or two. If one, # the maximum number of characters ("length") in \code{s}. If two, # the minimum and maximum length of \code{s}.} # \item{useNames}{If @TRUE, the 'names' attribute is preserved, otherwise # it is dropped.} # \item{asGString}{If @TRUE, each string is treated as a @see "GString".} # \item{.name}{A @character string for name used in error messages.} # \item{...}{Not used.} # } # # \value{ # Returns a @character @vector, if it is valid. Otherwise an exception is # thrown. # } # # \section{Missing values}{ # If \code{s} contains missing values, and \code{nchar} is not @NULL, # then an exception is thrown. # } # # @author # # \seealso{ # @seeclass # } # # @keyword IO #*/######################################################################### setMethodS3("getCharacters", "Arguments", function(static, s, length=NULL, trim=FALSE, nchar=NULL, useNames=TRUE, asGString=getOption("Arguments$getCharacters/args/asGString", TRUE), .name=NULL, ...) { if (is.null(.name)) .name <- as.character(deparse(substitute(s))); s <- getVector(static, s, length=length, .name=.name); # Nothing to check? if (length(s) == 0L) return(s); # Coerce GString:s to character strings? if (asGString) { # Treat only strings with GString markup. This avoids lots of # GString overhead if there are no GStrings. hasMarkup <- (regexpr("${", s, fixed=TRUE) != -1); idxs <- which(hasMarkup & !is.na(s)); s[idxs] <- unlist(lapply(s[idxs], FUN=function(x) { x <- GString(x); as.character(x); }), use.names=FALSE); } if (trim) { # Trim the strings # (using s[] to preserve attributes) s[] <- unlist(lapply(s, FUN=trim), use.names=FALSE); } # Coerce to character strings # (using s[] to preserve attributes) s[] <- unlist(lapply(s, FUN=as.character), use.names=FALSE); if (!useNames) { names(s) <- NULL; } # Nothing to check? if (is.null(nchar)) return(s); # At this point, missing values are not allowed if (any(is.na(s))) { throw("Argument 'nchar' cannot be specified if character vector contains missing values: ", hpaste(sQuote(s))) } if (length(nchar) == 1L) nchar <- c(1L, nchar); # Check the string length of each character string for (kk in seq(length=length(s))) { slen <- nchar(s[kk], type="chars"); if (slen < nchar[1L] || slen > nchar[2L]) { throw(sprintf("String length of elements #%d in '%s' is out of range [%d,%d]: %d '%s'", kk, .name, nchar[1L], nchar[2L], slen, s[kk])); } } s; }, static=TRUE) setMethodS3("getCharacter", "Arguments", function(static, ..., length=c(0,1)) { getCharacters(static, ..., length=length); }, static=TRUE) #########################################################################/** # @RdocMethod getNumerics # @aliasmethod getNumeric # # @title "Coerces to a numeric vector and validates" # # \description{ # @get "title". # } # # @synopsis # # \arguments{ # \item{x}{A @vector.} # \item{range}{Two @numerics for the allowed ranged. If @NULL, range is # not checked.} # \item{asMode}{A @character specifying the mode to coerce to.} # \item{disallow}{A @character @vector specifying diallowed value sets, # i.e. \code{"NA"}, \code{"NaN"}, and/or \code{"Inf"}.} # \item{...}{Arguments passed to @method "getVector".} # \item{.name}{A @character string for name used in error messages.} # } # # \value{ # Returns a @numeric @vector. # } # # @author # # \seealso{ # @seeclass # } # # @keyword IO #*/######################################################################### setMethodS3("getNumerics", "Arguments", function(static, x, range=NULL, asMode=NULL, disallow=NULL, ..., .name=NULL) { # Argument '.name': if (is.null(.name)) { .name <- as.character(deparse(substitute(x))); } x <- getVector(static, x, ..., .name=.name); xMode <- storage.mode(x); # Coerce the mode of 'x' if (is.null(asMode)) { if (is.element(xMode, c("integer", "double"))) { asMode <- xMode; } else { asMode <- "double"; } } # Update/coerce mode? if (xMode != asMode) { storage.mode(x) <- asMode; } # Nothing to do? if (length(x) == 0) return(x); if (!is.null(disallow)) { if (is.element("NaN", disallow) && any(is.nan(x))) { throw(sprintf("Argument '%s' contains %d NaN value(s).", .name, sum(is.nan(x)))); } if (is.element("NA", disallow) && any(is.na(x) & !is.nan(x))) { throw(sprintf("Argument '%s' contains %d NA value(s).", .name, sum(is.na(x)))); } # For conveniency, disallow 'Inf' here too; other range takes care of it. if (is.element("Inf", disallow) && any(is.infinite(x))) { throw(sprintf("Argument '%s' contains %d (-/+)Inf value(s).", .name, sum(is.infinite(x)))); } } # Nothing to check? if (is.null(range)) return(x); # Argument 'range': if (length(range) != 2) { throw("Argument 'range' should be of length 2: ", length(range)); } if (range[2] < range[1]) { throw(sprintf("Argument 'range' is not ordered: c(%s,%s)", range[1], range[2])); } # Suppress warnings when there are no finite values in x. suppressWarnings({ xrange <- range(x, na.rm=TRUE); }) if (xrange[1] < range[1] || xrange[2] > range[2]) { xrange <- as.character(xrange); range <- as.character(range); if (length(x) == 1) { throw(sprintf("Argument '%s' is out of range [%s,%s]: %s", .name, range[1], range[2], x)); } else { throw(sprintf("Range of argument '%s' is out of range [%s,%s]: [%s,%s]", .name, range[1], range[2], xrange[1], xrange[2])); } } x; }, static=TRUE) setMethodS3("getNumeric", "Arguments", function(static, ..., length=1) { getNumerics(static, ..., length=length); }, static=TRUE) #########################################################################/** # @RdocMethod getDoubles # @aliasmethod getDouble # # @title "Coerces to a double vector and validates" # # \description{ # @get "title". # } # # @synopsis # # \arguments{ # \item{...}{Arguments passed to @method "getNumeric".} # \item{disallow}{Disallowed values. See @method "getNumerics" for details.} # } # # \value{ # Returns a @double @vector. # } # # @author # # \seealso{ # @seeclass # } # # @keyword IO #*/######################################################################### setMethodS3("getDoubles", "Arguments", function(static, ..., disallow=c("NA","NaN")) { getNumerics(static, ..., asMode="double", disallow=disallow); }, static=TRUE) setMethodS3("getDouble", "Arguments", function(static, ..., length=1) { getDoubles(static, ..., length=length); }, static=TRUE) #########################################################################/** # @RdocMethod getIntegers # @aliasmethod getInteger # # @title "Coerces to a integer vector and validates" # # \description{ # @get "title". # } # # @synopsis # # \arguments{ # \item{...}{Arguments passed to @method "getNumeric".} # \item{disallow}{Disallowed values. See @method "getNumerics" for details.} # } # # \value{ # Returns a @integer @vector. # } # # @author # # \seealso{ # @seeclass # } # # @keyword IO #*/######################################################################### setMethodS3("getIntegers", "Arguments", function(static, ..., disallow=c("NA","NaN")) { getNumerics(static, ..., asMode="integer", disallow=disallow); }, static=TRUE) setMethodS3("getInteger", "Arguments", function(static, ..., length=1) { getIntegers(static, ..., length=length); }, static=TRUE) #########################################################################/** # @RdocMethod getIndices # @aliasmethod getIndex # # @title "Coerces to a integer vector and validates" # # \description{ # @get "title". # } # # @synopsis # # \arguments{ # \item{x}{A single @vector. If @logical, @see "base::which" is used.} # \item{...}{Arguments passed to @method "getIntegers".} # \item{range}{Allowed range. See @method "getNumerics" for details.} # \item{max}{The maximum of the default range.} # \item{.name}{A @character string for name used in error messages.} # } # # \value{ # Returns an @integer @vector. # } # # @author # # \seealso{ # @seeclass # } # # @keyword IO #*/######################################################################### setMethodS3("getIndices", "Arguments", function(static, x, ..., max=Inf, range=c(1*(max > 0L),max), .name=NULL) { if (is.null(.name)) .name <- as.character(deparse(substitute(x))); # Argument 'x': if (is.logical(x)) { x <- which(x); } # Argument 'max': if (length(max) != 1) { throw("Argument 'max' must be a single value: ", length(max)); } max <- as.numeric(max); if (is.na(max)) { throw("Argument 'max' is NA/NaN: ", max); } else if (max < 0) { throw("Argument 'max' must be positive: ", max); } # Argument 'range': if (!is.null(range)) { if (length(range) != 2) { throw("Argument 'range' should be of length 2: ", length(range)); } if (range[2] < range[1]) { throw(sprintf("Argument 'range' is not ordered: c(%s,%s)", range[1], range[2])); } } # Identify indices x <- getIntegers(static, x, ..., range=range, .name=.name); # Special dealing with range = c(0,0) if (!is.null(range)) { if (range[2] < 1L) { xt <- x[is.finite(x)]; if (length(xt) > 0) { throw(sprintf("Argument 'x' contains %d non-missing indices although the range ([%s,%s]) implies that there should be none.", length(xt), range[1L], range[2L])); } } } x; }, static=TRUE) setMethodS3("getIndex", "Arguments", function(static, ..., length=1) { getIndices(static, ..., length=length); }, static=TRUE) #########################################################################/** # @RdocMethod getLogicals # @aliasmethod getLogical # # @title "Coerces to a logical vector and validates" # # \description{ # @get "title". # } # # @synopsis # # \arguments{ # \item{x}{A @vector.} # \item{disallow}{A @character @vector specifying diallowed value sets # after coercing, i.e. \code{"NA"}.} # \item{...}{Arguments passed to @method "getVector".} # \item{.name}{A @character string for name used in error messages.} # } # # \value{ # Returns a @numeric @vector. # } # # @author # # \seealso{ # @seeclass # } # # @keyword IO #*/######################################################################### setMethodS3("getLogicals", "Arguments", function(static, x, ..., disallow=c("NA", "NaN"), coerce=FALSE, .name=NULL) { if (is.null(.name)) .name <- as.character(deparse(substitute(x))); x <- getVector(static, x, ..., .name=.name); # Coerce to logicals? if (coerce) x <- as.logical(x); if (!is.null(disallow)) { if (is.element("NA", disallow) && any(is.na(x))) { throw(sprintf("Argument '%s' contains %d NA value(s).", .name, sum(is.na(x)))); } } # Assert that 'x' is logical before returning if (any(!is.logical(x))) throw(sprintf("Argument '%s' is non-logical: %s", .name, class(x))); x; }, static=TRUE) setMethodS3("getLogical", "Arguments", function(static, ..., length=1) { getLogicals(static, ..., length=length); }, static=TRUE) #########################################################################/** # @RdocMethod getVerbose # # @title "Coerces to Verbose object" # # \description{ # @get "title". # } # # @synopsis # # \arguments{ # \item{verbose}{A single object. If a @see "Verbose", it is immediately # returned. If a @numeric value, it is used as the threshold. # Otherwise the object is coerced to a @logical value and if @TRUE, # the threshold is \code{defaultThreshold}.} # \item{defaultThreshold}{A @numeric value for the default threshold, if # \code{verbose} was interpreted as a @logical value.} # \item{useNullVerbose}{If \code{verbose} can be interpreted as @FALSE, # return a @see NullVerbose object if @TRUE.} # \item{...}{Passed to the constructor of @see "Verbose".} # \item{.name}{A @character string for name used in error messages.} # } # # \value{ # Returns a @see Verbose (or a @see "NullVerbose") object. # } # # @author # # \seealso{ # @seeclass # } # # @keyword IO #*/######################################################################### setMethodS3("getVerbose", "Arguments", function(static, verbose, defaultThreshold=-1, useNullVerbose=TRUE, ..., .name=NULL) { if (inherits(verbose, "Verbose")) return(verbose); if (is.null(.name)) .name <- as.character(deparse(substitute(verbose))); if (is.numeric(verbose)) { verbose <- getDouble(static, verbose, .name=.name); verbose <- Verbose(threshold=verbose, ...); } else { verbose <- getLogical(static, verbose, .name=.name); if (!verbose && useNullVerbose) { verbose <- NullVerbose(); } else { defaultThreshold <- getNumeric(static, defaultThreshold); verbose <- Verbose(threshold=defaultThreshold, ...); } } verbose; }, static=TRUE) #########################################################################/** # @RdocMethod getRegularExpression # # @title "Gets a valid regular expression pattern" # # \description{ # @get "title". # } # # @synopsis # # \arguments{ # \item{pattern}{A @character string to be validated.} # \item{.name}{A @character string for name used in error messages.} # \item{...}{Not used.} # } # # \value{ # Returns a @character string. # } # # @author # # \seealso{ # @see "base::grep". # @seeclass # } # # @keyword IO #*/######################################################################### setMethodS3("getRegularExpression", "Arguments", function(static, pattern=NULL, ..., .name=NULL) { if (is.null(.name)) { .name <- as.character(deparse(substitute(pattern))); } if (is.null(pattern)) { throw(sprintf("Argument '%s' is not a valid regular expression: NULL", .name)); } pattern <- getCharacter(static, pattern, .name=.name, length=c(1,1)); # Validate it tryCatch({ regexpr(pattern, "dummy string", ...); }, error = function(ex) { throw(sprintf("Argument '%s' is not a valid regular expression: %s. Error message from regexpr() was: %s", .name, pattern, ex$message)); }) pattern; }, static=TRUE) #########################################################################/** # @RdocMethod getEnvironment # # @title "Gets an existing environment" # # \description{ # @get "title". # } # # @synopsis # # \arguments{ # \item{envir}{An @environment, the name of a loaded package, or @NULL. # If @NULL, the global environment is returned.} # \item{.name}{A @character string for name used in error messages.} # \item{...}{Not used.} # } # # \value{ # Returns an @environment. # } # # @author # # \seealso{ # @seeclass # } # # @keyword IO #*/######################################################################### setMethodS3("getEnvironment", "Arguments", function(static, envir=NULL, .name=NULL, ...) { if (is.null(.name)) .name <- as.character(deparse(substitute(envir))); if (is.null(envir)) { return(.GlobalEnv); } if (is.character(envir)) { name <- getCharacter(static, envir, length=c(1,1)); envirs <- gsub("^package:", "", search()); pos <- which(name == envirs); if (length(pos) == 0) throw("Argument 'envir' is not the name of a loaded package: ", envir); envir <- pos.to.env(pos); } if (!is.environment(envir)) { throw(sprintf("Argument '%s' is not an environment: %s", .name, class(envir)[1])); } }, static=TRUE) #########################################################################/** # @RdocMethod getInstanceOf # # @title "Gets an instance of the object that is of a particular class" # # \description{ # @get "title". # } # # @synopsis # # \arguments{ # \item{object}{The object that should be returned as an instance of # class \code{class}.} # \item{class}{A @character string specifying the name of the class that # the returned object should inherit from.} # \item{coerce}{If @TRUE and the object is not of the wanted class, then # method will be coerced to that class, if possible. Otherwise, # an error is thrown.} # \item{...}{Not used.} # \item{.name}{A @character string for name used in error messages.} # } # # \value{ # Returns an object inheriting from class \code{class}. # } # # @author # # \seealso{ # @seeclass # } # # @keyword programming #*/######################################################################### setMethodS3("getInstanceOf", "Arguments", function(static, object, class, coerce=FALSE, ..., .name=NULL) { if (is.null(.name)) { .name <- as.character(deparse(substitute(object))); } # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Validate arguments # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Argument 'class': class <- getCharacter(static, class); # Argument 'coerce': coerce <- getLogical(static, coerce); # Argument 'object': if (!inherits(object, class)) { if (coerce) { object <- as(object, class, ...); } else { throw(sprintf("Argument '%s' is neither of nor inherits class %s: %s", .name, class[1], paste(class(object), collapse=", "))); } } # Return the object object; }, static=TRUE, protected=TRUE) withoutGString <- function(..., envir=parent.frame()) { # Temporarily disable 'asGString' for Arguments$getCharacters() oopts <- options("Arguments$getCharacters/args/asGString"=FALSE); on.exit(options(oopts)); eval(..., envir=envir); } # withoutGString() ############################################################################ # HISTORY: # 2015-02-05 # o Now getReadablePathname() warns about too long pathnames on Windows. # 2014-10-03 # o Now Arguments$getReadablePathname(file, path) ignores 'path' if # 'file' specifies an absolute pathname. # 2014-05-04 # o Added argument 'adjust' to Arguments$getReadablePathname(). # 2014-01-12 # o Made argument 'useNames' to getCharacters() default to TRUE. # o Now Arguments$getCharacters() preserves attributes. # 2013-12-15 # o Added withoutGString(). # 2013-12-13 # o Now argument 'asGString' for Arguments$getCharacters() defaults to # getOption("Arguments$getCharacters/args/asGString", TRUE). This makes # it possible to disable this feature, even when it is not possible to # directly pass that argument. This will also make it possible to # set the default to FALSE in the future (instead of TRUE as today). # 2013-11-15 # o CLEANUP: Arguments$getNumerics(NA, range=c(0,1)) no longer gives # warnings on "no non-missing arguments to min()" etc. # 2013-08-26 # o CLEANUP: Arguments$getReadablePathnames(files, paths=NULL) no longer # warns about "rep(paths, length.out = nbrOfFiles) : 'x' is NULL so # the result will be NULL" if length(files) > 0. # 2012-12-01 # o BUG FIX: Arguments$getIndices(NA_integer_, max=0, disallow="NaN") # would give "Exception: Argument 'x' is of length 1 although the range # ([0,0]) implies that is should be empty." although it should return # NA_integer. # 2012-10-21 # o ROBUSTNESS: Added argument 'maxTries' to Arguments$getWritablePathname() # to have the method try to create missing directories multiple times # before giving up. # 2012-10-16 # o Moved Arguments$getFilename() from R.filesets to R.utils. # Added Rd help. # 2012-09-24 # o BUG FIX: Arguments$getReadablePath(..., mustExist=FALSE) did not work. # 2011-11-15 # o SPEEDUP: Now Arguments$getCharacters(s, asGString=TRUE) is much # faster for elements of 's' that are non-GStrings. For long character # vectors the speedup is 100-200x times. # 2011-10-16 # o CORRECTION: Arguments$getNumerics(c(Inf), disallow="Inf") would report # that it contains "NA" instead of "Inf" values". # 2011-03-08 # o Now Arguments$getWritablePath(NULL) returns NULL without asserting # write permission, which is analogue to how it is done with # Arguments$getReadablePath(NULL). # 2010-11-19 # o TYPO: Static methods getVector() and getRegularExpression() of # Arguments would report the incorrect argument name. # 2010-01-25 # o ROBUSTNESS: Added validation of argument 'range' in Arguments methods. # 2010-01-01 # o Now Arguments$getNumerics(x) displays the value of 'x' in the error # message if it is a *single* value and out of range. # o Added argument 'max' to Arguments$getIndices(). # 2009-12-30 # o Now Arguments$getWritablePath() and Arguments$getWritablePathname() # throws an error is an NA file/directory is specified. # o Now Arguments$getReadablePath() and Arguments$getReadablePathname() # throws an error is an NA file/directory is specified, unless # 'mustExist' is FALSE. # o Added Arguments$getInstanceOf(...). # o BUG FIX: Arguments$getCharacters(s) would return a *logical* instead # of a *character* vector if 's' contained all NAs. # 2009-11-20 # o If 'x' is a logical vector, Arguments$getIndices(x) will now return # the same as if x <- which(x). # 2009-10-30 # o Now Arguments$getWritablePathname(path) validates that there is enough # file permissions so that a file can be created in the 'path' directory. # 2009-06-29 # o Added argument 'useNames=FALSE' to getCharacters() of Arguments. # Don't remember why I didn't want names in the first place (see below). # 2009-05-18 # o UPDATE: Now getWritablePathname() gives a more precise error message # if the file exists but the rights to modifies it does not. # o UPDATE: Now getEnvironment(), getRegularExpression(), and # getReadablePathname() give clearer error messages if more the input # contains more than one element. # 2009-05-15 # o Changed argument 'asMode' for Arguments$getNumerics() to default to # NULL instead of "numeric". This will case the method to return integer # if the input is integer, and double if the input is double. The # previous default was alway returning doubles, cf. notes on common # misconception of how as.numeric() works. In the case when the input # is neither integer or double, the default is to coerce to doubles. # Also, the method is now using storage.mode() instead of mode(). # 2009-04-04 # o Now getReadablePathname(..., mustExist=TRUE) of Arguments reports also # the working directory if the a relative pathname is missing. # o BUG FIX: getReadablePathname(..., mustExist=TRUE) of Arguments gave an # internal error if the pathname was in the current directory and did # not exist. # 2008-12-27 # o Now getReadablePathname(..., mustExist=TRUE) and # getWritablePathname(..., mkdirs=FALSE) of Arguments report which # of the parent directories exists when the requested pathname is not # found. This will help troubleshooting missing pathnames. # 2008-12-01 # o Now getReadablePathname() and getWritablePathname() use the more # trusted fileAccess() of R.utils. # 2008-02-26 # o Now the '...' arguments to Arguments$getVerbose() are passed to the # constructor of Verbose. This allows the construct of # Arguments$getVerbose(-10, timestamp=TRUE). # 2005-12-05 # o getNumerics(Inf, range=c(0,Inf)) would give a warning "no finite # arguments to min; returning Inf". Fixed with a withCallingHandlers(). # 2005-11-22 # o Added Rdoc comments for getReadablePathnames(). # 2005-11-13 # o Added getReadablePathnames(). # o Now getCharacter() only accept vectors of length zero or one. # 2005-10-25 # o BUG FIX: New 'mustNotExist' argument got logically the inverse. # 2005-10-21 # o Renamed argument 'overwrite' in getWritablePathname() in Arguments to # 'mustNotExist'. Renamed all 'mustExists' to 'mustExist' in all methods # of class Arguments. # 2005-09-06 # o Replace argument 'gString' of getCharacters() to 'asGString', cf. # Verbose class. # o Now Arguments$getReadablePathname() follows Windows shortcut files. # 2005-08-01 # o getReadablePathname() no longer returns the absolute pathname by # default. This is because on some systems the relative pathname can # be queried wheras the absolute one may not be access due to missing # file permissions. # o Added getEnvironment(), getRegularExpression(), # getReadablePath(), getWritablePath(). # 2005-07-19 # o BUG FIX: getCharacters() would not coerce Object:s correctly. # 2005-07-07 # o getCharacters() returned attribute 'names' too. Removed. # 2005-06-20 # o Added argument 'absolutePath' to getReadablePathname(). # 2005-06-18 # o Added static methods getVector(), getNumeric/s(), getDouble/s(), # getInteger/s(), getIndices/getIndex(), and getLogical/s(). These should # be very handy. Also added getVector(). # Not sure if getVector() should be renamed to checkLength(), and even # be moved to the Assert class. Not sure where the assert class is # heading. # 2005-05-31 # o Created from former File$validateFileAndPath(). ############################################################################
/R/Arguments.R
no_license
monoguerin/sears-routes
R
false
false
46,658
r
###########################################################################/** # @RdocClass Arguments # # @title "Static class to validate and process arguments" # # \description{ # @classhierarchy # } # # \section{Fields and Methods}{ # @allmethods # } # # @author # # @keyword programming #*/########################################################################### setConstructorS3("Arguments", function(...) { extend(Object(), "Arguments"); }) #########################################################################/** # @RdocMethod getFilename # # @title "Gets and validates a filename" # # \description{ # @get "title". # } # # @synopsis # # \arguments{ # \item{filename}{A @character string.} # \item{nchar}{An @integer @vector of length two specifying the range # of valid filename lengths.} # \item{class}{A @character string specifying the class of valid # filenames.} # \item{.name}{The name of the argument validated.} # \item{.type}{Not used.} # \item{...}{Not used.} # } # # \value{ # Returns a @character string if filename is valid, # otherwise an exception is thrown. # } # # \section{Missing values}{ # If \code{filename} is a missing value, then an exception is thrown. # } # # \details{ # When argument \code{class="safe"}, the following 86 ASCII characters # are allowed in filenames: # \preformatted{ # #$%&'()+,-.0123456789;= (24 including initial space) # @ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_ (31) # `abcdefghijklmnopqrstuvwxyz{|}~ (31) # } # This class of filenames has been extensively tested on for # cross-platform support on Microsoft Windows, OSX and various # Unix flavors. # } # # \references{ # [1] Microsoft, \emph{Naming Files, Paths, and Namespaces} (Section 'Windows Naming Conventions'), 2012. \url{http://msdn.microsoft.com/en-us/library/aa365247.aspx#naming_conventions}. # } # # @author # # \seealso{ # @seeclass # } #*/######################################################################### setMethodS3("getFilename", "Arguments", function(static, filename, nchar=c(1,128), class=c("safe"), .name=NULL, .type="filename", ...) { ## ## OLD NOTES: ## Valid filename characters: ## * The FTP RFCs require (7-bit) ASCII characters (and presumably not control ## characters either). The 95 printable ASCII characters are (note initial ## space): ## ## !"#$%&'()*+,-./0123456789:;<=>? (32) ## @ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_ (32) ## `abcdefghijklmnopqrstuvwxyz{|}~ (31) ## ## * On Windows the following 9 characters aren't allowed: \ / : * ? " < > !. ## This leaves us with: ## ## #$%&'()+,-.0123456789;= (24) ## @ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_ (31) ## `abcdefghijklmnopqrstuvwxyz{|}~ (31) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Validate arguments # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Argument '.name': if (is.null(.name)) { .name <- as.character(deparse(substitute(filename))); } # Argument 'filename': if (is.na(filename)) { throw("Argument 'filename' cannot be a missing value: ", filename) } filename <- getCharacter(static, filename, nchar=nchar, .name=.name); # Argument 'class': class <- match.arg(class); # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Filter out valid characters # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - chars <- filename; # Always valid characters chars <- gsub("[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0-9_.,]", "", chars); chars <- gsub("[-]", "", chars); chars <- gsub("[+]", "", chars); # Filter out according to classes. if ("safe" %in% class) { chars <- gsub("[ ]", "", chars); chars <- gsub("[\\[\\]]", "", chars); chars <- gsub("[#$%&'()`{|}~]", "", chars); chars <- gsub("[=]", "", chars); } # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Check for remaining (=invalid) characters # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if (nchar(chars, type="chars") > 0L) { chars <- unlist(strsplit(chars, split="")); chars <- sort(unique(chars)); chars <- sprintf("'%s'", chars); chars <- paste(chars, collapse=", "); throw(sprintf("Not a valid %s. Argument '%s' contains non-valid %s characters (%s): %s", .type, .name, .type, chars, filename)); } filename; }, static=TRUE, private=TRUE) #########################################################################/** # @RdocMethod getReadablePathname # # @title "Gets a readable pathname" # # \description{ # @get "title". # } # # @synopsis # # \arguments{ # \item{file}{A @character string specifying the file.} # \item{path}{A @character string specifying the path.} # \item{mustExist}{If @TRUE, the pathname must exists and be readable, # otherwise an exception is thrown. If @FALSE, no such test is # performed.} # \item{absolutePath}{If @TRUE, the absolute pathname is returned.} # \item{...}{Not used.} # } # # \value{ # Returns a @character string of the absolute pathname of the file. # } # # \section{Missing values}{ # If \code{file} or \code{path} is @NA and \code{mustExist} is @FALSE, # then (character) @NA is returned, otherwise an exception is thrown. # } # # \section{Windows}{ # If a too long pathname is detected on Windows, an informative warning # is given. # The maximum number of symbols in a Windows pathname is 256, including # file separators '/' or '\', but excluding the drive letter, and initial # file separator (e.g. 'C:/'), and the string terminator ('\\0'), cf. # 'MSDN - Naming a File or Directory', Microsoft. In R, the limit is # one symbol less, i.e. 255. # } # # @author # # \seealso{ # @seemethod "getWritablePathname" # @see "R.utils::filePath". # @seeclass # } # # @keyword IO #*/######################################################################### setMethodS3("getReadablePathname", "Arguments", function(static, file=NULL, path=NULL, mustExist=TRUE, absolutePath=FALSE, adjust=c("none", "url"), ...) { # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Validate arguments # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Argument 'file': if (!is.null(file)) { if (inherits(file, "connection")) { throw("In this context, argument 'file' cannot be a connection."); } file <- getCharacter(static, file, length=c(1,1)); } # Ignore 'path'? if (isAbsolutePath(file)) path <- NULL # Argument 'path': if (!is.null(path)) { path <- getCharacter(static, path, length=c(1,1)); } if (is.null(file) && is.null(path)) { throw("Both argument 'file' and 'path' are NULL."); } # Argument 'mustExist': mustExist <- getLogical(static, mustExist); # Argument 'absolutePath': absolutePath <- getLogical(static, absolutePath); # Argument 'adjust': adjust <- match.arg(adjust); # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Process arguments # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if (mustExist) { if (!is.null(file) && is.na(file)) { throw("No such file/directory because argument 'file' is NA."); } if (!is.null(path) && is.na(path)) { throw("No such file/directory because argument 'path' is NA."); } } # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Make sure <path>/<file> is properly split up # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if (is.null(path)) { pathname <- file; } else if (is.null(file)) { pathname <- path; } else { pathname <- file.path(path, file); } # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Windows: The maximum number of symbols in a Windows pathname is 256, # in R it's 255. For more details, see: # https://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if (.Platform$OS.type == "windows") { if (!is.na(pathname) && nchar(pathname, type="chars") > 255L) { msg <- sprintf("A too long pathname (%d characters) was detected on Windows, where maximum number of symbols is 256 and in R it is one less: %s", nchar(pathname, type="chars"), pathname); warning(msg); } } path <- dirname(pathname); file <- basename(pathname); pathname <- NULL; # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Adjust filename? # FIXME: Adjust also directory names. /HB 2014-05-04 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if (adjust == "url") { # Decode non-problematic filename characters, e.g. '%20' -> ' ' file <- URLdecode(file); # But encode problematic ones, e.g. ':', '*' file <- gsub(":", "%3A", file, fixed=TRUE) file <- gsub("*", "%2A", file, fixed=TRUE) file <- gsub("\\", "%5C", file, fixed=TRUE) # Encode tilde (~) unless first character # FIX ME: Needed or not? /HB 2014-05-04 } # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Expand links # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # NB: Here 'mustExist=TRUE' means that filePath() will always return # a pathname, not that it will give an error if file does not exist. pathname <- filePath(path, file, expandLinks="any", mustExist=TRUE); if (absolutePath) { pathname <- getAbsolutePath(pathname); } # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Windows: The maximum number of symbols in a Windows pathname is 256, # in R it's 255. For more details, see: # https://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if (.Platform$OS.type == "windows") { if (!is.na(pathname) && nchar(pathname, type="chars") > 255L) { msg <- sprintf("A too long pathname (%d characters) was detected on Windows, where maximum number of symbols is 256 and in R it is one less: %s", nchar(pathname, type="chars"), pathname); warning(msg); } } if (mustExist) { # Check if file exists if (!file.exists(pathname)) { # Locate the first parent directory that does not exist depth <- 1; while(TRUE) { parent <- getParent(pathname, depth=depth); if (is.na(parent) || is.null(parent) || isDirectory(parent)) break; depth <- depth + 1; } # while() reason <- NULL; if (is.na(parent) || is.null(parent)) { parent <- getParent(pathname); if (is.na(parent) || is.null(parent)) { reason <- "no such file in the current working directory"; } else { reason <- sprintf("none of the parent directories [%s/] exist", parent); } } else { reason <- sprintf("%s/ exists, but nothing beyond", parent); } if (!is.null(reason) && !isAbsolutePath(pathname)) { reason <- sprintf("%s; current directory is '%s'", reason, getwd()); } reason <- sprintf(" (%s)", reason); throw("Pathname not found: ", pathname, reason); } # Check if file permissions allow reading if (fileAccess(pathname, mode=4) == -1) { throw("Pathname exists, but there is no permission to read file: ", pathname); } } # if (mustExist) pathname; }, static=TRUE) setMethodS3("getReadablePath", "Arguments", function(static, path=NULL, mustExist=TRUE, ...) { if (is.null(path)) return(NULL); path <- getReadablePathname(static, path=path, mustExist=mustExist, ...); if (mustExist && !is.na(path) && !isDirectory(path)) { throw("Argument 'path' is not a directory: ", path); } path; }, static=TRUE, protected=TRUE) #########################################################################/** # @RdocMethod getReadablePathnames # # @title "Gets a readable pathname" # # \description{ # @get "title". # } # # @synopsis # # \arguments{ # \item{files}{A @character @vector of filenames.} # \item{paths}{A @character @vector of paths.} # \item{...}{Arguments passed to @seemethod "getReadablePathname".} # } # # \value{ # Returns a @character @vector of the pathnames for the files. # } # # @author # # \seealso{ # @seemethod "getReadablePathname" # @see "R.utils::filePath". # @seeclass # } # # @keyword IO #*/######################################################################### setMethodS3("getReadablePathnames", "Arguments", function(static, files=NULL, paths=NULL, ...) { nbrOfFiles <- length(files); # Argument 'paths': if (length(paths) > nbrOfFiles) { throw("Argument 'paths' is longer than argument 'files': ", length(paths), " > ", nbrOfFiles); } # Expand argument 'paths' to be of same length as 'files' if (!is.null(paths)) { paths <- rep(paths, length.out=nbrOfFiles); } pathnames <- list(); for (kk in seq(length=nbrOfFiles)) { pathnames[[kk]] <- getReadablePathname(static, files[kk], path=paths[kk], ...); } unlist(pathnames); }, static=TRUE) #########################################################################/** # @RdocMethod getWritablePathname # # @title "Gets a writable pathname" # # \description{ # @get "title". # } # # @synopsis # # \arguments{ # \item{...}{Arguments passed to @seemethod "getReadablePathname".} # \item{mustExist}{If @TRUE and the pathname does not exists, # an Exception is thrown, otherwise not.} # \item{mustNotExist}{If the file exists, and \code{mustNotExist} is # @TRUE, an Exception is thrown. If the file exists, and # \code{mustNotExist} is @FALSE, or the file does not exists, the # pathname is accepted.} # \item{mkdirs}{If @TRUE, \code{mustNotExist} is @FALSE, and the path to # the file does not exist, it is (recursively) created.} # \item{maxTries}{A positive @integer specifying how many times the # method should try to create a missing directory before giving up. # For more details, see @see "R.utils::mkdirs".} # } # # \value{ # Returns a @character string of the pathname of the file. # If the argument was invalid an @see "R.oo::Exception" is thrown. # } # # \section{Missing values}{ # If any argument in \code{...} is @NA, an exception is thrown. # } # # @author # # \seealso{ # @seemethod "getReadablePathname". # @see "R.utils::filePath". # @see "R.utils::mkdirs". # @seeclass # } # # @keyword IO #*/######################################################################### setMethodS3("getWritablePathname", "Arguments", function(static, ..., mustExist=FALSE, mustNotExist=FALSE, mkdirs=TRUE, maxTries=5L) { # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Validate arguments # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Argument 'mustExist': mustExist <- getLogical(static, mustExist); # Argument 'mustNotExist': mustNotExist <- getLogical(static, mustNotExist); # Argument 'mkdirs': mkdirs <- getLogical(static, mkdirs); # Create pathname pathname <- getReadablePathname(static, ..., mustExist=mustExist); if (is.na(pathname)) { throw("Cannot retrieve writable file/directory because it is NA."); } if (isFile(pathname)) { # Check if it is ok that the file already exists if (mustNotExist) { throw("File already exists: ", pathname); } # Check if file permissions allow to modify existing if (fileAccess(pathname, mode=2) == -1) { throw("No permission to modify existing file: ", pathname); } } else { # Check if directory exists path <- getParent(pathname); if (!isDirectory(path)) { # Does the directory have to exists (mkdirs=FALSE)? if (!mkdirs) { path <- getReadablePath(static, path, mustExist=TRUE); } # If not, first try to create the parent directory, iff missing. # This should give a more informative error message, if it fails. pathP <- getParent(path); createParent <- !isDirectory(pathP); if (createParent) { pathnameP <- getWritablePathname(static, file="dummy-not-tested", path=pathP, mustExist=FALSE, mustNotExist=FALSE, mkdirs=TRUE, maxTries=maxTries); } # Try to create the directory mkdirs(path, mustWork=TRUE, maxTries=maxTries) } filename <- basename(pathname); if (filename != "dummy-not-tested") { # Check if file permissions allow to create a file in the directory pathT <- ifelse(is.null(path), ".", path); if (fileAccess(pathT, mode=2) == -1) { throw("No write permission for directory: ", path); } # Try to create a file filenameT <- basename(tempfile()); pathnameT <- filePath(path, filenameT); on.exit({ if (isFile(pathnameT)) { # Try to remove the temporary file res <- FALSE; suppressWarnings({ for (tt in 1:maxTries) { res <- file.remove(pathnameT); if (res) break; # If not, wait a bit and try again... Sys.sleep(0.5); } }) if (!res) { warning("Failed to remove temporary file: ", sQuote(pathnameT)); } } }, add=TRUE); tryCatch({ cat(file=pathnameT, Sys.time()); }, error = function(ex) { throw("No permission to create a new file in directory: ", path); }); } # if (filename != "dummy-not-tested") } # if (isFile(pathname)) pathname; }, static=TRUE) setMethodS3("getWritablePath", "Arguments", function(static, path=NULL, ...) { # Special case: If path == NULL, the skip if (is.null(path)) return(NULL); pathname <- getWritablePathname(static, file="dummy-not-created", path=path, ...); getParent(pathname); }, static=TRUE, protected=TRUE) setMethodS3("getDirectory", "Arguments", function(static, path=NULL, ..., mustExist=FALSE, mkdirs=TRUE) { # Argument 'mustExist': mustExist <- getLogical(static, mustExist); # Argument 'mkdirs': mkdirs <- getLogical(static, mkdirs); # Create pathname pathname <- getReadablePathname(static, path=path, ..., mustExist=mustExist); if (is.na(pathname)) { throw("Cannot retrieve directory because it is NA."); } # Nothing to do? if (isDirectory(pathname)) { return(pathname); } if (!mkdirs) { throw("Directory does not exist: ", pathname); } mkdirs(pathname, mustWork=TRUE) pathname; }, static=TRUE, protected=TRUE) #########################################################################/** # @RdocMethod getVector # # @title "Validates a vector" # # \description{ # @get "title" by checking its length (number of elements). # } # # @synopsis # # \arguments{ # \item{x}{A single @vector.} # \item{length}{A @numeric @vector of length two or more. If two, it # is the minimum and maximum length of \code{x}. Elsewise it is the # set of possible lengths of \code{x}.} # \item{.name}{A @character string for name used in error messages.} # \item{...}{Not used.} # } # # \value{ # Returns the same @vector, if it is valid. Otherwise an exception is # thrown. # } # # @author # # \seealso{ # @seeclass # } # # @keyword IO #*/######################################################################### setMethodS3("getVector", "Arguments", function(static, x, length=NULL, .name=NULL, ...) { if (length(length) == 0) return(x); if (is.null(.name)) .name <- as.character(deparse(substitute(x))); # See ?is.vector for how it is defined. /HB 2009-05-19 attrs <- attributes(x); attributes(x) <- attrs[intersect(names(attrs), c("names", "dim"))]; if (length[1] > 0 && !is.vector(x)) { throw(sprintf("Argument '%s' is not a vector: %s", .name, storage.mode(x))); } xlen <- length(x); if (length(length) == 1) length <- c(1,length); if (length(length) == 2) { if (xlen < length[1] || xlen > length[2]) { if (length[1] == length[2] && length[1] == 1) { throw(sprintf("Argument '%s' should be a single value not %d values.", .name, xlen)); } else if (length[1] == length[2]) { throw(sprintf("Number of elements in argument '%s' should be exactly %d not %d value(s).", .name, length[1], xlen)); } else { throw(sprintf("Number of elements in argument '%s' is out of range [%d,%d]: %d", .name, length[1], length[2], xlen)); } } } else { if (!is.element(xlen, length)) { throw(sprintf("Number of elements in argument '%s' is not in {%s}: %d", .name, seqToHumanReadable(length), xlen, )); } } attributes(x) <- attrs; x; }, static=TRUE, private=TRUE) #########################################################################/** # @RdocMethod getCharacters # @aliasmethod getCharacter # # @title "Coerces to a character vector and validates" # # \description{ # @get "title". # } # # @synopsis # # \arguments{ # \item{s}{A @vector.} # \item{nchar}{A @numeric @vector of length one or two. If one, # the maximum number of characters ("length") in \code{s}. If two, # the minimum and maximum length of \code{s}.} # \item{useNames}{If @TRUE, the 'names' attribute is preserved, otherwise # it is dropped.} # \item{asGString}{If @TRUE, each string is treated as a @see "GString".} # \item{.name}{A @character string for name used in error messages.} # \item{...}{Not used.} # } # # \value{ # Returns a @character @vector, if it is valid. Otherwise an exception is # thrown. # } # # \section{Missing values}{ # If \code{s} contains missing values, and \code{nchar} is not @NULL, # then an exception is thrown. # } # # @author # # \seealso{ # @seeclass # } # # @keyword IO #*/######################################################################### setMethodS3("getCharacters", "Arguments", function(static, s, length=NULL, trim=FALSE, nchar=NULL, useNames=TRUE, asGString=getOption("Arguments$getCharacters/args/asGString", TRUE), .name=NULL, ...) { if (is.null(.name)) .name <- as.character(deparse(substitute(s))); s <- getVector(static, s, length=length, .name=.name); # Nothing to check? if (length(s) == 0L) return(s); # Coerce GString:s to character strings? if (asGString) { # Treat only strings with GString markup. This avoids lots of # GString overhead if there are no GStrings. hasMarkup <- (regexpr("${", s, fixed=TRUE) != -1); idxs <- which(hasMarkup & !is.na(s)); s[idxs] <- unlist(lapply(s[idxs], FUN=function(x) { x <- GString(x); as.character(x); }), use.names=FALSE); } if (trim) { # Trim the strings # (using s[] to preserve attributes) s[] <- unlist(lapply(s, FUN=trim), use.names=FALSE); } # Coerce to character strings # (using s[] to preserve attributes) s[] <- unlist(lapply(s, FUN=as.character), use.names=FALSE); if (!useNames) { names(s) <- NULL; } # Nothing to check? if (is.null(nchar)) return(s); # At this point, missing values are not allowed if (any(is.na(s))) { throw("Argument 'nchar' cannot be specified if character vector contains missing values: ", hpaste(sQuote(s))) } if (length(nchar) == 1L) nchar <- c(1L, nchar); # Check the string length of each character string for (kk in seq(length=length(s))) { slen <- nchar(s[kk], type="chars"); if (slen < nchar[1L] || slen > nchar[2L]) { throw(sprintf("String length of elements #%d in '%s' is out of range [%d,%d]: %d '%s'", kk, .name, nchar[1L], nchar[2L], slen, s[kk])); } } s; }, static=TRUE) setMethodS3("getCharacter", "Arguments", function(static, ..., length=c(0,1)) { getCharacters(static, ..., length=length); }, static=TRUE) #########################################################################/** # @RdocMethod getNumerics # @aliasmethod getNumeric # # @title "Coerces to a numeric vector and validates" # # \description{ # @get "title". # } # # @synopsis # # \arguments{ # \item{x}{A @vector.} # \item{range}{Two @numerics for the allowed ranged. If @NULL, range is # not checked.} # \item{asMode}{A @character specifying the mode to coerce to.} # \item{disallow}{A @character @vector specifying diallowed value sets, # i.e. \code{"NA"}, \code{"NaN"}, and/or \code{"Inf"}.} # \item{...}{Arguments passed to @method "getVector".} # \item{.name}{A @character string for name used in error messages.} # } # # \value{ # Returns a @numeric @vector. # } # # @author # # \seealso{ # @seeclass # } # # @keyword IO #*/######################################################################### setMethodS3("getNumerics", "Arguments", function(static, x, range=NULL, asMode=NULL, disallow=NULL, ..., .name=NULL) { # Argument '.name': if (is.null(.name)) { .name <- as.character(deparse(substitute(x))); } x <- getVector(static, x, ..., .name=.name); xMode <- storage.mode(x); # Coerce the mode of 'x' if (is.null(asMode)) { if (is.element(xMode, c("integer", "double"))) { asMode <- xMode; } else { asMode <- "double"; } } # Update/coerce mode? if (xMode != asMode) { storage.mode(x) <- asMode; } # Nothing to do? if (length(x) == 0) return(x); if (!is.null(disallow)) { if (is.element("NaN", disallow) && any(is.nan(x))) { throw(sprintf("Argument '%s' contains %d NaN value(s).", .name, sum(is.nan(x)))); } if (is.element("NA", disallow) && any(is.na(x) & !is.nan(x))) { throw(sprintf("Argument '%s' contains %d NA value(s).", .name, sum(is.na(x)))); } # For conveniency, disallow 'Inf' here too; other range takes care of it. if (is.element("Inf", disallow) && any(is.infinite(x))) { throw(sprintf("Argument '%s' contains %d (-/+)Inf value(s).", .name, sum(is.infinite(x)))); } } # Nothing to check? if (is.null(range)) return(x); # Argument 'range': if (length(range) != 2) { throw("Argument 'range' should be of length 2: ", length(range)); } if (range[2] < range[1]) { throw(sprintf("Argument 'range' is not ordered: c(%s,%s)", range[1], range[2])); } # Suppress warnings when there are no finite values in x. suppressWarnings({ xrange <- range(x, na.rm=TRUE); }) if (xrange[1] < range[1] || xrange[2] > range[2]) { xrange <- as.character(xrange); range <- as.character(range); if (length(x) == 1) { throw(sprintf("Argument '%s' is out of range [%s,%s]: %s", .name, range[1], range[2], x)); } else { throw(sprintf("Range of argument '%s' is out of range [%s,%s]: [%s,%s]", .name, range[1], range[2], xrange[1], xrange[2])); } } x; }, static=TRUE) setMethodS3("getNumeric", "Arguments", function(static, ..., length=1) { getNumerics(static, ..., length=length); }, static=TRUE) #########################################################################/** # @RdocMethod getDoubles # @aliasmethod getDouble # # @title "Coerces to a double vector and validates" # # \description{ # @get "title". # } # # @synopsis # # \arguments{ # \item{...}{Arguments passed to @method "getNumeric".} # \item{disallow}{Disallowed values. See @method "getNumerics" for details.} # } # # \value{ # Returns a @double @vector. # } # # @author # # \seealso{ # @seeclass # } # # @keyword IO #*/######################################################################### setMethodS3("getDoubles", "Arguments", function(static, ..., disallow=c("NA","NaN")) { getNumerics(static, ..., asMode="double", disallow=disallow); }, static=TRUE) setMethodS3("getDouble", "Arguments", function(static, ..., length=1) { getDoubles(static, ..., length=length); }, static=TRUE) #########################################################################/** # @RdocMethod getIntegers # @aliasmethod getInteger # # @title "Coerces to a integer vector and validates" # # \description{ # @get "title". # } # # @synopsis # # \arguments{ # \item{...}{Arguments passed to @method "getNumeric".} # \item{disallow}{Disallowed values. See @method "getNumerics" for details.} # } # # \value{ # Returns a @integer @vector. # } # # @author # # \seealso{ # @seeclass # } # # @keyword IO #*/######################################################################### setMethodS3("getIntegers", "Arguments", function(static, ..., disallow=c("NA","NaN")) { getNumerics(static, ..., asMode="integer", disallow=disallow); }, static=TRUE) setMethodS3("getInteger", "Arguments", function(static, ..., length=1) { getIntegers(static, ..., length=length); }, static=TRUE) #########################################################################/** # @RdocMethod getIndices # @aliasmethod getIndex # # @title "Coerces to a integer vector and validates" # # \description{ # @get "title". # } # # @synopsis # # \arguments{ # \item{x}{A single @vector. If @logical, @see "base::which" is used.} # \item{...}{Arguments passed to @method "getIntegers".} # \item{range}{Allowed range. See @method "getNumerics" for details.} # \item{max}{The maximum of the default range.} # \item{.name}{A @character string for name used in error messages.} # } # # \value{ # Returns an @integer @vector. # } # # @author # # \seealso{ # @seeclass # } # # @keyword IO #*/######################################################################### setMethodS3("getIndices", "Arguments", function(static, x, ..., max=Inf, range=c(1*(max > 0L),max), .name=NULL) { if (is.null(.name)) .name <- as.character(deparse(substitute(x))); # Argument 'x': if (is.logical(x)) { x <- which(x); } # Argument 'max': if (length(max) != 1) { throw("Argument 'max' must be a single value: ", length(max)); } max <- as.numeric(max); if (is.na(max)) { throw("Argument 'max' is NA/NaN: ", max); } else if (max < 0) { throw("Argument 'max' must be positive: ", max); } # Argument 'range': if (!is.null(range)) { if (length(range) != 2) { throw("Argument 'range' should be of length 2: ", length(range)); } if (range[2] < range[1]) { throw(sprintf("Argument 'range' is not ordered: c(%s,%s)", range[1], range[2])); } } # Identify indices x <- getIntegers(static, x, ..., range=range, .name=.name); # Special dealing with range = c(0,0) if (!is.null(range)) { if (range[2] < 1L) { xt <- x[is.finite(x)]; if (length(xt) > 0) { throw(sprintf("Argument 'x' contains %d non-missing indices although the range ([%s,%s]) implies that there should be none.", length(xt), range[1L], range[2L])); } } } x; }, static=TRUE) setMethodS3("getIndex", "Arguments", function(static, ..., length=1) { getIndices(static, ..., length=length); }, static=TRUE) #########################################################################/** # @RdocMethod getLogicals # @aliasmethod getLogical # # @title "Coerces to a logical vector and validates" # # \description{ # @get "title". # } # # @synopsis # # \arguments{ # \item{x}{A @vector.} # \item{disallow}{A @character @vector specifying diallowed value sets # after coercing, i.e. \code{"NA"}.} # \item{...}{Arguments passed to @method "getVector".} # \item{.name}{A @character string for name used in error messages.} # } # # \value{ # Returns a @numeric @vector. # } # # @author # # \seealso{ # @seeclass # } # # @keyword IO #*/######################################################################### setMethodS3("getLogicals", "Arguments", function(static, x, ..., disallow=c("NA", "NaN"), coerce=FALSE, .name=NULL) { if (is.null(.name)) .name <- as.character(deparse(substitute(x))); x <- getVector(static, x, ..., .name=.name); # Coerce to logicals? if (coerce) x <- as.logical(x); if (!is.null(disallow)) { if (is.element("NA", disallow) && any(is.na(x))) { throw(sprintf("Argument '%s' contains %d NA value(s).", .name, sum(is.na(x)))); } } # Assert that 'x' is logical before returning if (any(!is.logical(x))) throw(sprintf("Argument '%s' is non-logical: %s", .name, class(x))); x; }, static=TRUE) setMethodS3("getLogical", "Arguments", function(static, ..., length=1) { getLogicals(static, ..., length=length); }, static=TRUE) #########################################################################/** # @RdocMethod getVerbose # # @title "Coerces to Verbose object" # # \description{ # @get "title". # } # # @synopsis # # \arguments{ # \item{verbose}{A single object. If a @see "Verbose", it is immediately # returned. If a @numeric value, it is used as the threshold. # Otherwise the object is coerced to a @logical value and if @TRUE, # the threshold is \code{defaultThreshold}.} # \item{defaultThreshold}{A @numeric value for the default threshold, if # \code{verbose} was interpreted as a @logical value.} # \item{useNullVerbose}{If \code{verbose} can be interpreted as @FALSE, # return a @see NullVerbose object if @TRUE.} # \item{...}{Passed to the constructor of @see "Verbose".} # \item{.name}{A @character string for name used in error messages.} # } # # \value{ # Returns a @see Verbose (or a @see "NullVerbose") object. # } # # @author # # \seealso{ # @seeclass # } # # @keyword IO #*/######################################################################### setMethodS3("getVerbose", "Arguments", function(static, verbose, defaultThreshold=-1, useNullVerbose=TRUE, ..., .name=NULL) { if (inherits(verbose, "Verbose")) return(verbose); if (is.null(.name)) .name <- as.character(deparse(substitute(verbose))); if (is.numeric(verbose)) { verbose <- getDouble(static, verbose, .name=.name); verbose <- Verbose(threshold=verbose, ...); } else { verbose <- getLogical(static, verbose, .name=.name); if (!verbose && useNullVerbose) { verbose <- NullVerbose(); } else { defaultThreshold <- getNumeric(static, defaultThreshold); verbose <- Verbose(threshold=defaultThreshold, ...); } } verbose; }, static=TRUE) #########################################################################/** # @RdocMethod getRegularExpression # # @title "Gets a valid regular expression pattern" # # \description{ # @get "title". # } # # @synopsis # # \arguments{ # \item{pattern}{A @character string to be validated.} # \item{.name}{A @character string for name used in error messages.} # \item{...}{Not used.} # } # # \value{ # Returns a @character string. # } # # @author # # \seealso{ # @see "base::grep". # @seeclass # } # # @keyword IO #*/######################################################################### setMethodS3("getRegularExpression", "Arguments", function(static, pattern=NULL, ..., .name=NULL) { if (is.null(.name)) { .name <- as.character(deparse(substitute(pattern))); } if (is.null(pattern)) { throw(sprintf("Argument '%s' is not a valid regular expression: NULL", .name)); } pattern <- getCharacter(static, pattern, .name=.name, length=c(1,1)); # Validate it tryCatch({ regexpr(pattern, "dummy string", ...); }, error = function(ex) { throw(sprintf("Argument '%s' is not a valid regular expression: %s. Error message from regexpr() was: %s", .name, pattern, ex$message)); }) pattern; }, static=TRUE) #########################################################################/** # @RdocMethod getEnvironment # # @title "Gets an existing environment" # # \description{ # @get "title". # } # # @synopsis # # \arguments{ # \item{envir}{An @environment, the name of a loaded package, or @NULL. # If @NULL, the global environment is returned.} # \item{.name}{A @character string for name used in error messages.} # \item{...}{Not used.} # } # # \value{ # Returns an @environment. # } # # @author # # \seealso{ # @seeclass # } # # @keyword IO #*/######################################################################### setMethodS3("getEnvironment", "Arguments", function(static, envir=NULL, .name=NULL, ...) { if (is.null(.name)) .name <- as.character(deparse(substitute(envir))); if (is.null(envir)) { return(.GlobalEnv); } if (is.character(envir)) { name <- getCharacter(static, envir, length=c(1,1)); envirs <- gsub("^package:", "", search()); pos <- which(name == envirs); if (length(pos) == 0) throw("Argument 'envir' is not the name of a loaded package: ", envir); envir <- pos.to.env(pos); } if (!is.environment(envir)) { throw(sprintf("Argument '%s' is not an environment: %s", .name, class(envir)[1])); } }, static=TRUE) #########################################################################/** # @RdocMethod getInstanceOf # # @title "Gets an instance of the object that is of a particular class" # # \description{ # @get "title". # } # # @synopsis # # \arguments{ # \item{object}{The object that should be returned as an instance of # class \code{class}.} # \item{class}{A @character string specifying the name of the class that # the returned object should inherit from.} # \item{coerce}{If @TRUE and the object is not of the wanted class, then # method will be coerced to that class, if possible. Otherwise, # an error is thrown.} # \item{...}{Not used.} # \item{.name}{A @character string for name used in error messages.} # } # # \value{ # Returns an object inheriting from class \code{class}. # } # # @author # # \seealso{ # @seeclass # } # # @keyword programming #*/######################################################################### setMethodS3("getInstanceOf", "Arguments", function(static, object, class, coerce=FALSE, ..., .name=NULL) { if (is.null(.name)) { .name <- as.character(deparse(substitute(object))); } # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Validate arguments # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Argument 'class': class <- getCharacter(static, class); # Argument 'coerce': coerce <- getLogical(static, coerce); # Argument 'object': if (!inherits(object, class)) { if (coerce) { object <- as(object, class, ...); } else { throw(sprintf("Argument '%s' is neither of nor inherits class %s: %s", .name, class[1], paste(class(object), collapse=", "))); } } # Return the object object; }, static=TRUE, protected=TRUE) withoutGString <- function(..., envir=parent.frame()) { # Temporarily disable 'asGString' for Arguments$getCharacters() oopts <- options("Arguments$getCharacters/args/asGString"=FALSE); on.exit(options(oopts)); eval(..., envir=envir); } # withoutGString() ############################################################################ # HISTORY: # 2015-02-05 # o Now getReadablePathname() warns about too long pathnames on Windows. # 2014-10-03 # o Now Arguments$getReadablePathname(file, path) ignores 'path' if # 'file' specifies an absolute pathname. # 2014-05-04 # o Added argument 'adjust' to Arguments$getReadablePathname(). # 2014-01-12 # o Made argument 'useNames' to getCharacters() default to TRUE. # o Now Arguments$getCharacters() preserves attributes. # 2013-12-15 # o Added withoutGString(). # 2013-12-13 # o Now argument 'asGString' for Arguments$getCharacters() defaults to # getOption("Arguments$getCharacters/args/asGString", TRUE). This makes # it possible to disable this feature, even when it is not possible to # directly pass that argument. This will also make it possible to # set the default to FALSE in the future (instead of TRUE as today). # 2013-11-15 # o CLEANUP: Arguments$getNumerics(NA, range=c(0,1)) no longer gives # warnings on "no non-missing arguments to min()" etc. # 2013-08-26 # o CLEANUP: Arguments$getReadablePathnames(files, paths=NULL) no longer # warns about "rep(paths, length.out = nbrOfFiles) : 'x' is NULL so # the result will be NULL" if length(files) > 0. # 2012-12-01 # o BUG FIX: Arguments$getIndices(NA_integer_, max=0, disallow="NaN") # would give "Exception: Argument 'x' is of length 1 although the range # ([0,0]) implies that is should be empty." although it should return # NA_integer. # 2012-10-21 # o ROBUSTNESS: Added argument 'maxTries' to Arguments$getWritablePathname() # to have the method try to create missing directories multiple times # before giving up. # 2012-10-16 # o Moved Arguments$getFilename() from R.filesets to R.utils. # Added Rd help. # 2012-09-24 # o BUG FIX: Arguments$getReadablePath(..., mustExist=FALSE) did not work. # 2011-11-15 # o SPEEDUP: Now Arguments$getCharacters(s, asGString=TRUE) is much # faster for elements of 's' that are non-GStrings. For long character # vectors the speedup is 100-200x times. # 2011-10-16 # o CORRECTION: Arguments$getNumerics(c(Inf), disallow="Inf") would report # that it contains "NA" instead of "Inf" values". # 2011-03-08 # o Now Arguments$getWritablePath(NULL) returns NULL without asserting # write permission, which is analogue to how it is done with # Arguments$getReadablePath(NULL). # 2010-11-19 # o TYPO: Static methods getVector() and getRegularExpression() of # Arguments would report the incorrect argument name. # 2010-01-25 # o ROBUSTNESS: Added validation of argument 'range' in Arguments methods. # 2010-01-01 # o Now Arguments$getNumerics(x) displays the value of 'x' in the error # message if it is a *single* value and out of range. # o Added argument 'max' to Arguments$getIndices(). # 2009-12-30 # o Now Arguments$getWritablePath() and Arguments$getWritablePathname() # throws an error is an NA file/directory is specified. # o Now Arguments$getReadablePath() and Arguments$getReadablePathname() # throws an error is an NA file/directory is specified, unless # 'mustExist' is FALSE. # o Added Arguments$getInstanceOf(...). # o BUG FIX: Arguments$getCharacters(s) would return a *logical* instead # of a *character* vector if 's' contained all NAs. # 2009-11-20 # o If 'x' is a logical vector, Arguments$getIndices(x) will now return # the same as if x <- which(x). # 2009-10-30 # o Now Arguments$getWritablePathname(path) validates that there is enough # file permissions so that a file can be created in the 'path' directory. # 2009-06-29 # o Added argument 'useNames=FALSE' to getCharacters() of Arguments. # Don't remember why I didn't want names in the first place (see below). # 2009-05-18 # o UPDATE: Now getWritablePathname() gives a more precise error message # if the file exists but the rights to modifies it does not. # o UPDATE: Now getEnvironment(), getRegularExpression(), and # getReadablePathname() give clearer error messages if more the input # contains more than one element. # 2009-05-15 # o Changed argument 'asMode' for Arguments$getNumerics() to default to # NULL instead of "numeric". This will case the method to return integer # if the input is integer, and double if the input is double. The # previous default was alway returning doubles, cf. notes on common # misconception of how as.numeric() works. In the case when the input # is neither integer or double, the default is to coerce to doubles. # Also, the method is now using storage.mode() instead of mode(). # 2009-04-04 # o Now getReadablePathname(..., mustExist=TRUE) of Arguments reports also # the working directory if the a relative pathname is missing. # o BUG FIX: getReadablePathname(..., mustExist=TRUE) of Arguments gave an # internal error if the pathname was in the current directory and did # not exist. # 2008-12-27 # o Now getReadablePathname(..., mustExist=TRUE) and # getWritablePathname(..., mkdirs=FALSE) of Arguments report which # of the parent directories exists when the requested pathname is not # found. This will help troubleshooting missing pathnames. # 2008-12-01 # o Now getReadablePathname() and getWritablePathname() use the more # trusted fileAccess() of R.utils. # 2008-02-26 # o Now the '...' arguments to Arguments$getVerbose() are passed to the # constructor of Verbose. This allows the construct of # Arguments$getVerbose(-10, timestamp=TRUE). # 2005-12-05 # o getNumerics(Inf, range=c(0,Inf)) would give a warning "no finite # arguments to min; returning Inf". Fixed with a withCallingHandlers(). # 2005-11-22 # o Added Rdoc comments for getReadablePathnames(). # 2005-11-13 # o Added getReadablePathnames(). # o Now getCharacter() only accept vectors of length zero or one. # 2005-10-25 # o BUG FIX: New 'mustNotExist' argument got logically the inverse. # 2005-10-21 # o Renamed argument 'overwrite' in getWritablePathname() in Arguments to # 'mustNotExist'. Renamed all 'mustExists' to 'mustExist' in all methods # of class Arguments. # 2005-09-06 # o Replace argument 'gString' of getCharacters() to 'asGString', cf. # Verbose class. # o Now Arguments$getReadablePathname() follows Windows shortcut files. # 2005-08-01 # o getReadablePathname() no longer returns the absolute pathname by # default. This is because on some systems the relative pathname can # be queried wheras the absolute one may not be access due to missing # file permissions. # o Added getEnvironment(), getRegularExpression(), # getReadablePath(), getWritablePath(). # 2005-07-19 # o BUG FIX: getCharacters() would not coerce Object:s correctly. # 2005-07-07 # o getCharacters() returned attribute 'names' too. Removed. # 2005-06-20 # o Added argument 'absolutePath' to getReadablePathname(). # 2005-06-18 # o Added static methods getVector(), getNumeric/s(), getDouble/s(), # getInteger/s(), getIndices/getIndex(), and getLogical/s(). These should # be very handy. Also added getVector(). # Not sure if getVector() should be renamed to checkLength(), and even # be moved to the Assert class. Not sure where the assert class is # heading. # 2005-05-31 # o Created from former File$validateFileAndPath(). ############################################################################
#' Rboretum Unique Clade Fetcher #' #' This function takes a named multiPhylo object and a focal tree, and returns clades that occur in the focal clade but not all other trees in the multiPhylo #' @param trees Named multiPhylo object #' @param focal_tree Name of focal tree #' @return Character vector of clades that occur in the focal tree, and are missing from at least one other tree in the multiPhylo #' @export #' get.uniqueClades <- function(trees,focal_tree){ if(!Rboretum::is.multiPhylo(trees)){ stop("'trees' does not appear to be a valid multiPhlyo object with 2+ trees") } else if(!Rboretum::check.shared(trees)){ stop("'trees' don't appear to share at least 3 taxa in common.") } else if(Rboretum::same.topology(trees)){ stop("'trees' have identical topology. No comparison possible.") } else if(is.null(names(trees))){ stop("'trees' must be named for get.uniqueClades. Name multiPhylo by assigning through names(trees) <- c('name1','name2',etc)") } tree_count <- length(trees) if(missing(focal_tree)){ stop("'focal_tree' name not assigned.") } else{ focal_tree <- as.character(focal_tree) } if(has_error(tree <- trees[[focal_tree]])){ stop("'focal_tree' must be the name of a tree in the multiPhylo. Check names(trees).") } clade_compare <- Rboretum::compare.clades(trees) %>% filter(Tree_Percent < 100) clades <- c() for(i in 1:nrow(clade_compare)){ if(str_detect(clade_compare$Trees_with_Clade[i],";")){ check <- semiVector(clade_compare$Trees_with_Clade[i]) } else{ check <- clade_compare$Trees_with_Clade[i] } if(focal_tree %in% check){ clades <- c(clades,clade_compare$Clade[i]) } } return(clades) }
/R/get.uniqueClades.R
no_license
erenada/Rboretum
R
false
false
1,734
r
#' Rboretum Unique Clade Fetcher #' #' This function takes a named multiPhylo object and a focal tree, and returns clades that occur in the focal clade but not all other trees in the multiPhylo #' @param trees Named multiPhylo object #' @param focal_tree Name of focal tree #' @return Character vector of clades that occur in the focal tree, and are missing from at least one other tree in the multiPhylo #' @export #' get.uniqueClades <- function(trees,focal_tree){ if(!Rboretum::is.multiPhylo(trees)){ stop("'trees' does not appear to be a valid multiPhlyo object with 2+ trees") } else if(!Rboretum::check.shared(trees)){ stop("'trees' don't appear to share at least 3 taxa in common.") } else if(Rboretum::same.topology(trees)){ stop("'trees' have identical topology. No comparison possible.") } else if(is.null(names(trees))){ stop("'trees' must be named for get.uniqueClades. Name multiPhylo by assigning through names(trees) <- c('name1','name2',etc)") } tree_count <- length(trees) if(missing(focal_tree)){ stop("'focal_tree' name not assigned.") } else{ focal_tree <- as.character(focal_tree) } if(has_error(tree <- trees[[focal_tree]])){ stop("'focal_tree' must be the name of a tree in the multiPhylo. Check names(trees).") } clade_compare <- Rboretum::compare.clades(trees) %>% filter(Tree_Percent < 100) clades <- c() for(i in 1:nrow(clade_compare)){ if(str_detect(clade_compare$Trees_with_Clade[i],";")){ check <- semiVector(clade_compare$Trees_with_Clade[i]) } else{ check <- clade_compare$Trees_with_Clade[i] } if(focal_tree %in% check){ clades <- c(clades,clade_compare$Clade[i]) } } return(clades) }
\name{show_news} \alias{show_news} \title{Show package news...} \usage{ show_news(pkg = NULL, latest = TRUE, ...) } \arguments{ \item{pkg}{package description, can be path or package name. See \code{\link{as.package}} for more information} \item{latest}{if \code{TRUE}, only show the news for the most recent version.} \item{...}{other arguments passed on to \code{news}} } \description{ Show package news }
/man/show_news.Rd
no_license
BrianDiggs/devtools
R
false
false
426
rd
\name{show_news} \alias{show_news} \title{Show package news...} \usage{ show_news(pkg = NULL, latest = TRUE, ...) } \arguments{ \item{pkg}{package description, can be path or package name. See \code{\link{as.package}} for more information} \item{latest}{if \code{TRUE}, only show the news for the most recent version.} \item{...}{other arguments passed on to \code{news}} } \description{ Show package news }
#Define colors phyla.col <- c("Acidimicrobiia"="#AA4488", "Actinobacteria" = "#DDAA77", "Alphaproteobacteria"= "#771155", "Bacilli"="#117744", "Bacteroidia"= "#77AADD", "Campylobacteria" = "#FF2222", #"Chlamydiae"= "#DD1232" , #"Clostridia"= "#77CCCC", "Cyanobacteriia"= "#AAAA44", "Clostridia" ="#CC1234", #"Desulfobulbia"= "#117744", "Gammaproteobacteria"="#117777", "Gracilibacteria"= "#44AA77", "Kiritimatiellae" = "#DD7788", "Negativicutes"= "#34ABAA", "Paracubacteria"= "#11BBCC", #"NB1-j_uncl" = "#774411", "Rhodothermia" = "#E69F00", "Parcubacteria"= "#88CCAA", "Planctomycetes"= "#777711", #"OM190"= "#009E73", #"SAR324_clade(Marine_group_B)_uncl"="#CC99BB", "Saccharimonadia" = "#AACC45", #"Thermoplasmata" = "#0072B2", "Verrucomicrobiae" = "#AA7744", #"Vicinamibacteria" ="#DDDD77", "Other taxa"= "#114477") indicators.col <- c("Aeromonadaceae"="#AA4488", "Arcobacteraceae" = "#771155", "Bacteroidaceae"= "#DDAA77", "Bdellovibrionaceae"="#AAAA44", "Carnobacteriaceae"= "#77AADD", "Campylobacteraceae" = "#FF2222", "Chlamydiaceae"= "#E5C494" , "Enterococcaceae"= "#117777", "Clostridiaceae" ="#CC1234", "Desulfovibrionaceae"= "#117744", "Enterobacteriaceae"="#77CCCC", "Flavobacteriaceae"= "#44AA77", "Helicobacteraceae" = "#88CCAA", "Lachnospiraceae"= "#34ABAA", "Legionellaceae"= "#11BBCC", "Leptospiraceae" = "#774411", "Listeriaceae" = "#E69F00", "Moraxellaceae"= "#DDDD77", "Mycobacteriaceae"= "#777711", "Porphyromonadaceae"= "#009E73", "Pseudomonadaceae"="#CC99BB", "Ruminococcaceae" = "#AACC45", "Staphylococcaceae" = "#0072B2", "Streptococcaceae" = "#AA7744", "Vibrionaceae" = "#DD7788", "Yersiniaceae"= "#117744", "Other taxa"= "#114477") location.col <- c("R-Estuary-1" = "#FC8D62", "R-Estuary-2" = "#FFD92F", "NS-Marine" = "#E5C494", "OS-Marine" = "#8DA0CB", "SM-Outfall" = "#66C2A5", "R-Mouth" = "#E41A1C") season.col <- c("winter" = "#8960b3", "spring" = "#56ae6c", "summer" = "#ba495b", "autumn" = "#b0923b") tol21rainbow<- c("#771155", "#AA4488", "#CC99BB", "#114477", "#4477AA", "#117744", "#117777", "#88CCAA", "#77CCCC", "#00ffff", "#44AA77", "#44AAAA", "#777711", "#AAAA44", "#DDDD77", "#774411", "#AA7744", "#DDAA77", "#771122", "#AA4455", "#DD7788")
/scripts/Color_palettes.R
no_license
Orel-N/microbiome
R
false
false
3,601
r
#Define colors phyla.col <- c("Acidimicrobiia"="#AA4488", "Actinobacteria" = "#DDAA77", "Alphaproteobacteria"= "#771155", "Bacilli"="#117744", "Bacteroidia"= "#77AADD", "Campylobacteria" = "#FF2222", #"Chlamydiae"= "#DD1232" , #"Clostridia"= "#77CCCC", "Cyanobacteriia"= "#AAAA44", "Clostridia" ="#CC1234", #"Desulfobulbia"= "#117744", "Gammaproteobacteria"="#117777", "Gracilibacteria"= "#44AA77", "Kiritimatiellae" = "#DD7788", "Negativicutes"= "#34ABAA", "Paracubacteria"= "#11BBCC", #"NB1-j_uncl" = "#774411", "Rhodothermia" = "#E69F00", "Parcubacteria"= "#88CCAA", "Planctomycetes"= "#777711", #"OM190"= "#009E73", #"SAR324_clade(Marine_group_B)_uncl"="#CC99BB", "Saccharimonadia" = "#AACC45", #"Thermoplasmata" = "#0072B2", "Verrucomicrobiae" = "#AA7744", #"Vicinamibacteria" ="#DDDD77", "Other taxa"= "#114477") indicators.col <- c("Aeromonadaceae"="#AA4488", "Arcobacteraceae" = "#771155", "Bacteroidaceae"= "#DDAA77", "Bdellovibrionaceae"="#AAAA44", "Carnobacteriaceae"= "#77AADD", "Campylobacteraceae" = "#FF2222", "Chlamydiaceae"= "#E5C494" , "Enterococcaceae"= "#117777", "Clostridiaceae" ="#CC1234", "Desulfovibrionaceae"= "#117744", "Enterobacteriaceae"="#77CCCC", "Flavobacteriaceae"= "#44AA77", "Helicobacteraceae" = "#88CCAA", "Lachnospiraceae"= "#34ABAA", "Legionellaceae"= "#11BBCC", "Leptospiraceae" = "#774411", "Listeriaceae" = "#E69F00", "Moraxellaceae"= "#DDDD77", "Mycobacteriaceae"= "#777711", "Porphyromonadaceae"= "#009E73", "Pseudomonadaceae"="#CC99BB", "Ruminococcaceae" = "#AACC45", "Staphylococcaceae" = "#0072B2", "Streptococcaceae" = "#AA7744", "Vibrionaceae" = "#DD7788", "Yersiniaceae"= "#117744", "Other taxa"= "#114477") location.col <- c("R-Estuary-1" = "#FC8D62", "R-Estuary-2" = "#FFD92F", "NS-Marine" = "#E5C494", "OS-Marine" = "#8DA0CB", "SM-Outfall" = "#66C2A5", "R-Mouth" = "#E41A1C") season.col <- c("winter" = "#8960b3", "spring" = "#56ae6c", "summer" = "#ba495b", "autumn" = "#b0923b") tol21rainbow<- c("#771155", "#AA4488", "#CC99BB", "#114477", "#4477AA", "#117744", "#117777", "#88CCAA", "#77CCCC", "#00ffff", "#44AA77", "#44AAAA", "#777711", "#AAAA44", "#DDDD77", "#774411", "#AA7744", "#DDAA77", "#771122", "#AA4455", "#DD7788")
# Downloading the data and loading it into R if(!file.exists('data')){ dir.create('data') } fileUrl <- 'https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2FNEI_data.zip' download.file(fileUrl, destfile = './data/EmissionData.zip') unzip('./data/EmissionData.zip') NEI <- readRDS("summarySCC_PM25.rds") SCC <- readRDS("Source_Classification_Code.rds") # Question 2 # Have total emissions from PM2.5 decreased in the Baltimore City, Maryland (fips == "24510") from 1999 to # 2008? Use the base plotting system to make a plot answering this question. Baltimore <- NEI[NEI$fips == '24510', ] baltimore <- aggregate(Baltimore$Emission, by = list(Baltimore$year), FUN = sum) names(baltimore) <- c('Year', 'Emission') png(filename = 'plot2.png') plot(x = baltimore$Year, y = baltimore$Emission, type = 'b', main = 'M2.5 Emission in Baltimore (1999 - 2008)', xlab = 'Year', ylab = 'Total Emission [tons]') dev.off()
/plot2.R
no_license
ajladz/ExploratoryDataAnalysis---CourseProject2
R
false
false
927
r
# Downloading the data and loading it into R if(!file.exists('data')){ dir.create('data') } fileUrl <- 'https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2FNEI_data.zip' download.file(fileUrl, destfile = './data/EmissionData.zip') unzip('./data/EmissionData.zip') NEI <- readRDS("summarySCC_PM25.rds") SCC <- readRDS("Source_Classification_Code.rds") # Question 2 # Have total emissions from PM2.5 decreased in the Baltimore City, Maryland (fips == "24510") from 1999 to # 2008? Use the base plotting system to make a plot answering this question. Baltimore <- NEI[NEI$fips == '24510', ] baltimore <- aggregate(Baltimore$Emission, by = list(Baltimore$year), FUN = sum) names(baltimore) <- c('Year', 'Emission') png(filename = 'plot2.png') plot(x = baltimore$Year, y = baltimore$Emission, type = 'b', main = 'M2.5 Emission in Baltimore (1999 - 2008)', xlab = 'Year', ylab = 'Total Emission [tons]') dev.off()
library(sf) library(sp) library(mapview) library(tidyverse) library(plotrix) library(spatstat) library(maptools) library(raster) setwd("C:/Users/Rocket/Google Drive/1.Materias/Analisis_espacial/2_Analisis_puntos") data<-read.csv("input/crime-lat-long.csv") str(data) summary(data$lat) summary(data$long) data<-data[!is.na(data$long)&!is.na(data$lat),] data<-data[data$year==2013,] summary(data$lat) summary(data$long) #https://hoyodecrimen.com/ #zero <- zerodist(data) border <- shapefile("input/DF_Delegaciones.shp") #crime_sf = st_as_sf(data, coords = c("long", "lat"), crs = 4326) #rs<-st_crs(border) #st_crs(c)<-rs coordinates(data)=~long+lat plot(data,pch="+",cex=0.5,main="",col=data$crime) plot(border,add=T) legend(x=-0.53,y=51.41,pch="+",legend=unique(data$crime),cex=0.4) projection(data)=projection(border) #crime_utm<-st_transform(crime_sf,crs=6369) #border_utm<-st_transform(border,crs=6369) data_utm<-spTransform(data, CRS("+init=epsg:6369")) border_utm<-spTransform(border, CRS("+init=epsg:6369")) x_coord<-data_utm@coords[,1] y_coord<-data_utm@coords[,2] mean_centerX<-mean(data_utm@coords[,1]) mean_centerY<-mean(data_utm@coords[,2]) standard_deviationX <- sd(x_coord) standard_deviationY <- sd(y_coord) standard_distance <- sqrt(sum(((x_coord-mean_centerX)^2+(y_coord-mean_centerY)^2))/(nrow(data_utm))) plot(data_utm,pch="+",cex=0.05,main="") plot(border,add=T,cex=0.001) points(mean_centerX,mean_centerY,col="red",pch=16) draw.circle(mean_centerX,mean_centerY,radius=standard_distance,border="red",lwd=2) plot(data_utm,pch="+",cex=0.05,main="") plot(border,add=T,cex=0.001) points(mean_centerX,mean_centerY,col="red",pch=16) draw.ellipse(mean_centerX,mean_centerY,a=standard_deviationX,b=standard_deviationY,border="red",lwd=2) #Homicidios homicides<-data_utm[data_utm$crime=="HOMICIDIO DOLOSO",] homicides <- remove.duplicates(homicides) w<-as(border_utm, "owin") homicides.ppp <- ppp(x=homicides@coords[,1],y=homicides@coords[,2],window=w) homicides.ppp$n/sum(sapply(slot(border_utm, "polygons"), slot, "area")) q<-quadratcount(homicides.ppp, nx = 8, ny = 8) plot(homicides.ppp,pch=20, cols="grey70",cex=0.05,main="Homicidios") plot(q,add=TRUE,col="red") Local.Intensity <- data.frame(Mun=factor(),Number=numeric()) for(i in unique(border_utm$Name)){ sub.pol <- border_utm[border_utm$Name==i,] sub.ppp <- ppp(x=homicides.ppp$x,y=homicides.ppp$y,window=as.owin(sub.pol)) Local.Intensity <- rbind(Local.Intensity,data.frame(Mun=factor(i,levels=border_utm$Name),Number=sub.ppp$n)) } colorScale <- color.scale(Local.Intensity[order(Local.Intensity[,2]),2],color.spec="rgb",extremes=c("green","red"),alpha=0.8) barplot(Local.Intensity[order(Local.Intensity[,2]),2],names.arg=Local.Intensity[order(Local.Intensity[,2]),1],horiz=T,las=2,space=1,col=colorScale) sigma1<- bw.diggle(homicides.ppp) sigma2<- bw.ppl(homicides.ppp) sigma3<- bw.scott(homicides.ppp)[1] sigma4<- bw.scott(homicides.ppp)[2] d1<-density.ppp(homicides.ppp, sigma =sigma1,edge=T) d2<-density.ppp(homicides.ppp, sigma =sigma2,edge=T) d3<-density.ppp(homicides.ppp, sigma =sigma3,edge=T) d4<-density.ppp(homicides.ppp, sigma =sigma4,edge=T) plot(d1,main=paste("h =",round(sigma1,2))) plot(d2,main=paste("h =",round(sigma2,2))) plot(d3,main=paste("h =",round(sigma2,2))) plot(d3,main=paste("h =",round(sigma2,2))) plot(Gest(homicides.ppp),main="Homicidios")
/2_Analisis_puntos/Script02.R
no_license
alequech/Curso-analisis-espacial2018
R
false
false
3,397
r
library(sf) library(sp) library(mapview) library(tidyverse) library(plotrix) library(spatstat) library(maptools) library(raster) setwd("C:/Users/Rocket/Google Drive/1.Materias/Analisis_espacial/2_Analisis_puntos") data<-read.csv("input/crime-lat-long.csv") str(data) summary(data$lat) summary(data$long) data<-data[!is.na(data$long)&!is.na(data$lat),] data<-data[data$year==2013,] summary(data$lat) summary(data$long) #https://hoyodecrimen.com/ #zero <- zerodist(data) border <- shapefile("input/DF_Delegaciones.shp") #crime_sf = st_as_sf(data, coords = c("long", "lat"), crs = 4326) #rs<-st_crs(border) #st_crs(c)<-rs coordinates(data)=~long+lat plot(data,pch="+",cex=0.5,main="",col=data$crime) plot(border,add=T) legend(x=-0.53,y=51.41,pch="+",legend=unique(data$crime),cex=0.4) projection(data)=projection(border) #crime_utm<-st_transform(crime_sf,crs=6369) #border_utm<-st_transform(border,crs=6369) data_utm<-spTransform(data, CRS("+init=epsg:6369")) border_utm<-spTransform(border, CRS("+init=epsg:6369")) x_coord<-data_utm@coords[,1] y_coord<-data_utm@coords[,2] mean_centerX<-mean(data_utm@coords[,1]) mean_centerY<-mean(data_utm@coords[,2]) standard_deviationX <- sd(x_coord) standard_deviationY <- sd(y_coord) standard_distance <- sqrt(sum(((x_coord-mean_centerX)^2+(y_coord-mean_centerY)^2))/(nrow(data_utm))) plot(data_utm,pch="+",cex=0.05,main="") plot(border,add=T,cex=0.001) points(mean_centerX,mean_centerY,col="red",pch=16) draw.circle(mean_centerX,mean_centerY,radius=standard_distance,border="red",lwd=2) plot(data_utm,pch="+",cex=0.05,main="") plot(border,add=T,cex=0.001) points(mean_centerX,mean_centerY,col="red",pch=16) draw.ellipse(mean_centerX,mean_centerY,a=standard_deviationX,b=standard_deviationY,border="red",lwd=2) #Homicidios homicides<-data_utm[data_utm$crime=="HOMICIDIO DOLOSO",] homicides <- remove.duplicates(homicides) w<-as(border_utm, "owin") homicides.ppp <- ppp(x=homicides@coords[,1],y=homicides@coords[,2],window=w) homicides.ppp$n/sum(sapply(slot(border_utm, "polygons"), slot, "area")) q<-quadratcount(homicides.ppp, nx = 8, ny = 8) plot(homicides.ppp,pch=20, cols="grey70",cex=0.05,main="Homicidios") plot(q,add=TRUE,col="red") Local.Intensity <- data.frame(Mun=factor(),Number=numeric()) for(i in unique(border_utm$Name)){ sub.pol <- border_utm[border_utm$Name==i,] sub.ppp <- ppp(x=homicides.ppp$x,y=homicides.ppp$y,window=as.owin(sub.pol)) Local.Intensity <- rbind(Local.Intensity,data.frame(Mun=factor(i,levels=border_utm$Name),Number=sub.ppp$n)) } colorScale <- color.scale(Local.Intensity[order(Local.Intensity[,2]),2],color.spec="rgb",extremes=c("green","red"),alpha=0.8) barplot(Local.Intensity[order(Local.Intensity[,2]),2],names.arg=Local.Intensity[order(Local.Intensity[,2]),1],horiz=T,las=2,space=1,col=colorScale) sigma1<- bw.diggle(homicides.ppp) sigma2<- bw.ppl(homicides.ppp) sigma3<- bw.scott(homicides.ppp)[1] sigma4<- bw.scott(homicides.ppp)[2] d1<-density.ppp(homicides.ppp, sigma =sigma1,edge=T) d2<-density.ppp(homicides.ppp, sigma =sigma2,edge=T) d3<-density.ppp(homicides.ppp, sigma =sigma3,edge=T) d4<-density.ppp(homicides.ppp, sigma =sigma4,edge=T) plot(d1,main=paste("h =",round(sigma1,2))) plot(d2,main=paste("h =",round(sigma2,2))) plot(d3,main=paste("h =",round(sigma2,2))) plot(d3,main=paste("h =",round(sigma2,2))) plot(Gest(homicides.ppp),main="Homicidios")
\name{redisMove} \alias{redisMove} \title{ Move the specified key/value pair to another database. } \description{ Move the specified key/value pair in the currently selected database to another database. } \usage{ redisMove(key, dbindex) } \arguments{ \item{key}{The key to move.} \item{dbindex}{The destination database index number.} } \details{ This command returns TRUE only if the key was successfully moved, and FALSE if the target key was already there or if the source key was not found at all. It is possible to use \code{redisMove} as a locking primitive. } \value{ Returns TRUE if the key/value pair was moved, or FALSE otherwise. } \references{ http://redis.io/commands } \author{ B. W. Lewis } \seealso{ \code{\link{redisSelect}} } \examples{ \dontrun{ redisConnect() redisSelect(1) redisSet('x',5) redisMove('x',2) redisSelect(2) redisGet('x') } }
/man/redisMove.Rd
no_license
bwlewis/rredis
R
false
false
869
rd
\name{redisMove} \alias{redisMove} \title{ Move the specified key/value pair to another database. } \description{ Move the specified key/value pair in the currently selected database to another database. } \usage{ redisMove(key, dbindex) } \arguments{ \item{key}{The key to move.} \item{dbindex}{The destination database index number.} } \details{ This command returns TRUE only if the key was successfully moved, and FALSE if the target key was already there or if the source key was not found at all. It is possible to use \code{redisMove} as a locking primitive. } \value{ Returns TRUE if the key/value pair was moved, or FALSE otherwise. } \references{ http://redis.io/commands } \author{ B. W. Lewis } \seealso{ \code{\link{redisSelect}} } \examples{ \dontrun{ redisConnect() redisSelect(1) redisSet('x',5) redisMove('x',2) redisSelect(2) redisGet('x') } }
library(dplyr) library(ggplot2) library(gridExtra) library(rmarkdown) library(car) library(yhat) library(lme4) library(grplasso) library(polycor) #Columns we care about cols = c('resident_status', 'detail_age_type', 'detail_age', 'age_recode_27', 'education_reporting_flag', 'education_2003_revision', 'education_1989_revision', 'sex', 'marital_status', 'race_recode_5', 'hispanic_originrace_recode', 'X39_cause_recode', 'current_data_year' ) #Read the data from 2011 - 2015 and subsample each of them to 40K rows set.seed(100) #to reproduce the results Data1 = read.csv("2015_data.csv",header = TRUE) Data1 = Data1[,cols] Data1s <- Data1[sample(1:nrow(Data1), 40*10^3, replace=FALSE),] Data2 = read.csv("2014_data.csv",header = TRUE) Data2 = Data2[,cols] Data2s <- Data2[sample(1:nrow(Data2), 40*10^3, replace=FALSE),] Data3 = read.csv("2013_data.csv",header = TRUE) Data3 = Data3[,cols] Data3s <- Data3[sample(1:nrow(Data3), 40*10^3, replace=FALSE),] Data4 = read.csv("2012_data.csv",header = TRUE) Data4 = Data4[,cols] Data4s <- Data4[sample(1:nrow(Data4), 40*10^3, replace=FALSE),] Data5 = read.csv("2011_data.csv",header = TRUE) Data5 = Data5[,cols] Data5s <- Data5[sample(1:nrow(Data5), 40*10^3, replace=FALSE),] #Data = Data[,cols] #Data2 = read.csv("2014_data.csv",header = TRUE) Data = rbind(Data1s, Data2s, Data3s, Data4s, Data5s) #Save Memory by removing the data we've stitched together rm(Data1, Data1s, Data2, Data2s, Data3, Data3s, Data4, Data4s, Data5, Data5s) ######################################################################### ## Data Cleaning #Age #get the cases where age is in years Data = Data[Data$detail_age_type == 1, ] Data = Data[Data$age_recode_27 != 27, ] #remove where age is not present Data = Data[Data$age_recode_27 >= 10, ] #filter for only adults >=19 Data$age = Data$detail_age #Data$age_recode_27 = as.factor(Data$age_recode_27) #Education Data = Data[Data$education_reporting_flag != 2, ] #remove where education is not present #recoding education into 3 levels : high school or less, less than 4 year college, greater than 4 years college Data[, 'education'] <- ifelse(is.na(Data$education_2003_revision), cut(Data$education_1989_revision, breaks=c(-1, 12, 15, 17, 100)), cut(Data$education_2003_revision, breaks=c(0,3,5,8, 100))) Data$education = as.factor(Data$education) Data = Data[Data$education != 4,] #remove where education is not reported levels(Data$education) <- c('Up to High School','College < 4 years', 'College > 4 years', 'unknown' ) Data$education <- recode(Data$education, 1 = '') Data$education <- factor(Data$education) #Resident Status Data$resident_status = as.factor(Data$resident_status) levels(Data$resident_status) <- c('Resident', 'Intrastate NR', 'Interstate NR', 'Foreign Residents') #gender #nothing to be done, already a categorical variable #Race Data$race = as.factor(Data$race_recode_5) levels(Data$race) <- c('White', 'Black', 'American Indian', 'Asian/Pacific') #recode hispanic into 3 levels: hispanic, nonhispanic, unreported Data$hispanic_originrace_recode = as.numeric(Data$hispanic_originrace_recode) Data[, 'hispanic'] <- cut(Data$hispanic_originrace_recode, breaks=c(0,5,8,10), labels=c('hispanic','non-hispanic','unknown')) Data = Data[Data$hispanic !='unknown',] #remove where hispanic origin not reported Data$hispanic <- factor(Data$hispanic) #marital_status levels(Data$marital_status) <- c('Divorced', 'Married', 'Never Married', 'Unknown', 'Widowed') #X39_recode_cause Data$cause_of_death = as.factor(Data$X39_cause_recode) levels(Data$cause_of_death) = c("Tuberculosis", "Syphilis", "HIV", "Malignant neoplasms", "Malignant neoplasm Stomach", "Malignant neoplasms of Colon", "Malignant neoplasm of Pancreas (C25)", "Malignant neoplasms of Lung", "Malignant neoplasm of breast", "Malignant neoplasms of Ovary", "Malignant neoplasm of prostate", "Malignant neoplasms of urinary tract", "Non-Hodgkin's lymphoma", "Leukemia", "Other malignant neoplasms", "Diabetes", "Alzheimer's", "Major cardiovascular diseases", "Diseases of heart", "Hypertensive heart disease", "Ischemic heart diseases", "Other diseases of heart", "hypertension and hypertensive renal disease", "Cerebrovascular diseases", "Atherosclerosis", "Other diseases of circulatory system", "Influenza and pneumonia", "Chronic lower respiratory diseases", "Peptic ulcer", "Chronic liver disease and cirrhosis", "Nephritis", "Pregnancy", "Perinatal period", "Congenital malformations", "Sudden infant death syndrome", "Abnormal clinical and laboratory findings", "All other diseases (Residual)", "Motor vehicle accidents", "All other and unspecified accidents", "Suicide", "Assault", "external causes") #current year Data$current_data_year = as.factor(Data$current_data_year) Data$year = Data$current_data_year ##################################################################### cols = c('resident_status', 'age', 'education', 'sex', 'marital_status', 'race', 'hispanic', 'cause_of_death', 'year' ) Data = Data[,cols] ######################################################################## # Exploratory Data Analysis #histogram of the response variable hist(Data$age, breaks=100, xlab='Age at Time of Death', main='') #histogram of age at TOD, makes since it's left tailed # boxplots of response vs qualitative predictors boxplot(Data$age ~ Data$resident_status, ylab='Age', xlab='Resident Status', main='Variation of Age by Residency', col= rainbow(10)) boxplot(Data$age ~ Data$sex, ylab='Age', xlab='Sex', main='Variation of Age by Sex', col= rainbow(10)) boxplot(Data$age ~ Data$race, ylab='Age', xlab='Race', main='Variation of Age by Race', col= rainbow(10)) boxplot(Data$age ~ Data$hispanic, ylab='Age', xlab='Hispanic', main='Variation of Age by Hispanic Origin', col= rainbow(10)) boxplot(Data$age ~ Data$education, ylab='Age', xlab='Education Level', main='Variation of Age by Education', col= rainbow(10)) boxplot(Data$age ~ Data$marital_status, ylab='Age', xlab='Marital Status', main='Variation of Age by Marital Status', col= rainbow(10)) boxplot(Data$age ~ Data$year, ylab='Age', xlab='Year', main='Variation of Age by Year', col= rainbow(10)) boxplot(Data$age ~ Data$cause_of_death, ylab='Age', xlab='Cause of Death', main='Variation of Age by Cause of Death', col= rainbow(30)) #Correlation matrix cor = hetcor(Data) cor$correlations cor$correlations > 0.2 #Build the model model <- lm(age ~ resident_status + sex + marital_status + race + hispanic + education + cause_of_death + year, data=Data) summary(model)$r.squared summary(model)$adjusted.r.squared ggplot(Data[,c('age', 'sex')], aes(x = sex, y = age)) + geom_point(position = position_dodge(width = 0.4)) #Check for multicollinearity vif = vif(model) vif threshold = 1/(1-summary(model)$r.squared) threshold threshold = max(10, threshold) vif > threshold #this shows that there is no multicollinearity ######################################################################## # model selection attach(Data) lambda = seq(0, 10, by=0.25) # VARIABLE SELECTION # Group Lasso predictors = cbind(resident_status, sex, marital_status, race, hispanic, education, cause_of_death) index <- c(4,2,5,4,2,3,42) grouplasso_model <- grplasso(y=Data$age,predictors, lambda=lambda, model=LinReg(), index=index,center=T, standardize=T) summary(grouplasso_model) grouplasso_model$coefficients # None excluded # MODEL BUIDING # MLR Full Model max_model <- lm(age ~ resident_status + sex + marital_status + race + hispanic + education + cause_of_death, data=Data) summary(max_model) # SubSampling for Full model - looking for significant variables count=1 n = nrow(Data) p = matrix(0,nrow = length(summary(max_model)$coefficients[,4]),ncol = 100) while (count<101) { set.seed(100) subsample = sample(n, ceiling(n*0.02), replace = FALSE) subdata = Data[subsample,] submod = lm(age ~ resident_status + sex + marital_status + race + hispanic + education + cause_of_death, data=subdata) p[,count] = summary(submod)$coefficients[,4] count= count + 1 } p[p>0.01] # All significant at 0.05 level summary(submod) # CHECKING ASSUMPTIONS - FULL MODEL full.resid = rstandard(max_model) fits = max_model$fitted cook = cooks.distance(max_model) par(mfrow =c(1,1)) plot(fits, full.resid, xlab="Fitted Values", ylab="Residuals", main="Scatter Plot") abline(0,0,col='blue') plot(cook, type="h", lwd=3, col="red", ylab = "Cook's Distance", main="Cook's Distance") qqPlot(full.resid, ylab="Residuals", main = "QQ Plot") hist(full.resid, xlab="Residuals", main = "Histogram") # LOG TRANSFORMATION OF AGE (RESPONSE) TO SEE IF FIT IMPROVES log_model <- lm(log(age) ~ resident_status + sex + marital_status + race + hispanic + education + cause_of_death, data=Data) summary(log_model) # CHECKING MODEL ASSUMPTIONS - LOG TRANFORMED MODEL log.resid = rstandard(log_model) fits = log_model$fitted plot(fits, log.resid, xlab="Fitted Values", ylab="Residuals", main="Scatter Plot") abline(0,0,col='red') qqPlot(log.resid, ylab="Residuals", main = "QQ Plot") hist(log.resid, xlab="Residuals", main = "Histogram") # MIXED EFFECTS MODEL Data = within(Data,race<-relevel(race,ref='White')) mixed_model <- lmer(age ~ resident_status + sex + marital_status + race + hispanic + education + cause_of_death+ (1|year), data=Data) summary(mixed_model) # vcov(mixed_model) # CHECKING MODEL ASSUMPTIONS - MIXED EFFECTS MODEL # Fitted Values VS Residuals mixed.resid = resid(mixed_model) plot(mixed_model,xlab="Fitted Values", ylab="Residuals") qqPlot(mixed.resid, ylab="Residuals", main = "QQ Plot") # qqnorm(mixed.resid, ylab="Residuals", main = "QQ Plot") qqline(mixed.resid) hist(mixed.resid, xlab="Residuals", main = "Histogram") # MIXED EFFECTS MODEL WITH SUBSET OF DATA with AGE > 40 mixed_age40 <- lmer(age ~ resident_status + sex + marital_status + race + hispanic + education + cause_of_death+ (1|year), data=subdata[subdata$age>=40, ]) summary(mixed_age40) mixed_age40.resid = resid(mixed_age40) plot(mixed_age40,xlab="Fitted Values", ylab="Residuals") abline(0,0,col="purple") qqPlot(mixed_age40.resid, ylab="Residuals", main = "QQ Plot") hist(mixed_age40.resid, xlab="Residuals", main = "Histogram") # ANOVA reduced.resident <- lm(age~resident_status,data=subdata[subdata$age>=40, ]) anova(mixed_age40, reduced.resident) reduced.sex <- lm(age~resident_status + sex,data=subdata[subdata$age>=40, ]) anova(reduced.resident, reduced.sex) reduced.marital_status <- lm(age~resident_status + sex + marital_status,data=subdata[subdata$age>=40, ]) anova(reduced.sex, reduced.marital_status) reduced.race <- lm(age~resident_status + sex + marital_status + race,data=subdata[subdata$age>=40, ]) anova(reduced.marital_status, reduced.race) reduced.education <- lm(age~resident_status + sex + marital_status + race + hispanic,data=subdata[subdata$age>=40, ]) anova(reduced.race, reduced.education) reduced.hispanic <- lm(age~resident_status + sex + marital_status + race + hispanic,data=subdata[subdata$age>=40, ]) anova(reduced.race, reduced.hispanic) # MIXED EFFECTS MODEL ON POPULATIONS WITH AGE <80 mixed_age80 <- lmer(age ~ resident_status + sex + marital_status + race + hispanic + education + cause_of_death+ (1|year), data=subdata[subdata$age<=80, ]) summary(mixed_age80) mixed_age80.resid = resid(mixed_age80) plot(mixed_age80,xlab="Fitted Values", ylab="Residuals") abline(0,0,col="purple") qqPlot(mixed_age80.resid, ylab="Residuals", main = "QQ Plot") hist(mixed_age80.resid, xlab="Residuals", main = "Histogram")
/moratality.R
no_license
kunaalahuja/Mortality-Model
R
false
false
13,158
r
library(dplyr) library(ggplot2) library(gridExtra) library(rmarkdown) library(car) library(yhat) library(lme4) library(grplasso) library(polycor) #Columns we care about cols = c('resident_status', 'detail_age_type', 'detail_age', 'age_recode_27', 'education_reporting_flag', 'education_2003_revision', 'education_1989_revision', 'sex', 'marital_status', 'race_recode_5', 'hispanic_originrace_recode', 'X39_cause_recode', 'current_data_year' ) #Read the data from 2011 - 2015 and subsample each of them to 40K rows set.seed(100) #to reproduce the results Data1 = read.csv("2015_data.csv",header = TRUE) Data1 = Data1[,cols] Data1s <- Data1[sample(1:nrow(Data1), 40*10^3, replace=FALSE),] Data2 = read.csv("2014_data.csv",header = TRUE) Data2 = Data2[,cols] Data2s <- Data2[sample(1:nrow(Data2), 40*10^3, replace=FALSE),] Data3 = read.csv("2013_data.csv",header = TRUE) Data3 = Data3[,cols] Data3s <- Data3[sample(1:nrow(Data3), 40*10^3, replace=FALSE),] Data4 = read.csv("2012_data.csv",header = TRUE) Data4 = Data4[,cols] Data4s <- Data4[sample(1:nrow(Data4), 40*10^3, replace=FALSE),] Data5 = read.csv("2011_data.csv",header = TRUE) Data5 = Data5[,cols] Data5s <- Data5[sample(1:nrow(Data5), 40*10^3, replace=FALSE),] #Data = Data[,cols] #Data2 = read.csv("2014_data.csv",header = TRUE) Data = rbind(Data1s, Data2s, Data3s, Data4s, Data5s) #Save Memory by removing the data we've stitched together rm(Data1, Data1s, Data2, Data2s, Data3, Data3s, Data4, Data4s, Data5, Data5s) ######################################################################### ## Data Cleaning #Age #get the cases where age is in years Data = Data[Data$detail_age_type == 1, ] Data = Data[Data$age_recode_27 != 27, ] #remove where age is not present Data = Data[Data$age_recode_27 >= 10, ] #filter for only adults >=19 Data$age = Data$detail_age #Data$age_recode_27 = as.factor(Data$age_recode_27) #Education Data = Data[Data$education_reporting_flag != 2, ] #remove where education is not present #recoding education into 3 levels : high school or less, less than 4 year college, greater than 4 years college Data[, 'education'] <- ifelse(is.na(Data$education_2003_revision), cut(Data$education_1989_revision, breaks=c(-1, 12, 15, 17, 100)), cut(Data$education_2003_revision, breaks=c(0,3,5,8, 100))) Data$education = as.factor(Data$education) Data = Data[Data$education != 4,] #remove where education is not reported levels(Data$education) <- c('Up to High School','College < 4 years', 'College > 4 years', 'unknown' ) Data$education <- recode(Data$education, 1 = '') Data$education <- factor(Data$education) #Resident Status Data$resident_status = as.factor(Data$resident_status) levels(Data$resident_status) <- c('Resident', 'Intrastate NR', 'Interstate NR', 'Foreign Residents') #gender #nothing to be done, already a categorical variable #Race Data$race = as.factor(Data$race_recode_5) levels(Data$race) <- c('White', 'Black', 'American Indian', 'Asian/Pacific') #recode hispanic into 3 levels: hispanic, nonhispanic, unreported Data$hispanic_originrace_recode = as.numeric(Data$hispanic_originrace_recode) Data[, 'hispanic'] <- cut(Data$hispanic_originrace_recode, breaks=c(0,5,8,10), labels=c('hispanic','non-hispanic','unknown')) Data = Data[Data$hispanic !='unknown',] #remove where hispanic origin not reported Data$hispanic <- factor(Data$hispanic) #marital_status levels(Data$marital_status) <- c('Divorced', 'Married', 'Never Married', 'Unknown', 'Widowed') #X39_recode_cause Data$cause_of_death = as.factor(Data$X39_cause_recode) levels(Data$cause_of_death) = c("Tuberculosis", "Syphilis", "HIV", "Malignant neoplasms", "Malignant neoplasm Stomach", "Malignant neoplasms of Colon", "Malignant neoplasm of Pancreas (C25)", "Malignant neoplasms of Lung", "Malignant neoplasm of breast", "Malignant neoplasms of Ovary", "Malignant neoplasm of prostate", "Malignant neoplasms of urinary tract", "Non-Hodgkin's lymphoma", "Leukemia", "Other malignant neoplasms", "Diabetes", "Alzheimer's", "Major cardiovascular diseases", "Diseases of heart", "Hypertensive heart disease", "Ischemic heart diseases", "Other diseases of heart", "hypertension and hypertensive renal disease", "Cerebrovascular diseases", "Atherosclerosis", "Other diseases of circulatory system", "Influenza and pneumonia", "Chronic lower respiratory diseases", "Peptic ulcer", "Chronic liver disease and cirrhosis", "Nephritis", "Pregnancy", "Perinatal period", "Congenital malformations", "Sudden infant death syndrome", "Abnormal clinical and laboratory findings", "All other diseases (Residual)", "Motor vehicle accidents", "All other and unspecified accidents", "Suicide", "Assault", "external causes") #current year Data$current_data_year = as.factor(Data$current_data_year) Data$year = Data$current_data_year ##################################################################### cols = c('resident_status', 'age', 'education', 'sex', 'marital_status', 'race', 'hispanic', 'cause_of_death', 'year' ) Data = Data[,cols] ######################################################################## # Exploratory Data Analysis #histogram of the response variable hist(Data$age, breaks=100, xlab='Age at Time of Death', main='') #histogram of age at TOD, makes since it's left tailed # boxplots of response vs qualitative predictors boxplot(Data$age ~ Data$resident_status, ylab='Age', xlab='Resident Status', main='Variation of Age by Residency', col= rainbow(10)) boxplot(Data$age ~ Data$sex, ylab='Age', xlab='Sex', main='Variation of Age by Sex', col= rainbow(10)) boxplot(Data$age ~ Data$race, ylab='Age', xlab='Race', main='Variation of Age by Race', col= rainbow(10)) boxplot(Data$age ~ Data$hispanic, ylab='Age', xlab='Hispanic', main='Variation of Age by Hispanic Origin', col= rainbow(10)) boxplot(Data$age ~ Data$education, ylab='Age', xlab='Education Level', main='Variation of Age by Education', col= rainbow(10)) boxplot(Data$age ~ Data$marital_status, ylab='Age', xlab='Marital Status', main='Variation of Age by Marital Status', col= rainbow(10)) boxplot(Data$age ~ Data$year, ylab='Age', xlab='Year', main='Variation of Age by Year', col= rainbow(10)) boxplot(Data$age ~ Data$cause_of_death, ylab='Age', xlab='Cause of Death', main='Variation of Age by Cause of Death', col= rainbow(30)) #Correlation matrix cor = hetcor(Data) cor$correlations cor$correlations > 0.2 #Build the model model <- lm(age ~ resident_status + sex + marital_status + race + hispanic + education + cause_of_death + year, data=Data) summary(model)$r.squared summary(model)$adjusted.r.squared ggplot(Data[,c('age', 'sex')], aes(x = sex, y = age)) + geom_point(position = position_dodge(width = 0.4)) #Check for multicollinearity vif = vif(model) vif threshold = 1/(1-summary(model)$r.squared) threshold threshold = max(10, threshold) vif > threshold #this shows that there is no multicollinearity ######################################################################## # model selection attach(Data) lambda = seq(0, 10, by=0.25) # VARIABLE SELECTION # Group Lasso predictors = cbind(resident_status, sex, marital_status, race, hispanic, education, cause_of_death) index <- c(4,2,5,4,2,3,42) grouplasso_model <- grplasso(y=Data$age,predictors, lambda=lambda, model=LinReg(), index=index,center=T, standardize=T) summary(grouplasso_model) grouplasso_model$coefficients # None excluded # MODEL BUIDING # MLR Full Model max_model <- lm(age ~ resident_status + sex + marital_status + race + hispanic + education + cause_of_death, data=Data) summary(max_model) # SubSampling for Full model - looking for significant variables count=1 n = nrow(Data) p = matrix(0,nrow = length(summary(max_model)$coefficients[,4]),ncol = 100) while (count<101) { set.seed(100) subsample = sample(n, ceiling(n*0.02), replace = FALSE) subdata = Data[subsample,] submod = lm(age ~ resident_status + sex + marital_status + race + hispanic + education + cause_of_death, data=subdata) p[,count] = summary(submod)$coefficients[,4] count= count + 1 } p[p>0.01] # All significant at 0.05 level summary(submod) # CHECKING ASSUMPTIONS - FULL MODEL full.resid = rstandard(max_model) fits = max_model$fitted cook = cooks.distance(max_model) par(mfrow =c(1,1)) plot(fits, full.resid, xlab="Fitted Values", ylab="Residuals", main="Scatter Plot") abline(0,0,col='blue') plot(cook, type="h", lwd=3, col="red", ylab = "Cook's Distance", main="Cook's Distance") qqPlot(full.resid, ylab="Residuals", main = "QQ Plot") hist(full.resid, xlab="Residuals", main = "Histogram") # LOG TRANSFORMATION OF AGE (RESPONSE) TO SEE IF FIT IMPROVES log_model <- lm(log(age) ~ resident_status + sex + marital_status + race + hispanic + education + cause_of_death, data=Data) summary(log_model) # CHECKING MODEL ASSUMPTIONS - LOG TRANFORMED MODEL log.resid = rstandard(log_model) fits = log_model$fitted plot(fits, log.resid, xlab="Fitted Values", ylab="Residuals", main="Scatter Plot") abline(0,0,col='red') qqPlot(log.resid, ylab="Residuals", main = "QQ Plot") hist(log.resid, xlab="Residuals", main = "Histogram") # MIXED EFFECTS MODEL Data = within(Data,race<-relevel(race,ref='White')) mixed_model <- lmer(age ~ resident_status + sex + marital_status + race + hispanic + education + cause_of_death+ (1|year), data=Data) summary(mixed_model) # vcov(mixed_model) # CHECKING MODEL ASSUMPTIONS - MIXED EFFECTS MODEL # Fitted Values VS Residuals mixed.resid = resid(mixed_model) plot(mixed_model,xlab="Fitted Values", ylab="Residuals") qqPlot(mixed.resid, ylab="Residuals", main = "QQ Plot") # qqnorm(mixed.resid, ylab="Residuals", main = "QQ Plot") qqline(mixed.resid) hist(mixed.resid, xlab="Residuals", main = "Histogram") # MIXED EFFECTS MODEL WITH SUBSET OF DATA with AGE > 40 mixed_age40 <- lmer(age ~ resident_status + sex + marital_status + race + hispanic + education + cause_of_death+ (1|year), data=subdata[subdata$age>=40, ]) summary(mixed_age40) mixed_age40.resid = resid(mixed_age40) plot(mixed_age40,xlab="Fitted Values", ylab="Residuals") abline(0,0,col="purple") qqPlot(mixed_age40.resid, ylab="Residuals", main = "QQ Plot") hist(mixed_age40.resid, xlab="Residuals", main = "Histogram") # ANOVA reduced.resident <- lm(age~resident_status,data=subdata[subdata$age>=40, ]) anova(mixed_age40, reduced.resident) reduced.sex <- lm(age~resident_status + sex,data=subdata[subdata$age>=40, ]) anova(reduced.resident, reduced.sex) reduced.marital_status <- lm(age~resident_status + sex + marital_status,data=subdata[subdata$age>=40, ]) anova(reduced.sex, reduced.marital_status) reduced.race <- lm(age~resident_status + sex + marital_status + race,data=subdata[subdata$age>=40, ]) anova(reduced.marital_status, reduced.race) reduced.education <- lm(age~resident_status + sex + marital_status + race + hispanic,data=subdata[subdata$age>=40, ]) anova(reduced.race, reduced.education) reduced.hispanic <- lm(age~resident_status + sex + marital_status + race + hispanic,data=subdata[subdata$age>=40, ]) anova(reduced.race, reduced.hispanic) # MIXED EFFECTS MODEL ON POPULATIONS WITH AGE <80 mixed_age80 <- lmer(age ~ resident_status + sex + marital_status + race + hispanic + education + cause_of_death+ (1|year), data=subdata[subdata$age<=80, ]) summary(mixed_age80) mixed_age80.resid = resid(mixed_age80) plot(mixed_age80,xlab="Fitted Values", ylab="Residuals") abline(0,0,col="purple") qqPlot(mixed_age80.resid, ylab="Residuals", main = "QQ Plot") hist(mixed_age80.resid, xlab="Residuals", main = "Histogram")
##============ Sink warnings and errors to a file ============== ## use the sink() function to wrap all code within it. ##============================================================== zz = file(paste0(Sys.getenv('REPORT_FILES_PATH'), '/.r_rendering.log.txt')) sink(zz) sink(zz, type = 'message') #============== preparation ==================================== options(stringsAsFactors = FALSE) # import libraries #------------------------------------------------------------------ # ADD MORE LIBRARIES HERE IF YOUR TOOL DEPENDS ON OTHER R LIBRARIES #------------------------------------------------------------------ library('getopt') library('rmarkdown') library('htmltools') # load helper functions source(paste0(Sys.getenv('TOOL_INSTALL_DIR'), '/helper.R')) # import getopt specification matrix from a csv file opt = getopt(getopt_specification_matrix('getopt_specification.csv', tool_dir=Sys.getenv('TOOL_INSTALL_DIR'))) # define environment variables for all input values. this is useful when we # want to use input values by other programming language in r markdown do.call(Sys.setenv, opt[-1]) #=============================================================== #======================== render Rmd files ========================= # NOTICE: # we should copy all rmarkdown files from tool install directory to REPORT_FILES_PATH directory. # and render rmarkdown files in the REPORT_FILES_PATH directory. file.copy(from = paste0(Sys.getenv('TOOL_INSTALL_DIR'), '/vakata-jstree-3.3.5'), to = Sys.getenv('REPORT_FILES_PATH'), recursive = TRUE) system(command = 'cp -r ${TOOL_INSTALL_DIR}/*.Rmd ${REPORT_FILES_PATH}') #----------------BELOW IS WHERE YOU NEED TO CUSTOMIZE --------------------- render(input = paste0(Sys.getenv('REPORT_FILES_PATH'), '/skewer.Rmd')) # add more lines below if there are more Rmd files to be rendered #=============================================================== #============== expose outputs to galaxy history =============== system(command = 'sh ${TOOL_INSTALL_DIR}/expose-outputs.sh') #=============================================================== ##--------end of code rendering .Rmd templates---------------- sink() ##=========== End of sinking output=============================
/old-tools/aurora_skewer/skewer_v2.0.0/skewer_render.R
permissive
statonlab/aurora-galaxy-tools
R
false
false
2,299
r
##============ Sink warnings and errors to a file ============== ## use the sink() function to wrap all code within it. ##============================================================== zz = file(paste0(Sys.getenv('REPORT_FILES_PATH'), '/.r_rendering.log.txt')) sink(zz) sink(zz, type = 'message') #============== preparation ==================================== options(stringsAsFactors = FALSE) # import libraries #------------------------------------------------------------------ # ADD MORE LIBRARIES HERE IF YOUR TOOL DEPENDS ON OTHER R LIBRARIES #------------------------------------------------------------------ library('getopt') library('rmarkdown') library('htmltools') # load helper functions source(paste0(Sys.getenv('TOOL_INSTALL_DIR'), '/helper.R')) # import getopt specification matrix from a csv file opt = getopt(getopt_specification_matrix('getopt_specification.csv', tool_dir=Sys.getenv('TOOL_INSTALL_DIR'))) # define environment variables for all input values. this is useful when we # want to use input values by other programming language in r markdown do.call(Sys.setenv, opt[-1]) #=============================================================== #======================== render Rmd files ========================= # NOTICE: # we should copy all rmarkdown files from tool install directory to REPORT_FILES_PATH directory. # and render rmarkdown files in the REPORT_FILES_PATH directory. file.copy(from = paste0(Sys.getenv('TOOL_INSTALL_DIR'), '/vakata-jstree-3.3.5'), to = Sys.getenv('REPORT_FILES_PATH'), recursive = TRUE) system(command = 'cp -r ${TOOL_INSTALL_DIR}/*.Rmd ${REPORT_FILES_PATH}') #----------------BELOW IS WHERE YOU NEED TO CUSTOMIZE --------------------- render(input = paste0(Sys.getenv('REPORT_FILES_PATH'), '/skewer.Rmd')) # add more lines below if there are more Rmd files to be rendered #=============================================================== #============== expose outputs to galaxy history =============== system(command = 'sh ${TOOL_INSTALL_DIR}/expose-outputs.sh') #=============================================================== ##--------end of code rendering .Rmd templates---------------- sink() ##=========== End of sinking output=============================
#' Retrieve data from the Roswell Park Data Commons #' #' @rdname retrieve #' #' @param x An object of class `Rosy`, created and authenticated with #' `rosy()` with subsets defined via `filter()` and `select()`. #' #' @param ... additional arguments; ignored. #' #' @return A tibble containing desired data. #' #' @importFrom tibble as_tibble #' #' @export as_tibble.Rosy <- function(x, ...) { as_tibble() }
/R/retrieve.R
no_license
mtmorgan/rosy
R
false
false
420
r
#' Retrieve data from the Roswell Park Data Commons #' #' @rdname retrieve #' #' @param x An object of class `Rosy`, created and authenticated with #' `rosy()` with subsets defined via `filter()` and `select()`. #' #' @param ... additional arguments; ignored. #' #' @return A tibble containing desired data. #' #' @importFrom tibble as_tibble #' #' @export as_tibble.Rosy <- function(x, ...) { as_tibble() }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/plot.R \name{plot_single_uts_vector} \alias{plot_single_uts_vector} \title{Plot a uts_vector in a single plot} \usage{ plot_single_uts_vector(x, ..., max_dt = ddays(Inf), xlab = "", ylab = "", col = seq_along(x), lty = 1, lwd = 1, pch = 1, type = "l", legend = TRUE, legend.x = "topright", legend.y = NULL) } \arguments{ \item{x}{a \code{"uts_vector"} object with numeric or logical observation values.} \item{\dots}{arguments passed to \code{\link[uts]{plot.uts}}.} \item{max_dt}{a non-negative \code{\link[lubridate]{duration}} object. Consecutive observations that are more than this amount apart in time, are not connected by a line in the graph.} \item{xlab}{a label for the x axis.} \item{ylab}{a label for the y axis} \item{col, lty, lwd, pch, type}{graphical parameters. See \code{\link{plot.default}}.} \item{legend}{boolean. Whether to add a legend to the plot.} \item{legend.x, legend.y}{the x and y co-ordinates to be used to position the legend.} } \description{ A helper function that implements \code{plot.uts_vector} for argument \code{plot.type="single"}. } \examples{ plot_single_uts_vector(ex_uts_vector(), xlab="time") plot_single_uts_vector(ex_uts_vector(), type="o", main="Fruit", max_dt=dhours(12)) plot_single_uts_vector(ex_uts_vector(), type="p", pch=2, ylim=c(40, 60), cex=2) } \seealso{ \code{\link{matplot}} } \keyword{internal}
/man/plot_single_uts_vector.Rd
no_license
yanliangs/utsMultivariate
R
false
true
1,446
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/plot.R \name{plot_single_uts_vector} \alias{plot_single_uts_vector} \title{Plot a uts_vector in a single plot} \usage{ plot_single_uts_vector(x, ..., max_dt = ddays(Inf), xlab = "", ylab = "", col = seq_along(x), lty = 1, lwd = 1, pch = 1, type = "l", legend = TRUE, legend.x = "topright", legend.y = NULL) } \arguments{ \item{x}{a \code{"uts_vector"} object with numeric or logical observation values.} \item{\dots}{arguments passed to \code{\link[uts]{plot.uts}}.} \item{max_dt}{a non-negative \code{\link[lubridate]{duration}} object. Consecutive observations that are more than this amount apart in time, are not connected by a line in the graph.} \item{xlab}{a label for the x axis.} \item{ylab}{a label for the y axis} \item{col, lty, lwd, pch, type}{graphical parameters. See \code{\link{plot.default}}.} \item{legend}{boolean. Whether to add a legend to the plot.} \item{legend.x, legend.y}{the x and y co-ordinates to be used to position the legend.} } \description{ A helper function that implements \code{plot.uts_vector} for argument \code{plot.type="single"}. } \examples{ plot_single_uts_vector(ex_uts_vector(), xlab="time") plot_single_uts_vector(ex_uts_vector(), type="o", main="Fruit", max_dt=dhours(12)) plot_single_uts_vector(ex_uts_vector(), type="p", pch=2, ylim=c(40, 60), cex=2) } \seealso{ \code{\link{matplot}} } \keyword{internal}
#' DataFiltering #' @description CountResponseFractions #' @param data data.frame with colnames \code{response} #' @param response chartacter, that specify name of the column that represents the output response #' @param response.min numeric, lower bound of \code{response}, default \code{response.min = 10^(0)} #' @param response.max numeric, lower bound of \code{response}, default \code{response.max = 10^(4)} #' @return filtered data #' @export DataFiltering <- function( data, response, response.min = 10^(0), response.max = 10^(4) ){ data %>% dplyr::filter( !!!quos(!!sym(response) > response.min, !!sym(response) < response.max ) ) }
/R/preprocess_DataFiltering.R
no_license
stork119/SysBioSigHeterogeneity
R
false
false
721
r
#' DataFiltering #' @description CountResponseFractions #' @param data data.frame with colnames \code{response} #' @param response chartacter, that specify name of the column that represents the output response #' @param response.min numeric, lower bound of \code{response}, default \code{response.min = 10^(0)} #' @param response.max numeric, lower bound of \code{response}, default \code{response.max = 10^(4)} #' @return filtered data #' @export DataFiltering <- function( data, response, response.min = 10^(0), response.max = 10^(4) ){ data %>% dplyr::filter( !!!quos(!!sym(response) > response.min, !!sym(response) < response.max ) ) }
# LOAD, MERGE, AND QC DATA source("setup.R") Mcap.ff.all$year <- ifelse(Mcap.ff.all$date < as.Date("2015-05-07"), "y1", "y2") # # FILTER OUT COLONIES WITH <= 4 OBSERVATIONS ----- nobs <- aggregate(data.frame(obs=Mcap.ff.all$colony), by=list(colony=Mcap.ff.all$colony), FUN=length) Mcap.ff.all <- droplevels(Mcap.ff.all[Mcap.ff.all$colony %in% nobs[nobs$obs > 4, "colony"], ]) Mcap.ff.all <- droplevels(Mcap.ff.all[Mcap.ff.all$reef!="42", ]) # WAS VISUAL BLEACHING SCORE THE SAME IN BOTH YEARS? bscore <- aggregate(data.frame(minscore=Mcap.ff.all$score), by=list(colony=Mcap.ff.all$colony, year=Mcap.ff.all$year), FUN=min, na.rm=T) dcast(bscore, colony ~ year, value.var="minscore") # IDENTIFY COLONIES THAT SHUFFLED SYMBIONTS ----- res <- ldply(levels(Mcap.ff.all$colony), plotpropD) par(mfrow=c(4,2), mar=c(3,3,2,1)) ldply(list(11,71,119,125,40,72,78), plotpropD, method="loess") rownames(res) <- unlist(levels(Mcap.ff.all$colony)) apply(res, 2, table) # Count number of shufflers determined by each fitting technique Mcap.ff.all$shuff <- res[Mcap.ff.all$colony, "loess"] # GROUP COLONIES BY SHUFFLING, BLEACHING, AND DOMINANT CLADE ----- Mcap.ff.all$bleach1 <- ifelse(Mcap.ff.all$colony %in% Mcap.ff.all[Mcap.ff.all$score==1 & Mcap.ff.all$year=="y1", "colony"], "bleach", "notbleached") Mcap.ff.all$bleach2 <- ifelse(Mcap.ff.all$year=="y1", NA, ifelse(is.na(Mcap.ff.all$score), NA, ifelse(Mcap.ff.all$colony %in% Mcap.ff.all[Mcap.ff.all$score==1 & Mcap.ff.all$year=="y2", "colony"], "bleach", "notbleached"))) Mcap.ff.all$group <- as.character(droplevels(interaction(Mcap.ff.all$bleach2, Mcap.ff.all$shuff))) Mcap.ff.all[Mcap.ff.all$group=="notbleached.noshuff", "group"] <- ifelse(Mcap.ff.all[Mcap.ff.all$group=="notbleached.noshuff", "tdom"]=="C", "notbleached.noshuff.C", "notbleached.noshuff.D") Mcap.ff.all$group <- factor(Mcap.ff.all$group) #Mcap.ff.all[Mcap.ff.all$colony=="207", "group"] <- "bleach.shuff" # assume this colony was C-dominated prior to bleaching # ADDITIONAL GROUPING FACTOR BY SURVIVAL OF SECOND BLEACHING EVENT numberofsamplesafter12042015 <- aggregate(data.frame(n=Mcap.ff.all$date>="2015-12-04"), by=list(colony=Mcap.ff.all$colony), FUN=function(x) table(x)[2]) Mcap.ff.all$survival <- ifelse(Mcap.ff.all$colony %in% numberofsamplesafter12042015[numberofsamplesafter12042015$n>=2, "colony"], TRUE, FALSE) Mcap.ff.all$group2 <- interaction(Mcap.ff.all$survival, Mcap.ff.all$group) # IDENTIFY AND COUNT COLONIES IN EACH GROUP cols <- aggregate(Mcap.ff.all$colony, by=list(Mcap.ff.all$group), FUN=function(x) unique(as.character(x))) ncols <- aggregate(Mcap.ff.all$colony, by=list(Mcap.ff.all$group), FUN=function(x) length(unique(as.character(x)))) cols <- aggregate(Mcap.ff.all$colony, by=list(Mcap.ff.all$group2), FUN=function(x) unique(as.character(x))) ncols <- aggregate(Mcap.ff.all$colony, by=list(Mcap.ff.all$group2), FUN=function(x) length(unique(as.character(x)))) #Plot Bleaching vs non bleaching dominant symbiont clade eight11 <- Mcap.ff.all[Mcap.ff.all$date=="2015-08-11",] st <- table(eight11$dom, eight11$bleach2) bars <- barplot(st, col=c("blue","red"), width=1, xlim=c(0,6), ylab="Number of Colonies", names.arg=c("Bleached", "Not Bleached")) text(0.7, 22, labels="n=21", xpd=NA) text(1.9, 26, labels="n=25", xpd=NA) legend("topleft",legend=c("D","C"), bty="n", pt.cex=2, pch=22, pt.bg=c("red","blue")) #Pie chart function for proportion D at a specific timepoint h <- Mcap.ff.all[(Mcap.ff.all$colony=="71" & Mcap.ff.all$date=="2015-10-21"),] htable <- c(h$propD, 1-h$propD) pie(htable) pieintheface <- function(x,y) { h <- Mcap.ff.all[(Mcap.ff.all$colony==x & Mcap.ff.all$date==y),] htable <- c(h$propD, 1-h$propD) lbls <- c("Clade D","Clade C") pct <- round(htable/sum(htable)*100) lbls <- paste(lbls,pct) lbls <- paste(lbls,"%",sep="") pie(htable, col=c("red","blue"), labels=lbls, main=y) } pieintheface("71", "2016-02-11") plotcolony <- function(colony) { df <- Mcap.ff.all[Mcap.ff.all$colony==colony, ] df <- df[order(df$date), ] par(mar=c(5,3,1,1)) plot(df$date, log(df$tot.SH), type="b", pch=21, cex=2, bg=c("blue","lightblue","pink","red")[df$syms], ylim=c(-11,1), xlab="", ylab="Log SH", xaxt="n") dates <- as.Date(c("2014-10-24","2014-11-04","2014-11-24","2014-12-16","2015-01-14","2015-05-06","2015-08-11", "2015-09-14", "2015-10-01", "2015-10-21", "2015-11-04", "2015-12-04","2015-12-17", "2016-01-20", "2016-02-11","2016-03-31")) axis(side=1, at=dates, labels=FALSE) text(x=dates, y=par("usr")[3]-.2, srt=45, labels=as.character(dates), xpd=NA, pos=2) legend("topleft", legend=c("C","C>D","D>C","D"), pch=21, pt.cex=2, pt.bg=c("blue","lightblue","pink","red")) } plotcolony(11) #plot mortality dead <- condition[condition$mortality=="3",] missing <- condition[condition$mortality=="missing",] plot(condition$date, condition$mortality) condition <- condition[!condition$colony %in% missing$colony,] condition <- condition[condition$reef!="42",] table <- table(condition$mortality, condition$date, condition$reef) table HIMB <- table[,,1] HIMB <- melt(HIMB) HIMB2or3 <- aggregate(HIMB$value, by=list(HIMB$Var1 %in% c(2,3), HIMB$Var2), FUN=sum) HIMB2or3 <- HIMB2or3[HIMB2or3$Group.1==T, ] HIMB2or3 plot(as.Date(HIMB2or3$Group.2), HIMB2or3$x, type="o", col="magenta", xlab="Date", ylab="Number of Colonies over 50% Dead", Main="Mortality over Time") lines(as.Date(TF2or3$Group.2), TF2or3$x, type="o",col="purple") lines(as.Date(FF2or3$Group.2), FF2or3$x, type="o",col="turquoise") legend("topleft", legend=c("Reef HIMB","Reef 25", "Reef 44"), fill=c("magenta","purple","turquoise")) TF <- table[,,2] TF <- melt(TF) TF2or3 <- aggregate(TF$value, by=list(TF$Var1 %in% c(2,3), TF$Var2), FUN=sum) TF2or3 <- TF2or3[TF2or3$Group.1==T, ] TF2or3 plot(as.Date(TF2or3$Group.2), TF2or3$x, type="o") FF <- table[,,3] FF <- melt(FF) FF2or3 <- aggregate(FF$value, by=list(FF$Var1 %in% c(2,3), FF$Var2), FUN=sum) FF2or3 <- FF2or3[FF2or3$Group.1==T, ] FF2or3 plot(as.Date(FF2or3$Group.2), FF2or3$x, type="o") table1 <-table(condition$mortality, condition$date) table1 All <- melt(table1) All All2or3 <- aggregate(All$value, by=list(All$Var1 %in% c(2,3), All$Var2), FUN=sum) All2or3 <- All2or3[All2or3$Group.1==T, ] All2or3 plot(as.Date(All2or3$Group.2), All2or3$x, type="o", col="magenta", xlab="Date", ylab="Number of Colonies over 50% Dead") abline(v=c()) nlevels(droplevels(condition$colony)) dev.off() Byr2 <- subset(Mcap.ff.all, bleach2=="bleach") NByr2 <- subset(Mcap.ff.all, bleach2=="notbleached") head(Byr2) plot(Mcap.ff.all$date, log(Mcap.ff.all$tot.SH)) table(Mcap.ff.all$date, log(Mcap.ff.all$tot.SH)) # PLOT SYMBIONT ABUNDANCE AND COMPOSITION FOR INDIVIDUAL COLONIES ----- # XYPLOT ALL COLONIES IN EACH GROUP xyplot(log(tot.SH) ~ date | group, groups=~colony, ylim=c(-11,1), data=Mcap.ff.all, type="o", cex=0.25) xyplot(propD ~ date | group, groups=~colony, ylim=c(-0.1,1.1), data=Mcap.ff.all, type="o", cex=0.25) # XYPLOT INDIVIDUAL COLONIES BY GROUP, RAW DATA for (g in levels(Mcap.ff.all$group)) { df <- subset(Mcap.ff.all, group==g) print(doubleYScale( # Plot total S/H with GAM fit xyplot(log(tot.SH) ~ date | colony, ylim=c(-11,1), data=df, type="o", cex=0.25, main=g), # Plot propD with locfit xyplot(propD ~ date | colony, ylim=c(-0.1, 1.1), data=df, type="o", cex=0.25) )) } # XYPLOT INDIVIDUAL COLONIES BY GROUP, FITTED RESPONSES for (g in levels(Mcap.ff.all$group)) { df <- subset(Mcap.ff.all, group==g) print(doubleYScale( # Plot total S/H with GAM fit xyplot(log(tot.SH) ~ days | colony, ylim=c(-11,1), data=df, main=g, panel = function(x, y, ...) { panel.xyplot(x, y, cex=0.5, ...) dayrange <- seq(min(x), max(x), 1) tryCatch({ m <- gam(y ~ s(x), family="gaussian") p <- predict(m, newdata=data.frame(x=dayrange)) panel.lines(p ~ dayrange) }, error=function(e) { m <- gam(y ~ s(x, k=3), family="gaussian") p <- predict(m, newdata=data.frame(x=dayrange)) panel.lines(p ~ dayrange) }, warning=function(w) print(w)) }), # Plot propD with locfit xyplot(propD ~ days | colony, ylim=c(-0.1, 1.1), data=df, panel = function(x, y, ...) { panel.xyplot(x, y, cex=0.25, ...) dayrange <- seq(min(x), max(x), 1) tryCatch({ m <- locfit(y ~ lp(x, nn=1), family="betar", lfproc=locfit.raw) p <- predict(m, newdata=data.frame(x=dayrange)) panel.lines(p ~ dayrange) CtoD <- dayrange[which(diff(sign(p-0.5))>0)] DtoC <- dayrange[which(diff(sign(p-0.5))<0)] panel.xyplot(c(CtoD, DtoC), rep(0.5, length(c(CtoD, DtoC))), pch="*", cex=2, col="red") }, error=function(e) print(e), warning=function(w) print(w)) }) )) } # MODEL SYMBIONT ABUNDANCE AND COMPOSITION FOR EACH GROUP ----- # Exclude groups that didn't quite make it df <- Mcap.ff.all[as.numeric(Mcap.ff.all$group2) %in% c(2,4,6,8,10), ] df <- droplevels(df) # FIT PROPD GAMM BY GROUP xyplot(propD ~ days | group2, data=df) propDmod <- gamm4(propD ~ group2 + s(days, by=group2), random=~(1|colony), data=df) # FIT TOTSH GAMM BY GROUP xyplot(log(tot.SH) ~ days | group, data=df) totSHmod <- gamm4(log(tot.SH) ~ group2 + s(days, by=group2), random=~(1|colony), data=df) # GET FITTED VALUES FOR EACH GROUP newdata <- expand.grid(days=seq(0,524,1), group2=levels(df$group2)) newdata$tot.SH <- predict(totSHmod$gam, newdata) newdata$propD <- predict(propDmod$gam, newdata) newdata$predse <- predict(totSHmod$gam, newdata, se.fit=T)$se.fit # PLOT FITTED VALUES FOR EACH GROUP xyplot(tot.SH ~ days, groups=~group2, newdata) xyplot(propD ~ days, groups=~group2, newdata, ylim=c(0,1)) doubleYScale(xyplot(tot.SH ~ days | group2, newdata, type="l"), xyplot(propD ~ days | group2, newdata, type="l", ylim=c(-0.1,1.1))) # PLOT FITTED RESPONSES FOR EACH GROUP, MULTIPANEL SHUFFLERS vs. NONSHUFFLERS ----- rbPal <- colorRampPalette(c('dodgerblue','red')) newdata$color <- rbPal(100)[as.numeric(cut(newdata$propD, breaks = 100))] par(mfrow=c(2,1), mar=c(1,3,1,2), mgp=c(1.5,0.4,0), tcl=-0.25) plot(NA, ylim=c(-7,0), xlim=range(newdata$days), xaxs="i", xaxt="n", yaxt="n", ylab="") axis(side=2, at=seq(-7,-1,1), cex.axis=0.75) dateticks <- seq.Date(as.Date("2014-11-01"), as.Date("2016-02-01"), by="month") axis(side=1, at=as.numeric(dateticks-as.Date("2014-10-24")), labels=NA) for (group2 in levels(newdata$group2)[c(1,3,4)]) { df <- newdata[newdata$group2==group2, ] addpoly(df$days, df$tot.SH - 1.96*df$predse, df$tot.SH + 1.96*df$predse, col=alpha("gray", 0.7)) } points(tot.SH ~ days, newdata[as.numeric(newdata$group2) %in% c(1,3,4), ], pch=21, col=color, bg=color) text(par("usr")[1], quantile(par("usr")[3:4], 0.9), pos=4, expression(bold("A. Non-shuffling colonies"))) gradient.rect(quantile(par("usr")[1:2], 0.1), quantile(par("usr")[3:4], 0.1), quantile(par("usr")[1:2], 0.35), quantile(par("usr")[3:4], 0.175), col=rbPal(100), border=NA) text(quantile(par("usr")[1:2], c(0.1, 0.35)), rep(quantile(par("usr")[3:4], 0.1375), 2), pos=c(2,4), labels=c("C", "D"), cex=0.75) par(mar=c(2,3,0,2)) plot(NA, ylim=c(-7,0), xlim=range(newdata$days), xaxs="i", xlab="", ylab="", xaxt="n", yaxt="n", xpd=NA) axis(side=2, at=seq(-7,-1,1), cex.axis=0.75) mtext(side=2, text="Symbiont abundance (ln S/H)", line=-1.5, outer=T) dateticks <- seq.Date(as.Date("2014-11-01"), as.Date("2016-02-01"), by="month") axis(side=1, at=as.numeric(dateticks-as.Date("2014-10-24")), labels=format(dateticks, "%b"), cex.axis=0.75) for (group2 in levels(df$group2)[c(2,5)]) { df <- newdata[newdata$group2==group2, ] addpoly(df$days, df$tot.SH - 1.96*df$predse, df$tot.SH + 1.96*df$predse, col=alpha("gray", 0.7)) } points(tot.SH ~ days, newdata[as.numeric(newdata$group2) %in% c(2,5), ], pch=21, col=color, bg=color) gradient.rect(quantile(par("usr")[1:2], 0.1), quantile(par("usr")[3:4], 0.1), quantile(par("usr")[1:2], 0.35), quantile(par("usr")[3:4], 0.175), col=rbPal(100), border=NA) text(quantile(par("usr")[1:2], c(0.1, 0.35)), rep(quantile(par("usr")[3:4], 0.1375), 2), pos=c(2,4), labels=c("C", "D"), cex=0.75) text(par("usr")[1], quantile(par("usr")[3:4], 0.9), pos=4, expression(bold("B. Shuffling colonies"))) # DOES SHUFFLING DEPEND ON REEF? MC <- unique(Mcap.ff.all[, c("colony", "reef","shuff","bleach", "group", "depth")]) MC$shuff <- factor(MC$shuff) MCb <- droplevels(MC[MC$bleach=="bleach", ]) plot(MCb$group ~ MCb$reef) chisq.test(MCb$reef, MCb$group) MCnb <- droplevels(MC[MC$bleach=="notbleached", ]) plot(MCnb$group ~ MCnb$reef) chisq.test(MCnb$reef, MCnb$group) # DOES SHUFFLING DEPEND ON DEPTH? plot(shuff ~ depth, MCb) chisq.test(MCb$depth, MCb$shuff) plot(as.numeric(shuff) ~ depth, MCnb) # DOES SHUFFLING RELATE TO BLEACHING SEVERITY? bsev <- aggregate(data.frame(minscore=Mcap.ff.all$tot.SH), by=list(colony=Mcap.ff.all$colony), FUN=min, na.rm=T) bsev <- merge(MCb, bsev) plot(bsev$shuff ~ log(bsev$minscore)) plot(as.numeric(bsev$shuff) ~ log(bsev$minscore)) mod <- glm(shuff ~ depth * log(minscore), family="binomial", data=bsev) plot(mod) anova(mod, test="Chisq") plot(effect("depth:log(minscore)", mod), x.var="minscore") plot(effect("depth", mod)) # HEATMAP OF SHUFFLING --------- # Create matrix for image function clades <- melt(Mcap.f, id.vars=c("colony", "date", "vis", "reef", "tdom"), measure.vars="syms", factorsAsStrings=FALSE) head(clades) clades$value <- as.numeric(factor(clades$value)) clades <- unique(clades) clades <- dcast(clades, vis + colony + reef + tdom ~ date, drop=T) head(clades) clades[is.na(clades)] <- -1 # Recode missing values as -1 #clades[which(clades$colony=="129"), 8:10] <- -2 # Recode mortality as -2 clades.m0 <- clades[with(clades, order(clades[, 12], clades[, 5], clades[, 7], clades[, 8], clades[, 9], clades[, 10])), ] clades.m <- as.matrix(clades.m0[,5:12]) rownames(clades.m) <- as.character(clades.m0$colony) # Plot figure library(RColorBrewer) par(mfrow=c(1,1), mar=c(3,5,2,2), bg="white") image(x=seq(1, ncol(clades.m)), y=seq(1, nrow(clades.m)), z=t(clades.m), xaxt="n", yaxt="n", xlab="", ylab="", breaks=c(-2,-1.1,0,1,2,3,4,5), col=c("black", "white", rev(brewer.pal(11, "RdYlBu")[c(2,1,3,9,11)]))) # Plot date axis #axis(side=3, at=seq(1:8), labels=FALSE, cex.axis=0.75, par("tck"=-0.025), xpd=T) text(0.5:7.5, par("usr")[4], xpd=T, cex=0.6, pos=4, labels=levels(Mcap$fdate), srt=45, adj=-0.1) # # Plot Bleached vs. Not Bleached rectangles # rect(par("usr")[1] - 2.25, par("usr")[3], par("usr")[1] - 1.25, par("usr")[4], xpd=T) # text(par("usr")[1] - 1.75, quantile(par("usr")[3:4])[c(2, 4)], labels=c("Not Bleached", "Bleached"), # srt=90, xpd=2) # Plot colony numbers text(0, 1:nrow(clades.m), labels=rownames(clades.m), xpd=T, cex=0.5) # get shufflers Mcap[which(Mcap$colony %in% c(71,54,40,119)), ] head(clades.m) # Plot Row Side Colors reefcols <- c("#bebada", "#8dd3c7", "#d9d9d9") for (i in 1:nrow(clades.m0)) { reef <- clades.m0$reef[i] rect(par("usr")[1] - 1.25, par("usr")[3] + 1 * (i - 1), par("usr")[1] - 0.25, par("usr")[3] + 1 * (i - 1) + 1, col=reefcols[as.numeric(reef)], xpd=T, border=NA) } rect(par("usr")[1] - 1.25, par("usr")[3], par("usr")[1] - 0.25, par("usr")[4], xpd=T) lines(x=c(par("usr")[1] - 2.25, par("usr")[1] - 0.25), y=rep(quantile(par("usr")[3:4], 0.5), 2), xpd=T) # Plot tdom side boxes breaks <- c(0, which(diff(as.numeric(clades.m0$tdom))!=0), length(clades.m0$tdom)) doms <- clades.m0$tdom[breaks] for (i in 2:length(breaks)) { rect(par("usr")[2] + 0.25, par("usr")[3] + breaks[i-1], par("usr")[2] + 0.75, par("usr")[3] + breaks[i], xpd=T) } for (i in 1:(length(breaks)-1)) { text(par("usr")[2] + 0.5, (breaks[i] + breaks[i+1]) / 2, paste(doms[i], "dominant"), xpd=T, srt=90, cex=0.75) } # Plot Row Side Color Key for (i in 1:3) { rect(par("usr")[1] - 1.25, quantile(par("usr")[3:4], 0) * -1.05 - ((i - 1) * 1), par("usr")[1] - 0.25, quantile(par("usr")[3:4], 0) * -1.05 - ((i - 1) * 1) - 1, xpd=T, border=NA, col=reefcols[i]) } rect(par("usr")[1] - 1.25, quantile(par("usr")[3:4], 0) * -1.05, par("usr")[1] - 0.25, quantile(par("usr")[3:4], 0) * -1.05 - 3, xpd=T) axis(side=2, xpd=T, pos=par("usr")[1] - 1.25, lwd=0, lwd.ticks=0, at=c(-1, -2, -3), labels=c("Rf 25", "Rf 44", "HIMB"), las=2, cex.axis=0.6, mgp=c(0,0.4,0)) # Plot Heatmap Key x <- quantile(par("usr")[1:2], probs=seq(0, 1, length.out=7)) y <- rep(quantile(par("usr")[3:4], 0) * -1.05, 2) - c(0, 1) rect(x[1], y[1], x[7], y[2], xpd=T) for (i in 1:6) { rect(x[i], y[1], x[i + 1], y[2], xpd=T, border=NA, col=c(brewer.pal(11, "RdYlBu")[c(1,3,9,11)], "white", "black")[i]) } text(xpd=T, y=y[1] - 0.75, pos=1, cex=0.6, x=seq(par("usr")[1], par("usr")[2], length=7)[-7] + 0.5, labels=c("D only", "D > C", "C > D", "C only", "no data", "dead")) text(xpd=T, y=quantile(par("usr")[3:4], 0) * -1.05 - 2.5, pos=1, cex=0.9, x=quantile(par("usr")[1:2], 0.5), labels=expression(italic(Symbiodinium)~clades)) # MODEL TRAJECTORIES USING SPIDA ------ # Model trajectories of symbiont populations over time using mixed model # Build piecewise polynomial model with knot at 82 days (January time point) # From October to January, fit a quadratic polynomial (1st element of degree=2) # From January to May, fit a linear model (2nd element of degree=1) # Function is continuous at time=82 days (smooth=0) Mcap.ff$days <- as.numeric(Mcap.ff$date - as.Date("2015-08-11")) #offset <- 0 # optional to center "days" axis at any point sp <- function(x) gsp(x, knots=c(51,85,128), degree=c(2,3,2,2)) #sp <- function(x) cs(x) #sp <- function(x) bs(x, knots=c(71,128)) # Build full model with fixed effects of vis, tdom, reef, and time, random effect of colony Mcapdf <- Mcap.ff[Mcap.ff$reef!="42",] #mod.all.full <- lmerTest::lmer(log(Mcapdf$tot.SH) ~ sp(Mcapdf$days) * Mcapdf$vis * Mcapdf$reef + (sp(Mcapdf$days) | Mcapdf$colony)) #mod.all.full <- lmerTest::lmer(log(tot.SH) ~ poly(days, 3) * vis * reef + (1 | colony), data=Mcap.ff[Mcap.ff$reef!="42",]) #plot(Effect(c("days", "vis", "reef"), mod.all.full, xlevels=list(days=unique(Mcap.ff$days))), # multiline=T, z.var="reef", ci.style="bars") # Test significance of fixed effects by backwards selection #modselect <- step(mod.all.full, lsmeans.calc=F, difflsmeans.calc=F, alpha.fixed=0.05) #modselect #summary(mod.all.full) # Rebuild model omitting non-significant fixed effects #mod.all <- mod.all.full # Identify outliers with standardized residuals > 2.5 #out <- abs(residuals(mod.all)) > sd(residuals(mod.all)) * 2.5 #Mcap.ff[out, ] # outlying data points # Refit model without outliers #Mcapdf <- Mcapdf[!out, ] mod.all <- lmerTest::lmer(log(tot.SH) ~ sp(days) * vis * reef + (1 | colony), data=Mcapdf) #mod.all <- mod.all.full # Print and save ANOVA table for model anovatab <- anova(mod.all) #write.csv(round(anovatab, digits=3), file="output/Table1.csv") # pseudo-r2 value-- squared correlation between fitted and observed values summary(lm(model.response(model.frame(mod.all)) ~ fitted(mod.all)))$r.squared # Plotting function plotreefs <- function(mod, n) { dat <- get(as.character(summary(mod)$call$data)) dat <- droplevels(dat) levs <- expand.grid(reef=levels(dat$reef), vis=levels(dat$vis), days=as.numeric(levels(as.factor(dat$days)))) datlevs <- list(interaction(dat$reef, dat$vis, dat$days)) datsumm <- data.frame(levs, mean=with(dat, aggregate(log(tot.SH), by=datlevs, FUN=mean)$x), sd=with(dat, aggregate(log(tot.SH), by=datlevs, FUN=sd)$x), se=with(dat, aggregate(log(tot.SH), by=datlevs, FUN=function(x) sd(x)/sqrt(length(x)))$x), conf95=with(dat, aggregate(log(tot.SH), by=datlevs, FUN=function(x) sd(x)/sqrt(length(x)) * qt(0.975, length(x)-1))$x)) datlist <- split(datsumm, f=datsumm$reef) datlist <- lapply(datlist, function(x) rev(split(x, f=x$vis))) pred <- expand.grid(days=seq_len(max(dat$days)), reef=levels(dat$reef), vis=levels(dat$vis)) bootfit <- bootMer(mod, FUN=function(x) predict(x, pred, re.form=NA), nsim=n) # Extract 90% confidence interval on predicted values pred$fit <- predict(mod, pred, re.form=NA) pred$lci <- apply(bootfit$t, 2, quantile, 0.05) pred$uci <- apply(bootfit$t, 2, quantile, 0.95) predlist <- split(pred, f=pred$reef) predlist <- lapply(predlist, function(x) rev(split(x, f=x$vis))) par(mgp=c(1.75,0.4,0), oma=c(0,0,0,0)) par(mar=c(0,3,0.3,1)) layout(mat=matrix(seq_len(nlevels(dat$reef)+1))) for (reef in levels(dat$reef)) { with(datlist[[reef]], { # Create plot frame for each reef plot(NA, xlim=range(dat$days), ylim=c(-9,-1), xaxt="n", bty="n", tck=-0.03, ylab="ln S/H") title(paste("Reef", reef), line=-0.9, adj=0, outer=F) # Plot model fit line and shaded CI for bleached and/or not bleached corals with(predlist[[reef]], { lapply(predlist[[reef]], function(vis) { addpoly(vis$days, vis$lci, vis$uci, col=alpha(reefcols[[reef]], 0.4), xpd=NA) lines(vis$days, vis$fit, lty=vislty[[vis$vis[1]]]) }) }) # Plot raw data +/- standard error lapply(datlist[[reef]], function(vis) { arrows(vis$days, vis$mean + vis$se, vis$days, vis$mean - vis$se, code=3, angle=90, length=0.03, xpd=NA) points(vis$days, vis$mean, pch=vispch[[vis$vis[1]]], bg=visbg[[vis$vis[1]]]) }) }) #rect(xleft = 0, ybottom = -6, xright = 82, ytop = -1, lty = 3, border="black") } axis(side=1, at=as.numeric(as.Date(c("2015-08-01", "2015-09-01", "2015-10-01", "2015-11-01", "2015-12-01", "2016-01-01", "2016-02-01")) - as.Date("2015-08-11")), labels=c("Aug", "Sep", "Oct", "Nov", "Dec", "Jan", "Feb")) return(list(predlist=predlist, datlist=datlist)) } # Plot reefcols <- list(`25`="#bebada", `44`="#8dd3c7", HIMB="#d9d9d9", `42`="green") vislty <- list("bleached"=2, "not bleached"=1) vispch <- list("bleached"=24, "not bleached"=21) visbg <- list("bleached"="white", "not bleached"="black") modelplot <- plotreefs(mod.all, 99) Mcap42 <- Mcap.ff[Mcap.ff$reef==42,] sp2 <- function(x) gsp(x, knots=c(85,128), degree=c(2,2,2)) mod.42 <- lmerTest::lmer(log(tot.SH) ~ sp2(days) * vis + (1 | colony), data=Mcap42) plot42 <- function(mod, n) { dat <- get(as.character(summary(mod)$call$data)) dat <- droplevels(dat) levs <- expand.grid(vis=levels(dat$vis), days=as.numeric(levels(as.factor(dat$days)))) datlevs <- list(interaction(dat$vis, dat$days)) datsumm <- data.frame(levs, mean=with(dat, aggregate(log(tot.SH), by=datlevs, FUN=mean)$x), sd=with(dat, aggregate(log(tot.SH), by=datlevs, FUN=sd)$x), se=with(dat, aggregate(log(tot.SH), by=datlevs, FUN=function(x) sd(x)/sqrt(length(x)))$x), conf95=with(dat, aggregate(log(tot.SH), by=datlevs, FUN=function(x) sd(x)/sqrt(length(x)) * qt(0.975, length(x)-1))$x)) datlist <- split(datsumm, f=datsumm$vis) pred <- expand.grid(days=seq(min(dat$days), max(dat$days)), vis=levels(dat$vis)) bootfit <- bootMer(mod, FUN=function(x) predict(x, pred, re.form=NA), nsim=n) # Extract 90% confidence interval on predicted values pred$fit <- predict(mod, pred, re.form=NA) pred$lci <- apply(bootfit$t, 2, quantile, 0.05) pred$uci <- apply(bootfit$t, 2, quantile, 0.95) predlist <- split(pred, f=pred$vis) plot(NA, xlim=c(0, max(dat$days)), ylim=c(-9,-1), xaxt="n", bty="n", tck=-0.03, ylab="ln S/H") title("Reef 42", line=-0.9, adj=0, outer=F) # Plot model fit line and shaded CI for bleached and/or not bleached corals with(predlist, { lapply(predlist, function(vis) { addpoly(vis$days, vis$lci, vis$uci, col=alpha("green", 0.4), xpd=NA) lines(vis$days, vis$fit, lty=vislty[[vis$vis[1]]]) }) }) # Plot raw data +/- standard error lapply(datlist, function(vis) { arrows(vis$days, vis$mean + vis$se, vis$days, vis$mean - vis$se, code=3, angle=90, length=0.03, xpd=NA) points(vis$days, vis$mean, pch=vispch[[vis$vis[1]]], bg=visbg[[vis$vis[1]]]) }) #rect(xleft = 0, ybottom = -6, xright = 82, ytop = -1, lty = 3, border="black") return(list(predlist=predlist, datlist=datlist)) } plot42(mod.42, 99) # MODEL TRAJECTORIES FOR BOTH YEARS Mcap.ff.all$days <- as.numeric(Mcap.ff.all$date - as.Date("2014-10-24")) Mcap.ff.all$days <- scale(Mcap.ff.all$days) points <- unique(Mcap.ff.all$days) knots <- points[c(5,7,9,11,13)] sp <- function(x) gsp(x, knots=knots, degree=c(2,1,2,3,2,1), smooth=c(0,1,1,1,1)) Mcapdf <- Mcap.ff.all[Mcap.ff.all$reef!="42",] Mcapdf$reef <- factor(Mcapdf$reef, levels=c("44","25","HIMB")) Mcapdf$batch <- Mcapdf$days < 195 mod.all <- lmerTest::lmer(log(tot.SH) ~ sp(days) * vis * reef + (1 | colony), data=Mcapdf) #anova(mod.all) summary(lm(model.response(model.frame(mod.all)) ~ fitted(mod.all)))$r.squared plotreefs <- function(mod, n) { dat <- get(as.character(summary(mod)$call$data)) dat <- droplevels(dat) levs <- expand.grid(reef=levels(dat$reef), vis=levels(dat$vis), days=as.numeric(levels(as.factor(dat$days)))) datlevs <- list(interaction(dat$reef, dat$vis, dat$days)) datsumm <- data.frame(levs, mean=with(dat, aggregate(log(tot.SH), by=datlevs, FUN=mean)$x), sd=with(dat, aggregate(log(tot.SH), by=datlevs, FUN=sd)$x), se=with(dat, aggregate(log(tot.SH), by=datlevs, FUN=function(x) sd(x)/sqrt(length(x)))$x), conf95=with(dat, aggregate(log(tot.SH), by=datlevs, FUN=function(x) sd(x)/sqrt(length(x)) * qt(0.975, length(x)-1))$x)) datlist <- split(datsumm, f=datsumm$reef) datlist <- lapply(datlist, function(x) rev(split(x, f=x$vis))) pred <- expand.grid(days=seq(min(dat$days), max(dat$days), length.out=475), reef=levels(dat$reef), vis=levels(dat$vis)) bootfit <- bootMer(mod, FUN=function(x) predict(x, pred, re.form=NA), nsim=n) # Extract 90% confidence interval on predicted values pred$fit <- predict(mod, pred, re.form=NA) pred$lci <- apply(bootfit$t, 2, quantile, 0.05) pred$uci <- apply(bootfit$t, 2, quantile, 0.95) predlist <- split(pred, f=pred$reef) predlist <- lapply(predlist, function(x) rev(split(x, f=x$vis))) par(mgp=c(1.75,0.4,0), oma=c(0,0,0,0)) par(mar=c(0,3,0.3,1)) layout(mat=matrix(seq_len(nlevels(dat$reef)+1))) for (reef in levels(dat$reef)) { with(datlist[[reef]], { # Create plot frame for each reef plot(NA, xlim=range(dat$days), ylim=c(-9,0), xaxt="n", bty="n", tck=-0.03, ylab="ln S/H") title(paste("Reef", reef), line=-0.9, adj=0, outer=F) # Plot model fit line and shaded CI for bleached and/or not bleached corals with(predlist[[reef]], { lapply(predlist[[reef]], function(vis) { addpoly(vis$days, vis$lci, vis$uci, col=alpha(reefcols[[reef]], 0.4), xpd=NA) lines(vis$days, vis$fit, lty=vislty[[vis$vis[1]]]) }) }) # Plot raw data +/- standard error lapply(datlist[[reef]], function(vis) { arrows(vis$days, vis$mean + vis$se, vis$days, vis$mean - vis$se, code=3, angle=90, length=0.03, xpd=NA) points(vis$days, vis$mean, pch=vispch[[vis$vis[1]]], bg=visbg[[vis$vis[1]]]) }) }) #rect(xleft = 0, ybottom = -6, xright = 82, ytop = -1, lty = 3, border="black") } axdates <- seq.Date(as.Date("2014-11-01"), as.Date("2016-04-01"), by="month") unscaled <- Mcap.ff.all$days * attr(Mcap.ff.all$days, 'scaled:scale') + attr(Mcap.ff.all$days, 'scaled:center') axdays <- as.numeric(axdates - as.Date("2014-10-24")) tdays <- scales::rescale(axdays, to=range(dat$days), from=range(unscaled)) axis(side=1, at=tdays, labels=format(axdates, format="%b\n%y"), padj=1) return(list(predlist=predlist, datlist=datlist)) } # Plot reefcols <- list(`25`="#bebada", `44`="#8dd3c7", HIMB="#d9d9d9", `42`="green") vislty <- list("bleached"=2, "not bleached"=1) vispch <- list("bleached"=24, "not bleached"=21) visbg <- list("bleached"="white", "not bleached"="black") modelplot <- plotreefs(mod.all, 99)
/analysis.R
no_license
jrcunning/kbayrecov2015
R
false
false
28,373
r
# LOAD, MERGE, AND QC DATA source("setup.R") Mcap.ff.all$year <- ifelse(Mcap.ff.all$date < as.Date("2015-05-07"), "y1", "y2") # # FILTER OUT COLONIES WITH <= 4 OBSERVATIONS ----- nobs <- aggregate(data.frame(obs=Mcap.ff.all$colony), by=list(colony=Mcap.ff.all$colony), FUN=length) Mcap.ff.all <- droplevels(Mcap.ff.all[Mcap.ff.all$colony %in% nobs[nobs$obs > 4, "colony"], ]) Mcap.ff.all <- droplevels(Mcap.ff.all[Mcap.ff.all$reef!="42", ]) # WAS VISUAL BLEACHING SCORE THE SAME IN BOTH YEARS? bscore <- aggregate(data.frame(minscore=Mcap.ff.all$score), by=list(colony=Mcap.ff.all$colony, year=Mcap.ff.all$year), FUN=min, na.rm=T) dcast(bscore, colony ~ year, value.var="minscore") # IDENTIFY COLONIES THAT SHUFFLED SYMBIONTS ----- res <- ldply(levels(Mcap.ff.all$colony), plotpropD) par(mfrow=c(4,2), mar=c(3,3,2,1)) ldply(list(11,71,119,125,40,72,78), plotpropD, method="loess") rownames(res) <- unlist(levels(Mcap.ff.all$colony)) apply(res, 2, table) # Count number of shufflers determined by each fitting technique Mcap.ff.all$shuff <- res[Mcap.ff.all$colony, "loess"] # GROUP COLONIES BY SHUFFLING, BLEACHING, AND DOMINANT CLADE ----- Mcap.ff.all$bleach1 <- ifelse(Mcap.ff.all$colony %in% Mcap.ff.all[Mcap.ff.all$score==1 & Mcap.ff.all$year=="y1", "colony"], "bleach", "notbleached") Mcap.ff.all$bleach2 <- ifelse(Mcap.ff.all$year=="y1", NA, ifelse(is.na(Mcap.ff.all$score), NA, ifelse(Mcap.ff.all$colony %in% Mcap.ff.all[Mcap.ff.all$score==1 & Mcap.ff.all$year=="y2", "colony"], "bleach", "notbleached"))) Mcap.ff.all$group <- as.character(droplevels(interaction(Mcap.ff.all$bleach2, Mcap.ff.all$shuff))) Mcap.ff.all[Mcap.ff.all$group=="notbleached.noshuff", "group"] <- ifelse(Mcap.ff.all[Mcap.ff.all$group=="notbleached.noshuff", "tdom"]=="C", "notbleached.noshuff.C", "notbleached.noshuff.D") Mcap.ff.all$group <- factor(Mcap.ff.all$group) #Mcap.ff.all[Mcap.ff.all$colony=="207", "group"] <- "bleach.shuff" # assume this colony was C-dominated prior to bleaching # ADDITIONAL GROUPING FACTOR BY SURVIVAL OF SECOND BLEACHING EVENT numberofsamplesafter12042015 <- aggregate(data.frame(n=Mcap.ff.all$date>="2015-12-04"), by=list(colony=Mcap.ff.all$colony), FUN=function(x) table(x)[2]) Mcap.ff.all$survival <- ifelse(Mcap.ff.all$colony %in% numberofsamplesafter12042015[numberofsamplesafter12042015$n>=2, "colony"], TRUE, FALSE) Mcap.ff.all$group2 <- interaction(Mcap.ff.all$survival, Mcap.ff.all$group) # IDENTIFY AND COUNT COLONIES IN EACH GROUP cols <- aggregate(Mcap.ff.all$colony, by=list(Mcap.ff.all$group), FUN=function(x) unique(as.character(x))) ncols <- aggregate(Mcap.ff.all$colony, by=list(Mcap.ff.all$group), FUN=function(x) length(unique(as.character(x)))) cols <- aggregate(Mcap.ff.all$colony, by=list(Mcap.ff.all$group2), FUN=function(x) unique(as.character(x))) ncols <- aggregate(Mcap.ff.all$colony, by=list(Mcap.ff.all$group2), FUN=function(x) length(unique(as.character(x)))) #Plot Bleaching vs non bleaching dominant symbiont clade eight11 <- Mcap.ff.all[Mcap.ff.all$date=="2015-08-11",] st <- table(eight11$dom, eight11$bleach2) bars <- barplot(st, col=c("blue","red"), width=1, xlim=c(0,6), ylab="Number of Colonies", names.arg=c("Bleached", "Not Bleached")) text(0.7, 22, labels="n=21", xpd=NA) text(1.9, 26, labels="n=25", xpd=NA) legend("topleft",legend=c("D","C"), bty="n", pt.cex=2, pch=22, pt.bg=c("red","blue")) #Pie chart function for proportion D at a specific timepoint h <- Mcap.ff.all[(Mcap.ff.all$colony=="71" & Mcap.ff.all$date=="2015-10-21"),] htable <- c(h$propD, 1-h$propD) pie(htable) pieintheface <- function(x,y) { h <- Mcap.ff.all[(Mcap.ff.all$colony==x & Mcap.ff.all$date==y),] htable <- c(h$propD, 1-h$propD) lbls <- c("Clade D","Clade C") pct <- round(htable/sum(htable)*100) lbls <- paste(lbls,pct) lbls <- paste(lbls,"%",sep="") pie(htable, col=c("red","blue"), labels=lbls, main=y) } pieintheface("71", "2016-02-11") plotcolony <- function(colony) { df <- Mcap.ff.all[Mcap.ff.all$colony==colony, ] df <- df[order(df$date), ] par(mar=c(5,3,1,1)) plot(df$date, log(df$tot.SH), type="b", pch=21, cex=2, bg=c("blue","lightblue","pink","red")[df$syms], ylim=c(-11,1), xlab="", ylab="Log SH", xaxt="n") dates <- as.Date(c("2014-10-24","2014-11-04","2014-11-24","2014-12-16","2015-01-14","2015-05-06","2015-08-11", "2015-09-14", "2015-10-01", "2015-10-21", "2015-11-04", "2015-12-04","2015-12-17", "2016-01-20", "2016-02-11","2016-03-31")) axis(side=1, at=dates, labels=FALSE) text(x=dates, y=par("usr")[3]-.2, srt=45, labels=as.character(dates), xpd=NA, pos=2) legend("topleft", legend=c("C","C>D","D>C","D"), pch=21, pt.cex=2, pt.bg=c("blue","lightblue","pink","red")) } plotcolony(11) #plot mortality dead <- condition[condition$mortality=="3",] missing <- condition[condition$mortality=="missing",] plot(condition$date, condition$mortality) condition <- condition[!condition$colony %in% missing$colony,] condition <- condition[condition$reef!="42",] table <- table(condition$mortality, condition$date, condition$reef) table HIMB <- table[,,1] HIMB <- melt(HIMB) HIMB2or3 <- aggregate(HIMB$value, by=list(HIMB$Var1 %in% c(2,3), HIMB$Var2), FUN=sum) HIMB2or3 <- HIMB2or3[HIMB2or3$Group.1==T, ] HIMB2or3 plot(as.Date(HIMB2or3$Group.2), HIMB2or3$x, type="o", col="magenta", xlab="Date", ylab="Number of Colonies over 50% Dead", Main="Mortality over Time") lines(as.Date(TF2or3$Group.2), TF2or3$x, type="o",col="purple") lines(as.Date(FF2or3$Group.2), FF2or3$x, type="o",col="turquoise") legend("topleft", legend=c("Reef HIMB","Reef 25", "Reef 44"), fill=c("magenta","purple","turquoise")) TF <- table[,,2] TF <- melt(TF) TF2or3 <- aggregate(TF$value, by=list(TF$Var1 %in% c(2,3), TF$Var2), FUN=sum) TF2or3 <- TF2or3[TF2or3$Group.1==T, ] TF2or3 plot(as.Date(TF2or3$Group.2), TF2or3$x, type="o") FF <- table[,,3] FF <- melt(FF) FF2or3 <- aggregate(FF$value, by=list(FF$Var1 %in% c(2,3), FF$Var2), FUN=sum) FF2or3 <- FF2or3[FF2or3$Group.1==T, ] FF2or3 plot(as.Date(FF2or3$Group.2), FF2or3$x, type="o") table1 <-table(condition$mortality, condition$date) table1 All <- melt(table1) All All2or3 <- aggregate(All$value, by=list(All$Var1 %in% c(2,3), All$Var2), FUN=sum) All2or3 <- All2or3[All2or3$Group.1==T, ] All2or3 plot(as.Date(All2or3$Group.2), All2or3$x, type="o", col="magenta", xlab="Date", ylab="Number of Colonies over 50% Dead") abline(v=c()) nlevels(droplevels(condition$colony)) dev.off() Byr2 <- subset(Mcap.ff.all, bleach2=="bleach") NByr2 <- subset(Mcap.ff.all, bleach2=="notbleached") head(Byr2) plot(Mcap.ff.all$date, log(Mcap.ff.all$tot.SH)) table(Mcap.ff.all$date, log(Mcap.ff.all$tot.SH)) # PLOT SYMBIONT ABUNDANCE AND COMPOSITION FOR INDIVIDUAL COLONIES ----- # XYPLOT ALL COLONIES IN EACH GROUP xyplot(log(tot.SH) ~ date | group, groups=~colony, ylim=c(-11,1), data=Mcap.ff.all, type="o", cex=0.25) xyplot(propD ~ date | group, groups=~colony, ylim=c(-0.1,1.1), data=Mcap.ff.all, type="o", cex=0.25) # XYPLOT INDIVIDUAL COLONIES BY GROUP, RAW DATA for (g in levels(Mcap.ff.all$group)) { df <- subset(Mcap.ff.all, group==g) print(doubleYScale( # Plot total S/H with GAM fit xyplot(log(tot.SH) ~ date | colony, ylim=c(-11,1), data=df, type="o", cex=0.25, main=g), # Plot propD with locfit xyplot(propD ~ date | colony, ylim=c(-0.1, 1.1), data=df, type="o", cex=0.25) )) } # XYPLOT INDIVIDUAL COLONIES BY GROUP, FITTED RESPONSES for (g in levels(Mcap.ff.all$group)) { df <- subset(Mcap.ff.all, group==g) print(doubleYScale( # Plot total S/H with GAM fit xyplot(log(tot.SH) ~ days | colony, ylim=c(-11,1), data=df, main=g, panel = function(x, y, ...) { panel.xyplot(x, y, cex=0.5, ...) dayrange <- seq(min(x), max(x), 1) tryCatch({ m <- gam(y ~ s(x), family="gaussian") p <- predict(m, newdata=data.frame(x=dayrange)) panel.lines(p ~ dayrange) }, error=function(e) { m <- gam(y ~ s(x, k=3), family="gaussian") p <- predict(m, newdata=data.frame(x=dayrange)) panel.lines(p ~ dayrange) }, warning=function(w) print(w)) }), # Plot propD with locfit xyplot(propD ~ days | colony, ylim=c(-0.1, 1.1), data=df, panel = function(x, y, ...) { panel.xyplot(x, y, cex=0.25, ...) dayrange <- seq(min(x), max(x), 1) tryCatch({ m <- locfit(y ~ lp(x, nn=1), family="betar", lfproc=locfit.raw) p <- predict(m, newdata=data.frame(x=dayrange)) panel.lines(p ~ dayrange) CtoD <- dayrange[which(diff(sign(p-0.5))>0)] DtoC <- dayrange[which(diff(sign(p-0.5))<0)] panel.xyplot(c(CtoD, DtoC), rep(0.5, length(c(CtoD, DtoC))), pch="*", cex=2, col="red") }, error=function(e) print(e), warning=function(w) print(w)) }) )) } # MODEL SYMBIONT ABUNDANCE AND COMPOSITION FOR EACH GROUP ----- # Exclude groups that didn't quite make it df <- Mcap.ff.all[as.numeric(Mcap.ff.all$group2) %in% c(2,4,6,8,10), ] df <- droplevels(df) # FIT PROPD GAMM BY GROUP xyplot(propD ~ days | group2, data=df) propDmod <- gamm4(propD ~ group2 + s(days, by=group2), random=~(1|colony), data=df) # FIT TOTSH GAMM BY GROUP xyplot(log(tot.SH) ~ days | group, data=df) totSHmod <- gamm4(log(tot.SH) ~ group2 + s(days, by=group2), random=~(1|colony), data=df) # GET FITTED VALUES FOR EACH GROUP newdata <- expand.grid(days=seq(0,524,1), group2=levels(df$group2)) newdata$tot.SH <- predict(totSHmod$gam, newdata) newdata$propD <- predict(propDmod$gam, newdata) newdata$predse <- predict(totSHmod$gam, newdata, se.fit=T)$se.fit # PLOT FITTED VALUES FOR EACH GROUP xyplot(tot.SH ~ days, groups=~group2, newdata) xyplot(propD ~ days, groups=~group2, newdata, ylim=c(0,1)) doubleYScale(xyplot(tot.SH ~ days | group2, newdata, type="l"), xyplot(propD ~ days | group2, newdata, type="l", ylim=c(-0.1,1.1))) # PLOT FITTED RESPONSES FOR EACH GROUP, MULTIPANEL SHUFFLERS vs. NONSHUFFLERS ----- rbPal <- colorRampPalette(c('dodgerblue','red')) newdata$color <- rbPal(100)[as.numeric(cut(newdata$propD, breaks = 100))] par(mfrow=c(2,1), mar=c(1,3,1,2), mgp=c(1.5,0.4,0), tcl=-0.25) plot(NA, ylim=c(-7,0), xlim=range(newdata$days), xaxs="i", xaxt="n", yaxt="n", ylab="") axis(side=2, at=seq(-7,-1,1), cex.axis=0.75) dateticks <- seq.Date(as.Date("2014-11-01"), as.Date("2016-02-01"), by="month") axis(side=1, at=as.numeric(dateticks-as.Date("2014-10-24")), labels=NA) for (group2 in levels(newdata$group2)[c(1,3,4)]) { df <- newdata[newdata$group2==group2, ] addpoly(df$days, df$tot.SH - 1.96*df$predse, df$tot.SH + 1.96*df$predse, col=alpha("gray", 0.7)) } points(tot.SH ~ days, newdata[as.numeric(newdata$group2) %in% c(1,3,4), ], pch=21, col=color, bg=color) text(par("usr")[1], quantile(par("usr")[3:4], 0.9), pos=4, expression(bold("A. Non-shuffling colonies"))) gradient.rect(quantile(par("usr")[1:2], 0.1), quantile(par("usr")[3:4], 0.1), quantile(par("usr")[1:2], 0.35), quantile(par("usr")[3:4], 0.175), col=rbPal(100), border=NA) text(quantile(par("usr")[1:2], c(0.1, 0.35)), rep(quantile(par("usr")[3:4], 0.1375), 2), pos=c(2,4), labels=c("C", "D"), cex=0.75) par(mar=c(2,3,0,2)) plot(NA, ylim=c(-7,0), xlim=range(newdata$days), xaxs="i", xlab="", ylab="", xaxt="n", yaxt="n", xpd=NA) axis(side=2, at=seq(-7,-1,1), cex.axis=0.75) mtext(side=2, text="Symbiont abundance (ln S/H)", line=-1.5, outer=T) dateticks <- seq.Date(as.Date("2014-11-01"), as.Date("2016-02-01"), by="month") axis(side=1, at=as.numeric(dateticks-as.Date("2014-10-24")), labels=format(dateticks, "%b"), cex.axis=0.75) for (group2 in levels(df$group2)[c(2,5)]) { df <- newdata[newdata$group2==group2, ] addpoly(df$days, df$tot.SH - 1.96*df$predse, df$tot.SH + 1.96*df$predse, col=alpha("gray", 0.7)) } points(tot.SH ~ days, newdata[as.numeric(newdata$group2) %in% c(2,5), ], pch=21, col=color, bg=color) gradient.rect(quantile(par("usr")[1:2], 0.1), quantile(par("usr")[3:4], 0.1), quantile(par("usr")[1:2], 0.35), quantile(par("usr")[3:4], 0.175), col=rbPal(100), border=NA) text(quantile(par("usr")[1:2], c(0.1, 0.35)), rep(quantile(par("usr")[3:4], 0.1375), 2), pos=c(2,4), labels=c("C", "D"), cex=0.75) text(par("usr")[1], quantile(par("usr")[3:4], 0.9), pos=4, expression(bold("B. Shuffling colonies"))) # DOES SHUFFLING DEPEND ON REEF? MC <- unique(Mcap.ff.all[, c("colony", "reef","shuff","bleach", "group", "depth")]) MC$shuff <- factor(MC$shuff) MCb <- droplevels(MC[MC$bleach=="bleach", ]) plot(MCb$group ~ MCb$reef) chisq.test(MCb$reef, MCb$group) MCnb <- droplevels(MC[MC$bleach=="notbleached", ]) plot(MCnb$group ~ MCnb$reef) chisq.test(MCnb$reef, MCnb$group) # DOES SHUFFLING DEPEND ON DEPTH? plot(shuff ~ depth, MCb) chisq.test(MCb$depth, MCb$shuff) plot(as.numeric(shuff) ~ depth, MCnb) # DOES SHUFFLING RELATE TO BLEACHING SEVERITY? bsev <- aggregate(data.frame(minscore=Mcap.ff.all$tot.SH), by=list(colony=Mcap.ff.all$colony), FUN=min, na.rm=T) bsev <- merge(MCb, bsev) plot(bsev$shuff ~ log(bsev$minscore)) plot(as.numeric(bsev$shuff) ~ log(bsev$minscore)) mod <- glm(shuff ~ depth * log(minscore), family="binomial", data=bsev) plot(mod) anova(mod, test="Chisq") plot(effect("depth:log(minscore)", mod), x.var="minscore") plot(effect("depth", mod)) # HEATMAP OF SHUFFLING --------- # Create matrix for image function clades <- melt(Mcap.f, id.vars=c("colony", "date", "vis", "reef", "tdom"), measure.vars="syms", factorsAsStrings=FALSE) head(clades) clades$value <- as.numeric(factor(clades$value)) clades <- unique(clades) clades <- dcast(clades, vis + colony + reef + tdom ~ date, drop=T) head(clades) clades[is.na(clades)] <- -1 # Recode missing values as -1 #clades[which(clades$colony=="129"), 8:10] <- -2 # Recode mortality as -2 clades.m0 <- clades[with(clades, order(clades[, 12], clades[, 5], clades[, 7], clades[, 8], clades[, 9], clades[, 10])), ] clades.m <- as.matrix(clades.m0[,5:12]) rownames(clades.m) <- as.character(clades.m0$colony) # Plot figure library(RColorBrewer) par(mfrow=c(1,1), mar=c(3,5,2,2), bg="white") image(x=seq(1, ncol(clades.m)), y=seq(1, nrow(clades.m)), z=t(clades.m), xaxt="n", yaxt="n", xlab="", ylab="", breaks=c(-2,-1.1,0,1,2,3,4,5), col=c("black", "white", rev(brewer.pal(11, "RdYlBu")[c(2,1,3,9,11)]))) # Plot date axis #axis(side=3, at=seq(1:8), labels=FALSE, cex.axis=0.75, par("tck"=-0.025), xpd=T) text(0.5:7.5, par("usr")[4], xpd=T, cex=0.6, pos=4, labels=levels(Mcap$fdate), srt=45, adj=-0.1) # # Plot Bleached vs. Not Bleached rectangles # rect(par("usr")[1] - 2.25, par("usr")[3], par("usr")[1] - 1.25, par("usr")[4], xpd=T) # text(par("usr")[1] - 1.75, quantile(par("usr")[3:4])[c(2, 4)], labels=c("Not Bleached", "Bleached"), # srt=90, xpd=2) # Plot colony numbers text(0, 1:nrow(clades.m), labels=rownames(clades.m), xpd=T, cex=0.5) # get shufflers Mcap[which(Mcap$colony %in% c(71,54,40,119)), ] head(clades.m) # Plot Row Side Colors reefcols <- c("#bebada", "#8dd3c7", "#d9d9d9") for (i in 1:nrow(clades.m0)) { reef <- clades.m0$reef[i] rect(par("usr")[1] - 1.25, par("usr")[3] + 1 * (i - 1), par("usr")[1] - 0.25, par("usr")[3] + 1 * (i - 1) + 1, col=reefcols[as.numeric(reef)], xpd=T, border=NA) } rect(par("usr")[1] - 1.25, par("usr")[3], par("usr")[1] - 0.25, par("usr")[4], xpd=T) lines(x=c(par("usr")[1] - 2.25, par("usr")[1] - 0.25), y=rep(quantile(par("usr")[3:4], 0.5), 2), xpd=T) # Plot tdom side boxes breaks <- c(0, which(diff(as.numeric(clades.m0$tdom))!=0), length(clades.m0$tdom)) doms <- clades.m0$tdom[breaks] for (i in 2:length(breaks)) { rect(par("usr")[2] + 0.25, par("usr")[3] + breaks[i-1], par("usr")[2] + 0.75, par("usr")[3] + breaks[i], xpd=T) } for (i in 1:(length(breaks)-1)) { text(par("usr")[2] + 0.5, (breaks[i] + breaks[i+1]) / 2, paste(doms[i], "dominant"), xpd=T, srt=90, cex=0.75) } # Plot Row Side Color Key for (i in 1:3) { rect(par("usr")[1] - 1.25, quantile(par("usr")[3:4], 0) * -1.05 - ((i - 1) * 1), par("usr")[1] - 0.25, quantile(par("usr")[3:4], 0) * -1.05 - ((i - 1) * 1) - 1, xpd=T, border=NA, col=reefcols[i]) } rect(par("usr")[1] - 1.25, quantile(par("usr")[3:4], 0) * -1.05, par("usr")[1] - 0.25, quantile(par("usr")[3:4], 0) * -1.05 - 3, xpd=T) axis(side=2, xpd=T, pos=par("usr")[1] - 1.25, lwd=0, lwd.ticks=0, at=c(-1, -2, -3), labels=c("Rf 25", "Rf 44", "HIMB"), las=2, cex.axis=0.6, mgp=c(0,0.4,0)) # Plot Heatmap Key x <- quantile(par("usr")[1:2], probs=seq(0, 1, length.out=7)) y <- rep(quantile(par("usr")[3:4], 0) * -1.05, 2) - c(0, 1) rect(x[1], y[1], x[7], y[2], xpd=T) for (i in 1:6) { rect(x[i], y[1], x[i + 1], y[2], xpd=T, border=NA, col=c(brewer.pal(11, "RdYlBu")[c(1,3,9,11)], "white", "black")[i]) } text(xpd=T, y=y[1] - 0.75, pos=1, cex=0.6, x=seq(par("usr")[1], par("usr")[2], length=7)[-7] + 0.5, labels=c("D only", "D > C", "C > D", "C only", "no data", "dead")) text(xpd=T, y=quantile(par("usr")[3:4], 0) * -1.05 - 2.5, pos=1, cex=0.9, x=quantile(par("usr")[1:2], 0.5), labels=expression(italic(Symbiodinium)~clades)) # MODEL TRAJECTORIES USING SPIDA ------ # Model trajectories of symbiont populations over time using mixed model # Build piecewise polynomial model with knot at 82 days (January time point) # From October to January, fit a quadratic polynomial (1st element of degree=2) # From January to May, fit a linear model (2nd element of degree=1) # Function is continuous at time=82 days (smooth=0) Mcap.ff$days <- as.numeric(Mcap.ff$date - as.Date("2015-08-11")) #offset <- 0 # optional to center "days" axis at any point sp <- function(x) gsp(x, knots=c(51,85,128), degree=c(2,3,2,2)) #sp <- function(x) cs(x) #sp <- function(x) bs(x, knots=c(71,128)) # Build full model with fixed effects of vis, tdom, reef, and time, random effect of colony Mcapdf <- Mcap.ff[Mcap.ff$reef!="42",] #mod.all.full <- lmerTest::lmer(log(Mcapdf$tot.SH) ~ sp(Mcapdf$days) * Mcapdf$vis * Mcapdf$reef + (sp(Mcapdf$days) | Mcapdf$colony)) #mod.all.full <- lmerTest::lmer(log(tot.SH) ~ poly(days, 3) * vis * reef + (1 | colony), data=Mcap.ff[Mcap.ff$reef!="42",]) #plot(Effect(c("days", "vis", "reef"), mod.all.full, xlevels=list(days=unique(Mcap.ff$days))), # multiline=T, z.var="reef", ci.style="bars") # Test significance of fixed effects by backwards selection #modselect <- step(mod.all.full, lsmeans.calc=F, difflsmeans.calc=F, alpha.fixed=0.05) #modselect #summary(mod.all.full) # Rebuild model omitting non-significant fixed effects #mod.all <- mod.all.full # Identify outliers with standardized residuals > 2.5 #out <- abs(residuals(mod.all)) > sd(residuals(mod.all)) * 2.5 #Mcap.ff[out, ] # outlying data points # Refit model without outliers #Mcapdf <- Mcapdf[!out, ] mod.all <- lmerTest::lmer(log(tot.SH) ~ sp(days) * vis * reef + (1 | colony), data=Mcapdf) #mod.all <- mod.all.full # Print and save ANOVA table for model anovatab <- anova(mod.all) #write.csv(round(anovatab, digits=3), file="output/Table1.csv") # pseudo-r2 value-- squared correlation between fitted and observed values summary(lm(model.response(model.frame(mod.all)) ~ fitted(mod.all)))$r.squared # Plotting function plotreefs <- function(mod, n) { dat <- get(as.character(summary(mod)$call$data)) dat <- droplevels(dat) levs <- expand.grid(reef=levels(dat$reef), vis=levels(dat$vis), days=as.numeric(levels(as.factor(dat$days)))) datlevs <- list(interaction(dat$reef, dat$vis, dat$days)) datsumm <- data.frame(levs, mean=with(dat, aggregate(log(tot.SH), by=datlevs, FUN=mean)$x), sd=with(dat, aggregate(log(tot.SH), by=datlevs, FUN=sd)$x), se=with(dat, aggregate(log(tot.SH), by=datlevs, FUN=function(x) sd(x)/sqrt(length(x)))$x), conf95=with(dat, aggregate(log(tot.SH), by=datlevs, FUN=function(x) sd(x)/sqrt(length(x)) * qt(0.975, length(x)-1))$x)) datlist <- split(datsumm, f=datsumm$reef) datlist <- lapply(datlist, function(x) rev(split(x, f=x$vis))) pred <- expand.grid(days=seq_len(max(dat$days)), reef=levels(dat$reef), vis=levels(dat$vis)) bootfit <- bootMer(mod, FUN=function(x) predict(x, pred, re.form=NA), nsim=n) # Extract 90% confidence interval on predicted values pred$fit <- predict(mod, pred, re.form=NA) pred$lci <- apply(bootfit$t, 2, quantile, 0.05) pred$uci <- apply(bootfit$t, 2, quantile, 0.95) predlist <- split(pred, f=pred$reef) predlist <- lapply(predlist, function(x) rev(split(x, f=x$vis))) par(mgp=c(1.75,0.4,0), oma=c(0,0,0,0)) par(mar=c(0,3,0.3,1)) layout(mat=matrix(seq_len(nlevels(dat$reef)+1))) for (reef in levels(dat$reef)) { with(datlist[[reef]], { # Create plot frame for each reef plot(NA, xlim=range(dat$days), ylim=c(-9,-1), xaxt="n", bty="n", tck=-0.03, ylab="ln S/H") title(paste("Reef", reef), line=-0.9, adj=0, outer=F) # Plot model fit line and shaded CI for bleached and/or not bleached corals with(predlist[[reef]], { lapply(predlist[[reef]], function(vis) { addpoly(vis$days, vis$lci, vis$uci, col=alpha(reefcols[[reef]], 0.4), xpd=NA) lines(vis$days, vis$fit, lty=vislty[[vis$vis[1]]]) }) }) # Plot raw data +/- standard error lapply(datlist[[reef]], function(vis) { arrows(vis$days, vis$mean + vis$se, vis$days, vis$mean - vis$se, code=3, angle=90, length=0.03, xpd=NA) points(vis$days, vis$mean, pch=vispch[[vis$vis[1]]], bg=visbg[[vis$vis[1]]]) }) }) #rect(xleft = 0, ybottom = -6, xright = 82, ytop = -1, lty = 3, border="black") } axis(side=1, at=as.numeric(as.Date(c("2015-08-01", "2015-09-01", "2015-10-01", "2015-11-01", "2015-12-01", "2016-01-01", "2016-02-01")) - as.Date("2015-08-11")), labels=c("Aug", "Sep", "Oct", "Nov", "Dec", "Jan", "Feb")) return(list(predlist=predlist, datlist=datlist)) } # Plot reefcols <- list(`25`="#bebada", `44`="#8dd3c7", HIMB="#d9d9d9", `42`="green") vislty <- list("bleached"=2, "not bleached"=1) vispch <- list("bleached"=24, "not bleached"=21) visbg <- list("bleached"="white", "not bleached"="black") modelplot <- plotreefs(mod.all, 99) Mcap42 <- Mcap.ff[Mcap.ff$reef==42,] sp2 <- function(x) gsp(x, knots=c(85,128), degree=c(2,2,2)) mod.42 <- lmerTest::lmer(log(tot.SH) ~ sp2(days) * vis + (1 | colony), data=Mcap42) plot42 <- function(mod, n) { dat <- get(as.character(summary(mod)$call$data)) dat <- droplevels(dat) levs <- expand.grid(vis=levels(dat$vis), days=as.numeric(levels(as.factor(dat$days)))) datlevs <- list(interaction(dat$vis, dat$days)) datsumm <- data.frame(levs, mean=with(dat, aggregate(log(tot.SH), by=datlevs, FUN=mean)$x), sd=with(dat, aggregate(log(tot.SH), by=datlevs, FUN=sd)$x), se=with(dat, aggregate(log(tot.SH), by=datlevs, FUN=function(x) sd(x)/sqrt(length(x)))$x), conf95=with(dat, aggregate(log(tot.SH), by=datlevs, FUN=function(x) sd(x)/sqrt(length(x)) * qt(0.975, length(x)-1))$x)) datlist <- split(datsumm, f=datsumm$vis) pred <- expand.grid(days=seq(min(dat$days), max(dat$days)), vis=levels(dat$vis)) bootfit <- bootMer(mod, FUN=function(x) predict(x, pred, re.form=NA), nsim=n) # Extract 90% confidence interval on predicted values pred$fit <- predict(mod, pred, re.form=NA) pred$lci <- apply(bootfit$t, 2, quantile, 0.05) pred$uci <- apply(bootfit$t, 2, quantile, 0.95) predlist <- split(pred, f=pred$vis) plot(NA, xlim=c(0, max(dat$days)), ylim=c(-9,-1), xaxt="n", bty="n", tck=-0.03, ylab="ln S/H") title("Reef 42", line=-0.9, adj=0, outer=F) # Plot model fit line and shaded CI for bleached and/or not bleached corals with(predlist, { lapply(predlist, function(vis) { addpoly(vis$days, vis$lci, vis$uci, col=alpha("green", 0.4), xpd=NA) lines(vis$days, vis$fit, lty=vislty[[vis$vis[1]]]) }) }) # Plot raw data +/- standard error lapply(datlist, function(vis) { arrows(vis$days, vis$mean + vis$se, vis$days, vis$mean - vis$se, code=3, angle=90, length=0.03, xpd=NA) points(vis$days, vis$mean, pch=vispch[[vis$vis[1]]], bg=visbg[[vis$vis[1]]]) }) #rect(xleft = 0, ybottom = -6, xright = 82, ytop = -1, lty = 3, border="black") return(list(predlist=predlist, datlist=datlist)) } plot42(mod.42, 99) # MODEL TRAJECTORIES FOR BOTH YEARS Mcap.ff.all$days <- as.numeric(Mcap.ff.all$date - as.Date("2014-10-24")) Mcap.ff.all$days <- scale(Mcap.ff.all$days) points <- unique(Mcap.ff.all$days) knots <- points[c(5,7,9,11,13)] sp <- function(x) gsp(x, knots=knots, degree=c(2,1,2,3,2,1), smooth=c(0,1,1,1,1)) Mcapdf <- Mcap.ff.all[Mcap.ff.all$reef!="42",] Mcapdf$reef <- factor(Mcapdf$reef, levels=c("44","25","HIMB")) Mcapdf$batch <- Mcapdf$days < 195 mod.all <- lmerTest::lmer(log(tot.SH) ~ sp(days) * vis * reef + (1 | colony), data=Mcapdf) #anova(mod.all) summary(lm(model.response(model.frame(mod.all)) ~ fitted(mod.all)))$r.squared plotreefs <- function(mod, n) { dat <- get(as.character(summary(mod)$call$data)) dat <- droplevels(dat) levs <- expand.grid(reef=levels(dat$reef), vis=levels(dat$vis), days=as.numeric(levels(as.factor(dat$days)))) datlevs <- list(interaction(dat$reef, dat$vis, dat$days)) datsumm <- data.frame(levs, mean=with(dat, aggregate(log(tot.SH), by=datlevs, FUN=mean)$x), sd=with(dat, aggregate(log(tot.SH), by=datlevs, FUN=sd)$x), se=with(dat, aggregate(log(tot.SH), by=datlevs, FUN=function(x) sd(x)/sqrt(length(x)))$x), conf95=with(dat, aggregate(log(tot.SH), by=datlevs, FUN=function(x) sd(x)/sqrt(length(x)) * qt(0.975, length(x)-1))$x)) datlist <- split(datsumm, f=datsumm$reef) datlist <- lapply(datlist, function(x) rev(split(x, f=x$vis))) pred <- expand.grid(days=seq(min(dat$days), max(dat$days), length.out=475), reef=levels(dat$reef), vis=levels(dat$vis)) bootfit <- bootMer(mod, FUN=function(x) predict(x, pred, re.form=NA), nsim=n) # Extract 90% confidence interval on predicted values pred$fit <- predict(mod, pred, re.form=NA) pred$lci <- apply(bootfit$t, 2, quantile, 0.05) pred$uci <- apply(bootfit$t, 2, quantile, 0.95) predlist <- split(pred, f=pred$reef) predlist <- lapply(predlist, function(x) rev(split(x, f=x$vis))) par(mgp=c(1.75,0.4,0), oma=c(0,0,0,0)) par(mar=c(0,3,0.3,1)) layout(mat=matrix(seq_len(nlevels(dat$reef)+1))) for (reef in levels(dat$reef)) { with(datlist[[reef]], { # Create plot frame for each reef plot(NA, xlim=range(dat$days), ylim=c(-9,0), xaxt="n", bty="n", tck=-0.03, ylab="ln S/H") title(paste("Reef", reef), line=-0.9, adj=0, outer=F) # Plot model fit line and shaded CI for bleached and/or not bleached corals with(predlist[[reef]], { lapply(predlist[[reef]], function(vis) { addpoly(vis$days, vis$lci, vis$uci, col=alpha(reefcols[[reef]], 0.4), xpd=NA) lines(vis$days, vis$fit, lty=vislty[[vis$vis[1]]]) }) }) # Plot raw data +/- standard error lapply(datlist[[reef]], function(vis) { arrows(vis$days, vis$mean + vis$se, vis$days, vis$mean - vis$se, code=3, angle=90, length=0.03, xpd=NA) points(vis$days, vis$mean, pch=vispch[[vis$vis[1]]], bg=visbg[[vis$vis[1]]]) }) }) #rect(xleft = 0, ybottom = -6, xright = 82, ytop = -1, lty = 3, border="black") } axdates <- seq.Date(as.Date("2014-11-01"), as.Date("2016-04-01"), by="month") unscaled <- Mcap.ff.all$days * attr(Mcap.ff.all$days, 'scaled:scale') + attr(Mcap.ff.all$days, 'scaled:center') axdays <- as.numeric(axdates - as.Date("2014-10-24")) tdays <- scales::rescale(axdays, to=range(dat$days), from=range(unscaled)) axis(side=1, at=tdays, labels=format(axdates, format="%b\n%y"), padj=1) return(list(predlist=predlist, datlist=datlist)) } # Plot reefcols <- list(`25`="#bebada", `44`="#8dd3c7", HIMB="#d9d9d9", `42`="green") vislty <- list("bleached"=2, "not bleached"=1) vispch <- list("bleached"=24, "not bleached"=21) visbg <- list("bleached"="white", "not bleached"="black") modelplot <- plotreefs(mod.all, 99)
library(Matrix) library(caret) library(xgboost) library(ROCR) url <- "https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data" train_df <- read.csv(url, header = FALSE, na.strings = " ?") url <- "https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.names" decrp <- readLines(url) names <- sub("(.*):.*", "\\1", decrp[97:110]) names colnames(train_df) <- c(names, "Y") head(train_df) str(train_df) ## one-hot encoding encoding <- dummyVars(~ . - Y, train_df) train_data <- predict(encoding, train_df, na.action = na.pass) train_data <- as(train_data, "sparseMatrix") train_label <- as.numeric(train_df$Y) - 1 train <- xgb.DMatrix(data = train_data, label = train_label) ## test data url <- "https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.test" test_df <- read.csv(url, header = FALSE, na.strings = " ?", skip = 1) colnames(test_df) <- c(names, "Y") encoding <- dummyVars(~ . - Y, test_df) test_data <- predict(encoding, test_df, na.action = na.pass) test_data <- as(test_data, "sparseMatrix") test_label <- as.numeric(test_df$Y) - 1 test <- xgb.DMatrix(data = test_data, label = test_label) param_1 <- list( eta = 0.3, # learning rate gamma = 0, # minimum reduction of loss for split max.depth = 6, # maximum depth of the tree subsample = 1, # row subsampling colsample_bylevel = 1, # feature subsampling lambda = 1 # l2 penalty ) ## 5-fold cross validation gbcv_1 <- xgb.cv(params = param_1, data = train, nfold = 5, objective = "binary:logistic", nrounds = 200, early_stopping_rounds = 15, eval_metric = "auc", missing = NA, seed = 12345) param_2 <- list( eta = 0.15, # learning rate gamma = 0, # minimum reduction of loss for split max.depth = 4, # maximum depth of the tree subsample = 0.7, # row subsampling colsample_bylevel = 0.5, # feature subsampling lambda = 3 ) gbcv_2 <- xgb.cv(params = param_2, data = train, nfold = 5, objective = "binary:logistic", nrounds = 500, early_stopping_rounds = 10, eval_metric = "auc", missing = NA, seed = 12345) ## validation set set.seed(12345) index <- sample(1:nrow(train_df), 6000, replace = FALSE) train_df_sub <- train_df[-index,] vali_df <- train_df[index,] encoding <- dummyVars(~ . - Y, train_df_sub) train_sub_data <- predict(encoding, train_df_sub, na.action = na.pass) train_sub_data <- as(train_sub_data, "sparseMatrix") train_sub_label <- as.numeric(train_df_sub$Y) - 1 train_sub <- xgb.DMatrix(data = train_sub_data, label = train_sub_label) encoding <- dummyVars(~ . - Y, vali_df) vali_data <- predict(encoding, vali_df, na.action = na.pass) vali_data <- as(vali_data, "sparseMatrix") vali_label <- as.numeric(vali_df$Y) - 1 vali <- xgb.DMatrix(data = vali_data, label = vali_label) watchlist <- list(train = train_sub, test = vali) xgb_vali_1 <- xgb.train(params = param_1, data = train_sub, watchlist = watchlist, objective = "binary:logistic", nrounds = 200, early_stopping_rounds = 15, eval_metric = "auc", missing = NA, seed = 12345) xgb_vali_2 <- xgb.train(params = param_2, data = train_sub, watchlist = watchlist, objective = "binary:logistic", nrounds = 200, early_stopping_rounds = 15, eval_metric = "auc", missing = NA, seed = 12345) ## Final model xgbtree_1 <- xgboost(params = param_1, data = train, verbose = 0, objective = "binary:logistic", nrounds = 25, missing = NA, seed = 12345) xgbtree_2 <- xgboost(params = param_2, data = train, verbose = 0, objective = "binary:logistic", nrounds = 130, missing = NA, seed = 12345) performance(prediction(predict(xgbtree_1, test), test_label), "auc") performance(prediction(predict(xgbtree_2, test), test_label), "auc") importance <- xgb.importance(feature_names = dimnames(train)[[2]], model = xgbtree_1) xgb.ggplot.importance(importance, top_n = 15) + theme(legend.position="none")
/example_2.R
no_license
lqyliuqingyang/class-presentation
R
false
false
4,340
r
library(Matrix) library(caret) library(xgboost) library(ROCR) url <- "https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data" train_df <- read.csv(url, header = FALSE, na.strings = " ?") url <- "https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.names" decrp <- readLines(url) names <- sub("(.*):.*", "\\1", decrp[97:110]) names colnames(train_df) <- c(names, "Y") head(train_df) str(train_df) ## one-hot encoding encoding <- dummyVars(~ . - Y, train_df) train_data <- predict(encoding, train_df, na.action = na.pass) train_data <- as(train_data, "sparseMatrix") train_label <- as.numeric(train_df$Y) - 1 train <- xgb.DMatrix(data = train_data, label = train_label) ## test data url <- "https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.test" test_df <- read.csv(url, header = FALSE, na.strings = " ?", skip = 1) colnames(test_df) <- c(names, "Y") encoding <- dummyVars(~ . - Y, test_df) test_data <- predict(encoding, test_df, na.action = na.pass) test_data <- as(test_data, "sparseMatrix") test_label <- as.numeric(test_df$Y) - 1 test <- xgb.DMatrix(data = test_data, label = test_label) param_1 <- list( eta = 0.3, # learning rate gamma = 0, # minimum reduction of loss for split max.depth = 6, # maximum depth of the tree subsample = 1, # row subsampling colsample_bylevel = 1, # feature subsampling lambda = 1 # l2 penalty ) ## 5-fold cross validation gbcv_1 <- xgb.cv(params = param_1, data = train, nfold = 5, objective = "binary:logistic", nrounds = 200, early_stopping_rounds = 15, eval_metric = "auc", missing = NA, seed = 12345) param_2 <- list( eta = 0.15, # learning rate gamma = 0, # minimum reduction of loss for split max.depth = 4, # maximum depth of the tree subsample = 0.7, # row subsampling colsample_bylevel = 0.5, # feature subsampling lambda = 3 ) gbcv_2 <- xgb.cv(params = param_2, data = train, nfold = 5, objective = "binary:logistic", nrounds = 500, early_stopping_rounds = 10, eval_metric = "auc", missing = NA, seed = 12345) ## validation set set.seed(12345) index <- sample(1:nrow(train_df), 6000, replace = FALSE) train_df_sub <- train_df[-index,] vali_df <- train_df[index,] encoding <- dummyVars(~ . - Y, train_df_sub) train_sub_data <- predict(encoding, train_df_sub, na.action = na.pass) train_sub_data <- as(train_sub_data, "sparseMatrix") train_sub_label <- as.numeric(train_df_sub$Y) - 1 train_sub <- xgb.DMatrix(data = train_sub_data, label = train_sub_label) encoding <- dummyVars(~ . - Y, vali_df) vali_data <- predict(encoding, vali_df, na.action = na.pass) vali_data <- as(vali_data, "sparseMatrix") vali_label <- as.numeric(vali_df$Y) - 1 vali <- xgb.DMatrix(data = vali_data, label = vali_label) watchlist <- list(train = train_sub, test = vali) xgb_vali_1 <- xgb.train(params = param_1, data = train_sub, watchlist = watchlist, objective = "binary:logistic", nrounds = 200, early_stopping_rounds = 15, eval_metric = "auc", missing = NA, seed = 12345) xgb_vali_2 <- xgb.train(params = param_2, data = train_sub, watchlist = watchlist, objective = "binary:logistic", nrounds = 200, early_stopping_rounds = 15, eval_metric = "auc", missing = NA, seed = 12345) ## Final model xgbtree_1 <- xgboost(params = param_1, data = train, verbose = 0, objective = "binary:logistic", nrounds = 25, missing = NA, seed = 12345) xgbtree_2 <- xgboost(params = param_2, data = train, verbose = 0, objective = "binary:logistic", nrounds = 130, missing = NA, seed = 12345) performance(prediction(predict(xgbtree_1, test), test_label), "auc") performance(prediction(predict(xgbtree_2, test), test_label), "auc") importance <- xgb.importance(feature_names = dimnames(train)[[2]], model = xgbtree_1) xgb.ggplot.importance(importance, top_n = 15) + theme(legend.position="none")
setClass("DMNGroup", contains="SimpleList", prototype=prototype(elementType="DMN")) .DMNGroup <- function(...) { new("DMNGroup", listData=list(...)) } ## dmngroup dmngroup <- function(count, group, k, ..., simplify=TRUE, .lapply=parallel::mclapply) { if (length(group) != nrow(count)) stop("'length(group)' does not equal 'nrow(count)'") if (!is.factor(group)) group <- factor(group) lvls <- setNames(nm=levels(group)) counts <- lapply(lvls, csubset, count, group) tasks <- expand.grid(group=names(counts), k=k) tid <- seq_len(nrow(tasks)) ans0 <- .lapply(tid, function(i, tasks, counts, ...) { count <- counts[[tasks[i,"group"]]] k <- tasks[i,"k"] dmn(count, k, ...) }, tasks, counts, ...) ans <- if (simplify) { ans1 <- split(ans0, tasks[,"group"]) opt <- lapply(ans1, function(ans) { which.min(sapply(ans, laplace)) }) Map("[[", ans1, opt) } else ans0 do.call(.DMNGroup, ans) } ## predict .predict.DMNGroup <- function(object, newdata, ..., assign=FALSE) { if (2 < length(object)) stop("only 2 groups can be used for classification") res <- lapply(object, predict, newdata, ..., logevidence=TRUE) offset <- apply(do.call(cbind, res), 1, min) prClass <- local({ nClass <- sapply(object, function(x) nrow(mixture(x))) nClass / sum(nClass) }) pr <- simplify2array(Map(function(x, alpha, prClass, offset) { prMix <- sweep(exp(-(alpha - offset)), 2, mixturewt(x)$pi, "*") rowSums(prMix) * prClass }, object, res, prClass, MoreArgs=list(offset=offset))) if (!is.matrix(pr)) { dmnms <- list(rownames(newdata), names(prClass)) pr <- matrix(pr, nrow=1, dimnames=dmnms) } if (assign) names(object)[ifelse((pr[,1] / rowSums(pr)) > .5, 1, 2)] else pr / rowSums(pr) } setMethod(predict, "DMNGroup", .predict.DMNGroup) ## cross-validation .cv_dmngroup <- function(dropidx, count, k, z, ..., verbose=FALSE) ## e.g., k = c(Lean=1, Obese=3) --> 1 group for lean, 3 for obese { tryCatch({ trainz <- z[-dropidx] u <- unique(trainz) train <- count[-dropidx,,drop=FALSE] if (!is.factor(trainz)) trainz <- factor(trainz, levels=names(k)) if (any(is.na(trainz))) stop("values of 'z' not all in 'names(k)'") if (!all(names(k) %in% as.character(trainz))) stop("not all names(k) in z subset") trains <- sapply(levels(trainz), csubset, train, trainz) fits <- Map(dmn, trains, k[levels(trainz)], ..., verbose=verbose) fits <- do.call(.DMNGroup, fits) predict(fits, count[dropidx,,drop=FALSE], assign=FALSE) }, error=function(err) { message(".cv_dmngroup error: ", conditionMessage(err)) matrix(NA_integer_, nrow=length(dropidx), ncol=length(k), dimnames=list(rownames(count)[dropidx], names(k))) }) } cvdmngroup <- function(ncv, count, k, z, ..., verbose=FALSE, .lapply=parallel::mclapply) { n <- seq_len(nrow(count)) grp <- split(sample(length(n)), cut(n, ncv)) names(grp) <- seq_along(grp) cvresult <- .lapply(names(grp), function(idx, grp, ..., verbose) { if (verbose) cat("cross-validation group", names(grp[idx]), "\n") .cv_dmngroup(grp[[idx]], ..., verbose=verbose) }, grp, count, k, z, ..., verbose=verbose) gid <- rep(seq_along(cvresult), sapply(cvresult, nrow)) cbind(data.frame(group=gid, row.names=NULL), do.call(rbind, cvresult)) } ## summary / print / plot setMethod(summary, "DMNGroup", function(object, ...) { k <- data.frame(k=sapply(object, function(elt) ncol(mixture(elt)))) sxt <- t(sapply(object, function(elt) { c(samples=nrow(mixture(elt)), taxa=nrow(fitted(elt))) })) goodness <- t(sapply(object, goodnessOfFit)) cbind(k=k, sxt, goodness) }) setMethod(show, "DMNGroup", function(object) { cat("class:", class(object), "\n") cat("summary:\n") print(summary(object)) })
/R/dmngroup.R
no_license
mtmorgan/DirichletMultinomial
R
false
false
4,155
r
setClass("DMNGroup", contains="SimpleList", prototype=prototype(elementType="DMN")) .DMNGroup <- function(...) { new("DMNGroup", listData=list(...)) } ## dmngroup dmngroup <- function(count, group, k, ..., simplify=TRUE, .lapply=parallel::mclapply) { if (length(group) != nrow(count)) stop("'length(group)' does not equal 'nrow(count)'") if (!is.factor(group)) group <- factor(group) lvls <- setNames(nm=levels(group)) counts <- lapply(lvls, csubset, count, group) tasks <- expand.grid(group=names(counts), k=k) tid <- seq_len(nrow(tasks)) ans0 <- .lapply(tid, function(i, tasks, counts, ...) { count <- counts[[tasks[i,"group"]]] k <- tasks[i,"k"] dmn(count, k, ...) }, tasks, counts, ...) ans <- if (simplify) { ans1 <- split(ans0, tasks[,"group"]) opt <- lapply(ans1, function(ans) { which.min(sapply(ans, laplace)) }) Map("[[", ans1, opt) } else ans0 do.call(.DMNGroup, ans) } ## predict .predict.DMNGroup <- function(object, newdata, ..., assign=FALSE) { if (2 < length(object)) stop("only 2 groups can be used for classification") res <- lapply(object, predict, newdata, ..., logevidence=TRUE) offset <- apply(do.call(cbind, res), 1, min) prClass <- local({ nClass <- sapply(object, function(x) nrow(mixture(x))) nClass / sum(nClass) }) pr <- simplify2array(Map(function(x, alpha, prClass, offset) { prMix <- sweep(exp(-(alpha - offset)), 2, mixturewt(x)$pi, "*") rowSums(prMix) * prClass }, object, res, prClass, MoreArgs=list(offset=offset))) if (!is.matrix(pr)) { dmnms <- list(rownames(newdata), names(prClass)) pr <- matrix(pr, nrow=1, dimnames=dmnms) } if (assign) names(object)[ifelse((pr[,1] / rowSums(pr)) > .5, 1, 2)] else pr / rowSums(pr) } setMethod(predict, "DMNGroup", .predict.DMNGroup) ## cross-validation .cv_dmngroup <- function(dropidx, count, k, z, ..., verbose=FALSE) ## e.g., k = c(Lean=1, Obese=3) --> 1 group for lean, 3 for obese { tryCatch({ trainz <- z[-dropidx] u <- unique(trainz) train <- count[-dropidx,,drop=FALSE] if (!is.factor(trainz)) trainz <- factor(trainz, levels=names(k)) if (any(is.na(trainz))) stop("values of 'z' not all in 'names(k)'") if (!all(names(k) %in% as.character(trainz))) stop("not all names(k) in z subset") trains <- sapply(levels(trainz), csubset, train, trainz) fits <- Map(dmn, trains, k[levels(trainz)], ..., verbose=verbose) fits <- do.call(.DMNGroup, fits) predict(fits, count[dropidx,,drop=FALSE], assign=FALSE) }, error=function(err) { message(".cv_dmngroup error: ", conditionMessage(err)) matrix(NA_integer_, nrow=length(dropidx), ncol=length(k), dimnames=list(rownames(count)[dropidx], names(k))) }) } cvdmngroup <- function(ncv, count, k, z, ..., verbose=FALSE, .lapply=parallel::mclapply) { n <- seq_len(nrow(count)) grp <- split(sample(length(n)), cut(n, ncv)) names(grp) <- seq_along(grp) cvresult <- .lapply(names(grp), function(idx, grp, ..., verbose) { if (verbose) cat("cross-validation group", names(grp[idx]), "\n") .cv_dmngroup(grp[[idx]], ..., verbose=verbose) }, grp, count, k, z, ..., verbose=verbose) gid <- rep(seq_along(cvresult), sapply(cvresult, nrow)) cbind(data.frame(group=gid, row.names=NULL), do.call(rbind, cvresult)) } ## summary / print / plot setMethod(summary, "DMNGroup", function(object, ...) { k <- data.frame(k=sapply(object, function(elt) ncol(mixture(elt)))) sxt <- t(sapply(object, function(elt) { c(samples=nrow(mixture(elt)), taxa=nrow(fitted(elt))) })) goodness <- t(sapply(object, goodnessOfFit)) cbind(k=k, sxt, goodness) }) setMethod(show, "DMNGroup", function(object) { cat("class:", class(object), "\n") cat("summary:\n") print(summary(object)) })
# Final submission # # Set variable for which ensemble (QRA or QA (mean)) ensemble_dir = "qra-state-ensemble" # c("qra-state-ensemble" "qra-ensemble", "quantile-average") # Get ensemble submit_ensemble <- suppressMessages(readr::read_csv(here::here("ensembling", ensemble_dir, "submission-files", paste0("latest.csv")))) # Filter to states with minimum deaths in last week source(here::here("utils", "states-min-last-week.R")) keep_states <- states_min_last_week(min_last_week = 5, last_week = 1) submit_ensemble <- dplyr::filter(submit_ensemble, location %in% c(keep_states$state_code, "US")) # Set forecast date forecast_date <- unique(dplyr::pull(submit_ensemble, forecast_date)) # Filter to forecasts within Rt forecast # rt_max_date <- suppressMessages(readr::read_csv(here::here("rt-forecast/submission-files/latest.csv"))) %>% # dplyr::pull(target_end_date) %>% # unique() %>% # max() submit_ensemble <- dplyr::filter(submit_ensemble, (target_end_date - submission_date) <= 30) %>% dplyr::select(-submission_date) # Checks ------------------------------------------------------------------ # 1. Check population limit pop_check <- dplyr::left_join(submit_ensemble, readr::read_csv("utils/state_pop_totals.csv"), by = c("location" = "state_code")) %>% dplyr::mutate(pop_check = ifelse(value > tot_pop, FALSE, TRUE)) %>% dplyr::filter(pop_check == FALSE) %>% dplyr::pull(location) %>% unique() # 2. Check for NA values na_check <- submit_ensemble %>% dplyr::filter(is.na(value)) %>% dplyr::pull(location) # 3. Incident and cumulative add up ------------------------------------------ # - check each model to find the issue # Check incident forecast adds to cumulative source("utils/load-submissions-function.R") source("utils/get-us-data.R") state_codes <- readRDS("utils/state_codes.rds") # get cumulative data cumulative <- get_us_deaths(data = "cumulative") %>% dplyr::ungroup() %>% dplyr::filter(date == forecast_date-2) %>% dplyr::add_row(state="US", deaths = sum(.$deaths), date = forecast_date-2) %>% dplyr::left_join(state_codes, by = "state") # Check each model to find the issue forecasts <- load_submission_files(dates = "all", num_last = 1, models = "single") %>% dplyr::filter(location == "US") us_inc <- dplyr::filter(forecasts, grepl("inc", forecasts$target)) us_cum <- dplyr::filter(forecasts, grepl("cum", forecasts$target)) %>% dplyr::group_by(location, quantile, type) %>% dplyr::mutate(cum_to_inc = value - dplyr::lag(value, 1)) %>% dplyr::ungroup() us_join <- dplyr::left_join(us_inc, us_cum, by = c("model", "location", "target_end_date", "type", "quantile")) %>% dplyr::left_join(cumulative, by = c("location")) %>% dplyr::rename(value_inc = value.x, value_cum = value.y) %>% dplyr::mutate(cum_to_inc = ifelse(is.na(cum_to_inc), value_cum - deaths, cum_to_inc), diff_inc_cum = value_inc - cum_to_inc) %>% dplyr::select(model, location, state, target_end_date, type, quantile, deaths, value_inc, value_cum, cum_to_inc, diff_inc_cum) %>% dplyr::group_by(model, target_end_date) %>% dplyr::summarise(diff_inc_cum = mean(diff_inc_cum), .groups = "drop") if(!mean(us_join$diff_inc_cum) == 0){ warning("Incident and cumulative forecasts don't match. Re-writing cumulative forecasts for the submission ensemble") incident_forecast <- dplyr::filter(submit_ensemble, grepl("wk ahead inc", target)) cumulative_data <- get_us_deaths(data = "cumulative") cumulative_deaths <- cumulative_data %>% dplyr::ungroup() %>% dplyr::filter(date == min(max(date), forecast_date)) %>% dplyr::add_row(state="US", deaths = sum(.$deaths), date = forecast_date) %>% dplyr::left_join(state_codes, by = "state") cumulative_forecast <- incident_forecast %>% dplyr::left_join(dplyr::select(cumulative_deaths, location, deaths), by = "location") %>% dplyr::group_by(location, quantile, type) %>% dplyr::mutate(value = cumsum(value), value = value + deaths, target = stringr::str_replace_all(target, "inc", "cum")) %>% dplyr::ungroup() %>% dplyr::select(-deaths) # Check this also adds up # join <- dplyr::left_join(incident_forecast, cumulative_forecast, # by = c("forecast_date", "target_end_date", # "location", "type", "quantile")) %>% # dplyr::rename(value_inc = value.x, value_cum = value.y) %>% # dplyr::group_by(location, type, quantile) %>% # dplyr::mutate(cum_to_inc = (value_cum - dplyr::lag(value_cum))-value_inc) submit_ensemble <- dplyr::bind_rows(incident_forecast, cumulative_forecast) } # Filter failing checks --------------------------------------------------- if((length(na_check) | length(pop_check)) > 0){ message("Excluding states failing checks:") print(dplyr::filter(state_codes, location %in% c(pop_check, na_check)) %>% dplyr::pull(state)) } submit_ensemble <- submit_ensemble %>% dplyr::filter(!location %in% pop_check & !location %in% na_check) # Save in final-submissions readr::write_csv(submit_ensemble, here::here("final-submissions", "death-forecast", paste0(unique(submit_ensemble$forecast_date), "-epiforecasts-ensemble1.csv")))
/final-submissions/update-final-submission.R
permissive
signaturescience/covid-us-forecasts
R
false
false
5,667
r
# Final submission # # Set variable for which ensemble (QRA or QA (mean)) ensemble_dir = "qra-state-ensemble" # c("qra-state-ensemble" "qra-ensemble", "quantile-average") # Get ensemble submit_ensemble <- suppressMessages(readr::read_csv(here::here("ensembling", ensemble_dir, "submission-files", paste0("latest.csv")))) # Filter to states with minimum deaths in last week source(here::here("utils", "states-min-last-week.R")) keep_states <- states_min_last_week(min_last_week = 5, last_week = 1) submit_ensemble <- dplyr::filter(submit_ensemble, location %in% c(keep_states$state_code, "US")) # Set forecast date forecast_date <- unique(dplyr::pull(submit_ensemble, forecast_date)) # Filter to forecasts within Rt forecast # rt_max_date <- suppressMessages(readr::read_csv(here::here("rt-forecast/submission-files/latest.csv"))) %>% # dplyr::pull(target_end_date) %>% # unique() %>% # max() submit_ensemble <- dplyr::filter(submit_ensemble, (target_end_date - submission_date) <= 30) %>% dplyr::select(-submission_date) # Checks ------------------------------------------------------------------ # 1. Check population limit pop_check <- dplyr::left_join(submit_ensemble, readr::read_csv("utils/state_pop_totals.csv"), by = c("location" = "state_code")) %>% dplyr::mutate(pop_check = ifelse(value > tot_pop, FALSE, TRUE)) %>% dplyr::filter(pop_check == FALSE) %>% dplyr::pull(location) %>% unique() # 2. Check for NA values na_check <- submit_ensemble %>% dplyr::filter(is.na(value)) %>% dplyr::pull(location) # 3. Incident and cumulative add up ------------------------------------------ # - check each model to find the issue # Check incident forecast adds to cumulative source("utils/load-submissions-function.R") source("utils/get-us-data.R") state_codes <- readRDS("utils/state_codes.rds") # get cumulative data cumulative <- get_us_deaths(data = "cumulative") %>% dplyr::ungroup() %>% dplyr::filter(date == forecast_date-2) %>% dplyr::add_row(state="US", deaths = sum(.$deaths), date = forecast_date-2) %>% dplyr::left_join(state_codes, by = "state") # Check each model to find the issue forecasts <- load_submission_files(dates = "all", num_last = 1, models = "single") %>% dplyr::filter(location == "US") us_inc <- dplyr::filter(forecasts, grepl("inc", forecasts$target)) us_cum <- dplyr::filter(forecasts, grepl("cum", forecasts$target)) %>% dplyr::group_by(location, quantile, type) %>% dplyr::mutate(cum_to_inc = value - dplyr::lag(value, 1)) %>% dplyr::ungroup() us_join <- dplyr::left_join(us_inc, us_cum, by = c("model", "location", "target_end_date", "type", "quantile")) %>% dplyr::left_join(cumulative, by = c("location")) %>% dplyr::rename(value_inc = value.x, value_cum = value.y) %>% dplyr::mutate(cum_to_inc = ifelse(is.na(cum_to_inc), value_cum - deaths, cum_to_inc), diff_inc_cum = value_inc - cum_to_inc) %>% dplyr::select(model, location, state, target_end_date, type, quantile, deaths, value_inc, value_cum, cum_to_inc, diff_inc_cum) %>% dplyr::group_by(model, target_end_date) %>% dplyr::summarise(diff_inc_cum = mean(diff_inc_cum), .groups = "drop") if(!mean(us_join$diff_inc_cum) == 0){ warning("Incident and cumulative forecasts don't match. Re-writing cumulative forecasts for the submission ensemble") incident_forecast <- dplyr::filter(submit_ensemble, grepl("wk ahead inc", target)) cumulative_data <- get_us_deaths(data = "cumulative") cumulative_deaths <- cumulative_data %>% dplyr::ungroup() %>% dplyr::filter(date == min(max(date), forecast_date)) %>% dplyr::add_row(state="US", deaths = sum(.$deaths), date = forecast_date) %>% dplyr::left_join(state_codes, by = "state") cumulative_forecast <- incident_forecast %>% dplyr::left_join(dplyr::select(cumulative_deaths, location, deaths), by = "location") %>% dplyr::group_by(location, quantile, type) %>% dplyr::mutate(value = cumsum(value), value = value + deaths, target = stringr::str_replace_all(target, "inc", "cum")) %>% dplyr::ungroup() %>% dplyr::select(-deaths) # Check this also adds up # join <- dplyr::left_join(incident_forecast, cumulative_forecast, # by = c("forecast_date", "target_end_date", # "location", "type", "quantile")) %>% # dplyr::rename(value_inc = value.x, value_cum = value.y) %>% # dplyr::group_by(location, type, quantile) %>% # dplyr::mutate(cum_to_inc = (value_cum - dplyr::lag(value_cum))-value_inc) submit_ensemble <- dplyr::bind_rows(incident_forecast, cumulative_forecast) } # Filter failing checks --------------------------------------------------- if((length(na_check) | length(pop_check)) > 0){ message("Excluding states failing checks:") print(dplyr::filter(state_codes, location %in% c(pop_check, na_check)) %>% dplyr::pull(state)) } submit_ensemble <- submit_ensemble %>% dplyr::filter(!location %in% pop_check & !location %in% na_check) # Save in final-submissions readr::write_csv(submit_ensemble, here::here("final-submissions", "death-forecast", paste0(unique(submit_ensemble$forecast_date), "-epiforecasts-ensemble1.csv")))
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/focal.events.R \name{read.genes.info.tsv} \alias{read.genes.info.tsv} \title{Read Biomart annotation file.} \usage{ read.genes.info.tsv(build.file, filter.chr = NULL) } \arguments{ \item{build.file}{The TSV file exported from Biomart.} \item{filter.chr}{A character vector of wanted chromosomes.} } \value{ The \code{data.table} containing the genome annotations. } \description{ Read Biomart annotation file. } \section{Warning}{ This function is expecting at least the following headers: 'Ensembl Gene ID', 'Gene Start (bp)', 'Gene End (bp)', 'Chromosome Name', 'Associated Gene Name'. }
/man/read.genes.info.tsv.Rd
permissive
NKI-CCB/RUBIC
R
false
true
696
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/focal.events.R \name{read.genes.info.tsv} \alias{read.genes.info.tsv} \title{Read Biomart annotation file.} \usage{ read.genes.info.tsv(build.file, filter.chr = NULL) } \arguments{ \item{build.file}{The TSV file exported from Biomart.} \item{filter.chr}{A character vector of wanted chromosomes.} } \value{ The \code{data.table} containing the genome annotations. } \description{ Read Biomart annotation file. } \section{Warning}{ This function is expecting at least the following headers: 'Ensembl Gene ID', 'Gene Start (bp)', 'Gene End (bp)', 'Chromosome Name', 'Associated Gene Name'. }
context("Create a dust object") fit <- lm(mpg ~ qsec + factor(am) + wt + factor(gear), data = mtcars) test_that("Create a dust object", { x <- dust(fit) expect_equal(class(x), "dust") }) test_that("dust object has expected names", { x <- dust(fit) expect_equal(names(x), c("head", "body", "interfoot", "foot", "border_collapse", "caption", "label", "justify", "float", "longtable", "table_width", "tabcolsep", "hhline", "bookdown", "print_method")) }) test_that("dust object body component has correct dimensions", { fit <- lm(mpg ~ qsec + factor(am) + wt + factor(gear), data = mtcars) x <- dust(fit) Dims <- list(dim(x$head), dim(x$body), dim(x$interfoot), dim(x$foot)) expect_equal(Dims, list(c(5, 34), c(30, 34), NULL, NULL)) }) test_that("dust runs when passed a data frame with tidy_df = FALSE", { expect_silent(dust(mtcars, tidy_df = FALSE)) }) test_that("dust runs when passed a data frame with tidy_df = TRUE", { expect_silent(dust(mtcars, tidy_df = TRUE)) }) test_that("dust with keep_rownames = TRUE adds rownames to object", { x <- dust(mtcars, keep_rownames = TRUE) expect_equal(x$body$value[1:32], rownames(mtcars)) }) test_that("dust with additional descriptors", { expect_silent(dust(fit, descriptors = c("label", "level_detail"))) }) test_that("dust with additional descriptors and term_plain numeric_label", { expect_silent(dust(fit, descriptors = c("label", "level_detail"), numeric_label = "term_plain")) }) test_that("dust with glance_foot", { expect_silent(dust(fit, glance_foot = TRUE)) }) test_that("dust with glance_foot and col_pairs a divisor of total_cols", { fit <- lm(mpg ~ qsec + factor(am) + wt * factor(gear), data = mtcars) expect_silent(dust(fit, descriptors = c("label", "level_detail"), glance_foot = TRUE, col_pairs = 3)) }) test_that("dust a list", { x <- split(mtcars, list(mtcars$am, mtcars$vs)) expect_silent(dust(x)) })
/pixiedust/tests/testthat/test-dust.R
no_license
ingted/R-Examples
R
false
false
2,385
r
context("Create a dust object") fit <- lm(mpg ~ qsec + factor(am) + wt + factor(gear), data = mtcars) test_that("Create a dust object", { x <- dust(fit) expect_equal(class(x), "dust") }) test_that("dust object has expected names", { x <- dust(fit) expect_equal(names(x), c("head", "body", "interfoot", "foot", "border_collapse", "caption", "label", "justify", "float", "longtable", "table_width", "tabcolsep", "hhline", "bookdown", "print_method")) }) test_that("dust object body component has correct dimensions", { fit <- lm(mpg ~ qsec + factor(am) + wt + factor(gear), data = mtcars) x <- dust(fit) Dims <- list(dim(x$head), dim(x$body), dim(x$interfoot), dim(x$foot)) expect_equal(Dims, list(c(5, 34), c(30, 34), NULL, NULL)) }) test_that("dust runs when passed a data frame with tidy_df = FALSE", { expect_silent(dust(mtcars, tidy_df = FALSE)) }) test_that("dust runs when passed a data frame with tidy_df = TRUE", { expect_silent(dust(mtcars, tidy_df = TRUE)) }) test_that("dust with keep_rownames = TRUE adds rownames to object", { x <- dust(mtcars, keep_rownames = TRUE) expect_equal(x$body$value[1:32], rownames(mtcars)) }) test_that("dust with additional descriptors", { expect_silent(dust(fit, descriptors = c("label", "level_detail"))) }) test_that("dust with additional descriptors and term_plain numeric_label", { expect_silent(dust(fit, descriptors = c("label", "level_detail"), numeric_label = "term_plain")) }) test_that("dust with glance_foot", { expect_silent(dust(fit, glance_foot = TRUE)) }) test_that("dust with glance_foot and col_pairs a divisor of total_cols", { fit <- lm(mpg ~ qsec + factor(am) + wt * factor(gear), data = mtcars) expect_silent(dust(fit, descriptors = c("label", "level_detail"), glance_foot = TRUE, col_pairs = 3)) }) test_that("dust a list", { x <- split(mtcars, list(mtcars$am, mtcars$vs)) expect_silent(dust(x)) })
#script to import, analyse and produce plots for prop biomass in secondary forests #load in necessary libraries library(RODBC) library(ggplot2) library(nlme) library(lme4) library(MuMIn) #connect to database sec <- odbcConnect("Secondary/Degraded forests") sqlTables(sec) #import proportion query Prop<- sqlFetch(sec, "Proportion query") head(Prop) #Rename columns colnames(Prop) <- c("ID", "Site","Disturbance","Age","Type","Measurement","Prop_Ref","Prop_Sec","Tax") head(Prop) Prop<-data.frame(Prop) Prop$Prop<-Prop$Prop_Sec/Prop$Prop_Ref #subset data to remove logging, fire and missing values Prop<-subset(Prop,Disturbance!="Fire") Prop<-subset(Prop,Disturbance!="Logging") Prop<-subset(Prop,Disturbance!="Agroforestry") Tree_prop<-Prop #new variable to rescale data Tree_prop$proploss<-Tree_prop$Prop-1/1 Tree_prop$proploss2<-(qlogis((Tree_prop$proploss+1))) Tree_prop$asin<-(sqrt(asin(Tree_prop$Prop))) hist(Tree_prop$proploss2) head(Tree_prop) #logit transformation Tree_prop$logprop<-log(Tree_prop$Prop)-log(1-Tree_prop$Prop) #Mixed model of Prop prop #null model M0<-glmer(Prop~1+(1|ID),family=binomial(logit),data=Tree_prop,REML=F) nulldev<--2*logLik(M0)[1] #full model M1<-glmer(Prop~1+Age+Type+Disturbance+(1|ID),family=binomial(logit),data=Tree_prop,REML=F) plot(fitted(M1),resid(M1)) summary(M1) plot(Tree_prop$Age,Tree_prop$Prop) #model selection using AICc MS1<- dredge(M1, trace = TRUE, rank = "AICc", REML = FALSE) #subset models with delta<7 (to remove implausible models) poss_mod<- get.models(MS1, subset = delta <7) modsumm <- model.sel(poss_mod, rank = "AICc") modsumm plot(Tree_prop$Age,Tree_prop$Prop) Age<-seq(0,115,0.1) lines(Age,1/(1+1/(exp(-1.551+(0.01726*(Age)))))) lines(Age,(plogis(-2.2035532+(Age*0.0151852)*2)) #calculate deviance of model modsumm$dev<--2*modsumm$logLik #calculate deviance explained for each model modsumm$dev_ex<-((nulldev-modsumm$dev)/nulldev) modsumm$dev_ex #output possible models setwd("C:/Documents and Settings/Phil/My Documents/My Dropbox/Publications, Reports and Responsibilities/Chapters/4. Forest restoration trajectories/Analysis/Statistics") write.csv(modsumm, "Model - Species pool.csv") #calculate model averaged coefficients #create predictions based on models >0.6 weight averaged<-model.avg(MS1,subset=cumsum(weight)<=0.6) averaged2<-averaged$avg.model write.csv(averaged2, "Multimodel inferences Prop primary.csv") #save table #set parameter values from best model Avgest.mod$avg.model Int<-averaged2[1] Int Age<-averaged2[2] Age #create new data for predictions range(Tree_prop$Age) preds<-expand.grid(Age=seq(1.5,81,0.1)) preds$predicted<-Int+(preds$Age*Age) preds$Prop<-1/(1+1/(exp(preds$predicted))) #produce plots of model windowsFonts(Times=windowsFont("TT Times New Roman")) theme_set(theme_bw(base_size=18)) a<-ggplot(Tree_prop,aes(x=Age,y=Prop))+geom_point(size=4,shape=1)+opts(panel.grid.major = theme_line(colour =NA)) a d<-a+coord_cartesian(ylim = c(0, 1.05),xlim=c(0,120))+ylab("Proportion of primary species pool\n found in secondary forest")+geom_hline(y=1,lty=2) e<-d+xlab("Time since last disturbance (Years)")+ scale_colour_discrete(name="Type of \nforest") f<-e+scale_y_continuous(breaks=seq(0, 1, 0.5))+scale_x_continuous(breaks=seq(0, 120, 40)) f f+theme(text=element_text(family="Times")) setwd("C:/Documents and Settings/Phil/My Documents/My Dropbox/Publications, Reports and Responsibilities/Chapters/4. Forest restoration trajectories/Analysis/Figures") ggsave(filename="Prop_trees_pres.jpeg",height=6,width=10,dpi=300,) #produce plots of model theme_set(theme_bw(base_size=18)) a<-ggplot(Tree_prop,aes(x=Age,y=Prop))+geom_point(size=4,shape=1)+opts(panel.grid.major = theme_line(colour =NA)) a d<-a+coord_cartesian(ylim = c(0, 1.05),xlim=c(0,120))+ylab("Proportion of primary species pool\n found in secondary forest")+geom_hline(y=1,lty=2) e<-d+xlab("Time since last disturbance (Years)")+ scale_colour_discrete(name="Type of \nforest") f<-e+scale_y_continuous(breaks=seq(0, 1, 0.5))+scale_x_continuous(breaks=seq(0, 120, 40)) f+geom_hline(y=mean(Tree_prop$Prop),lty=1,size=2) setwd("C:/Documents and Settings/Phil/My Documents/My Dropbox/Publications, Reports and Responsibilities/Chapters/4. Forest restoration trajectories/Analysis/Figures") ggsave(filename="Prop_trees_pres_mean.jpeg",height=6,width=10,dpi=300,)
/Scripts/Shared species for presentations.R
no_license
fdbesanto2/SecFor
R
false
false
4,351
r
#script to import, analyse and produce plots for prop biomass in secondary forests #load in necessary libraries library(RODBC) library(ggplot2) library(nlme) library(lme4) library(MuMIn) #connect to database sec <- odbcConnect("Secondary/Degraded forests") sqlTables(sec) #import proportion query Prop<- sqlFetch(sec, "Proportion query") head(Prop) #Rename columns colnames(Prop) <- c("ID", "Site","Disturbance","Age","Type","Measurement","Prop_Ref","Prop_Sec","Tax") head(Prop) Prop<-data.frame(Prop) Prop$Prop<-Prop$Prop_Sec/Prop$Prop_Ref #subset data to remove logging, fire and missing values Prop<-subset(Prop,Disturbance!="Fire") Prop<-subset(Prop,Disturbance!="Logging") Prop<-subset(Prop,Disturbance!="Agroforestry") Tree_prop<-Prop #new variable to rescale data Tree_prop$proploss<-Tree_prop$Prop-1/1 Tree_prop$proploss2<-(qlogis((Tree_prop$proploss+1))) Tree_prop$asin<-(sqrt(asin(Tree_prop$Prop))) hist(Tree_prop$proploss2) head(Tree_prop) #logit transformation Tree_prop$logprop<-log(Tree_prop$Prop)-log(1-Tree_prop$Prop) #Mixed model of Prop prop #null model M0<-glmer(Prop~1+(1|ID),family=binomial(logit),data=Tree_prop,REML=F) nulldev<--2*logLik(M0)[1] #full model M1<-glmer(Prop~1+Age+Type+Disturbance+(1|ID),family=binomial(logit),data=Tree_prop,REML=F) plot(fitted(M1),resid(M1)) summary(M1) plot(Tree_prop$Age,Tree_prop$Prop) #model selection using AICc MS1<- dredge(M1, trace = TRUE, rank = "AICc", REML = FALSE) #subset models with delta<7 (to remove implausible models) poss_mod<- get.models(MS1, subset = delta <7) modsumm <- model.sel(poss_mod, rank = "AICc") modsumm plot(Tree_prop$Age,Tree_prop$Prop) Age<-seq(0,115,0.1) lines(Age,1/(1+1/(exp(-1.551+(0.01726*(Age)))))) lines(Age,(plogis(-2.2035532+(Age*0.0151852)*2)) #calculate deviance of model modsumm$dev<--2*modsumm$logLik #calculate deviance explained for each model modsumm$dev_ex<-((nulldev-modsumm$dev)/nulldev) modsumm$dev_ex #output possible models setwd("C:/Documents and Settings/Phil/My Documents/My Dropbox/Publications, Reports and Responsibilities/Chapters/4. Forest restoration trajectories/Analysis/Statistics") write.csv(modsumm, "Model - Species pool.csv") #calculate model averaged coefficients #create predictions based on models >0.6 weight averaged<-model.avg(MS1,subset=cumsum(weight)<=0.6) averaged2<-averaged$avg.model write.csv(averaged2, "Multimodel inferences Prop primary.csv") #save table #set parameter values from best model Avgest.mod$avg.model Int<-averaged2[1] Int Age<-averaged2[2] Age #create new data for predictions range(Tree_prop$Age) preds<-expand.grid(Age=seq(1.5,81,0.1)) preds$predicted<-Int+(preds$Age*Age) preds$Prop<-1/(1+1/(exp(preds$predicted))) #produce plots of model windowsFonts(Times=windowsFont("TT Times New Roman")) theme_set(theme_bw(base_size=18)) a<-ggplot(Tree_prop,aes(x=Age,y=Prop))+geom_point(size=4,shape=1)+opts(panel.grid.major = theme_line(colour =NA)) a d<-a+coord_cartesian(ylim = c(0, 1.05),xlim=c(0,120))+ylab("Proportion of primary species pool\n found in secondary forest")+geom_hline(y=1,lty=2) e<-d+xlab("Time since last disturbance (Years)")+ scale_colour_discrete(name="Type of \nforest") f<-e+scale_y_continuous(breaks=seq(0, 1, 0.5))+scale_x_continuous(breaks=seq(0, 120, 40)) f f+theme(text=element_text(family="Times")) setwd("C:/Documents and Settings/Phil/My Documents/My Dropbox/Publications, Reports and Responsibilities/Chapters/4. Forest restoration trajectories/Analysis/Figures") ggsave(filename="Prop_trees_pres.jpeg",height=6,width=10,dpi=300,) #produce plots of model theme_set(theme_bw(base_size=18)) a<-ggplot(Tree_prop,aes(x=Age,y=Prop))+geom_point(size=4,shape=1)+opts(panel.grid.major = theme_line(colour =NA)) a d<-a+coord_cartesian(ylim = c(0, 1.05),xlim=c(0,120))+ylab("Proportion of primary species pool\n found in secondary forest")+geom_hline(y=1,lty=2) e<-d+xlab("Time since last disturbance (Years)")+ scale_colour_discrete(name="Type of \nforest") f<-e+scale_y_continuous(breaks=seq(0, 1, 0.5))+scale_x_continuous(breaks=seq(0, 120, 40)) f+geom_hline(y=mean(Tree_prop$Prop),lty=1,size=2) setwd("C:/Documents and Settings/Phil/My Documents/My Dropbox/Publications, Reports and Responsibilities/Chapters/4. Forest restoration trajectories/Analysis/Figures") ggsave(filename="Prop_trees_pres_mean.jpeg",height=6,width=10,dpi=300,)
get_issues_by_date <- function(city,after = Sys.time()-86400, before = Sys.time(), status = "open,acknowledged,closed,archived", limit = 100) { total <- 0 page <- 1 pagelimit <- min(100,limit) after <- as.character(after,format="%Y-%m-%dT%H:%M:%SZ") before <- as.character(before,format="%Y-%m-%dT%H:%M:%SZ") url <- paste("https://seeclickfix.com/api/v2/issues?place_url=",city,"&after=",after,"&before=",before,"&status=",status, "&per_page=",pagelimit,"&page=",page,sep = "") url <- gsub(" ","%20",x=url) rawdata <- RCurl::getURL(url) scf <- jsonlite::fromJSON(txt=rawdata,simplifyDataFrame = T,flatten=F) issue_id = scf$issues$id issue_status = scf$issues$status summary = scf$issues$summary description = scf$issues$description rating = scf$issues$rating lat = scf$issues$lat lng = scf$issues$lng issue_address = scf$issues$address created_at = scf$issues$created_at acknowledged_at = scf$issues$acknowledged_at closed_at = scf$issues$closed_at reopened_at = scf$issues$reopened_at updated_at = scf$issues$updated_at shortened_url = scf$issues$shortened_url video_url = scf$issues$media$video_url image_full = scf$issues$media$image_full image_square_100x100 = scf$issues$media$image_square_100x100 representative_image_url = scf$issues$media$representative_image_url issue_types = scf$issues$point$type # scf$issues$point$coordinates # duplicate of lat/lng url = scf$issues$url html_url = scf$issues$html_url comment_url = scf$issues$comment_url flag_url = scf$issues$flag_url close_url = if(length(scf$issues$transitions$close_url)>0){scf$issues$transitions$close_url} else{NA} open_url = if(length(scf$issues$transitions$open_url)>0){scf$issues$transitions$open_url} else{NA} reporter_id = scf$issues$reporter$id reporter_name = scf$issues$reporter$name reporter_wittytitle = scf$issues$reporter$witty_title reporter_role = scf$issues$reporter$role reporter_civicpoints = scf$issues$reporter$civic_points reporter_avatar_full = scf$issues$reporter$avatar$full reporter_avatar_square = scf$issues$reporter$avatar$square_100x100 allout <- data.frame( issue_id, issue_status, summary, description, rating, lat, lng, issue_address, created_at, acknowledged_at, closed_at, reopened_at, updated_at, shortened_url, video_url, image_full, image_square_100x100, representative_image_url, issue_types, url, html_url, comment_url, flag_url, close_url, open_url, reporter_id, reporter_name, reporter_wittytitle, reporter_role, reporter_civicpoints, reporter_avatar_full, reporter_avatar_square ) total <- nrow(allout) ## check if total n issues < inputted limit: limit <- min(limit,scf$metadata$pagination$entries) while(limit>total){ page <- page+1 if((limit-total)<100){pagelimit <- (limit-total)} url <- paste("https://seeclickfix.com/api/v2/issues?place_url=",city,"&after=",after,"&before=",before,"&status=",status, "&per_page=",pagelimit,"&page=",page,sep = "") url <- gsub(" ","%20",x=url) rawdata <- RCurl::getURL(url) scf <- jsonlite::fromJSON(txt=rawdata,simplifyDataFrame = T,flatten=F) issue_id = scf$issues$id issue_status = scf$issues$status summary = scf$issues$summary description = scf$issues$description rating = scf$issues$rating lat = scf$issues$lat lng = scf$issues$lng issue_address = scf$issues$address created_at = scf$issues$created_at acknowledged_at = scf$issues$acknowledged_at closed_at = scf$issues$closed_at reopened_at = scf$issues$reopened_at updated_at = scf$issues$updated_at shortened_url = scf$issues$shortened_url video_url = scf$issues$media$video_url image_full = scf$issues$media$image_full image_square_100x100 = scf$issues$media$image_square_100x100 representative_image_url = scf$issues$media$representative_image_url issue_types = scf$issues$point$type # scf$issues$point$coordinates # duplicate of lat/lng url = scf$issues$url html_url = scf$issues$html_url comment_url = scf$issues$comment_url flag_url = scf$issues$flag_url close_url = if(length(scf$issues$transitions$close_url)>0){scf$issues$transitions$close_url} else{NA} open_url = if(length(scf$issues$transitions$open_url)>0){scf$issues$transitions$open_url} else{NA} reporter_id = scf$issues$reporter$id reporter_name = scf$issues$reporter$name reporter_wittytitle = scf$issues$reporter$witty_title reporter_role = scf$issues$reporter$role reporter_civicpoints = scf$issues$reporter$civic_points reporter_avatar_full = scf$issues$reporter$avatar$full reporter_avatar_square = scf$issues$reporter$avatar$square_100x100 holder <- data.frame( issue_id, issue_status, summary, description, rating, lat, lng, issue_address, created_at, acknowledged_at, closed_at, reopened_at, updated_at, shortened_url, video_url, image_full, image_square_100x100, representative_image_url, issue_types, url, html_url, comment_url, flag_url, close_url, open_url, reporter_id, reporter_name, reporter_wittytitle, reporter_role, reporter_civicpoints, reporter_avatar_full, reporter_avatar_square ) allout <- rbind(allout,holder) total <- nrow(allout) } return(allout) }
/R/get_issues_by_date.R
no_license
cran/seeclickfixr
R
false
false
5,572
r
get_issues_by_date <- function(city,after = Sys.time()-86400, before = Sys.time(), status = "open,acknowledged,closed,archived", limit = 100) { total <- 0 page <- 1 pagelimit <- min(100,limit) after <- as.character(after,format="%Y-%m-%dT%H:%M:%SZ") before <- as.character(before,format="%Y-%m-%dT%H:%M:%SZ") url <- paste("https://seeclickfix.com/api/v2/issues?place_url=",city,"&after=",after,"&before=",before,"&status=",status, "&per_page=",pagelimit,"&page=",page,sep = "") url <- gsub(" ","%20",x=url) rawdata <- RCurl::getURL(url) scf <- jsonlite::fromJSON(txt=rawdata,simplifyDataFrame = T,flatten=F) issue_id = scf$issues$id issue_status = scf$issues$status summary = scf$issues$summary description = scf$issues$description rating = scf$issues$rating lat = scf$issues$lat lng = scf$issues$lng issue_address = scf$issues$address created_at = scf$issues$created_at acknowledged_at = scf$issues$acknowledged_at closed_at = scf$issues$closed_at reopened_at = scf$issues$reopened_at updated_at = scf$issues$updated_at shortened_url = scf$issues$shortened_url video_url = scf$issues$media$video_url image_full = scf$issues$media$image_full image_square_100x100 = scf$issues$media$image_square_100x100 representative_image_url = scf$issues$media$representative_image_url issue_types = scf$issues$point$type # scf$issues$point$coordinates # duplicate of lat/lng url = scf$issues$url html_url = scf$issues$html_url comment_url = scf$issues$comment_url flag_url = scf$issues$flag_url close_url = if(length(scf$issues$transitions$close_url)>0){scf$issues$transitions$close_url} else{NA} open_url = if(length(scf$issues$transitions$open_url)>0){scf$issues$transitions$open_url} else{NA} reporter_id = scf$issues$reporter$id reporter_name = scf$issues$reporter$name reporter_wittytitle = scf$issues$reporter$witty_title reporter_role = scf$issues$reporter$role reporter_civicpoints = scf$issues$reporter$civic_points reporter_avatar_full = scf$issues$reporter$avatar$full reporter_avatar_square = scf$issues$reporter$avatar$square_100x100 allout <- data.frame( issue_id, issue_status, summary, description, rating, lat, lng, issue_address, created_at, acknowledged_at, closed_at, reopened_at, updated_at, shortened_url, video_url, image_full, image_square_100x100, representative_image_url, issue_types, url, html_url, comment_url, flag_url, close_url, open_url, reporter_id, reporter_name, reporter_wittytitle, reporter_role, reporter_civicpoints, reporter_avatar_full, reporter_avatar_square ) total <- nrow(allout) ## check if total n issues < inputted limit: limit <- min(limit,scf$metadata$pagination$entries) while(limit>total){ page <- page+1 if((limit-total)<100){pagelimit <- (limit-total)} url <- paste("https://seeclickfix.com/api/v2/issues?place_url=",city,"&after=",after,"&before=",before,"&status=",status, "&per_page=",pagelimit,"&page=",page,sep = "") url <- gsub(" ","%20",x=url) rawdata <- RCurl::getURL(url) scf <- jsonlite::fromJSON(txt=rawdata,simplifyDataFrame = T,flatten=F) issue_id = scf$issues$id issue_status = scf$issues$status summary = scf$issues$summary description = scf$issues$description rating = scf$issues$rating lat = scf$issues$lat lng = scf$issues$lng issue_address = scf$issues$address created_at = scf$issues$created_at acknowledged_at = scf$issues$acknowledged_at closed_at = scf$issues$closed_at reopened_at = scf$issues$reopened_at updated_at = scf$issues$updated_at shortened_url = scf$issues$shortened_url video_url = scf$issues$media$video_url image_full = scf$issues$media$image_full image_square_100x100 = scf$issues$media$image_square_100x100 representative_image_url = scf$issues$media$representative_image_url issue_types = scf$issues$point$type # scf$issues$point$coordinates # duplicate of lat/lng url = scf$issues$url html_url = scf$issues$html_url comment_url = scf$issues$comment_url flag_url = scf$issues$flag_url close_url = if(length(scf$issues$transitions$close_url)>0){scf$issues$transitions$close_url} else{NA} open_url = if(length(scf$issues$transitions$open_url)>0){scf$issues$transitions$open_url} else{NA} reporter_id = scf$issues$reporter$id reporter_name = scf$issues$reporter$name reporter_wittytitle = scf$issues$reporter$witty_title reporter_role = scf$issues$reporter$role reporter_civicpoints = scf$issues$reporter$civic_points reporter_avatar_full = scf$issues$reporter$avatar$full reporter_avatar_square = scf$issues$reporter$avatar$square_100x100 holder <- data.frame( issue_id, issue_status, summary, description, rating, lat, lng, issue_address, created_at, acknowledged_at, closed_at, reopened_at, updated_at, shortened_url, video_url, image_full, image_square_100x100, representative_image_url, issue_types, url, html_url, comment_url, flag_url, close_url, open_url, reporter_id, reporter_name, reporter_wittytitle, reporter_role, reporter_civicpoints, reporter_avatar_full, reporter_avatar_square ) allout <- rbind(allout,holder) total <- nrow(allout) } return(allout) }
# Project 1, plot 2 code: # # Note that this script assumes that this script and the input file are in the same directory. # Also, the code is written in Windows Operating System through RStudio hence windows() # graphics device is utilized to plot the figures on screen. # # Step: Record date and R version: (DownloadDate <- date()) (DownloadRversion <- R.version) # load the data, partially: datain <- read.table("household_power_consumption.txt", nrows= 150000, sep=";", header=TRUE, na.string="?") # Transform the date: datain$DateTransformed <- as.Date(datain$Date, "%d/%m/%Y") # Extract the data for the date of 2007-02-01: DataForDate1 <- datain[datain$DateTransformed == "2007-02-01",] # Extract the data for the date of 2007-02-02: DataForDate2 <- datain[datain$DateTransformed == "2007-02-02",] # Combine the extracted data sets into single data set: DataExtracted <- rbind(DataForDate1, DataForDate2) # Subset the Global_active_power column for the histogram: GAP <- DataExtracted$Global_active_power dates <- DataExtracted$Date times <- DataExtracted$Time x <- paste(dates,times) xx <- strptime(x, format="%d/%m/%Y %H:%M:%S") # Display the figure on the screen: windows() plot(xx,GAP, type="l", xlab=" ", ylab="Global Active Power (kilowatts)") dev.off() # Save the figure to PNG: png(file = "plot2.png", units = "px", width=480, height=480, res=NA) plot(xx,GAP, type="l", xlab=" ", ylab="Global Active Power (kilowatts)") dev.off() ########################################################## ########################################################## # end-of-file
/plot2.R
no_license
zikribayraktar/ExData_Plotting1
R
false
false
1,590
r
# Project 1, plot 2 code: # # Note that this script assumes that this script and the input file are in the same directory. # Also, the code is written in Windows Operating System through RStudio hence windows() # graphics device is utilized to plot the figures on screen. # # Step: Record date and R version: (DownloadDate <- date()) (DownloadRversion <- R.version) # load the data, partially: datain <- read.table("household_power_consumption.txt", nrows= 150000, sep=";", header=TRUE, na.string="?") # Transform the date: datain$DateTransformed <- as.Date(datain$Date, "%d/%m/%Y") # Extract the data for the date of 2007-02-01: DataForDate1 <- datain[datain$DateTransformed == "2007-02-01",] # Extract the data for the date of 2007-02-02: DataForDate2 <- datain[datain$DateTransformed == "2007-02-02",] # Combine the extracted data sets into single data set: DataExtracted <- rbind(DataForDate1, DataForDate2) # Subset the Global_active_power column for the histogram: GAP <- DataExtracted$Global_active_power dates <- DataExtracted$Date times <- DataExtracted$Time x <- paste(dates,times) xx <- strptime(x, format="%d/%m/%Y %H:%M:%S") # Display the figure on the screen: windows() plot(xx,GAP, type="l", xlab=" ", ylab="Global Active Power (kilowatts)") dev.off() # Save the figure to PNG: png(file = "plot2.png", units = "px", width=480, height=480, res=NA) plot(xx,GAP, type="l", xlab=" ", ylab="Global Active Power (kilowatts)") dev.off() ########################################################## ########################################################## # end-of-file
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/plot_data_one_iso.R \name{plot_data_one_iso} \alias{plot_data_one_iso} \title{Plot biotracer data (1-D)} \usage{ plot_data_one_iso(mix, source, discr, filename, plot_save_pdf, plot_save_png) } \arguments{ \item{mix}{output from \code{\link{load_mix_data}}} \item{source}{output from \code{\link{load_source_data}}} \item{discr}{output from \code{\link{load_discr_data}}} \item{filename}{name of the plot file(s) to save (e.g. "isospace_plot")} \item{plot_save_pdf}{T/F, save the plot(s) as a pdf?} \item{plot_save_png}{T/F, save the plot(s) as a png?} } \description{ \code{plot_data_one_iso} creates a 1-D plot of mix and source tracer data and saves the plot to a file in the working directory } \details{ An important detail is that \code{plot_data_one_iso} plots the raw mix data and \emph{adds the TDF to the source data}, since this is the polygon that the mixing model uses to determine proportions. The plotted source means are: \deqn{\mu_source + \mu_discr} The source error bars are +/- 1 standard deviation, \emph{calculated as a combination of source and TDF variances:} \deqn{\sqrt{\sigma^2_source + \sigma^2_discr}} \code{plot_data_one_iso} looks for 'C', 'N', 'S', and 'O' in the biotracer column headers and assumes they are stable isotopes, labeling the axes with, e.g., expression(paste(delta^13, "C (u2030)",sep="")). } \seealso{ \code{\link{plot_data}} }
/man/plot_data_one_iso.Rd
no_license
izabelabujak/MixSIAR
R
false
true
1,459
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/plot_data_one_iso.R \name{plot_data_one_iso} \alias{plot_data_one_iso} \title{Plot biotracer data (1-D)} \usage{ plot_data_one_iso(mix, source, discr, filename, plot_save_pdf, plot_save_png) } \arguments{ \item{mix}{output from \code{\link{load_mix_data}}} \item{source}{output from \code{\link{load_source_data}}} \item{discr}{output from \code{\link{load_discr_data}}} \item{filename}{name of the plot file(s) to save (e.g. "isospace_plot")} \item{plot_save_pdf}{T/F, save the plot(s) as a pdf?} \item{plot_save_png}{T/F, save the plot(s) as a png?} } \description{ \code{plot_data_one_iso} creates a 1-D plot of mix and source tracer data and saves the plot to a file in the working directory } \details{ An important detail is that \code{plot_data_one_iso} plots the raw mix data and \emph{adds the TDF to the source data}, since this is the polygon that the mixing model uses to determine proportions. The plotted source means are: \deqn{\mu_source + \mu_discr} The source error bars are +/- 1 standard deviation, \emph{calculated as a combination of source and TDF variances:} \deqn{\sqrt{\sigma^2_source + \sigma^2_discr}} \code{plot_data_one_iso} looks for 'C', 'N', 'S', and 'O' in the biotracer column headers and assumes they are stable isotopes, labeling the axes with, e.g., expression(paste(delta^13, "C (u2030)",sep="")). } \seealso{ \code{\link{plot_data}} }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/url.R \name{update_seafile_url} \alias{update_seafile_url} \title{Update seafile URL} \usage{ update_seafile_url() } \description{ update the seafile api url }
/man/update_seafile_url.Rd
no_license
VincentGuyader/seafile
R
false
true
249
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/url.R \name{update_seafile_url} \alias{update_seafile_url} \title{Update seafile URL} \usage{ update_seafile_url() } \description{ update the seafile api url }
getFlights <- function(status = c("ankunft", "abflug"), hour = formatC(c(0, 3:11 * 2), flag = "0", width = 2, format = "d")) { stopifnot(require("XML")) status <- match.arg(status) hour <- match.arg(hour, several.ok = TRUE) URLs <- switch(status, "ankunft" = paste("http://www.munich-airport.de/de/consumer/fluginfo/ankunft/h", hour, "00_de_L.jsp", sep = ""), "abflug" = paste("http://www.munich-airport.de/de/consumer/fluginfo/abflug/h", hour, "00_de_S.jsp", sep = "")) websites <- lapply(URLs, htmlTreeParse, useInternalNodes = TRUE, encoding = "UTF-8") ## raw Data List rDL<- lapply(websites, xpathSApply, path="//table//input[@type='hidden']", xmlAttrs) lapply(websites, free) ### remove pages without a flight table rDL <- rDL[sapply(rDL, length) > 0] dataList <- lapply(rDL, function(z) { ret <- matrix(z["value", ], ncol = 20, byrow = TRUE) colnames(ret) <- z["name", 1:20] as.data.frame(ret, stringsAsFactors = FALSE) }) ## ornamente resDF <- do.call(rbind, dataList) resDF <- resDF[, !colnames(resDF) %in% c("key", "zurueck")] resDF$ett[resDF$ett == ""] <- resDF$stt[resDF$ett == ""] ## resDF$stt <- strftime(resDF$stt, format = "%Y-%m-%d %H:%M:%S.0") ## resDF$ett <- strftime(resDF$ett, format = "%Y-%m-%d %H:%M:%S.0") return(resDF) } # muc <- rbind(getFlights("ankunft"), getFlights("abflug")) # save(muc, file = paste("../data/", Sys.Date(), "_Flugdaten", ".RData", sep = "" ))
/MUCflights/R/getFlights.R
no_license
ingted/R-Examples
R
false
false
1,585
r
getFlights <- function(status = c("ankunft", "abflug"), hour = formatC(c(0, 3:11 * 2), flag = "0", width = 2, format = "d")) { stopifnot(require("XML")) status <- match.arg(status) hour <- match.arg(hour, several.ok = TRUE) URLs <- switch(status, "ankunft" = paste("http://www.munich-airport.de/de/consumer/fluginfo/ankunft/h", hour, "00_de_L.jsp", sep = ""), "abflug" = paste("http://www.munich-airport.de/de/consumer/fluginfo/abflug/h", hour, "00_de_S.jsp", sep = "")) websites <- lapply(URLs, htmlTreeParse, useInternalNodes = TRUE, encoding = "UTF-8") ## raw Data List rDL<- lapply(websites, xpathSApply, path="//table//input[@type='hidden']", xmlAttrs) lapply(websites, free) ### remove pages without a flight table rDL <- rDL[sapply(rDL, length) > 0] dataList <- lapply(rDL, function(z) { ret <- matrix(z["value", ], ncol = 20, byrow = TRUE) colnames(ret) <- z["name", 1:20] as.data.frame(ret, stringsAsFactors = FALSE) }) ## ornamente resDF <- do.call(rbind, dataList) resDF <- resDF[, !colnames(resDF) %in% c("key", "zurueck")] resDF$ett[resDF$ett == ""] <- resDF$stt[resDF$ett == ""] ## resDF$stt <- strftime(resDF$stt, format = "%Y-%m-%d %H:%M:%S.0") ## resDF$ett <- strftime(resDF$ett, format = "%Y-%m-%d %H:%M:%S.0") return(resDF) } # muc <- rbind(getFlights("ankunft"), getFlights("abflug")) # save(muc, file = paste("../data/", Sys.Date(), "_Flugdaten", ".RData", sep = "" ))
#setwd("~/Desktop/PSM/Spring 2019/Multivariate-Stats/Project") #Make my n=2 dimenstional data/hypershpere image library(plotrix) p1=data.frame(x=double(),y=double()) #Points names(p1)=c("X", "Y") while(dim(p1)[1]<200){ #Get 200 points for the first bubble by making circle x=runif(1, min=-1, max=1) y=runif(1, min=-1, max=1) if((x**2+y**2)<=1){ p1[nrow(p1)+1,]=c(x,y) } } while(dim(p1)[1]<400){ #200 more but with a shift to a new center now x=runif(1, min=-1, max=1) y=runif(1, min=-1, max=1) if((x**2+y**2)<=1){ p1[nrow(p1)+1,]=c(x+3,y+3) } } plot(p1) png("circles.png") plot(p1) dev.off() ####### Example 12.4 library(sem) rm(list=ls()) X <- readMoments("T12-3.DAT",diag=TRUE) #Language Linakage data colnames(X) <- c("E","N", "Da", "Du", "G","Fr", "Sp", "I", "P", "H", "Fi") rownames(X) <- c("E","N", "Da", "Du", "G","Fr", "Sp", "I", "P", "H", "Fi") D <- 10-X #Convert to distance C <- hclust(as.dist(D), method = "average") #Do an average distance cluster analysis plot(C) #Dendro Plot png("LanguageDendo.png") plot(C) dev.off() ### Example 12.5 rm(list = ls()) D <- matrix(c(0, 9, 3, 6,11, 9,0, 7 , 5, 10, 3,7,0, 9,2, 6,5,9,0,8, 11,10,2,8,0), byrow=TRUE, ncol=5) #Complete linkage example C <- hclust(as.dist(D), method = "complete") #Desired Result plot(C) #This plot shows that the first cluster will be (35), then (24), then (124), #and finally (12345) min(D[D>0]) #Find the smallest value in distance matrix Dnew=D #Corresponds to (35) cluster. Remove relevant rows, and add new row, Dnew <- Dnew[-c(3,5),-c(3,5)] d351 <- max(D[3,1],D[5,1]) d352 <- max(D[3,2],D[5,2]) d354 <- max(D[3,4],D[5,4]) Dnew <- cbind(c(d351,d352,d354),Dnew) Dnew <- rbind(c(0,d351,d352,d354),Dnew) D <- Dnew min(D[D>0])#Find the smallest value in distance matrix #Corresponds to (24) cluster. Remove relevant rows, and add new row, Dnew <- Dnew[-c(3,4),-c(3,4)] d2435 <- max(D[1,3],D[1,4]) d241 <- max(D[3,2],D[4,2]) Dnew <- cbind(Dnew[,1],c(0,d241),Dnew[,2]) Dnew <- rbind(Dnew[1,],c(d2435,0,d241),Dnew[2,]) min(D[D>0]) #Corresponds to (124) cluster. Remove relevant rows, and add new row, Dnew <- Dnew[-c(2,3),-c(2,3)] d24135 <- max(D[1,3],D[1,2]) Dnew <- cbind(c(0,d24135),c(d24135,0)) D<- Dnew min(D[D>0])#Find the smallest value in distance matrix #Corresponds to the (12345) cluster, we are done. #We see here that our results matched perfectly the complete linkage method in R ### Example 12.7 rm(list=ls()) library(sem) X <- readMoments("T12-5.DAT",diag=TRUE) #Correlations in public utility data C <- hclust(as.dist(X), method = "complete") plot(C) ####################################################################### ####################################################################### ############# Some Worked Problems #################################### ####################################################################### ####################################################################### #12 .1 ''' Consider the binary values: {1 if from South, 0 else} {1 if elected first term, 0 else} {1 if Democrat, 0 else} {1 if Prior Experience, 0 else} {1 if former Vice, 0 else} Then, consider the following, ''' rm(list = ls()) X <- matrix(c(0,1,0,0,0, 1,1,1,0,0, 0,0,0,1,1, 0,1,0,1,1, 1,0,1,1,1, 0,1,1,1,0), byrow=TRUE, ncol=5) #Reagan Carter a=1 b=3 sim1 <- matrix(c(0,0, 0,0), byrow=TRUE, ncol=2) for(i in 1:5){ if(X[a,i]==1 && X[b,i]==1){ sim1[1,1]<- sim1[1,1]+1 } if(X[a,i]==1 && X[b,i]==0){ sim1[1,2]<- sim1[1,2]+1 } if(X[a,i]==0 && X[b,i]==1){ sim1[2,1]<- sim1[2,1]+1 } if(X[a,i]==0 && X[b,i]==0){ sim1[2,2]<- sim1[2,2]+1 } } (simCoef1 <- (sim1[1,1]+sim1[2,2])/sum(sim1)) ## 12.7 Stock Data rm(list=ls()) X <- matrix(c(1,.63,.51,.12,.16, .63,1,.57,.32,.21, .51,.57,1,.18,.15, .12,.32,.18,1,.68, .16,.21,.15,.68,1), byrow = TRUE, ncol=5) row.names(X) <- c("JP Morgan", "Citibank","Wells Fargo", "Royal DutchShell","ExxonMobil") C <- hclust(as.dist(X), method = "complete") plot(C) #We see based on this analysis that JP Morgan and Royal DutchShell are closely related, followed by Wells fargo and ExxonMobil C <- hclust(as.dist(X), method = "average") plot(C) #We see that there is a similar initial breakdown in this dendrogram, but uwing the average method actually causes the two pairs to merge before adding Citibank now ## 12.15 #This one will be k-means clustering rm(list=ls()) X <- read.table("T11-9.dat") X<-X[-c(1,2)] k1 <- kmeans(X[,1:5],2) print(k1) k2 <- kmeans(X[,1:5],3) print(k2) k3 <- kmeans(X[,1:5],4) print(k3) hist(k1$cluster) hist(k2$cluster) hist(k3$cluster) #We see that the data clusters into roughly even groups, and that each successive addtion of a group is likely just a natural partition of an existing group # 12.26 Maloi Farm rm(list=ls()) X <- read.table("T8-7.DAT", header=FALSE) X <- X[-c(25,34,69,72),]#,-c(1,7:9)] D <- matrix(0, nrow= 72, ncol=72) for(i in 1:72){ for(j in i:72){ d <- sqrt(sum((X[i,]-X[j,])^2)) D[i,j] <- d } } D<-t(D) D <- as.dist(D) avg <- hclust(D, method="average") plot(avg) ward <- hclust(D, method = "ward.D") plot(ward) ## Based on the Ward method, we see tat there are around 7 base clusters of farms based on Euclidean Distance library(cluster) k1 <- kmeans(X,5) s=silhouette(k1$cl,D) plot(s) clusplot(X,k1$cluster) k2 <- kmeans(X,6) s2=silhouette(k2$cl,D) plot(s2) clusplot(X,k2$cluster) #We see that the data is well wrapped within the 5 or 6 clusters that we are using.
/Project/ALL FILES/Clustering.R
no_license
justinhood/Multivariate-Stats
R
false
false
5,637
r
#setwd("~/Desktop/PSM/Spring 2019/Multivariate-Stats/Project") #Make my n=2 dimenstional data/hypershpere image library(plotrix) p1=data.frame(x=double(),y=double()) #Points names(p1)=c("X", "Y") while(dim(p1)[1]<200){ #Get 200 points for the first bubble by making circle x=runif(1, min=-1, max=1) y=runif(1, min=-1, max=1) if((x**2+y**2)<=1){ p1[nrow(p1)+1,]=c(x,y) } } while(dim(p1)[1]<400){ #200 more but with a shift to a new center now x=runif(1, min=-1, max=1) y=runif(1, min=-1, max=1) if((x**2+y**2)<=1){ p1[nrow(p1)+1,]=c(x+3,y+3) } } plot(p1) png("circles.png") plot(p1) dev.off() ####### Example 12.4 library(sem) rm(list=ls()) X <- readMoments("T12-3.DAT",diag=TRUE) #Language Linakage data colnames(X) <- c("E","N", "Da", "Du", "G","Fr", "Sp", "I", "P", "H", "Fi") rownames(X) <- c("E","N", "Da", "Du", "G","Fr", "Sp", "I", "P", "H", "Fi") D <- 10-X #Convert to distance C <- hclust(as.dist(D), method = "average") #Do an average distance cluster analysis plot(C) #Dendro Plot png("LanguageDendo.png") plot(C) dev.off() ### Example 12.5 rm(list = ls()) D <- matrix(c(0, 9, 3, 6,11, 9,0, 7 , 5, 10, 3,7,0, 9,2, 6,5,9,0,8, 11,10,2,8,0), byrow=TRUE, ncol=5) #Complete linkage example C <- hclust(as.dist(D), method = "complete") #Desired Result plot(C) #This plot shows that the first cluster will be (35), then (24), then (124), #and finally (12345) min(D[D>0]) #Find the smallest value in distance matrix Dnew=D #Corresponds to (35) cluster. Remove relevant rows, and add new row, Dnew <- Dnew[-c(3,5),-c(3,5)] d351 <- max(D[3,1],D[5,1]) d352 <- max(D[3,2],D[5,2]) d354 <- max(D[3,4],D[5,4]) Dnew <- cbind(c(d351,d352,d354),Dnew) Dnew <- rbind(c(0,d351,d352,d354),Dnew) D <- Dnew min(D[D>0])#Find the smallest value in distance matrix #Corresponds to (24) cluster. Remove relevant rows, and add new row, Dnew <- Dnew[-c(3,4),-c(3,4)] d2435 <- max(D[1,3],D[1,4]) d241 <- max(D[3,2],D[4,2]) Dnew <- cbind(Dnew[,1],c(0,d241),Dnew[,2]) Dnew <- rbind(Dnew[1,],c(d2435,0,d241),Dnew[2,]) min(D[D>0]) #Corresponds to (124) cluster. Remove relevant rows, and add new row, Dnew <- Dnew[-c(2,3),-c(2,3)] d24135 <- max(D[1,3],D[1,2]) Dnew <- cbind(c(0,d24135),c(d24135,0)) D<- Dnew min(D[D>0])#Find the smallest value in distance matrix #Corresponds to the (12345) cluster, we are done. #We see here that our results matched perfectly the complete linkage method in R ### Example 12.7 rm(list=ls()) library(sem) X <- readMoments("T12-5.DAT",diag=TRUE) #Correlations in public utility data C <- hclust(as.dist(X), method = "complete") plot(C) ####################################################################### ####################################################################### ############# Some Worked Problems #################################### ####################################################################### ####################################################################### #12 .1 ''' Consider the binary values: {1 if from South, 0 else} {1 if elected first term, 0 else} {1 if Democrat, 0 else} {1 if Prior Experience, 0 else} {1 if former Vice, 0 else} Then, consider the following, ''' rm(list = ls()) X <- matrix(c(0,1,0,0,0, 1,1,1,0,0, 0,0,0,1,1, 0,1,0,1,1, 1,0,1,1,1, 0,1,1,1,0), byrow=TRUE, ncol=5) #Reagan Carter a=1 b=3 sim1 <- matrix(c(0,0, 0,0), byrow=TRUE, ncol=2) for(i in 1:5){ if(X[a,i]==1 && X[b,i]==1){ sim1[1,1]<- sim1[1,1]+1 } if(X[a,i]==1 && X[b,i]==0){ sim1[1,2]<- sim1[1,2]+1 } if(X[a,i]==0 && X[b,i]==1){ sim1[2,1]<- sim1[2,1]+1 } if(X[a,i]==0 && X[b,i]==0){ sim1[2,2]<- sim1[2,2]+1 } } (simCoef1 <- (sim1[1,1]+sim1[2,2])/sum(sim1)) ## 12.7 Stock Data rm(list=ls()) X <- matrix(c(1,.63,.51,.12,.16, .63,1,.57,.32,.21, .51,.57,1,.18,.15, .12,.32,.18,1,.68, .16,.21,.15,.68,1), byrow = TRUE, ncol=5) row.names(X) <- c("JP Morgan", "Citibank","Wells Fargo", "Royal DutchShell","ExxonMobil") C <- hclust(as.dist(X), method = "complete") plot(C) #We see based on this analysis that JP Morgan and Royal DutchShell are closely related, followed by Wells fargo and ExxonMobil C <- hclust(as.dist(X), method = "average") plot(C) #We see that there is a similar initial breakdown in this dendrogram, but uwing the average method actually causes the two pairs to merge before adding Citibank now ## 12.15 #This one will be k-means clustering rm(list=ls()) X <- read.table("T11-9.dat") X<-X[-c(1,2)] k1 <- kmeans(X[,1:5],2) print(k1) k2 <- kmeans(X[,1:5],3) print(k2) k3 <- kmeans(X[,1:5],4) print(k3) hist(k1$cluster) hist(k2$cluster) hist(k3$cluster) #We see that the data clusters into roughly even groups, and that each successive addtion of a group is likely just a natural partition of an existing group # 12.26 Maloi Farm rm(list=ls()) X <- read.table("T8-7.DAT", header=FALSE) X <- X[-c(25,34,69,72),]#,-c(1,7:9)] D <- matrix(0, nrow= 72, ncol=72) for(i in 1:72){ for(j in i:72){ d <- sqrt(sum((X[i,]-X[j,])^2)) D[i,j] <- d } } D<-t(D) D <- as.dist(D) avg <- hclust(D, method="average") plot(avg) ward <- hclust(D, method = "ward.D") plot(ward) ## Based on the Ward method, we see tat there are around 7 base clusters of farms based on Euclidean Distance library(cluster) k1 <- kmeans(X,5) s=silhouette(k1$cl,D) plot(s) clusplot(X,k1$cluster) k2 <- kmeans(X,6) s2=silhouette(k2$cl,D) plot(s2) clusplot(X,k2$cluster) #We see that the data is well wrapped within the 5 or 6 clusters that we are using.
## Take in data and create a pomp object for each individual # --------------------------------------------------- make_pomp_panel <- function(i, infection_data = data, times_data = times, covariates = covartable, n_cov = n_covariates, test_params = guess, rprocess = rprocess_homologous_immunity, init = init_homologous_immunity ){ log_paramnames <- names(test_params) cat("i is: ", i , "\n") n.cov <- length(grep("cov",names(covariates))) data_i <- infection_data[i,grep("y",names(infection_data))] ind <- which(!is.na(data_i)) data_i_complete <- data_i[ind] covariates_i <- subset(covariates, subjectId == infection_data[i,]$subjectId) times_i <- times_data[i,grep("v",names(times_data))] times_i_complete <- times_i[ind] covs <- covariates_i[ind, grep("cov|c_i",names(covariates_i))] n.vis <- length(times_i_complete) print(n.vis) t <- as.numeric(get_tbv(times_i_complete)) stopifnot(t[1] == 0) t <- t[-1] covartab <- data.frame(tbv = c(t,0) , covs ) names(covartab) <- c("tbv", paste0("cov",c(1:n_cov)),"c_i","cov_7_2","cov_8_2") covartab$visit <- c(1:n.vis) pomp_data <- data.frame(y = as.numeric(data_i_complete[1:n.vis]), visit = c(1:n.vis)) statenames = c("x","duration_remaining", "previously_cleared", "t_activate", "t_cum") obsnames = "y" pomp_object <- pomp( data = pomp_data, times ="visit", t0=1, params=unlist(test_params), rprocess = discrete.time.sim(step.fun=rprocess,delta.t=1), dmeasure = dmeasure, rmeasure = rmeasure, covar = covartab, tcovar = "visit", obsnames = obsnames, statenames = statenames, paramnames = log_paramnames, initializer = init ) return(pomp_object) }
/Inference/homologous_immunity_model/data_processing/make_one_panel_pomp_unit.R
no_license
jabogaards/HPV-model
R
false
false
1,794
r
## Take in data and create a pomp object for each individual # --------------------------------------------------- make_pomp_panel <- function(i, infection_data = data, times_data = times, covariates = covartable, n_cov = n_covariates, test_params = guess, rprocess = rprocess_homologous_immunity, init = init_homologous_immunity ){ log_paramnames <- names(test_params) cat("i is: ", i , "\n") n.cov <- length(grep("cov",names(covariates))) data_i <- infection_data[i,grep("y",names(infection_data))] ind <- which(!is.na(data_i)) data_i_complete <- data_i[ind] covariates_i <- subset(covariates, subjectId == infection_data[i,]$subjectId) times_i <- times_data[i,grep("v",names(times_data))] times_i_complete <- times_i[ind] covs <- covariates_i[ind, grep("cov|c_i",names(covariates_i))] n.vis <- length(times_i_complete) print(n.vis) t <- as.numeric(get_tbv(times_i_complete)) stopifnot(t[1] == 0) t <- t[-1] covartab <- data.frame(tbv = c(t,0) , covs ) names(covartab) <- c("tbv", paste0("cov",c(1:n_cov)),"c_i","cov_7_2","cov_8_2") covartab$visit <- c(1:n.vis) pomp_data <- data.frame(y = as.numeric(data_i_complete[1:n.vis]), visit = c(1:n.vis)) statenames = c("x","duration_remaining", "previously_cleared", "t_activate", "t_cum") obsnames = "y" pomp_object <- pomp( data = pomp_data, times ="visit", t0=1, params=unlist(test_params), rprocess = discrete.time.sim(step.fun=rprocess,delta.t=1), dmeasure = dmeasure, rmeasure = rmeasure, covar = covartab, tcovar = "visit", obsnames = obsnames, statenames = statenames, paramnames = log_paramnames, initializer = init ) return(pomp_object) }
library(MXM) ### Name: Conditional independence test for longitudinal and clustered data using GLMM ### Title: Linear mixed models conditional independence test for ### longitudinal class variables ### Aliases: testIndGLMMReg testIndGLMMLogistic testIndGLMMPois ### testIndGLMMGamma testIndGLMMNormLog testIndGLMMOrdinal testIndGLMMCR ### testIndLMM ### Keywords: Linear mixed model Conditional independence test ### ** Examples y <- rnorm(150) x <- matrix(rnorm(150 * 5), ncol = 5) id <- sample(1:20, 150, replace = TRUE) testIndGLMMReg(y, group=id, dataset=x, xIndex=1, csIndex=3) testIndLMM(y, group=id, dataset=x, xIndex=1, csIndex=3)
/data/genthat_extracted_code/MXM/examples/testIndGLMMReg.Rd.R
no_license
surayaaramli/typeRrh
R
false
false
652
r
library(MXM) ### Name: Conditional independence test for longitudinal and clustered data using GLMM ### Title: Linear mixed models conditional independence test for ### longitudinal class variables ### Aliases: testIndGLMMReg testIndGLMMLogistic testIndGLMMPois ### testIndGLMMGamma testIndGLMMNormLog testIndGLMMOrdinal testIndGLMMCR ### testIndLMM ### Keywords: Linear mixed model Conditional independence test ### ** Examples y <- rnorm(150) x <- matrix(rnorm(150 * 5), ncol = 5) id <- sample(1:20, 150, replace = TRUE) testIndGLMMReg(y, group=id, dataset=x, xIndex=1, csIndex=3) testIndLMM(y, group=id, dataset=x, xIndex=1, csIndex=3)
#### Utility for TR pattern and flanking MH identification #### This utility requires the genome utility clousure # sequence identity below this threshold will be denied consensus_thresh <- 0.75 consensus_lower <- 0.5 # consensus_thresh <- 0.3 # consensus_lower <- 0.5 # 4 bases bases <- c("A", "C", "G", "T") # this function returns the base freq matrix given a vector of # sequences with the same length (nchar) makeFrequencyMatrix <- function(seqs) { n <- nchar(seqs[1]) seqs <- matrix(unlist(strsplit(seqs, "")), n) m <- matrix(0, 4, n) for (j in 1:n) { b <- seqs[j, ] for (i in 1:4) { m[i, j] <- sum(b == bases[i]) } } rownames(m) <- bases m / ncol(seqs) } # this function returns a consensus sequence given a freq matrix makeConsensus <- function(fm) { use <- paste(apply(fm, 2, function(cl) bases[which(cl == max(cl))[1]]), collapse = "") out <- paste(apply(fm, 2, function(cl) { if (all(cl < 0.4)) b <- "*" else { b <- bases[which(cl > max(cl) - 0.1)] if (length(b) > 1) b <- paste0("[", paste(b, collapse = "/"), "]") else b <- bases[which(cl == max(cl))[1]] } b } ), collapse = "") attr(use, "output") <- out use } # this function returns the entropy of a given freq matrix seqEntropy <- function(fm) { baserate <- rowSums(fm) / ncol(fm) sum(ifelse(baserate == 0, 0, -baserate * log2(baserate))) } # this function returns the information content of a given freq matrix # infoContent <- function(fm) {} # this function calculate the match between a sequence and a freq matrix match <- function(seq, fm) { seq <- unlist(strsplit(seq, "")) s <- 0 for (i in 1:length(seq)) { s <- s + fm[seq[i], (i-1)%%ncol(fm)+1] } s } # this function find if a given subsequence have inner repetitive pattern findInnerRep <- function(seq) { # find the inner repeating pattern of a given seq n <- nchar(seq) inner <- 1 for (i in (2:n)[n %% (2:n) == 0]) { ss <- substring(seq, (1:i - 1) * n/i + 1, 1:i * n/i) fm <- makeFrequencyMatrix(ss) if (all(sapply(ss, match, fm = fm) > consensus_thresh * n / i)) inner <- i } inner } # this is the main function that identifies the TR given the unit info annotateTR <- function(gu, chr, posOriginal, k) { pos <- posOriginal seq <- gu$extract(chr, pos, pos+k-1) endpos <- pos + k ir <- 1 ir <- tryCatch( { findInnerRep(seq) }) if (ir > 1) seq <- substring(seq, (1:ir - 1) * nchar(seq)/ir + 1, 1:ir * nchar(seq)/ir) k <- nchar(seq[1]) lor <- 0 score <- numeric() repeat { e <- gu$extract(chr, pos - (lor+1) * k, pos - lor * k - 1) if (e == -1) break else { s <- match(e, makeFrequencyMatrix(seq)) if (s < consensus_lower*k) break else { score[length(score)+1] <- s ; seq <- c(e, seq) ; lor <- lor+1 } } } lor <- which(score > consensus_thresh*k) if (length(lor)) lor <- max(lor) else lor <- 0 seq <- seq[(length(seq)-ir-lor+1):length(seq)] ror <- 0 score <- numeric() repeat { e <- gu$extract(chr, endpos + ror * k, endpos + (ror+1) * k - 1) if (e == -1) break else { s <- match(e, makeFrequencyMatrix(seq)) if (s < consensus_lower*k) break else { score[length(score)+1] <- s ; seq <- c(seq, e) ; ror <- ror+1 } } } ror <- which(score > consensus_thresh*k) if (length(ror)) ror <- max(ror) else ror <- 0 seq <- seq[1:(lor+ir+ror)] pos <- pos - lor * k rep <- length(seq) if (rep > 1) { repeat { e <- gu$extract(chr, pos - 1) if (e == -1) break else { shift <- paste0( c(e, substring(seq[1:(rep-1)], k, k)), substring(seq, 1, k-1) ) if (match(shift, makeFrequencyMatrix(shift)) >= match(seq, makeFrequencyMatrix(seq))) { pos <- pos-1 ; seq <- shift e <- gu$extract(chr, pos + k*rep, pos + k*(rep+1) - 1) if (e != -1 && match(e, makeFrequencyMatrix(seq)) >= consensus_thresh*k) { seq <- c(seq, e) ; rep <- rep+1 } } else break } } } fl <- 0 mh <- "" counter_to_avoid_loop = 0 repeat { counter_to_avoid_loop = counter_to_avoid_loop + 1 if(counter_to_avoid_loop>1000){ mh = 'XXXXXXXXXXXXXXXXXXXXXX' break } if (fl >= consensus_thresh*k && k-fl < 4) { e <- gu$extract(chr, pos + rep * k, pos + (rep+1) * k-1) if (e != -1) { seq[rep+1] <- gu$extract(chr, pos + rep * k, pos + (rep+1) * k-1) rep <- rep + 1 ; fl <- 0 ; mh <- "" } } else { e <- gu$extract(chr, pos + rep * k, pos + rep * k + fl) if (e == -1) break else { if (all(e == substring(seq, 1, fl+1))) { fl <- fl+1 ; mh <- e } else break } } } if (nchar(mh) < 2) mh <- "" mat <- makeFrequencyMatrix(seq) cons <- makeConsensus(mat) entropy <- seqEntropy(mat) list(chr = chr, posOriginal = posOriginal , pos = pos, rep = rep, k = k, seq = seq, cons = attr(cons, "output"), entropy = entropy, mh = mh) } # annotateIndelTR <- function(gu, chr, pos, seq, is_insert = F) { # endpos <- ifelse(is_insert, pos, pos + nchar(seq)) # ir <- findInnerRep(seq) # repeat unit count in the indel seq # if (ir > 1) seq <- substring(seq, (1:ir - 1) * nchar(seq)/ir + 1, 1:ir * nchar(seq)/ir) # k <- nchar(seq[1]) # lor <- 0 # repeat unit count on the left side of indel site # while ({ # e <- gu$extract(chr, pos - (lor+1) * k + 1, pos - lor * k) # if (e != -1) { # seq <- c(e, seq) # meanEntropy(makeFrequencyMatrix(seq)) < consensus_thresh # } else { # if (1 < pos - lor * k) { # seq <- c(gu$extract(chr, 1, pos - lor * k), seq) # } else seq <- c("", seq) # FALSE # } # }) lor <- lor + 1 # ror <- 0 # repeat unit count on the right side of indel site # while ({ # e <- gu$extract(chr, endpos + ror * k, endpos + (ror+1) * k - 1) # if (e != -1) { # seq <- c(seq, e) # meanEntropy(makeFrequencyMatrix(seq[-1])) < consensus_thresh # } else { # if (endpos + ror * k < gu$getLength(chr)) { # seq <- c(seq, gu$extract(chr, endpos + ror * k, gu$getLength(chr))) # } else seq <- c(seq, "") # FALSE # } # }) ror <- ror + 1 # mat <- makeFrequencyMatrix(seq[2:(length(seq)-1)]) # frequency matrix # con <- makeConsensus(mat) # consensus sequence # lf <- 0 # left flanking homology # # while ({ # # pb <- mat[substring(seq[1], k-lf, k-lf), k-lf] # # # pb > 0.4 && pb > max(mat[, k-lf]) - 0.1 # # pb == 1 # # }) lf <- lf + 1 # rf <- 0 # right flanking homology # while ( (rf < nchar(seq[length(seq)])) && # (mat[substring(seq[length(seq)], rf+1, rf+1), rf+1] == 1) ) rf <- rf + 1 # if (lf + rf >= 3 && lf + rf <= min(15, 0.75 * k) ) { # recognize as microhomology # if (lf > 0 && rf == 0) mh <- mat[ ,(k-lf+1):k] # else if (lf ==0 && rf > 0) mh <- mat[, 1:rf] # else mh <- mat[, c((k - lf + 1):k, 1:rf)] # mh <- makeConsensus(mh) # if (lf != 0) seq[1:(length(seq) - 1)] <- paste( # substring(seq[1:(length(seq) - 1)], 1, k-lf), # tolower(substring(seq[1:(length(seq) - 1)], k-lf+1, k)), sep = "" # ) # if (rf != 0) seq[2:length(seq)] <- paste( # tolower(substring(seq[2:length(seq)], 1, rf)), # substring(seq[2:length(seq)], rf+1, k), sep = "" # ) # } else mh <- "" # rnc <- if (is_insert) { c(lor + ror, lor + ir + ror) # } else { c(lor + ir + ror, lor + ror) } # repeat number # # reformat sequence # if (rnc[1] > 0) { # seq[(lor+2)] <- paste0(ifelse(is_insert, ">", "<"), seq[(lor+2)]) # seq[(lor+1+ir)] <- paste0(seq[(lor+1+ir)], ifelse(is_insert, "<", ">")) # seq <- paste0(chr, ":",pos - (lor+1) * k, " - ", paste(seq, collapse = " ")) # repstarts <- pos + c((-lor):(ir + ror - is_insert - 1)) * k # repends <- repstarts + k # mhstarts <- c(repstarts[1], repends) # mhends <- mhstarts + nchar(mh) # return(list(repeat_number = rnc, consensus = con, seq = seq, microhomology = mh, # repeat_starts = repstarts, repeat_ends = repends, # mh_starts = mhstarts, mh_ends = mhends)) # } else return(NULL) # }
/reference_genome_TRs/code/tr_util.R
no_license
SarahChen0401/MicroHomologyMediatedTandemDuplications
R
false
false
8,943
r
#### Utility for TR pattern and flanking MH identification #### This utility requires the genome utility clousure # sequence identity below this threshold will be denied consensus_thresh <- 0.75 consensus_lower <- 0.5 # consensus_thresh <- 0.3 # consensus_lower <- 0.5 # 4 bases bases <- c("A", "C", "G", "T") # this function returns the base freq matrix given a vector of # sequences with the same length (nchar) makeFrequencyMatrix <- function(seqs) { n <- nchar(seqs[1]) seqs <- matrix(unlist(strsplit(seqs, "")), n) m <- matrix(0, 4, n) for (j in 1:n) { b <- seqs[j, ] for (i in 1:4) { m[i, j] <- sum(b == bases[i]) } } rownames(m) <- bases m / ncol(seqs) } # this function returns a consensus sequence given a freq matrix makeConsensus <- function(fm) { use <- paste(apply(fm, 2, function(cl) bases[which(cl == max(cl))[1]]), collapse = "") out <- paste(apply(fm, 2, function(cl) { if (all(cl < 0.4)) b <- "*" else { b <- bases[which(cl > max(cl) - 0.1)] if (length(b) > 1) b <- paste0("[", paste(b, collapse = "/"), "]") else b <- bases[which(cl == max(cl))[1]] } b } ), collapse = "") attr(use, "output") <- out use } # this function returns the entropy of a given freq matrix seqEntropy <- function(fm) { baserate <- rowSums(fm) / ncol(fm) sum(ifelse(baserate == 0, 0, -baserate * log2(baserate))) } # this function returns the information content of a given freq matrix # infoContent <- function(fm) {} # this function calculate the match between a sequence and a freq matrix match <- function(seq, fm) { seq <- unlist(strsplit(seq, "")) s <- 0 for (i in 1:length(seq)) { s <- s + fm[seq[i], (i-1)%%ncol(fm)+1] } s } # this function find if a given subsequence have inner repetitive pattern findInnerRep <- function(seq) { # find the inner repeating pattern of a given seq n <- nchar(seq) inner <- 1 for (i in (2:n)[n %% (2:n) == 0]) { ss <- substring(seq, (1:i - 1) * n/i + 1, 1:i * n/i) fm <- makeFrequencyMatrix(ss) if (all(sapply(ss, match, fm = fm) > consensus_thresh * n / i)) inner <- i } inner } # this is the main function that identifies the TR given the unit info annotateTR <- function(gu, chr, posOriginal, k) { pos <- posOriginal seq <- gu$extract(chr, pos, pos+k-1) endpos <- pos + k ir <- 1 ir <- tryCatch( { findInnerRep(seq) }) if (ir > 1) seq <- substring(seq, (1:ir - 1) * nchar(seq)/ir + 1, 1:ir * nchar(seq)/ir) k <- nchar(seq[1]) lor <- 0 score <- numeric() repeat { e <- gu$extract(chr, pos - (lor+1) * k, pos - lor * k - 1) if (e == -1) break else { s <- match(e, makeFrequencyMatrix(seq)) if (s < consensus_lower*k) break else { score[length(score)+1] <- s ; seq <- c(e, seq) ; lor <- lor+1 } } } lor <- which(score > consensus_thresh*k) if (length(lor)) lor <- max(lor) else lor <- 0 seq <- seq[(length(seq)-ir-lor+1):length(seq)] ror <- 0 score <- numeric() repeat { e <- gu$extract(chr, endpos + ror * k, endpos + (ror+1) * k - 1) if (e == -1) break else { s <- match(e, makeFrequencyMatrix(seq)) if (s < consensus_lower*k) break else { score[length(score)+1] <- s ; seq <- c(seq, e) ; ror <- ror+1 } } } ror <- which(score > consensus_thresh*k) if (length(ror)) ror <- max(ror) else ror <- 0 seq <- seq[1:(lor+ir+ror)] pos <- pos - lor * k rep <- length(seq) if (rep > 1) { repeat { e <- gu$extract(chr, pos - 1) if (e == -1) break else { shift <- paste0( c(e, substring(seq[1:(rep-1)], k, k)), substring(seq, 1, k-1) ) if (match(shift, makeFrequencyMatrix(shift)) >= match(seq, makeFrequencyMatrix(seq))) { pos <- pos-1 ; seq <- shift e <- gu$extract(chr, pos + k*rep, pos + k*(rep+1) - 1) if (e != -1 && match(e, makeFrequencyMatrix(seq)) >= consensus_thresh*k) { seq <- c(seq, e) ; rep <- rep+1 } } else break } } } fl <- 0 mh <- "" counter_to_avoid_loop = 0 repeat { counter_to_avoid_loop = counter_to_avoid_loop + 1 if(counter_to_avoid_loop>1000){ mh = 'XXXXXXXXXXXXXXXXXXXXXX' break } if (fl >= consensus_thresh*k && k-fl < 4) { e <- gu$extract(chr, pos + rep * k, pos + (rep+1) * k-1) if (e != -1) { seq[rep+1] <- gu$extract(chr, pos + rep * k, pos + (rep+1) * k-1) rep <- rep + 1 ; fl <- 0 ; mh <- "" } } else { e <- gu$extract(chr, pos + rep * k, pos + rep * k + fl) if (e == -1) break else { if (all(e == substring(seq, 1, fl+1))) { fl <- fl+1 ; mh <- e } else break } } } if (nchar(mh) < 2) mh <- "" mat <- makeFrequencyMatrix(seq) cons <- makeConsensus(mat) entropy <- seqEntropy(mat) list(chr = chr, posOriginal = posOriginal , pos = pos, rep = rep, k = k, seq = seq, cons = attr(cons, "output"), entropy = entropy, mh = mh) } # annotateIndelTR <- function(gu, chr, pos, seq, is_insert = F) { # endpos <- ifelse(is_insert, pos, pos + nchar(seq)) # ir <- findInnerRep(seq) # repeat unit count in the indel seq # if (ir > 1) seq <- substring(seq, (1:ir - 1) * nchar(seq)/ir + 1, 1:ir * nchar(seq)/ir) # k <- nchar(seq[1]) # lor <- 0 # repeat unit count on the left side of indel site # while ({ # e <- gu$extract(chr, pos - (lor+1) * k + 1, pos - lor * k) # if (e != -1) { # seq <- c(e, seq) # meanEntropy(makeFrequencyMatrix(seq)) < consensus_thresh # } else { # if (1 < pos - lor * k) { # seq <- c(gu$extract(chr, 1, pos - lor * k), seq) # } else seq <- c("", seq) # FALSE # } # }) lor <- lor + 1 # ror <- 0 # repeat unit count on the right side of indel site # while ({ # e <- gu$extract(chr, endpos + ror * k, endpos + (ror+1) * k - 1) # if (e != -1) { # seq <- c(seq, e) # meanEntropy(makeFrequencyMatrix(seq[-1])) < consensus_thresh # } else { # if (endpos + ror * k < gu$getLength(chr)) { # seq <- c(seq, gu$extract(chr, endpos + ror * k, gu$getLength(chr))) # } else seq <- c(seq, "") # FALSE # } # }) ror <- ror + 1 # mat <- makeFrequencyMatrix(seq[2:(length(seq)-1)]) # frequency matrix # con <- makeConsensus(mat) # consensus sequence # lf <- 0 # left flanking homology # # while ({ # # pb <- mat[substring(seq[1], k-lf, k-lf), k-lf] # # # pb > 0.4 && pb > max(mat[, k-lf]) - 0.1 # # pb == 1 # # }) lf <- lf + 1 # rf <- 0 # right flanking homology # while ( (rf < nchar(seq[length(seq)])) && # (mat[substring(seq[length(seq)], rf+1, rf+1), rf+1] == 1) ) rf <- rf + 1 # if (lf + rf >= 3 && lf + rf <= min(15, 0.75 * k) ) { # recognize as microhomology # if (lf > 0 && rf == 0) mh <- mat[ ,(k-lf+1):k] # else if (lf ==0 && rf > 0) mh <- mat[, 1:rf] # else mh <- mat[, c((k - lf + 1):k, 1:rf)] # mh <- makeConsensus(mh) # if (lf != 0) seq[1:(length(seq) - 1)] <- paste( # substring(seq[1:(length(seq) - 1)], 1, k-lf), # tolower(substring(seq[1:(length(seq) - 1)], k-lf+1, k)), sep = "" # ) # if (rf != 0) seq[2:length(seq)] <- paste( # tolower(substring(seq[2:length(seq)], 1, rf)), # substring(seq[2:length(seq)], rf+1, k), sep = "" # ) # } else mh <- "" # rnc <- if (is_insert) { c(lor + ror, lor + ir + ror) # } else { c(lor + ir + ror, lor + ror) } # repeat number # # reformat sequence # if (rnc[1] > 0) { # seq[(lor+2)] <- paste0(ifelse(is_insert, ">", "<"), seq[(lor+2)]) # seq[(lor+1+ir)] <- paste0(seq[(lor+1+ir)], ifelse(is_insert, "<", ">")) # seq <- paste0(chr, ":",pos - (lor+1) * k, " - ", paste(seq, collapse = " ")) # repstarts <- pos + c((-lor):(ir + ror - is_insert - 1)) * k # repends <- repstarts + k # mhstarts <- c(repstarts[1], repends) # mhends <- mhstarts + nchar(mh) # return(list(repeat_number = rnc, consensus = con, seq = seq, microhomology = mh, # repeat_starts = repstarts, repeat_ends = repends, # mh_starts = mhstarts, mh_ends = mhends)) # } else return(NULL) # }
Annotationbychemical_IDschild <- function(adduct_index=NA,dataA,queryadductlist=c("M+H"),adduct_table,max.mz.diff=10,outloc, otherdbs=FALSE,otherinfo=FALSE,keggCompMZ){ #load("~/Documents/Emory/JonesLab/Projects/xMSannotator/keggCompMZ.Rda") dataA<-as.data.frame(dataA) adduct_names<-as.character(adduct_table[,1]) adductlist<-adduct_table[,4] mult_charge<-adduct_table[,3] num_mol<-adduct_table[,2] names(adductlist)<-as.character(adduct_names) names(mult_charge)<-as.character(adduct_names) names(num_mol)<-as.character(adduct_names) alladducts<-adduct_names if(is.na(adduct_index)==FALSE){ queryadductlist=queryadductlist[adduct_index] } #load("~/Documents/Emory/JonesLab/Projects/xMSannotator/keggCompMZ.Rda") alladducts<-adduct_names #print(queryadductlist) #print(alladducts) if(queryadductlist[1]=="positive") { queryadductlist<-adduct_names[which(adduct_table[,5]=="positive")] }else{ if(queryadductlist[1]=="negative") { queryadductlist<-adduct_names[which(adduct_table[,5]=="negative")] }else{ if(queryadductlist[1]=="all"){ queryadductlist<-alladducts }else{ if(length(which(queryadductlist%in%alladducts==FALSE))>0){ errormsg<-paste("Adduct should be one of:",sep="") for(i in alladducts){errormsg<-paste(errormsg, i,sep=" ; ")} stop(errormsg, "\n\n") } } } } adduct_table<-as.data.frame(adduct_table) adduct_table<-adduct_table[which(adduct_table$Adduct%in%queryadductlist),] dir.create(outloc) setwd(outloc) #keggres<-KEGG.annotation(dataA=mz_search_list,queryadductlist = c("positive"),xMSannotator.outloc) #cur_fname<-"/Users/karanuppal/Documents/Emory/JonesLab/Projects/MaHPIC/Exp2/c18/apLCMS_with_xMSanalyzer_merged_data/apLCMS_feature_list_at_p1_U_p2cor0.7_CV100.txt" #dataA<-read.table(cur_fname,sep="\t",header=TRUE) mz_search_list_1<-as.data.frame(keggCompMZ[which(keggCompMZ$Adduct%in%adduct_table$Adduct),c(1,7)]) mz_search_list_1<-apply(mz_search_list_1,2,as.numeric) gcur<-getVenn(dataA=dataA,name_a="Experimental",name_b="DB",dataB=mz_search_list_1,mz.thresh=max.mz.diff,time.thresh=NA, xMSanalyzer.outloc=outloc,alignment.tool=NA) #print("here 1") #print(length(gcur$common)) #print("here 2") if(length(gcur$common)>0){ mcur<-merge(keggCompMZ[which(keggCompMZ$Adduct%in%adduct_table$Adduct),],gcur$common,by.x="mz",by.y="mz.data.B") #print(mcur[1,1:4]) #print(dataA[1,]) mcur_2<-merge(mcur,dataA,by.x="mz.data.A",by.y="mz") mcur_3<-mcur_2[order(mcur_2$Name),] mcur_3<-mcur_3[,-c(9,10)] cnames<-colnames(mcur_3) cnames[1]<-"mz" cnames[2]<-"theoretical.mz" colnames(mcur_3)<-as.character(cnames) mcur_4<-as.data.frame(mcur_3) rm(keggCompMZ) rm(dataA) rm(mcur_2) rm(mcur_3) rm(mz_search_list_1) if(dim(mcur)[1]>1){ h1<-table(mcur_4$mz) #Adduct if(length(h1)>0){ #u1<-c(u1,which(h1<=1)) u1<-which(h1<=1) } match_status<-rep("Multiple",dim(h1)[1]) uniq_kegg_matches<-names(u1) match_status[u1]<-"Unique" match_status_mat<-cbind(rownames(h1),match_status) colnames(match_status_mat)<-c("mz","MatchCategory") match_status_mat<-as.data.frame(match_status_mat) mcur_5<-merge(match_status_mat,mcur_4,by="mz") print(dim(mcur_5)) rm(mcur_4) #h1<-table(mcur_5$chemical_ID,mcur_5$mz) print("here 2") #s2<-apply(h1,2,sum) mcur_5<-as.data.frame(mcur_5) #mcur_5$mz<-as.numeric(mcur_5$mz) mcur_5<-mcur_5[order(mcur_5$mz),] }else{ MatchCategory<-"Unique" cnames1<-colnames(mcur_4) cnames1<-c(cnames1[1],"MatchCategory",cnames[-c(1)]) mcur_5<-cbind(mcur_4[1,1],MatchCategory,mcur_4[,-c(1)]) mcur_5<-as.data.frame(mcur_5) colnames(mcur_5)<-as.character(cnames1) #mcur_5$mz<-as.numeric(mcur_5$mz) mcur_5<-mcur_5[order(mcur_5$mz),] } if(otherinfo==TRUE){ info_mat<-sapply(1:dim(mcur_5)[1],function(j){ b1<-keggGet(paste("cpd:",mcur_5[j,1],sep="")) brite_inf<-paste(b1[[1]]$BRITE,collapse=";") path_inf<-paste(b1[[1]]$PATHWAYS,collapse=";") otherdb_inf<-paste(b1[[1]]$DBLINKS,collapse=";") r1<-c(as.character(mcur_5[j,1]),as.character(brite_inf),as.character(path_inf),as.character(otherdb_inf)) return(r1) }) info_mat_1<-as.data.frame(t(info_mat)) colnames(info_mat_1)<-c("chemical_ID","BriteCategory","Pathways","ExternalLinks") mcur_6<-merge(info_mat_1,mcur_5,by="chemical_ID") mcur_7<-unique(mcur_6) rm(mcur_6) if(otherdbs==TRUE){ info_mat_2<-sapply(1:dim(mcur_7)[1],function(j){ b1<-keggLink(paste("cpd:",mcur_7[j,1],"+-e",sep="")) hmdbID<-"-" lipidmapsID<-"-" link_text<-b1[,2] t2<-gregexpr(pattern="hmdb:",perl=FALSE,text=link_text) if(length(t2)>1){ g_ind<-which(t2==1) if(length(g_ind)>0){ if(length(g_ind)>1){ for(g in g_ind){ t3=t2[[g]] hmdbID<-c(hmdbID,gsub(b1[g,2],pattern="hmdb:",replacement="")) } if(length(g_ind)>1){hmdbID<-paste(hmdbID,collapse=";")} }else{ hmdbID<-gsub(b1[g_ind,2],pattern="hmdb:",replacement="") } } } t2<-gregexpr(pattern="lipidmaps:",perl=FALSE,text=link_text) if(length(t2)>1){ g_ind<-which(t2==1) if(length(g_ind)>0){ if(length(g_ind)>1){ for(g in g_ind){ t3=t2[[g]] lipidmapsID<-c(lipidmapsID,gsub(b1[g,2],pattern="lipidmaps:",replacement="")) } lipidmapsID<-paste(lipidmapsID,collapse=";") }else{lipidmapsID<-gsub(b1[g_ind,2],pattern="lipidmaps:",replacement="")} } } return(list(keggid=as.character(mcur_7[j,1]),hmdb=hmdbID,lipidmaps=lipidmapsID)) c1<-c(as.character(mcur_7[j,1]),hmdbID,lipidmapsID) c1<-as.data.frame(c1) return(c1) }) info_mat_3<-{} #for(i in 1:dim(info_mat_2)[1]){ cdata<-rbind(info_mat_2[1,],info_mat_2[2,]) cdata<-rbind(cdata,info_mat_2[3,]) cdata<-as.data.frame(cdata) info_mat_3<-rbind(info_mat_3,cdata) #} #info_mat_3<-as.data.frame(t(info_mat_2)) info_mat_3<-t(info_mat_3) colnames(info_mat_3)<-c("chemical_ID","HMDBID","LIPIDMAPS") mcur_7<-as.data.frame(mcur_7) mcur_8<-cbind(info_mat_3,mcur_7) #,by="chemical_ID") mcur_8<-unique(mcur_8) rownames(mcur_8)<-NULL return(mcur_8) }else{ mcur_7<-as.data.frame(mcur_7) rownames(mcur_7)<-NULL return(mcur_7) } }else{ mcur_5<-unique(mcur_5) return(mcur_5) } }else{return("no match found.")} #}else{return("no match found.")} }
/R/Annotationbychemical_IDschild.R
no_license
jaspershen/MSannotator
R
false
false
6,407
r
Annotationbychemical_IDschild <- function(adduct_index=NA,dataA,queryadductlist=c("M+H"),adduct_table,max.mz.diff=10,outloc, otherdbs=FALSE,otherinfo=FALSE,keggCompMZ){ #load("~/Documents/Emory/JonesLab/Projects/xMSannotator/keggCompMZ.Rda") dataA<-as.data.frame(dataA) adduct_names<-as.character(adduct_table[,1]) adductlist<-adduct_table[,4] mult_charge<-adduct_table[,3] num_mol<-adduct_table[,2] names(adductlist)<-as.character(adduct_names) names(mult_charge)<-as.character(adduct_names) names(num_mol)<-as.character(adduct_names) alladducts<-adduct_names if(is.na(adduct_index)==FALSE){ queryadductlist=queryadductlist[adduct_index] } #load("~/Documents/Emory/JonesLab/Projects/xMSannotator/keggCompMZ.Rda") alladducts<-adduct_names #print(queryadductlist) #print(alladducts) if(queryadductlist[1]=="positive") { queryadductlist<-adduct_names[which(adduct_table[,5]=="positive")] }else{ if(queryadductlist[1]=="negative") { queryadductlist<-adduct_names[which(adduct_table[,5]=="negative")] }else{ if(queryadductlist[1]=="all"){ queryadductlist<-alladducts }else{ if(length(which(queryadductlist%in%alladducts==FALSE))>0){ errormsg<-paste("Adduct should be one of:",sep="") for(i in alladducts){errormsg<-paste(errormsg, i,sep=" ; ")} stop(errormsg, "\n\n") } } } } adduct_table<-as.data.frame(adduct_table) adduct_table<-adduct_table[which(adduct_table$Adduct%in%queryadductlist),] dir.create(outloc) setwd(outloc) #keggres<-KEGG.annotation(dataA=mz_search_list,queryadductlist = c("positive"),xMSannotator.outloc) #cur_fname<-"/Users/karanuppal/Documents/Emory/JonesLab/Projects/MaHPIC/Exp2/c18/apLCMS_with_xMSanalyzer_merged_data/apLCMS_feature_list_at_p1_U_p2cor0.7_CV100.txt" #dataA<-read.table(cur_fname,sep="\t",header=TRUE) mz_search_list_1<-as.data.frame(keggCompMZ[which(keggCompMZ$Adduct%in%adduct_table$Adduct),c(1,7)]) mz_search_list_1<-apply(mz_search_list_1,2,as.numeric) gcur<-getVenn(dataA=dataA,name_a="Experimental",name_b="DB",dataB=mz_search_list_1,mz.thresh=max.mz.diff,time.thresh=NA, xMSanalyzer.outloc=outloc,alignment.tool=NA) #print("here 1") #print(length(gcur$common)) #print("here 2") if(length(gcur$common)>0){ mcur<-merge(keggCompMZ[which(keggCompMZ$Adduct%in%adduct_table$Adduct),],gcur$common,by.x="mz",by.y="mz.data.B") #print(mcur[1,1:4]) #print(dataA[1,]) mcur_2<-merge(mcur,dataA,by.x="mz.data.A",by.y="mz") mcur_3<-mcur_2[order(mcur_2$Name),] mcur_3<-mcur_3[,-c(9,10)] cnames<-colnames(mcur_3) cnames[1]<-"mz" cnames[2]<-"theoretical.mz" colnames(mcur_3)<-as.character(cnames) mcur_4<-as.data.frame(mcur_3) rm(keggCompMZ) rm(dataA) rm(mcur_2) rm(mcur_3) rm(mz_search_list_1) if(dim(mcur)[1]>1){ h1<-table(mcur_4$mz) #Adduct if(length(h1)>0){ #u1<-c(u1,which(h1<=1)) u1<-which(h1<=1) } match_status<-rep("Multiple",dim(h1)[1]) uniq_kegg_matches<-names(u1) match_status[u1]<-"Unique" match_status_mat<-cbind(rownames(h1),match_status) colnames(match_status_mat)<-c("mz","MatchCategory") match_status_mat<-as.data.frame(match_status_mat) mcur_5<-merge(match_status_mat,mcur_4,by="mz") print(dim(mcur_5)) rm(mcur_4) #h1<-table(mcur_5$chemical_ID,mcur_5$mz) print("here 2") #s2<-apply(h1,2,sum) mcur_5<-as.data.frame(mcur_5) #mcur_5$mz<-as.numeric(mcur_5$mz) mcur_5<-mcur_5[order(mcur_5$mz),] }else{ MatchCategory<-"Unique" cnames1<-colnames(mcur_4) cnames1<-c(cnames1[1],"MatchCategory",cnames[-c(1)]) mcur_5<-cbind(mcur_4[1,1],MatchCategory,mcur_4[,-c(1)]) mcur_5<-as.data.frame(mcur_5) colnames(mcur_5)<-as.character(cnames1) #mcur_5$mz<-as.numeric(mcur_5$mz) mcur_5<-mcur_5[order(mcur_5$mz),] } if(otherinfo==TRUE){ info_mat<-sapply(1:dim(mcur_5)[1],function(j){ b1<-keggGet(paste("cpd:",mcur_5[j,1],sep="")) brite_inf<-paste(b1[[1]]$BRITE,collapse=";") path_inf<-paste(b1[[1]]$PATHWAYS,collapse=";") otherdb_inf<-paste(b1[[1]]$DBLINKS,collapse=";") r1<-c(as.character(mcur_5[j,1]),as.character(brite_inf),as.character(path_inf),as.character(otherdb_inf)) return(r1) }) info_mat_1<-as.data.frame(t(info_mat)) colnames(info_mat_1)<-c("chemical_ID","BriteCategory","Pathways","ExternalLinks") mcur_6<-merge(info_mat_1,mcur_5,by="chemical_ID") mcur_7<-unique(mcur_6) rm(mcur_6) if(otherdbs==TRUE){ info_mat_2<-sapply(1:dim(mcur_7)[1],function(j){ b1<-keggLink(paste("cpd:",mcur_7[j,1],"+-e",sep="")) hmdbID<-"-" lipidmapsID<-"-" link_text<-b1[,2] t2<-gregexpr(pattern="hmdb:",perl=FALSE,text=link_text) if(length(t2)>1){ g_ind<-which(t2==1) if(length(g_ind)>0){ if(length(g_ind)>1){ for(g in g_ind){ t3=t2[[g]] hmdbID<-c(hmdbID,gsub(b1[g,2],pattern="hmdb:",replacement="")) } if(length(g_ind)>1){hmdbID<-paste(hmdbID,collapse=";")} }else{ hmdbID<-gsub(b1[g_ind,2],pattern="hmdb:",replacement="") } } } t2<-gregexpr(pattern="lipidmaps:",perl=FALSE,text=link_text) if(length(t2)>1){ g_ind<-which(t2==1) if(length(g_ind)>0){ if(length(g_ind)>1){ for(g in g_ind){ t3=t2[[g]] lipidmapsID<-c(lipidmapsID,gsub(b1[g,2],pattern="lipidmaps:",replacement="")) } lipidmapsID<-paste(lipidmapsID,collapse=";") }else{lipidmapsID<-gsub(b1[g_ind,2],pattern="lipidmaps:",replacement="")} } } return(list(keggid=as.character(mcur_7[j,1]),hmdb=hmdbID,lipidmaps=lipidmapsID)) c1<-c(as.character(mcur_7[j,1]),hmdbID,lipidmapsID) c1<-as.data.frame(c1) return(c1) }) info_mat_3<-{} #for(i in 1:dim(info_mat_2)[1]){ cdata<-rbind(info_mat_2[1,],info_mat_2[2,]) cdata<-rbind(cdata,info_mat_2[3,]) cdata<-as.data.frame(cdata) info_mat_3<-rbind(info_mat_3,cdata) #} #info_mat_3<-as.data.frame(t(info_mat_2)) info_mat_3<-t(info_mat_3) colnames(info_mat_3)<-c("chemical_ID","HMDBID","LIPIDMAPS") mcur_7<-as.data.frame(mcur_7) mcur_8<-cbind(info_mat_3,mcur_7) #,by="chemical_ID") mcur_8<-unique(mcur_8) rownames(mcur_8)<-NULL return(mcur_8) }else{ mcur_7<-as.data.frame(mcur_7) rownames(mcur_7)<-NULL return(mcur_7) } }else{ mcur_5<-unique(mcur_5) return(mcur_5) } }else{return("no match found.")} #}else{return("no match found.")} }
library(RInno) library(dplyr) library(magrittr) depends = c("googledrive", 'magrittr', 'dplyr', 'diceSyntax', 'purrr', 'ogbox', 'glue', 'shiny', 'shinythemes', 'shinyjs', 'shinyWidgets', 'DT', 'shinyBS') appVersion = '1.0.0' unlink('sheet',recursive = TRUE) unlink('sheetCI',recursive = TRUE,force = TRUE) system('svn checkout https://github.com/oganm/import5eChar/trunk/inst/app') unlink('app/.svn', recursive = TRUE, force = TRUE) file.rename('app','sheet') dir.create('sheetCI') # git2r::clone('https://github.com/oganm/import5eChar.git',local_path = 'sheetCI') ####################### create_app(app_name = "5eInteractiveSheet", app_dir = "sheet",include_R = TRUE) file.copy('dice_icon.ico','sheet/default.ico',overwrite = TRUE) file.copy('dice_icon.ico','sheet/setup.ico',overwrite = TRUE) file.copy('infoafter.txt','sheet/infoafter.txt',overwrite = TRUE) file.copy('infobefore.txt','sheet/infobefore.txt',overwrite = TRUE) appR = readLines('sheet/global.R') appR = c('options(ImThePortableClient = TRUE)',appR) writeLines(appR,'sheet/global.R') iss = readLines('sheet/5eInteractiveSheet.iss') iss[2] %<>% gsub(pattern = '0.0.0',replacement = appVersion,.) writeLines(iss,'sheet/5eInteractiveSheet.iss') compile_iss() ####################### create_app( app_name = "import5eChar", app_repo_url = "https://github.com/oganm/import5eChar", pkgs = depends, app_dir = 'sheetCI',include_R = TRUE ) file.copy('dice_icon.ico','sheetCI/default.ico',overwrite = TRUE) file.copy('dice_icon.ico','sheetCI/setup.ico',overwrite = TRUE) file.copy('infoafter.txt','sheetCI/infoafter.txt',overwrite = TRUE) file.copy('infobefore.txt','sheetCI/infobefore.txt',overwrite = TRUE) appR = readLines('sheetCI/utils/app.R') appR = c('options(ImThePortableClient = TRUE)',appR) writeLines(appR,'sheetCI/utils/app.R') iss = readLines('sheetCI/import5eChar.iss') iss[2] %<>% gsub(pattern = '0.0.0',replacement = appVersion,.) writeLines(iss,'sheetCI/import5eChar.iss') compile_iss()
/appBuilder.R
no_license
chsims1/5eInteractiveSheet
R
false
false
2,147
r
library(RInno) library(dplyr) library(magrittr) depends = c("googledrive", 'magrittr', 'dplyr', 'diceSyntax', 'purrr', 'ogbox', 'glue', 'shiny', 'shinythemes', 'shinyjs', 'shinyWidgets', 'DT', 'shinyBS') appVersion = '1.0.0' unlink('sheet',recursive = TRUE) unlink('sheetCI',recursive = TRUE,force = TRUE) system('svn checkout https://github.com/oganm/import5eChar/trunk/inst/app') unlink('app/.svn', recursive = TRUE, force = TRUE) file.rename('app','sheet') dir.create('sheetCI') # git2r::clone('https://github.com/oganm/import5eChar.git',local_path = 'sheetCI') ####################### create_app(app_name = "5eInteractiveSheet", app_dir = "sheet",include_R = TRUE) file.copy('dice_icon.ico','sheet/default.ico',overwrite = TRUE) file.copy('dice_icon.ico','sheet/setup.ico',overwrite = TRUE) file.copy('infoafter.txt','sheet/infoafter.txt',overwrite = TRUE) file.copy('infobefore.txt','sheet/infobefore.txt',overwrite = TRUE) appR = readLines('sheet/global.R') appR = c('options(ImThePortableClient = TRUE)',appR) writeLines(appR,'sheet/global.R') iss = readLines('sheet/5eInteractiveSheet.iss') iss[2] %<>% gsub(pattern = '0.0.0',replacement = appVersion,.) writeLines(iss,'sheet/5eInteractiveSheet.iss') compile_iss() ####################### create_app( app_name = "import5eChar", app_repo_url = "https://github.com/oganm/import5eChar", pkgs = depends, app_dir = 'sheetCI',include_R = TRUE ) file.copy('dice_icon.ico','sheetCI/default.ico',overwrite = TRUE) file.copy('dice_icon.ico','sheetCI/setup.ico',overwrite = TRUE) file.copy('infoafter.txt','sheetCI/infoafter.txt',overwrite = TRUE) file.copy('infobefore.txt','sheetCI/infobefore.txt',overwrite = TRUE) appR = readLines('sheetCI/utils/app.R') appR = c('options(ImThePortableClient = TRUE)',appR) writeLines(appR,'sheetCI/utils/app.R') iss = readLines('sheetCI/import5eChar.iss') iss[2] %<>% gsub(pattern = '0.0.0',replacement = appVersion,.) writeLines(iss,'sheetCI/import5eChar.iss') compile_iss()
#example using mapply for noise function noise <- function(n,mean_s,std_s){ rnorm(n,mean_s,std_s) } different_noises_fixed_std <- function(listn,listmean,std_s){ mapply(noise,listn,listmean,std_s) }
/Rprogramming.dir/Week3.dir/lesson_3_mapply.r
no_license
hhorus/dataAnalysisCoursera
R
false
false
204
r
#example using mapply for noise function noise <- function(n,mean_s,std_s){ rnorm(n,mean_s,std_s) } different_noises_fixed_std <- function(listn,listmean,std_s){ mapply(noise,listn,listmean,std_s) }
source('populateNewDirectory2.R') source('makeNewFolder.R') source('makeLink.R') source('crawlSynapseObject.R') source('makeHeadFolder.R') #crawl folderA in projectD synObj <- crawlSynapseObject('syn3157162') synObj <- makeHeadFolder(synObj,'syn3157162') populateNewDirectory2('syn3157160',synObj,topId = 'syn3157160')
/RFunctions/testMigration.R
no_license
alma2moon434/ampAdScripts
R
false
false
320
r
source('populateNewDirectory2.R') source('makeNewFolder.R') source('makeLink.R') source('crawlSynapseObject.R') source('makeHeadFolder.R') #crawl folderA in projectD synObj <- crawlSynapseObject('syn3157162') synObj <- makeHeadFolder(synObj,'syn3157162') populateNewDirectory2('syn3157160',synObj,topId = 'syn3157160')
rm(list = ls()) library(leaflet) library(leaflet.extras) library(leaflet.minicharts) library(sf) library(dplyr) library(tidyr) setwd(setwd('C:/Users/REACH/Dropbox (SSD REACH)/REACH South Sudan upscale/34_WFP/11_WFP_IACWG')) disputed <- st_read('8. Dashboard/r_dashboard/app_plot/Disputed/SSD_Undetermined.shp') disputed <- st_transform(disputed,"+init=epsg:4326" ) country <- st_read('8. Dashboard/r_dashboard/app_plot/Country/SSD_Country.shp') country <- st_transform(country,"+init=epsg:4326" ) states <- st_read("8. Dashboard/r_dashboard/app_plot/States/SSD_States.shp") states <- st_transform(states,"+init=epsg:4326" ) counties <- st_read("8. Dashboard/r_dashboard/app_plot/Counties/SSD_counties.shp") counties <- st_transform(counties,"+init=epsg:4326" ) settlements <- st_read("Settlements/SSD_Settlements.shp") settlements <- st_transform(settlements, "+init=epsg:4326") rivers <- st_read("8. Dashboard/r_dashboard/app_plot/Rivers/SSD_Rivers.shp") rivers <- st_transform(rivers, "+init=epsg:4326") rivers_primary <- rivers %>% filter(OBJECTID == c(5, 6)) #st_write(rivers_primary, "rivers_primary.shp") lakes <- st_read("8. Dashboard/r_dashboard/app_plot/Lakes/SSD_Lakes.shp") lakes <- st_transform(lakes, "+init=epsg:4326") roads <- st_read("8. Dashboard/r_dashboard/app_plot/Roads/SSD_roads.shp") roads <- st_transform(roads, "+init=epsg:4326") roads_primary <- roads %>% filter(CLASS == "Primary") #st_write(roads_primary, "roads_primary.shp") leaflet() %>% #addTiles() %>% addProviderTiles(providers$OpenStreetMap) %>% addPolygons(data = lakes, group = "Lakes", fill = TRUE, stroke = FALSE, fillColor = "#D5EAF1", fillOpacity = 0.75) %>% addPolygons(data = counties, group = "Counties", fill = FALSE, stroke = TRUE, color = "#BDBDBD", weight = 0.6, opacity = 0.5) %>% addPolygons(data = states, group = "States", fill = FALSE, stroke = TRUE, color = "#58585A", weight = 1, opacity = 0.7) %>% #addPolygons(data = disputed, group = "Disputed Territory", fill = FALSE, stroke = TRUE, color = "#58585A", weight = 1, opacity = 0.7) %>% addPolylines(data = rivers_primary, group = "Rivers", stroke = TRUE, color = "#94CCDC", weight = 1.3, opacity = 0.7) %>% addPolylines(data = roads_primary, group = "Roads", stroke = TRUE, color = "#F69E61", weight = 1.5, opacity = 0.4) %>% # addCircleMarkers(data = settlements, group = "Settlements", radius = 3, stroke = FALSE, fillOpacity = 0.5) %>% #addLegend("bottomright", colors = c("#03F", "#03F"), labels = c("States", "Counties")) %>% addLayersControl( overlayGroups = c("States", "Counties", "Lakes", "Rivers", "Roads"), options = layersControlOptions(collapsed = FALSE)) %>% setMapWidgetStyle(style = list(background = "transparent"))
/app_plot/4_Practice/script.R
no_license
JonathanBuckleyREACHSSD/SSD-JMMI-Draft
R
false
false
2,786
r
rm(list = ls()) library(leaflet) library(leaflet.extras) library(leaflet.minicharts) library(sf) library(dplyr) library(tidyr) setwd(setwd('C:/Users/REACH/Dropbox (SSD REACH)/REACH South Sudan upscale/34_WFP/11_WFP_IACWG')) disputed <- st_read('8. Dashboard/r_dashboard/app_plot/Disputed/SSD_Undetermined.shp') disputed <- st_transform(disputed,"+init=epsg:4326" ) country <- st_read('8. Dashboard/r_dashboard/app_plot/Country/SSD_Country.shp') country <- st_transform(country,"+init=epsg:4326" ) states <- st_read("8. Dashboard/r_dashboard/app_plot/States/SSD_States.shp") states <- st_transform(states,"+init=epsg:4326" ) counties <- st_read("8. Dashboard/r_dashboard/app_plot/Counties/SSD_counties.shp") counties <- st_transform(counties,"+init=epsg:4326" ) settlements <- st_read("Settlements/SSD_Settlements.shp") settlements <- st_transform(settlements, "+init=epsg:4326") rivers <- st_read("8. Dashboard/r_dashboard/app_plot/Rivers/SSD_Rivers.shp") rivers <- st_transform(rivers, "+init=epsg:4326") rivers_primary <- rivers %>% filter(OBJECTID == c(5, 6)) #st_write(rivers_primary, "rivers_primary.shp") lakes <- st_read("8. Dashboard/r_dashboard/app_plot/Lakes/SSD_Lakes.shp") lakes <- st_transform(lakes, "+init=epsg:4326") roads <- st_read("8. Dashboard/r_dashboard/app_plot/Roads/SSD_roads.shp") roads <- st_transform(roads, "+init=epsg:4326") roads_primary <- roads %>% filter(CLASS == "Primary") #st_write(roads_primary, "roads_primary.shp") leaflet() %>% #addTiles() %>% addProviderTiles(providers$OpenStreetMap) %>% addPolygons(data = lakes, group = "Lakes", fill = TRUE, stroke = FALSE, fillColor = "#D5EAF1", fillOpacity = 0.75) %>% addPolygons(data = counties, group = "Counties", fill = FALSE, stroke = TRUE, color = "#BDBDBD", weight = 0.6, opacity = 0.5) %>% addPolygons(data = states, group = "States", fill = FALSE, stroke = TRUE, color = "#58585A", weight = 1, opacity = 0.7) %>% #addPolygons(data = disputed, group = "Disputed Territory", fill = FALSE, stroke = TRUE, color = "#58585A", weight = 1, opacity = 0.7) %>% addPolylines(data = rivers_primary, group = "Rivers", stroke = TRUE, color = "#94CCDC", weight = 1.3, opacity = 0.7) %>% addPolylines(data = roads_primary, group = "Roads", stroke = TRUE, color = "#F69E61", weight = 1.5, opacity = 0.4) %>% # addCircleMarkers(data = settlements, group = "Settlements", radius = 3, stroke = FALSE, fillOpacity = 0.5) %>% #addLegend("bottomright", colors = c("#03F", "#03F"), labels = c("States", "Counties")) %>% addLayersControl( overlayGroups = c("States", "Counties", "Lakes", "Rivers", "Roads"), options = layersControlOptions(collapsed = FALSE)) %>% setMapWidgetStyle(style = list(background = "transparent"))
H<-matrix(readBin("histograms.bin", "double", 640000), 40000, 16) # add small constant to empty bins eps<-0.01 index<-which(H==0,arr.ind=TRUE) for (i in 1:dim(index)[1]){ H[index[i,1],index[i,2]]<-eps } # parameters k_1<-3 k_2<-4 k_3<-5 # EM algorithm MultinomialEM<-function(H,k,t){ n<-dim(H)[1] d<-dim(H)[2] H<-H/rowSums(H) # normalize each histogram to avoid overflow/underflow theta<-t(H[sample(1:n,k),]) count<-1 repeat { if(count==1){ a_old<-matrix(0,n,k) } else{ a_old<-a } phi<-exp(H%*%(log(theta))) a<-phi/colSums(phi) b<-t(H)%*%a theta<-b/colSums(b) c<-norm(a-a_old,"o") count<-count+1 if(c<t) break } m<-max.col(a) return(m) } # plot to check which parameter produce the best cluster result tune_par<-function(H,k){ param<-seq(0.1,0.9,length=9) for (i in 1:length(param)){ m<-MultinomialEM(H,k,param[i]) m<-matrix(m,nrow=200,ncol=200) n<-matrix(NA,nrow=200,ncol=200) for (j in 0:(200-1)){ n[,j+1]<-m[,200-j] } pdf(paste(k,'_cluster_',param[i],'.pdf',sep='')) image(n,axes=FALSE,col=grey(0:k/k)) dev.off() } }
/em.R
no_license
Shemster/machine-learning
R
false
false
1,085
r
H<-matrix(readBin("histograms.bin", "double", 640000), 40000, 16) # add small constant to empty bins eps<-0.01 index<-which(H==0,arr.ind=TRUE) for (i in 1:dim(index)[1]){ H[index[i,1],index[i,2]]<-eps } # parameters k_1<-3 k_2<-4 k_3<-5 # EM algorithm MultinomialEM<-function(H,k,t){ n<-dim(H)[1] d<-dim(H)[2] H<-H/rowSums(H) # normalize each histogram to avoid overflow/underflow theta<-t(H[sample(1:n,k),]) count<-1 repeat { if(count==1){ a_old<-matrix(0,n,k) } else{ a_old<-a } phi<-exp(H%*%(log(theta))) a<-phi/colSums(phi) b<-t(H)%*%a theta<-b/colSums(b) c<-norm(a-a_old,"o") count<-count+1 if(c<t) break } m<-max.col(a) return(m) } # plot to check which parameter produce the best cluster result tune_par<-function(H,k){ param<-seq(0.1,0.9,length=9) for (i in 1:length(param)){ m<-MultinomialEM(H,k,param[i]) m<-matrix(m,nrow=200,ncol=200) n<-matrix(NA,nrow=200,ncol=200) for (j in 0:(200-1)){ n[,j+1]<-m[,200-j] } pdf(paste(k,'_cluster_',param[i],'.pdf',sep='')) image(n,axes=FALSE,col=grey(0:k/k)) dev.off() } }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/configure.R \name{configure_get} \alias{configure_get} \title{Get a config setting} \usage{ configure_get(varname) }
/man/configure_get.Rd
permissive
mmuurr/awscli
R
false
true
195
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/configure.R \name{configure_get} \alias{configure_get} \title{Get a config setting} \usage{ configure_get(varname) }
# Define ko_pep ko_pep <- ko / pep # Make a time series plot of ko_pep plot.zoo(ko_pep) # Add as a reference, a horizontal line at 1 abline(h = 1) # Define the vector values values <- c(4000, 4000, 2000) # Define the vector weights weights <- values / sum(values) # Print the resulting weights print(weights) # Define marketcaps marketcaps <- c(5, 8, 9, 20, 25, 100, 100, 500, 700, 2000) # Compute the weights weights <- marketcaps / sum(marketcaps) # Inspect summary statistics summary(weights) # Create a barplot of weights barplot(weights) # Vector of initial value of the assets in_values <- c(1000, 5000, 2000) # Vector of final values of the assets fin_values <- c(1100, 4500, 3000) # Weights as the proportion of total value invested in each assets weights <- in_values / sum(in_values) # Vector of simple returns of the assets returns <- (fin_values - in_values) / in_values # Compute portfolio return using the portfolio return formula preturns <- sum(weights * returns) # Suppose that you have an investment horizon of two periods. In the first period you make a 10% return. But in the second period you take a loss of 5%. ((1 + .10) * (1 + -.05) - 1) * 1000
/portfolio.analysis_01/01 - building.blocks/01 - intro.R
no_license
aliawaischeema/DataCamp
R
false
false
1,188
r
# Define ko_pep ko_pep <- ko / pep # Make a time series plot of ko_pep plot.zoo(ko_pep) # Add as a reference, a horizontal line at 1 abline(h = 1) # Define the vector values values <- c(4000, 4000, 2000) # Define the vector weights weights <- values / sum(values) # Print the resulting weights print(weights) # Define marketcaps marketcaps <- c(5, 8, 9, 20, 25, 100, 100, 500, 700, 2000) # Compute the weights weights <- marketcaps / sum(marketcaps) # Inspect summary statistics summary(weights) # Create a barplot of weights barplot(weights) # Vector of initial value of the assets in_values <- c(1000, 5000, 2000) # Vector of final values of the assets fin_values <- c(1100, 4500, 3000) # Weights as the proportion of total value invested in each assets weights <- in_values / sum(in_values) # Vector of simple returns of the assets returns <- (fin_values - in_values) / in_values # Compute portfolio return using the portfolio return formula preturns <- sum(weights * returns) # Suppose that you have an investment horizon of two periods. In the first period you make a 10% return. But in the second period you take a loss of 5%. ((1 + .10) * (1 + -.05) - 1) * 1000
############################################################################## # # # PAYOFF MATRIX FOR THE QUANTUM BATTLE OF THE SEXES GAME # # # ############################################################################## #' @title #' Quantum Battle of the Sexes game: Payoff Matrix #' #' @description #' This function generates the payoff matrix for the Quantum Battle of Sexes game for all the four combinations of \code{p} and \code{q}. \code{moves} is a list of two possible strategies for each of the players and \code{alpha, beta, gamma} are the payoffs for the players corresponding to the choices available to them with the chain of inequalities, \code{alpha>beta>gamma}. #' #' @param moves a list of matrices #' @param alpha a number #' @param beta a number #' @param gamma a number #' #' @usage #' PayoffMatrix_QBOS(moves, alpha, beta, gamma) #' #' @return The payoff matrices for the two players as two elements of a list. #' #' @references #' \url{https://arxiv.org/pdf/quant-ph/0506219.pdf}\cr #' \url{https://arxiv.org/pdf/quant-ph/0208069.pdf}\cr #' \url{https://arxiv.org/abs/quant-ph/0110096}\cr #' #' #' @examples #' init() #' moves <- list(Q$I2, sigmaX(Q$I2)) #' PayoffMatrix_QBOS(moves, 5, 3, 1) #' #' @export #' PayoffMatrix_QBOS <- function(moves, alpha, beta, gamma){ Alice <- matrix(0, 2, 2) Bob <- matrix(0, 2, 2) for(i in 1:2){ for (j in 1:2){ X <- QBOS(i-1, j-1, moves, alpha, beta, gamma) Alice[i, j] <- X[[1]] Bob[i, j] <- X[[2]] } } return(list(Alice, Bob)) }
/R/PayoffMatrix_QBOS.R
permissive
indrag49/QGameTheory
R
false
false
1,701
r
############################################################################## # # # PAYOFF MATRIX FOR THE QUANTUM BATTLE OF THE SEXES GAME # # # ############################################################################## #' @title #' Quantum Battle of the Sexes game: Payoff Matrix #' #' @description #' This function generates the payoff matrix for the Quantum Battle of Sexes game for all the four combinations of \code{p} and \code{q}. \code{moves} is a list of two possible strategies for each of the players and \code{alpha, beta, gamma} are the payoffs for the players corresponding to the choices available to them with the chain of inequalities, \code{alpha>beta>gamma}. #' #' @param moves a list of matrices #' @param alpha a number #' @param beta a number #' @param gamma a number #' #' @usage #' PayoffMatrix_QBOS(moves, alpha, beta, gamma) #' #' @return The payoff matrices for the two players as two elements of a list. #' #' @references #' \url{https://arxiv.org/pdf/quant-ph/0506219.pdf}\cr #' \url{https://arxiv.org/pdf/quant-ph/0208069.pdf}\cr #' \url{https://arxiv.org/abs/quant-ph/0110096}\cr #' #' #' @examples #' init() #' moves <- list(Q$I2, sigmaX(Q$I2)) #' PayoffMatrix_QBOS(moves, 5, 3, 1) #' #' @export #' PayoffMatrix_QBOS <- function(moves, alpha, beta, gamma){ Alice <- matrix(0, 2, 2) Bob <- matrix(0, 2, 2) for(i in 1:2){ for (j in 1:2){ X <- QBOS(i-1, j-1, moves, alpha, beta, gamma) Alice[i, j] <- X[[1]] Bob[i, j] <- X[[2]] } } return(list(Alice, Bob)) }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/visualize.R \name{TCGAvisualize_SurvivalCoxNET} \alias{TCGAvisualize_SurvivalCoxNET} \title{Survival analysis with univariate Cox regression package (dnet)} \usage{ TCGAvisualize_SurvivalCoxNET( clinical_patient, dataGE, Genelist, org.Hs.string, scoreConfidence = 700, titlePlot = "TCGAvisualize_SurvivalCoxNET Example" ) } \arguments{ \item{clinical_patient}{is a data.frame using function 'clinic' with information related to barcode / samples such as bcr_patient_barcode, days_to_death , days_to_last_followup , vital_status, etc} \item{dataGE}{is a matrix of Gene expression (genes in rows, samples in cols) from TCGAprepare} \item{Genelist}{is a list of gene symbols where perform survival KM.} \item{org.Hs.string}{an igraph object that contains a functional protein association network in human. The network is extracted from the STRING database (version 10).} \item{scoreConfidence}{restrict to those edges with high confidence (eg. score>=700)} \item{titlePlot}{is the title to show in the final plot.} } \value{ net IGRAPH with related Cox survival genes in community (same pval and color) and with interactions from STRING database. } \description{ TCGAvisualize_SurvivalCoxNET can help an user to identify a group of survival genes that are significant from univariate Kaplan Meier Analysis and also for Cox Regression. It shows in the end a network build with community of genes with similar range of pvalues from Cox regression (same color) and that interaction among those genes is already validated in literatures using the STRING database (version 9.1). TCGAvisualize_SurvivalCoxNET perform survival analysis with univariate Cox regression and package (dnet) using following functions wrapping from these packages: \enumerate{ \item survival::coxph \item igraph::subgraph.edges \item igraph::layout.fruchterman.reingold \item igraph::spinglass.community \item igraph::communities \item dnet::dRDataLoader \item dnet::dNetInduce \item dnet::dNetPipeline \item dnet::visNet \item dnet::dCommSignif } } \details{ TCGAvisualize_SurvivalCoxNET allow user to perform the complete workflow using coxph and dnet package related to survival analysis with an identification of gene-active networks from high-throughput omics data using gene expression and clinical data. \enumerate{ \item Cox regression survival analysis to obtain hazard ratio (HR) and p-values \item fit a Cox proportional hazards model and ANOVA (Chisq test) \item Network comunites \item An igraph object that contains a functional protein association network in human. The network is extracted from the STRING database (version 9.1). Only those associations with medium confidence (score>=400) are retained. \item restrict to those edges with high confidence (score>=700) \item extract network that only contains genes in pvals \item Identification of gene-active network \item visualisation of the gene-active network itself \item the layout of the network visualisation (fixed in different visuals) \item color nodes according to communities (identified via a spin-glass model and simulated annealing) \item node sizes according to degrees \item highlight different communities \item visualize the subnetwork } }
/man/TCGAvisualize_SurvivalCoxNET.Rd
no_license
BioinformaticsFMRP/TCGAbiolinks
R
false
true
3,290
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/visualize.R \name{TCGAvisualize_SurvivalCoxNET} \alias{TCGAvisualize_SurvivalCoxNET} \title{Survival analysis with univariate Cox regression package (dnet)} \usage{ TCGAvisualize_SurvivalCoxNET( clinical_patient, dataGE, Genelist, org.Hs.string, scoreConfidence = 700, titlePlot = "TCGAvisualize_SurvivalCoxNET Example" ) } \arguments{ \item{clinical_patient}{is a data.frame using function 'clinic' with information related to barcode / samples such as bcr_patient_barcode, days_to_death , days_to_last_followup , vital_status, etc} \item{dataGE}{is a matrix of Gene expression (genes in rows, samples in cols) from TCGAprepare} \item{Genelist}{is a list of gene symbols where perform survival KM.} \item{org.Hs.string}{an igraph object that contains a functional protein association network in human. The network is extracted from the STRING database (version 10).} \item{scoreConfidence}{restrict to those edges with high confidence (eg. score>=700)} \item{titlePlot}{is the title to show in the final plot.} } \value{ net IGRAPH with related Cox survival genes in community (same pval and color) and with interactions from STRING database. } \description{ TCGAvisualize_SurvivalCoxNET can help an user to identify a group of survival genes that are significant from univariate Kaplan Meier Analysis and also for Cox Regression. It shows in the end a network build with community of genes with similar range of pvalues from Cox regression (same color) and that interaction among those genes is already validated in literatures using the STRING database (version 9.1). TCGAvisualize_SurvivalCoxNET perform survival analysis with univariate Cox regression and package (dnet) using following functions wrapping from these packages: \enumerate{ \item survival::coxph \item igraph::subgraph.edges \item igraph::layout.fruchterman.reingold \item igraph::spinglass.community \item igraph::communities \item dnet::dRDataLoader \item dnet::dNetInduce \item dnet::dNetPipeline \item dnet::visNet \item dnet::dCommSignif } } \details{ TCGAvisualize_SurvivalCoxNET allow user to perform the complete workflow using coxph and dnet package related to survival analysis with an identification of gene-active networks from high-throughput omics data using gene expression and clinical data. \enumerate{ \item Cox regression survival analysis to obtain hazard ratio (HR) and p-values \item fit a Cox proportional hazards model and ANOVA (Chisq test) \item Network comunites \item An igraph object that contains a functional protein association network in human. The network is extracted from the STRING database (version 9.1). Only those associations with medium confidence (score>=400) are retained. \item restrict to those edges with high confidence (score>=700) \item extract network that only contains genes in pvals \item Identification of gene-active network \item visualisation of the gene-active network itself \item the layout of the network visualisation (fixed in different visuals) \item color nodes according to communities (identified via a spin-glass model and simulated annealing) \item node sizes according to degrees \item highlight different communities \item visualize the subnetwork } }
#' @title Spatial Variance Inflation Factor #' #' @description Calculate the VIF #' #' @param base_model model to use as comparison. #' @param model model to compare. #' #' @return res data.frame with VIF for fixed parameters #' #' @export SVIF <- function(base_model, model) { fixed_names <- rownames(base_model$summary_fixed) vif <- (model$summary_fixed$sd^2)/(base_model$summary_fixed$sd^2) vif <- data.frame(vif) res <- data.frame(fixed_names, vif, stringsAsFactors = FALSE) names(res) <- c("parameter", "VIF") return(res) } #' @title Spatial Variance Retraction Factor #' #' @description Calculate the VRF #' #' @param base_model model to use as comparison #' @param model model to compare #' #' @return res data.frame with VRF for fixed parameters #' #' @export SVRF <- function(base_model, model) { res <- SVIF(base_model = base_model, model = model) res$VIF <- 1- 1/res$VIF names(res) <- c(c("parameter", "VRF")) return(res) } #' @title Projection matrix #' #' @description Calculate the projection matrix under several approaches #' #' @param X covariate matrix #' @param groups ids for the subjects #' @param method projection's method #' #' @return Px Projection matrix #' Px_ort (I - Px) proj_mat <- function(X, groups = NULL, method = "rhz") { N <- nrow(X) if(is.null(groups)) groups <- 1:N n_groups <- length(unique(groups)) ##-- Projection matrices ---- if(method == "rhz"){ if(n_groups != N){ n_group <- diag(1/tapply(groups, groups, length)) XX_inv <- solve(t(X)%*%X) Paux <- XX_inv%*%(t(X) %r% groups) Px <- (X %r% groups)%*%Paux Px_ort <- diag(1, nrow = n_groups, ncol = n_groups) - n_group%*%Px } else{ XX_inv <- solve(t(X)%*%X) Paux <- XX_inv%*%t(X) Px <- X%*%Paux Px_ort <- diag(nrow(X)) - Px } } return(list(Paux = Paux, Px = Px, Px_ort = Px_ort)) } #' @title Generate data from ICAR model #' #' @description Generate data from ICAR model #' #' @param W adjcency matrix #' @param sig standard deviation #' #' @importFrom stats rnorm #' #' @return x ricar <- function(W, sig = 1) { n <- ncol(W) num <- rowSums(W) Q <- -W diag(Q) <- num Q_aux <- eigen(Q)$vectors[, order(eigen(Q)$values)] D_aux <- sort(eigen(Q)$values) rnd <- rnorm(n-1, 0, sqrt(sig*(1/D_aux[-1]))) rnd <- Q_aux%*%c(0, rnd) return(as.vector(rnd)) } #' #' @title Generate data from CAR model #' #' #' #' @description Generate data from CAR model #' #' #' #' @param W adjcency matrix #' #' @param sig standard deviation #' #' @param rho dependence parameter #' #' #' #' @return x #' #' rcar <- function(W, sig, rho = 0.9999){ #' D <- diag(colSums(W)) #' Q <- sig*(D - rho*W) #' sigma <- solve(Q) #' #' samp <- as.numeric(rmvnorm(n = 1, mean = rep(0, ncol(W)), sigma = sigma)) #' return(samp) #' } #' @title select_marginal #' #' @description Select the desired marginals on a INLA models #' #' @param samp a sample from ?inla.posterior.sample #' @param ids ids to restore select_marginal <- function(samp, ids) { row_names <- row.names(samp$latent) samp <- c(samp$latent[row_names %in% ids]) return(samp) } #' @title Append two lists #' #' @description Get commom parameters in two list and generate one append list #' #' @param x list base #' @param y second list #' #' @return x append_list <- function (x, y) { xnames <- names(x) for (v in names(y)) { if(v %in% xnames && is.list(x[[v]]) && is.list(y[[v]])){ x[[v]] <- append_list(x[[v]], y[[v]]) } else{ if(!is.null(y[[v]])){ x[[v]] <- y[[v]] } } } return(x) } #' @title meang #' #' @description Mean by groups #' #' @param x a numeric vector #' @param g group indexes #' @param weighted TRUE for weighted mean meang <- function(x, g, weighted = FALSE) { if(weighted){ res <- tapply(X = x, INDEX = g, FUN = function(x) mean(x)*length(x)) } else{ res <- tapply(X = x, INDEX = g, FUN = mean) } return(res) } #' @title Reduction operator #' #' @description Reduction operator #' #' @param x a numeric vector or a numeric matrix #' @param g_index group indexes #' #' @export `%r%` <- function(x, g_index) { if(!(class(x) %in% c("numeric", "matrix"))) stop("x must be a vector or a matrix") if(is.matrix(x)){ n <- nrow(x) p <- ncol(x) if(!(length(g_index) %in% c(n, p))) stop("g_index should be equal to nrow(x) or ncol(x)") dim_reduction <- ifelse(length(g_index) == p, 1, 2) reduction <- apply(X = x, MARGIN = dim_reduction, FUN = function(y) tapply(X = y, INDEX = g_index, FUN = sum)) if(dim_reduction == 1) reduction <- t(reduction) } else{ reduction <- tapply(X = x, INDEX = g_index, FUN = sum) } return(reduction) } #' @title Enlargement operator #' #' @description Enlargement operator #' #' @param x a numeric vector or a numeric matrix #' @param g_index group indexes `%e%` <- function(x, g_index) { if(!(class(x) %in% c("numeric", "matrix"))) stop("x must be a vector or a matrix") if(is.matrix(x)) if(is.null(colnames(x)) & is.null(row.names(x))) stop("x must be a named matrix") if(!is.matrix(x)) if(is.null(names(x))) stop("x must be a named vector.") if(!all(names(x) %in% unique(g_index))) stop("names(x) and g_index does not match.") if(is.matrix(x)){ n <- nrow(x) p <- ncol(x) ng <- length(unique(g_index)) if(!(ng %in% c(n, p))) stop("Number of g_index groups should be equal to nrow(x) or ncol(x)") if(ng == p){ dim_enlargement <- 1 names_x <- colnames(x) } else{ dim_enlargement <- 2 names_x <- row.names(x) } n_group <- table(g_index)[names_x] enlargement <- apply(X = x, MARGIN = dim_enlargement, FUN = function(x) (x/n_group)[g_index]) if(dim_enlargement == 1) enlargement <- t(enlargement) } else{ names_x <- names(x) n_group <- table(g_index)[names_x] enlargement <- (x/table(g_index)[names(x)])[g_index] enlargement <- as.numeric(enlargement) names(enlargement) <- g_index } return(enlargement) } #' @title Updating INLA formula #' #' @description Updating INLA formula #' #' @param formula a formula to be updated to INLA format #' #' @importFrom stats terms.formula update_inla_formula <- function(formula) { ##-- Checking formula terms_formula <- terms.formula(formula, specials = c("f"), data = NULL) terms_labels <- paste(attr(terms_formula, "variables")) terms_f <- attr(terms_formula, "specials")$f + 1 ##-- + 1 for the list parameter pos_restricted <- grep(x = terms_labels, pattern = "restricted|r_") pos_unrestricted <- grep(x = terms_labels, pattern = "\"(iid|besag|besag2|besagproper|besagproper2)") ##-- Updating formula if(length(pos_restricted) > 0){ formula_char <- format(formula) formula_char <- gsub(pattern = "restricted_besag", replacement = "besag", x = formula_char) formula_new <- as.formula(formula_char) terms_formula <- terms.formula(formula_new, specials = c("f"), data = NULL) terms_labels <- paste(attr(terms_formula, "variables")) } else{ formula_new <- formula } if(length(terms_f) > 0){ var_f <- list() for(i in seq_along(terms_f)){ var_f[[i]] = eval(expr = parse(text = gsub(pattern = "^f\\(", replacement = "INLA::f(", x = terms_labels[terms_f[i]])), envir = parent.frame(n = 2)) } ##-- Restricted and unrestricted components list_models <- lapply(var_f, "[", c("label", "model", "n")) list_restricted <- list_models[terms_f %in% pos_restricted] var_restricted <- unlist(lapply(list_restricted, FUN = "[[", "label")) size_restricted <- unlist(lapply(list_restricted, FUN = "[[", "n")) list_unrestricted <- list_models[terms_f %in% pos_unrestricted] var_unrestricted <- unlist(lapply(list_unrestricted, FUN = "[[", "label")) size_unrestricted <- unlist(lapply(list_unrestricted, FUN = "[[", "n")) } else{ var_restricted <- NULL size_restricted <- NULL var_unrestricted <- NULL size_unrestricted <- NULL } return(list(formula = formula_new, var_restricted = var_restricted, vars_unrestricted = var_unrestricted, size_restricted = size_restricted, size_unrestricted = size_unrestricted)) } #' @title Deviance Information Criterion #' #' @description Get the Deviance Information Criterion (DIC) from a model #' #' @param object a object from ?rsglmm, ?rscm or ?rsfm #' #' @return DIC #' #' @export DIC <- function(object) { out <- object$out if(class(out) == "inla") { return(out$dic$dic) } if(class(out) == "sparse.sglmm") { return(out$dic) } stop(sprintf("Don't know how to deal with an object of class %s. Did you fit a model using rsglmm, rscm or rsfm?", class(out))) } #' @title Watanabe–Akaike information criterion #' #' @description Get the Watanabe–Akaike information criterion (WAIC) from a model #' #' @param object a object from ?rsglmm, ?rscm or ?rsfm #' #' @return WAIC #' #' @export WAIC <- function(object) { out <- object$out if(class(out) == "inla") { return(out$waic$waic) } if(class(out) == "sparse.sglmm") { return(NA_real_) } stop(sprintf("Don't know how to deal with an object of class %s. Did you fit a model using rsglmm, rscm or rsfm?", class(out))) }
/R/utils.R
no_license
bandyopd/RASCO
R
false
false
9,442
r
#' @title Spatial Variance Inflation Factor #' #' @description Calculate the VIF #' #' @param base_model model to use as comparison. #' @param model model to compare. #' #' @return res data.frame with VIF for fixed parameters #' #' @export SVIF <- function(base_model, model) { fixed_names <- rownames(base_model$summary_fixed) vif <- (model$summary_fixed$sd^2)/(base_model$summary_fixed$sd^2) vif <- data.frame(vif) res <- data.frame(fixed_names, vif, stringsAsFactors = FALSE) names(res) <- c("parameter", "VIF") return(res) } #' @title Spatial Variance Retraction Factor #' #' @description Calculate the VRF #' #' @param base_model model to use as comparison #' @param model model to compare #' #' @return res data.frame with VRF for fixed parameters #' #' @export SVRF <- function(base_model, model) { res <- SVIF(base_model = base_model, model = model) res$VIF <- 1- 1/res$VIF names(res) <- c(c("parameter", "VRF")) return(res) } #' @title Projection matrix #' #' @description Calculate the projection matrix under several approaches #' #' @param X covariate matrix #' @param groups ids for the subjects #' @param method projection's method #' #' @return Px Projection matrix #' Px_ort (I - Px) proj_mat <- function(X, groups = NULL, method = "rhz") { N <- nrow(X) if(is.null(groups)) groups <- 1:N n_groups <- length(unique(groups)) ##-- Projection matrices ---- if(method == "rhz"){ if(n_groups != N){ n_group <- diag(1/tapply(groups, groups, length)) XX_inv <- solve(t(X)%*%X) Paux <- XX_inv%*%(t(X) %r% groups) Px <- (X %r% groups)%*%Paux Px_ort <- diag(1, nrow = n_groups, ncol = n_groups) - n_group%*%Px } else{ XX_inv <- solve(t(X)%*%X) Paux <- XX_inv%*%t(X) Px <- X%*%Paux Px_ort <- diag(nrow(X)) - Px } } return(list(Paux = Paux, Px = Px, Px_ort = Px_ort)) } #' @title Generate data from ICAR model #' #' @description Generate data from ICAR model #' #' @param W adjcency matrix #' @param sig standard deviation #' #' @importFrom stats rnorm #' #' @return x ricar <- function(W, sig = 1) { n <- ncol(W) num <- rowSums(W) Q <- -W diag(Q) <- num Q_aux <- eigen(Q)$vectors[, order(eigen(Q)$values)] D_aux <- sort(eigen(Q)$values) rnd <- rnorm(n-1, 0, sqrt(sig*(1/D_aux[-1]))) rnd <- Q_aux%*%c(0, rnd) return(as.vector(rnd)) } #' #' @title Generate data from CAR model #' #' #' #' @description Generate data from CAR model #' #' #' #' @param W adjcency matrix #' #' @param sig standard deviation #' #' @param rho dependence parameter #' #' #' #' @return x #' #' rcar <- function(W, sig, rho = 0.9999){ #' D <- diag(colSums(W)) #' Q <- sig*(D - rho*W) #' sigma <- solve(Q) #' #' samp <- as.numeric(rmvnorm(n = 1, mean = rep(0, ncol(W)), sigma = sigma)) #' return(samp) #' } #' @title select_marginal #' #' @description Select the desired marginals on a INLA models #' #' @param samp a sample from ?inla.posterior.sample #' @param ids ids to restore select_marginal <- function(samp, ids) { row_names <- row.names(samp$latent) samp <- c(samp$latent[row_names %in% ids]) return(samp) } #' @title Append two lists #' #' @description Get commom parameters in two list and generate one append list #' #' @param x list base #' @param y second list #' #' @return x append_list <- function (x, y) { xnames <- names(x) for (v in names(y)) { if(v %in% xnames && is.list(x[[v]]) && is.list(y[[v]])){ x[[v]] <- append_list(x[[v]], y[[v]]) } else{ if(!is.null(y[[v]])){ x[[v]] <- y[[v]] } } } return(x) } #' @title meang #' #' @description Mean by groups #' #' @param x a numeric vector #' @param g group indexes #' @param weighted TRUE for weighted mean meang <- function(x, g, weighted = FALSE) { if(weighted){ res <- tapply(X = x, INDEX = g, FUN = function(x) mean(x)*length(x)) } else{ res <- tapply(X = x, INDEX = g, FUN = mean) } return(res) } #' @title Reduction operator #' #' @description Reduction operator #' #' @param x a numeric vector or a numeric matrix #' @param g_index group indexes #' #' @export `%r%` <- function(x, g_index) { if(!(class(x) %in% c("numeric", "matrix"))) stop("x must be a vector or a matrix") if(is.matrix(x)){ n <- nrow(x) p <- ncol(x) if(!(length(g_index) %in% c(n, p))) stop("g_index should be equal to nrow(x) or ncol(x)") dim_reduction <- ifelse(length(g_index) == p, 1, 2) reduction <- apply(X = x, MARGIN = dim_reduction, FUN = function(y) tapply(X = y, INDEX = g_index, FUN = sum)) if(dim_reduction == 1) reduction <- t(reduction) } else{ reduction <- tapply(X = x, INDEX = g_index, FUN = sum) } return(reduction) } #' @title Enlargement operator #' #' @description Enlargement operator #' #' @param x a numeric vector or a numeric matrix #' @param g_index group indexes `%e%` <- function(x, g_index) { if(!(class(x) %in% c("numeric", "matrix"))) stop("x must be a vector or a matrix") if(is.matrix(x)) if(is.null(colnames(x)) & is.null(row.names(x))) stop("x must be a named matrix") if(!is.matrix(x)) if(is.null(names(x))) stop("x must be a named vector.") if(!all(names(x) %in% unique(g_index))) stop("names(x) and g_index does not match.") if(is.matrix(x)){ n <- nrow(x) p <- ncol(x) ng <- length(unique(g_index)) if(!(ng %in% c(n, p))) stop("Number of g_index groups should be equal to nrow(x) or ncol(x)") if(ng == p){ dim_enlargement <- 1 names_x <- colnames(x) } else{ dim_enlargement <- 2 names_x <- row.names(x) } n_group <- table(g_index)[names_x] enlargement <- apply(X = x, MARGIN = dim_enlargement, FUN = function(x) (x/n_group)[g_index]) if(dim_enlargement == 1) enlargement <- t(enlargement) } else{ names_x <- names(x) n_group <- table(g_index)[names_x] enlargement <- (x/table(g_index)[names(x)])[g_index] enlargement <- as.numeric(enlargement) names(enlargement) <- g_index } return(enlargement) } #' @title Updating INLA formula #' #' @description Updating INLA formula #' #' @param formula a formula to be updated to INLA format #' #' @importFrom stats terms.formula update_inla_formula <- function(formula) { ##-- Checking formula terms_formula <- terms.formula(formula, specials = c("f"), data = NULL) terms_labels <- paste(attr(terms_formula, "variables")) terms_f <- attr(terms_formula, "specials")$f + 1 ##-- + 1 for the list parameter pos_restricted <- grep(x = terms_labels, pattern = "restricted|r_") pos_unrestricted <- grep(x = terms_labels, pattern = "\"(iid|besag|besag2|besagproper|besagproper2)") ##-- Updating formula if(length(pos_restricted) > 0){ formula_char <- format(formula) formula_char <- gsub(pattern = "restricted_besag", replacement = "besag", x = formula_char) formula_new <- as.formula(formula_char) terms_formula <- terms.formula(formula_new, specials = c("f"), data = NULL) terms_labels <- paste(attr(terms_formula, "variables")) } else{ formula_new <- formula } if(length(terms_f) > 0){ var_f <- list() for(i in seq_along(terms_f)){ var_f[[i]] = eval(expr = parse(text = gsub(pattern = "^f\\(", replacement = "INLA::f(", x = terms_labels[terms_f[i]])), envir = parent.frame(n = 2)) } ##-- Restricted and unrestricted components list_models <- lapply(var_f, "[", c("label", "model", "n")) list_restricted <- list_models[terms_f %in% pos_restricted] var_restricted <- unlist(lapply(list_restricted, FUN = "[[", "label")) size_restricted <- unlist(lapply(list_restricted, FUN = "[[", "n")) list_unrestricted <- list_models[terms_f %in% pos_unrestricted] var_unrestricted <- unlist(lapply(list_unrestricted, FUN = "[[", "label")) size_unrestricted <- unlist(lapply(list_unrestricted, FUN = "[[", "n")) } else{ var_restricted <- NULL size_restricted <- NULL var_unrestricted <- NULL size_unrestricted <- NULL } return(list(formula = formula_new, var_restricted = var_restricted, vars_unrestricted = var_unrestricted, size_restricted = size_restricted, size_unrestricted = size_unrestricted)) } #' @title Deviance Information Criterion #' #' @description Get the Deviance Information Criterion (DIC) from a model #' #' @param object a object from ?rsglmm, ?rscm or ?rsfm #' #' @return DIC #' #' @export DIC <- function(object) { out <- object$out if(class(out) == "inla") { return(out$dic$dic) } if(class(out) == "sparse.sglmm") { return(out$dic) } stop(sprintf("Don't know how to deal with an object of class %s. Did you fit a model using rsglmm, rscm or rsfm?", class(out))) } #' @title Watanabe–Akaike information criterion #' #' @description Get the Watanabe–Akaike information criterion (WAIC) from a model #' #' @param object a object from ?rsglmm, ?rscm or ?rsfm #' #' @return WAIC #' #' @export WAIC <- function(object) { out <- object$out if(class(out) == "inla") { return(out$waic$waic) } if(class(out) == "sparse.sglmm") { return(NA_real_) } stop(sprintf("Don't know how to deal with an object of class %s. Did you fit a model using rsglmm, rscm or rsfm?", class(out))) }
data_proc_africa <- function(outputdir){ # LOAD REQUIRED PACKAGES AND FUNCTIONS ----------------------------------------- if (!require("pacman")) install.packages("pacman") pkgs = c("dplyr", "sf","sp") # package names pacman::p_load(pkgs, character.only = T) # LOAD DATA -------------------------------------------------------------------- # Cases at country level # ECDC # cases <- readr::read_csv("https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/ecdc/new_cases.csv") # JHU cases <- readr::read_csv("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv") # Shapefile for Africa africa <- st_read("data/original/geodata/africa.gpkg") # Policy index policy <- readr::read_csv("https://raw.githubusercontent.com/OxCGRT/covid-policy-tracker/master/data/OxCGRT_latest.csv") # DATA PREPARATION ------------------------------------------------------------- caseloc = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv" africaloc = "data/original/geodata/africa.gpkg" policyloc = "https://raw.githubusercontent.com/OxCGRT/covid-policy-tracker/master/data/OxCGRT_latest.csv" alldata = read_all(cases=caseloc, areas=africaloc, policy=policyloc) # Remove Countries with missing policy data countries_to_remove <- c("Madagascar", "Western Sahara", "Guinea-Bissau", "Equatorial Guinea") alldata$areas <- alldata$areas[!(alldata$areas$name %in% countries_to_remove), ] # # THIS IS THE CLEANING FOR ECDC DATA # # Change names of countries according to the shapefils # names(cases)[grep("Congo", names(cases))] <- c("Republic of Congo", "Democratic Republic of the Congo") # names(cases)[grep("Gambia", names(cases))] <- "The Gambia" # # # # Subset the cases only to the 46 African countries we work with # cases <- cases[, c(1, match(africa$name, names(cases)))] # cases[is.na(cases)] <- 0 # Clean JHU data : # - rename countries according to shapefile # - keep only countries that we are going to analyse # - calculate daily new cases # - replace the 4 negatives with 0 alldata$cases <- alldata$cases %>% select(-`Province/State`, -Lat, -Long) %>% rename(country = `Country/Region`) %>% mutate(country = case_when( country == "Congo (Kinshasa)" ~ "Democratic Republic of the Congo", country == "Gambia" ~ "The Gambia", country == "Eswatini" ~ "Swaziland", country == "Congo (Brazzaville)" ~ "Republic of Congo", country == "Gambia" ~ "The Gambia", TRUE ~ country )) %>% filter(country %in% alldata$areas$name) # Check that the order of cases and countries in the shapefile are the same alldata$cases <- alldata$cases[order(alldata$cases$country), ] all(alldata$cases$country == alldata$areas$name) # Reshape cases with times in the row and geographical units in the column # so each column is the cases time series for the county # the results should be of dimension T x N # where T is the number of time points and N is the number of countries # remember that this structure needs to be kept also for the # predictors # First change the names of the columns to proper dates names(alldata$cases)[-1] <- paste0(names(alldata$cases)[-1], 20) %>% as.Date(format = "%m/%d/%Y") %>% as.character() alldata$counts <- t(alldata$cases[, -1]) colnames(alldata$counts) <- alldata$cases$country alldata$counts <- apply(alldata$counts, 2, diff) alldata$counts[alldata$counts < 0] <- 0 # Clean policy data alldata$policy_clean <- alldata$policy %>% select(country = CountryName, date = Date, testing = `H2_Testing policy`, sindex = StringencyIndex) %>% mutate(date = as.Date(as.character(date), format = "%Y%m%d"), country = case_when( country == "Democratic Republic of Congo" ~ "Democratic Republic of the Congo", country == "Gambia" ~ "The Gambia", country == "Eswatini" ~ "Swaziland", country == "Congo" ~ "Republic of Congo", TRUE ~ country )) %>% filter(country %in% alldata$areas$name) alldata$testing <- alldata$policy_clean %>% select(-sindex) %>% tidyr::spread(key = country, value = testing) %>% select(-date) %>% as.matrix() alldata$testing[is.na(alldata$testing)] <- 0 rownames(alldata$testing) <- unique(as.character(alldata$policy_clean$date)) alldata$sindex <- alldata$policy_clean %>% select(-testing) %>% tidyr::spread(key = country, value = sindex) %>% select(-date) %>% as.matrix() alldata$sindex[is.na(alldata$sindex)] <- 0 rownames(alldata$sindex) <- unique(as.character(alldata$policy_clean$date)) # Subset to the cases dates alldata$testing <- alldata$testing[rownames(alldata$testing) %in% rownames(alldata$counts), ] alldata$sindex <- alldata$sindex[rownames(alldata$sindex) %in% rownames(alldata$counts), ] return(alldata) }
/01_data-processing.R
no_license
Jacob-Snyder/chicas-stsmodel
R
false
false
5,088
r
data_proc_africa <- function(outputdir){ # LOAD REQUIRED PACKAGES AND FUNCTIONS ----------------------------------------- if (!require("pacman")) install.packages("pacman") pkgs = c("dplyr", "sf","sp") # package names pacman::p_load(pkgs, character.only = T) # LOAD DATA -------------------------------------------------------------------- # Cases at country level # ECDC # cases <- readr::read_csv("https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/ecdc/new_cases.csv") # JHU cases <- readr::read_csv("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv") # Shapefile for Africa africa <- st_read("data/original/geodata/africa.gpkg") # Policy index policy <- readr::read_csv("https://raw.githubusercontent.com/OxCGRT/covid-policy-tracker/master/data/OxCGRT_latest.csv") # DATA PREPARATION ------------------------------------------------------------- caseloc = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv" africaloc = "data/original/geodata/africa.gpkg" policyloc = "https://raw.githubusercontent.com/OxCGRT/covid-policy-tracker/master/data/OxCGRT_latest.csv" alldata = read_all(cases=caseloc, areas=africaloc, policy=policyloc) # Remove Countries with missing policy data countries_to_remove <- c("Madagascar", "Western Sahara", "Guinea-Bissau", "Equatorial Guinea") alldata$areas <- alldata$areas[!(alldata$areas$name %in% countries_to_remove), ] # # THIS IS THE CLEANING FOR ECDC DATA # # Change names of countries according to the shapefils # names(cases)[grep("Congo", names(cases))] <- c("Republic of Congo", "Democratic Republic of the Congo") # names(cases)[grep("Gambia", names(cases))] <- "The Gambia" # # # # Subset the cases only to the 46 African countries we work with # cases <- cases[, c(1, match(africa$name, names(cases)))] # cases[is.na(cases)] <- 0 # Clean JHU data : # - rename countries according to shapefile # - keep only countries that we are going to analyse # - calculate daily new cases # - replace the 4 negatives with 0 alldata$cases <- alldata$cases %>% select(-`Province/State`, -Lat, -Long) %>% rename(country = `Country/Region`) %>% mutate(country = case_when( country == "Congo (Kinshasa)" ~ "Democratic Republic of the Congo", country == "Gambia" ~ "The Gambia", country == "Eswatini" ~ "Swaziland", country == "Congo (Brazzaville)" ~ "Republic of Congo", country == "Gambia" ~ "The Gambia", TRUE ~ country )) %>% filter(country %in% alldata$areas$name) # Check that the order of cases and countries in the shapefile are the same alldata$cases <- alldata$cases[order(alldata$cases$country), ] all(alldata$cases$country == alldata$areas$name) # Reshape cases with times in the row and geographical units in the column # so each column is the cases time series for the county # the results should be of dimension T x N # where T is the number of time points and N is the number of countries # remember that this structure needs to be kept also for the # predictors # First change the names of the columns to proper dates names(alldata$cases)[-1] <- paste0(names(alldata$cases)[-1], 20) %>% as.Date(format = "%m/%d/%Y") %>% as.character() alldata$counts <- t(alldata$cases[, -1]) colnames(alldata$counts) <- alldata$cases$country alldata$counts <- apply(alldata$counts, 2, diff) alldata$counts[alldata$counts < 0] <- 0 # Clean policy data alldata$policy_clean <- alldata$policy %>% select(country = CountryName, date = Date, testing = `H2_Testing policy`, sindex = StringencyIndex) %>% mutate(date = as.Date(as.character(date), format = "%Y%m%d"), country = case_when( country == "Democratic Republic of Congo" ~ "Democratic Republic of the Congo", country == "Gambia" ~ "The Gambia", country == "Eswatini" ~ "Swaziland", country == "Congo" ~ "Republic of Congo", TRUE ~ country )) %>% filter(country %in% alldata$areas$name) alldata$testing <- alldata$policy_clean %>% select(-sindex) %>% tidyr::spread(key = country, value = testing) %>% select(-date) %>% as.matrix() alldata$testing[is.na(alldata$testing)] <- 0 rownames(alldata$testing) <- unique(as.character(alldata$policy_clean$date)) alldata$sindex <- alldata$policy_clean %>% select(-testing) %>% tidyr::spread(key = country, value = sindex) %>% select(-date) %>% as.matrix() alldata$sindex[is.na(alldata$sindex)] <- 0 rownames(alldata$sindex) <- unique(as.character(alldata$policy_clean$date)) # Subset to the cases dates alldata$testing <- alldata$testing[rownames(alldata$testing) %in% rownames(alldata$counts), ] alldata$sindex <- alldata$sindex[rownames(alldata$sindex) %in% rownames(alldata$counts), ] return(alldata) }
library(data.table); library(dplyr) # load required dataset nv <- readRDS("9 net value.rds") # Net value before standardisation mean(nv$nv_50k) mean(nv$nv_100k) mean(nv$nv_200k) # classify participants by age groups and gender df <- mutate(nv, group = cut(age, breaks=c(seq(from = 14, to = 84, by = 5), Inf), labels=c("15-19", "20-24", "25-29", "30-34", "35-39", "40-44", "45-49", "50-54", "55-59", "60-64", "65-69", "70-74", "75-79", "80-84", "85+"))) %>% as.data.table df <- df[, .(nv_50k = mean(nv_50k), nv_100k = mean(nv_100k), nv_200k = mean(nv_200k), diff.spend = mean(diff.spend.mod)), keyby = .(group, female)] # Net Value 2: Age- and sex-standardized population, using Hong Kong diabetes patient reference population for adults up to age 79 (for comparability with Japan sample) # Net Value 3: Age- and sex-standardized population, using WHO world population referencepopulation (modified for adult population 15 - 85+ years old) df$hkdm <- c(0.001340, 0.000997, 0.001315, 0.001293, 0.001794, 0.002307, 0.003605, 0.004583, 0.007690, 0.008642, 0.016029, 0.014628, 0.029435, 0.023546, 0.059159, 0.046097, 0.082705, 0.068599, 0.090264, 0.081155, 0.090036, 0.084927, 0.070938, 0.066088, 0.067006, 0.075821, 0, 0, 0, 0) df$who <- rep(c(0.057318597, 0.055626862, 0.053664342, 0.051498732, 0.048386049, 0.0445964, 0.040874449, 0.03634014, 0.03079106, 0.025174285, 0.020031384, 0.014955503, 0.010286478, 0.006158347, 0.004297372), each = 2) df$nv_50k_hkdm <- df$nv_50k * df$hkdm df$nv_100k_hkdm <- df$nv_100k * df$hkdm df$nv_200k_hkdm <- df$nv_200k * df$hkdm df$nv_50k_who <- df$nv_50k * df$who df$nv_100k_who <- df$nv_100k * df$who df$nv_200k_who <- df$nv_200k * df$who # Overall weighted net value, standardised to HKDM reference population sum(df$nv_50k_hkdm) # assuming value of 1 life-year = 50k sum(df$nv_100k_hkdm) # assuming value of 1 life-year = 100k sum(df$nv_200k_hkdm) # assuming value of 1 life-year = 200k # Overall weighted net value, standardised to WHO reference population sum(df$nv_50k_who) # assuming value of 1 life-year = 50k sum(df$nv_100k_who) # assuming value of 1 life-year = 100k sum(df$nv_200k_who) # assuming value of 1 life-year = 200k
/10 Age and sex standardisation.R
no_license
janetltk/dm-net-value
R
false
false
2,214
r
library(data.table); library(dplyr) # load required dataset nv <- readRDS("9 net value.rds") # Net value before standardisation mean(nv$nv_50k) mean(nv$nv_100k) mean(nv$nv_200k) # classify participants by age groups and gender df <- mutate(nv, group = cut(age, breaks=c(seq(from = 14, to = 84, by = 5), Inf), labels=c("15-19", "20-24", "25-29", "30-34", "35-39", "40-44", "45-49", "50-54", "55-59", "60-64", "65-69", "70-74", "75-79", "80-84", "85+"))) %>% as.data.table df <- df[, .(nv_50k = mean(nv_50k), nv_100k = mean(nv_100k), nv_200k = mean(nv_200k), diff.spend = mean(diff.spend.mod)), keyby = .(group, female)] # Net Value 2: Age- and sex-standardized population, using Hong Kong diabetes patient reference population for adults up to age 79 (for comparability with Japan sample) # Net Value 3: Age- and sex-standardized population, using WHO world population referencepopulation (modified for adult population 15 - 85+ years old) df$hkdm <- c(0.001340, 0.000997, 0.001315, 0.001293, 0.001794, 0.002307, 0.003605, 0.004583, 0.007690, 0.008642, 0.016029, 0.014628, 0.029435, 0.023546, 0.059159, 0.046097, 0.082705, 0.068599, 0.090264, 0.081155, 0.090036, 0.084927, 0.070938, 0.066088, 0.067006, 0.075821, 0, 0, 0, 0) df$who <- rep(c(0.057318597, 0.055626862, 0.053664342, 0.051498732, 0.048386049, 0.0445964, 0.040874449, 0.03634014, 0.03079106, 0.025174285, 0.020031384, 0.014955503, 0.010286478, 0.006158347, 0.004297372), each = 2) df$nv_50k_hkdm <- df$nv_50k * df$hkdm df$nv_100k_hkdm <- df$nv_100k * df$hkdm df$nv_200k_hkdm <- df$nv_200k * df$hkdm df$nv_50k_who <- df$nv_50k * df$who df$nv_100k_who <- df$nv_100k * df$who df$nv_200k_who <- df$nv_200k * df$who # Overall weighted net value, standardised to HKDM reference population sum(df$nv_50k_hkdm) # assuming value of 1 life-year = 50k sum(df$nv_100k_hkdm) # assuming value of 1 life-year = 100k sum(df$nv_200k_hkdm) # assuming value of 1 life-year = 200k # Overall weighted net value, standardised to WHO reference population sum(df$nv_50k_who) # assuming value of 1 life-year = 50k sum(df$nv_100k_who) # assuming value of 1 life-year = 100k sum(df$nv_200k_who) # assuming value of 1 life-year = 200k
#' Continuum removal by removing the convex hull #' #' This function applies a linearly interpolated convex hull to the spectra and returns the ratio of the deviation to the hull value #' #' @param spectra a matrix or data.frame with wavelengths as columns and spectra as rows #' @export chBLC <- function(spectra){ interval <- seq_len(ncol(spectra)) hull_spectra <- matrix(NA,ncol=ncol(spectra),nrow=nrow(spectra)) for (i in seq_len(nrow(spectra))){ tempSpect <- as.matrix(spectra[i,]) data1 <- sortedXyData(interval, tempSpect) ## calculate convex hull c_hull <- chull(data1) ## get the appropriate region: the points of the polygon over the spectra # Create vector which wraps around c_hull <- c(c_hull, c_hull) # remove all points before the first one. c_hull <- c_hull[which.min(c_hull):length(c_hull)] # Go until the first end c_hull <- c_hull[1:which.max(c_hull)] ## calculate linear approximation between hull points linear_approx <- approx(data1[c_hull,], xout = interval, method = 'linear', ties = 'mean') ## calculate the deviation from the convex hull hull_spectra[i,] <- ( linear_approx[[2]] - tempSpect )/linear_approx[[2]]} colnames(hull_spectra) <- colnames(spectra) return(hull_spectra)}
/R/chBLC.R
no_license
mmbaye/spectroscopy
R
false
false
1,287
r
#' Continuum removal by removing the convex hull #' #' This function applies a linearly interpolated convex hull to the spectra and returns the ratio of the deviation to the hull value #' #' @param spectra a matrix or data.frame with wavelengths as columns and spectra as rows #' @export chBLC <- function(spectra){ interval <- seq_len(ncol(spectra)) hull_spectra <- matrix(NA,ncol=ncol(spectra),nrow=nrow(spectra)) for (i in seq_len(nrow(spectra))){ tempSpect <- as.matrix(spectra[i,]) data1 <- sortedXyData(interval, tempSpect) ## calculate convex hull c_hull <- chull(data1) ## get the appropriate region: the points of the polygon over the spectra # Create vector which wraps around c_hull <- c(c_hull, c_hull) # remove all points before the first one. c_hull <- c_hull[which.min(c_hull):length(c_hull)] # Go until the first end c_hull <- c_hull[1:which.max(c_hull)] ## calculate linear approximation between hull points linear_approx <- approx(data1[c_hull,], xout = interval, method = 'linear', ties = 'mean') ## calculate the deviation from the convex hull hull_spectra[i,] <- ( linear_approx[[2]] - tempSpect )/linear_approx[[2]]} colnames(hull_spectra) <- colnames(spectra) return(hull_spectra)}
# Global ------------------------------------------------------------------ library(shiny) library(shinymanager) # data.frame with credentials info credentials <- data.frame( user = c("fanny", "victor", "benoit"), password = c("azerty", "12345", "azerty"), comment = c("alsace", "auvergne", "bretagne"), applications = c("app1;shiny-sqlite", "app1", "shiny-sqlite"), age = c(14, 20, 30), expire = as.Date(c(NA, "2019-12-31", "2019-12-31")), admin = c(TRUE, TRUE, FALSE), stringsAsFactors = FALSE ) if (!file.exists("credentials.sqlite")) { create_db(credentials_data = credentials, sqlite_path = "credentials.sqlite", passphrase = "supersecret") }
/dev/shiny-sqlite/global.R
no_license
abhik1368/shinymanager
R
false
false
672
r
# Global ------------------------------------------------------------------ library(shiny) library(shinymanager) # data.frame with credentials info credentials <- data.frame( user = c("fanny", "victor", "benoit"), password = c("azerty", "12345", "azerty"), comment = c("alsace", "auvergne", "bretagne"), applications = c("app1;shiny-sqlite", "app1", "shiny-sqlite"), age = c(14, 20, 30), expire = as.Date(c(NA, "2019-12-31", "2019-12-31")), admin = c(TRUE, TRUE, FALSE), stringsAsFactors = FALSE ) if (!file.exists("credentials.sqlite")) { create_db(credentials_data = credentials, sqlite_path = "credentials.sqlite", passphrase = "supersecret") }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/elementApi.r \name{element$createElement} \alias{element$createElement} \title{Create a child element.} \arguments{ \item{webId}{The ID of the parent element on which to create the element.} \item{piElement}{The new element definition.} } \value{ The element was created. The response's Location header is a link to the element. } \description{ Create a child element. }
/man/element-cash-createElement.Rd
permissive
aj9253/PI-Web-API-Client-R
R
false
true
450
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/elementApi.r \name{element$createElement} \alias{element$createElement} \title{Create a child element.} \arguments{ \item{webId}{The ID of the parent element on which to create the element.} \item{piElement}{The new element definition.} } \value{ The element was created. The response's Location header is a link to the element. } \description{ Create a child element. }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/check4Gaps.R \name{check4Gaps} \alias{check4Gaps} \title{Check for Discontinuities (Gaps) in a Vector & Optionally Make a Plot} \usage{ check4Gaps(x, y = NULL, silent = FALSE, tol = NULL, ...) } \arguments{ \item{x}{A numeric vector to be checked for gaps.} \item{y}{An optional vector of \code{y}-values which correspond to the \code{x} values. Only used in \code{ChemoSpec}. If provided, a plot will be made in the style of a \code{\link[ChemoSpec]{Spectra}} object showing the gap(s).} \item{silent}{Logical indicating a "no gap" message should not be reported to the console. Important because \code{check4Gaps} is called iteratively by other functions.} \item{tol}{A number indicating the tolerance for checking to see if the step between successive \code{x} values are the same. Depending upon how the \code{x} values are stored and rounded, you may need to change the value of \code{tol} to avoid flagging trivial "gaps". If \code{NULL}, a value is chosen which is just above the median difference between \code{x} values.} \item{\dots}{Other parameters to be passed to the plot routines if \code{y} is provided, e.g. \code{xlim}.} } \value{ A data frame giving the data chunks found, with one chunk per row. Also a plot if {y} is provided. In the event there are no gaps found, a data frame with one row is returned. The data frame has columns as follows: \item{beg.freq }{The first frequency value in a given data chunk.} \item{end.freq }{The last frequency value in a given data chunk.} \item{size }{The length (in frequency units) of the data chunk.} \item{beg.indx }{The index of the first frequency value in the data chunk.} \item{end.indx }{The index of the last frequency value in the data chunk.} } \description{ The basic procedure is to compare x[n + 1] - x[n] for successive values of n. When this value jumps, there is a gap which is flagged. \code{beg.indx} and \code{end.indx} will always be contiguous as indices must be; it is the \code{x} values that jump or have the gap. The indices are provided as they are more convenient in some programming contexts. If not assigned, the result appears at the console. } \examples{ x <- seq(0, 2 * pi, 0.1) y <- sin(x) remove <- c(8:11, 40:45) x <- x[-remove] y <- y[-remove] gaps <- check4Gaps(x, tol = 0.11) # tol just larger than orig spacing gaps gaps <- check4Gaps(x, y, tol = 0.11) # show a plot if y given } \seealso{ \code{\link{sumSpectra}} which make extensive use of this function. } \author{ Bryan A. Hanson, DePauw University. } \keyword{utilities}
/man/check4Gaps.Rd
no_license
Tejasvigupta/ChemoSpecUtils
R
false
true
2,619
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/check4Gaps.R \name{check4Gaps} \alias{check4Gaps} \title{Check for Discontinuities (Gaps) in a Vector & Optionally Make a Plot} \usage{ check4Gaps(x, y = NULL, silent = FALSE, tol = NULL, ...) } \arguments{ \item{x}{A numeric vector to be checked for gaps.} \item{y}{An optional vector of \code{y}-values which correspond to the \code{x} values. Only used in \code{ChemoSpec}. If provided, a plot will be made in the style of a \code{\link[ChemoSpec]{Spectra}} object showing the gap(s).} \item{silent}{Logical indicating a "no gap" message should not be reported to the console. Important because \code{check4Gaps} is called iteratively by other functions.} \item{tol}{A number indicating the tolerance for checking to see if the step between successive \code{x} values are the same. Depending upon how the \code{x} values are stored and rounded, you may need to change the value of \code{tol} to avoid flagging trivial "gaps". If \code{NULL}, a value is chosen which is just above the median difference between \code{x} values.} \item{\dots}{Other parameters to be passed to the plot routines if \code{y} is provided, e.g. \code{xlim}.} } \value{ A data frame giving the data chunks found, with one chunk per row. Also a plot if {y} is provided. In the event there are no gaps found, a data frame with one row is returned. The data frame has columns as follows: \item{beg.freq }{The first frequency value in a given data chunk.} \item{end.freq }{The last frequency value in a given data chunk.} \item{size }{The length (in frequency units) of the data chunk.} \item{beg.indx }{The index of the first frequency value in the data chunk.} \item{end.indx }{The index of the last frequency value in the data chunk.} } \description{ The basic procedure is to compare x[n + 1] - x[n] for successive values of n. When this value jumps, there is a gap which is flagged. \code{beg.indx} and \code{end.indx} will always be contiguous as indices must be; it is the \code{x} values that jump or have the gap. The indices are provided as they are more convenient in some programming contexts. If not assigned, the result appears at the console. } \examples{ x <- seq(0, 2 * pi, 0.1) y <- sin(x) remove <- c(8:11, 40:45) x <- x[-remove] y <- y[-remove] gaps <- check4Gaps(x, tol = 0.11) # tol just larger than orig spacing gaps gaps <- check4Gaps(x, y, tol = 0.11) # show a plot if y given } \seealso{ \code{\link{sumSpectra}} which make extensive use of this function. } \author{ Bryan A. Hanson, DePauw University. } \keyword{utilities}
# Correlation # Prepare the Data mydata <- mtcars[, c(1,3,4,5,6,7)] head(mydata) # Compute the correlation matrix - cor() cormat <- round(cor(mydata),2) head(cormat) # Create the correlation heatmap with ggplot2 # The package reshape is required to melt the correlation matrix. library(reshape2) melted_cormat <- melt(cormat) head(melted_cormat) #The function geom_tile()[ggplot2 package] is used to visualize the correlation matrix : library(ggplot2) ggplot(data = melted_cormat, aes(x=Var1, y=Var2, fill=value)) + geom_tile() #Doesnot Look Great.. Let's Enhance the viz! #Get the lower and upper triangles of the correlation matrix ## a correlation matrix has redundant information. We'll use the functions below to set half of it to NA. # Get lower triangle of the correlation matrix get_lower_tri<-function(cormat){ cormat[upper.tri(cormat)] <- NA return(cormat) } # Get upper triangle of the correlation matrix get_upper_tri <- function(cormat){ cormat[lower.tri(cormat)]<- NA return(cormat) } upper_tri <- get_upper_tri(cormat) upper_tri # Finished correlation matrix heatmap ## Melt the correlation data and drop the rows with NA values # Melt the correlation matrix library(reshape2) melted_cormat <- melt(upper_tri, na.rm = TRUE) # Heatmap library(ggplot2) ggplot(data = melted_cormat, aes(Var2, Var1, fill = value))+ geom_tile(color = "white")+ scale_fill_gradient2(low = "blue", high = "red", mid = "white", midpoint = 0, limit = c(-1,1), space = "Lab", name="Pearson\nCorrelation") + theme_minimal()+ theme(axis.text.x = element_text(angle = 45, vjust = 1, size = 12, hjust = 1))+ coord_fixed() # negative correlations are in blue color and positive correlations in red. # The function scale_fill_gradient2 is used with the argument limit = c(-1,1) as correlation coefficients range from -1 to 1. # coord_fixed() : this function ensures that one unit on the x-axis is the same length as one unit on the y-axis. # Reorder the correlation matrix # This section describes how to reorder the correlation matrix according to the correlation coefficient. # This is useful to identify the hidden pattern in the matrix. # hclust for hierarchical clustering order is used in the example below. reorder_cormat <- function(cormat){ # Use correlation between variables as distance dd <- as.dist((1-cormat)/2) hc <- hclust(dd) cormat <-cormat[hc$order, hc$order] } # Reorder the correlation matrix cormat <- reorder_cormat(cormat) upper_tri <- get_upper_tri(cormat) # Melt the correlation matrix melted_cormat <- melt(upper_tri, na.rm = TRUE) # Create a ggheatmap ggheatmap <- ggplot(melted_cormat, aes(Var2, Var1, fill = value))+ geom_tile(color = "white")+ scale_fill_gradient2(low = "blue", high = "red", mid = "white", midpoint = 0, limit = c(-1,1), space = "Lab", name="Pearson\nCorrelation") + theme_minimal()+ # minimal theme theme(axis.text.x = element_text(angle = 45, vjust = 1, size = 12, hjust = 1))+ coord_fixed() # Print the heatmap print(ggheatmap) #Add correlation coefficients on the heatmap ## Use geom_text() to add the correlation coefficients on the graph ## Use a blank theme (remove axis labels, panel grids and background, and axis ticks) ## Use guides() to change the position of the legend title ggheatmap + geom_text(aes(Var2, Var1, label = value), color = "black", size = 4) + theme( axis.title.x = element_blank(), axis.title.y = element_blank(), panel.grid.major = element_blank(), panel.border = element_blank(), panel.background = element_blank(), axis.ticks = element_blank(), legend.justification = c(1, 0), legend.position = c(0.6, 0.7), legend.direction = "horizontal")+ guides(fill = guide_colorbar(barwidth = 7, barheight = 1, title.position = "top", title.hjust = 0.5))
/5.2 DSA - R - EDA -Correlation Heatmap - 6 Dec 2020.R
no_license
sridhar-v/R-Codes
R
false
false
4,125
r
# Correlation # Prepare the Data mydata <- mtcars[, c(1,3,4,5,6,7)] head(mydata) # Compute the correlation matrix - cor() cormat <- round(cor(mydata),2) head(cormat) # Create the correlation heatmap with ggplot2 # The package reshape is required to melt the correlation matrix. library(reshape2) melted_cormat <- melt(cormat) head(melted_cormat) #The function geom_tile()[ggplot2 package] is used to visualize the correlation matrix : library(ggplot2) ggplot(data = melted_cormat, aes(x=Var1, y=Var2, fill=value)) + geom_tile() #Doesnot Look Great.. Let's Enhance the viz! #Get the lower and upper triangles of the correlation matrix ## a correlation matrix has redundant information. We'll use the functions below to set half of it to NA. # Get lower triangle of the correlation matrix get_lower_tri<-function(cormat){ cormat[upper.tri(cormat)] <- NA return(cormat) } # Get upper triangle of the correlation matrix get_upper_tri <- function(cormat){ cormat[lower.tri(cormat)]<- NA return(cormat) } upper_tri <- get_upper_tri(cormat) upper_tri # Finished correlation matrix heatmap ## Melt the correlation data and drop the rows with NA values # Melt the correlation matrix library(reshape2) melted_cormat <- melt(upper_tri, na.rm = TRUE) # Heatmap library(ggplot2) ggplot(data = melted_cormat, aes(Var2, Var1, fill = value))+ geom_tile(color = "white")+ scale_fill_gradient2(low = "blue", high = "red", mid = "white", midpoint = 0, limit = c(-1,1), space = "Lab", name="Pearson\nCorrelation") + theme_minimal()+ theme(axis.text.x = element_text(angle = 45, vjust = 1, size = 12, hjust = 1))+ coord_fixed() # negative correlations are in blue color and positive correlations in red. # The function scale_fill_gradient2 is used with the argument limit = c(-1,1) as correlation coefficients range from -1 to 1. # coord_fixed() : this function ensures that one unit on the x-axis is the same length as one unit on the y-axis. # Reorder the correlation matrix # This section describes how to reorder the correlation matrix according to the correlation coefficient. # This is useful to identify the hidden pattern in the matrix. # hclust for hierarchical clustering order is used in the example below. reorder_cormat <- function(cormat){ # Use correlation between variables as distance dd <- as.dist((1-cormat)/2) hc <- hclust(dd) cormat <-cormat[hc$order, hc$order] } # Reorder the correlation matrix cormat <- reorder_cormat(cormat) upper_tri <- get_upper_tri(cormat) # Melt the correlation matrix melted_cormat <- melt(upper_tri, na.rm = TRUE) # Create a ggheatmap ggheatmap <- ggplot(melted_cormat, aes(Var2, Var1, fill = value))+ geom_tile(color = "white")+ scale_fill_gradient2(low = "blue", high = "red", mid = "white", midpoint = 0, limit = c(-1,1), space = "Lab", name="Pearson\nCorrelation") + theme_minimal()+ # minimal theme theme(axis.text.x = element_text(angle = 45, vjust = 1, size = 12, hjust = 1))+ coord_fixed() # Print the heatmap print(ggheatmap) #Add correlation coefficients on the heatmap ## Use geom_text() to add the correlation coefficients on the graph ## Use a blank theme (remove axis labels, panel grids and background, and axis ticks) ## Use guides() to change the position of the legend title ggheatmap + geom_text(aes(Var2, Var1, label = value), color = "black", size = 4) + theme( axis.title.x = element_blank(), axis.title.y = element_blank(), panel.grid.major = element_blank(), panel.border = element_blank(), panel.background = element_blank(), axis.ticks = element_blank(), legend.justification = c(1, 0), legend.position = c(0.6, 0.7), legend.direction = "horizontal")+ guides(fill = guide_colorbar(barwidth = 7, barheight = 1, title.position = "top", title.hjust = 0.5))
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/SwarnTopTags.R \name{SwarnTopTags} \alias{SwarnTopTags} \title{This function selects the top genes in scRNA-seq data.} \usage{ SwarnTopTags(results, m) } \arguments{ \item{results}{A output data frame from \code{SwarnSeqLRT} or \code{SwarnUnadjLRT} which contains the unclassified differential expression analysis results.} \item{m}{A scalar representing the number of top performing genes to be selected from the scRNA-seq data.} } \value{ A list of the top genes along with their statistics. } \description{ This function selects the top genes in scRNA-seq data. } \examples{ #Load the test count data, spike-in counts and spike-in concentration data for SwarnSeq. data(TestData) counts <- TestData$CountData Spikes <- TestData$SpikeCounts SpikeConc <- TestData$SpikeConc #specifying the group information, the group 1 and 2 have two hundred cells each. group <- c(rep(1, 200), rep(2, 200)) #Specifying the cluster memberships of the cells in columns of countData. cellcluster <- c(rep(1, 60), rep(2, 40), rep(3, 50), rep(4, 50), rep(5, 30), rep(6, 90), rep(7, 80)) #results <- SwarnSeqLRT(CountData=counts, RNAspike.use=TRUE, spikes=Spikes, spike.conc=SpikeConc, #parallel=FALSE, norm.method="TMM", group=group, CellCluster=cellcluster, #CellAuxil=NULL, maxit=500, eps=1e-10, #muoffset=NULL, phioffset=NULL, weights=NULL, p.adjust.method="hochberg") #DEGtypes <- SwarnTopTags(results, m = 100) } \seealso{ \code{\link{SwarnSeqLRT}}, for the detection of differentially expressed genes from scRNA-seq data. \code{\link{TestData}}, a test dataset for SwarnSeq. } \author{ Samarendra Das }
/man/SwarnTopTags.Rd
no_license
sam-uofl/SwarnSeq
R
false
true
1,810
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/SwarnTopTags.R \name{SwarnTopTags} \alias{SwarnTopTags} \title{This function selects the top genes in scRNA-seq data.} \usage{ SwarnTopTags(results, m) } \arguments{ \item{results}{A output data frame from \code{SwarnSeqLRT} or \code{SwarnUnadjLRT} which contains the unclassified differential expression analysis results.} \item{m}{A scalar representing the number of top performing genes to be selected from the scRNA-seq data.} } \value{ A list of the top genes along with their statistics. } \description{ This function selects the top genes in scRNA-seq data. } \examples{ #Load the test count data, spike-in counts and spike-in concentration data for SwarnSeq. data(TestData) counts <- TestData$CountData Spikes <- TestData$SpikeCounts SpikeConc <- TestData$SpikeConc #specifying the group information, the group 1 and 2 have two hundred cells each. group <- c(rep(1, 200), rep(2, 200)) #Specifying the cluster memberships of the cells in columns of countData. cellcluster <- c(rep(1, 60), rep(2, 40), rep(3, 50), rep(4, 50), rep(5, 30), rep(6, 90), rep(7, 80)) #results <- SwarnSeqLRT(CountData=counts, RNAspike.use=TRUE, spikes=Spikes, spike.conc=SpikeConc, #parallel=FALSE, norm.method="TMM", group=group, CellCluster=cellcluster, #CellAuxil=NULL, maxit=500, eps=1e-10, #muoffset=NULL, phioffset=NULL, weights=NULL, p.adjust.method="hochberg") #DEGtypes <- SwarnTopTags(results, m = 100) } \seealso{ \code{\link{SwarnSeqLRT}}, for the detection of differentially expressed genes from scRNA-seq data. \code{\link{TestData}}, a test dataset for SwarnSeq. } \author{ Samarendra Das }
## Matrix inversion is usually a costly computation and there may be some ## benefit to caching the inverse of a matrix rather than compute it repeatedly. ## stores a matrix and caches its inverse. ## This function creates a special "matrix" object that can cache its inverse. makeCacheMatrix <- function(x = matrix()) { inv <- NULL set <- function(y) { x <<- y inv <<- NULL } get <- function() x setInverse <- function(inverse) inv <<- inverse getInverse <- function() inv list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) } ## This function computes the inverse of the special "matrix" returned ## by makeCacheMatrix above. 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, ...) { ## Return a matrix that is the inverse of 'x' inv <- x$getInverse() if (!is.null(inv)) { message("getting cached data") return(inv) } mat <- x$get() inv <- solve(mat, ...) x$setInverse(inv) inv }
/cachematrix.R
no_license
rtodoc/ProgrammingAssignment2
R
false
false
1,105
r
## Matrix inversion is usually a costly computation and there may be some ## benefit to caching the inverse of a matrix rather than compute it repeatedly. ## stores a matrix and caches its inverse. ## This function creates a special "matrix" object that can cache its inverse. makeCacheMatrix <- function(x = matrix()) { inv <- NULL set <- function(y) { x <<- y inv <<- NULL } get <- function() x setInverse <- function(inverse) inv <<- inverse getInverse <- function() inv list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) } ## This function computes the inverse of the special "matrix" returned ## by makeCacheMatrix above. 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, ...) { ## Return a matrix that is the inverse of 'x' inv <- x$getInverse() if (!is.null(inv)) { message("getting cached data") return(inv) } mat <- x$get() inv <- solve(mat, ...) x$setInverse(inv) inv }
#' @keywords internal .pkgSnapshot <- function(instPkgs, instVers, packageVersionFile = "._packageVersionsAuto.txt") { browser(expr = exists("aaaa")) inst <- data.frame(instPkgs, instVers = unlist(instVers), stringsAsFactors = FALSE) write.table(inst, file = packageVersionFile, row.names = FALSE) inst } #' @importFrom utils chooseCRANmirror #' @keywords internal getCRANrepos <- function(repos = NULL) { if (is.null(repos)) { repos <- getOption("repos")["CRAN"] } # still might be imprecise repository, specifically "" if (isTRUE("" == repos)) { repos <- "@CRAN@" } # if @CRAN@, and non interactive session if (isTRUE("@CRAN@" %in% repos)) { cranRepo <- Sys.getenv("CRAN_REPO") repos <- if (nzchar(cranRepo)) { cranRepo } else { chooseCRANmirror2() ## sets repo option getOption("repos")["CRAN"] } } return(repos) } #' @importFrom utils chooseCRANmirror #' @keywords internal chooseCRANmirror2 <- function() { if (isInteractive()) { chooseCRANmirror() } else { chooseCRANmirror(ind = 1) ## https://cloud.r-project.org } } #' Add a prefix or suffix to the basename part of a file path #' #' Prepend (or postpend) a filename with a prefix (or suffix). #' If the directory name of the file cannot be ascertained from its path, #' it is assumed to be in the current working directory. #' #' @param f A character string giving the name/path of a file. #' @param prefix A character string to prepend to the filename. #' @param suffix A character string to postpend to the filename. #' #' @author Jean Marchal and Alex Chubaty #' @export #' @importFrom tools file_ext file_path_sans_ext #' @rdname prefix #' #' @examples #' # file's full path is specified (i.e., dirname is known) #' myFile <- file.path("~/data", "file.tif") #' .prefix(myFile, "small_") ## "/home/username/data/small_file.tif" #' .suffix(myFile, "_cropped") ## "/home/username/data/myFile_cropped.shp" #' #' # file's full path is not specified #' .prefix("myFile.shp", "small") ## "./small_myFile.shp" #' .suffix("myFile.shp", "_cropped") ## "./myFile_cropped.shp" #' .prefix <- function(f, prefix = "") { file.path(dirname(f), paste0(prefix, basename(f))) } #' @export #' @name suffix #' @rdname prefix .suffix <- function(f, suffix = "") { file.path(dirname(f), paste0(tools::file_path_sans_ext(basename(f)), suffix, ".", tools::file_ext(f))) } #' Get a unique name for a given study area #' #' Digest a spatial object to get a unique character string (hash) of the study area. #' Use \code{.suffix()} to append the hash to a filename, e.g., when using \code{filename2} in \code{prepInputs}. #' #' @param studyArea Spatial object. #' @param ... Other arguments (not currently used) #' #' @export #' @importFrom digest digest setGeneric("studyAreaName", function(studyArea, ...) { standardGeneric("studyAreaName") }) #' @export #' @rdname studyAreaName setMethod( "studyAreaName", signature = "SpatialPolygonsDataFrame", definition = function (studyArea, ...) { digest(studyArea[, -c(1:ncol(studyArea))], algo = "xxhash64") ## TODO: use `...` to pass `algo` }) #' Identify which formals to a function are not in the current \code{...} #' #' Advanced use. #' #' @keywords internal #' @export #' @param fun A function #' @param ... The ... from inside a function. Will be ignored if \code{dots} is #' provided explicitly. #' @param dots Optional. If this is provided via say \code{dots = list(...)}, #' then this will cause the \code{...} to be ignored. .formalsNotInCurrentDots <- function(fun, ..., dots) { if (!missing(dots)) { out <- names(dots)[!(names(dots) %in% names(formals(fun)))] } else { out <- names(list(...))[!(names(list(...)) %in% names(formals(fun)))] } out } #' @keywords internal rndstr <- function(n = 1, len = 8) { unlist(lapply(character(n), function(x) { x <- paste0(sample(c(0:9, letters, LETTERS), size = len, replace = TRUE), collapse = "") })) } #' Alternative to \code{interactive()} for unit testing #' #' This is a suggestion from #' \url{https://github.com/MangoTheCat/blog-with-mock/blob/master/Blogpost1.Rmd} #' as a way to test interactive code in unit tests. Basically, in the unit tests, #' we use \code{testthat::with_mock}, and inside that we redefine \code{isInteractive} #' just for the test. In all other times, this returns the same things as #' \code{interactive()}. #' @keywords internal #' @examples #' \dontrun{ #' testthat::with_mock( #' `isInteractive` = function() {browser(); TRUE}, #' { #' tmpdir <- tempdir() #' aa <- Cache(rnorm, 1, cacheRepo = tmpdir, userTags = "something2") #' # Test clearCache -- has an internal isInteractive() call #' clearCache(tmpdir, ask = FALSE) #' }) #' } isInteractive <- function() interactive() #' A version of \code{base::basename} that is \code{NULL} resistant #' #' Returns \code{NULL} if x is \code{NULL}, otherwise, as \code{basename}. #' #' @param x A character vector of paths #' @export #' @return Same as \code{\link[base]{basename}} #' basename2 <- function(x) { if (is.null(x)) { NULL } else { basename(x) } } #' A wrapper around \code{try} that retries on failure #' #' This is useful for functions that are "flaky", such as \code{curl}, which may fail for unknown #' reasons that do not persist. #' #' @details #' Based on \url{https://github.com/jennybc/googlesheets/issues/219#issuecomment-195218525}. #' #' @param expr Quoted expression to run, i.e., \code{quote(...)} #' @param retries Numeric. The maximum number of retries. #' @param envir The environment in which to evaluate the quoted expression, default #' to \code{parent.frame(1)} #' @param exponentialDecayBase Numeric > 1.0. The delay between #' successive retries will be \code{runif(1, min = 0, max = exponentialDecayBase ^ i - 1)} #' where \code{i} is the retry number (i.e., follows \code{seq_len(retries)}) #' @param silent Logical indicating whether to \code{try} silently. #' #' @export retry <- function(expr, envir = parent.frame(), retries = 5, exponentialDecayBase = 1.3, silent = TRUE) { if (exponentialDecayBase <= 1) stop("exponentialDecayBase must be greater than 1.0") for (i in seq_len(retries)) { if (!(is.call(expr) || is.name(expr))) warning("expr is not a quoted expression") result <- try(expr = eval(expr, envir = envir), silent = silent) if (inherits(result, "try-error")) { backoff <- runif(n = 1, min = 0, max = exponentialDecayBase^i - 1) if (backoff > 3) { message("Waiting for ", round(backoff, 1), " seconds to retry; the attempt is failing") } Sys.sleep(backoff) } else { break } } if (inherits(result, "try-error")) { stop(result, "\nFailed after ", retries, " attempts.") } else { return(result) } } #' Test whether system is Windows #' #' This is used so that unit tests can override this using \code{testthat::with_mock}. #' @keywords internal isWindows <- function() identical(.Platform$OS.type, "windows") #' Provide standard messaging for missing package dependencies #' #' This provides a standard message format for missing packages, e.g., #' detected via \code{requireNamespace}. #' #' @export #' @param pkg Character string indicating name of package required #' @param minVersion Character string indicating minimum version of package #' that is needed #' @param messageStart A character string with a prefix of message to provide .requireNamespace <- function(pkg = "methods", minVersion = NULL, messageStart = paste0(pkg, if (!is.null(minVersion)) paste0("(>=", minVersion, ")"), " is required. Try: ")) { need <- FALSE if (suppressWarnings(!requireNamespace(pkg, quietly = TRUE, warn.conflicts = FALSE))) { need <- TRUE } else { if (isTRUE(packageVersion(pkg) < minVersion)) need <- TRUE } if (need) { message(messageStart, "install.packages('",pkg,"')") } !need }
/R/helpers.R
no_license
mdsumner/reproducible
R
false
false
8,067
r
#' @keywords internal .pkgSnapshot <- function(instPkgs, instVers, packageVersionFile = "._packageVersionsAuto.txt") { browser(expr = exists("aaaa")) inst <- data.frame(instPkgs, instVers = unlist(instVers), stringsAsFactors = FALSE) write.table(inst, file = packageVersionFile, row.names = FALSE) inst } #' @importFrom utils chooseCRANmirror #' @keywords internal getCRANrepos <- function(repos = NULL) { if (is.null(repos)) { repos <- getOption("repos")["CRAN"] } # still might be imprecise repository, specifically "" if (isTRUE("" == repos)) { repos <- "@CRAN@" } # if @CRAN@, and non interactive session if (isTRUE("@CRAN@" %in% repos)) { cranRepo <- Sys.getenv("CRAN_REPO") repos <- if (nzchar(cranRepo)) { cranRepo } else { chooseCRANmirror2() ## sets repo option getOption("repos")["CRAN"] } } return(repos) } #' @importFrom utils chooseCRANmirror #' @keywords internal chooseCRANmirror2 <- function() { if (isInteractive()) { chooseCRANmirror() } else { chooseCRANmirror(ind = 1) ## https://cloud.r-project.org } } #' Add a prefix or suffix to the basename part of a file path #' #' Prepend (or postpend) a filename with a prefix (or suffix). #' If the directory name of the file cannot be ascertained from its path, #' it is assumed to be in the current working directory. #' #' @param f A character string giving the name/path of a file. #' @param prefix A character string to prepend to the filename. #' @param suffix A character string to postpend to the filename. #' #' @author Jean Marchal and Alex Chubaty #' @export #' @importFrom tools file_ext file_path_sans_ext #' @rdname prefix #' #' @examples #' # file's full path is specified (i.e., dirname is known) #' myFile <- file.path("~/data", "file.tif") #' .prefix(myFile, "small_") ## "/home/username/data/small_file.tif" #' .suffix(myFile, "_cropped") ## "/home/username/data/myFile_cropped.shp" #' #' # file's full path is not specified #' .prefix("myFile.shp", "small") ## "./small_myFile.shp" #' .suffix("myFile.shp", "_cropped") ## "./myFile_cropped.shp" #' .prefix <- function(f, prefix = "") { file.path(dirname(f), paste0(prefix, basename(f))) } #' @export #' @name suffix #' @rdname prefix .suffix <- function(f, suffix = "") { file.path(dirname(f), paste0(tools::file_path_sans_ext(basename(f)), suffix, ".", tools::file_ext(f))) } #' Get a unique name for a given study area #' #' Digest a spatial object to get a unique character string (hash) of the study area. #' Use \code{.suffix()} to append the hash to a filename, e.g., when using \code{filename2} in \code{prepInputs}. #' #' @param studyArea Spatial object. #' @param ... Other arguments (not currently used) #' #' @export #' @importFrom digest digest setGeneric("studyAreaName", function(studyArea, ...) { standardGeneric("studyAreaName") }) #' @export #' @rdname studyAreaName setMethod( "studyAreaName", signature = "SpatialPolygonsDataFrame", definition = function (studyArea, ...) { digest(studyArea[, -c(1:ncol(studyArea))], algo = "xxhash64") ## TODO: use `...` to pass `algo` }) #' Identify which formals to a function are not in the current \code{...} #' #' Advanced use. #' #' @keywords internal #' @export #' @param fun A function #' @param ... The ... from inside a function. Will be ignored if \code{dots} is #' provided explicitly. #' @param dots Optional. If this is provided via say \code{dots = list(...)}, #' then this will cause the \code{...} to be ignored. .formalsNotInCurrentDots <- function(fun, ..., dots) { if (!missing(dots)) { out <- names(dots)[!(names(dots) %in% names(formals(fun)))] } else { out <- names(list(...))[!(names(list(...)) %in% names(formals(fun)))] } out } #' @keywords internal rndstr <- function(n = 1, len = 8) { unlist(lapply(character(n), function(x) { x <- paste0(sample(c(0:9, letters, LETTERS), size = len, replace = TRUE), collapse = "") })) } #' Alternative to \code{interactive()} for unit testing #' #' This is a suggestion from #' \url{https://github.com/MangoTheCat/blog-with-mock/blob/master/Blogpost1.Rmd} #' as a way to test interactive code in unit tests. Basically, in the unit tests, #' we use \code{testthat::with_mock}, and inside that we redefine \code{isInteractive} #' just for the test. In all other times, this returns the same things as #' \code{interactive()}. #' @keywords internal #' @examples #' \dontrun{ #' testthat::with_mock( #' `isInteractive` = function() {browser(); TRUE}, #' { #' tmpdir <- tempdir() #' aa <- Cache(rnorm, 1, cacheRepo = tmpdir, userTags = "something2") #' # Test clearCache -- has an internal isInteractive() call #' clearCache(tmpdir, ask = FALSE) #' }) #' } isInteractive <- function() interactive() #' A version of \code{base::basename} that is \code{NULL} resistant #' #' Returns \code{NULL} if x is \code{NULL}, otherwise, as \code{basename}. #' #' @param x A character vector of paths #' @export #' @return Same as \code{\link[base]{basename}} #' basename2 <- function(x) { if (is.null(x)) { NULL } else { basename(x) } } #' A wrapper around \code{try} that retries on failure #' #' This is useful for functions that are "flaky", such as \code{curl}, which may fail for unknown #' reasons that do not persist. #' #' @details #' Based on \url{https://github.com/jennybc/googlesheets/issues/219#issuecomment-195218525}. #' #' @param expr Quoted expression to run, i.e., \code{quote(...)} #' @param retries Numeric. The maximum number of retries. #' @param envir The environment in which to evaluate the quoted expression, default #' to \code{parent.frame(1)} #' @param exponentialDecayBase Numeric > 1.0. The delay between #' successive retries will be \code{runif(1, min = 0, max = exponentialDecayBase ^ i - 1)} #' where \code{i} is the retry number (i.e., follows \code{seq_len(retries)}) #' @param silent Logical indicating whether to \code{try} silently. #' #' @export retry <- function(expr, envir = parent.frame(), retries = 5, exponentialDecayBase = 1.3, silent = TRUE) { if (exponentialDecayBase <= 1) stop("exponentialDecayBase must be greater than 1.0") for (i in seq_len(retries)) { if (!(is.call(expr) || is.name(expr))) warning("expr is not a quoted expression") result <- try(expr = eval(expr, envir = envir), silent = silent) if (inherits(result, "try-error")) { backoff <- runif(n = 1, min = 0, max = exponentialDecayBase^i - 1) if (backoff > 3) { message("Waiting for ", round(backoff, 1), " seconds to retry; the attempt is failing") } Sys.sleep(backoff) } else { break } } if (inherits(result, "try-error")) { stop(result, "\nFailed after ", retries, " attempts.") } else { return(result) } } #' Test whether system is Windows #' #' This is used so that unit tests can override this using \code{testthat::with_mock}. #' @keywords internal isWindows <- function() identical(.Platform$OS.type, "windows") #' Provide standard messaging for missing package dependencies #' #' This provides a standard message format for missing packages, e.g., #' detected via \code{requireNamespace}. #' #' @export #' @param pkg Character string indicating name of package required #' @param minVersion Character string indicating minimum version of package #' that is needed #' @param messageStart A character string with a prefix of message to provide .requireNamespace <- function(pkg = "methods", minVersion = NULL, messageStart = paste0(pkg, if (!is.null(minVersion)) paste0("(>=", minVersion, ")"), " is required. Try: ")) { need <- FALSE if (suppressWarnings(!requireNamespace(pkg, quietly = TRUE, warn.conflicts = FALSE))) { need <- TRUE } else { if (isTRUE(packageVersion(pkg) < minVersion)) need <- TRUE } if (need) { message(messageStart, "install.packages('",pkg,"')") } !need }
testlist <- list(a = 1684825385L, b = 676545880L, x = NA_integer_) result <- do.call(grattan:::anyOutside,testlist) str(result)
/grattan/inst/testfiles/anyOutside/libFuzzer_anyOutside/anyOutside_valgrind_files/1610388256-test.R
no_license
akhikolla/updated-only-Issues
R
false
false
127
r
testlist <- list(a = 1684825385L, b = 676545880L, x = NA_integer_) result <- do.call(grattan:::anyOutside,testlist) str(result)
# # test-subset_dfdates.R # ---------------------- # # Test suite for testing function subset_dfdates # # context("Testing function: subset_dfdates()") library(testthat) test_that("Testing basic functionality", { library(testthat) library(mlStocks) df = Earnings[, c(1,2,13)] timeframe = "2011-01-03/2011-01-21" datecol = 2 keep_NAs = FALSE #--------------------------------------------------- # Test to include both start and end boundaries #--------------------------------------------------- bounds_rm = c(FALSE, FALSE) dftest <- subset_dfdates(df, timeframe = timeframe, datecol = datecol, keep_NAs = keep_NAs, bounds_rm = bounds_rm) N <- nrow(dftest) expect_equal(dftest[1, "dtBuy"], as.Date("2011-01-03")) # include first date expect_equal(dftest[N, "dtBuy"], as.Date("2011-01-21")) # include last date #--------------------------------------------------- # Test to include start but not end boundary #--------------------------------------------------- bounds_rm <- c(FALSE, TRUE) dftest <- subset_dfdates(df, timeframe = timeframe, datecol = datecol, keep_NAs = keep_NAs, bounds_rm = bounds_rm) N <- nrow(dftest) expect_equal(dftest[1, "dtBuy"], as.Date("2011-01-03")) # include first date expect_equal(dftest[N, "dtBuy"], as.Date("2011-01-20")) # EXclude last date #--------------------------------------------------- # Test to include start but exclude end boundary #--------------------------------------------------- bounds_rm <- c(TRUE, FALSE) dftest <- subset_dfdates(df, timeframe = timeframe, datecol = datecol, keep_NAs = keep_NAs, bounds_rm = bounds_rm) N <- nrow(dftest) expect_equal(dftest[1, "dtBuy"], as.Date("2011-01-04")) # EXclude first date expect_equal(dftest[N, "dtBuy"], as.Date("2011-01-21")) # include last date #--------------------------------------------------- # Test to include start but exclude end boundary #--------------------------------------------------- bounds_rm <- c(TRUE, TRUE) dftest <- subset_dfdates(df, timeframe = timeframe, datecol = datecol, keep_NAs = keep_NAs, bounds_rm = bounds_rm) N <- nrow(dftest) expect_equal(dftest[1, "dtBuy"], as.Date("2011-01-04")) # EXclude first date expect_equal(dftest[N, "dtBuy"], as.Date("2011-01-20")) # EXclude last date })
/tests/testthat/test-subset_dfdates.R
no_license
jeanmarcgp/mlStocks
R
false
false
2,347
r
# # test-subset_dfdates.R # ---------------------- # # Test suite for testing function subset_dfdates # # context("Testing function: subset_dfdates()") library(testthat) test_that("Testing basic functionality", { library(testthat) library(mlStocks) df = Earnings[, c(1,2,13)] timeframe = "2011-01-03/2011-01-21" datecol = 2 keep_NAs = FALSE #--------------------------------------------------- # Test to include both start and end boundaries #--------------------------------------------------- bounds_rm = c(FALSE, FALSE) dftest <- subset_dfdates(df, timeframe = timeframe, datecol = datecol, keep_NAs = keep_NAs, bounds_rm = bounds_rm) N <- nrow(dftest) expect_equal(dftest[1, "dtBuy"], as.Date("2011-01-03")) # include first date expect_equal(dftest[N, "dtBuy"], as.Date("2011-01-21")) # include last date #--------------------------------------------------- # Test to include start but not end boundary #--------------------------------------------------- bounds_rm <- c(FALSE, TRUE) dftest <- subset_dfdates(df, timeframe = timeframe, datecol = datecol, keep_NAs = keep_NAs, bounds_rm = bounds_rm) N <- nrow(dftest) expect_equal(dftest[1, "dtBuy"], as.Date("2011-01-03")) # include first date expect_equal(dftest[N, "dtBuy"], as.Date("2011-01-20")) # EXclude last date #--------------------------------------------------- # Test to include start but exclude end boundary #--------------------------------------------------- bounds_rm <- c(TRUE, FALSE) dftest <- subset_dfdates(df, timeframe = timeframe, datecol = datecol, keep_NAs = keep_NAs, bounds_rm = bounds_rm) N <- nrow(dftest) expect_equal(dftest[1, "dtBuy"], as.Date("2011-01-04")) # EXclude first date expect_equal(dftest[N, "dtBuy"], as.Date("2011-01-21")) # include last date #--------------------------------------------------- # Test to include start but exclude end boundary #--------------------------------------------------- bounds_rm <- c(TRUE, TRUE) dftest <- subset_dfdates(df, timeframe = timeframe, datecol = datecol, keep_NAs = keep_NAs, bounds_rm = bounds_rm) N <- nrow(dftest) expect_equal(dftest[1, "dtBuy"], as.Date("2011-01-04")) # EXclude first date expect_equal(dftest[N, "dtBuy"], as.Date("2011-01-20")) # EXclude last date })
library("neuRosim") # Valeurs constantes dim <- c(53,63,46) nscan <- 421 TR <- 2 total.time <- nscan * TR onsets.F <- c((10:30),(100:120),(160:180),(190:210),(250:270),(280:300),(400:420))*TR # onsets.H <- c((40:60),(70:90),(130:150),(220:240),(310:330),(340:360),(370:390))*TR # lis<-(1:nscan) event<-lis event[lis]<-'Rest' event[(onsets.F/TR)+1]<-'Face' event[(onsets.H/TR)+1]<-'House' write(event,'D:/sim/event_sim.csv') region.1a.radius <- 3 region.1b.radius <- 3 region.4a.radius <- 3 region.2a.radius <-5 region.2b.radius <- 5 region.3a.radius <- 4 region.3b.radius <- 4 region.4b.radius <- 3 onsets <- list(onsets.H, onsets.F) onsets.regions <- list(onsets, onsets, onsets, onsets, onsets,onsets, onsets, onsets) dur <- list(0, 0) dur.regions <- list(dur, dur, dur, dur, dur, dur, dur, dur) # Valeurs qui varient selon sujet library("oro.nifti") mask <- readNIfTI("D:/mask.nii.gz") Haxby <- readNIfTI("D:/restbaseline.nii.gz") baseline <- apply(Haxby@.Data, 1:3, mean) r1a.center<- c(12,21,9)#110 r1a.d<- c(239, 258) r1b.center<- c(39,21,9)#697 r1b.d<- c(229,247) r2a.center<- c(23,7,16)#93 r2a.d<- c(225,225) r2b.center<- c(30,7,16)#46 r2b.d<- c(252,252) r3a.center<- c(31,12,13)#200 r3a.d<- c(309,291) r3b.center<- c(21,13,13)#716 r3b.d<- c(333,323) r4a.center<- c(35,21,13)#860 r4a.d<- c(335,314) r4b.center<- c(17,22,12)#680 r4b.d<- c(308,288) snr.or <- 4.3 for(s in 2:5) { # Assign value to each subject region.1a.center <- round(r1a.center*runif(3,min=0.9, max=1.1),0) region.1b.center <- round(r1b.center*runif(3,min=0.9, max=1.1),0) region.2a.center <- round(r2a.center*runif(3,min=0.99, max=1.01),0) region.2b.center <- round(r2b.center*runif(3,min=0.99, max=1.01),0) region.3a.center <- round(r3a.center*runif(3,min=0.9, max=1.1),0) region.3b.center <- round(r3b.center*runif(3,min=0.9, max=1.1),0) region.4a.center <- round(r4a.center*runif(3,min=0.9, max=1.1),0) region.4b.center <- round(r4b.center*runif(3,min=0.9, max=1.1),0) region.1a.d <- list(r1a.d[1]*runif(1,min=0.95, max=1.05),r1a.d[2]*runif(1,min=0.95, max=1.05)) region.1b.d <- list(r1b.d[1]*runif(1,min=0.95, max=1.05),r1b.d[2]*runif(1,min=0.95, max=1.05)) region.2a.d <- list(r2a.d[1]*runif(1,min=0.95, max=1.05),r2a.d[2]*runif(1,min=0.95, max=1.05)) region.2b.d <- list(r2b.d[1]*runif(1,min=0.95, max=1.05),r2b.d[2]*runif(1,min=0.95, max=1.05)) region.3a.d <- list(r3a.d[1]*runif(1,min=0.95, max=1.05),r3a.d[2]*runif(1,min=0.95, max=1.05)) region.3b.d <- list(r3b.d[1]*runif(1,min=0.95, max=1.05),r3b.d[2]*runif(1,min=0.95, max=1.05)) region.4a.d<- list(r4a.d[1]*runif(1,min=0.95, max=1.05),r4a.d[2]*runif(1,min=0.95, max=1.05)) region.4b.d<- list(r4b.d[1]*runif(1,min=0.95, max=1.05),r4b.d[2]*runif(1,min=0.95, max=1.05)) effect <- list(region.1a.d, region.1b.d, region.2a.d, region.2b.d,region.3a.d,region.3b.d,region.4a.d,region.4b.d) snr <- snr.or*runif(1,min=0.9, max=1.1) design <- simprepTemporal(regions = 8, onsets = onsets.regions, durations = dur.regions, hrf = "Balloon", TR = TR, totaltime = total.time, effectsize = effect) spatial <- simprepSpatial(regions = 8, coord = list(region.1a.center, region.1b.center, region.2a.center, region.2b.center, region.3a.center, region.3b.center,region.4a.center, region.4b.center), radius = c(region.1a.radius, region.1b.radius, region.2a.radius, region.2b.radius, region.3a.radius, region.3b.radius, region.4a.radius, region.4b.radius), form = "sphere", fading = 0.01) name_val = paste('D:/sim/sim',s,'val.txt', sep='_') write.table(rbind(region.1a.center,region.1b.center,region.2a.center, region.2b.center,region.3a.center,region.3b.center,region.4a.center, region.4b.center,region.1a.d,region.1b.d,region.2a.d , region.2b.d,region.3a.d,region.3b.d,region.4a.d,region.4b.d,snr),file=name_val) for(n in 1:50) { sim.data <- simVOLfmri(design = design, image = spatial, SNR = snr, noise = "mixture" , type = "rician", rho.temp = c(0.142, 0.108, 0.084), base= baseline, rho.spat = 0.4, w = c(0.05, 0.1, 0.01, 0.09, 0.05, 0.7), dim = dim, nscan = nscan, vee = 0,template=mask, spat = "gaussRF") sim.nifti <- nifti(img = sim.data, dim=c(53,63,46,nscan),pixdim = c(-1,3,3,3,2,0,0,0), xyzt_units=10) name = paste('D:/sim/sim',s,n, sep='_') writeNIfTI(sim.nifti,name) } }
/SimulationR/neuRosim_loop_haxby.R
no_license
brain-bzh/gsp-learn
R
false
false
4,268
r
library("neuRosim") # Valeurs constantes dim <- c(53,63,46) nscan <- 421 TR <- 2 total.time <- nscan * TR onsets.F <- c((10:30),(100:120),(160:180),(190:210),(250:270),(280:300),(400:420))*TR # onsets.H <- c((40:60),(70:90),(130:150),(220:240),(310:330),(340:360),(370:390))*TR # lis<-(1:nscan) event<-lis event[lis]<-'Rest' event[(onsets.F/TR)+1]<-'Face' event[(onsets.H/TR)+1]<-'House' write(event,'D:/sim/event_sim.csv') region.1a.radius <- 3 region.1b.radius <- 3 region.4a.radius <- 3 region.2a.radius <-5 region.2b.radius <- 5 region.3a.radius <- 4 region.3b.radius <- 4 region.4b.radius <- 3 onsets <- list(onsets.H, onsets.F) onsets.regions <- list(onsets, onsets, onsets, onsets, onsets,onsets, onsets, onsets) dur <- list(0, 0) dur.regions <- list(dur, dur, dur, dur, dur, dur, dur, dur) # Valeurs qui varient selon sujet library("oro.nifti") mask <- readNIfTI("D:/mask.nii.gz") Haxby <- readNIfTI("D:/restbaseline.nii.gz") baseline <- apply(Haxby@.Data, 1:3, mean) r1a.center<- c(12,21,9)#110 r1a.d<- c(239, 258) r1b.center<- c(39,21,9)#697 r1b.d<- c(229,247) r2a.center<- c(23,7,16)#93 r2a.d<- c(225,225) r2b.center<- c(30,7,16)#46 r2b.d<- c(252,252) r3a.center<- c(31,12,13)#200 r3a.d<- c(309,291) r3b.center<- c(21,13,13)#716 r3b.d<- c(333,323) r4a.center<- c(35,21,13)#860 r4a.d<- c(335,314) r4b.center<- c(17,22,12)#680 r4b.d<- c(308,288) snr.or <- 4.3 for(s in 2:5) { # Assign value to each subject region.1a.center <- round(r1a.center*runif(3,min=0.9, max=1.1),0) region.1b.center <- round(r1b.center*runif(3,min=0.9, max=1.1),0) region.2a.center <- round(r2a.center*runif(3,min=0.99, max=1.01),0) region.2b.center <- round(r2b.center*runif(3,min=0.99, max=1.01),0) region.3a.center <- round(r3a.center*runif(3,min=0.9, max=1.1),0) region.3b.center <- round(r3b.center*runif(3,min=0.9, max=1.1),0) region.4a.center <- round(r4a.center*runif(3,min=0.9, max=1.1),0) region.4b.center <- round(r4b.center*runif(3,min=0.9, max=1.1),0) region.1a.d <- list(r1a.d[1]*runif(1,min=0.95, max=1.05),r1a.d[2]*runif(1,min=0.95, max=1.05)) region.1b.d <- list(r1b.d[1]*runif(1,min=0.95, max=1.05),r1b.d[2]*runif(1,min=0.95, max=1.05)) region.2a.d <- list(r2a.d[1]*runif(1,min=0.95, max=1.05),r2a.d[2]*runif(1,min=0.95, max=1.05)) region.2b.d <- list(r2b.d[1]*runif(1,min=0.95, max=1.05),r2b.d[2]*runif(1,min=0.95, max=1.05)) region.3a.d <- list(r3a.d[1]*runif(1,min=0.95, max=1.05),r3a.d[2]*runif(1,min=0.95, max=1.05)) region.3b.d <- list(r3b.d[1]*runif(1,min=0.95, max=1.05),r3b.d[2]*runif(1,min=0.95, max=1.05)) region.4a.d<- list(r4a.d[1]*runif(1,min=0.95, max=1.05),r4a.d[2]*runif(1,min=0.95, max=1.05)) region.4b.d<- list(r4b.d[1]*runif(1,min=0.95, max=1.05),r4b.d[2]*runif(1,min=0.95, max=1.05)) effect <- list(region.1a.d, region.1b.d, region.2a.d, region.2b.d,region.3a.d,region.3b.d,region.4a.d,region.4b.d) snr <- snr.or*runif(1,min=0.9, max=1.1) design <- simprepTemporal(regions = 8, onsets = onsets.regions, durations = dur.regions, hrf = "Balloon", TR = TR, totaltime = total.time, effectsize = effect) spatial <- simprepSpatial(regions = 8, coord = list(region.1a.center, region.1b.center, region.2a.center, region.2b.center, region.3a.center, region.3b.center,region.4a.center, region.4b.center), radius = c(region.1a.radius, region.1b.radius, region.2a.radius, region.2b.radius, region.3a.radius, region.3b.radius, region.4a.radius, region.4b.radius), form = "sphere", fading = 0.01) name_val = paste('D:/sim/sim',s,'val.txt', sep='_') write.table(rbind(region.1a.center,region.1b.center,region.2a.center, region.2b.center,region.3a.center,region.3b.center,region.4a.center, region.4b.center,region.1a.d,region.1b.d,region.2a.d , region.2b.d,region.3a.d,region.3b.d,region.4a.d,region.4b.d,snr),file=name_val) for(n in 1:50) { sim.data <- simVOLfmri(design = design, image = spatial, SNR = snr, noise = "mixture" , type = "rician", rho.temp = c(0.142, 0.108, 0.084), base= baseline, rho.spat = 0.4, w = c(0.05, 0.1, 0.01, 0.09, 0.05, 0.7), dim = dim, nscan = nscan, vee = 0,template=mask, spat = "gaussRF") sim.nifti <- nifti(img = sim.data, dim=c(53,63,46,nscan),pixdim = c(-1,3,3,3,2,0,0,0), xyzt_units=10) name = paste('D:/sim/sim',s,n, sep='_') writeNIfTI(sim.nifti,name) } }
#' @title Print \code{'gainstable'} Object #' #' @description S3 print method to print \code{"gainstable"} object. #' #' #' @param x An object of class \code{"gainstable"}, created with either #' \code{\link{gainstable.default}} or \code{\link{gainstable.rocit}}. #' #' @param maxdigit How many digits after decimal to be printed. #' #' @param ... \code{NULL}. Used for S3 generic/method consistency. #' #' @examples #' data("Loan") #' class <- Loan$Status #' score <- Loan$Score #' rocit_emp <- rocit(score = score, class = class, negref = "FP") #' # ---------------------------------------------------------------- #' gtable8 <- gainstable(rocit_emp, ngroup = 8) #' print(gtable8) #' print(gtable8, maxdigit = 4) #' @method print gainstable #' @export print.gainstable <- function(x, maxdigit = 3, ... = NULL) { df <- as.data.frame( cbind( Bucket = x$Bucket, Obs = x$Obs, CObs = x$CObs, Depth = x$Depth, Resp = x$Resp, CResp = x$CResp, RespRate = x$RespRate, CRespRate = x$CRespRate, CCapRate = x$CCapRate, Lift = x$Lift, CLift = x$CLift ) ) ncol <- ncol(df) tempindex <- NULL -> rounddigits for (i in 1:ncol) { tempindex <- df[, i] %% 1 rounddigits[i] <- ifelse((max(nchar(tempindex)) > maxdigit), T, F) } longcols <- which(rounddigits) for (i in longcols) { df[, i] <- round(df[, i], maxdigit) } print(df) }
/R/printGainsTable.R
no_license
cran/ROCit
R
false
false
1,479
r
#' @title Print \code{'gainstable'} Object #' #' @description S3 print method to print \code{"gainstable"} object. #' #' #' @param x An object of class \code{"gainstable"}, created with either #' \code{\link{gainstable.default}} or \code{\link{gainstable.rocit}}. #' #' @param maxdigit How many digits after decimal to be printed. #' #' @param ... \code{NULL}. Used for S3 generic/method consistency. #' #' @examples #' data("Loan") #' class <- Loan$Status #' score <- Loan$Score #' rocit_emp <- rocit(score = score, class = class, negref = "FP") #' # ---------------------------------------------------------------- #' gtable8 <- gainstable(rocit_emp, ngroup = 8) #' print(gtable8) #' print(gtable8, maxdigit = 4) #' @method print gainstable #' @export print.gainstable <- function(x, maxdigit = 3, ... = NULL) { df <- as.data.frame( cbind( Bucket = x$Bucket, Obs = x$Obs, CObs = x$CObs, Depth = x$Depth, Resp = x$Resp, CResp = x$CResp, RespRate = x$RespRate, CRespRate = x$CRespRate, CCapRate = x$CCapRate, Lift = x$Lift, CLift = x$CLift ) ) ncol <- ncol(df) tempindex <- NULL -> rounddigits for (i in 1:ncol) { tempindex <- df[, i] %% 1 rounddigits[i] <- ifelse((max(nchar(tempindex)) > maxdigit), T, F) } longcols <- which(rounddigits) for (i in longcols) { df[, i] <- round(df[, i], maxdigit) } print(df) }
%% %% WARNING! DO NOT EDIT! %% This file is automatically generated from pc-gammacount.R %% \name{pc.gammacount} \alias{inla.pc.gammacount} \alias{pc.gammacount} \alias{pc.rgammacount} \alias{inla.pc.rgammacount} \alias{pc.dgammacount} \alias{inla.pc.dgammacount} \alias{pc.pgammacount} \alias{inla.pc.pgammacount} \alias{pc.qgammacount} \alias{inla.pc.qgammacount} \title{Utility functions for the PC prior for the \code{gammacount} likelihood} \description{Functions to evaluate, sample, compute quantiles and percentiles of the PC prior for the \code{gammacount} likelihood} \usage{ inla.pc.rgammacount(n, lambda = 1) inla.pc.dgammacount(x, lambda = 1, log = FALSE) inla.pc.qgammacount(p, lambda = 1) inla.pc.pgammacount(q, lambda = 1) } \arguments{ \item{n}{Number of observations} \item{lambda}{The rate parameter (see Details)} \item{x}{Evaluation points} \item{log}{Logical. Return the density in natural or log-scale.} \item{p}{Vector of probabilities} \item{q}{Vector of quantiles} } \details{ This gives the PC prior for the \code{gammacount} likelihood, which is the PC prior for \code{a} in \code{Gamma(a, 1)} where \code{Gamma(1, 1)} is the base model. } \value{%% \code{inla.pc.dgammacount} gives the density, \code{inla.pc.pgammacount} gives the distribution function, \code{inla.pc.qgammacount} gives the quantile function, and \code{inla.pc.rgammacount} generates random deviates. } \seealso{inla.doc("pc.gammacount")} \author{Havard Rue \email{hrue@r-inla.org}} \examples{ x = inla.pc.rgammacount(100, lambda = 1) d = inla.pc.dgammacount(x, lambda = 1) x = inla.pc.qgammacount(0.5, lambda = 1) inla.pc.pgammacount(x, lambda = 1) }
/man/pc-gammacount.Rd
no_license
jdsimkin04/shinyinla
R
false
false
1,727
rd
%% %% WARNING! DO NOT EDIT! %% This file is automatically generated from pc-gammacount.R %% \name{pc.gammacount} \alias{inla.pc.gammacount} \alias{pc.gammacount} \alias{pc.rgammacount} \alias{inla.pc.rgammacount} \alias{pc.dgammacount} \alias{inla.pc.dgammacount} \alias{pc.pgammacount} \alias{inla.pc.pgammacount} \alias{pc.qgammacount} \alias{inla.pc.qgammacount} \title{Utility functions for the PC prior for the \code{gammacount} likelihood} \description{Functions to evaluate, sample, compute quantiles and percentiles of the PC prior for the \code{gammacount} likelihood} \usage{ inla.pc.rgammacount(n, lambda = 1) inla.pc.dgammacount(x, lambda = 1, log = FALSE) inla.pc.qgammacount(p, lambda = 1) inla.pc.pgammacount(q, lambda = 1) } \arguments{ \item{n}{Number of observations} \item{lambda}{The rate parameter (see Details)} \item{x}{Evaluation points} \item{log}{Logical. Return the density in natural or log-scale.} \item{p}{Vector of probabilities} \item{q}{Vector of quantiles} } \details{ This gives the PC prior for the \code{gammacount} likelihood, which is the PC prior for \code{a} in \code{Gamma(a, 1)} where \code{Gamma(1, 1)} is the base model. } \value{%% \code{inla.pc.dgammacount} gives the density, \code{inla.pc.pgammacount} gives the distribution function, \code{inla.pc.qgammacount} gives the quantile function, and \code{inla.pc.rgammacount} generates random deviates. } \seealso{inla.doc("pc.gammacount")} \author{Havard Rue \email{hrue@r-inla.org}} \examples{ x = inla.pc.rgammacount(100, lambda = 1) d = inla.pc.dgammacount(x, lambda = 1) x = inla.pc.qgammacount(0.5, lambda = 1) inla.pc.pgammacount(x, lambda = 1) }
conc.fun <-function(sample_data, standard_coeffs, chamber_volumes, directory, gas, print=FALSE){ #Note: edited on 8/28/15 to include a fixed standard coefficient slope and intercept collar_surface_area <- 0.064 #meters std_curve_nums <- unique(standard_coeffs$Std_Curve_Num) for(j in 1:nrow(sample_data)) { sample_data$Concentration[j] <- sapply(sample_data$Area[j], function(x) x*standard_coeffs$Slope + standard_coeffs$Intercept) if (is.na(sample_data$Concentration[j])){ sample_data$Concentration[j]=NA }else if(sample_data$Concentration[j]<0){ sample_data$Concentration[j]=0 } } sample_data$Time <- as.numeric(sample_data$Time) sample_data$Time_min <- sapply(sample_data$Time, function(x) x/60) conc_data <- sample_data }
/conc.fun.R
no_license
SoilWaterLab/Septic-GHGs
R
false
false
755
r
conc.fun <-function(sample_data, standard_coeffs, chamber_volumes, directory, gas, print=FALSE){ #Note: edited on 8/28/15 to include a fixed standard coefficient slope and intercept collar_surface_area <- 0.064 #meters std_curve_nums <- unique(standard_coeffs$Std_Curve_Num) for(j in 1:nrow(sample_data)) { sample_data$Concentration[j] <- sapply(sample_data$Area[j], function(x) x*standard_coeffs$Slope + standard_coeffs$Intercept) if (is.na(sample_data$Concentration[j])){ sample_data$Concentration[j]=NA }else if(sample_data$Concentration[j]<0){ sample_data$Concentration[j]=0 } } sample_data$Time <- as.numeric(sample_data$Time) sample_data$Time_min <- sapply(sample_data$Time, function(x) x/60) conc_data <- sample_data }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/visNetworkEditor.R \name{visNetworkEditor-module} \alias{visNetworkEditor-module} \alias{visNetworkEditorServer} \alias{visNetworkEditorUI} \title{Module shiny for visualize and customize and get back a \code{visNetwork} object. Using the javascript interface \link{visConfigure}.} \usage{ visNetworkEditorServer(input, output, session, object, filter = shiny::reactive(NULL), showButton = shiny::reactive(NULL)) visNetworkEditorUI(id, quitButton = FALSE, height = "700px") } \arguments{ \item{input}{\code{list} shiny input} \item{output}{\code{list}, shiny output} \item{session}{\code{list}, shiny session} \item{object}{a \code{visNetwork} object. Must be a reactive.} \item{filter}{: see \link{visConfigure}. Must be a reactive.} \item{showButton}{: see \link{visConfigure}. Must be a reactive.} \item{id}{\code{character} id of module, linked to \link{visNetworkEditorUI}} \item{quitButton}{: logical. Add a button for quit shiny and get back network in R ?} \item{height}{: height of the configuration div. Defaut to "700px"} } \description{ Module shiny for visualize and customize and get back a \code{visNetwork} object. Using the javascript interface \link{visConfigure}. } \examples{ \dontrun{ nodes <- data.frame(id = 1:3, label = paste("Node", 1:3)) edges <- data.frame(from = c(1,2), to = c(1,3), label = paste("Edge", 1:2)) network <- visNetwork(nodes, edges) shiny::shinyApp(ui = shiny::fluidPage( visNetworkEditorUI(id = "id1")), server = function(input, output, session) { shiny::callModule(visNetworkEditorServer, "id1", object = shiny::reactive(network)) }) } } \references{ See online documentation \url{http://datastorm-open.github.io/visNetwork/} } \seealso{ \link{visConfigure}, \link{visTree}, \link{visNetworkEditor} }
/man/visNetworkEditor-module.Rd
no_license
42-Discworld/visNetwork
R
false
true
1,901
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/visNetworkEditor.R \name{visNetworkEditor-module} \alias{visNetworkEditor-module} \alias{visNetworkEditorServer} \alias{visNetworkEditorUI} \title{Module shiny for visualize and customize and get back a \code{visNetwork} object. Using the javascript interface \link{visConfigure}.} \usage{ visNetworkEditorServer(input, output, session, object, filter = shiny::reactive(NULL), showButton = shiny::reactive(NULL)) visNetworkEditorUI(id, quitButton = FALSE, height = "700px") } \arguments{ \item{input}{\code{list} shiny input} \item{output}{\code{list}, shiny output} \item{session}{\code{list}, shiny session} \item{object}{a \code{visNetwork} object. Must be a reactive.} \item{filter}{: see \link{visConfigure}. Must be a reactive.} \item{showButton}{: see \link{visConfigure}. Must be a reactive.} \item{id}{\code{character} id of module, linked to \link{visNetworkEditorUI}} \item{quitButton}{: logical. Add a button for quit shiny and get back network in R ?} \item{height}{: height of the configuration div. Defaut to "700px"} } \description{ Module shiny for visualize and customize and get back a \code{visNetwork} object. Using the javascript interface \link{visConfigure}. } \examples{ \dontrun{ nodes <- data.frame(id = 1:3, label = paste("Node", 1:3)) edges <- data.frame(from = c(1,2), to = c(1,3), label = paste("Edge", 1:2)) network <- visNetwork(nodes, edges) shiny::shinyApp(ui = shiny::fluidPage( visNetworkEditorUI(id = "id1")), server = function(input, output, session) { shiny::callModule(visNetworkEditorServer, "id1", object = shiny::reactive(network)) }) } } \references{ See online documentation \url{http://datastorm-open.github.io/visNetwork/} } \seealso{ \link{visConfigure}, \link{visTree}, \link{visNetworkEditor} }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/breakpoint.density.r \docType{class} \name{breaks-class} \alias{breaks-class} \alias{breaks} \title{Class to store breakpoint annotations in association with genomic features (e.g. gene loci)} \arguments{ \item{breaks}{(data.table): the breakpoint info containing data.table, this will be occupied by the CNV segmentation data in the case of cnv.break.annot or SV for sv.break.annot. Unique random string rownames are added to the returned breaks data.frame.} \item{burden}{(numeric): a vector containing the total number of breakpoints in each sample} \item{param}{(list): a list of parametres provided} } \value{ an instance of the class 'breaks' containing breakpoint and breakpoint burden information } \description{ Class to store breakpoint annotations in association with genomic features (e.g. gene loci) }
/man/breaks-class.Rd
no_license
gonzolgarcia/svpluscnv
R
false
true
895
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/breakpoint.density.r \docType{class} \name{breaks-class} \alias{breaks-class} \alias{breaks} \title{Class to store breakpoint annotations in association with genomic features (e.g. gene loci)} \arguments{ \item{breaks}{(data.table): the breakpoint info containing data.table, this will be occupied by the CNV segmentation data in the case of cnv.break.annot or SV for sv.break.annot. Unique random string rownames are added to the returned breaks data.frame.} \item{burden}{(numeric): a vector containing the total number of breakpoints in each sample} \item{param}{(list): a list of parametres provided} } \value{ an instance of the class 'breaks' containing breakpoint and breakpoint burden information } \description{ Class to store breakpoint annotations in association with genomic features (e.g. gene loci) }
RDA2 A 2 133632 131840 1026 1 9 5 times 13 500 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 1026 1 9 7 states0 526 4 -1 -2 5 10 1026 1 9 5 names 16 4 9 1 W 9 1 D 9 1 S 9 1 K 254 1026 1 9 5 parms 531 13 14 1 5 14 1 1 14 1 1 14 1 1 14 1 1 14 1 0 14 1 1 14 1 1 14 1 1 14 1 1 14 1 1 14 1 1 14 1 0.5 1026 1023 16 13 9 5 alpha 9 4 beta 9 5 gamma 9 5 theta 9 4 kmax 9 1 m 9 3 l.B 9 3 k.B 9 3 l.K 9 3 k.K 9 4 gmax 9 2 gs 9 3 wpg 254 1026 1 9 8 modelout 782 22 1 1.470241976126563 -1 -1 -2 -2 5 -4.047275267139263e+98 10 4.047275267139263e+98 -1.625 -1.5 -0.625 -0.5 -3.125 -2.5 -45 1.638043708799719e+197 0.9845583760209703 -9.03069178521563e+97 0 0 1026 1 9 3 dim 13 2 2 11 1026 1 9 8 dimnames 19 2 254 16 11 9 4 time 9 1 W 9 1 D 9 1 S 9 1 K 9 1 X 9 1 G 9 1 P 9 1 R 9 1 B 9 1 M 1026 1 9 6 istate 13 21 -1 5000 12348 NA 4 4 0 84 24 NA NA NA NA 39 1 1 NA NA NA NA NA 1026 1 9 6 rstate 14 5 1.262517368508104e-100 1.262517368508104e-100 1.470241976126563 0 1.250031732649044 1026 1 9 5 class 16 2 9 7 deSolve 9 6 matrix 1026 1 9 4 type 16 1 9 5 lsoda 254 254
/Outputs/Modelrun_20110413_134157.R
no_license
Sandy4321/Tree-Death-Physiological-Models
R
false
false
2,896
r
RDA2 A 2 133632 131840 1026 1 9 5 times 13 500 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 1026 1 9 7 states0 526 4 -1 -2 5 10 1026 1 9 5 names 16 4 9 1 W 9 1 D 9 1 S 9 1 K 254 1026 1 9 5 parms 531 13 14 1 5 14 1 1 14 1 1 14 1 1 14 1 1 14 1 0 14 1 1 14 1 1 14 1 1 14 1 1 14 1 1 14 1 1 14 1 0.5 1026 1023 16 13 9 5 alpha 9 4 beta 9 5 gamma 9 5 theta 9 4 kmax 9 1 m 9 3 l.B 9 3 k.B 9 3 l.K 9 3 k.K 9 4 gmax 9 2 gs 9 3 wpg 254 1026 1 9 8 modelout 782 22 1 1.470241976126563 -1 -1 -2 -2 5 -4.047275267139263e+98 10 4.047275267139263e+98 -1.625 -1.5 -0.625 -0.5 -3.125 -2.5 -45 1.638043708799719e+197 0.9845583760209703 -9.03069178521563e+97 0 0 1026 1 9 3 dim 13 2 2 11 1026 1 9 8 dimnames 19 2 254 16 11 9 4 time 9 1 W 9 1 D 9 1 S 9 1 K 9 1 X 9 1 G 9 1 P 9 1 R 9 1 B 9 1 M 1026 1 9 6 istate 13 21 -1 5000 12348 NA 4 4 0 84 24 NA NA NA NA 39 1 1 NA NA NA NA NA 1026 1 9 6 rstate 14 5 1.262517368508104e-100 1.262517368508104e-100 1.470241976126563 0 1.250031732649044 1026 1 9 5 class 16 2 9 7 deSolve 9 6 matrix 1026 1 9 4 type 16 1 9 5 lsoda 254 254
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/RcppExports.R \name{binMin} \alias{binMin} \title{Function that computes a minimum value for each bin} \usage{ binMin(x, n) } \arguments{ \item{x}{NumericVector - vector of values of a bin} \item{n}{intiger - number of bins} } \description{ Function that computes a minimum value for each bin } \keyword{internal}
/man/binMin.Rd
no_license
alexg9010/genomation
R
false
true
393
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/RcppExports.R \name{binMin} \alias{binMin} \title{Function that computes a minimum value for each bin} \usage{ binMin(x, n) } \arguments{ \item{x}{NumericVector - vector of values of a bin} \item{n}{intiger - number of bins} } \description{ Function that computes a minimum value for each bin } \keyword{internal}
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/num-rpd.R \name{rpd} \alias{rpd} \alias{rpd.data.frame} \alias{rpd_vec} \title{Ratio of performance to deviation} \usage{ rpd(data, ...) \method{rpd}{data.frame}(data, truth, estimate, na_rm = TRUE, ...) rpd_vec(truth, estimate, na_rm = TRUE, ...) } \arguments{ \item{data}{A \code{data.frame} containing the \code{truth} and \code{estimate} columns.} \item{...}{Not currently used.} \item{truth}{The column identifier for the true results (that is \code{numeric}). This should be an unquoted column name although this argument is passed by expression and supports \link[rlang:quasiquotation]{quasiquotation} (you can unquote column names). For \code{_vec()} functions, a \code{numeric} vector.} \item{estimate}{The column identifier for the predicted results (that is also \code{numeric}). As with \code{truth} this can be specified different ways but the primary method is to use an unquoted variable name. For \code{_vec()} functions, a \code{numeric} vector.} \item{na_rm}{A \code{logical} value indicating whether \code{NA} values should be stripped before the computation proceeds.} } \value{ A \code{tibble} with columns \code{.metric}, \code{.estimator}, and \code{.estimate} and 1 row of values. For grouped data frames, the number of rows returned will be the same as the number of groups. For \code{rpd_vec()}, a single \code{numeric} value (or \code{NA}). } \description{ These functions are appropriate for cases where the model outcome is a numeric. The ratio of performance to deviation (\code{\link[=rpd]{rpd()}}) and the ratio of performance to inter-quartile (\code{\link[=rpiq]{rpiq()}}) are both measures of consistency/correlation between observed and predicted values (and not of accuracy). } \details{ In the field of spectroscopy in particular, the ratio of performance to deviation (RPD) has been used as the standard way to report the quality of a model. It is the ratio between the standard deviation of a variable and the standard error of prediction of that variable by a given model. However, its systematic use has been criticized by several authors, since using the standard deviation to represent the spread of a variable can be misleading on skewed dataset. The ratio of performance to inter-quartile has been introduced by Bellon-Maurel et al. (2010) to address some of these issues, and generalise the RPD to non-normally distributed variables. } \examples{ # Supply truth and predictions as bare column names rpd(solubility_test, solubility, prediction) library(dplyr) set.seed(1234) size <- 100 times <- 10 # create 10 resamples solubility_resampled <- bind_rows( replicate( n = times, expr = sample_n(solubility_test, size, replace = TRUE), simplify = FALSE ), .id = "resample" ) # Compute the metric by group metric_results <- solubility_resampled \%>\% group_by(resample) \%>\% rpd(solubility, prediction) metric_results # Resampled mean estimate metric_results \%>\% summarise(avg_estimate = mean(.estimate)) } \references{ Williams, P.C. (1987) Variables affecting near-infrared reflectance spectroscopic analysis. In: Near Infrared Technology in the Agriculture and Food Industries. 1st Ed. P.Williams and K.Norris, Eds. Am. Cereal Assoc. Cereal Chem., St. Paul, MN. Bellon-Maurel, V., Fernandez-Ahumada, E., Palagos, B., Roger, J.M. and McBratney, A., (2010). Critical review of chemometric indicators commonly used for assessing the quality of the prediction of soil attributes by NIR spectroscopy. TrAC Trends in Analytical Chemistry, 29(9), pp.1073-1081. } \seealso{ The closely related inter-quartile metric: \code{\link[=rpiq]{rpiq()}} Other numeric metrics: \code{\link{ccc}}, \code{\link{huber_loss_pseudo}}, \code{\link{huber_loss}}, \code{\link{mae}}, \code{\link{mape}}, \code{\link{mase}}, \code{\link{rmse}}, \code{\link{rpiq}}, \code{\link{rsq_trad}}, \code{\link{rsq}}, \code{\link{smape}} Other consistency metrics: \code{\link{ccc}}, \code{\link{rpiq}}, \code{\link{rsq_trad}}, \code{\link{rsq}} } \author{ Pierre Roudier } \concept{consistency metrics} \concept{numeric metrics}
/man/rpd.Rd
no_license
jyuu/yardstick
R
false
true
4,176
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/num-rpd.R \name{rpd} \alias{rpd} \alias{rpd.data.frame} \alias{rpd_vec} \title{Ratio of performance to deviation} \usage{ rpd(data, ...) \method{rpd}{data.frame}(data, truth, estimate, na_rm = TRUE, ...) rpd_vec(truth, estimate, na_rm = TRUE, ...) } \arguments{ \item{data}{A \code{data.frame} containing the \code{truth} and \code{estimate} columns.} \item{...}{Not currently used.} \item{truth}{The column identifier for the true results (that is \code{numeric}). This should be an unquoted column name although this argument is passed by expression and supports \link[rlang:quasiquotation]{quasiquotation} (you can unquote column names). For \code{_vec()} functions, a \code{numeric} vector.} \item{estimate}{The column identifier for the predicted results (that is also \code{numeric}). As with \code{truth} this can be specified different ways but the primary method is to use an unquoted variable name. For \code{_vec()} functions, a \code{numeric} vector.} \item{na_rm}{A \code{logical} value indicating whether \code{NA} values should be stripped before the computation proceeds.} } \value{ A \code{tibble} with columns \code{.metric}, \code{.estimator}, and \code{.estimate} and 1 row of values. For grouped data frames, the number of rows returned will be the same as the number of groups. For \code{rpd_vec()}, a single \code{numeric} value (or \code{NA}). } \description{ These functions are appropriate for cases where the model outcome is a numeric. The ratio of performance to deviation (\code{\link[=rpd]{rpd()}}) and the ratio of performance to inter-quartile (\code{\link[=rpiq]{rpiq()}}) are both measures of consistency/correlation between observed and predicted values (and not of accuracy). } \details{ In the field of spectroscopy in particular, the ratio of performance to deviation (RPD) has been used as the standard way to report the quality of a model. It is the ratio between the standard deviation of a variable and the standard error of prediction of that variable by a given model. However, its systematic use has been criticized by several authors, since using the standard deviation to represent the spread of a variable can be misleading on skewed dataset. The ratio of performance to inter-quartile has been introduced by Bellon-Maurel et al. (2010) to address some of these issues, and generalise the RPD to non-normally distributed variables. } \examples{ # Supply truth and predictions as bare column names rpd(solubility_test, solubility, prediction) library(dplyr) set.seed(1234) size <- 100 times <- 10 # create 10 resamples solubility_resampled <- bind_rows( replicate( n = times, expr = sample_n(solubility_test, size, replace = TRUE), simplify = FALSE ), .id = "resample" ) # Compute the metric by group metric_results <- solubility_resampled \%>\% group_by(resample) \%>\% rpd(solubility, prediction) metric_results # Resampled mean estimate metric_results \%>\% summarise(avg_estimate = mean(.estimate)) } \references{ Williams, P.C. (1987) Variables affecting near-infrared reflectance spectroscopic analysis. In: Near Infrared Technology in the Agriculture and Food Industries. 1st Ed. P.Williams and K.Norris, Eds. Am. Cereal Assoc. Cereal Chem., St. Paul, MN. Bellon-Maurel, V., Fernandez-Ahumada, E., Palagos, B., Roger, J.M. and McBratney, A., (2010). Critical review of chemometric indicators commonly used for assessing the quality of the prediction of soil attributes by NIR spectroscopy. TrAC Trends in Analytical Chemistry, 29(9), pp.1073-1081. } \seealso{ The closely related inter-quartile metric: \code{\link[=rpiq]{rpiq()}} Other numeric metrics: \code{\link{ccc}}, \code{\link{huber_loss_pseudo}}, \code{\link{huber_loss}}, \code{\link{mae}}, \code{\link{mape}}, \code{\link{mase}}, \code{\link{rmse}}, \code{\link{rpiq}}, \code{\link{rsq_trad}}, \code{\link{rsq}}, \code{\link{smape}} Other consistency metrics: \code{\link{ccc}}, \code{\link{rpiq}}, \code{\link{rsq_trad}}, \code{\link{rsq}} } \author{ Pierre Roudier } \concept{consistency metrics} \concept{numeric metrics}
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/plot_umap.R \name{pal_ggplot} \alias{pal_ggplot} \title{UMAP Palette using ggplot2 colors} \usage{ pal_ggplot(object, group_col, jitter = TRUE, comp = 3, alpha = 0.7) } \arguments{ \item{comp}{integer setting the color complementarity to be used} } \description{ UMAP Palette using ggplot2 colors }
/man/pal_ggplot.Rd
no_license
dbrookeUAB/dbsinglecell
R
false
true
377
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/plot_umap.R \name{pal_ggplot} \alias{pal_ggplot} \title{UMAP Palette using ggplot2 colors} \usage{ pal_ggplot(object, group_col, jitter = TRUE, comp = 3, alpha = 0.7) } \arguments{ \item{comp}{integer setting the color complementarity to be used} } \description{ UMAP Palette using ggplot2 colors }
cols = 40 rows = 36 ncls.grid = 20 ncls.hour = 6 ncls.ia.h.g=-1 ncls.ia.h.l=-1 ncls.ia.h.w=-1 ncls.ia.g.l=-1 ncls.ia.g.w=-1 ncls.ia.l.w=-1 ncls.ia.h.g.l=-1 ncls.ia.h.g.w=-1 ncls.ia.h.l.w=-1 ncls.ia.g.l.w=-1 ncls.ia.h.g.l.w = -1 job.id = 3 job.group.id = 11 regression.formula = paste("cate_l1 ~", "ugrid.id.cid", "+ hour.cid", "+ last.cate_l1", # "+ isweekend", # "+ hour_grid.cid", # "+ hour_last.cid", # "+ hour_weekday.cid", # "+ grid_last.cid", # "+ grid_weekday.cid", # "+ last_weekday.cid", # "+ hour_grid_last.cid", # "+ hour_grid_weekday.cid", # "+ hour_last_weekday.cid", # "+ grid_last_weekday.cid", # "+ hour_grid_last_weekday.cid", "- 1")
/Proj-Experiment/201411-predictability(CEUS)/experiments-3/JOB3/configs.R
no_license
almatrix/work-RProject
R
false
false
785
r
cols = 40 rows = 36 ncls.grid = 20 ncls.hour = 6 ncls.ia.h.g=-1 ncls.ia.h.l=-1 ncls.ia.h.w=-1 ncls.ia.g.l=-1 ncls.ia.g.w=-1 ncls.ia.l.w=-1 ncls.ia.h.g.l=-1 ncls.ia.h.g.w=-1 ncls.ia.h.l.w=-1 ncls.ia.g.l.w=-1 ncls.ia.h.g.l.w = -1 job.id = 3 job.group.id = 11 regression.formula = paste("cate_l1 ~", "ugrid.id.cid", "+ hour.cid", "+ last.cate_l1", # "+ isweekend", # "+ hour_grid.cid", # "+ hour_last.cid", # "+ hour_weekday.cid", # "+ grid_last.cid", # "+ grid_weekday.cid", # "+ last_weekday.cid", # "+ hour_grid_last.cid", # "+ hour_grid_weekday.cid", # "+ hour_last_weekday.cid", # "+ grid_last_weekday.cid", # "+ hour_grid_last_weekday.cid", "- 1")
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/move.R \name{adjacted_move} \alias{adjacted_move} \title{Create adjacent movement matrix} \usage{ adjacted_move(n_rows, n_cols, prob) } \arguments{ \item{n_rows}{number of rows in population matrix} \item{n_cols}{number of columns in population matrix} \item{prob}{probability of movement} } \description{ Create a transition matrix of movement to adjacent cells }
/man/adjacted_move.Rd
no_license
AustralianAntarcticDivision/tagsim
R
false
true
445
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/move.R \name{adjacted_move} \alias{adjacted_move} \title{Create adjacent movement matrix} \usage{ adjacted_move(n_rows, n_cols, prob) } \arguments{ \item{n_rows}{number of rows in population matrix} \item{n_cols}{number of columns in population matrix} \item{prob}{probability of movement} } \description{ Create a transition matrix of movement to adjacent cells }
# get current directory to script folder script.directory <- dirname(sys.frame(1)$ofile) download_dataset <- function() { # download file assignment_file <- "https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip" assignment_dest_file <- "assignment.zip" # downloading file print(paste("Downloading dataset from :", assignment_file)) download.file(assignment_file, destfile = assignment_dest_file, method = "curl") # Unzip files print("Extracting dataset files!") unzip(assignment_dest_file, exdir = ".") if (!file.exists("UCI HAR Dataset")) return (FALSE) else return (TRUE) } # install and load dependent packages install_dependences <- function() { requiredPackages = c('plyr','dplyr') for(p in requiredPackages){ if(!require(p,character.only = TRUE)) install.packages(p) library(p,character.only = TRUE) } } set_working_folder <- function() { if (getwd() != script.directory) { print(paste("Current directory NOT set correctly : ", getwd())) setwd(script.directory) if (getwd() != script.directory) answer <- FALSE else answer <- TRUE print(paste("Setting current directory to correct", answer, ":", getwd())) } else { print(paste("Current directory set correctly : ", getwd())) } } run_analysis <- function() { # load dependent libraries install_dependences() # set working directory set_working_folder() # check if dataset folder exist if (!file.exists("UCI HAR Dataset")) { ans <- readline(prompt="Dataset NOT exist, do you like to download it?") if (ans != "y" && ans != "Y") { stop("Dataset NOT exist, exiting!!!") } # download and unzip dataset if (download_dataset() == TRUE) { print("Dataset downloaded and extracted correctly") } else { stop("Problem occurred when downloading and extracting dataset!") } } print("Dataset exist, starting to analyse it!") # files path activity_labels_file <- ".\\UCI HAR Dataset\\activity_labels.txt" features_labels_file <- ".\\UCI HAR Dataset\\features.txt" x_train_file <- ".\\UCI HAR Dataset\\train\\X_train.txt" y_train_file <- ".\\UCI HAR Dataset\\train\\Y_train.txt" sub_train_file <- ".\\UCI HAR Dataset\\train\\subject_train.txt" train_files <- c(sub_train_file, x_train_file, y_train_file) x_test_file <- ".\\UCI HAR Dataset\\test\\X_test.txt" y_test_file <- ".\\UCI HAR Dataset\\test\\Y_test.txt" sub_test_file <- ".\\UCI HAR Dataset\\test\\subject_test.txt" test_files <- c(sub_test_file, x_test_file, y_test_file) #constants activity_label <- c("activity") subject_label <- c("subject") # load files print("Loading dataset files!") activity_labels <- read.table(activity_labels_file) names(activity_labels) <- c("activity_index", "activity_label") features_labels <- read.table(features_labels_file) names(features_labels) <- c("feature_index", "feature_label") data_train_x <- read.table(x_train_file, col.names = features_labels$feature_label, check.names = FALSE) data_train_y <- read.table(y_train_file, col.names = activity_label) data_train_subjects <- read.table(sub_train_file, col.names = subject_label) data_test_x <- read.table(x_test_file, col.names = features_labels$feature_label, check.names = FALSE) data_test_y <- read.table(y_test_file, col.names = activity_label) data_test_subjects <- read.table(sub_test_file, col.names = subject_label) # select only columns that have mean and std values mean_features_idx <- grep("mean()", features_labels$feature_label) std_features_idx <- grep("std()", features_labels$feature_label) # extract only mean and std columns (sorted) from measurements data_train_x <- data_train_x[,sort(c(mean_features_idx, std_features_idx))] data_test_x <- data_test_x[,sort(c(mean_features_idx, std_features_idx))] # merge train and test column print("Merging data") data_train <- cbind(data_train_subjects, data_train_y, data_train_x) data_test <- cbind(data_test_subjects, data_test_y, data_test_x) # join train and test data data_total <- rbind(data_train, data_test) # descriptive names of the activities data_total$activity <- factor(data_total$activity, labels = activity_labels$activity_label) data_total$subject <- as.factor(data_total$subject) # delete unused data to clean memory rm(list = c("data_train", "data_test", "data_train_x", "data_test_x", "data_train_y", "data_test_y", "data_train_subjects", "data_test_subjects")) # calculate mean for each column grouped by activity and subject data_new <- ddply(data_total, .(activity, subject), colwise(mean)) # save new dataset in files print("Writing new dataset!") write.table(data_new, file = "new_dataset.txt", row.names = FALSE) if (file.exists("new_dataset.txt")) { print("Everything finished correctly!") } else { stop("Problem occurred when saving new dataset!") } }
/run_analysis.R
no_license
rfribeiro/GettingAndCleaningDataCourseProject
R
false
false
5,008
r
# get current directory to script folder script.directory <- dirname(sys.frame(1)$ofile) download_dataset <- function() { # download file assignment_file <- "https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip" assignment_dest_file <- "assignment.zip" # downloading file print(paste("Downloading dataset from :", assignment_file)) download.file(assignment_file, destfile = assignment_dest_file, method = "curl") # Unzip files print("Extracting dataset files!") unzip(assignment_dest_file, exdir = ".") if (!file.exists("UCI HAR Dataset")) return (FALSE) else return (TRUE) } # install and load dependent packages install_dependences <- function() { requiredPackages = c('plyr','dplyr') for(p in requiredPackages){ if(!require(p,character.only = TRUE)) install.packages(p) library(p,character.only = TRUE) } } set_working_folder <- function() { if (getwd() != script.directory) { print(paste("Current directory NOT set correctly : ", getwd())) setwd(script.directory) if (getwd() != script.directory) answer <- FALSE else answer <- TRUE print(paste("Setting current directory to correct", answer, ":", getwd())) } else { print(paste("Current directory set correctly : ", getwd())) } } run_analysis <- function() { # load dependent libraries install_dependences() # set working directory set_working_folder() # check if dataset folder exist if (!file.exists("UCI HAR Dataset")) { ans <- readline(prompt="Dataset NOT exist, do you like to download it?") if (ans != "y" && ans != "Y") { stop("Dataset NOT exist, exiting!!!") } # download and unzip dataset if (download_dataset() == TRUE) { print("Dataset downloaded and extracted correctly") } else { stop("Problem occurred when downloading and extracting dataset!") } } print("Dataset exist, starting to analyse it!") # files path activity_labels_file <- ".\\UCI HAR Dataset\\activity_labels.txt" features_labels_file <- ".\\UCI HAR Dataset\\features.txt" x_train_file <- ".\\UCI HAR Dataset\\train\\X_train.txt" y_train_file <- ".\\UCI HAR Dataset\\train\\Y_train.txt" sub_train_file <- ".\\UCI HAR Dataset\\train\\subject_train.txt" train_files <- c(sub_train_file, x_train_file, y_train_file) x_test_file <- ".\\UCI HAR Dataset\\test\\X_test.txt" y_test_file <- ".\\UCI HAR Dataset\\test\\Y_test.txt" sub_test_file <- ".\\UCI HAR Dataset\\test\\subject_test.txt" test_files <- c(sub_test_file, x_test_file, y_test_file) #constants activity_label <- c("activity") subject_label <- c("subject") # load files print("Loading dataset files!") activity_labels <- read.table(activity_labels_file) names(activity_labels) <- c("activity_index", "activity_label") features_labels <- read.table(features_labels_file) names(features_labels) <- c("feature_index", "feature_label") data_train_x <- read.table(x_train_file, col.names = features_labels$feature_label, check.names = FALSE) data_train_y <- read.table(y_train_file, col.names = activity_label) data_train_subjects <- read.table(sub_train_file, col.names = subject_label) data_test_x <- read.table(x_test_file, col.names = features_labels$feature_label, check.names = FALSE) data_test_y <- read.table(y_test_file, col.names = activity_label) data_test_subjects <- read.table(sub_test_file, col.names = subject_label) # select only columns that have mean and std values mean_features_idx <- grep("mean()", features_labels$feature_label) std_features_idx <- grep("std()", features_labels$feature_label) # extract only mean and std columns (sorted) from measurements data_train_x <- data_train_x[,sort(c(mean_features_idx, std_features_idx))] data_test_x <- data_test_x[,sort(c(mean_features_idx, std_features_idx))] # merge train and test column print("Merging data") data_train <- cbind(data_train_subjects, data_train_y, data_train_x) data_test <- cbind(data_test_subjects, data_test_y, data_test_x) # join train and test data data_total <- rbind(data_train, data_test) # descriptive names of the activities data_total$activity <- factor(data_total$activity, labels = activity_labels$activity_label) data_total$subject <- as.factor(data_total$subject) # delete unused data to clean memory rm(list = c("data_train", "data_test", "data_train_x", "data_test_x", "data_train_y", "data_test_y", "data_train_subjects", "data_test_subjects")) # calculate mean for each column grouped by activity and subject data_new <- ddply(data_total, .(activity, subject), colwise(mean)) # save new dataset in files print("Writing new dataset!") write.table(data_new, file = "new_dataset.txt", row.names = FALSE) if (file.exists("new_dataset.txt")) { print("Everything finished correctly!") } else { stop("Problem occurred when saving new dataset!") } }
## this file allows for a cached retrieval of an inverted matrix. ## creates an object representing a matrix with an precomputed inverted matrix. makeCacheMatrix <- function(m = matrix()) { mi <- NULL set <- function(y) { m <<- y mi <<- NULL } get <- function() m setinverse <- function(inverse) mi <<- inverse getinverse <- function() mi list(set = set, get = get, setinverse = setinverse, getinverse = getinverse) } ## computes the inverted matrix if it has not been cached yet. Returns the inverted matrix. cacheSolve <- function(m, ...) { inverse <- m$getinverse() if(!is.null(inverse)) { message("getting cached data") return(inverse) } thematrix <- m$get() inverse <- solve(thematrix, ...) m$setinverse(inverse) inverse }
/cachematrix.R
no_license
netchkin/ProgrammingAssignment2
R
false
false
789
r
## this file allows for a cached retrieval of an inverted matrix. ## creates an object representing a matrix with an precomputed inverted matrix. makeCacheMatrix <- function(m = matrix()) { mi <- NULL set <- function(y) { m <<- y mi <<- NULL } get <- function() m setinverse <- function(inverse) mi <<- inverse getinverse <- function() mi list(set = set, get = get, setinverse = setinverse, getinverse = getinverse) } ## computes the inverted matrix if it has not been cached yet. Returns the inverted matrix. cacheSolve <- function(m, ...) { inverse <- m$getinverse() if(!is.null(inverse)) { message("getting cached data") return(inverse) } thematrix <- m$get() inverse <- solve(thematrix, ...) m$setinverse(inverse) inverse }
# Script para agrupar as curvas de carga com observações a cada 10 minutos, dentro de 1 dia (144 observações). source("data_houses_10minutes.R") # Dados já normalizados # Gráficos das 20 casas gg1 <- ggplot() + geom_line(data = dayHouse1, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg2 <- ggplot() + geom_line(data = dayHouse2, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg3 <- ggplot() + geom_line(data = dayHouse3, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg4 <- ggplot() + geom_line(data = dayHouse4, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg5 <- ggplot() + geom_line(data = dayHouse5, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg6 <- ggplot() + geom_line(data = dayHouse6, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg7 <- ggplot() + geom_line(data = dayHouse7, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg8 <- ggplot() + geom_line(data = dayHouse8, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg9 <- ggplot() + geom_line(data = dayHouse9, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg10 <- ggplot() + geom_line(data = dayHouse10, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg11 <- ggplot() + geom_line(data = dayHouse11, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg12 <- ggplot() + geom_line(data = dayHouse12, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg13 <- ggplot() + geom_line(data = dayHouse13, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg14 <- ggplot() + geom_line(data = dayHouse15, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg15 <- ggplot() + geom_line(data = dayHouse16, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg16 <- ggplot() + geom_line(data = dayHouse17, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg17 <- ggplot() + geom_line(data = dayHouse18, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg18 <- ggplot() + geom_line(data = dayHouse19, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg19 <- ggplot() + geom_line(data = dayHouse20, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg20 <- ggplot() + geom_line(data = dayHouse21, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') grid.arrange(gg1, gg2, gg3, gg4, gg5, gg6, gg7, gg8, gg9, gg10, gg11, gg12, gg13, gg14, gg15, gg16, gg17, gg18, gg19, gg20, nrow = 4, ncol = 5) # Unir os dados em um data frame series <- dayHouse1 series <- cbind(series, dayHouse2$Aggregate, dayHouse3$Aggregate, dayHouse4$Aggregate, dayHouse5$Aggregate, dayHouse6$Aggregate, dayHouse7$Aggregate, dayHouse8$Aggregate, dayHouse9$Aggregate, dayHouse10$Aggregate, dayHouse11$Aggregate, dayHouse12$Aggregate, dayHouse13$Aggregate, dayHouse15$Aggregate, dayHouse16$Aggregate, dayHouse17$Aggregate, dayHouse18$Aggregate, dayHouse19$Aggregate, dayHouse20$Aggregate, dayHouse21$Aggregate) series$Time <- NULL # Fixando a quantidade de clusters qtdCluster <- 5 # Agrupando os perfis de consumo source("functions_cluster_profile.R") # ---------- # # Correlação # # ---------- # simCorrelacao <- as.data.frame(correlacao_20U(dayHouse1,dayHouse2,dayHouse3,dayHouse4,dayHouse5,dayHouse6,dayHouse7,dayHouse8, dayHouse9,dayHouse10,dayHouse11,dayHouse12,dayHouse13,dayHouse15,dayHouse16, dayHouse17,dayHouse18,dayHouse19,dayHouse20,dayHouse21) ) simCorrelacao <- data.frame(user1=simCorrelacao$V1, user2=simCorrelacao$V2, user3=simCorrelacao$V3, user4=simCorrelacao$V4, user5=simCorrelacao$V5, user6=simCorrelacao$V6, user7=simCorrelacao$V7, user8=simCorrelacao$V8, user9=simCorrelacao$V9, user10=simCorrelacao$V10, user11=simCorrelacao$V11, user12=simCorrelacao$V12, user13=simCorrelacao$V13, user14=simCorrelacao$V14, user15=simCorrelacao$V15, user16=simCorrelacao$V16, user17=simCorrelacao$V17, user18=simCorrelacao$V18, user19=simCorrelacao$V19, user20=simCorrelacao$V20) for(i in 1:nrow(simCorrelacao)){ # linha for(j in 1:ncol(simCorrelacao)){ # coluna simCorrelacao[i,j] <- sqrt( (1-simCorrelacao[i,j])/2 ) } } # Agrupamento #qtdCluster <- wssplot(simCorrelacao, nc = nrow(simCorrelacao)-1) hierarchical(simCorrelacao, qtdCluster) # Dendrogram k.res <- kmeans(simCorrelacao, centers = qtdCluster, nstart = 25) simCorrelacao$cluster <- k.res$cluster # Validação Dist <- as.dist(simCorrelacao[,-(ncol(simCorrelacao))]) cluster.stats(Dist, simCorrelacao$cluster)$dunn # 0.4949157 cluster.stats(Dist, simCorrelacao$cluster)$avg.silwidth # 0.266 plot(silhouette(simCorrelacao$cluster, Dist)) # Calculando o MAE maeSeries(series, k.res$cluster, qtdCluster) # 0.1103037 # Grupos for(i in 1:qtdCluster){ print(which(simCorrelacao$cluster == i)) } # Sequencia: (H = house) # H1,H2,H3,H4,H5,H6,H7,H8,H9,H10,H11,H12,H13,H15,H16,H17,H18,H19,H20,H21 # 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 # 1 # 15,16,19 # 5 # 4,6,11,21 # 2,3,7,8,9,10,12,13,17,18,20 # Gráficos gg1 <- ggplot() + geom_line(data = dayHouse1, aes(x = Time, y = Aggregate, group = 1)) + xlab('Hora (1 dia)') + ylab('Consumo normalizado') + ggtitle('Correlação (grupo 1)') + theme_bw() + theme(title = element_text(size = 18), axis.title = element_text(size = 15)) gg2 <- ggplot() + geom_line(data = dayHouse15, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse16, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse19, aes(x = Time, y = Aggregate, group = 1)) + xlab('Hora (1 dia)') + ylab('Consumo normalizado') + ggtitle('Correlação (grupo 2)') + theme_bw() + theme(title = element_text(size = 18), axis.title = element_text(size = 15)) gg3 <- ggplot() + geom_line(data = dayHouse5, aes(x = Time, y = Aggregate, group = 1)) + xlab('Hora (1 dia)') + ylab('Consumo normalizado') + ggtitle('Correlação (grupo 3)') + theme_bw() + theme(title = element_text(size = 18), axis.title = element_text(size = 15)) gg4 <- ggplot() + geom_line(data = dayHouse4, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse6, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse11, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse21, aes(x = Time, y = Aggregate, group = 1)) + xlab('Hora (1 dia)') + ylab('Consumo normalizado') + ggtitle('Correlação (grupo 4)') + theme_bw() + theme(title = element_text(size = 18), axis.title = element_text(size = 15)) gg5 <- ggplot() + geom_line(data = dayHouse2, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse3, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse7, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse8, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse9, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse10, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse12, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse13, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse17, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse18, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse20, aes(x = Time, y = Aggregate, group = 1)) + xlab('Hora (1 dia)') + ylab('Consumo normalizado') + ggtitle('Correlação (grupo 5)') + theme_bw() + theme(title = element_text(size = 18), axis.title = element_text(size = 15)) grid.arrange(gg1,gg2,gg3,gg4,gg5, nrow = 3, ncol = 2) # ---------- # # Euclidiana # # ---------- # simEuclid <- as.data.frame(distaciaEuclid_20U(dayHouse1,dayHouse2,dayHouse3,dayHouse4,dayHouse5,dayHouse6,dayHouse7,dayHouse8, dayHouse9,dayHouse10,dayHouse11,dayHouse12,dayHouse13,dayHouse15,dayHouse16, dayHouse17,dayHouse18,dayHouse19,dayHouse20,dayHouse21) ) simEuclid <- data.frame(user1=simEuclid$V1, user2=simEuclid$V2, user3=simEuclid$V3, user4=simEuclid$V4, user5=simEuclid$V5, user6=simEuclid$V6, user7=simEuclid$V7, user8=simEuclid$V8, user9=simEuclid$V9, user10=simEuclid$V10, user11=simEuclid$V11, user12=simEuclid$V12, user13=simEuclid$V13, user14=simEuclid$V14, user15=simEuclid$V15, user16=simEuclid$V16, user17=simEuclid$V17, user18=simEuclid$V18, user19=simEuclid$V19, user20=simEuclid$V20) # Agrupamento #qtdCluster <- wssplot(simEuclid, nc = nrow(simEuclid)-1) hierarchical(simEuclid, qtdCluster) # Dendrogram k.res <- kmeans(simEuclid, centers = qtdCluster, nstart = 25) simEuclid$cluster <- k.res$cluster # Validação Dist <- dist(simEuclid[,-(ncol(simEuclid))]) cluster.stats(Dist, simEuclid$cluster)$dunn # 0.3589234 cluster.stats(Dist, simEuclid$cluster)$avg.silwidth # 0.2978361 plot(silhouette(simEuclid$cluster, Dist)) # Calculando o MAE maeSeries(series, k.res$cluster, qtdCluster) # 0.09944951 # Grupos for(i in 1:qtdCluster){ print(which(simEuclid$cluster == i)) } # Sequencia: (H = house) # H1,H2,H3,H4,H5,H6,H7,H8,H9,H10,H11,H12,H13,H15,H16,H17,H18,H19,H20,H21 # 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 # 4,5,8 # 2,3,11,12,18,20,21 # 1 # 6,7,9,10,13,17 # 15,16,19 # Gráficos gg6 <- ggplot() + geom_line(data = dayHouse4, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse5, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse8, aes(x = Time, y = Aggregate, group = 1)) + xlab('Hora (1 dia)') + ylab('Consumo normalizado') + ggtitle('Euclidiana (grupo 1)') + theme_bw() + theme(title = element_text(size = 18), axis.title = element_text(size = 15)) gg7 <- ggplot() + geom_line(data = dayHouse2, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse3, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse11, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse12, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse18, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse20, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse21, aes(x = Time, y = Aggregate, group = 1)) + xlab('Hora (1 dia)') + ylab('Consumo normalizado') + ggtitle('Euclidiana (grupo 2)') + theme_bw() + theme(title = element_text(size = 18), axis.title = element_text(size = 15)) gg8 <- ggplot() + geom_line(data = dayHouse1, aes(x = Time, y = Aggregate, group = 1)) + xlab('Hora (1 dia)') + ylab('Consumo normalizado') + ggtitle('Euclidiana (grupo 3)') + theme_bw() + theme(title = element_text(size = 18), axis.title = element_text(size = 15)) gg9 <- ggplot() + geom_line(data = dayHouse6, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse7, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse9, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse10, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse13, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse17, aes(x = Time, y = Aggregate, group = 1)) + xlab('Hora (1 dia)') + ylab('Consumo normalizado') + ggtitle('Euclidiana (grupo 4)') + theme_bw() + theme(title = element_text(size = 18), axis.title = element_text(size = 15)) gg10 <- ggplot() + geom_line(data = dayHouse15, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse16, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse19, aes(x = Time, y = Aggregate, group = 1)) + xlab('Hora (1 dia)') + ylab('Consumo normalizado') + ggtitle('Euclidiana (grupo 5)') + theme_bw() + theme(title = element_text(size = 18), axis.title = element_text(size = 15)) grid.arrange(gg5,gg6,gg7,gg8,gg9,gg10, nrow = 3, ncol = 2) # --- # # DTW # # --- # simDtw <- as.data.frame(distanciaDTW_20U(dayHouse1,dayHouse2,dayHouse3,dayHouse4,dayHouse5,dayHouse6,dayHouse7,dayHouse8, dayHouse9,dayHouse10,dayHouse11,dayHouse12,dayHouse13,dayHouse15,dayHouse16, dayHouse17,dayHouse18,dayHouse19,dayHouse20,dayHouse21) ) simDtw <- data.frame(user1=simDtw$V1, user2=simDtw$V2, user3=simDtw$V3, user4=simDtw$V4, user5=simDtw$V5, user6=simDtw$V6, user7=simDtw$V7, user8=simDtw$V8, user9=simDtw$V9, user10=simDtw$V10, user11=simDtw$V11, user12=simDtw$V12, user13=simDtw$V13, user14=simDtw$V14, user15=simDtw$V15, user16=simDtw$V16, user17=simDtw$V17, user18=simDtw$V18, user19=simDtw$V19, user20=simDtw$V20) # Agrupamento #qtdCluster <- wssplot(simDtw, nc = nrow(simDtw)-1) hierarchical(simDtw, qtdCluster) # Dendrogram k.res <- kmeans(simDtw, centers = qtdCluster, nstart = 25) simDtw$cluster <- k.res$cluster # Validação Dist <- dist(simDtw[,-(ncol(simDtw))]) cluster.stats(Dist, simDtw$cluster)$dunn # 0.3128908 cluster.stats(Dist, simDtw$cluster)$avg.silwidth # 0.2319691 plot(silhouette(simDtw$cluster, Dist)) # Calculando o MAE maeSeries(series, k.res$cluster, qtdCluster) # 0.1008105 # Grupos for(i in 1:qtdCluster){ print(which(simDtw$cluster == i)) } # 1,4,5 # 16 # 6,7,9,10,13,17,18,21 # 15,19 # 2,3,8,11,12,20 # Gráficos gg11 <- ggplot() + geom_line(data = dayHouse1, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse4, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse5, aes(x = Time, y = Aggregate, group = 1)) + xlab('Hora (1 dia)') + ylab('Consumo normalizado') + ggtitle('DTW (grupo 1)') + theme_bw() + theme(title = element_text(size = 18), axis.title = element_text(size = 15)) gg12 <- ggplot() + geom_line(data = dayHouse16, aes(x = Time, y = Aggregate, group = 1)) + xlab('Hora (1 dia)') + ylab('Consumo normalizado') + ggtitle('DTW (grupo 2)') + theme_bw() + theme(title = element_text(size = 18), axis.title = element_text(size = 15)) gg13 <- ggplot() + geom_line(data = dayHouse6, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse7, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse9, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse10, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse13, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse17, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse18, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse21, aes(x = Time, y = Aggregate, group = 1)) + xlab('Hora (1 dia)') + ylab('Consumo normalizado') + ggtitle('DTW (grupo 3)') + theme_bw() + theme(title = element_text(size = 18), axis.title = element_text(size = 15)) gg14 <- ggplot() + geom_line(data = dayHouse15, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse19, aes(x = Time, y = Aggregate, group = 1)) + xlab('Hora (1 dia)') + ylab('Consumo normalizado') + ggtitle('DTW (grupo 4)') + theme_bw() + theme(title = element_text(size = 18), axis.title = element_text(size = 15)) gg15 <- ggplot() + geom_line(data = dayHouse2, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse3, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse8, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse11, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse12, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse20, aes(x = Time, y = Aggregate, group = 1)) + xlab('Hora (1 dia)') + ylab('Consumo normalizado') + ggtitle('DTW (grupo 5)') + theme_bw() + theme(title = element_text(size = 18), axis.title = element_text(size = 15)) grid.arrange(gg11,gg12,gg13,gg14,gg15, nrow = 3, ncol = 2) # Todos os agrupamentos png(filename = "../Results/cluster_20users_mean_10min_1day.png", width = 1920, height = 1080) grid.arrange(gg1,gg6,gg11, gg2,gg7,gg12, gg3,gg8,gg13, gg4,gg9,gg14, gg5,gg10,gg15, nrow = 5, ncol = 3) dev.off()
/Consumption_Profile_REFIT/Scripts/results_1_day_10_min.R
no_license
HarllanAndrye/EnergyEfficiency-clustering-
R
false
false
17,388
r
# Script para agrupar as curvas de carga com observações a cada 10 minutos, dentro de 1 dia (144 observações). source("data_houses_10minutes.R") # Dados já normalizados # Gráficos das 20 casas gg1 <- ggplot() + geom_line(data = dayHouse1, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg2 <- ggplot() + geom_line(data = dayHouse2, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg3 <- ggplot() + geom_line(data = dayHouse3, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg4 <- ggplot() + geom_line(data = dayHouse4, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg5 <- ggplot() + geom_line(data = dayHouse5, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg6 <- ggplot() + geom_line(data = dayHouse6, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg7 <- ggplot() + geom_line(data = dayHouse7, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg8 <- ggplot() + geom_line(data = dayHouse8, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg9 <- ggplot() + geom_line(data = dayHouse9, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg10 <- ggplot() + geom_line(data = dayHouse10, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg11 <- ggplot() + geom_line(data = dayHouse11, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg12 <- ggplot() + geom_line(data = dayHouse12, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg13 <- ggplot() + geom_line(data = dayHouse13, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg14 <- ggplot() + geom_line(data = dayHouse15, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg15 <- ggplot() + geom_line(data = dayHouse16, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg16 <- ggplot() + geom_line(data = dayHouse17, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg17 <- ggplot() + geom_line(data = dayHouse18, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg18 <- ggplot() + geom_line(data = dayHouse19, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg19 <- ggplot() + geom_line(data = dayHouse20, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') gg20 <- ggplot() + geom_line(data = dayHouse21, aes(x = Time, y = Aggregate, group = 1)) + xlab('Date') + ylab('Power') + ggtitle('1 day of January') grid.arrange(gg1, gg2, gg3, gg4, gg5, gg6, gg7, gg8, gg9, gg10, gg11, gg12, gg13, gg14, gg15, gg16, gg17, gg18, gg19, gg20, nrow = 4, ncol = 5) # Unir os dados em um data frame series <- dayHouse1 series <- cbind(series, dayHouse2$Aggregate, dayHouse3$Aggregate, dayHouse4$Aggregate, dayHouse5$Aggregate, dayHouse6$Aggregate, dayHouse7$Aggregate, dayHouse8$Aggregate, dayHouse9$Aggregate, dayHouse10$Aggregate, dayHouse11$Aggregate, dayHouse12$Aggregate, dayHouse13$Aggregate, dayHouse15$Aggregate, dayHouse16$Aggregate, dayHouse17$Aggregate, dayHouse18$Aggregate, dayHouse19$Aggregate, dayHouse20$Aggregate, dayHouse21$Aggregate) series$Time <- NULL # Fixando a quantidade de clusters qtdCluster <- 5 # Agrupando os perfis de consumo source("functions_cluster_profile.R") # ---------- # # Correlação # # ---------- # simCorrelacao <- as.data.frame(correlacao_20U(dayHouse1,dayHouse2,dayHouse3,dayHouse4,dayHouse5,dayHouse6,dayHouse7,dayHouse8, dayHouse9,dayHouse10,dayHouse11,dayHouse12,dayHouse13,dayHouse15,dayHouse16, dayHouse17,dayHouse18,dayHouse19,dayHouse20,dayHouse21) ) simCorrelacao <- data.frame(user1=simCorrelacao$V1, user2=simCorrelacao$V2, user3=simCorrelacao$V3, user4=simCorrelacao$V4, user5=simCorrelacao$V5, user6=simCorrelacao$V6, user7=simCorrelacao$V7, user8=simCorrelacao$V8, user9=simCorrelacao$V9, user10=simCorrelacao$V10, user11=simCorrelacao$V11, user12=simCorrelacao$V12, user13=simCorrelacao$V13, user14=simCorrelacao$V14, user15=simCorrelacao$V15, user16=simCorrelacao$V16, user17=simCorrelacao$V17, user18=simCorrelacao$V18, user19=simCorrelacao$V19, user20=simCorrelacao$V20) for(i in 1:nrow(simCorrelacao)){ # linha for(j in 1:ncol(simCorrelacao)){ # coluna simCorrelacao[i,j] <- sqrt( (1-simCorrelacao[i,j])/2 ) } } # Agrupamento #qtdCluster <- wssplot(simCorrelacao, nc = nrow(simCorrelacao)-1) hierarchical(simCorrelacao, qtdCluster) # Dendrogram k.res <- kmeans(simCorrelacao, centers = qtdCluster, nstart = 25) simCorrelacao$cluster <- k.res$cluster # Validação Dist <- as.dist(simCorrelacao[,-(ncol(simCorrelacao))]) cluster.stats(Dist, simCorrelacao$cluster)$dunn # 0.4949157 cluster.stats(Dist, simCorrelacao$cluster)$avg.silwidth # 0.266 plot(silhouette(simCorrelacao$cluster, Dist)) # Calculando o MAE maeSeries(series, k.res$cluster, qtdCluster) # 0.1103037 # Grupos for(i in 1:qtdCluster){ print(which(simCorrelacao$cluster == i)) } # Sequencia: (H = house) # H1,H2,H3,H4,H5,H6,H7,H8,H9,H10,H11,H12,H13,H15,H16,H17,H18,H19,H20,H21 # 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 # 1 # 15,16,19 # 5 # 4,6,11,21 # 2,3,7,8,9,10,12,13,17,18,20 # Gráficos gg1 <- ggplot() + geom_line(data = dayHouse1, aes(x = Time, y = Aggregate, group = 1)) + xlab('Hora (1 dia)') + ylab('Consumo normalizado') + ggtitle('Correlação (grupo 1)') + theme_bw() + theme(title = element_text(size = 18), axis.title = element_text(size = 15)) gg2 <- ggplot() + geom_line(data = dayHouse15, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse16, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse19, aes(x = Time, y = Aggregate, group = 1)) + xlab('Hora (1 dia)') + ylab('Consumo normalizado') + ggtitle('Correlação (grupo 2)') + theme_bw() + theme(title = element_text(size = 18), axis.title = element_text(size = 15)) gg3 <- ggplot() + geom_line(data = dayHouse5, aes(x = Time, y = Aggregate, group = 1)) + xlab('Hora (1 dia)') + ylab('Consumo normalizado') + ggtitle('Correlação (grupo 3)') + theme_bw() + theme(title = element_text(size = 18), axis.title = element_text(size = 15)) gg4 <- ggplot() + geom_line(data = dayHouse4, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse6, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse11, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse21, aes(x = Time, y = Aggregate, group = 1)) + xlab('Hora (1 dia)') + ylab('Consumo normalizado') + ggtitle('Correlação (grupo 4)') + theme_bw() + theme(title = element_text(size = 18), axis.title = element_text(size = 15)) gg5 <- ggplot() + geom_line(data = dayHouse2, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse3, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse7, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse8, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse9, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse10, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse12, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse13, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse17, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse18, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse20, aes(x = Time, y = Aggregate, group = 1)) + xlab('Hora (1 dia)') + ylab('Consumo normalizado') + ggtitle('Correlação (grupo 5)') + theme_bw() + theme(title = element_text(size = 18), axis.title = element_text(size = 15)) grid.arrange(gg1,gg2,gg3,gg4,gg5, nrow = 3, ncol = 2) # ---------- # # Euclidiana # # ---------- # simEuclid <- as.data.frame(distaciaEuclid_20U(dayHouse1,dayHouse2,dayHouse3,dayHouse4,dayHouse5,dayHouse6,dayHouse7,dayHouse8, dayHouse9,dayHouse10,dayHouse11,dayHouse12,dayHouse13,dayHouse15,dayHouse16, dayHouse17,dayHouse18,dayHouse19,dayHouse20,dayHouse21) ) simEuclid <- data.frame(user1=simEuclid$V1, user2=simEuclid$V2, user3=simEuclid$V3, user4=simEuclid$V4, user5=simEuclid$V5, user6=simEuclid$V6, user7=simEuclid$V7, user8=simEuclid$V8, user9=simEuclid$V9, user10=simEuclid$V10, user11=simEuclid$V11, user12=simEuclid$V12, user13=simEuclid$V13, user14=simEuclid$V14, user15=simEuclid$V15, user16=simEuclid$V16, user17=simEuclid$V17, user18=simEuclid$V18, user19=simEuclid$V19, user20=simEuclid$V20) # Agrupamento #qtdCluster <- wssplot(simEuclid, nc = nrow(simEuclid)-1) hierarchical(simEuclid, qtdCluster) # Dendrogram k.res <- kmeans(simEuclid, centers = qtdCluster, nstart = 25) simEuclid$cluster <- k.res$cluster # Validação Dist <- dist(simEuclid[,-(ncol(simEuclid))]) cluster.stats(Dist, simEuclid$cluster)$dunn # 0.3589234 cluster.stats(Dist, simEuclid$cluster)$avg.silwidth # 0.2978361 plot(silhouette(simEuclid$cluster, Dist)) # Calculando o MAE maeSeries(series, k.res$cluster, qtdCluster) # 0.09944951 # Grupos for(i in 1:qtdCluster){ print(which(simEuclid$cluster == i)) } # Sequencia: (H = house) # H1,H2,H3,H4,H5,H6,H7,H8,H9,H10,H11,H12,H13,H15,H16,H17,H18,H19,H20,H21 # 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 # 4,5,8 # 2,3,11,12,18,20,21 # 1 # 6,7,9,10,13,17 # 15,16,19 # Gráficos gg6 <- ggplot() + geom_line(data = dayHouse4, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse5, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse8, aes(x = Time, y = Aggregate, group = 1)) + xlab('Hora (1 dia)') + ylab('Consumo normalizado') + ggtitle('Euclidiana (grupo 1)') + theme_bw() + theme(title = element_text(size = 18), axis.title = element_text(size = 15)) gg7 <- ggplot() + geom_line(data = dayHouse2, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse3, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse11, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse12, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse18, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse20, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse21, aes(x = Time, y = Aggregate, group = 1)) + xlab('Hora (1 dia)') + ylab('Consumo normalizado') + ggtitle('Euclidiana (grupo 2)') + theme_bw() + theme(title = element_text(size = 18), axis.title = element_text(size = 15)) gg8 <- ggplot() + geom_line(data = dayHouse1, aes(x = Time, y = Aggregate, group = 1)) + xlab('Hora (1 dia)') + ylab('Consumo normalizado') + ggtitle('Euclidiana (grupo 3)') + theme_bw() + theme(title = element_text(size = 18), axis.title = element_text(size = 15)) gg9 <- ggplot() + geom_line(data = dayHouse6, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse7, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse9, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse10, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse13, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse17, aes(x = Time, y = Aggregate, group = 1)) + xlab('Hora (1 dia)') + ylab('Consumo normalizado') + ggtitle('Euclidiana (grupo 4)') + theme_bw() + theme(title = element_text(size = 18), axis.title = element_text(size = 15)) gg10 <- ggplot() + geom_line(data = dayHouse15, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse16, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse19, aes(x = Time, y = Aggregate, group = 1)) + xlab('Hora (1 dia)') + ylab('Consumo normalizado') + ggtitle('Euclidiana (grupo 5)') + theme_bw() + theme(title = element_text(size = 18), axis.title = element_text(size = 15)) grid.arrange(gg5,gg6,gg7,gg8,gg9,gg10, nrow = 3, ncol = 2) # --- # # DTW # # --- # simDtw <- as.data.frame(distanciaDTW_20U(dayHouse1,dayHouse2,dayHouse3,dayHouse4,dayHouse5,dayHouse6,dayHouse7,dayHouse8, dayHouse9,dayHouse10,dayHouse11,dayHouse12,dayHouse13,dayHouse15,dayHouse16, dayHouse17,dayHouse18,dayHouse19,dayHouse20,dayHouse21) ) simDtw <- data.frame(user1=simDtw$V1, user2=simDtw$V2, user3=simDtw$V3, user4=simDtw$V4, user5=simDtw$V5, user6=simDtw$V6, user7=simDtw$V7, user8=simDtw$V8, user9=simDtw$V9, user10=simDtw$V10, user11=simDtw$V11, user12=simDtw$V12, user13=simDtw$V13, user14=simDtw$V14, user15=simDtw$V15, user16=simDtw$V16, user17=simDtw$V17, user18=simDtw$V18, user19=simDtw$V19, user20=simDtw$V20) # Agrupamento #qtdCluster <- wssplot(simDtw, nc = nrow(simDtw)-1) hierarchical(simDtw, qtdCluster) # Dendrogram k.res <- kmeans(simDtw, centers = qtdCluster, nstart = 25) simDtw$cluster <- k.res$cluster # Validação Dist <- dist(simDtw[,-(ncol(simDtw))]) cluster.stats(Dist, simDtw$cluster)$dunn # 0.3128908 cluster.stats(Dist, simDtw$cluster)$avg.silwidth # 0.2319691 plot(silhouette(simDtw$cluster, Dist)) # Calculando o MAE maeSeries(series, k.res$cluster, qtdCluster) # 0.1008105 # Grupos for(i in 1:qtdCluster){ print(which(simDtw$cluster == i)) } # 1,4,5 # 16 # 6,7,9,10,13,17,18,21 # 15,19 # 2,3,8,11,12,20 # Gráficos gg11 <- ggplot() + geom_line(data = dayHouse1, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse4, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse5, aes(x = Time, y = Aggregate, group = 1)) + xlab('Hora (1 dia)') + ylab('Consumo normalizado') + ggtitle('DTW (grupo 1)') + theme_bw() + theme(title = element_text(size = 18), axis.title = element_text(size = 15)) gg12 <- ggplot() + geom_line(data = dayHouse16, aes(x = Time, y = Aggregate, group = 1)) + xlab('Hora (1 dia)') + ylab('Consumo normalizado') + ggtitle('DTW (grupo 2)') + theme_bw() + theme(title = element_text(size = 18), axis.title = element_text(size = 15)) gg13 <- ggplot() + geom_line(data = dayHouse6, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse7, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse9, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse10, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse13, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse17, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse18, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse21, aes(x = Time, y = Aggregate, group = 1)) + xlab('Hora (1 dia)') + ylab('Consumo normalizado') + ggtitle('DTW (grupo 3)') + theme_bw() + theme(title = element_text(size = 18), axis.title = element_text(size = 15)) gg14 <- ggplot() + geom_line(data = dayHouse15, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse19, aes(x = Time, y = Aggregate, group = 1)) + xlab('Hora (1 dia)') + ylab('Consumo normalizado') + ggtitle('DTW (grupo 4)') + theme_bw() + theme(title = element_text(size = 18), axis.title = element_text(size = 15)) gg15 <- ggplot() + geom_line(data = dayHouse2, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse3, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse8, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse11, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse12, aes(x = Time, y = Aggregate, group = 1)) + geom_line(data = dayHouse20, aes(x = Time, y = Aggregate, group = 1)) + xlab('Hora (1 dia)') + ylab('Consumo normalizado') + ggtitle('DTW (grupo 5)') + theme_bw() + theme(title = element_text(size = 18), axis.title = element_text(size = 15)) grid.arrange(gg11,gg12,gg13,gg14,gg15, nrow = 3, ncol = 2) # Todos os agrupamentos png(filename = "../Results/cluster_20users_mean_10min_1day.png", width = 1920, height = 1080) grid.arrange(gg1,gg6,gg11, gg2,gg7,gg12, gg3,gg8,gg13, gg4,gg9,gg14, gg5,gg10,gg15, nrow = 5, ncol = 3) dev.off()
install_learners("classif.liblinearl1l2svc") test_that("autotest", { learner = LearnerClassifLiblineaRL1L2SVC$new() expect_learner(learner) result = run_autotest(learner) expect_true(result, info = result$error) })
/tests/testthat/test_LiblineaR_classif_liblinearl1l2svc.R
no_license
0livier1O1/mlr3extralearners
R
false
false
224
r
install_learners("classif.liblinearl1l2svc") test_that("autotest", { learner = LearnerClassifLiblineaRL1L2SVC$new() expect_learner(learner) result = run_autotest(learner) expect_true(result, info = result$error) })
testlist <- list(m = NULL, repetitions = 0L, in_m = structure(c(2.31584307392677e+77, 9.53818252179844e+295, 1.22810536108214e+146, 4.12396251261199e-221, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(8L, 3L))) result <- do.call(CNull:::communities_individual_based_sampling_alpha,testlist) str(result)
/CNull/inst/testfiles/communities_individual_based_sampling_alpha/AFL_communities_individual_based_sampling_alpha/communities_individual_based_sampling_alpha_valgrind_files/1615784318-test.R
no_license
akhikolla/updatedatatype-list2
R
false
false
329
r
testlist <- list(m = NULL, repetitions = 0L, in_m = structure(c(2.31584307392677e+77, 9.53818252179844e+295, 1.22810536108214e+146, 4.12396251261199e-221, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(8L, 3L))) result <- do.call(CNull:::communities_individual_based_sampling_alpha,testlist) str(result)
##investment data_csv <- read.csv("C:/Users/Huhu/Downloads/data_csv.csv", stringsAsFactors = FALSE) head(data_csv) # Doing stuff with dates: # Reformatting the dates to make it readable by the system. data_csv$ID <- seq.int(nrow(data_csv)) data_csv$Date[1513] # S&P 500 was started in 1923; prior history is from Shiller. If you # only want the "real" sp500 values, uncomment the line below: #subset the data from 2007 sp500<-subset(data_csv,data_csv$ID >= 1513) #sp500$Date<-as.Date(sp500$Date,"%Y%m%d") #Calculate real returns (Reinvested dividends) sp500$real.return <- 1 # Start with initial conditions. I invest one dollar at the beginning of the stock market. for(r in 2:nrow(sp500)){ sp500$real.return[r]<- # Start with previous value: sp500$real.return[r-1]* # Multiply it by the % change in stock value in the last month: (((sp500$Real.Price[r]-sp500$Real.Price[r-1])/ (sp500$Real.Price[r-1]))+1)+ # Finally, add last month's dividends to the party; they get reinvested: (sp500$Real.Dividend[r-1]/sp500$Real.Price[r-1])* (sp500$real.return[r-1]/12) } sp500$real.return summary(sp500$real.return) sp500$rr.log = log(sp500$real.return) x = sp500[ -c(1, 11, 12) ] cor(x) cormat<-signif(cor(x),2) cormat col<- colorRampPalette(c("blue", "white", "red"))(20) heatmap(cormat, col=col, symm=TRUE) # Master Loop # If you're not regenerating the source data, uncomment this part # Warning: May take a very long time to solve. ############### stocks<-data.frame(NA,NA,NA,NA) names(stocks)<-c("year","real","percent","inv.date") for(f in 0:nrow(sp500)){ sp500$future.f<-NA #Future S&P Price sp500$cpi.f <- NA #Future CPI sp500$future.r <- NA #Future Real Returns buffer<-data.frame(NA,NA,NA,NA) names(buffer)<-c("year","real","percent","inv.date") for(n in (f+1):nrow(sp500)){ # Get values for "f" years in the future sp500$future.f[n-f] <- sp500$SP500[n] # Work our Future S&P Price into its own column sp500$cpi.f[n-f] <- sp500$Consumer.Price.Index[n] # Work the Future CPI into its own column sp500$future.r[n-f] <- sp500$real.return[n] # Work the Real Returns into its own column buffer<-rbind(buffer,c(f/12,sp500$future.r[n-f], # Record all history (sp500$future.r[n-f]-sp500$real.return[n-f]) / sp500$real.return[n-f], as.character(sp500$Date[n-f]) )) } stocks<-rbind(stocks,buffer) print(paste(f, " of ", nrow(sp500), " completed: ", signif(f*100/nrow(sp500),4),"%",sep=""))} stocks<-subset(stocks,!is.na(stocks$percent)) rm(buffer) # Use a cash multiplier instead of a percent: stocks$multip<-as.numeric(stocks$percent)+1 stocks$year<-as.numeric(stocks$year) stocks$real<-as.numeric(stocks$real) stocks$percent<-as.numeric(stocks$percent) #write.table(stocks,"returns.csv",sep=",") head(stocks)
/src/investment.R
permissive
tamarakatic/financial-prediction
R
false
false
3,032
r
##investment data_csv <- read.csv("C:/Users/Huhu/Downloads/data_csv.csv", stringsAsFactors = FALSE) head(data_csv) # Doing stuff with dates: # Reformatting the dates to make it readable by the system. data_csv$ID <- seq.int(nrow(data_csv)) data_csv$Date[1513] # S&P 500 was started in 1923; prior history is from Shiller. If you # only want the "real" sp500 values, uncomment the line below: #subset the data from 2007 sp500<-subset(data_csv,data_csv$ID >= 1513) #sp500$Date<-as.Date(sp500$Date,"%Y%m%d") #Calculate real returns (Reinvested dividends) sp500$real.return <- 1 # Start with initial conditions. I invest one dollar at the beginning of the stock market. for(r in 2:nrow(sp500)){ sp500$real.return[r]<- # Start with previous value: sp500$real.return[r-1]* # Multiply it by the % change in stock value in the last month: (((sp500$Real.Price[r]-sp500$Real.Price[r-1])/ (sp500$Real.Price[r-1]))+1)+ # Finally, add last month's dividends to the party; they get reinvested: (sp500$Real.Dividend[r-1]/sp500$Real.Price[r-1])* (sp500$real.return[r-1]/12) } sp500$real.return summary(sp500$real.return) sp500$rr.log = log(sp500$real.return) x = sp500[ -c(1, 11, 12) ] cor(x) cormat<-signif(cor(x),2) cormat col<- colorRampPalette(c("blue", "white", "red"))(20) heatmap(cormat, col=col, symm=TRUE) # Master Loop # If you're not regenerating the source data, uncomment this part # Warning: May take a very long time to solve. ############### stocks<-data.frame(NA,NA,NA,NA) names(stocks)<-c("year","real","percent","inv.date") for(f in 0:nrow(sp500)){ sp500$future.f<-NA #Future S&P Price sp500$cpi.f <- NA #Future CPI sp500$future.r <- NA #Future Real Returns buffer<-data.frame(NA,NA,NA,NA) names(buffer)<-c("year","real","percent","inv.date") for(n in (f+1):nrow(sp500)){ # Get values for "f" years in the future sp500$future.f[n-f] <- sp500$SP500[n] # Work our Future S&P Price into its own column sp500$cpi.f[n-f] <- sp500$Consumer.Price.Index[n] # Work the Future CPI into its own column sp500$future.r[n-f] <- sp500$real.return[n] # Work the Real Returns into its own column buffer<-rbind(buffer,c(f/12,sp500$future.r[n-f], # Record all history (sp500$future.r[n-f]-sp500$real.return[n-f]) / sp500$real.return[n-f], as.character(sp500$Date[n-f]) )) } stocks<-rbind(stocks,buffer) print(paste(f, " of ", nrow(sp500), " completed: ", signif(f*100/nrow(sp500),4),"%",sep=""))} stocks<-subset(stocks,!is.na(stocks$percent)) rm(buffer) # Use a cash multiplier instead of a percent: stocks$multip<-as.numeric(stocks$percent)+1 stocks$year<-as.numeric(stocks$year) stocks$real<-as.numeric(stocks$real) stocks$percent<-as.numeric(stocks$percent) #write.table(stocks,"returns.csv",sep=",") head(stocks)
meshRatio <- function(design){ #---------------------------------- # Compute the meshratio criterion # For a regular mesh, ratio=1 # input : design of n experiments # Example : Meshratio(matrix(runif(40),20,2)) #---------------------------------- X <- as.matrix(design) n <- dim(X)[1] dimension <- dim(X)[2] if ( n < dimension ){ stop('Warning : the number of points is lower than the dimension') } # To check the experimental region if ( min(X)<0 || max(X)>1 ){ warning("The design is rescaling into the unit cube [0,1]^d.") M <- apply(X,2,max) m <- apply(X,2,min) for (j in 1:dim(X)[2]){ X[,j] <- (X[,j]-m[j])/(M[j]-m[j]) } } DistanceMax <- -1.0E30 DistanceMin <- 1.0E30 for (i in 1:(n-1)) { DistMin <- 1.0E30 DistMax <- -1.0E30 for (k in 1 : n){ if (i != k){ # if the differs from current point Dist <- 0 for (j in 1 : dimension){ Dist <- Dist + (X[i,j] -X[k,j])*(X[i,j] - X[k,j]) } if (Dist > DistMax){ DistMax <- Dist; } if (Dist < DistMin){ DistMin <- Dist; } } } if (DistanceMax < DistMin){ DistanceMax <- DistMin } if (DistanceMin > DistMin){ DistanceMin <- DistMin } } ratio <- sqrt(DistanceMax/DistanceMin) return(ratio) }
/A_github/sources/authors/2765/DiceDesign/meshRatio.R
no_license
Irbis3/crantasticScrapper
R
false
false
1,329
r
meshRatio <- function(design){ #---------------------------------- # Compute the meshratio criterion # For a regular mesh, ratio=1 # input : design of n experiments # Example : Meshratio(matrix(runif(40),20,2)) #---------------------------------- X <- as.matrix(design) n <- dim(X)[1] dimension <- dim(X)[2] if ( n < dimension ){ stop('Warning : the number of points is lower than the dimension') } # To check the experimental region if ( min(X)<0 || max(X)>1 ){ warning("The design is rescaling into the unit cube [0,1]^d.") M <- apply(X,2,max) m <- apply(X,2,min) for (j in 1:dim(X)[2]){ X[,j] <- (X[,j]-m[j])/(M[j]-m[j]) } } DistanceMax <- -1.0E30 DistanceMin <- 1.0E30 for (i in 1:(n-1)) { DistMin <- 1.0E30 DistMax <- -1.0E30 for (k in 1 : n){ if (i != k){ # if the differs from current point Dist <- 0 for (j in 1 : dimension){ Dist <- Dist + (X[i,j] -X[k,j])*(X[i,j] - X[k,j]) } if (Dist > DistMax){ DistMax <- Dist; } if (Dist < DistMin){ DistMin <- Dist; } } } if (DistanceMax < DistMin){ DistanceMax <- DistMin } if (DistanceMin > DistMin){ DistanceMin <- DistMin } } ratio <- sqrt(DistanceMax/DistanceMin) return(ratio) }
#postscript("indicators_NSGAII_SPEA2.eps", horizontal=FALSE, onefile=FALSE, height=8, width=12, pointsize=10) pdf("indicators_NSGAII_NSGAII_DKM.pdf", onefile=FALSE, width=10) NSGAIIresultDirectory<-"." NSGAIIqIndicator <- function(indicator) { fileNSGAII<-paste(NSGAIIresultDirectory, "NSGAII", sep="/") #filePolynomialMutation<-paste(filePolynomialMutation, problem, sep="/") fileNSGAII<-paste(fileNSGAII, indicator, sep="/") NSGAII_results<-scan(fileNSGAII) fileNSGAIIDKM<-paste(NSGAIIresultDirectory, "NSGAIIWithDKMutation", sep="/") #fileDKMutation<-paste(fileDKMutation, problem, sep="/") fileNSGAIIDKM<-paste(fileNSGAIIDKM, indicator, sep="/") NSGAIIDKM_results<-scan(fileNSGAIIDKM) algs<-c("NSGAII","NSGAIIDKM") boxplot(NSGAII_results,NSGAIIDKM_results,names=algs, notch = FALSE) titulo <-paste(indicator) title(main=titulo) } #SPEA2resultDirectory<-"./MutationStudySPEA2/data/" #SPEA2qIndicator <- function(indicator, problem) #{ #filePolynomialMutation<-paste(SPEA2resultDirectory, "PolynomialMutation", sep="/") #filePolynomialMutation<-paste(filePolynomialMutation, problem, sep="/") #filePolynomialMutation<-paste(filePolynomialMutation, indicator, sep="/") #PolynomialMutation<-scan(filePolynomialMutation) #fileDKMutation<-paste(SPEA2resultDirectory, "DKMutation", sep="/") #fileDKMutation<-paste(fileDKMutation, problem, sep="/") #fileDKMutation<-paste(fileDKMutation, indicator, sep="/") #DKMutation<-scan(fileDKMutation) #algs<-c("Polynomial","DKMutation") #boxplot(PolynomialMutation,DKMutation,names=algs, notch = FALSE) #titulo <-paste(indicator, "SPEA2", sep=":") #title(main=titulo) #} par(mfrow=c(2,3)) indicator<-"HV" NSGAIIqIndicator(indicator) indicator<-"IGD" NSGAIIqIndicator(indicator) indicator<-"GD" NSGAIIqIndicator(indicator) indicator<-"Epsilon" NSGAIIqIndicator(indicator) indicator<-"Spread" NSGAIIqIndicator(indicator) #indicator<-"HV" #SPEA2qIndicator(indicator, "OptimizeElecEnergy_SPEA2") #indicator<-"IGD" #SPEA2qIndicator(indicator, "OptimizeElecEnergy_SPEA2") #indicator<-"GD" #SPEA2qIndicator(indicator, "OptimizeElecEnergy_SPEA2") #indicator<-"Epsilon" #SPEA2qIndicator(indicator, "OptimizeElecEnergy_SPEA2")
/mutationResults/AalborgProblem/compare.indicators.NSGAII.NSGAII_DKM.R
no_license
shaikatcse/EnergyPLANDomainKnowledgeEAStep1
R
false
false
2,169
r
#postscript("indicators_NSGAII_SPEA2.eps", horizontal=FALSE, onefile=FALSE, height=8, width=12, pointsize=10) pdf("indicators_NSGAII_NSGAII_DKM.pdf", onefile=FALSE, width=10) NSGAIIresultDirectory<-"." NSGAIIqIndicator <- function(indicator) { fileNSGAII<-paste(NSGAIIresultDirectory, "NSGAII", sep="/") #filePolynomialMutation<-paste(filePolynomialMutation, problem, sep="/") fileNSGAII<-paste(fileNSGAII, indicator, sep="/") NSGAII_results<-scan(fileNSGAII) fileNSGAIIDKM<-paste(NSGAIIresultDirectory, "NSGAIIWithDKMutation", sep="/") #fileDKMutation<-paste(fileDKMutation, problem, sep="/") fileNSGAIIDKM<-paste(fileNSGAIIDKM, indicator, sep="/") NSGAIIDKM_results<-scan(fileNSGAIIDKM) algs<-c("NSGAII","NSGAIIDKM") boxplot(NSGAII_results,NSGAIIDKM_results,names=algs, notch = FALSE) titulo <-paste(indicator) title(main=titulo) } #SPEA2resultDirectory<-"./MutationStudySPEA2/data/" #SPEA2qIndicator <- function(indicator, problem) #{ #filePolynomialMutation<-paste(SPEA2resultDirectory, "PolynomialMutation", sep="/") #filePolynomialMutation<-paste(filePolynomialMutation, problem, sep="/") #filePolynomialMutation<-paste(filePolynomialMutation, indicator, sep="/") #PolynomialMutation<-scan(filePolynomialMutation) #fileDKMutation<-paste(SPEA2resultDirectory, "DKMutation", sep="/") #fileDKMutation<-paste(fileDKMutation, problem, sep="/") #fileDKMutation<-paste(fileDKMutation, indicator, sep="/") #DKMutation<-scan(fileDKMutation) #algs<-c("Polynomial","DKMutation") #boxplot(PolynomialMutation,DKMutation,names=algs, notch = FALSE) #titulo <-paste(indicator, "SPEA2", sep=":") #title(main=titulo) #} par(mfrow=c(2,3)) indicator<-"HV" NSGAIIqIndicator(indicator) indicator<-"IGD" NSGAIIqIndicator(indicator) indicator<-"GD" NSGAIIqIndicator(indicator) indicator<-"Epsilon" NSGAIIqIndicator(indicator) indicator<-"Spread" NSGAIIqIndicator(indicator) #indicator<-"HV" #SPEA2qIndicator(indicator, "OptimizeElecEnergy_SPEA2") #indicator<-"IGD" #SPEA2qIndicator(indicator, "OptimizeElecEnergy_SPEA2") #indicator<-"GD" #SPEA2qIndicator(indicator, "OptimizeElecEnergy_SPEA2") #indicator<-"Epsilon" #SPEA2qIndicator(indicator, "OptimizeElecEnergy_SPEA2")
trades <- read.table("data/trades.csv", header = T, sep = ",", skip = 3, #stringsAsFactors = T, colClasses = c("NULL", "NULL", "factor", "NULL", "factor", "character", "character", "integer", "numeric", "factor", "numeric", "numeric", "factor", "numeric", "factor")) trades str(trades)
/import.R
no_license
olk/examples_R
R
false
false
895
r
trades <- read.table("data/trades.csv", header = T, sep = ",", skip = 3, #stringsAsFactors = T, colClasses = c("NULL", "NULL", "factor", "NULL", "factor", "character", "character", "integer", "numeric", "factor", "numeric", "numeric", "factor", "numeric", "factor")) trades str(trades)
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/ram_service.R \name{ram} \alias{ram} \title{AWS Resource Access Manager} \usage{ ram() } \description{ Use AWS Resource Access Manager to share AWS resources between AWS accounts. To share a resource, you create a resource share, associate the resource with the resource share, and specify the principals that can access the resource. The following principals are supported: \itemize{ \item The ID of an AWS account \item The Amazon Resource Name (ARN) of an OU from AWS Organizations \item The Amazon Resource Name (ARN) of an organization from AWS Organizations } If you specify an AWS account that doesn't exist in the same organization as the account that owns the resource share, the owner of the specified account receives an invitation to accept the resource share. After the owner accepts the invitation, they can access the resources in the resource share. An administrator of the specified account can use IAM policies to restrict access resources in the resource share. } \section{Operations}{ \tabular{ll}{ \link[=ram_accept_resource_share_invitation]{accept_resource_share_invitation} \tab Accepts an invitation to a resource share from another AWS account \cr \link[=ram_associate_resource_share]{associate_resource_share} \tab Associates the specified resource share with the specified principals and resources \cr \link[=ram_create_resource_share]{create_resource_share} \tab Creates a resource share \cr \link[=ram_delete_resource_share]{delete_resource_share} \tab Deletes the specified resource share \cr \link[=ram_disassociate_resource_share]{disassociate_resource_share} \tab Disassociates the specified principals or resources from the specified resource share\cr \link[=ram_enable_sharing_with_aws_organization]{enable_sharing_with_aws_organization} \tab Enables resource sharing within your organization \cr \link[=ram_get_resource_policies]{get_resource_policies} \tab Gets the policies for the specifies resources \cr \link[=ram_get_resource_share_associations]{get_resource_share_associations} \tab Gets the associations for the specified resource share \cr \link[=ram_get_resource_share_invitations]{get_resource_share_invitations} \tab Gets the specified invitations for resource sharing \cr \link[=ram_get_resource_shares]{get_resource_shares} \tab Gets the specified resource shares or all of your resource shares \cr \link[=ram_list_principals]{list_principals} \tab Lists the principals with access to the specified resource \cr \link[=ram_list_resources]{list_resources} \tab Lists the resources that the specified principal can access \cr \link[=ram_reject_resource_share_invitation]{reject_resource_share_invitation} \tab Rejects an invitation to a resource share from another AWS account \cr \link[=ram_tag_resource]{tag_resource} \tab Adds the specified tags to the specified resource share \cr \link[=ram_untag_resource]{untag_resource} \tab Removes the specified tags from the specified resource share \cr \link[=ram_update_resource_share]{update_resource_share} \tab Updates the specified resource share } } \examples{ \donttest{svc <- ram() svc$accept_resource_share_invitation( Foo = 123 )} }
/paws/man/ram.Rd
permissive
peoplecure/paws
R
false
true
3,221
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/ram_service.R \name{ram} \alias{ram} \title{AWS Resource Access Manager} \usage{ ram() } \description{ Use AWS Resource Access Manager to share AWS resources between AWS accounts. To share a resource, you create a resource share, associate the resource with the resource share, and specify the principals that can access the resource. The following principals are supported: \itemize{ \item The ID of an AWS account \item The Amazon Resource Name (ARN) of an OU from AWS Organizations \item The Amazon Resource Name (ARN) of an organization from AWS Organizations } If you specify an AWS account that doesn't exist in the same organization as the account that owns the resource share, the owner of the specified account receives an invitation to accept the resource share. After the owner accepts the invitation, they can access the resources in the resource share. An administrator of the specified account can use IAM policies to restrict access resources in the resource share. } \section{Operations}{ \tabular{ll}{ \link[=ram_accept_resource_share_invitation]{accept_resource_share_invitation} \tab Accepts an invitation to a resource share from another AWS account \cr \link[=ram_associate_resource_share]{associate_resource_share} \tab Associates the specified resource share with the specified principals and resources \cr \link[=ram_create_resource_share]{create_resource_share} \tab Creates a resource share \cr \link[=ram_delete_resource_share]{delete_resource_share} \tab Deletes the specified resource share \cr \link[=ram_disassociate_resource_share]{disassociate_resource_share} \tab Disassociates the specified principals or resources from the specified resource share\cr \link[=ram_enable_sharing_with_aws_organization]{enable_sharing_with_aws_organization} \tab Enables resource sharing within your organization \cr \link[=ram_get_resource_policies]{get_resource_policies} \tab Gets the policies for the specifies resources \cr \link[=ram_get_resource_share_associations]{get_resource_share_associations} \tab Gets the associations for the specified resource share \cr \link[=ram_get_resource_share_invitations]{get_resource_share_invitations} \tab Gets the specified invitations for resource sharing \cr \link[=ram_get_resource_shares]{get_resource_shares} \tab Gets the specified resource shares or all of your resource shares \cr \link[=ram_list_principals]{list_principals} \tab Lists the principals with access to the specified resource \cr \link[=ram_list_resources]{list_resources} \tab Lists the resources that the specified principal can access \cr \link[=ram_reject_resource_share_invitation]{reject_resource_share_invitation} \tab Rejects an invitation to a resource share from another AWS account \cr \link[=ram_tag_resource]{tag_resource} \tab Adds the specified tags to the specified resource share \cr \link[=ram_untag_resource]{untag_resource} \tab Removes the specified tags from the specified resource share \cr \link[=ram_update_resource_share]{update_resource_share} \tab Updates the specified resource share } } \examples{ \donttest{svc <- ram() svc$accept_resource_share_invitation( Foo = 123 )} }
#--PLOT MSE OF FILTERED VS SMOOTH-- # M monte carlo runs # Test 2 cases sigma.meas=3 and sigma.meas=1 #load library source("filter_mod.R") #set model variables x0<-0 tau<-100 sigma<-3 sigma.meas<-3 #sigma.meas=1 N<-500 M<-100 #generate states and simulated data y set.seed(123) x<-rand.walk.1D(tau=tau,x0=x0,sigma=sigma) y.mat<-matrix(NA,nrow=tau,ncol=M) for(k in 1:M){ y.mat[,k]<-rand.y.1D(x,sigma.meas=sigma.meas) } #compute MSE for smoothing and filtered MSE<-matrix(NA,tau,M) MSE.filter<-matrix(NA,tau,M) means<-matrix(NA,tau,M) means.filter<-matrix(NA,tau,M) neff<-matrix(NA,tau,M) for(k in 1:M){ obj<-particle.filter.path(N=N,x=x,y=y.mat[,k],x0=5,sigma=sigma,sigma.meas=sigma.meas,resample.type="standard",N.thr=1) x.pf<-obj$x.pf.out means.filter[,k]<-obj$m.out means[,k]<-rowMeans(x.pf) MSE[,k]<-(rowMeans(x.pf)-x)^2 MSE.filter[,k]<-(obj$m.out-x)^2 neff[,k]<-obj$N.eff.out } #plot MSE for smoothing and filtered plot(rowMeans(MSE),main="MSE",ylab="MSE",xlab="Time,t",type="l") lines(rowMeans(MSE.filter),col="red",type="l") legend(10, 14, legend=c("Filtered", "Joint Smoothing"), col=c( "red","black"),pch=c(1,1), cex=0.8) #legend(75, 1.8, legend=c("Filtered", "Joint Smoothing"), # col=c( "red","black"),pch=c(1,1), cex=0.8)
/R/old_scripts/smooth_vs_filter_plot.R
no_license
tintinthong/pfilter
R
false
false
1,270
r
#--PLOT MSE OF FILTERED VS SMOOTH-- # M monte carlo runs # Test 2 cases sigma.meas=3 and sigma.meas=1 #load library source("filter_mod.R") #set model variables x0<-0 tau<-100 sigma<-3 sigma.meas<-3 #sigma.meas=1 N<-500 M<-100 #generate states and simulated data y set.seed(123) x<-rand.walk.1D(tau=tau,x0=x0,sigma=sigma) y.mat<-matrix(NA,nrow=tau,ncol=M) for(k in 1:M){ y.mat[,k]<-rand.y.1D(x,sigma.meas=sigma.meas) } #compute MSE for smoothing and filtered MSE<-matrix(NA,tau,M) MSE.filter<-matrix(NA,tau,M) means<-matrix(NA,tau,M) means.filter<-matrix(NA,tau,M) neff<-matrix(NA,tau,M) for(k in 1:M){ obj<-particle.filter.path(N=N,x=x,y=y.mat[,k],x0=5,sigma=sigma,sigma.meas=sigma.meas,resample.type="standard",N.thr=1) x.pf<-obj$x.pf.out means.filter[,k]<-obj$m.out means[,k]<-rowMeans(x.pf) MSE[,k]<-(rowMeans(x.pf)-x)^2 MSE.filter[,k]<-(obj$m.out-x)^2 neff[,k]<-obj$N.eff.out } #plot MSE for smoothing and filtered plot(rowMeans(MSE),main="MSE",ylab="MSE",xlab="Time,t",type="l") lines(rowMeans(MSE.filter),col="red",type="l") legend(10, 14, legend=c("Filtered", "Joint Smoothing"), col=c( "red","black"),pch=c(1,1), cex=0.8) #legend(75, 1.8, legend=c("Filtered", "Joint Smoothing"), # col=c( "red","black"),pch=c(1,1), cex=0.8)