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
## File Location fileurl<- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip" ## Download file to a temporary location, read in dataframe, and delete tempfile temp<-tempfile() download.file(fileurl, temp) filename<-unzip(temp, list=TRUE)[[1]] message("Reading in data frame... please wait.") data<-read.csv(unzip(temp,filename), header = TRUE, sep = ";", na.strings = c("?")) unlink(temp) unlink(filename) ## Converting dates, subsetting data$Date <- as.Date(data$Date, format = "%d/%m/%Y") Date1 <- as.Date("2007-02-01", format = "%Y-%m-%d") Date2 <- as.Date("2007-02-02", format = "%Y-%m-%d") data<-subset(data, (data$Date == Date1) | (data$Date == Date2)) ## Combining date and time x<-strptime(as.vector(paste(data$Date, data$Time)), format = "%Y-%m-%d %H:%M:%S", tz="") ## Generating the 2 by 2 plots png(file = "plot4.png", bg = "white") par(mfrow = c(2,2)) plot(x,data$Global_active_power, xlab = "", ylab = "Global Active Power (kilowatts)", type = "l") plot(x,data$Voltage, xlab = "datetime", ylab = "Voltage", type = "l") plot(x,data$Sub_metering_1, xlab = "", ylab = "Energy sub metering", type = "l") lines(x, data$Sub_metering_2, col = "red") lines(x, data$Sub_metering_3, col = "blue") legend("topright", names(data)[7:9], bty ="n", col = c("black", "red", "blue"), lty = c(1,1,1)) plot(x, data$Global_reactive_power, xlab = "datetime", ylab = "Global_reactive_power", type="l") dev.off() message("Done! Plots stored as plot4.png")
/CP1/plot4.R
no_license
lachrymator/ExpDataAnalysis
R
false
false
1,493
r
## File Location fileurl<- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip" ## Download file to a temporary location, read in dataframe, and delete tempfile temp<-tempfile() download.file(fileurl, temp) filename<-unzip(temp, list=TRUE)[[1]] message("Reading in data frame... please wait.") data<-read.csv(unzip(temp,filename), header = TRUE, sep = ";", na.strings = c("?")) unlink(temp) unlink(filename) ## Converting dates, subsetting data$Date <- as.Date(data$Date, format = "%d/%m/%Y") Date1 <- as.Date("2007-02-01", format = "%Y-%m-%d") Date2 <- as.Date("2007-02-02", format = "%Y-%m-%d") data<-subset(data, (data$Date == Date1) | (data$Date == Date2)) ## Combining date and time x<-strptime(as.vector(paste(data$Date, data$Time)), format = "%Y-%m-%d %H:%M:%S", tz="") ## Generating the 2 by 2 plots png(file = "plot4.png", bg = "white") par(mfrow = c(2,2)) plot(x,data$Global_active_power, xlab = "", ylab = "Global Active Power (kilowatts)", type = "l") plot(x,data$Voltage, xlab = "datetime", ylab = "Voltage", type = "l") plot(x,data$Sub_metering_1, xlab = "", ylab = "Energy sub metering", type = "l") lines(x, data$Sub_metering_2, col = "red") lines(x, data$Sub_metering_3, col = "blue") legend("topright", names(data)[7:9], bty ="n", col = c("black", "red", "blue"), lty = c(1,1,1)) plot(x, data$Global_reactive_power, xlab = "datetime", ylab = "Global_reactive_power", type="l") dev.off() message("Done! Plots stored as plot4.png")
#P(t | l) = P(l | t) P(t) dt <- function(t, l, n, b){ f <- function(tc)dtl(tc, l) * d_mutant_age2(t-tc, n, b) integrate(f, 0, t-1e-14)$value } dtl <- function(t, l) pt(t) * plt(t, l) / pl(l) pt <- function(t) dexp(t, 1) plt <- function(t, l) dexp(l * 1e-4, t) pl <- function(l){ f <- function(t)pt(t) * plt(t, l) integrate(f, 0, Inf)$value } #eq 5.1 in griffiths tavare 2003 #n : sample size #b : subsample size #t : time #d_mutant_age: exact eqn #d_mu d_mutant_age2 <- function(t, n, b){ sapply(t, d_mutant_age_detapprox_st, n, b) } d_mutant_age <- function(t, n, b){ sapply(t, d_mutant_age_single_t, n, b) } d_mutant_age_single_t <- function(t, n, b){ k <- 2:n a <- sum(exp(log(k) + p_nk(b, n, k, log=T) + log(PA_n(k, t, n)))) b <- sum(exp(log(k) + p_nk(b, n, k, log=T) + lET_k(k))) a / b } d_mutant_age_detapprox_st<- function(t, n, b){ ka <- EA_n(t, n) a <- exp(log(ka) + p_nk_cont(b, n, ka, log=T) ) k <- 2:n b <- sum(exp(log(k) + p_nk(b, n, k, log=T) + lET_k(k))) a / b } p_nk <- function(b, n, k, log=F){ if (log){ lchoose(n-b-1, k-2) - lchoose(n-1, k-1) } else { choose(n-b-1, k-2) / choose(n-1, k-1) } } p_nk_cont <- function(b, n, k, log=T){ a = lgamma(n-b) - lgamma(k-1) - lgamma(n-b - k + 2) b = lgamma(n) - lgamma(k) - lgamma(n - k +1) a - b } ET_k <- function(k){ 1 / choose(k, 2) } lET_k <- function(k){ - lchoose(k, 2) } PA_n <- function(k, t, n){ sapply(k, PA_n_single_k, t, n) } PA_n_single_k <- function(k, t, n){ j <- k:n sign <- (-1)^(j-k) log_rho_jt <- -choose(j, 2) * t a <- log(2 * j - 1) + lrfact(k, j-1) + lffact(n, j) b <- lfactorial(k) + lfactorial(j-k) + lrfact(n, j) log_terms <- log_rho_jt + a - b sum(sign * exp(log_terms)) } EA_n <- function(t, n){ n / (n + (1-n)*exp(-t/2) ) } rfact <- function(x,y){ if(y==0) return (1) mapply(function(x, y)prod(x:(x+y-1)), x, y) } lrfact <- function(x,y){ res <- mapply(function(x, y)sum(log(x:(x+y-1))), x, y) res[y==0] <- 0 res } lffact <- function(x,y){ res <- mapply(function(x, y)sum(log(x:(x-y+1))), x, y) res[y==0] <- 0 res }
/scripts/age.R
no_license
BenjaminPeter/hapage
R
false
false
2,237
r
#P(t | l) = P(l | t) P(t) dt <- function(t, l, n, b){ f <- function(tc)dtl(tc, l) * d_mutant_age2(t-tc, n, b) integrate(f, 0, t-1e-14)$value } dtl <- function(t, l) pt(t) * plt(t, l) / pl(l) pt <- function(t) dexp(t, 1) plt <- function(t, l) dexp(l * 1e-4, t) pl <- function(l){ f <- function(t)pt(t) * plt(t, l) integrate(f, 0, Inf)$value } #eq 5.1 in griffiths tavare 2003 #n : sample size #b : subsample size #t : time #d_mutant_age: exact eqn #d_mu d_mutant_age2 <- function(t, n, b){ sapply(t, d_mutant_age_detapprox_st, n, b) } d_mutant_age <- function(t, n, b){ sapply(t, d_mutant_age_single_t, n, b) } d_mutant_age_single_t <- function(t, n, b){ k <- 2:n a <- sum(exp(log(k) + p_nk(b, n, k, log=T) + log(PA_n(k, t, n)))) b <- sum(exp(log(k) + p_nk(b, n, k, log=T) + lET_k(k))) a / b } d_mutant_age_detapprox_st<- function(t, n, b){ ka <- EA_n(t, n) a <- exp(log(ka) + p_nk_cont(b, n, ka, log=T) ) k <- 2:n b <- sum(exp(log(k) + p_nk(b, n, k, log=T) + lET_k(k))) a / b } p_nk <- function(b, n, k, log=F){ if (log){ lchoose(n-b-1, k-2) - lchoose(n-1, k-1) } else { choose(n-b-1, k-2) / choose(n-1, k-1) } } p_nk_cont <- function(b, n, k, log=T){ a = lgamma(n-b) - lgamma(k-1) - lgamma(n-b - k + 2) b = lgamma(n) - lgamma(k) - lgamma(n - k +1) a - b } ET_k <- function(k){ 1 / choose(k, 2) } lET_k <- function(k){ - lchoose(k, 2) } PA_n <- function(k, t, n){ sapply(k, PA_n_single_k, t, n) } PA_n_single_k <- function(k, t, n){ j <- k:n sign <- (-1)^(j-k) log_rho_jt <- -choose(j, 2) * t a <- log(2 * j - 1) + lrfact(k, j-1) + lffact(n, j) b <- lfactorial(k) + lfactorial(j-k) + lrfact(n, j) log_terms <- log_rho_jt + a - b sum(sign * exp(log_terms)) } EA_n <- function(t, n){ n / (n + (1-n)*exp(-t/2) ) } rfact <- function(x,y){ if(y==0) return (1) mapply(function(x, y)prod(x:(x+y-1)), x, y) } lrfact <- function(x,y){ res <- mapply(function(x, y)sum(log(x:(x+y-1))), x, y) res[y==0] <- 0 res } lffact <- function(x,y){ res <- mapply(function(x, y)sum(log(x:(x-y+1))), x, y) res[y==0] <- 0 res }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/mcnemar-test.R \name{mcnemar_test} \alias{mcnemar_test} \title{McNemar Test} \usage{ mcnemar_test(x, y = NULL) } \arguments{ \item{x}{2 x 2 matrix or 2 x 2 table or numeric variable or factor variable} \item{y}{numeric or factor variable} } \value{ \code{mcnemar_test} returns an object of class \code{"mcnemar_test"}. An object of class \code{"mcnemar_test"} is a list containing the following components: \item{statistic}{chi square statistic} \item{df}{degrees of freedom} \item{pvalue}{p-value} \item{exactp}{exact p-value} \item{cstat}{continuity correction chi square statistic} \item{cpvalue}{continuity correction p-value} \item{kappa}{kappa coefficient; measure of interrater agreement} \item{std_err}{asymptotic standard error} \item{kappa_cil}{95\% kappa lower confidence limit} \item{kappa_ciu}{95\% kappa upper confidence limit} \item{cases}{cases} \item{controls}{controls} \item{ratio}{ratio of proportion with factor} \item{odratio}{odds ratio} \item{tbl}{two way table} } \description{ Test if the proportions of two dichotomous variables are equal in the same population. } \examples{ # test if the proportion of students in himath and hiread group is same himath <- ifelse(hsb$math > 60, 1, 0) hiread <- ifelse(hsb$read > 60, 1, 0) mcnemar_test(table(himath, hiread)) # using matrix mcnemar_test(matrix(c(135, 18, 21, 26), nrow = 2)) } \references{ Sheskin, D. J. 2007. Handbook of Parametric and Nonparametric Statistical Procedures, 4th edition. : Chapman & Hall/CRC. } \seealso{ \code{\link[stats]{mcnemar.test}} }
/man/mcnemar_test.Rd
no_license
sunilkumar87/inferr
R
false
true
1,619
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/mcnemar-test.R \name{mcnemar_test} \alias{mcnemar_test} \title{McNemar Test} \usage{ mcnemar_test(x, y = NULL) } \arguments{ \item{x}{2 x 2 matrix or 2 x 2 table or numeric variable or factor variable} \item{y}{numeric or factor variable} } \value{ \code{mcnemar_test} returns an object of class \code{"mcnemar_test"}. An object of class \code{"mcnemar_test"} is a list containing the following components: \item{statistic}{chi square statistic} \item{df}{degrees of freedom} \item{pvalue}{p-value} \item{exactp}{exact p-value} \item{cstat}{continuity correction chi square statistic} \item{cpvalue}{continuity correction p-value} \item{kappa}{kappa coefficient; measure of interrater agreement} \item{std_err}{asymptotic standard error} \item{kappa_cil}{95\% kappa lower confidence limit} \item{kappa_ciu}{95\% kappa upper confidence limit} \item{cases}{cases} \item{controls}{controls} \item{ratio}{ratio of proportion with factor} \item{odratio}{odds ratio} \item{tbl}{two way table} } \description{ Test if the proportions of two dichotomous variables are equal in the same population. } \examples{ # test if the proportion of students in himath and hiread group is same himath <- ifelse(hsb$math > 60, 1, 0) hiread <- ifelse(hsb$read > 60, 1, 0) mcnemar_test(table(himath, hiread)) # using matrix mcnemar_test(matrix(c(135, 18, 21, 26), nrow = 2)) } \references{ Sheskin, D. J. 2007. Handbook of Parametric and Nonparametric Statistical Procedures, 4th edition. : Chapman & Hall/CRC. } \seealso{ \code{\link[stats]{mcnemar.test}} }
getwd() setwd('/home/parikshit/Desktop/R') install.packages("dplyr") library(dplyr) # downloading data FileLocation <- "https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip" File <- "UCI HAR Dataset.zip" if (!file.exists(File)) { download.file(FileLocation, File, mode = "wb") } # unziping zip dataLocation <- "UCI HAR Dataset" if (!file.exists(dataLocation)) { unzip(File) } # read training data trainingSubjects <- read.table(file.path(dataLocation, "train", "subject_train.txt")) trainingValues <- read.table(file.path(dataLocation, "train", "X_train.txt")) trainingActivity <- read.table(file.path(dataLocation, "train", "y_train.txt")) # read test data testSubjects <- read.table(file.path(dataLocation, "test", "subject_test.txt")) testValues <- read.table(file.path(dataLocation, "test", "X_test.txt")) testActivity <- read.table(file.path(dataLocation, "test", "y_test.txt")) # read features features <- read.table(file.path(dataLocation, "features.txt"), as.is = TRUE) # read activity labels activities <- read.table(file.path(dataLocation, "activity_labels.txt")) colnames(activities) <- c("activityId", "activityLabel") # Merge train and test datasets humanActivity <- rbind( cbind(trainingSubjects, trainingValues, trainingActivity), cbind(testSubjects, testValues, testActivity) ) # remove individual data tables to save memory rm(trainingSubjects, trainingValues, trainingActivity, testSubjects, testValues, testActivity) # assign column names colnames(humanActivity) <- c("subject", features[, 2], "activity") # determine columns of data set to keep based on column name... columnsToKeep <- grepl("subject|activity|mean|std", colnames(humanActivity)) # ... and keep data in these columns only humanActivity <- humanActivity[, columnsToKeep] # replace activity values with named factor levels humanActivity$activity <- factor(humanActivity$activity, levels = activities[, 1], labels = activities[, 2]) # get column names humanActivityCols <- colnames(humanActivity) # remove special characters humanActivityCols <- gsub("[\\(\\)-]", "", humanActivityCols) # expand abbreviations and clean up names humanActivityCols <- gsub("^f", "frequencyDomain", humanActivityCols) humanActivityCols <- gsub("^t", "timeDomain", humanActivityCols) humanActivityCols <- gsub("Acc", "Accelerometer", humanActivityCols) humanActivityCols <- gsub("Gyro", "Gyroscope", humanActivityCols) humanActivityCols <- gsub("Mag", "Magnitude", humanActivityCols) humanActivityCols <- gsub("Freq", "Frequency", humanActivityCols) humanActivityCols <- gsub("mean", "Mean", humanActivityCols) humanActivityCols <- gsub("std", "StandardDeviation", humanActivityCols) # correct typo humanActivityCols <- gsub("BodyBody", "Body", humanActivityCols) # use new labels as column names colnames(humanActivity) <- humanActivityCols # group by subject and activity and summarise using mean humanActivityMeans <- humanActivity %>% group_by(subject, activity) %>% summarise_all(funs(mean)) # output to file "tidy_data.txt" write.table(humanActivityMeans, "tidy_data.txt", row.names = FALSE, quote = FALSE)
/run_analysis.R
no_license
ParikshitAD/getting-and-cleaning-data-course-project
R
false
false
3,246
r
getwd() setwd('/home/parikshit/Desktop/R') install.packages("dplyr") library(dplyr) # downloading data FileLocation <- "https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip" File <- "UCI HAR Dataset.zip" if (!file.exists(File)) { download.file(FileLocation, File, mode = "wb") } # unziping zip dataLocation <- "UCI HAR Dataset" if (!file.exists(dataLocation)) { unzip(File) } # read training data trainingSubjects <- read.table(file.path(dataLocation, "train", "subject_train.txt")) trainingValues <- read.table(file.path(dataLocation, "train", "X_train.txt")) trainingActivity <- read.table(file.path(dataLocation, "train", "y_train.txt")) # read test data testSubjects <- read.table(file.path(dataLocation, "test", "subject_test.txt")) testValues <- read.table(file.path(dataLocation, "test", "X_test.txt")) testActivity <- read.table(file.path(dataLocation, "test", "y_test.txt")) # read features features <- read.table(file.path(dataLocation, "features.txt"), as.is = TRUE) # read activity labels activities <- read.table(file.path(dataLocation, "activity_labels.txt")) colnames(activities) <- c("activityId", "activityLabel") # Merge train and test datasets humanActivity <- rbind( cbind(trainingSubjects, trainingValues, trainingActivity), cbind(testSubjects, testValues, testActivity) ) # remove individual data tables to save memory rm(trainingSubjects, trainingValues, trainingActivity, testSubjects, testValues, testActivity) # assign column names colnames(humanActivity) <- c("subject", features[, 2], "activity") # determine columns of data set to keep based on column name... columnsToKeep <- grepl("subject|activity|mean|std", colnames(humanActivity)) # ... and keep data in these columns only humanActivity <- humanActivity[, columnsToKeep] # replace activity values with named factor levels humanActivity$activity <- factor(humanActivity$activity, levels = activities[, 1], labels = activities[, 2]) # get column names humanActivityCols <- colnames(humanActivity) # remove special characters humanActivityCols <- gsub("[\\(\\)-]", "", humanActivityCols) # expand abbreviations and clean up names humanActivityCols <- gsub("^f", "frequencyDomain", humanActivityCols) humanActivityCols <- gsub("^t", "timeDomain", humanActivityCols) humanActivityCols <- gsub("Acc", "Accelerometer", humanActivityCols) humanActivityCols <- gsub("Gyro", "Gyroscope", humanActivityCols) humanActivityCols <- gsub("Mag", "Magnitude", humanActivityCols) humanActivityCols <- gsub("Freq", "Frequency", humanActivityCols) humanActivityCols <- gsub("mean", "Mean", humanActivityCols) humanActivityCols <- gsub("std", "StandardDeviation", humanActivityCols) # correct typo humanActivityCols <- gsub("BodyBody", "Body", humanActivityCols) # use new labels as column names colnames(humanActivity) <- humanActivityCols # group by subject and activity and summarise using mean humanActivityMeans <- humanActivity %>% group_by(subject, activity) %>% summarise_all(funs(mean)) # output to file "tidy_data.txt" write.table(humanActivityMeans, "tidy_data.txt", row.names = FALSE, quote = FALSE)
#' Convert Lon/Lat to UTM #' #' Convert longitude and latitude coordinates to Universal Transverse #' Mercator coordinates. #' @param lon #' Numeric vector of longitudes. #' @param lat #' Numeric vector of latitudes, same length as \code{lon}. #' @param zone #' Numeric scalar of the UTM zone, default NULL. See details. #' @param quiet #' Logical scalar indicating whether to refrain from printing the determined #' zone when \code{zone} is NULL, default TRUE. #' @details #' If \code{zone} is NULL, then the zone is determined from the medians #' of \code{lon} and \code{lat}. #' @return #' A data frame with two columns (easting and northing) and as many rows as #' the length of \code{lon} containing the converted UTM coordinates in #' meters. #' @export #' @seealso #' \code{\link{lon2utmZone}} #' @references #' Based on a function posted by Stanislav on 13 May 2015 on stackoverflow #' \href{http://stackoverflow.com/a/30225804/2140956}{[link]}. #' @importFrom sp coordinates proj4string CRS spTransform #' @examples #' mylon <- c(-92.11, -76.47, -82.27, -83.42) #' mylat <- c(46.76, 44.34, 44.76, 45.41) #' latlon2utm(mylon, mylat, quiet=FALSE) #' sapply(1:length(mylon), function(i) #' latlon2utm(mylon[i], mylat[i], quiet=FALSE)) #' latlon2utm(mylon, mylat, 18) #' latlon2utm <- function(lon, lat, zone=NULL, quiet=TRUE) { if(is.null(zone)) { zone <- lon2utmZone(median(lon, na.rm=TRUE), median(lat, na.rm=TRUE)) if(!quiet) print(zone) } xy <- data.frame(easting=lon, northing=lat) sp::coordinates(xy) <- c("easting", "northing") sp::proj4string(xy) <- sp::CRS("+proj=longlat +datum=WGS84") res <- sp::spTransform(xy, sp::CRS(paste0("+proj=utm +zone=", zone, " ellps=WGS84"))) return(as.data.frame(res)) }
/R/latlon2utm.R
no_license
JVAdams/EchoNet2Fish
R
false
false
1,768
r
#' Convert Lon/Lat to UTM #' #' Convert longitude and latitude coordinates to Universal Transverse #' Mercator coordinates. #' @param lon #' Numeric vector of longitudes. #' @param lat #' Numeric vector of latitudes, same length as \code{lon}. #' @param zone #' Numeric scalar of the UTM zone, default NULL. See details. #' @param quiet #' Logical scalar indicating whether to refrain from printing the determined #' zone when \code{zone} is NULL, default TRUE. #' @details #' If \code{zone} is NULL, then the zone is determined from the medians #' of \code{lon} and \code{lat}. #' @return #' A data frame with two columns (easting and northing) and as many rows as #' the length of \code{lon} containing the converted UTM coordinates in #' meters. #' @export #' @seealso #' \code{\link{lon2utmZone}} #' @references #' Based on a function posted by Stanislav on 13 May 2015 on stackoverflow #' \href{http://stackoverflow.com/a/30225804/2140956}{[link]}. #' @importFrom sp coordinates proj4string CRS spTransform #' @examples #' mylon <- c(-92.11, -76.47, -82.27, -83.42) #' mylat <- c(46.76, 44.34, 44.76, 45.41) #' latlon2utm(mylon, mylat, quiet=FALSE) #' sapply(1:length(mylon), function(i) #' latlon2utm(mylon[i], mylat[i], quiet=FALSE)) #' latlon2utm(mylon, mylat, 18) #' latlon2utm <- function(lon, lat, zone=NULL, quiet=TRUE) { if(is.null(zone)) { zone <- lon2utmZone(median(lon, na.rm=TRUE), median(lat, na.rm=TRUE)) if(!quiet) print(zone) } xy <- data.frame(easting=lon, northing=lat) sp::coordinates(xy) <- c("easting", "northing") sp::proj4string(xy) <- sp::CRS("+proj=longlat +datum=WGS84") res <- sp::spTransform(xy, sp::CRS(paste0("+proj=utm +zone=", zone, " ellps=WGS84"))) return(as.data.frame(res)) }
#!/usr/bin/env Rscript # Author: David Scott # Contact: david.scott18@imperial.ac.uk # Date: October 24 2018 # Description: use of apply function rm(list=ls()) # clears workspace # use of *apply functions # vectorise data for you ## apply: applying the same function to rows/colums of a matrix ## Build a random matrix M <- matrix(rnorm(100), 10, 10) ## Take the mean of each row RowMeans <- apply(M, 1, mean) print (RowMeans) ## Now the variance RowVars <- apply(M, 1, var) print (RowVars) ## By column ColMeans <- apply(M, 2, mean) print (ColMeans)
/Week3/Code/apply1.R
no_license
davidtscott/CMEECoursework
R
false
false
560
r
#!/usr/bin/env Rscript # Author: David Scott # Contact: david.scott18@imperial.ac.uk # Date: October 24 2018 # Description: use of apply function rm(list=ls()) # clears workspace # use of *apply functions # vectorise data for you ## apply: applying the same function to rows/colums of a matrix ## Build a random matrix M <- matrix(rnorm(100), 10, 10) ## Take the mean of each row RowMeans <- apply(M, 1, mean) print (RowMeans) ## Now the variance RowVars <- apply(M, 1, var) print (RowVars) ## By column ColMeans <- apply(M, 2, mean) print (ColMeans)
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/doSimulation.R \name{doSimulation} \alias{doSimulation} \title{Discrete Time Character Simulation} \usage{ doSimulation(splits, intrinsicFn, extrinsicFn, startingValues, intrinsicValues, extrinsicValues, timeStep, saveHistory = FALSE, saveRealParams = FALSE, jobName = "") } \arguments{ \item{splits}{Output from the function getSimulationSplits; is a data frame of branching times, ancestor and descendant vectors} \item{intrinsicFn}{Name of intrinsic function characters should be simulated under} \item{extrinsicFn}{Name of extrinsic function characters should be simulated under} \item{startingValues}{State at the root} \item{intrinsicValues}{Vector of values corresponding to the params of the intrinsic model} \item{extrinsicValues}{Vector of values corresponding to the params of the extrinsic model} \item{timeStep}{This value corresponds to the number of discrete time steps on the shortest branch} \item{saveHistory}{Saves the character history throughout the simulation} \item{saveRealParams}{Saves intrinsicValues and extrinsicValues as both a matrix and a vector} \item{jobName}{Optional name for the job} } \value{ A data frame of species character (tip) values in the tree. } \description{ This function evolves continuous characters in a discrete time process. } \details{ When saveHistory is TRUE, processor time will increase quite a bit. SaveRealParams is useful for tracking the "real" true values if simulating data for abc runs. It is not useful for empirical abc runs. } \examples{ phy<-rcoal(30) #Simple Brownian motion char<-doSimulation( splits=getSimulationSplits(phy), intrinsicFn=brownianIntrinsic, extrinsicFn=nullExtrinsic, startingValues=c(10), #root state intrinsicValues=c(0.01), extrinsicValues=c(0), timeStep=0.0001, saveHistory=FALSE) #Character displacement model with minimum bound char<-doSimulation( splits=getSimulationSplits(phy), intrinsicFn=boundaryMinIntrinsic, extrinsicFn=ExponentiallyDecayingPush, startingValues=c(10), #root state intrinsicValues=c(0.05, 10, 0.01), extrinsicValues=c(0, .1, .25), timeStep=0.001, saveHistory=FALSE) } \author{ Brian O'Meara and Barb Banbury } \references{ O'Meara and Banbury, unpublished } \keyword{doSimulation}
/man/doSimulation.Rd
no_license
JakeJing/treevo
R
false
true
2,313
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/doSimulation.R \name{doSimulation} \alias{doSimulation} \title{Discrete Time Character Simulation} \usage{ doSimulation(splits, intrinsicFn, extrinsicFn, startingValues, intrinsicValues, extrinsicValues, timeStep, saveHistory = FALSE, saveRealParams = FALSE, jobName = "") } \arguments{ \item{splits}{Output from the function getSimulationSplits; is a data frame of branching times, ancestor and descendant vectors} \item{intrinsicFn}{Name of intrinsic function characters should be simulated under} \item{extrinsicFn}{Name of extrinsic function characters should be simulated under} \item{startingValues}{State at the root} \item{intrinsicValues}{Vector of values corresponding to the params of the intrinsic model} \item{extrinsicValues}{Vector of values corresponding to the params of the extrinsic model} \item{timeStep}{This value corresponds to the number of discrete time steps on the shortest branch} \item{saveHistory}{Saves the character history throughout the simulation} \item{saveRealParams}{Saves intrinsicValues and extrinsicValues as both a matrix and a vector} \item{jobName}{Optional name for the job} } \value{ A data frame of species character (tip) values in the tree. } \description{ This function evolves continuous characters in a discrete time process. } \details{ When saveHistory is TRUE, processor time will increase quite a bit. SaveRealParams is useful for tracking the "real" true values if simulating data for abc runs. It is not useful for empirical abc runs. } \examples{ phy<-rcoal(30) #Simple Brownian motion char<-doSimulation( splits=getSimulationSplits(phy), intrinsicFn=brownianIntrinsic, extrinsicFn=nullExtrinsic, startingValues=c(10), #root state intrinsicValues=c(0.01), extrinsicValues=c(0), timeStep=0.0001, saveHistory=FALSE) #Character displacement model with minimum bound char<-doSimulation( splits=getSimulationSplits(phy), intrinsicFn=boundaryMinIntrinsic, extrinsicFn=ExponentiallyDecayingPush, startingValues=c(10), #root state intrinsicValues=c(0.05, 10, 0.01), extrinsicValues=c(0, .1, .25), timeStep=0.001, saveHistory=FALSE) } \author{ Brian O'Meara and Barb Banbury } \references{ O'Meara and Banbury, unpublished } \keyword{doSimulation}
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/ppt_ph_with_methods.R \name{ph_with} \alias{ph_with} \alias{ph_with.character} \alias{ph_with.numeric} \alias{ph_with.factor} \alias{ph_with.logical} \alias{ph_with.block_list} \alias{ph_with.unordered_list} \alias{ph_with.data.frame} \alias{ph_with.gg} \alias{ph_with.plot_instr} \alias{ph_with.external_img} \alias{ph_with.fpar} \alias{ph_with.empty_content} \alias{ph_with.xml_document} \title{add objects into a new shape on the current slide} \usage{ ph_with(x, value, location, ...) \method{ph_with}{character}(x, value, location, ...) \method{ph_with}{numeric}(x, value, location, format_fun = format, ...) \method{ph_with}{factor}(x, value, location, ...) \method{ph_with}{logical}(x, value, location, format_fun = format, ...) \method{ph_with}{block_list}(x, value, location, is_list = FALSE, ...) \method{ph_with}{unordered_list}(x, value, location, ...) \method{ph_with}{data.frame}( x, value, location, header = TRUE, tcf = table_conditional_formatting(), ... ) \method{ph_with}{gg}(x, value, location, res = 300, ...) \method{ph_with}{plot_instr}(x, value, location, res = 300, ...) \method{ph_with}{external_img}(x, value, location, use_loc_size = TRUE, ...) \method{ph_with}{fpar}(x, value, location, ...) \method{ph_with}{empty_content}(x, value, location, ...) \method{ph_with}{xml_document}(x, value, location, ...) } \arguments{ \item{x}{an rpptx object} \item{value}{object to add as a new shape. Supported objects are vectors, data.frame, graphics, block of formatted paragraphs, unordered list of formatted paragraphs, pretty tables with package flextable, editable graphics with package rvg, 'Microsoft' charts with package mschart.} \item{location}{a placeholder location object. It will be used to specify the location of the new shape. This location can be defined with a call to one of the ph_location functions. See section \code{"see also"}.} \item{...}{further arguments passed to or from other methods. When adding a \code{ggplot} object or \code{plot_instr}, these arguments will be used by png function.} \item{format_fun}{format function for non character vectors} \item{is_list}{experimental paramater to make block_list formated as an unordered list. This should evolve in the next versions.} \item{header}{display header if TRUE} \item{tcf}{conditional formatting settings defined by \code{\link[=table_conditional_formatting]{table_conditional_formatting()}}} \item{res}{resolution of the png image in ppi} \item{use_loc_size}{if set to FALSE, external_img width and height will be used.} } \description{ add object into a new shape in the current slide. This function is able to add all supported outputs to a presentation and should replace calls to older functions starting with \code{ph_with_*}. } \section{Methods (by class)}{ \itemize{ \item \code{character}: add a character vector to a new shape on the current slide, values will be added as paragraphs. \item \code{numeric}: add a numeric vector to a new shape on the current slide, values will be be first formatted then added as paragraphs. \item \code{factor}: add a factor vector to a new shape on the current slide, values will be be converted as character and then added as paragraphs. \item \code{block_list}: add a \code{\link{block_list}} made of \code{\link{fpar}} to a new shape on the current slide. \item \code{unordered_list}: add a \code{\link{unordered_list}} made of \code{\link{fpar}} to a new shape on the current slide. \item \code{data.frame}: add a data.frame to a new shape on the current slide with function \code{\link[=block_table]{block_table()}}. Use package \code{flextable} instead for more advanced formattings. \item \code{gg}: add a ggplot object to a new shape on the current slide. Use package \code{rvg} for more advanced graphical features. \item \code{plot_instr}: add an R plot to a new shape on the current slide. Use package \code{rvg} for more advanced graphical features. \item \code{external_img}: add a \code{\link{external_img}} to a new shape on the current slide. When value is a external_img object, image will be copied into the PowerPoint presentation. The width and height specified in call to \code{external_img} will be ignored, their values will be those of the location, unless use_loc_size is set to FALSE. \item \code{fpar}: add an \code{\link{fpar}} to a new shape on the current slide as a single paragraph in a \code{\link{block_list}}. \item \code{empty_content}: add an \code{\link{empty_content}} to a new shape on the current slide. \item \code{xml_document}: add an xml_document object to a new shape on the current slide. This function is to be used to add custom openxml code. }} \examples{ # this name will be used to print the file # change it to "youfile.pptx" to write the pptx # file in your working directory. fileout <- tempfile(fileext = ".pptx") doc_1 <- read_pptx() sz <- slide_size(doc_1) # add text and a table ---- doc_1 <- add_slide(doc_1, layout = "Two Content", master = "Office Theme") doc_1 <- ph_with(x = doc_1, value = c("Table cars"), location = ph_location_type(type = "title") ) doc_1 <- ph_with(x = doc_1, value = names(cars), location = ph_location_left() ) doc_1 <- ph_with(x = doc_1, value = cars, location = ph_location_right() ) # add a base plot ---- anyplot <- plot_instr(code = { col <- c("#440154FF", "#443A83FF", "#31688EFF", "#21908CFF", "#35B779FF", "#8FD744FF", "#FDE725FF") barplot(1:7, col = col, yaxt="n") }) doc_1 <- add_slide(doc_1) doc_1 <- ph_with( doc_1, anyplot, location = ph_location_fullsize(), bg = "#006699") # add a ggplot2 plot ---- if( require("ggplot2") ){ doc_1 <- add_slide(doc_1) gg_plot <- ggplot(data = iris ) + geom_point(mapping = aes(Sepal.Length, Petal.Length), size = 3) + theme_minimal() doc_1 <- ph_with(x = doc_1, value = gg_plot, location = ph_location_type(type = "body"), bg = "transparent" ) doc_1 <- ph_with(x = doc_1, value = "graphic title", location = ph_location_type(type="title") ) } # add a external images ---- doc_1 <- add_slide(doc_1, layout = "Title and Content", master = "Office Theme") doc_1 <- ph_with(x = doc_1, value = empty_content(), location = ph_location(left = 0, top = 0, width = sz$width, height = sz$height, bg = "black") ) svg_file <- file.path(R.home(component = "doc"), "html/Rlogo.svg") if( require("rsvg") ){ doc_1 <- ph_with(x = doc_1, value = "External images", location = ph_location_type(type = "title") ) doc_1 <- ph_with(x = doc_1, external_img(svg_file, 100/72, 76/72), location = ph_location_right(), use_loc_size = FALSE ) doc_1 <- ph_with(x = doc_1, external_img(svg_file), location = ph_location_left(), use_loc_size = TRUE ) } # add a block_list ---- dummy_text <- readLines(system.file(package = "officer", "doc_examples/text.txt")) fp_1 <- fp_text(bold = TRUE, color = "pink", font.size = 0) fp_2 <- fp_text(bold = TRUE, font.size = 0) fp_3 <- fp_text(italic = TRUE, color="red", font.size = 0) bl <- block_list( fpar(ftext("hello world", fp_1)), fpar( ftext("hello", fp_2), ftext("hello", fp_3) ), dummy_text ) doc_1 <- add_slide(doc_1) doc_1 <- ph_with(x = doc_1, value = bl, location = ph_location_type(type="body") ) # fpar ------ hw <- fpar(ftext("hello world", fp_text(bold = TRUE, font.family = "Bradley Hand", font.size = 150, color = "#F5595B"))) doc_1 <- add_slide(doc_1) doc_1 <- ph_with(x = doc_1, value = hw, location = ph_location_type(type="body") ) # unordered_list ---- ul <- unordered_list( level_list = c(1, 2, 2, 3, 3, 1), str_list = c("Level1", "Level2", "Level2", "Level3", "Level3", "Level1"), style = fp_text(color = "red", font.size = 0) ) doc_1 <- add_slide(doc_1) doc_1 <- ph_with(x = doc_1, value = ul, location = ph_location_type() ) print(doc_1, target = fileout ) } \seealso{ \link{ph_location_type}, \link{ph_location}, \link{ph_location_label}, \link{ph_location_left}, \link{ph_location_right}, \link{ph_location_fullsize}, \link{ph_location_template} }
/man/ph_with.Rd
no_license
berthetclement/officer
R
false
true
8,296
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/ppt_ph_with_methods.R \name{ph_with} \alias{ph_with} \alias{ph_with.character} \alias{ph_with.numeric} \alias{ph_with.factor} \alias{ph_with.logical} \alias{ph_with.block_list} \alias{ph_with.unordered_list} \alias{ph_with.data.frame} \alias{ph_with.gg} \alias{ph_with.plot_instr} \alias{ph_with.external_img} \alias{ph_with.fpar} \alias{ph_with.empty_content} \alias{ph_with.xml_document} \title{add objects into a new shape on the current slide} \usage{ ph_with(x, value, location, ...) \method{ph_with}{character}(x, value, location, ...) \method{ph_with}{numeric}(x, value, location, format_fun = format, ...) \method{ph_with}{factor}(x, value, location, ...) \method{ph_with}{logical}(x, value, location, format_fun = format, ...) \method{ph_with}{block_list}(x, value, location, is_list = FALSE, ...) \method{ph_with}{unordered_list}(x, value, location, ...) \method{ph_with}{data.frame}( x, value, location, header = TRUE, tcf = table_conditional_formatting(), ... ) \method{ph_with}{gg}(x, value, location, res = 300, ...) \method{ph_with}{plot_instr}(x, value, location, res = 300, ...) \method{ph_with}{external_img}(x, value, location, use_loc_size = TRUE, ...) \method{ph_with}{fpar}(x, value, location, ...) \method{ph_with}{empty_content}(x, value, location, ...) \method{ph_with}{xml_document}(x, value, location, ...) } \arguments{ \item{x}{an rpptx object} \item{value}{object to add as a new shape. Supported objects are vectors, data.frame, graphics, block of formatted paragraphs, unordered list of formatted paragraphs, pretty tables with package flextable, editable graphics with package rvg, 'Microsoft' charts with package mschart.} \item{location}{a placeholder location object. It will be used to specify the location of the new shape. This location can be defined with a call to one of the ph_location functions. See section \code{"see also"}.} \item{...}{further arguments passed to or from other methods. When adding a \code{ggplot} object or \code{plot_instr}, these arguments will be used by png function.} \item{format_fun}{format function for non character vectors} \item{is_list}{experimental paramater to make block_list formated as an unordered list. This should evolve in the next versions.} \item{header}{display header if TRUE} \item{tcf}{conditional formatting settings defined by \code{\link[=table_conditional_formatting]{table_conditional_formatting()}}} \item{res}{resolution of the png image in ppi} \item{use_loc_size}{if set to FALSE, external_img width and height will be used.} } \description{ add object into a new shape in the current slide. This function is able to add all supported outputs to a presentation and should replace calls to older functions starting with \code{ph_with_*}. } \section{Methods (by class)}{ \itemize{ \item \code{character}: add a character vector to a new shape on the current slide, values will be added as paragraphs. \item \code{numeric}: add a numeric vector to a new shape on the current slide, values will be be first formatted then added as paragraphs. \item \code{factor}: add a factor vector to a new shape on the current slide, values will be be converted as character and then added as paragraphs. \item \code{block_list}: add a \code{\link{block_list}} made of \code{\link{fpar}} to a new shape on the current slide. \item \code{unordered_list}: add a \code{\link{unordered_list}} made of \code{\link{fpar}} to a new shape on the current slide. \item \code{data.frame}: add a data.frame to a new shape on the current slide with function \code{\link[=block_table]{block_table()}}. Use package \code{flextable} instead for more advanced formattings. \item \code{gg}: add a ggplot object to a new shape on the current slide. Use package \code{rvg} for more advanced graphical features. \item \code{plot_instr}: add an R plot to a new shape on the current slide. Use package \code{rvg} for more advanced graphical features. \item \code{external_img}: add a \code{\link{external_img}} to a new shape on the current slide. When value is a external_img object, image will be copied into the PowerPoint presentation. The width and height specified in call to \code{external_img} will be ignored, their values will be those of the location, unless use_loc_size is set to FALSE. \item \code{fpar}: add an \code{\link{fpar}} to a new shape on the current slide as a single paragraph in a \code{\link{block_list}}. \item \code{empty_content}: add an \code{\link{empty_content}} to a new shape on the current slide. \item \code{xml_document}: add an xml_document object to a new shape on the current slide. This function is to be used to add custom openxml code. }} \examples{ # this name will be used to print the file # change it to "youfile.pptx" to write the pptx # file in your working directory. fileout <- tempfile(fileext = ".pptx") doc_1 <- read_pptx() sz <- slide_size(doc_1) # add text and a table ---- doc_1 <- add_slide(doc_1, layout = "Two Content", master = "Office Theme") doc_1 <- ph_with(x = doc_1, value = c("Table cars"), location = ph_location_type(type = "title") ) doc_1 <- ph_with(x = doc_1, value = names(cars), location = ph_location_left() ) doc_1 <- ph_with(x = doc_1, value = cars, location = ph_location_right() ) # add a base plot ---- anyplot <- plot_instr(code = { col <- c("#440154FF", "#443A83FF", "#31688EFF", "#21908CFF", "#35B779FF", "#8FD744FF", "#FDE725FF") barplot(1:7, col = col, yaxt="n") }) doc_1 <- add_slide(doc_1) doc_1 <- ph_with( doc_1, anyplot, location = ph_location_fullsize(), bg = "#006699") # add a ggplot2 plot ---- if( require("ggplot2") ){ doc_1 <- add_slide(doc_1) gg_plot <- ggplot(data = iris ) + geom_point(mapping = aes(Sepal.Length, Petal.Length), size = 3) + theme_minimal() doc_1 <- ph_with(x = doc_1, value = gg_plot, location = ph_location_type(type = "body"), bg = "transparent" ) doc_1 <- ph_with(x = doc_1, value = "graphic title", location = ph_location_type(type="title") ) } # add a external images ---- doc_1 <- add_slide(doc_1, layout = "Title and Content", master = "Office Theme") doc_1 <- ph_with(x = doc_1, value = empty_content(), location = ph_location(left = 0, top = 0, width = sz$width, height = sz$height, bg = "black") ) svg_file <- file.path(R.home(component = "doc"), "html/Rlogo.svg") if( require("rsvg") ){ doc_1 <- ph_with(x = doc_1, value = "External images", location = ph_location_type(type = "title") ) doc_1 <- ph_with(x = doc_1, external_img(svg_file, 100/72, 76/72), location = ph_location_right(), use_loc_size = FALSE ) doc_1 <- ph_with(x = doc_1, external_img(svg_file), location = ph_location_left(), use_loc_size = TRUE ) } # add a block_list ---- dummy_text <- readLines(system.file(package = "officer", "doc_examples/text.txt")) fp_1 <- fp_text(bold = TRUE, color = "pink", font.size = 0) fp_2 <- fp_text(bold = TRUE, font.size = 0) fp_3 <- fp_text(italic = TRUE, color="red", font.size = 0) bl <- block_list( fpar(ftext("hello world", fp_1)), fpar( ftext("hello", fp_2), ftext("hello", fp_3) ), dummy_text ) doc_1 <- add_slide(doc_1) doc_1 <- ph_with(x = doc_1, value = bl, location = ph_location_type(type="body") ) # fpar ------ hw <- fpar(ftext("hello world", fp_text(bold = TRUE, font.family = "Bradley Hand", font.size = 150, color = "#F5595B"))) doc_1 <- add_slide(doc_1) doc_1 <- ph_with(x = doc_1, value = hw, location = ph_location_type(type="body") ) # unordered_list ---- ul <- unordered_list( level_list = c(1, 2, 2, 3, 3, 1), str_list = c("Level1", "Level2", "Level2", "Level3", "Level3", "Level1"), style = fp_text(color = "red", font.size = 0) ) doc_1 <- add_slide(doc_1) doc_1 <- ph_with(x = doc_1, value = ul, location = ph_location_type() ) print(doc_1, target = fileout ) } \seealso{ \link{ph_location_type}, \link{ph_location}, \link{ph_location_label}, \link{ph_location_left}, \link{ph_location_right}, \link{ph_location_fullsize}, \link{ph_location_template} }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/data.R \docType{data} \name{flow_survival_params} \alias{flow_survival_params} \title{Flow-survival parameters} \format{A list of named vectors (B0) for the following reaches: \describe{ \item{Sac1}{Sacramento River from Freeport to junction with Sutter Slough.} \item{Sac2}{Sacramento River from Sutter Slough junction to junction with Delta Cross Channel.} \item{Sac3}{Sacramento River from Delta Cross Channel junction to Rio Vista.} \item{SS}{Combined reach of Sutter Slough and Steamboat Slough ending at Rio Vista.} }} \usage{ flow_survival_params } \description{ Statistical parameters for the flow-survival relationship. } \keyword{datasets}
/man/flow_survival_params.Rd
no_license
fishsciences/DeltaPassageModel
R
false
true
736
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/data.R \docType{data} \name{flow_survival_params} \alias{flow_survival_params} \title{Flow-survival parameters} \format{A list of named vectors (B0) for the following reaches: \describe{ \item{Sac1}{Sacramento River from Freeport to junction with Sutter Slough.} \item{Sac2}{Sacramento River from Sutter Slough junction to junction with Delta Cross Channel.} \item{Sac3}{Sacramento River from Delta Cross Channel junction to Rio Vista.} \item{SS}{Combined reach of Sutter Slough and Steamboat Slough ending at Rio Vista.} }} \usage{ flow_survival_params } \description{ Statistical parameters for the flow-survival relationship. } \keyword{datasets}
\name{plot.biso} \alias{plot.biso} \title{ Plot a biso object} \description{ Plots the data and the fit a Bayesian monontoic regression function (with optional confidence bands) } \usage{ \method{plot}{biso}(x, xnew, cl = TRUE, add = FALSE, color ="red", \dots) } \arguments{ \item{x}{ a \code{biso} object} \item{xnew}{ \code{x} values at which to plot the regression fit. If missing, the function uses the orginal \code{x} values } \item{cl}{ plot confidence bands (default is \code{TRUE}) } \item{add}{ add a line to the existing plot rather than create a new plot (default is \code{FALSE})} \item{color}{ color of the fitted line (default is red)} \item{\dots}{ other options to pass to the plotting functions} } \details{None.} \value{Returns a plot.} \references{None.} \author{S. McKay Curtis} \note{None.} \seealso{\code{\link{bisoreg}}} \examples{ ## See examples for bisoreg } \keyword{smooth}
/man/plot.biso.Rd
no_license
cran/bisoreg
R
false
false
943
rd
\name{plot.biso} \alias{plot.biso} \title{ Plot a biso object} \description{ Plots the data and the fit a Bayesian monontoic regression function (with optional confidence bands) } \usage{ \method{plot}{biso}(x, xnew, cl = TRUE, add = FALSE, color ="red", \dots) } \arguments{ \item{x}{ a \code{biso} object} \item{xnew}{ \code{x} values at which to plot the regression fit. If missing, the function uses the orginal \code{x} values } \item{cl}{ plot confidence bands (default is \code{TRUE}) } \item{add}{ add a line to the existing plot rather than create a new plot (default is \code{FALSE})} \item{color}{ color of the fitted line (default is red)} \item{\dots}{ other options to pass to the plotting functions} } \details{None.} \value{Returns a plot.} \references{None.} \author{S. McKay Curtis} \note{None.} \seealso{\code{\link{bisoreg}}} \examples{ ## See examples for bisoreg } \keyword{smooth}
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/util.R \name{addAverages} \alias{addAverages} \title{Add averages} \usage{ addAverages(data_set) } \arguments{ \item{data_set}{the data frame to add averages to} } \value{ the same data_set with averages added for pitchers, batters, and league } \description{ Add averages }
/matchups/man/addAverages.Rd
no_license
dpmeixner/baseball
R
false
true
353
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/util.R \name{addAverages} \alias{addAverages} \title{Add averages} \usage{ addAverages(data_set) } \arguments{ \item{data_set}{the data frame to add averages to} } \value{ the same data_set with averages added for pitchers, batters, and league } \description{ Add averages }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/whibo_clustering.R \name{plot_pairs} \alias{plot_pairs} \title{Plot WhiBo Cluster Representatives} \usage{ plot_pairs(model, data) } \arguments{ \item{model}{WhiBo Cluster model.} \item{data}{Data used for clustering (optional).} } \value{ Ploting pairs plot where Cluster representatives are presented with data (if provided). } \description{ Plot WhiBo Cluster Representatives } \examples{ data <- iris[, 1:4] #Numerical data only model <- whibo_clustering(data = data, k = 3) plot_pairs(model) #Ploting Cluster Representatives only plot_pairs(model, data) #Ploting Cluster Representatives and Data } \author{ Sandro Radovanovic \email{sandro.radovanovic@gmail.com} }
/man/plot_pairs.Rd
no_license
cran/whiboclustering
R
false
true
783
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/whibo_clustering.R \name{plot_pairs} \alias{plot_pairs} \title{Plot WhiBo Cluster Representatives} \usage{ plot_pairs(model, data) } \arguments{ \item{model}{WhiBo Cluster model.} \item{data}{Data used for clustering (optional).} } \value{ Ploting pairs plot where Cluster representatives are presented with data (if provided). } \description{ Plot WhiBo Cluster Representatives } \examples{ data <- iris[, 1:4] #Numerical data only model <- whibo_clustering(data = data, k = 3) plot_pairs(model) #Ploting Cluster Representatives only plot_pairs(model, data) #Ploting Cluster Representatives and Data } \author{ Sandro Radovanovic \email{sandro.radovanovic@gmail.com} }
library(stockassessment) tol <- sqrt(.Machine$double.eps) set.seed(298374) ## jacobian <- function(func, x, ...){ ## r <- .Call("jacobian", ## function(x)func(x,...), ## x, ## globalenv(), ## 30L, ## 0.1 * 10^floor(log10(abs(x))) + 1e-4,##abs(1e-4 * x) + 1e-4 * (abs(x) < 1e-8), ## 1e-12) ## do.call("cbind",r[-1]) ## } ## grad <- function(func, x, ...){ ## r <- .Call("jacobian", ## function(x)func(x,...), ## x, ## globalenv(), ## 30L, ## 0.1 * 10^floor(log10(abs(x))) + 1e-4,##abs(1e-4 * x) + 1e-4 * (abs(x) < 1e-8), ## 1e-12) ## v <- do.call("cbind",r[-1]) ## if(nrow(v) == 1) ## return(as.vector(v)) ## return(diag(v)) ## } jacobian <- function(f, x) stockassessment:::jacobian(f, x, 0.1 * 10^floor(log10(abs(x))) + 1e-4) grad <- function(f, x) stockassessment:::grad(f, x, 0.1 * 10^floor(log10(abs(x))) + 1e-4) gr.sym <- function(x, fn){ eval(D(parse(text=as.character(functionBody(fn))[2]),"x")) } isTRUE <- function(x){is.logical(x) && length(x) == 1L && !is.na(x) && x} check <- function(x, fn, gr = grad){ r <- (gr(fn,x) / gr.sym(x,fn) - 1) b <- max(abs(r)) < tol attr(b,"error") <- max(abs(r)) b } ## Test fn0 <- function(x){ sin(x) } x0 <- runif(1000, -pi, pi) v <- check(x0,fn0) cat(isTRUE(v),"\n", sep = "", file = "res.out") ## Test fn1 <- function(x){ cos(x) } x1 <- runif(1000, -pi, pi) v <- check(x1,fn1) cat(isTRUE(v),"\n", sep = "", file = "res.out", append = TRUE) ## Test fn2 <- function(x){ exp(x) } x2 <- runif(1000, -pi, pi) v <- check(x2,fn2) cat(isTRUE(v),"\n", sep = "", file = "res.out", append = TRUE) ## Test fn3 <- function(x){ exp(x) / sqrt(cos(x)^3 + sin(x)^3) } x3 <- runif(1000, 0, 2) v <- check(x3,fn3) cat(isTRUE(v),"\n", sep = "", file = "res.out", append = TRUE) ## Test fn4 <- function(x){ 1/x } x4 <- runif(1000, -5, 5) v <- check(x4,fn4) cat(isTRUE(v),"\n", sep = "", file = "res.out", append = TRUE) ## Test fn5 <- function(x){ 1/x^2 } x5 <- runif(1000, -5, 5) v <- check(x5,fn5) cat(isTRUE(v),"\n", sep = "", file = "res.out", append = TRUE) ## Test fn6 <- function(x){ exp(x) / (sin(x) - x^2) } x6 <- runif(1000, -5, 5) v <- check(x6,fn6) cat(isTRUE(v),"\n", sep = "", file = "res.out", append = TRUE) ## Test fn7 <- function(x){ asin(x) } x7 <- runif(1000, 0, 1) suppressWarnings(v <- check(x7,fn7)) ## default step size produces NaN for x close to 1 cat(isTRUE(v),"\n", sep = "", file = "res.out", append = TRUE) ## Test fn8 <- function(x){ (x-100)^2 + 1.e-06 * (x - 300)^3 } x8 <- runif(1000, -5, 5) v <- check(x8,fn8) cat(isTRUE(v),"\n", sep = "", file = "res.out", append = TRUE) ## Test fn9 <- function(x){ digamma(x) * x } x9 <- runif(1000, 0, 5) v <- check(x9,fn9) cat(isTRUE(v),"\n", sep = "", file = "res.out", append = TRUE) ## Test fn10 <- function(x){ log1p(dnorm(x)) } x10 <- runif(1000, -5, 5) v <- check(x10,fn10) cat(isTRUE(v),"\n", sep = "", file = "res.out", append = TRUE) ### Compare to other methods if(FALSE){ gr1 <- function(fn, x){ e <- new.env() e$x <- x diag(attr(stats::numericDeriv(quote(fn(x)),"x",e),"gradient")) } gr2 <- function(fn, x){ numDeriv::grad(fn,x) } compare <- function(fn,x){ v <- c("stats" = attr(check(x,fn,gr1),"error"), "numDeriv" = attr(check(x,fn,gr2),"error"), "SAM" = attr(check(x,fn,grad),"error")) cat("Not worse than numDeriv:",v[3] <= v[2],"\n") cat("Not much worse than numDeriv:",v[3] < 1.05 * v[2],"\n") cat("Not worse than stats:",v[3] <= v[1],"\n") sort(v) } compare(fn0,x0) compare(fn1,x1) compare(fn2,x2) compare(fn3,x3) compare(fn4,x4) compare(fn5,x5) compare(fn6,x6) compare(fn7,x7) compare(fn8,x8) compare(fn9,x9) compare(fn10,x10) }
/testmore/jacobian/script.R
no_license
ejosymart/SAM
R
false
false
4,214
r
library(stockassessment) tol <- sqrt(.Machine$double.eps) set.seed(298374) ## jacobian <- function(func, x, ...){ ## r <- .Call("jacobian", ## function(x)func(x,...), ## x, ## globalenv(), ## 30L, ## 0.1 * 10^floor(log10(abs(x))) + 1e-4,##abs(1e-4 * x) + 1e-4 * (abs(x) < 1e-8), ## 1e-12) ## do.call("cbind",r[-1]) ## } ## grad <- function(func, x, ...){ ## r <- .Call("jacobian", ## function(x)func(x,...), ## x, ## globalenv(), ## 30L, ## 0.1 * 10^floor(log10(abs(x))) + 1e-4,##abs(1e-4 * x) + 1e-4 * (abs(x) < 1e-8), ## 1e-12) ## v <- do.call("cbind",r[-1]) ## if(nrow(v) == 1) ## return(as.vector(v)) ## return(diag(v)) ## } jacobian <- function(f, x) stockassessment:::jacobian(f, x, 0.1 * 10^floor(log10(abs(x))) + 1e-4) grad <- function(f, x) stockassessment:::grad(f, x, 0.1 * 10^floor(log10(abs(x))) + 1e-4) gr.sym <- function(x, fn){ eval(D(parse(text=as.character(functionBody(fn))[2]),"x")) } isTRUE <- function(x){is.logical(x) && length(x) == 1L && !is.na(x) && x} check <- function(x, fn, gr = grad){ r <- (gr(fn,x) / gr.sym(x,fn) - 1) b <- max(abs(r)) < tol attr(b,"error") <- max(abs(r)) b } ## Test fn0 <- function(x){ sin(x) } x0 <- runif(1000, -pi, pi) v <- check(x0,fn0) cat(isTRUE(v),"\n", sep = "", file = "res.out") ## Test fn1 <- function(x){ cos(x) } x1 <- runif(1000, -pi, pi) v <- check(x1,fn1) cat(isTRUE(v),"\n", sep = "", file = "res.out", append = TRUE) ## Test fn2 <- function(x){ exp(x) } x2 <- runif(1000, -pi, pi) v <- check(x2,fn2) cat(isTRUE(v),"\n", sep = "", file = "res.out", append = TRUE) ## Test fn3 <- function(x){ exp(x) / sqrt(cos(x)^3 + sin(x)^3) } x3 <- runif(1000, 0, 2) v <- check(x3,fn3) cat(isTRUE(v),"\n", sep = "", file = "res.out", append = TRUE) ## Test fn4 <- function(x){ 1/x } x4 <- runif(1000, -5, 5) v <- check(x4,fn4) cat(isTRUE(v),"\n", sep = "", file = "res.out", append = TRUE) ## Test fn5 <- function(x){ 1/x^2 } x5 <- runif(1000, -5, 5) v <- check(x5,fn5) cat(isTRUE(v),"\n", sep = "", file = "res.out", append = TRUE) ## Test fn6 <- function(x){ exp(x) / (sin(x) - x^2) } x6 <- runif(1000, -5, 5) v <- check(x6,fn6) cat(isTRUE(v),"\n", sep = "", file = "res.out", append = TRUE) ## Test fn7 <- function(x){ asin(x) } x7 <- runif(1000, 0, 1) suppressWarnings(v <- check(x7,fn7)) ## default step size produces NaN for x close to 1 cat(isTRUE(v),"\n", sep = "", file = "res.out", append = TRUE) ## Test fn8 <- function(x){ (x-100)^2 + 1.e-06 * (x - 300)^3 } x8 <- runif(1000, -5, 5) v <- check(x8,fn8) cat(isTRUE(v),"\n", sep = "", file = "res.out", append = TRUE) ## Test fn9 <- function(x){ digamma(x) * x } x9 <- runif(1000, 0, 5) v <- check(x9,fn9) cat(isTRUE(v),"\n", sep = "", file = "res.out", append = TRUE) ## Test fn10 <- function(x){ log1p(dnorm(x)) } x10 <- runif(1000, -5, 5) v <- check(x10,fn10) cat(isTRUE(v),"\n", sep = "", file = "res.out", append = TRUE) ### Compare to other methods if(FALSE){ gr1 <- function(fn, x){ e <- new.env() e$x <- x diag(attr(stats::numericDeriv(quote(fn(x)),"x",e),"gradient")) } gr2 <- function(fn, x){ numDeriv::grad(fn,x) } compare <- function(fn,x){ v <- c("stats" = attr(check(x,fn,gr1),"error"), "numDeriv" = attr(check(x,fn,gr2),"error"), "SAM" = attr(check(x,fn,grad),"error")) cat("Not worse than numDeriv:",v[3] <= v[2],"\n") cat("Not much worse than numDeriv:",v[3] < 1.05 * v[2],"\n") cat("Not worse than stats:",v[3] <= v[1],"\n") sort(v) } compare(fn0,x0) compare(fn1,x1) compare(fn2,x2) compare(fn3,x3) compare(fn4,x4) compare(fn5,x5) compare(fn6,x6) compare(fn7,x7) compare(fn8,x8) compare(fn9,x9) compare(fn10,x10) }
#==================================== # AnomaliaMensual.R # # Calcula Anomalias mensuales: # restamos medias de la climatologia a # cada tabla de resumen mensual #==================================== library(dplyr) # Directorio base bdir <- "CUENCAS" Cl_glob <- "GLOBAL/MegaTClimaAnual.RData" load(Cl_glob) # Contiene MegaT generada con ClimaAnual.R cuencas <- list.files(bdir) for (cc in cuencas) { # Directorio c/cuenca: cdir <- paste0(bdir, "/", cc) # Los archivos en cada cuenca que terminan en ".._Ranual.txt": files <- system2("ls", paste0(cdir, "/*_Ranual.txt"), stdout=T) for (ff in files) { # El nombre del archivo sin el apéndice ".._Ranual.txt" bare <- strsplit(ff, "_Ranual." , fixed=T)[[1]][1] # Sin "_Ranual.txt" # El nombre de la estación: ename <- tail(strsplit(bare, "/", fixed=T)[[1]], 1) # último elemento # Se lee el archivo como una tabla de "dplyr" tt <- tbl_df(read.table(ff, header=T)) # Ahora leemos la climatología mensual para esa estación # podría filtrar por cuenca y estación, pero como las # estaciones no se repiten, bastará con filtrar por estación: tclima <- filter(MegaT, est==ename) # Tiene 1 renglón # La operación de resta, agrupada por (anio: --12 meses--) tt <- tt %>% mutate( # SE USARAN ANOMALIAS ESTANDARIZADAS (div por sd) y por década #CAMBIA>> ppAcc = 100*(ppAcc - tclima$mApp)/tclima$mApp, # Esta va en % # POR: ppAcc = 10*(ppAcc - tclima$mApp)/tclima$sdApp, #CAMBIA>> mTmax = (mTmax - tclima$mmTmax)*10, # Por década # POR: mTmax = 10*(mTmax - tclima$mmTmax)/tclima$sdTmax, #CAMBIA>> mTmin = (mTmin - tclima$mmTmin)*10 # Por década # POR: mTmin = 10*(mTmin - tclima$mmTmin)/tclima$sdTmin ) # Nuevo nombre del archivo: postfijo <- "_AnomAnual.txt" newname <- paste0(bare, postfijo) # reescribimos la tabla, en el mismo directorio, con el nuevo nombre: write.table(tt, newname, row.names=F) } }
/AnomaliaAnual.R
no_license
juliosergio/BID2012
R
false
false
2,222
r
#==================================== # AnomaliaMensual.R # # Calcula Anomalias mensuales: # restamos medias de la climatologia a # cada tabla de resumen mensual #==================================== library(dplyr) # Directorio base bdir <- "CUENCAS" Cl_glob <- "GLOBAL/MegaTClimaAnual.RData" load(Cl_glob) # Contiene MegaT generada con ClimaAnual.R cuencas <- list.files(bdir) for (cc in cuencas) { # Directorio c/cuenca: cdir <- paste0(bdir, "/", cc) # Los archivos en cada cuenca que terminan en ".._Ranual.txt": files <- system2("ls", paste0(cdir, "/*_Ranual.txt"), stdout=T) for (ff in files) { # El nombre del archivo sin el apéndice ".._Ranual.txt" bare <- strsplit(ff, "_Ranual." , fixed=T)[[1]][1] # Sin "_Ranual.txt" # El nombre de la estación: ename <- tail(strsplit(bare, "/", fixed=T)[[1]], 1) # último elemento # Se lee el archivo como una tabla de "dplyr" tt <- tbl_df(read.table(ff, header=T)) # Ahora leemos la climatología mensual para esa estación # podría filtrar por cuenca y estación, pero como las # estaciones no se repiten, bastará con filtrar por estación: tclima <- filter(MegaT, est==ename) # Tiene 1 renglón # La operación de resta, agrupada por (anio: --12 meses--) tt <- tt %>% mutate( # SE USARAN ANOMALIAS ESTANDARIZADAS (div por sd) y por década #CAMBIA>> ppAcc = 100*(ppAcc - tclima$mApp)/tclima$mApp, # Esta va en % # POR: ppAcc = 10*(ppAcc - tclima$mApp)/tclima$sdApp, #CAMBIA>> mTmax = (mTmax - tclima$mmTmax)*10, # Por década # POR: mTmax = 10*(mTmax - tclima$mmTmax)/tclima$sdTmax, #CAMBIA>> mTmin = (mTmin - tclima$mmTmin)*10 # Por década # POR: mTmin = 10*(mTmin - tclima$mmTmin)/tclima$sdTmin ) # Nuevo nombre del archivo: postfijo <- "_AnomAnual.txt" newname <- paste0(bare, postfijo) # reescribimos la tabla, en el mismo directorio, con el nuevo nombre: write.table(tt, newname, row.names=F) } }
#' Adds a dataframe that defines each interaction as true positive, false negative or true negative #' #' @param list Network list #' #' @return A Network list object with ObsSuccess, a dataframe detailing all the interactions and whether they are True Positives, False Negative or True Negatives #' @export #' SortResponseCategory <- function(list){ ## Compares observations with known truth to assess fit quality Observed <- (list$obs>0) TrueMissed <- (list$TrueWeb>0) &(list$obs==0) dimnames(Observed)<-NULL dimnames(TrueMissed)<-NULL reshape2::melt(TrueMissed - Observed)%>% dplyr::rename('Host' = Var1, 'Wasp' = Var2, 'Category' = value)%>% mutate(Category = ifelse(Category == -1, 'True Positive', Category), Category = ifelse(Category == 1, 'False Negative', Category), Category = ifelse(Category == 0, 'True Negative', Category ))%>% mutate(int_code = paste(Host,Wasp, sep='_'))-> ObsSuccess if(!is.null(list$TrueWeb)){ reshape2::melt(list$TrueWeb)%>% mutate(int_code = paste(Var1,Var2, sep='_'), LogStr = log10(value))%>% select(int_code, LogStr)%>% filter(!is.infinite(LogStr))-> Strengths ObsSuccess <- left_join(ObsSuccess,Strengths, by = 'int_code') } reshape2::melt(list$obs)%>% mutate(int_code = paste(Var1,Var2, sep='_'), ObsStr = value)%>% select(int_code, ObsStr)-> ObsStrengths ObsSuccess <- left_join(ObsSuccess,ObsStrengths, by = 'int_code') if(!is.null(list$EmpDataMat)){ reshape2::melt( list$EmpDataMat)%>% mutate(int_code = paste(Var1,Var2, sep='_'), LogStr = log10(value))%>% select(int_code, LogStr)%>% filter(!is.infinite(LogStr))-> Strengths ObsSuccess <- left_join(ObsSuccess,Strengths, by = 'int_code') } list$ObsSuccess <- ObsSuccess return(list) }
/R/SortResponseCategory.R
no_license
jcdterry/cassandRa
R
false
false
1,889
r
#' Adds a dataframe that defines each interaction as true positive, false negative or true negative #' #' @param list Network list #' #' @return A Network list object with ObsSuccess, a dataframe detailing all the interactions and whether they are True Positives, False Negative or True Negatives #' @export #' SortResponseCategory <- function(list){ ## Compares observations with known truth to assess fit quality Observed <- (list$obs>0) TrueMissed <- (list$TrueWeb>0) &(list$obs==0) dimnames(Observed)<-NULL dimnames(TrueMissed)<-NULL reshape2::melt(TrueMissed - Observed)%>% dplyr::rename('Host' = Var1, 'Wasp' = Var2, 'Category' = value)%>% mutate(Category = ifelse(Category == -1, 'True Positive', Category), Category = ifelse(Category == 1, 'False Negative', Category), Category = ifelse(Category == 0, 'True Negative', Category ))%>% mutate(int_code = paste(Host,Wasp, sep='_'))-> ObsSuccess if(!is.null(list$TrueWeb)){ reshape2::melt(list$TrueWeb)%>% mutate(int_code = paste(Var1,Var2, sep='_'), LogStr = log10(value))%>% select(int_code, LogStr)%>% filter(!is.infinite(LogStr))-> Strengths ObsSuccess <- left_join(ObsSuccess,Strengths, by = 'int_code') } reshape2::melt(list$obs)%>% mutate(int_code = paste(Var1,Var2, sep='_'), ObsStr = value)%>% select(int_code, ObsStr)-> ObsStrengths ObsSuccess <- left_join(ObsSuccess,ObsStrengths, by = 'int_code') if(!is.null(list$EmpDataMat)){ reshape2::melt( list$EmpDataMat)%>% mutate(int_code = paste(Var1,Var2, sep='_'), LogStr = log10(value))%>% select(int_code, LogStr)%>% filter(!is.infinite(LogStr))-> Strengths ObsSuccess <- left_join(ObsSuccess,Strengths, by = 'int_code') } list$ObsSuccess <- ObsSuccess return(list) }
loginfo('Beginning munge (versionless products)', logger = logger_module) prod_info <- get_product_info(network = network, domain = domain, status_level = 'munge', get_statuses = 'ready') %>% filter(grepl(pattern = '^VERSIONLESS', x = prodcode)) if(! is.null(prodname_filter)){ prod_info <- filter(prod_info, prodname %in% prodname_filter) } if(nrow(prod_info) == 0) return() #i = 1 for(i in seq_len(nrow(prod_info))){ prodname_ms <<- paste0(prod_info$prodname[i], '__', prod_info$prodcode[i]) held_data <<- get_data_tracker(network=network, domain=domain) if(! product_is_tracked(held_data, prodname_ms)){ logwarn(glue('Product {p} is not yet tracked. Retrieve ', 'it before munging it.', p = prodname_ms), logger = logger_module) next } sites <- names(held_data[[prodname_ms]]) #j = 1 for(j in 1:length(sites)){ site_code <- sites[j] munge_status <- get_munge_status(tracker = held_data, prodname_ms = prodname_ms, site_code = site_code) if(munge_status == 'ok'){ loginfo(glue('Nothing to do for {s} {p}', s = site_code, p = prodname_ms), logger = logger_module) next } else { loginfo(glue('Munging {s} {p}', s = site_code, p = prodname_ms), logger = logger_module) } munge_rtn <- munge_versionless_product( network = network, domain = domain, prodname_ms = prodname_ms, site_code = sites[j], tracker = held_data) if(is_ms_err(munge_rtn)){ update_data_tracker_m(network = network, domain = domain, tracker_name = 'held_data', prodname_ms = prodname_ms, site_code = sites[j], new_status = 'error') } else { invalidate_derived_products(successor_string = prod_info$precursor_of[i]) } } gc() } loginfo('Munge complete for all versionless products', logger = logger_module)
/src/usfs/tenderfoot/munge_versionless.R
permissive
MacroSHEDS/data_processing
R
false
false
2,518
r
loginfo('Beginning munge (versionless products)', logger = logger_module) prod_info <- get_product_info(network = network, domain = domain, status_level = 'munge', get_statuses = 'ready') %>% filter(grepl(pattern = '^VERSIONLESS', x = prodcode)) if(! is.null(prodname_filter)){ prod_info <- filter(prod_info, prodname %in% prodname_filter) } if(nrow(prod_info) == 0) return() #i = 1 for(i in seq_len(nrow(prod_info))){ prodname_ms <<- paste0(prod_info$prodname[i], '__', prod_info$prodcode[i]) held_data <<- get_data_tracker(network=network, domain=domain) if(! product_is_tracked(held_data, prodname_ms)){ logwarn(glue('Product {p} is not yet tracked. Retrieve ', 'it before munging it.', p = prodname_ms), logger = logger_module) next } sites <- names(held_data[[prodname_ms]]) #j = 1 for(j in 1:length(sites)){ site_code <- sites[j] munge_status <- get_munge_status(tracker = held_data, prodname_ms = prodname_ms, site_code = site_code) if(munge_status == 'ok'){ loginfo(glue('Nothing to do for {s} {p}', s = site_code, p = prodname_ms), logger = logger_module) next } else { loginfo(glue('Munging {s} {p}', s = site_code, p = prodname_ms), logger = logger_module) } munge_rtn <- munge_versionless_product( network = network, domain = domain, prodname_ms = prodname_ms, site_code = sites[j], tracker = held_data) if(is_ms_err(munge_rtn)){ update_data_tracker_m(network = network, domain = domain, tracker_name = 'held_data', prodname_ms = prodname_ms, site_code = sites[j], new_status = 'error') } else { invalidate_derived_products(successor_string = prod_info$precursor_of[i]) } } gc() } loginfo('Munge complete for all versionless products', logger = logger_module)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Do not modify this file since it was automatically generated from: % % Explorer.R % % by the Rdoc compiler part of the R.oo package. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \name{getRootPath.Explorer} \alias{getRootPath.Explorer} \alias{Explorer.getRootPath} \alias{getRootPath,Explorer-method} \title{Gets the root path of the output directory} \description{ Gets the root path of the output directory that is returned by \code{\link[aroma.core:getPath.Explorer]{*getPath}()}. A root path is a directory in the current working directory. } \usage{ \method{getRootPath}{Explorer}(this, ...) } \arguments{ \item{...}{Not used.} } \value{ Returns a \code{\link[base]{character}} string. } \author{Henrik Bengtsson} \seealso{ \code{\link[aroma.core:getPath.Explorer]{*getPath}()}. For more information see \code{\link{Explorer}}. } \keyword{internal} \keyword{methods}
/man/getRootPath.Explorer.Rd
no_license
HenrikBengtsson/aroma.core
R
false
false
998
rd
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Do not modify this file since it was automatically generated from: % % Explorer.R % % by the Rdoc compiler part of the R.oo package. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \name{getRootPath.Explorer} \alias{getRootPath.Explorer} \alias{Explorer.getRootPath} \alias{getRootPath,Explorer-method} \title{Gets the root path of the output directory} \description{ Gets the root path of the output directory that is returned by \code{\link[aroma.core:getPath.Explorer]{*getPath}()}. A root path is a directory in the current working directory. } \usage{ \method{getRootPath}{Explorer}(this, ...) } \arguments{ \item{...}{Not used.} } \value{ Returns a \code{\link[base]{character}} string. } \author{Henrik Bengtsson} \seealso{ \code{\link[aroma.core:getPath.Explorer]{*getPath}()}. For more information see \code{\link{Explorer}}. } \keyword{internal} \keyword{methods}
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/AllClasses.R \docType{class} \name{SpatialExperiment-class} \alias{SpatialExperiment-class} \alias{SpatialExperiment} \alias{coerce,SingleCellExperiment,SpatialExperiment-method} \title{The SpatialExperiment class} \usage{ SpatialExperiment(..., spatialCoords = data.frame()) } \arguments{ \item{...}{arguments to be passed to the \code{\link{SingleCellExperiment}} constructor to fill the slots of the base class.} \item{spatialCoords}{the spatial coordinates} } \value{ none } \description{ The SpatialExperiment class is designed to represent 10x Visium spatial Gene Expression data. It inherits from the \linkS4class{SingleCellExperiment} class and is used in the same manner. In addition, the class supports the integration with 10x Visium spatial coordinates and its scale factors. } \examples{ ## building random seqFISH data coordinates fishCoordinates <- data.frame(Cell_ID=paste0("cell",c(1:30)), Irrelevant=100, x=sample(c(-4000:4000), size=30, replace=TRUE), y=sample(c(-4000:4000), size=30, replace=TRUE)) ## building random seqFISH cell labels fishCellLabels <- data.frame(Cell_ID=paste0("cell",c(1:30)), class="neuron", classID=sample(c(0:5), size=30, replace=TRUE)) ## building random seqFISH count matrix fishCounts <- matrix(sample(0:100, size=(30*30), replace=TRUE), nrow=30, ncol=30, dimnames=list(paste0("gene",c(1:30)), paste0("cell",c(1:30)))) ## creating SpatialExperiment object se <- SpatialExperiment(rowData=rownames(fishCounts), colData=fishCellLabels, assays=SimpleList(counts=as.matrix(fishCounts)), spatialCoords=fishCoordinates) } \author{ Dario Righelli }
/man/SpatialExperiment.Rd
no_license
celsomilne/SpatialExperiment
R
false
true
1,928
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/AllClasses.R \docType{class} \name{SpatialExperiment-class} \alias{SpatialExperiment-class} \alias{SpatialExperiment} \alias{coerce,SingleCellExperiment,SpatialExperiment-method} \title{The SpatialExperiment class} \usage{ SpatialExperiment(..., spatialCoords = data.frame()) } \arguments{ \item{...}{arguments to be passed to the \code{\link{SingleCellExperiment}} constructor to fill the slots of the base class.} \item{spatialCoords}{the spatial coordinates} } \value{ none } \description{ The SpatialExperiment class is designed to represent 10x Visium spatial Gene Expression data. It inherits from the \linkS4class{SingleCellExperiment} class and is used in the same manner. In addition, the class supports the integration with 10x Visium spatial coordinates and its scale factors. } \examples{ ## building random seqFISH data coordinates fishCoordinates <- data.frame(Cell_ID=paste0("cell",c(1:30)), Irrelevant=100, x=sample(c(-4000:4000), size=30, replace=TRUE), y=sample(c(-4000:4000), size=30, replace=TRUE)) ## building random seqFISH cell labels fishCellLabels <- data.frame(Cell_ID=paste0("cell",c(1:30)), class="neuron", classID=sample(c(0:5), size=30, replace=TRUE)) ## building random seqFISH count matrix fishCounts <- matrix(sample(0:100, size=(30*30), replace=TRUE), nrow=30, ncol=30, dimnames=list(paste0("gene",c(1:30)), paste0("cell",c(1:30)))) ## creating SpatialExperiment object se <- SpatialExperiment(rowData=rownames(fishCounts), colData=fishCellLabels, assays=SimpleList(counts=as.matrix(fishCounts)), spatialCoords=fishCoordinates) } \author{ Dario Righelli }
library(tidyverse) # library() load("~/Documents/Projects/ESDL_earlyadopter/ESDL/Results/200819_summary_lai.RData") # run the 07-ecoregions script and merge with results data frame: df <- left_join(df, df_biomes) q75 <- df %>% group_by(biome, stat) %>% filter(feature == "diff") %>% summarise(q75 = quantile(value, prob = 0.75)) df <- left_join(df, q75) %>% mutate(q75_plus = value > q75) df %>% filter(stat == "fd", feature == "diff") %>% filter(!is.na(biome)) %>% ggplot(aes(lon, lat)) + geom_tile(aes(fill = value, alpha = q75_plus)) + # , alpha = q75_plus scale_fill_viridis_c(option = "C", name = "Difference") + scale_alpha_discrete(range = c(0.3,1), name = "Percentile", label = c("< 90%", "> 90%")) + theme_void() ## select the pixels where stark differences were detected: ## J200825: Note that fd is not working, the same for all pixels with min 0. df_ews <- df %>% filter(q75_plus == TRUE, feature == "diff") %>% group_by(lon, lat, biome) %>% # ggplot(aes(biome)) + geom_bar() + coord_flip() summarise(n_ews = n()) df_ews %>% # ggplot(aes(lon, lat)) + geom_tile(aes(fill = n_ews)) ggplot(aes(biome)) + geom_bar() + coord_flip() ## calculate the bar plots also as proportion of the biome showing EWS. df_affected <- df_ews %>% group_by(biome) %>% summarise(affected_area = n()) df_affected %>% left_join((df_biomes %>% group_by(biome) %>% summarize(n = n()))) %>% mutate(proportion = affected_area / n) %>% filter(!is.na(biome)) %>% ggplot(aes(biome, proportion)) + geom_col( alpha = 0.7) + coord_flip() + theme_light() ## save results: save(df_ews, file = "~/Documents/Projects/ESDL_earlyadopter/ESDL/Results/200825_detected_gpp.RData") ## load("~/Documents/Projects/ESDL_earlyadopter/ESDL/Results/200825_detected_gpp.RData") lats <- df_ews %>% pull(lat) %>% unique() %>% sort() lats <- as.character(lats) path <- "~/Documents/Projects/ESDL_earlyadopter/ESDL/Results/ews_halfwindow_gpp/" file <- paste(path, "lat_",lats[460], ".csv", sep = "") tic() df <- read_csv( file = file, col_types = cols( time = col_datetime(), lon = col_double(), gpp = col_double(), gpp_1d = col_double(), ews_std = col_double(), ews_ac1 = col_double(), ews_kur = col_double(), ews_skw = col_double(), ews_fd = col_double() ) ) toc() lons <- df_ews %>% filter(lat == as.numeric(lats[460])) %>% pull(lon) %>% unique() lon_tundra <- df_biomes %>% filter(lat == lats[460], biome == "Tundra") %>% pull(lon) %>% unique() df %>% filter(lon %in% lons) %>% filter(lon %in% lon_tundra) %>% # pull(gpp) %>% #forecast::ndiffs() # urca::ur.kpss(., lags = "long", use.lag = 0) %>% slot("teststat") # ggplot(aes(time, ews_fd)) + # geom_line(size = 0.5) + # geom_smooth() ggplot(aes(gpp, ews_std)) + geom_density2d()
/select_outliers.R
permissive
yangxhcaf/ESDL
R
false
false
2,848
r
library(tidyverse) # library() load("~/Documents/Projects/ESDL_earlyadopter/ESDL/Results/200819_summary_lai.RData") # run the 07-ecoregions script and merge with results data frame: df <- left_join(df, df_biomes) q75 <- df %>% group_by(biome, stat) %>% filter(feature == "diff") %>% summarise(q75 = quantile(value, prob = 0.75)) df <- left_join(df, q75) %>% mutate(q75_plus = value > q75) df %>% filter(stat == "fd", feature == "diff") %>% filter(!is.na(biome)) %>% ggplot(aes(lon, lat)) + geom_tile(aes(fill = value, alpha = q75_plus)) + # , alpha = q75_plus scale_fill_viridis_c(option = "C", name = "Difference") + scale_alpha_discrete(range = c(0.3,1), name = "Percentile", label = c("< 90%", "> 90%")) + theme_void() ## select the pixels where stark differences were detected: ## J200825: Note that fd is not working, the same for all pixels with min 0. df_ews <- df %>% filter(q75_plus == TRUE, feature == "diff") %>% group_by(lon, lat, biome) %>% # ggplot(aes(biome)) + geom_bar() + coord_flip() summarise(n_ews = n()) df_ews %>% # ggplot(aes(lon, lat)) + geom_tile(aes(fill = n_ews)) ggplot(aes(biome)) + geom_bar() + coord_flip() ## calculate the bar plots also as proportion of the biome showing EWS. df_affected <- df_ews %>% group_by(biome) %>% summarise(affected_area = n()) df_affected %>% left_join((df_biomes %>% group_by(biome) %>% summarize(n = n()))) %>% mutate(proportion = affected_area / n) %>% filter(!is.na(biome)) %>% ggplot(aes(biome, proportion)) + geom_col( alpha = 0.7) + coord_flip() + theme_light() ## save results: save(df_ews, file = "~/Documents/Projects/ESDL_earlyadopter/ESDL/Results/200825_detected_gpp.RData") ## load("~/Documents/Projects/ESDL_earlyadopter/ESDL/Results/200825_detected_gpp.RData") lats <- df_ews %>% pull(lat) %>% unique() %>% sort() lats <- as.character(lats) path <- "~/Documents/Projects/ESDL_earlyadopter/ESDL/Results/ews_halfwindow_gpp/" file <- paste(path, "lat_",lats[460], ".csv", sep = "") tic() df <- read_csv( file = file, col_types = cols( time = col_datetime(), lon = col_double(), gpp = col_double(), gpp_1d = col_double(), ews_std = col_double(), ews_ac1 = col_double(), ews_kur = col_double(), ews_skw = col_double(), ews_fd = col_double() ) ) toc() lons <- df_ews %>% filter(lat == as.numeric(lats[460])) %>% pull(lon) %>% unique() lon_tundra <- df_biomes %>% filter(lat == lats[460], biome == "Tundra") %>% pull(lon) %>% unique() df %>% filter(lon %in% lons) %>% filter(lon %in% lon_tundra) %>% # pull(gpp) %>% #forecast::ndiffs() # urca::ur.kpss(., lags = "long", use.lag = 0) %>% slot("teststat") # ggplot(aes(time, ews_fd)) + # geom_line(size = 0.5) + # geom_smooth() ggplot(aes(gpp, ews_std)) + geom_density2d()
## ----comment=NA--------------------------------------------------------------- require(moonBook) data(acs) mytable(Dx~.,data=acs) ## ----comment=NA--------------------------------------------------------------- str(acs) ## ----comment=NA--------------------------------------------------------------- mytable(acs) ## ----comment=NA--------------------------------------------------------------- mytable(~age+sex,data=acs) ## ----comment=NA--------------------------------------------------------------- if(!require(sjlabelled)) { install.packages("sjlabelled") require(sjlabelled) } df=mtcars df$am<-set_label(df$am,label="Transmission") df$am<-set_labels(df$am,labels=c("automatic","manual")) df$vs<-set_label(df$vs,label="Engine") df$vs<-set_labels(df$vs,labels=c("V-shaped","straight")) ## ----comment=NA--------------------------------------------------------------- str(df) ## ----comment=NA--------------------------------------------------------------- mytable(df) mytable(df,use.labels=FALSE, use.column.label=FALSE) mytable(am~.,data=df) # mytable(vs+am~.,data=df) ## ----comment=NA--------------------------------------------------------------- mytable(sex~age+Dx,data=acs) ## ---- comment=NA-------------------------------------------------------------- mytable(am~.-hp-disp-cyl-carb-gear,data=mtcars) ## ----comment=NA--------------------------------------------------------------- mytable(sex~height+weight+BMI,data=acs,method=3) ## ---- comment=NA,warning=FALSE------------------------------------------------ mytable(am~.,data=mtcars) ## ----comment=NA,warning=FALSE------------------------------------------------- mytable(am~carb,data=mtcars,max.ylev=6) ## ----comment=NA,warning=FALSE------------------------------------------------- mytable(sex+DM~.,data=acs) ## ----results='asis'----------------------------------------------------------- out=mytable(Dx~.,data=acs) myhtml(out) out1=mytable(sex+DM~.,data=acs) myhtml(out1) ## ----eval=FALSE--------------------------------------------------------------- # mylatex(mytable(sex+DM~age+Dx,data=acs)) ## ----eval=FALSE--------------------------------------------------------------- # out=mytable(sex~age+Dx,data=acs) # for(i in c(3,5)) # mylatex(out,size=i,caption=paste("Table ",i,". Fontsize=",i,sep="")) ## ----eval=FALSE--------------------------------------------------------------- # mycsv(out,file="test.csv") # mycsv(out1,fil="test1.csv") ## ----messgae=FALSE,results='asis'--------------------------------------------- require(ztable) require(magrittr) mytable(sex+DM~.,data=acs) %>% ztable %>% addSigColor %>% print(type="html") ## ----fig.height=5,fig.width=6------------------------------------------------- library(moonBook) densityplot(age~sex,data=acs) densityplot(age~Dx,data=acs) ## ----fig.width=6,fig.height=6,comment=NA-------------------------------------- require(survival) data(colon) out1=glm(status~sex+age+rx+obstruct+node4,data=colon) out2=glm(status~rx+node4,data=colon) ORplot(out1,type=2,show.CI=TRUE,xlab="This is xlab",main="Odds Ratio") ORplot(out2,type=1) ORplot(out1,type=1,show.CI=TRUE,col=c("blue","red")) ORplot(out1,type=4,show.CI=TRUE,sig.level=0.05) ORplot(out1,type=1,show.CI=TRUE,main="Odds Ratio",sig.level=0.05, pch=1,cex=2,lwd=4,col=c("red","blue")) ## ----fig.width=6,fig.height=6,comment=NA-------------------------------------- attach(colon) colon$TS=Surv(time,status==1) out=mycph(TS~.,data=colon) out HRplot(out,type=2,show.CI=TRUE,cex=2,sig=0.05, main="Hazard ratios of all individual variables")
/inst/doc/moonBook.R
no_license
cran/moonBook
R
false
false
3,585
r
## ----comment=NA--------------------------------------------------------------- require(moonBook) data(acs) mytable(Dx~.,data=acs) ## ----comment=NA--------------------------------------------------------------- str(acs) ## ----comment=NA--------------------------------------------------------------- mytable(acs) ## ----comment=NA--------------------------------------------------------------- mytable(~age+sex,data=acs) ## ----comment=NA--------------------------------------------------------------- if(!require(sjlabelled)) { install.packages("sjlabelled") require(sjlabelled) } df=mtcars df$am<-set_label(df$am,label="Transmission") df$am<-set_labels(df$am,labels=c("automatic","manual")) df$vs<-set_label(df$vs,label="Engine") df$vs<-set_labels(df$vs,labels=c("V-shaped","straight")) ## ----comment=NA--------------------------------------------------------------- str(df) ## ----comment=NA--------------------------------------------------------------- mytable(df) mytable(df,use.labels=FALSE, use.column.label=FALSE) mytable(am~.,data=df) # mytable(vs+am~.,data=df) ## ----comment=NA--------------------------------------------------------------- mytable(sex~age+Dx,data=acs) ## ---- comment=NA-------------------------------------------------------------- mytable(am~.-hp-disp-cyl-carb-gear,data=mtcars) ## ----comment=NA--------------------------------------------------------------- mytable(sex~height+weight+BMI,data=acs,method=3) ## ---- comment=NA,warning=FALSE------------------------------------------------ mytable(am~.,data=mtcars) ## ----comment=NA,warning=FALSE------------------------------------------------- mytable(am~carb,data=mtcars,max.ylev=6) ## ----comment=NA,warning=FALSE------------------------------------------------- mytable(sex+DM~.,data=acs) ## ----results='asis'----------------------------------------------------------- out=mytable(Dx~.,data=acs) myhtml(out) out1=mytable(sex+DM~.,data=acs) myhtml(out1) ## ----eval=FALSE--------------------------------------------------------------- # mylatex(mytable(sex+DM~age+Dx,data=acs)) ## ----eval=FALSE--------------------------------------------------------------- # out=mytable(sex~age+Dx,data=acs) # for(i in c(3,5)) # mylatex(out,size=i,caption=paste("Table ",i,". Fontsize=",i,sep="")) ## ----eval=FALSE--------------------------------------------------------------- # mycsv(out,file="test.csv") # mycsv(out1,fil="test1.csv") ## ----messgae=FALSE,results='asis'--------------------------------------------- require(ztable) require(magrittr) mytable(sex+DM~.,data=acs) %>% ztable %>% addSigColor %>% print(type="html") ## ----fig.height=5,fig.width=6------------------------------------------------- library(moonBook) densityplot(age~sex,data=acs) densityplot(age~Dx,data=acs) ## ----fig.width=6,fig.height=6,comment=NA-------------------------------------- require(survival) data(colon) out1=glm(status~sex+age+rx+obstruct+node4,data=colon) out2=glm(status~rx+node4,data=colon) ORplot(out1,type=2,show.CI=TRUE,xlab="This is xlab",main="Odds Ratio") ORplot(out2,type=1) ORplot(out1,type=1,show.CI=TRUE,col=c("blue","red")) ORplot(out1,type=4,show.CI=TRUE,sig.level=0.05) ORplot(out1,type=1,show.CI=TRUE,main="Odds Ratio",sig.level=0.05, pch=1,cex=2,lwd=4,col=c("red","blue")) ## ----fig.width=6,fig.height=6,comment=NA-------------------------------------- attach(colon) colon$TS=Surv(time,status==1) out=mycph(TS~.,data=colon) out HRplot(out,type=2,show.CI=TRUE,cex=2,sig=0.05, main="Hazard ratios of all individual variables")
testlist <- list(b = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), p1 = c(8.5728629954997e-312, 1.56898424065867e+82, 8.96970809549085e-158, -1.3258495253834e-113, 2.79620616433656e-119, -6.80033518839696e+41, 2.68298522855314e-211, 1444042902784.06, 6.68889884134308e+51, -4.05003163986346e-308, -3.52601820453991e+43, -1.49815227045093e+197, -2.61605817623304e+76, -1.18078903777423e-90, 1.86807199752274e+112, -5.58551357556946e+160, 2.00994342527714e-162, 1.81541609400943e-79, 7.89363005545926e+139, 2.3317908961407e-93, 2.16562581831091e+161), p2 = -1.72131968218895e+83) result <- do.call(metacoder:::intersect_line_rectangle,testlist) str(result)
/metacoder/inst/testfiles/intersect_line_rectangle/AFL_intersect_line_rectangle/intersect_line_rectangle_valgrind_files/1615769225-test.R
permissive
akhikolla/updatedatatype-list3
R
false
false
727
r
testlist <- list(b = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), p1 = c(8.5728629954997e-312, 1.56898424065867e+82, 8.96970809549085e-158, -1.3258495253834e-113, 2.79620616433656e-119, -6.80033518839696e+41, 2.68298522855314e-211, 1444042902784.06, 6.68889884134308e+51, -4.05003163986346e-308, -3.52601820453991e+43, -1.49815227045093e+197, -2.61605817623304e+76, -1.18078903777423e-90, 1.86807199752274e+112, -5.58551357556946e+160, 2.00994342527714e-162, 1.81541609400943e-79, 7.89363005545926e+139, 2.3317908961407e-93, 2.16562581831091e+161), p2 = -1.72131968218895e+83) result <- do.call(metacoder:::intersect_line_rectangle,testlist) str(result)
# This file is generated by make.paws. Please do not edit here. #' @importFrom paws.common populate #' @include sns_service.R NULL .sns$add_permission_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(TopicArn = structure(logical(0), tags = list(type = "string")), Label = structure(logical(0), tags = list(type = "string")), AWSAccountId = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), ActionName = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$add_permission_output <- function(...) { list() } .sns$check_if_phone_number_is_opted_out_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(phoneNumber = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$check_if_phone_number_is_opted_out_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(isOptedOut = structure(logical(0), tags = list(type = "boolean"))), tags = list(type = "structure", resultWrapper = "CheckIfPhoneNumberIsOptedOutResult")) return(populate(args, shape)) } .sns$confirm_subscription_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(TopicArn = structure(logical(0), tags = list(type = "string")), Token = structure(logical(0), tags = list(type = "string")), AuthenticateOnUnsubscribe = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$confirm_subscription_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(SubscriptionArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure", resultWrapper = "ConfirmSubscriptionResult")) return(populate(args, shape)) } .sns$create_platform_application_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Name = structure(logical(0), tags = list(type = "string")), Platform = structure(logical(0), tags = list(type = "string")), Attributes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$create_platform_application_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(PlatformApplicationArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure", resultWrapper = "CreatePlatformApplicationResult")) return(populate(args, shape)) } .sns$create_platform_endpoint_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(PlatformApplicationArn = structure(logical(0), tags = list(type = "string")), Token = structure(logical(0), tags = list(type = "string")), CustomUserData = structure(logical(0), tags = list(type = "string")), Attributes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$create_platform_endpoint_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(EndpointArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure", resultWrapper = "CreatePlatformEndpointResult")) return(populate(args, shape)) } .sns$create_sms_sandbox_phone_number_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(PhoneNumber = structure(logical(0), tags = list(type = "string")), LanguageCode = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$create_sms_sandbox_phone_number_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(), tags = list(type = "structure", resultWrapper = "CreateSMSSandboxPhoneNumberResult")) return(populate(args, shape)) } .sns$create_topic_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Name = structure(logical(0), tags = list(type = "string")), Attributes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map")), Tags = structure(list(structure(list(Key = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), DataProtectionPolicy = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$create_topic_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(TopicArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure", resultWrapper = "CreateTopicResult")) return(populate(args, shape)) } .sns$delete_endpoint_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(EndpointArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$delete_endpoint_output <- function(...) { list() } .sns$delete_platform_application_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(PlatformApplicationArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$delete_platform_application_output <- function(...) { list() } .sns$delete_sms_sandbox_phone_number_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(PhoneNumber = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$delete_sms_sandbox_phone_number_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(), tags = list(type = "structure", resultWrapper = "DeleteSMSSandboxPhoneNumberResult")) return(populate(args, shape)) } .sns$delete_topic_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(TopicArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$delete_topic_output <- function(...) { list() } .sns$get_data_protection_policy_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ResourceArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$get_data_protection_policy_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(DataProtectionPolicy = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure", resultWrapper = "GetDataProtectionPolicyResult")) return(populate(args, shape)) } .sns$get_endpoint_attributes_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(EndpointArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$get_endpoint_attributes_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Attributes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure", resultWrapper = "GetEndpointAttributesResult")) return(populate(args, shape)) } .sns$get_platform_application_attributes_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(PlatformApplicationArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$get_platform_application_attributes_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Attributes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure", resultWrapper = "GetPlatformApplicationAttributesResult")) return(populate(args, shape)) } .sns$get_sms_attributes_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(attributes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$get_sms_attributes_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(attributes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure", resultWrapper = "GetSMSAttributesResult")) return(populate(args, shape)) } .sns$get_sms_sandbox_account_status_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(), tags = list(type = "structure")) return(populate(args, shape)) } .sns$get_sms_sandbox_account_status_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(IsInSandbox = structure(logical(0), tags = list(type = "boolean"))), tags = list(type = "structure", resultWrapper = "GetSMSSandboxAccountStatusResult")) return(populate(args, shape)) } .sns$get_subscription_attributes_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(SubscriptionArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$get_subscription_attributes_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Attributes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure", resultWrapper = "GetSubscriptionAttributesResult")) return(populate(args, shape)) } .sns$get_topic_attributes_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(TopicArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$get_topic_attributes_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Attributes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure", resultWrapper = "GetTopicAttributesResult")) return(populate(args, shape)) } .sns$list_endpoints_by_platform_application_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(PlatformApplicationArn = structure(logical(0), tags = list(type = "string")), NextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$list_endpoints_by_platform_application_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Endpoints = structure(list(structure(list(EndpointArn = structure(logical(0), tags = list(type = "string")), Attributes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure"))), tags = list(type = "list")), NextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure", resultWrapper = "ListEndpointsByPlatformApplicationResult")) return(populate(args, shape)) } .sns$list_origination_numbers_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(type = "string")), MaxResults = structure(logical(0), tags = list(type = "integer"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$list_origination_numbers_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(type = "string")), PhoneNumbers = structure(list(structure(list(CreatedAt = structure(logical(0), tags = list(type = "timestamp")), PhoneNumber = structure(logical(0), tags = list(type = "string")), Status = structure(logical(0), tags = list(type = "string")), Iso2CountryCode = structure(logical(0), tags = list(type = "string")), RouteType = structure(logical(0), tags = list(type = "string")), NumberCapabilities = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure", resultWrapper = "ListOriginationNumbersResult")) return(populate(args, shape)) } .sns$list_phone_numbers_opted_out_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(nextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$list_phone_numbers_opted_out_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(phoneNumbers = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), nextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure", resultWrapper = "ListPhoneNumbersOptedOutResult")) return(populate(args, shape)) } .sns$list_platform_applications_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$list_platform_applications_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(PlatformApplications = structure(list(structure(list(PlatformApplicationArn = structure(logical(0), tags = list(type = "string")), Attributes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure"))), tags = list(type = "list")), NextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure", resultWrapper = "ListPlatformApplicationsResult")) return(populate(args, shape)) } .sns$list_sms_sandbox_phone_numbers_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(type = "string")), MaxResults = structure(logical(0), tags = list(type = "integer"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$list_sms_sandbox_phone_numbers_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(PhoneNumbers = structure(list(structure(list(PhoneNumber = structure(logical(0), tags = list(type = "string")), Status = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), NextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure", resultWrapper = "ListSMSSandboxPhoneNumbersResult")) return(populate(args, shape)) } .sns$list_subscriptions_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$list_subscriptions_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Subscriptions = structure(list(structure(list(SubscriptionArn = structure(logical(0), tags = list(type = "string")), Owner = structure(logical(0), tags = list(type = "string")), Protocol = structure(logical(0), tags = list(type = "string")), Endpoint = structure(logical(0), tags = list(type = "string")), TopicArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), NextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure", resultWrapper = "ListSubscriptionsResult")) return(populate(args, shape)) } .sns$list_subscriptions_by_topic_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(TopicArn = structure(logical(0), tags = list(type = "string")), NextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$list_subscriptions_by_topic_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Subscriptions = structure(list(structure(list(SubscriptionArn = structure(logical(0), tags = list(type = "string")), Owner = structure(logical(0), tags = list(type = "string")), Protocol = structure(logical(0), tags = list(type = "string")), Endpoint = structure(logical(0), tags = list(type = "string")), TopicArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), NextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure", resultWrapper = "ListSubscriptionsByTopicResult")) return(populate(args, shape)) } .sns$list_tags_for_resource_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ResourceArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$list_tags_for_resource_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Tags = structure(list(structure(list(Key = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure", resultWrapper = "ListTagsForResourceResult")) return(populate(args, shape)) } .sns$list_topics_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$list_topics_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Topics = structure(list(structure(list(TopicArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), NextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure", resultWrapper = "ListTopicsResult")) return(populate(args, shape)) } .sns$opt_in_phone_number_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(phoneNumber = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$opt_in_phone_number_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(), tags = list(type = "structure", resultWrapper = "OptInPhoneNumberResult")) return(populate(args, shape)) } .sns$publish_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(TopicArn = structure(logical(0), tags = list(type = "string")), TargetArn = structure(logical(0), tags = list(type = "string")), PhoneNumber = structure(logical(0), tags = list(type = "string")), Message = structure(logical(0), tags = list(type = "string")), Subject = structure(logical(0), tags = list(type = "string")), MessageStructure = structure(logical(0), tags = list(type = "string")), MessageAttributes = structure(list(structure(list(DataType = structure(logical(0), tags = list(type = "string")), StringValue = structure(logical(0), tags = list(type = "string")), BinaryValue = structure(logical(0), tags = list(type = "blob"))), tags = list(locationName = "Value", type = "structure"))), tags = list(locationNameKey = "Name", locationNameValue = "Value", type = "map")), MessageDeduplicationId = structure(logical(0), tags = list(type = "string")), MessageGroupId = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$publish_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(MessageId = structure(logical(0), tags = list(type = "string")), SequenceNumber = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure", resultWrapper = "PublishResult")) return(populate(args, shape)) } .sns$publish_batch_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(TopicArn = structure(logical(0), tags = list(type = "string")), PublishBatchRequestEntries = structure(list(structure(list(Id = structure(logical(0), tags = list(type = "string")), Message = structure(logical(0), tags = list(type = "string")), Subject = structure(logical(0), tags = list(type = "string")), MessageStructure = structure(logical(0), tags = list(type = "string")), MessageAttributes = structure(list(structure(list(DataType = structure(logical(0), tags = list(type = "string")), StringValue = structure(logical(0), tags = list(type = "string")), BinaryValue = structure(logical(0), tags = list(type = "blob"))), tags = list(locationName = "Value", type = "structure"))), tags = list(locationNameKey = "Name", locationNameValue = "Value", type = "map")), MessageDeduplicationId = structure(logical(0), tags = list(type = "string")), MessageGroupId = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$publish_batch_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Successful = structure(list(structure(list(Id = structure(logical(0), tags = list(type = "string")), MessageId = structure(logical(0), tags = list(type = "string")), SequenceNumber = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), Failed = structure(list(structure(list(Id = structure(logical(0), tags = list(type = "string")), Code = structure(logical(0), tags = list(type = "string")), Message = structure(logical(0), tags = list(type = "string")), SenderFault = structure(logical(0), tags = list(type = "boolean"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure", resultWrapper = "PublishBatchResult")) return(populate(args, shape)) } .sns$put_data_protection_policy_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ResourceArn = structure(logical(0), tags = list(type = "string")), DataProtectionPolicy = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$put_data_protection_policy_output <- function(...) { list() } .sns$remove_permission_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(TopicArn = structure(logical(0), tags = list(type = "string")), Label = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$remove_permission_output <- function(...) { list() } .sns$set_endpoint_attributes_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(EndpointArn = structure(logical(0), tags = list(type = "string")), Attributes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$set_endpoint_attributes_output <- function(...) { list() } .sns$set_platform_application_attributes_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(PlatformApplicationArn = structure(logical(0), tags = list(type = "string")), Attributes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$set_platform_application_attributes_output <- function(...) { list() } .sns$set_sms_attributes_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(attributes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$set_sms_attributes_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(), tags = list(type = "structure", resultWrapper = "SetSMSAttributesResult")) return(populate(args, shape)) } .sns$set_subscription_attributes_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(SubscriptionArn = structure(logical(0), tags = list(type = "string")), AttributeName = structure(logical(0), tags = list(type = "string")), AttributeValue = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$set_subscription_attributes_output <- function(...) { list() } .sns$set_topic_attributes_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(TopicArn = structure(logical(0), tags = list(type = "string")), AttributeName = structure(logical(0), tags = list(type = "string")), AttributeValue = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$set_topic_attributes_output <- function(...) { list() } .sns$subscribe_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(TopicArn = structure(logical(0), tags = list(type = "string")), Protocol = structure(logical(0), tags = list(type = "string")), Endpoint = structure(logical(0), tags = list(type = "string")), Attributes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map")), ReturnSubscriptionArn = structure(logical(0), tags = list(type = "boolean"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$subscribe_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(SubscriptionArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure", resultWrapper = "SubscribeResult")) return(populate(args, shape)) } .sns$tag_resource_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ResourceArn = structure(logical(0), tags = list(type = "string")), Tags = structure(list(structure(list(Key = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$tag_resource_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(), tags = list(type = "structure", resultWrapper = "TagResourceResult")) return(populate(args, shape)) } .sns$unsubscribe_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(SubscriptionArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$unsubscribe_output <- function(...) { list() } .sns$untag_resource_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ResourceArn = structure(logical(0), tags = list(type = "string")), TagKeys = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$untag_resource_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(), tags = list(type = "structure", resultWrapper = "UntagResourceResult")) return(populate(args, shape)) } .sns$verify_sms_sandbox_phone_number_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(PhoneNumber = structure(logical(0), tags = list(type = "string")), OneTimePassword = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$verify_sms_sandbox_phone_number_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(), tags = list(type = "structure", resultWrapper = "VerifySMSSandboxPhoneNumberResult")) return(populate(args, shape)) }
/cran/paws.application.integration/R/sns_interfaces.R
permissive
paws-r/paws
R
false
false
29,340
r
# This file is generated by make.paws. Please do not edit here. #' @importFrom paws.common populate #' @include sns_service.R NULL .sns$add_permission_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(TopicArn = structure(logical(0), tags = list(type = "string")), Label = structure(logical(0), tags = list(type = "string")), AWSAccountId = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), ActionName = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$add_permission_output <- function(...) { list() } .sns$check_if_phone_number_is_opted_out_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(phoneNumber = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$check_if_phone_number_is_opted_out_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(isOptedOut = structure(logical(0), tags = list(type = "boolean"))), tags = list(type = "structure", resultWrapper = "CheckIfPhoneNumberIsOptedOutResult")) return(populate(args, shape)) } .sns$confirm_subscription_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(TopicArn = structure(logical(0), tags = list(type = "string")), Token = structure(logical(0), tags = list(type = "string")), AuthenticateOnUnsubscribe = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$confirm_subscription_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(SubscriptionArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure", resultWrapper = "ConfirmSubscriptionResult")) return(populate(args, shape)) } .sns$create_platform_application_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Name = structure(logical(0), tags = list(type = "string")), Platform = structure(logical(0), tags = list(type = "string")), Attributes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$create_platform_application_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(PlatformApplicationArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure", resultWrapper = "CreatePlatformApplicationResult")) return(populate(args, shape)) } .sns$create_platform_endpoint_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(PlatformApplicationArn = structure(logical(0), tags = list(type = "string")), Token = structure(logical(0), tags = list(type = "string")), CustomUserData = structure(logical(0), tags = list(type = "string")), Attributes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$create_platform_endpoint_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(EndpointArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure", resultWrapper = "CreatePlatformEndpointResult")) return(populate(args, shape)) } .sns$create_sms_sandbox_phone_number_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(PhoneNumber = structure(logical(0), tags = list(type = "string")), LanguageCode = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$create_sms_sandbox_phone_number_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(), tags = list(type = "structure", resultWrapper = "CreateSMSSandboxPhoneNumberResult")) return(populate(args, shape)) } .sns$create_topic_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Name = structure(logical(0), tags = list(type = "string")), Attributes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map")), Tags = structure(list(structure(list(Key = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), DataProtectionPolicy = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$create_topic_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(TopicArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure", resultWrapper = "CreateTopicResult")) return(populate(args, shape)) } .sns$delete_endpoint_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(EndpointArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$delete_endpoint_output <- function(...) { list() } .sns$delete_platform_application_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(PlatformApplicationArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$delete_platform_application_output <- function(...) { list() } .sns$delete_sms_sandbox_phone_number_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(PhoneNumber = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$delete_sms_sandbox_phone_number_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(), tags = list(type = "structure", resultWrapper = "DeleteSMSSandboxPhoneNumberResult")) return(populate(args, shape)) } .sns$delete_topic_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(TopicArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$delete_topic_output <- function(...) { list() } .sns$get_data_protection_policy_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ResourceArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$get_data_protection_policy_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(DataProtectionPolicy = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure", resultWrapper = "GetDataProtectionPolicyResult")) return(populate(args, shape)) } .sns$get_endpoint_attributes_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(EndpointArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$get_endpoint_attributes_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Attributes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure", resultWrapper = "GetEndpointAttributesResult")) return(populate(args, shape)) } .sns$get_platform_application_attributes_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(PlatformApplicationArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$get_platform_application_attributes_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Attributes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure", resultWrapper = "GetPlatformApplicationAttributesResult")) return(populate(args, shape)) } .sns$get_sms_attributes_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(attributes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$get_sms_attributes_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(attributes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure", resultWrapper = "GetSMSAttributesResult")) return(populate(args, shape)) } .sns$get_sms_sandbox_account_status_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(), tags = list(type = "structure")) return(populate(args, shape)) } .sns$get_sms_sandbox_account_status_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(IsInSandbox = structure(logical(0), tags = list(type = "boolean"))), tags = list(type = "structure", resultWrapper = "GetSMSSandboxAccountStatusResult")) return(populate(args, shape)) } .sns$get_subscription_attributes_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(SubscriptionArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$get_subscription_attributes_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Attributes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure", resultWrapper = "GetSubscriptionAttributesResult")) return(populate(args, shape)) } .sns$get_topic_attributes_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(TopicArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$get_topic_attributes_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Attributes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure", resultWrapper = "GetTopicAttributesResult")) return(populate(args, shape)) } .sns$list_endpoints_by_platform_application_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(PlatformApplicationArn = structure(logical(0), tags = list(type = "string")), NextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$list_endpoints_by_platform_application_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Endpoints = structure(list(structure(list(EndpointArn = structure(logical(0), tags = list(type = "string")), Attributes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure"))), tags = list(type = "list")), NextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure", resultWrapper = "ListEndpointsByPlatformApplicationResult")) return(populate(args, shape)) } .sns$list_origination_numbers_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(type = "string")), MaxResults = structure(logical(0), tags = list(type = "integer"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$list_origination_numbers_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(type = "string")), PhoneNumbers = structure(list(structure(list(CreatedAt = structure(logical(0), tags = list(type = "timestamp")), PhoneNumber = structure(logical(0), tags = list(type = "string")), Status = structure(logical(0), tags = list(type = "string")), Iso2CountryCode = structure(logical(0), tags = list(type = "string")), RouteType = structure(logical(0), tags = list(type = "string")), NumberCapabilities = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure", resultWrapper = "ListOriginationNumbersResult")) return(populate(args, shape)) } .sns$list_phone_numbers_opted_out_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(nextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$list_phone_numbers_opted_out_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(phoneNumbers = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), nextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure", resultWrapper = "ListPhoneNumbersOptedOutResult")) return(populate(args, shape)) } .sns$list_platform_applications_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$list_platform_applications_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(PlatformApplications = structure(list(structure(list(PlatformApplicationArn = structure(logical(0), tags = list(type = "string")), Attributes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure"))), tags = list(type = "list")), NextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure", resultWrapper = "ListPlatformApplicationsResult")) return(populate(args, shape)) } .sns$list_sms_sandbox_phone_numbers_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(type = "string")), MaxResults = structure(logical(0), tags = list(type = "integer"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$list_sms_sandbox_phone_numbers_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(PhoneNumbers = structure(list(structure(list(PhoneNumber = structure(logical(0), tags = list(type = "string")), Status = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), NextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure", resultWrapper = "ListSMSSandboxPhoneNumbersResult")) return(populate(args, shape)) } .sns$list_subscriptions_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$list_subscriptions_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Subscriptions = structure(list(structure(list(SubscriptionArn = structure(logical(0), tags = list(type = "string")), Owner = structure(logical(0), tags = list(type = "string")), Protocol = structure(logical(0), tags = list(type = "string")), Endpoint = structure(logical(0), tags = list(type = "string")), TopicArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), NextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure", resultWrapper = "ListSubscriptionsResult")) return(populate(args, shape)) } .sns$list_subscriptions_by_topic_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(TopicArn = structure(logical(0), tags = list(type = "string")), NextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$list_subscriptions_by_topic_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Subscriptions = structure(list(structure(list(SubscriptionArn = structure(logical(0), tags = list(type = "string")), Owner = structure(logical(0), tags = list(type = "string")), Protocol = structure(logical(0), tags = list(type = "string")), Endpoint = structure(logical(0), tags = list(type = "string")), TopicArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), NextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure", resultWrapper = "ListSubscriptionsByTopicResult")) return(populate(args, shape)) } .sns$list_tags_for_resource_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ResourceArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$list_tags_for_resource_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Tags = structure(list(structure(list(Key = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure", resultWrapper = "ListTagsForResourceResult")) return(populate(args, shape)) } .sns$list_topics_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$list_topics_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Topics = structure(list(structure(list(TopicArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), NextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure", resultWrapper = "ListTopicsResult")) return(populate(args, shape)) } .sns$opt_in_phone_number_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(phoneNumber = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$opt_in_phone_number_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(), tags = list(type = "structure", resultWrapper = "OptInPhoneNumberResult")) return(populate(args, shape)) } .sns$publish_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(TopicArn = structure(logical(0), tags = list(type = "string")), TargetArn = structure(logical(0), tags = list(type = "string")), PhoneNumber = structure(logical(0), tags = list(type = "string")), Message = structure(logical(0), tags = list(type = "string")), Subject = structure(logical(0), tags = list(type = "string")), MessageStructure = structure(logical(0), tags = list(type = "string")), MessageAttributes = structure(list(structure(list(DataType = structure(logical(0), tags = list(type = "string")), StringValue = structure(logical(0), tags = list(type = "string")), BinaryValue = structure(logical(0), tags = list(type = "blob"))), tags = list(locationName = "Value", type = "structure"))), tags = list(locationNameKey = "Name", locationNameValue = "Value", type = "map")), MessageDeduplicationId = structure(logical(0), tags = list(type = "string")), MessageGroupId = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$publish_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(MessageId = structure(logical(0), tags = list(type = "string")), SequenceNumber = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure", resultWrapper = "PublishResult")) return(populate(args, shape)) } .sns$publish_batch_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(TopicArn = structure(logical(0), tags = list(type = "string")), PublishBatchRequestEntries = structure(list(structure(list(Id = structure(logical(0), tags = list(type = "string")), Message = structure(logical(0), tags = list(type = "string")), Subject = structure(logical(0), tags = list(type = "string")), MessageStructure = structure(logical(0), tags = list(type = "string")), MessageAttributes = structure(list(structure(list(DataType = structure(logical(0), tags = list(type = "string")), StringValue = structure(logical(0), tags = list(type = "string")), BinaryValue = structure(logical(0), tags = list(type = "blob"))), tags = list(locationName = "Value", type = "structure"))), tags = list(locationNameKey = "Name", locationNameValue = "Value", type = "map")), MessageDeduplicationId = structure(logical(0), tags = list(type = "string")), MessageGroupId = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$publish_batch_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Successful = structure(list(structure(list(Id = structure(logical(0), tags = list(type = "string")), MessageId = structure(logical(0), tags = list(type = "string")), SequenceNumber = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), Failed = structure(list(structure(list(Id = structure(logical(0), tags = list(type = "string")), Code = structure(logical(0), tags = list(type = "string")), Message = structure(logical(0), tags = list(type = "string")), SenderFault = structure(logical(0), tags = list(type = "boolean"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure", resultWrapper = "PublishBatchResult")) return(populate(args, shape)) } .sns$put_data_protection_policy_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ResourceArn = structure(logical(0), tags = list(type = "string")), DataProtectionPolicy = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$put_data_protection_policy_output <- function(...) { list() } .sns$remove_permission_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(TopicArn = structure(logical(0), tags = list(type = "string")), Label = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$remove_permission_output <- function(...) { list() } .sns$set_endpoint_attributes_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(EndpointArn = structure(logical(0), tags = list(type = "string")), Attributes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$set_endpoint_attributes_output <- function(...) { list() } .sns$set_platform_application_attributes_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(PlatformApplicationArn = structure(logical(0), tags = list(type = "string")), Attributes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$set_platform_application_attributes_output <- function(...) { list() } .sns$set_sms_attributes_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(attributes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$set_sms_attributes_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(), tags = list(type = "structure", resultWrapper = "SetSMSAttributesResult")) return(populate(args, shape)) } .sns$set_subscription_attributes_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(SubscriptionArn = structure(logical(0), tags = list(type = "string")), AttributeName = structure(logical(0), tags = list(type = "string")), AttributeValue = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$set_subscription_attributes_output <- function(...) { list() } .sns$set_topic_attributes_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(TopicArn = structure(logical(0), tags = list(type = "string")), AttributeName = structure(logical(0), tags = list(type = "string")), AttributeValue = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$set_topic_attributes_output <- function(...) { list() } .sns$subscribe_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(TopicArn = structure(logical(0), tags = list(type = "string")), Protocol = structure(logical(0), tags = list(type = "string")), Endpoint = structure(logical(0), tags = list(type = "string")), Attributes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map")), ReturnSubscriptionArn = structure(logical(0), tags = list(type = "boolean"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$subscribe_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(SubscriptionArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure", resultWrapper = "SubscribeResult")) return(populate(args, shape)) } .sns$tag_resource_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ResourceArn = structure(logical(0), tags = list(type = "string")), Tags = structure(list(structure(list(Key = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$tag_resource_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(), tags = list(type = "structure", resultWrapper = "TagResourceResult")) return(populate(args, shape)) } .sns$unsubscribe_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(SubscriptionArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$unsubscribe_output <- function(...) { list() } .sns$untag_resource_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ResourceArn = structure(logical(0), tags = list(type = "string")), TagKeys = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$untag_resource_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(), tags = list(type = "structure", resultWrapper = "UntagResourceResult")) return(populate(args, shape)) } .sns$verify_sms_sandbox_phone_number_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(PhoneNumber = structure(logical(0), tags = list(type = "string")), OneTimePassword = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .sns$verify_sms_sandbox_phone_number_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(), tags = list(type = "structure", resultWrapper = "VerifySMSSandboxPhoneNumberResult")) return(populate(args, shape)) }
library(tidyverse) library(lubridate) all_files<-list.files("Data/Processed/filteredData",full.names = TRUE) first_list<-list() for (i in 1:length(all_files)){ print(i) temp<-readRDS(all_files[i]) temp$LATITUDE<-as.numeric(temp$LATITUDE) temp$LONGITUDE<-as.numeric(temp$LONGITUDE) temp$OBSERVATION.DATE<-as.character(temp$OBSERVATION.DATE) first_list<-bind_rows(first_list,temp) } first_list$in_fire <- recode(first_list$in_fire,True = "In Fire") first_list$in_fire <- replace_na(first_list$in_fire,"Not in Fire") table(first_list$in_fire) first_list$OBSERVATION.DATE<-ymd(first_list$OBSERVATION.DATE) first_list$after_fire<-first_list$OBSERVATION.DATE > ymd("2020-01-10") table(first_list$in_fire,first_list$after_fire) filter(first_list,after_fire&in_fire=="In Fire") %>% ggplot(aes(OBSERVATION.DATE))+geom_histogram()+theme_bw() ggsave("figures/histogram_of_in_fire_samples.pdf") fireshape<- st_read("National_Indicative_Aggregated_Fire_Extent_Dataset_v20200211/National_Indicative_Aggregated_Fire_Extent_Dataset_v20200211.shp") map<- filter(first_list, first_list$in_fire == "In Fire") map2 <- st_as_sf(map, coords=c("LONGITUDE", "LATITUDE"), crs=st_crs(fireshape)) base<- sp::plot(ne_countries(country = 'Australia', scale = 'medium')) library(rnaturalearth) library(sf) library(ggplot2) aus <- ne_countries(country="Australia", returnclass="sf") auscrop <- st_crop(aus, xmin = 110, xmax = 155, ymin = 45, ymax = 25) ggplot()+ geom_sf(data=aus, fill="orange") Mapby3<- ggplot() + geom_sf(data = aus) + geom_sf(data = fireshape, size = 0.1, color = "Red", fill = "Red") + geom_sf(data=map2, size=0.5, colour = 'Blue')+ ggtitle("Checklists inside Fire Boundary") + coord_sf() + theme_bw() + geom_sf(data = aus) make_map <- ggplot()+ geom_sf(data=aus)+ geom_sf(data=fireshape, size = 0.1, colour = "Red", fill = "Red")+ geom_sf(data=map2, size=0.5, colour = 'Blue')+ xlim(110, 155)+ ylim(45, 25)+ coord_sf() + theme_bw() + ggtitle("Checklists inside Fire Boundary")+ theme(legend.title = element_blank()) + scale_fill_manual(values = c('Blue', 'Red'), labels = c('Points', 'Fire')) print(make_map)
/R/Knitandfilter_ebird.R
no_license
Josh-Lee1/eBird-Fire-Index
R
false
false
2,231
r
library(tidyverse) library(lubridate) all_files<-list.files("Data/Processed/filteredData",full.names = TRUE) first_list<-list() for (i in 1:length(all_files)){ print(i) temp<-readRDS(all_files[i]) temp$LATITUDE<-as.numeric(temp$LATITUDE) temp$LONGITUDE<-as.numeric(temp$LONGITUDE) temp$OBSERVATION.DATE<-as.character(temp$OBSERVATION.DATE) first_list<-bind_rows(first_list,temp) } first_list$in_fire <- recode(first_list$in_fire,True = "In Fire") first_list$in_fire <- replace_na(first_list$in_fire,"Not in Fire") table(first_list$in_fire) first_list$OBSERVATION.DATE<-ymd(first_list$OBSERVATION.DATE) first_list$after_fire<-first_list$OBSERVATION.DATE > ymd("2020-01-10") table(first_list$in_fire,first_list$after_fire) filter(first_list,after_fire&in_fire=="In Fire") %>% ggplot(aes(OBSERVATION.DATE))+geom_histogram()+theme_bw() ggsave("figures/histogram_of_in_fire_samples.pdf") fireshape<- st_read("National_Indicative_Aggregated_Fire_Extent_Dataset_v20200211/National_Indicative_Aggregated_Fire_Extent_Dataset_v20200211.shp") map<- filter(first_list, first_list$in_fire == "In Fire") map2 <- st_as_sf(map, coords=c("LONGITUDE", "LATITUDE"), crs=st_crs(fireshape)) base<- sp::plot(ne_countries(country = 'Australia', scale = 'medium')) library(rnaturalearth) library(sf) library(ggplot2) aus <- ne_countries(country="Australia", returnclass="sf") auscrop <- st_crop(aus, xmin = 110, xmax = 155, ymin = 45, ymax = 25) ggplot()+ geom_sf(data=aus, fill="orange") Mapby3<- ggplot() + geom_sf(data = aus) + geom_sf(data = fireshape, size = 0.1, color = "Red", fill = "Red") + geom_sf(data=map2, size=0.5, colour = 'Blue')+ ggtitle("Checklists inside Fire Boundary") + coord_sf() + theme_bw() + geom_sf(data = aus) make_map <- ggplot()+ geom_sf(data=aus)+ geom_sf(data=fireshape, size = 0.1, colour = "Red", fill = "Red")+ geom_sf(data=map2, size=0.5, colour = 'Blue')+ xlim(110, 155)+ ylim(45, 25)+ coord_sf() + theme_bw() + ggtitle("Checklists inside Fire Boundary")+ theme(legend.title = element_blank()) + scale_fill_manual(values = c('Blue', 'Red'), labels = c('Points', 'Fire')) print(make_map)
#' add_axes #' #' Adds axes to the internal region of an OSM plot. #' #' @param map A ggplot2 object to which the axes are to be added #' @param colour Colour of axis (determines colour of all elements: lines, #' ticks, and labels) #' @param pos Positions of axes and labels relative to entire plot device #' @param alpha alpha value for semi-transparent background surrounding axes and #' labels (lower values increase transparency) #' @param fontsize Size of axis font #' @param fontface Fontface for axis labels (1:4=plain,bold,italic,bold-italic) #' @param fontfamily Family of axis font (for example, 'Times') #' @return Modified version of map with axes added #' @export #' #' @seealso \code{\link{plot_osm_basemap}}. #' #' @examples #' bbox <- get_bbox (c (-0.13, 51.5, -0.11, 51.52)) #' map <- plot_osm_basemap (bbox=bbox, bg="gray20") #' map <- add_osm_objects (map, london$dat_BNR, col="gray40") #' map <- add_axes (map) #' print (map) #' #' # Map items are added sequentially, so adding axes prior to objects will #' # produce a different result. #' map <- plot_osm_basemap (bbox=bbox, bg="gray20") #' map <- add_axes (map) #' map <- add_osm_objects (map, london$dat_BNR, col="gray40") #' print_osm_map (map) add_axes <- function (map, colour="black", pos=c(0.02,0.03), alpha=0.4, fontsize=3, fontface, fontfamily) { # --------------- sanity checks and warnings --------------- # ---------- map if (missing (map)) stop ('map must be supplied to add_axes') if (!is (map, 'ggplot')) stop ('map must be a ggplot object') # ---------- alpha alpha <- test_len1 (alpha, 'alpha') alpha <- test_numeric (alpha, 'alpha', 0.4) alpha <- test_range (alpha, 'alpha', c (0, 1), 0.4) # ---------- pos pos <- test_len2 (pos, 'pos') pos <- test_numeric (pos, 'pos', c (0.02, 0.03)) pos <- test_range (pos, 'pos', c (0, 1), c (0.02, 0.03)) # ---------- fontsize fontsize <- test_len1 (fontsize, 'fontsize') fontsize <- test_numeric (fontsize, 'fontsize', 3) fontsize <- test_pos (fontsize, 'fontsize', 3) # --------------- end sanity checks and warnings --------------- # The following are defaults from ggplot2/geom-label.R if (missing (fontface)) fontface <- 1 if (missing (fontfamily)) fontfamily <- "" gs <- ggplot2::geom_segment glab <- ggplot2::geom_label aes <- ggplot2::aes xrange <- map$coordinates$limits$x yrange <- map$coordinates$limits$y xp <- pretty (xrange) [2:(length (pretty (xrange))-1)] yp <- pretty (yrange) [2:(length (pretty (yrange))-1)] xlims <- c (xp [1] - (xp [1] - min (xrange)) / 2, max (xp) - (max (xp) - max (xrange)) / 2) ylims <- c (yp [1] - (yp [1] - min (yrange)) / 2, max (yp) - (max (yp) - max (yrange)) / 2) xaxs_pos <- min (yrange) + pos * diff (yrange) axis_ratio <- diff (yrange) / diff (xrange) yaxs_pos <- min (xrange) + pos * axis_ratio * diff (xrange) # Rectangle around axes expand <- 0.02 x0 <- yaxs_pos [1] - expand * diff (yaxs_pos) x1 <- xrange [2] y0 <- xaxs_pos [1] - expand * diff (xaxs_pos) y1 <- yrange [2] rdat <- data.frame (cbind ("lon"=c (x0, x0, x1, x1, x0), "lat"=c (y0, y1, y1, y0, y0))) lon <- lat <- id <- NULL # suppress 'no visible binding' error aes2 <- ggplot2::aes (x=lon, y=lat, size=0) map <- map + ggplot2::geom_path (data=rdat, mapping=aes2, inherit.aes=FALSE, colour=rgb (1, 1, 1, alpha)) # And rectangles around tick marks, starting with horiztonal x0 <- xp - expand * diff (yaxs_pos) x1 <- xp + expand * diff (yaxs_pos) y <- rep (xaxs_pos [c (1, 2, 2, 1, 1)], length (xp)) x <- as.numeric (rbind (x0, x0, x1, x1, x0)) rdat <- data.frame (cbind ("id"=rep (seq (xp), each=5), "lon"=x, "lat"=y)) aes2 <- ggplot2::aes (x=lon, y=lat, group=id, size=0) map <- map + ggplot2::geom_path (data=rdat, mapping=aes2, inherit.aes=FALSE, colour=rgb (1, 1, 1, alpha)) # Then rectangles around vertical tick marks y0 <- yp - expand * diff (xaxs_pos) y1 <- yp + expand * diff (xaxs_pos) x <- rep (yaxs_pos [c (1, 2, 2, 1, 1)], length (yp)) y <- as.numeric (rbind (y0, y0, y1, y1, y0)) rdat <- data.frame (cbind ("id"=rep (seq (yp), each=5), "lon"=x, "lat"=y)) aes2 <- ggplot2::aes (x=lon, y=lat, group=id, size=0) map <- map + ggplot2::geom_path (data=rdat, mapping=aes2, inherit.aes=FALSE, colour=rgb (1, 1, 1, alpha)) # ------------- horiztonal axis # main line segdat <- data.frame (x1=yaxs_pos [1], x2=max (xrange), y1=xaxs_pos [1], y2=xaxs_pos [1]) x2 <- y2 <- NULL map <- map + gs (data=segdat, colour=colour, mapping=aes (x=x1, y=y1, xend=x2, yend=y2)) # ticks and labels segdat <- data.frame (x1=xp, x2=xp, y1=xaxs_pos [1], y2=xaxs_pos [2]) labdat <- data.frame (x=xp, y=xaxs_pos [2]) map <- map + gs (data=segdat, colour=colour, mapping=ggplot2::aes (x=x1, y=y1, xend=x2, yend=y2)) + glab (data=labdat, mapping=ggplot2::aes (x=x, y=y, label=x), alpha=alpha, size=fontsize, colour=colour, inherit.aes=FALSE, label.size=0, vjust="inward", fontface=fontface, family=fontfamily) # ------------- vertical axis # main line segdat <- data.frame (x1=yaxs_pos [1], x2=yaxs_pos [1], y1=xaxs_pos [1], y2=max (yrange)) map <- map + gs (data=segdat, colour=colour, mapping=aes (x=x1, y=y1, xend=x2, yend=y2)) # ticks and labels segdat <- data.frame (x1=yaxs_pos [1], x2=yaxs_pos [2], y1=yp, y2=yp) labdat <- data.frame (x=yaxs_pos [2], y=yp) map <- map + gs (data=segdat, colour=colour, mapping=aes (x=x1, y=y1, xend=x2, yend=y2)) + glab (data=labdat, mapping=aes (x=x, y=y, label=y), alpha=alpha, size=fontsize, colour=colour, inherit.aes=FALSE, label.size=0, hjust="inward", fontface=fontface, family=fontfamily) return (map) }
/R/add-axes.R
no_license
jeperez/osmplotr
R
false
false
6,367
r
#' add_axes #' #' Adds axes to the internal region of an OSM plot. #' #' @param map A ggplot2 object to which the axes are to be added #' @param colour Colour of axis (determines colour of all elements: lines, #' ticks, and labels) #' @param pos Positions of axes and labels relative to entire plot device #' @param alpha alpha value for semi-transparent background surrounding axes and #' labels (lower values increase transparency) #' @param fontsize Size of axis font #' @param fontface Fontface for axis labels (1:4=plain,bold,italic,bold-italic) #' @param fontfamily Family of axis font (for example, 'Times') #' @return Modified version of map with axes added #' @export #' #' @seealso \code{\link{plot_osm_basemap}}. #' #' @examples #' bbox <- get_bbox (c (-0.13, 51.5, -0.11, 51.52)) #' map <- plot_osm_basemap (bbox=bbox, bg="gray20") #' map <- add_osm_objects (map, london$dat_BNR, col="gray40") #' map <- add_axes (map) #' print (map) #' #' # Map items are added sequentially, so adding axes prior to objects will #' # produce a different result. #' map <- plot_osm_basemap (bbox=bbox, bg="gray20") #' map <- add_axes (map) #' map <- add_osm_objects (map, london$dat_BNR, col="gray40") #' print_osm_map (map) add_axes <- function (map, colour="black", pos=c(0.02,0.03), alpha=0.4, fontsize=3, fontface, fontfamily) { # --------------- sanity checks and warnings --------------- # ---------- map if (missing (map)) stop ('map must be supplied to add_axes') if (!is (map, 'ggplot')) stop ('map must be a ggplot object') # ---------- alpha alpha <- test_len1 (alpha, 'alpha') alpha <- test_numeric (alpha, 'alpha', 0.4) alpha <- test_range (alpha, 'alpha', c (0, 1), 0.4) # ---------- pos pos <- test_len2 (pos, 'pos') pos <- test_numeric (pos, 'pos', c (0.02, 0.03)) pos <- test_range (pos, 'pos', c (0, 1), c (0.02, 0.03)) # ---------- fontsize fontsize <- test_len1 (fontsize, 'fontsize') fontsize <- test_numeric (fontsize, 'fontsize', 3) fontsize <- test_pos (fontsize, 'fontsize', 3) # --------------- end sanity checks and warnings --------------- # The following are defaults from ggplot2/geom-label.R if (missing (fontface)) fontface <- 1 if (missing (fontfamily)) fontfamily <- "" gs <- ggplot2::geom_segment glab <- ggplot2::geom_label aes <- ggplot2::aes xrange <- map$coordinates$limits$x yrange <- map$coordinates$limits$y xp <- pretty (xrange) [2:(length (pretty (xrange))-1)] yp <- pretty (yrange) [2:(length (pretty (yrange))-1)] xlims <- c (xp [1] - (xp [1] - min (xrange)) / 2, max (xp) - (max (xp) - max (xrange)) / 2) ylims <- c (yp [1] - (yp [1] - min (yrange)) / 2, max (yp) - (max (yp) - max (yrange)) / 2) xaxs_pos <- min (yrange) + pos * diff (yrange) axis_ratio <- diff (yrange) / diff (xrange) yaxs_pos <- min (xrange) + pos * axis_ratio * diff (xrange) # Rectangle around axes expand <- 0.02 x0 <- yaxs_pos [1] - expand * diff (yaxs_pos) x1 <- xrange [2] y0 <- xaxs_pos [1] - expand * diff (xaxs_pos) y1 <- yrange [2] rdat <- data.frame (cbind ("lon"=c (x0, x0, x1, x1, x0), "lat"=c (y0, y1, y1, y0, y0))) lon <- lat <- id <- NULL # suppress 'no visible binding' error aes2 <- ggplot2::aes (x=lon, y=lat, size=0) map <- map + ggplot2::geom_path (data=rdat, mapping=aes2, inherit.aes=FALSE, colour=rgb (1, 1, 1, alpha)) # And rectangles around tick marks, starting with horiztonal x0 <- xp - expand * diff (yaxs_pos) x1 <- xp + expand * diff (yaxs_pos) y <- rep (xaxs_pos [c (1, 2, 2, 1, 1)], length (xp)) x <- as.numeric (rbind (x0, x0, x1, x1, x0)) rdat <- data.frame (cbind ("id"=rep (seq (xp), each=5), "lon"=x, "lat"=y)) aes2 <- ggplot2::aes (x=lon, y=lat, group=id, size=0) map <- map + ggplot2::geom_path (data=rdat, mapping=aes2, inherit.aes=FALSE, colour=rgb (1, 1, 1, alpha)) # Then rectangles around vertical tick marks y0 <- yp - expand * diff (xaxs_pos) y1 <- yp + expand * diff (xaxs_pos) x <- rep (yaxs_pos [c (1, 2, 2, 1, 1)], length (yp)) y <- as.numeric (rbind (y0, y0, y1, y1, y0)) rdat <- data.frame (cbind ("id"=rep (seq (yp), each=5), "lon"=x, "lat"=y)) aes2 <- ggplot2::aes (x=lon, y=lat, group=id, size=0) map <- map + ggplot2::geom_path (data=rdat, mapping=aes2, inherit.aes=FALSE, colour=rgb (1, 1, 1, alpha)) # ------------- horiztonal axis # main line segdat <- data.frame (x1=yaxs_pos [1], x2=max (xrange), y1=xaxs_pos [1], y2=xaxs_pos [1]) x2 <- y2 <- NULL map <- map + gs (data=segdat, colour=colour, mapping=aes (x=x1, y=y1, xend=x2, yend=y2)) # ticks and labels segdat <- data.frame (x1=xp, x2=xp, y1=xaxs_pos [1], y2=xaxs_pos [2]) labdat <- data.frame (x=xp, y=xaxs_pos [2]) map <- map + gs (data=segdat, colour=colour, mapping=ggplot2::aes (x=x1, y=y1, xend=x2, yend=y2)) + glab (data=labdat, mapping=ggplot2::aes (x=x, y=y, label=x), alpha=alpha, size=fontsize, colour=colour, inherit.aes=FALSE, label.size=0, vjust="inward", fontface=fontface, family=fontfamily) # ------------- vertical axis # main line segdat <- data.frame (x1=yaxs_pos [1], x2=yaxs_pos [1], y1=xaxs_pos [1], y2=max (yrange)) map <- map + gs (data=segdat, colour=colour, mapping=aes (x=x1, y=y1, xend=x2, yend=y2)) # ticks and labels segdat <- data.frame (x1=yaxs_pos [1], x2=yaxs_pos [2], y1=yp, y2=yp) labdat <- data.frame (x=yaxs_pos [2], y=yp) map <- map + gs (data=segdat, colour=colour, mapping=aes (x=x1, y=y1, xend=x2, yend=y2)) + glab (data=labdat, mapping=aes (x=x, y=y, label=y), alpha=alpha, size=fontsize, colour=colour, inherit.aes=FALSE, label.size=0, hjust="inward", fontface=fontface, family=fontfamily) return (map) }
#FigS2F #single_tails_minus_compile.R library(ggplot2) library(reshape2) library(plyr) binwidth = 1 bin_vector<-function(v,n){unname(tapply(v, (seq_along(v)-1) %/% n, sum))} #note that the 51st bin is the 251st tail length, it is excluded source("ggplot_theme.R") library(ggplot2) library(reshape2) library(plyr) stds<-read.table("/lab/solexa_bartel/teisen/RNAseq/Annotation_files/TAIL_seq/list_of_standards_SWE_notation.txt") hl <- read.table("processed_files/halflifeComparisons/miR-155_minu_PAL_halflives_logspace_global_offset_SS.txt",head=TRUE) colnames(hl)[5] <- "halflife" # hl$halflife<-log(2)/hl$beta # hl<-hl[,c(1,11)] # print(quantile(hl$halflife)) raw<-read.table("/lab/solexa_bartel/teisen/Tail-seq/miR-155_final_analyses/single_tag_files/40min_minus_tag_reformat_no_cutoff_miR-155.txt",sep="\t") sub<-read.table("/lab/solexa_bartel/teisen/Tail-seq/miR-155_final_analyses/single_tag_files/background_subtracted_single_tag_files/tp40m_bs_minus_miR-155_v7.txt",sep="\t") #cleaning data frames raw_accession<-raw[,1] raw[,1]<-NULL raw[,252]<-raw_accession raw<-raw[which(rowSums(raw[,-252])>=50),] colnames(raw)[252]<-"accession" colnames(sub)[252]<-"accession" long_hl_genes<-hl[hl$halflife>8,]$accession short_hl_genes<-hl[hl$halflife<0.5,]$accession raw_long_hl<-raw[which(raw$accession %in% long_hl_genes & raw$accession %in% sub$accession),] raw_short_hl<-raw[which(raw$accession %in% short_hl_genes),] sub_long_hl<-sub[which(sub$accession %in% long_hl_genes),] sub_short_hl<-sub[which(sub$accession %in% short_hl_genes),] print(nrow(raw_long_hl)) print(nrow(sub_long_hl)) print(nrow(raw_short_hl)) print(nrow(sub_short_hl)) tails<-data.frame( "raw_long_hl" = colSums(raw_long_hl[,-252]), "sub_long_hl" = colSums(sub_long_hl[,-252]), "raw_short_hl" = colSums(raw_short_hl[,-252]), "sub_short_hl" = colSums(sub_short_hl[,-252])) tails<-data.frame(apply(tails,2,function(x){x/sum(x)})) print(head(tails)) tails_long<-tails[,c(1,2)] tails_short<-tails[,c(3,4)] colnames(tails_long)[c(1,2)]<-c("raw","sub") colnames(tails_short)[c(1,2)]<-c("raw","sub") tails_long<-data.frame("raw" = bin_vector(tails_long[,1],binwidth), "sub" = bin_vector(tails_long[,2],binwidth)) tails_short<-data.frame("raw" = bin_vector(tails_short[,1],binwidth), "sub" = bin_vector(tails_short[,2],binwidth)) tails_long$hl<-"long" tails_short$hl<-"short" tails_long$tail_length<-0:(250/binwidth) tails_short$tail_length<-0:(250/binwidth) tails<-rbind(tails_long,tails_short) tails_melt<-melt(tails,id=c("tail_length","hl")) tails_melt$hl<-factor(tails_melt$hl,levels=c("short","long")) tails_melt$size = "a" tails_melt[which(tails_melt$variable == "sub"),]$size = "b" tails_melt$variable <- factor(tails_melt$variable, levels = c("sub","raw")) p1<-ggplot(tails_melt[which(tails_melt$tail_length*binwidth != 250),],aes(x=tail_length*binwidth,y=value,color=variable))+facet_wrap(~hl)+ geom_step(aes(size = size),size = rep(c(0.5,1),each = 500))+scale_y_continuous(name=NULL,expand=c(0,0),limits=c(-0.01,0.02))+theme_tim()+ scale_x_continuous(name=NULL,expand=c(0,0),limits=c(0,250))+geom_hline(yintercept=0,linetype="dashed",color="grey") p2<-ggplot(tails,aes(x=raw,y=sub,))+facet_wrap(~hl)+ geom_point(size=0.5)+scale_y_continuous(trans="log10")+theme_tim()+ scale_x_continuous(trans="log10")+geom_abline(slope=1,intercept=0,linetype="dashed",color="grey") ggsave(p1,file="figures/version_9/FigS4.pdf",width=2.5,height=2,useDingbats=FALSE)
/KinetTlnFigures/FigS2FmRNA.R
no_license
timeisen/DynamicsOfCytoplasmicMrnaMetabolism
R
false
false
3,467
r
#FigS2F #single_tails_minus_compile.R library(ggplot2) library(reshape2) library(plyr) binwidth = 1 bin_vector<-function(v,n){unname(tapply(v, (seq_along(v)-1) %/% n, sum))} #note that the 51st bin is the 251st tail length, it is excluded source("ggplot_theme.R") library(ggplot2) library(reshape2) library(plyr) stds<-read.table("/lab/solexa_bartel/teisen/RNAseq/Annotation_files/TAIL_seq/list_of_standards_SWE_notation.txt") hl <- read.table("processed_files/halflifeComparisons/miR-155_minu_PAL_halflives_logspace_global_offset_SS.txt",head=TRUE) colnames(hl)[5] <- "halflife" # hl$halflife<-log(2)/hl$beta # hl<-hl[,c(1,11)] # print(quantile(hl$halflife)) raw<-read.table("/lab/solexa_bartel/teisen/Tail-seq/miR-155_final_analyses/single_tag_files/40min_minus_tag_reformat_no_cutoff_miR-155.txt",sep="\t") sub<-read.table("/lab/solexa_bartel/teisen/Tail-seq/miR-155_final_analyses/single_tag_files/background_subtracted_single_tag_files/tp40m_bs_minus_miR-155_v7.txt",sep="\t") #cleaning data frames raw_accession<-raw[,1] raw[,1]<-NULL raw[,252]<-raw_accession raw<-raw[which(rowSums(raw[,-252])>=50),] colnames(raw)[252]<-"accession" colnames(sub)[252]<-"accession" long_hl_genes<-hl[hl$halflife>8,]$accession short_hl_genes<-hl[hl$halflife<0.5,]$accession raw_long_hl<-raw[which(raw$accession %in% long_hl_genes & raw$accession %in% sub$accession),] raw_short_hl<-raw[which(raw$accession %in% short_hl_genes),] sub_long_hl<-sub[which(sub$accession %in% long_hl_genes),] sub_short_hl<-sub[which(sub$accession %in% short_hl_genes),] print(nrow(raw_long_hl)) print(nrow(sub_long_hl)) print(nrow(raw_short_hl)) print(nrow(sub_short_hl)) tails<-data.frame( "raw_long_hl" = colSums(raw_long_hl[,-252]), "sub_long_hl" = colSums(sub_long_hl[,-252]), "raw_short_hl" = colSums(raw_short_hl[,-252]), "sub_short_hl" = colSums(sub_short_hl[,-252])) tails<-data.frame(apply(tails,2,function(x){x/sum(x)})) print(head(tails)) tails_long<-tails[,c(1,2)] tails_short<-tails[,c(3,4)] colnames(tails_long)[c(1,2)]<-c("raw","sub") colnames(tails_short)[c(1,2)]<-c("raw","sub") tails_long<-data.frame("raw" = bin_vector(tails_long[,1],binwidth), "sub" = bin_vector(tails_long[,2],binwidth)) tails_short<-data.frame("raw" = bin_vector(tails_short[,1],binwidth), "sub" = bin_vector(tails_short[,2],binwidth)) tails_long$hl<-"long" tails_short$hl<-"short" tails_long$tail_length<-0:(250/binwidth) tails_short$tail_length<-0:(250/binwidth) tails<-rbind(tails_long,tails_short) tails_melt<-melt(tails,id=c("tail_length","hl")) tails_melt$hl<-factor(tails_melt$hl,levels=c("short","long")) tails_melt$size = "a" tails_melt[which(tails_melt$variable == "sub"),]$size = "b" tails_melt$variable <- factor(tails_melt$variable, levels = c("sub","raw")) p1<-ggplot(tails_melt[which(tails_melt$tail_length*binwidth != 250),],aes(x=tail_length*binwidth,y=value,color=variable))+facet_wrap(~hl)+ geom_step(aes(size = size),size = rep(c(0.5,1),each = 500))+scale_y_continuous(name=NULL,expand=c(0,0),limits=c(-0.01,0.02))+theme_tim()+ scale_x_continuous(name=NULL,expand=c(0,0),limits=c(0,250))+geom_hline(yintercept=0,linetype="dashed",color="grey") p2<-ggplot(tails,aes(x=raw,y=sub,))+facet_wrap(~hl)+ geom_point(size=0.5)+scale_y_continuous(trans="log10")+theme_tim()+ scale_x_continuous(trans="log10")+geom_abline(slope=1,intercept=0,linetype="dashed",color="grey") ggsave(p1,file="figures/version_9/FigS4.pdf",width=2.5,height=2,useDingbats=FALSE)
## surveys <- read.csv(file="data/surveys.csv") args(read.csv) ## read.csv(file="data/surveys.csv", header=TRUE) # is identical to: ## read.csv("data/surveys.csv", TRUE) ## read.csv(file="data/surveys.csv", header=TRUE) # is identical to: ## read.csv(header=TRUE, file="data/surveys.csv") ## ?barplot ## args(lm) ## ??geom_point ## help.search("kruskal") dput(head(iris)) # iris is an example data.frame that comes with R ## saveRDS(iris, file="/tmp/iris.rds") ## some_data <- readRDS(file="~/Downloads/iris.rds") sessionInfo() ### Creating objects (assignments) ### Vectors and data types # Presentation of the survey data ## if (!require("curl")) { ## install.packages("curl") ## } ## library("curl") ## curl_download("https://dl.dropboxusercontent.com/u/22808457/portal_data_joined.csv", ## "data/portal_data_joined.csv") ## Exercise ## Based on the output of `str(surveys)`, can you answer the following questions? ## * What is the class of the object `surveys`? ## * How many rows and how many columns are in this object? ## * How many species have been recorded during these surveys? ### Factors sex <- factor(c("male", "female", "female", "male")) food <- factor(c("low", "high", "medium", "high", "low", "medium", "high")) levels(food) food <- factor(food, levels=c("low", "medium", "high")) levels(food) min(food) ## doesn't work food <- factor(food, levels=c("low", "medium", "high"), ordered=TRUE) levels(food) min(food) ## works! f <- factor(c(1, 5, 10, 2)) as.numeric(f) ## wrong! and there is no warning... as.numeric(as.character(f)) ## works... as.numeric(levels(f))[f] ## The recommended way. ## Question: How can you recreate this plot but by having "control" ## being listed last instead of first? exprmt <- factor(c("treat1", "treat2", "treat1", "treat3", "treat1", "control", "treat1", "treat2", "treat3")) table(exprmt) barplot(table(exprmt)) ## The data.frame class example_data <- data.frame(animal=c("dog", "cat", "sea cucumber", "sea urchin"), feel=c("furry", "furry", "squishy", "spiny"), weight=c(45, 8, 1.1, 0.8)) str(example_data) example_data <- data.frame(animal=c("dog", "cat", "sea cucumber", "sea urchin"), feel=c("furry", "furry", "squishy", "spiny"), weight=c(45, 8, 1.1, 0.8), stringsAsFactors=FALSE) str(example_data) ## ## There are a few mistakes in this hand crafted `data.frame`, ## ## can you spot and fix them? Don't hesitate to experiment! ## author_book <- data.frame(author_first=c("Charles", "Ernst", "Theodosius"), ## author_last=c(Darwin, Mayr, Dobzhansky), ## year=c(1942, 1970)) ## ## Can you predict the class for each of the columns in the following example? ## ## Check your guesses using `str(country_climate)`. Are they what you expected? ## ## Why? why not? ## country_climate <- data.frame(country=c("Canada", "Panama", "South Africa", "Australia"), ## climate=c("cold", "hot", "temperate", "hot/temperate"), ## temperature=c(10, 30, 18, "15"), ## north_hemisphere=c(TRUE, TRUE, FALSE, "FALSE"), ## has_kangaroo=c(FALSE, FALSE, FALSE, 1)) ## Indexing and sequences ### The function `nrow()` on a `data.frame` returns the number of ### rows. Use it, in conjuction with `seq()` to create a new ### `data.frame` called `surveys_by_10` that includes every 10th row ### of the survey data frame starting at row 10 (10, 20, 30, ...)
/skeleton-lessons.R
permissive
karthik/R-ecology
R
false
false
3,643
r
## surveys <- read.csv(file="data/surveys.csv") args(read.csv) ## read.csv(file="data/surveys.csv", header=TRUE) # is identical to: ## read.csv("data/surveys.csv", TRUE) ## read.csv(file="data/surveys.csv", header=TRUE) # is identical to: ## read.csv(header=TRUE, file="data/surveys.csv") ## ?barplot ## args(lm) ## ??geom_point ## help.search("kruskal") dput(head(iris)) # iris is an example data.frame that comes with R ## saveRDS(iris, file="/tmp/iris.rds") ## some_data <- readRDS(file="~/Downloads/iris.rds") sessionInfo() ### Creating objects (assignments) ### Vectors and data types # Presentation of the survey data ## if (!require("curl")) { ## install.packages("curl") ## } ## library("curl") ## curl_download("https://dl.dropboxusercontent.com/u/22808457/portal_data_joined.csv", ## "data/portal_data_joined.csv") ## Exercise ## Based on the output of `str(surveys)`, can you answer the following questions? ## * What is the class of the object `surveys`? ## * How many rows and how many columns are in this object? ## * How many species have been recorded during these surveys? ### Factors sex <- factor(c("male", "female", "female", "male")) food <- factor(c("low", "high", "medium", "high", "low", "medium", "high")) levels(food) food <- factor(food, levels=c("low", "medium", "high")) levels(food) min(food) ## doesn't work food <- factor(food, levels=c("low", "medium", "high"), ordered=TRUE) levels(food) min(food) ## works! f <- factor(c(1, 5, 10, 2)) as.numeric(f) ## wrong! and there is no warning... as.numeric(as.character(f)) ## works... as.numeric(levels(f))[f] ## The recommended way. ## Question: How can you recreate this plot but by having "control" ## being listed last instead of first? exprmt <- factor(c("treat1", "treat2", "treat1", "treat3", "treat1", "control", "treat1", "treat2", "treat3")) table(exprmt) barplot(table(exprmt)) ## The data.frame class example_data <- data.frame(animal=c("dog", "cat", "sea cucumber", "sea urchin"), feel=c("furry", "furry", "squishy", "spiny"), weight=c(45, 8, 1.1, 0.8)) str(example_data) example_data <- data.frame(animal=c("dog", "cat", "sea cucumber", "sea urchin"), feel=c("furry", "furry", "squishy", "spiny"), weight=c(45, 8, 1.1, 0.8), stringsAsFactors=FALSE) str(example_data) ## ## There are a few mistakes in this hand crafted `data.frame`, ## ## can you spot and fix them? Don't hesitate to experiment! ## author_book <- data.frame(author_first=c("Charles", "Ernst", "Theodosius"), ## author_last=c(Darwin, Mayr, Dobzhansky), ## year=c(1942, 1970)) ## ## Can you predict the class for each of the columns in the following example? ## ## Check your guesses using `str(country_climate)`. Are they what you expected? ## ## Why? why not? ## country_climate <- data.frame(country=c("Canada", "Panama", "South Africa", "Australia"), ## climate=c("cold", "hot", "temperate", "hot/temperate"), ## temperature=c(10, 30, 18, "15"), ## north_hemisphere=c(TRUE, TRUE, FALSE, "FALSE"), ## has_kangaroo=c(FALSE, FALSE, FALSE, 1)) ## Indexing and sequences ### The function `nrow()` on a `data.frame` returns the number of ### rows. Use it, in conjuction with `seq()` to create a new ### `data.frame` called `surveys_by_10` that includes every 10th row ### of the survey data frame starting at row 10 (10, 20, 30, ...)
# Exercise 1: practice with basic R syntax # Create a variable `hometown` that stores the city in which you were born hometown <- 'Hangzhou' # Assign your name to the variable `my_name` my_name <- 'Sihan' # Assign your height (in inches) to a variable `my_height` my_height <- 5.7 # Create a variable `puppies` equal to the number of puppies you'd like to have puppies <- 1 # Create a variable `puppy_price`, which is how much you think a puppy costs puppy_price <- 2000 # Create a variable `total_cost` that has the total cost of all of your puppies total_cost <- puppies * puppy_price # Create a boolean variable `too_expensive`, set to TRUE if the cost is greater # than $1,000 too_expensive <- TRUE # Create a variable `max_puppies`, which is the number of puppies you can # afford for $1,000 max_puppies <- 0
/chapter-05-exercises/exercise-1/exercise.R
permissive
sihanlu2013/book-exercises
R
false
false
824
r
# Exercise 1: practice with basic R syntax # Create a variable `hometown` that stores the city in which you were born hometown <- 'Hangzhou' # Assign your name to the variable `my_name` my_name <- 'Sihan' # Assign your height (in inches) to a variable `my_height` my_height <- 5.7 # Create a variable `puppies` equal to the number of puppies you'd like to have puppies <- 1 # Create a variable `puppy_price`, which is how much you think a puppy costs puppy_price <- 2000 # Create a variable `total_cost` that has the total cost of all of your puppies total_cost <- puppies * puppy_price # Create a boolean variable `too_expensive`, set to TRUE if the cost is greater # than $1,000 too_expensive <- TRUE # Create a variable `max_puppies`, which is the number of puppies you can # afford for $1,000 max_puppies <- 0
rhessysver = "/PATH/rhessys7.0" setwd("/PATH/scripts") # Load these libraries library(pse) library(tidyverse) library(RHESSysIOinR) library(RHESSysPreprocessing) library(lubridate) # define a function - nse NSE = function (m, o) { err = m - o meanobs = mean(o) mse = sum(err*err) ovar = sum((o-meanobs)*(o-meanobs)) nse = ifelse(ovar > 0, 1.0 - mse/ovar,0) nse } # set period for the calibration simulation startyr = YEAR endyr = YEAR # startoutyear - when output should start printing startoutyr = YEAR nyrs = endyr-startoutyr # generate a tec file tecfile = "../tecfiles/tec.cal" strg = sprintf("%d 10 1 1 print_daily_on \n%d 10 1 2 print_daily_growth_on", startoutyr-1, startoutyr-1) write(strg, file=tecfile) # generate parameter sets # how many parameter sets nsets=20 # list parameters factors = c("m","K","pa","po") # type of distributions they arise from q = c("qlnorm", "qunif", "qunif","qunif") # parameters for those distributions q.arg = list(list(meanlog=1,sd=2), list(min=0.9, max=1000), list(min=0.5, max=2.0), list(min=0.5, max=2.0)) # you can choose different distributions and different parameter sets # for example # parameters for those distributions # factors = c("m","K") #q = c("qnorm", "qunif") #q.arg = list(list(mean=0.5,sd=0.01), list(min=100, max=200)) # or for example #factors = c("m","K","gw1","gw2") #q = c("qunif","qunif","qunif","qunif") #q.arg = list(list(min=0.2, max=10), list(min=1, max=1000), list(min=0,max=0.3), list(min=0.5, max=0.99)) #LHS = latin hypercube sample sens = LHS(NULL,factors,nsets,q,q.arg, nboot=500) sens.pars = get.data(sens) # check to make sure values look reasonable summary(sens.pars) # set a unique scenarios number for each parameter set sens.pars$scen = seq(from=1,to=length(sens.pars$m)) # create some data structures to store results # first one to store simulation output # these will just be daily values that you want to keep for ALL simulations, so be cautious # ecovars = c("scen","date","streamflow") might be best ecovars = c("scen", "date","precip", "streamflow","trans","evap","psn","lai") # create a data structure to store calibration metric results # expand this to add additional metrics calmetrics = as.data.frame(matrix(nrow=nsets,ncol=7)) colnames(calmetrics)=c("scen","nse","nselog","rmse","annualbias","perr","meanerr_minmonth") # readin some observed data # this is just an example remember RHESSys streamflow is mm/day obsflow = read.csv("../../flow.csv") colnames(obsflow)=c("ID","PARAM","bdate","value","err") obsflow$date = mdy(obsflow$bdate) obsflow$year = as.integer(year(obsflow$date)) obsflow$month = as.integer(month(obsflow$date)) obsflow$day = as.integer(day(obsflow$date)) obsflow = mkdate(obsflow) # convert to mm/day divide by basin area basin.area = 209 #km2 stoday = 60*60*24 obsflow$mm = obsflow$value * stoday / (basin.area * 1000 * 1000)*1000 ggplot(obsflow, aes(date, mm))+geom_line() obs_wy = obsflow %>% group_by(wy) %>% summarize(totalflow=sum(mm)) ggplot(obs_wy, aes(wy, totalflow))+geom_col() # set the worldfile, flowtable, header, make sure paths make sense relative to working directory worldfile = "../worldfiles/NAME.world" flowtable = "../flowtables/NAME.flow" headrh = "../worldfiles/NAME.hdr" # run rhessys for all the parameters sets start=1 for (j in 1:nsets) { cmd1 = sprintf("%s -t %s -w %s -r %s", rhessysver, tecfile, worldfile, flowtable) cmd2 = sprintf("-pre ../out/test -s %f %f -sv %f %f -gw 0.0 1.0 -svalt %f %f", sens.pars$m[j], sens.pars$K[j], sens.pars$m[j], sens.pars$K[j], sens.pars$pa[j], sens.pars$po[j]) # you will need to edit this line if you are changing other parameters for example #cmd2 = sprintf("-pre ../out/test -s %f %f -sv %f %f -gw 0.0 1.0 -svalt 5.0 1.0", sens.pars$m[j], sens.pars$K[j], sens.pars$m[j], sens.pars$K[j]) cmd3 = sprintf("-st %d 10 1 1 -ed %d 10 1 1 -b -whdr %s -b -tchange 0 0 -climrepeat -b -g", startyr, endyr, headrh) cmdall = paste(cmd1,cmd2,cmd3) # as an alterantive to system you could write all runs to a script and then source that #write(cmdall, file="newscrpt", append=FALSE) system(cmdall) a = readin_rhessys_output("../out/test", g=1, c=1, wy=0) compa = inner_join(a$bd, obsflow) # add additional metrics here if needed calmetrics[j,"rmse"] = sqrt(sum( (compa$streamflow-compa$mm)*(compa$streamflow-compa$mm)) / length(compa$wy)) calmetrics[j,"scen"]=j calmetrics[j,"nse"] = NSE(m=compa$streamflow, o=compa$mm) calmetrics[j,"lognse"]=NSE(m=log(compa$streamflow+0.000001), o=log(compa$mm+0.000001)) calmetrics[j,"pbias"] = sum(compa$streamflow-compa$mm)/sum(compa$mm)*100 calmetrics[j,"annualbias"] = (mean(compa$streamflow)-mean(compa$mm))*365 # min monthly flow cal compa_mwy = compa %>% group_by(wy, month) %>% summarize_all(funs(mean)) compa_mth = compa_mwy %>% group_by(month) %>% summarize(flow=mean(mm)) minmonth = compa_mth[which.min(compa_mth$flow),"month"]$month tmp = subset(compa_mwy, month == minmonth) calmetrics[j,"meanerr_minmonth"] = mean(tmp$streamflow-tmp$mm) # if you want to save some of the results # if not comment all of this out - note calres can be large for long simulation times and/or large nsets if (j==1) { simlen = length(a$bd$year) calres = as.data.frame(matrix(nrow=nsets*simlen, ncol=length(ecovars))) colnames(calres)=ecovars calres$date = ymd(a$bd$date) } endj = start+length(a$bd$wy)-1 calres$scen[start:endj] = j calres$wy[start:endj] = a$bd$wy calres$date[start:endj]=ymd(a$bd$date) calres$streamflow[start:endj] = a$bd$streamflow calres$lai[start:endj] = a$bd$lai calres$psn[start:endj] = a$bd$psn calres$evap[start:endj] = a$bd$evap calres$trans[start:endj] = a$bd$trans calres$precip[start:endj] = a$bd$precip start = endj+1 } # this is the end of the calibration # some output examples ggplot(calres, aes(date, trans, col=as.factor(scen)))+geom_line()+ labs(y="Daily Transpiration mm/day",x="Date") calres$year = year(calres$date) calres$month = as.integer(month(calres$date)) calres$day = day(calres$date) calres = mkdate(calres) ggplot(calres, aes(wy, psn, col=as.factor(scen)))+stat_summary(fun.y=sum, geom="line")+ labs(y="Total Annual Psn (kg/m2/yr)",x="Water Year") calres$month = months(calres$date) ggplot(calres, aes(as.factor(month), trans))+geom_boxplot() calresc = left_join(calres, sens.pars) calresb = left_join(calresc,obsflow[,c("mm","date")], by="date") str_wy = calresb %>% group_by(scen,wy) %>% summarize(streamflow=sum(streamflow), trans=sum(trans), precip=sum(precip), obsstr=sum(mm)) ggplot(str_wy, aes(as.factor(wy), streamflow-obsstr, fill=as.factor(scen)))+geom_col(position="dodge")+ labs(y="Annual Flow Err mm/yr") ggplot(calresc, aes(m, streamflow-mm))+geom_points()+labs(main="Daily Error by m parameter") ggplot(calresc, aes(as.factor(round(K/10)), streamflow-mm))+geom_boxplot()+labs(main="Daily Error by K parameter") ggplot(calresc, aes(po, lai) )+stat_summary(fun.y=mean, geom="point", cex=2, col="red")+ labs(main="Mean Simulation LAI across PO parameter") save.image("cal.RData")
/SnowDrought/scripts/cal_in_R.R
no_license
LouisGraup/SnowDrought
R
false
false
7,131
r
rhessysver = "/PATH/rhessys7.0" setwd("/PATH/scripts") # Load these libraries library(pse) library(tidyverse) library(RHESSysIOinR) library(RHESSysPreprocessing) library(lubridate) # define a function - nse NSE = function (m, o) { err = m - o meanobs = mean(o) mse = sum(err*err) ovar = sum((o-meanobs)*(o-meanobs)) nse = ifelse(ovar > 0, 1.0 - mse/ovar,0) nse } # set period for the calibration simulation startyr = YEAR endyr = YEAR # startoutyear - when output should start printing startoutyr = YEAR nyrs = endyr-startoutyr # generate a tec file tecfile = "../tecfiles/tec.cal" strg = sprintf("%d 10 1 1 print_daily_on \n%d 10 1 2 print_daily_growth_on", startoutyr-1, startoutyr-1) write(strg, file=tecfile) # generate parameter sets # how many parameter sets nsets=20 # list parameters factors = c("m","K","pa","po") # type of distributions they arise from q = c("qlnorm", "qunif", "qunif","qunif") # parameters for those distributions q.arg = list(list(meanlog=1,sd=2), list(min=0.9, max=1000), list(min=0.5, max=2.0), list(min=0.5, max=2.0)) # you can choose different distributions and different parameter sets # for example # parameters for those distributions # factors = c("m","K") #q = c("qnorm", "qunif") #q.arg = list(list(mean=0.5,sd=0.01), list(min=100, max=200)) # or for example #factors = c("m","K","gw1","gw2") #q = c("qunif","qunif","qunif","qunif") #q.arg = list(list(min=0.2, max=10), list(min=1, max=1000), list(min=0,max=0.3), list(min=0.5, max=0.99)) #LHS = latin hypercube sample sens = LHS(NULL,factors,nsets,q,q.arg, nboot=500) sens.pars = get.data(sens) # check to make sure values look reasonable summary(sens.pars) # set a unique scenarios number for each parameter set sens.pars$scen = seq(from=1,to=length(sens.pars$m)) # create some data structures to store results # first one to store simulation output # these will just be daily values that you want to keep for ALL simulations, so be cautious # ecovars = c("scen","date","streamflow") might be best ecovars = c("scen", "date","precip", "streamflow","trans","evap","psn","lai") # create a data structure to store calibration metric results # expand this to add additional metrics calmetrics = as.data.frame(matrix(nrow=nsets,ncol=7)) colnames(calmetrics)=c("scen","nse","nselog","rmse","annualbias","perr","meanerr_minmonth") # readin some observed data # this is just an example remember RHESSys streamflow is mm/day obsflow = read.csv("../../flow.csv") colnames(obsflow)=c("ID","PARAM","bdate","value","err") obsflow$date = mdy(obsflow$bdate) obsflow$year = as.integer(year(obsflow$date)) obsflow$month = as.integer(month(obsflow$date)) obsflow$day = as.integer(day(obsflow$date)) obsflow = mkdate(obsflow) # convert to mm/day divide by basin area basin.area = 209 #km2 stoday = 60*60*24 obsflow$mm = obsflow$value * stoday / (basin.area * 1000 * 1000)*1000 ggplot(obsflow, aes(date, mm))+geom_line() obs_wy = obsflow %>% group_by(wy) %>% summarize(totalflow=sum(mm)) ggplot(obs_wy, aes(wy, totalflow))+geom_col() # set the worldfile, flowtable, header, make sure paths make sense relative to working directory worldfile = "../worldfiles/NAME.world" flowtable = "../flowtables/NAME.flow" headrh = "../worldfiles/NAME.hdr" # run rhessys for all the parameters sets start=1 for (j in 1:nsets) { cmd1 = sprintf("%s -t %s -w %s -r %s", rhessysver, tecfile, worldfile, flowtable) cmd2 = sprintf("-pre ../out/test -s %f %f -sv %f %f -gw 0.0 1.0 -svalt %f %f", sens.pars$m[j], sens.pars$K[j], sens.pars$m[j], sens.pars$K[j], sens.pars$pa[j], sens.pars$po[j]) # you will need to edit this line if you are changing other parameters for example #cmd2 = sprintf("-pre ../out/test -s %f %f -sv %f %f -gw 0.0 1.0 -svalt 5.0 1.0", sens.pars$m[j], sens.pars$K[j], sens.pars$m[j], sens.pars$K[j]) cmd3 = sprintf("-st %d 10 1 1 -ed %d 10 1 1 -b -whdr %s -b -tchange 0 0 -climrepeat -b -g", startyr, endyr, headrh) cmdall = paste(cmd1,cmd2,cmd3) # as an alterantive to system you could write all runs to a script and then source that #write(cmdall, file="newscrpt", append=FALSE) system(cmdall) a = readin_rhessys_output("../out/test", g=1, c=1, wy=0) compa = inner_join(a$bd, obsflow) # add additional metrics here if needed calmetrics[j,"rmse"] = sqrt(sum( (compa$streamflow-compa$mm)*(compa$streamflow-compa$mm)) / length(compa$wy)) calmetrics[j,"scen"]=j calmetrics[j,"nse"] = NSE(m=compa$streamflow, o=compa$mm) calmetrics[j,"lognse"]=NSE(m=log(compa$streamflow+0.000001), o=log(compa$mm+0.000001)) calmetrics[j,"pbias"] = sum(compa$streamflow-compa$mm)/sum(compa$mm)*100 calmetrics[j,"annualbias"] = (mean(compa$streamflow)-mean(compa$mm))*365 # min monthly flow cal compa_mwy = compa %>% group_by(wy, month) %>% summarize_all(funs(mean)) compa_mth = compa_mwy %>% group_by(month) %>% summarize(flow=mean(mm)) minmonth = compa_mth[which.min(compa_mth$flow),"month"]$month tmp = subset(compa_mwy, month == minmonth) calmetrics[j,"meanerr_minmonth"] = mean(tmp$streamflow-tmp$mm) # if you want to save some of the results # if not comment all of this out - note calres can be large for long simulation times and/or large nsets if (j==1) { simlen = length(a$bd$year) calres = as.data.frame(matrix(nrow=nsets*simlen, ncol=length(ecovars))) colnames(calres)=ecovars calres$date = ymd(a$bd$date) } endj = start+length(a$bd$wy)-1 calres$scen[start:endj] = j calres$wy[start:endj] = a$bd$wy calres$date[start:endj]=ymd(a$bd$date) calres$streamflow[start:endj] = a$bd$streamflow calres$lai[start:endj] = a$bd$lai calres$psn[start:endj] = a$bd$psn calres$evap[start:endj] = a$bd$evap calres$trans[start:endj] = a$bd$trans calres$precip[start:endj] = a$bd$precip start = endj+1 } # this is the end of the calibration # some output examples ggplot(calres, aes(date, trans, col=as.factor(scen)))+geom_line()+ labs(y="Daily Transpiration mm/day",x="Date") calres$year = year(calres$date) calres$month = as.integer(month(calres$date)) calres$day = day(calres$date) calres = mkdate(calres) ggplot(calres, aes(wy, psn, col=as.factor(scen)))+stat_summary(fun.y=sum, geom="line")+ labs(y="Total Annual Psn (kg/m2/yr)",x="Water Year") calres$month = months(calres$date) ggplot(calres, aes(as.factor(month), trans))+geom_boxplot() calresc = left_join(calres, sens.pars) calresb = left_join(calresc,obsflow[,c("mm","date")], by="date") str_wy = calresb %>% group_by(scen,wy) %>% summarize(streamflow=sum(streamflow), trans=sum(trans), precip=sum(precip), obsstr=sum(mm)) ggplot(str_wy, aes(as.factor(wy), streamflow-obsstr, fill=as.factor(scen)))+geom_col(position="dodge")+ labs(y="Annual Flow Err mm/yr") ggplot(calresc, aes(m, streamflow-mm))+geom_points()+labs(main="Daily Error by m parameter") ggplot(calresc, aes(as.factor(round(K/10)), streamflow-mm))+geom_boxplot()+labs(main="Daily Error by K parameter") ggplot(calresc, aes(po, lai) )+stat_summary(fun.y=mean, geom="point", cex=2, col="red")+ labs(main="Mean Simulation LAI across PO parameter") save.image("cal.RData")
## Given below are two functions that cache and compute the ## inverse of a matrix. ## This function creates a special "matrix" object ## that can cache its inverse. makeCacheMatrix <- function(mtx = matrix()) { inverse <- NULL set <- function(x) { mtx <<- x; inverse <<- NULL; } get <- function() return(mtx); setinv <- function(inv) inverse <<- inv; getinv <- function() return(inverse); return(list(set = set, get = get, setinv = setinv, getinv = getinv)) } ## This function computes the inverse of the ## "matrix" returned by `makeCacheMatrix` function above. If the inverse has ## already been calculated (and the matrix has not changed), then ## `cacheSolve` should retrieve the inverse from the cache. cacheSolve <- function(mtx, ...) { inverse <- mtx$getinv() if(!is.null(inverse)) { message("Getting cached data...") return(inverse) } data <- mtx$get() invserse <- solve(data, ...) mtx$setinv(inverse) return(inverse) }
/cachematrix.R
no_license
shaunakgupte1/datasharing
R
false
false
1,022
r
## Given below are two functions that cache and compute the ## inverse of a matrix. ## This function creates a special "matrix" object ## that can cache its inverse. makeCacheMatrix <- function(mtx = matrix()) { inverse <- NULL set <- function(x) { mtx <<- x; inverse <<- NULL; } get <- function() return(mtx); setinv <- function(inv) inverse <<- inv; getinv <- function() return(inverse); return(list(set = set, get = get, setinv = setinv, getinv = getinv)) } ## This function computes the inverse of the ## "matrix" returned by `makeCacheMatrix` function above. If the inverse has ## already been calculated (and the matrix has not changed), then ## `cacheSolve` should retrieve the inverse from the cache. cacheSolve <- function(mtx, ...) { inverse <- mtx$getinv() if(!is.null(inverse)) { message("Getting cached data...") return(inverse) } data <- mtx$get() invserse <- solve(data, ...) mtx$setinv(inverse) return(inverse) }
hiv.mortmod <- function(e0 = NULL, child.mort = NULL, adult.mort = NULL, prev = NULL, child.art = NULL, adult.art = NULL, model = 1, region = 1, sex = 1, lt = FALSE, opt = TRUE, recal = NULL){ #data(HIV-MLTs-obs) # e0 if(model==1){ mx.out <- mortmod.e0(e0 = e0, prev = prev, child.art = child.art, adult.art = adult.art, region = region, sex = sex, opt = opt, recal = recal) } # 5q0 if(model==2){ mx.out <- mortmod.5q0(child.mort = child.mort, prev = prev, child.art = child.art, adult.art = adult.art, region = region, sex = sex, opt = opt, recal = recal) } # 5q0 and 45q15 if(model==3){ mx.out <- mortmod.45q15(child.mort = child.mort, adult.mort = adult.mort, prev = prev, child.art = child.art, adult.art = adult.art, region = region, sex = sex, opt = opt, recal = recal) } ## make a life table lt.mx <- function (nmx, sex="female", age = ages, nax=NULL){ n <- c(diff(age), 999) if(is.null(nax)){ nax <- 0.5*n if(n[2]==4){ if(sex == "male"){ if (nmx[1] >= 0.107) { nax[1] <- 0.33 nax[2] <- 1.352 } else { nax[1] <- 0.045 + 2.684 * nmx[1] nax[2] <- 1.651 - 2.816 * nmx[1] } # else } # if (sex == "male") if(sex == "female"){ if (nmx[1] >= 0.107) { nax[1] <- 0.35 nax[2] <- 1.361 } else { nax[1] <- 0.053 + 2.8 * nmx[1] nax[2] <- 1.522 - 1.518 * nmx[1] } # else } #if (sex == "female") } #if(n[2]==4) } #if(is.null(nax)) nqx <- (n * nmx)/(1 + (n - nax) * nmx) nqx <- c(nqx[-(length(nqx))], 1) for (i in 1:length(nqx)) { if (nqx[i] > 1) nqx[i] <- 1 } nage <- length(age) nqx <- round(nqx, 4) npx <- 1 - nqx l0 = 1e+05 lx <- round(cumprod(c(l0, npx))) ndx <- -diff(lx) lxpn <- lx[-1] nLx <- n * lxpn + ndx * nax Tx <- c(rev(cumsum(rev(nLx[-length(nLx)]))),0) lx <- lx[1:length(age)] ex <- Tx/lx lt <- cbind(Age = age, nax = c(round(nax[-length(nax)], 3),NA), nmx = round(nmx,4), nqx = round(nqx, 4), npx = round(npx, 4), ndx = ndx, lx = lx, nLx = c(round(nLx[-length(nLx)]),NA), Tx = c(round(Tx[-length(Tx)]),NA), ex = c(round(ex[-length(ex)],2),NA)) lt <- lt[lt[, 6] != 0, ] e0 <- lt[1, 10] lt.45q15 <- 1 - (lx[which(age==60)]/lx[which(age==15)]) lt.5q0 <- 1 - (lx[which(age==5)]/lx[which(age==0)]) return(list(e0 = e0, lt.5q0 = lt.5q0, lt.45q15 = lt.45q15, lt = lt)) } if(lt==TRUE){ if(sex==1){ sex.tab<-"female" } if(sex==0){ sex.tab<-"male" } lt.out <- lt.mx(nmx=mx.out, sex=sex.tab, age=ages)$lt return(lt.out) } else { return(mx.out)} }
/R/hiv.mortmod.R
no_license
PPgp/HIV.LifeTables
R
false
false
2,933
r
hiv.mortmod <- function(e0 = NULL, child.mort = NULL, adult.mort = NULL, prev = NULL, child.art = NULL, adult.art = NULL, model = 1, region = 1, sex = 1, lt = FALSE, opt = TRUE, recal = NULL){ #data(HIV-MLTs-obs) # e0 if(model==1){ mx.out <- mortmod.e0(e0 = e0, prev = prev, child.art = child.art, adult.art = adult.art, region = region, sex = sex, opt = opt, recal = recal) } # 5q0 if(model==2){ mx.out <- mortmod.5q0(child.mort = child.mort, prev = prev, child.art = child.art, adult.art = adult.art, region = region, sex = sex, opt = opt, recal = recal) } # 5q0 and 45q15 if(model==3){ mx.out <- mortmod.45q15(child.mort = child.mort, adult.mort = adult.mort, prev = prev, child.art = child.art, adult.art = adult.art, region = region, sex = sex, opt = opt, recal = recal) } ## make a life table lt.mx <- function (nmx, sex="female", age = ages, nax=NULL){ n <- c(diff(age), 999) if(is.null(nax)){ nax <- 0.5*n if(n[2]==4){ if(sex == "male"){ if (nmx[1] >= 0.107) { nax[1] <- 0.33 nax[2] <- 1.352 } else { nax[1] <- 0.045 + 2.684 * nmx[1] nax[2] <- 1.651 - 2.816 * nmx[1] } # else } # if (sex == "male") if(sex == "female"){ if (nmx[1] >= 0.107) { nax[1] <- 0.35 nax[2] <- 1.361 } else { nax[1] <- 0.053 + 2.8 * nmx[1] nax[2] <- 1.522 - 1.518 * nmx[1] } # else } #if (sex == "female") } #if(n[2]==4) } #if(is.null(nax)) nqx <- (n * nmx)/(1 + (n - nax) * nmx) nqx <- c(nqx[-(length(nqx))], 1) for (i in 1:length(nqx)) { if (nqx[i] > 1) nqx[i] <- 1 } nage <- length(age) nqx <- round(nqx, 4) npx <- 1 - nqx l0 = 1e+05 lx <- round(cumprod(c(l0, npx))) ndx <- -diff(lx) lxpn <- lx[-1] nLx <- n * lxpn + ndx * nax Tx <- c(rev(cumsum(rev(nLx[-length(nLx)]))),0) lx <- lx[1:length(age)] ex <- Tx/lx lt <- cbind(Age = age, nax = c(round(nax[-length(nax)], 3),NA), nmx = round(nmx,4), nqx = round(nqx, 4), npx = round(npx, 4), ndx = ndx, lx = lx, nLx = c(round(nLx[-length(nLx)]),NA), Tx = c(round(Tx[-length(Tx)]),NA), ex = c(round(ex[-length(ex)],2),NA)) lt <- lt[lt[, 6] != 0, ] e0 <- lt[1, 10] lt.45q15 <- 1 - (lx[which(age==60)]/lx[which(age==15)]) lt.5q0 <- 1 - (lx[which(age==5)]/lx[which(age==0)]) return(list(e0 = e0, lt.5q0 = lt.5q0, lt.45q15 = lt.45q15, lt = lt)) } if(lt==TRUE){ if(sex==1){ sex.tab<-"female" } if(sex==0){ sex.tab<-"male" } lt.out <- lt.mx(nmx=mx.out, sex=sex.tab, age=ages)$lt return(lt.out) } else { return(mx.out)} }
source('~/NBS-DS/R/impala/package.R') options(error=traceback) options(warn=1) # Performance tests for R+impala query transformation library # Select statement for all data for artists below some id on the time range 2014-01-01 to 2014-05-26 query_format = 'SELECT * FROM idx_entity WHERE entity_id < %s and unix_seconds between 1388534400 and 1401062400' # Takes ~20 seconds, returns ~400k rows, takes 24 seconds to unstack system.time(metric.data <- impalaQuery(sprintf(query_format, 100), col.names=COLS_IDX_ENTITY)) system.time(unstacked <- UnstackTimeseries(metric.data)) # Takes ~140 seconds, returns ~3.3M rows, takes 197 seconds to unstack system.time(metric.data <- impalaQuery(sprintf(query_format, 1000), col.names=COLS_IDX_ENTITY)) system.time(unstacked <- UnstackTimeseries(metric.data)) # Takes ~993 seconds (only 400s user), returns ~22.2M rows, takes 1288 seconds to unstack system.time(metric.data <- impalaQuery(sprintf(query_format, 10000), col.names=COLS_IDX_ENTITY)) system.time(unstacked <- UnstackTimeseries(metric.data))
/demonstrative/R/impala/transforms_ptest.R
no_license
eric-czech/portfolio
R
false
false
1,053
r
source('~/NBS-DS/R/impala/package.R') options(error=traceback) options(warn=1) # Performance tests for R+impala query transformation library # Select statement for all data for artists below some id on the time range 2014-01-01 to 2014-05-26 query_format = 'SELECT * FROM idx_entity WHERE entity_id < %s and unix_seconds between 1388534400 and 1401062400' # Takes ~20 seconds, returns ~400k rows, takes 24 seconds to unstack system.time(metric.data <- impalaQuery(sprintf(query_format, 100), col.names=COLS_IDX_ENTITY)) system.time(unstacked <- UnstackTimeseries(metric.data)) # Takes ~140 seconds, returns ~3.3M rows, takes 197 seconds to unstack system.time(metric.data <- impalaQuery(sprintf(query_format, 1000), col.names=COLS_IDX_ENTITY)) system.time(unstacked <- UnstackTimeseries(metric.data)) # Takes ~993 seconds (only 400s user), returns ~22.2M rows, takes 1288 seconds to unstack system.time(metric.data <- impalaQuery(sprintf(query_format, 10000), col.names=COLS_IDX_ENTITY)) system.time(unstacked <- UnstackTimeseries(metric.data))
library (igraph) library (ggplot2) time1 <- c() time2 <- c() time3 <- c() vertex_col <- function(add_df, graph_df) { add_df_1 <- add_df for (i in 1:nrow(add_df)) { if (add_df[i,3] == "SP") { for (j in 1:nrow(graph_df)) { if (graph_df[j,1] == add_df[i,1]) { for (k in 1:nrow(add_df)) { if (add_df[k,1] == graph_df[j,2] & add_df_1[k,2] == 0 & graph_df[j,4] == 0) { tell <- sample (c(T, F), prob = c(0.8, 0.2), size = 1) if (tell == T) { add_df_1[k,2] <- 1 add_df_1[k,3] <- sample(c("SP","ST"), prob = c(0.7,0.3), size = 1) } } else if (add_df[k,1] == graph_df[j,2] & add_df_1[k,2] == 0 & graph_df[j,4] == 1) { add_df_1[k,2] <- 1 add_df_1[k,3] <- sample(c("SP","ST"), prob = c(0.7,0.3), size = 1) } } } else if (graph_df[j,2] == add_df[i,1]) { for (k in 1:nrow(add_df)) { if (add_df[k,1] == graph_df[j,1] & add_df_1[k,2] == 0 & graph_df[j,4] == 0) { tell <- sample (c(T, F), prob = c(0.5, 0.5), size = 1) if (tell == T & add_df_1[k,2] == 0) { add_df_1[k,2] <- 1 add_df_1[k,3] <- sample(c("SP","ST"), prob = c(0.7,0.3), size = 1) } } else if (add_df[k,1] == graph_df[j,1] & add_df_1[k,2] == 0 & graph_df[j,4] == 1) { tell <- sample (c(T, F), prob = c(0.9, 0.1), size = 1) if (tell == T & add_df_1[k,2] == 0) { add_df_1[k,2] <- 1 add_df_1[k,3] <- sample(c("SP","ST"), prob = c(0.7,0.3), size = 1) } } } } } } } return (add_df_1) } edge_col <- function(add_df, graph_df) { add_list <- c() for (i in 1:nrow(add_df)) { if (add_df[i,3] == "SP") { add_list <- c(add_list, as.character(add_df[i,1])) for (j in 1:nrow(graph_df)) { if (graph_df[j,1] == add_df[i,1] | graph_df[j,2] == add_df[i,1]) { graph_df[j,3] <- 1 } } } else if (add_df[i,3] == "ST") { add_list <- c(add_list, as.character(add_df[i,1])) #### for (j in 1:nrow(graph_df)) { if (graph_df[j,1] == add_df[i,1] | graph_df[j,2] == add_df[i,1]) { graph_df[j,3] <- 2 } } } } for (i in 1:nrow(graph_df)) { if (graph_df[i,3] == 1) { if (graph_df[i,2] %in% add_list & graph_df[i,1] %in% add_list) { graph_df[i,3] <- 3 } } } return (graph_df) } print("RANDOM") for (i in 1:20) { g <- sample_gnp(200, 8/200, directed = FALSE, loops = FALSE) people <- paste0("P", as.character(1:200)) V(g)$name <- people graph_df <- as_data_frame(g) graph_df$pass <- 0 graph_df$cf <- 0 for (i in 1:nrow(graph_df)) { graph_df[i,4] <- sample (c(0, 1), prob = c(0.9, 0.1), size = 1) } add_df <- data.frame(people) add_df$knows <- 0 vert <- sample(1:200,1) add_df[vert,2] <- 1 add_df$type <- "I" add_df[vert,3] <- "SP" graph_df <- edge_col(add_df, graph_df) net <- graph_from_data_frame(d=graph_df, vertices=add_df, directed=F) t=1 while (sum(add_df$knows)<nrow(add_df)) { prev_sum <- sum(add_df$knows) add_df <- vertex_col(add_df, graph_df) if (sum(add_df$knows) == prev_sum) { t=t+1 break #Either everyone who migh know already does, or the rumor has gone out of style } graph_df <- edge_col(add_df, graph_df) t=t+1 } time1 = c(time1, t-1) print (time1) } print("SMALL WORLD") for (i in 1:20) { g <- sample_smallworld(1, 200, 5, 8/200) g <- simplify(g) #Just for smallworld people <- paste0("P", as.character(1:200)) V(g)$name <- people graph_df <- as_data_frame(g) graph_df$pass <- 0 graph_df$cf <- 0 for (i in 1:nrow(graph_df)) { graph_df[i,4] <- sample (c(0, 1), prob = c(0.9, 0.1), size = 1) } add_df <- data.frame(people) add_df$knows <- 0 vert <- sample(1:200,1) add_df[vert,2] <- 1 add_df$type <- "I" add_df[vert,3] <- "SP" graph_df <- edge_col(add_df, graph_df) net <- graph_from_data_frame(d=graph_df, vertices=add_df, directed=F) t=1 while (sum(add_df$knows)<nrow(add_df)) { prev_sum <- sum(add_df$knows) add_df <- vertex_col(add_df, graph_df) if (sum(add_df$knows) == prev_sum) { t=t+1 break #Either everyone who migh know already does, or the rumor has gone out of style } graph_df <- edge_col(add_df, graph_df) t=t+1 } time2 = c(time2, t-1) print (time2) } print("PREF attachment") for (i in 1:20) { g <- sample_pa(200, m=4) people <- paste0("P", as.character(1:200)) V(g)$name <- people graph_df <- as_data_frame(g) graph_df$pass <- 0 graph_df$cf <- 0 for (i in 1:nrow(graph_df)) { graph_df[i,4] <- sample (c(0, 1), prob = c(0.9, 0.1), size = 1) } add_df <- data.frame(people) add_df$knows <- 0 vert <- sample(1:200,1) add_df[vert,2] <- 1 add_df$type <- "I" add_df[vert,3] <- "SP" graph_df <- edge_col(add_df, graph_df) net <- graph_from_data_frame(d=graph_df, vertices=add_df, directed=F) t=1 while (sum(add_df$knows)<nrow(add_df)) { prev_sum <- sum(add_df$knows) add_df <- vertex_col(add_df, graph_df) if (sum(add_df$knows) == prev_sum) { t=t+1 break #Either everyone who migh know already does, or the rumor has gone out of style } graph_df <- edge_col(add_df, graph_df) t=t+1 } time3 = c(time3, t-1) print (time3) } group.index <- rep(1:3, c(length(time1), length(time2), length(time3))) den <- sm.density.compare(c(time1, time2, time3), group = group.index, model = "equal", xlim=c(0,14), main = "Rumor extinction times", xlab = "Generations", col = c("steelblue", "forestgreen", "darkred")) legend(x=9, y=0.45, c("Random network", "Small world network", "Preferential attachment network"), cex= 0.95, pch = 1, col = c("red","green","blue"), bty = "n")
/Lesson 5/density.R
no_license
itaguas/Modelizaci-n
R
false
false
6,158
r
library (igraph) library (ggplot2) time1 <- c() time2 <- c() time3 <- c() vertex_col <- function(add_df, graph_df) { add_df_1 <- add_df for (i in 1:nrow(add_df)) { if (add_df[i,3] == "SP") { for (j in 1:nrow(graph_df)) { if (graph_df[j,1] == add_df[i,1]) { for (k in 1:nrow(add_df)) { if (add_df[k,1] == graph_df[j,2] & add_df_1[k,2] == 0 & graph_df[j,4] == 0) { tell <- sample (c(T, F), prob = c(0.8, 0.2), size = 1) if (tell == T) { add_df_1[k,2] <- 1 add_df_1[k,3] <- sample(c("SP","ST"), prob = c(0.7,0.3), size = 1) } } else if (add_df[k,1] == graph_df[j,2] & add_df_1[k,2] == 0 & graph_df[j,4] == 1) { add_df_1[k,2] <- 1 add_df_1[k,3] <- sample(c("SP","ST"), prob = c(0.7,0.3), size = 1) } } } else if (graph_df[j,2] == add_df[i,1]) { for (k in 1:nrow(add_df)) { if (add_df[k,1] == graph_df[j,1] & add_df_1[k,2] == 0 & graph_df[j,4] == 0) { tell <- sample (c(T, F), prob = c(0.5, 0.5), size = 1) if (tell == T & add_df_1[k,2] == 0) { add_df_1[k,2] <- 1 add_df_1[k,3] <- sample(c("SP","ST"), prob = c(0.7,0.3), size = 1) } } else if (add_df[k,1] == graph_df[j,1] & add_df_1[k,2] == 0 & graph_df[j,4] == 1) { tell <- sample (c(T, F), prob = c(0.9, 0.1), size = 1) if (tell == T & add_df_1[k,2] == 0) { add_df_1[k,2] <- 1 add_df_1[k,3] <- sample(c("SP","ST"), prob = c(0.7,0.3), size = 1) } } } } } } } return (add_df_1) } edge_col <- function(add_df, graph_df) { add_list <- c() for (i in 1:nrow(add_df)) { if (add_df[i,3] == "SP") { add_list <- c(add_list, as.character(add_df[i,1])) for (j in 1:nrow(graph_df)) { if (graph_df[j,1] == add_df[i,1] | graph_df[j,2] == add_df[i,1]) { graph_df[j,3] <- 1 } } } else if (add_df[i,3] == "ST") { add_list <- c(add_list, as.character(add_df[i,1])) #### for (j in 1:nrow(graph_df)) { if (graph_df[j,1] == add_df[i,1] | graph_df[j,2] == add_df[i,1]) { graph_df[j,3] <- 2 } } } } for (i in 1:nrow(graph_df)) { if (graph_df[i,3] == 1) { if (graph_df[i,2] %in% add_list & graph_df[i,1] %in% add_list) { graph_df[i,3] <- 3 } } } return (graph_df) } print("RANDOM") for (i in 1:20) { g <- sample_gnp(200, 8/200, directed = FALSE, loops = FALSE) people <- paste0("P", as.character(1:200)) V(g)$name <- people graph_df <- as_data_frame(g) graph_df$pass <- 0 graph_df$cf <- 0 for (i in 1:nrow(graph_df)) { graph_df[i,4] <- sample (c(0, 1), prob = c(0.9, 0.1), size = 1) } add_df <- data.frame(people) add_df$knows <- 0 vert <- sample(1:200,1) add_df[vert,2] <- 1 add_df$type <- "I" add_df[vert,3] <- "SP" graph_df <- edge_col(add_df, graph_df) net <- graph_from_data_frame(d=graph_df, vertices=add_df, directed=F) t=1 while (sum(add_df$knows)<nrow(add_df)) { prev_sum <- sum(add_df$knows) add_df <- vertex_col(add_df, graph_df) if (sum(add_df$knows) == prev_sum) { t=t+1 break #Either everyone who migh know already does, or the rumor has gone out of style } graph_df <- edge_col(add_df, graph_df) t=t+1 } time1 = c(time1, t-1) print (time1) } print("SMALL WORLD") for (i in 1:20) { g <- sample_smallworld(1, 200, 5, 8/200) g <- simplify(g) #Just for smallworld people <- paste0("P", as.character(1:200)) V(g)$name <- people graph_df <- as_data_frame(g) graph_df$pass <- 0 graph_df$cf <- 0 for (i in 1:nrow(graph_df)) { graph_df[i,4] <- sample (c(0, 1), prob = c(0.9, 0.1), size = 1) } add_df <- data.frame(people) add_df$knows <- 0 vert <- sample(1:200,1) add_df[vert,2] <- 1 add_df$type <- "I" add_df[vert,3] <- "SP" graph_df <- edge_col(add_df, graph_df) net <- graph_from_data_frame(d=graph_df, vertices=add_df, directed=F) t=1 while (sum(add_df$knows)<nrow(add_df)) { prev_sum <- sum(add_df$knows) add_df <- vertex_col(add_df, graph_df) if (sum(add_df$knows) == prev_sum) { t=t+1 break #Either everyone who migh know already does, or the rumor has gone out of style } graph_df <- edge_col(add_df, graph_df) t=t+1 } time2 = c(time2, t-1) print (time2) } print("PREF attachment") for (i in 1:20) { g <- sample_pa(200, m=4) people <- paste0("P", as.character(1:200)) V(g)$name <- people graph_df <- as_data_frame(g) graph_df$pass <- 0 graph_df$cf <- 0 for (i in 1:nrow(graph_df)) { graph_df[i,4] <- sample (c(0, 1), prob = c(0.9, 0.1), size = 1) } add_df <- data.frame(people) add_df$knows <- 0 vert <- sample(1:200,1) add_df[vert,2] <- 1 add_df$type <- "I" add_df[vert,3] <- "SP" graph_df <- edge_col(add_df, graph_df) net <- graph_from_data_frame(d=graph_df, vertices=add_df, directed=F) t=1 while (sum(add_df$knows)<nrow(add_df)) { prev_sum <- sum(add_df$knows) add_df <- vertex_col(add_df, graph_df) if (sum(add_df$knows) == prev_sum) { t=t+1 break #Either everyone who migh know already does, or the rumor has gone out of style } graph_df <- edge_col(add_df, graph_df) t=t+1 } time3 = c(time3, t-1) print (time3) } group.index <- rep(1:3, c(length(time1), length(time2), length(time3))) den <- sm.density.compare(c(time1, time2, time3), group = group.index, model = "equal", xlim=c(0,14), main = "Rumor extinction times", xlab = "Generations", col = c("steelblue", "forestgreen", "darkred")) legend(x=9, y=0.45, c("Random network", "Small world network", "Preferential attachment network"), cex= 0.95, pch = 1, col = c("red","green","blue"), bty = "n")
# Exercise 6: dplyr join operations # Install the `"nycflights13"` package. Load (`library()`) the package. # You'll also need to load `dplyr` #install.packages("nycflights13") # should be done already library("nycflights13") library("dplyr") # Create a dataframe of the average arrival delays for each _destination_, then # use `left_join()` to join on the "airports" dataframe, which has the airport # information # Which airport had the largest average arrival delay? avg_arr_delay_df <- flights %>% group_by(dest) %>% summarize(avg_arr_delay = mean(arr_delay)) avg_arr_delay_df <- left_join(airports, avg_arr_delay_df) # Create a dataframe of the average arrival delay for each _airline_, then use # `left_join()` to join on the "airlines" dataframe # Which airline had the smallest average arrival delay?
/chapter-11-exercises/exercise-6/exercise.R
permissive
k1997fh/book-exercises
R
false
false
841
r
# Exercise 6: dplyr join operations # Install the `"nycflights13"` package. Load (`library()`) the package. # You'll also need to load `dplyr` #install.packages("nycflights13") # should be done already library("nycflights13") library("dplyr") # Create a dataframe of the average arrival delays for each _destination_, then # use `left_join()` to join on the "airports" dataframe, which has the airport # information # Which airport had the largest average arrival delay? avg_arr_delay_df <- flights %>% group_by(dest) %>% summarize(avg_arr_delay = mean(arr_delay)) avg_arr_delay_df <- left_join(airports, avg_arr_delay_df) # Create a dataframe of the average arrival delay for each _airline_, then use # `left_join()` to join on the "airlines" dataframe # Which airline had the smallest average arrival delay?
#' Format a string #' @name str_format #' @title format a string like python #' #' @param str A string #' @param ... See details #' @return A string or a string vector #' #' @references \url{https://docs.python.org/3/library/stdtypes.html#str.format} #' \url{https://github.com/nicolewhite/pystr/blob/master/R/pystr_format.R} #' #' @examples #' #Numeric placeholders #' str_format("Hello {1}, Hello {2}", "world", "data") #' str_format("Hello {1}, Hello {2}", c("world", "data")) #' str_format("Hello {1}, Hello {2}", list("world", "data")) #' #' #Named placeholders #' str_format("Hello {name}, Hello {name_}", name="world", name_="data") #' str_format("Hello {name}, Hello {name_}", list(name="world", name_="data")) #' str_format("Hello {name}, Hello {name_}", c(name="world", name_="data")) #' #' #vector paramters #' str_format("Hello {name}, Hello {name_}", name=paste0("World", 1:10), name_=paste0("Data", 1:10)) str_format <- function(str, ...) { args <- list(...) if (length(args) == 0) return(str) params <- if (length(args) == 1) args[[1]] else args len <- sapply(params, length) if (any(len != mean(len))) stop("The arguments should have the same length") if (is.null(names(params))) names(params) <- 1:length(params) str_tmp <- rep(str, mean(len)) for (i in 1:length(params)) { pattern <- paste0("\\{", names(params[i]), "\\}") sub_params <- params[[i]] for (j in 1:len[1]) { str_tmp[j] <- gsub(pattern, sub_params[j], str_tmp[j]) } } str_res <- if (mean(len) == 1) str_tmp[1] else str_tmp return(str_res) }
/R/py_format.R
no_license
evanwang1990/stringr
R
false
false
1,576
r
#' Format a string #' @name str_format #' @title format a string like python #' #' @param str A string #' @param ... See details #' @return A string or a string vector #' #' @references \url{https://docs.python.org/3/library/stdtypes.html#str.format} #' \url{https://github.com/nicolewhite/pystr/blob/master/R/pystr_format.R} #' #' @examples #' #Numeric placeholders #' str_format("Hello {1}, Hello {2}", "world", "data") #' str_format("Hello {1}, Hello {2}", c("world", "data")) #' str_format("Hello {1}, Hello {2}", list("world", "data")) #' #' #Named placeholders #' str_format("Hello {name}, Hello {name_}", name="world", name_="data") #' str_format("Hello {name}, Hello {name_}", list(name="world", name_="data")) #' str_format("Hello {name}, Hello {name_}", c(name="world", name_="data")) #' #' #vector paramters #' str_format("Hello {name}, Hello {name_}", name=paste0("World", 1:10), name_=paste0("Data", 1:10)) str_format <- function(str, ...) { args <- list(...) if (length(args) == 0) return(str) params <- if (length(args) == 1) args[[1]] else args len <- sapply(params, length) if (any(len != mean(len))) stop("The arguments should have the same length") if (is.null(names(params))) names(params) <- 1:length(params) str_tmp <- rep(str, mean(len)) for (i in 1:length(params)) { pattern <- paste0("\\{", names(params[i]), "\\}") sub_params <- params[[i]] for (j in 1:len[1]) { str_tmp[j] <- gsub(pattern, sub_params[j], str_tmp[j]) } } str_res <- if (mean(len) == 1) str_tmp[1] else str_tmp return(str_res) }
testlist <- list(doy = c(4.62595082430429e-312, 3.64097969159734e-277, -0.427429395729092, 2.09887675795476e-104, 1.55322770574539e-47, 1.45474215376015e+135, 3.56441595774554e+114, -2.64525441665141e+303, -9.52682579807939e+139, -3.98397415900396e+183, -1.77863325536183e+126, 6.42851301544252e-310, 1.66013830765329e-307, 0.000234804018098546, 1.91570942562165e+206, 365.687522888184, 2.07029838648818e+24, -7.21048519616203e+198, 3.51433879412484e+125, -7.92665263616256e+107, 1.17913068623545e+75 ), latitude = c(-2.61899946856284e-59, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)) result <- do.call(meteor:::Photoperiod,testlist) str(result)
/meteor/inst/testfiles/Photoperiod/AFL_Photoperiod/Photoperiod_valgrind_files/1615769492-test.R
no_license
akhikolla/updatedatatype-list3
R
false
false
683
r
testlist <- list(doy = c(4.62595082430429e-312, 3.64097969159734e-277, -0.427429395729092, 2.09887675795476e-104, 1.55322770574539e-47, 1.45474215376015e+135, 3.56441595774554e+114, -2.64525441665141e+303, -9.52682579807939e+139, -3.98397415900396e+183, -1.77863325536183e+126, 6.42851301544252e-310, 1.66013830765329e-307, 0.000234804018098546, 1.91570942562165e+206, 365.687522888184, 2.07029838648818e+24, -7.21048519616203e+198, 3.51433879412484e+125, -7.92665263616256e+107, 1.17913068623545e+75 ), latitude = c(-2.61899946856284e-59, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)) result <- do.call(meteor:::Photoperiod,testlist) str(result)
#********************************* 277 Yelp Social Network Analysis *************************************************** #Filename: Yelp_extraction.R #Date: January 2021 #Author: Team1A #*************************************************************************************************** library(jsonlite) library(tidyr) library(dplyr) library(stringr) library(tidyjson) library(tidyverse) #install.packages("tidyjson") user_out <- lapply(readLines("yelp_academic_dataset_user.json"), fromJSON) #parse through each user's data and only obtain columns we are interested in yelp_parse <- function(x) { parse_list <- list(user_id = x$user_id, name = x$name, review_count = x$review_count, yelping_since = x$yelping_since, elite = x$elite, friends = x$friends, fans = x$fans, average_stars = x$average_stars) parse_list <- lapply(parse_list, FUN = function(x) ifelse(is.null(x), "", x)) df <- data_frame(user_id=parse_list$user_id, name=parse_list$name, review_count = parse_list$review_count, yelping_since=parse_list$yelping_since, elite = parse_list$elite, friends = parse_list$friends, fans = parse_list$fans, average_stars = parse_list$average_stars) df } user_list <- lapply(user_out, FUN = yelp_parse) #should now have a dictionary with only keys and values we want #now, make this into a table user_df <- data.frame(matrix(unlist(user_list), nrow=length(user_list), byrow=TRUE),stringsAsFactors=FALSE) #set column names colnames(user_df) <- c("user_id", "name", "review_count", "yelping_since", "elite", "friends", "fans", "average_stars") #count string of friends (how many characters appear after comma) num_friends <- count.fields(textConnection(user_df$friends), sep = ",") user_df$friend_count <- num_friends #count string of elite count (how many times they earned 'elite' status) user_df$elite_count <- sapply(strsplit(as.character(user_df$elite), ","), length) #reformat date and split date into three columns (year, month, day) user_df <- user_df %>% mutate(year = year(user_df$yelping_since), month = month(user_df$yelping_since), day = day(user_df$yelping_since)) #remove columns we don't need user_df[ ,c('yelping_since', 'yelping_date', 'month', 'day')] <- list(NULL) #save as csv write.csv(user_df, file="user_df.csv") #make subgroups of elite and non-elite non_elite <- subset(user_df, user_df$elite_count == 0) elite <- subset(user_df, user_df$elite_count != 0) write.csv(non_elite, file="non_elite_users.csv") write.csv(elite, file = "elite_users.csv")
/Yelp_data_extraction.R
no_license
chengwuw/Yelp-Social-Network-Analysis
R
false
false
2,826
r
#********************************* 277 Yelp Social Network Analysis *************************************************** #Filename: Yelp_extraction.R #Date: January 2021 #Author: Team1A #*************************************************************************************************** library(jsonlite) library(tidyr) library(dplyr) library(stringr) library(tidyjson) library(tidyverse) #install.packages("tidyjson") user_out <- lapply(readLines("yelp_academic_dataset_user.json"), fromJSON) #parse through each user's data and only obtain columns we are interested in yelp_parse <- function(x) { parse_list <- list(user_id = x$user_id, name = x$name, review_count = x$review_count, yelping_since = x$yelping_since, elite = x$elite, friends = x$friends, fans = x$fans, average_stars = x$average_stars) parse_list <- lapply(parse_list, FUN = function(x) ifelse(is.null(x), "", x)) df <- data_frame(user_id=parse_list$user_id, name=parse_list$name, review_count = parse_list$review_count, yelping_since=parse_list$yelping_since, elite = parse_list$elite, friends = parse_list$friends, fans = parse_list$fans, average_stars = parse_list$average_stars) df } user_list <- lapply(user_out, FUN = yelp_parse) #should now have a dictionary with only keys and values we want #now, make this into a table user_df <- data.frame(matrix(unlist(user_list), nrow=length(user_list), byrow=TRUE),stringsAsFactors=FALSE) #set column names colnames(user_df) <- c("user_id", "name", "review_count", "yelping_since", "elite", "friends", "fans", "average_stars") #count string of friends (how many characters appear after comma) num_friends <- count.fields(textConnection(user_df$friends), sep = ",") user_df$friend_count <- num_friends #count string of elite count (how many times they earned 'elite' status) user_df$elite_count <- sapply(strsplit(as.character(user_df$elite), ","), length) #reformat date and split date into three columns (year, month, day) user_df <- user_df %>% mutate(year = year(user_df$yelping_since), month = month(user_df$yelping_since), day = day(user_df$yelping_since)) #remove columns we don't need user_df[ ,c('yelping_since', 'yelping_date', 'month', 'day')] <- list(NULL) #save as csv write.csv(user_df, file="user_df.csv") #make subgroups of elite and non-elite non_elite <- subset(user_df, user_df$elite_count == 0) elite <- subset(user_df, user_df$elite_count != 0) write.csv(non_elite, file="non_elite_users.csv") write.csv(elite, file = "elite_users.csv")
# load 10 lines of data data <- read.table("data/household_power_consumption.txt", header = TRUE, sep = ";", nrows = 10, na.strings = '?') # get column classes colClasses <- sapply(data, class) # read data data <- read.table("data/household_power_consumption.txt", header = TRUE, sep = ";", colClasses = colClasses, na.strings = '?') # Parse date/time into datetime and delete unnecesary columns data$DateTime <- strptime(paste(as.character(data[,1]), as.character(data[,2])), '%d/%m/%Y %H:%M:%S') # Delete unnecessary columns data <- data[,3:10] # Keep only records from 2007-02-01 and 2007-02-02 data <- data[as.Date(data$DateTime) >= as.Date('2007-02-01') & as.Date(data$DateTime) < as.Date('2007-02-03'),] png(filename = "plot2.png", width = 480, height = 480) plot(data$DateTime, data$Global_active_power, type = "s", ylab = "Global Active Power (kilowatts)", xlab = "") dev.off()
/plot2.R
no_license
martjanz/ExData_Plotting1
R
false
false
1,114
r
# load 10 lines of data data <- read.table("data/household_power_consumption.txt", header = TRUE, sep = ";", nrows = 10, na.strings = '?') # get column classes colClasses <- sapply(data, class) # read data data <- read.table("data/household_power_consumption.txt", header = TRUE, sep = ";", colClasses = colClasses, na.strings = '?') # Parse date/time into datetime and delete unnecesary columns data$DateTime <- strptime(paste(as.character(data[,1]), as.character(data[,2])), '%d/%m/%Y %H:%M:%S') # Delete unnecessary columns data <- data[,3:10] # Keep only records from 2007-02-01 and 2007-02-02 data <- data[as.Date(data$DateTime) >= as.Date('2007-02-01') & as.Date(data$DateTime) < as.Date('2007-02-03'),] png(filename = "plot2.png", width = 480, height = 480) plot(data$DateTime, data$Global_active_power, type = "s", ylab = "Global Active Power (kilowatts)", xlab = "") dev.off()
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/GMLMultiSurface.R \docType{class} \name{GMLMultiSurface} \alias{GMLMultiSurface} \title{GMLMultiSurface} \format{ \code{\link{R6Class}} object. } \value{ Object of \code{\link{R6Class}} for modelling an GML multisurface } \description{ GMLMultiSurface GMLMultiSurface } \note{ Experimental } \references{ ISO 19136:2007 Geographic Information -- Geographic Markup Language. http://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=32554 OGC Geography Markup Language. http://www.opengeospatial.org/standards/gml } \author{ Emmanuel Blondel <emmanuel.blondel1@gmail.com> } \keyword{GML} \keyword{ISO} \keyword{MultiSurface} \section{Super classes}{ \code{\link[geometa:geometaLogger]{geometa::geometaLogger}} -> \code{\link[geometa:ISOAbstractObject]{geometa::ISOAbstractObject}} -> \code{\link[geometa:GMLAbstractObject]{geometa::GMLAbstractObject}} -> \code{\link[geometa:GMLAbstractGML]{geometa::GMLAbstractGML}} -> \code{\link[geometa:GMLAbstractGeometry]{geometa::GMLAbstractGeometry}} -> \code{\link[geometa:GMLAbstractGeometricAggregate]{geometa::GMLAbstractGeometricAggregate}} -> \code{GMLMultiSurface} } \section{Public fields}{ \if{html}{\out{<div class="r6-fields">}} \describe{ \item{\code{attrs}}{gml attributes} \item{\code{surfaceMember}}{surface members} } \if{html}{\out{</div>}} } \section{Methods}{ \subsection{Public methods}{ \itemize{ \item \href{#method-GMLMultiSurface-new}{\code{GMLMultiSurface$new()}} \item \href{#method-GMLMultiSurface-addSurfaceMember}{\code{GMLMultiSurface$addSurfaceMember()}} \item \href{#method-GMLMultiSurface-delSurfaceMember}{\code{GMLMultiSurface$delSurfaceMember()}} \item \href{#method-GMLMultiSurface-clone}{\code{GMLMultiSurface$clone()}} } } \if{html}{\out{ <details><summary>Inherited methods</summary> <ul> <li><span class="pkg-link" data-pkg="geometa" data-topic="geometaLogger" data-id="ERROR"><a href='../../geometa/html/geometaLogger.html#method-geometaLogger-ERROR'><code>geometa::geometaLogger$ERROR()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="geometaLogger" data-id="INFO"><a href='../../geometa/html/geometaLogger.html#method-geometaLogger-INFO'><code>geometa::geometaLogger$INFO()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="geometaLogger" data-id="WARN"><a href='../../geometa/html/geometaLogger.html#method-geometaLogger-WARN'><code>geometa::geometaLogger$WARN()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="addFieldAttrs"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-addFieldAttrs'><code>geometa::ISOAbstractObject$addFieldAttrs()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="addListElement"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-addListElement'><code>geometa::ISOAbstractObject$addListElement()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="contains"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-contains'><code>geometa::ISOAbstractObject$contains()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="createLocalisedProperty"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-createLocalisedProperty'><code>geometa::ISOAbstractObject$createLocalisedProperty()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="decode"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-decode'><code>geometa::ISOAbstractObject$decode()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="delListElement"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-delListElement'><code>geometa::ISOAbstractObject$delListElement()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="encode"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-encode'><code>geometa::ISOAbstractObject$encode()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="getClass"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-getClass'><code>geometa::ISOAbstractObject$getClass()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="getClassName"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-getClassName'><code>geometa::ISOAbstractObject$getClassName()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="getNamespaceDefinition"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-getNamespaceDefinition'><code>geometa::ISOAbstractObject$getNamespaceDefinition()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="isDocument"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-isDocument'><code>geometa::ISOAbstractObject$isDocument()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="isFieldInheritedFrom"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-isFieldInheritedFrom'><code>geometa::ISOAbstractObject$isFieldInheritedFrom()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="print"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-print'><code>geometa::ISOAbstractObject$print()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="save"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-save'><code>geometa::ISOAbstractObject$save()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="setAttr"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-setAttr'><code>geometa::ISOAbstractObject$setAttr()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="setCodeList"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-setCodeList'><code>geometa::ISOAbstractObject$setCodeList()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="setCodeListValue"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-setCodeListValue'><code>geometa::ISOAbstractObject$setCodeListValue()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="setCodeSpace"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-setCodeSpace'><code>geometa::ISOAbstractObject$setCodeSpace()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="setHref"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-setHref'><code>geometa::ISOAbstractObject$setHref()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="setId"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-setId'><code>geometa::ISOAbstractObject$setId()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="setIsNull"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-setIsNull'><code>geometa::ISOAbstractObject$setIsNull()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="setValue"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-setValue'><code>geometa::ISOAbstractObject$setValue()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="validate"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-validate'><code>geometa::ISOAbstractObject$validate()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="wrapBaseElement"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-wrapBaseElement'><code>geometa::ISOAbstractObject$wrapBaseElement()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="GMLAbstractGML" data-id="addName"><a href='../../geometa/html/GMLAbstractGML.html#method-GMLAbstractGML-addName'><code>geometa::GMLAbstractGML$addName()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="GMLAbstractGML" data-id="delName"><a href='../../geometa/html/GMLAbstractGML.html#method-GMLAbstractGML-delName'><code>geometa::GMLAbstractGML$delName()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="GMLAbstractGML" data-id="setDescription"><a href='../../geometa/html/GMLAbstractGML.html#method-GMLAbstractGML-setDescription'><code>geometa::GMLAbstractGML$setDescription()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="GMLAbstractGML" data-id="setDescriptionReference"><a href='../../geometa/html/GMLAbstractGML.html#method-GMLAbstractGML-setDescriptionReference'><code>geometa::GMLAbstractGML$setDescriptionReference()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="GMLAbstractGML" data-id="setIdentifier"><a href='../../geometa/html/GMLAbstractGML.html#method-GMLAbstractGML-setIdentifier'><code>geometa::GMLAbstractGML$setIdentifier()</code></a></span></li> </ul> </details> }} \if{html}{\out{<hr>}} \if{html}{\out{<a id="method-GMLMultiSurface-new"></a>}} \if{latex}{\out{\hypertarget{method-GMLMultiSurface-new}{}}} \subsection{Method \code{new()}}{ Initializes object \subsection{Usage}{ \if{html}{\out{<div class="r">}}\preformatted{GMLMultiSurface$new(xml = NULL, sfg = NULL)}\if{html}{\out{</div>}} } \subsection{Arguments}{ \if{html}{\out{<div class="arguments">}} \describe{ \item{\code{xml}}{object of class \link{XMLInternalNode-class}} \item{\code{sfg}}{simple feature geometry resulting from \pkg{sf}} } \if{html}{\out{</div>}} } } \if{html}{\out{<hr>}} \if{html}{\out{<a id="method-GMLMultiSurface-addSurfaceMember"></a>}} \if{latex}{\out{\hypertarget{method-GMLMultiSurface-addSurfaceMember}{}}} \subsection{Method \code{addSurfaceMember()}}{ Adds surface member \subsection{Usage}{ \if{html}{\out{<div class="r">}}\preformatted{GMLMultiSurface$addSurfaceMember(surface)}\if{html}{\out{</div>}} } \subsection{Arguments}{ \if{html}{\out{<div class="arguments">}} \describe{ \item{\code{surface}}{surface object of class inheriting \link{GMLAbstractSurface}} } \if{html}{\out{</div>}} } \subsection{Returns}{ \code{TRUE} if added, \code{FALSE} otherwise } } \if{html}{\out{<hr>}} \if{html}{\out{<a id="method-GMLMultiSurface-delSurfaceMember"></a>}} \if{latex}{\out{\hypertarget{method-GMLMultiSurface-delSurfaceMember}{}}} \subsection{Method \code{delSurfaceMember()}}{ Deletes surface member \subsection{Usage}{ \if{html}{\out{<div class="r">}}\preformatted{GMLMultiSurface$delSurfaceMember(surface)}\if{html}{\out{</div>}} } \subsection{Arguments}{ \if{html}{\out{<div class="arguments">}} \describe{ \item{\code{surface}}{surface object of class inheriting \link{GMLAbstractSurface}} } \if{html}{\out{</div>}} } \subsection{Returns}{ \code{TRUE} if deleted, \code{FALSE} otherwise } } \if{html}{\out{<hr>}} \if{html}{\out{<a id="method-GMLMultiSurface-clone"></a>}} \if{latex}{\out{\hypertarget{method-GMLMultiSurface-clone}{}}} \subsection{Method \code{clone()}}{ The objects of this class are cloneable with this method. \subsection{Usage}{ \if{html}{\out{<div class="r">}}\preformatted{GMLMultiSurface$clone(deep = FALSE)}\if{html}{\out{</div>}} } \subsection{Arguments}{ \if{html}{\out{<div class="arguments">}} \describe{ \item{\code{deep}}{Whether to make a deep clone.} } \if{html}{\out{</div>}} } } }
/man/GMLMultiSurface.Rd
no_license
cran/geometa
R
false
true
12,531
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/GMLMultiSurface.R \docType{class} \name{GMLMultiSurface} \alias{GMLMultiSurface} \title{GMLMultiSurface} \format{ \code{\link{R6Class}} object. } \value{ Object of \code{\link{R6Class}} for modelling an GML multisurface } \description{ GMLMultiSurface GMLMultiSurface } \note{ Experimental } \references{ ISO 19136:2007 Geographic Information -- Geographic Markup Language. http://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=32554 OGC Geography Markup Language. http://www.opengeospatial.org/standards/gml } \author{ Emmanuel Blondel <emmanuel.blondel1@gmail.com> } \keyword{GML} \keyword{ISO} \keyword{MultiSurface} \section{Super classes}{ \code{\link[geometa:geometaLogger]{geometa::geometaLogger}} -> \code{\link[geometa:ISOAbstractObject]{geometa::ISOAbstractObject}} -> \code{\link[geometa:GMLAbstractObject]{geometa::GMLAbstractObject}} -> \code{\link[geometa:GMLAbstractGML]{geometa::GMLAbstractGML}} -> \code{\link[geometa:GMLAbstractGeometry]{geometa::GMLAbstractGeometry}} -> \code{\link[geometa:GMLAbstractGeometricAggregate]{geometa::GMLAbstractGeometricAggregate}} -> \code{GMLMultiSurface} } \section{Public fields}{ \if{html}{\out{<div class="r6-fields">}} \describe{ \item{\code{attrs}}{gml attributes} \item{\code{surfaceMember}}{surface members} } \if{html}{\out{</div>}} } \section{Methods}{ \subsection{Public methods}{ \itemize{ \item \href{#method-GMLMultiSurface-new}{\code{GMLMultiSurface$new()}} \item \href{#method-GMLMultiSurface-addSurfaceMember}{\code{GMLMultiSurface$addSurfaceMember()}} \item \href{#method-GMLMultiSurface-delSurfaceMember}{\code{GMLMultiSurface$delSurfaceMember()}} \item \href{#method-GMLMultiSurface-clone}{\code{GMLMultiSurface$clone()}} } } \if{html}{\out{ <details><summary>Inherited methods</summary> <ul> <li><span class="pkg-link" data-pkg="geometa" data-topic="geometaLogger" data-id="ERROR"><a href='../../geometa/html/geometaLogger.html#method-geometaLogger-ERROR'><code>geometa::geometaLogger$ERROR()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="geometaLogger" data-id="INFO"><a href='../../geometa/html/geometaLogger.html#method-geometaLogger-INFO'><code>geometa::geometaLogger$INFO()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="geometaLogger" data-id="WARN"><a href='../../geometa/html/geometaLogger.html#method-geometaLogger-WARN'><code>geometa::geometaLogger$WARN()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="addFieldAttrs"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-addFieldAttrs'><code>geometa::ISOAbstractObject$addFieldAttrs()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="addListElement"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-addListElement'><code>geometa::ISOAbstractObject$addListElement()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="contains"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-contains'><code>geometa::ISOAbstractObject$contains()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="createLocalisedProperty"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-createLocalisedProperty'><code>geometa::ISOAbstractObject$createLocalisedProperty()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="decode"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-decode'><code>geometa::ISOAbstractObject$decode()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="delListElement"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-delListElement'><code>geometa::ISOAbstractObject$delListElement()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="encode"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-encode'><code>geometa::ISOAbstractObject$encode()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="getClass"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-getClass'><code>geometa::ISOAbstractObject$getClass()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="getClassName"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-getClassName'><code>geometa::ISOAbstractObject$getClassName()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="getNamespaceDefinition"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-getNamespaceDefinition'><code>geometa::ISOAbstractObject$getNamespaceDefinition()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="isDocument"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-isDocument'><code>geometa::ISOAbstractObject$isDocument()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="isFieldInheritedFrom"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-isFieldInheritedFrom'><code>geometa::ISOAbstractObject$isFieldInheritedFrom()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="print"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-print'><code>geometa::ISOAbstractObject$print()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="save"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-save'><code>geometa::ISOAbstractObject$save()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="setAttr"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-setAttr'><code>geometa::ISOAbstractObject$setAttr()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="setCodeList"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-setCodeList'><code>geometa::ISOAbstractObject$setCodeList()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="setCodeListValue"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-setCodeListValue'><code>geometa::ISOAbstractObject$setCodeListValue()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="setCodeSpace"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-setCodeSpace'><code>geometa::ISOAbstractObject$setCodeSpace()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="setHref"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-setHref'><code>geometa::ISOAbstractObject$setHref()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="setId"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-setId'><code>geometa::ISOAbstractObject$setId()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="setIsNull"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-setIsNull'><code>geometa::ISOAbstractObject$setIsNull()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="setValue"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-setValue'><code>geometa::ISOAbstractObject$setValue()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="validate"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-validate'><code>geometa::ISOAbstractObject$validate()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="ISOAbstractObject" data-id="wrapBaseElement"><a href='../../geometa/html/ISOAbstractObject.html#method-ISOAbstractObject-wrapBaseElement'><code>geometa::ISOAbstractObject$wrapBaseElement()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="GMLAbstractGML" data-id="addName"><a href='../../geometa/html/GMLAbstractGML.html#method-GMLAbstractGML-addName'><code>geometa::GMLAbstractGML$addName()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="GMLAbstractGML" data-id="delName"><a href='../../geometa/html/GMLAbstractGML.html#method-GMLAbstractGML-delName'><code>geometa::GMLAbstractGML$delName()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="GMLAbstractGML" data-id="setDescription"><a href='../../geometa/html/GMLAbstractGML.html#method-GMLAbstractGML-setDescription'><code>geometa::GMLAbstractGML$setDescription()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="GMLAbstractGML" data-id="setDescriptionReference"><a href='../../geometa/html/GMLAbstractGML.html#method-GMLAbstractGML-setDescriptionReference'><code>geometa::GMLAbstractGML$setDescriptionReference()</code></a></span></li> <li><span class="pkg-link" data-pkg="geometa" data-topic="GMLAbstractGML" data-id="setIdentifier"><a href='../../geometa/html/GMLAbstractGML.html#method-GMLAbstractGML-setIdentifier'><code>geometa::GMLAbstractGML$setIdentifier()</code></a></span></li> </ul> </details> }} \if{html}{\out{<hr>}} \if{html}{\out{<a id="method-GMLMultiSurface-new"></a>}} \if{latex}{\out{\hypertarget{method-GMLMultiSurface-new}{}}} \subsection{Method \code{new()}}{ Initializes object \subsection{Usage}{ \if{html}{\out{<div class="r">}}\preformatted{GMLMultiSurface$new(xml = NULL, sfg = NULL)}\if{html}{\out{</div>}} } \subsection{Arguments}{ \if{html}{\out{<div class="arguments">}} \describe{ \item{\code{xml}}{object of class \link{XMLInternalNode-class}} \item{\code{sfg}}{simple feature geometry resulting from \pkg{sf}} } \if{html}{\out{</div>}} } } \if{html}{\out{<hr>}} \if{html}{\out{<a id="method-GMLMultiSurface-addSurfaceMember"></a>}} \if{latex}{\out{\hypertarget{method-GMLMultiSurface-addSurfaceMember}{}}} \subsection{Method \code{addSurfaceMember()}}{ Adds surface member \subsection{Usage}{ \if{html}{\out{<div class="r">}}\preformatted{GMLMultiSurface$addSurfaceMember(surface)}\if{html}{\out{</div>}} } \subsection{Arguments}{ \if{html}{\out{<div class="arguments">}} \describe{ \item{\code{surface}}{surface object of class inheriting \link{GMLAbstractSurface}} } \if{html}{\out{</div>}} } \subsection{Returns}{ \code{TRUE} if added, \code{FALSE} otherwise } } \if{html}{\out{<hr>}} \if{html}{\out{<a id="method-GMLMultiSurface-delSurfaceMember"></a>}} \if{latex}{\out{\hypertarget{method-GMLMultiSurface-delSurfaceMember}{}}} \subsection{Method \code{delSurfaceMember()}}{ Deletes surface member \subsection{Usage}{ \if{html}{\out{<div class="r">}}\preformatted{GMLMultiSurface$delSurfaceMember(surface)}\if{html}{\out{</div>}} } \subsection{Arguments}{ \if{html}{\out{<div class="arguments">}} \describe{ \item{\code{surface}}{surface object of class inheriting \link{GMLAbstractSurface}} } \if{html}{\out{</div>}} } \subsection{Returns}{ \code{TRUE} if deleted, \code{FALSE} otherwise } } \if{html}{\out{<hr>}} \if{html}{\out{<a id="method-GMLMultiSurface-clone"></a>}} \if{latex}{\out{\hypertarget{method-GMLMultiSurface-clone}{}}} \subsection{Method \code{clone()}}{ The objects of this class are cloneable with this method. \subsection{Usage}{ \if{html}{\out{<div class="r">}}\preformatted{GMLMultiSurface$clone(deep = FALSE)}\if{html}{\out{</div>}} } \subsection{Arguments}{ \if{html}{\out{<div class="arguments">}} \describe{ \item{\code{deep}}{Whether to make a deep clone.} } \if{html}{\out{</div>}} } } }
#Missing Values - Visualisation library(VIM) #Visualisation VIM::aggr(sleep, prop=F, numbers=T) #Total nos #NonD max NA values VIM::aggr(sleep, prop=T) # Proportion VIM::matrixplot(sleep) # rowno and missing values in red #The continuous variable is rescaled and represented by grayscale colors. Lighter colors indicate lower values and darker colors suggest larger values names(sleep) VIM::barMiss(sleep) VIM::histMiss(sleep[,3:8]) sleep$BodyWgt #Click in in the left margin to switch to the previous variable or in the right margin to switch to the next variable. #To regain use of the VIM GUI and the R console, click anywhere else in the graphics window. VIM::spineMiss(sleep[c('Gest','Dream')]) VIM::marginmatrix(sleep) VIM::scattmatrixMiss(sleep) VIM::marginplot(sleep[c('Gest','Dream')], pch=c(20), col=c("darkgray", "red", "blue")) # finding relationship between NA value (shadow = as.data.frame(abs(is.na(sleep)))) #Exploration x = as.data.frame(abs(is.na(sleep))) head(sleep, na=5) head(x, n=5) y = x[which(apply(x, 2, sum) > 0)] cor(y) #Dream - NonD 0.9 cor(sleep, y, use="pairwise.complete.obs") #ignore NA, # #Listwise Deletion options(digits=3) na.omit(sleep) cor(na.omit(sleep)) cor(sleep, use="complete.obs") fit = lm(Dream ~ Span + Gest, data= na.omit(sleep)) summary(fit) #imputations Packages - mice, Amelia, mi : mice, with, pool imp = mice::mice(sleep, seed=1234) imp ?mice # explore more
/23-functions/61c-missing2.R
no_license
DUanalytics/rAnalytics
R
false
false
1,430
r
#Missing Values - Visualisation library(VIM) #Visualisation VIM::aggr(sleep, prop=F, numbers=T) #Total nos #NonD max NA values VIM::aggr(sleep, prop=T) # Proportion VIM::matrixplot(sleep) # rowno and missing values in red #The continuous variable is rescaled and represented by grayscale colors. Lighter colors indicate lower values and darker colors suggest larger values names(sleep) VIM::barMiss(sleep) VIM::histMiss(sleep[,3:8]) sleep$BodyWgt #Click in in the left margin to switch to the previous variable or in the right margin to switch to the next variable. #To regain use of the VIM GUI and the R console, click anywhere else in the graphics window. VIM::spineMiss(sleep[c('Gest','Dream')]) VIM::marginmatrix(sleep) VIM::scattmatrixMiss(sleep) VIM::marginplot(sleep[c('Gest','Dream')], pch=c(20), col=c("darkgray", "red", "blue")) # finding relationship between NA value (shadow = as.data.frame(abs(is.na(sleep)))) #Exploration x = as.data.frame(abs(is.na(sleep))) head(sleep, na=5) head(x, n=5) y = x[which(apply(x, 2, sum) > 0)] cor(y) #Dream - NonD 0.9 cor(sleep, y, use="pairwise.complete.obs") #ignore NA, # #Listwise Deletion options(digits=3) na.omit(sleep) cor(na.omit(sleep)) cor(sleep, use="complete.obs") fit = lm(Dream ~ Span + Gest, data= na.omit(sleep)) summary(fit) #imputations Packages - mice, Amelia, mi : mice, with, pool imp = mice::mice(sleep, seed=1234) imp ?mice # explore more
#' Set the number of decimal places #' x = numeric #' k = integer set_decimal <- function(x, k, cut = 200 ){ if( !is.null(x) && length(x)> 0 ){ if( x[ 1 ]< cut ){ format(round(x, k), nsmall=k,big.mark=",") }else { format(round(x, 0), nsmall=0,big.mark=",") } } } #' General object viewer view_object <- function( obj ){ obj_attr <- attributes( obj ) n <- length( obj_attr$names ) return( obj[ obj_attr$names[1:n]] ) } #' Load R library. Install if not already installed use_package <- function(p, load_packages = TRUE) { if (!is.element(p, installed.packages()[,1])){ install.packages(p, dep = TRUE) } if(load_packages) { require(p, character.only = TRUE) } } #devtools::install_github('eamoakohene/beamaUtils') use_ea_github<- function(p , load_packages = TRUE) { if (!is.element(p, installed.packages()[,1])){ devtools::install_github(sprintf('eamoakohene/%s',p), upgrade = "never", force = "true") } if( load_packages) { require(p, character.only = TRUE) } } install_packages <- function(load_packages = FALSE){ if (!is.element("devtools", installed.packages()[, 1])) { install.packages("devtools", dep = TRUE) require("devtools") } use_package("installr", load_packages = load_packages) use_package("digest", load_packages = load_packages) use_package("quantmod", load_packages = load_packages) use_package("gridExtra", load_packages = load_packages) use_package("reshape2", load_packages = load_packages) use_package('tidyr', load_packages = load_packages) use_package("ggplot2", load_packages = load_packages) use_package("MASS", load_packages = load_packages) use_package("tseries", load_packages = load_packages) use_package("x12", load_packages = load_packages) use_package("R.oo", load_packages = load_packages) use_package("forecast", load_packages = load_packages) use_package("plyr", load_packages = load_packages) use_package("scales", load_packages = load_packages) use_package("RODBC", load_packages = load_packages) use_package("xtable", load_packages = load_packages) use_package("gdata", load_packages = load_packages) use_package("RJSONIO", load_packages = load_packages) use_package("WDI", load_packages = load_packages) use_package("lubridate", load_packages = load_packages) use_package("grid", load_packages = load_packages) use_package("Quandl", load_packages = load_packages) use_package("dplyr", load_packages = load_packages) use_package("plotly", load_packages = load_packages) use_package("sqldf", load_packages = load_packages) use_package("PerformanceAnalytics", load_packages = load_packages) use_package("ggthemes", load_packages = load_packages) use_package("RCurl", load_packages = load_packages) use_package("XML", load_packages = load_packages) use_package("codetools", load_packages = load_packages) use_package("pbapply", load_packages = load_packages) use_package("cranlogs", load_packages = load_packages) use_package("NMF", load_packages = load_packages) use_package("doParallel", load_packages = load_packages) use_package("foreach", load_packages = load_packages) use_package("googleVis", load_packages = load_packages) use_package("gridBase", load_packages = load_packages) use_package("irlba", load_packages = load_packages) use_package("iterators", load_packages = load_packages) use_package("pkgmaker", load_packages = load_packages) use_package("registry", load_packages = load_packages) use_package("rngtools", load_packages = load_packages) use_package("seasonal", load_packages = load_packages) use_package("RSQLite", load_packages = load_packages) use_package("zeallot", load_packages = load_packages) use_package("rlang", load_packages = load_packages) use_package("selectr", load_packages = load_packages) use_package("lattice", load_packages = load_packages) use_package("Rcpp", load_packages = load_packages) use_package("inline", load_packages = load_packages) use_package("animation", load_packages = load_packages) #use_package("rstan") use_package("microbenchmark", load_packages = load_packages) use_package("XLConnect", load_packages = load_packages) use_package("mosaic", load_packages = load_packages) use_package("qdap", load_packages = load_packages) use_package("pipeR", load_packages = load_packages) use_package("colorspace", load_packages = load_packages) use_package("MAPA", load_packages = load_packages) use_package('networkD3', load_packages = load_packages) use_package('dygraphs', load_packages = load_packages) #use_package("bigrquery") use_package("rlist", load_packages = load_packages) use_package("stsm", load_packages = load_packages) use_package("knitr", load_packages = load_packages) use_package("DT", load_packages = load_packages) use_package("shiny", load_packages = load_packages) use_package("shinyjs", load_packages = load_packages) use_package("shinyBS", load_packages = load_packages) use_package("shinydashboard", load_packages = load_packages) use_package("bsplus", load_packages = load_packages) use_package("ggpol", load_packages = load_packages) use_package("fredr", load_packages = load_packages) use_package("ggrepel", load_packages = load_packages) use_package("geosphere", load_packages = load_packages) use_package("extrafont", load_packages = load_packages) use_package("curl", load_packages = load_packages) use_package("ggforce", load_packages = load_packages) use_package("sjmisc", load_packages = load_packages) use_package("RJDemetra", load_packages = load_packages) use_package("showtext", load_packages = load_packages) use_package("gganimate", load_packages = load_packages) use_package("gifski", load_packages = load_packages) use_package("packcircles", load_packages = load_packages) use_package("likert", load_packages = load_packages) use_package("RODBCext", load_packages = load_packages) use_package("sparkline", load_packages = load_packages) use_package("rsconnect", load_packages = load_packages) #use_package("", load_packages = load_packages) ## EA github repositories use_ea_github("beamaColours", load_packages = load_packages) use_ea_github("storedQry", load_packages = load_packages) use_ea_github("beamaSankey", load_packages = load_packages) use_ea_github("beamafx", load_packages = load_packages) use_ea_github("onsR2", load_packages = load_packages) #use_ea_github("beamaTrends", load_packages = load_packages) } plot_latest_packages <- function( since="2019-01-01", cran_url = "http://dirk.eddelbuettel.com/cranberries/", top = 25 ){ require(ggplot2) page <- xml2::read_html(cran_url) titles <- rvest::html_text(rvest::html_nodes(page,"b")) new_packages <- unique( gsub( "^New package (.*) with initial .*", "\\1", titles[grepl("^New package", titles)] ) ) logs <- pbapply::pblapply( new_packages, function(x) { down <- cranlogs::cran_downloads(x, from = since)$count if(sum(down) > 0) { public <- down[which(down > 0)[1]:length(down)] } else { public <- 0 } return( data.frame( package = x, downloads = sum(down), avg = mean(public) ) ) } ) logs <- do.call( rbind, logs) logs <- dplyr::arrange(logs,desc(downloads)) logs$package <- factor(logs$package,levels = logs$package) gg_data <- logs[1:top,] p <- ggplot(gg_data,ggplot2::aes(x=package, y=downloads, fill=package)) p <- p + geom_bar( stat='identity' ) p <- p + coord_flip() p <- p + theme(legend.position = "none") p <- p + labs(y='Downloads') print(p) return(gg_data) } split_str <- function( s="CHAY,CHAW,D7BT"){ abc <- base::gsub(",","','",s) abc <- base::paste0("('",abc,"')") return(abc) } split_int <- function( s="CHAY,CHAW,D7BT"){ #abc <- base::gsub(",","','",s) abc <- base::paste0("",s,")") return(abc) } to_clipboard <- function( x, row.names=FALSE, col.names=TRUE, ...) { write.table( x,"clipboard", sep="\t", row.names=row.names, col.names=col.names, ...) } #' Timeseries to Dataframe #' Convert timeseries object \code{my_ts} to a data frame with columns \code{yr, mth, value, date} #' ts_to_df <- function( my_ts, na.rm = FALSE){ my_freq <- frequency( my_ts ) my_date <- my_yr <- my_mon<- my_df <- NULL if( my_freq %in% c(1,12) ){ my_df <- data.frame( date=zoo::as.Date(zoo::as.yearmon(time(my_ts))), value=as.matrix(my_ts )) my_df$mth <- lubridate::month(my_df$date) my_df$yr <- lubridate::year( my_df$date) }else if( my_freq == 4){ my_df <- data.frame( date=zoo::as.Date(zoo::as.yearqtr(time(my_ts))), value=as.matrix(my_ts )) my_df$mth <- lubridate::month(my_df$date) + 2 my_df$yr <- lubridate::year(my_df$date) my_df$date <- as.Date( paste(my_df$yr, my_df$mth, 1, sep='-')) } if( na.rm ){ return( dplyr::filter( my_df , is.na( value ) == FALSE) ) }else{ return(my_df) } } ts_dates <- function(x){ if(! is.ts( x )){ return( NULL )} if(frequency(x)==12){ return( seq( as.Date(paste(c(start(x),28), collapse = "/")), by = "month", length.out = length(x) ) ) }else if(frequency(x)==4){ return( seq.Date( as.Date(paste(start(x)[1],start(x)[2]*3,28,sep="/")), length.out = length(x), by="3 months" ) ) }else if(frequency(x)==1){ return( seq( as.Date(paste(c(start(x),1), collapse = "/")), by = "year", length.out = length(x) ) ) }else{ stop("Frequency of time series UNKNOWN") } } df_to_ts <- function(my_df, frq = 12, my_start = NULL){ if(!is.data.frame(my_df)){ cat("Please supply dataframe\n") return( NULL) } if(frq %in% c(4,12)){ cat("Please ensure that frequency is 4 or 12\n") return(NULL) } ts_start <- my_start if(is.null(my_start)){ ts_start <- c(df$yr[1], df$mth[1]) } if(is.null(my_start)){ cat("Please supply start\n") return(NULL) } ts_freq <- frq } #' Data days #' Convert a date to days using assuming \code{d360} days in a year #' Returns number of days #' ddays <- function(yr, mth, dy = 0 , d360 = 31 ){ return( yr * d360 * 12 + mth * d360 + dy ) } #' Difference between dates #' days_diff <- function(d1="1969-09-28", d2=Sys.Date() ){ y1 <- lubridate::year(d1) m1 <- lubridate::month(d1) d1 <- lubridate::day(d1) y2 <- lubridate::year(d2) m2 <- lubridate::month(d2) d2 <- lubridate::day(d2) return( ddays(y2,m2,d2) - ddays(y1,m1,d1) ) } days_to <- function(d="2050-01-01"){ return( days_diff(Sys.Date(), d) ) } days_since <- function(d="2050-01-01"){ return( days_diff( d, Sys.Date()) ) } run_sql <- function(qry, db='R:/shiny/beama/bmonitor/bss.sqlite'){ conn <- DBI::dbConnect( RSQLite::SQLite(), dbname= db ) results <- RSQLite::dbGetQuery(conn, qry) DBI::dbDisconnect(conn) return(results) } run_sql_db <- function(sql, db, drv = "R:"){ db_name <- dbp(db,drv) if(nchar(db_name) > 5){ return( run_sql(sql, db_name) ) } return (NULL) } get_fxn <- function(name, db='R:/shiny/beama/bmonitor/bss.sqlite', view = FALSE){ my_name <- tolower(name) my_sql <- sprintf("select fxn from stored_fxns where lower(name) ='%s'", my_name) my_data <- run_sql(qry = my_sql, db = db ) my_fxn <- NULL if( nrow(my_data) > 0){ my_fxn <- my_data$fxn if(!view){ return( eval(parse(text = my_fxn)) ) }else{ cat( my_fxn,"\n") } } return(NULL) } scrap_fxn <- function(){ return( get_fxn("scrap_web_data") ) } save_plot <- function( file="glance.png", width=633, height=219, path="W:/reports/latex/images/", ppi=72 ){ ggplot2::ggsave( file = paste0(path,file), height = height / ppi, width = width / ppi, dpi = ppi, units = "in" ) } df_to_list <- function(df,col_name, col_value){ e <- base::new.env(hash = TRUE) for (i in 1:nrow(df) ) { base::assign( df[i, col_name], df[i, col_value], e) } return( as.list(e)) } db_paths <- function(){ return( data.frame( db=c( 'bistats', 'beamafx', 'sankeys', 'ibeama_indices', 'ibtrends', 'bnetworks', 'datastore', 'fame', 'onsR2', 'orgalime', 'bts', 'storedfxns', 'bmm', 'bts_emails', 'cepe', 'prodcom', 'badd', 'centre_point', 'uktrade', 'uktrade_info', 'covid19', 'surveys', 'bindx', 'bmonitor', 'badd' ), path=c( '/packages/bistats/inst/extdata/bistats.sqlite', '/packages/beamafx/inst/extdata/beamafx.sqlite', '/packages/beamaSankey/inst/extdata/sankeys.sqlite', '/packages/bindx/R/beama_indices.sqlite', '/packages/bindx/R/btrends.sqlite', '/packages/bnetworks/inst/networks/bnetworks1/bnetworks.sqlite', '/packages/datastore/R/datastore.sqlite', '/packages/fame27/inst/extdata/fame.sqlite', '/packages/onsR2/inst/extdata/onsR2.sqlite', '/packages/orgalime/inst/extdata/orgalime.sqlite', '/packages/surveyapp/bts.sqlite', '/packages/storedFxns/storedfxns.sqlite', '/shiny/beama/bmonitor/bss.sqlite', '/data/lite/bts_emails.sqlite', '/shiny/cepe/cepe.sqlite', '/data/lite/prodcom.sqlite', '/data/badd.db', '/shiny/centrePoint/centre_point.sqlite', '/data/lite/uktrade.sqlite', '/data/lite/uktrade_info.sqlite', '/data/lite/covid19', '/packages/surveys/surveys.sqlite', '/packages/bindx/R/beama_indices.sqlite', '/shiny/beama/bmonitor/bss.sqlite', '/data/badd.db' ), stringsAsFactors = FALSE ) ) } dbp <- function(db, drv = 'R:' ){ ldb <- db_paths() df <- sqldf::sqldf( sprintf("select path from ldb where db ='%s';", db ) ) if(nrow(df)>0){ return( paste0(drv,df$path[1]) ) } NULL } view_tbls <- function(db, drv = 'R:'){ # db='bindx' sql <- "SELECT name FROM sqlite_master WHERE type ='table' AND name NOT LIKE 'sqlite_%';" return( run_sql( sql, db=dbp(db, drv=drv) ) ) } df_trends <- get_data <- function(codes, db='bistats', fmt = 'wide', y1 = 2010, tbl = 'trends_data', drv = 'R:', dp = 1){ # db ='bindx' ldb <- dbp(db, drv) if(!is.null(ldb)){ mcode <- split_str( tolower(codes)) sql <- sprintf( "select yr,mth,dy, data_code,data_value from %s where yr>=%s and lower(data_code) in %s order by data_code, yr, mth, dy", tbl,y1,mcode ) df <- run_sql( sql, db=ldb ) if(nrow(df)>0){ if(tolower(fmt) =='wide'){ return( tidyr::spread( df, data_code, data_value) ) }else if(tolower(fmt) =='ts'){ ts_start <- c(df$yr[1], df$mth[1]) ts_freq <- run_sql( sprintf("select data_frq from trends_meta where lower(data_code) in %s limit 1", mcode), db = ldb )$data_frq return( stats::ts( round(df$data_value,1), start = ts_start, frequency = ts_freq)) }else{ return( df) } } return (NULL) }else{ return (NULL) } } search_code <- function(x, db = 'bistats', drv = 'R:'){ ldb <- dbp( db, drv) sql <- sprintf("select data_code, data_frq from trends_meta where data_code like '%%%s%%'", x) return( run_sql(sql, db = ldb) ) } bif <- function(..., env=parent.frame()) { fx <- function(dots) { if (length(dots) == 1) { return(dots[[1]]) } else { tmp <- dots[[1]] return(call("ifelse", tmp[[3]], tmp[[2]], fx(dots[-1]))) } } isa <- function(x) { if (length(x) > 1) { return (identical(x[[1]], quote(`<-`))) }else{ return(FALSE) } } isv <- function(dots) { check <- sapply(dots, isa) if (all(head(check, -1)) && !tail(check, 1)) { return("HDF") } else if (all(check)) { return("NDF") } else { stop("invalid bif arguments", call. = FALSE) } } dots <- eval(substitute(alist(...))) status <- isv(dots) if (status == "NDF") { dots <- c(dots, expression(NA)) } eval(fx(dots), envir = env) } test_url<- web_url <- function(url = "https://www.beama.org/?pg=404"){ require(magrittr) require(curl) curl_fetch_memory(url = url , handle = new_handle())%$% content %>% rawToChar } web_tbls <- function(url="https://www.bbc.co.uk/sport/olympics/57836709"){ x <- rvest::read_html(url) tbls <- x|> rvest::html_table(fill=T) if( length(tbls) == 0){ return(NULL) } return(tbls) } #### DAYS IN MONTH dmth <- function(mth,yr) { dt <- as.Date(sprintf("%s-%02d-01", yr, mth)) days <- 28:31 return( rev( days[ which( !is.na( as.Date(paste0( substr(dt, 1, 8), days), '%Y-%m-%d') ) ) ] )[1] ) }
/R/beama_utils.R
no_license
eamoakohene/beamaUtils
R
false
false
17,163
r
#' Set the number of decimal places #' x = numeric #' k = integer set_decimal <- function(x, k, cut = 200 ){ if( !is.null(x) && length(x)> 0 ){ if( x[ 1 ]< cut ){ format(round(x, k), nsmall=k,big.mark=",") }else { format(round(x, 0), nsmall=0,big.mark=",") } } } #' General object viewer view_object <- function( obj ){ obj_attr <- attributes( obj ) n <- length( obj_attr$names ) return( obj[ obj_attr$names[1:n]] ) } #' Load R library. Install if not already installed use_package <- function(p, load_packages = TRUE) { if (!is.element(p, installed.packages()[,1])){ install.packages(p, dep = TRUE) } if(load_packages) { require(p, character.only = TRUE) } } #devtools::install_github('eamoakohene/beamaUtils') use_ea_github<- function(p , load_packages = TRUE) { if (!is.element(p, installed.packages()[,1])){ devtools::install_github(sprintf('eamoakohene/%s',p), upgrade = "never", force = "true") } if( load_packages) { require(p, character.only = TRUE) } } install_packages <- function(load_packages = FALSE){ if (!is.element("devtools", installed.packages()[, 1])) { install.packages("devtools", dep = TRUE) require("devtools") } use_package("installr", load_packages = load_packages) use_package("digest", load_packages = load_packages) use_package("quantmod", load_packages = load_packages) use_package("gridExtra", load_packages = load_packages) use_package("reshape2", load_packages = load_packages) use_package('tidyr', load_packages = load_packages) use_package("ggplot2", load_packages = load_packages) use_package("MASS", load_packages = load_packages) use_package("tseries", load_packages = load_packages) use_package("x12", load_packages = load_packages) use_package("R.oo", load_packages = load_packages) use_package("forecast", load_packages = load_packages) use_package("plyr", load_packages = load_packages) use_package("scales", load_packages = load_packages) use_package("RODBC", load_packages = load_packages) use_package("xtable", load_packages = load_packages) use_package("gdata", load_packages = load_packages) use_package("RJSONIO", load_packages = load_packages) use_package("WDI", load_packages = load_packages) use_package("lubridate", load_packages = load_packages) use_package("grid", load_packages = load_packages) use_package("Quandl", load_packages = load_packages) use_package("dplyr", load_packages = load_packages) use_package("plotly", load_packages = load_packages) use_package("sqldf", load_packages = load_packages) use_package("PerformanceAnalytics", load_packages = load_packages) use_package("ggthemes", load_packages = load_packages) use_package("RCurl", load_packages = load_packages) use_package("XML", load_packages = load_packages) use_package("codetools", load_packages = load_packages) use_package("pbapply", load_packages = load_packages) use_package("cranlogs", load_packages = load_packages) use_package("NMF", load_packages = load_packages) use_package("doParallel", load_packages = load_packages) use_package("foreach", load_packages = load_packages) use_package("googleVis", load_packages = load_packages) use_package("gridBase", load_packages = load_packages) use_package("irlba", load_packages = load_packages) use_package("iterators", load_packages = load_packages) use_package("pkgmaker", load_packages = load_packages) use_package("registry", load_packages = load_packages) use_package("rngtools", load_packages = load_packages) use_package("seasonal", load_packages = load_packages) use_package("RSQLite", load_packages = load_packages) use_package("zeallot", load_packages = load_packages) use_package("rlang", load_packages = load_packages) use_package("selectr", load_packages = load_packages) use_package("lattice", load_packages = load_packages) use_package("Rcpp", load_packages = load_packages) use_package("inline", load_packages = load_packages) use_package("animation", load_packages = load_packages) #use_package("rstan") use_package("microbenchmark", load_packages = load_packages) use_package("XLConnect", load_packages = load_packages) use_package("mosaic", load_packages = load_packages) use_package("qdap", load_packages = load_packages) use_package("pipeR", load_packages = load_packages) use_package("colorspace", load_packages = load_packages) use_package("MAPA", load_packages = load_packages) use_package('networkD3', load_packages = load_packages) use_package('dygraphs', load_packages = load_packages) #use_package("bigrquery") use_package("rlist", load_packages = load_packages) use_package("stsm", load_packages = load_packages) use_package("knitr", load_packages = load_packages) use_package("DT", load_packages = load_packages) use_package("shiny", load_packages = load_packages) use_package("shinyjs", load_packages = load_packages) use_package("shinyBS", load_packages = load_packages) use_package("shinydashboard", load_packages = load_packages) use_package("bsplus", load_packages = load_packages) use_package("ggpol", load_packages = load_packages) use_package("fredr", load_packages = load_packages) use_package("ggrepel", load_packages = load_packages) use_package("geosphere", load_packages = load_packages) use_package("extrafont", load_packages = load_packages) use_package("curl", load_packages = load_packages) use_package("ggforce", load_packages = load_packages) use_package("sjmisc", load_packages = load_packages) use_package("RJDemetra", load_packages = load_packages) use_package("showtext", load_packages = load_packages) use_package("gganimate", load_packages = load_packages) use_package("gifski", load_packages = load_packages) use_package("packcircles", load_packages = load_packages) use_package("likert", load_packages = load_packages) use_package("RODBCext", load_packages = load_packages) use_package("sparkline", load_packages = load_packages) use_package("rsconnect", load_packages = load_packages) #use_package("", load_packages = load_packages) ## EA github repositories use_ea_github("beamaColours", load_packages = load_packages) use_ea_github("storedQry", load_packages = load_packages) use_ea_github("beamaSankey", load_packages = load_packages) use_ea_github("beamafx", load_packages = load_packages) use_ea_github("onsR2", load_packages = load_packages) #use_ea_github("beamaTrends", load_packages = load_packages) } plot_latest_packages <- function( since="2019-01-01", cran_url = "http://dirk.eddelbuettel.com/cranberries/", top = 25 ){ require(ggplot2) page <- xml2::read_html(cran_url) titles <- rvest::html_text(rvest::html_nodes(page,"b")) new_packages <- unique( gsub( "^New package (.*) with initial .*", "\\1", titles[grepl("^New package", titles)] ) ) logs <- pbapply::pblapply( new_packages, function(x) { down <- cranlogs::cran_downloads(x, from = since)$count if(sum(down) > 0) { public <- down[which(down > 0)[1]:length(down)] } else { public <- 0 } return( data.frame( package = x, downloads = sum(down), avg = mean(public) ) ) } ) logs <- do.call( rbind, logs) logs <- dplyr::arrange(logs,desc(downloads)) logs$package <- factor(logs$package,levels = logs$package) gg_data <- logs[1:top,] p <- ggplot(gg_data,ggplot2::aes(x=package, y=downloads, fill=package)) p <- p + geom_bar( stat='identity' ) p <- p + coord_flip() p <- p + theme(legend.position = "none") p <- p + labs(y='Downloads') print(p) return(gg_data) } split_str <- function( s="CHAY,CHAW,D7BT"){ abc <- base::gsub(",","','",s) abc <- base::paste0("('",abc,"')") return(abc) } split_int <- function( s="CHAY,CHAW,D7BT"){ #abc <- base::gsub(",","','",s) abc <- base::paste0("",s,")") return(abc) } to_clipboard <- function( x, row.names=FALSE, col.names=TRUE, ...) { write.table( x,"clipboard", sep="\t", row.names=row.names, col.names=col.names, ...) } #' Timeseries to Dataframe #' Convert timeseries object \code{my_ts} to a data frame with columns \code{yr, mth, value, date} #' ts_to_df <- function( my_ts, na.rm = FALSE){ my_freq <- frequency( my_ts ) my_date <- my_yr <- my_mon<- my_df <- NULL if( my_freq %in% c(1,12) ){ my_df <- data.frame( date=zoo::as.Date(zoo::as.yearmon(time(my_ts))), value=as.matrix(my_ts )) my_df$mth <- lubridate::month(my_df$date) my_df$yr <- lubridate::year( my_df$date) }else if( my_freq == 4){ my_df <- data.frame( date=zoo::as.Date(zoo::as.yearqtr(time(my_ts))), value=as.matrix(my_ts )) my_df$mth <- lubridate::month(my_df$date) + 2 my_df$yr <- lubridate::year(my_df$date) my_df$date <- as.Date( paste(my_df$yr, my_df$mth, 1, sep='-')) } if( na.rm ){ return( dplyr::filter( my_df , is.na( value ) == FALSE) ) }else{ return(my_df) } } ts_dates <- function(x){ if(! is.ts( x )){ return( NULL )} if(frequency(x)==12){ return( seq( as.Date(paste(c(start(x),28), collapse = "/")), by = "month", length.out = length(x) ) ) }else if(frequency(x)==4){ return( seq.Date( as.Date(paste(start(x)[1],start(x)[2]*3,28,sep="/")), length.out = length(x), by="3 months" ) ) }else if(frequency(x)==1){ return( seq( as.Date(paste(c(start(x),1), collapse = "/")), by = "year", length.out = length(x) ) ) }else{ stop("Frequency of time series UNKNOWN") } } df_to_ts <- function(my_df, frq = 12, my_start = NULL){ if(!is.data.frame(my_df)){ cat("Please supply dataframe\n") return( NULL) } if(frq %in% c(4,12)){ cat("Please ensure that frequency is 4 or 12\n") return(NULL) } ts_start <- my_start if(is.null(my_start)){ ts_start <- c(df$yr[1], df$mth[1]) } if(is.null(my_start)){ cat("Please supply start\n") return(NULL) } ts_freq <- frq } #' Data days #' Convert a date to days using assuming \code{d360} days in a year #' Returns number of days #' ddays <- function(yr, mth, dy = 0 , d360 = 31 ){ return( yr * d360 * 12 + mth * d360 + dy ) } #' Difference between dates #' days_diff <- function(d1="1969-09-28", d2=Sys.Date() ){ y1 <- lubridate::year(d1) m1 <- lubridate::month(d1) d1 <- lubridate::day(d1) y2 <- lubridate::year(d2) m2 <- lubridate::month(d2) d2 <- lubridate::day(d2) return( ddays(y2,m2,d2) - ddays(y1,m1,d1) ) } days_to <- function(d="2050-01-01"){ return( days_diff(Sys.Date(), d) ) } days_since <- function(d="2050-01-01"){ return( days_diff( d, Sys.Date()) ) } run_sql <- function(qry, db='R:/shiny/beama/bmonitor/bss.sqlite'){ conn <- DBI::dbConnect( RSQLite::SQLite(), dbname= db ) results <- RSQLite::dbGetQuery(conn, qry) DBI::dbDisconnect(conn) return(results) } run_sql_db <- function(sql, db, drv = "R:"){ db_name <- dbp(db,drv) if(nchar(db_name) > 5){ return( run_sql(sql, db_name) ) } return (NULL) } get_fxn <- function(name, db='R:/shiny/beama/bmonitor/bss.sqlite', view = FALSE){ my_name <- tolower(name) my_sql <- sprintf("select fxn from stored_fxns where lower(name) ='%s'", my_name) my_data <- run_sql(qry = my_sql, db = db ) my_fxn <- NULL if( nrow(my_data) > 0){ my_fxn <- my_data$fxn if(!view){ return( eval(parse(text = my_fxn)) ) }else{ cat( my_fxn,"\n") } } return(NULL) } scrap_fxn <- function(){ return( get_fxn("scrap_web_data") ) } save_plot <- function( file="glance.png", width=633, height=219, path="W:/reports/latex/images/", ppi=72 ){ ggplot2::ggsave( file = paste0(path,file), height = height / ppi, width = width / ppi, dpi = ppi, units = "in" ) } df_to_list <- function(df,col_name, col_value){ e <- base::new.env(hash = TRUE) for (i in 1:nrow(df) ) { base::assign( df[i, col_name], df[i, col_value], e) } return( as.list(e)) } db_paths <- function(){ return( data.frame( db=c( 'bistats', 'beamafx', 'sankeys', 'ibeama_indices', 'ibtrends', 'bnetworks', 'datastore', 'fame', 'onsR2', 'orgalime', 'bts', 'storedfxns', 'bmm', 'bts_emails', 'cepe', 'prodcom', 'badd', 'centre_point', 'uktrade', 'uktrade_info', 'covid19', 'surveys', 'bindx', 'bmonitor', 'badd' ), path=c( '/packages/bistats/inst/extdata/bistats.sqlite', '/packages/beamafx/inst/extdata/beamafx.sqlite', '/packages/beamaSankey/inst/extdata/sankeys.sqlite', '/packages/bindx/R/beama_indices.sqlite', '/packages/bindx/R/btrends.sqlite', '/packages/bnetworks/inst/networks/bnetworks1/bnetworks.sqlite', '/packages/datastore/R/datastore.sqlite', '/packages/fame27/inst/extdata/fame.sqlite', '/packages/onsR2/inst/extdata/onsR2.sqlite', '/packages/orgalime/inst/extdata/orgalime.sqlite', '/packages/surveyapp/bts.sqlite', '/packages/storedFxns/storedfxns.sqlite', '/shiny/beama/bmonitor/bss.sqlite', '/data/lite/bts_emails.sqlite', '/shiny/cepe/cepe.sqlite', '/data/lite/prodcom.sqlite', '/data/badd.db', '/shiny/centrePoint/centre_point.sqlite', '/data/lite/uktrade.sqlite', '/data/lite/uktrade_info.sqlite', '/data/lite/covid19', '/packages/surveys/surveys.sqlite', '/packages/bindx/R/beama_indices.sqlite', '/shiny/beama/bmonitor/bss.sqlite', '/data/badd.db' ), stringsAsFactors = FALSE ) ) } dbp <- function(db, drv = 'R:' ){ ldb <- db_paths() df <- sqldf::sqldf( sprintf("select path from ldb where db ='%s';", db ) ) if(nrow(df)>0){ return( paste0(drv,df$path[1]) ) } NULL } view_tbls <- function(db, drv = 'R:'){ # db='bindx' sql <- "SELECT name FROM sqlite_master WHERE type ='table' AND name NOT LIKE 'sqlite_%';" return( run_sql( sql, db=dbp(db, drv=drv) ) ) } df_trends <- get_data <- function(codes, db='bistats', fmt = 'wide', y1 = 2010, tbl = 'trends_data', drv = 'R:', dp = 1){ # db ='bindx' ldb <- dbp(db, drv) if(!is.null(ldb)){ mcode <- split_str( tolower(codes)) sql <- sprintf( "select yr,mth,dy, data_code,data_value from %s where yr>=%s and lower(data_code) in %s order by data_code, yr, mth, dy", tbl,y1,mcode ) df <- run_sql( sql, db=ldb ) if(nrow(df)>0){ if(tolower(fmt) =='wide'){ return( tidyr::spread( df, data_code, data_value) ) }else if(tolower(fmt) =='ts'){ ts_start <- c(df$yr[1], df$mth[1]) ts_freq <- run_sql( sprintf("select data_frq from trends_meta where lower(data_code) in %s limit 1", mcode), db = ldb )$data_frq return( stats::ts( round(df$data_value,1), start = ts_start, frequency = ts_freq)) }else{ return( df) } } return (NULL) }else{ return (NULL) } } search_code <- function(x, db = 'bistats', drv = 'R:'){ ldb <- dbp( db, drv) sql <- sprintf("select data_code, data_frq from trends_meta where data_code like '%%%s%%'", x) return( run_sql(sql, db = ldb) ) } bif <- function(..., env=parent.frame()) { fx <- function(dots) { if (length(dots) == 1) { return(dots[[1]]) } else { tmp <- dots[[1]] return(call("ifelse", tmp[[3]], tmp[[2]], fx(dots[-1]))) } } isa <- function(x) { if (length(x) > 1) { return (identical(x[[1]], quote(`<-`))) }else{ return(FALSE) } } isv <- function(dots) { check <- sapply(dots, isa) if (all(head(check, -1)) && !tail(check, 1)) { return("HDF") } else if (all(check)) { return("NDF") } else { stop("invalid bif arguments", call. = FALSE) } } dots <- eval(substitute(alist(...))) status <- isv(dots) if (status == "NDF") { dots <- c(dots, expression(NA)) } eval(fx(dots), envir = env) } test_url<- web_url <- function(url = "https://www.beama.org/?pg=404"){ require(magrittr) require(curl) curl_fetch_memory(url = url , handle = new_handle())%$% content %>% rawToChar } web_tbls <- function(url="https://www.bbc.co.uk/sport/olympics/57836709"){ x <- rvest::read_html(url) tbls <- x|> rvest::html_table(fill=T) if( length(tbls) == 0){ return(NULL) } return(tbls) } #### DAYS IN MONTH dmth <- function(mth,yr) { dt <- as.Date(sprintf("%s-%02d-01", yr, mth)) days <- 28:31 return( rev( days[ which( !is.na( as.Date(paste0( substr(dt, 1, 8), days), '%Y-%m-%d') ) ) ] )[1] ) }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/lexical_classification.R \name{print.cumulative_lexical_classification} \alias{print.cumulative_lexical_classification} \title{Prints a cumulative_lexical_classification Object} \usage{ \method{print}{cumulative_lexical_classification}(x, ...) } \arguments{ \item{x}{The cumulative_lexical_classification object.} \item{\ldots}{ignored} } \description{ Prints a cumulative_lexical_classification object. }
/man/print.cumulative_lexical_classification.Rd
no_license
cran/qdap
R
false
true
486
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/lexical_classification.R \name{print.cumulative_lexical_classification} \alias{print.cumulative_lexical_classification} \title{Prints a cumulative_lexical_classification Object} \usage{ \method{print}{cumulative_lexical_classification}(x, ...) } \arguments{ \item{x}{The cumulative_lexical_classification object.} \item{\ldots}{ignored} } \description{ Prints a cumulative_lexical_classification object. }
#' Implements simple linear regression by hand #' #' @param dat A data frame #' @param response The name of a response variable in the data frame (unquoted) #' @param explanatory The name of the explanatory variable in the data frame (unquoted) #' #' @return A data frame of coefficients #' #' @import dplyr #' #' @export simple_linear_regression <- function(dat, response, explanatory){ x <- dat %>% pull({{explanatory}}) y <- dat %>% pull({{response}}) explan_name <- data %>% select({{explanatory}}) %>% names() x_bar <- mean(x) y_bar <- mean(y) ### Edit code after here sd_x <- 1 sd_y <- 1 beta_0 <- 1 beta_1 <- 1 ### Stop editing results <- tibble::tibble( Intercept = beta_0, Slope = beta_1 ) names(results)[2] <- explan_name return(results) } #' Implements linear regression with many predictors by hand #' #' This function computes coefficients for multiple regression by hand. #' All columns of the provided data frame are used as predictors, except the #' one specified as a response. #' #' No interaction terms are included. #' #' #' @param dat A data frame #' @param response The name of a response variable in the data frame (unquoted) #' #' @return A data frame of coefficients #' #' @import dplyr #' #'@export multiple_linear_regression <- function(dat, response) { results <- 0 ### This should be a data frame, with columns named ### "Intercept" and the same variable names as dat. return(results) }
/R/linear_regression.R
permissive
shanealman/regress431
R
false
false
1,500
r
#' Implements simple linear regression by hand #' #' @param dat A data frame #' @param response The name of a response variable in the data frame (unquoted) #' @param explanatory The name of the explanatory variable in the data frame (unquoted) #' #' @return A data frame of coefficients #' #' @import dplyr #' #' @export simple_linear_regression <- function(dat, response, explanatory){ x <- dat %>% pull({{explanatory}}) y <- dat %>% pull({{response}}) explan_name <- data %>% select({{explanatory}}) %>% names() x_bar <- mean(x) y_bar <- mean(y) ### Edit code after here sd_x <- 1 sd_y <- 1 beta_0 <- 1 beta_1 <- 1 ### Stop editing results <- tibble::tibble( Intercept = beta_0, Slope = beta_1 ) names(results)[2] <- explan_name return(results) } #' Implements linear regression with many predictors by hand #' #' This function computes coefficients for multiple regression by hand. #' All columns of the provided data frame are used as predictors, except the #' one specified as a response. #' #' No interaction terms are included. #' #' #' @param dat A data frame #' @param response The name of a response variable in the data frame (unquoted) #' #' @return A data frame of coefficients #' #' @import dplyr #' #'@export multiple_linear_regression <- function(dat, response) { results <- 0 ### This should be a data frame, with columns named ### "Intercept" and the same variable names as dat. return(results) }
sv <- function(data, lower1, upper1, lower2, upper2) { F <- prepare_data(data, lower1, upper1, lower2, upper2) S <- starting_values(F) return(list(mu1=S[1], mu2=S[2], var1=exp(S[3]), cor=S[4], var2=exp(S[5]))) } starting_values <- function(F) { # Generate starting values for the first and second moments using # complete case analysis. # # Result: # The return value is a vector with the elements (mean of Y1, mean of # Y2, variance of Y1, covariance between Y1 and Y2, variance of # Y2). ii = intersect(F$Obs[[1]], F$Obs[[2]]) Y1 <- F$Y1[ii,1] Y2 <- F$Y2[ii,1] m1 <- mean(Y1) m2 <- mean(Y2) v1 <- log(var(Y1)) v2 <- log(var(Y2)) c <- cov(Y1, Y2) sv <- c(m1, m2, v1, c, v2) return(sv) }
/R/sv.R
no_license
cran/clikcorr
R
false
false
815
r
sv <- function(data, lower1, upper1, lower2, upper2) { F <- prepare_data(data, lower1, upper1, lower2, upper2) S <- starting_values(F) return(list(mu1=S[1], mu2=S[2], var1=exp(S[3]), cor=S[4], var2=exp(S[5]))) } starting_values <- function(F) { # Generate starting values for the first and second moments using # complete case analysis. # # Result: # The return value is a vector with the elements (mean of Y1, mean of # Y2, variance of Y1, covariance between Y1 and Y2, variance of # Y2). ii = intersect(F$Obs[[1]], F$Obs[[2]]) Y1 <- F$Y1[ii,1] Y2 <- F$Y2[ii,1] m1 <- mean(Y1) m2 <- mean(Y2) v1 <- log(var(Y1)) v2 <- log(var(Y2)) c <- cov(Y1, Y2) sv <- c(m1, m2, v1, c, v2) return(sv) }
makeCacheMatrix <- function(x = matrix()) { j <- NULL set <- function(y){ x <<- y j <<- NULL } get <- function()x setInverse <- function(inverse) j <<- inverse getInverse <- function() j list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) } ##Please include your own comment to explain your code (Required in Rubric) cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' j <- x$getInverse() if(!is.null(j)){ message("getting cached data") return(j) } mat <- x$get() j <- solve(mat,...) x$setInverse(j) j }
/cachematrix.R
no_license
Krithika-hub/rasi
R
false
false
627
r
makeCacheMatrix <- function(x = matrix()) { j <- NULL set <- function(y){ x <<- y j <<- NULL } get <- function()x setInverse <- function(inverse) j <<- inverse getInverse <- function() j list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) } ##Please include your own comment to explain your code (Required in Rubric) cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' j <- x$getInverse() if(!is.null(j)){ message("getting cached data") return(j) } mat <- x$get() j <- solve(mat,...) x$setInverse(j) j }
# ALADYM Age length based dynamic model - version 12.3 # Authors: G. Lembo, I. Bitetto, M.T. Facchini, M.T. Spedicato 2018 # COISPA Tecnologia & Ricerca, Via dei Trulli 18/20 - (Bari), Italy # In case of use of the model, the Authors should be cited. # If you have any comments or suggestions please contact the following e-mail address: facchini@coispa.it # ALADYM is believed to be reliable. However, we disclaim any implied warranty or representation about its accuracy, # completeness or appropriateness for any particular purpose. # # # # # # # # ------------------------------------------------------------------------------ # add elements to the list of the p production values # ------------------------------------------------------------------------------ # add.DAYS <- function() { #print("Adding elements to the list...") if (!is.null(fleet.DAYS)) { for (r in 1:nrow(fleet.DAYS)) { DAYS_temp <- as.list(fleet.DAYS[r,]) names(DAYS_temp) <- c("year",MONTHS) DAYS <<- c(DAYS, list(DAYS_temp)) } } else { DAYS_matrix <- data.frame(matrix(0, nrow=length(years), ncol=13)) colnames(DAYS_matrix) <- c("year",MONTHS) DAYS_matrix$year <- years for (r in 1:nrow(DAYS_matrix)) { DAYS_temp <- as.list(DAYS_matrix[r,]) DAYS <<- c(DAYS, list(DAYS_temp)) } } #print("DAYS (simulation) list successfully updated!", quote=F) }
/BEMTOOL-ver2.5-2018_0901/src/biol/bmtALADYM/ALADYM-ver12.3-2017_0501/gui/fishery/effort.daysFun/add.DAYS.r
no_license
gresci/BEMTOOL2.5
R
false
false
1,374
r
# ALADYM Age length based dynamic model - version 12.3 # Authors: G. Lembo, I. Bitetto, M.T. Facchini, M.T. Spedicato 2018 # COISPA Tecnologia & Ricerca, Via dei Trulli 18/20 - (Bari), Italy # In case of use of the model, the Authors should be cited. # If you have any comments or suggestions please contact the following e-mail address: facchini@coispa.it # ALADYM is believed to be reliable. However, we disclaim any implied warranty or representation about its accuracy, # completeness or appropriateness for any particular purpose. # # # # # # # # ------------------------------------------------------------------------------ # add elements to the list of the p production values # ------------------------------------------------------------------------------ # add.DAYS <- function() { #print("Adding elements to the list...") if (!is.null(fleet.DAYS)) { for (r in 1:nrow(fleet.DAYS)) { DAYS_temp <- as.list(fleet.DAYS[r,]) names(DAYS_temp) <- c("year",MONTHS) DAYS <<- c(DAYS, list(DAYS_temp)) } } else { DAYS_matrix <- data.frame(matrix(0, nrow=length(years), ncol=13)) colnames(DAYS_matrix) <- c("year",MONTHS) DAYS_matrix$year <- years for (r in 1:nrow(DAYS_matrix)) { DAYS_temp <- as.list(DAYS_matrix[r,]) DAYS <<- c(DAYS, list(DAYS_temp)) } } #print("DAYS (simulation) list successfully updated!", quote=F) }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/event_model.R \name{nuisance} \alias{nuisance} \title{nuisance} \usage{ nuisance(x) } \arguments{ \item{x}{a \code{matrix}} } \value{ a class of type \code{nuisancespec} } \description{ a 'nuisance' term that consists of an arbitrary numeric matrix with the same number of rows as image time points. }
/man/nuisance.Rd
no_license
muschellij2/fmrireg
R
false
true
381
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/event_model.R \name{nuisance} \alias{nuisance} \title{nuisance} \usage{ nuisance(x) } \arguments{ \item{x}{a \code{matrix}} } \value{ a class of type \code{nuisancespec} } \description{ a 'nuisance' term that consists of an arbitrary numeric matrix with the same number of rows as image time points. }
\name{summary.tcga.norm} \alias{summary.tcga.norm} \docType{data} \title{ Example dataset of input data for shinyMethyl for the 450k platform } \description{ Extracted data from 369 TCGA Head and Neck Cancer DNA methylation samples. The extracted data serve as an example dataset for the package shinyMethyl. Original samples are from 450k methylation arrays, and were obtained from The Cancer Genome Atlas (TCGA). 310 samples are from tumor, 50 are matched normals and 9 are technical replicates of a control cell line. } \usage{data(summary.tcga.norm)} \format{ A \code{list} containing the necessary information to launch a shinyMethyl session. See the links below for more details on the data. } \references{ The Cancer Genome Atltas (TCGA) Head and Neck Cancer dataset: http://cancergenome.nih.gov/cancersselected/headandneck } \seealso{ These data objects were created by See \code{\link[shinyMethyl]{shinySummarize}} for details on how to perform the data extraction. See \code{\link[shinyMethyl]{runShinyMethyl}} for how to launch a shinyMethyl session. } \examples{ data(summary.tcga.norm) \dontrun{ runShinyMethyl(summary.tcga.norm) } } \keyword{datasets}
/man/summary.tcga.norm.Rd
no_license
Jfortin1/shinyMethylData
R
false
false
1,169
rd
\name{summary.tcga.norm} \alias{summary.tcga.norm} \docType{data} \title{ Example dataset of input data for shinyMethyl for the 450k platform } \description{ Extracted data from 369 TCGA Head and Neck Cancer DNA methylation samples. The extracted data serve as an example dataset for the package shinyMethyl. Original samples are from 450k methylation arrays, and were obtained from The Cancer Genome Atlas (TCGA). 310 samples are from tumor, 50 are matched normals and 9 are technical replicates of a control cell line. } \usage{data(summary.tcga.norm)} \format{ A \code{list} containing the necessary information to launch a shinyMethyl session. See the links below for more details on the data. } \references{ The Cancer Genome Atltas (TCGA) Head and Neck Cancer dataset: http://cancergenome.nih.gov/cancersselected/headandneck } \seealso{ These data objects were created by See \code{\link[shinyMethyl]{shinySummarize}} for details on how to perform the data extraction. See \code{\link[shinyMethyl]{runShinyMethyl}} for how to launch a shinyMethyl session. } \examples{ data(summary.tcga.norm) \dontrun{ runShinyMethyl(summary.tcga.norm) } } \keyword{datasets}
# Tests for file Helper.R test_that("Test checkInputFileEncoding expected pass", { testData <- data.frame(id=c(1), name=c("test")) testFile <- tempfile("test_data.csv") readr::write_csv(x = testData, file = testFile) expect_invisible(ROhdsiWebApi::checkInputFileEncoding(testFile)) on.exit(unlink(testFile)) }) test_that("Test checkInputFileEncoding expected fail", { expect_error(ROhdsiWebApi::checkInputFileEncoding("resources/bad-file-encoding.csv")) })
/tests/testthat/test-Helper.R
permissive
OHDSI/ROhdsiWebApi
R
false
false
471
r
# Tests for file Helper.R test_that("Test checkInputFileEncoding expected pass", { testData <- data.frame(id=c(1), name=c("test")) testFile <- tempfile("test_data.csv") readr::write_csv(x = testData, file = testFile) expect_invisible(ROhdsiWebApi::checkInputFileEncoding(testFile)) on.exit(unlink(testFile)) }) test_that("Test checkInputFileEncoding expected fail", { expect_error(ROhdsiWebApi::checkInputFileEncoding("resources/bad-file-encoding.csv")) })
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/generate.graph.params.R \name{generate.graph.params} \alias{generate.graph.params} \title{Generate a graph parameter object to fit admixture graph to observed fstats} \usage{ generate.graph.params( graph, fstats = NULL, popref = NULL, outfileprefix = NULL, verbose = TRUE ) } \arguments{ \item{graph}{A three columns matrix containing graph information in a simple format (see details)} \item{fstats}{A fstats object containing estimates of fstats} \item{popref}{Reference population of the fstats basis used to fit the graph.} \item{outfileprefix}{The prefix of the dot file that will represent the graph (with extension ".dot"). If NULL, no graph file generated} \item{verbose}{If TRUE some information is printed on the terminal} } \value{ An object of class graph.params (see help(graph.params) for details) } \description{ Generate a graph parameter object to fit admixture graph to observed fstats } \details{ The graph needs to be specified by a three column (character) matrix corresponding for each edge (wether admixed or not) to i) the child node; ii) the parent node; iii) the admixture proportion. For non-admixed edge, the third column must be blank. An admixed node should be referred two times as a child node with two different parent node and two different admixture proportions coded as alpha and (1-alpha) (Note that the parentheses are mandatory) if alpha is the name of the admixture proportion. The root is automatically identified as a node only present in the parent node column. Several checks are made within the function but it is recommended to check the graph by plotting the resulting dot file named {outfileprefix.}dot using for instance the grViz() from the DiagrammeR package that may be called directly with plot or with the dot program (e.g., dot -Tpng inputgraph.dot in terminal). Note that the dot file may be easily customized (e.g., to change leave color, parameter names...). The fstats object should be of class fstats (see help(fstats) for details) containing estimates of F2 and F3 statistics and block jackknife as generated with the \code{\link{compute.fstats}} function with computeF3 set to TRUE. If no fstats object is provided, only graph parameters will be generated. } \examples{ graph=rbind(c("P1","P7",""),c("P2","s1",""),c("P3","s2",""),c("P6","S",""), c("S","s1","a"),c("S","s2","(1-a)"),c("s2","P8",""),c("s1","P7",""), c("P4","P9",""),c("P5","P9",""),c("P7","P8",""), c("P8","R",""),c("P9","R","")) graph.params=generate.graph.params(graph) plot(graph.params) ##NOTE: this calls grViz from DiagrammeR which cannot easily be plotted #within pdf or other device. To that end the easiest is to output #the graph in a dot file (using the outfileprefix argument) and #then to use the dot program out of R in a terminal: dot -Tpng inputgraph.dot } \seealso{ The object may be used to estimate graph parameters with the function \code{\link{fit.graph}} or to generate files for the qpGraph software with \code{\link{graph.params2qpGraphFiles}}. See also \code{\link{graph.params2symbolic.fstats}} to obtain symbolic representation of Fstats. }
/man/generate.graph.params.Rd
no_license
cran/poolfstat
R
false
true
3,227
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/generate.graph.params.R \name{generate.graph.params} \alias{generate.graph.params} \title{Generate a graph parameter object to fit admixture graph to observed fstats} \usage{ generate.graph.params( graph, fstats = NULL, popref = NULL, outfileprefix = NULL, verbose = TRUE ) } \arguments{ \item{graph}{A three columns matrix containing graph information in a simple format (see details)} \item{fstats}{A fstats object containing estimates of fstats} \item{popref}{Reference population of the fstats basis used to fit the graph.} \item{outfileprefix}{The prefix of the dot file that will represent the graph (with extension ".dot"). If NULL, no graph file generated} \item{verbose}{If TRUE some information is printed on the terminal} } \value{ An object of class graph.params (see help(graph.params) for details) } \description{ Generate a graph parameter object to fit admixture graph to observed fstats } \details{ The graph needs to be specified by a three column (character) matrix corresponding for each edge (wether admixed or not) to i) the child node; ii) the parent node; iii) the admixture proportion. For non-admixed edge, the third column must be blank. An admixed node should be referred two times as a child node with two different parent node and two different admixture proportions coded as alpha and (1-alpha) (Note that the parentheses are mandatory) if alpha is the name of the admixture proportion. The root is automatically identified as a node only present in the parent node column. Several checks are made within the function but it is recommended to check the graph by plotting the resulting dot file named {outfileprefix.}dot using for instance the grViz() from the DiagrammeR package that may be called directly with plot or with the dot program (e.g., dot -Tpng inputgraph.dot in terminal). Note that the dot file may be easily customized (e.g., to change leave color, parameter names...). The fstats object should be of class fstats (see help(fstats) for details) containing estimates of F2 and F3 statistics and block jackknife as generated with the \code{\link{compute.fstats}} function with computeF3 set to TRUE. If no fstats object is provided, only graph parameters will be generated. } \examples{ graph=rbind(c("P1","P7",""),c("P2","s1",""),c("P3","s2",""),c("P6","S",""), c("S","s1","a"),c("S","s2","(1-a)"),c("s2","P8",""),c("s1","P7",""), c("P4","P9",""),c("P5","P9",""),c("P7","P8",""), c("P8","R",""),c("P9","R","")) graph.params=generate.graph.params(graph) plot(graph.params) ##NOTE: this calls grViz from DiagrammeR which cannot easily be plotted #within pdf or other device. To that end the easiest is to output #the graph in a dot file (using the outfileprefix argument) and #then to use the dot program out of R in a terminal: dot -Tpng inputgraph.dot } \seealso{ The object may be used to estimate graph parameters with the function \code{\link{fit.graph}} or to generate files for the qpGraph software with \code{\link{graph.params2qpGraphFiles}}. See also \code{\link{graph.params2symbolic.fstats}} to obtain symbolic representation of Fstats. }
\name{sim.glm} \alias{sim.glm} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Simulation of glm } \description{ function for predictions from the results of model fitting functions (\code{\link{fit.glm}}) or (\code{\link{glm}}) } \usage{ sim.glm(fit, datapred, fam.glm = "gaussian", occ.cond = NULL) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{fit}{ climatic variable fitted returned from "glm" which inherits from the class "lm". } \item{datapred}{ Data frame that contains dates, climatic variables and all covariates used to fit the variable to simulate } \item{fam.glm}{ family objects to specify probability distribution used for the model ("gaussian", "gaussian-hetero", "binomial" or "Gamma") } \item{occ.cond}{ character object that specifies the name of the occurrence variable if that exists } } \value{ Value returned belong to the same class of its first argument } \seealso{ \code{\link{glm}}, \code{\link{fit.glm}} } \examples{ temp_fitted=glm(temp~Rh, family=gaussian, data=myclimatic_data) temp.sim=sim.glm(temp_fitted, myclimatic_data, fam.glm = "gaussian", occ.cond = NULL) }
/man/sim.glm.Rd
no_license
cran/MetGen
R
false
false
1,163
rd
\name{sim.glm} \alias{sim.glm} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Simulation of glm } \description{ function for predictions from the results of model fitting functions (\code{\link{fit.glm}}) or (\code{\link{glm}}) } \usage{ sim.glm(fit, datapred, fam.glm = "gaussian", occ.cond = NULL) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{fit}{ climatic variable fitted returned from "glm" which inherits from the class "lm". } \item{datapred}{ Data frame that contains dates, climatic variables and all covariates used to fit the variable to simulate } \item{fam.glm}{ family objects to specify probability distribution used for the model ("gaussian", "gaussian-hetero", "binomial" or "Gamma") } \item{occ.cond}{ character object that specifies the name of the occurrence variable if that exists } } \value{ Value returned belong to the same class of its first argument } \seealso{ \code{\link{glm}}, \code{\link{fit.glm}} } \examples{ temp_fitted=glm(temp~Rh, family=gaussian, data=myclimatic_data) temp.sim=sim.glm(temp_fitted, myclimatic_data, fam.glm = "gaussian", occ.cond = NULL) }
library(ggplot2) library(dplyr) data=read.csv("googleplaystore.csv") summary(na.omit(data$Rating)) dim(data) corrupted=data %>% filter(Rating==19) corrupted data=subset(data, Category != "1.9") summary(na.omit(data$Rating)) ggplot(data, aes(x = Rating)) + geom_histogram() data=data %>% mutate(Price=na.omit(as.double(gsub("\\$","", Price)))) summary(data$Price) ggplot(data, aes(x = Price)) + geom_histogram() data=data %>% mutate(Reviews = na.omit(as.numeric(levels(data$Reviews))[data$Reviews])) summary(data$Reviews) ggplot(data, aes(x = Reviews)) + geom_histogram()
/googleplaystore.r
no_license
alekhyatati/GooglePlayStore-Apps-Project
R
false
false
601
r
library(ggplot2) library(dplyr) data=read.csv("googleplaystore.csv") summary(na.omit(data$Rating)) dim(data) corrupted=data %>% filter(Rating==19) corrupted data=subset(data, Category != "1.9") summary(na.omit(data$Rating)) ggplot(data, aes(x = Rating)) + geom_histogram() data=data %>% mutate(Price=na.omit(as.double(gsub("\\$","", Price)))) summary(data$Price) ggplot(data, aes(x = Price)) + geom_histogram() data=data %>% mutate(Reviews = na.omit(as.numeric(levels(data$Reviews))[data$Reviews])) summary(data$Reviews) ggplot(data, aes(x = Reviews)) + geom_histogram()
#' Daily mean temperatures for Ljubljana from 2016 - 1930 #' #' A dataset of daily mean temperatures in Ljubljana (Slovenia). The first row #' represents temperatures in 1930. The first column represents the first day #' of a year, the second column represents the second day of a year, etc. #' #' @format A data frame with 87 rows and 366 variables: #' \describe{ #' \item{X1}{Temperatures on the day 1 of a year} #' \item{X2}{Temperatures on the day 2 of a year} #' \item{X3}{Temperatures on the day 3 of a year} #' \item{X4}{Temperatures on the day 4 of a year} #' \item{X5}{Temperatures on the day 5 of a year} #' \item{X6}{Temperatures on the day 6 of a year} #' \item{X7}{Temperatures on the day 7 of a year} #' \item{X8}{Temperatures on the day 8 of a year} #' \item{X9}{Temperatures on the day 9 of a year} #' \item{X10}{Temperatures on the day 10 of a year} #' \item{X11}{Temperatures on the day 11 of a year} #' \item{X12}{Temperatures on the day 12 of a year} #' \item{X13}{Temperatures on the day 13 of a year} #' \item{X14}{Temperatures on the day 14 of a year} #' \item{X15}{Temperatures on the day 15 of a year} #' \item{X16}{Temperatures on the day 16 of a year} #' \item{X17}{Temperatures on the day 17 of a year} #' \item{X18}{Temperatures on the day 18 of a year} #' \item{X19}{Temperatures on the day 19 of a year} #' \item{X20}{Temperatures on the day 20 of a year} #' \item{X21}{Temperatures on the day 21 of a year} #' \item{X22}{Temperatures on the day 22 of a year} #' \item{X23}{Temperatures on the day 23 of a year} #' \item{X24}{Temperatures on the day 24 of a year} #' \item{X25}{Temperatures on the day 25 of a year} #' \item{X26}{Temperatures on the day 26 of a year} #' \item{X27}{Temperatures on the day 27 of a year} #' \item{X28}{Temperatures on the day 28 of a year} #' \item{X29}{Temperatures on the day 29 of a year} #' \item{X30}{Temperatures on the day 30 of a year} #' \item{X31}{Temperatures on the day 31 of a year} #' \item{X32}{Temperatures on the day 32 of a year} #' \item{X33}{Temperatures on the day 33 of a year} #' \item{X34}{Temperatures on the day 34 of a year} #' \item{X35}{Temperatures on the day 35 of a year} #' \item{X36}{Temperatures on the day 36 of a year} #' \item{X37}{Temperatures on the day 37 of a year} #' \item{X38}{Temperatures on the day 38 of a year} #' \item{X39}{Temperatures on the day 39 of a year} #' \item{X40}{Temperatures on the day 40 of a year} #' \item{X41}{Temperatures on the day 41 of a year} #' \item{X42}{Temperatures on the day 42 of a year} #' \item{X43}{Temperatures on the day 43 of a year} #' \item{X44}{Temperatures on the day 44 of a year} #' \item{X45}{Temperatures on the day 45 of a year} #' \item{X46}{Temperatures on the day 46 of a year} #' \item{X47}{Temperatures on the day 47 of a year} #' \item{X48}{Temperatures on the day 48 of a year} #' \item{X49}{Temperatures on the day 49 of a year} #' \item{X50}{Temperatures on the day 50 of a year} #' \item{X51}{Temperatures on the day 51 of a year} #' \item{X52}{Temperatures on the day 52 of a year} #' \item{X53}{Temperatures on the day 53 of a year} #' \item{X54}{Temperatures on the day 54 of a year} #' \item{X55}{Temperatures on the day 55 of a year} #' \item{X56}{Temperatures on the day 56 of a year} #' \item{X57}{Temperatures on the day 57 of a year} #' \item{X58}{Temperatures on the day 58 of a year} #' \item{X59}{Temperatures on the day 59 of a year} #' \item{X60}{Temperatures on the day 60 of a year} #' \item{X61}{Temperatures on the day 61 of a year} #' \item{X62}{Temperatures on the day 62 of a year} #' \item{X63}{Temperatures on the day 63 of a year} #' \item{X64}{Temperatures on the day 64 of a year} #' \item{X65}{Temperatures on the day 65 of a year} #' \item{X66}{Temperatures on the day 66 of a year} #' \item{X67}{Temperatures on the day 67 of a year} #' \item{X68}{Temperatures on the day 68 of a year} #' \item{X69}{Temperatures on the day 69 of a year} #' \item{X70}{Temperatures on the day 70 of a year} #' \item{X71}{Temperatures on the day 71 of a year} #' \item{X72}{Temperatures on the day 72 of a year} #' \item{X73}{Temperatures on the day 73 of a year} #' \item{X74}{Temperatures on the day 74 of a year} #' \item{X75}{Temperatures on the day 75 of a year} #' \item{X76}{Temperatures on the day 76 of a year} #' \item{X77}{Temperatures on the day 77 of a year} #' \item{X78}{Temperatures on the day 78 of a year} #' \item{X79}{Temperatures on the day 79 of a year} #' \item{X80}{Temperatures on the day 80 of a year} #' \item{X81}{Temperatures on the day 81 of a year} #' \item{X82}{Temperatures on the day 82 of a year} #' \item{X83}{Temperatures on the day 83 of a year} #' \item{X84}{Temperatures on the day 84 of a year} #' \item{X85}{Temperatures on the day 85 of a year} #' \item{X86}{Temperatures on the day 86 of a year} #' \item{X87}{Temperatures on the day 87 of a year} #' \item{X88}{Temperatures on the day 88 of a year} #' \item{X89}{Temperatures on the day 89 of a year} #' \item{X90}{Temperatures on the day 90 of a year} #' \item{X91}{Temperatures on the day 91 of a year} #' \item{X92}{Temperatures on the day 92 of a year} #' \item{X93}{Temperatures on the day 93 of a year} #' \item{X94}{Temperatures on the day 94 of a year} #' \item{X95}{Temperatures on the day 95 of a year} #' \item{X96}{Temperatures on the day 96 of a year} #' \item{X97}{Temperatures on the day 97 of a year} #' \item{X98}{Temperatures on the day 98 of a year} #' \item{X99}{Temperatures on the day 99 of a year} #' \item{X100}{Temperatures on the day 100 of a year} #' \item{X101}{Temperatures on the day 101 of a year} #' \item{X102}{Temperatures on the day 102 of a year} #' \item{X103}{Temperatures on the day 103 of a year} #' \item{X104}{Temperatures on the day 104 of a year} #' \item{X105}{Temperatures on the day 105 of a year} #' \item{X106}{Temperatures on the day 106 of a year} #' \item{X107}{Temperatures on the day 107 of a year} #' \item{X108}{Temperatures on the day 108 of a year} #' \item{X109}{Temperatures on the day 109 of a year} #' \item{X110}{Temperatures on the day 110 of a year} #' \item{X111}{Temperatures on the day 111 of a year} #' \item{X112}{Temperatures on the day 112 of a year} #' \item{X113}{Temperatures on the day 113 of a year} #' \item{X114}{Temperatures on the day 114 of a year} #' \item{X115}{Temperatures on the day 115 of a year} #' \item{X116}{Temperatures on the day 116 of a year} #' \item{X117}{Temperatures on the day 117 of a year} #' \item{X118}{Temperatures on the day 118 of a year} #' \item{X119}{Temperatures on the day 119 of a year} #' \item{X120}{Temperatures on the day 120 of a year} #' \item{X121}{Temperatures on the day 121 of a year} #' \item{X122}{Temperatures on the day 122 of a year} #' \item{X123}{Temperatures on the day 123 of a year} #' \item{X124}{Temperatures on the day 124 of a year} #' \item{X125}{Temperatures on the day 125 of a year} #' \item{X126}{Temperatures on the day 126 of a year} #' \item{X127}{Temperatures on the day 127 of a year} #' \item{X128}{Temperatures on the day 128 of a year} #' \item{X129}{Temperatures on the day 129 of a year} #' \item{X130}{Temperatures on the day 130 of a year} #' \item{X131}{Temperatures on the day 131 of a year} #' \item{X132}{Temperatures on the day 132 of a year} #' \item{X133}{Temperatures on the day 133 of a year} #' \item{X134}{Temperatures on the day 134 of a year} #' \item{X135}{Temperatures on the day 135 of a year} #' \item{X136}{Temperatures on the day 136 of a year} #' \item{X137}{Temperatures on the day 137 of a year} #' \item{X138}{Temperatures on the day 138 of a year} #' \item{X139}{Temperatures on the day 139 of a year} #' \item{X140}{Temperatures on the day 140 of a year} #' \item{X141}{Temperatures on the day 141 of a year} #' \item{X142}{Temperatures on the day 142 of a year} #' \item{X143}{Temperatures on the day 143 of a year} #' \item{X144}{Temperatures on the day 144 of a year} #' \item{X145}{Temperatures on the day 145 of a year} #' \item{X146}{Temperatures on the day 146 of a year} #' \item{X147}{Temperatures on the day 147 of a year} #' \item{X148}{Temperatures on the day 148 of a year} #' \item{X149}{Temperatures on the day 149 of a year} #' \item{X150}{Temperatures on the day 150 of a year} #' \item{X151}{Temperatures on the day 151 of a year} #' \item{X152}{Temperatures on the day 152 of a year} #' \item{X153}{Temperatures on the day 153 of a year} #' \item{X154}{Temperatures on the day 154 of a year} #' \item{X155}{Temperatures on the day 155 of a year} #' \item{X156}{Temperatures on the day 156 of a year} #' \item{X157}{Temperatures on the day 157 of a year} #' \item{X158}{Temperatures on the day 158 of a year} #' \item{X159}{Temperatures on the day 159 of a year} #' \item{X160}{Temperatures on the day 160 of a year} #' \item{X161}{Temperatures on the day 161 of a year} #' \item{X162}{Temperatures on the day 162 of a year} #' \item{X163}{Temperatures on the day 163 of a year} #' \item{X164}{Temperatures on the day 164 of a year} #' \item{X165}{Temperatures on the day 165 of a year} #' \item{X166}{Temperatures on the day 166 of a year} #' \item{X167}{Temperatures on the day 167 of a year} #' \item{X168}{Temperatures on the day 168 of a year} #' \item{X169}{Temperatures on the day 169 of a year} #' \item{X170}{Temperatures on the day 170 of a year} #' \item{X171}{Temperatures on the day 171 of a year} #' \item{X172}{Temperatures on the day 172 of a year} #' \item{X173}{Temperatures on the day 173 of a year} #' \item{X174}{Temperatures on the day 174 of a year} #' \item{X175}{Temperatures on the day 175 of a year} #' \item{X176}{Temperatures on the day 176 of a year} #' \item{X177}{Temperatures on the day 177 of a year} #' \item{X178}{Temperatures on the day 178 of a year} #' \item{X179}{Temperatures on the day 179 of a year} #' \item{X180}{Temperatures on the day 180 of a year} #' \item{X181}{Temperatures on the day 181 of a year} #' \item{X182}{Temperatures on the day 182 of a year} #' \item{X183}{Temperatures on the day 183 of a year} #' \item{X184}{Temperatures on the day 184 of a year} #' \item{X185}{Temperatures on the day 185 of a year} #' \item{X186}{Temperatures on the day 186 of a year} #' \item{X187}{Temperatures on the day 187 of a year} #' \item{X188}{Temperatures on the day 188 of a year} #' \item{X189}{Temperatures on the day 189 of a year} #' \item{X190}{Temperatures on the day 190 of a year} #' \item{X191}{Temperatures on the day 191 of a year} #' \item{X192}{Temperatures on the day 192 of a year} #' \item{X193}{Temperatures on the day 193 of a year} #' \item{X194}{Temperatures on the day 194 of a year} #' \item{X195}{Temperatures on the day 195 of a year} #' \item{X196}{Temperatures on the day 196 of a year} #' \item{X197}{Temperatures on the day 197 of a year} #' \item{X198}{Temperatures on the day 198 of a year} #' \item{X199}{Temperatures on the day 199 of a year} #' \item{X200}{Temperatures on the day 200 of a year} #' \item{X201}{Temperatures on the day 201 of a year} #' \item{X202}{Temperatures on the day 202 of a year} #' \item{X203}{Temperatures on the day 203 of a year} #' \item{X204}{Temperatures on the day 204 of a year} #' \item{X205}{Temperatures on the day 205 of a year} #' \item{X206}{Temperatures on the day 206 of a year} #' \item{X207}{Temperatures on the day 207 of a year} #' \item{X208}{Temperatures on the day 208 of a year} #' \item{X209}{Temperatures on the day 209 of a year} #' \item{X210}{Temperatures on the day 210 of a year} #' \item{X211}{Temperatures on the day 211 of a year} #' \item{X212}{Temperatures on the day 212 of a year} #' \item{X213}{Temperatures on the day 213 of a year} #' \item{X214}{Temperatures on the day 214 of a year} #' \item{X215}{Temperatures on the day 215 of a year} #' \item{X216}{Temperatures on the day 216 of a year} #' \item{X217}{Temperatures on the day 217 of a year} #' \item{X218}{Temperatures on the day 218 of a year} #' \item{X219}{Temperatures on the day 219 of a year} #' \item{X220}{Temperatures on the day 220 of a year} #' \item{X221}{Temperatures on the day 221 of a year} #' \item{X222}{Temperatures on the day 222 of a year} #' \item{X223}{Temperatures on the day 223 of a year} #' \item{X224}{Temperatures on the day 224 of a year} #' \item{X225}{Temperatures on the day 225 of a year} #' \item{X226}{Temperatures on the day 226 of a year} #' \item{X227}{Temperatures on the day 227 of a year} #' \item{X228}{Temperatures on the day 228 of a year} #' \item{X229}{Temperatures on the day 229 of a year} #' \item{X230}{Temperatures on the day 230 of a year} #' \item{X231}{Temperatures on the day 231 of a year} #' \item{X232}{Temperatures on the day 232 of a year} #' \item{X233}{Temperatures on the day 233 of a year} #' \item{X234}{Temperatures on the day 234 of a year} #' \item{X235}{Temperatures on the day 235 of a year} #' \item{X236}{Temperatures on the day 236 of a year} #' \item{X237}{Temperatures on the day 237 of a year} #' \item{X238}{Temperatures on the day 238 of a year} #' \item{X239}{Temperatures on the day 239 of a year} #' \item{X240}{Temperatures on the day 240 of a year} #' \item{X241}{Temperatures on the day 241 of a year} #' \item{X242}{Temperatures on the day 242 of a year} #' \item{X243}{Temperatures on the day 243 of a year} #' \item{X244}{Temperatures on the day 244 of a year} #' \item{X245}{Temperatures on the day 245 of a year} #' \item{X246}{Temperatures on the day 246 of a year} #' \item{X247}{Temperatures on the day 247 of a year} #' \item{X248}{Temperatures on the day 248 of a year} #' \item{X249}{Temperatures on the day 249 of a year} #' \item{X250}{Temperatures on the day 250 of a year} #' \item{X251}{Temperatures on the day 251 of a year} #' \item{X252}{Temperatures on the day 252 of a year} #' \item{X253}{Temperatures on the day 253 of a year} #' \item{X254}{Temperatures on the day 254 of a year} #' \item{X255}{Temperatures on the day 255 of a year} #' \item{X256}{Temperatures on the day 256 of a year} #' \item{X257}{Temperatures on the day 257 of a year} #' \item{X258}{Temperatures on the day 258 of a year} #' \item{X259}{Temperatures on the day 259 of a year} #' \item{X260}{Temperatures on the day 260 of a year} #' \item{X261}{Temperatures on the day 261 of a year} #' \item{X262}{Temperatures on the day 262 of a year} #' \item{X263}{Temperatures on the day 263 of a year} #' \item{X264}{Temperatures on the day 264 of a year} #' \item{X265}{Temperatures on the day 265 of a year} #' \item{X266}{Temperatures on the day 266 of a year} #' \item{X267}{Temperatures on the day 267 of a year} #' \item{X268}{Temperatures on the day 268 of a year} #' \item{X269}{Temperatures on the day 269 of a year} #' \item{X270}{Temperatures on the day 270 of a year} #' \item{X271}{Temperatures on the day 271 of a year} #' \item{X272}{Temperatures on the day 272 of a year} #' \item{X273}{Temperatures on the day 273 of a year} #' \item{X274}{Temperatures on the day 274 of a year} #' \item{X275}{Temperatures on the day 275 of a year} #' \item{X276}{Temperatures on the day 276 of a year} #' \item{X277}{Temperatures on the day 277 of a year} #' \item{X278}{Temperatures on the day 278 of a year} #' \item{X279}{Temperatures on the day 279 of a year} #' \item{X280}{Temperatures on the day 280 of a year} #' \item{X281}{Temperatures on the day 281 of a year} #' \item{X282}{Temperatures on the day 282 of a year} #' \item{X283}{Temperatures on the day 283 of a year} #' \item{X284}{Temperatures on the day 284 of a year} #' \item{X285}{Temperatures on the day 285 of a year} #' \item{X286}{Temperatures on the day 286 of a year} #' \item{X287}{Temperatures on the day 287 of a year} #' \item{X288}{Temperatures on the day 288 of a year} #' \item{X289}{Temperatures on the day 289 of a year} #' \item{X290}{Temperatures on the day 290 of a year} #' \item{X291}{Temperatures on the day 291 of a year} #' \item{X292}{Temperatures on the day 292 of a year} #' \item{X293}{Temperatures on the day 293 of a year} #' \item{X294}{Temperatures on the day 294 of a year} #' \item{X295}{Temperatures on the day 295 of a year} #' \item{X296}{Temperatures on the day 296 of a year} #' \item{X297}{Temperatures on the day 297 of a year} #' \item{X298}{Temperatures on the day 298 of a year} #' \item{X299}{Temperatures on the day 299 of a year} #' \item{X300}{Temperatures on the day 300 of a year} #' \item{X301}{Temperatures on the day 301 of a year} #' \item{X302}{Temperatures on the day 302 of a year} #' \item{X303}{Temperatures on the day 303 of a year} #' \item{X304}{Temperatures on the day 304 of a year} #' \item{X305}{Temperatures on the day 305 of a year} #' \item{X306}{Temperatures on the day 306 of a year} #' \item{X307}{Temperatures on the day 307 of a year} #' \item{X308}{Temperatures on the day 308 of a year} #' \item{X309}{Temperatures on the day 309 of a year} #' \item{X310}{Temperatures on the day 310 of a year} #' \item{X311}{Temperatures on the day 311 of a year} #' \item{X312}{Temperatures on the day 312 of a year} #' \item{X313}{Temperatures on the day 313 of a year} #' \item{X314}{Temperatures on the day 314 of a year} #' \item{X315}{Temperatures on the day 315 of a year} #' \item{X316}{Temperatures on the day 316 of a year} #' \item{X317}{Temperatures on the day 317 of a year} #' \item{X318}{Temperatures on the day 318 of a year} #' \item{X319}{Temperatures on the day 319 of a year} #' \item{X320}{Temperatures on the day 320 of a year} #' \item{X321}{Temperatures on the day 321 of a year} #' \item{X322}{Temperatures on the day 322 of a year} #' \item{X323}{Temperatures on the day 323 of a year} #' \item{X324}{Temperatures on the day 324 of a year} #' \item{X325}{Temperatures on the day 325 of a year} #' \item{X326}{Temperatures on the day 326 of a year} #' \item{X327}{Temperatures on the day 327 of a year} #' \item{X328}{Temperatures on the day 328 of a year} #' \item{X329}{Temperatures on the day 329 of a year} #' \item{X330}{Temperatures on the day 330 of a year} #' \item{X331}{Temperatures on the day 331 of a year} #' \item{X332}{Temperatures on the day 332 of a year} #' \item{X333}{Temperatures on the day 333 of a year} #' \item{X334}{Temperatures on the day 334 of a year} #' \item{X335}{Temperatures on the day 335 of a year} #' \item{X336}{Temperatures on the day 336 of a year} #' \item{X337}{Temperatures on the day 337 of a year} #' \item{X338}{Temperatures on the day 338 of a year} #' \item{X339}{Temperatures on the day 339 of a year} #' \item{X340}{Temperatures on the day 340 of a year} #' \item{X341}{Temperatures on the day 341 of a year} #' \item{X342}{Temperatures on the day 342 of a year} #' \item{X343}{Temperatures on the day 343 of a year} #' \item{X344}{Temperatures on the day 344 of a year} #' \item{X345}{Temperatures on the day 345 of a year} #' \item{X346}{Temperatures on the day 346 of a year} #' \item{X347}{Temperatures on the day 347 of a year} #' \item{X348}{Temperatures on the day 348 of a year} #' \item{X349}{Temperatures on the day 349 of a year} #' \item{X350}{Temperatures on the day 350 of a year} #' \item{X351}{Temperatures on the day 351 of a year} #' \item{X352}{Temperatures on the day 352 of a year} #' \item{X353}{Temperatures on the day 353 of a year} #' \item{X354}{Temperatures on the day 354 of a year} #' \item{X355}{Temperatures on the day 355 of a year} #' \item{X356}{Temperatures on the day 356 of a year} #' \item{X357}{Temperatures on the day 357 of a year} #' \item{X358}{Temperatures on the day 358 of a year} #' \item{X359}{Temperatures on the day 359 of a year} #' \item{X360}{Temperatures on the day 360 of a year} #' \item{X361}{Temperatures on the day 361 of a year} #' \item{X362}{Temperatures on the day 362 of a year} #' \item{X363}{Temperatures on the day 363 of a year} #' \item{X364}{Temperatures on the day 364 of a year} #' \item{X365}{Temperatures on the day 365 of a year} #' \item{X366}{Temperatures on the day 366 of a year} #' } #' @source \url{http://climexp.knmi.nl/start.cgi} #' @export "LJ_daily_temperatures"
/R/LJ_daily_temperatures.R
no_license
cran/dendroTools
R
false
false
21,113
r
#' Daily mean temperatures for Ljubljana from 2016 - 1930 #' #' A dataset of daily mean temperatures in Ljubljana (Slovenia). The first row #' represents temperatures in 1930. The first column represents the first day #' of a year, the second column represents the second day of a year, etc. #' #' @format A data frame with 87 rows and 366 variables: #' \describe{ #' \item{X1}{Temperatures on the day 1 of a year} #' \item{X2}{Temperatures on the day 2 of a year} #' \item{X3}{Temperatures on the day 3 of a year} #' \item{X4}{Temperatures on the day 4 of a year} #' \item{X5}{Temperatures on the day 5 of a year} #' \item{X6}{Temperatures on the day 6 of a year} #' \item{X7}{Temperatures on the day 7 of a year} #' \item{X8}{Temperatures on the day 8 of a year} #' \item{X9}{Temperatures on the day 9 of a year} #' \item{X10}{Temperatures on the day 10 of a year} #' \item{X11}{Temperatures on the day 11 of a year} #' \item{X12}{Temperatures on the day 12 of a year} #' \item{X13}{Temperatures on the day 13 of a year} #' \item{X14}{Temperatures on the day 14 of a year} #' \item{X15}{Temperatures on the day 15 of a year} #' \item{X16}{Temperatures on the day 16 of a year} #' \item{X17}{Temperatures on the day 17 of a year} #' \item{X18}{Temperatures on the day 18 of a year} #' \item{X19}{Temperatures on the day 19 of a year} #' \item{X20}{Temperatures on the day 20 of a year} #' \item{X21}{Temperatures on the day 21 of a year} #' \item{X22}{Temperatures on the day 22 of a year} #' \item{X23}{Temperatures on the day 23 of a year} #' \item{X24}{Temperatures on the day 24 of a year} #' \item{X25}{Temperatures on the day 25 of a year} #' \item{X26}{Temperatures on the day 26 of a year} #' \item{X27}{Temperatures on the day 27 of a year} #' \item{X28}{Temperatures on the day 28 of a year} #' \item{X29}{Temperatures on the day 29 of a year} #' \item{X30}{Temperatures on the day 30 of a year} #' \item{X31}{Temperatures on the day 31 of a year} #' \item{X32}{Temperatures on the day 32 of a year} #' \item{X33}{Temperatures on the day 33 of a year} #' \item{X34}{Temperatures on the day 34 of a year} #' \item{X35}{Temperatures on the day 35 of a year} #' \item{X36}{Temperatures on the day 36 of a year} #' \item{X37}{Temperatures on the day 37 of a year} #' \item{X38}{Temperatures on the day 38 of a year} #' \item{X39}{Temperatures on the day 39 of a year} #' \item{X40}{Temperatures on the day 40 of a year} #' \item{X41}{Temperatures on the day 41 of a year} #' \item{X42}{Temperatures on the day 42 of a year} #' \item{X43}{Temperatures on the day 43 of a year} #' \item{X44}{Temperatures on the day 44 of a year} #' \item{X45}{Temperatures on the day 45 of a year} #' \item{X46}{Temperatures on the day 46 of a year} #' \item{X47}{Temperatures on the day 47 of a year} #' \item{X48}{Temperatures on the day 48 of a year} #' \item{X49}{Temperatures on the day 49 of a year} #' \item{X50}{Temperatures on the day 50 of a year} #' \item{X51}{Temperatures on the day 51 of a year} #' \item{X52}{Temperatures on the day 52 of a year} #' \item{X53}{Temperatures on the day 53 of a year} #' \item{X54}{Temperatures on the day 54 of a year} #' \item{X55}{Temperatures on the day 55 of a year} #' \item{X56}{Temperatures on the day 56 of a year} #' \item{X57}{Temperatures on the day 57 of a year} #' \item{X58}{Temperatures on the day 58 of a year} #' \item{X59}{Temperatures on the day 59 of a year} #' \item{X60}{Temperatures on the day 60 of a year} #' \item{X61}{Temperatures on the day 61 of a year} #' \item{X62}{Temperatures on the day 62 of a year} #' \item{X63}{Temperatures on the day 63 of a year} #' \item{X64}{Temperatures on the day 64 of a year} #' \item{X65}{Temperatures on the day 65 of a year} #' \item{X66}{Temperatures on the day 66 of a year} #' \item{X67}{Temperatures on the day 67 of a year} #' \item{X68}{Temperatures on the day 68 of a year} #' \item{X69}{Temperatures on the day 69 of a year} #' \item{X70}{Temperatures on the day 70 of a year} #' \item{X71}{Temperatures on the day 71 of a year} #' \item{X72}{Temperatures on the day 72 of a year} #' \item{X73}{Temperatures on the day 73 of a year} #' \item{X74}{Temperatures on the day 74 of a year} #' \item{X75}{Temperatures on the day 75 of a year} #' \item{X76}{Temperatures on the day 76 of a year} #' \item{X77}{Temperatures on the day 77 of a year} #' \item{X78}{Temperatures on the day 78 of a year} #' \item{X79}{Temperatures on the day 79 of a year} #' \item{X80}{Temperatures on the day 80 of a year} #' \item{X81}{Temperatures on the day 81 of a year} #' \item{X82}{Temperatures on the day 82 of a year} #' \item{X83}{Temperatures on the day 83 of a year} #' \item{X84}{Temperatures on the day 84 of a year} #' \item{X85}{Temperatures on the day 85 of a year} #' \item{X86}{Temperatures on the day 86 of a year} #' \item{X87}{Temperatures on the day 87 of a year} #' \item{X88}{Temperatures on the day 88 of a year} #' \item{X89}{Temperatures on the day 89 of a year} #' \item{X90}{Temperatures on the day 90 of a year} #' \item{X91}{Temperatures on the day 91 of a year} #' \item{X92}{Temperatures on the day 92 of a year} #' \item{X93}{Temperatures on the day 93 of a year} #' \item{X94}{Temperatures on the day 94 of a year} #' \item{X95}{Temperatures on the day 95 of a year} #' \item{X96}{Temperatures on the day 96 of a year} #' \item{X97}{Temperatures on the day 97 of a year} #' \item{X98}{Temperatures on the day 98 of a year} #' \item{X99}{Temperatures on the day 99 of a year} #' \item{X100}{Temperatures on the day 100 of a year} #' \item{X101}{Temperatures on the day 101 of a year} #' \item{X102}{Temperatures on the day 102 of a year} #' \item{X103}{Temperatures on the day 103 of a year} #' \item{X104}{Temperatures on the day 104 of a year} #' \item{X105}{Temperatures on the day 105 of a year} #' \item{X106}{Temperatures on the day 106 of a year} #' \item{X107}{Temperatures on the day 107 of a year} #' \item{X108}{Temperatures on the day 108 of a year} #' \item{X109}{Temperatures on the day 109 of a year} #' \item{X110}{Temperatures on the day 110 of a year} #' \item{X111}{Temperatures on the day 111 of a year} #' \item{X112}{Temperatures on the day 112 of a year} #' \item{X113}{Temperatures on the day 113 of a year} #' \item{X114}{Temperatures on the day 114 of a year} #' \item{X115}{Temperatures on the day 115 of a year} #' \item{X116}{Temperatures on the day 116 of a year} #' \item{X117}{Temperatures on the day 117 of a year} #' \item{X118}{Temperatures on the day 118 of a year} #' \item{X119}{Temperatures on the day 119 of a year} #' \item{X120}{Temperatures on the day 120 of a year} #' \item{X121}{Temperatures on the day 121 of a year} #' \item{X122}{Temperatures on the day 122 of a year} #' \item{X123}{Temperatures on the day 123 of a year} #' \item{X124}{Temperatures on the day 124 of a year} #' \item{X125}{Temperatures on the day 125 of a year} #' \item{X126}{Temperatures on the day 126 of a year} #' \item{X127}{Temperatures on the day 127 of a year} #' \item{X128}{Temperatures on the day 128 of a year} #' \item{X129}{Temperatures on the day 129 of a year} #' \item{X130}{Temperatures on the day 130 of a year} #' \item{X131}{Temperatures on the day 131 of a year} #' \item{X132}{Temperatures on the day 132 of a year} #' \item{X133}{Temperatures on the day 133 of a year} #' \item{X134}{Temperatures on the day 134 of a year} #' \item{X135}{Temperatures on the day 135 of a year} #' \item{X136}{Temperatures on the day 136 of a year} #' \item{X137}{Temperatures on the day 137 of a year} #' \item{X138}{Temperatures on the day 138 of a year} #' \item{X139}{Temperatures on the day 139 of a year} #' \item{X140}{Temperatures on the day 140 of a year} #' \item{X141}{Temperatures on the day 141 of a year} #' \item{X142}{Temperatures on the day 142 of a year} #' \item{X143}{Temperatures on the day 143 of a year} #' \item{X144}{Temperatures on the day 144 of a year} #' \item{X145}{Temperatures on the day 145 of a year} #' \item{X146}{Temperatures on the day 146 of a year} #' \item{X147}{Temperatures on the day 147 of a year} #' \item{X148}{Temperatures on the day 148 of a year} #' \item{X149}{Temperatures on the day 149 of a year} #' \item{X150}{Temperatures on the day 150 of a year} #' \item{X151}{Temperatures on the day 151 of a year} #' \item{X152}{Temperatures on the day 152 of a year} #' \item{X153}{Temperatures on the day 153 of a year} #' \item{X154}{Temperatures on the day 154 of a year} #' \item{X155}{Temperatures on the day 155 of a year} #' \item{X156}{Temperatures on the day 156 of a year} #' \item{X157}{Temperatures on the day 157 of a year} #' \item{X158}{Temperatures on the day 158 of a year} #' \item{X159}{Temperatures on the day 159 of a year} #' \item{X160}{Temperatures on the day 160 of a year} #' \item{X161}{Temperatures on the day 161 of a year} #' \item{X162}{Temperatures on the day 162 of a year} #' \item{X163}{Temperatures on the day 163 of a year} #' \item{X164}{Temperatures on the day 164 of a year} #' \item{X165}{Temperatures on the day 165 of a year} #' \item{X166}{Temperatures on the day 166 of a year} #' \item{X167}{Temperatures on the day 167 of a year} #' \item{X168}{Temperatures on the day 168 of a year} #' \item{X169}{Temperatures on the day 169 of a year} #' \item{X170}{Temperatures on the day 170 of a year} #' \item{X171}{Temperatures on the day 171 of a year} #' \item{X172}{Temperatures on the day 172 of a year} #' \item{X173}{Temperatures on the day 173 of a year} #' \item{X174}{Temperatures on the day 174 of a year} #' \item{X175}{Temperatures on the day 175 of a year} #' \item{X176}{Temperatures on the day 176 of a year} #' \item{X177}{Temperatures on the day 177 of a year} #' \item{X178}{Temperatures on the day 178 of a year} #' \item{X179}{Temperatures on the day 179 of a year} #' \item{X180}{Temperatures on the day 180 of a year} #' \item{X181}{Temperatures on the day 181 of a year} #' \item{X182}{Temperatures on the day 182 of a year} #' \item{X183}{Temperatures on the day 183 of a year} #' \item{X184}{Temperatures on the day 184 of a year} #' \item{X185}{Temperatures on the day 185 of a year} #' \item{X186}{Temperatures on the day 186 of a year} #' \item{X187}{Temperatures on the day 187 of a year} #' \item{X188}{Temperatures on the day 188 of a year} #' \item{X189}{Temperatures on the day 189 of a year} #' \item{X190}{Temperatures on the day 190 of a year} #' \item{X191}{Temperatures on the day 191 of a year} #' \item{X192}{Temperatures on the day 192 of a year} #' \item{X193}{Temperatures on the day 193 of a year} #' \item{X194}{Temperatures on the day 194 of a year} #' \item{X195}{Temperatures on the day 195 of a year} #' \item{X196}{Temperatures on the day 196 of a year} #' \item{X197}{Temperatures on the day 197 of a year} #' \item{X198}{Temperatures on the day 198 of a year} #' \item{X199}{Temperatures on the day 199 of a year} #' \item{X200}{Temperatures on the day 200 of a year} #' \item{X201}{Temperatures on the day 201 of a year} #' \item{X202}{Temperatures on the day 202 of a year} #' \item{X203}{Temperatures on the day 203 of a year} #' \item{X204}{Temperatures on the day 204 of a year} #' \item{X205}{Temperatures on the day 205 of a year} #' \item{X206}{Temperatures on the day 206 of a year} #' \item{X207}{Temperatures on the day 207 of a year} #' \item{X208}{Temperatures on the day 208 of a year} #' \item{X209}{Temperatures on the day 209 of a year} #' \item{X210}{Temperatures on the day 210 of a year} #' \item{X211}{Temperatures on the day 211 of a year} #' \item{X212}{Temperatures on the day 212 of a year} #' \item{X213}{Temperatures on the day 213 of a year} #' \item{X214}{Temperatures on the day 214 of a year} #' \item{X215}{Temperatures on the day 215 of a year} #' \item{X216}{Temperatures on the day 216 of a year} #' \item{X217}{Temperatures on the day 217 of a year} #' \item{X218}{Temperatures on the day 218 of a year} #' \item{X219}{Temperatures on the day 219 of a year} #' \item{X220}{Temperatures on the day 220 of a year} #' \item{X221}{Temperatures on the day 221 of a year} #' \item{X222}{Temperatures on the day 222 of a year} #' \item{X223}{Temperatures on the day 223 of a year} #' \item{X224}{Temperatures on the day 224 of a year} #' \item{X225}{Temperatures on the day 225 of a year} #' \item{X226}{Temperatures on the day 226 of a year} #' \item{X227}{Temperatures on the day 227 of a year} #' \item{X228}{Temperatures on the day 228 of a year} #' \item{X229}{Temperatures on the day 229 of a year} #' \item{X230}{Temperatures on the day 230 of a year} #' \item{X231}{Temperatures on the day 231 of a year} #' \item{X232}{Temperatures on the day 232 of a year} #' \item{X233}{Temperatures on the day 233 of a year} #' \item{X234}{Temperatures on the day 234 of a year} #' \item{X235}{Temperatures on the day 235 of a year} #' \item{X236}{Temperatures on the day 236 of a year} #' \item{X237}{Temperatures on the day 237 of a year} #' \item{X238}{Temperatures on the day 238 of a year} #' \item{X239}{Temperatures on the day 239 of a year} #' \item{X240}{Temperatures on the day 240 of a year} #' \item{X241}{Temperatures on the day 241 of a year} #' \item{X242}{Temperatures on the day 242 of a year} #' \item{X243}{Temperatures on the day 243 of a year} #' \item{X244}{Temperatures on the day 244 of a year} #' \item{X245}{Temperatures on the day 245 of a year} #' \item{X246}{Temperatures on the day 246 of a year} #' \item{X247}{Temperatures on the day 247 of a year} #' \item{X248}{Temperatures on the day 248 of a year} #' \item{X249}{Temperatures on the day 249 of a year} #' \item{X250}{Temperatures on the day 250 of a year} #' \item{X251}{Temperatures on the day 251 of a year} #' \item{X252}{Temperatures on the day 252 of a year} #' \item{X253}{Temperatures on the day 253 of a year} #' \item{X254}{Temperatures on the day 254 of a year} #' \item{X255}{Temperatures on the day 255 of a year} #' \item{X256}{Temperatures on the day 256 of a year} #' \item{X257}{Temperatures on the day 257 of a year} #' \item{X258}{Temperatures on the day 258 of a year} #' \item{X259}{Temperatures on the day 259 of a year} #' \item{X260}{Temperatures on the day 260 of a year} #' \item{X261}{Temperatures on the day 261 of a year} #' \item{X262}{Temperatures on the day 262 of a year} #' \item{X263}{Temperatures on the day 263 of a year} #' \item{X264}{Temperatures on the day 264 of a year} #' \item{X265}{Temperatures on the day 265 of a year} #' \item{X266}{Temperatures on the day 266 of a year} #' \item{X267}{Temperatures on the day 267 of a year} #' \item{X268}{Temperatures on the day 268 of a year} #' \item{X269}{Temperatures on the day 269 of a year} #' \item{X270}{Temperatures on the day 270 of a year} #' \item{X271}{Temperatures on the day 271 of a year} #' \item{X272}{Temperatures on the day 272 of a year} #' \item{X273}{Temperatures on the day 273 of a year} #' \item{X274}{Temperatures on the day 274 of a year} #' \item{X275}{Temperatures on the day 275 of a year} #' \item{X276}{Temperatures on the day 276 of a year} #' \item{X277}{Temperatures on the day 277 of a year} #' \item{X278}{Temperatures on the day 278 of a year} #' \item{X279}{Temperatures on the day 279 of a year} #' \item{X280}{Temperatures on the day 280 of a year} #' \item{X281}{Temperatures on the day 281 of a year} #' \item{X282}{Temperatures on the day 282 of a year} #' \item{X283}{Temperatures on the day 283 of a year} #' \item{X284}{Temperatures on the day 284 of a year} #' \item{X285}{Temperatures on the day 285 of a year} #' \item{X286}{Temperatures on the day 286 of a year} #' \item{X287}{Temperatures on the day 287 of a year} #' \item{X288}{Temperatures on the day 288 of a year} #' \item{X289}{Temperatures on the day 289 of a year} #' \item{X290}{Temperatures on the day 290 of a year} #' \item{X291}{Temperatures on the day 291 of a year} #' \item{X292}{Temperatures on the day 292 of a year} #' \item{X293}{Temperatures on the day 293 of a year} #' \item{X294}{Temperatures on the day 294 of a year} #' \item{X295}{Temperatures on the day 295 of a year} #' \item{X296}{Temperatures on the day 296 of a year} #' \item{X297}{Temperatures on the day 297 of a year} #' \item{X298}{Temperatures on the day 298 of a year} #' \item{X299}{Temperatures on the day 299 of a year} #' \item{X300}{Temperatures on the day 300 of a year} #' \item{X301}{Temperatures on the day 301 of a year} #' \item{X302}{Temperatures on the day 302 of a year} #' \item{X303}{Temperatures on the day 303 of a year} #' \item{X304}{Temperatures on the day 304 of a year} #' \item{X305}{Temperatures on the day 305 of a year} #' \item{X306}{Temperatures on the day 306 of a year} #' \item{X307}{Temperatures on the day 307 of a year} #' \item{X308}{Temperatures on the day 308 of a year} #' \item{X309}{Temperatures on the day 309 of a year} #' \item{X310}{Temperatures on the day 310 of a year} #' \item{X311}{Temperatures on the day 311 of a year} #' \item{X312}{Temperatures on the day 312 of a year} #' \item{X313}{Temperatures on the day 313 of a year} #' \item{X314}{Temperatures on the day 314 of a year} #' \item{X315}{Temperatures on the day 315 of a year} #' \item{X316}{Temperatures on the day 316 of a year} #' \item{X317}{Temperatures on the day 317 of a year} #' \item{X318}{Temperatures on the day 318 of a year} #' \item{X319}{Temperatures on the day 319 of a year} #' \item{X320}{Temperatures on the day 320 of a year} #' \item{X321}{Temperatures on the day 321 of a year} #' \item{X322}{Temperatures on the day 322 of a year} #' \item{X323}{Temperatures on the day 323 of a year} #' \item{X324}{Temperatures on the day 324 of a year} #' \item{X325}{Temperatures on the day 325 of a year} #' \item{X326}{Temperatures on the day 326 of a year} #' \item{X327}{Temperatures on the day 327 of a year} #' \item{X328}{Temperatures on the day 328 of a year} #' \item{X329}{Temperatures on the day 329 of a year} #' \item{X330}{Temperatures on the day 330 of a year} #' \item{X331}{Temperatures on the day 331 of a year} #' \item{X332}{Temperatures on the day 332 of a year} #' \item{X333}{Temperatures on the day 333 of a year} #' \item{X334}{Temperatures on the day 334 of a year} #' \item{X335}{Temperatures on the day 335 of a year} #' \item{X336}{Temperatures on the day 336 of a year} #' \item{X337}{Temperatures on the day 337 of a year} #' \item{X338}{Temperatures on the day 338 of a year} #' \item{X339}{Temperatures on the day 339 of a year} #' \item{X340}{Temperatures on the day 340 of a year} #' \item{X341}{Temperatures on the day 341 of a year} #' \item{X342}{Temperatures on the day 342 of a year} #' \item{X343}{Temperatures on the day 343 of a year} #' \item{X344}{Temperatures on the day 344 of a year} #' \item{X345}{Temperatures on the day 345 of a year} #' \item{X346}{Temperatures on the day 346 of a year} #' \item{X347}{Temperatures on the day 347 of a year} #' \item{X348}{Temperatures on the day 348 of a year} #' \item{X349}{Temperatures on the day 349 of a year} #' \item{X350}{Temperatures on the day 350 of a year} #' \item{X351}{Temperatures on the day 351 of a year} #' \item{X352}{Temperatures on the day 352 of a year} #' \item{X353}{Temperatures on the day 353 of a year} #' \item{X354}{Temperatures on the day 354 of a year} #' \item{X355}{Temperatures on the day 355 of a year} #' \item{X356}{Temperatures on the day 356 of a year} #' \item{X357}{Temperatures on the day 357 of a year} #' \item{X358}{Temperatures on the day 358 of a year} #' \item{X359}{Temperatures on the day 359 of a year} #' \item{X360}{Temperatures on the day 360 of a year} #' \item{X361}{Temperatures on the day 361 of a year} #' \item{X362}{Temperatures on the day 362 of a year} #' \item{X363}{Temperatures on the day 363 of a year} #' \item{X364}{Temperatures on the day 364 of a year} #' \item{X365}{Temperatures on the day 365 of a year} #' \item{X366}{Temperatures on the day 366 of a year} #' } #' @source \url{http://climexp.knmi.nl/start.cgi} #' @export "LJ_daily_temperatures"
##################################################### ## Testing and Summary stats methods for internal use in tableby ########################################### #' tableby Summary Statistics Functions #' #' A collection of functions that will report summary statistics. To create a custom function, #' consider using a function with all three arguments and \code{...}. See the \code{\link{tableby}} vignette #' for an example. #' #' @param x Usually a vector. #' @param na.rm Should NAs be removed? #' @param weights A vector of weights. #' @param levels A vector of levels that character \code{x}s should have. #' @param times A vector of times to use for survival summaries. #' @param by a vector of the by-values. #' @param by.levels a vector of the levels of \code{by}. #' @param conf.level Numeric, denoting what confidence level to use for confidence intervals. #' @param ... Other arguments. #' @return Usually a vector of the appropriate numbers. #' @details Not all these functions are exported, in order to avoid conflicting NAMESPACES. #' Note also that the functions prefixed with \code{"arsenal_"} can be referred to by their short names #' (e.g., \code{"min"} for \code{"arsenal_min"}). #' @seealso \code{\link{includeNA}}, \code{\link{tableby.control}} #' @name tableby.stats NULL #> NULL get_stat_function <- function(x) switch(x, sum = , min = , max = , range = , mean = , sd = , var = , median = paste0("arsenal_", x), x) #' @rdname tableby.stats arsenal_sum <- function(x, na.rm=TRUE, ...) { y <- if(na.rm && allNA(x)) { NA_real_ } else { sum(x, na.rm=na.rm) } as.tbstat(y) # unclear what the sum of dates should be? } #' @rdname tableby.stats arsenal_min <- function(x, na.rm=TRUE, ...) { y <- if(na.rm && allNA(x)) { NA_real_ } else { min(x, na.rm=na.rm) } as.tbstat(y, oldClass = if(is.Date(x)) "Date" else NULL) } #' @rdname tableby.stats arsenal_max <- function(x, na.rm=TRUE, ...) { y <- if(na.rm && allNA(x)) { NA_real_ } else { max(x, na.rm=na.rm) } as.tbstat(y, oldClass = if(is.Date(x)) "Date" else NULL) } #' @rdname tableby.stats arsenal_mean <- function(x, na.rm=TRUE, weights = NULL, ...) { y <- if(na.rm && allNA(x)) { NA_real_ } else { wtd.mean(x, weights=weights, na.rm=na.rm) } as.tbstat(y, oldClass = if(is.Date(x)) "Date" else NULL) } #' @rdname tableby.stats arsenal_sd <- function(x, na.rm=TRUE, weights = NULL, ...) { y <- if(na.rm && allNA(x)) { NA_real_ } else { s <- sqrt(wtd.var(x, weights=weights, na.rm=na.rm)) if(is.Date(x)) list(as.difftime(s, units = "days")) else s } as.tbstat(y) } #' @rdname tableby.stats arsenal_var <- function(x, na.rm=TRUE, weights = NULL, ...) { y <- if(na.rm && allNA(x)) { NA_real_ } else { wtd.var(x, weights=weights, na.rm=na.rm) # if(is.Date(x)) as.difftime(s, units = "days") else s } as.tbstat(y) } #' @rdname tableby.stats #' @export meansd <- function(x, na.rm=TRUE, weights = NULL, ...) { y <- if(na.rm && allNA(x)) { NA_real_ } else { m <- wtd.mean(x, weights=weights, na.rm=na.rm) s <- sqrt(wtd.var(x, weights=weights, na.rm=na.rm)) if(is.Date(x)) list(as.character(m), as.difftime(s, units = "days")) else c(m, s) } as.tbstat(y, parens = c("(", ")")) } #' @rdname tableby.stats #' @export meanCI <- function(x, na.rm=TRUE, weights = NULL, conf.level = 0.95, ...) { y <- if(!is.null(weights) || (na.rm && allNA(x))) { NA_real_ } else { if(na.rm) x <- x[!is.na(x)] s <- stats::sd(x, na.rm = na.rm) m <- mean(x, na.rm = na.rm) n <- length(x) a <- (1 - conf.level)/2 c(m, m + stats::qt(c(a, 1 - a), df = n - 1) * s / sqrt(n)) } as.tbstat(y, oldClass = if(is.Date(x)) "Date" else NULL, parens = c("(", ")"), sep2 = ", ") } #' @rdname tableby.stats #' @export medianrange <- function(x, na.rm=TRUE, weights = NULL, ...) { y <- if(na.rm && allNA(x)) NA_real_ else wtd.quantile(x, probs=c(0.5, 0, 1), na.rm=na.rm, weights=weights) as.tbstat(y, oldClass = if(is.Date(x)) "Date" else NULL, parens = c("(", ")"), sep2 = ", ") } #' @rdname tableby.stats #' @export medianmad <- function(x, na.rm=TRUE, weights = NULL, ...) { y <- if(!is.null(weights) || (na.rm && allNA(x))) { NA_real_ } else { m <- stats::median(x, na.rm=na.rm) s <- stats::mad(x, na.rm=na.rm, constant = 1) if(is.Date(x)) list(as.character(m), as.difftime(s, units = "days")) else c(m, s) } as.tbstat(y, parens = c("(", ")")) } #' @rdname tableby.stats arsenal_median <- function(x, na.rm=TRUE, weights = NULL, ...) { y <- if(na.rm && allNA(x)) { NA_real_ } else if(is.Date(x)) { as.Date(wtd.quantile(as.integer(x), weights=weights, probs=0.5, na.rm=na.rm), origin="1970/01/01") } else { wtd.quantile(x, weights=weights, probs=0.5, na.rm=na.rm) } as.tbstat(y, oldClass = if(is.Date(x)) "Date" else NULL) } #' @rdname tableby.stats arsenal_range <- function(x, na.rm=TRUE, ...) { y <- if(na.rm && allNA(x)) { NA_real_ } else { range(x, na.rm=na.rm) } as.tbstat(y, oldClass = if(is.Date(x)) "Date" else NULL, sep = " - ") } #' @rdname tableby.stats #' @export gmean <- function(x, na.rm=TRUE, weights = NULL, ...) { y <- if((na.rm && allNA(x)) || any(x < 0, na.rm = TRUE) || is.Date(x)) { NA_real_ } else { exp(wtd.mean(log(x), weights=weights, na.rm=na.rm)) } as.tbstat(y) } #' @rdname tableby.stats #' @export gsd <- function(x, na.rm=TRUE, weights = NULL, ...) { y <- if((na.rm && allNA(x)) || any(x <= 0, na.rm = TRUE) || is.Date(x)) { NA_real_ } else { n <- sum(!is.na(x)) exp(sqrt(wtd.var(log(x), weights = weights, na.rm = na.rm) * (n-1)/n)) } as.tbstat(y) } #' @rdname tableby.stats #' @export gmeansd <- function(x, na.rm=TRUE, weights = NULL, ...) { y <- if((na.rm && allNA(x)) || any(x < 0, na.rm = TRUE) || is.Date(x)) { NA_real_ } else { m <- exp(wtd.mean(log(x), weights=weights, na.rm=na.rm)) n <- sum(!is.na(x)) s <- if(any(x == 0, na.rm = TRUE)) { NA_real_ } else exp(sqrt(wtd.var(log(x), weights = weights, na.rm = na.rm) * (n-1)/n)) c(m, s) } as.tbstat(y, parens = c("(", ")")) } #' @rdname tableby.stats #' @export gmeanCI <- function(x, na.rm=TRUE, weights = NULL, conf.level = 0.95, ...) { y <- if(!is.null(weights) || (na.rm && allNA(x)) || any(x < 0, na.rm = TRUE) || is.Date(x)) { NA_real_ } else { if(na.rm) x <- x[!is.na(x)] n <- length(x) s <- sqrt(stats::var(log(x), na.rm = na.rm) * (n-1)/n) m <- mean(log(x), na.rm = na.rm) a <- (1 - conf.level)/2 ci <- if(any(x == 0, na.rm = TRUE)) NA_real_ else m + stats::qt(c(a, 1 - a), df = n - 1) * s / sqrt(n) exp(c(m, ci)) } as.tbstat(y, parens = c("(", ")"), sep2 = ", ") } ## survival stats #' @rdname tableby.stats #' @export Nevents <- function(x, na.rm = TRUE, weights = NULL, ...) { y <- if(na.rm && allNA(x)) { NA_real_ } else { mat <- summary(survival::survfit(x ~ 1, weights = weights))$table as.numeric(mat["events"]) } as.countpct(y) } ## Median survival #' @rdname tableby.stats #' @export medSurv <- function(x, na.rm = TRUE, weights = NULL, ...) { y <- if(na.rm && allNA(x)) { NA_real_ } else { mat <- summary(survival::survfit(x ~ 1, weights = weights))$table as.numeric(mat["median"]) # if we don't hit the median, or if all obs are censors, this is NA } as.tbstat(y) } #' @rdname tableby.stats #' @export NeventsSurv <- function(x, na.rm = TRUE, weights = NULL, times=1:5, ...) { y <- if(na.rm && allNA(x)) { matrix(NA_real_, nrow = 1, ncol = length(times)) } else { xsumm <- summary(survival::survfit(x ~ 1, weights = weights), times=times) t(cbind(cumsum(xsumm$n.event), 100*xsumm$surv)) } out <- stats::setNames(as.list(as.data.frame(y)), paste0("time = ", times)) as.tbstat_multirow(lapply(out, as.countpct, parens = c("(", ")"), which.pct = 2L)) } #' @rdname tableby.stats #' @export NriskSurv <- function(x, na.rm = TRUE, weights = NULL, times=1:5, ...) { y <- if(na.rm && allNA(x)) { matrix(NA_real_, nrow = 1, ncol = length(times)) } else { xsumm <- summary(survival::survfit(x ~ 1, weights = weights), times=times) t(cbind(xsumm$n.risk, 100*xsumm$surv)) } out <- stats::setNames(as.list(as.data.frame(y)), paste0("time = ", times)) as.tbstat_multirow(lapply(out, as.countpct, parens = c("(", ")"), which.pct = 2L)) } #' @rdname tableby.stats #' @export Nrisk <- function(x, na.rm = TRUE, weights = NULL, times=1:5, ...) { y <- if(na.rm && allNA(x)) { rep(NA_real_, times = length(times)) } else summary(survival::survfit(x ~ 1, weights = weights), times=times)$n.risk out <- stats::setNames(as.list(y), paste0("time = ", times)) as.tbstat_multirow(lapply(out, as.countpct)) } #' @rdname tableby.stats #' @export medTime <- function(x, na.rm = TRUE, weights = NULL, ...) { y <- if(na.rm && allNA(x)) { NA_real_ } else { x[, 2] <- 1 - x[, 2] # censor events instead mat <- summary(survival::survfit(x ~ 1, weights = weights))$table as.numeric(mat["median"]) # if we don't hit the median, or if all obs are events, this is NA } as.tbstat(y) } ## quantiles #' @rdname tableby.stats #' @export q1q3 <- function(x, na.rm=TRUE, weights = NULL, ...) { y <- if(na.rm && allNA(x)) { NA_real_ } else wtd.quantile(x, weights=weights, probs=c(0.25, .75), na.rm=na.rm) as.tbstat(y, oldClass = if(is.Date(x)) "Date" else NULL, sep = ", ") } #' @rdname tableby.stats #' @export medianq1q3 <- function(x, na.rm=TRUE, weights = NULL, ...) { y <- if(na.rm && allNA(x)) { NA_real_ } else wtd.quantile(x, weights=weights, probs=c(0.5, 0.25, 0.75), na.rm=na.rm) as.tbstat(y, oldClass = if(is.Date(x)) "Date" else NULL, parens = c("(", ")"), sep2 = ", ") } #' @rdname tableby.stats #' @export iqr <- function(x, na.rm=TRUE, weights = NULL, ...) { y <- if(na.rm && allNA(x)) { NA_real_ } else { s <- diff(wtd.quantile(x, weights=weights, probs=c(0.25, 0.75), na.rm=na.rm)) if(is.Date(x)) list(as.difftime(s, units = "days")) else s } as.tbstat(y) } ## Count of missings: always show missings #' @rdname tableby.stats #' @export Nmiss <- function(x, na.rm=TRUE, weights = NULL, ...) { if(is.null(weights)) weights <- rep(1, length(x)) as.countpct(sum(weights[is.na(x)])) } ## Nmiss2 make similar, but in tableby, always keep nmiss, ## even if there are no missings #' @rdname tableby.stats #' @export Nmiss2 <- Nmiss ## count of complete samples #' @rdname tableby.stats #' @export N <- function(x, na.rm=TRUE, weights = NULL, ...) { if(is.null(weights)) weights <- rep(1, length(x)) as.countpct(sum(weights[!is.na(x)])) } #' @rdname tableby.stats #' @export Npct <- function(x, levels=NULL, by, by.levels=sort(unique(by)), na.rm=TRUE, weights = NULL, ...) { if(is.null(levels)) levels <- sort(unique(x)) if(na.rm) { idx <- !is.na(x) & !is.na(by) if(!is.null(weights)) idx <- idx & !is.na(weights) x <- x[idx] by <- by[idx] weights <- weights[idx] } tmp <- wtd.table(factor(by, levels = by.levels), weights = weights) wtbl <- c(tmp, Total = sum(tmp)) lapply(wtbl, function(elt) as.countpct(c(elt, 100*elt/sum(tmp)), parens = c("(", ")"), pct = "%", which.pct = 2L)) } ## count within group variable #' @rdname tableby.stats count <- function (x, levels=NULL, na.rm = TRUE, weights = NULL, ...) { if(is.null(levels)) levels <- sort(unique(x)) as.tbstat_multirow(lapply(as.list(wtd.table(factor(x[!is.na(x)], levels = levels), weights = weights[!is.na(x)])), as.countpct)) } ## count (pct) where pct is within group variable total #' @rdname tableby.stats #' @export countpct <- function(x, levels=NULL, na.rm=TRUE, weights = NULL, ...) { if(is.null(levels)) levels <- sort(unique(x)) wtbl <- wtd.table(factor(x[!is.na(x)], levels=levels), weights=weights[!is.na(x)]) as.tbstat_multirow(lapply(Map(c, wtbl, if(any(wtbl > 0)) 100*wtbl/sum(wtbl) else rep(list(NULL), times = length(wtbl))), as.countpct, parens = c("(", ")"), pct = "%", which.pct = 2L)) } #' @rdname tableby.stats #' @export countN <- function(x, levels=NULL, na.rm=TRUE, weights = NULL, ...) { if(is.null(levels)) levels <- sort(unique(x)) wtbl <- wtd.table(factor(x[!is.na(x)], levels=levels), weights=weights[!is.na(x)]) n <- sum(wtbl) as.tbstat_multirow(lapply(Map(c, wtbl, rep(n, times = length(wtbl))), as.countpct, sep = "/")) } transpose_list <- function(x, levels, by.levels) stats::setNames(lapply(by.levels, function(i) as.tbstat_multirow(stats::setNames(lapply(x, "[[", i), levels))), by.levels) #' @rdname tableby.stats #' @export countrowpct <- function(x, levels=NULL, by, by.levels=sort(unique(by)), na.rm=TRUE, weights = NULL, ...) { if(is.null(levels)) levels <- sort(unique(x)) if(na.rm) { idx <- !is.na(x) & !is.na(by) if(!is.null(weights)) idx <- idx & !is.na(weights) x <- x[idx] by <- by[idx] weights <- weights[idx] } wtbls <- lapply(levels, function(L) { tmp <- wtd.table(factor(by[x == L], levels = by.levels), weights = weights[x == L]) wtbl <- c(tmp, Total = sum(tmp)) lapply(wtbl, function(elt) as.countpct(c(elt, 100*elt/sum(tmp)), parens = c("(", ")"), pct = "%", which.pct = 2L)) }) transpose_list(wtbls, levels, c(by.levels, "Total")) } #' @rdname tableby.stats #' @export countcellpct <- function(x, levels=NULL, by, by.levels=sort(unique(by)), na.rm=TRUE, weights = NULL, ...) { if(is.null(levels)) levels <- sort(unique(x)) if(na.rm) { idx <- !is.na(x) & !is.na(by) if(!is.null(weights)) idx <- idx & !is.na(weights) x <- x[idx] by <- by[idx] weights <- weights[idx] } tot <- sum(vapply(levels, function(L) { sum(wtd.table(factor(by[x == L], levels = by.levels), weights = weights[x == L])) }, numeric(1))) wtbls <- lapply(levels, function(L) { tmp <- wtd.table(factor(by[x == L], levels = by.levels), weights = weights[x == L]) wtbl <- c(tmp, Total = sum(tmp)) lapply(wtbl, function(elt) as.countpct(c(elt, 100*elt/tot), parens = c("(", ")"), pct = "%", which.pct = 2L)) }) transpose_list(wtbls, levels, c(by.levels, "Total")) } get_binom_est_ci <- function(x, tot, setNA, conf.level = 0.95) { if(setNA) return(NA_real_) b <- stats::binom.test(x, tot, conf.level = conf.level) unname(c(b$estimate, b$conf.int)) } #' @rdname tableby.stats #' @export binomCI <- function(x, levels=NULL, na.rm=TRUE, weights = NULL, conf.level = 0.95, ...) { if(is.null(levels)) levels <- sort(unique(x)) wtbl <- wtd.table(factor(x[!is.na(x)], levels=levels), weights=weights[!is.na(x)]) ests <- lapply(wtbl, get_binom_est_ci, tot = sum(wtbl), setNA = !is.null(weights), conf.level = conf.level) as.tbstat_multirow(lapply(ests, as.tbstat, parens = c("(", ")"), sep2 = ", ")) } #' @rdname tableby.stats #' @export rowbinomCI <- function(x, levels=NULL, by, by.levels=sort(unique(by)), na.rm=TRUE, weights = NULL, conf.level = 0.95, ...) { if(is.null(levels)) levels <- sort(unique(x)) wts <- !is.null(weights) if(na.rm) { idx <- !is.na(x) & !is.na(by) if(wts) idx <- idx & !is.na(weights) x <- x[idx] by <- by[idx] weights <- weights[idx] } wtbls <- lapply(levels, function(L) { tmp <- wtd.table(factor(by[x == L], levels = by.levels), weights = weights[x == L]) wtbl <- c(tmp, Total = sum(tmp)) wtbl <- lapply(wtbl, get_binom_est_ci, tot = sum(tmp), setNA = wts, conf.level = conf.level) lapply(wtbl, as.tbstat, parens = c("(", ")"), sep2 = ", ") }) # as.tbstat_multirow(lapply(wtbl, f)) transpose_list(wtbls, levels, c(by.levels, "Total")) } ######## internal functions that we use above ######## wtd.table <- function(x, weights = NULL, na.rm = TRUE) { if(!length(weights)) return(table(x)) tmp <- tapply(weights, x, sum, na.rm = na.rm) tmp[is.na(tmp)] <- 0 # (tapply(default = 0) would be enough in R >= 3.4, but we'll make this backwards-compatible) tmp } wtd.mean <- function(x, weights = NULL, na.rm = TRUE) { if(!length(weights)) return(mean(x, na.rm = na.rm)) if(na.rm) { idx <- !is.na(x + weights) x <- x[idx] weights <- weights[idx] } sum(weights * x)/sum(weights) } wtd.quantile <- function(x, weights=NULL, probs=c(0,0.25,0.5,0.75,1), na.rm=TRUE) { if(!length(weights)) return(stats::quantile(as.numeric(x), probs = probs, na.rm = na.rm)) if(any(probs < 0) || any(probs > 1)) stop("Probabilities must be between 0 and 1 inclusive") wts <- wtd.table(x, weights, na.rm = na.rm) x <- if(is.Date(x)) as.numeric(as.Date(names(wts))) else as.numeric(names(wts)) n <- sum(wts) order <- 1 + (n - 1) * probs low <- pmax(floor(order), 1) high <- pmin(low + 1, n) order <- order%%1 allq <- stats::approx(cumsum(wts), x, xout = c(low, high), method = "constant", f = 1, rule = 2)$y k <- length(probs) stats::setNames((1 - order) * allq[1:k] + order * allq[-(1:k)], probs) } wtd.var <- function(x, weights = NULL, na.rm=TRUE, method = c("unbiased", "ML")) { method <- match.arg(method) if(!length(weights)) return(stats::var(x, na.rm = na.rm)) if(na.rm) { idx <- !is.na(x + weights) x <- x[idx] weights <- weights[idx] } if(length(x) < 2) return(NA_real_) as.numeric(stats::cov.wt(matrix(x, ncol = 1), weights, method = method)$cov) }
/R/tableby.stats.R
no_license
umarfaruk9/arsenal
R
false
false
17,383
r
##################################################### ## Testing and Summary stats methods for internal use in tableby ########################################### #' tableby Summary Statistics Functions #' #' A collection of functions that will report summary statistics. To create a custom function, #' consider using a function with all three arguments and \code{...}. See the \code{\link{tableby}} vignette #' for an example. #' #' @param x Usually a vector. #' @param na.rm Should NAs be removed? #' @param weights A vector of weights. #' @param levels A vector of levels that character \code{x}s should have. #' @param times A vector of times to use for survival summaries. #' @param by a vector of the by-values. #' @param by.levels a vector of the levels of \code{by}. #' @param conf.level Numeric, denoting what confidence level to use for confidence intervals. #' @param ... Other arguments. #' @return Usually a vector of the appropriate numbers. #' @details Not all these functions are exported, in order to avoid conflicting NAMESPACES. #' Note also that the functions prefixed with \code{"arsenal_"} can be referred to by their short names #' (e.g., \code{"min"} for \code{"arsenal_min"}). #' @seealso \code{\link{includeNA}}, \code{\link{tableby.control}} #' @name tableby.stats NULL #> NULL get_stat_function <- function(x) switch(x, sum = , min = , max = , range = , mean = , sd = , var = , median = paste0("arsenal_", x), x) #' @rdname tableby.stats arsenal_sum <- function(x, na.rm=TRUE, ...) { y <- if(na.rm && allNA(x)) { NA_real_ } else { sum(x, na.rm=na.rm) } as.tbstat(y) # unclear what the sum of dates should be? } #' @rdname tableby.stats arsenal_min <- function(x, na.rm=TRUE, ...) { y <- if(na.rm && allNA(x)) { NA_real_ } else { min(x, na.rm=na.rm) } as.tbstat(y, oldClass = if(is.Date(x)) "Date" else NULL) } #' @rdname tableby.stats arsenal_max <- function(x, na.rm=TRUE, ...) { y <- if(na.rm && allNA(x)) { NA_real_ } else { max(x, na.rm=na.rm) } as.tbstat(y, oldClass = if(is.Date(x)) "Date" else NULL) } #' @rdname tableby.stats arsenal_mean <- function(x, na.rm=TRUE, weights = NULL, ...) { y <- if(na.rm && allNA(x)) { NA_real_ } else { wtd.mean(x, weights=weights, na.rm=na.rm) } as.tbstat(y, oldClass = if(is.Date(x)) "Date" else NULL) } #' @rdname tableby.stats arsenal_sd <- function(x, na.rm=TRUE, weights = NULL, ...) { y <- if(na.rm && allNA(x)) { NA_real_ } else { s <- sqrt(wtd.var(x, weights=weights, na.rm=na.rm)) if(is.Date(x)) list(as.difftime(s, units = "days")) else s } as.tbstat(y) } #' @rdname tableby.stats arsenal_var <- function(x, na.rm=TRUE, weights = NULL, ...) { y <- if(na.rm && allNA(x)) { NA_real_ } else { wtd.var(x, weights=weights, na.rm=na.rm) # if(is.Date(x)) as.difftime(s, units = "days") else s } as.tbstat(y) } #' @rdname tableby.stats #' @export meansd <- function(x, na.rm=TRUE, weights = NULL, ...) { y <- if(na.rm && allNA(x)) { NA_real_ } else { m <- wtd.mean(x, weights=weights, na.rm=na.rm) s <- sqrt(wtd.var(x, weights=weights, na.rm=na.rm)) if(is.Date(x)) list(as.character(m), as.difftime(s, units = "days")) else c(m, s) } as.tbstat(y, parens = c("(", ")")) } #' @rdname tableby.stats #' @export meanCI <- function(x, na.rm=TRUE, weights = NULL, conf.level = 0.95, ...) { y <- if(!is.null(weights) || (na.rm && allNA(x))) { NA_real_ } else { if(na.rm) x <- x[!is.na(x)] s <- stats::sd(x, na.rm = na.rm) m <- mean(x, na.rm = na.rm) n <- length(x) a <- (1 - conf.level)/2 c(m, m + stats::qt(c(a, 1 - a), df = n - 1) * s / sqrt(n)) } as.tbstat(y, oldClass = if(is.Date(x)) "Date" else NULL, parens = c("(", ")"), sep2 = ", ") } #' @rdname tableby.stats #' @export medianrange <- function(x, na.rm=TRUE, weights = NULL, ...) { y <- if(na.rm && allNA(x)) NA_real_ else wtd.quantile(x, probs=c(0.5, 0, 1), na.rm=na.rm, weights=weights) as.tbstat(y, oldClass = if(is.Date(x)) "Date" else NULL, parens = c("(", ")"), sep2 = ", ") } #' @rdname tableby.stats #' @export medianmad <- function(x, na.rm=TRUE, weights = NULL, ...) { y <- if(!is.null(weights) || (na.rm && allNA(x))) { NA_real_ } else { m <- stats::median(x, na.rm=na.rm) s <- stats::mad(x, na.rm=na.rm, constant = 1) if(is.Date(x)) list(as.character(m), as.difftime(s, units = "days")) else c(m, s) } as.tbstat(y, parens = c("(", ")")) } #' @rdname tableby.stats arsenal_median <- function(x, na.rm=TRUE, weights = NULL, ...) { y <- if(na.rm && allNA(x)) { NA_real_ } else if(is.Date(x)) { as.Date(wtd.quantile(as.integer(x), weights=weights, probs=0.5, na.rm=na.rm), origin="1970/01/01") } else { wtd.quantile(x, weights=weights, probs=0.5, na.rm=na.rm) } as.tbstat(y, oldClass = if(is.Date(x)) "Date" else NULL) } #' @rdname tableby.stats arsenal_range <- function(x, na.rm=TRUE, ...) { y <- if(na.rm && allNA(x)) { NA_real_ } else { range(x, na.rm=na.rm) } as.tbstat(y, oldClass = if(is.Date(x)) "Date" else NULL, sep = " - ") } #' @rdname tableby.stats #' @export gmean <- function(x, na.rm=TRUE, weights = NULL, ...) { y <- if((na.rm && allNA(x)) || any(x < 0, na.rm = TRUE) || is.Date(x)) { NA_real_ } else { exp(wtd.mean(log(x), weights=weights, na.rm=na.rm)) } as.tbstat(y) } #' @rdname tableby.stats #' @export gsd <- function(x, na.rm=TRUE, weights = NULL, ...) { y <- if((na.rm && allNA(x)) || any(x <= 0, na.rm = TRUE) || is.Date(x)) { NA_real_ } else { n <- sum(!is.na(x)) exp(sqrt(wtd.var(log(x), weights = weights, na.rm = na.rm) * (n-1)/n)) } as.tbstat(y) } #' @rdname tableby.stats #' @export gmeansd <- function(x, na.rm=TRUE, weights = NULL, ...) { y <- if((na.rm && allNA(x)) || any(x < 0, na.rm = TRUE) || is.Date(x)) { NA_real_ } else { m <- exp(wtd.mean(log(x), weights=weights, na.rm=na.rm)) n <- sum(!is.na(x)) s <- if(any(x == 0, na.rm = TRUE)) { NA_real_ } else exp(sqrt(wtd.var(log(x), weights = weights, na.rm = na.rm) * (n-1)/n)) c(m, s) } as.tbstat(y, parens = c("(", ")")) } #' @rdname tableby.stats #' @export gmeanCI <- function(x, na.rm=TRUE, weights = NULL, conf.level = 0.95, ...) { y <- if(!is.null(weights) || (na.rm && allNA(x)) || any(x < 0, na.rm = TRUE) || is.Date(x)) { NA_real_ } else { if(na.rm) x <- x[!is.na(x)] n <- length(x) s <- sqrt(stats::var(log(x), na.rm = na.rm) * (n-1)/n) m <- mean(log(x), na.rm = na.rm) a <- (1 - conf.level)/2 ci <- if(any(x == 0, na.rm = TRUE)) NA_real_ else m + stats::qt(c(a, 1 - a), df = n - 1) * s / sqrt(n) exp(c(m, ci)) } as.tbstat(y, parens = c("(", ")"), sep2 = ", ") } ## survival stats #' @rdname tableby.stats #' @export Nevents <- function(x, na.rm = TRUE, weights = NULL, ...) { y <- if(na.rm && allNA(x)) { NA_real_ } else { mat <- summary(survival::survfit(x ~ 1, weights = weights))$table as.numeric(mat["events"]) } as.countpct(y) } ## Median survival #' @rdname tableby.stats #' @export medSurv <- function(x, na.rm = TRUE, weights = NULL, ...) { y <- if(na.rm && allNA(x)) { NA_real_ } else { mat <- summary(survival::survfit(x ~ 1, weights = weights))$table as.numeric(mat["median"]) # if we don't hit the median, or if all obs are censors, this is NA } as.tbstat(y) } #' @rdname tableby.stats #' @export NeventsSurv <- function(x, na.rm = TRUE, weights = NULL, times=1:5, ...) { y <- if(na.rm && allNA(x)) { matrix(NA_real_, nrow = 1, ncol = length(times)) } else { xsumm <- summary(survival::survfit(x ~ 1, weights = weights), times=times) t(cbind(cumsum(xsumm$n.event), 100*xsumm$surv)) } out <- stats::setNames(as.list(as.data.frame(y)), paste0("time = ", times)) as.tbstat_multirow(lapply(out, as.countpct, parens = c("(", ")"), which.pct = 2L)) } #' @rdname tableby.stats #' @export NriskSurv <- function(x, na.rm = TRUE, weights = NULL, times=1:5, ...) { y <- if(na.rm && allNA(x)) { matrix(NA_real_, nrow = 1, ncol = length(times)) } else { xsumm <- summary(survival::survfit(x ~ 1, weights = weights), times=times) t(cbind(xsumm$n.risk, 100*xsumm$surv)) } out <- stats::setNames(as.list(as.data.frame(y)), paste0("time = ", times)) as.tbstat_multirow(lapply(out, as.countpct, parens = c("(", ")"), which.pct = 2L)) } #' @rdname tableby.stats #' @export Nrisk <- function(x, na.rm = TRUE, weights = NULL, times=1:5, ...) { y <- if(na.rm && allNA(x)) { rep(NA_real_, times = length(times)) } else summary(survival::survfit(x ~ 1, weights = weights), times=times)$n.risk out <- stats::setNames(as.list(y), paste0("time = ", times)) as.tbstat_multirow(lapply(out, as.countpct)) } #' @rdname tableby.stats #' @export medTime <- function(x, na.rm = TRUE, weights = NULL, ...) { y <- if(na.rm && allNA(x)) { NA_real_ } else { x[, 2] <- 1 - x[, 2] # censor events instead mat <- summary(survival::survfit(x ~ 1, weights = weights))$table as.numeric(mat["median"]) # if we don't hit the median, or if all obs are events, this is NA } as.tbstat(y) } ## quantiles #' @rdname tableby.stats #' @export q1q3 <- function(x, na.rm=TRUE, weights = NULL, ...) { y <- if(na.rm && allNA(x)) { NA_real_ } else wtd.quantile(x, weights=weights, probs=c(0.25, .75), na.rm=na.rm) as.tbstat(y, oldClass = if(is.Date(x)) "Date" else NULL, sep = ", ") } #' @rdname tableby.stats #' @export medianq1q3 <- function(x, na.rm=TRUE, weights = NULL, ...) { y <- if(na.rm && allNA(x)) { NA_real_ } else wtd.quantile(x, weights=weights, probs=c(0.5, 0.25, 0.75), na.rm=na.rm) as.tbstat(y, oldClass = if(is.Date(x)) "Date" else NULL, parens = c("(", ")"), sep2 = ", ") } #' @rdname tableby.stats #' @export iqr <- function(x, na.rm=TRUE, weights = NULL, ...) { y <- if(na.rm && allNA(x)) { NA_real_ } else { s <- diff(wtd.quantile(x, weights=weights, probs=c(0.25, 0.75), na.rm=na.rm)) if(is.Date(x)) list(as.difftime(s, units = "days")) else s } as.tbstat(y) } ## Count of missings: always show missings #' @rdname tableby.stats #' @export Nmiss <- function(x, na.rm=TRUE, weights = NULL, ...) { if(is.null(weights)) weights <- rep(1, length(x)) as.countpct(sum(weights[is.na(x)])) } ## Nmiss2 make similar, but in tableby, always keep nmiss, ## even if there are no missings #' @rdname tableby.stats #' @export Nmiss2 <- Nmiss ## count of complete samples #' @rdname tableby.stats #' @export N <- function(x, na.rm=TRUE, weights = NULL, ...) { if(is.null(weights)) weights <- rep(1, length(x)) as.countpct(sum(weights[!is.na(x)])) } #' @rdname tableby.stats #' @export Npct <- function(x, levels=NULL, by, by.levels=sort(unique(by)), na.rm=TRUE, weights = NULL, ...) { if(is.null(levels)) levels <- sort(unique(x)) if(na.rm) { idx <- !is.na(x) & !is.na(by) if(!is.null(weights)) idx <- idx & !is.na(weights) x <- x[idx] by <- by[idx] weights <- weights[idx] } tmp <- wtd.table(factor(by, levels = by.levels), weights = weights) wtbl <- c(tmp, Total = sum(tmp)) lapply(wtbl, function(elt) as.countpct(c(elt, 100*elt/sum(tmp)), parens = c("(", ")"), pct = "%", which.pct = 2L)) } ## count within group variable #' @rdname tableby.stats count <- function (x, levels=NULL, na.rm = TRUE, weights = NULL, ...) { if(is.null(levels)) levels <- sort(unique(x)) as.tbstat_multirow(lapply(as.list(wtd.table(factor(x[!is.na(x)], levels = levels), weights = weights[!is.na(x)])), as.countpct)) } ## count (pct) where pct is within group variable total #' @rdname tableby.stats #' @export countpct <- function(x, levels=NULL, na.rm=TRUE, weights = NULL, ...) { if(is.null(levels)) levels <- sort(unique(x)) wtbl <- wtd.table(factor(x[!is.na(x)], levels=levels), weights=weights[!is.na(x)]) as.tbstat_multirow(lapply(Map(c, wtbl, if(any(wtbl > 0)) 100*wtbl/sum(wtbl) else rep(list(NULL), times = length(wtbl))), as.countpct, parens = c("(", ")"), pct = "%", which.pct = 2L)) } #' @rdname tableby.stats #' @export countN <- function(x, levels=NULL, na.rm=TRUE, weights = NULL, ...) { if(is.null(levels)) levels <- sort(unique(x)) wtbl <- wtd.table(factor(x[!is.na(x)], levels=levels), weights=weights[!is.na(x)]) n <- sum(wtbl) as.tbstat_multirow(lapply(Map(c, wtbl, rep(n, times = length(wtbl))), as.countpct, sep = "/")) } transpose_list <- function(x, levels, by.levels) stats::setNames(lapply(by.levels, function(i) as.tbstat_multirow(stats::setNames(lapply(x, "[[", i), levels))), by.levels) #' @rdname tableby.stats #' @export countrowpct <- function(x, levels=NULL, by, by.levels=sort(unique(by)), na.rm=TRUE, weights = NULL, ...) { if(is.null(levels)) levels <- sort(unique(x)) if(na.rm) { idx <- !is.na(x) & !is.na(by) if(!is.null(weights)) idx <- idx & !is.na(weights) x <- x[idx] by <- by[idx] weights <- weights[idx] } wtbls <- lapply(levels, function(L) { tmp <- wtd.table(factor(by[x == L], levels = by.levels), weights = weights[x == L]) wtbl <- c(tmp, Total = sum(tmp)) lapply(wtbl, function(elt) as.countpct(c(elt, 100*elt/sum(tmp)), parens = c("(", ")"), pct = "%", which.pct = 2L)) }) transpose_list(wtbls, levels, c(by.levels, "Total")) } #' @rdname tableby.stats #' @export countcellpct <- function(x, levels=NULL, by, by.levels=sort(unique(by)), na.rm=TRUE, weights = NULL, ...) { if(is.null(levels)) levels <- sort(unique(x)) if(na.rm) { idx <- !is.na(x) & !is.na(by) if(!is.null(weights)) idx <- idx & !is.na(weights) x <- x[idx] by <- by[idx] weights <- weights[idx] } tot <- sum(vapply(levels, function(L) { sum(wtd.table(factor(by[x == L], levels = by.levels), weights = weights[x == L])) }, numeric(1))) wtbls <- lapply(levels, function(L) { tmp <- wtd.table(factor(by[x == L], levels = by.levels), weights = weights[x == L]) wtbl <- c(tmp, Total = sum(tmp)) lapply(wtbl, function(elt) as.countpct(c(elt, 100*elt/tot), parens = c("(", ")"), pct = "%", which.pct = 2L)) }) transpose_list(wtbls, levels, c(by.levels, "Total")) } get_binom_est_ci <- function(x, tot, setNA, conf.level = 0.95) { if(setNA) return(NA_real_) b <- stats::binom.test(x, tot, conf.level = conf.level) unname(c(b$estimate, b$conf.int)) } #' @rdname tableby.stats #' @export binomCI <- function(x, levels=NULL, na.rm=TRUE, weights = NULL, conf.level = 0.95, ...) { if(is.null(levels)) levels <- sort(unique(x)) wtbl <- wtd.table(factor(x[!is.na(x)], levels=levels), weights=weights[!is.na(x)]) ests <- lapply(wtbl, get_binom_est_ci, tot = sum(wtbl), setNA = !is.null(weights), conf.level = conf.level) as.tbstat_multirow(lapply(ests, as.tbstat, parens = c("(", ")"), sep2 = ", ")) } #' @rdname tableby.stats #' @export rowbinomCI <- function(x, levels=NULL, by, by.levels=sort(unique(by)), na.rm=TRUE, weights = NULL, conf.level = 0.95, ...) { if(is.null(levels)) levels <- sort(unique(x)) wts <- !is.null(weights) if(na.rm) { idx <- !is.na(x) & !is.na(by) if(wts) idx <- idx & !is.na(weights) x <- x[idx] by <- by[idx] weights <- weights[idx] } wtbls <- lapply(levels, function(L) { tmp <- wtd.table(factor(by[x == L], levels = by.levels), weights = weights[x == L]) wtbl <- c(tmp, Total = sum(tmp)) wtbl <- lapply(wtbl, get_binom_est_ci, tot = sum(tmp), setNA = wts, conf.level = conf.level) lapply(wtbl, as.tbstat, parens = c("(", ")"), sep2 = ", ") }) # as.tbstat_multirow(lapply(wtbl, f)) transpose_list(wtbls, levels, c(by.levels, "Total")) } ######## internal functions that we use above ######## wtd.table <- function(x, weights = NULL, na.rm = TRUE) { if(!length(weights)) return(table(x)) tmp <- tapply(weights, x, sum, na.rm = na.rm) tmp[is.na(tmp)] <- 0 # (tapply(default = 0) would be enough in R >= 3.4, but we'll make this backwards-compatible) tmp } wtd.mean <- function(x, weights = NULL, na.rm = TRUE) { if(!length(weights)) return(mean(x, na.rm = na.rm)) if(na.rm) { idx <- !is.na(x + weights) x <- x[idx] weights <- weights[idx] } sum(weights * x)/sum(weights) } wtd.quantile <- function(x, weights=NULL, probs=c(0,0.25,0.5,0.75,1), na.rm=TRUE) { if(!length(weights)) return(stats::quantile(as.numeric(x), probs = probs, na.rm = na.rm)) if(any(probs < 0) || any(probs > 1)) stop("Probabilities must be between 0 and 1 inclusive") wts <- wtd.table(x, weights, na.rm = na.rm) x <- if(is.Date(x)) as.numeric(as.Date(names(wts))) else as.numeric(names(wts)) n <- sum(wts) order <- 1 + (n - 1) * probs low <- pmax(floor(order), 1) high <- pmin(low + 1, n) order <- order%%1 allq <- stats::approx(cumsum(wts), x, xout = c(low, high), method = "constant", f = 1, rule = 2)$y k <- length(probs) stats::setNames((1 - order) * allq[1:k] + order * allq[-(1:k)], probs) } wtd.var <- function(x, weights = NULL, na.rm=TRUE, method = c("unbiased", "ML")) { method <- match.arg(method) if(!length(weights)) return(stats::var(x, na.rm = na.rm)) if(na.rm) { idx <- !is.na(x + weights) x <- x[idx] weights <- weights[idx] } if(length(x) < 2) return(NA_real_) as.numeric(stats::cov.wt(matrix(x, ncol = 1), weights, method = method)$cov) }
# Automatically generated by openapi-generator (https://openapi-generator.tech) # Please update as you see appropriate context("Test MarkerPosition") model.instance <- MarkerPosition$new() test_that("additionalInfo", { # tests for the property `additionalInfo` (map(character)) # Additional arbitrary info # uncomment below to test the property #expect_equal(model.instance$`additionalInfo`, "EXPECTED_RESULT") }) test_that("linkageGroupName", { # tests for the property `linkageGroupName` (character) # The Uniquely Identifiable name of this linkage group # uncomment below to test the property #expect_equal(model.instance$`linkageGroupName`, "EXPECTED_RESULT") }) test_that("mapDbId", { # tests for the property `mapDbId` (character) # The unique ID of the map # uncomment below to test the property #expect_equal(model.instance$`mapDbId`, "EXPECTED_RESULT") }) test_that("mapName", { # tests for the property `mapName` (character) # The human readable name of the map # uncomment below to test the property #expect_equal(model.instance$`mapName`, "EXPECTED_RESULT") }) test_that("position", { # tests for the property `position` (integer) # The position of a marker within a linkage group # uncomment below to test the property #expect_equal(model.instance$`position`, "EXPECTED_RESULT") }) test_that("variantDbId", { # tests for the property `variantDbId` (character) # Internal db identifier # uncomment below to test the property #expect_equal(model.instance$`variantDbId`, "EXPECTED_RESULT") }) test_that("variantName", { # tests for the property `variantName` (character) # The human readable name for a marker # uncomment below to test the property #expect_equal(model.instance$`variantName`, "EXPECTED_RESULT") })
/tests/testthat/test_marker_position.R
no_license
Breeding-Insight/brapi-r-v2
R
false
false
1,805
r
# Automatically generated by openapi-generator (https://openapi-generator.tech) # Please update as you see appropriate context("Test MarkerPosition") model.instance <- MarkerPosition$new() test_that("additionalInfo", { # tests for the property `additionalInfo` (map(character)) # Additional arbitrary info # uncomment below to test the property #expect_equal(model.instance$`additionalInfo`, "EXPECTED_RESULT") }) test_that("linkageGroupName", { # tests for the property `linkageGroupName` (character) # The Uniquely Identifiable name of this linkage group # uncomment below to test the property #expect_equal(model.instance$`linkageGroupName`, "EXPECTED_RESULT") }) test_that("mapDbId", { # tests for the property `mapDbId` (character) # The unique ID of the map # uncomment below to test the property #expect_equal(model.instance$`mapDbId`, "EXPECTED_RESULT") }) test_that("mapName", { # tests for the property `mapName` (character) # The human readable name of the map # uncomment below to test the property #expect_equal(model.instance$`mapName`, "EXPECTED_RESULT") }) test_that("position", { # tests for the property `position` (integer) # The position of a marker within a linkage group # uncomment below to test the property #expect_equal(model.instance$`position`, "EXPECTED_RESULT") }) test_that("variantDbId", { # tests for the property `variantDbId` (character) # Internal db identifier # uncomment below to test the property #expect_equal(model.instance$`variantDbId`, "EXPECTED_RESULT") }) test_that("variantName", { # tests for the property `variantName` (character) # The human readable name for a marker # uncomment below to test the property #expect_equal(model.instance$`variantName`, "EXPECTED_RESULT") })
library(tidyverse) Bom_data <- read_csv("data/Bom_data.csv") view(Bom_data) Bom_stations <- read.csv("data/Bom_stations.csv") view(Bom_stations) #Challenge 1: stations_data <- Bom_data %>% separate(Temp_min_max,into=c("min_temp","max_temp"),sep = "/") %>% filter(min_temp != "-", max_temp != "-", Rainfall != "-") %>% group_by(Station_number) %>% summarise() stations_data write_csv(stations_data,"results/stations_data.csv") # Answer:20 stations have those data recorded. #Challenge 2: lowest_ave_temp <- Bom_data %>% separate(Temp_min_max,into=c("min_temp","max_temp"),sep="/")%>% filter(min_temp!="-",max_temp!="-")%>% mutate(min_temp=as.numeric(min_temp))%>% mutate(max_temp=as.numeric(max_temp)) %>% mutate(temp_diff=max_temp-min_temp) %>% group_by(Month) %>% summarise(average=mean(temp_diff)) %>% arrange(average) %>% slice(1) lowest_ave_temp write_csv(lowest_ave_temp,"results/lowest_ave_temp.csv") Bom_stations <- read_csv("data/Bom_stations.csv") Bom_stations #Challenge 3 Tidy_bom_station <- Bom_stations %>% gather(key = Station_number, value = amount,-info) %>% spread(key = info, value = amount) %>% #mutate(Station_number=str_replace_all(string = Station_number, #pattern = "X", #replacement = "")) %>% mutate(Station_number=as.numeric(Station_number)) Tidy_bom_station state_ave_temp <- Bom_data %>% separate(Temp_min_max,into=c("min_temp","max_temp"),sep = "/") %>% mutate(min_temp=as.numeric(min_temp))%>% mutate(max_temp=as.numeric(max_temp)) %>% mutate(temp_diff=max_temp-min_temp) state_ave_temp Station_df <- Bom_stations %>% gather(key = Station_number, value = amount,-info) %>% spread(key = info, value = amount) Station_df stations_meteo_merge <- full_join(state_ave_temp,Tidy_bom_station, by=c("Station_number"="Station_number")) stations_meteo_merge write_csv(stations_meteo_merge,"results/stations_mateo_merge.csv") #Which state saw the lowest average daily temperature difference? answer3 <- stations_meteo_merge %>% mutate(min_temp=as.numeric(min_temp))%>% mutate(max_temp=as.numeric(max_temp)) %>% #mutate(temp_diff=max_temp-min_temp) %>% group_by(state) %>% summarise(average=mean(temp_diff,na.rm = TRUE)) %>% arrange(average) %>% slice(1) #Answer for this challenge came to QLD 7.15 answer3 write_csv(answer3,"results/answer3.csv") #Does the westmost (lowest longitude) or eastmost (highest longitude) #weather station in our dataset have a higher average solar exposure? Question4 <- stations_meteo_merge %>% mutate(Solar_exposure = as.numeric(Solar_exposure)) %>% mutate(lon=as.numeric(lon)) %>% group_by(Station_number,lon) %>% summarise(average = mean(Solar_exposure, na.rm = TRUE)) %>% ungroup() %>% filter(lon==min(lon)|lon==max(lon)) Question4 write_csv(Question4,"results/Question4.csv") #Second part-----------------------------------of the challenge library(tidyverse) read_csv("data/Bom_data.csv") BOM_data_new BOM_data_temp BOM_data_temp_solar #question1 perth <- filter(BOM_data_temp_solar, Station_number==9225) perth perths <- filter(perth, Solar_exposure!="-") perths plot1 <-ggplot(data = perths)+ geom_point(aes(as.numeric(max), as.numeric(min), alpha=0.3), colour="red")+ xlab("Max Temp")+ ylab("Min Temp")+ theme(legend.position = "none") plot1 #plot2 perths$min<-as.numeric(perths$min) perths$max<-as.numeric(perths$max) perths$Rainfall<-as.numeric(perths$Rainfall) plot2<- ggplot(data = perths, aes(x = max, y = Rainfall) )+ geom_point(alpha =0.3, colour="blue") plot2 perths plot3 <-ggplot(data = perths, aes(x = max, y = Solar_exposure))+ geom_point(alpha = 0.3, colour ="green") plot3 #question 2 plot4 <-ggplot(data = perths, aes(x = max, y = min))+ geom_point(aes(size = Rainfall, colour=Solar_exposure))+ labs(x="Max Temp", y="Min Temp", size="Solar exposure", colour="Rainfall")+ theme(legend.text = element_text(size = 8), legend.title = element_text(size = 8)) plot4 #question 3 install.packages("cowplot") library(cowplot) theme_set(theme_cowplot()) combined_plot<- plot_grid(plot1, plot2, plot3, plot4, labels = "AUTO") combined_plot ggsave(filename = "combined plot.png", plot=combined_plot) #question 4 BOM_data BOM_data_new4 <- select(BOM_data, Station_number, Month, Day, Rainfall) %>% filter(Rainfall!='-') BOM_data_new4$Rainfall <- as.numeric(BOM_data_new4$Rainfall) BOM_data_new4 Station_mean_rainfall <- group_by(BOM_data_new4, Station_number, Month) %>% summarise(Station_mean_rainfall=mean(Rainfall)) Station_mean_rainfall BOM_Stations_wide$Station_number <- as.numeric(BOM_Stations_wide$Station_number) BOM_combined2 <- left_join(Station_mean_rainfall, BOM_Stations_wide, by="Station_number") View(BOM_combined2) plot5 <-ggplot(data = BOM_combined2, aes(as.factor(Month), Station_mean_rainfall, colour=state, group=Station_number))+ geom_line(size=1) plot5 plot6 <-BOM_combined2 %>% ggplot(aes(as.factor(Month), Station_mean_rainfall, group=as.factor(Station_number), colour=state))+ geom_line(size=1)+ facet_wrap(~state)+ theme(legend.text = element_text(size = 8), legend.title = element_text(size = 8))+ labs(x="Month", y="Average rainfall", colour="State") plot6 ggsave(filename = "Average rainfall per month for each state.png", plot=plot6)
/scripts.R
no_license
ram-ghimire/bom_challenge
R
false
false
5,398
r
library(tidyverse) Bom_data <- read_csv("data/Bom_data.csv") view(Bom_data) Bom_stations <- read.csv("data/Bom_stations.csv") view(Bom_stations) #Challenge 1: stations_data <- Bom_data %>% separate(Temp_min_max,into=c("min_temp","max_temp"),sep = "/") %>% filter(min_temp != "-", max_temp != "-", Rainfall != "-") %>% group_by(Station_number) %>% summarise() stations_data write_csv(stations_data,"results/stations_data.csv") # Answer:20 stations have those data recorded. #Challenge 2: lowest_ave_temp <- Bom_data %>% separate(Temp_min_max,into=c("min_temp","max_temp"),sep="/")%>% filter(min_temp!="-",max_temp!="-")%>% mutate(min_temp=as.numeric(min_temp))%>% mutate(max_temp=as.numeric(max_temp)) %>% mutate(temp_diff=max_temp-min_temp) %>% group_by(Month) %>% summarise(average=mean(temp_diff)) %>% arrange(average) %>% slice(1) lowest_ave_temp write_csv(lowest_ave_temp,"results/lowest_ave_temp.csv") Bom_stations <- read_csv("data/Bom_stations.csv") Bom_stations #Challenge 3 Tidy_bom_station <- Bom_stations %>% gather(key = Station_number, value = amount,-info) %>% spread(key = info, value = amount) %>% #mutate(Station_number=str_replace_all(string = Station_number, #pattern = "X", #replacement = "")) %>% mutate(Station_number=as.numeric(Station_number)) Tidy_bom_station state_ave_temp <- Bom_data %>% separate(Temp_min_max,into=c("min_temp","max_temp"),sep = "/") %>% mutate(min_temp=as.numeric(min_temp))%>% mutate(max_temp=as.numeric(max_temp)) %>% mutate(temp_diff=max_temp-min_temp) state_ave_temp Station_df <- Bom_stations %>% gather(key = Station_number, value = amount,-info) %>% spread(key = info, value = amount) Station_df stations_meteo_merge <- full_join(state_ave_temp,Tidy_bom_station, by=c("Station_number"="Station_number")) stations_meteo_merge write_csv(stations_meteo_merge,"results/stations_mateo_merge.csv") #Which state saw the lowest average daily temperature difference? answer3 <- stations_meteo_merge %>% mutate(min_temp=as.numeric(min_temp))%>% mutate(max_temp=as.numeric(max_temp)) %>% #mutate(temp_diff=max_temp-min_temp) %>% group_by(state) %>% summarise(average=mean(temp_diff,na.rm = TRUE)) %>% arrange(average) %>% slice(1) #Answer for this challenge came to QLD 7.15 answer3 write_csv(answer3,"results/answer3.csv") #Does the westmost (lowest longitude) or eastmost (highest longitude) #weather station in our dataset have a higher average solar exposure? Question4 <- stations_meteo_merge %>% mutate(Solar_exposure = as.numeric(Solar_exposure)) %>% mutate(lon=as.numeric(lon)) %>% group_by(Station_number,lon) %>% summarise(average = mean(Solar_exposure, na.rm = TRUE)) %>% ungroup() %>% filter(lon==min(lon)|lon==max(lon)) Question4 write_csv(Question4,"results/Question4.csv") #Second part-----------------------------------of the challenge library(tidyverse) read_csv("data/Bom_data.csv") BOM_data_new BOM_data_temp BOM_data_temp_solar #question1 perth <- filter(BOM_data_temp_solar, Station_number==9225) perth perths <- filter(perth, Solar_exposure!="-") perths plot1 <-ggplot(data = perths)+ geom_point(aes(as.numeric(max), as.numeric(min), alpha=0.3), colour="red")+ xlab("Max Temp")+ ylab("Min Temp")+ theme(legend.position = "none") plot1 #plot2 perths$min<-as.numeric(perths$min) perths$max<-as.numeric(perths$max) perths$Rainfall<-as.numeric(perths$Rainfall) plot2<- ggplot(data = perths, aes(x = max, y = Rainfall) )+ geom_point(alpha =0.3, colour="blue") plot2 perths plot3 <-ggplot(data = perths, aes(x = max, y = Solar_exposure))+ geom_point(alpha = 0.3, colour ="green") plot3 #question 2 plot4 <-ggplot(data = perths, aes(x = max, y = min))+ geom_point(aes(size = Rainfall, colour=Solar_exposure))+ labs(x="Max Temp", y="Min Temp", size="Solar exposure", colour="Rainfall")+ theme(legend.text = element_text(size = 8), legend.title = element_text(size = 8)) plot4 #question 3 install.packages("cowplot") library(cowplot) theme_set(theme_cowplot()) combined_plot<- plot_grid(plot1, plot2, plot3, plot4, labels = "AUTO") combined_plot ggsave(filename = "combined plot.png", plot=combined_plot) #question 4 BOM_data BOM_data_new4 <- select(BOM_data, Station_number, Month, Day, Rainfall) %>% filter(Rainfall!='-') BOM_data_new4$Rainfall <- as.numeric(BOM_data_new4$Rainfall) BOM_data_new4 Station_mean_rainfall <- group_by(BOM_data_new4, Station_number, Month) %>% summarise(Station_mean_rainfall=mean(Rainfall)) Station_mean_rainfall BOM_Stations_wide$Station_number <- as.numeric(BOM_Stations_wide$Station_number) BOM_combined2 <- left_join(Station_mean_rainfall, BOM_Stations_wide, by="Station_number") View(BOM_combined2) plot5 <-ggplot(data = BOM_combined2, aes(as.factor(Month), Station_mean_rainfall, colour=state, group=Station_number))+ geom_line(size=1) plot5 plot6 <-BOM_combined2 %>% ggplot(aes(as.factor(Month), Station_mean_rainfall, group=as.factor(Station_number), colour=state))+ geom_line(size=1)+ facet_wrap(~state)+ theme(legend.text = element_text(size = 8), legend.title = element_text(size = 8))+ labs(x="Month", y="Average rainfall", colour="State") plot6 ggsave(filename = "Average rainfall per month for each state.png", plot=plot6)
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/slurm_files.R \name{make_slurm} \alias{make_slurm} \title{Creates a SLURM file} \usage{ make_slurm( slurm_config, launcher_file = "", launcher_prefix = "", launcher_suffix = "", ... ) } \arguments{ \item{slurm_config}{the configuration header, from \code{make_slurm_config()}} \item{launcher_file}{the job file for launcher scripts; if empty the launcher isn't used} \item{launcher_prefix, launcher_suffix}{code to run before and after the launcher code is run} \item{...}{unused} } \value{ text of a slurm file } \description{ Creates a SLURM file }
/man/make_slurm.Rd
no_license
Christopher-Peterson/slurmr
R
false
true
642
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/slurm_files.R \name{make_slurm} \alias{make_slurm} \title{Creates a SLURM file} \usage{ make_slurm( slurm_config, launcher_file = "", launcher_prefix = "", launcher_suffix = "", ... ) } \arguments{ \item{slurm_config}{the configuration header, from \code{make_slurm_config()}} \item{launcher_file}{the job file for launcher scripts; if empty the launcher isn't used} \item{launcher_prefix, launcher_suffix}{code to run before and after the launcher code is run} \item{...}{unused} } \value{ text of a slurm file } \description{ Creates a SLURM file }
\name{qde} \Rdversion{2.0} \alias{qde} \alias{update.qde} \title{Quantiles based Density Estimation} \description{Provides a semiparametric estimation of the quantiles for independented univariate data with possible right censoring. This is same as estimating the intercept function within a joint linear quantile regression model with no predictors. } \usage{ qde(y, nsamp = 1e3, thin = 10, cens = NULL, wt = NULL, incr = 0.01, par = "prior", nknots = 6, hyper = list(sig = c(.1,.1), lam = c(6,4), kap = c(0.1,0.1,1)), prox.range = c(.2,.95), acpt.target = 0.15, ref.size = 3, blocking = "single", temp = 1, expo = 2, blocks.mu, blocks.S, fix.nu = FALSE, fbase = c("t", "logistic", "unif"), verbose = TRUE) \method{update}{qde}(object, nadd, append = TRUE, ...) } \arguments{ \item{y}{numeric vector of response data.} \item{nsamp}{number of posterior samples to be saved; defaults to 1000.} \item{thin}{thinning rate for the Markov chain sampler -- one posterior sample is saved per \code{thin} iterations. Defaults to 10. The Markov chain sampler runs for a total of \code{nsamp * thin} many iterations.} \item{cens}{censoring status of response. Must be a vector of length length(y), with 0 indicating no censoring, 1 indicating right censoring, and 2 indicating left censoring. If not supplied, defaults to all zeros.} \item{wt}{weights attached to the observation units, expected to be non-negative numbers, and defaults to a vector of ones if not otherwise supplied.} \item{incr}{tau grid increment. Defaults to 0.01.} \item{par}{character string indicating how the sampler is to be initialized. Only two options are currently supported: "prior" to initialize at a random draw from the prior; "RQ" to initialize at a model space approximation of the estimates from \code{\link{rq}}.} \item{nknots}{number of knots to be used for low rank approximation of the Gaussian process priors. Defaults to 6.} \item{hyper}{hyperparameters of the prior distribution. Must be a list with some of all of the following fields: \code{sig}: a two vector giving the parameters of the inverse-gamma distribution on sigma-square that is used when \code{shrink}=TRUE, \code{lam}: a two vector giving the parameters of the beta distribution on proximity = \eqn{\exp(-0.01* \lambda^2)}{exp(-0.01 * lambda^2)}, and \code{kap}: a vector to be coerced into a \code{3 * nkap} matrix, with \code{nkap} being the number of components in the mixture of gamma prior on \code{kappa}, and each column of the matrix gives the shape, rate and mixing weight of a component.} \item{prox.range}{for specifying the range of length-scale parameter of the Gaussian process prior.} \item{acpt.target}{target acceptance rate of the adaptive Metropolis sampler; defaults to 0.15} \item{ref.size}{adaptation rate of the adaptive Metropolis sampler. The proposal density is updated once every \code{ref.size} iterations. Could be a single number or a vector of length same as the number of blocks.} \item{blocking}{type of blocking to be applied. Either a character string specifying one to be chosen from the supplied menu (see Details), or a list giving user specified blocks. In the latter case, each element of the list is a logical vector of length equal to the total number of model parameters, which equals \code{nknots+3} indicating which model parameters belong to the block.} \item{temp}{temperature of the log-likelihood function. The log-likelihood function is raised to the power of \code{temp}. Defaults to 1.} \item{expo}{the exponent to be used in the covariance kernel of the Gaussian process priors. Defaults to 2, giving the standard squared-exponential covariance kernel.} \item{blocks.mu}{initial block specific means in the form of a list. If left unspecified then will be automatically generated as a list of vectors of zeros of appropriate lengths matching the corresponding block sizes.} \item{blocks.S}{initial block specific covariance matrices in the form of a list. If left unspecified then will be automatically generated as a list of identity matrices of appropriate dimensions matching the corresponding block sizes. When \code{blocking} is chosen as one of the menu items of the form "std*", known prior covariance information and estimated variance matrices from \code{\link{rq}} are used.} \item{fix.nu}{either the logical FALSE indicating that nu should be learned, or a positive real number giving the fixed value of nu, which is then excluded from MCMC updates} \item{fbase}{either "t" (default), "logistic" or "unif" to indicate what base distribution is to be used.} \item{verbose}{logical indicating whether MCMC progress should be printed, defaults to TRUE} \item{object}{a fitted model of the class 'qde'.} \item{nadd}{number of additional MCMC samples.} \item{append}{logical indicating whether new samples should be appended to old ones. If FALSE then old samples are discarded.} \item{...}{no additional arguments are allowed} } \value{ \code{qde(y, ...)} returns a `qde' class object to be used by \code{\link{coef}} and \code{\link{summary}}. Returned object is a list containing the following variables. \item{par}{latest draw of the parameter vector} \item{y}{response vector} \item{cens}{censoring status vector} \item{wt}{vector of observation weights} \item{hyper}{completed list of hyper-parameters} \item{dim}{model dimension vector of the form c(n, p, length of tau grid, position of \eqn{\tau_0}{tau0} on the grid, nknots, length of lambda grid, nkap, total number of MCMC iterations, thin, nsamp)} \item{gridmats}{details of covariance matrix factors etc, intended for internal use.} \item{tau.g}{the tau grid} \item{muV}{list of means for parameter blocks} \item{SV}{list of covariance matrices for parameter blocks} \item{blocks}{list of blocks} \item{blocks.size}{vector of block lengths} \item{dmcmcpar}{numeric vector containing details of adaptive MCMC runs, equals c(temp, decay rate of adaptation, vector of target acceptance rates for the blocks, vector of increment scales used in adaptation). Intended strictly for internal use.} \item{imcmcpar}{numeric vector containing details of adaptive MCMC runs, equals c(number of parameter blocks, ref.size, indicator on whether details are to be printed during MCMC progress, rate of details printing, a vector of counters needed for printing). Intended strictly for internal use.} \item{parsamp}{a long vector containing the parameter draws. Could be coerced into a matrix of dim \code{npar * nsamp}. Intended primarily for use by \code{\link{summary}} and \code{\link{coef}}.} \item{acptsamp}{a long vector containing rates of acceptance statistics for parameter blocks. Could be coerced into a matrix of dim \code{nblocks * nsamp}. Not very informative, because thinning times and adaptation times may not be exactly synced.} \item{lpsamp}{vector of log posterior values for the saved MCMC draws.} \item{fbase.choice}{integer 1 for "t", 2 for "logistic" and 3 for "unif" base.} \item{prox}{vector of proximity (exp(-0.01*lambda^2)) grid values} \item{reg.ix}{positions of the regular tau grid on the expanded tail-appended grid} \item{runtime}{run time of the MCMC} } \details{ The model assumes the quantile function of the data is given by: \code{Q(t) = gamma_0 + sigma * (Qb(zeta(t)|nu) - Qb(zeta(0,5)|nu))}, \code{Qb(.|nu)} is a parametric quantile function with unknown parameter \code{nu}, \code{gamma_0} is the unknown median, \code{sigma} is an unknown saling factor, and, \code{zeta} is an unknown distortion of the unit interval. The distortion \code{zeta} is modeled nonparametrically through a logistic Gaussian process prior, other parameters are given diffuse priors. In running the MCMC, the following menu choices are available for blocking the parameter vector. For this special case \code{p = ncol(X) = 0}, some of the menu choices are actually the same, in particular, "std0" is same as "single", "std1" is same as "single2", and, "std2" is same as "single3". \code{"single"}: a single block containing all parameters \code{"single2"}: one block containing all parameters and an additional block containing only (gamma[0], gamma, sigma, nu) \code{"single3"}: like \code{"single2"}, but the second block is split into two further blocks, one with \eqn{(\gamma_0, \gamma)}{(gamma[0], gamma)}, the other with \eqn{(\sigma, \nu)}{(sigma, nu)} \code{"std0"}: Same as \code{"single"}. \code{"std1"}: Same as \code{"single2"}. \code{"std2"}: Same as \code{"single3"}. \code{"std3"}: total 3 blocks. First block is \eqn{W_{*0}}{W*[0]}, last two are \eqn{(\gamma_0, \gamma)}{(gamma[0], gamma)} and \eqn{(\sigma, \nu)}{(sigma, nu)} \code{"std4"}: total 3 blocks. First block is \eqn{(W_{*0}, \gamma_0)}{(W*[0], gamma[0])}, last two are \eqn{(\gamma_0, \gamma)}{(gamma[0], gamma)} and \eqn{(\sigma, \nu)}{(sigma, nu)} \code{"std5"}: total 4 blocks. First three are same as \code{"std4"} and one additional block containing all parameters. } \references{Yang, Y. and Tokdar, S.T., 2017. Joint estimation of quantile planes over arbitrary predictor spaces. Journal of the American Statistical Association, 112(519), pp.1107-1120.} \seealso{\code{\link{summary.qde}}, \code{\link{coef.qde}} and \code{\link{predict.qde}}. Also see \code{\link{qrjoint}} for regression model fitting in presence of covariates.} \examples{ ## Plasma data analysis data(plasma) Y <- plasma$BetaPlasma # model fitting with 100 posterior samples from 200 iterations (thin = 2) # this is of course for illustration, for practical model fitting you # ought to try at least something like nsamp = 500, thin = 20 fit.qde <- qde(Y, nsamp = 100, thin = 2) summary(fit.qde, more = TRUE) pred <- predict(fit.qde) hist(Y, freq = FALSE, col = "gray", border = "white", ylim = c(0, max(pred$fest))) lines(pred$y, pred$fest[,2]) lines(pred$y, pred$fest[,1], lty = 2) lines(pred$y, pred$fest[,3], lty = 2) } \keyword{programming}
/qrjoint/man/qde.Rd
no_license
tokdarstat/qrjoint
R
false
false
9,916
rd
\name{qde} \Rdversion{2.0} \alias{qde} \alias{update.qde} \title{Quantiles based Density Estimation} \description{Provides a semiparametric estimation of the quantiles for independented univariate data with possible right censoring. This is same as estimating the intercept function within a joint linear quantile regression model with no predictors. } \usage{ qde(y, nsamp = 1e3, thin = 10, cens = NULL, wt = NULL, incr = 0.01, par = "prior", nknots = 6, hyper = list(sig = c(.1,.1), lam = c(6,4), kap = c(0.1,0.1,1)), prox.range = c(.2,.95), acpt.target = 0.15, ref.size = 3, blocking = "single", temp = 1, expo = 2, blocks.mu, blocks.S, fix.nu = FALSE, fbase = c("t", "logistic", "unif"), verbose = TRUE) \method{update}{qde}(object, nadd, append = TRUE, ...) } \arguments{ \item{y}{numeric vector of response data.} \item{nsamp}{number of posterior samples to be saved; defaults to 1000.} \item{thin}{thinning rate for the Markov chain sampler -- one posterior sample is saved per \code{thin} iterations. Defaults to 10. The Markov chain sampler runs for a total of \code{nsamp * thin} many iterations.} \item{cens}{censoring status of response. Must be a vector of length length(y), with 0 indicating no censoring, 1 indicating right censoring, and 2 indicating left censoring. If not supplied, defaults to all zeros.} \item{wt}{weights attached to the observation units, expected to be non-negative numbers, and defaults to a vector of ones if not otherwise supplied.} \item{incr}{tau grid increment. Defaults to 0.01.} \item{par}{character string indicating how the sampler is to be initialized. Only two options are currently supported: "prior" to initialize at a random draw from the prior; "RQ" to initialize at a model space approximation of the estimates from \code{\link{rq}}.} \item{nknots}{number of knots to be used for low rank approximation of the Gaussian process priors. Defaults to 6.} \item{hyper}{hyperparameters of the prior distribution. Must be a list with some of all of the following fields: \code{sig}: a two vector giving the parameters of the inverse-gamma distribution on sigma-square that is used when \code{shrink}=TRUE, \code{lam}: a two vector giving the parameters of the beta distribution on proximity = \eqn{\exp(-0.01* \lambda^2)}{exp(-0.01 * lambda^2)}, and \code{kap}: a vector to be coerced into a \code{3 * nkap} matrix, with \code{nkap} being the number of components in the mixture of gamma prior on \code{kappa}, and each column of the matrix gives the shape, rate and mixing weight of a component.} \item{prox.range}{for specifying the range of length-scale parameter of the Gaussian process prior.} \item{acpt.target}{target acceptance rate of the adaptive Metropolis sampler; defaults to 0.15} \item{ref.size}{adaptation rate of the adaptive Metropolis sampler. The proposal density is updated once every \code{ref.size} iterations. Could be a single number or a vector of length same as the number of blocks.} \item{blocking}{type of blocking to be applied. Either a character string specifying one to be chosen from the supplied menu (see Details), or a list giving user specified blocks. In the latter case, each element of the list is a logical vector of length equal to the total number of model parameters, which equals \code{nknots+3} indicating which model parameters belong to the block.} \item{temp}{temperature of the log-likelihood function. The log-likelihood function is raised to the power of \code{temp}. Defaults to 1.} \item{expo}{the exponent to be used in the covariance kernel of the Gaussian process priors. Defaults to 2, giving the standard squared-exponential covariance kernel.} \item{blocks.mu}{initial block specific means in the form of a list. If left unspecified then will be automatically generated as a list of vectors of zeros of appropriate lengths matching the corresponding block sizes.} \item{blocks.S}{initial block specific covariance matrices in the form of a list. If left unspecified then will be automatically generated as a list of identity matrices of appropriate dimensions matching the corresponding block sizes. When \code{blocking} is chosen as one of the menu items of the form "std*", known prior covariance information and estimated variance matrices from \code{\link{rq}} are used.} \item{fix.nu}{either the logical FALSE indicating that nu should be learned, or a positive real number giving the fixed value of nu, which is then excluded from MCMC updates} \item{fbase}{either "t" (default), "logistic" or "unif" to indicate what base distribution is to be used.} \item{verbose}{logical indicating whether MCMC progress should be printed, defaults to TRUE} \item{object}{a fitted model of the class 'qde'.} \item{nadd}{number of additional MCMC samples.} \item{append}{logical indicating whether new samples should be appended to old ones. If FALSE then old samples are discarded.} \item{...}{no additional arguments are allowed} } \value{ \code{qde(y, ...)} returns a `qde' class object to be used by \code{\link{coef}} and \code{\link{summary}}. Returned object is a list containing the following variables. \item{par}{latest draw of the parameter vector} \item{y}{response vector} \item{cens}{censoring status vector} \item{wt}{vector of observation weights} \item{hyper}{completed list of hyper-parameters} \item{dim}{model dimension vector of the form c(n, p, length of tau grid, position of \eqn{\tau_0}{tau0} on the grid, nknots, length of lambda grid, nkap, total number of MCMC iterations, thin, nsamp)} \item{gridmats}{details of covariance matrix factors etc, intended for internal use.} \item{tau.g}{the tau grid} \item{muV}{list of means for parameter blocks} \item{SV}{list of covariance matrices for parameter blocks} \item{blocks}{list of blocks} \item{blocks.size}{vector of block lengths} \item{dmcmcpar}{numeric vector containing details of adaptive MCMC runs, equals c(temp, decay rate of adaptation, vector of target acceptance rates for the blocks, vector of increment scales used in adaptation). Intended strictly for internal use.} \item{imcmcpar}{numeric vector containing details of adaptive MCMC runs, equals c(number of parameter blocks, ref.size, indicator on whether details are to be printed during MCMC progress, rate of details printing, a vector of counters needed for printing). Intended strictly for internal use.} \item{parsamp}{a long vector containing the parameter draws. Could be coerced into a matrix of dim \code{npar * nsamp}. Intended primarily for use by \code{\link{summary}} and \code{\link{coef}}.} \item{acptsamp}{a long vector containing rates of acceptance statistics for parameter blocks. Could be coerced into a matrix of dim \code{nblocks * nsamp}. Not very informative, because thinning times and adaptation times may not be exactly synced.} \item{lpsamp}{vector of log posterior values for the saved MCMC draws.} \item{fbase.choice}{integer 1 for "t", 2 for "logistic" and 3 for "unif" base.} \item{prox}{vector of proximity (exp(-0.01*lambda^2)) grid values} \item{reg.ix}{positions of the regular tau grid on the expanded tail-appended grid} \item{runtime}{run time of the MCMC} } \details{ The model assumes the quantile function of the data is given by: \code{Q(t) = gamma_0 + sigma * (Qb(zeta(t)|nu) - Qb(zeta(0,5)|nu))}, \code{Qb(.|nu)} is a parametric quantile function with unknown parameter \code{nu}, \code{gamma_0} is the unknown median, \code{sigma} is an unknown saling factor, and, \code{zeta} is an unknown distortion of the unit interval. The distortion \code{zeta} is modeled nonparametrically through a logistic Gaussian process prior, other parameters are given diffuse priors. In running the MCMC, the following menu choices are available for blocking the parameter vector. For this special case \code{p = ncol(X) = 0}, some of the menu choices are actually the same, in particular, "std0" is same as "single", "std1" is same as "single2", and, "std2" is same as "single3". \code{"single"}: a single block containing all parameters \code{"single2"}: one block containing all parameters and an additional block containing only (gamma[0], gamma, sigma, nu) \code{"single3"}: like \code{"single2"}, but the second block is split into two further blocks, one with \eqn{(\gamma_0, \gamma)}{(gamma[0], gamma)}, the other with \eqn{(\sigma, \nu)}{(sigma, nu)} \code{"std0"}: Same as \code{"single"}. \code{"std1"}: Same as \code{"single2"}. \code{"std2"}: Same as \code{"single3"}. \code{"std3"}: total 3 blocks. First block is \eqn{W_{*0}}{W*[0]}, last two are \eqn{(\gamma_0, \gamma)}{(gamma[0], gamma)} and \eqn{(\sigma, \nu)}{(sigma, nu)} \code{"std4"}: total 3 blocks. First block is \eqn{(W_{*0}, \gamma_0)}{(W*[0], gamma[0])}, last two are \eqn{(\gamma_0, \gamma)}{(gamma[0], gamma)} and \eqn{(\sigma, \nu)}{(sigma, nu)} \code{"std5"}: total 4 blocks. First three are same as \code{"std4"} and one additional block containing all parameters. } \references{Yang, Y. and Tokdar, S.T., 2017. Joint estimation of quantile planes over arbitrary predictor spaces. Journal of the American Statistical Association, 112(519), pp.1107-1120.} \seealso{\code{\link{summary.qde}}, \code{\link{coef.qde}} and \code{\link{predict.qde}}. Also see \code{\link{qrjoint}} for regression model fitting in presence of covariates.} \examples{ ## Plasma data analysis data(plasma) Y <- plasma$BetaPlasma # model fitting with 100 posterior samples from 200 iterations (thin = 2) # this is of course for illustration, for practical model fitting you # ought to try at least something like nsamp = 500, thin = 20 fit.qde <- qde(Y, nsamp = 100, thin = 2) summary(fit.qde, more = TRUE) pred <- predict(fit.qde) hist(Y, freq = FALSE, col = "gray", border = "white", ylim = c(0, max(pred$fest))) lines(pred$y, pred$fest[,2]) lines(pred$y, pred$fest[,1], lty = 2) lines(pred$y, pred$fest[,3], lty = 2) } \keyword{programming}
library(ncdf4) #library(RCurl) #library(raster) library(tidyverse) library(chron) library(RColorBrewer) library(lattice) # http://geog.uoregon.edu/bartlein/courses/geog607/Rmd/netCDF_01.htm # open NetCDF file ncfname<-"fram/MARTINI800/Combined_martini800_avg_Chl_surf.nc" dname <- "Chl" # note: tmp means temperature (not temporary) ncfname<-"fram/MARTINI800/martini800_v2_Chl_surf.nc" ncfname<-"fram/MARTINI800/martini800_avg_17317.nc" dname <- "light_Chl" ncin <- nc_open(ncfname) s<-print(ncin) names(ncin$var) # Get the longtiudes and latitudes, using the ncvar_get() function in ncdf4. lon <- ncvar_get(ncin, "lon_rho") nlon <- dim(lon) lat <- ncvar_get(ncin, "lat_rho", verbose = F) nlat <- dim(lat) #head(lat) print(c(nlon, nlat)) # Get the time variable and its attributes using the ncvar_get() and ncatt_get() functions # also get the number of times using the dim() function. t <- ncvar_get(ncin, "ocean_time") tunits <- ncatt_get(ncin, "ocean_time", "units") nt <- dim(t) # Get the variable and its attributes, and verify the size of the array. tmp.array <- ncvar_get(ncin, dname) dlname <- ncatt_get(ncin, dname, "long_name") dunits <- ncatt_get(ncin, dname, "units") fillvalue <- ncatt_get(ncin, dname, "_FillValue") dim(tmp.array) # Get the global attributes. title <- ncatt_get(ncin, 0, "title") institution <- ncatt_get(ncin, 0, "institution") datasource <- ncatt_get(ncin, 0, "source") references <- ncatt_get(ncin, 0, "references") history <- ncatt_get(ncin, 0, "history") Conventions <- ncatt_get(ncin, 0, "Conventions") # Close the NetCDF file using the nc_close() function nc_close(ncin) # Convert the time variable # The time variable, in “time-since” units can be converted into “real” (or more easily readable) time values by splitting the time tunits$value string into its component parts, and then using the chron() function to determine the absolute value of each time value from the time origin. # split the time units string into fields tustr <- strsplit(tunits$value, " ") tdstr <- strsplit(unlist(tustr)[3], "-") tmonth = as.integer(unlist(tdstr)[2]) tday = as.integer(unlist(tdstr)[3]) tyear = as.integer(unlist(tdstr)[1]) chron(t, origin = c(tmonth, tday, tyear)) # Replace NetCDF fillvalues with R NAs tmp.array[tmp.array == fillvalue$value] <- NA # Get the total number of non-missing grid cells length(na.omit(as.vector(tmp.array[, , 1]))) # Get a single time slice of the data, create an R data frame, and write a .csv file m <- 364 tmp.slice <- tmp.array[, , m] ts<-tmp.array[249,213,] tsdf<-data.frame(value=ts) tsdf$time<-seq(1,364,1) plot(tsdf) image(lon,lat,tmp.slice, col = rev(brewer.pal(10, "RdBu"))) dim(tmp.slice) dim(lon) dim(lat) image(tmp.slice, col = rev(brewer.pal(10, "RdBu"))) lat[1,2]-lat[1,1] lat[480,2]-lat[480,1] lat[1,426]-lat[1,425] lat[480,426]-lat[480,425] res[,,1]<-lon res[,,2]<-lat res[,,3]<-tmp.slice r <- raster(ncfname, varname = dname) plot(r) library(rasterVis) # Notice `g`plot (from rasterVis) and not `gg`plot gplot(r) + geom_tile(aes(fill = value)) ggplot(aes(x=lat, y=lon, fill=tmp.slice), data=mpr) + geom_raster() + coord_equal() raster(x, xmn=0, xmx=1, ymn=0, ymx=1, crs=NA, template=NULL) levelplot(tmp.slice~lon*lat,col=rev(brewer.pal(10, "RdBu"))) grid <- expand.grid(lon=lon, lat=lat) cutpts <- c(-50,-40,-30,-20,-10,0,10,20,30,40,50) levelplot(tmp_slice ~ lon * lat, data=grid, at=cutpts, cuts=11, pretty=T, col.regions=(rev(brewer.pal(10,"RdBu"))))
/app/MARTINI800.R
permissive
NIVANorge/MARTINI
R
false
false
3,486
r
library(ncdf4) #library(RCurl) #library(raster) library(tidyverse) library(chron) library(RColorBrewer) library(lattice) # http://geog.uoregon.edu/bartlein/courses/geog607/Rmd/netCDF_01.htm # open NetCDF file ncfname<-"fram/MARTINI800/Combined_martini800_avg_Chl_surf.nc" dname <- "Chl" # note: tmp means temperature (not temporary) ncfname<-"fram/MARTINI800/martini800_v2_Chl_surf.nc" ncfname<-"fram/MARTINI800/martini800_avg_17317.nc" dname <- "light_Chl" ncin <- nc_open(ncfname) s<-print(ncin) names(ncin$var) # Get the longtiudes and latitudes, using the ncvar_get() function in ncdf4. lon <- ncvar_get(ncin, "lon_rho") nlon <- dim(lon) lat <- ncvar_get(ncin, "lat_rho", verbose = F) nlat <- dim(lat) #head(lat) print(c(nlon, nlat)) # Get the time variable and its attributes using the ncvar_get() and ncatt_get() functions # also get the number of times using the dim() function. t <- ncvar_get(ncin, "ocean_time") tunits <- ncatt_get(ncin, "ocean_time", "units") nt <- dim(t) # Get the variable and its attributes, and verify the size of the array. tmp.array <- ncvar_get(ncin, dname) dlname <- ncatt_get(ncin, dname, "long_name") dunits <- ncatt_get(ncin, dname, "units") fillvalue <- ncatt_get(ncin, dname, "_FillValue") dim(tmp.array) # Get the global attributes. title <- ncatt_get(ncin, 0, "title") institution <- ncatt_get(ncin, 0, "institution") datasource <- ncatt_get(ncin, 0, "source") references <- ncatt_get(ncin, 0, "references") history <- ncatt_get(ncin, 0, "history") Conventions <- ncatt_get(ncin, 0, "Conventions") # Close the NetCDF file using the nc_close() function nc_close(ncin) # Convert the time variable # The time variable, in “time-since” units can be converted into “real” (or more easily readable) time values by splitting the time tunits$value string into its component parts, and then using the chron() function to determine the absolute value of each time value from the time origin. # split the time units string into fields tustr <- strsplit(tunits$value, " ") tdstr <- strsplit(unlist(tustr)[3], "-") tmonth = as.integer(unlist(tdstr)[2]) tday = as.integer(unlist(tdstr)[3]) tyear = as.integer(unlist(tdstr)[1]) chron(t, origin = c(tmonth, tday, tyear)) # Replace NetCDF fillvalues with R NAs tmp.array[tmp.array == fillvalue$value] <- NA # Get the total number of non-missing grid cells length(na.omit(as.vector(tmp.array[, , 1]))) # Get a single time slice of the data, create an R data frame, and write a .csv file m <- 364 tmp.slice <- tmp.array[, , m] ts<-tmp.array[249,213,] tsdf<-data.frame(value=ts) tsdf$time<-seq(1,364,1) plot(tsdf) image(lon,lat,tmp.slice, col = rev(brewer.pal(10, "RdBu"))) dim(tmp.slice) dim(lon) dim(lat) image(tmp.slice, col = rev(brewer.pal(10, "RdBu"))) lat[1,2]-lat[1,1] lat[480,2]-lat[480,1] lat[1,426]-lat[1,425] lat[480,426]-lat[480,425] res[,,1]<-lon res[,,2]<-lat res[,,3]<-tmp.slice r <- raster(ncfname, varname = dname) plot(r) library(rasterVis) # Notice `g`plot (from rasterVis) and not `gg`plot gplot(r) + geom_tile(aes(fill = value)) ggplot(aes(x=lat, y=lon, fill=tmp.slice), data=mpr) + geom_raster() + coord_equal() raster(x, xmn=0, xmx=1, ymn=0, ymx=1, crs=NA, template=NULL) levelplot(tmp.slice~lon*lat,col=rev(brewer.pal(10, "RdBu"))) grid <- expand.grid(lon=lon, lat=lat) cutpts <- c(-50,-40,-30,-20,-10,0,10,20,30,40,50) levelplot(tmp_slice ~ lon * lat, data=grid, at=cutpts, cuts=11, pretty=T, col.regions=(rev(brewer.pal(10,"RdBu"))))
#How have emissions from motor vehicle sources changed from 1999–2008 in # Baltimore City? ## Read data NEI <- readRDS("data/summarySCC_PM25.rds") ##Select data ### Baltimore City, Maryland (fips == "24510") ### On-road only BaltimoreEmission.byMotor <-NEI[(NEI$fips=="24510") & (NEI$type=="ON-ROAD"),] ## Calculation total.BaltimoreEmission.byMotor <- tapply(BaltimoreEmission.byMotor$Emissions, BaltimoreEmission.byMotor$year,sum) ##Generate graph png(filename='plot5.png') barplot(total.BaltimoreEmission.byMotor, main=expression(paste('Total Emission of PM', ''[2.5], 'by motor vehicle sources in Baltimore City"')), xlab='Year', ylab=expression(paste('PM', ''[2.5], ' in Kilotons'))) dev.off()
/plot5.R
no_license
mstaelen/exdata-004
R
false
false
794
r
#How have emissions from motor vehicle sources changed from 1999–2008 in # Baltimore City? ## Read data NEI <- readRDS("data/summarySCC_PM25.rds") ##Select data ### Baltimore City, Maryland (fips == "24510") ### On-road only BaltimoreEmission.byMotor <-NEI[(NEI$fips=="24510") & (NEI$type=="ON-ROAD"),] ## Calculation total.BaltimoreEmission.byMotor <- tapply(BaltimoreEmission.byMotor$Emissions, BaltimoreEmission.byMotor$year,sum) ##Generate graph png(filename='plot5.png') barplot(total.BaltimoreEmission.byMotor, main=expression(paste('Total Emission of PM', ''[2.5], 'by motor vehicle sources in Baltimore City"')), xlab='Year', ylab=expression(paste('PM', ''[2.5], ' in Kilotons'))) dev.off()
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/fars_functions.R \name{fars_read} \alias{fars_read} \title{Read Data} \usage{ fars_read(filename) } \arguments{ \item{filename}{A character string giving the filename of the data} } \value{ This function returns a data frame } \description{ This function reads data in compressed .csv format and creates a data frame. It throws an error if the filename in the argument does not exist. } \examples{ \dontrun{fars_read("Data.csv.bz2")} }
/man/fars_read.Rd
no_license
nandhinidev/farsplot
R
false
true
515
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/fars_functions.R \name{fars_read} \alias{fars_read} \title{Read Data} \usage{ fars_read(filename) } \arguments{ \item{filename}{A character string giving the filename of the data} } \value{ This function returns a data frame } \description{ This function reads data in compressed .csv format and creates a data frame. It throws an error if the filename in the argument does not exist. } \examples{ \dontrun{fars_read("Data.csv.bz2")} }
#변수 만들기 a<-1 a b<-2 b c<-3 c d<-3.5 d #변수를 조합해 연산하기 a+b a+b+c 4/b 5*b #여러 값으로 구성된 변수 만들기 (c()함수 이용하기) var1 <-c(1,2,5,7,8) var1 #콜론(:)을 이용해 시작 숫자와 마지막 숫자를 입력하면 1씩 증가함 var2 <-c(1:5) var2 #seq()함수를 이용해 연속적인 값으로 변수 생성 var3 <-seq(1,5) var3 #by파라미터를 이용해 일정한 간격을 두고 연속된 숫자변수를 만듦 var4<-seq(1,10,by=2) var4 var5 <-seq(1,10,by=3) var5 #여러 값으로 구성된 변수로도 연산할 수 있다 var1 var1+2 var1 var2 var1+var2 #문자로 된 변수 만들기 str1 <-"a" str1 str2<-"text" str2 str3<-"Hello world!" str3 #문자로 된 변수도 c()함수를 이용하면 여러개의 문자로 구성 가능 str5 <-c("hello","world","is","good") str5 #숫자를 다루는 함수 이용하기 (평균을 구하는 mean함수) x <-c(1,2,3) x mean(x) #숫자의 최대값 최소값을 구하는 max , min함수 max(x) min(x) #문자를 다루는 함수 이용하기 (paste함수, collapse 파라미터) str5 paste(str5,collapse=",") #4개의 단어가 쉼표로 구분되어 하나로 합쳐진 모습 paste(str5,collapse=" ") #4개의 단어가 띄어쓰기로 구분되어 하나로 합쳐진 모습 #함수의 옵션을 설정하는 명령어를 "파라미터","매개변수"라고 함 #새 변수에 함수를 적용해 저장하기 x_mean <-mean(x) x_mean str5_paste<-paste(str5,collapse=" ") str5_paste #패키지 설치하기 (install.packages("패키지명")) #패키지 로드하기 library(패키지명) library(ggplot2) x<-c("a","a","b","c") x #빈도막대그래프 출력 qplot(x) #ggplot2의 mpg데이터로 그래프 만들기 #ggplot2에는 mpg데이터가 있다. qplot(data=mpg,x=hwy) qplot(data=mpg,x=cty) qplot(data=mpg,x=drv,y=hwy) qplot(data=mpg,x=drv,y=hwy,geom="boxplot",colour=drv) #혼자서 해보기 #Q1 시험 점수 변수 만들고 출력하기 stu<-c(80,60,70,50,90) stu #Q2 전체 평균 구하기 mean(stu) #Q3 전체 평균 변수 만들고 출력하기 stu_mean <-mean(stu) stu_mean
/practice_1.R
no_license
Kimdumchit/R_practice
R
false
false
2,140
r
#변수 만들기 a<-1 a b<-2 b c<-3 c d<-3.5 d #변수를 조합해 연산하기 a+b a+b+c 4/b 5*b #여러 값으로 구성된 변수 만들기 (c()함수 이용하기) var1 <-c(1,2,5,7,8) var1 #콜론(:)을 이용해 시작 숫자와 마지막 숫자를 입력하면 1씩 증가함 var2 <-c(1:5) var2 #seq()함수를 이용해 연속적인 값으로 변수 생성 var3 <-seq(1,5) var3 #by파라미터를 이용해 일정한 간격을 두고 연속된 숫자변수를 만듦 var4<-seq(1,10,by=2) var4 var5 <-seq(1,10,by=3) var5 #여러 값으로 구성된 변수로도 연산할 수 있다 var1 var1+2 var1 var2 var1+var2 #문자로 된 변수 만들기 str1 <-"a" str1 str2<-"text" str2 str3<-"Hello world!" str3 #문자로 된 변수도 c()함수를 이용하면 여러개의 문자로 구성 가능 str5 <-c("hello","world","is","good") str5 #숫자를 다루는 함수 이용하기 (평균을 구하는 mean함수) x <-c(1,2,3) x mean(x) #숫자의 최대값 최소값을 구하는 max , min함수 max(x) min(x) #문자를 다루는 함수 이용하기 (paste함수, collapse 파라미터) str5 paste(str5,collapse=",") #4개의 단어가 쉼표로 구분되어 하나로 합쳐진 모습 paste(str5,collapse=" ") #4개의 단어가 띄어쓰기로 구분되어 하나로 합쳐진 모습 #함수의 옵션을 설정하는 명령어를 "파라미터","매개변수"라고 함 #새 변수에 함수를 적용해 저장하기 x_mean <-mean(x) x_mean str5_paste<-paste(str5,collapse=" ") str5_paste #패키지 설치하기 (install.packages("패키지명")) #패키지 로드하기 library(패키지명) library(ggplot2) x<-c("a","a","b","c") x #빈도막대그래프 출력 qplot(x) #ggplot2의 mpg데이터로 그래프 만들기 #ggplot2에는 mpg데이터가 있다. qplot(data=mpg,x=hwy) qplot(data=mpg,x=cty) qplot(data=mpg,x=drv,y=hwy) qplot(data=mpg,x=drv,y=hwy,geom="boxplot",colour=drv) #혼자서 해보기 #Q1 시험 점수 변수 만들고 출력하기 stu<-c(80,60,70,50,90) stu #Q2 전체 평균 구하기 mean(stu) #Q3 전체 평균 변수 만들고 출력하기 stu_mean <-mean(stu) stu_mean
household_power_consumption <- read.csv("~/R/Exploratory Data Analysis/household_power_consumption.txt", sep=";", stringsAsFactors = FALSE, na.strings="?") # load csv not as factors, ; separator and ?=NA power_subset <- subset(household_power_consumption, Date == "1/2/2007"| Date == "2/2/2007") # sub set data power_subset$nGlobal_active_power<-as.numeric(power_subset$Global_active_power) # active power as numeric power_subset$nSub_metering_3<-as.numeric(power_subset$Sub_metering_3) # nSub as numeric par(mfrow = c(1,1),mar=c(4,4,4,4)) hist(power_subset$nGlobal_active_power, col = "red", main = "Global Active Power", breaks=20, ylab="Frequency", xlab="Global Active Power (kilowatts)") # histogram on active power in subset
/Plot 1.R
no_license
JohanNilsTommy/Exploratory-Data-Analysis-Week-1-Power-Consumption
R
false
false
762
r
household_power_consumption <- read.csv("~/R/Exploratory Data Analysis/household_power_consumption.txt", sep=";", stringsAsFactors = FALSE, na.strings="?") # load csv not as factors, ; separator and ?=NA power_subset <- subset(household_power_consumption, Date == "1/2/2007"| Date == "2/2/2007") # sub set data power_subset$nGlobal_active_power<-as.numeric(power_subset$Global_active_power) # active power as numeric power_subset$nSub_metering_3<-as.numeric(power_subset$Sub_metering_3) # nSub as numeric par(mfrow = c(1,1),mar=c(4,4,4,4)) hist(power_subset$nGlobal_active_power, col = "red", main = "Global Active Power", breaks=20, ylab="Frequency", xlab="Global Active Power (kilowatts)") # histogram on active power in subset
args = commandArgs(trailingOnly=TRUE) require(MCMCpack) library(doParallel) library(foreach) library(cluster) library(Rcpp) library(RcppArmadillo) library(RcppGSL) library(scales) library(coda) #Sys.setenv("PKG_CXXFLAGS"="-std=c++11") #sourceCpp("~/BI/BI.cpp") qcutAll <- c(0.05, 0.1, 0.15, 0.2, 0.25, 0.3) localTest <- 0 singleTest <- 0 multipleReplicates <- 0 fullRun <- 0 if(args[7] == "local"){ localTest <- 1 } else if (args[7] == "single"){ singleTest <- 1 } else if (args[7] == "multiple"){ multipleReplicates <- 1 } else if (args[7] == "full"){ fullRun <- 1 } Mode <- function(x) { ux <- unique(x) ux[which.max(tabulate(match(x, ux)))] } ####################################################### ### Bayesian Imputation (BI) with gene/methy missing ## ####################################################### #now using Rcpp BFDR <- function(Ipm, n, nGene){ #Ipm is the feature selection posterior mean. BFDRtmp <- matrix(NA,nGene,2) #t, BFDR(t) PMtmp <- rep(NA, nGene) qtmp <- rep(NA, nGene) # PMtmp <- 2*( 1- pt( abs((est[[r]]$gammaMEst) / (est[[r]]$gammaMSd / sqrt(all_n[n]))), all_n[n]-1) ) #PMtmp <- 2*( 1- pt( abs(mean) / (sd / sqrt(n)), n-1) ) PMtmp <- 1-Ipm sortedPM <- sort(PMtmp) for(k in 1:nGene){ BFDRtmp[k,1] <- sortedPM[k] BFDRtmp[k,2] <- sum(sortedPM[1:k])/k } for(k in 1:nGene){ qtmp[k] <- min( BFDRtmp[ which(BFDRtmp[,1] >= PMtmp[k]), 2] ) } return(list(q=qtmp)) } nGene <- as.numeric(args[8]) nCausalM <- as.numeric(args[9]) nCausalMbar <- as.numeric(args[10]) nMethy <- as.numeric(args[11]) nC <- 2 exchangeable <- FALSE MCAR <- TRUE nGene<-1000 nMethy <- 2619 #nCausalM <- 10 #fix #nCausalMbar <- 10 if( fullRun | multipleReplicates ){ wd <- args[1] setwd(wd) noCFlag <- 0 #flag for no clinical variable input nCtmp <- nC if(nC==0){ noCFlag=1 nCtmp <- 1 } nItr <- as.numeric(args[4]) seed <- as.numeric(args[3]) thetaGene <- as.numeric(args[5]) thetaMethy <- as.numeric(args[6]) # cl <- makeCluster(as.numeric(args[2])) # registerDoParallel(cl) # all_n <- c(20,30,50,100,200,500) # all_n <- c(50,100,200,500) all_n <- c(460) if(args[13] == "strong"){ epsilon <- 0.01 } else if( args[13]=="mid"){ epsilon <- 0.5 } else if( args[13]=="weak"){ epsilon <- 2 }else if( args[13]=="midstrong"){ epsilon <- 0.1 }else if( args[13]=="superweak"){ epsilon <- 3 }else if( args[13]=="ultraweak"){ epsilon <- 5 } epsilonGeneMbar <- 2 if( multipleReplicates ){ all_n <- 100 } load("~/BI/nasal/nasalProcessed.rdata") geneNames <- colnames(gene) load(paste(wd, "/dataSilver.rdata",sep="")) nGene= dim(dataSilver$geneMTrue)[2] nMethy = dim(dataSilver$methyTrue)[2] nCausalM <- length(dataSilver$causalGeneMIdx) nCausalMbar <- length(dataSilver$causalGeneMbarIdx) parNames <- c( expression(paste(gamma^M," causal")), expression(paste(gamma^bar(M), " causal")), expression(paste(gamma^M, " non-causal")), expression(paste(gamma^bar(M), " non-causal")), expression(gamma^C), expression(omega), expression(hat(Y))) nPar <- length(parNames) # gammaM_causal, gammaMbar_causal,gammaM_nc, gammaMbar_nc, gammaC, omegaMean, yHat sensSpecNames <- c( expression(paste(I^M,"sens")), expression(paste(I^M,"spec")), expression(paste(I^bar(M),"sens")),expression(paste(I^bar(M),"spec")), expression("Overall sens"), expression("Overall spec")) methods <- c("CC", "BI","Full","BIgene") nReplicates <- as.numeric(args[12]) #50 replicates (MCMC chains) qcut <- as.numeric(args[14]) # colors <- c(colors()[461], colors()[282], colors()[555], colors()[610]) colors<- c(colors()[26], colors()[261], colors()[35], colors()[614], colors()[621], colors()[121]) #blue, grey, red, green, yellow. light blue[6] print( nReplicates) print(paste("CausalM",nCausalM)) print(paste("CausalMbar",nCausalMbar)) tmp <- rep(NA, nReplicates*length(qcutAll)*length(all_n)) yHatAll <- array(tmp, c(length(all_n),nReplicates, length(qcutAll))) #different from all the other, stores MSE(yHat-yTrue) for each replicate. Store different for each qcut yHatAll_CC <- array(tmp, c(length(all_n),nReplicates, length(qcutAll))) yHatAll_Full <- array(tmp, c(length(all_n),nReplicates, length(qcutAll))) yHatAll_Gene <- array(tmp, c(length(all_n),nReplicates, length(qcutAll))) tmp <- rep(NA, length(all_n)*2*length(qcutAll)) mse <- array(tmp, c(length(all_n), 2, length(qcutAll))) mseCC <- array(tmp, c(length(all_n), 2, length(qcutAll))) mseFull <- array(tmp, c(length(all_n), 2, length(qcutAll))) mseGene <- array(tmp, c(length(all_n), 2, length(qcutAll))) bi <- list() biCC<- list() biFull <- list() biGene <- list() est <- list() estCC <- list() estFull <- list() estGene <- list() pdf(paste(wd,"/TP.pdf",sep="")) par(mfrow=c(1,1),mar=c(5.1,4.1,1.9,2.1),pin=c(4,4)) repLoop <- 1:nReplicates # if(thetaMethy!=0 & thetaGene!=0) ### manually remove unconverged replications by Geweke # repLoop <- (1:nReplicates)[-2] set.seed(seed) for (n in 1:length(all_n)){ # qMSilverIdx <- 1:10 # qMbarSilverIdx <- 1:10 #fix #qMSilverIdx <- which(estSilver$qM < qcut) #qMbarSilverIdx <- which(estSilver$qMbar < qcut) #qMSilverIdx <- order(estSilver$qM) #qMbarSilverIdx <- order(estSilver$qMbar) #Instead of comparing with silver standard, we now compare with the results from each of the full training set: qSilverIdx <- list() geneNamesSilver <- list() tp <- rep(0, nGene) #combining M and Mbar together , so top 1 p is 1M+1Mbar tpCC <- rep(0, nGene) tpGene <- rep(0, nGene) tpCV <- rep(0,nGene) pp <- matrix(0,10, nGene) #combining M and Mbar together , so top 1 p is 1M+1Mbar ppCC <- matrix(0,10, nGene) ppGene <- matrix(0,10, nGene) ppCV <- matrix(0,10,nGene) decisionFinal <- rep(1,length(repLoop)) for (r in repLoop){ # wdSub <- paste(wd,"/n",n,"_r",r,"_Full",sep="") # load(paste(wdSub,"/run.RData",sep="")) # qSilverIdx[[r]] <- order(estFull[[r]]$q) # qSilverIdx[[r]] <- order(estSilver$q) #fix: use silver instead of full for each fold # geneNamesSilver[[r]] <- geneNames[order(estFull[[r]]$q)] geneNamesSilver[[r]] <- geneNames[order(estSilver$q)] # yHatAll_Full[n,r,] <- as.numeric(estFull[[r]]$MSEyHatEst) #MSE(yHat-yTrue) } for (r in repLoop){ wdSub <- paste(wd,"/n",n,"_r",r,"_CV",sep="") load(paste(wdSub,"/run.RData",sep="")) decisionFinal[r] <- which(decisions == max(decisions))[1] } decisions <- decisionFinal repTmp <- 0 repTmpCV <- 0 #repTmpCV for (r in repLoop){ wdSub <- paste(wd,"/n",n,"_r",r,sep="") load(paste(wdSub,"/run.RData",sep="")) yHatAll[n,r,] <- as.numeric(est[[r]]$MSEyHatEst) #MSE(yHat-yTrue) # qMIdx <- order(est[[r]]$qM) # qMbarIdx <- order(est[[r]]$qMbar) shuffleIdx <- sample(1:nGene) # shuffleIdx <- 1:nGene # qIdx <- order(qShuffled) geneNamesShuffle <- (geneNames[shuffleIdx])[ order(est[[r]]$q[shuffleIdx]) ] for(i in 1:nGene){ # tp[i] = tp[i] + length( which(qMIdx[1:i] %in% qMSilverIdx[1:i])) + length( which(qMbarIdx[1:i] %in% qMbarSilverIdx[1:i])) #intead of comparing tp[i] = tp[i] + length( which(geneNamesShuffle[1:i] %in% geneNamesSilver[[r]][1:i]) ) } repTmp <- repTmp +1 for(i in 1:nGene){ # tp[i] = tp[i] + length( which(qMIdx[1:i] %in% qMSilverIdx[1:i])) + length( which(qMbarIdx[1:i] %in% qMbarSilverIdx[1:i])) #intead of comparing tpCV[i] = tpCV[i] + length( which(geneNamesShuffle[1:i] %in% geneNamesSilver[[r]][1:i]) ) } repTmpCV <- repTmpCV + 1 for(i in 1:nGene){ pp[r,i] = length( which(geneNamesShuffle[1:i] %in% geneNamesSilver[[r]][1:i]) ) } } tp <- tp/repTmp tpCV <- tpCV /repTmpCV pp[r,] <- pp[r,] repTmp <- 0 for (r in repLoop){ wdSub <- paste(wd,"/n",n,"_r",r,"_CC",sep="") load(paste(wdSub,"/run.RData",sep="")) yHatAll_CC[n,r,] <- as.numeric(estCC[[r]]$MSEyHatEst) # qMIdx <- order(estCC[[r]]$qM) # qMbarIdx <- order(estCC[[r]]$qMbar) shuffleIdx <- sample(1:nGene) geneNamesShuffle <- (geneNames[shuffleIdx])[ order(estCC[[r]]$q[shuffleIdx]) ] for(i in 1:nGene){ tpCC[i] = tpCC[i] + length( which(geneNamesShuffle[1:i] %in% geneNamesSilver[[r]][1:i]) ) } repTmp <- repTmp +1 for(i in 1:nGene){ ppCC[r,i] = length( which(geneNamesShuffle[1:i] %in% geneNamesSilver[[r]][1:i]) ) } } tpCC <- tpCC/repTmp ppCC[r,] <- ppCC[r,] if(thetaGene !=0 & thetaMethy!=0){ repTmp <- 0 for (r in repLoop){ wdSub <- paste(wd,"/n",n,"_r",r,"_Gene",sep="") load(paste(wdSub,"/run.RData",sep="")) yHatAll_Gene[n,r,] <- as.numeric(estGene[[r]]$MSEyHatEst) # qMIdx <- order(estCC[[r]]$qM) # qMbarIdx <- order(estCC[[r]]$qMbar) # qIdx <- order(estGene[[r]]$q) shuffleIdx <- sample(1:nGene) geneNamesShuffle <- (geneNames[shuffleIdx])[ order(estGene[[r]]$q[shuffleIdx]) ] for(i in 1:nGene){ tpGene[i] = tpGene[i] + length( which(geneNamesShuffle[1:i] %in% geneNamesSilver[[r]][1:i]) ) } repTmp <- repTmp+1 for(i in 1:nGene){ ppGene[r,i] = length( which(geneNamesShuffle[1:i] %in% geneNamesSilver[[r]][1:i]) ) } } # print(tpGene) #print(repTmp) tpGene <- tpGene/repTmp ppGene[r,] <- ppGene[r,] } # maxIdx <- min( max( min(which( tp == 1)), min(which( tpCC == 1)) )*1.4, nGene) maxIdx <- c(nGene,10, 20, 50, 100, 200, 300, 500, length(which(estSilver$q !=1 ))) for(m in 1:length(maxIdx)){ ylimTmp <- max(tp[maxIdx[m]], tpCC[maxIdx[m]])*1.2 plot(0:maxIdx[m], c(0,tp[1:maxIdx[m]]), ylim=c(0, ylimTmp), main=NA, xlab="Positive features",ylab="Overlapped features",sub=paste("nSample",all_n[n]),col=colors[1],type="l") # abline(h=1, col=colors[2],lty=2) curve(0.001*x^2, 0,maxIdx[m], add = TRUE, col = colors[2], lwd=0.7) lines(0:maxIdx[m], c(0,tpCC[1:maxIdx[m]]), col=colors[3],type="l") if(thetaGene !=0 & thetaMethy!=0){ lines(0:maxIdx[m], c(0,tpGene[1:maxIdx[m]]), col=colors[6],type="l") legend("bottomright", bty = "n", c("CC","BI","BIgene"), cex=1, col=colors[c(3,1,6)], lty=c(1,1)) } else{ legend("bottomright", bty = "n", c("CC","BI"), cex=1, col=colors[c(3,1)], lty=c(1,1)) } r = repLoop[1] plot(0:maxIdx[m], c(0,pp[r,1:maxIdx[m]]), ylim=c(0, ylimTmp), main=NA, xlab="Positive features",ylab="Overlapped features",sub=paste("nSample",all_n[n]),col=colors()[180+r],type="l") lines(0:maxIdx[m], c(0,ppCC[r,1:maxIdx[m]]), col=colors()[180+r],lty=2) if(thetaGene !=0 & thetaMethy!=0) lines(0:maxIdx[m], c(0,ppGene[r,1:maxIdx[m]]), col=colors()[180+r],lty=3) # legend("bottomright", bty = "n", c("CC","BI"), cex=1, col=colors[c(3,1)], lty=c(1,1)) for(r in repLoop[-1]){ lines(0:maxIdx[m], c(0,pp[r,1:maxIdx[m]]), col=colors()[180+ r],lty=1) text(maxIdx[m]-2*r, pp[r,maxIdx[m]], r) lines(0:maxIdx[m], c(0,ppCC[r,1:maxIdx[m]]), col=colors()[180+r],lty=2) text(maxIdx[m]-2*r, ppCC[r,maxIdx[m]], r) if(thetaGene !=0 & thetaMethy!=0){ lines(0:maxIdx[m], c(0,ppGene[r,1:maxIdx[m]]), col=colors()[180+r],lty=3) text(maxIdx[m]-2*r, ppGene[r,maxIdx[m]], r) # legend("bottomright", bty = "n", c("CC","BI","BIgene"), cex=1, col=colors[c(3,1,6)], lty=c(1,1)) } } } if (thetaGene==0) save(tp, tpCC, tpGene,tpCV,file=paste("~/BI/SAll/0_05_pp.RData", sep="")) if (thetaMethy==0) save(tp, tpCC, tpGene,tpCV,file=paste("~/BI/SAll/05_0_pp.RData", sep="")) if (thetaGene!=0 & thetaMethy!=0) save(tp, tpCC, tpGene,tpCV,file=paste("~/BI/SAll/02_02_pp.RData", sep="")) } dev.off() for(q in 1:length(qcutAll)){ for(n in 1:length(all_n)){ mse[n,1,q] <- signif( mean(yHatAll[n,,q],na.rm=TRUE), 3) mse[n,2,q] <- signif( sd(yHatAll[n,,q],na.rm=TRUE)/sqrt(length(repLoop)), 3) mseCC[n,1,q] <- signif( mean(yHatAll_CC[n,,q],na.rm=TRUE), 3) mseCC[n,2,q] <- signif( sd(yHatAll_CC[n,,q],na.rm=TRUE)/sqrt(length(repLoop)), 3) # mseFull[n,1,q] <- signif( mean(yHatAll_Full[n,,q],na.rm=TRUE), 3) # mseFull[n,2,q] <- signif( sd(yHatAll_Full[n,,q],na.rm=TRUE)/sqrt(length(repLoop)), 3) if(thetaGene !=0 & thetaMethy!=0){ mseGene[n,1,q] <- signif( mean(yHatAll_Gene[n,,q],na.rm=TRUE), 3) mseGene[n,2,q] <- signif( sd(yHatAll_Gene[n,,q],na.rm=TRUE)/sqrt(length(repLoop)), 3) } } } save(mse, mseCC,mseFull,mseGene, yHatAll, yHatAll_CC, yHatAll_Full,yHatAll_Gene,all_n, decisions, file=paste(wd, "/mse.RData", sep="")) ## print(mse) ## print(mseCC) ## print(mseFull) ## print(mseGene) ## pdf(paste(wd,"/MSEyHat.pdf",sep="")) ## par(mfrow=c(1,1),mar=c(5.1,4.1,1.9,2.1),pin=c(4,4)) ## x <- 1:length(all_n) ## barEpsilon <- 0.04 ## #plot MSE(yhat) and feature selections separatedly ## for(q in 1:length(qcutAll)){ ## # ylimTmp <- max(mse[x,1,q],mseCC[x,1,q], mseFull[x,1,q]) + max(mse[x,2,q],mseCC[x,2,q], mseFull[x,2,q]) ## ylimTmp <- max(mse[x,1,q],mseCC[x,1,q]) + max(mse[x,2,q],mseCC[x,2,q]+10) ## ylimTmp <- ylimTmp*1.2 ## # ylimTmpNeg <- min(mse[x,1,q],mseCC[x,1,q],mseFull[x,1,q])-max(mse[x,2,q],mseCC[x,2,q],mseFull[x,2,q]) ## ylimTmpNeg <- min(mse[x,1,q],mseCC[x,1,q])-max(mse[x,2,q],mseCC[x,2,q]) ## ylimTmpNeg<-min(ylimTmpNeg*1.1,-10) ## plot(x, mse[x,1,q], ylim=c(ylimTmpNeg,ylimTmp),xlab="N",main=paste("FDR <",qcutAll[q]), ## ylab="MSE",xaxt="n",col=colors[1],type="l") ## axis(1,at=x,label=all_n[x],las=2,cex.axis=0.8) ## segments(x,mse[x,1,q]-mse[x,2,q], x, mse[x,1,q]+mse[x,2,q],col=colors[1]) ## segments(x-barEpsilon, mse[x,1,q]-mse[x,2,q], x+barEpsilon, mse[x,1,q]-mse[x,2,q],col=colors[1] ) ## segments(x-barEpsilon, mse[x,1,q]+mse[x,2,q], x+barEpsilon, mse[x,1,q]+mse[x,2,q],col=colors[1] ) ## lines(x+barEpsilon, mseCC[x,1,q],col=colors[3],type="l") ## segments(x+barEpsilon,mseCC[x,1,q]-mseCC[x,2,q], x+barEpsilon, mseCC[x,1,q]+mseCC[x,2,q],col=colors[3]) ## segments(x, mseCC[x,1,q]-mseCC[x,2,q], x+2*barEpsilon, mseCC[x,1,q]-mseCC[x,2,q],col=colors[3] ) ## segments(x, mseCC[x,1,q]+mseCC[x,2,q], x+2*barEpsilon, mseCC[x,1,q]+mseCC[x,2,q],col=colors[3] ) ## # lines(x+barEpsilon, mseFull[x,1,q],col=colors[4],type="l") ## # segments(x+barEpsilon,mseFull[x,1,q]-mseFull[x,2,q], x+barEpsilon, mseFull[x,1,q]+mseFull[x,2,q],col=colors[4]) ## # segments(x, mseFull[x,1,q]-mseFull[x,2,q], x+2*barEpsilon, mseFull[x,1,q]-mseFull[x,2,q],col=colors[4] ) ## # segments(x, mseFull[x,1,q]+mseFull[x,2,q], x+2*barEpsilon, mseFull[x,1,q]+mseFull[x,2,q],col=colors[4] ) ## if(thetaGene !=0 & thetaMethy!=0){ ## lines(x+barEpsilon, mseGene[x,1,q],col=colors[6],type="l") ## segments(x+barEpsilon,mseGene[x,1,q]-mseGene[x,2,q], x+barEpsilon, mseGene[x,1,q]+mseGene[x,2,q],col=colors[6]) ## segments(x, mseGene[x,1,q]-mseGene[x,2,q], x+2*barEpsilon, mseGene[x,1,q]-mseGene[x,2,q],col=colors[6] ) ## segments(x, mseGene[x,1,q]+mseGene[x,2,q], x+2*barEpsilon, mseGene[x,1,q]+mseGene[x,2,q],col=colors[6] ) ## # legend("topright", bty = "n", methods, cex=0.8, col=colors[c(3,1,4,6)], lty=c(1,1,1,1)) ## legend("topright", bty = "n", methods[c(1,2,4)], cex=0.8, col=colors[c(3,1,6)], lty=c(1,1,1)) ## } else{ ## legend("topright", bty = "n", methods[1:3], cex=0.8, col=colors[c(3,1)], lty=c(1,1)) ## } ## # abline(epsilon^2,0,col=colors[2],lty=2) #mse of yhat should shrink to sigma^2 ## } ## dev.off() print("Done for varying nSample") }
/bioinformatics_replication_code/BIsummarySilver.R
no_license
6guojun/FBM
R
false
false
16,944
r
args = commandArgs(trailingOnly=TRUE) require(MCMCpack) library(doParallel) library(foreach) library(cluster) library(Rcpp) library(RcppArmadillo) library(RcppGSL) library(scales) library(coda) #Sys.setenv("PKG_CXXFLAGS"="-std=c++11") #sourceCpp("~/BI/BI.cpp") qcutAll <- c(0.05, 0.1, 0.15, 0.2, 0.25, 0.3) localTest <- 0 singleTest <- 0 multipleReplicates <- 0 fullRun <- 0 if(args[7] == "local"){ localTest <- 1 } else if (args[7] == "single"){ singleTest <- 1 } else if (args[7] == "multiple"){ multipleReplicates <- 1 } else if (args[7] == "full"){ fullRun <- 1 } Mode <- function(x) { ux <- unique(x) ux[which.max(tabulate(match(x, ux)))] } ####################################################### ### Bayesian Imputation (BI) with gene/methy missing ## ####################################################### #now using Rcpp BFDR <- function(Ipm, n, nGene){ #Ipm is the feature selection posterior mean. BFDRtmp <- matrix(NA,nGene,2) #t, BFDR(t) PMtmp <- rep(NA, nGene) qtmp <- rep(NA, nGene) # PMtmp <- 2*( 1- pt( abs((est[[r]]$gammaMEst) / (est[[r]]$gammaMSd / sqrt(all_n[n]))), all_n[n]-1) ) #PMtmp <- 2*( 1- pt( abs(mean) / (sd / sqrt(n)), n-1) ) PMtmp <- 1-Ipm sortedPM <- sort(PMtmp) for(k in 1:nGene){ BFDRtmp[k,1] <- sortedPM[k] BFDRtmp[k,2] <- sum(sortedPM[1:k])/k } for(k in 1:nGene){ qtmp[k] <- min( BFDRtmp[ which(BFDRtmp[,1] >= PMtmp[k]), 2] ) } return(list(q=qtmp)) } nGene <- as.numeric(args[8]) nCausalM <- as.numeric(args[9]) nCausalMbar <- as.numeric(args[10]) nMethy <- as.numeric(args[11]) nC <- 2 exchangeable <- FALSE MCAR <- TRUE nGene<-1000 nMethy <- 2619 #nCausalM <- 10 #fix #nCausalMbar <- 10 if( fullRun | multipleReplicates ){ wd <- args[1] setwd(wd) noCFlag <- 0 #flag for no clinical variable input nCtmp <- nC if(nC==0){ noCFlag=1 nCtmp <- 1 } nItr <- as.numeric(args[4]) seed <- as.numeric(args[3]) thetaGene <- as.numeric(args[5]) thetaMethy <- as.numeric(args[6]) # cl <- makeCluster(as.numeric(args[2])) # registerDoParallel(cl) # all_n <- c(20,30,50,100,200,500) # all_n <- c(50,100,200,500) all_n <- c(460) if(args[13] == "strong"){ epsilon <- 0.01 } else if( args[13]=="mid"){ epsilon <- 0.5 } else if( args[13]=="weak"){ epsilon <- 2 }else if( args[13]=="midstrong"){ epsilon <- 0.1 }else if( args[13]=="superweak"){ epsilon <- 3 }else if( args[13]=="ultraweak"){ epsilon <- 5 } epsilonGeneMbar <- 2 if( multipleReplicates ){ all_n <- 100 } load("~/BI/nasal/nasalProcessed.rdata") geneNames <- colnames(gene) load(paste(wd, "/dataSilver.rdata",sep="")) nGene= dim(dataSilver$geneMTrue)[2] nMethy = dim(dataSilver$methyTrue)[2] nCausalM <- length(dataSilver$causalGeneMIdx) nCausalMbar <- length(dataSilver$causalGeneMbarIdx) parNames <- c( expression(paste(gamma^M," causal")), expression(paste(gamma^bar(M), " causal")), expression(paste(gamma^M, " non-causal")), expression(paste(gamma^bar(M), " non-causal")), expression(gamma^C), expression(omega), expression(hat(Y))) nPar <- length(parNames) # gammaM_causal, gammaMbar_causal,gammaM_nc, gammaMbar_nc, gammaC, omegaMean, yHat sensSpecNames <- c( expression(paste(I^M,"sens")), expression(paste(I^M,"spec")), expression(paste(I^bar(M),"sens")),expression(paste(I^bar(M),"spec")), expression("Overall sens"), expression("Overall spec")) methods <- c("CC", "BI","Full","BIgene") nReplicates <- as.numeric(args[12]) #50 replicates (MCMC chains) qcut <- as.numeric(args[14]) # colors <- c(colors()[461], colors()[282], colors()[555], colors()[610]) colors<- c(colors()[26], colors()[261], colors()[35], colors()[614], colors()[621], colors()[121]) #blue, grey, red, green, yellow. light blue[6] print( nReplicates) print(paste("CausalM",nCausalM)) print(paste("CausalMbar",nCausalMbar)) tmp <- rep(NA, nReplicates*length(qcutAll)*length(all_n)) yHatAll <- array(tmp, c(length(all_n),nReplicates, length(qcutAll))) #different from all the other, stores MSE(yHat-yTrue) for each replicate. Store different for each qcut yHatAll_CC <- array(tmp, c(length(all_n),nReplicates, length(qcutAll))) yHatAll_Full <- array(tmp, c(length(all_n),nReplicates, length(qcutAll))) yHatAll_Gene <- array(tmp, c(length(all_n),nReplicates, length(qcutAll))) tmp <- rep(NA, length(all_n)*2*length(qcutAll)) mse <- array(tmp, c(length(all_n), 2, length(qcutAll))) mseCC <- array(tmp, c(length(all_n), 2, length(qcutAll))) mseFull <- array(tmp, c(length(all_n), 2, length(qcutAll))) mseGene <- array(tmp, c(length(all_n), 2, length(qcutAll))) bi <- list() biCC<- list() biFull <- list() biGene <- list() est <- list() estCC <- list() estFull <- list() estGene <- list() pdf(paste(wd,"/TP.pdf",sep="")) par(mfrow=c(1,1),mar=c(5.1,4.1,1.9,2.1),pin=c(4,4)) repLoop <- 1:nReplicates # if(thetaMethy!=0 & thetaGene!=0) ### manually remove unconverged replications by Geweke # repLoop <- (1:nReplicates)[-2] set.seed(seed) for (n in 1:length(all_n)){ # qMSilverIdx <- 1:10 # qMbarSilverIdx <- 1:10 #fix #qMSilverIdx <- which(estSilver$qM < qcut) #qMbarSilverIdx <- which(estSilver$qMbar < qcut) #qMSilverIdx <- order(estSilver$qM) #qMbarSilverIdx <- order(estSilver$qMbar) #Instead of comparing with silver standard, we now compare with the results from each of the full training set: qSilverIdx <- list() geneNamesSilver <- list() tp <- rep(0, nGene) #combining M and Mbar together , so top 1 p is 1M+1Mbar tpCC <- rep(0, nGene) tpGene <- rep(0, nGene) tpCV <- rep(0,nGene) pp <- matrix(0,10, nGene) #combining M and Mbar together , so top 1 p is 1M+1Mbar ppCC <- matrix(0,10, nGene) ppGene <- matrix(0,10, nGene) ppCV <- matrix(0,10,nGene) decisionFinal <- rep(1,length(repLoop)) for (r in repLoop){ # wdSub <- paste(wd,"/n",n,"_r",r,"_Full",sep="") # load(paste(wdSub,"/run.RData",sep="")) # qSilverIdx[[r]] <- order(estFull[[r]]$q) # qSilverIdx[[r]] <- order(estSilver$q) #fix: use silver instead of full for each fold # geneNamesSilver[[r]] <- geneNames[order(estFull[[r]]$q)] geneNamesSilver[[r]] <- geneNames[order(estSilver$q)] # yHatAll_Full[n,r,] <- as.numeric(estFull[[r]]$MSEyHatEst) #MSE(yHat-yTrue) } for (r in repLoop){ wdSub <- paste(wd,"/n",n,"_r",r,"_CV",sep="") load(paste(wdSub,"/run.RData",sep="")) decisionFinal[r] <- which(decisions == max(decisions))[1] } decisions <- decisionFinal repTmp <- 0 repTmpCV <- 0 #repTmpCV for (r in repLoop){ wdSub <- paste(wd,"/n",n,"_r",r,sep="") load(paste(wdSub,"/run.RData",sep="")) yHatAll[n,r,] <- as.numeric(est[[r]]$MSEyHatEst) #MSE(yHat-yTrue) # qMIdx <- order(est[[r]]$qM) # qMbarIdx <- order(est[[r]]$qMbar) shuffleIdx <- sample(1:nGene) # shuffleIdx <- 1:nGene # qIdx <- order(qShuffled) geneNamesShuffle <- (geneNames[shuffleIdx])[ order(est[[r]]$q[shuffleIdx]) ] for(i in 1:nGene){ # tp[i] = tp[i] + length( which(qMIdx[1:i] %in% qMSilverIdx[1:i])) + length( which(qMbarIdx[1:i] %in% qMbarSilverIdx[1:i])) #intead of comparing tp[i] = tp[i] + length( which(geneNamesShuffle[1:i] %in% geneNamesSilver[[r]][1:i]) ) } repTmp <- repTmp +1 for(i in 1:nGene){ # tp[i] = tp[i] + length( which(qMIdx[1:i] %in% qMSilverIdx[1:i])) + length( which(qMbarIdx[1:i] %in% qMbarSilverIdx[1:i])) #intead of comparing tpCV[i] = tpCV[i] + length( which(geneNamesShuffle[1:i] %in% geneNamesSilver[[r]][1:i]) ) } repTmpCV <- repTmpCV + 1 for(i in 1:nGene){ pp[r,i] = length( which(geneNamesShuffle[1:i] %in% geneNamesSilver[[r]][1:i]) ) } } tp <- tp/repTmp tpCV <- tpCV /repTmpCV pp[r,] <- pp[r,] repTmp <- 0 for (r in repLoop){ wdSub <- paste(wd,"/n",n,"_r",r,"_CC",sep="") load(paste(wdSub,"/run.RData",sep="")) yHatAll_CC[n,r,] <- as.numeric(estCC[[r]]$MSEyHatEst) # qMIdx <- order(estCC[[r]]$qM) # qMbarIdx <- order(estCC[[r]]$qMbar) shuffleIdx <- sample(1:nGene) geneNamesShuffle <- (geneNames[shuffleIdx])[ order(estCC[[r]]$q[shuffleIdx]) ] for(i in 1:nGene){ tpCC[i] = tpCC[i] + length( which(geneNamesShuffle[1:i] %in% geneNamesSilver[[r]][1:i]) ) } repTmp <- repTmp +1 for(i in 1:nGene){ ppCC[r,i] = length( which(geneNamesShuffle[1:i] %in% geneNamesSilver[[r]][1:i]) ) } } tpCC <- tpCC/repTmp ppCC[r,] <- ppCC[r,] if(thetaGene !=0 & thetaMethy!=0){ repTmp <- 0 for (r in repLoop){ wdSub <- paste(wd,"/n",n,"_r",r,"_Gene",sep="") load(paste(wdSub,"/run.RData",sep="")) yHatAll_Gene[n,r,] <- as.numeric(estGene[[r]]$MSEyHatEst) # qMIdx <- order(estCC[[r]]$qM) # qMbarIdx <- order(estCC[[r]]$qMbar) # qIdx <- order(estGene[[r]]$q) shuffleIdx <- sample(1:nGene) geneNamesShuffle <- (geneNames[shuffleIdx])[ order(estGene[[r]]$q[shuffleIdx]) ] for(i in 1:nGene){ tpGene[i] = tpGene[i] + length( which(geneNamesShuffle[1:i] %in% geneNamesSilver[[r]][1:i]) ) } repTmp <- repTmp+1 for(i in 1:nGene){ ppGene[r,i] = length( which(geneNamesShuffle[1:i] %in% geneNamesSilver[[r]][1:i]) ) } } # print(tpGene) #print(repTmp) tpGene <- tpGene/repTmp ppGene[r,] <- ppGene[r,] } # maxIdx <- min( max( min(which( tp == 1)), min(which( tpCC == 1)) )*1.4, nGene) maxIdx <- c(nGene,10, 20, 50, 100, 200, 300, 500, length(which(estSilver$q !=1 ))) for(m in 1:length(maxIdx)){ ylimTmp <- max(tp[maxIdx[m]], tpCC[maxIdx[m]])*1.2 plot(0:maxIdx[m], c(0,tp[1:maxIdx[m]]), ylim=c(0, ylimTmp), main=NA, xlab="Positive features",ylab="Overlapped features",sub=paste("nSample",all_n[n]),col=colors[1],type="l") # abline(h=1, col=colors[2],lty=2) curve(0.001*x^2, 0,maxIdx[m], add = TRUE, col = colors[2], lwd=0.7) lines(0:maxIdx[m], c(0,tpCC[1:maxIdx[m]]), col=colors[3],type="l") if(thetaGene !=0 & thetaMethy!=0){ lines(0:maxIdx[m], c(0,tpGene[1:maxIdx[m]]), col=colors[6],type="l") legend("bottomright", bty = "n", c("CC","BI","BIgene"), cex=1, col=colors[c(3,1,6)], lty=c(1,1)) } else{ legend("bottomright", bty = "n", c("CC","BI"), cex=1, col=colors[c(3,1)], lty=c(1,1)) } r = repLoop[1] plot(0:maxIdx[m], c(0,pp[r,1:maxIdx[m]]), ylim=c(0, ylimTmp), main=NA, xlab="Positive features",ylab="Overlapped features",sub=paste("nSample",all_n[n]),col=colors()[180+r],type="l") lines(0:maxIdx[m], c(0,ppCC[r,1:maxIdx[m]]), col=colors()[180+r],lty=2) if(thetaGene !=0 & thetaMethy!=0) lines(0:maxIdx[m], c(0,ppGene[r,1:maxIdx[m]]), col=colors()[180+r],lty=3) # legend("bottomright", bty = "n", c("CC","BI"), cex=1, col=colors[c(3,1)], lty=c(1,1)) for(r in repLoop[-1]){ lines(0:maxIdx[m], c(0,pp[r,1:maxIdx[m]]), col=colors()[180+ r],lty=1) text(maxIdx[m]-2*r, pp[r,maxIdx[m]], r) lines(0:maxIdx[m], c(0,ppCC[r,1:maxIdx[m]]), col=colors()[180+r],lty=2) text(maxIdx[m]-2*r, ppCC[r,maxIdx[m]], r) if(thetaGene !=0 & thetaMethy!=0){ lines(0:maxIdx[m], c(0,ppGene[r,1:maxIdx[m]]), col=colors()[180+r],lty=3) text(maxIdx[m]-2*r, ppGene[r,maxIdx[m]], r) # legend("bottomright", bty = "n", c("CC","BI","BIgene"), cex=1, col=colors[c(3,1,6)], lty=c(1,1)) } } } if (thetaGene==0) save(tp, tpCC, tpGene,tpCV,file=paste("~/BI/SAll/0_05_pp.RData", sep="")) if (thetaMethy==0) save(tp, tpCC, tpGene,tpCV,file=paste("~/BI/SAll/05_0_pp.RData", sep="")) if (thetaGene!=0 & thetaMethy!=0) save(tp, tpCC, tpGene,tpCV,file=paste("~/BI/SAll/02_02_pp.RData", sep="")) } dev.off() for(q in 1:length(qcutAll)){ for(n in 1:length(all_n)){ mse[n,1,q] <- signif( mean(yHatAll[n,,q],na.rm=TRUE), 3) mse[n,2,q] <- signif( sd(yHatAll[n,,q],na.rm=TRUE)/sqrt(length(repLoop)), 3) mseCC[n,1,q] <- signif( mean(yHatAll_CC[n,,q],na.rm=TRUE), 3) mseCC[n,2,q] <- signif( sd(yHatAll_CC[n,,q],na.rm=TRUE)/sqrt(length(repLoop)), 3) # mseFull[n,1,q] <- signif( mean(yHatAll_Full[n,,q],na.rm=TRUE), 3) # mseFull[n,2,q] <- signif( sd(yHatAll_Full[n,,q],na.rm=TRUE)/sqrt(length(repLoop)), 3) if(thetaGene !=0 & thetaMethy!=0){ mseGene[n,1,q] <- signif( mean(yHatAll_Gene[n,,q],na.rm=TRUE), 3) mseGene[n,2,q] <- signif( sd(yHatAll_Gene[n,,q],na.rm=TRUE)/sqrt(length(repLoop)), 3) } } } save(mse, mseCC,mseFull,mseGene, yHatAll, yHatAll_CC, yHatAll_Full,yHatAll_Gene,all_n, decisions, file=paste(wd, "/mse.RData", sep="")) ## print(mse) ## print(mseCC) ## print(mseFull) ## print(mseGene) ## pdf(paste(wd,"/MSEyHat.pdf",sep="")) ## par(mfrow=c(1,1),mar=c(5.1,4.1,1.9,2.1),pin=c(4,4)) ## x <- 1:length(all_n) ## barEpsilon <- 0.04 ## #plot MSE(yhat) and feature selections separatedly ## for(q in 1:length(qcutAll)){ ## # ylimTmp <- max(mse[x,1,q],mseCC[x,1,q], mseFull[x,1,q]) + max(mse[x,2,q],mseCC[x,2,q], mseFull[x,2,q]) ## ylimTmp <- max(mse[x,1,q],mseCC[x,1,q]) + max(mse[x,2,q],mseCC[x,2,q]+10) ## ylimTmp <- ylimTmp*1.2 ## # ylimTmpNeg <- min(mse[x,1,q],mseCC[x,1,q],mseFull[x,1,q])-max(mse[x,2,q],mseCC[x,2,q],mseFull[x,2,q]) ## ylimTmpNeg <- min(mse[x,1,q],mseCC[x,1,q])-max(mse[x,2,q],mseCC[x,2,q]) ## ylimTmpNeg<-min(ylimTmpNeg*1.1,-10) ## plot(x, mse[x,1,q], ylim=c(ylimTmpNeg,ylimTmp),xlab="N",main=paste("FDR <",qcutAll[q]), ## ylab="MSE",xaxt="n",col=colors[1],type="l") ## axis(1,at=x,label=all_n[x],las=2,cex.axis=0.8) ## segments(x,mse[x,1,q]-mse[x,2,q], x, mse[x,1,q]+mse[x,2,q],col=colors[1]) ## segments(x-barEpsilon, mse[x,1,q]-mse[x,2,q], x+barEpsilon, mse[x,1,q]-mse[x,2,q],col=colors[1] ) ## segments(x-barEpsilon, mse[x,1,q]+mse[x,2,q], x+barEpsilon, mse[x,1,q]+mse[x,2,q],col=colors[1] ) ## lines(x+barEpsilon, mseCC[x,1,q],col=colors[3],type="l") ## segments(x+barEpsilon,mseCC[x,1,q]-mseCC[x,2,q], x+barEpsilon, mseCC[x,1,q]+mseCC[x,2,q],col=colors[3]) ## segments(x, mseCC[x,1,q]-mseCC[x,2,q], x+2*barEpsilon, mseCC[x,1,q]-mseCC[x,2,q],col=colors[3] ) ## segments(x, mseCC[x,1,q]+mseCC[x,2,q], x+2*barEpsilon, mseCC[x,1,q]+mseCC[x,2,q],col=colors[3] ) ## # lines(x+barEpsilon, mseFull[x,1,q],col=colors[4],type="l") ## # segments(x+barEpsilon,mseFull[x,1,q]-mseFull[x,2,q], x+barEpsilon, mseFull[x,1,q]+mseFull[x,2,q],col=colors[4]) ## # segments(x, mseFull[x,1,q]-mseFull[x,2,q], x+2*barEpsilon, mseFull[x,1,q]-mseFull[x,2,q],col=colors[4] ) ## # segments(x, mseFull[x,1,q]+mseFull[x,2,q], x+2*barEpsilon, mseFull[x,1,q]+mseFull[x,2,q],col=colors[4] ) ## if(thetaGene !=0 & thetaMethy!=0){ ## lines(x+barEpsilon, mseGene[x,1,q],col=colors[6],type="l") ## segments(x+barEpsilon,mseGene[x,1,q]-mseGene[x,2,q], x+barEpsilon, mseGene[x,1,q]+mseGene[x,2,q],col=colors[6]) ## segments(x, mseGene[x,1,q]-mseGene[x,2,q], x+2*barEpsilon, mseGene[x,1,q]-mseGene[x,2,q],col=colors[6] ) ## segments(x, mseGene[x,1,q]+mseGene[x,2,q], x+2*barEpsilon, mseGene[x,1,q]+mseGene[x,2,q],col=colors[6] ) ## # legend("topright", bty = "n", methods, cex=0.8, col=colors[c(3,1,4,6)], lty=c(1,1,1,1)) ## legend("topright", bty = "n", methods[c(1,2,4)], cex=0.8, col=colors[c(3,1,6)], lty=c(1,1,1)) ## } else{ ## legend("topright", bty = "n", methods[1:3], cex=0.8, col=colors[c(3,1)], lty=c(1,1)) ## } ## # abline(epsilon^2,0,col=colors[2],lty=2) #mse of yhat should shrink to sigma^2 ## } ## dev.off() print("Done for varying nSample") }
# Compare fraction spliced in each of the experiments # and methods setwd("../") library(diem) library(ggplot2) library(ggpubr) library(gridExtra) library(scales) source("scripts/common/plotting.R") #========================================= # Plot functions #========================================= ct <- theme(legend.position="none", text=element_text(size=16), plot.title=element_text(size=18, hjust=0.5, face="bold") ) yexp <- 1.1 xa_angle <- 30 hj <- 0.9 ts <- 18 #========================================= #========================================= # Labels at_labs <- c("AT1", "AT2", "AT3", "AT4", "AT5", "AT6") samples <- c("adpcyte", "mouse_nuclei_2k", at_labs) expr <- c("adpcyte", "mouse_nuclei_2k", rep("atsn", 6)) names(samples) <- expr labels <- c("DiffPA", "Mouse Brain", at_labs) names(labels) <- samples mthds <- c("DIEM", "EmptyDrops", "Quantile") #========================================= # Read in data #========================================= all_sf <- read.table("data/processed/meta_data.txt", header=TRUE, sep="\t") all_sf <- all_sf[all_sf[,"n_genes"] >= 200,] all_sf[,"Exprm"] <- factor(all_sf[,"Exprm"], levels=unique(expr)) all_sf[,"Sample"] <- factor(all_sf[,"Sample"], levels=samples) all_sf[,"Label"] <- factor(all_sf[,"Label"], levels=labels) all_sf[,"SpliceFrctn"] <- all_sf[,"SpliceFrctn"] / 100 midpoints <- read.table("data/raw/splice_frctn/midpoints.txt", stringsAsFactors=FALSE) rownames(midpoints) <- midpoints[,1] midpoints[,1] <- labels[midpoints[,1]] colnames(midpoints) <- c("Label", "h") midpoints[,"Label"] <- factor(midpoints[,"Label"], levels = labels) #========================================= # Plot method vs fraction spliced in passing droplets #========================================= datf <- subset(all_sf, Call == "Clean") p <- ggplot(datf, aes(x = Method, y = SpliceFrctn)) + geom_boxplot(outlier.shape = NA) + geom_jitter(alpha = 0.1, width = 0.1, shape=16) + facet_wrap(~Label, nrow = 1) + geom_abline(data = midpoints, aes(intercept = h, slope = 0, col="red")) + ylab("Percent spliced reads\nin passingd droplets") + theme_bw() + ct + scale_y_continuous(labels = scales::percent, breaks = c(0, .25, .5, .75, 1), limits = c(0, 1.25)) + theme(strip.background = element_blank(), strip.placement = "outside", text=element_text(size=ts), axis.title = element_text(size = 20), axis.title.y = element_text(size = 22), axis.text.x = element_text(angle=xa_angle,hjust=hj), strip.text = element_text(size = 20)) dir_plot <- "results/plots/" outfn <- paste0(dir_plot, "method.sample.pct_sf_droplet.clean.jpeg") ggsave(outfn, width = 20, height = 4) outfn <- paste0(dir_plot, "method.sample.pct_sf_droplet.clean.pdf") ggsave(outfn, width = 20, height = 4) #========================================= # Plot method vs fraction spliced in debris droplets #========================================= datf <- subset(all_sf, Call == "Debris") p <- ggplot(datf, aes(x = Method, y = SpliceFrctn)) + geom_boxplot(outlier.shape = NA) + geom_jitter(alpha = 0.1, width = 0.1, shape=16) + facet_wrap(~Label, nrow = 1) + geom_abline(data = midpoints, aes(intercept = h, slope = 0, col="red")) + ylab("Percent spliced reads\nin removed droplets") + scale_y_continuous(labels = scales::percent, breaks = c(0, .25, .5, .75, 1), limits = c(0, 1.25)) + theme_bw() + ct + theme(strip.background = element_blank(), strip.placement = "outside", text=element_text(size=ts), axis.title = element_text(size = 20), axis.title.y = element_text(size = 22), axis.text.x = element_text(angle=xa_angle,hjust=hj), strip.text = element_text(size = 20)) dir_plot <- "results/plots/" outfn <- paste0(dir_plot, "method.sample.pct_sf_droplet.debris.jpeg") ggsave(outfn, width = 20, height = 4) outfn <- paste0(dir_plot, "method.sample.pct_sf_droplet.debris.pdf") ggsave(outfn, width = 20, height = 4) #========================================= # Run stats #========================================= sf_col <- "SpliceFrctn" # Wilcox test of droplets datf_s <- all_sf[all_sf[,"Call"] == "Clean",] for (s in samples){ datf <- datf_s[datf_s[,"Sample"] == s,] qcl <- datf$Method == "Quantile" dcl <- datf$Method == "DIEM" print(s) tr <- wilcox.test(datf[qcl,sf_col], datf[dcl,sf_col], conf.int=T) message("\t", tr$estimate) message("\t", tr$p.value * 8) } for (s in samples){ datf <- datf_s[datf_s[,"Sample"] == s,] ecl <- datf$Method == "EmptyDrops" dcl <- datf$Method == "DIEM" print(s) tr <- wilcox.test(datf[ecl,sf_col], datf[dcl,sf_col], conf.int=T) message("\t", tr$estimate) message("\t", tr$p.value) * 8 } datf_s <- all_sf[all_sf[,"Call"] == "Debris",] for (s in samples){ datf <- datf_s[datf_s[,"Sample"] == s,] qcl <- datf$Method == "Quantile" dcl <- datf$Method == "DIEM" print(s) tr <- wilcox.test(datf[qcl,sf_col], datf[dcl,sf_col], conf.int=T) message("\t", tr$estimate) message("\t", tr$p.value * 8) } for (s in samples){ datf <- datf_s[datf_s[,"Sample"] == s,] ecl <- datf$Method == "EmptyDrops" dcl <- datf$Method == "DIEM" print(s) tr <- wilcox.test(datf[ecl,sf_col], datf[dcl,sf_col], conf.int=T) message("\t", tr$estimate) message("\t", tr$p.value) * 8 } # Quantifications datf_s <- all_sf[all_sf$Call == "Clean",] s <- "adpcyte" for (m in mthds){ k <- datf_s$Method == m & datf_s$Sample == s tb <- table(datf_s[k,"Truth"]) tbb <- tb["Background"] tbc <- tb["Nuclear"] tall <- sum(tb) message(m, "\t: all:", tall, "; BG: ", tbb, "(", 100*tbb/tall, ")", "; N: ", tbc, "(", 100*tbc/tall, ")") } s <- "mouse_nuclei_2k" for (m in mthds){ k <- datf_s$Method == m & datf_s$Sample == s tb <- table(datf_s[k,"Truth"]) tbb <- tb["Background"] tbc <- tb["Nuclear"] tall <- sum(tb) message(m, "\t: all:", tall, "; BG: ", tbb, "(", 100*tbb/tall, ")", "; N: ", tbc, "(", 100*tbc/tall, ")") } e <- "atsn" for (m in mthds){ k <- datf_s$Method == m & datf_s$Exprm == e tb <- table(datf_s[k,"Truth"]) tbb <- tb["Background"] tbc <- tb["Nuclear"] tall <- sum(tb) message(m, "\t: all:", tall, "; BG: ", tbb, "(", 100*tbb/tall, ")", "; N: ", tbc, "(", 100*tbc/tall, ")") }
/scripts/plot_method.droplet_sf.R
no_license
marcalva/DIEM2019
R
false
false
6,499
r
# Compare fraction spliced in each of the experiments # and methods setwd("../") library(diem) library(ggplot2) library(ggpubr) library(gridExtra) library(scales) source("scripts/common/plotting.R") #========================================= # Plot functions #========================================= ct <- theme(legend.position="none", text=element_text(size=16), plot.title=element_text(size=18, hjust=0.5, face="bold") ) yexp <- 1.1 xa_angle <- 30 hj <- 0.9 ts <- 18 #========================================= #========================================= # Labels at_labs <- c("AT1", "AT2", "AT3", "AT4", "AT5", "AT6") samples <- c("adpcyte", "mouse_nuclei_2k", at_labs) expr <- c("adpcyte", "mouse_nuclei_2k", rep("atsn", 6)) names(samples) <- expr labels <- c("DiffPA", "Mouse Brain", at_labs) names(labels) <- samples mthds <- c("DIEM", "EmptyDrops", "Quantile") #========================================= # Read in data #========================================= all_sf <- read.table("data/processed/meta_data.txt", header=TRUE, sep="\t") all_sf <- all_sf[all_sf[,"n_genes"] >= 200,] all_sf[,"Exprm"] <- factor(all_sf[,"Exprm"], levels=unique(expr)) all_sf[,"Sample"] <- factor(all_sf[,"Sample"], levels=samples) all_sf[,"Label"] <- factor(all_sf[,"Label"], levels=labels) all_sf[,"SpliceFrctn"] <- all_sf[,"SpliceFrctn"] / 100 midpoints <- read.table("data/raw/splice_frctn/midpoints.txt", stringsAsFactors=FALSE) rownames(midpoints) <- midpoints[,1] midpoints[,1] <- labels[midpoints[,1]] colnames(midpoints) <- c("Label", "h") midpoints[,"Label"] <- factor(midpoints[,"Label"], levels = labels) #========================================= # Plot method vs fraction spliced in passing droplets #========================================= datf <- subset(all_sf, Call == "Clean") p <- ggplot(datf, aes(x = Method, y = SpliceFrctn)) + geom_boxplot(outlier.shape = NA) + geom_jitter(alpha = 0.1, width = 0.1, shape=16) + facet_wrap(~Label, nrow = 1) + geom_abline(data = midpoints, aes(intercept = h, slope = 0, col="red")) + ylab("Percent spliced reads\nin passingd droplets") + theme_bw() + ct + scale_y_continuous(labels = scales::percent, breaks = c(0, .25, .5, .75, 1), limits = c(0, 1.25)) + theme(strip.background = element_blank(), strip.placement = "outside", text=element_text(size=ts), axis.title = element_text(size = 20), axis.title.y = element_text(size = 22), axis.text.x = element_text(angle=xa_angle,hjust=hj), strip.text = element_text(size = 20)) dir_plot <- "results/plots/" outfn <- paste0(dir_plot, "method.sample.pct_sf_droplet.clean.jpeg") ggsave(outfn, width = 20, height = 4) outfn <- paste0(dir_plot, "method.sample.pct_sf_droplet.clean.pdf") ggsave(outfn, width = 20, height = 4) #========================================= # Plot method vs fraction spliced in debris droplets #========================================= datf <- subset(all_sf, Call == "Debris") p <- ggplot(datf, aes(x = Method, y = SpliceFrctn)) + geom_boxplot(outlier.shape = NA) + geom_jitter(alpha = 0.1, width = 0.1, shape=16) + facet_wrap(~Label, nrow = 1) + geom_abline(data = midpoints, aes(intercept = h, slope = 0, col="red")) + ylab("Percent spliced reads\nin removed droplets") + scale_y_continuous(labels = scales::percent, breaks = c(0, .25, .5, .75, 1), limits = c(0, 1.25)) + theme_bw() + ct + theme(strip.background = element_blank(), strip.placement = "outside", text=element_text(size=ts), axis.title = element_text(size = 20), axis.title.y = element_text(size = 22), axis.text.x = element_text(angle=xa_angle,hjust=hj), strip.text = element_text(size = 20)) dir_plot <- "results/plots/" outfn <- paste0(dir_plot, "method.sample.pct_sf_droplet.debris.jpeg") ggsave(outfn, width = 20, height = 4) outfn <- paste0(dir_plot, "method.sample.pct_sf_droplet.debris.pdf") ggsave(outfn, width = 20, height = 4) #========================================= # Run stats #========================================= sf_col <- "SpliceFrctn" # Wilcox test of droplets datf_s <- all_sf[all_sf[,"Call"] == "Clean",] for (s in samples){ datf <- datf_s[datf_s[,"Sample"] == s,] qcl <- datf$Method == "Quantile" dcl <- datf$Method == "DIEM" print(s) tr <- wilcox.test(datf[qcl,sf_col], datf[dcl,sf_col], conf.int=T) message("\t", tr$estimate) message("\t", tr$p.value * 8) } for (s in samples){ datf <- datf_s[datf_s[,"Sample"] == s,] ecl <- datf$Method == "EmptyDrops" dcl <- datf$Method == "DIEM" print(s) tr <- wilcox.test(datf[ecl,sf_col], datf[dcl,sf_col], conf.int=T) message("\t", tr$estimate) message("\t", tr$p.value) * 8 } datf_s <- all_sf[all_sf[,"Call"] == "Debris",] for (s in samples){ datf <- datf_s[datf_s[,"Sample"] == s,] qcl <- datf$Method == "Quantile" dcl <- datf$Method == "DIEM" print(s) tr <- wilcox.test(datf[qcl,sf_col], datf[dcl,sf_col], conf.int=T) message("\t", tr$estimate) message("\t", tr$p.value * 8) } for (s in samples){ datf <- datf_s[datf_s[,"Sample"] == s,] ecl <- datf$Method == "EmptyDrops" dcl <- datf$Method == "DIEM" print(s) tr <- wilcox.test(datf[ecl,sf_col], datf[dcl,sf_col], conf.int=T) message("\t", tr$estimate) message("\t", tr$p.value) * 8 } # Quantifications datf_s <- all_sf[all_sf$Call == "Clean",] s <- "adpcyte" for (m in mthds){ k <- datf_s$Method == m & datf_s$Sample == s tb <- table(datf_s[k,"Truth"]) tbb <- tb["Background"] tbc <- tb["Nuclear"] tall <- sum(tb) message(m, "\t: all:", tall, "; BG: ", tbb, "(", 100*tbb/tall, ")", "; N: ", tbc, "(", 100*tbc/tall, ")") } s <- "mouse_nuclei_2k" for (m in mthds){ k <- datf_s$Method == m & datf_s$Sample == s tb <- table(datf_s[k,"Truth"]) tbb <- tb["Background"] tbc <- tb["Nuclear"] tall <- sum(tb) message(m, "\t: all:", tall, "; BG: ", tbb, "(", 100*tbb/tall, ")", "; N: ", tbc, "(", 100*tbc/tall, ")") } e <- "atsn" for (m in mthds){ k <- datf_s$Method == m & datf_s$Exprm == e tb <- table(datf_s[k,"Truth"]) tbb <- tb["Background"] tbc <- tb["Nuclear"] tall <- sum(tb) message(m, "\t: all:", tall, "; BG: ", tbb, "(", 100*tbb/tall, ")", "; N: ", tbc, "(", 100*tbc/tall, ")") }
#=================== src_biogridr Documentation ===================================== #' Connect to local BioGRID database #' #' @description #' Connect to the biogridr package's interaction database #' #' @param path Path to BioGRID SQLite database. Defaults to #' \code{getOption('biogridr.db')}. #' #' @details #' BioGRID interactions are stored in a local SQLite database, and #' \code{src_biogridr()} returns a connection to this database via #' \link[dplyr]{dplyr}. This allows the user to aviod loading all 700,000+ #' interactions into memory by using \code{dplyr} to \link[dplyr]{select} #' columns and \link[dplyr]{filter} rows. #' #' @examples \dontrun{ #' #' # First download all interaction data #' # WARNING: This takes a few minutes! #' update_biogridr() #' #' # Connect to the database #' db <- src_biogridr() #' #' # Query the database for a CTF4 outer network #' outer_net(db, 'CTF4') #' #' # Aggregate the CTF4 outer network #' aggregate(outer_net('CTF4')) #' #' # Use dplyr to make custom queries to the database #' library(dplyr) #' tbl(db, 'systems') #' tbl(db, 'organisms') #' #' genes <- c('TOF1', 'CTF4') #' organism <- organism('cerevisiae') #' tbl(db, 'interactions') %>% #' filter( #' (a %in% genes | b %in% genes) & #' a_organism == organism & #' b_organism == organism #' ) %>% #' select(a, b) %>% #' collect() #' } #' #' @name src_biogridr #' @aliases biogridr #' @importFrom dplyr %>% #' @importFrom DBI dbConnect dbGetQuery #' @importFrom RSQLite SQLite initExtension #' @export #' src_biogridr <- function(path = getOption('biogridr.db')) { if (!requireNamespace("RSQLite", quietly = TRUE)) { stop("RSQLite package required to connect to sqlite db", call. = FALSE) } if (!file.exists(path)) { stop("Path does not exist", call. = FALSE) } con <- dbConnect(SQLite(), path) initExtension(con) release <- as.character(dbGetQuery(con, "SELECT release FROM log")) if (release == 'example') { warning('Currently using an example dataset.\n', 'Use ?update_biogridr to download the latest release of ', 'BioGRID interaction data.', call. = FALSE) } list(con = con, path = path, release = release) %>% add_class('src_biogridr') } #---- src_biogridr methods -------------------------------------------------- #' @export print.src_biogridr <- function(x) { cat(paste0( 'sqlite ', RSQLite::rsqliteVersion()[[2]], ' [biogridr - ', x$release, ']\n', dplyr:::wrap('tbls: ', paste0(RSQLite::dbListTables(x$con), collapse = ', ')) )) } #' @importFrom dbplyr tbl_sql #' @export tbl.src_biogridr <- function(src, from, ...) { dbplyr::tbl_sql('sqlite', src = src, from = from, ...) %>% add_class('tbl_biogridr') } #' @export collect.tbl_rothfreezer <- function(x, ...) { result <- drop_class(x) %>% collect(...) coltypes <- x$src$cnf$column_types present <- intersect(names(coltypes), names(result)) if (length(present)) { coerce <- coltypes[present] for (i in 1:length(coerce)) { type <- coerce[[i]] column <- names(coerce[i]) result[[column]] <- switch( type, logical = as.logical(result[[column]]), integer = as.integer(result[[column]]), character = as.character(result[[column]]), numeric = as.numeric(result[[column]]), double = as.numeric(result[[column]]), factor = as.factor(result[[column]]) ) } } # Coerce to desired column type return(result) } #---- OO Utilities ------------------------------------------------------------ # Add an S3 subclass in pipeline # @param x an S3 object # @param ... Character; S3 subclasses to add to object add_class <- function(x, ...) { class(x) <- c(..., class(x)); return(x) } # Drop an S3 subclass in pipeline # @param x an S3 object drop_class <- function(x) { class(x) <- class(x)[-1]; return(x)}
/R/src_biogrid.R
no_license
EricEdwardBryant/biogridr
R
false
false
3,946
r
#=================== src_biogridr Documentation ===================================== #' Connect to local BioGRID database #' #' @description #' Connect to the biogridr package's interaction database #' #' @param path Path to BioGRID SQLite database. Defaults to #' \code{getOption('biogridr.db')}. #' #' @details #' BioGRID interactions are stored in a local SQLite database, and #' \code{src_biogridr()} returns a connection to this database via #' \link[dplyr]{dplyr}. This allows the user to aviod loading all 700,000+ #' interactions into memory by using \code{dplyr} to \link[dplyr]{select} #' columns and \link[dplyr]{filter} rows. #' #' @examples \dontrun{ #' #' # First download all interaction data #' # WARNING: This takes a few minutes! #' update_biogridr() #' #' # Connect to the database #' db <- src_biogridr() #' #' # Query the database for a CTF4 outer network #' outer_net(db, 'CTF4') #' #' # Aggregate the CTF4 outer network #' aggregate(outer_net('CTF4')) #' #' # Use dplyr to make custom queries to the database #' library(dplyr) #' tbl(db, 'systems') #' tbl(db, 'organisms') #' #' genes <- c('TOF1', 'CTF4') #' organism <- organism('cerevisiae') #' tbl(db, 'interactions') %>% #' filter( #' (a %in% genes | b %in% genes) & #' a_organism == organism & #' b_organism == organism #' ) %>% #' select(a, b) %>% #' collect() #' } #' #' @name src_biogridr #' @aliases biogridr #' @importFrom dplyr %>% #' @importFrom DBI dbConnect dbGetQuery #' @importFrom RSQLite SQLite initExtension #' @export #' src_biogridr <- function(path = getOption('biogridr.db')) { if (!requireNamespace("RSQLite", quietly = TRUE)) { stop("RSQLite package required to connect to sqlite db", call. = FALSE) } if (!file.exists(path)) { stop("Path does not exist", call. = FALSE) } con <- dbConnect(SQLite(), path) initExtension(con) release <- as.character(dbGetQuery(con, "SELECT release FROM log")) if (release == 'example') { warning('Currently using an example dataset.\n', 'Use ?update_biogridr to download the latest release of ', 'BioGRID interaction data.', call. = FALSE) } list(con = con, path = path, release = release) %>% add_class('src_biogridr') } #---- src_biogridr methods -------------------------------------------------- #' @export print.src_biogridr <- function(x) { cat(paste0( 'sqlite ', RSQLite::rsqliteVersion()[[2]], ' [biogridr - ', x$release, ']\n', dplyr:::wrap('tbls: ', paste0(RSQLite::dbListTables(x$con), collapse = ', ')) )) } #' @importFrom dbplyr tbl_sql #' @export tbl.src_biogridr <- function(src, from, ...) { dbplyr::tbl_sql('sqlite', src = src, from = from, ...) %>% add_class('tbl_biogridr') } #' @export collect.tbl_rothfreezer <- function(x, ...) { result <- drop_class(x) %>% collect(...) coltypes <- x$src$cnf$column_types present <- intersect(names(coltypes), names(result)) if (length(present)) { coerce <- coltypes[present] for (i in 1:length(coerce)) { type <- coerce[[i]] column <- names(coerce[i]) result[[column]] <- switch( type, logical = as.logical(result[[column]]), integer = as.integer(result[[column]]), character = as.character(result[[column]]), numeric = as.numeric(result[[column]]), double = as.numeric(result[[column]]), factor = as.factor(result[[column]]) ) } } # Coerce to desired column type return(result) } #---- OO Utilities ------------------------------------------------------------ # Add an S3 subclass in pipeline # @param x an S3 object # @param ... Character; S3 subclasses to add to object add_class <- function(x, ...) { class(x) <- c(..., class(x)); return(x) } # Drop an S3 subclass in pipeline # @param x an S3 object drop_class <- function(x) { class(x) <- class(x)[-1]; return(x)}
tidy_CYdata <- function(dataframe){ df <- dataframe %>% mutate(Date = as.Date(date, format = "%d/%m/%y")) %>% rename(newcases = daily.new.cases, newdeaths = daily.deaths, newrecovered = daily.recovered.cases, newtests = daily.tests.performed, totalcases = total.cases, totaldeaths = total.deaths, totalrecovered = total.recovered, totaltests = total.tests) %>% mutate_if(is.numeric, ~replace(., is.na(.), 0)) %>% select(Date, newcases, newdeaths, newrecovered, totalcases, totaldeaths, totalrecovered, newtests, totaltests) return(df) #return output } #end function # creating new variables Manage_CYdata <- function(dataframe) { df <- dataframe %>% mutate(CFR = (totaldeaths/totalcases)* 100, GF = totalcases / lag(totalcases, default = first(totalcases))) } tidy_ECDCdata <- function(dataframe){ df <- dataframe %>% mutate(Date = as.Date(date)) %>% rename(newcases = cases, newdeaths = deaths, #newrecovered = daily.recovered.cases, #newtests = daily.tests.performed, totalcases = cases_cum, totaldeaths = deaths_cum, #totalrecovered = total.recovered, #totaltests = total.tests ) %>% mutate_if(is.numeric, ~replace(., is.na(.), 0)) %>% select(Date, country, code, newcases, newdeaths, totalcases, totaldeaths, population, continentExp) return(df) #return output } #end function Manage_ECDCdata <- function(dataframe) { df <- dataframe %>% mutate(CFR = (totaldeaths/totalcases)* 100, GF = totalcases / lag(totalcases, default = first(totalcases))) } collect_ECDCdata <- function(dataframe){ df <- dataframe %>% group_by(country) %>% # Remove all rows of country if there aren't any rows with values==0 filter(any(newcases==0)) %>% # Remove all rows with values != 0 filter(newcases != 0) %>% # Keep the first row of each variable, after sorting by Date # This gives us the first non-zero row arrange(Date) %>% slice(1) %>% # Use complete to bring back a row for any level of variable that # didn't start with any rows with values==0 ungroup() %>% complete(country) return(df) }
/useful_functions.R
no_license
solis9753/Covid_19
R
false
false
2,313
r
tidy_CYdata <- function(dataframe){ df <- dataframe %>% mutate(Date = as.Date(date, format = "%d/%m/%y")) %>% rename(newcases = daily.new.cases, newdeaths = daily.deaths, newrecovered = daily.recovered.cases, newtests = daily.tests.performed, totalcases = total.cases, totaldeaths = total.deaths, totalrecovered = total.recovered, totaltests = total.tests) %>% mutate_if(is.numeric, ~replace(., is.na(.), 0)) %>% select(Date, newcases, newdeaths, newrecovered, totalcases, totaldeaths, totalrecovered, newtests, totaltests) return(df) #return output } #end function # creating new variables Manage_CYdata <- function(dataframe) { df <- dataframe %>% mutate(CFR = (totaldeaths/totalcases)* 100, GF = totalcases / lag(totalcases, default = first(totalcases))) } tidy_ECDCdata <- function(dataframe){ df <- dataframe %>% mutate(Date = as.Date(date)) %>% rename(newcases = cases, newdeaths = deaths, #newrecovered = daily.recovered.cases, #newtests = daily.tests.performed, totalcases = cases_cum, totaldeaths = deaths_cum, #totalrecovered = total.recovered, #totaltests = total.tests ) %>% mutate_if(is.numeric, ~replace(., is.na(.), 0)) %>% select(Date, country, code, newcases, newdeaths, totalcases, totaldeaths, population, continentExp) return(df) #return output } #end function Manage_ECDCdata <- function(dataframe) { df <- dataframe %>% mutate(CFR = (totaldeaths/totalcases)* 100, GF = totalcases / lag(totalcases, default = first(totalcases))) } collect_ECDCdata <- function(dataframe){ df <- dataframe %>% group_by(country) %>% # Remove all rows of country if there aren't any rows with values==0 filter(any(newcases==0)) %>% # Remove all rows with values != 0 filter(newcases != 0) %>% # Keep the first row of each variable, after sorting by Date # This gives us the first non-zero row arrange(Date) %>% slice(1) %>% # Use complete to bring back a row for any level of variable that # didn't start with any rows with values==0 ungroup() %>% complete(country) return(df) }
ATTEDII_pair <- paste0(CoExp_absth04_cyto$souce, CoExp_absth04_cyto$target) ATTEDII_pair <- data.frame(AGI_pair = mastercluster_pair, PCC = CoExp_absth04_cyto$PCC ) filename <- list.files("~/Nakano_RNAseq/network_analysis/base/genes_set/CY_FDR005_DEGs/CY20/", pattern=".txt", full.names = T) temp2 <- c("12h", "1h", "24h", "3h") object_name <- c() object_name_all <- c() n <- 1 for (n in 1:length(filename)){ object_name <- paste0("CY20", "_", temp2[n], "_DEGs") assign(object_name, read.table(filename[n], header=T, sep="\t", stringsAsFactors = F)) n <- n+1 } AGI_list <- list(rownames(CY15_1h_FDR005), rownames(CY15_3h_FDR005), rownames(CY15_12h_FDR005), rownames(CY15_24h_FDR005), rownames(CY16_1h_FDR005), rownames(CY16_3h_FDR005), rownames(CY16_12h_FDR005), rownames(CY16_24h_FDR005), rownames(CY20_1h_FDR005), rownames(CY20_3h_FDR005), rownames(CY20_12h_FDR005), rownames(CY20_24h_FDR005) ) names(AGI) <- list("CY15_1h_FDR005", "CY15_3h_FDR005", "CY15_12h_FDR005", "CY15_24h_FDR005", "CY16_1h_FDR005", "CY16_3h_FDR005", "CY16_12h_FDR005", "CY16_24h_FDR005", "CY20_1h_FDR005", "CY20_3h_FDR005", "CY20_12h_FDR005", "CY20_24h_FDR005" ) i <- 1 for(i in i:length(AGI_list)){ CY <- combn(AGI_list[[i]], 2) pair <- paste0(CY[1, ], CY[2, ]) edge <- intersect(mastercluster_pair$AGI_pair, pair) PCC <- mastercluster_pair$PCC[match(edge, mastercluster_pair$AGI_pair)] souce <- c() target <- c() m <- 1 for(m in m:length(edge)){ souce <- c(souce, substr(edge[m], 1, 9)) target <- c(target, substr(edge[m], 10, 18)) m <- m+1 } temp <- data.frame(souce = souce, PCC = PCC, target = target ) File <- paste0("~/Nakano_RNAseq/network_analysis/base/eachCY_131224h/", names(AGI)[i], ".txt") write.table(temp, file = File, append=F, quote = F, sep = "\t", row.names = F) print(i) }
/ATTEDII_CY_eachtime_cytoscape.R
no_license
YKeito/ATTEDII
R
false
false
2,049
r
ATTEDII_pair <- paste0(CoExp_absth04_cyto$souce, CoExp_absth04_cyto$target) ATTEDII_pair <- data.frame(AGI_pair = mastercluster_pair, PCC = CoExp_absth04_cyto$PCC ) filename <- list.files("~/Nakano_RNAseq/network_analysis/base/genes_set/CY_FDR005_DEGs/CY20/", pattern=".txt", full.names = T) temp2 <- c("12h", "1h", "24h", "3h") object_name <- c() object_name_all <- c() n <- 1 for (n in 1:length(filename)){ object_name <- paste0("CY20", "_", temp2[n], "_DEGs") assign(object_name, read.table(filename[n], header=T, sep="\t", stringsAsFactors = F)) n <- n+1 } AGI_list <- list(rownames(CY15_1h_FDR005), rownames(CY15_3h_FDR005), rownames(CY15_12h_FDR005), rownames(CY15_24h_FDR005), rownames(CY16_1h_FDR005), rownames(CY16_3h_FDR005), rownames(CY16_12h_FDR005), rownames(CY16_24h_FDR005), rownames(CY20_1h_FDR005), rownames(CY20_3h_FDR005), rownames(CY20_12h_FDR005), rownames(CY20_24h_FDR005) ) names(AGI) <- list("CY15_1h_FDR005", "CY15_3h_FDR005", "CY15_12h_FDR005", "CY15_24h_FDR005", "CY16_1h_FDR005", "CY16_3h_FDR005", "CY16_12h_FDR005", "CY16_24h_FDR005", "CY20_1h_FDR005", "CY20_3h_FDR005", "CY20_12h_FDR005", "CY20_24h_FDR005" ) i <- 1 for(i in i:length(AGI_list)){ CY <- combn(AGI_list[[i]], 2) pair <- paste0(CY[1, ], CY[2, ]) edge <- intersect(mastercluster_pair$AGI_pair, pair) PCC <- mastercluster_pair$PCC[match(edge, mastercluster_pair$AGI_pair)] souce <- c() target <- c() m <- 1 for(m in m:length(edge)){ souce <- c(souce, substr(edge[m], 1, 9)) target <- c(target, substr(edge[m], 10, 18)) m <- m+1 } temp <- data.frame(souce = souce, PCC = PCC, target = target ) File <- paste0("~/Nakano_RNAseq/network_analysis/base/eachCY_131224h/", names(AGI)[i], ".txt") write.table(temp, file = File, append=F, quote = F, sep = "\t", row.names = F) print(i) }
library(deldir) ### Name: divchain ### Title: Dividing chain; generic. ### Aliases: divchain ### Keywords: spatial ### ** Examples set.seed(42) x <- runif(50) y <- runif(50) z <- factor(kmeans(cbind(x,y),centers=4)$cluster) dc1 <- divchain(x,y,z,rw=c(0,1,0,1)) dxy <- deldir(x,y,z=z,rw=c(0,1,0,1)) dc2 <- divchain(dxy)
/data/genthat_extracted_code/deldir/examples/divchain.Rd.R
no_license
surayaaramli/typeRrh
R
false
false
353
r
library(deldir) ### Name: divchain ### Title: Dividing chain; generic. ### Aliases: divchain ### Keywords: spatial ### ** Examples set.seed(42) x <- runif(50) y <- runif(50) z <- factor(kmeans(cbind(x,y),centers=4)$cluster) dc1 <- divchain(x,y,z,rw=c(0,1,0,1)) dxy <- deldir(x,y,z=z,rw=c(0,1,0,1)) dc2 <- divchain(dxy)
####################################################### # To create aliquot names for glioma life history. # Date: 2018.08.30 # Author: Kevin J ####################################################### # Local directory for github repo. mybasedir = here::here() setwd(mybasedir) # Hong Kong samples sequenced by Novogene. hong_kong_path = "data/sequencing-information/HK/hong-kong-sample-maps.txt" # TCGA LGG and GBM datasets. tcga_path = "data/clinical-data/TCGA/LGG-GBM-samples.tsv" # Low-pass whole genome sequencing for MD Anderson samples. rv_jdg_path = "data/clinical-data/Roel-JDG/Roel_JDG-original_bam_map.txt" # Glioblastoma case from the Henry Ford data set. hgbm_path = "data/clinical-data/HF/HGBM-original_bam_map.txt" # The Australian subject (Northern Sydney Cancer Centre) that had multile recurrences and a bone metastasis. ns_path ="data/sequencing-information/NS/Sample_Identifiers.txt" # Different tissue source sites from TCGA. tss_path = "data/sequencing-information/tissueSourceSite.txt" # MDA: Files with information about fastq information and barcodes, but also aliquot names. mda_batch1_file_path = "data/sequencing-information/MDACC/file_list_C202SC18030593_batch1_n14_20180405.tsv" mda_batch2_file_path = "data/sequencing-information/MDACC/file_list_C202SC18030593_batch2_n94_20180603.tsv" mda_batch3_file_path = "data/sequencing-information/MDACC/file_list_C202SC18030593_batch2_n13_20180716.tsv" # Clinical dataset priovided by Kristin Alfaro-Munoz at MD Anderson. # Modified to generate a sample_type (TP, R1, R2, R3) using the clinical information. See github issue #16. mda_master_path = "data/clinical-data/MDACC/MDA-Clinical-Dataset/Master Log for WGS_sampletype.20180630.xlsx" # 2018.07.06 Katie Shao (Novogene) provided the following sheet linking libraryID with submitted sample names in the email: # "Re:RE: Novogene Project Report - Confirm -C202SC18030593-Davis-MDACC-156-libseq-hWGS-WOBI-NVUS2018022505[J1-C202SC18030593-1000]" novogene_sample_path = "data/sequencing-information/MDACC/Novogene_SIF_14.xlsx" ####################################################### # Necessary packages. library(tidyverse) library(openxlsx) library(stringr) library(stringi) ####################################################### # Inspect how each cohort currently barcodes each file. hk_df = read.table(hong_kong_path, header=T) tcga_df = read_tsv(tcga_path) rv_jdg_df = read_tsv(rv_jdg_path) hgbm_df = read_tsv(hgbm_path) ns_df = read_tsv(ns_path) # The sample-specific barcode should include the following: # project_id, tissue source site, subject_id, sample_type, portion, analysis_type, and legacy_aliquot_id hk_sample_map = hk_df %>% mutate(project_id = "GLSS", tss = "HK", subject_id = recode_factor(Patient_ID, "CHUK5" = "0005", "CHUK4" = "0004", "CHUK3" = "0003", "CHUK2" = "0002", "CHUK1" = "0001"), sample_type = recode_factor(Sample_Type, "Blood" = "NB", "Primary" = "TP", "Recurrence" = "R1"), portion = "01D", analysis_type = "WGS", legacy_aliquot_id = Verhaak_Sample_ID) %>% unite(glass_aliquot_id, c(project_id, tss, subject_id, sample_type, portion, analysis_type), sep = "-", remove = FALSE) %>% select(glass_aliquot_id, legacy_aliquot_id) ### MDA (Novogene cohort) barcode generation #### # Novogene has processed 120 samples. In our master sheet normal blood samples were not provided. We need them for barcodes. # Inspect both batch1, batch2, and batch 3 sequencing data for tumor/normal samples. mda_batch1_df <- read.table(mda_batch1_file_path, col.names="relative_file_path", stringsAsFactors = F) mda_batch1_df$filename = sapply(strsplit(mda_batch1_df$relative_file_path, "/"), "[[", 3) mda_batch2_df <- read.table(mda_batch2_file_path, col.names="relative_file_path", stringsAsFactors = F) mda_batch2_df$filename = sapply(strsplit(mda_batch2_df$relative_file_path, "/"), "[[", 3) mda_batch3_df <- read.table(mda_batch3_file_path, col.names="relative_file_path", stringsAsFactors = F) mda_batch3_df$filename = sapply(strsplit(mda_batch3_df$relative_file_path, "/"), "[[", 3) # Replace the placeholder for pwd "./" from unix cmd: "find -name ".fq.gz" in parent directory of fastqs. mda_batch1_df$working_file_path <- gsub("^", "/fastscratch/johnsk/GLASS-WG/mdacc/C202SC18030593_batch1_n14_20180405", mda_batch1_df$relative_file_path) mda_batch2_df$working_file_path <- gsub("^", "/fastscratch/johnsk/GLASS-WG/mdacc/C202SC18030593_batch1_n94_20180603", mda_batch2_df$relative_file_path) mda_batch3_df$working_file_path <- gsub("^", "/fastscratch/johnsk/GLASS-WG/mdacc/C202SC18030593_batch2_n13_20180716", mda_batch3_df$relative_file_path) # Combine these three sequencing data sets. There should be 552 files. mda_df <- bind_rows(mda_batch1_df, mda_batch2_df, mda_batch3_df) # Katie Shao (Novogene) provided the filename and sample linker file. novogene_linker = readWorkbook(novogene_sample_path, sheet = 1, startRow = 18, colNames = TRUE) novogene_linker_unique <- novogene_linker[1:121, ] # Retrieve only the blood samples ("10D"). Blood samples not contained in master sheet. normal_blood_samples = novogene_linker_unique[grep("[b|B]lood", novogene_linker_unique$`*SampleName`), ] # Retrieve the subject ID in same format as tumor samples. normal_blood_samples$SubjectID = sapply(strsplit(normal_blood_samples$`*SampleName`, "-"), "[", 3) # Create a barcode for available blood samples (n=39). mda_normal_blood_map <- normal_blood_samples %>% mutate(project_id = "GLSS", tss = "MD", subject_id = SubjectID, portion = "01D", analysis_type = "WGS", sample_type = "NB", legacy_aliquot_id = `*SampleName`) %>% unite(glass_aliquot_id, c(project_id, tss, subject_id, sample_type, portion, analysis_type), sep = "-", remove = FALSE) %>% select(glass_aliquot_id, legacy_aliquot_id) ### Use master sheet containing tumor sample information, necessary to build barcodes.#### # Kristin Alfaro-Munoz kindly pointed me to the sequencing identifier link to these samples. mda_master = readWorkbook(mda_master_path, sheet = 2, startRow = 1, colNames = TRUE) # The master sheet from MDA only contains normal samples. Sum should equal 81 (tumor samples). sum(novogene_linker_unique$'*SampleName'%in%mda_master$Jax.Lib.Prep.Customer.Sample.Name) # Extract the 4-digit SUBJECT identifier. mda_master$SubjectID = sapply(strsplit(mda_master$Jax.Lib.Prep.Customer.Sample.Name, "-"), "[", 3) # Create a new MD Anderson to map the old to new sample names. mda_tumor_sample_map = mda_master[1:81,] %>% mutate(project_id = "GLSS", tss = "MD", legacy_aliquot_id = Jax.Lib.Prep.Customer.Sample.Name, subject_id = SubjectID, portion = "01D", analysis_type = "WGS") %>% unite(glass_aliquot_id, c(project_id, tss, subject_id, sample_type, portion, analysis_type), sep = "-", remove = FALSE) %>% select(glass_aliquot_id, legacy_aliquot_id) # Combine all tumor and normal samples together. mda_all_samples_map <- bind_rows(mda_normal_blood_map, mda_tumor_sample_map) ##### TCGA ##### # Create a new TCGA to map the old to new sample names. tcga_sample_map = tcga_df %>% rename(legacy_aliquot_id = aliquot_id) %>% separate(legacy_aliquot_id, c("project_id", "tss", "subject_id", "sample_type", "portion", "plate_id", "center"), remove = FALSE) %>% mutate(glass_sample_type = recode_factor(sample_type, "01A" = "TP", "01B" = "TP", "02A" = "R1", "02B" = "R2", "10A" = "NB", "10B" = "NB", "10D" = "NB"), analysis_type = "WGS") %>% unite(glass_aliquot_id, c(project_id, tss, subject_id, glass_sample_type, portion, analysis_type), sep = "-", remove = FALSE) %>% select(glass_aliquot_id, legacy_aliquot_id) ##### RV-JDG ##### # Modify barcode to make it the same as the other studies with only 4 characters. # Replacing Neuro-oncologist with "LP" identifier to indicate "Low Pass" and disambiguate from other MD set. rv_jdg_df$AnalysisID = gsub("JDG", "LP", rv_jdg_df$AnalysisID) # Create a new RV_JDG sample map to connect with the old sample names. rvjdg_sample_map = rv_jdg_df %>% separate(col=AnalysisID, into = c("Study", "PtIdentifier", "WrongTissueID", "Analyte"), sep="-") %>% separate(PtIdentifier, into = c("Text", "Num"), sep = "(?<=[A-Za-z])(?=[0-9])") %>% mutate_at("Num", str_pad, width = 2, side='left', pad = 0) %>% unite(PtIdentifier, c(Text,Num), sep = "") %>% mutate(sample_type = recode_factor(Tissue.Type.Revised, "first" = "TP", "second" = "R1", "normal" = "NB"), project_id = "GLSS", tss = "MD", subject_id = PtIdentifier, portion = Analyte, analysis_type = "WGS", legacy_aliquot_id = samplename) %>% group_by(PatientID) %>% filter(n() >= 3) %>% # Extract only trios. unite(glass_aliquot_id, c(project_id, tss, subject_id, sample_type, portion, analysis_type), sep = "-", remove = FALSE) %>% ungroup() %>% select(glass_aliquot_id, legacy_aliquot_id) ##### HGBM #### # Create a new hGBM sample map to connect with the old sample names. hgbm_sample_map = hgbm_df %>% filter(samplename!="HF-3177-10-01D") %>% # Removing the second normal blood sample from this same patient. separate(samplename, c("tss", "subject_id", "sample_type", "portion"), remove = FALSE) %>% mutate(project_id = "GLSS", tss = "HF", analysis_type = "WGS", subject_id = substring(PatientID, 4, 7), sample_type = recode_factor(SampleType2, "P" = "TP", "R" = "R1", "N" = "NB"), legacy_aliquot_id = samplename) %>% unite(glass_aliquot_id, c(project_id, tss, subject_id, sample_type, portion, analysis_type), sep = "-", remove = FALSE) %>% select(glass_aliquot_id, legacy_aliquot_id) ###### NS subject ##### ns_sample_map = ns_df %>% separate(Sample, c("original_id", "lane_id"), sep="_L[0-9]{1}_", extra = "merge") %>% distinct(original_id) %>% mutate(project_id = "GLSS", subject_id = "0001", tss ="NS", portion = "01D", sample_type = c("TP", "R1", "R2", "M1", "NB"), analysis_type = "WGS", legacy_aliquot_id = original_id) %>% unite(glass_aliquot_id, c(project_id, tss, subject_id, sample_type, portion, analysis_type), sep = "-", remove = FALSE) %>% select(glass_aliquot_id, legacy_aliquot_id) ############################################# # Combine 6 datasets into master table with each linker ############################################# life_history_barcodes = bind_rows(hk_sample_map, mda_tumor_sample_map, tcga_sample_map, hgbm_sample_map, rvjdg_sample_map, mda_normal_blood_map, ns_sample_map) ## Addition of random string to use as a shortened identifier. # Create a random string identifier for each SAMPLE in the Life History study. set.seed(1) uuid_life_history = as.data.frame(stri_rand_strings(dim(life_history_barcodes)[1], 6, "[A-Z0-9]")) colnames(uuid_life_history) = "uuid" # Sanity check: make sure each is unique. ifelse(n_distinct(uuid_life_history)==dim(uuid_life_history)[1], message("UUIDs are unique."), message("WARNING! Not unique")) # Write final combined dataset set for a data freeze. life_history_all_samples = bind_cols(life_history_barcodes, uuid_life_history) %>% unite(aliquot_id, c(glass_aliquot_id, uuid), sep = "-", remove = TRUE) # Write file to be uploaded to GLASS-WG github page. write.table(life_history_all_samples, file='data/ref/glass_wg_aliquots_mapping_table.txt', quote=FALSE, sep='\t', row.names = F) ### Create dictionaries for different tissue centers. #### # Subset list of TissueSourceSites from TCGA plus add new rows for other datasets. tss_info = read_tsv(tss_path) # Retrieve list of TissueSourceSites for future use. tcga_map = tcga_df %>% rename(legacy_aliquot_id = aliquot_id) %>% separate(legacy_aliquot_id, c("project_id", "tss", "subject_id", "sample_type", "portion", "plate_id", "center"), remove = FALSE) %>% distinct(tss, as.character) tcga_tss <- unique(tcga_map$tss) # Collapse space into "." separated. colnames(tss_info) = gsub( " ", ".", colnames(tss_info)) # Create more formal definitions. tss_glass = data.frame(tss_code = c("HK", "MD", "HF", "NS"), source_site = c("Chinese University of Hong Kong", "MD Anderson Cancer Center", "Henry Ford Hospital", "Northern Sydney Cancer Centre"), study_name = c("Lower Grade Glioma / Glioblastoma", "Lower Grade Glioma / Glioblastoma", "Glioblastoma", "Metastatic Gliosarcoma"), bcr = rep("GLASS", 4)) # Only those TCGA centers that are present in the NB, TP, R1/R2 samples. tss_tcga_filtered = tss_info %>% filter(TSS.Code %in% tcga_tss) # Create new tissue source site dictionary. tissue_source_site_dict = bind_rows(tss_tcga_filtered, tss_glass) write.table(tissue_source_site_dict, file='data/ref/life-history-tissue-source-sites.txt', quote=FALSE, sep='\t', row.names = F) # Create sample type dictionary. sample_type_dict = data.frame(Code = c("NB", "TP", "R1", "R2", "R3", "M1"), Definition = c("Blood Derived Normal", "Primary Tumor", "First Recurrence Tumor", "Second Recurrence Tumor", "Third Reccurence Tumor", "Bone Metastasis")) write.table(sample_type_dict, file='data/ref/life-history-sample-type-dict.txt', quote=FALSE, sep='\t', row.names = F)
/R/manifest/life-history-barcode-generation.R
permissive
fpbarthel/GLASS
R
false
false
13,364
r
####################################################### # To create aliquot names for glioma life history. # Date: 2018.08.30 # Author: Kevin J ####################################################### # Local directory for github repo. mybasedir = here::here() setwd(mybasedir) # Hong Kong samples sequenced by Novogene. hong_kong_path = "data/sequencing-information/HK/hong-kong-sample-maps.txt" # TCGA LGG and GBM datasets. tcga_path = "data/clinical-data/TCGA/LGG-GBM-samples.tsv" # Low-pass whole genome sequencing for MD Anderson samples. rv_jdg_path = "data/clinical-data/Roel-JDG/Roel_JDG-original_bam_map.txt" # Glioblastoma case from the Henry Ford data set. hgbm_path = "data/clinical-data/HF/HGBM-original_bam_map.txt" # The Australian subject (Northern Sydney Cancer Centre) that had multile recurrences and a bone metastasis. ns_path ="data/sequencing-information/NS/Sample_Identifiers.txt" # Different tissue source sites from TCGA. tss_path = "data/sequencing-information/tissueSourceSite.txt" # MDA: Files with information about fastq information and barcodes, but also aliquot names. mda_batch1_file_path = "data/sequencing-information/MDACC/file_list_C202SC18030593_batch1_n14_20180405.tsv" mda_batch2_file_path = "data/sequencing-information/MDACC/file_list_C202SC18030593_batch2_n94_20180603.tsv" mda_batch3_file_path = "data/sequencing-information/MDACC/file_list_C202SC18030593_batch2_n13_20180716.tsv" # Clinical dataset priovided by Kristin Alfaro-Munoz at MD Anderson. # Modified to generate a sample_type (TP, R1, R2, R3) using the clinical information. See github issue #16. mda_master_path = "data/clinical-data/MDACC/MDA-Clinical-Dataset/Master Log for WGS_sampletype.20180630.xlsx" # 2018.07.06 Katie Shao (Novogene) provided the following sheet linking libraryID with submitted sample names in the email: # "Re:RE: Novogene Project Report - Confirm -C202SC18030593-Davis-MDACC-156-libseq-hWGS-WOBI-NVUS2018022505[J1-C202SC18030593-1000]" novogene_sample_path = "data/sequencing-information/MDACC/Novogene_SIF_14.xlsx" ####################################################### # Necessary packages. library(tidyverse) library(openxlsx) library(stringr) library(stringi) ####################################################### # Inspect how each cohort currently barcodes each file. hk_df = read.table(hong_kong_path, header=T) tcga_df = read_tsv(tcga_path) rv_jdg_df = read_tsv(rv_jdg_path) hgbm_df = read_tsv(hgbm_path) ns_df = read_tsv(ns_path) # The sample-specific barcode should include the following: # project_id, tissue source site, subject_id, sample_type, portion, analysis_type, and legacy_aliquot_id hk_sample_map = hk_df %>% mutate(project_id = "GLSS", tss = "HK", subject_id = recode_factor(Patient_ID, "CHUK5" = "0005", "CHUK4" = "0004", "CHUK3" = "0003", "CHUK2" = "0002", "CHUK1" = "0001"), sample_type = recode_factor(Sample_Type, "Blood" = "NB", "Primary" = "TP", "Recurrence" = "R1"), portion = "01D", analysis_type = "WGS", legacy_aliquot_id = Verhaak_Sample_ID) %>% unite(glass_aliquot_id, c(project_id, tss, subject_id, sample_type, portion, analysis_type), sep = "-", remove = FALSE) %>% select(glass_aliquot_id, legacy_aliquot_id) ### MDA (Novogene cohort) barcode generation #### # Novogene has processed 120 samples. In our master sheet normal blood samples were not provided. We need them for barcodes. # Inspect both batch1, batch2, and batch 3 sequencing data for tumor/normal samples. mda_batch1_df <- read.table(mda_batch1_file_path, col.names="relative_file_path", stringsAsFactors = F) mda_batch1_df$filename = sapply(strsplit(mda_batch1_df$relative_file_path, "/"), "[[", 3) mda_batch2_df <- read.table(mda_batch2_file_path, col.names="relative_file_path", stringsAsFactors = F) mda_batch2_df$filename = sapply(strsplit(mda_batch2_df$relative_file_path, "/"), "[[", 3) mda_batch3_df <- read.table(mda_batch3_file_path, col.names="relative_file_path", stringsAsFactors = F) mda_batch3_df$filename = sapply(strsplit(mda_batch3_df$relative_file_path, "/"), "[[", 3) # Replace the placeholder for pwd "./" from unix cmd: "find -name ".fq.gz" in parent directory of fastqs. mda_batch1_df$working_file_path <- gsub("^", "/fastscratch/johnsk/GLASS-WG/mdacc/C202SC18030593_batch1_n14_20180405", mda_batch1_df$relative_file_path) mda_batch2_df$working_file_path <- gsub("^", "/fastscratch/johnsk/GLASS-WG/mdacc/C202SC18030593_batch1_n94_20180603", mda_batch2_df$relative_file_path) mda_batch3_df$working_file_path <- gsub("^", "/fastscratch/johnsk/GLASS-WG/mdacc/C202SC18030593_batch2_n13_20180716", mda_batch3_df$relative_file_path) # Combine these three sequencing data sets. There should be 552 files. mda_df <- bind_rows(mda_batch1_df, mda_batch2_df, mda_batch3_df) # Katie Shao (Novogene) provided the filename and sample linker file. novogene_linker = readWorkbook(novogene_sample_path, sheet = 1, startRow = 18, colNames = TRUE) novogene_linker_unique <- novogene_linker[1:121, ] # Retrieve only the blood samples ("10D"). Blood samples not contained in master sheet. normal_blood_samples = novogene_linker_unique[grep("[b|B]lood", novogene_linker_unique$`*SampleName`), ] # Retrieve the subject ID in same format as tumor samples. normal_blood_samples$SubjectID = sapply(strsplit(normal_blood_samples$`*SampleName`, "-"), "[", 3) # Create a barcode for available blood samples (n=39). mda_normal_blood_map <- normal_blood_samples %>% mutate(project_id = "GLSS", tss = "MD", subject_id = SubjectID, portion = "01D", analysis_type = "WGS", sample_type = "NB", legacy_aliquot_id = `*SampleName`) %>% unite(glass_aliquot_id, c(project_id, tss, subject_id, sample_type, portion, analysis_type), sep = "-", remove = FALSE) %>% select(glass_aliquot_id, legacy_aliquot_id) ### Use master sheet containing tumor sample information, necessary to build barcodes.#### # Kristin Alfaro-Munoz kindly pointed me to the sequencing identifier link to these samples. mda_master = readWorkbook(mda_master_path, sheet = 2, startRow = 1, colNames = TRUE) # The master sheet from MDA only contains normal samples. Sum should equal 81 (tumor samples). sum(novogene_linker_unique$'*SampleName'%in%mda_master$Jax.Lib.Prep.Customer.Sample.Name) # Extract the 4-digit SUBJECT identifier. mda_master$SubjectID = sapply(strsplit(mda_master$Jax.Lib.Prep.Customer.Sample.Name, "-"), "[", 3) # Create a new MD Anderson to map the old to new sample names. mda_tumor_sample_map = mda_master[1:81,] %>% mutate(project_id = "GLSS", tss = "MD", legacy_aliquot_id = Jax.Lib.Prep.Customer.Sample.Name, subject_id = SubjectID, portion = "01D", analysis_type = "WGS") %>% unite(glass_aliquot_id, c(project_id, tss, subject_id, sample_type, portion, analysis_type), sep = "-", remove = FALSE) %>% select(glass_aliquot_id, legacy_aliquot_id) # Combine all tumor and normal samples together. mda_all_samples_map <- bind_rows(mda_normal_blood_map, mda_tumor_sample_map) ##### TCGA ##### # Create a new TCGA to map the old to new sample names. tcga_sample_map = tcga_df %>% rename(legacy_aliquot_id = aliquot_id) %>% separate(legacy_aliquot_id, c("project_id", "tss", "subject_id", "sample_type", "portion", "plate_id", "center"), remove = FALSE) %>% mutate(glass_sample_type = recode_factor(sample_type, "01A" = "TP", "01B" = "TP", "02A" = "R1", "02B" = "R2", "10A" = "NB", "10B" = "NB", "10D" = "NB"), analysis_type = "WGS") %>% unite(glass_aliquot_id, c(project_id, tss, subject_id, glass_sample_type, portion, analysis_type), sep = "-", remove = FALSE) %>% select(glass_aliquot_id, legacy_aliquot_id) ##### RV-JDG ##### # Modify barcode to make it the same as the other studies with only 4 characters. # Replacing Neuro-oncologist with "LP" identifier to indicate "Low Pass" and disambiguate from other MD set. rv_jdg_df$AnalysisID = gsub("JDG", "LP", rv_jdg_df$AnalysisID) # Create a new RV_JDG sample map to connect with the old sample names. rvjdg_sample_map = rv_jdg_df %>% separate(col=AnalysisID, into = c("Study", "PtIdentifier", "WrongTissueID", "Analyte"), sep="-") %>% separate(PtIdentifier, into = c("Text", "Num"), sep = "(?<=[A-Za-z])(?=[0-9])") %>% mutate_at("Num", str_pad, width = 2, side='left', pad = 0) %>% unite(PtIdentifier, c(Text,Num), sep = "") %>% mutate(sample_type = recode_factor(Tissue.Type.Revised, "first" = "TP", "second" = "R1", "normal" = "NB"), project_id = "GLSS", tss = "MD", subject_id = PtIdentifier, portion = Analyte, analysis_type = "WGS", legacy_aliquot_id = samplename) %>% group_by(PatientID) %>% filter(n() >= 3) %>% # Extract only trios. unite(glass_aliquot_id, c(project_id, tss, subject_id, sample_type, portion, analysis_type), sep = "-", remove = FALSE) %>% ungroup() %>% select(glass_aliquot_id, legacy_aliquot_id) ##### HGBM #### # Create a new hGBM sample map to connect with the old sample names. hgbm_sample_map = hgbm_df %>% filter(samplename!="HF-3177-10-01D") %>% # Removing the second normal blood sample from this same patient. separate(samplename, c("tss", "subject_id", "sample_type", "portion"), remove = FALSE) %>% mutate(project_id = "GLSS", tss = "HF", analysis_type = "WGS", subject_id = substring(PatientID, 4, 7), sample_type = recode_factor(SampleType2, "P" = "TP", "R" = "R1", "N" = "NB"), legacy_aliquot_id = samplename) %>% unite(glass_aliquot_id, c(project_id, tss, subject_id, sample_type, portion, analysis_type), sep = "-", remove = FALSE) %>% select(glass_aliquot_id, legacy_aliquot_id) ###### NS subject ##### ns_sample_map = ns_df %>% separate(Sample, c("original_id", "lane_id"), sep="_L[0-9]{1}_", extra = "merge") %>% distinct(original_id) %>% mutate(project_id = "GLSS", subject_id = "0001", tss ="NS", portion = "01D", sample_type = c("TP", "R1", "R2", "M1", "NB"), analysis_type = "WGS", legacy_aliquot_id = original_id) %>% unite(glass_aliquot_id, c(project_id, tss, subject_id, sample_type, portion, analysis_type), sep = "-", remove = FALSE) %>% select(glass_aliquot_id, legacy_aliquot_id) ############################################# # Combine 6 datasets into master table with each linker ############################################# life_history_barcodes = bind_rows(hk_sample_map, mda_tumor_sample_map, tcga_sample_map, hgbm_sample_map, rvjdg_sample_map, mda_normal_blood_map, ns_sample_map) ## Addition of random string to use as a shortened identifier. # Create a random string identifier for each SAMPLE in the Life History study. set.seed(1) uuid_life_history = as.data.frame(stri_rand_strings(dim(life_history_barcodes)[1], 6, "[A-Z0-9]")) colnames(uuid_life_history) = "uuid" # Sanity check: make sure each is unique. ifelse(n_distinct(uuid_life_history)==dim(uuid_life_history)[1], message("UUIDs are unique."), message("WARNING! Not unique")) # Write final combined dataset set for a data freeze. life_history_all_samples = bind_cols(life_history_barcodes, uuid_life_history) %>% unite(aliquot_id, c(glass_aliquot_id, uuid), sep = "-", remove = TRUE) # Write file to be uploaded to GLASS-WG github page. write.table(life_history_all_samples, file='data/ref/glass_wg_aliquots_mapping_table.txt', quote=FALSE, sep='\t', row.names = F) ### Create dictionaries for different tissue centers. #### # Subset list of TissueSourceSites from TCGA plus add new rows for other datasets. tss_info = read_tsv(tss_path) # Retrieve list of TissueSourceSites for future use. tcga_map = tcga_df %>% rename(legacy_aliquot_id = aliquot_id) %>% separate(legacy_aliquot_id, c("project_id", "tss", "subject_id", "sample_type", "portion", "plate_id", "center"), remove = FALSE) %>% distinct(tss, as.character) tcga_tss <- unique(tcga_map$tss) # Collapse space into "." separated. colnames(tss_info) = gsub( " ", ".", colnames(tss_info)) # Create more formal definitions. tss_glass = data.frame(tss_code = c("HK", "MD", "HF", "NS"), source_site = c("Chinese University of Hong Kong", "MD Anderson Cancer Center", "Henry Ford Hospital", "Northern Sydney Cancer Centre"), study_name = c("Lower Grade Glioma / Glioblastoma", "Lower Grade Glioma / Glioblastoma", "Glioblastoma", "Metastatic Gliosarcoma"), bcr = rep("GLASS", 4)) # Only those TCGA centers that are present in the NB, TP, R1/R2 samples. tss_tcga_filtered = tss_info %>% filter(TSS.Code %in% tcga_tss) # Create new tissue source site dictionary. tissue_source_site_dict = bind_rows(tss_tcga_filtered, tss_glass) write.table(tissue_source_site_dict, file='data/ref/life-history-tissue-source-sites.txt', quote=FALSE, sep='\t', row.names = F) # Create sample type dictionary. sample_type_dict = data.frame(Code = c("NB", "TP", "R1", "R2", "R3", "M1"), Definition = c("Blood Derived Normal", "Primary Tumor", "First Recurrence Tumor", "Second Recurrence Tumor", "Third Reccurence Tumor", "Bone Metastasis")) write.table(sample_type_dict, file='data/ref/life-history-sample-type-dict.txt', quote=FALSE, sep='\t', row.names = F)
testlist <- list(b = c(1785358954L, 1785358954L, 1785358954L, 1785358954L, 1785358954L, 1785358954L, 1785358954L, 1785358954L, 1785358954L, 1785358954L, -65281L, -16711841L, -12059008L, -2130837632L, -1895846273L, 38862848L, -16777216L, -16053493L, 1358954496L, -1L, -1L, -1L, -1L, 1090519039L, 973078783L, -8388608L, 8454143L, -1L, -1L, 28L, 0L, 0L, -16711681L)) result <- do.call(mcga:::ByteVectorToDoubles,testlist) str(result)
/mcga/inst/testfiles/ByteVectorToDoubles/libFuzzer_ByteVectorToDoubles/ByteVectorToDoubles_valgrind_files/1612760937-test.R
no_license
akhikolla/updatedatatype-list3
R
false
false
435
r
testlist <- list(b = c(1785358954L, 1785358954L, 1785358954L, 1785358954L, 1785358954L, 1785358954L, 1785358954L, 1785358954L, 1785358954L, 1785358954L, -65281L, -16711841L, -12059008L, -2130837632L, -1895846273L, 38862848L, -16777216L, -16053493L, 1358954496L, -1L, -1L, -1L, -1L, 1090519039L, 973078783L, -8388608L, 8454143L, -1L, -1L, 28L, 0L, 0L, -16711681L)) result <- do.call(mcga:::ByteVectorToDoubles,testlist) str(result)
#' Blackwell Data for Covariate Balancing Propensity Score #' #' This data set gives the outcomes a well as treatment assignments and #' covariates for the example from Blackwell (2013). #' #' #' @name Blackwell #' @docType data #' @format A data frame consisting of 13 columns (including treatment #' assignment, time, and identifier vectors) and 570 observations. #' @references Blackwell, Matthew. (2013). A framework for dynamic causal #' inference in political science. American Journal of Political Science 57, 2, #' 504-619. #' @source d.gone.neg is the treatment. d.gone.neg.l1, d.gone.neg.l2, and #' d.gone.neg.l3 are lagged treatment variables. camp.length, deminc, #' base.poll, base.und, and office covariates. year is the year of the #' particular race, and time goes from the first measurement (time = 1) to the #' election (time = 5). demName is the identifier, and demprcnt is the outcome. #' @keywords datasets NULL #' LaLonde Data for Covariate Balancing Propensity Score #' #' This data set gives the outcomes a well as treatment assignments and #' covariates for the econometric evaluation of training programs in LaLonde #' (1986). #' #' #' @name LaLonde #' @docType data #' @format A data frame consisting of 12 columns (including a treatment #' assignment vector) and 3212 observations. #' @references LaLonde, R.J. (1986). Evaluating the econometric evaluations of #' training programs with experimental data. American Economic Review 76, 4, #' 604-620. #' @source Data from the National Supported Work Study. A benchmark matching #' dataset. Columns consist of an indicator for whether the observed unit was #' in the experimental subset; an indicator for whether the individual received #' the treatment; age in years; schooling in years; indicators for black and #' Hispanic; an indicator for marriage status, one of married; an indicator for #' no high school degree; reported earnings in 1974, 1975, and 1978; and #' whether the 1974 earnings variable is missing. Data not missing 1974 #' earnings are the Dehejia-Wahba subsample of the LaLonde data. Missing #' values for 1974 earnings set to zero. 1974 and 1975 earnings are #' pre-treatment. 1978 earnings is taken as the outcome variable. #' @keywords datasets NULL
/R/CBPS-package.R
no_license
cran/CBPS
R
false
false
2,326
r
#' Blackwell Data for Covariate Balancing Propensity Score #' #' This data set gives the outcomes a well as treatment assignments and #' covariates for the example from Blackwell (2013). #' #' #' @name Blackwell #' @docType data #' @format A data frame consisting of 13 columns (including treatment #' assignment, time, and identifier vectors) and 570 observations. #' @references Blackwell, Matthew. (2013). A framework for dynamic causal #' inference in political science. American Journal of Political Science 57, 2, #' 504-619. #' @source d.gone.neg is the treatment. d.gone.neg.l1, d.gone.neg.l2, and #' d.gone.neg.l3 are lagged treatment variables. camp.length, deminc, #' base.poll, base.und, and office covariates. year is the year of the #' particular race, and time goes from the first measurement (time = 1) to the #' election (time = 5). demName is the identifier, and demprcnt is the outcome. #' @keywords datasets NULL #' LaLonde Data for Covariate Balancing Propensity Score #' #' This data set gives the outcomes a well as treatment assignments and #' covariates for the econometric evaluation of training programs in LaLonde #' (1986). #' #' #' @name LaLonde #' @docType data #' @format A data frame consisting of 12 columns (including a treatment #' assignment vector) and 3212 observations. #' @references LaLonde, R.J. (1986). Evaluating the econometric evaluations of #' training programs with experimental data. American Economic Review 76, 4, #' 604-620. #' @source Data from the National Supported Work Study. A benchmark matching #' dataset. Columns consist of an indicator for whether the observed unit was #' in the experimental subset; an indicator for whether the individual received #' the treatment; age in years; schooling in years; indicators for black and #' Hispanic; an indicator for marriage status, one of married; an indicator for #' no high school degree; reported earnings in 1974, 1975, and 1978; and #' whether the 1974 earnings variable is missing. Data not missing 1974 #' earnings are the Dehejia-Wahba subsample of the LaLonde data. Missing #' values for 1974 earnings set to zero. 1974 and 1975 earnings are #' pre-treatment. 1978 earnings is taken as the outcome variable. #' @keywords datasets NULL
# Hadiza Mamman # Technical Interview # Analytical Flavor Systems library(GGally) library(ggplot2) library(caret) library(car) library(e1071) library(MASS) library(moments) library(corrplot) library(dplyr) library(pls) library(mgcv) library(nlme) library(MuMIn) setwd("~/Desktop/analyticalFlavorSystems/") redWine <- read.csv('winequality-red.csv', sep = ';') whiteWine <- read.csv('winequality-white.csv', sep = ';') redWine['color'] <- 'red' whiteWine['color'] <- 'white' data <- rbind(redWine,whiteWine) head(data) tail(data) names(data) summary(data) str(data) summary(data$quality) # calculate binwidth using the Freedman-Diaconis rule bw <- 2 * IQR(data$quality) / length(data$quality)^(1/3) qplot(quality, data=data, geom= "histogram",fill=color, binwidth=bw) #seems to follow a normal distribution, summary(data$alcohol) bw <- 2 * IQR(data$alcohol) / length(data$alcohol)^(1/3) qplot(alcohol, data=data, geom="histogram", fill=color, binwidth=bw ) # seems to be skewed to the right, will transform data alcoholTrans <- BoxCoxTrans(data$alcohol) alcoholTrans str(alcoholTrans) #lambda=-1.8 # check skewness skewness(data$alcohol) # the value is .565, indicating the predictor variable is moderately skewed qplot(alcohol, data=data, fill=color, binwidth=0.02)+ scale_x_log10() # after the log transformation the data resembles a normal distribution skewness(log(data$alcohol)) # the value decreased to 0.381 summary(data$density) bw <- 2 * IQR(data$density) / length(data$density)^(1/3) qplot(density, data=data, geom="histogram", fill=color, binwidth=bw) # seems to follow a normal distribution summary(data$volatile.acidity) bw <- 2 * IQR(data$volatile.acidity) / length(data$volatile.acidity)^(1/3) qplot(volatile.acidity, data=data, geom="histogram", fill=color, binwidth=bw) # seems to follow a normal distribution summary(data$sulphates) bw <- 2 * IQR(data$sulphates) / length(data$sulphates)^(1/3) qplot(sulphates, data=data, geom="histogram", fill=color, binwidth=bw) # seems to be slighlty skewed skewness(data$sulphates) #value is 1.79 indicating extreme skewness qplot(sulphates, data=data, fill=color, binwidth=0.02)+ scale_x_log10() #now resembles a normal distribution w/ skew value of .4 summary(data$pH) bw <- 2 * IQR(data$pH) / length(data$pH)^(1/3) qplot(pH, data=data, geom="histogram", fill=color, binwidth=bw) # seems to follow a normal distribution summary(data$total.sulfur.dioxide) bw <- 2 * IQR(data$total.sulfur.dioxide) / length(data$total.sulfur.dioxide)^(1/3) qplot(total.sulfur.dioxide, data=data, geom="histogram", fill=color, binwidth=bw) # seems to follow a normal distribution, w/ significant difference between red&white wine summary(data$free.sulfur.dioxide) bw <- 2 * IQR(data$free.sulfur.dioxide) / length(data$free.sulfur.dioxide)^(1/3) qplot(free.sulfur.dioxide, data=data, geom="histogram", fill=color, binwidth=bw) # seems to be skewed to the right skewness(data$free.sulfur.dioxide) #value is 1.22 indicating significant skewness qplot(free.sulfur.dioxide, data=data, fill=color, binwidth=0.02)+ scale_x_log10() skewness(log10(data$free.sulfur.dioxide)) summary(data$chlorides) bw <- 2 * IQR(data$chlorides) / length(data$chlorides)^(1/3) qplot(chlorides, data=data, geom="histogram", fill=color, binwidth=bw) # skewed to the right, will transform chlorideTrans <- BoxCoxTrans(data$chlorides) chlorideTrans # check skewness skewness(data$chlorides) # The value is 5.397, indicating significant skewness qplot(chlorides, data=data, fill=color, binwidth=0.002)+ scale_x_log10() # atfer the log transformation the data resembles a normal distribution summary(data$residual.sugar) bw <- 2 * IQR(data$residual.sugar) / length(data$residual.sugar)^(1/3) qplot(data$residual.sugar, data=data, geom="histogram", fill=color, binwidth=bw) # seems to be extremely skewed to the right skewness(data$residual.sugar) #value is 1.43 qplot(chlorides, data=data, fill=color, binwidth=0.02)+ scale_x_log10() summary(data$citric.acid) bw <- 2 * IQR(data$citric.acid) / length(data$citric.acid)^(1/3) qplot(data$citric.acid, data=data, geom="histogram", fill=color, binwidth=bw) # seems to follow a normal distribution summary(data$fixed.acidity) bw <- 2 * IQR(data$fixed.acidity) / length(data$fixed.acidity)^(1/3) qplot(data$fixed.acidity, data=data, geom="histogram", fill=color, binwidth=bw) # seems to be extremely skewed to the right qplot(data$fixed.acidity, data=data, fill=color, binwidth=0.02)+ scale_x_log10() #big difference between red&white wine #FILTERING PREDICTORS ggpairs(data) # seems to be correlation between : # alcohol&density,fixed acidity&density,residualsugar&denisty/sulfur dioxide nearZeroVar(data) #indicates no problematic near zero variance predictors cor(data$alcohol,data$density) # -.68 cor(data$fixed.acidity,data$density) #.459 cor(data$residual.sugar,data$density) #.553 cor(data$residual.sugar,data$total.sulfur.dioxide) #.495 data_set <- data[,-13] str(data_set) #get rid of non numeric variable (color) #remove high correlation variable df <- cor(data_set) df highCorr = findCorrelation(df,cutoff = .6) highCorr = sort(highCorr) adjData = data_set[,-c(highCorr)] str(adjData) str(data) # density and total.sulfur.dioxide were removed from the matrix plot(data$pH, data$quality) #seems that the quality is highest when the ph is between 3.2-3.5 plot(data$citric.acid,data$quality) #consistent pattern w highest quality score when citric acid is between 0.35-0.5 plot(data$volatile.acidity, data$quality) #consistent pattern w high quality score when acidity below 0.5 plot(data$residual.sugar,data$quality) #higher quality scores when lower than 15 plot(data$chlorides, data$quality) #consistent pattern w higher quality score when chloride content lower than 0.2 plot(data$alcohol,data$quality) #inconsistent pattern plot(data$fixed.acidity,data$quality) #higher quality scores when below 10 plot(data$sulphates,data$quality) #higher the sulphate content, the lower the score # DATA SPLITTING # first, center & scale data wineData <- scale(adjData, center = TRUE, scale = TRUE) wineData set.seed(1) trainIndex <- createDataPartition(adjData$quality, p=0.8, list = FALSE) trainSet <- wineData[trainIndex,] testSet <- wineData[-trainIndex,] trainSet1 <- as.data.frame(trainSet) testSet1 <- as.data.frame(testSet) repeatSplits <- createDataPartition(trainSet, p=0.8, list = FALSE, times =3) str(repeatSplits) model1 <- plsr(quality~fixed.acidity+volatile.acidity+citric.acid+residual.sugar+chlorides+free.sulfur.dioxide+pH+sulphates+alcohol,data=trainSet) summary(model1) model2 <- plsr(quality~fixed.acidity+volatile.acidity+citric.acid+chlorides+pH+sulphates,data=trainSet1) summary(model2) predictions <- predict(model1,testSet[1:6], ncomp = 1:3) predictions predictions1 <- predict(model2,testSet1[1:6]) predictions1 head(data) head(predictions) head(predictions1) model1res <- resid(model1) print(model1res) #majority of the residuals are close to zero, indicating a decent model RMSE(testSet[1:6],predictions) #value is 5.61608 RMSE(trainSet[1:6],predictions)#value is 5.114963 #RMSE values for both train and test set are close indicating a good model plot(quality~fixed.acidity+volatile.acidity+citric.acid+residual.sugar+chlorides+free.sulfur.dioxide+pH+sulphates+alcohol,data=trainSet) abline(model1)
/WineTasting Code.R
no_license
diza-m/WineTasting
R
false
false
7,336
r
# Hadiza Mamman # Technical Interview # Analytical Flavor Systems library(GGally) library(ggplot2) library(caret) library(car) library(e1071) library(MASS) library(moments) library(corrplot) library(dplyr) library(pls) library(mgcv) library(nlme) library(MuMIn) setwd("~/Desktop/analyticalFlavorSystems/") redWine <- read.csv('winequality-red.csv', sep = ';') whiteWine <- read.csv('winequality-white.csv', sep = ';') redWine['color'] <- 'red' whiteWine['color'] <- 'white' data <- rbind(redWine,whiteWine) head(data) tail(data) names(data) summary(data) str(data) summary(data$quality) # calculate binwidth using the Freedman-Diaconis rule bw <- 2 * IQR(data$quality) / length(data$quality)^(1/3) qplot(quality, data=data, geom= "histogram",fill=color, binwidth=bw) #seems to follow a normal distribution, summary(data$alcohol) bw <- 2 * IQR(data$alcohol) / length(data$alcohol)^(1/3) qplot(alcohol, data=data, geom="histogram", fill=color, binwidth=bw ) # seems to be skewed to the right, will transform data alcoholTrans <- BoxCoxTrans(data$alcohol) alcoholTrans str(alcoholTrans) #lambda=-1.8 # check skewness skewness(data$alcohol) # the value is .565, indicating the predictor variable is moderately skewed qplot(alcohol, data=data, fill=color, binwidth=0.02)+ scale_x_log10() # after the log transformation the data resembles a normal distribution skewness(log(data$alcohol)) # the value decreased to 0.381 summary(data$density) bw <- 2 * IQR(data$density) / length(data$density)^(1/3) qplot(density, data=data, geom="histogram", fill=color, binwidth=bw) # seems to follow a normal distribution summary(data$volatile.acidity) bw <- 2 * IQR(data$volatile.acidity) / length(data$volatile.acidity)^(1/3) qplot(volatile.acidity, data=data, geom="histogram", fill=color, binwidth=bw) # seems to follow a normal distribution summary(data$sulphates) bw <- 2 * IQR(data$sulphates) / length(data$sulphates)^(1/3) qplot(sulphates, data=data, geom="histogram", fill=color, binwidth=bw) # seems to be slighlty skewed skewness(data$sulphates) #value is 1.79 indicating extreme skewness qplot(sulphates, data=data, fill=color, binwidth=0.02)+ scale_x_log10() #now resembles a normal distribution w/ skew value of .4 summary(data$pH) bw <- 2 * IQR(data$pH) / length(data$pH)^(1/3) qplot(pH, data=data, geom="histogram", fill=color, binwidth=bw) # seems to follow a normal distribution summary(data$total.sulfur.dioxide) bw <- 2 * IQR(data$total.sulfur.dioxide) / length(data$total.sulfur.dioxide)^(1/3) qplot(total.sulfur.dioxide, data=data, geom="histogram", fill=color, binwidth=bw) # seems to follow a normal distribution, w/ significant difference between red&white wine summary(data$free.sulfur.dioxide) bw <- 2 * IQR(data$free.sulfur.dioxide) / length(data$free.sulfur.dioxide)^(1/3) qplot(free.sulfur.dioxide, data=data, geom="histogram", fill=color, binwidth=bw) # seems to be skewed to the right skewness(data$free.sulfur.dioxide) #value is 1.22 indicating significant skewness qplot(free.sulfur.dioxide, data=data, fill=color, binwidth=0.02)+ scale_x_log10() skewness(log10(data$free.sulfur.dioxide)) summary(data$chlorides) bw <- 2 * IQR(data$chlorides) / length(data$chlorides)^(1/3) qplot(chlorides, data=data, geom="histogram", fill=color, binwidth=bw) # skewed to the right, will transform chlorideTrans <- BoxCoxTrans(data$chlorides) chlorideTrans # check skewness skewness(data$chlorides) # The value is 5.397, indicating significant skewness qplot(chlorides, data=data, fill=color, binwidth=0.002)+ scale_x_log10() # atfer the log transformation the data resembles a normal distribution summary(data$residual.sugar) bw <- 2 * IQR(data$residual.sugar) / length(data$residual.sugar)^(1/3) qplot(data$residual.sugar, data=data, geom="histogram", fill=color, binwidth=bw) # seems to be extremely skewed to the right skewness(data$residual.sugar) #value is 1.43 qplot(chlorides, data=data, fill=color, binwidth=0.02)+ scale_x_log10() summary(data$citric.acid) bw <- 2 * IQR(data$citric.acid) / length(data$citric.acid)^(1/3) qplot(data$citric.acid, data=data, geom="histogram", fill=color, binwidth=bw) # seems to follow a normal distribution summary(data$fixed.acidity) bw <- 2 * IQR(data$fixed.acidity) / length(data$fixed.acidity)^(1/3) qplot(data$fixed.acidity, data=data, geom="histogram", fill=color, binwidth=bw) # seems to be extremely skewed to the right qplot(data$fixed.acidity, data=data, fill=color, binwidth=0.02)+ scale_x_log10() #big difference between red&white wine #FILTERING PREDICTORS ggpairs(data) # seems to be correlation between : # alcohol&density,fixed acidity&density,residualsugar&denisty/sulfur dioxide nearZeroVar(data) #indicates no problematic near zero variance predictors cor(data$alcohol,data$density) # -.68 cor(data$fixed.acidity,data$density) #.459 cor(data$residual.sugar,data$density) #.553 cor(data$residual.sugar,data$total.sulfur.dioxide) #.495 data_set <- data[,-13] str(data_set) #get rid of non numeric variable (color) #remove high correlation variable df <- cor(data_set) df highCorr = findCorrelation(df,cutoff = .6) highCorr = sort(highCorr) adjData = data_set[,-c(highCorr)] str(adjData) str(data) # density and total.sulfur.dioxide were removed from the matrix plot(data$pH, data$quality) #seems that the quality is highest when the ph is between 3.2-3.5 plot(data$citric.acid,data$quality) #consistent pattern w highest quality score when citric acid is between 0.35-0.5 plot(data$volatile.acidity, data$quality) #consistent pattern w high quality score when acidity below 0.5 plot(data$residual.sugar,data$quality) #higher quality scores when lower than 15 plot(data$chlorides, data$quality) #consistent pattern w higher quality score when chloride content lower than 0.2 plot(data$alcohol,data$quality) #inconsistent pattern plot(data$fixed.acidity,data$quality) #higher quality scores when below 10 plot(data$sulphates,data$quality) #higher the sulphate content, the lower the score # DATA SPLITTING # first, center & scale data wineData <- scale(adjData, center = TRUE, scale = TRUE) wineData set.seed(1) trainIndex <- createDataPartition(adjData$quality, p=0.8, list = FALSE) trainSet <- wineData[trainIndex,] testSet <- wineData[-trainIndex,] trainSet1 <- as.data.frame(trainSet) testSet1 <- as.data.frame(testSet) repeatSplits <- createDataPartition(trainSet, p=0.8, list = FALSE, times =3) str(repeatSplits) model1 <- plsr(quality~fixed.acidity+volatile.acidity+citric.acid+residual.sugar+chlorides+free.sulfur.dioxide+pH+sulphates+alcohol,data=trainSet) summary(model1) model2 <- plsr(quality~fixed.acidity+volatile.acidity+citric.acid+chlorides+pH+sulphates,data=trainSet1) summary(model2) predictions <- predict(model1,testSet[1:6], ncomp = 1:3) predictions predictions1 <- predict(model2,testSet1[1:6]) predictions1 head(data) head(predictions) head(predictions1) model1res <- resid(model1) print(model1res) #majority of the residuals are close to zero, indicating a decent model RMSE(testSet[1:6],predictions) #value is 5.61608 RMSE(trainSet[1:6],predictions)#value is 5.114963 #RMSE values for both train and test set are close indicating a good model plot(quality~fixed.acidity+volatile.acidity+citric.acid+residual.sugar+chlorides+free.sulfur.dioxide+pH+sulphates+alcohol,data=trainSet) abline(model1)
#' Improved function for reducing an adjacency matrix to present compounds, #' with the option to include `n`-nearest neighours. #' - A bit of testing puts it at ~0.023 seconds to reduce the full adjacency #' matrix (8810 compounds) to 207 compounds, with `n = 0`. #' @param adjmat Adjacency matrix to reduce. #' @param isomericReduction Output from the function `isomericReduction`, i.e. #' the three-column dataframe with names, anchor IDs, and peripheral IDs. #' @param n Number of neighbours. Defaults to 0. #' @return Reduced adjacency matrix, with `n`-nearest neighbours. If `n == 0`, #' the reduced adjacency matrix with relevant IDs only is returned. adjmatReduceNplus <- function(adjmat, isomericReduction, n = 0) { # Shorthand dimension names, and check square dn1 <- dimnames(adjmat)[[1]] if (!(all(dn1 == dimnames(adjmat)[[2]]))) { stop("dimnames(adjmat) are not all exactly equal") } # Get the IDs to reduce by idReduce <- sort(unique(c(isomericReduction[, 2], isomericReduction[, 3]))) # Get the IDs that occur in the adjacency matrix target <- dn1[which(dn1 %in% idReduce)] # If any neighbours if (n > 0) { # Loop over n for (i in seq_len(n)) { # Include neighbouring compounds in the target IDs target <- sort(unique(c( target, sort(unique(unlist(sapply( target, function(x) { dn1[which(adjmat[x, ] != 0)] } )))) ))) } } # Reduce the adjacency matrix to the overall target adjmatSub <- adjmat[target, target] # Get the rows to reduce by isomer isomer <- isomericReduction[which(!(is.na(isomericReduction[, 3]))), ] # Specify target/anchor isomers isomerTarget <- isomer[, 2] # Get the data to use in reduction operations reductionData <- lapply( isomerTarget, function(x) { # Peripheral IDs isomerPeri <- isomer[which(isomer[, 2] == x), 3] # Contents of the new row (and column) newRow <- apply(adjmatSub[c(x, isomerPeri), ], 2, max) return(list("isomerPeri" = isomerPeri, "newRow" = newRow)) } ) # Loop over the reduction data for (i in seq_along(reductionData)) { # Assign the new value for each relevant row and column adjmatSub[isomerTarget[i], ] <- reductionData[[i]][["newRow"]] adjmatSub[, isomerTarget[i]] <- reductionData[[i]][["newRow"]] } # Shorthand dimension names of the subset adjacency matrix dn1s <- dimnames(adjmatSub)[[1]] dn2s <- dimnames(adjmatSub)[[2]] # Get the vector of peripheral IDs peri <- sort(unique(unlist( sapply(reductionData, function(x) { x[["isomerPeri"]] }) ))) # Reduce the matrix to the present compounds, and eliminate loops dn1smp <- which(!(dn1s %in% peri)) dn2smp <- which(!(dn2s %in% peri)) result <- adjmatSub[dn1s[dn1smp], dn2s[dn2smp]] diag(result) <- 0 # Return return(result) }
/old/kegg/networkApp202012/coreData/functions/adjmatReduceNplus.R
permissive
glm729/anpc_public
R
false
false
2,855
r
#' Improved function for reducing an adjacency matrix to present compounds, #' with the option to include `n`-nearest neighours. #' - A bit of testing puts it at ~0.023 seconds to reduce the full adjacency #' matrix (8810 compounds) to 207 compounds, with `n = 0`. #' @param adjmat Adjacency matrix to reduce. #' @param isomericReduction Output from the function `isomericReduction`, i.e. #' the three-column dataframe with names, anchor IDs, and peripheral IDs. #' @param n Number of neighbours. Defaults to 0. #' @return Reduced adjacency matrix, with `n`-nearest neighbours. If `n == 0`, #' the reduced adjacency matrix with relevant IDs only is returned. adjmatReduceNplus <- function(adjmat, isomericReduction, n = 0) { # Shorthand dimension names, and check square dn1 <- dimnames(adjmat)[[1]] if (!(all(dn1 == dimnames(adjmat)[[2]]))) { stop("dimnames(adjmat) are not all exactly equal") } # Get the IDs to reduce by idReduce <- sort(unique(c(isomericReduction[, 2], isomericReduction[, 3]))) # Get the IDs that occur in the adjacency matrix target <- dn1[which(dn1 %in% idReduce)] # If any neighbours if (n > 0) { # Loop over n for (i in seq_len(n)) { # Include neighbouring compounds in the target IDs target <- sort(unique(c( target, sort(unique(unlist(sapply( target, function(x) { dn1[which(adjmat[x, ] != 0)] } )))) ))) } } # Reduce the adjacency matrix to the overall target adjmatSub <- adjmat[target, target] # Get the rows to reduce by isomer isomer <- isomericReduction[which(!(is.na(isomericReduction[, 3]))), ] # Specify target/anchor isomers isomerTarget <- isomer[, 2] # Get the data to use in reduction operations reductionData <- lapply( isomerTarget, function(x) { # Peripheral IDs isomerPeri <- isomer[which(isomer[, 2] == x), 3] # Contents of the new row (and column) newRow <- apply(adjmatSub[c(x, isomerPeri), ], 2, max) return(list("isomerPeri" = isomerPeri, "newRow" = newRow)) } ) # Loop over the reduction data for (i in seq_along(reductionData)) { # Assign the new value for each relevant row and column adjmatSub[isomerTarget[i], ] <- reductionData[[i]][["newRow"]] adjmatSub[, isomerTarget[i]] <- reductionData[[i]][["newRow"]] } # Shorthand dimension names of the subset adjacency matrix dn1s <- dimnames(adjmatSub)[[1]] dn2s <- dimnames(adjmatSub)[[2]] # Get the vector of peripheral IDs peri <- sort(unique(unlist( sapply(reductionData, function(x) { x[["isomerPeri"]] }) ))) # Reduce the matrix to the present compounds, and eliminate loops dn1smp <- which(!(dn1s %in% peri)) dn2smp <- which(!(dn2s %in% peri)) result <- adjmatSub[dn1s[dn1smp], dn2s[dn2smp]] diag(result) <- 0 # Return return(result) }
# cv for classification tree (smoker) # models used glm.smoker.2$call #glm bestmod$call #svm nn3$call #neural network set.seed(5) MC.1 <- c() MC.2 <- c() MC.3 <- c() for(i in 1:10){ train.YES <- sample(x = c(TRUE, FALSE), size = nrow(insurance), replace = TRUE) insurance.train <- insurance[train.YES, ] insurance.test <- insurance[!train.YES, ] insurance.train.normalized <-dplyr::select(insurance.train, smoker, charges, age, bmi) insurance.test.normalized <-dplyr::select(insurance.test, smoker, charges, age, bmi) # Min-Max Normalization insurance.train.normalized$charges <- (insurance.train.normalized$charges - min(insurance.train.normalized$charges))/(max(insurance.train.normalized$charges) - min(insurance.train.normalized$charges)) insurance.train.normalized$age <- (insurance.train.normalized$age - min(insurance.train.normalized$age))/(max(insurance.train.normalized$age) - min(insurance.train.normalized$age)) insurance.train.normalized$bmi <- (insurance.train.normalized$bmi - min(insurance.train.normalized$bmi))/(max(insurance.train.normalized$bmi)-min(insurance.train.normalized$bmi)) insurance.test.normalized$charges <- (insurance.test.normalized$charges - min(insurance.test.normalized$charges))/(max(insurance.test.normalized$charges) - min(insurance.test.normalized$charges)) insurance.test.normalized$age <- (insurance.test.normalized$age - min(insurance.test.normalized$age))/(max(insurance.test.normalized$age) - min(insurance.test.normalized$age)) insurance.test.normalized$bmi <- (insurance.test.normalized$bmi - min(insurance.test.normalized$bmi))/(max(insurance.test.normalized$bmi)-min(insurance.test.normalized$bmi)) # fit model with train data mod.1 <- glm(formula = smoker ~ age + bmi + charges, family = "binomial", data = insurance.train) mod.2 <- svm(smoker~charges+bmi, data = insurance.train, cost =5) nn3 <- neuralnet(smoker~charges + age + bmi, data = insurance.train.normalized, hidden = c(3,2,1), threshold = 0.0025, lifesign = 'full', lifesign.step = 500, linear.output = FALSE) # make prediction on test data #mod1 mod.1.pred <- predict(mod.1, newdata = insurance.test, type="response") mod.1.pred.binomial <- ifelse(mod.1.pred > 0.5, yes = 1, no = 0) df.mod.1.pred <- data.frame(obs = insurance.test$smoker, fitted = mod.1.pred.binomial) mc.table.1 <- table(obs = df.mod.1.pred$obs,fit = df.mod.1.pred$fitted) MC.1[i] <- (mc.table.1[2]+mc.table.1[3])/(mc.table.1[2]+mc.table.1[3]+mc.table.1[1]+mc.table.1[4]) #mod2 mod.2.pred <- predict(mod.2, newdata = insurance.test) df.mod.2.pred <- data.frame(obs = insurance.test$smoker, fitted = mod.2.pred) mc.table.2 <- table(obs = df.mod.2.pred$obs,fit = df.mod.2.pred$fitted) MC.2[i] <- (mc.table.2[2]+mc.table.2[3])/(mc.table.2[2]+mc.table.2[3]+mc.table.2[1]+mc.table.2[4]) #mod3 prediction_nn3 <- predict(nn3,insurance.test.normalized) class_nn <- apply(prediction_nn3, 1, which.max) df.mod.3.pred <- data.frame(obs = insurance.test$smoker, fitted = class_nn) mc.table.3 <- table(obs = df.mod.3.pred$obs,fit = df.mod.3.pred$fitted) MC.3[i] <- (mc.table.3[2]+mc.table.3[3])/(mc.table.3[2]+mc.table.3[3]+mc.table.3[1]+mc.table.3[4]) } #misclassification rates of the models mean(MC.1) mean(MC.2) mean(MC.3)
/02_analysis/cv_classification2.R
no_license
caro-mat/machinelearning
R
false
false
3,517
r
# cv for classification tree (smoker) # models used glm.smoker.2$call #glm bestmod$call #svm nn3$call #neural network set.seed(5) MC.1 <- c() MC.2 <- c() MC.3 <- c() for(i in 1:10){ train.YES <- sample(x = c(TRUE, FALSE), size = nrow(insurance), replace = TRUE) insurance.train <- insurance[train.YES, ] insurance.test <- insurance[!train.YES, ] insurance.train.normalized <-dplyr::select(insurance.train, smoker, charges, age, bmi) insurance.test.normalized <-dplyr::select(insurance.test, smoker, charges, age, bmi) # Min-Max Normalization insurance.train.normalized$charges <- (insurance.train.normalized$charges - min(insurance.train.normalized$charges))/(max(insurance.train.normalized$charges) - min(insurance.train.normalized$charges)) insurance.train.normalized$age <- (insurance.train.normalized$age - min(insurance.train.normalized$age))/(max(insurance.train.normalized$age) - min(insurance.train.normalized$age)) insurance.train.normalized$bmi <- (insurance.train.normalized$bmi - min(insurance.train.normalized$bmi))/(max(insurance.train.normalized$bmi)-min(insurance.train.normalized$bmi)) insurance.test.normalized$charges <- (insurance.test.normalized$charges - min(insurance.test.normalized$charges))/(max(insurance.test.normalized$charges) - min(insurance.test.normalized$charges)) insurance.test.normalized$age <- (insurance.test.normalized$age - min(insurance.test.normalized$age))/(max(insurance.test.normalized$age) - min(insurance.test.normalized$age)) insurance.test.normalized$bmi <- (insurance.test.normalized$bmi - min(insurance.test.normalized$bmi))/(max(insurance.test.normalized$bmi)-min(insurance.test.normalized$bmi)) # fit model with train data mod.1 <- glm(formula = smoker ~ age + bmi + charges, family = "binomial", data = insurance.train) mod.2 <- svm(smoker~charges+bmi, data = insurance.train, cost =5) nn3 <- neuralnet(smoker~charges + age + bmi, data = insurance.train.normalized, hidden = c(3,2,1), threshold = 0.0025, lifesign = 'full', lifesign.step = 500, linear.output = FALSE) # make prediction on test data #mod1 mod.1.pred <- predict(mod.1, newdata = insurance.test, type="response") mod.1.pred.binomial <- ifelse(mod.1.pred > 0.5, yes = 1, no = 0) df.mod.1.pred <- data.frame(obs = insurance.test$smoker, fitted = mod.1.pred.binomial) mc.table.1 <- table(obs = df.mod.1.pred$obs,fit = df.mod.1.pred$fitted) MC.1[i] <- (mc.table.1[2]+mc.table.1[3])/(mc.table.1[2]+mc.table.1[3]+mc.table.1[1]+mc.table.1[4]) #mod2 mod.2.pred <- predict(mod.2, newdata = insurance.test) df.mod.2.pred <- data.frame(obs = insurance.test$smoker, fitted = mod.2.pred) mc.table.2 <- table(obs = df.mod.2.pred$obs,fit = df.mod.2.pred$fitted) MC.2[i] <- (mc.table.2[2]+mc.table.2[3])/(mc.table.2[2]+mc.table.2[3]+mc.table.2[1]+mc.table.2[4]) #mod3 prediction_nn3 <- predict(nn3,insurance.test.normalized) class_nn <- apply(prediction_nn3, 1, which.max) df.mod.3.pred <- data.frame(obs = insurance.test$smoker, fitted = class_nn) mc.table.3 <- table(obs = df.mod.3.pred$obs,fit = df.mod.3.pred$fitted) MC.3[i] <- (mc.table.3[2]+mc.table.3[3])/(mc.table.3[2]+mc.table.3[3]+mc.table.3[1]+mc.table.3[4]) } #misclassification rates of the models mean(MC.1) mean(MC.2) mean(MC.3)
#' Run the party calls classifier #' #' Use the iterative algorithm that (1) predicts ideal points based on last #' iteration's non-party calls, (2) runs regressions of roll call vote on #' ideal points and party, (3) classify new iteration of non-party calls as #' votes for which the p value on party is > .05. #' @param rc a rollcall object #' @return rollcall object with record of classification algorithm and #' list of classified party calls #' @import data.table emIRT pscl #' @export code_party_calls <- function(rc) { rc <- pscl::dropRollCall(rc, dropList = alist(dropLegis = state == "USA")) ## BEGIN NEW # rc <- pscl::dropRollCall(rc, dropList = alist(lop = 0)) ## END NEW rc <- emIRT::convertRC(rc, type = "binIRT") DT <- CJ(vt = colnames(rc$votes), mc = rownames(rc$votes), sorted = FALSE) DT$y <- as.vector(rc$votes) DT$party <- rc$legis.data$party DT[y %in% c(0, 9), y:= NA] DT[y == -1, y := 0] ## BEGIN REPLACE #noncalls <- sample(rc$m, floor(.5 * rc$m)) ## REPLACED WITH noncalls_DT <- DT[, .(yea_perc = mean(y, na.rm = TRUE)), by = vt] noncalls <- which(noncalls_DT[, yea_perc <= .35 | .65 <= yea_perc]) ## END REPLACE ## BEGIN NEW match_switch <- FALSE ## END NEW switched_votes <- seq_len(rc$m) match_counter <- 0 counter <- 0 record_of_coding <- list() while (counter <= 15 | ## BEGIN REPLACE # (counter < 100 & match_counter < 10 & length(switched_votes) > 0)) { ## REPLACED WITH (counter < 100 & match_counter < 15 & length(switched_votes) > 0)) { ## END REPLACE record_of_coding[[counter + 1]] <- noncalls old_noncalls <- noncalls old_switched_votes <- switched_votes noncalls <- code_party_calls_1step(rc, DT, noncalls) switched_votes <- symdiff(noncalls, old_noncalls) ## BEGIN REPLACE # if (length(switched_votes) <= 5) { # match_counter <- match_counter + 1 # } else { # match_counter <- 0 # } # counter <- counter + 1 # cat("Iteration", counter, "had", length(switched_votes), "out of", rc$m, # "switched votes\n") ## REPLACED WITH counter <- counter + 1 countdown <- "" if ((length(switched_votes) > length(old_switched_votes) | length(switched_votes) <= 5) & counter > 15) { match_switch <- TRUE } if (match_switch) { match_counter <- match_counter + 1 countdown <- paste0("(", 15 - match_counter, " iterations left)") } cat("Iteration", counter, "had", length(switched_votes), "out of", rc$m, "switched votes", countdown, "\n") ## END REPLACE } rc$party_calls <- seq_len(rc$m)[-noncalls] rc$record_of_coding <- record_of_coding rc } #' Run one step of the party calls algorithm #' #' To be used inside a call to code_party_calls #' @param rc a rollcall object #' @param DT data.table with votes and party indicators #' @param noncalls indices for non-party calls from last run #' @return vector of indices for non-party calls code_party_calls_1step <- function(rc, DT, noncalls) { rc1 <- rc rc2 <- rc rc1$votes <- rc$votes[, noncalls] rc2$votes <- rc$votes[, -noncalls] rc1$m <- ncol(rc1$votes) rc2$m <- ncol(rc2$votes) p <- emIRT::makePriors(rc1$n, rc1$m, 1) s <- emIRT::getStarts(rc1$n, rc1$m, 1) sink_target <- if (Sys.info()[["sysname"]] == "Windows") { "NUL" } else { "/dev/null" } sink(sink_target) l <- emIRT::binIRT(.rc = rc1, .starts = s, .priors = p, .control = list(threads = 1, verbose = FALSE, thresh = 1e-6)) sink() unlink(sink_target) DT$x <- l$means$x regs <- DT[party %in% c("D", "R"), test_rollcall(.SD), .(vt)] pvals <- regs$p pvals[is.na(pvals)] <- 1 ok <- pvals > .05 which(ok) } #' Find symmetric difference #' #' The symmetric difference is defined as the set difference between the #' union of two sets and the intersection of those sets. #' @param x vector #' @param y vector #' @return vector of elements in either x or y but not both symdiff <- function(x, y) { sort(setdiff(base::union(x, y), base::intersect(x, y))) } #' Regress a single roll call on party indicator and ideal points #' #' To be used inside a call to code_party_calls_1step #' @param .SD subset of a data.table of roll call votes, with a column for party #' labels #' @return list of coefficient, standard error, t value, and p value for the #' coefficient on party test_rollcall <- function(.SD) { ## BEGIN NEW .SD <- .SD[party %in% c("D", "R")] n_yea_reps <- .SD[, sum(y == 1 & party == "R", na.rm = TRUE)] n_nay_reps <- .SD[, sum(y == 0 & party == "R", na.rm = TRUE)] n_yea_dems <- .SD[, sum(y == 1 & party == "D", na.rm = TRUE)] n_nay_dems <- .SD[, sum(y == 0 & party == "D", na.rm = TRUE)] party_line_vote <- (n_yea_reps == 0 & n_nay_reps > 0 & n_yea_dems > 0 & n_nay_dems == 0) | (n_yea_reps > 0 & n_nay_reps == 0 & n_yea_dems == 0 & n_nay_dems > 0) ## END NEW if (mean(.SD[, y], na.rm = TRUE) %in% c(0:1, NaN) | length(unique(.SD[!is.na(y) & party %in% c("D", "R"), party])) == 1L) { list(b = 0, se = 0, t = Inf, p = NA_real_) ## BEGIN NEW } else if (party_line_vote) { list(b = 1, se = 0, t = Inf, p = 0) ## END NEW } else { ## BEGIN REPLACE m <- lm(y ~ party + x, data = .SD) suppressWarnings(summ <- summary(m)$coef["partyR", ]) list(b = summ["Estimate"], se = summ["Std. Error"], t = summ["t value"], p = summ["Pr(>|t|)"]) ## REPLACED WITH # m <- brglm::brglm(y ~ party + x, data = .SD, family = binomial) # suppressWarnings(summ <- summary(m)$coef["partyR", ]) # list(b = summ["Estimate"], se = summ["Std. Error"], # t = summ["z value"], p = summ["Pr(>|z|)"]) ## END REPLACE } }
/old/modified_summer_version_tests.R
no_license
Hershberger/partycalls
R
false
false
5,711
r
#' Run the party calls classifier #' #' Use the iterative algorithm that (1) predicts ideal points based on last #' iteration's non-party calls, (2) runs regressions of roll call vote on #' ideal points and party, (3) classify new iteration of non-party calls as #' votes for which the p value on party is > .05. #' @param rc a rollcall object #' @return rollcall object with record of classification algorithm and #' list of classified party calls #' @import data.table emIRT pscl #' @export code_party_calls <- function(rc) { rc <- pscl::dropRollCall(rc, dropList = alist(dropLegis = state == "USA")) ## BEGIN NEW # rc <- pscl::dropRollCall(rc, dropList = alist(lop = 0)) ## END NEW rc <- emIRT::convertRC(rc, type = "binIRT") DT <- CJ(vt = colnames(rc$votes), mc = rownames(rc$votes), sorted = FALSE) DT$y <- as.vector(rc$votes) DT$party <- rc$legis.data$party DT[y %in% c(0, 9), y:= NA] DT[y == -1, y := 0] ## BEGIN REPLACE #noncalls <- sample(rc$m, floor(.5 * rc$m)) ## REPLACED WITH noncalls_DT <- DT[, .(yea_perc = mean(y, na.rm = TRUE)), by = vt] noncalls <- which(noncalls_DT[, yea_perc <= .35 | .65 <= yea_perc]) ## END REPLACE ## BEGIN NEW match_switch <- FALSE ## END NEW switched_votes <- seq_len(rc$m) match_counter <- 0 counter <- 0 record_of_coding <- list() while (counter <= 15 | ## BEGIN REPLACE # (counter < 100 & match_counter < 10 & length(switched_votes) > 0)) { ## REPLACED WITH (counter < 100 & match_counter < 15 & length(switched_votes) > 0)) { ## END REPLACE record_of_coding[[counter + 1]] <- noncalls old_noncalls <- noncalls old_switched_votes <- switched_votes noncalls <- code_party_calls_1step(rc, DT, noncalls) switched_votes <- symdiff(noncalls, old_noncalls) ## BEGIN REPLACE # if (length(switched_votes) <= 5) { # match_counter <- match_counter + 1 # } else { # match_counter <- 0 # } # counter <- counter + 1 # cat("Iteration", counter, "had", length(switched_votes), "out of", rc$m, # "switched votes\n") ## REPLACED WITH counter <- counter + 1 countdown <- "" if ((length(switched_votes) > length(old_switched_votes) | length(switched_votes) <= 5) & counter > 15) { match_switch <- TRUE } if (match_switch) { match_counter <- match_counter + 1 countdown <- paste0("(", 15 - match_counter, " iterations left)") } cat("Iteration", counter, "had", length(switched_votes), "out of", rc$m, "switched votes", countdown, "\n") ## END REPLACE } rc$party_calls <- seq_len(rc$m)[-noncalls] rc$record_of_coding <- record_of_coding rc } #' Run one step of the party calls algorithm #' #' To be used inside a call to code_party_calls #' @param rc a rollcall object #' @param DT data.table with votes and party indicators #' @param noncalls indices for non-party calls from last run #' @return vector of indices for non-party calls code_party_calls_1step <- function(rc, DT, noncalls) { rc1 <- rc rc2 <- rc rc1$votes <- rc$votes[, noncalls] rc2$votes <- rc$votes[, -noncalls] rc1$m <- ncol(rc1$votes) rc2$m <- ncol(rc2$votes) p <- emIRT::makePriors(rc1$n, rc1$m, 1) s <- emIRT::getStarts(rc1$n, rc1$m, 1) sink_target <- if (Sys.info()[["sysname"]] == "Windows") { "NUL" } else { "/dev/null" } sink(sink_target) l <- emIRT::binIRT(.rc = rc1, .starts = s, .priors = p, .control = list(threads = 1, verbose = FALSE, thresh = 1e-6)) sink() unlink(sink_target) DT$x <- l$means$x regs <- DT[party %in% c("D", "R"), test_rollcall(.SD), .(vt)] pvals <- regs$p pvals[is.na(pvals)] <- 1 ok <- pvals > .05 which(ok) } #' Find symmetric difference #' #' The symmetric difference is defined as the set difference between the #' union of two sets and the intersection of those sets. #' @param x vector #' @param y vector #' @return vector of elements in either x or y but not both symdiff <- function(x, y) { sort(setdiff(base::union(x, y), base::intersect(x, y))) } #' Regress a single roll call on party indicator and ideal points #' #' To be used inside a call to code_party_calls_1step #' @param .SD subset of a data.table of roll call votes, with a column for party #' labels #' @return list of coefficient, standard error, t value, and p value for the #' coefficient on party test_rollcall <- function(.SD) { ## BEGIN NEW .SD <- .SD[party %in% c("D", "R")] n_yea_reps <- .SD[, sum(y == 1 & party == "R", na.rm = TRUE)] n_nay_reps <- .SD[, sum(y == 0 & party == "R", na.rm = TRUE)] n_yea_dems <- .SD[, sum(y == 1 & party == "D", na.rm = TRUE)] n_nay_dems <- .SD[, sum(y == 0 & party == "D", na.rm = TRUE)] party_line_vote <- (n_yea_reps == 0 & n_nay_reps > 0 & n_yea_dems > 0 & n_nay_dems == 0) | (n_yea_reps > 0 & n_nay_reps == 0 & n_yea_dems == 0 & n_nay_dems > 0) ## END NEW if (mean(.SD[, y], na.rm = TRUE) %in% c(0:1, NaN) | length(unique(.SD[!is.na(y) & party %in% c("D", "R"), party])) == 1L) { list(b = 0, se = 0, t = Inf, p = NA_real_) ## BEGIN NEW } else if (party_line_vote) { list(b = 1, se = 0, t = Inf, p = 0) ## END NEW } else { ## BEGIN REPLACE m <- lm(y ~ party + x, data = .SD) suppressWarnings(summ <- summary(m)$coef["partyR", ]) list(b = summ["Estimate"], se = summ["Std. Error"], t = summ["t value"], p = summ["Pr(>|t|)"]) ## REPLACED WITH # m <- brglm::brglm(y ~ party + x, data = .SD, family = binomial) # suppressWarnings(summ <- summary(m)$coef["partyR", ]) # list(b = summ["Estimate"], se = summ["Std. Error"], # t = summ["z value"], p = summ["Pr(>|z|)"]) ## END REPLACE } }
rm(list=ls()) library(lubridate) library(sqldf) library(DMwR) hpd200405<- read.table("200405hpd.txt", sep=",",header = T, dec = ".") # Read 01 File # Changing Format as applicable hpd200405$YearMonthDay<-ymd(hpd200405$YearMonthDay) hpd200405$YearMonthDay<-as.factor(hpd200405$YearMonthDay) hpd200405$WeatherStationID<-as.factor(hpd200405$WeatherStationID) # Deriving time slots in weather data hpd200405$TimeSlot<-ifelse(hpd200405$Time<200,'Midnight to 2AM',ifelse(hpd200405$Time<400,'2AM to 4AM', ifelse(hpd200405$Time<600,'4AM to 6AM', ifelse(hpd200405$Time<800,'6AM to 8AM', ifelse(hpd200405$Time<1000,'8AM to 10AM', ifelse(hpd200405$Time<1200,'10AM to Noon', ifelse(hpd200405$Time<1400,'Noon to 2PM', ifelse(hpd200405$Time<1600,'2PM to 4PM', ifelse(hpd200405$Time<1800,'4PM to 6PM', ifelse(hpd200405$Time<2000,'6PM to 8PM', ifelse(hpd200405$Time<2200,'8PM to 10PM','10PM to Midnight'))))))))))) hpd200405$Time<-NULL # Dropping time column # Aggregating Hourly Precipitation by Station, Date & Slot hpd200405<-sqldf('select distinct a.WeatherStationID, a.YearMonthDay, a.TimeSlot, avg(a.HourlyPrecip) as AvgPrecip from hpd200405 a group by a.WeatherStationID, a.YearMonthDay, a.TimeSlot') # Merging with close station data closestation <- readRDS("closestation.rds") hpd0405<-merge(hpd200405,closestation,by.x="WeatherStationID",by.y="WeatherStationID") # Creating Keys for future merging hpd0405$Key0<-paste(hpd0405$WeatherStationID,hpd0405$YearMonthDay,hpd0405$TimeSlot) hpd0405$Key1<-paste(hpd0405$ClosestWS,hpd0405$YearMonthDay,hpd0405$TimeSlot) hpd0405$Key2<-paste(hpd0405$Closest2ndWS,hpd0405$YearMonthDay,hpd0405$TimeSlot) hpd0405$Key3<-paste(hpd0405$Closest3rdWS,hpd0405$YearMonthDay,hpd0405$TimeSlot) hpd0405$Key4<-paste(hpd0405$Closest4thWS,hpd0405$YearMonthDay,hpd0405$TimeSlot) hpd0405$Key5<-paste(hpd0405$Closest5thWS,hpd0405$YearMonthDay,hpd0405$TimeSlot) # Merging with Closest Weather Stations rm(hpd200405) # Free up memory temp<-hpd0405 names(hpd0405)[names(hpd0405) == "AvgPrecip"] = "OrigPrecip" hpd0405<-sqldf('select a.*, b.AvgPrecip from hpd0405 a left join (select Key0, AvgPrecip from temp) b on a.Key1=b.Key0') names(hpd0405)[names(hpd0405) == "AvgPrecip"] = "ClosestPrecip" gc() hpd0405<-sqldf('select a.*, b.AvgPrecip from hpd0405 a left join (select Key0, AvgPrecip from temp) b on a.Key2=b.Key0') names(hpd0405)[names(hpd0405) == "AvgPrecip"] = "Closest2ndPrecip" gc() hpd0405<-sqldf('select a.*, b.AvgPrecip from hpd0405 a left join (select Key0, AvgPrecip from temp) b on a.Key3=b.Key0') names(hpd0405)[names(hpd0405) == "AvgPrecip"] = "Closest3rdPrecip" gc() hpd0405<-sqldf('select a.*, b.AvgPrecip from hpd0405 a left join (select Key0, AvgPrecip from temp) b on a.Key4=b.Key0') names(hpd0405)[names(hpd0405) == "AvgPrecip"] = "Closest4thPrecip" gc() hpd0405<-sqldf('select a.*, b.AvgPrecip from hpd0405 a left join (select Key0, AvgPrecip from temp) b on a.Key5=b.Key0') names(hpd0405)[names(hpd0405) == "AvgPrecip"] = "Closest5thPrecip" gc() # Check for null values & impute using closest neighbours rm(temp) # Remove temp file rm(closestation) # Remove unrequired file colSums(is.na(hpd0405)) # NA values in OrigPrecip column hpd0405$OrigPrecip<-ifelse(is.na(hpd0405$OrigPrecip),rowMeans(hpd0405[,c("ClosestPrecip", "Closest2ndPrecip", "Closest3rdPrecip","Closest4thPrecip", "Closest5thPrecip")], na.rm=TRUE), hpd0405$OrigPrecip) saveRDS(hpd0405, file = "hpd0405.rds") # Saving externally
/Aircraft Delay Prediction/2_HourlyPrecipitation/Train/hpd05.R
no_license
kunalrayscorpio/DSProjects
R
false
false
4,680
r
rm(list=ls()) library(lubridate) library(sqldf) library(DMwR) hpd200405<- read.table("200405hpd.txt", sep=",",header = T, dec = ".") # Read 01 File # Changing Format as applicable hpd200405$YearMonthDay<-ymd(hpd200405$YearMonthDay) hpd200405$YearMonthDay<-as.factor(hpd200405$YearMonthDay) hpd200405$WeatherStationID<-as.factor(hpd200405$WeatherStationID) # Deriving time slots in weather data hpd200405$TimeSlot<-ifelse(hpd200405$Time<200,'Midnight to 2AM',ifelse(hpd200405$Time<400,'2AM to 4AM', ifelse(hpd200405$Time<600,'4AM to 6AM', ifelse(hpd200405$Time<800,'6AM to 8AM', ifelse(hpd200405$Time<1000,'8AM to 10AM', ifelse(hpd200405$Time<1200,'10AM to Noon', ifelse(hpd200405$Time<1400,'Noon to 2PM', ifelse(hpd200405$Time<1600,'2PM to 4PM', ifelse(hpd200405$Time<1800,'4PM to 6PM', ifelse(hpd200405$Time<2000,'6PM to 8PM', ifelse(hpd200405$Time<2200,'8PM to 10PM','10PM to Midnight'))))))))))) hpd200405$Time<-NULL # Dropping time column # Aggregating Hourly Precipitation by Station, Date & Slot hpd200405<-sqldf('select distinct a.WeatherStationID, a.YearMonthDay, a.TimeSlot, avg(a.HourlyPrecip) as AvgPrecip from hpd200405 a group by a.WeatherStationID, a.YearMonthDay, a.TimeSlot') # Merging with close station data closestation <- readRDS("closestation.rds") hpd0405<-merge(hpd200405,closestation,by.x="WeatherStationID",by.y="WeatherStationID") # Creating Keys for future merging hpd0405$Key0<-paste(hpd0405$WeatherStationID,hpd0405$YearMonthDay,hpd0405$TimeSlot) hpd0405$Key1<-paste(hpd0405$ClosestWS,hpd0405$YearMonthDay,hpd0405$TimeSlot) hpd0405$Key2<-paste(hpd0405$Closest2ndWS,hpd0405$YearMonthDay,hpd0405$TimeSlot) hpd0405$Key3<-paste(hpd0405$Closest3rdWS,hpd0405$YearMonthDay,hpd0405$TimeSlot) hpd0405$Key4<-paste(hpd0405$Closest4thWS,hpd0405$YearMonthDay,hpd0405$TimeSlot) hpd0405$Key5<-paste(hpd0405$Closest5thWS,hpd0405$YearMonthDay,hpd0405$TimeSlot) # Merging with Closest Weather Stations rm(hpd200405) # Free up memory temp<-hpd0405 names(hpd0405)[names(hpd0405) == "AvgPrecip"] = "OrigPrecip" hpd0405<-sqldf('select a.*, b.AvgPrecip from hpd0405 a left join (select Key0, AvgPrecip from temp) b on a.Key1=b.Key0') names(hpd0405)[names(hpd0405) == "AvgPrecip"] = "ClosestPrecip" gc() hpd0405<-sqldf('select a.*, b.AvgPrecip from hpd0405 a left join (select Key0, AvgPrecip from temp) b on a.Key2=b.Key0') names(hpd0405)[names(hpd0405) == "AvgPrecip"] = "Closest2ndPrecip" gc() hpd0405<-sqldf('select a.*, b.AvgPrecip from hpd0405 a left join (select Key0, AvgPrecip from temp) b on a.Key3=b.Key0') names(hpd0405)[names(hpd0405) == "AvgPrecip"] = "Closest3rdPrecip" gc() hpd0405<-sqldf('select a.*, b.AvgPrecip from hpd0405 a left join (select Key0, AvgPrecip from temp) b on a.Key4=b.Key0') names(hpd0405)[names(hpd0405) == "AvgPrecip"] = "Closest4thPrecip" gc() hpd0405<-sqldf('select a.*, b.AvgPrecip from hpd0405 a left join (select Key0, AvgPrecip from temp) b on a.Key5=b.Key0') names(hpd0405)[names(hpd0405) == "AvgPrecip"] = "Closest5thPrecip" gc() # Check for null values & impute using closest neighbours rm(temp) # Remove temp file rm(closestation) # Remove unrequired file colSums(is.na(hpd0405)) # NA values in OrigPrecip column hpd0405$OrigPrecip<-ifelse(is.na(hpd0405$OrigPrecip),rowMeans(hpd0405[,c("ClosestPrecip", "Closest2ndPrecip", "Closest3rdPrecip","Closest4thPrecip", "Closest5thPrecip")], na.rm=TRUE), hpd0405$OrigPrecip) saveRDS(hpd0405, file = "hpd0405.rds") # Saving externally
## set working directory #setwd("/media/ssdp1/Coursera/ExploratoryDataAnalysis-2014/data/") #One off commands to get data #download.file("https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip","./data/exdata_data_household_power_consumption.zip","curl") ##unzip data unzip("exdata_data_household_power_consumption.zip") ## install date libraries -- one off #install.packages("lubridate") ##load library library(lubridate) ##read data courseproj1 <- read.table("household_power_consumption.txt", header = TRUE, sep = ";", na.strings = "?", colClasses = c("character","character","numeric","numeric", "numeric","numeric","numeric","numeric") ) ## convert columns to date format courseproj1$Date <- as.Date(courseproj1$Date, format = "%d/%m/%Y") ## get subset of data to work with # Pull out relevant date range cp1subset <- courseproj1[ which( courseproj1$Date >= "2007-02-01" & courseproj1$Date <="2007-02-02"), ] ## original raw data nolonger required. rm(courseproj1) ##Explore ##summary(cp1subset) ## add new variable timestamp with cancat of date & time cp1subset$TimeStamp <- strptime(paste(cp1subset$Date, cp1subset$Time), format="%Y-%m-%d %H:%M:%S" ) # open PNG graphics device for plot-4 #png will be like empty canvas png(file="courseproject1-plot4.png", width = 480, height = 480, units = "px", bg="transparent") # draw plot4 as per requirement # 4 figures arranged in 2 rows and 2 columns par(mfrow=c(2,2)) ##plot 1st row & 1st column plot(cp1subset$TimeStamp , cp1subset$Global_active_power, type="n", col="black", xlab="", ylab = "Global Active Power") lines(cp1subset$TimeStamp , cp1subset$Global_active_power) ##plot 1st row & 2nd column plot(cp1subset$TimeStamp , cp1subset$Voltage, type="l", col="black", xlab="datetime", ylab = "Voltage", ylim=c(min(cp1subset$Voltage), max(cp1subset$Voltage)) ) ##plot 2nd row & 1st column plot(cp1subset$TimeStamp , cp1subset$Sub_metering_1, type="n", col="black", xlab="", ylab = "Energy sub metering") ##add lines lines(cp1subset$TimeStamp, cp1subset$Sub_metering_1, col="black") lines(cp1subset$TimeStamp, cp1subset$Sub_metering_2, col="red") lines(cp1subset$TimeStamp, cp1subset$Sub_metering_3, col="blue") ##add legend legend("topright", legend=c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), col=c("black","red","blue"), lty=1, bty ="n") ##plot 2nd row & 2nd column plot(cp1subset$TimeStamp , cp1subset$Global_reactive_power, type="l", col="black", xlab="datetime", ylab = "Global_reactive_power", ylim=c(min(cp1subset$Global_reactive_power), max(cp1subset$Global_reactive_power)) ) #close the device dev.off()
/plot4.R
no_license
allene/ExData_Plotting1
R
false
false
2,921
r
## set working directory #setwd("/media/ssdp1/Coursera/ExploratoryDataAnalysis-2014/data/") #One off commands to get data #download.file("https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip","./data/exdata_data_household_power_consumption.zip","curl") ##unzip data unzip("exdata_data_household_power_consumption.zip") ## install date libraries -- one off #install.packages("lubridate") ##load library library(lubridate) ##read data courseproj1 <- read.table("household_power_consumption.txt", header = TRUE, sep = ";", na.strings = "?", colClasses = c("character","character","numeric","numeric", "numeric","numeric","numeric","numeric") ) ## convert columns to date format courseproj1$Date <- as.Date(courseproj1$Date, format = "%d/%m/%Y") ## get subset of data to work with # Pull out relevant date range cp1subset <- courseproj1[ which( courseproj1$Date >= "2007-02-01" & courseproj1$Date <="2007-02-02"), ] ## original raw data nolonger required. rm(courseproj1) ##Explore ##summary(cp1subset) ## add new variable timestamp with cancat of date & time cp1subset$TimeStamp <- strptime(paste(cp1subset$Date, cp1subset$Time), format="%Y-%m-%d %H:%M:%S" ) # open PNG graphics device for plot-4 #png will be like empty canvas png(file="courseproject1-plot4.png", width = 480, height = 480, units = "px", bg="transparent") # draw plot4 as per requirement # 4 figures arranged in 2 rows and 2 columns par(mfrow=c(2,2)) ##plot 1st row & 1st column plot(cp1subset$TimeStamp , cp1subset$Global_active_power, type="n", col="black", xlab="", ylab = "Global Active Power") lines(cp1subset$TimeStamp , cp1subset$Global_active_power) ##plot 1st row & 2nd column plot(cp1subset$TimeStamp , cp1subset$Voltage, type="l", col="black", xlab="datetime", ylab = "Voltage", ylim=c(min(cp1subset$Voltage), max(cp1subset$Voltage)) ) ##plot 2nd row & 1st column plot(cp1subset$TimeStamp , cp1subset$Sub_metering_1, type="n", col="black", xlab="", ylab = "Energy sub metering") ##add lines lines(cp1subset$TimeStamp, cp1subset$Sub_metering_1, col="black") lines(cp1subset$TimeStamp, cp1subset$Sub_metering_2, col="red") lines(cp1subset$TimeStamp, cp1subset$Sub_metering_3, col="blue") ##add legend legend("topright", legend=c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), col=c("black","red","blue"), lty=1, bty ="n") ##plot 2nd row & 2nd column plot(cp1subset$TimeStamp , cp1subset$Global_reactive_power, type="l", col="black", xlab="datetime", ylab = "Global_reactive_power", ylim=c(min(cp1subset$Global_reactive_power), max(cp1subset$Global_reactive_power)) ) #close the device dev.off()
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/daily_stat.R \name{daily_stat_page} \alias{daily_stat_page} \alias{no2_daily_max} \alias{o3_daily_max} \alias{pm_daily_avg} \alias{so2_daily_max} \title{Cacluate daily maxima or averages for different sensor readings.} \usage{ o3_daily_max(data, dt = "date_time", val = "rolling8", by = NULL, exclude_df = NULL, exclude_df_dt = NULL) no2_daily_max(data, dt = "date_time", val = "value", by = NULL, exclude_df = NULL, exclude_df_dt = NULL) so2_daily_max(data, dt = "date_time", val = "value", by = NULL, exclude_df = NULL, exclude_df_dt = NULL) pm_daily_avg(data, dt = "date_time", val = "value", by = NULL, exclude_df = NULL, exclude_df_dt = NULL) } \arguments{ \item{data}{data frame with date and value} \item{dt}{the name (as a character string) of the date-time column. Default \code{"date_time"}} \item{val}{the name (as a character string) of the PM2.5 value column. Default \code{"value"}} \item{by}{character vector of grouping variables in data, probably an id if using multiple sites. Even if not using multiple sites, you shoud specfify the id column so that it is retained in the output.} \item{exclude_df}{a data.frame specifying which date ranges and sites to exclude. The data.frame must have to one date column if specific dates or date-times are to be excluded, and exactly two date or date-time columns if a date range is needed. must have all the columns of by provided,} \item{exclude_df_dt}{specifies the one (or two) date columns to be use in the exclude_df data.frame.} } \value{ data frame with the daily averages, can be input into } \description{ Cacluate daily maxima or averages for different sensor readings. }
/man/daily_stat_page.Rd
permissive
paulroberts68/rcaaqs
R
false
true
1,736
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/daily_stat.R \name{daily_stat_page} \alias{daily_stat_page} \alias{no2_daily_max} \alias{o3_daily_max} \alias{pm_daily_avg} \alias{so2_daily_max} \title{Cacluate daily maxima or averages for different sensor readings.} \usage{ o3_daily_max(data, dt = "date_time", val = "rolling8", by = NULL, exclude_df = NULL, exclude_df_dt = NULL) no2_daily_max(data, dt = "date_time", val = "value", by = NULL, exclude_df = NULL, exclude_df_dt = NULL) so2_daily_max(data, dt = "date_time", val = "value", by = NULL, exclude_df = NULL, exclude_df_dt = NULL) pm_daily_avg(data, dt = "date_time", val = "value", by = NULL, exclude_df = NULL, exclude_df_dt = NULL) } \arguments{ \item{data}{data frame with date and value} \item{dt}{the name (as a character string) of the date-time column. Default \code{"date_time"}} \item{val}{the name (as a character string) of the PM2.5 value column. Default \code{"value"}} \item{by}{character vector of grouping variables in data, probably an id if using multiple sites. Even if not using multiple sites, you shoud specfify the id column so that it is retained in the output.} \item{exclude_df}{a data.frame specifying which date ranges and sites to exclude. The data.frame must have to one date column if specific dates or date-times are to be excluded, and exactly two date or date-time columns if a date range is needed. must have all the columns of by provided,} \item{exclude_df_dt}{specifies the one (or two) date columns to be use in the exclude_df data.frame.} } \value{ data frame with the daily averages, can be input into } \description{ Cacluate daily maxima or averages for different sensor readings. }
N <- 1000 Mu <- c(0, 5, 2) Sigma <- cbind( c(25, -1, 7), c(-1, 4, -4), c(7, -4, 10) ) library('MASS') X <- mvrnorm(n = 1000, mu = Mu, Sigma = Sigma) # install.packages('rgl') library('rgl') plot3d(X) ev <- eigen(Sigma) eigenvalues <- ev$values eigenvectors <- ev$vectors PCA <- prcomp(X) PCA.PC1 <- PCA$x[,1] PCA.slope1 <- PCA$rotation[2,1] / PCA$rotation[1,1] PCA.PC2 <- PCA$x[,2] PCA.slope2 <- PCA$rotation[2,2] / PCA$rotation[1,2] PCA.PC3 <- PCA$x[,3] PCA.slope3 <- PCA$rotation[2,3] / PCA$rotation[1,3] plot(x = PCA.PC1, xlab = "PC1", y = PCA.PC2, ylab = "PC2") plot(x = PCA.PC1, xlab = "PC1", y = PCA.PC3, ylab = "PC3") plot(x = PCA.PC2, xlab = "PC2", y = PCA.PC3, ylab = "PC3")
/Problemes/P2-3/p3.R
no_license
josepdecid/APA-FIB
R
false
false
697
r
N <- 1000 Mu <- c(0, 5, 2) Sigma <- cbind( c(25, -1, 7), c(-1, 4, -4), c(7, -4, 10) ) library('MASS') X <- mvrnorm(n = 1000, mu = Mu, Sigma = Sigma) # install.packages('rgl') library('rgl') plot3d(X) ev <- eigen(Sigma) eigenvalues <- ev$values eigenvectors <- ev$vectors PCA <- prcomp(X) PCA.PC1 <- PCA$x[,1] PCA.slope1 <- PCA$rotation[2,1] / PCA$rotation[1,1] PCA.PC2 <- PCA$x[,2] PCA.slope2 <- PCA$rotation[2,2] / PCA$rotation[1,2] PCA.PC3 <- PCA$x[,3] PCA.slope3 <- PCA$rotation[2,3] / PCA$rotation[1,3] plot(x = PCA.PC1, xlab = "PC1", y = PCA.PC2, ylab = "PC2") plot(x = PCA.PC1, xlab = "PC1", y = PCA.PC3, ylab = "PC3") plot(x = PCA.PC2, xlab = "PC2", y = PCA.PC3, ylab = "PC3")
rit_to_efl <- read.csv('./data-raw/rit_to_efl.csv', stringsAsFactors = FALSE, na.strings = '') # data cleaning ----------------------------------------------------------- library(dplyr) rit_to_efl <- rit_to_efl %>% filter(!is.na(rit)) %>% select(rit, tabe_reading:nrs_efl) %>% arrange(rit, tabe_reading) # Remove duplicate values of RIT rit_to_efl <- rit_to_efl[!duplicated(rit_to_efl$rit, fromLast = TRUE), ] # Add rows for low values of RIT that are not in the original dataset rit <- 150:175 tabe_reading <- rep(NA, 26) lexile <- rep(NA, 26) nrs_efl <- rep(1, 26) temp <- data.frame(rit, tabe_reading, lexile, nrs_efl) rit_to_efl <- rbind(temp, rit_to_efl) ## TO DO: # Deal with duplicate rit value of 188 devtools::use_data(rit_to_efl, overwrite = TRUE)
/data-raw/rit_to_efl.R
no_license
thelayc/laycca
R
false
false
773
r
rit_to_efl <- read.csv('./data-raw/rit_to_efl.csv', stringsAsFactors = FALSE, na.strings = '') # data cleaning ----------------------------------------------------------- library(dplyr) rit_to_efl <- rit_to_efl %>% filter(!is.na(rit)) %>% select(rit, tabe_reading:nrs_efl) %>% arrange(rit, tabe_reading) # Remove duplicate values of RIT rit_to_efl <- rit_to_efl[!duplicated(rit_to_efl$rit, fromLast = TRUE), ] # Add rows for low values of RIT that are not in the original dataset rit <- 150:175 tabe_reading <- rep(NA, 26) lexile <- rep(NA, 26) nrs_efl <- rep(1, 26) temp <- data.frame(rit, tabe_reading, lexile, nrs_efl) rit_to_efl <- rbind(temp, rit_to_efl) ## TO DO: # Deal with duplicate rit value of 188 devtools::use_data(rit_to_efl, overwrite = TRUE)
#Editing names names(theDF) <- c("popularity", "team strength", "sport") View(theDF) #summary of referrencing data from elements theDF[2,3] theDF[c(1,3)] theDF[3] theDF$sport theDF["sport"] theDF$"Team strength" View(theDF)
/Assignment02b.R
no_license
JohnDanforth/Assignment02b.R
R
false
false
225
r
#Editing names names(theDF) <- c("popularity", "team strength", "sport") View(theDF) #summary of referrencing data from elements theDF[2,3] theDF[c(1,3)] theDF[3] theDF$sport theDF["sport"] theDF$"Team strength" View(theDF)
# load the library library(caret) library(doParallel) set.seed(1) t <- proc.time() cl <- makeCluster(detectCores()-1) registerDoParallel(cl) # Prepare train data digits_csv <- read.csv("./digits.csv", head = FALSE) train_data <- digits_csv[,-65] train_labels <- as.factor(digits_csv[, 65]) # Prepare test data test_csv <- read.csv("./test.csv", head = FALSE) test_data <- test_csv[, -65] test_labels <- as.factor(test_csv[, 65]) fitControl <- trainControl(method = "cv", number = 10) partGrid <- expand.grid(cp = (1:9)*0.001) # Train the model model <- train(train_data, train_labels, trControl = fitControl, tuneGrid = partGrid, method = "rpart") print.train(model) plot.train(model) plot(model$finalModel) text(model$finalModel) # Predict values predictions <- predict(model, test_data) # print results output <- data.frame(PREDICT=predictions, LABEL=test_labels, HIT=predictions==test_labels) head(output) # summarize results res <- confusionMatrix(predictions, test_labels) res res$overall["Accuracy"] proc.time()-t # Other result model$results max(model$results$Accuracy)
/week_4-5/algorithms-10-fold-tune/rpart.R
no_license
el-sorral/BigData-Masteam-UPC
R
false
false
1,184
r
# load the library library(caret) library(doParallel) set.seed(1) t <- proc.time() cl <- makeCluster(detectCores()-1) registerDoParallel(cl) # Prepare train data digits_csv <- read.csv("./digits.csv", head = FALSE) train_data <- digits_csv[,-65] train_labels <- as.factor(digits_csv[, 65]) # Prepare test data test_csv <- read.csv("./test.csv", head = FALSE) test_data <- test_csv[, -65] test_labels <- as.factor(test_csv[, 65]) fitControl <- trainControl(method = "cv", number = 10) partGrid <- expand.grid(cp = (1:9)*0.001) # Train the model model <- train(train_data, train_labels, trControl = fitControl, tuneGrid = partGrid, method = "rpart") print.train(model) plot.train(model) plot(model$finalModel) text(model$finalModel) # Predict values predictions <- predict(model, test_data) # print results output <- data.frame(PREDICT=predictions, LABEL=test_labels, HIT=predictions==test_labels) head(output) # summarize results res <- confusionMatrix(predictions, test_labels) res res$overall["Accuracy"] proc.time()-t # Other result model$results max(model$results$Accuracy)
library(glmnet) mydata = read.table("../../../../TrainingSet/FullSet/Lasso/lymphoid.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.04,family="gaussian",standardize=FALSE) sink('./lymphoid_020.txt',append=TRUE) print(glm$glmnet.fit) sink()
/Model/EN/Lasso/lymphoid/lymphoid_020.R
no_license
esbgkannan/QSMART
R
false
false
349
r
library(glmnet) mydata = read.table("../../../../TrainingSet/FullSet/Lasso/lymphoid.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.04,family="gaussian",standardize=FALSE) sink('./lymphoid_020.txt',append=TRUE) print(glm$glmnet.fit) sink()
library(ggplot2) library(dplyr) # data("diamonds") # while(TRUE){ # temp=sample_frac(diamonds,0.1) # write.csv(temp, paste0("sampled", gsub("[^0-9]","",Sys.time()),".csv"), # row.names = FALSE) # Sys.sleep(2) # Suspend execution of R expressions. The time interval to suspend execution for, in seconds. # } # stream_tweets( # timeout = (60 * 5), # parse = FALSE, # file_name = "tweets1" # )
/03-SNA/tesstream/global.R
permissive
eppofahmi/belajaR
R
false
false
417
r
library(ggplot2) library(dplyr) # data("diamonds") # while(TRUE){ # temp=sample_frac(diamonds,0.1) # write.csv(temp, paste0("sampled", gsub("[^0-9]","",Sys.time()),".csv"), # row.names = FALSE) # Sys.sleep(2) # Suspend execution of R expressions. The time interval to suspend execution for, in seconds. # } # stream_tweets( # timeout = (60 * 5), # parse = FALSE, # file_name = "tweets1" # )
##################### # load libraries # set wd # clear global .envir ##################### # remove objects rm(list=ls()) # detach all libraries detachAllPackages <- function() { basic.packages <- c("package:stats", "package:graphics", "package:grDevices", "package:utils", "package:datasets", "package:methods", "package:base") package.list <- search()[ifelse(unlist(gregexpr("package:", search()))==1, TRUE, FALSE)] package.list <- setdiff(package.list, basic.packages) if (length(package.list)>0) for (package in package.list) detach(package, character.only=TRUE) } detachAllPackages() # load libraries pkgTest <- function(pkg){ new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])] if (length(new.pkg)) install.packages(new.pkg, dependencies = TRUE) sapply(pkg, require, character.only = TRUE) } # here is where you load any necessary packages install.packages("car") library(car) data(Prestige) help(Prestige) # set working directory setwd("~/Documents/GitHub/QTM200Spring2020/problem_sets/PS4/Answer") ##################### # Problem 1 ##################### #(a) Create a new variable professional by recoding the variable type so that professionals #are coded as 1, and blue and white collar workers are coded as 0 (Hint: ifelse.) #Check the levels of the variable levels(Prestige$type) #Store the edited varaible into a newe variable called "Prof" Prof <- ifelse(Prestige$type=="prof",1,0) str(Prof) #(b) Run a linear model with prestige as an outcome and income, professional, and the #interaction of the two as predictors (Note: this is a continuous x dummy interaction.) lm(prestige~income+Prof+income:Prof, data=Prestige) #(c) Write the prediction equation based on the result. #Yi= 21.14 + 0.003*X1(income) + 37.78*X2(Prof) - 0.002*D(income:Prof) #(d) Interpret the coefficient for income. #The coefficient is a positive number, indicating that there is a positive relationship between income and prestige. # The coefficient of income is 0.003, which means, controlling other variables, a unit increase in average income will result in 0.3% increase in the score of prestige. #(e) Interpret the coefficient for professional. #The coefficient is a positive number, indicating that there is a positive relationship between professional and prestige. #The coefficient of professional is 37.78, which means, controlling income, a unit increase in type of occupation (i.e, from blue and white collar to professionals) will result in 3778% increase in the score of prestige. #(f) Recall the prediction equation: Yi= 21.14 + 0.003*X1(income) + 37.78*X2(Prof) - 0.002*D(income:Prof) #Since we are interestd in the effect of income on profeessional occupations, D(income:Prof) should equal to 1. #So we get Yi= 21.14 + 0.003*X1(income) + 37.78*1 - 0.002*1*income = 58.92 + 0.001*income, where 0.001*income is the marginal effect. #When income equals to 1000, the marginal effect would be 0.001*1000 = 1. #Therefore, the effect of a 1000 increase in incomee will lead to 1 prestige score increase for professional occupations. #(g) What is the effect of changing one's occupations from non-professional to professional #when her income is $6,000? We are interested in the marginal effect of professional #jobs when the variable income takes the value of 6, 000. Calculate the change in ^y based on your answer for (c). #Recall the prediction equation: Yi= 21.14 + 0.003*X1(income) + 37.78*X2(Prof) - 0.002*D(income:Prof) #When income equals to 6000, the prediction equation would be Yi= 21.14 + 0.003*6000 + 37.78*X2(Prof) - 0.002*6000*Prof = 39.14 + 25.78*Prof #When one's occupation is non-professional, prof = 0, Yi =39.14. #When onee's occupation is professional, prof = 1, Yi = 64.92. #The difference between the two equations is 25.78, which means th effect of changing one's occupations from non-professional to professional, given her income is 6000, is 25.78 unit increase in the prestige score. #A #Hypothesis: Ho:Beta2 = 0 vs. Ha:Beta2 is not 0. #Test statistic: t=(0.042-0)/0.016=2.625 #p-value: #df= n-3 parameters = 131-3 = 128 2*pt(2.625, 128, lower.tail = F) #p-value = 0.0097 #p-value is 0.0097, which is smaller than the confidence lvel 0.05. #We have enough evidence to reject the null hypothesis that there is no relationship between the lawn signs and the vote share. #In other words, we can say that having these yard signs does affect the vote share. #B #Hypothesis: Ho:Beta3 = 0 vs. Ha:Beta3 is not 0. #Test statistic: t=(0.042-0)/0.013=3.230 #p-value: #df= n-3 = 131-3 = 128 2*pt(3.23, 128, lower.tail = F) #p-value = 0.0016 #p-value is 0.0016, which is smaller than the confidence lvel 0.05. #We have enough evidence to reject the null hypothesis that there is no relationship between living next to lawn signs and the vote share. #In other words, we can say that adjacent to these yard signs does affect the vote share. #C #The coefficient of the constant equals to 0.302, which means when there is no lawn sign either in or near the precinct, #the average proportion of the vote that went to Ken Cuccinelli is 30.2%. #D #The model does not work good enough to find out the influential factors that affect the vote share. #As we can learn from the value of R square, which is 0.094 in this case, only 9.4% of variation is explained by this model. #90.6% of variation cannot be explained by having lawn signs or not. So there should be other explanotary variables that have significant impact on the vote hare but is not included in this model. #And these omitted variables might have greater explanotary power than yard signs.
/problem_sets/PS4/Answer/PS4_Answer.R
no_license
Yumeng-Xu/QTM200Spring2020
R
false
false
5,613
r
##################### # load libraries # set wd # clear global .envir ##################### # remove objects rm(list=ls()) # detach all libraries detachAllPackages <- function() { basic.packages <- c("package:stats", "package:graphics", "package:grDevices", "package:utils", "package:datasets", "package:methods", "package:base") package.list <- search()[ifelse(unlist(gregexpr("package:", search()))==1, TRUE, FALSE)] package.list <- setdiff(package.list, basic.packages) if (length(package.list)>0) for (package in package.list) detach(package, character.only=TRUE) } detachAllPackages() # load libraries pkgTest <- function(pkg){ new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])] if (length(new.pkg)) install.packages(new.pkg, dependencies = TRUE) sapply(pkg, require, character.only = TRUE) } # here is where you load any necessary packages install.packages("car") library(car) data(Prestige) help(Prestige) # set working directory setwd("~/Documents/GitHub/QTM200Spring2020/problem_sets/PS4/Answer") ##################### # Problem 1 ##################### #(a) Create a new variable professional by recoding the variable type so that professionals #are coded as 1, and blue and white collar workers are coded as 0 (Hint: ifelse.) #Check the levels of the variable levels(Prestige$type) #Store the edited varaible into a newe variable called "Prof" Prof <- ifelse(Prestige$type=="prof",1,0) str(Prof) #(b) Run a linear model with prestige as an outcome and income, professional, and the #interaction of the two as predictors (Note: this is a continuous x dummy interaction.) lm(prestige~income+Prof+income:Prof, data=Prestige) #(c) Write the prediction equation based on the result. #Yi= 21.14 + 0.003*X1(income) + 37.78*X2(Prof) - 0.002*D(income:Prof) #(d) Interpret the coefficient for income. #The coefficient is a positive number, indicating that there is a positive relationship between income and prestige. # The coefficient of income is 0.003, which means, controlling other variables, a unit increase in average income will result in 0.3% increase in the score of prestige. #(e) Interpret the coefficient for professional. #The coefficient is a positive number, indicating that there is a positive relationship between professional and prestige. #The coefficient of professional is 37.78, which means, controlling income, a unit increase in type of occupation (i.e, from blue and white collar to professionals) will result in 3778% increase in the score of prestige. #(f) Recall the prediction equation: Yi= 21.14 + 0.003*X1(income) + 37.78*X2(Prof) - 0.002*D(income:Prof) #Since we are interestd in the effect of income on profeessional occupations, D(income:Prof) should equal to 1. #So we get Yi= 21.14 + 0.003*X1(income) + 37.78*1 - 0.002*1*income = 58.92 + 0.001*income, where 0.001*income is the marginal effect. #When income equals to 1000, the marginal effect would be 0.001*1000 = 1. #Therefore, the effect of a 1000 increase in incomee will lead to 1 prestige score increase for professional occupations. #(g) What is the effect of changing one's occupations from non-professional to professional #when her income is $6,000? We are interested in the marginal effect of professional #jobs when the variable income takes the value of 6, 000. Calculate the change in ^y based on your answer for (c). #Recall the prediction equation: Yi= 21.14 + 0.003*X1(income) + 37.78*X2(Prof) - 0.002*D(income:Prof) #When income equals to 6000, the prediction equation would be Yi= 21.14 + 0.003*6000 + 37.78*X2(Prof) - 0.002*6000*Prof = 39.14 + 25.78*Prof #When one's occupation is non-professional, prof = 0, Yi =39.14. #When onee's occupation is professional, prof = 1, Yi = 64.92. #The difference between the two equations is 25.78, which means th effect of changing one's occupations from non-professional to professional, given her income is 6000, is 25.78 unit increase in the prestige score. #A #Hypothesis: Ho:Beta2 = 0 vs. Ha:Beta2 is not 0. #Test statistic: t=(0.042-0)/0.016=2.625 #p-value: #df= n-3 parameters = 131-3 = 128 2*pt(2.625, 128, lower.tail = F) #p-value = 0.0097 #p-value is 0.0097, which is smaller than the confidence lvel 0.05. #We have enough evidence to reject the null hypothesis that there is no relationship between the lawn signs and the vote share. #In other words, we can say that having these yard signs does affect the vote share. #B #Hypothesis: Ho:Beta3 = 0 vs. Ha:Beta3 is not 0. #Test statistic: t=(0.042-0)/0.013=3.230 #p-value: #df= n-3 = 131-3 = 128 2*pt(3.23, 128, lower.tail = F) #p-value = 0.0016 #p-value is 0.0016, which is smaller than the confidence lvel 0.05. #We have enough evidence to reject the null hypothesis that there is no relationship between living next to lawn signs and the vote share. #In other words, we can say that adjacent to these yard signs does affect the vote share. #C #The coefficient of the constant equals to 0.302, which means when there is no lawn sign either in or near the precinct, #the average proportion of the vote that went to Ken Cuccinelli is 30.2%. #D #The model does not work good enough to find out the influential factors that affect the vote share. #As we can learn from the value of R square, which is 0.094 in this case, only 9.4% of variation is explained by this model. #90.6% of variation cannot be explained by having lawn signs or not. So there should be other explanotary variables that have significant impact on the vote hare but is not included in this model. #And these omitted variables might have greater explanotary power than yard signs.
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/plot_res.R, R/res.plot.R \name{res.plot} \alias{res.plot} \title{Plotting the results} \usage{ res.plot( res.tcG = NULL, res.extGP = NULL, y, ym = 0, step = 0, zoom = range(y, na.rm = TRUE), select = NULL, choice = c("dens", "qqplot"), legend = TRUE, ... ) res.plot( res.tcG = NULL, res.extGP = NULL, y, ym = 0, step = 0, zoom = range(y, na.rm = TRUE), select = NULL, choice = c("dens", "qqplot"), legend = TRUE, ... ) } \arguments{ \item{res.tcG, res.extGP}{a list resulting respectively from \code{fit.tcG} and \code{fit.extGP}, at least one of them must be non-null} \item{y}{vector of data (if both \code{res.tcG} and \code{res.extGP} are given, \code{y} must include the zeros)} \item{ym}{minimal value that can be observed} \item{step}{discretization step} \item{zoom}{vector of length 2, range to zoom on} \item{select}{for \code{res.tcG}, a the model(s) that should be plotted. A subset of \code{c('gp', 'power', 'power-exp', 'quadratic-power')}} \item{choice}{A subset of \code{c('qqplot', 'dens')}. Which plots should be drawn?} \item{legend}{boolean, should there be a legend?} \item{...}{graphical parameters such as \code{main}, \code{cex}, etc.} } \description{ This function offers choices for plotting results of \code{fit.tcG} and \code{fit.extGP}. Two types of plots are available: a density plot (histogram or barplot) and a QQ plot. In particular the function allows plotting the results of both fit functions together on the QQ plot. This function offers choices for plotting results of \code{fit.tcG} and \code{fit.extGP}. Two types of plots are available: a density plot (histogram or barplot) and a QQ plot. In particular the function allows plotting the results of both fit functions together on the QQ plot. } \examples{ \dontrun{ # Comparing meta-Gaussian models data(rain, package = "ismev") res=tcG.fit(rain, name=c("power", "gp"), init=list("power"=c(0,2,2), "gp"=c(0,2,0.5,0.5)), ym=0.3, step=0.1, R=50, plots=FALSE) res.plot(res.tcG=res, y=rain, ym=.3, step=.1, zoom=c(0,30), choice="qqplot") # Comparing the GP meta-Gaussian and the extended GP res2=extGP.fit(rain[rain>0], c(2,.5,.5), ym=.3, step=.1, R=50, plots=FALSE) res.plot(res.tcG=res, res.extGP=res2, y=rain, ym=.3, step=.1, select="gp", choice="qqplot") } \dontrun{ # Comparing meta-Gaussian models data(rain, package = "ismev") res=tcG.fit(rain, name=c("power", "gp"), init=list("power"=c(0,2,2), "gp"=c(0,2,0.5,0.5)), ym=0.3, step=0.1, R=50, plots=FALSE) res.plot(res.tcG=res, y=rain, ym=.3, step=.1, zoom=c(0,30), choice="qqplot") # Comparing the GP meta-Gaussian and the extended GP res2=extGP.fit(rain[rain>0], c(2,.5,.5), ym=.3, step=.1, R=50, plots=FALSE) res.plot(res.tcG=res, res.extGP=res2, y=rain, ym=.3, step=.1, select="gp", choice="qqplot") } }
/man/res.plot.Rd
permissive
mbtgy/tcG
R
false
true
2,939
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/plot_res.R, R/res.plot.R \name{res.plot} \alias{res.plot} \title{Plotting the results} \usage{ res.plot( res.tcG = NULL, res.extGP = NULL, y, ym = 0, step = 0, zoom = range(y, na.rm = TRUE), select = NULL, choice = c("dens", "qqplot"), legend = TRUE, ... ) res.plot( res.tcG = NULL, res.extGP = NULL, y, ym = 0, step = 0, zoom = range(y, na.rm = TRUE), select = NULL, choice = c("dens", "qqplot"), legend = TRUE, ... ) } \arguments{ \item{res.tcG, res.extGP}{a list resulting respectively from \code{fit.tcG} and \code{fit.extGP}, at least one of them must be non-null} \item{y}{vector of data (if both \code{res.tcG} and \code{res.extGP} are given, \code{y} must include the zeros)} \item{ym}{minimal value that can be observed} \item{step}{discretization step} \item{zoom}{vector of length 2, range to zoom on} \item{select}{for \code{res.tcG}, a the model(s) that should be plotted. A subset of \code{c('gp', 'power', 'power-exp', 'quadratic-power')}} \item{choice}{A subset of \code{c('qqplot', 'dens')}. Which plots should be drawn?} \item{legend}{boolean, should there be a legend?} \item{...}{graphical parameters such as \code{main}, \code{cex}, etc.} } \description{ This function offers choices for plotting results of \code{fit.tcG} and \code{fit.extGP}. Two types of plots are available: a density plot (histogram or barplot) and a QQ plot. In particular the function allows plotting the results of both fit functions together on the QQ plot. This function offers choices for plotting results of \code{fit.tcG} and \code{fit.extGP}. Two types of plots are available: a density plot (histogram or barplot) and a QQ plot. In particular the function allows plotting the results of both fit functions together on the QQ plot. } \examples{ \dontrun{ # Comparing meta-Gaussian models data(rain, package = "ismev") res=tcG.fit(rain, name=c("power", "gp"), init=list("power"=c(0,2,2), "gp"=c(0,2,0.5,0.5)), ym=0.3, step=0.1, R=50, plots=FALSE) res.plot(res.tcG=res, y=rain, ym=.3, step=.1, zoom=c(0,30), choice="qqplot") # Comparing the GP meta-Gaussian and the extended GP res2=extGP.fit(rain[rain>0], c(2,.5,.5), ym=.3, step=.1, R=50, plots=FALSE) res.plot(res.tcG=res, res.extGP=res2, y=rain, ym=.3, step=.1, select="gp", choice="qqplot") } \dontrun{ # Comparing meta-Gaussian models data(rain, package = "ismev") res=tcG.fit(rain, name=c("power", "gp"), init=list("power"=c(0,2,2), "gp"=c(0,2,0.5,0.5)), ym=0.3, step=0.1, R=50, plots=FALSE) res.plot(res.tcG=res, y=rain, ym=.3, step=.1, zoom=c(0,30), choice="qqplot") # Comparing the GP meta-Gaussian and the extended GP res2=extGP.fit(rain[rain>0], c(2,.5,.5), ym=.3, step=.1, R=50, plots=FALSE) res.plot(res.tcG=res, res.extGP=res2, y=rain, ym=.3, step=.1, select="gp", choice="qqplot") } }
#set working directory setwd("/Users/theochristian/Dropbox/Coursera/exploratory_data_analysis/Assignment1/ExData_Plotting1") # load req libraries library(data.table) library(lubridate) # read in data for period 1/2/2007 - 2/2/2007 from source text file variable.class<-c(rep('character',2),rep('numeric',7)) power.consumption<-read.table('household_power_consumption.txt',header=TRUE, sep=';',na.strings='?',colClasses=variable.class) power.consumption<-power.consumption[power.consumption$Date=='1/2/2007' | power.consumption$Date=='2/2/2007',] # clean data cols<-c('Date','Time','GlobalActivePower','GlobalReactivePower','Voltage','GlobalIntensity', 'SubMetering1','SubMetering2','SubMetering3') colnames(power.consumption)<-cols power.consumption$DateTime<-dmy(power.consumption$Date)+hms(power.consumption$Time) power.consumption<-power.consumption[,c(10,3:9)] # write cleaned data to file new_power_consumption.txt write.table(power.consumption,file='new_power_consumption.txt',sep=';',row.names=FALSE) dir.create('plot 4') # create .png png(filename='plot 4/plot4.png',width=480,height=480,units='px') # generate 4 quardrant par(mfrow=c(2,2)) # Generate top left quardrant plot(power.consumption$DateTime,power.consumption$GlobalActivePower,ylab='Global Active Power',xlab='',type='l') # Generate top right quardrant plot(power.consumption$DateTime,power.consumption$Voltage,xlab='datetime',ylab='Voltage',type='l') # Generate bottom left quardrant lncol<-c('black','red','blue') lbls<-c('Sub_metering_1','Sub_metering_2','Sub_metering_3') plot(power.consumption$DateTime,power.consumption$SubMetering1,type='l',col=lncol[1],xlab='',ylab='Energy sub metering') lines(power.consumption$DateTime,power.consumption$SubMetering2,col=lncol[2]) lines(power.consumption$DateTime,power.consumption$SubMetering3,col=lncol[3]) legend('topright',legend=lbls,col=lncol,lty='solid') # Generate bottom right quardrant plot(power.consumption$DateTime,power.consumption$GlobalReactivePower,xlab='datetime',ylab='Global_reactive_power',type='l') # Close off graphic device x<-dev.off()
/plot4.R
no_license
tgjc/ExData_Plotting1
R
false
false
2,123
r
#set working directory setwd("/Users/theochristian/Dropbox/Coursera/exploratory_data_analysis/Assignment1/ExData_Plotting1") # load req libraries library(data.table) library(lubridate) # read in data for period 1/2/2007 - 2/2/2007 from source text file variable.class<-c(rep('character',2),rep('numeric',7)) power.consumption<-read.table('household_power_consumption.txt',header=TRUE, sep=';',na.strings='?',colClasses=variable.class) power.consumption<-power.consumption[power.consumption$Date=='1/2/2007' | power.consumption$Date=='2/2/2007',] # clean data cols<-c('Date','Time','GlobalActivePower','GlobalReactivePower','Voltage','GlobalIntensity', 'SubMetering1','SubMetering2','SubMetering3') colnames(power.consumption)<-cols power.consumption$DateTime<-dmy(power.consumption$Date)+hms(power.consumption$Time) power.consumption<-power.consumption[,c(10,3:9)] # write cleaned data to file new_power_consumption.txt write.table(power.consumption,file='new_power_consumption.txt',sep=';',row.names=FALSE) dir.create('plot 4') # create .png png(filename='plot 4/plot4.png',width=480,height=480,units='px') # generate 4 quardrant par(mfrow=c(2,2)) # Generate top left quardrant plot(power.consumption$DateTime,power.consumption$GlobalActivePower,ylab='Global Active Power',xlab='',type='l') # Generate top right quardrant plot(power.consumption$DateTime,power.consumption$Voltage,xlab='datetime',ylab='Voltage',type='l') # Generate bottom left quardrant lncol<-c('black','red','blue') lbls<-c('Sub_metering_1','Sub_metering_2','Sub_metering_3') plot(power.consumption$DateTime,power.consumption$SubMetering1,type='l',col=lncol[1],xlab='',ylab='Energy sub metering') lines(power.consumption$DateTime,power.consumption$SubMetering2,col=lncol[2]) lines(power.consumption$DateTime,power.consumption$SubMetering3,col=lncol[3]) legend('topright',legend=lbls,col=lncol,lty='solid') # Generate bottom right quardrant plot(power.consumption$DateTime,power.consumption$GlobalReactivePower,xlab='datetime',ylab='Global_reactive_power',type='l') # Close off graphic device x<-dev.off()
# # This is the server logic of a Shiny web application. You can run the # application by clicking 'Run App' above. # # Find out more about building applications with Shiny here: # # http://shiny.rstudio.com/ # library(shiny) library(plotly) load("covidcases.Rda") # Define server logic required to draw a histogram shinyServer(function(input, output) { myFinalData <- reactive({ cat(file=stderr(),input$timeRange[2]) # Get data rows for selected year covidcases %>% dplyr::filter(geoId %in% input$countries) %>% dplyr::filter(time >= as.Date(input$timeRange[1])) %>% dplyr::filter(time <= as.Date(input$timeRange[2])) # }) output$slidervalue <- reactive({ input$timeRange[1] }) output$mygraph <- renderPlotly({ plot_ly(myFinalData(),x = ~time,y = ~cases,color = ~geoId, mode="lines") }) # preparing data for cumultative sum plot sumdata<- reactive({ aggregate(myFinalData()$cases,by = list(Country = myFinalData()$geoId), FUN = sum) %>% rename(`sum of cases` = x) }) output$cumsum <- renderTable({ sumdata() }) })
/server.R
no_license
Aniaw81/COVID19shiny
R
false
false
1,253
r
# # This is the server logic of a Shiny web application. You can run the # application by clicking 'Run App' above. # # Find out more about building applications with Shiny here: # # http://shiny.rstudio.com/ # library(shiny) library(plotly) load("covidcases.Rda") # Define server logic required to draw a histogram shinyServer(function(input, output) { myFinalData <- reactive({ cat(file=stderr(),input$timeRange[2]) # Get data rows for selected year covidcases %>% dplyr::filter(geoId %in% input$countries) %>% dplyr::filter(time >= as.Date(input$timeRange[1])) %>% dplyr::filter(time <= as.Date(input$timeRange[2])) # }) output$slidervalue <- reactive({ input$timeRange[1] }) output$mygraph <- renderPlotly({ plot_ly(myFinalData(),x = ~time,y = ~cases,color = ~geoId, mode="lines") }) # preparing data for cumultative sum plot sumdata<- reactive({ aggregate(myFinalData()$cases,by = list(Country = myFinalData()$geoId), FUN = sum) %>% rename(`sum of cases` = x) }) output$cumsum <- renderTable({ sumdata() }) })
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/makeA.R \name{makeA} \alias{makeA} \title{Creates the additive genetic relationship matrix} \usage{ makeA(pedigree) } \arguments{ \item{pedigree}{A pedigree where the columns are ordered ID, Dam, Sire} } \value{ Returns A, or the numerator relationship matrix, in sparse matrix form. } \description{ This returns the additive relationship matrix in sparse matrix format. } \details{ Missing parents (e.g., base population) should be denoted by either 'NA', '0', or '*'. Used as a support function to \code{\link{makeD}}. See function \code{\link{makeAinv}} for directly obtaining the inverse of the additive genetic relationship matrix. } \examples{ makeA(Mrode2) } \seealso{ \code{\link{makeD}}, \code{\link{makeS}} } \author{ \email{matthewwolak@gmail.com} }
/man/makeA.Rd
no_license
matthewwolak/nadiv
R
false
true
847
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/makeA.R \name{makeA} \alias{makeA} \title{Creates the additive genetic relationship matrix} \usage{ makeA(pedigree) } \arguments{ \item{pedigree}{A pedigree where the columns are ordered ID, Dam, Sire} } \value{ Returns A, or the numerator relationship matrix, in sparse matrix form. } \description{ This returns the additive relationship matrix in sparse matrix format. } \details{ Missing parents (e.g., base population) should be denoted by either 'NA', '0', or '*'. Used as a support function to \code{\link{makeD}}. See function \code{\link{makeAinv}} for directly obtaining the inverse of the additive genetic relationship matrix. } \examples{ makeA(Mrode2) } \seealso{ \code{\link{makeD}}, \code{\link{makeS}} } \author{ \email{matthewwolak@gmail.com} }
library(ggplot2) library(gridExtra) rm(list=ls()) setwd("/Users/sunhuabin/Dropbox/Data/Electric Data/interlayer effect/pulse test") getwd ## Working path setting PulseN <- read.csv("N 100u 20v.csv", header=T) PulseP <- read.csv("p1 100u 20v.csv", header=T) DeviceIDN <- rep("Device withtout PMMA", times=565) DeviceIDP <- rep("Device with PMMA", times=565) IDVG <- rep("Gate Voltage", times=565) IDID <- rep("Drain Current", times=565) DataN <- data.frame(PulseN$Drain.Time.1. , PulseN$Gate.Voltage.1. , PulseN$Drain.Current.1. , PulseN$Gate.Current.1. , DeviceIDN) colnames(DataN)[1] <- "time" colnames(DataN)[2] <- "Vg" colnames(DataN)[3] <- "Id" colnames(DataN)[4] <- "Ig" colnames(DataN)[5] <- "DeviceID" DataP <- data.frame(PulseP$Drain.Time.1. , PulseP$Gate.Voltage.1. , PulseP$Drain.Current.1. , PulseP$Gate.Current.1. , DeviceIDP) colnames(DataP)[1] <- "time" colnames(DataP)[2] <- "Vg" colnames(DataP)[3] <- "Id" colnames(DataP)[4] <- "Ig" colnames(DataP)[5] <- "DeviceID" DeviceData <- rbind(DataN,DataP) DeviceNVG <- data.frame(DataN$time,DataN$Vg,IDVG) names(DeviceNVG) <- c("time","Vg","facel") DeviceNID <- data.frame(DataN$time,DataN$Id,IDID) names(DeviceNID) <- c("time","Vg","facel") NAll <- rbind(DeviceNVG,DeviceNID) ymajP <- c(10^-10,10^-8,10^-7,10^-6,10^-5) ymajN <- c(10^-9,10^-8,10^-6) xmaj <- c(2.5,2.6,2.7,2.8,2.9,3.0) # # # IdPic1 <- qplot(time-1.06,abs(Id),data=DataP,geom=("point"),size = I(2), xlab = "Time (s)", ylab = expression(paste("I"["d"]," (A)")))+ theme_set(theme_bw()) # IdPic1 <- IdPic1+ geom_path(alpha=0.5,size=2) + scale_x_continuous(limits=c(-0.01,7.01))+scale_y_log10(limits=c(4*10^-9,1*10^-5),breaks= ymajP,labels=c(expression(paste("10"^"-10")),expression(paste("10"^"-8")),expression(paste("10"^"-7")),expression(paste("10"^"-6")),expression(paste("10"^"-5"))))+ theme(axis.title.x=element_text(size=0), axis.title.y=element_text(size=24), plot.title=element_text(size=30), axis.text.x=element_text(size=0), axis.text.y=element_text(size=24), legend.text=element_text(size=24), legend.title=element_text(size=0)) + theme(legend.justification=c(1,0), legend.position=c(1,0.7)) + theme(panel.border = element_rect(size= 1, colour = "black")) + theme(panel.grid.major = element_line(size= NA, colour = NA))+ theme(panel.background=element_rect(fill='transparent', color='grey'),panel.grid=element_blank()) # IdPic2 <- qplot(time-1.06,Vg,data=DataP, geom=("point"),size = I(2), xlab = "Time (s)", ylab = expression(paste("V"["g"]," (V)")))+ theme_set(theme_bw()) # IdPic2 <- IdPic2 + scale_x_continuous(limits=c(-0.01,7.01))+scale_y_continuous(limits=c(-25,25))+geom_path(alpha=1,size=1) + theme(axis.title.x=element_text(size=28), axis.title.y=element_text(size=24), plot.title=element_text(size=30), axis.text.x=element_text(size=24), axis.text.y=element_text(size=24), legend.text=element_text(size=24), legend.title=element_text(size=0)) + theme(legend.justification=c(1,0), legend.position=c(1,0.7)) + theme(panel.border = element_rect(size= 1, colour = "black")) + theme(panel.grid.major = element_line(size= NA, colour = NA))+ theme(panel.background=element_rect(fill='transparent', color='grey'),panel.grid=element_blank()) IdPic1 <- qplot(time-1.12,abs(Id),data=DataN, geom=("point"),size = I(2), ylab = expression(paste("I"["d"]," (A)")))+ theme_set(theme_bw()) IdPic1 <- IdPic1 + scale_x_continuous(limits=c(-0.01,7.01))+scale_y_log10(limits=c(10^-10,1*10^-7), breaks= ymajN,labels=c(expression(paste("10"^"-9")),expression(paste("10"^"-8")),expression(paste("10"^"-6"))))+geom_line(alpha=0.5,size=2) + theme(axis.title.x=element_text(size=0), axis.title.y=element_text(size=24), plot.title=element_text(size=30), axis.text.x=element_text(size=0), axis.text.y=element_text(size=24), legend.text=element_text(size=24), legend.title=element_text(size=0)) + theme(legend.justification=c(1,0), legend.position=c(1,0.7)) + theme(panel.border = element_rect(size= 1, colour = "black")) + theme(panel.background=element_rect(fill='transparent', color='gray'),panel.grid=element_blank()) IdPic2 <- qplot(time-1.12,Vg,data=DataN, geom=("point"),size = I(2), xlab = "Time (s)", ylab = expression(paste("V"["g"]," (V)")))+ theme_set(theme_bw()) IdPic2 <- IdPic2 + scale_x_continuous(limits=c(-0.01,7.01))+scale_y_continuous(limits=c(-25,25))+geom_path(alpha=1,size=1) + theme(axis.title.x=element_text(size=28), axis.title.y=element_text(size=24), plot.title=element_text(size=30), axis.text.x=element_text(size=24), axis.text.y=element_text(size=24), legend.text=element_text(size=24), legend.title=element_text(size=0)) + theme(legend.justification=c(1,0), legend.position=c(1,0.7)) + theme(panel.border = element_rect(size= 1, colour = "black")) + theme(panel.background=element_rect(fill='transparent', color='grey'),panel.grid=element_blank()) gp1<- ggplot_gtable(ggplot_build(IdPic1)) gp2<- ggplot_gtable(ggplot_build(IdPic2)) maxWidth = unit.pmax(gp1$widths[2:3], gp2$widths[2:3]) gp1$widths[2:3] <- maxWidth gp2$widths[2:3] <- maxWidth grid.arrange(gp1, gp2)
/RScriptForSp/Plot Puls - Id relation.R
no_license
skatingsun/R-for-Data-analysis
R
false
false
5,046
r
library(ggplot2) library(gridExtra) rm(list=ls()) setwd("/Users/sunhuabin/Dropbox/Data/Electric Data/interlayer effect/pulse test") getwd ## Working path setting PulseN <- read.csv("N 100u 20v.csv", header=T) PulseP <- read.csv("p1 100u 20v.csv", header=T) DeviceIDN <- rep("Device withtout PMMA", times=565) DeviceIDP <- rep("Device with PMMA", times=565) IDVG <- rep("Gate Voltage", times=565) IDID <- rep("Drain Current", times=565) DataN <- data.frame(PulseN$Drain.Time.1. , PulseN$Gate.Voltage.1. , PulseN$Drain.Current.1. , PulseN$Gate.Current.1. , DeviceIDN) colnames(DataN)[1] <- "time" colnames(DataN)[2] <- "Vg" colnames(DataN)[3] <- "Id" colnames(DataN)[4] <- "Ig" colnames(DataN)[5] <- "DeviceID" DataP <- data.frame(PulseP$Drain.Time.1. , PulseP$Gate.Voltage.1. , PulseP$Drain.Current.1. , PulseP$Gate.Current.1. , DeviceIDP) colnames(DataP)[1] <- "time" colnames(DataP)[2] <- "Vg" colnames(DataP)[3] <- "Id" colnames(DataP)[4] <- "Ig" colnames(DataP)[5] <- "DeviceID" DeviceData <- rbind(DataN,DataP) DeviceNVG <- data.frame(DataN$time,DataN$Vg,IDVG) names(DeviceNVG) <- c("time","Vg","facel") DeviceNID <- data.frame(DataN$time,DataN$Id,IDID) names(DeviceNID) <- c("time","Vg","facel") NAll <- rbind(DeviceNVG,DeviceNID) ymajP <- c(10^-10,10^-8,10^-7,10^-6,10^-5) ymajN <- c(10^-9,10^-8,10^-6) xmaj <- c(2.5,2.6,2.7,2.8,2.9,3.0) # # # IdPic1 <- qplot(time-1.06,abs(Id),data=DataP,geom=("point"),size = I(2), xlab = "Time (s)", ylab = expression(paste("I"["d"]," (A)")))+ theme_set(theme_bw()) # IdPic1 <- IdPic1+ geom_path(alpha=0.5,size=2) + scale_x_continuous(limits=c(-0.01,7.01))+scale_y_log10(limits=c(4*10^-9,1*10^-5),breaks= ymajP,labels=c(expression(paste("10"^"-10")),expression(paste("10"^"-8")),expression(paste("10"^"-7")),expression(paste("10"^"-6")),expression(paste("10"^"-5"))))+ theme(axis.title.x=element_text(size=0), axis.title.y=element_text(size=24), plot.title=element_text(size=30), axis.text.x=element_text(size=0), axis.text.y=element_text(size=24), legend.text=element_text(size=24), legend.title=element_text(size=0)) + theme(legend.justification=c(1,0), legend.position=c(1,0.7)) + theme(panel.border = element_rect(size= 1, colour = "black")) + theme(panel.grid.major = element_line(size= NA, colour = NA))+ theme(panel.background=element_rect(fill='transparent', color='grey'),panel.grid=element_blank()) # IdPic2 <- qplot(time-1.06,Vg,data=DataP, geom=("point"),size = I(2), xlab = "Time (s)", ylab = expression(paste("V"["g"]," (V)")))+ theme_set(theme_bw()) # IdPic2 <- IdPic2 + scale_x_continuous(limits=c(-0.01,7.01))+scale_y_continuous(limits=c(-25,25))+geom_path(alpha=1,size=1) + theme(axis.title.x=element_text(size=28), axis.title.y=element_text(size=24), plot.title=element_text(size=30), axis.text.x=element_text(size=24), axis.text.y=element_text(size=24), legend.text=element_text(size=24), legend.title=element_text(size=0)) + theme(legend.justification=c(1,0), legend.position=c(1,0.7)) + theme(panel.border = element_rect(size= 1, colour = "black")) + theme(panel.grid.major = element_line(size= NA, colour = NA))+ theme(panel.background=element_rect(fill='transparent', color='grey'),panel.grid=element_blank()) IdPic1 <- qplot(time-1.12,abs(Id),data=DataN, geom=("point"),size = I(2), ylab = expression(paste("I"["d"]," (A)")))+ theme_set(theme_bw()) IdPic1 <- IdPic1 + scale_x_continuous(limits=c(-0.01,7.01))+scale_y_log10(limits=c(10^-10,1*10^-7), breaks= ymajN,labels=c(expression(paste("10"^"-9")),expression(paste("10"^"-8")),expression(paste("10"^"-6"))))+geom_line(alpha=0.5,size=2) + theme(axis.title.x=element_text(size=0), axis.title.y=element_text(size=24), plot.title=element_text(size=30), axis.text.x=element_text(size=0), axis.text.y=element_text(size=24), legend.text=element_text(size=24), legend.title=element_text(size=0)) + theme(legend.justification=c(1,0), legend.position=c(1,0.7)) + theme(panel.border = element_rect(size= 1, colour = "black")) + theme(panel.background=element_rect(fill='transparent', color='gray'),panel.grid=element_blank()) IdPic2 <- qplot(time-1.12,Vg,data=DataN, geom=("point"),size = I(2), xlab = "Time (s)", ylab = expression(paste("V"["g"]," (V)")))+ theme_set(theme_bw()) IdPic2 <- IdPic2 + scale_x_continuous(limits=c(-0.01,7.01))+scale_y_continuous(limits=c(-25,25))+geom_path(alpha=1,size=1) + theme(axis.title.x=element_text(size=28), axis.title.y=element_text(size=24), plot.title=element_text(size=30), axis.text.x=element_text(size=24), axis.text.y=element_text(size=24), legend.text=element_text(size=24), legend.title=element_text(size=0)) + theme(legend.justification=c(1,0), legend.position=c(1,0.7)) + theme(panel.border = element_rect(size= 1, colour = "black")) + theme(panel.background=element_rect(fill='transparent', color='grey'),panel.grid=element_blank()) gp1<- ggplot_gtable(ggplot_build(IdPic1)) gp2<- ggplot_gtable(ggplot_build(IdPic2)) maxWidth = unit.pmax(gp1$widths[2:3], gp2$widths[2:3]) gp1$widths[2:3] <- maxWidth gp2$widths[2:3] <- maxWidth grid.arrange(gp1, gp2)
#' Organising my workspace #' #' This package contains code to organise code and data within my workspace. #' #' @docType package #' @name workspace #' NULL
/R/0_package.R
no_license
rcannood/workspace
R
false
false
158
r
#' Organising my workspace #' #' This package contains code to organise code and data within my workspace. #' #' @docType package #' @name workspace #' NULL
#' Play the ``Lights Out'' game in R #' #' By default, the white squares in the plot denote the lights that are on, and #' black ones for the off. When you click on a light, this light as well as the #' four neighbors will switch theirs status. Your mission is to close all the #' lights. #' @param width number of lights in x axis #' @param height number of lights in y axis #' @param steps number of ``seed'' lights to initialize the puzzle. In general, #' the larger \code{steps} is, the more complex this puzzle may be #' @param cheat logical. If \code{TRUE} a data frame indicating the steps to #' solve this puzzle will be printed #' @param col.off color when lights off #' @param col.on color when lights on #' @param col.frame color of lights border #' @param seed seed for random number generator #' @author Yixuan Qiu \email{yixuan.qiu@@cos.name} #' @note Linux/Mac users have to use \code{X11(type = 'Xlib')} or the Cairo #' graphics device \code{Cairo()} in the package \pkg{cairoDevice}. #' @references \url{http://en.wikipedia.org/wiki/Lights_Out_(game)} #' @export #' @examples #' ## should use Xlib for the x11() device under *nix, e.g #' if (interactive()) { #' if (.Platform$OS.type == 'windows') x11() else x11(type = 'Xlib') #' lights_out() #' } lights_out = function( width = 5, height = 5, steps = 3, cheat = FALSE, col.off = "black", col.on = "white", col.frame = "lightblue", seed = NULL ) { if (!interactive()) return() zmat <- mat.ini <- matrix(1, height, width) trans <- function(z, x, y) { nr <- nrow(z) nc <- ncol(z) mrow <- intersect(1:nr, (x - 1):(x + 1)) mcol <- intersect(1:nc, (y - 1):(y + 1)) z[x, y] <- z[x, y] * (-1) z[x, mcol] <- z[x, mcol] * (-1) z[mrow, y] <- z[mrow, y] * (-1) return(z) } if (!is.null(seed)) set.seed(seed) grid.x <- sample(1:height, steps, replace = TRUE) grid.y <- sample(1:width, steps, replace = TRUE) if (cheat) { print(data.frame(row = grid.x, col = grid.y)) } for (i in 1:steps) { zmat <- trans(zmat, grid.x[i], grid.y[i]) } replot <- function(z) { nr <- nrow(z) nc <- ncol(z) xv <- rep(1:nc, rep(nr, nc)) yv <- nr + +1 - rep(1:nr, nc) color <- ifelse(as.vector(z) == 1, col.off, col.on) symbols(xv, yv, rectangles = matrix(1, length(xv), 2), inches = FALSE, fg = col.frame, bg = color, add = TRUE) } par(mar = c(0, 0, 0, 0)) plot(1, type = "n", asp = 1, xlab = "", ylab = "", xlim = c(0.5, width + 0.5), ylim = c(0.5, height + 0.5), axes = FALSE) replot(zmat) mousedown <- function(buttons, x, y) { nr <- nrow(zmat) nc <- ncol(zmat) plx <- round(grconvertX(x, "ndc", "user")) ply <- round(grconvertY(y, "ndc", "user")) if (plx < 1 | plx > nc | ply < 1 | ply > nr) { return(zmat) } zmat.trans <- trans(zmat, nr - ply + 1, plx) replot(zmat.trans) return(zmat.trans) } while (1) { if (!any(zmat == -1)) { cat("You win!") break } zmat <- getGraphicsEvent(prompt = "", onMouseDown = mousedown) } }
/R/lights_out.R
no_license
maryglover/fun
R
false
false
3,064
r
#' Play the ``Lights Out'' game in R #' #' By default, the white squares in the plot denote the lights that are on, and #' black ones for the off. When you click on a light, this light as well as the #' four neighbors will switch theirs status. Your mission is to close all the #' lights. #' @param width number of lights in x axis #' @param height number of lights in y axis #' @param steps number of ``seed'' lights to initialize the puzzle. In general, #' the larger \code{steps} is, the more complex this puzzle may be #' @param cheat logical. If \code{TRUE} a data frame indicating the steps to #' solve this puzzle will be printed #' @param col.off color when lights off #' @param col.on color when lights on #' @param col.frame color of lights border #' @param seed seed for random number generator #' @author Yixuan Qiu \email{yixuan.qiu@@cos.name} #' @note Linux/Mac users have to use \code{X11(type = 'Xlib')} or the Cairo #' graphics device \code{Cairo()} in the package \pkg{cairoDevice}. #' @references \url{http://en.wikipedia.org/wiki/Lights_Out_(game)} #' @export #' @examples #' ## should use Xlib for the x11() device under *nix, e.g #' if (interactive()) { #' if (.Platform$OS.type == 'windows') x11() else x11(type = 'Xlib') #' lights_out() #' } lights_out = function( width = 5, height = 5, steps = 3, cheat = FALSE, col.off = "black", col.on = "white", col.frame = "lightblue", seed = NULL ) { if (!interactive()) return() zmat <- mat.ini <- matrix(1, height, width) trans <- function(z, x, y) { nr <- nrow(z) nc <- ncol(z) mrow <- intersect(1:nr, (x - 1):(x + 1)) mcol <- intersect(1:nc, (y - 1):(y + 1)) z[x, y] <- z[x, y] * (-1) z[x, mcol] <- z[x, mcol] * (-1) z[mrow, y] <- z[mrow, y] * (-1) return(z) } if (!is.null(seed)) set.seed(seed) grid.x <- sample(1:height, steps, replace = TRUE) grid.y <- sample(1:width, steps, replace = TRUE) if (cheat) { print(data.frame(row = grid.x, col = grid.y)) } for (i in 1:steps) { zmat <- trans(zmat, grid.x[i], grid.y[i]) } replot <- function(z) { nr <- nrow(z) nc <- ncol(z) xv <- rep(1:nc, rep(nr, nc)) yv <- nr + +1 - rep(1:nr, nc) color <- ifelse(as.vector(z) == 1, col.off, col.on) symbols(xv, yv, rectangles = matrix(1, length(xv), 2), inches = FALSE, fg = col.frame, bg = color, add = TRUE) } par(mar = c(0, 0, 0, 0)) plot(1, type = "n", asp = 1, xlab = "", ylab = "", xlim = c(0.5, width + 0.5), ylim = c(0.5, height + 0.5), axes = FALSE) replot(zmat) mousedown <- function(buttons, x, y) { nr <- nrow(zmat) nc <- ncol(zmat) plx <- round(grconvertX(x, "ndc", "user")) ply <- round(grconvertY(y, "ndc", "user")) if (plx < 1 | plx > nc | ply < 1 | ply > nr) { return(zmat) } zmat.trans <- trans(zmat, nr - ply + 1, plx) replot(zmat.trans) return(zmat.trans) } while (1) { if (!any(zmat == -1)) { cat("You win!") break } zmat <- getGraphicsEvent(prompt = "", onMouseDown = mousedown) } }
\name{Conditional independence tests for survival data } \alias{censIndCR} \alias{censIndWR} \alias{censIndER} \alias{permCR} \alias{permWR} \alias{permER} \alias{waldCR} \alias{waldWR} \alias{waldER} \title{ Conditional independence test for survival data } \description{ The main task of this test is to provide a p-value PVALUE for the null hypothesis: feature 'X' is independent from 'TARGET' given a conditioning set CS. This test can based on the Cox (semi-parametric) regression or on the Weibull (parametric) regression. } \usage{ censIndCR(target, dataset, xIndex, csIndex, wei = NULL, dataInfo = NULL, univariateModels = NULL, hash = FALSE, stat_hash = NULL, pvalue_hash = NULL, robust = FALSE) censIndWR(target, dataset, xIndex, csIndex, wei = NULL, dataInfo = NULL, univariateModels = NULL, hash = FALSE, stat_hash = NULL, pvalue_hash = NULL, robust = FALSE) censIndER(target, dataset, xIndex, csIndex, wei = NULL, dataInfo = NULL, univariateModels = NULL, hash = FALSE, stat_hash = NULL, pvalue_hash = NULL, robust = FALSE) permCR(target, dataset, xIndex, csIndex, wei = NULL, dataInfo = NULL, univariateModels = NULL, hash = FALSE, stat_hash = NULL, pvalue_hash = NULL, robust = FALSE, threshold = 0.05, R = 999) permWR(target, dataset, xIndex, csIndex, wei = NULL, dataInfo = NULL, univariateModels = NULL, hash = FALSE, stat_hash = NULL, pvalue_hash = NULL, robust = FALSE, threshold = 0.05, R = 999) permER(target, dataset, xIndex, csIndex, wei = NULL, dataInfo = NULL, univariateModels = NULL, hash = FALSE, stat_hash = NULL, pvalue_hash = NULL, robust = FALSE, threshold = 0.05, R = 999) waldCR(target, dataset, xIndex, csIndex, wei = NULL, dataInfo = NULL, univariateModels = NULL, hash = FALSE, stat_hash = NULL, pvalue_hash = NULL, robust = FALSE) waldWR(target, dataset, xIndex, csIndex, wei = NULL, dataInfo = NULL, univariateModels = NULL, hash = FALSE, stat_hash = NULL, pvalue_hash = NULL, robust = FALSE) waldER(target, dataset, xIndex, csIndex, wei = NULL, dataInfo = NULL, univariateModels = NULL, hash = FALSE, stat_hash = NULL, pvalue_hash = NULL, robust = FALSE) } \arguments{ \item{target}{ A Survival object (class Surv from package survival) containing the time to event data (time) and the status indicator vector (event). View \link{Surv} documentation for more information. } \item{dataset}{ A numeric matrix or data frame, in case of categorical predictors (factors), containing the variables for performing the test. Rows as samples and columns as features. In the cases of "waldCR", "waldWR", "waldER", "waldCR", "permWR" and "permER" this is strictly a matrix. } \item{xIndex}{ The index of the variable whose association with the target we want to test. } \item{csIndex}{ The indices of the variables to condition on. } \item{wei}{ A vector of weights to be used for weighted regression. The default value is NULL. } \item{dataInfo}{ A list object with information on the structure of the data. Default value is NULL. } \item{univariateModels}{ Fast alternative to the hash object for univariate test. List with vectors "pvalues" (p-values), "stats" (statistics) and "flags" (flag = TRUE if the test was succesful) representing the univariate association of each variable with the target. Default value is NULL. } \item{hash}{ A boolean variable which indicates whether (TRUE) or not (FALSE) to use the hash-based implementation of the statistics of SES. Default value is FALSE. If TRUE you have to specify the stat_hash argument and the pvalue_hash argument. } \item{stat_hash}{ A hash object (hash package required) which contains the cached generated statistics of a SES run in the current dataset, using the current test. } \item{pvalue_hash}{ A hash object (hash package required) which contains the cached generated p-values of a SES run in the current dataset, using the current test. } \item{robust}{ A boolean variable which indicates whether (TRUE) or not (FALSE) to use a robustified version of Cox regression. Currently the robust version is not available for this test. Note, that Cox and Weibull regressions offer robust (sandwich) estimation of the standard error of the coefficients, but not robust estimation of the parameters. } \item{threshold}{ Threshold (suitable values in [0,1]) for assessing p-values significance. } \item{R}{ The number of permutations, set to 999 by default. There is a trick to avoind doing all permutations. As soon as the number of times the permuted test statistic is more than the observed test statistic is more than 50 (in this example case), the p-value has exceeded the signifiance level (threshold value) and hence the predictor variable is not significant. There is no need to continue do the extra permutations, as a decision has already been made. } } \details{ The censIndCR implies the Cox (semiparametric) regression, the censIndWR the Weibull (parametric) regression and the censIndER the exponential (parametric) regression, which is a special case of the Weibull regression (when shape parameter is 1). If hash = TRUE, censIndCR, censIndWR and censIndER require the arguments 'stat_hash' and 'pvalue_hash' for the hash-based implementation of the statistic test. These hash Objects are produced or updated by each run of SES (if hash == TRUE) and they can be reused in order to speed up next runs of the current statistic test. If "SESoutput" is the output of a SES run, then these objects can be retrieved by SESoutput@hashObject$stat_hash and the SESoutput@hashObject$pvalue_hash. Important: Use these arguments only with the same dataset that was used at initialization. For all the available conditional independence tests that are currently included on the package, please see "?CondIndTests". The log-likelihood ratio test used in "censIndCR", "censIndWR" and "censIndER" requires the fitting of two models. The Wald tests used in "waldCR", "waldWR" and "waldER" requires fitting of only one model, the full one. The significance of the variable is examined only. Only continuous (or binary) predictor variables are currently accepted in this test. } \value{ A list including: \item{pvalue}{ A numeric value that represents the logarithm of the generated p-value. } \item{stat}{ A numeric value that represents the generated statistic. } \item{flag}{ A numeric value (control flag) which indicates whether the test was succesful (0) or not (1). } \item{stat_hash}{ The current hash object used for the statistics. See argument stat_hash and details. If argument hash = FALSE this is NULL. } \item{pvalue_hash}{ The current hash object used for the p-values. See argument stat_hash and details. If argument hash = FALSE this is NULL. } } \references{ V. Lagani and I. Tsamardinos (2010). Structure-based variable selection for survival data. Bioinformatics Journal 16(15): 1887-1894. Cox,D.R. (1972) Regression models and life-tables. J. R. Stat. Soc., 34, 187-220. Scholz, F. W. (2001). Maximum likelihood estimation for type I censored Weibull data including covariates. ISSTECH-96-022, Boeing Information & Support Services. Smith, R. L. (1991). Weibull regression models for reliability data. Reliability Engineering & System Safety, 34(1), 55-76. } \author{ R implementation and documentation: Vincenzo Lagani <vlagani@csd.uoc.gr>, Giorgos Athineou <athineou@csd.uoc.gr> } \note{ This test uses the functions coxph and Surv of the package survival and the function anova (analysis of variance) of the package stats. } \seealso{ \code{\link{SES}, \link{censIndWR}, \link{testIndFisher}, \link{gSquare}, \link{testIndLogistic}, \link{Surv}, \link{anova}, \link{CondIndTests}} } \examples{ #create a survival simulated dataset dataset <- matrix(runif(1000 * 20, 1, 100), nrow = 1000 , ncol = 20) dataset <- as.data.frame(dataset); timeToEvent <- numeric(1000) event <- numeric(1000) ca <- numeric(1000) for(i in 1:1000) { timeToEvent[i] <- dataset[i, 1] + 0.5 * dataset[i, 10] + 2 * dataset[i, 15] + runif(1, 0, 3); event[i] <- sample( c(0, 1), 1) ca[i] <- runif(1, 0, timeToEvent[i] - 0.5) if(event[i] == 0) timeToEvent[i] = timeToEvent[i] - ca[i] } require(survival, quietly = TRUE) #init the Surv object class feature target <- Surv(time = timeToEvent, event = event) #run the censIndCR conditional independence test censIndCR( target, dataset, xIndex = 12, csIndex = c(5, 7, 4) ) # run the SESC algorithm \dontrun{ ses1 <- SES(target, dataset, max_k = 1, threshold = 0.05, test = "censIndCR"); ses2 <- SES(target, dataset, max_k = 1, threshold = 0.05, test = "censIndWR"); } } \keyword{ Survival } \keyword{ Cox regression } \keyword{ Weibull regression } \keyword{ exponential regression } \keyword{ Log likelihood ratio } \keyword{ Conditional independence test }
/man/censIndCR.Rd
no_license
JokerWhy233/MXM
R
false
false
8,975
rd
\name{Conditional independence tests for survival data } \alias{censIndCR} \alias{censIndWR} \alias{censIndER} \alias{permCR} \alias{permWR} \alias{permER} \alias{waldCR} \alias{waldWR} \alias{waldER} \title{ Conditional independence test for survival data } \description{ The main task of this test is to provide a p-value PVALUE for the null hypothesis: feature 'X' is independent from 'TARGET' given a conditioning set CS. This test can based on the Cox (semi-parametric) regression or on the Weibull (parametric) regression. } \usage{ censIndCR(target, dataset, xIndex, csIndex, wei = NULL, dataInfo = NULL, univariateModels = NULL, hash = FALSE, stat_hash = NULL, pvalue_hash = NULL, robust = FALSE) censIndWR(target, dataset, xIndex, csIndex, wei = NULL, dataInfo = NULL, univariateModels = NULL, hash = FALSE, stat_hash = NULL, pvalue_hash = NULL, robust = FALSE) censIndER(target, dataset, xIndex, csIndex, wei = NULL, dataInfo = NULL, univariateModels = NULL, hash = FALSE, stat_hash = NULL, pvalue_hash = NULL, robust = FALSE) permCR(target, dataset, xIndex, csIndex, wei = NULL, dataInfo = NULL, univariateModels = NULL, hash = FALSE, stat_hash = NULL, pvalue_hash = NULL, robust = FALSE, threshold = 0.05, R = 999) permWR(target, dataset, xIndex, csIndex, wei = NULL, dataInfo = NULL, univariateModels = NULL, hash = FALSE, stat_hash = NULL, pvalue_hash = NULL, robust = FALSE, threshold = 0.05, R = 999) permER(target, dataset, xIndex, csIndex, wei = NULL, dataInfo = NULL, univariateModels = NULL, hash = FALSE, stat_hash = NULL, pvalue_hash = NULL, robust = FALSE, threshold = 0.05, R = 999) waldCR(target, dataset, xIndex, csIndex, wei = NULL, dataInfo = NULL, univariateModels = NULL, hash = FALSE, stat_hash = NULL, pvalue_hash = NULL, robust = FALSE) waldWR(target, dataset, xIndex, csIndex, wei = NULL, dataInfo = NULL, univariateModels = NULL, hash = FALSE, stat_hash = NULL, pvalue_hash = NULL, robust = FALSE) waldER(target, dataset, xIndex, csIndex, wei = NULL, dataInfo = NULL, univariateModels = NULL, hash = FALSE, stat_hash = NULL, pvalue_hash = NULL, robust = FALSE) } \arguments{ \item{target}{ A Survival object (class Surv from package survival) containing the time to event data (time) and the status indicator vector (event). View \link{Surv} documentation for more information. } \item{dataset}{ A numeric matrix or data frame, in case of categorical predictors (factors), containing the variables for performing the test. Rows as samples and columns as features. In the cases of "waldCR", "waldWR", "waldER", "waldCR", "permWR" and "permER" this is strictly a matrix. } \item{xIndex}{ The index of the variable whose association with the target we want to test. } \item{csIndex}{ The indices of the variables to condition on. } \item{wei}{ A vector of weights to be used for weighted regression. The default value is NULL. } \item{dataInfo}{ A list object with information on the structure of the data. Default value is NULL. } \item{univariateModels}{ Fast alternative to the hash object for univariate test. List with vectors "pvalues" (p-values), "stats" (statistics) and "flags" (flag = TRUE if the test was succesful) representing the univariate association of each variable with the target. Default value is NULL. } \item{hash}{ A boolean variable which indicates whether (TRUE) or not (FALSE) to use the hash-based implementation of the statistics of SES. Default value is FALSE. If TRUE you have to specify the stat_hash argument and the pvalue_hash argument. } \item{stat_hash}{ A hash object (hash package required) which contains the cached generated statistics of a SES run in the current dataset, using the current test. } \item{pvalue_hash}{ A hash object (hash package required) which contains the cached generated p-values of a SES run in the current dataset, using the current test. } \item{robust}{ A boolean variable which indicates whether (TRUE) or not (FALSE) to use a robustified version of Cox regression. Currently the robust version is not available for this test. Note, that Cox and Weibull regressions offer robust (sandwich) estimation of the standard error of the coefficients, but not robust estimation of the parameters. } \item{threshold}{ Threshold (suitable values in [0,1]) for assessing p-values significance. } \item{R}{ The number of permutations, set to 999 by default. There is a trick to avoind doing all permutations. As soon as the number of times the permuted test statistic is more than the observed test statistic is more than 50 (in this example case), the p-value has exceeded the signifiance level (threshold value) and hence the predictor variable is not significant. There is no need to continue do the extra permutations, as a decision has already been made. } } \details{ The censIndCR implies the Cox (semiparametric) regression, the censIndWR the Weibull (parametric) regression and the censIndER the exponential (parametric) regression, which is a special case of the Weibull regression (when shape parameter is 1). If hash = TRUE, censIndCR, censIndWR and censIndER require the arguments 'stat_hash' and 'pvalue_hash' for the hash-based implementation of the statistic test. These hash Objects are produced or updated by each run of SES (if hash == TRUE) and they can be reused in order to speed up next runs of the current statistic test. If "SESoutput" is the output of a SES run, then these objects can be retrieved by SESoutput@hashObject$stat_hash and the SESoutput@hashObject$pvalue_hash. Important: Use these arguments only with the same dataset that was used at initialization. For all the available conditional independence tests that are currently included on the package, please see "?CondIndTests". The log-likelihood ratio test used in "censIndCR", "censIndWR" and "censIndER" requires the fitting of two models. The Wald tests used in "waldCR", "waldWR" and "waldER" requires fitting of only one model, the full one. The significance of the variable is examined only. Only continuous (or binary) predictor variables are currently accepted in this test. } \value{ A list including: \item{pvalue}{ A numeric value that represents the logarithm of the generated p-value. } \item{stat}{ A numeric value that represents the generated statistic. } \item{flag}{ A numeric value (control flag) which indicates whether the test was succesful (0) or not (1). } \item{stat_hash}{ The current hash object used for the statistics. See argument stat_hash and details. If argument hash = FALSE this is NULL. } \item{pvalue_hash}{ The current hash object used for the p-values. See argument stat_hash and details. If argument hash = FALSE this is NULL. } } \references{ V. Lagani and I. Tsamardinos (2010). Structure-based variable selection for survival data. Bioinformatics Journal 16(15): 1887-1894. Cox,D.R. (1972) Regression models and life-tables. J. R. Stat. Soc., 34, 187-220. Scholz, F. W. (2001). Maximum likelihood estimation for type I censored Weibull data including covariates. ISSTECH-96-022, Boeing Information & Support Services. Smith, R. L. (1991). Weibull regression models for reliability data. Reliability Engineering & System Safety, 34(1), 55-76. } \author{ R implementation and documentation: Vincenzo Lagani <vlagani@csd.uoc.gr>, Giorgos Athineou <athineou@csd.uoc.gr> } \note{ This test uses the functions coxph and Surv of the package survival and the function anova (analysis of variance) of the package stats. } \seealso{ \code{\link{SES}, \link{censIndWR}, \link{testIndFisher}, \link{gSquare}, \link{testIndLogistic}, \link{Surv}, \link{anova}, \link{CondIndTests}} } \examples{ #create a survival simulated dataset dataset <- matrix(runif(1000 * 20, 1, 100), nrow = 1000 , ncol = 20) dataset <- as.data.frame(dataset); timeToEvent <- numeric(1000) event <- numeric(1000) ca <- numeric(1000) for(i in 1:1000) { timeToEvent[i] <- dataset[i, 1] + 0.5 * dataset[i, 10] + 2 * dataset[i, 15] + runif(1, 0, 3); event[i] <- sample( c(0, 1), 1) ca[i] <- runif(1, 0, timeToEvent[i] - 0.5) if(event[i] == 0) timeToEvent[i] = timeToEvent[i] - ca[i] } require(survival, quietly = TRUE) #init the Surv object class feature target <- Surv(time = timeToEvent, event = event) #run the censIndCR conditional independence test censIndCR( target, dataset, xIndex = 12, csIndex = c(5, 7, 4) ) # run the SESC algorithm \dontrun{ ses1 <- SES(target, dataset, max_k = 1, threshold = 0.05, test = "censIndCR"); ses2 <- SES(target, dataset, max_k = 1, threshold = 0.05, test = "censIndWR"); } } \keyword{ Survival } \keyword{ Cox regression } \keyword{ Weibull regression } \keyword{ exponential regression } \keyword{ Log likelihood ratio } \keyword{ Conditional independence test }
### Prepare Data ### DateStart <- as.POSIXlt("2007-02-01 00:00:00") DateEnd <- as.POSIXlt("2007-02-02 23:59:59") data <- read.table("household_power_consumption.txt",sep=";",header=TRUE,na.strings = '?', blank.lines.skip = TRUE) DateTime<-strptime(paste(data$Date,data$Time),"%d/%m/%Y %H:%M:%S") data<- cbind(data,DateTime) data <- data[data$DateTime >= DateStart & data$DateTime <= DateEnd,] data<- data[complete.cases(data),] ### Plot Data ### png("plot3.png", width=480, height=480) plot(data$Sub_metering_1~data$DateTime ,type="l",ylab = "Energy sub metering",xlab="", col="black") lines(data$Sub_metering_2~data$DateTime, type="l", col="red") lines(data$Sub_metering_3~data$DateTime, type="l", col="blue") legend("topright",c("Sub_metering_1","Sub_metering_2","Sub_metering_3"),col=c("black","red","blue"),lty=c(1,1,1)) dev.off()
/plot3.R
no_license
tomchal/ExData_Plotting1
R
false
false
847
r
### Prepare Data ### DateStart <- as.POSIXlt("2007-02-01 00:00:00") DateEnd <- as.POSIXlt("2007-02-02 23:59:59") data <- read.table("household_power_consumption.txt",sep=";",header=TRUE,na.strings = '?', blank.lines.skip = TRUE) DateTime<-strptime(paste(data$Date,data$Time),"%d/%m/%Y %H:%M:%S") data<- cbind(data,DateTime) data <- data[data$DateTime >= DateStart & data$DateTime <= DateEnd,] data<- data[complete.cases(data),] ### Plot Data ### png("plot3.png", width=480, height=480) plot(data$Sub_metering_1~data$DateTime ,type="l",ylab = "Energy sub metering",xlab="", col="black") lines(data$Sub_metering_2~data$DateTime, type="l", col="red") lines(data$Sub_metering_3~data$DateTime, type="l", col="blue") legend("topright",c("Sub_metering_1","Sub_metering_2","Sub_metering_3"),col=c("black","red","blue"),lty=c(1,1,1)) dev.off()
read.fmridata <- function( directory, format, prefix, nimages, dim.image, nii=TRUE ) { fmridata <- array(NA, dim=c(dim.image,nimages)) if(format=="Analyze") { for(i in 1:nimages) { if (i <= 9) aux <- paste0("000",i,".img") if ((i > 9) && (i <= 99)) aux <- paste0("00",i,".img") if ((i > 99) && (i <= 999)) aux <- paste0("0",i,".img") if (i > 999) aux <- paste0(i,".img") a <- f.read.analyze.volume(paste0(directory, "/", prefix, aux)) fmridata[,,,i] <- a[,,,1] } return(fmridata) } if(format=="Nifti") { for(i in 1:nimages) { if(nii==TRUE) ext <- ".nii" else ext <- ".img" if (i <= 9) aux <- paste0("000",i,ext) if ((i > 9) && (i <= 99)) aux <- paste0("00",i,ext) if ((i > 99) && (i <= 999)) aux <- paste0("0",i,ext) if (i > 999) aux <- paste0(i,ext) a <- f.read.nifti.volume(paste0(directory, "/", prefix, aux)) fmridata[,,,i] <- a } return(fmridata) } if(format=="Afni") { a <- read.AFNI(paste0(directory, "/", prefix)) fmridata <- extract.data(a, what="data") return(fmridata) } }
/R/11.read.fmridata.r
no_license
Tavpritesh/BHMSMAfMRI
R
false
false
1,154
r
read.fmridata <- function( directory, format, prefix, nimages, dim.image, nii=TRUE ) { fmridata <- array(NA, dim=c(dim.image,nimages)) if(format=="Analyze") { for(i in 1:nimages) { if (i <= 9) aux <- paste0("000",i,".img") if ((i > 9) && (i <= 99)) aux <- paste0("00",i,".img") if ((i > 99) && (i <= 999)) aux <- paste0("0",i,".img") if (i > 999) aux <- paste0(i,".img") a <- f.read.analyze.volume(paste0(directory, "/", prefix, aux)) fmridata[,,,i] <- a[,,,1] } return(fmridata) } if(format=="Nifti") { for(i in 1:nimages) { if(nii==TRUE) ext <- ".nii" else ext <- ".img" if (i <= 9) aux <- paste0("000",i,ext) if ((i > 9) && (i <= 99)) aux <- paste0("00",i,ext) if ((i > 99) && (i <= 999)) aux <- paste0("0",i,ext) if (i > 999) aux <- paste0(i,ext) a <- f.read.nifti.volume(paste0(directory, "/", prefix, aux)) fmridata[,,,i] <- a } return(fmridata) } if(format=="Afni") { a <- read.AFNI(paste0(directory, "/", prefix)) fmridata <- extract.data(a, what="data") return(fmridata) } }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/regression.R \name{setKernel.default} \alias{setKernel.default} \title{\code{RegFitObj} (regression approach)} \usage{ \method{setKernel}{default}(rfo, Kernel) } \arguments{ \item{rfo}{[\code{RegFitObj}(1)]\cr object taken in the argument.} \item{Kernel}{[\code{\link{Kernel}(1)}]\cr new object of class \code{Kernel}.} } \value{ [\code{RegFitObj}(1)] modified object. } \description{ setKernel.default } \keyword{internal}
/man/setKernel.default.Rd
no_license
cran/survivalsvm
R
false
true
503
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/regression.R \name{setKernel.default} \alias{setKernel.default} \title{\code{RegFitObj} (regression approach)} \usage{ \method{setKernel}{default}(rfo, Kernel) } \arguments{ \item{rfo}{[\code{RegFitObj}(1)]\cr object taken in the argument.} \item{Kernel}{[\code{\link{Kernel}(1)}]\cr new object of class \code{Kernel}.} } \value{ [\code{RegFitObj}(1)] modified object. } \description{ setKernel.default } \keyword{internal}
tidy_data_convert_spreadsheet <- function(input_file_name) { # read in the csv file with correct date format using readr and read_csv covid_data_tidy <- readr::read_csv(input_file_name) # convert read file into a long spreadsheet format covid_tidy_data_long <- covid_data_tidy %>% pivot_longer(!c( transportation_type, geo_type, country, region, alternative_name, `sub-region`), names_to = "date", values_to = "rel_mobility") # check to see if number of columns is correct after reformating if (ncol(covid_tidy_data_long) >= 10) { stop("ERROR, too many columns, did not reformat") } # save the longer format spreadsheet as a csv in the output directory readr::write_csv( covid_tidy_data_long, path = paste0( "output/", "subsetted_state_long/", tools::file_path_sans_ext( basename(input_file_name)), "_long.csv")) return(covid_tidy_data_long) }
/code/functions/tidy_data_convert_spreadsheet.R
no_license
mbogaczynska/apple_mobility_data
R
false
false
902
r
tidy_data_convert_spreadsheet <- function(input_file_name) { # read in the csv file with correct date format using readr and read_csv covid_data_tidy <- readr::read_csv(input_file_name) # convert read file into a long spreadsheet format covid_tidy_data_long <- covid_data_tidy %>% pivot_longer(!c( transportation_type, geo_type, country, region, alternative_name, `sub-region`), names_to = "date", values_to = "rel_mobility") # check to see if number of columns is correct after reformating if (ncol(covid_tidy_data_long) >= 10) { stop("ERROR, too many columns, did not reformat") } # save the longer format spreadsheet as a csv in the output directory readr::write_csv( covid_tidy_data_long, path = paste0( "output/", "subsetted_state_long/", tools::file_path_sans_ext( basename(input_file_name)), "_long.csv")) return(covid_tidy_data_long) }
#' SP500_px #' #'the daily returns for telecommunication stocks #'from July 2012 through June 2015. #' #' @docType data #' #' @usage data(sp500_px) #' #' @keywords datasets #' #' #' @examples #' data(sp500_px) "sp500_px" #' SP500_sym #' #'the daily returns for telecommunication stocks #'from July 2012 through June 2015. #' #' @docType data #' #' @usage data(sp500_sym) #' #' @keywords datasets #' #' @examples #' data(sp500_sym) "sp500_sym"
/R/sp500-data.R
no_license
g4challenge/statistics-for-data-scientists
R
false
false
445
r
#' SP500_px #' #'the daily returns for telecommunication stocks #'from July 2012 through June 2015. #' #' @docType data #' #' @usage data(sp500_px) #' #' @keywords datasets #' #' #' @examples #' data(sp500_px) "sp500_px" #' SP500_sym #' #'the daily returns for telecommunication stocks #'from July 2012 through June 2015. #' #' @docType data #' #' @usage data(sp500_sym) #' #' @keywords datasets #' #' @examples #' data(sp500_sym) "sp500_sym"
systematic.resample = function(weights, num.samples=length(weights), engine="R") { check.weights(weights, log=F, normalized=T) stopifnot(num.samples>0) engine=pmatch(engine, c("R","C")) n = length(weights) switch(engine, { u = stats::runif(1,0,1/num.samples)+seq(0,by=1/num.samples,length=num.samples) return(inverse.cdf.weights(weights,u,engine="R")) }, { # C implementation out = .C("systematic_resample_R", as.integer(n), as.double(weights), as.integer(num.samples), id = integer(num.samples)) return(out$id+1) }) }
/R/systematic.resample.R
no_license
AnthonyEbert/smcUtils
R
false
false
668
r
systematic.resample = function(weights, num.samples=length(weights), engine="R") { check.weights(weights, log=F, normalized=T) stopifnot(num.samples>0) engine=pmatch(engine, c("R","C")) n = length(weights) switch(engine, { u = stats::runif(1,0,1/num.samples)+seq(0,by=1/num.samples,length=num.samples) return(inverse.cdf.weights(weights,u,engine="R")) }, { # C implementation out = .C("systematic_resample_R", as.integer(n), as.double(weights), as.integer(num.samples), id = integer(num.samples)) return(out$id+1) }) }
rm(list = ls()) n.range = 1:(1e6-1) collatz = function(n){ if (n %% 2 == 0){ return(n / 2) } else{ return(3 * n + 1) } } collatz.seq = function(n){ n.seq = n i = 1 while (n.seq[i] > 1){ n.seq[i + 1] = collatz(n.seq[i]) i = i + 1 } return(n.seq) } collatz.length = function(n){ n.current = n i = 1 while (n.current > 1){ n.current = collatz(n.current) i = i + 1 } return(i) } seq.lengths = sapply(1:(1e6-1), collatz.length) n.range[which.max(seq.lengths)]
/PE/14.R
no_license
tkmckenzie/pan
R
false
false
511
r
rm(list = ls()) n.range = 1:(1e6-1) collatz = function(n){ if (n %% 2 == 0){ return(n / 2) } else{ return(3 * n + 1) } } collatz.seq = function(n){ n.seq = n i = 1 while (n.seq[i] > 1){ n.seq[i + 1] = collatz(n.seq[i]) i = i + 1 } return(n.seq) } collatz.length = function(n){ n.current = n i = 1 while (n.current > 1){ n.current = collatz(n.current) i = i + 1 } return(i) } seq.lengths = sapply(1:(1e6-1), collatz.length) n.range[which.max(seq.lengths)]