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
% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/ISODigitalTransferOptions.R \docType{class} \name{ISODigitalTransferOptions} \alias{ISODigitalTransferOptions} \title{ISODigitalTransferOptions} \format{\code{\link{R6Class}} object.} \usage{ ISODigitalTransferOptions } \value{ Object of \code{\link{R6Class}} for modelling an ISO DigitalTransferOptions } \description{ ISODigitalTransferOptions } \section{Fields}{ \describe{ \item{\code{onLine}}{} }} \section{Methods}{ \describe{ \item{\code{new(xml,value)}}{ This method is used to instantiate an ISODigitalTransferOptions } \item{\code{setUnitsOfDistribution(unit)}}{ Sets the units of distribution } \item{\code{setTransferSize(transferSize)}}{ Sets the transfer Size } \item{\code{addOnlineResource(onlineResource)}}{ Adds an object of class \code{ISOOnlineResource} } \item{\code{setOnlineResource(onlineResource)}}{ Sets an object of class \code{ISOOnlineResource} } \item{\code{delOnlineResource(onlineResource)}}{ Deletes an object of class \code{ISOOnlineResource} } } } \examples{ md <- ISODigitalTransferOptions$new() or <- ISOOnlineResource$new() or$setLinkage("http://somelink") or$setName("name") or$setDescription("description") or$setProtocol("WWW:LINK-1.0-http--link") md$addOnlineResource(or) xml <- md$encode() } \author{ Emmanuel Blondel <emmanuel.blondel1@gmail.com> } \references{ ISO 19115:2003 - Geographic information -- Metadata } \keyword{ISO} \keyword{distribution}
/man/ISODigitalTransferOptions.Rd
no_license
sebkopf/geometa
R
false
false
1,532
rd
% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/ISODigitalTransferOptions.R \docType{class} \name{ISODigitalTransferOptions} \alias{ISODigitalTransferOptions} \title{ISODigitalTransferOptions} \format{\code{\link{R6Class}} object.} \usage{ ISODigitalTransferOptions } \value{ Object of \code{\link{R6Class}} for modelling an ISO DigitalTransferOptions } \description{ ISODigitalTransferOptions } \section{Fields}{ \describe{ \item{\code{onLine}}{} }} \section{Methods}{ \describe{ \item{\code{new(xml,value)}}{ This method is used to instantiate an ISODigitalTransferOptions } \item{\code{setUnitsOfDistribution(unit)}}{ Sets the units of distribution } \item{\code{setTransferSize(transferSize)}}{ Sets the transfer Size } \item{\code{addOnlineResource(onlineResource)}}{ Adds an object of class \code{ISOOnlineResource} } \item{\code{setOnlineResource(onlineResource)}}{ Sets an object of class \code{ISOOnlineResource} } \item{\code{delOnlineResource(onlineResource)}}{ Deletes an object of class \code{ISOOnlineResource} } } } \examples{ md <- ISODigitalTransferOptions$new() or <- ISOOnlineResource$new() or$setLinkage("http://somelink") or$setName("name") or$setDescription("description") or$setProtocol("WWW:LINK-1.0-http--link") md$addOnlineResource(or) xml <- md$encode() } \author{ Emmanuel Blondel <emmanuel.blondel1@gmail.com> } \references{ ISO 19115:2003 - Geographic information -- Metadata } \keyword{ISO} \keyword{distribution}
shinyUI(bootstrapPage( plotOutput(outputId = "full_image", height = "500px"), sliderInput(inputId = "iterations_count", label = "Количество итераций:", min = 1, max = 10, value = 1, step = 1), actionButton(inputId = "my_button", label = "Click me"), selectInput(inputId = "n_breaks", label = "Number of bins in histogram (approximate):", choices = c(10, 20, 35, 50), selected = 20), checkboxInput(inputId = "individual_obs", label = strong("Show individual observations"), value = FALSE), checkboxInput(inputId = "density", label = strong("Show density estimate"), value = FALSE), plotOutput(outputId = "main_plot", height = "300px"), # Display this only if the density is shown conditionalPanel(condition = "input.density == true", sliderInput(inputId = "bw_adjust", label = "Bandwidth adjustment:", min = 0.2, max = 2, value = 1, step = 0.2) ), radioButtons("colorSelect", "Color:", c("Red" = "red", "Green" = "green", "Blue" = "blue") ), sliderInput(inputId = "mySliderInput", label = "Test:", min = 0.2, max = 2, value = 1, step = 0.2) ) )
/UI.R
permissive
pasvistelik/r-combine-cutted-pictures
R
false
false
1,282
r
shinyUI(bootstrapPage( plotOutput(outputId = "full_image", height = "500px"), sliderInput(inputId = "iterations_count", label = "Количество итераций:", min = 1, max = 10, value = 1, step = 1), actionButton(inputId = "my_button", label = "Click me"), selectInput(inputId = "n_breaks", label = "Number of bins in histogram (approximate):", choices = c(10, 20, 35, 50), selected = 20), checkboxInput(inputId = "individual_obs", label = strong("Show individual observations"), value = FALSE), checkboxInput(inputId = "density", label = strong("Show density estimate"), value = FALSE), plotOutput(outputId = "main_plot", height = "300px"), # Display this only if the density is shown conditionalPanel(condition = "input.density == true", sliderInput(inputId = "bw_adjust", label = "Bandwidth adjustment:", min = 0.2, max = 2, value = 1, step = 0.2) ), radioButtons("colorSelect", "Color:", c("Red" = "red", "Green" = "green", "Blue" = "blue") ), sliderInput(inputId = "mySliderInput", label = "Test:", min = 0.2, max = 2, value = 1, step = 0.2) ) )
wide.form <- function(group.by, spread.by, values, fill = 0 , prop = FALSE, prune = TRUE){ sum.mat <- tapply(values, list(group.by, spread.by), sum) sum.mat[is.na(sum.mat)] = fill if(prune){ sum.mat <- sum.mat[rowSums(sum.mat) > 0, colSums(sum.mat) > 0] } if(prop){ sum.mat = prop.table(sum.mat, 1) } return(sum.mat) }
/functions/wide.form.R
no_license
jack-w-hill/mangrove-hydro-edaphics
R
false
false
528
r
wide.form <- function(group.by, spread.by, values, fill = 0 , prop = FALSE, prune = TRUE){ sum.mat <- tapply(values, list(group.by, spread.by), sum) sum.mat[is.na(sum.mat)] = fill if(prune){ sum.mat <- sum.mat[rowSums(sum.mat) > 0, colSums(sum.mat) > 0] } if(prop){ sum.mat = prop.table(sum.mat, 1) } return(sum.mat) }
#' Check matches of reported project (PROJ) codes in SMHIs codelist #' @param data for tibble be be checked #' @return unmatched codes with true or false results #' @export check_code_proj <- function(data) { toMatch <- unique(data$sample_project_name_sv) shark_codes <- read_delim(system.file("extdata", "codelist_SMHI.txt", package = "SHARK4R"), skip = 1, delim ="\t", guess_max = 2000, col_names = T, locale = readr::locale(encoding = "latin1")) shark_proj_codes <- shark_codes %>% filter(Data_field == "PROJ") match_type <- toMatch %in% shark_proj_codes$`Description/English translate` matches <- data.frame(reported_PROJ_code = unique(data$sample_project_name_sv), match_type = match_type) if (length(which(match_type == FALSE)) > 0) { message("ERROR: Unmatched Project (PROJ) code found") print(matches[!match_type,]) } else { message("All project (PROJ) codes found") } }
/R/check_codes.R
permissive
sharksmhi/SHARK4R
R
false
false
948
r
#' Check matches of reported project (PROJ) codes in SMHIs codelist #' @param data for tibble be be checked #' @return unmatched codes with true or false results #' @export check_code_proj <- function(data) { toMatch <- unique(data$sample_project_name_sv) shark_codes <- read_delim(system.file("extdata", "codelist_SMHI.txt", package = "SHARK4R"), skip = 1, delim ="\t", guess_max = 2000, col_names = T, locale = readr::locale(encoding = "latin1")) shark_proj_codes <- shark_codes %>% filter(Data_field == "PROJ") match_type <- toMatch %in% shark_proj_codes$`Description/English translate` matches <- data.frame(reported_PROJ_code = unique(data$sample_project_name_sv), match_type = match_type) if (length(which(match_type == FALSE)) > 0) { message("ERROR: Unmatched Project (PROJ) code found") print(matches[!match_type,]) } else { message("All project (PROJ) codes found") } }
## Predicting with Regression Multiple Covariates library(ISLR); library(ggplot2); library(caret); data(Wage); Wage <- subset(Wage, select =- c(logwage)) # remove column logwage which we will predict summary(Wage) # getting training/test sets inTrain <- createDataPartition(y=Wage$wage, p=0.7, list=FALSE) training <- Wage[inTrain,]; testing <- Wage[-inTrain,] dim(training); dim(testing) # Feature Plot featurePlot(x=training[,c("age", "education", "jobclass")], y=training$wage, plot="pairs") # plot age versus wage qplot(age, wage, data=training) # plot age versus wage color by jobclass qplot(age, wage, color=jobclass, data=training) # plot age versus wage color by education qplot(age, wage, color= education, data=training) # fit a linear model modelFit <- train(wage ~ age + jobclass + education, method="lm", data=training) modelFit finModel <- modelFit$finalModel finModel # Diagnostics plot(finModel, # plot the predicted values vs the residuals, outliers will be plotted too. 1, # this 1 uses the plot1. other numbers fill give you other plots pch=18,cex=0.5,col="#00000010") # color by variables which are not used in the model qplot(finModel$fitted, finModel $residuals, color=race, data=training) # plot by index plot(finModel$residuals,pch=19) # if you see a trend, it means there is a vriable that you're missing. something that rows are order by # predicted versus truth in test set pred <- predict(modelFit, testing) qplot(wage,pred,color=year,data=testing) # if you want all the covariates in your model modelFitAll <- train(wage ~ .,data=training,method="lm") pred <- predict(modelFitAll, testing) qplot(wage,pred,data=testing)
/weekly-practices/week2_part7_multivariate_regression.r
no_license
branjbar/practical-ML-R
R
false
false
1,682
r
## Predicting with Regression Multiple Covariates library(ISLR); library(ggplot2); library(caret); data(Wage); Wage <- subset(Wage, select =- c(logwage)) # remove column logwage which we will predict summary(Wage) # getting training/test sets inTrain <- createDataPartition(y=Wage$wage, p=0.7, list=FALSE) training <- Wage[inTrain,]; testing <- Wage[-inTrain,] dim(training); dim(testing) # Feature Plot featurePlot(x=training[,c("age", "education", "jobclass")], y=training$wage, plot="pairs") # plot age versus wage qplot(age, wage, data=training) # plot age versus wage color by jobclass qplot(age, wage, color=jobclass, data=training) # plot age versus wage color by education qplot(age, wage, color= education, data=training) # fit a linear model modelFit <- train(wage ~ age + jobclass + education, method="lm", data=training) modelFit finModel <- modelFit$finalModel finModel # Diagnostics plot(finModel, # plot the predicted values vs the residuals, outliers will be plotted too. 1, # this 1 uses the plot1. other numbers fill give you other plots pch=18,cex=0.5,col="#00000010") # color by variables which are not used in the model qplot(finModel$fitted, finModel $residuals, color=race, data=training) # plot by index plot(finModel$residuals,pch=19) # if you see a trend, it means there is a vriable that you're missing. something that rows are order by # predicted versus truth in test set pred <- predict(modelFit, testing) qplot(wage,pred,color=year,data=testing) # if you want all the covariates in your model modelFitAll <- train(wage ~ .,data=training,method="lm") pred <- predict(modelFitAll, testing) qplot(wage,pred,data=testing)
#Attempting to split UK map into 1km x 1km squares on a raster library(ggplot2) library(raster) library(sp) #My usual map #Using cleann gg1 <- ggplot() + geom_polygon(data = uk, aes(x = long, y = lat, group = group), fill = "white", color = "black") + #Add in counties if needed geom_polygon(data = gadm, aes(x = long, y = lat, group = group), fill = NA, color = "black") + geom_polygon(data = gadmireland, aes(x = long, y = lat, group = group), fill = NA, color = "black") + coord_fixed(1.3) #Adds long and lat points points <- data.frame( long = cleaneddata$Longitude, lat = cleaneddata$Latitude, Name.Current.Sci = cleaneddata$Name.Current.Sci ) #Plotting lats and longs gg1 + geom_point(data = longlat, aes(x = points, y = lat), color = "red", size = 0.5) + geom_point(data = longlat, aes(x = points, y = lat), color = "red", size = 0.5) + #over(geom_polygon(data = UKmap_utm, aes(x=long, y=lat, group=group), fill=NA, color="black")) + geom_path(sq_grid, border = "orange", add = TRUE) + coord_map(xlim=c(-11,3), ylim=c(49,60.9)) ########### library(dplyr) #This just plots a part of Scotland.... study_area <- Britain %>% disaggregate %>% geometry study_area <- sapply(study_area@polygons, slot, "area") %>% {which(. == max(.))} %>% study_area[.] plot(study_area, col = "grey50", bg = "light blue",xlim=c(-11,3), ylim=c(49,60.9)) text(11, 60.9, "Study Area:\nUnited Kingdom") Britain <- c(UKmap, IRmap) #Plots hexagons of 0.5 size <- 0.3 hex_points <- spsample(UKmap, type = "hexagonal", cellsize = size) hex_grid <- HexPoints2SpatialPolygons(hex_points, dx = size) plot(UKmap, col = "grey50", bg = "light blue", axes = TRUE) plot(hex_points, col = "black", pch = 20, cex = 0.5, add = T) plot(hex_grid, border = "orange", add = T) #Function for making maps with square or hexagonal grids as required make_grid <- function(x, type, cell_width, cell_area, clip = FALSE) { if (!type %in% c("square", "hexagonal")) { stop("Type must be either 'square' or 'hexagonal'") } if (missing(cell_width)) { if (missing(cell_area)) { stop("Must provide cell_width or cell_area") } else { if (type == "square") { cell_width <- sqrt(cell_area) } else if (type == "hexagonal") { cell_width <- sqrt(2 * cell_area / sqrt(3)) } } } # buffered extent of study area to define cells over ext <- as(extent(x) + cell_width, "SpatialPolygons") projection(ext) <- projection(x) # generate grid if (type == "square") { g <- raster(ext, resolution = cell_width) g <- as(g, "SpatialPolygons") } else if (type == "hexagonal") { # generate array of hexagon centers g <- spsample(ext, type = "hexagonal", cellsize = cell_width, offset = c(0, 0)) # convert center points to hexagons g <- HexPoints2SpatialPolygons(g, dx = cell_width) } # clip to boundary of study area if (clip) { g <- gIntersection(g, x, byid = TRUE) } else { g <- g[x, ] } # clean up feature IDs row.names(g) <- as.character(1:length(g)) return(g) } #Square maps install.packages("rgeos") library(rgeos) UKmap_utm <- CRS("+proj=utm +zone=44 +datum=WGS84 +units=km +no_defs") %>% spTransform(UKmap, .) IRmap_utm <- CRS("+proj=utm +zone=44 +datum=WGS84 +units=km +no_defs") %>% spTransform(IRmap, .) points_utm <- CRS("+proj=utm +zone=44 +datum=WGS84 +units=km +no_defs") %>% spTransform(points, .) #Square cells sq_grid <- make_grid(UKmap_utm, type = "square", cell_area = 625, clip = FALSE) plot(UKmap_utm, col = "grey50", bg = "light blue", axes = FALSE) plot(sq_grid, border = "orange", add = TRUE) overlay(points) box() geom_point(longlat) ################################# library(rgdal) library(sp) sp_poly <- CRS("+proj=longlat +zone=44 +datum=WGS84 +units=km +no_defs") # set coordinate reference system with SpatialPolygons(..., proj4string=CRS(...)) # e.g. CRS("+proj=longlat +datum=WGS84") sp_poly_df <- SpatialPolygonsDataFrame(sp_poly, data=data.frame(ID=1)) writeOGR(sp_poly_df, "points", layer="points", driver="ESRI Shapefile") install.packages("config") library(config) GB <- getData(name = "GADM", country = "GB", level = 0) %>% disaggregate %>% geometry # exclude gapalapos GB <- sapply(GB@polygons, slot, "area") %>% {which(. == max(.))} %>% GB[.] # albers equal area for Great Britain GB <- spTransform(GB, CRS( paste("+proj=aea +lat_1=-5 +lat_2=-42 +lat_0=-32 +lon_0=-60", "+x_0=0 +y_0=0 +ellps=aust_SA +units=km +no_defs"))) hex_gb <- make_grid(GB, type = "hexagonal", cell_area = 2500, clip = FALSE) #families = name #family = species #bird_families = categories fill_missing <- expand.grid(id = row.names(hex_gb), family = points, stringsAsFactors = FALSE) point_density <- overlay(hex_gb, longlat, returnList = TRUE) %>% plyr::ldply(.fun = function(x) x, .id = "id") %>% mutate(id = as.character(id)) %>% count(id, points) %>% left_join(fill_missing, ., by = c("id", "family")) %>% # log transform mutate(n = ifelse(is.na(n), -1, log10(n))) %>% spread(points, n, fill = -1) %>% SpatialPolygonsDataFrame(hex_gb, .) spplot(point_density, points, main = "Ecuador eBird Sightings by Family", col.regions = c("grey20", viridis(255)), colorkey = list( space = "bottom", at = c(-0.1, seq(0, log10(1200), length.out = 255)), labels = list( at = c(-0.1, log10(c(1, 5, 25, 75, 250, 1200))), labels = c(0, 1, 5, 25, 75, 250, 1200) ) ), xlim = bbexpand(bbox(point_density)[1, ], 0.04), ylim = bbexpand(bbox(point_density)[2, ], 0.04), par.strip.text = list(col = "white"), par.settings = list( strip.background = list(col = "grey40")) )
/maps/Rasters.R
permissive
EllenJCoombs/cetacean-strandings-project
R
false
false
5,764
r
#Attempting to split UK map into 1km x 1km squares on a raster library(ggplot2) library(raster) library(sp) #My usual map #Using cleann gg1 <- ggplot() + geom_polygon(data = uk, aes(x = long, y = lat, group = group), fill = "white", color = "black") + #Add in counties if needed geom_polygon(data = gadm, aes(x = long, y = lat, group = group), fill = NA, color = "black") + geom_polygon(data = gadmireland, aes(x = long, y = lat, group = group), fill = NA, color = "black") + coord_fixed(1.3) #Adds long and lat points points <- data.frame( long = cleaneddata$Longitude, lat = cleaneddata$Latitude, Name.Current.Sci = cleaneddata$Name.Current.Sci ) #Plotting lats and longs gg1 + geom_point(data = longlat, aes(x = points, y = lat), color = "red", size = 0.5) + geom_point(data = longlat, aes(x = points, y = lat), color = "red", size = 0.5) + #over(geom_polygon(data = UKmap_utm, aes(x=long, y=lat, group=group), fill=NA, color="black")) + geom_path(sq_grid, border = "orange", add = TRUE) + coord_map(xlim=c(-11,3), ylim=c(49,60.9)) ########### library(dplyr) #This just plots a part of Scotland.... study_area <- Britain %>% disaggregate %>% geometry study_area <- sapply(study_area@polygons, slot, "area") %>% {which(. == max(.))} %>% study_area[.] plot(study_area, col = "grey50", bg = "light blue",xlim=c(-11,3), ylim=c(49,60.9)) text(11, 60.9, "Study Area:\nUnited Kingdom") Britain <- c(UKmap, IRmap) #Plots hexagons of 0.5 size <- 0.3 hex_points <- spsample(UKmap, type = "hexagonal", cellsize = size) hex_grid <- HexPoints2SpatialPolygons(hex_points, dx = size) plot(UKmap, col = "grey50", bg = "light blue", axes = TRUE) plot(hex_points, col = "black", pch = 20, cex = 0.5, add = T) plot(hex_grid, border = "orange", add = T) #Function for making maps with square or hexagonal grids as required make_grid <- function(x, type, cell_width, cell_area, clip = FALSE) { if (!type %in% c("square", "hexagonal")) { stop("Type must be either 'square' or 'hexagonal'") } if (missing(cell_width)) { if (missing(cell_area)) { stop("Must provide cell_width or cell_area") } else { if (type == "square") { cell_width <- sqrt(cell_area) } else if (type == "hexagonal") { cell_width <- sqrt(2 * cell_area / sqrt(3)) } } } # buffered extent of study area to define cells over ext <- as(extent(x) + cell_width, "SpatialPolygons") projection(ext) <- projection(x) # generate grid if (type == "square") { g <- raster(ext, resolution = cell_width) g <- as(g, "SpatialPolygons") } else if (type == "hexagonal") { # generate array of hexagon centers g <- spsample(ext, type = "hexagonal", cellsize = cell_width, offset = c(0, 0)) # convert center points to hexagons g <- HexPoints2SpatialPolygons(g, dx = cell_width) } # clip to boundary of study area if (clip) { g <- gIntersection(g, x, byid = TRUE) } else { g <- g[x, ] } # clean up feature IDs row.names(g) <- as.character(1:length(g)) return(g) } #Square maps install.packages("rgeos") library(rgeos) UKmap_utm <- CRS("+proj=utm +zone=44 +datum=WGS84 +units=km +no_defs") %>% spTransform(UKmap, .) IRmap_utm <- CRS("+proj=utm +zone=44 +datum=WGS84 +units=km +no_defs") %>% spTransform(IRmap, .) points_utm <- CRS("+proj=utm +zone=44 +datum=WGS84 +units=km +no_defs") %>% spTransform(points, .) #Square cells sq_grid <- make_grid(UKmap_utm, type = "square", cell_area = 625, clip = FALSE) plot(UKmap_utm, col = "grey50", bg = "light blue", axes = FALSE) plot(sq_grid, border = "orange", add = TRUE) overlay(points) box() geom_point(longlat) ################################# library(rgdal) library(sp) sp_poly <- CRS("+proj=longlat +zone=44 +datum=WGS84 +units=km +no_defs") # set coordinate reference system with SpatialPolygons(..., proj4string=CRS(...)) # e.g. CRS("+proj=longlat +datum=WGS84") sp_poly_df <- SpatialPolygonsDataFrame(sp_poly, data=data.frame(ID=1)) writeOGR(sp_poly_df, "points", layer="points", driver="ESRI Shapefile") install.packages("config") library(config) GB <- getData(name = "GADM", country = "GB", level = 0) %>% disaggregate %>% geometry # exclude gapalapos GB <- sapply(GB@polygons, slot, "area") %>% {which(. == max(.))} %>% GB[.] # albers equal area for Great Britain GB <- spTransform(GB, CRS( paste("+proj=aea +lat_1=-5 +lat_2=-42 +lat_0=-32 +lon_0=-60", "+x_0=0 +y_0=0 +ellps=aust_SA +units=km +no_defs"))) hex_gb <- make_grid(GB, type = "hexagonal", cell_area = 2500, clip = FALSE) #families = name #family = species #bird_families = categories fill_missing <- expand.grid(id = row.names(hex_gb), family = points, stringsAsFactors = FALSE) point_density <- overlay(hex_gb, longlat, returnList = TRUE) %>% plyr::ldply(.fun = function(x) x, .id = "id") %>% mutate(id = as.character(id)) %>% count(id, points) %>% left_join(fill_missing, ., by = c("id", "family")) %>% # log transform mutate(n = ifelse(is.na(n), -1, log10(n))) %>% spread(points, n, fill = -1) %>% SpatialPolygonsDataFrame(hex_gb, .) spplot(point_density, points, main = "Ecuador eBird Sightings by Family", col.regions = c("grey20", viridis(255)), colorkey = list( space = "bottom", at = c(-0.1, seq(0, log10(1200), length.out = 255)), labels = list( at = c(-0.1, log10(c(1, 5, 25, 75, 250, 1200))), labels = c(0, 1, 5, 25, 75, 250, 1200) ) ), xlim = bbexpand(bbox(point_density)[1, ], 0.04), ylim = bbexpand(bbox(point_density)[2, ], 0.04), par.strip.text = list(col = "white"), par.settings = list( strip.background = list(col = "grey40")) )
# Download if(!file.exists("./data")){dir.create("./Data")} fileUrl<-"https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip" if(!file.exists("./data/exdata_data_household_power_consumption.zip")) {download.file(fileUrl, "./Data/exdata_data_household_power_consumption.zip", mode="wb") } # Unzip the file if(!file.exists("./Data/household_power_consumption.txt")){ unzip("./Data/exdata_data_household_power_consumption.zip", files = NULL, exdir="./Data") } #Read the informtion from the file powerconsumition <- read.table("./Data/household_power_consumption.txt", sep=";", header=TRUE,colClasses = c('character', 'character', 'numeric', 'numeric', 'numeric', 'numeric', 'numeric', 'numeric', 'numeric'),na.strings="?") #Transform to Date powerconsumition$Date<-as.Date(powerconsumition$Date,"%d/%m/%Y") #Take information form 2007/02/01 and 2007/02/02 PWCD <- powerconsumition[ powerconsumition$Date=="2007-02-01" | powerconsumition$Date=="2007-02-02", ] # Plot 1 par(mfrow=c(1,1)) #Generate the histogram with(PWCD, hist(Global_active_power, col="red", main = "Global Active Power", xlab = "Global Active Power (kilowatts)", ylim = c(0, 1200))) #Generate the file dev.copy(png, file="Plot1.png") #close the PNG device dev.off()
/Plot1.R
no_license
monicatgs/ExData_Plotting1
R
false
false
1,315
r
# Download if(!file.exists("./data")){dir.create("./Data")} fileUrl<-"https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip" if(!file.exists("./data/exdata_data_household_power_consumption.zip")) {download.file(fileUrl, "./Data/exdata_data_household_power_consumption.zip", mode="wb") } # Unzip the file if(!file.exists("./Data/household_power_consumption.txt")){ unzip("./Data/exdata_data_household_power_consumption.zip", files = NULL, exdir="./Data") } #Read the informtion from the file powerconsumition <- read.table("./Data/household_power_consumption.txt", sep=";", header=TRUE,colClasses = c('character', 'character', 'numeric', 'numeric', 'numeric', 'numeric', 'numeric', 'numeric', 'numeric'),na.strings="?") #Transform to Date powerconsumition$Date<-as.Date(powerconsumition$Date,"%d/%m/%Y") #Take information form 2007/02/01 and 2007/02/02 PWCD <- powerconsumition[ powerconsumition$Date=="2007-02-01" | powerconsumition$Date=="2007-02-02", ] # Plot 1 par(mfrow=c(1,1)) #Generate the histogram with(PWCD, hist(Global_active_power, col="red", main = "Global Active Power", xlab = "Global Active Power (kilowatts)", ylim = c(0, 1200))) #Generate the file dev.copy(png, file="Plot1.png") #close the PNG device dev.off()
#Postgres setwd("C:/R") library("RJDBC") library("readxl") library("arules") library("stringr") library("reshape2") library("tidyr") library("dplyr") library("mclust") library(arulesViz) library(igraph) library("data.table") library("reshape2") options("scipen"=999, "digits"=19) rs <- read.table(file = "awsrs.txt", sep = ",", stringsAsFactors = FALSE) driver <- JDBC(driverClass = "..", classPath = "C:/R/..", identifier.quote="`") oldurl <- rs$V1 conn <- dbConnect(driver, oldurl) rm(rs) #advanced pixel data from <- '2018-01-07' to <- Sys.Date() #query query <- paste("select * from Archit_client_converts_retain where dt>='",from,"'and dt<='", to,"'") client_base <- unique(dbGetQuery(conn,query)) # #mapping # mapping1 <- client_base[,c(4,5)] # sku1 <- str_split_fixed(string=mapping1$u2,pattern = ",",n=10) # sku_prod <- str_split_fixed(string=mapping1$u5,pattern = ",",n=10) # # sku_df <- data.frame(sku1) # sku_df$id <- row_number(sku_df$X1) # sku_melted <- melt(sku_df,id.vars = "id") # sku_melted <- filter(sku_melted,!(value=="")) # # # sku_prod_df <- data.frame(sku_prod) # sku_prod_df$id <- row_number(sku_prod_df$X1) # sku_prod_melted <- melt(sku_prod_df,id.vars = "id") # sku_prod_melted <- filter(sku_prod_melted,!(value=="")) # # mapping_new <- data.frame(cbind(sku_melted$value,sku_prod_melted$value)) #number of products #Trimming trim <- function (x) gsub("^\\s+|\\s+$", "", x) k <- max(str_count(client_base$u7,",")) #seperating products client_products_sep <- str_split_fixed(string = client_base$u7, pattern = ",", n = k) #converting into dataframe client_products_df <- as.data.frame(trim(client_products_sep)) # Adding Transaction ID client_products_df <- client_products_df %>% mutate(transaction_id = row_number()) #converting wide to long format client_products_final <- melt(client_products_df, variable.name = "Key", value.name = "Product", id.vars = "transaction_id") client_products_final <- melt(kk, variable.name = "Key", value.name = "kws", id.vars = "conc") # Filter for rows blank entries client_products_final <- client_products_final %>% filter(Product != "") # De-duping for order client_products_final <- client_products_final %>% distinct(transaction_id, Product) #converting to factors for transaction client_products_final$transaction_id <- as.factor(client_products_final$transaction_id) client_products_final$Product <- as.factor(client_products_final$Product) #save workspace # save.image("Market Basket Analysis.Rdata") # load("Market Basket Analysis.Rdata") #cleaning DFs from environment rm(DFS_products_df) #Sample splitting client_products_final_basketsplit <- split(client_products_final$Product, client_products_final$transaction_id) client_txn <- as(client_products_final_basketsplit,"transactions") basket_rules <- apriori(client_txn, parameter = list(sup = 0.002, conf = 0.1, target="rules", minlen=2)) #checking freqplot itemFrequencyPlot(client_txn, topN = 5) #writing to csv x<-data.frame(inspect(basket_rules)) write.csv(x,"client2.csv") #visualization #plot1 y <- plot(basket_rules,method="graph",interactive=TRUE,shading=NA) #Plot2 plot(basket_rules, method = "graph", measure = "lift",control = NULL) #Plot3 subrules2 <- head(sort(basket_rules, by="lift"), 10) plot(subrules2, method="graph")
/Market Basket Analysis.R
no_license
Architsi/Ecommerce
R
false
false
3,709
r
#Postgres setwd("C:/R") library("RJDBC") library("readxl") library("arules") library("stringr") library("reshape2") library("tidyr") library("dplyr") library("mclust") library(arulesViz) library(igraph) library("data.table") library("reshape2") options("scipen"=999, "digits"=19) rs <- read.table(file = "awsrs.txt", sep = ",", stringsAsFactors = FALSE) driver <- JDBC(driverClass = "..", classPath = "C:/R/..", identifier.quote="`") oldurl <- rs$V1 conn <- dbConnect(driver, oldurl) rm(rs) #advanced pixel data from <- '2018-01-07' to <- Sys.Date() #query query <- paste("select * from Archit_client_converts_retain where dt>='",from,"'and dt<='", to,"'") client_base <- unique(dbGetQuery(conn,query)) # #mapping # mapping1 <- client_base[,c(4,5)] # sku1 <- str_split_fixed(string=mapping1$u2,pattern = ",",n=10) # sku_prod <- str_split_fixed(string=mapping1$u5,pattern = ",",n=10) # # sku_df <- data.frame(sku1) # sku_df$id <- row_number(sku_df$X1) # sku_melted <- melt(sku_df,id.vars = "id") # sku_melted <- filter(sku_melted,!(value=="")) # # # sku_prod_df <- data.frame(sku_prod) # sku_prod_df$id <- row_number(sku_prod_df$X1) # sku_prod_melted <- melt(sku_prod_df,id.vars = "id") # sku_prod_melted <- filter(sku_prod_melted,!(value=="")) # # mapping_new <- data.frame(cbind(sku_melted$value,sku_prod_melted$value)) #number of products #Trimming trim <- function (x) gsub("^\\s+|\\s+$", "", x) k <- max(str_count(client_base$u7,",")) #seperating products client_products_sep <- str_split_fixed(string = client_base$u7, pattern = ",", n = k) #converting into dataframe client_products_df <- as.data.frame(trim(client_products_sep)) # Adding Transaction ID client_products_df <- client_products_df %>% mutate(transaction_id = row_number()) #converting wide to long format client_products_final <- melt(client_products_df, variable.name = "Key", value.name = "Product", id.vars = "transaction_id") client_products_final <- melt(kk, variable.name = "Key", value.name = "kws", id.vars = "conc") # Filter for rows blank entries client_products_final <- client_products_final %>% filter(Product != "") # De-duping for order client_products_final <- client_products_final %>% distinct(transaction_id, Product) #converting to factors for transaction client_products_final$transaction_id <- as.factor(client_products_final$transaction_id) client_products_final$Product <- as.factor(client_products_final$Product) #save workspace # save.image("Market Basket Analysis.Rdata") # load("Market Basket Analysis.Rdata") #cleaning DFs from environment rm(DFS_products_df) #Sample splitting client_products_final_basketsplit <- split(client_products_final$Product, client_products_final$transaction_id) client_txn <- as(client_products_final_basketsplit,"transactions") basket_rules <- apriori(client_txn, parameter = list(sup = 0.002, conf = 0.1, target="rules", minlen=2)) #checking freqplot itemFrequencyPlot(client_txn, topN = 5) #writing to csv x<-data.frame(inspect(basket_rules)) write.csv(x,"client2.csv") #visualization #plot1 y <- plot(basket_rules,method="graph",interactive=TRUE,shading=NA) #Plot2 plot(basket_rules, method = "graph", measure = "lift",control = NULL) #Plot3 subrules2 <- head(sort(basket_rules, by="lift"), 10) plot(subrules2, method="graph")
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/amaretto_htmlreport.R \name{readGMT} \alias{readGMT} \title{readGMT} \usage{ readGMT(filename) } \arguments{ \item{filename}{} } \description{ readGMT } \keyword{internal}
/man/readGMT.Rd
permissive
liefeld/AMARETTO
R
false
true
250
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/amaretto_htmlreport.R \name{readGMT} \alias{readGMT} \title{readGMT} \usage{ readGMT(filename) } \arguments{ \item{filename}{} } \description{ readGMT } \keyword{internal}
##Shape=vector point ##Rinde=field Shape ##output_plots_to_html ##showplots ##inliers=output vector library(sp) library(spdep) crs_imagen<-st_crs(Shape) filtro1 <- as_Spatial(Shape) cord <- filtro1@coords gri <- dnearneigh(cord,0,30) lw <- nb2listw(gri, style = "W",zero.policy=TRUE) par(mfrow=c(1,1)) ML <- localmoran (filtro1@data[,Rinde], lw, p.adjust.method="bonferroni",alternative ="less",zero.policy=TRUE) MP <- moran.plot(filtro1@data[,Rinde],lw,quiet=T,labels=F,col=3,zero.policy=T,xlab="Rendimiento", ylab="Rendimiento Spatially Lagged") Influ <- MP$is.inf ; datos0 <- data.frame(filtro1@data,filtro1@coords,ML,Influ) #eliminacion de datos con ?ndice de Moran Local negativo y estad?sticamente significativos (p<0.05). datos1 <- subset(datos0,datos0$Ii > 0 | datos0$Pr.z...0.>0.05) myshp.inlier<- subset(datos0,datos0$Ii < 0 | datos0$Pr.z...0.<0.05) datos2 <- datos1[datos1$dfb.1_ == FALSE & datos1$dfb.x == FALSE & datos1$dffit == FALSE & datos1$cov.r == FALSE & datos1$cook.d == FALSE & datos1$hat == FALSE, ] >print("--------------------------------------------------------") >str(datos2) datos3<-data.frame(datos2[Rinde],datos2["coords.x1"],datos2["coords.x2"]) coordinates(datos2)<-c("coords.x1","coords.x2") output <-sf::st_as_sf(datos3, coords = c("coords.x1", "coords.x2"),crs= crs_imagen) n<-nrow(filtro1@data[Rinde])-nrow(datos3[Rinde]) >print(paste("Se filtraron",n,"puntos")) inliers = output
/Ambientacion multivariado_inliers.rsx
no_license
francofrolla/ambientes_qgis
R
false
false
1,469
rsx
##Shape=vector point ##Rinde=field Shape ##output_plots_to_html ##showplots ##inliers=output vector library(sp) library(spdep) crs_imagen<-st_crs(Shape) filtro1 <- as_Spatial(Shape) cord <- filtro1@coords gri <- dnearneigh(cord,0,30) lw <- nb2listw(gri, style = "W",zero.policy=TRUE) par(mfrow=c(1,1)) ML <- localmoran (filtro1@data[,Rinde], lw, p.adjust.method="bonferroni",alternative ="less",zero.policy=TRUE) MP <- moran.plot(filtro1@data[,Rinde],lw,quiet=T,labels=F,col=3,zero.policy=T,xlab="Rendimiento", ylab="Rendimiento Spatially Lagged") Influ <- MP$is.inf ; datos0 <- data.frame(filtro1@data,filtro1@coords,ML,Influ) #eliminacion de datos con ?ndice de Moran Local negativo y estad?sticamente significativos (p<0.05). datos1 <- subset(datos0,datos0$Ii > 0 | datos0$Pr.z...0.>0.05) myshp.inlier<- subset(datos0,datos0$Ii < 0 | datos0$Pr.z...0.<0.05) datos2 <- datos1[datos1$dfb.1_ == FALSE & datos1$dfb.x == FALSE & datos1$dffit == FALSE & datos1$cov.r == FALSE & datos1$cook.d == FALSE & datos1$hat == FALSE, ] >print("--------------------------------------------------------") >str(datos2) datos3<-data.frame(datos2[Rinde],datos2["coords.x1"],datos2["coords.x2"]) coordinates(datos2)<-c("coords.x1","coords.x2") output <-sf::st_as_sf(datos3, coords = c("coords.x1", "coords.x2"),crs= crs_imagen) n<-nrow(filtro1@data[Rinde])-nrow(datos3[Rinde]) >print(paste("Se filtraron",n,"puntos")) inliers = output
# Matthew Smith, 12/2/18 # In this file, we create all the necessary functions to implement a sparse.matrix class #' Construct a sparse.matrix Object #' #' @description This functions creates an instance of the sparse.matrix object from scratch as a data.frame. By default, the dimensions will be the largest coordinates. #' @param i A vector of row indeces of the non-zero entries of the sparse.matrix #' @param j A vector of column indeces of the non-zero entries of the sparse.matrix #' @param x A vector of values for the non-zero entries of the sparse.matrix #' @param dims A vector of the desired dimensions of the sparse.matrix. By default, these are the largest coordinates #' @return A sparse.matrix object, which is a list of a data.frame with a column i of row indeces, a column j of column indeces, and a column x of values for non-zero entries; and a vector of dimensions #' @examples #' a <- sparse.matrix(i=c(1,2), j=c(1,1), x=c(3,1)) #' @export sparse.matrix <- function(i, j, x, dims=c(max(i), max(j))){ if(length(i) != length(j) || length(j) != length(x) || length(x) != length(i)){ stop("Unequal lengths of parameters. The number of rows (i), columns (j), and values (x) should be equivalent.") } ret <- list(entries=data.frame(i=i, j=j, x=x), dims=dims) #Store all of the information in a list of a data.frame and a vector class(ret) <- "sparse.matrix" #Make "sparse.matrix" the class of the return object ret #Return the updated vals object } #' Add Together Two sparse.matrix Objects #' #' @description This method implements the sparse_add function from class for our new sparse.matrix object #' @param a A sparse.matrix object #' @param b A sparse.matrix object #' @return A sparse.matrix that is the sum of a and b #' @examples #' a <- sparse.matrix(i=c(1,2), j=c(1,1), x=c(3,1), dims=c(3,2)) #' b <- sparse.matrix(i=c(1,2,3), j=c(1,1,2), x=c(4.4,1.2,3)) #' a + b #' @export `+.sparse.matrix` <- function(a, b){ #We use the tick marks because + is an infix operator. We do not need the generic function because + already exists as a method in R if(!inherits(b, "sparse.matrix")){ #The S3 dispatch method only checks that a is a sparse.matrix when calling this method, so here we check that b is as well stop("The object b is not a sparse.matrix.") } if(sum(a$dims != b$dims) > 0){ #We cannot add together two matrices that are not of the same dimensions stop("The sparse.matrices must have the same dimensions.") } c <- merge(a$entries, b$entries, by=c("i","j"), all=TRUE, suffixes=c("1","2")) #Merge the entries of a and b by the rows (i) and columns (j) of non-zero values c$x1[is.na(c$x1)] <- 0 #Fill in the missing values with 0 for the sum c$x2[is.na(c$x2)] <- 0 #Fill in the missing values with 0 for the sum c$x <- c$x1 + c$x2 #Take the sum of the entries for the two sparse.matrix's c <- c[, c("i", "j", "x")] #Keep the columns of c corresponding to the rows (i), columns (j), and values (x) of the non-zero entries of the resulting sparse.matrix ret <- list(entries=c, dims=a$dims) #Create the return object as a list class(ret) <- "sparse.matrix" #Set the class of the return object to be a sparse.matrix # A hack because of bad testing. ret$entries <- ret$entries[order(ret$entries$j),] rownames(ret$entries) <- seq_len(nrow(ret$entries)) ret } # To implement the matrix multiplication of sparse.matrix objects, we define the generic function for %*% and a default function #' @export `%*%` <- function(a, b){ UseMethod("%*%", a) } #' @export `%*%.default` <- function(a, b){ .Primitive("%*%")(a, b) } #' Matrix-Multiply Two sparse.matrix Objects #' #' @description This method is the implementation of the sparse_multiply from the homework. It matrix-multiplies two sparse.matrix objects. #' @param a A sparse.matrix object #' @param b A sparse.matrix object #' @return A sparse.matrix object that is the matrix multiple of a and b #' @examples #' a <- sparse.matrix(i=c(1,2), j=c(1,1), x=c(3,1)) #' b <- sparse.matrix(i=c(1,2,3), j=c(1,1,2), x=c(4.4,1.2,3)) #' b %*% a #' @export `%*%.sparse.matrix` <- function(a, b){ #We use the tick marks because %*% is an infix operator #browser() if(!inherits(b, "sparse.matrix")){ #The S3 dispatch method only checks that a is a sparse.matrix when calling this method, so here we check that b is as well stop("The object b is not a sparse.matrix.") } if(a$dims[2] != b$dims[1]){ #The number of columns of the first sparse.matrix must equal the number of rows of the second in order for multiplication to be defined stop("The number of columns of the first sparse.matrix must equal the number of rows of the second.") } # Since the rows of a determine the rows of the product and the columns of b determine the columns of the product, we must find the unique indeces of the rows of a and columns of b unique_rows <- unique(a$entries$i) #A vector of all the unique row indeces for non-zero entries of a unique_cols <- unique(b$entries$j) #A vector of all the unique column indeces for non-zero entries of b # Each entry of the product matrix c is the inner product (or dot product) of a row of a and a column of b # The dot product of row i of a (a[i,]) and column j of b (b([,j])) can only be non-zero if there is at least one shared index k for non-zero entries in a[i,] and b[,j] # That is, there is a value k such that a[i,k] and b[k,j] is not zero # If we only take the dot products for these shared indeces, we can avoid unnecessary calculations c <- data.frame(i=integer(), j=integer(), x=double()) #We initialize c as an empty data.frame for(i in unique_rows){ #Each row of a determines the rows of the product matrix c a_i <- a$entries[which(a$entries$i==i),] #Takes the ith row of a by finding all of the rows of the data.frame that have i as the i-value for(j in unique_cols){ #Each column of b determines the columns of the product matrix c b_j <- b$entries[which(b$entries$j==j),] #Takes the jth column of b by finding all of the rows of the data.frame that have j as the j-value k_vector <- intersect(a_i$j, b_j$i) #A vector of of the shared indeces for the columns of a[i,] and rows of b[,j] if(length(k_vector) > 0){ #If there is at least one overlap # To find where in a_i and b_j these indeces occur, we name their rows row.names(a_i) <- a_i$j row.names(b_j) <- b_j$i # We take the inner product (dot product) of row a_i and column b_j, but only for the indeces k_vector c_new <- as.numeric( t(as.matrix(a_i[as.character(k_vector),"x"])) %*% as.matrix(b_j[as.character(k_vector),"x"])) # We lastly append this new row to c c <- rbind(c, c(i, j, c_new)) } } } colnames(c) <- c("i", "j", "x") #We reset the column names of the product c ret <- list(entries=c, dims=c(a$dims[1], b$dims[2])) #We create the return object as a list, using the proper dimensions class(ret) <- "sparse.matrix" #Set the class of the return object to be a sparse.matrix # A hack because of bad testing. ret$entries <- ret$entries[order(ret$entries$j),] rownames(ret$entries) <- seq_len(nrow(ret$entries)) ret } #' Transpose a sparse.matrix Object #' #' @description This method transposes a sparse.matrix object. Since we only record the non-zero entries in a sparse.matrix, all we need to do is reverse those entries' row and column indeces, as well as the dimensions. #' @param a A sparse.matrix object #' @return A sparse.matrix object that is the matrix transpose of a #' @import Matrix #' @examples #' a <- sparse.matrix(i=c(1,2), j=c(1,1), x=c(3,1)) #' t(a) #' @export t.sparse.matrix <- function(a){ #We initialize the t() method for the sparse.matrix class. We do not need the generic function because t() already exists as a method in R a_t <- a$entries #Create the a data.frame of the entries that will be the transpose from the input a a_t$i <- a$entries$j #Replace the row indeces with the original column indeces a_t$j <- a$entries$i #Replace the column indeces with the original row indeces ret <- list(entries=a_t, dims=c(a$dims[2], a$dims[1])) #We create the return object as a list and change the dimensions class(ret) <- "sparse.matrix" #Set the class of the return object to be a sparse.matrix ret }
/R/sparse.matrix_class.R
no_license
r-medicine/bis557
R
false
false
8,344
r
# Matthew Smith, 12/2/18 # In this file, we create all the necessary functions to implement a sparse.matrix class #' Construct a sparse.matrix Object #' #' @description This functions creates an instance of the sparse.matrix object from scratch as a data.frame. By default, the dimensions will be the largest coordinates. #' @param i A vector of row indeces of the non-zero entries of the sparse.matrix #' @param j A vector of column indeces of the non-zero entries of the sparse.matrix #' @param x A vector of values for the non-zero entries of the sparse.matrix #' @param dims A vector of the desired dimensions of the sparse.matrix. By default, these are the largest coordinates #' @return A sparse.matrix object, which is a list of a data.frame with a column i of row indeces, a column j of column indeces, and a column x of values for non-zero entries; and a vector of dimensions #' @examples #' a <- sparse.matrix(i=c(1,2), j=c(1,1), x=c(3,1)) #' @export sparse.matrix <- function(i, j, x, dims=c(max(i), max(j))){ if(length(i) != length(j) || length(j) != length(x) || length(x) != length(i)){ stop("Unequal lengths of parameters. The number of rows (i), columns (j), and values (x) should be equivalent.") } ret <- list(entries=data.frame(i=i, j=j, x=x), dims=dims) #Store all of the information in a list of a data.frame and a vector class(ret) <- "sparse.matrix" #Make "sparse.matrix" the class of the return object ret #Return the updated vals object } #' Add Together Two sparse.matrix Objects #' #' @description This method implements the sparse_add function from class for our new sparse.matrix object #' @param a A sparse.matrix object #' @param b A sparse.matrix object #' @return A sparse.matrix that is the sum of a and b #' @examples #' a <- sparse.matrix(i=c(1,2), j=c(1,1), x=c(3,1), dims=c(3,2)) #' b <- sparse.matrix(i=c(1,2,3), j=c(1,1,2), x=c(4.4,1.2,3)) #' a + b #' @export `+.sparse.matrix` <- function(a, b){ #We use the tick marks because + is an infix operator. We do not need the generic function because + already exists as a method in R if(!inherits(b, "sparse.matrix")){ #The S3 dispatch method only checks that a is a sparse.matrix when calling this method, so here we check that b is as well stop("The object b is not a sparse.matrix.") } if(sum(a$dims != b$dims) > 0){ #We cannot add together two matrices that are not of the same dimensions stop("The sparse.matrices must have the same dimensions.") } c <- merge(a$entries, b$entries, by=c("i","j"), all=TRUE, suffixes=c("1","2")) #Merge the entries of a and b by the rows (i) and columns (j) of non-zero values c$x1[is.na(c$x1)] <- 0 #Fill in the missing values with 0 for the sum c$x2[is.na(c$x2)] <- 0 #Fill in the missing values with 0 for the sum c$x <- c$x1 + c$x2 #Take the sum of the entries for the two sparse.matrix's c <- c[, c("i", "j", "x")] #Keep the columns of c corresponding to the rows (i), columns (j), and values (x) of the non-zero entries of the resulting sparse.matrix ret <- list(entries=c, dims=a$dims) #Create the return object as a list class(ret) <- "sparse.matrix" #Set the class of the return object to be a sparse.matrix # A hack because of bad testing. ret$entries <- ret$entries[order(ret$entries$j),] rownames(ret$entries) <- seq_len(nrow(ret$entries)) ret } # To implement the matrix multiplication of sparse.matrix objects, we define the generic function for %*% and a default function #' @export `%*%` <- function(a, b){ UseMethod("%*%", a) } #' @export `%*%.default` <- function(a, b){ .Primitive("%*%")(a, b) } #' Matrix-Multiply Two sparse.matrix Objects #' #' @description This method is the implementation of the sparse_multiply from the homework. It matrix-multiplies two sparse.matrix objects. #' @param a A sparse.matrix object #' @param b A sparse.matrix object #' @return A sparse.matrix object that is the matrix multiple of a and b #' @examples #' a <- sparse.matrix(i=c(1,2), j=c(1,1), x=c(3,1)) #' b <- sparse.matrix(i=c(1,2,3), j=c(1,1,2), x=c(4.4,1.2,3)) #' b %*% a #' @export `%*%.sparse.matrix` <- function(a, b){ #We use the tick marks because %*% is an infix operator #browser() if(!inherits(b, "sparse.matrix")){ #The S3 dispatch method only checks that a is a sparse.matrix when calling this method, so here we check that b is as well stop("The object b is not a sparse.matrix.") } if(a$dims[2] != b$dims[1]){ #The number of columns of the first sparse.matrix must equal the number of rows of the second in order for multiplication to be defined stop("The number of columns of the first sparse.matrix must equal the number of rows of the second.") } # Since the rows of a determine the rows of the product and the columns of b determine the columns of the product, we must find the unique indeces of the rows of a and columns of b unique_rows <- unique(a$entries$i) #A vector of all the unique row indeces for non-zero entries of a unique_cols <- unique(b$entries$j) #A vector of all the unique column indeces for non-zero entries of b # Each entry of the product matrix c is the inner product (or dot product) of a row of a and a column of b # The dot product of row i of a (a[i,]) and column j of b (b([,j])) can only be non-zero if there is at least one shared index k for non-zero entries in a[i,] and b[,j] # That is, there is a value k such that a[i,k] and b[k,j] is not zero # If we only take the dot products for these shared indeces, we can avoid unnecessary calculations c <- data.frame(i=integer(), j=integer(), x=double()) #We initialize c as an empty data.frame for(i in unique_rows){ #Each row of a determines the rows of the product matrix c a_i <- a$entries[which(a$entries$i==i),] #Takes the ith row of a by finding all of the rows of the data.frame that have i as the i-value for(j in unique_cols){ #Each column of b determines the columns of the product matrix c b_j <- b$entries[which(b$entries$j==j),] #Takes the jth column of b by finding all of the rows of the data.frame that have j as the j-value k_vector <- intersect(a_i$j, b_j$i) #A vector of of the shared indeces for the columns of a[i,] and rows of b[,j] if(length(k_vector) > 0){ #If there is at least one overlap # To find where in a_i and b_j these indeces occur, we name their rows row.names(a_i) <- a_i$j row.names(b_j) <- b_j$i # We take the inner product (dot product) of row a_i and column b_j, but only for the indeces k_vector c_new <- as.numeric( t(as.matrix(a_i[as.character(k_vector),"x"])) %*% as.matrix(b_j[as.character(k_vector),"x"])) # We lastly append this new row to c c <- rbind(c, c(i, j, c_new)) } } } colnames(c) <- c("i", "j", "x") #We reset the column names of the product c ret <- list(entries=c, dims=c(a$dims[1], b$dims[2])) #We create the return object as a list, using the proper dimensions class(ret) <- "sparse.matrix" #Set the class of the return object to be a sparse.matrix # A hack because of bad testing. ret$entries <- ret$entries[order(ret$entries$j),] rownames(ret$entries) <- seq_len(nrow(ret$entries)) ret } #' Transpose a sparse.matrix Object #' #' @description This method transposes a sparse.matrix object. Since we only record the non-zero entries in a sparse.matrix, all we need to do is reverse those entries' row and column indeces, as well as the dimensions. #' @param a A sparse.matrix object #' @return A sparse.matrix object that is the matrix transpose of a #' @import Matrix #' @examples #' a <- sparse.matrix(i=c(1,2), j=c(1,1), x=c(3,1)) #' t(a) #' @export t.sparse.matrix <- function(a){ #We initialize the t() method for the sparse.matrix class. We do not need the generic function because t() already exists as a method in R a_t <- a$entries #Create the a data.frame of the entries that will be the transpose from the input a a_t$i <- a$entries$j #Replace the row indeces with the original column indeces a_t$j <- a$entries$i #Replace the column indeces with the original row indeces ret <- list(entries=a_t, dims=c(a$dims[2], a$dims[1])) #We create the return object as a list and change the dimensions class(ret) <- "sparse.matrix" #Set the class of the return object to be a sparse.matrix ret }
#' Compute similarity of matrices #' #' @param expr_mat single-cell expression matrix #' @param ref_mat reference expression matrix #' @param cluster_ids vector of cluster ids for each cell #' @param compute_method method(s) for computing similarity scores #' @param per_cell run per cell? #' @param rm0 consider 0 as missing data, recommended for per_cell #' @param if_log input data is natural log, #' averaging will be done on unlogged data #' @param low_threshold option to remove clusters with too few cells #' @param ... additional parameters not used yet #' @return matrix of numeric values, clusters from expr_mat as row names, #' cell types from ref_mat as column names get_similarity <- function(expr_mat, ref_mat, cluster_ids, compute_method, per_cell = FALSE, rm0 = FALSE, if_log = TRUE, low_threshold = 0, ...) { if (nrow(expr_mat) == 0) { stop("after subsetting to shared genes", "query expression matrix has 0 rows", call. = FALSE ) } if (ncol(expr_mat) == 0) { stop("query expression matrix has 0 cols", call. = FALSE ) } if (nrow(ref_mat) == 0) { stop("after subsetting to shared genes", "reference expression matrix has 0 rows", call. = FALSE ) } if (ncol(ref_mat) == 0) { stop("reference expression matrix has 0 cols", call. = FALSE ) } ref_clust <- colnames(ref_mat) if (ncol(expr_mat) != length(cluster_ids)) { stop("number of cells in expression matrix not equal", "to metadata/cluster_col", call. = FALSE ) } if (sum(is.na(cluster_ids)) > 0) { message("reassigning NAs to unknown") cluster_ids <- factor(cluster_ids) cluster_ids <- factor( cluster_ids, levels = c(levels(cluster_ids), NA), labels = c(levels(cluster_ids), "unknown"), exclude = NULL ) cluster_ids <- as.character(cluster_ids) } if (!per_cell) { sc_clust <- sort(unique(cluster_ids)) clust_avg <- average_clusters( expr_mat, cluster_ids, if_log = if_log, low_threshold = low_threshold ) } else { sc_clust <- cluster_ids clust_avg <- expr_mat } assigned_score <- calc_similarity( clust_avg, ref_mat, compute_method, rm0 = rm0, ... ) if (low_threshold == 0) { rownames(assigned_score) <- sc_clust colnames(assigned_score) <- ref_clust } return(assigned_score) } #' Compute a p-value for similarity using permutation #' #' @description Permute cluster labels to calculate empirical p-value #' #' #' @param expr_mat single-cell expression matrix #' @param cluster_ids clustering info of single-cell data assume that #' genes have ALREADY BEEN filtered #' @param ref_mat reference expression matrix #' @param n_perm number of permutations #' @param per_cell run per cell? #' @param compute_method method(s) for computing similarity scores #' @param rm0 consider 0 as missing data, recommended for per_cell #' @param ... additional parameters #' @return matrix of numeric values permute_similarity <- function(expr_mat, ref_mat, cluster_ids, n_perm, per_cell = FALSE, compute_method, rm0 = FALSE, ...) { ref_clust <- colnames(ref_mat) if (!per_cell) { sc_clust <- sort(unique(cluster_ids)) clust_avg <- average_clusters( expr_mat, cluster_ids ) } else { sc_clust <- colnames(expr_mat) clust_avg <- expr_mat } assigned_score <- calc_similarity(clust_avg, ref_mat, compute_method, rm0 = rm0, ... ) # perform permutation sig_counts <- matrix(0L, nrow = length(sc_clust), ncol = length(ref_clust) ) for (i in seq_len(n_perm)) { resampled <- sample(cluster_ids, length(cluster_ids), replace = FALSE ) if (!per_cell) { permuted_avg <- average_clusters( expr_mat, resampled ) } else { permuted_avg <- expr_mat[, resampled, drop = FALSE] } # permutate assignment new_score <- calc_similarity(permuted_avg, ref_mat, compute_method, rm0 = rm0, ... ) sig_counts <- sig_counts + as.numeric(new_score > assigned_score) } rownames(assigned_score) <- sc_clust colnames(assigned_score) <- ref_clust rownames(sig_counts) <- sc_clust colnames(sig_counts) <- ref_clust return(list( score = assigned_score, p_val = sig_counts / n_perm )) } #' compute similarity #' @param query_mat query data matrix #' @param ref_mat reference data matrix #' @param compute_method method(s) for computing similarity scores #' @param rm0 consider 0 as missing data, recommended for per_cell #' @param ... additional parameters #' @return matrix of numeric values calc_similarity <- function(query_mat, ref_mat, compute_method, rm0 = FALSE, ...) { # remove 0s ? if (rm0) { message("considering 0 as missing data") query_mat[query_mat == 0] <- NA similarity_score <- suppressWarnings(stats::cor(as.matrix(query_mat), ref_mat, method = compute_method, use = "pairwise.complete.obs" )) return(similarity_score) } else { if (any(compute_method %in% c( "pearson", "spearman", "kendall" ))) { similarity_score <- suppressWarnings( stats::cor(as.matrix(query_mat), ref_mat, method = compute_method ) ) return(similarity_score) } if (compute_method == "cosine") { res <- proxy::simil(as.matrix(query_mat),ref_mat, method = "cosine", by_rows = FALSE) similarity_score <- matrix(res, nrow = nrow(res)) return(similarity_score) } } sc_clust <- colnames(query_mat) ref_clust <- colnames(ref_mat) features <- intersect(rownames(query_mat), rownames(ref_mat)) query_mat <- query_mat[features, ] ref_mat <- ref_mat[features, ] similarity_score <- matrix(NA, nrow = length(sc_clust), ncol = length(ref_clust) ) for (i in seq_along(sc_clust)) { for (j in seq_along(ref_clust)) { similarity_score[i, j] <- vector_similarity( query_mat[, sc_clust[i]], ref_mat[, ref_clust[j]], compute_method, ... ) } } return(similarity_score) } #' Compute similarity between two vectors #' #' @description Compute the similarity score between two vectors using a #' customized scoring function #' Two vectors may be from either scRNA-seq or bulk RNA-seq data. #' The lengths of vec1 and vec2 must match, and must be arranged in the #' same order of genes. #' Both vectors should be provided to this function after pre-processing, #' feature selection and dimension reduction. #' #' @param vec1 test vector #' @param vec2 reference vector #' @param compute_method method to run i.e. corr_coef #' @param ... arguments to pass to compute_method function #' @return numeric value of desired correlation or distance measurement vector_similarity <- function(vec1, vec2, compute_method, ...) { # examine whether two vectors are of the same size if (!is.numeric(vec1) || !is.numeric(vec2) || length(vec1) != length(vec2)) { stop( "compute_similarity: two input vectors", " are not numeric or of different sizes.", call. = FALSE ) } if (!(compute_method %in% c("cosine", "kl_divergence"))) { stop(paste(compute_method, "not implemented"), call. = FALSE) } if (compute_method == "kl_divergence") { res <- kl_divergence(vec1, vec2, ...) } else if (compute_method == "cosine") { res <- cosine(vec1, vec2, ...) } # return the similarity score, must be return(res) } #' Cosine distance #' @param vec1 test vector #' @param vec2 reference vector #' @return numeric value of cosine distance between the vectors cosine <- function(vec1, vec2) { sum(vec1 * vec2) / sqrt(sum(vec1^2) * sum(vec2^2)) } #' KL divergence #' #' @description Use package entropy to compute Kullback-Leibler divergence. #' The function first converts each vector's reads to pseudo-number of #' transcripts by normalizing the total reads to total_reads. #' The normalized read for each gene is then rounded to serve as the #' pseudo-number of transcripts. #' Function entropy::KL.shrink is called to compute the KL-divergence between #' the two vectors, and the maximal allowed divergence is set to max_KL. #' Finally, a linear transform is performed to convert the KL divergence, #' which is between 0 and max_KL, to a similarity score between -1 and 1. #' #' @param vec1 Test vector #' @param vec2 Reference vector #' @param if_log Whether the vectors are log-transformed. If so, the #' raw count should be computed before computing KL-divergence. #' @param total_reads Pseudo-library size #' @param max_KL Maximal allowed value of KL-divergence. #' @return numeric value, with additional attributes, of kl divergence #' between the vectors kl_divergence <- function(vec1, vec2, if_log = FALSE, total_reads = 1000, max_KL = 1) { if (if_log) { vec1 <- expm1(vec1) vec2 <- expm1(vec2) } count1 <- round(vec1 * total_reads / sum(vec1)) count2 <- round(vec2 * total_reads / sum(vec2)) est_KL <- entropy::KL.shrink(count1, count2, unit = "log", verbose = FALSE ) return((max_KL - est_KL) / max_KL * 2 - 1) }
/R/compute_similarity.R
permissive
standardgalactic/clustifyr
R
false
false
10,108
r
#' Compute similarity of matrices #' #' @param expr_mat single-cell expression matrix #' @param ref_mat reference expression matrix #' @param cluster_ids vector of cluster ids for each cell #' @param compute_method method(s) for computing similarity scores #' @param per_cell run per cell? #' @param rm0 consider 0 as missing data, recommended for per_cell #' @param if_log input data is natural log, #' averaging will be done on unlogged data #' @param low_threshold option to remove clusters with too few cells #' @param ... additional parameters not used yet #' @return matrix of numeric values, clusters from expr_mat as row names, #' cell types from ref_mat as column names get_similarity <- function(expr_mat, ref_mat, cluster_ids, compute_method, per_cell = FALSE, rm0 = FALSE, if_log = TRUE, low_threshold = 0, ...) { if (nrow(expr_mat) == 0) { stop("after subsetting to shared genes", "query expression matrix has 0 rows", call. = FALSE ) } if (ncol(expr_mat) == 0) { stop("query expression matrix has 0 cols", call. = FALSE ) } if (nrow(ref_mat) == 0) { stop("after subsetting to shared genes", "reference expression matrix has 0 rows", call. = FALSE ) } if (ncol(ref_mat) == 0) { stop("reference expression matrix has 0 cols", call. = FALSE ) } ref_clust <- colnames(ref_mat) if (ncol(expr_mat) != length(cluster_ids)) { stop("number of cells in expression matrix not equal", "to metadata/cluster_col", call. = FALSE ) } if (sum(is.na(cluster_ids)) > 0) { message("reassigning NAs to unknown") cluster_ids <- factor(cluster_ids) cluster_ids <- factor( cluster_ids, levels = c(levels(cluster_ids), NA), labels = c(levels(cluster_ids), "unknown"), exclude = NULL ) cluster_ids <- as.character(cluster_ids) } if (!per_cell) { sc_clust <- sort(unique(cluster_ids)) clust_avg <- average_clusters( expr_mat, cluster_ids, if_log = if_log, low_threshold = low_threshold ) } else { sc_clust <- cluster_ids clust_avg <- expr_mat } assigned_score <- calc_similarity( clust_avg, ref_mat, compute_method, rm0 = rm0, ... ) if (low_threshold == 0) { rownames(assigned_score) <- sc_clust colnames(assigned_score) <- ref_clust } return(assigned_score) } #' Compute a p-value for similarity using permutation #' #' @description Permute cluster labels to calculate empirical p-value #' #' #' @param expr_mat single-cell expression matrix #' @param cluster_ids clustering info of single-cell data assume that #' genes have ALREADY BEEN filtered #' @param ref_mat reference expression matrix #' @param n_perm number of permutations #' @param per_cell run per cell? #' @param compute_method method(s) for computing similarity scores #' @param rm0 consider 0 as missing data, recommended for per_cell #' @param ... additional parameters #' @return matrix of numeric values permute_similarity <- function(expr_mat, ref_mat, cluster_ids, n_perm, per_cell = FALSE, compute_method, rm0 = FALSE, ...) { ref_clust <- colnames(ref_mat) if (!per_cell) { sc_clust <- sort(unique(cluster_ids)) clust_avg <- average_clusters( expr_mat, cluster_ids ) } else { sc_clust <- colnames(expr_mat) clust_avg <- expr_mat } assigned_score <- calc_similarity(clust_avg, ref_mat, compute_method, rm0 = rm0, ... ) # perform permutation sig_counts <- matrix(0L, nrow = length(sc_clust), ncol = length(ref_clust) ) for (i in seq_len(n_perm)) { resampled <- sample(cluster_ids, length(cluster_ids), replace = FALSE ) if (!per_cell) { permuted_avg <- average_clusters( expr_mat, resampled ) } else { permuted_avg <- expr_mat[, resampled, drop = FALSE] } # permutate assignment new_score <- calc_similarity(permuted_avg, ref_mat, compute_method, rm0 = rm0, ... ) sig_counts <- sig_counts + as.numeric(new_score > assigned_score) } rownames(assigned_score) <- sc_clust colnames(assigned_score) <- ref_clust rownames(sig_counts) <- sc_clust colnames(sig_counts) <- ref_clust return(list( score = assigned_score, p_val = sig_counts / n_perm )) } #' compute similarity #' @param query_mat query data matrix #' @param ref_mat reference data matrix #' @param compute_method method(s) for computing similarity scores #' @param rm0 consider 0 as missing data, recommended for per_cell #' @param ... additional parameters #' @return matrix of numeric values calc_similarity <- function(query_mat, ref_mat, compute_method, rm0 = FALSE, ...) { # remove 0s ? if (rm0) { message("considering 0 as missing data") query_mat[query_mat == 0] <- NA similarity_score <- suppressWarnings(stats::cor(as.matrix(query_mat), ref_mat, method = compute_method, use = "pairwise.complete.obs" )) return(similarity_score) } else { if (any(compute_method %in% c( "pearson", "spearman", "kendall" ))) { similarity_score <- suppressWarnings( stats::cor(as.matrix(query_mat), ref_mat, method = compute_method ) ) return(similarity_score) } if (compute_method == "cosine") { res <- proxy::simil(as.matrix(query_mat),ref_mat, method = "cosine", by_rows = FALSE) similarity_score <- matrix(res, nrow = nrow(res)) return(similarity_score) } } sc_clust <- colnames(query_mat) ref_clust <- colnames(ref_mat) features <- intersect(rownames(query_mat), rownames(ref_mat)) query_mat <- query_mat[features, ] ref_mat <- ref_mat[features, ] similarity_score <- matrix(NA, nrow = length(sc_clust), ncol = length(ref_clust) ) for (i in seq_along(sc_clust)) { for (j in seq_along(ref_clust)) { similarity_score[i, j] <- vector_similarity( query_mat[, sc_clust[i]], ref_mat[, ref_clust[j]], compute_method, ... ) } } return(similarity_score) } #' Compute similarity between two vectors #' #' @description Compute the similarity score between two vectors using a #' customized scoring function #' Two vectors may be from either scRNA-seq or bulk RNA-seq data. #' The lengths of vec1 and vec2 must match, and must be arranged in the #' same order of genes. #' Both vectors should be provided to this function after pre-processing, #' feature selection and dimension reduction. #' #' @param vec1 test vector #' @param vec2 reference vector #' @param compute_method method to run i.e. corr_coef #' @param ... arguments to pass to compute_method function #' @return numeric value of desired correlation or distance measurement vector_similarity <- function(vec1, vec2, compute_method, ...) { # examine whether two vectors are of the same size if (!is.numeric(vec1) || !is.numeric(vec2) || length(vec1) != length(vec2)) { stop( "compute_similarity: two input vectors", " are not numeric or of different sizes.", call. = FALSE ) } if (!(compute_method %in% c("cosine", "kl_divergence"))) { stop(paste(compute_method, "not implemented"), call. = FALSE) } if (compute_method == "kl_divergence") { res <- kl_divergence(vec1, vec2, ...) } else if (compute_method == "cosine") { res <- cosine(vec1, vec2, ...) } # return the similarity score, must be return(res) } #' Cosine distance #' @param vec1 test vector #' @param vec2 reference vector #' @return numeric value of cosine distance between the vectors cosine <- function(vec1, vec2) { sum(vec1 * vec2) / sqrt(sum(vec1^2) * sum(vec2^2)) } #' KL divergence #' #' @description Use package entropy to compute Kullback-Leibler divergence. #' The function first converts each vector's reads to pseudo-number of #' transcripts by normalizing the total reads to total_reads. #' The normalized read for each gene is then rounded to serve as the #' pseudo-number of transcripts. #' Function entropy::KL.shrink is called to compute the KL-divergence between #' the two vectors, and the maximal allowed divergence is set to max_KL. #' Finally, a linear transform is performed to convert the KL divergence, #' which is between 0 and max_KL, to a similarity score between -1 and 1. #' #' @param vec1 Test vector #' @param vec2 Reference vector #' @param if_log Whether the vectors are log-transformed. If so, the #' raw count should be computed before computing KL-divergence. #' @param total_reads Pseudo-library size #' @param max_KL Maximal allowed value of KL-divergence. #' @return numeric value, with additional attributes, of kl divergence #' between the vectors kl_divergence <- function(vec1, vec2, if_log = FALSE, total_reads = 1000, max_KL = 1) { if (if_log) { vec1 <- expm1(vec1) vec2 <- expm1(vec2) } count1 <- round(vec1 * total_reads / sum(vec1)) count2 <- round(vec2 * total_reads / sum(vec2)) est_KL <- entropy::KL.shrink(count1, count2, unit = "log", verbose = FALSE ) return((max_KL - est_KL) / max_KL * 2 - 1) }
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX # Data tablas Conversion ---- # XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX # XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX # Data tablas Conversion ---- # XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX library(RODBC) channel <- odbcDriverConnect( "Driver={Microsoft Access Driver (*.mdb, *.accdb)};D:/A COLSUBSIDIO/A REQUERIMIENTO 2020/4 ABRIL/Consuulta_CM_Droguerias/Consulta_CM_Establecimientos.accdb" ) sqlTables(channel) Tb_localidad<- sqlQuery( channel , paste ("select * from Tb_localidad"), as.is=T ) %>% data.frame() Tb_Division_Politica_Dane<- sqlQuery( channel , paste ("select * from Tb_Division_Politica_Dane"), as.is=T ) %>% data.frame() odbcCloseAll() cm_redencion2020 <- readRDS("//bogak08beimrodc/bi/Proteccion_Social/BD_MediosdePagosCM2020.rds") str(cm_redencion2020) table(cm_redencion2020$CodigoEstablecimiento)
/04_Abril/2 Consulta_CM_Droguerias/Consulta.R
no_license
edgaruio/A-Requerimiento-2020
R
false
false
1,087
r
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX # Data tablas Conversion ---- # XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX # XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX # Data tablas Conversion ---- # XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX library(RODBC) channel <- odbcDriverConnect( "Driver={Microsoft Access Driver (*.mdb, *.accdb)};D:/A COLSUBSIDIO/A REQUERIMIENTO 2020/4 ABRIL/Consuulta_CM_Droguerias/Consulta_CM_Establecimientos.accdb" ) sqlTables(channel) Tb_localidad<- sqlQuery( channel , paste ("select * from Tb_localidad"), as.is=T ) %>% data.frame() Tb_Division_Politica_Dane<- sqlQuery( channel , paste ("select * from Tb_Division_Politica_Dane"), as.is=T ) %>% data.frame() odbcCloseAll() cm_redencion2020 <- readRDS("//bogak08beimrodc/bi/Proteccion_Social/BD_MediosdePagosCM2020.rds") str(cm_redencion2020) table(cm_redencion2020$CodigoEstablecimiento)
#I use page “contacts” for example. library("RGA") rga_auth <- authorize(client.id = "your Client ID", client.secret = "your client secret") #1 Downloading pageviews metric for page or section of your web-site. content_data <- get_ga(profileId = "ga:View ID", start.date = "yyyy-mm-dd", end.date = "yyyy-mm-dd", dimensions = "ga:month", metrics = "ga:pageviews", filters = "ga:pagePathLevel1==/contacts/", fetch.by = "month", samplingLevel = "HIGHER_PRECISION", token = rga_auth) names(content_data)[1] <- "pageviews" names(content_data)[2] <- "contacts" all_pageviews <- get_ga(profileId = "ga:View ID", start.date = "yyyy-mm-dd", end.date = "yyyy-mm-dd", dimensions = "ga:month", metrics = "ga:pageviews", fetch.by = "month", samplingLevel = "HIGHER_PRECISION", token = rga_auth) all_pageviews <- all_pageviews[-1] names(all_pageviews)[1] <- "all" content_data <- cbind(content_data, all_pageviews) #2 Downloading sessions metric for page or section of your web-site. content_data <- cbind(content_data,"sessions") contacts_sessions <- get_ga(profileId = "ga:View ID", start.date = "yyyy-mm-dd", end.date = "yyyy-mm-dd", dimensions = "ga:month", metrics = "ga:sessions", filters = "ga:landingPagePath=@/contacts/", fetch.by = "month", samplingLevel = "HIGHER_PRECISION", token = rga_auth) contacts_sessions <- contacts_sessions[-1] names(contacts_sessions)[1] <- "contacts" content_data <- cbind(content_data, contacts_sessions) all_sessions <- get_ga(profileId = "ga:View ID", start.date = "yyyy-mm-dd", end.date = "yyyy-mm-dd", dimensions = "ga:month", metrics = "ga:sessions", fetch.by = "month", samplingLevel = "HIGHER_PRECISION", token = rga_auth) all_sessions <- all_sessions[-1] names(all_sessions)[1] <- "all" content_data <- cbind(content_data, all_sessions) #3 Downloading sessions metric for page or section of your web-site according to mediums. content_data <- cbind(content_data,"organic to pages") contacts_organic <- get_ga(profileId = "ga:View ID", start.date = "yyyy-mm-dd", end.date = "yyyy-mm-dd", dimensions = "ga:month", metrics = "ga:sessions", filters = "ga:landingPagePath=@/contactst/;ga:medium==organic", fetch.by = "month", samplingLevel = "HIGHER_PRECISION", token = rga_auth) contacts_organic <- contacts_organic[-1] names(contacts_organic)[1] <- "contacts" content_data <- cbind(content_data, contacts_organic) all_organic <- get_ga(profileId = "ga:View ID", start.date = "yyyy-mm-dd", end.date = "yyyy-mm-dd", dimensions = "ga:month", metrics = "ga:sessions", filters = "ga:medium==organic", fetch.by = "month", samplingLevel = "HIGHER_PRECISION", token = rga_auth) all_organic <- all_organic[-1] names(all_organic)[1] <- "all" content_data <- cbind(content_data, all_organic) #4 Downloading session metric for page or section according to medium and source. content_data <- cbind(content_data,"organic to the main pages") content_data <- cbind(content_data,"contacts") contacts_google <- get_ga(profileId = "ga:View ID", start.date = "yyyy-mm-dd", end.date = "yyyy-mm-dd", dimensions = "ga:month", metrics = "ga:sessions", filters = "ga:landingPagePath=@/contacts/;ga:medium==organic;ga:source=@google", fetch.by = "month", samplingLevel = "HIGHER_PRECISION", token = rga_auth) contacts_google <- contacts_google[-1] names(contacts_google)[1] <- "google" content_data <- cbind(content_data, contacts_google) #5 Downloading users metric for page or section. content_data <- cbind(content_data,"users") contacts_users <- get_ga(profileId = "ga:View ID", start.date = "yyyy-mm-dd", end.date = "yyyy-mm-dd", dimensions = "ga:month", metrics = "ga:users", segment = "users::condition::ga:landingPagePath=@/contacts/", fetch.by = "month", samplingLevel = "HIGHER_PRECISION", token = rga_auth) contacts_users <- contacts_users[-1] names(contacts_users)[1] <- "contacts" content_data <- cbind(content_data, contacts_users) all_users <- get_ga(profileId = "ga:View ID", start.date = "yyyy-mm-dd", end.date = "yyyy-mm-dd", dimensions = "ga:month", metrics = "ga:users", fetch.by = "month", samplingLevel = "HIGHER_PRECISION", token = rga_auth) all_users <- all_users[-1] names(all_users)[1] <- "all" content_data <- cbind(content_data, all_users) #6 Downloading bounce Rate metric for page or section. content_data <- cbind(content_data,"bounceRate") contacts_bounceRate <- get_ga(profileId = "ga:View ID", start.date = "yyyy-mm-dd", end.date = "yyyy-mm-dd", dimensions = "ga:month", metrics = "ga:bounceRate", filters = "ga:landingPagePath=@/contacts/", fetch.by = "month", samplingLevel = "HIGHER_PRECISION", token = rga_auth) contacts_bounceRate <- contacts_bounceRate[-1] names(contacts_bounceRate)[1] <- "contacts" content_data <- cbind(content_data, contacts_bounceRate)
/content.R
no_license
AlinaGay/Download-data-from-GA-by-R
R
false
false
6,925
r
#I use page “contacts” for example. library("RGA") rga_auth <- authorize(client.id = "your Client ID", client.secret = "your client secret") #1 Downloading pageviews metric for page or section of your web-site. content_data <- get_ga(profileId = "ga:View ID", start.date = "yyyy-mm-dd", end.date = "yyyy-mm-dd", dimensions = "ga:month", metrics = "ga:pageviews", filters = "ga:pagePathLevel1==/contacts/", fetch.by = "month", samplingLevel = "HIGHER_PRECISION", token = rga_auth) names(content_data)[1] <- "pageviews" names(content_data)[2] <- "contacts" all_pageviews <- get_ga(profileId = "ga:View ID", start.date = "yyyy-mm-dd", end.date = "yyyy-mm-dd", dimensions = "ga:month", metrics = "ga:pageviews", fetch.by = "month", samplingLevel = "HIGHER_PRECISION", token = rga_auth) all_pageviews <- all_pageviews[-1] names(all_pageviews)[1] <- "all" content_data <- cbind(content_data, all_pageviews) #2 Downloading sessions metric for page or section of your web-site. content_data <- cbind(content_data,"sessions") contacts_sessions <- get_ga(profileId = "ga:View ID", start.date = "yyyy-mm-dd", end.date = "yyyy-mm-dd", dimensions = "ga:month", metrics = "ga:sessions", filters = "ga:landingPagePath=@/contacts/", fetch.by = "month", samplingLevel = "HIGHER_PRECISION", token = rga_auth) contacts_sessions <- contacts_sessions[-1] names(contacts_sessions)[1] <- "contacts" content_data <- cbind(content_data, contacts_sessions) all_sessions <- get_ga(profileId = "ga:View ID", start.date = "yyyy-mm-dd", end.date = "yyyy-mm-dd", dimensions = "ga:month", metrics = "ga:sessions", fetch.by = "month", samplingLevel = "HIGHER_PRECISION", token = rga_auth) all_sessions <- all_sessions[-1] names(all_sessions)[1] <- "all" content_data <- cbind(content_data, all_sessions) #3 Downloading sessions metric for page or section of your web-site according to mediums. content_data <- cbind(content_data,"organic to pages") contacts_organic <- get_ga(profileId = "ga:View ID", start.date = "yyyy-mm-dd", end.date = "yyyy-mm-dd", dimensions = "ga:month", metrics = "ga:sessions", filters = "ga:landingPagePath=@/contactst/;ga:medium==organic", fetch.by = "month", samplingLevel = "HIGHER_PRECISION", token = rga_auth) contacts_organic <- contacts_organic[-1] names(contacts_organic)[1] <- "contacts" content_data <- cbind(content_data, contacts_organic) all_organic <- get_ga(profileId = "ga:View ID", start.date = "yyyy-mm-dd", end.date = "yyyy-mm-dd", dimensions = "ga:month", metrics = "ga:sessions", filters = "ga:medium==organic", fetch.by = "month", samplingLevel = "HIGHER_PRECISION", token = rga_auth) all_organic <- all_organic[-1] names(all_organic)[1] <- "all" content_data <- cbind(content_data, all_organic) #4 Downloading session metric for page or section according to medium and source. content_data <- cbind(content_data,"organic to the main pages") content_data <- cbind(content_data,"contacts") contacts_google <- get_ga(profileId = "ga:View ID", start.date = "yyyy-mm-dd", end.date = "yyyy-mm-dd", dimensions = "ga:month", metrics = "ga:sessions", filters = "ga:landingPagePath=@/contacts/;ga:medium==organic;ga:source=@google", fetch.by = "month", samplingLevel = "HIGHER_PRECISION", token = rga_auth) contacts_google <- contacts_google[-1] names(contacts_google)[1] <- "google" content_data <- cbind(content_data, contacts_google) #5 Downloading users metric for page or section. content_data <- cbind(content_data,"users") contacts_users <- get_ga(profileId = "ga:View ID", start.date = "yyyy-mm-dd", end.date = "yyyy-mm-dd", dimensions = "ga:month", metrics = "ga:users", segment = "users::condition::ga:landingPagePath=@/contacts/", fetch.by = "month", samplingLevel = "HIGHER_PRECISION", token = rga_auth) contacts_users <- contacts_users[-1] names(contacts_users)[1] <- "contacts" content_data <- cbind(content_data, contacts_users) all_users <- get_ga(profileId = "ga:View ID", start.date = "yyyy-mm-dd", end.date = "yyyy-mm-dd", dimensions = "ga:month", metrics = "ga:users", fetch.by = "month", samplingLevel = "HIGHER_PRECISION", token = rga_auth) all_users <- all_users[-1] names(all_users)[1] <- "all" content_data <- cbind(content_data, all_users) #6 Downloading bounce Rate metric for page or section. content_data <- cbind(content_data,"bounceRate") contacts_bounceRate <- get_ga(profileId = "ga:View ID", start.date = "yyyy-mm-dd", end.date = "yyyy-mm-dd", dimensions = "ga:month", metrics = "ga:bounceRate", filters = "ga:landingPagePath=@/contacts/", fetch.by = "month", samplingLevel = "HIGHER_PRECISION", token = rga_auth) contacts_bounceRate <- contacts_bounceRate[-1] names(contacts_bounceRate)[1] <- "contacts" content_data <- cbind(content_data, contacts_bounceRate)
library(shiny) library(twitteR) library(wordcloud2) library(tidyverse) library(stringr) library(tm) library(qdap) library(ggmap)
/Untitled.R
no_license
ravichikkam/Twitter_query_shiny
R
false
false
128
r
library(shiny) library(twitteR) library(wordcloud2) library(tidyverse) library(stringr) library(tm) library(qdap) library(ggmap)
#!/usr/bin/Rscript library("jsonlite") print("CARGANDO") json_data = fromJSON("/tmp/metal_db.json") paises = as.data.frame(table(json_data$pais)) paises_ord = paises[order(paises$Freq),] #print(tail(paises_ord, n = 10L)) f = function(cada) { p= cada[1] f= cada[2] cat(p, '=', f, '\n') data_pais = subset(json_data, json_data$pais == p) genero_por_pais = as.data.frame(table(data_pais$genero)) genero_por_pais_ord = genero_por_pais[order(genero_por_pais$Freq),] g = tail(genero_por_pais_ord, 1) #cat(g, '\n') print(g) } #invisible(apply(paises_ord, 1, function(c) map_print(c[1], json_data))) r = apply(paises_ord, 1, f)
/main.R
no_license
alvarezgarcia/metal-archives-stats
R
false
false
667
r
#!/usr/bin/Rscript library("jsonlite") print("CARGANDO") json_data = fromJSON("/tmp/metal_db.json") paises = as.data.frame(table(json_data$pais)) paises_ord = paises[order(paises$Freq),] #print(tail(paises_ord, n = 10L)) f = function(cada) { p= cada[1] f= cada[2] cat(p, '=', f, '\n') data_pais = subset(json_data, json_data$pais == p) genero_por_pais = as.data.frame(table(data_pais$genero)) genero_por_pais_ord = genero_por_pais[order(genero_por_pais$Freq),] g = tail(genero_por_pais_ord, 1) #cat(g, '\n') print(g) } #invisible(apply(paises_ord, 1, function(c) map_print(c[1], json_data))) r = apply(paises_ord, 1, f)
## An implementation of ## "A Resampling Approach for Correcting Systematic Spatiotemporal Biases for Multiple Variables in a Changing Climate" ## by Mehrotra and Sharma (2019), Water Resources Research, 55(1), pp.754-770, doi: 10.1029/2018WR023270 ## Refered to as 3DBC (3-dimensional bias-correction), as it keeps inter-variable, temporal and spatial consistencies from the reference data set. ## Basically a smart combination of quantile-mapping (or any usual bias-correction method) and Schaake Shuffle ### ### Implementation by A. Dobler, summer 2021 ### andreas.dobler@met.no library(ncdf4) #some print output print(paste("Processing year",YEAR)) RefYear <- YEAR print(paste("Using annual cycle from",RefYear)) # Split the domain into parts with about the same number of non-NA grid points (to save memory) # eqm data: 1195x1550=1'852'250 gps with 354'448 non-NA (ca. 19%) # use split.Domain.R to get the indices (idy) idy <- c(1,168,222,265,304,347,426,627,791,908,1008,1068,1116,1163,1208,1251,1295,1340,1388,1443) szy <- diff(c(idy,1551)) print(paste("Splitting domain into",length(idy),"parts (to save memory)")) print("==========================================") for (p in 1:length(idy)) { #some print output print(paste("Started part",p,"on", date())) #read data nc <- nc_open(paste("/lustre/storeB/users/andreasd/KiN_2023_data/3DBC/sfcWind/Obs/KliNoGrid_FFMRR-Nor_utm33_sN2_analysis_Nor_",RefYear,".nc",sep="")) ObsA <- ncvar_get(nc,"windspeed_10m",start = c(1,idy[p],1), count=c(-1,szy[p],-1)) nc_close(nc) nc <- nc_open(paste("/lustre/storeB/users/andreasd/KiN_2023_data/3DBC/sfcWind/Cur/cnrm-r1i1p1-aladin_hist_eqm-klinogrid1612_rawbc_norway_1km_sfcWind_daily_",RefYear,".nc4",sep="")) CurA <- ncvar_get(nc,"sfcWind",start = c(1,idy[p],1), count=c(-1,szy[p],-1)) nc_close(nc) #define mask with grid points with values ValMask <- which(!is.na(CurA[,,1]) ,arr.ind=T) NofPoints <- dim(ValMask)[1] nc <- nc_open(paste("/lustre/storeB/users/andreasd/KiN_2023_data/3DBC/sfcWind/Cur/cnrm-r1i1p1-aladin_hist_eqm-klinogrid1612_rawbc_norway_1km_sfcWind_daily_",YEAR,".nc4",sep="")) FutA <- ncvar_get(nc,"sfcWind",start = c(1,idy[p],1), count=c(-1,szy[p],-1)) nc_close(nc) #reading done print(paste0(NofPoints," points read")) #create arrays for corrected data FutCA <- array(NA,dim(FutA)) #loop over grid pointss for (i in 1:NofPoints) { x <- ValMask[i,1] y <- ValMask[i,2] Obs <- ObsA[x,y,] Cur <- CurA[x,y,] Fut <- FutA[x,y,] #number of values nod <- length(Obs) nodp1 <- nod+1 #Rank data in descending order RankO <- nodp1 - rank(Obs, ties.method = "first") RankC <- nodp1 - rank(Cur, ties.method = "first") RankF <- nodp1 - rank(Fut, ties.method = "first") #Cummulative probabilty ProbO <- 1-RankO/nodp1 ProbC <- 1-RankC/nodp1 ProbF <- 1-RankF/nodp1 #Gaussian transformation GaussO <- qnorm(ProbO) GaussC <- qnorm(ProbC) GaussF <- qnorm(ProbF) #Calculate lag-one autocorrelations rO <- acf(GaussO,plot=F,lag.max=1)$acf[2] rC <- acf(GaussC,plot=F,lag.max=1)$acf[2] rF <- acf(GaussF,plot=F,lag.max=1)$acf[2] #Remove rO from GaussO GaussOR <- GaussO/sqrt(1-rO*rO) GaussOR[2:nod] <- (GaussO[2:nod]-rO*GaussO[1:(nod-1)])/sqrt(1-rO*rO) #from 2nd time step #Calculate corrected autocorrelation rN <- ((1+rF) / (1+rC) * (1+rO) - (1-rF) / (1-rC) * (1-rO) ) / ((1+rF) / (1+rC) * (1+rO) + (1-rF) / (1-rC) * (1-rO) ) #Add rN to GaussOR. Note: Gauss for current climate equals GaussO! GaussFC <- sqrt(1-rN*rN) %*% t(GaussOR) for (t in 2:nod) GaussFC[,t] <- rN*GaussFC[,t-1] + sqrt(1-rN*rN) %*% t(GaussOR[t]) #from 2nd time step ##Rank and reorder values RankFC <- nodp1 - rank(GaussFC,ties.method = "first") FutCA[x,y,] <- sort(Fut,decreasing = TRUE)[RankFC] } #That's all :-) #Write to NetCDF nc <- nc_open(paste("/lustre/storeB/users/andreasd/KiN_2023_data/3DBC/sfcWind/CurC/app/cnrm-r1i1p1-aladin_hist_3dbc-eqm-klinogrid1612_rawbc_norway_1km_sfcWind_daily_",YEAR,".nc4",sep=""),write=TRUE) ncvar_put(nc,"sfcWind",FutCA,start = c(1,idy[p],1), count=c(-1,szy[p],-1)) nc_close(nc) rm(Obs,CurA,FutA,FutCA,ValMask) gc(full=TRUE) } print("==========================================") print(paste("Year",YEAR,"done.")) rm(list = ls(all.names = TRUE)) #clear environment gc() #free up memrory and report the memory usage.
/CNRM_ALADIN/HIST/3DBC_sfcWind_CNRM_ALADIN_APP_template.R
no_license
doblerone/3DBC
R
false
false
4,558
r
## An implementation of ## "A Resampling Approach for Correcting Systematic Spatiotemporal Biases for Multiple Variables in a Changing Climate" ## by Mehrotra and Sharma (2019), Water Resources Research, 55(1), pp.754-770, doi: 10.1029/2018WR023270 ## Refered to as 3DBC (3-dimensional bias-correction), as it keeps inter-variable, temporal and spatial consistencies from the reference data set. ## Basically a smart combination of quantile-mapping (or any usual bias-correction method) and Schaake Shuffle ### ### Implementation by A. Dobler, summer 2021 ### andreas.dobler@met.no library(ncdf4) #some print output print(paste("Processing year",YEAR)) RefYear <- YEAR print(paste("Using annual cycle from",RefYear)) # Split the domain into parts with about the same number of non-NA grid points (to save memory) # eqm data: 1195x1550=1'852'250 gps with 354'448 non-NA (ca. 19%) # use split.Domain.R to get the indices (idy) idy <- c(1,168,222,265,304,347,426,627,791,908,1008,1068,1116,1163,1208,1251,1295,1340,1388,1443) szy <- diff(c(idy,1551)) print(paste("Splitting domain into",length(idy),"parts (to save memory)")) print("==========================================") for (p in 1:length(idy)) { #some print output print(paste("Started part",p,"on", date())) #read data nc <- nc_open(paste("/lustre/storeB/users/andreasd/KiN_2023_data/3DBC/sfcWind/Obs/KliNoGrid_FFMRR-Nor_utm33_sN2_analysis_Nor_",RefYear,".nc",sep="")) ObsA <- ncvar_get(nc,"windspeed_10m",start = c(1,idy[p],1), count=c(-1,szy[p],-1)) nc_close(nc) nc <- nc_open(paste("/lustre/storeB/users/andreasd/KiN_2023_data/3DBC/sfcWind/Cur/cnrm-r1i1p1-aladin_hist_eqm-klinogrid1612_rawbc_norway_1km_sfcWind_daily_",RefYear,".nc4",sep="")) CurA <- ncvar_get(nc,"sfcWind",start = c(1,idy[p],1), count=c(-1,szy[p],-1)) nc_close(nc) #define mask with grid points with values ValMask <- which(!is.na(CurA[,,1]) ,arr.ind=T) NofPoints <- dim(ValMask)[1] nc <- nc_open(paste("/lustre/storeB/users/andreasd/KiN_2023_data/3DBC/sfcWind/Cur/cnrm-r1i1p1-aladin_hist_eqm-klinogrid1612_rawbc_norway_1km_sfcWind_daily_",YEAR,".nc4",sep="")) FutA <- ncvar_get(nc,"sfcWind",start = c(1,idy[p],1), count=c(-1,szy[p],-1)) nc_close(nc) #reading done print(paste0(NofPoints," points read")) #create arrays for corrected data FutCA <- array(NA,dim(FutA)) #loop over grid pointss for (i in 1:NofPoints) { x <- ValMask[i,1] y <- ValMask[i,2] Obs <- ObsA[x,y,] Cur <- CurA[x,y,] Fut <- FutA[x,y,] #number of values nod <- length(Obs) nodp1 <- nod+1 #Rank data in descending order RankO <- nodp1 - rank(Obs, ties.method = "first") RankC <- nodp1 - rank(Cur, ties.method = "first") RankF <- nodp1 - rank(Fut, ties.method = "first") #Cummulative probabilty ProbO <- 1-RankO/nodp1 ProbC <- 1-RankC/nodp1 ProbF <- 1-RankF/nodp1 #Gaussian transformation GaussO <- qnorm(ProbO) GaussC <- qnorm(ProbC) GaussF <- qnorm(ProbF) #Calculate lag-one autocorrelations rO <- acf(GaussO,plot=F,lag.max=1)$acf[2] rC <- acf(GaussC,plot=F,lag.max=1)$acf[2] rF <- acf(GaussF,plot=F,lag.max=1)$acf[2] #Remove rO from GaussO GaussOR <- GaussO/sqrt(1-rO*rO) GaussOR[2:nod] <- (GaussO[2:nod]-rO*GaussO[1:(nod-1)])/sqrt(1-rO*rO) #from 2nd time step #Calculate corrected autocorrelation rN <- ((1+rF) / (1+rC) * (1+rO) - (1-rF) / (1-rC) * (1-rO) ) / ((1+rF) / (1+rC) * (1+rO) + (1-rF) / (1-rC) * (1-rO) ) #Add rN to GaussOR. Note: Gauss for current climate equals GaussO! GaussFC <- sqrt(1-rN*rN) %*% t(GaussOR) for (t in 2:nod) GaussFC[,t] <- rN*GaussFC[,t-1] + sqrt(1-rN*rN) %*% t(GaussOR[t]) #from 2nd time step ##Rank and reorder values RankFC <- nodp1 - rank(GaussFC,ties.method = "first") FutCA[x,y,] <- sort(Fut,decreasing = TRUE)[RankFC] } #That's all :-) #Write to NetCDF nc <- nc_open(paste("/lustre/storeB/users/andreasd/KiN_2023_data/3DBC/sfcWind/CurC/app/cnrm-r1i1p1-aladin_hist_3dbc-eqm-klinogrid1612_rawbc_norway_1km_sfcWind_daily_",YEAR,".nc4",sep=""),write=TRUE) ncvar_put(nc,"sfcWind",FutCA,start = c(1,idy[p],1), count=c(-1,szy[p],-1)) nc_close(nc) rm(Obs,CurA,FutA,FutCA,ValMask) gc(full=TRUE) } print("==========================================") print(paste("Year",YEAR,"done.")) rm(list = ls(all.names = TRUE)) #clear environment gc() #free up memrory and report the memory usage.
\name{OraResult-class} \docType{class} \alias{OraResult-class} \title{Class OraResult} \description{ An Oracle query results class. This class encapsulates the result of a SQL statement. } \section{Generators}{ The main generator is \code{\link[DBI]{dbSendQuery}}. } \section{Extends}{ Class \code{"DBIResult"}, directly. Class \code{"DBIObject"}, by class \code{"DBIResult"}, distance 2. } \section{Methods}{ \describe{ \item{dbClearResult}{\code{signature(res = "OraResult")}: ... } \item{dbColumnInfo}{\code{signature(res = "OraResult")}: ... } \item{dbGetInfo}{\code{signature(dbObj = "OraResult")}: ... } \item{dbGetStatement}{\code{signature(res = "OraResult")}: ... } \item{dbGetRowCount}{\code{signature(res = "OraResult")}: ... } \item{dbGetRowsAffected}{\code{signature(res = "OraResult")}: ... } \item{dbHasCompleted}{\code{signature(res = "OraResult")}: ... } \item{fetch}{\code{signature(res = "OraResult", n = "numeric")}: ... } \item{fetch}{\code{signature(res = "OraResult", n = "missing")}: ... } \item{execute}{\code{signature(res = "OraResult")}: ...} \item{summary}{\code{signature(object = "OraResult")}: ... } \item{show}{\code{signature(object = "OraResult")} } } } \seealso{ DBI classes: \code{\link{OraDriver-class}} \code{\link{OraConnection-class}} \code{\link{OraResult-class}} } \examples{\dontrun{ ora <- dbDriver("Oracle") con <- dbConnect(ora, "scott", "tiger") res <- dbSendQuery(con, "select * from emp") fetch(res, n = 2) fetch(res) dbColumnInfo(res) dbClearResult(res) } } \keyword{database} \keyword{interface} \keyword{classes}
/man/OraResult-class.Rd
no_license
cran/ROracle
R
false
false
1,630
rd
\name{OraResult-class} \docType{class} \alias{OraResult-class} \title{Class OraResult} \description{ An Oracle query results class. This class encapsulates the result of a SQL statement. } \section{Generators}{ The main generator is \code{\link[DBI]{dbSendQuery}}. } \section{Extends}{ Class \code{"DBIResult"}, directly. Class \code{"DBIObject"}, by class \code{"DBIResult"}, distance 2. } \section{Methods}{ \describe{ \item{dbClearResult}{\code{signature(res = "OraResult")}: ... } \item{dbColumnInfo}{\code{signature(res = "OraResult")}: ... } \item{dbGetInfo}{\code{signature(dbObj = "OraResult")}: ... } \item{dbGetStatement}{\code{signature(res = "OraResult")}: ... } \item{dbGetRowCount}{\code{signature(res = "OraResult")}: ... } \item{dbGetRowsAffected}{\code{signature(res = "OraResult")}: ... } \item{dbHasCompleted}{\code{signature(res = "OraResult")}: ... } \item{fetch}{\code{signature(res = "OraResult", n = "numeric")}: ... } \item{fetch}{\code{signature(res = "OraResult", n = "missing")}: ... } \item{execute}{\code{signature(res = "OraResult")}: ...} \item{summary}{\code{signature(object = "OraResult")}: ... } \item{show}{\code{signature(object = "OraResult")} } } } \seealso{ DBI classes: \code{\link{OraDriver-class}} \code{\link{OraConnection-class}} \code{\link{OraResult-class}} } \examples{\dontrun{ ora <- dbDriver("Oracle") con <- dbConnect(ora, "scott", "tiger") res <- dbSendQuery(con, "select * from emp") fetch(res, n = 2) fetch(res) dbColumnInfo(res) dbClearResult(res) } } \keyword{database} \keyword{interface} \keyword{classes}
context("get.summary") # set up input of function get.summary adj_matrix <- matrix(c(0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0), byrow = TRUE, ncol = 4) dataSize <- 50 lambda <- 3.5 time <- 1 # test get.summary test_that("input adjacency matrix can be converted to the right edge list.", { ### Trivial case adj_matrix_trivial <- matrix(rep(0, 16), nrow = 4) no_parent <- vector("list", length = 4) no_parent <- lapply(no_parent, function(x){return(integer(0))}) expect_equal(get.summary(adj_matrix_trivial, dataSize, lambda, time)$nedge, 0) expect_equal(get.summary(adj_matrix_trivial, dataSize, lambda, time)$edges, sparsebnUtils::edgeList(no_parent)) ### when all nodes has just one parent adj_matrix_oneparent <- matrix(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1), byrow = TRUE, ncol = 4) expect_equal(get.summary(adj_matrix_oneparent, dataSize, lambda, time)$nedge, 3) true_edgeList_one <- vector("list", length = 4) true_edgeList_one[[1]] <- integer(0) true_edgeList_one[[2]] <- 4L true_edgeList_one[[3]] <- 4L true_edgeList_one[[4]] <- 4L true_edgeList_one <- sparsebnUtils::edgeList(true_edgeList_one) expect_equal(get.summary(adj_matrix_oneparent, dataSize, lambda, time)$edges, true_edgeList_one) ### Non-trivil case expect_equal(get.summary(adj_matrix, dataSize, lambda, time)$nedge, 4) true_edgeList <- vector("list", length = 4) true_edgeList[[1]] <- integer(0) true_edgeList[[2]] <- as.integer(1) true_edgeList[[3]] <- as.integer(c(1, 2)) true_edgeList[[4]] <- as.integer(3) true_edgeList <- sparsebnUtils::edgeList(true_edgeList) expect_equal(get.summary(adj_matrix, dataSize, lambda, time)$edges, true_edgeList) }) test_that("output the right lambda.", { expect_equal(get.summary(adj_matrix, dataSize, lambda, time)$lambda, 3.5) }) test_that("output the right time.", { ### Trivial case expect_equal(get.summary(adj_matrix, dataSize, lambda, time=NA)$time, NA) ### Non-trivial case expect_equal(get.summary(adj_matrix, dataSize, lambda, time)$time, 1) }) test_that("output the rigth nn.", { expect_equal(get.summary(adj_matrix, dataSize, lambda, time)$nn, 50) }) test_that("output the right pp.", { expect_equal(get.summary(adj_matrix, dataSize, lambda, time)$pp, 4) })
/fuzzedpackages/discretecdAlgorithm/tests/testthat/test-get_summary.R
no_license
akhikolla/testpackages
R
false
false
2,413
r
context("get.summary") # set up input of function get.summary adj_matrix <- matrix(c(0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0), byrow = TRUE, ncol = 4) dataSize <- 50 lambda <- 3.5 time <- 1 # test get.summary test_that("input adjacency matrix can be converted to the right edge list.", { ### Trivial case adj_matrix_trivial <- matrix(rep(0, 16), nrow = 4) no_parent <- vector("list", length = 4) no_parent <- lapply(no_parent, function(x){return(integer(0))}) expect_equal(get.summary(adj_matrix_trivial, dataSize, lambda, time)$nedge, 0) expect_equal(get.summary(adj_matrix_trivial, dataSize, lambda, time)$edges, sparsebnUtils::edgeList(no_parent)) ### when all nodes has just one parent adj_matrix_oneparent <- matrix(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1), byrow = TRUE, ncol = 4) expect_equal(get.summary(adj_matrix_oneparent, dataSize, lambda, time)$nedge, 3) true_edgeList_one <- vector("list", length = 4) true_edgeList_one[[1]] <- integer(0) true_edgeList_one[[2]] <- 4L true_edgeList_one[[3]] <- 4L true_edgeList_one[[4]] <- 4L true_edgeList_one <- sparsebnUtils::edgeList(true_edgeList_one) expect_equal(get.summary(adj_matrix_oneparent, dataSize, lambda, time)$edges, true_edgeList_one) ### Non-trivil case expect_equal(get.summary(adj_matrix, dataSize, lambda, time)$nedge, 4) true_edgeList <- vector("list", length = 4) true_edgeList[[1]] <- integer(0) true_edgeList[[2]] <- as.integer(1) true_edgeList[[3]] <- as.integer(c(1, 2)) true_edgeList[[4]] <- as.integer(3) true_edgeList <- sparsebnUtils::edgeList(true_edgeList) expect_equal(get.summary(adj_matrix, dataSize, lambda, time)$edges, true_edgeList) }) test_that("output the right lambda.", { expect_equal(get.summary(adj_matrix, dataSize, lambda, time)$lambda, 3.5) }) test_that("output the right time.", { ### Trivial case expect_equal(get.summary(adj_matrix, dataSize, lambda, time=NA)$time, NA) ### Non-trivial case expect_equal(get.summary(adj_matrix, dataSize, lambda, time)$time, 1) }) test_that("output the rigth nn.", { expect_equal(get.summary(adj_matrix, dataSize, lambda, time)$nn, 50) }) test_that("output the right pp.", { expect_equal(get.summary(adj_matrix, dataSize, lambda, time)$pp, 4) })
library(mosaic) library(lme4) library(tidyverse) library(lattice) library(MASS) library(MCMCpack) cheese = read.csv("/Users/zhendongwang/Desktop/R/cheese.csv") ## Linear regression hlm3 = lmer(log(vol) ~ (1 + log(price) + disp + log(price):disp | store), data=cheese) # Prior hyper-parameter for mu nu = colMeans(coef(hlm3)$store)[c(4, 1, 2, 3)] Kappa = 100 * diag(4) ## Build X and Y matrix cheese$store = factor(cheese$store) levels(cheese$store) <- c(1:88) cheese = cheese[order(cheese$store), ] M = as.numeric(summary(cheese$store)) n = 88 N = sum(M) cM = cumsum(M) mM = max(M) p = log(cheese$price) y = log(cheese$vol) d = cheese$disp l = cheese$store k = 4 Y = matrix(nrow = n, ncol = mM) X = array(dim = c(n, mM, k)) for (i in 1:n){ Y[i, ] = c(y[(cM[i]-M[i]+1):cM[i]], rep(0, mM-M[i])) X[i, , 1] = c(rep(1, M[i]), rep(0, mM-M[i])) X[i, , 2] = c(p[(cM[i]-M[i]+1):cM[i]], rep(0, mM-M[i])) X[i, , 3] = c(d[(cM[i]-M[i]+1):cM[i]], rep(0, mM-M[i])) X[i, , 4] = c(d[(cM[i]-M[i]+1):cM[i]] * p[(cM[i]-M[i]+1):cM[i]], rep(0, mM-M[i])) } Sxx = array(rep(0, n*k*k), dim = c(n, k, k)) Sxy = matrix(rep(0, n*k), nrow = n, ncol = k) for (i in 1:n){ for (j in 1:M[i]){ Sxx[i, , ] = Sxx[i, , ] + X[i, j, ] %*% t(X[i, j, ]) Sxy[i, ] = Sxy[i, ] + Y[i, j] * X[i, j, ] } } ## Set initial values mu = nu lambda = 1 Sigma = matrix(c(4.99925, -0.94*2.2359*2.1732, 0.48*2.2359*0.9807, -0.33*2.2359*0.8336, -0.94*2.2359*2.1732, 4.72274, -0.56*2.1732*0.9807, 0.39*2.1732*0.8336, 0.48*2.2359*0.9807, -0.56*2.1732*0.9807, 0.96184, -0.97*0.9807*0.8336, -0.33*2.2359*0.8336, 0.39*2.1732*0.8336, -0.97*0.9807*0.8336, 0.69495), nrow = 4, ncol = 4) Beta = matrix(nrow = n, ncol = k) ## Gibbs sampling burn = 5000 for (t in 1:burn){ print(t) IS = solve(Sigma) b = 0 # Update Beta for(i in 1:n){ V = solve(IS + lambda * Sxx[i, , ]) Mu = V %*% (lambda * Sxy[i, ] + IS %*% mu) Beta[i, ] = mvrnorm(1, Mu, V) b = b + sum((Y[i, 1:M[i]] - X[i, 1:M[i], ]%*%Beta[i, ])^2) } # Update lambda lambda = rgamma(1, (N+1)/2, b/2 + 1/2) # Update mu V = solve(n * IS + solve(Kappa)) Mu = V %*% (solve(Kappa) %*% nu + IS %*% apply(Beta, 2, sum)) mu = mvrnorm(1, Mu, V) # Update Sigma Mu = matrix(rep(mu,n), byrow=TRUE, nrow=n, ncol=k) Q = t(Beta - Mu) %*% (Beta - Mu) Sigma = riwish(n + 1, diag(k) + Q) } Sigma_sample = array(dim = c(B, k, k)) sigma_sample = c() mu_sample = matrix(nrow = B, ncol = k) Beta_sample = array(dim = c(B, n, k)) B = 10000 for (t in 1:B){ print(t) IS = solve(Sigma) b = 0 # Update Beta for(i in 1:n){ V = solve(IS + lambda * Sxx[i, , ]) Mu = V %*% (lambda * Sxy[i, ] + IS %*% mu) Beta[i, ] = mvrnorm(1, Mu, V) b = b + sum((Y[i, 1:M[i]] - X[i, 1:M[i], ]%*%Beta[i, ])^2) } # Update lambda lambda = rgamma(1, (N+1)/2, b/2 + 1/2) # Update mu V = solve(n * IS + solve(Kappa)) Mu = V %*% (solve(Kappa) %*% nu + IS %*% apply(Beta, 2, sum)) mu = mvrnorm(1, Mu, V) # Update Sigma Mu = matrix(rep(mu,n), byrow=TRUE, nrow=n, ncol=k) Q = t(Beta - Mu) %*% (Beta - Mu) Sigma = riwish(n + 1, diag(k) + Q) # Record samples Sigma_sample[t, , ] = Sigma sigma_sample[t] = lambda^(-0.5) mu_sample[t, ] = mu Beta_sample[t, , ] = Beta } ## Results sigma_hat = mean(sigma_sample) Beta_hat = matrix(nrow = n, ncol = k) error = 0 for (i in 1:n){ Beta_hat[i, ] = colMeans(Beta_sample[ , i, ]) error = error + sum((Y[i, 1:M[i]] - X[i, 1:M[i], ]%*%Beta[i, ])^2) } error = error / N
/Exercise-4-cheese.R
no_license
ShuyingWang/SDS383D
R
false
false
3,563
r
library(mosaic) library(lme4) library(tidyverse) library(lattice) library(MASS) library(MCMCpack) cheese = read.csv("/Users/zhendongwang/Desktop/R/cheese.csv") ## Linear regression hlm3 = lmer(log(vol) ~ (1 + log(price) + disp + log(price):disp | store), data=cheese) # Prior hyper-parameter for mu nu = colMeans(coef(hlm3)$store)[c(4, 1, 2, 3)] Kappa = 100 * diag(4) ## Build X and Y matrix cheese$store = factor(cheese$store) levels(cheese$store) <- c(1:88) cheese = cheese[order(cheese$store), ] M = as.numeric(summary(cheese$store)) n = 88 N = sum(M) cM = cumsum(M) mM = max(M) p = log(cheese$price) y = log(cheese$vol) d = cheese$disp l = cheese$store k = 4 Y = matrix(nrow = n, ncol = mM) X = array(dim = c(n, mM, k)) for (i in 1:n){ Y[i, ] = c(y[(cM[i]-M[i]+1):cM[i]], rep(0, mM-M[i])) X[i, , 1] = c(rep(1, M[i]), rep(0, mM-M[i])) X[i, , 2] = c(p[(cM[i]-M[i]+1):cM[i]], rep(0, mM-M[i])) X[i, , 3] = c(d[(cM[i]-M[i]+1):cM[i]], rep(0, mM-M[i])) X[i, , 4] = c(d[(cM[i]-M[i]+1):cM[i]] * p[(cM[i]-M[i]+1):cM[i]], rep(0, mM-M[i])) } Sxx = array(rep(0, n*k*k), dim = c(n, k, k)) Sxy = matrix(rep(0, n*k), nrow = n, ncol = k) for (i in 1:n){ for (j in 1:M[i]){ Sxx[i, , ] = Sxx[i, , ] + X[i, j, ] %*% t(X[i, j, ]) Sxy[i, ] = Sxy[i, ] + Y[i, j] * X[i, j, ] } } ## Set initial values mu = nu lambda = 1 Sigma = matrix(c(4.99925, -0.94*2.2359*2.1732, 0.48*2.2359*0.9807, -0.33*2.2359*0.8336, -0.94*2.2359*2.1732, 4.72274, -0.56*2.1732*0.9807, 0.39*2.1732*0.8336, 0.48*2.2359*0.9807, -0.56*2.1732*0.9807, 0.96184, -0.97*0.9807*0.8336, -0.33*2.2359*0.8336, 0.39*2.1732*0.8336, -0.97*0.9807*0.8336, 0.69495), nrow = 4, ncol = 4) Beta = matrix(nrow = n, ncol = k) ## Gibbs sampling burn = 5000 for (t in 1:burn){ print(t) IS = solve(Sigma) b = 0 # Update Beta for(i in 1:n){ V = solve(IS + lambda * Sxx[i, , ]) Mu = V %*% (lambda * Sxy[i, ] + IS %*% mu) Beta[i, ] = mvrnorm(1, Mu, V) b = b + sum((Y[i, 1:M[i]] - X[i, 1:M[i], ]%*%Beta[i, ])^2) } # Update lambda lambda = rgamma(1, (N+1)/2, b/2 + 1/2) # Update mu V = solve(n * IS + solve(Kappa)) Mu = V %*% (solve(Kappa) %*% nu + IS %*% apply(Beta, 2, sum)) mu = mvrnorm(1, Mu, V) # Update Sigma Mu = matrix(rep(mu,n), byrow=TRUE, nrow=n, ncol=k) Q = t(Beta - Mu) %*% (Beta - Mu) Sigma = riwish(n + 1, diag(k) + Q) } Sigma_sample = array(dim = c(B, k, k)) sigma_sample = c() mu_sample = matrix(nrow = B, ncol = k) Beta_sample = array(dim = c(B, n, k)) B = 10000 for (t in 1:B){ print(t) IS = solve(Sigma) b = 0 # Update Beta for(i in 1:n){ V = solve(IS + lambda * Sxx[i, , ]) Mu = V %*% (lambda * Sxy[i, ] + IS %*% mu) Beta[i, ] = mvrnorm(1, Mu, V) b = b + sum((Y[i, 1:M[i]] - X[i, 1:M[i], ]%*%Beta[i, ])^2) } # Update lambda lambda = rgamma(1, (N+1)/2, b/2 + 1/2) # Update mu V = solve(n * IS + solve(Kappa)) Mu = V %*% (solve(Kappa) %*% nu + IS %*% apply(Beta, 2, sum)) mu = mvrnorm(1, Mu, V) # Update Sigma Mu = matrix(rep(mu,n), byrow=TRUE, nrow=n, ncol=k) Q = t(Beta - Mu) %*% (Beta - Mu) Sigma = riwish(n + 1, diag(k) + Q) # Record samples Sigma_sample[t, , ] = Sigma sigma_sample[t] = lambda^(-0.5) mu_sample[t, ] = mu Beta_sample[t, , ] = Beta } ## Results sigma_hat = mean(sigma_sample) Beta_hat = matrix(nrow = n, ncol = k) error = 0 for (i in 1:n){ Beta_hat[i, ] = colMeans(Beta_sample[ , i, ]) error = error + sum((Y[i, 1:M[i]] - X[i, 1:M[i], ]%*%Beta[i, ])^2) } error = error / N
library(evd) library(Matrix) library(tidyverse) library(knitr) library(INLA) library(mapdata) library(data.table) library(rgdal) # A few helper functions source("helperFun.R") #### Get the data ready # Read in the data # Get catchment descriptors and flow data load("catchmentDesc.RData") # catchmentDesc load("flowDataSample.RData") # flowData # Number of stations n_st <- nrow(catchmentDesc) stations <- unique(catchmentDesc$Station) ###################### ML step ############################################ # Constants xi00 <- 0 alp3 <- 0.8 # c_phi alpha <- 4 beta <- 4 sig3 = (log(1 - (xi00+0.5)^alp3))*(1 - (xi00+0.5)^alp3)*(-(alp3)^(-1)*(xi00+0.5)^(-alp3+1)) # b_phi b3 <- -sig3*(log(-log(1-0.5^alp3))) # a_phi # Likelihood function to minimize fn <- function(theta,y,t) { n <- length(t) t_e <- 1975 delta_0 <- 1/125 #delta_0 <- 0.02 gamma <- theta[4] log_delta_i <- log(2*delta_0) + 2*gamma/delta_0 - log(1 + exp(2*gamma/delta_0)) delta_i <- exp(log_delta_i)-delta_0 mu_it <- (1 + delta_i*(t-t_e))*exp(theta[1]) sigma_i <- exp(theta[2] + theta[1]) if(sigma_i<=0){ return(100000) } sig3 <- (log(1 - (xi00+0.5)^alp3))*(1 - (xi00+0.5)^alp3)*(-(alp3)^(-1)*(xi00+0.5)^(-alp3+1)) b3 <- -sig3*(log(-log(1-0.5^alp3))) xitheta <- (1 - exp(-exp((theta[3]-b3)/sig3)))^(1/alp3) - 0.5 sum_loglik <- 0 for(i in 1:n){ sum_loglik <- sum_loglik + dgev(y[i], loc = mu_it[i], scale = sigma_i, shape = xitheta, log = TRUE) } res = -sum_loglik - ((alpha - alp3)*log(xitheta + 0.5) + (beta-1)*log(0.5 - xitheta) + (theta[3]-b3)/sig3 - exp((theta[3]-b3)/sig3) ) + 0.5*gamma^2/((0.5*delta_0)^2) return(res) } ####################### ML step ############################################## dt_mles <- data.frame() for(i in 1:n_st){ station <- stations[i] currentS <- flowData %>% filter(Station == station) # This is done to get some initial guess at the location, scale and shape parameters GEV_fit <- fgev(currentS$Flow) mu0 <- GEV_fit$estimate[1] sigma0 <- GEV_fit$estimate[2] xi0 <- GEV_fit$estimate[3] if (xi0 > 0) { xi0 <- min(xi0,0.45) } else { xi0 <- max(xi0,-0.45) } theta0 <- c(log(mu0),log(sigma0)-log(mu0),b3 + sig3*log(-log(1 - (xi0+0.5)^alp3)), 0) GEV_fit <- nlm(fn, theta <- theta0, y <- currentS$Flow, t <- currentS$year, hessian = T) S_d <- try(solve(GEV_fit$hessian),silent=T) if(i %% 10 == 0) print(i) res <- data.frame( Station = station, psi = GEV_fit$estimate[1], tau = GEV_fit$estimate[2], kappa = GEV_fit$estimate[3], gamma = GEV_fit$estimate[4], v_p = S_d[1,1], v_p_t = S_d[1,2], v_p_k = S_d[1,3], v_p_g = S_d[1,4], v_t = S_d[2,2], v_t_k = S_d[2,3], v_t_g = S_d[2,4], v_k = S_d[3,3], v_k_g = S_d[3,4], v_g = S_d[4,4] ) dt_mles <- rbind(res, dt_mles) } ################################## Make covariates ready ##################################################################### # To make sure that the covariates are in the same order as ml estimates catchmentDesc <- dt_mles %>% select(Station) %>% left_join(catchmentDesc) names <- c( "Int.", "log(Area)", "log(SAAR)", "log(FARL)", "BFIHOST^2", "log(FPEXT)", "log(URBEXT+1)", "log(DPLBAR)", "log(DPSBAR)", "log(LDP)", "log(SPRHOST)", "log(ASPBAR)", "log(ALTBAR)", "log(ASPVAR)", "log(PROPWET)") ncols <- length(names) covariates <- matrix(c( rep(1,n_st), # Intercept transform(catchmentDesc$Area, "AREA"), transform(catchmentDesc$SAAR, "SAAR"), transform(catchmentDesc$FARL, "FARL"), transform(catchmentDesc$BFIHOST, "BFIHOST"), transform(catchmentDesc$FPEXT, "FPEXT"), transform(catchmentDesc$URBEXT2000, "URBEXT"), transform(catchmentDesc$DPLBAR, "DPLBAR"), transform(catchmentDesc$DPSBAR, "DPSBAR"), transform(catchmentDesc$LDP, "LDP"), transform(catchmentDesc$SPRHOST, "SPRHOST"), transform(catchmentDesc$ASPBAR, "ASPBAR"), transform(catchmentDesc$ALTBAR, "ALTBAR"), transform(catchmentDesc$ASPVAR, "ASPVAR"), transform(catchmentDesc$PROPWET, "PROPWET") ), ncol = 15, nrow = n_st ) colnames(covariates) <- names ################################ Make X matrices for psi, tau and xi ######################################################### cov_names_psi <- c("Int.","log(Area)", "log(SAAR)", "log(FARL)", "BFIHOST^2") cov_names_tau <- c("Int.","log(Area)", "log(SAAR)", "log(FARL)", "log(FPEXT)", "log(URBEXT+1)") cov_names_kappa <- c("Int.", "log(FPEXT)") cov_names_gamma <- c("Int.", "log(PROPWET)") X_psi <- covariates[, c("Int.","log(Area)", "log(SAAR)", "log(FARL)", "BFIHOST^2")] X_tau <- covariates[, c("Int.","log(Area)", "log(SAAR)", "log(FARL)", "log(FPEXT)", "log(URBEXT+1)")] X_kappa <- as.matrix(covariates[, c("Int.", "log(FPEXT)")]) X_gamma <- as.matrix(covariates[, c("Int.", "log(PROPWET)")]) ############################### Make mesh and A matrices for spatial component ############################################### coords <- cbind(catchmentDesc$long, catchmentDesc$lat) mesh <- inla.mesh.2d( loc=coords, offset = 0.08, max.edge = 0.07, cutoff = 0.005) # To plot mesh # plot(mesh) # Make A matrix - The same for psi and tau A_mat <- inla.spde.make.A(mesh, loc=coords) A_psi <- A_mat A_tau <- A_mat ################# Fit INLA models, to have good starting proposal distribution ############### # Add location to MLE data dt_mles <- dt_mles %>% left_join(catchmentDesc %>% dplyr::select(Northing, Easting, Station,long,lat)) mdl_sep_psi <- fit_model_psi(data = dt_mles, desc = X_psi) mdl_sep_tau <- fit_model_tau(data = dt_mles, desc = X_tau) mdl_sep_xi <- fit_model_kappa(data = dt_mles, desc = X_kappa) mdl_sep_gamma <- fit_model_gamma(data = dt_mles, desc = X_gamma) # The spde object is only used for getting the precision matrix for a given range and sd # so priors do not matter here d_spde <- inla.spde2.pcmatern(mesh, prior.range = c(.5, .5), prior.sigma = c(.5, .5)) # Make the Z matrix Z <- bdiag(cbind(X_psi,A_psi), cbind(X_tau, A_tau), X_kappa, X_gamma) N_psi <- dim(X_psi)[2] N_tau <- dim(X_tau)[2] N_xi <- dim(X_kappa)[2] N_gamma <- dim(X_gamma)[2] N_colsA <- dim(A_psi)[2] ################################################ Helper functions ################################################### # Make the covariance matrix for the observations makeSigma_etay <- function(dt){ N_rows <- dim(dt)[1] Sigma_etay <- matrix(0, nrow = 4*N_rows, ncol = 4*N_rows) for(i in 1:N_rows){ Sigma_etay[i,i] <- dt$v_p[i] Sigma_etay[i,i+N_rows] <- dt$v_p_t[i] Sigma_etay[i,i+2*N_rows] <- dt$v_p_k[i] Sigma_etay[i,i+3*N_rows] <- dt$v_p_g[i] } for(i in 1:N_rows){ Sigma_etay[i+N_rows,i] <- dt$v_p_t[i] Sigma_etay[i+N_rows,i+N_rows] <- dt$v_t[i] Sigma_etay[i+N_rows,i+2*N_rows] <- dt$v_t_k[i] Sigma_etay[i+N_rows,i+3*N_rows] <- dt$v_t_g[i] } for(i in 1:N_rows){ Sigma_etay[i+2*N_rows,i] <- dt$v_p_k[i] Sigma_etay[i+2*N_rows,i+N_rows] <- dt$v_t_k[i] Sigma_etay[i+2*N_rows,i+2*N_rows] <- dt$v_k[i] Sigma_etay[i+2*N_rows,i+3*N_rows] <- dt$v_k_g[i] } for(i in 1:N_rows){ Sigma_etay[i+3*N_rows,i] <- dt$v_p_g[i] Sigma_etay[i+3*N_rows,i+N_rows] <- dt$v_t_g[i] Sigma_etay[i+3*N_rows,i+2*N_rows] <- dt$v_k_g[i] Sigma_etay[i+3*N_rows,i+3*N_rows] <- dt$v_g[i] } return(Matrix(Sigma_etay)) } get_mode_mean_sd_for_hyperparameter <- function(mdl, fun, hyperparameter){ x0 <- mdl$marginals.hyperpar[[hyperparameter]] E <- inla.emarginal(function(x) c(fun(x), fun(x)^2), x0) sd <- sqrt(E[2] - E[1]^2) mean <- E[1] mt_tmp <- inla.tmarginal(fun, x0) dat_tmp <- inla.smarginal(mt_tmp) mode <- dat_tmp$x[which(dat_tmp$y == max(dat_tmp$y))] return(list(sd = sd, mean = mean, mode = mode)) } log_f_x_given_theta <- function(kappa, Q_x){ res <- determinant(Q_x, logarithm = T) res <- .5*res$modulus[1]*res$sign return(res) } log_f_x_given_eta_hat_and_theta <- function(kappa, Q_x_given_etaHat, N, Z, eta_hat, Q_etay, K){ mu_x_given_etaHat <- solve(a = Cholesky(Q_x_given_etaHat),b = b) determ <- determinant(Q_x_given_etaHat, logarithm = T) res <- -.5*t(mu_x_given_etaHat)%*%(Q_x_given_etaHat%*%mu_x_given_etaHat) res <- res + .5*determ$modulus[1]*determ$sign return(res) } calc_Q_x_given_etaHat <- function(Q_x, N, Q_etay){ Q_x_given_etaHat <- Q_x Q_x_given_etaHat[1:(4*N), 1:(4*N)] <- Q_x[1:(4*N), 1:(4*N)] + Q_etay return(Q_x_given_etaHat) } calc_Q_x <- function(kappa = k_st, Q_beta_psi, Q_beta_tau, Q_beta_xi,Q_beta_gamma, N, Z, d_spde){ Q_u_psi <- makeQ_u(s = exp(kappa$u_psi), rho = exp(kappa$v_psi), d_spde) Q_u_tau <- makeQ_u(s = exp(kappa$u_tau), rho = exp(kappa$v_tau), d_spde) Q_nu <- bdiag(Q_beta_psi,Q_u_psi,Q_beta_tau,Q_u_tau,Q_beta_xi,Q_beta_gamma) Q_epsilon <- bdiag(Diagonal(N,exp(kappa$kappa_psi)), Diagonal(N,exp(kappa$kappa_tau)), Diagonal(N,exp(kappa$kappa_xi)),Diagonal(N,exp(kappa$kappa_gamma))) K <- dim(Q_nu)[1] Q_x[1:(4*N), 1:(4*N)] <- Q_epsilon Q_x[1:K + 4*N,1:(4*N)] <- -t(Z)%*%Q_epsilon Q_x[1:(4*N), 1:K + 4*N] <- - (Q_epsilon %*% Z) Q_x[1:K + 4*N, 1:K + 4*N] <- Q_nu + t(Z)%*%Q_epsilon%*%Z return(Q_x) } ################################## Prior matrices for covariate coefficients ################################### betaVarPrior <- 10000 K <- 2*N_colsA + N_psi +N_tau +N_xi + N_gamma Q_beta_psi <- Diagonal(N_psi, 1/betaVarPrior) Q_beta_tau <- Diagonal(N_tau, 1/betaVarPrior) Q_beta_xi <- Diagonal(N_xi, 1/betaVarPrior) Q_beta_gamma <- Diagonal(N_gamma, 1/betaVarPrior) ################# get variance and mode for hyper parameters for proposal distribution ############################### tau_psi_0 <- get_mode_mean_sd_for_hyperparameter(mdl_sep_psi$mdl, function(x) log(x), "Precision for idx") tau_tau_0 <- get_mode_mean_sd_for_hyperparameter(mdl_sep_tau$mdl, function(x) log(x), "Precision for idx") tau_xi_0 <- get_mode_mean_sd_for_hyperparameter(mdl_sep_xi$mdl, function(x) log(x), "Precision for idx") tau_gamma_0 <- get_mode_mean_sd_for_hyperparameter(mdl_sep_gamma$mdl, function(x) log(x), "Precision for idx") rho_psi_0 <- get_mode_mean_sd_for_hyperparameter(mdl_sep_psi$mdl, function(x) log(x), "Range for s") rho_tau_0 <- get_mode_mean_sd_for_hyperparameter(mdl_sep_tau$mdl, function(x) log(x), "Range for s") sigma_psi_0 <- get_mode_mean_sd_for_hyperparameter(mdl_sep_psi$mdl, function(x) log(x), "Stdev for s") sigma_tau_0 <- get_mode_mean_sd_for_hyperparameter(mdl_sep_tau$mdl, function(x) log(x), "Stdev for s") # Number of stations N <- nrow(dt_mles) eta_hat <- matrix(c(dt_mles$psi, dt_mles$tau, dt_mles$kappa, dt_mles$gamma), nrow = 4 * N) ###### Make sigma_eta_y sigma_eta_y <- makeSigma_etay(dt = dt_mles) Q_etay <- solve(sigma_eta_y) # Mean and covariance matrix of the proposal distribution in the first loop kappa_0 <- c(tau_psi_0$mode, rho_psi_0$mode, sigma_psi_0$mode, tau_tau_0$mode, rho_tau_0$mode, sigma_tau_0$mode, tau_xi_0$mode, tau_gamma_0$mode) %>% as.matrix() # Might need to change the proposal distribution #load("proposalCovar.RData") # This is another option for a covariance matrix for the proposal distribution Sigma_kappa_0 <- diag(c(tau_psi_0$sd^2*4, rho_psi_0$sd^2, sigma_psi_0$sd^2, tau_tau_0$sd^2*2, rho_tau_0$sd^2, sigma_tau_0$sd^2, tau_xi_0$sd^2*0.7, tau_gamma_0$sd^2/2)*0.5 ) library(MASS) library(SparseM) #################################### Model fitting - Hyperparameters (One chain) ################## # Could also run more chains here parallel for example using mclapply from the parallel package N_samples <- 500 # Change this number to take more samples Q_x <- Matrix(0,nrow = 4*N+K, ncol = 4*N+K) B <- Matrix(0,nrow = 4*N, ncol = 4*N+K) B[1:(4*N),1:(4*N)] <- diag(1,4*N) b <- t(B)%*%(Q_etay%*%eta_hat) kappa_k <- mvrnorm(mu = kappa_0, Sigma = Sigma_kappa_0) kappa_mat <- matrix(NA, nrow = length(kappa_k), ncol = N_samples) kappa_k_is_kappa_star <- F accept <- 0 for(i in 1:N_samples){ kappa_star <- mvrnorm(mu = kappa_k, Sigma = Sigma_kappa_0) k_st <- list( kappa_psi = kappa_star[1], v_psi = kappa_star[2], u_psi = kappa_star[3], kappa_tau = kappa_star[4], v_tau = kappa_star[5], u_tau = kappa_star[6], kappa_xi = kappa_star[7], kappa_gamma = kappa_star[8] ) k_k <- list( kappa_psi = kappa_k[1], v_psi = kappa_k[2], u_psi = kappa_k[3], kappa_tau = kappa_k[4], v_tau = kappa_k[5], u_tau = kappa_k[6], kappa_xi = kappa_k[7], kappa_gamma = kappa_k[8] ) if(i == 1){ Q_x <- calc_Q_x(kappa = k_st, Q_beta_psi, Q_beta_tau, Q_beta_xi, Q_beta_gamma, N, Z, d_spde) Q_x_given_etaHat <- calc_Q_x_given_etaHat(Q_x = Q_x, N = N, Q_etay = Q_etay) l_x_etaHat_k_st <- log_f_x_given_eta_hat_and_theta(kappa = k_st, Q_x_given_etaHat = Q_x_given_etaHat, N = N, Z = Z, eta_hat = eta_hat, Q_etay = Q_etay,K = K) l_x_k_st <- log_f_x_given_theta(kappa = k_st, Q_x) l_prior_k_st <- log_prior_logTheta(k_st) Q_x <- calc_Q_x(kappa = k_k, Q_beta_psi, Q_beta_tau, Q_beta_xi, Q_beta_gamma, N, Z, d_spde) Q_x_given_etaHat <- calc_Q_x_given_etaHat(Q_x = Q_x, N = N, Q_etay = Q_etay) l_x_etaHat_k_k <- log_f_x_given_eta_hat_and_theta(kappa = k_k, Q_x_given_etaHat = Q_x_given_etaHat, N = N, Z = Z, eta_hat = eta_hat, Q_etay = Q_etay,K = K) l_x_k_k <- log_f_x_given_theta(kappa = k_k, Q_x) l_prior_k_k <- log_prior_logTheta(kappa = k_k) }else if(kappa_k_is_kappa_star){ Q_x <- calc_Q_x(kappa = k_st, Q_beta_psi, Q_beta_tau, Q_beta_xi, Q_beta_gamma, N, Z, d_spde) Q_x_given_etaHat <- calc_Q_x_given_etaHat(Q_x = Q_x, N = N, Q_etay = Q_etay) l_x_etaHat_k_k <- l_x_etaHat_k_st l_x_k_k <- l_x_k_st l_prior_k_k <- l_prior_k_st l_x_etaHat_k_st <- log_f_x_given_eta_hat_and_theta(kappa = k_st, Q_x_given_etaHat = Q_x_given_etaHat, N = N, Z = Z, eta_hat = eta_hat, Q_etay = Q_etay,K = K) l_x_k_st <- log_f_x_given_theta(kappa = k_st, Q_x) l_prior_k_st <- log_prior_logTheta(k_st) }else{ Q_x <- calc_Q_x(kappa = k_st, Q_beta_psi, Q_beta_tau, Q_beta_xi, Q_beta_gamma, N, Z, d_spde) Q_x_given_etaHat <- calc_Q_x_given_etaHat(Q_x = Q_x, N = N, Q_etay = Q_etay) l_x_etaHat_k_st <- log_f_x_given_eta_hat_and_theta(kappa = k_st, Q_x_given_etaHat = Q_x_given_etaHat, N = N, Z = Z, eta_hat = eta_hat, Q_etay = Q_etay,K = K) l_x_k_st <- log_f_x_given_theta(kappa = k_st, Q_x) l_prior_k_st <- log_prior_logTheta(k_st) } r <- l_prior_k_st-l_prior_k_k+l_x_k_st-l_x_k_k+l_x_etaHat_k_k-l_x_etaHat_k_st if(as.numeric(r) > log(runif(1,0,1))){ kappa_k <- kappa_star kappa_k_is_kappa_star = T accept <- accept + 1 }else{ kappa_k <- kappa_k kappa_k_is_kappa_star = F } kappa_mat[,i] <- kappa_k } accept/N_samples # Take first 20% as burn-in. burnIn <- 0.2 chain <- kappa_mat[,seq(burnIn*N_samples,N_samples,1)] sigma_psi <- sqrt(1/exp(chain[1,])) sigma_tau <- sqrt(1/exp(chain[4,])) sigma_xi <- sqrt(1/exp(chain[7,])) sigma_gamma <- sqrt(1/exp(chain[8,])) r_psi <- exp(chain[2,]) s_psi <- exp(chain[3,]) r_tau <- exp(chain[5,]) s_tau <- exp(chain[6,]) ############################ ############################ Spatial hyper for psi ############################ ############################ psi_hyper_sp <- data.frame( rho_psi = r_psi, s_psi = s_psi ) N_dim_dens <- 100 kd <- with(psi_hyper_sp, MASS::kde2d(s_psi, rho_psi, n = 100)) tmpDraslDt <- data.table() for(i in 1:N_dim_dens){ tmpDraslDt <- rbind(tmpDraslDt, data.table(z = kd$z[i,], x = rep(kd$x[i],N_dim_dens), y=kd$y)) } p1 <- ggplot(tmpDraslDt, aes(x, y, z = z))+ geom_raster(aes(fill = z)) + geom_contour(col = "white") + #xlim(c(0.22,0.4)) + ylim(c(NA,0.08)) + labs( x = expression(s[psi]), y = expression(rho[psi]), fill = "Density" ) + scale_fill_gradientn(colours = terrain.colors(10)) + theme_bw() long_hyper_psi_sp <- gather(psi_hyper_sp, key = Type, value = Value) long_hyper_psi_sp$Type <- factor(long_hyper_psi_sp$Type) levels(long_hyper_psi_sp$Type) <- c("rho[psi]", "s[psi]") p2 <- ggplot(long_hyper_psi_sp, aes(Value)) + geom_density(fill = "black", alpha = .4) + facet_wrap(~Type, scales = "free", labeller = label_parsed) + theme_bw() + labs(x = "", y = "Density") multiplot(p1, p2) ############################ ############################ Spatial hyper for tau ############################ ############################ tau_hyper_sp <- data.table( rho_tau = r_tau, s_tau = s_tau ) N_dim_dens <- 100 kd <- with(tau_hyper_sp, MASS::kde2d(s_tau, rho_tau, n = 100)) tmpDraslDt2 <- data.table() for(i in 1:N_dim_dens){ tmpDraslDt2 <- rbind(tmpDraslDt2, data.table(z = kd$z[i,], x = rep(kd$x[i],N_dim_dens), y=kd$y)) } p1 <- ggplot(tmpDraslDt2, aes(x, y, z = z))+ geom_raster(aes(fill = z)) + geom_contour(col = "white") + ylim(c(NA,0.16)) + xlim(c(NA,0.25)) + labs( x = expression(s[tau]), y = expression(rho[tau]), fill = "Density" ) + scale_fill_gradientn(colours = terrain.colors(10)) + theme_bw() long_hyper_tau_sp <- gather(tau_hyper_sp, key = Type, value = Value) long_hyper_tau_sp$Type <- factor(long_hyper_tau_sp$Type) levels(long_hyper_tau_sp$Type) <- c("rho[tau]", "s[tau]") p2 <- ggplot(long_hyper_tau_sp, aes(Value)) + geom_density(fill = "black", alpha = .4) + facet_wrap(~Type, scales = "free", labeller = label_parsed) + theme_bw() + labs(x = "", y = "Density") multiplot(p1, p2) ################################################## iid random effects ############################ ############################ model_error_hyper <- data.table( sigma_psi = sigma_psi, sigma_tau = sigma_tau, sigma_xi = sigma_xi, sigma_gamma = sigma_gamma ) long_model_error_hyper <- gather(model_error_hyper, key = Type, value = Value) long_model_error_hyper$Type <- factor(long_model_error_hyper$Type, levels = c("sigma_psi","sigma_tau","sigma_xi","sigma_gamma")) levels(long_model_error_hyper$Type) <- c("sigma[psi*epsilon]","sigma[tau*epsilon]","sigma[phi*epsilon]","sigma[gamma*epsilon]") ggplot(long_model_error_hyper %>% filter(!(Type == "sigma[gamma*epsilon]" & Value > 0.0015)), aes(Value)) + geom_density(fill = "black", alpha = .3) + facet_wrap(~Type, scales = "free", ncol = 2, labeller = label_parsed) + labs(x="",y="Density") + theme_bw() #################################### Latent parameter posterior samples #################################### N_x_loops <- dim(chain)[2] x_mat <- matrix(NA, nrow = K+4*N, ncol = N_x_loops) kappa_old <- rep(0,8) start <- proc.time() Q_x <- Matrix(0,nrow = 4*N+K, ncol = 4*N+K) B <- Matrix(0,nrow = 4*N, ncol = 4*N+K) B[1:(4*N),1:(4*N)] <- Diagonal(4*N, 1) b <- t(B)%*%(Q_etay%*%eta_hat) for(i in 1:N_x_loops){ k <- list( kappa_psi = chain[1,i], v_psi = chain[2,i], u_psi = chain[3,i], kappa_tau = chain[4,i], v_tau = chain[5,i], u_tau = chain[6,i], kappa_xi = chain[7,i], kappa_gamma = chain[8,i] ) Q_x <- calc_Q_x(kappa = k, Q_beta_psi = Q_beta_psi, Q_beta_tau = Q_beta_tau, Q_beta_xi = Q_beta_xi, Q_beta_gamma = Q_beta_gamma, N = N, Z = Z, d_spde = d_spde) Q_x_given_etaHat <- calc_Q_x_given_etaHat(Q_x = Q_x,N = N, Q_etay = Q_etay) mu_x_given_etaHat <- solve(a = Cholesky(Q_x_given_etaHat),b = b) x <- inla.qsample(n = 1, mu = mu_x_given_etaHat, Q = Q_x_given_etaHat) x_mat[,i] <- x } stop <- proc.time()-start # x_mat contains the posterior samples for the latent parameters ############################## Posterior samples for psi, tau, kappa and gamma ######## eta <- x_mat[1:(4*N),] psi <- eta[1:N,] tau <- eta[1:N + N,] kappa <- eta[1:N + 2*N,] gamma <- eta[1:N + 3*N,] ############################################## covariate coefficient results ############################################## # Posterior samples for the covariate coefficients and the spatial components nu <- x_mat[(4*N+1):nrow(x_mat),] beta_psi <- nu[1:N_psi,] u_psi <- nu[1:N_colsA + N_psi,] beta_tau <- nu[1:N_tau + N_psi + N_colsA,] u_tau <- nu[1:N_colsA + N_tau + N_psi + N_colsA,] beta_kappa <- nu[1:N_xi + N_colsA + N_tau + N_psi + N_colsA,] beta_gamma <- nu[1:N_gamma + N_xi + N_colsA + N_tau + N_psi + N_colsA,] # results for the covariate coefficients beta_psi_results <- data.frame( Covariate = colnames(X_psi), Mean = apply(beta_psi, 1, mean), Sd = apply(beta_psi, 1, sd), q_025 = apply(beta_psi, 1, quantile, probs = 0.025), q_50 = apply(beta_psi, 1, quantile, probs = 0.5), q_975 = apply(beta_psi, 1, quantile, probs = 0.975) ) beta_psi_results beta_tau_results <- data.frame( Covariate = colnames(X_tau), Mean = apply(beta_tau, 1, mean), Sd = apply(beta_tau, 1, sd), q_025 = apply(beta_tau, 1, quantile, probs = 0.025), q_50 = apply(beta_tau, 1, quantile, probs = 0.5), q_975 = apply(beta_tau, 1, quantile, probs = 0.975) ) beta_tau_results beta_kappa_results <- data.frame( Covariate = colnames(X_kappa), Mean = apply(beta_kappa, 1, mean), Sd = apply(beta_kappa, 1, sd), q_025 = apply(beta_kappa, 1, quantile, probs = 0.025), q_50 = apply(beta_kappa, 1, quantile, probs = 0.5), q_975 = apply(beta_kappa, 1, quantile, probs = 0.975) ) beta_kappa_results beta_gamma_results <- data.frame( Covariate = colnames(X_gamma), Mean = apply(beta_gamma, 1, mean), Sd = apply(beta_gamma, 1, sd), q_025 = apply(beta_gamma, 1, quantile, probs = 0.025), q_50 = apply(beta_gamma, 1, quantile, probs = 0.5), q_975 = apply(beta_gamma, 1, quantile, probs = 0.975) ) beta_gamma_results # Spatial fields # This gives us the value of the spatial field for psi and tau at each station location Au_psi <- A_psi %*% u_psi Au_tau <- A_tau %*% u_tau # Plot the spatial field on a map of the UK local.plot.field = function(field, mesh, xlim=c(-0.1,1), ylim=c(-0.1,1), ...){ stopifnot(length(field) == mesh$n) # error when using the wrong mesh proj = inla.mesh.projector(mesh, dims=c(300, 300)) # Can project from the mesh onto a 300x300 plotting grid field.proj = inla.mesh.project(proj, field) # Do the projection image.plot(list(x = proj$x, y=proj$y, z = field.proj), xlim = xlim, ylim = ylim, ...) } u_psi_m <- apply(u_psi, 1, mean) u_tau_m <- apply(u_tau, 1, mean) library(RColorBrewer) library(fields) rf <- colorRampPalette(rev(brewer.pal(11,'Spectral'))) # make colors r <- rf(64) colorTable<- designer.colors(20, c( "#5ab4ac","white", "#d8b365"), x = c(min(u_psi_m), 0, max(u_psi_m)) / (max(u_psi_m) -min(u_psi_m))) colorTable<- designer.colors(100, c( "#e66101","#fdb863","#b2abd2", "#5e3c99"), x = c(min(u_psi_m),quantile(u_psi_m, 0.25), 0, max(u_psi_m)) / (max(u_psi_m) -min(u_psi_m))) colorTable2<- designer.colors(100, c( "#e66101","#fdb863","#b2abd2", "#5e3c99"), x = c(min(u_tau_m),quantile(u_tau_m, 0.25), 0, max(u_tau_m)) / (max(u_tau_m) -min(u_tau_m))) # Get the outlines of Great Britain map_scaled <- convertCoords(dt = dt_mles)$map_scaled # Spatial field for psi local.plot.field(field = u_psi_m, mesh, col = colorTable) points(map_scaled$long, map_scaled$lat, pch = 20, cex=.2) points(coords[,1],coords[,2], pch = 20, col = "black", cex = .3) # Spatial field for tau local.plot.field(field = u_tau_m, mesh, col = colorTable2) points(map_scaled$long, map_scaled$lat, pch = 20, cex=.2) points(coords[,1],coords[,2], pch = 20, col = "black", cex = .3)
/fitModel.R
no_license
ridivinra/GEV_LGM
R
false
false
23,560
r
library(evd) library(Matrix) library(tidyverse) library(knitr) library(INLA) library(mapdata) library(data.table) library(rgdal) # A few helper functions source("helperFun.R") #### Get the data ready # Read in the data # Get catchment descriptors and flow data load("catchmentDesc.RData") # catchmentDesc load("flowDataSample.RData") # flowData # Number of stations n_st <- nrow(catchmentDesc) stations <- unique(catchmentDesc$Station) ###################### ML step ############################################ # Constants xi00 <- 0 alp3 <- 0.8 # c_phi alpha <- 4 beta <- 4 sig3 = (log(1 - (xi00+0.5)^alp3))*(1 - (xi00+0.5)^alp3)*(-(alp3)^(-1)*(xi00+0.5)^(-alp3+1)) # b_phi b3 <- -sig3*(log(-log(1-0.5^alp3))) # a_phi # Likelihood function to minimize fn <- function(theta,y,t) { n <- length(t) t_e <- 1975 delta_0 <- 1/125 #delta_0 <- 0.02 gamma <- theta[4] log_delta_i <- log(2*delta_0) + 2*gamma/delta_0 - log(1 + exp(2*gamma/delta_0)) delta_i <- exp(log_delta_i)-delta_0 mu_it <- (1 + delta_i*(t-t_e))*exp(theta[1]) sigma_i <- exp(theta[2] + theta[1]) if(sigma_i<=0){ return(100000) } sig3 <- (log(1 - (xi00+0.5)^alp3))*(1 - (xi00+0.5)^alp3)*(-(alp3)^(-1)*(xi00+0.5)^(-alp3+1)) b3 <- -sig3*(log(-log(1-0.5^alp3))) xitheta <- (1 - exp(-exp((theta[3]-b3)/sig3)))^(1/alp3) - 0.5 sum_loglik <- 0 for(i in 1:n){ sum_loglik <- sum_loglik + dgev(y[i], loc = mu_it[i], scale = sigma_i, shape = xitheta, log = TRUE) } res = -sum_loglik - ((alpha - alp3)*log(xitheta + 0.5) + (beta-1)*log(0.5 - xitheta) + (theta[3]-b3)/sig3 - exp((theta[3]-b3)/sig3) ) + 0.5*gamma^2/((0.5*delta_0)^2) return(res) } ####################### ML step ############################################## dt_mles <- data.frame() for(i in 1:n_st){ station <- stations[i] currentS <- flowData %>% filter(Station == station) # This is done to get some initial guess at the location, scale and shape parameters GEV_fit <- fgev(currentS$Flow) mu0 <- GEV_fit$estimate[1] sigma0 <- GEV_fit$estimate[2] xi0 <- GEV_fit$estimate[3] if (xi0 > 0) { xi0 <- min(xi0,0.45) } else { xi0 <- max(xi0,-0.45) } theta0 <- c(log(mu0),log(sigma0)-log(mu0),b3 + sig3*log(-log(1 - (xi0+0.5)^alp3)), 0) GEV_fit <- nlm(fn, theta <- theta0, y <- currentS$Flow, t <- currentS$year, hessian = T) S_d <- try(solve(GEV_fit$hessian),silent=T) if(i %% 10 == 0) print(i) res <- data.frame( Station = station, psi = GEV_fit$estimate[1], tau = GEV_fit$estimate[2], kappa = GEV_fit$estimate[3], gamma = GEV_fit$estimate[4], v_p = S_d[1,1], v_p_t = S_d[1,2], v_p_k = S_d[1,3], v_p_g = S_d[1,4], v_t = S_d[2,2], v_t_k = S_d[2,3], v_t_g = S_d[2,4], v_k = S_d[3,3], v_k_g = S_d[3,4], v_g = S_d[4,4] ) dt_mles <- rbind(res, dt_mles) } ################################## Make covariates ready ##################################################################### # To make sure that the covariates are in the same order as ml estimates catchmentDesc <- dt_mles %>% select(Station) %>% left_join(catchmentDesc) names <- c( "Int.", "log(Area)", "log(SAAR)", "log(FARL)", "BFIHOST^2", "log(FPEXT)", "log(URBEXT+1)", "log(DPLBAR)", "log(DPSBAR)", "log(LDP)", "log(SPRHOST)", "log(ASPBAR)", "log(ALTBAR)", "log(ASPVAR)", "log(PROPWET)") ncols <- length(names) covariates <- matrix(c( rep(1,n_st), # Intercept transform(catchmentDesc$Area, "AREA"), transform(catchmentDesc$SAAR, "SAAR"), transform(catchmentDesc$FARL, "FARL"), transform(catchmentDesc$BFIHOST, "BFIHOST"), transform(catchmentDesc$FPEXT, "FPEXT"), transform(catchmentDesc$URBEXT2000, "URBEXT"), transform(catchmentDesc$DPLBAR, "DPLBAR"), transform(catchmentDesc$DPSBAR, "DPSBAR"), transform(catchmentDesc$LDP, "LDP"), transform(catchmentDesc$SPRHOST, "SPRHOST"), transform(catchmentDesc$ASPBAR, "ASPBAR"), transform(catchmentDesc$ALTBAR, "ALTBAR"), transform(catchmentDesc$ASPVAR, "ASPVAR"), transform(catchmentDesc$PROPWET, "PROPWET") ), ncol = 15, nrow = n_st ) colnames(covariates) <- names ################################ Make X matrices for psi, tau and xi ######################################################### cov_names_psi <- c("Int.","log(Area)", "log(SAAR)", "log(FARL)", "BFIHOST^2") cov_names_tau <- c("Int.","log(Area)", "log(SAAR)", "log(FARL)", "log(FPEXT)", "log(URBEXT+1)") cov_names_kappa <- c("Int.", "log(FPEXT)") cov_names_gamma <- c("Int.", "log(PROPWET)") X_psi <- covariates[, c("Int.","log(Area)", "log(SAAR)", "log(FARL)", "BFIHOST^2")] X_tau <- covariates[, c("Int.","log(Area)", "log(SAAR)", "log(FARL)", "log(FPEXT)", "log(URBEXT+1)")] X_kappa <- as.matrix(covariates[, c("Int.", "log(FPEXT)")]) X_gamma <- as.matrix(covariates[, c("Int.", "log(PROPWET)")]) ############################### Make mesh and A matrices for spatial component ############################################### coords <- cbind(catchmentDesc$long, catchmentDesc$lat) mesh <- inla.mesh.2d( loc=coords, offset = 0.08, max.edge = 0.07, cutoff = 0.005) # To plot mesh # plot(mesh) # Make A matrix - The same for psi and tau A_mat <- inla.spde.make.A(mesh, loc=coords) A_psi <- A_mat A_tau <- A_mat ################# Fit INLA models, to have good starting proposal distribution ############### # Add location to MLE data dt_mles <- dt_mles %>% left_join(catchmentDesc %>% dplyr::select(Northing, Easting, Station,long,lat)) mdl_sep_psi <- fit_model_psi(data = dt_mles, desc = X_psi) mdl_sep_tau <- fit_model_tau(data = dt_mles, desc = X_tau) mdl_sep_xi <- fit_model_kappa(data = dt_mles, desc = X_kappa) mdl_sep_gamma <- fit_model_gamma(data = dt_mles, desc = X_gamma) # The spde object is only used for getting the precision matrix for a given range and sd # so priors do not matter here d_spde <- inla.spde2.pcmatern(mesh, prior.range = c(.5, .5), prior.sigma = c(.5, .5)) # Make the Z matrix Z <- bdiag(cbind(X_psi,A_psi), cbind(X_tau, A_tau), X_kappa, X_gamma) N_psi <- dim(X_psi)[2] N_tau <- dim(X_tau)[2] N_xi <- dim(X_kappa)[2] N_gamma <- dim(X_gamma)[2] N_colsA <- dim(A_psi)[2] ################################################ Helper functions ################################################### # Make the covariance matrix for the observations makeSigma_etay <- function(dt){ N_rows <- dim(dt)[1] Sigma_etay <- matrix(0, nrow = 4*N_rows, ncol = 4*N_rows) for(i in 1:N_rows){ Sigma_etay[i,i] <- dt$v_p[i] Sigma_etay[i,i+N_rows] <- dt$v_p_t[i] Sigma_etay[i,i+2*N_rows] <- dt$v_p_k[i] Sigma_etay[i,i+3*N_rows] <- dt$v_p_g[i] } for(i in 1:N_rows){ Sigma_etay[i+N_rows,i] <- dt$v_p_t[i] Sigma_etay[i+N_rows,i+N_rows] <- dt$v_t[i] Sigma_etay[i+N_rows,i+2*N_rows] <- dt$v_t_k[i] Sigma_etay[i+N_rows,i+3*N_rows] <- dt$v_t_g[i] } for(i in 1:N_rows){ Sigma_etay[i+2*N_rows,i] <- dt$v_p_k[i] Sigma_etay[i+2*N_rows,i+N_rows] <- dt$v_t_k[i] Sigma_etay[i+2*N_rows,i+2*N_rows] <- dt$v_k[i] Sigma_etay[i+2*N_rows,i+3*N_rows] <- dt$v_k_g[i] } for(i in 1:N_rows){ Sigma_etay[i+3*N_rows,i] <- dt$v_p_g[i] Sigma_etay[i+3*N_rows,i+N_rows] <- dt$v_t_g[i] Sigma_etay[i+3*N_rows,i+2*N_rows] <- dt$v_k_g[i] Sigma_etay[i+3*N_rows,i+3*N_rows] <- dt$v_g[i] } return(Matrix(Sigma_etay)) } get_mode_mean_sd_for_hyperparameter <- function(mdl, fun, hyperparameter){ x0 <- mdl$marginals.hyperpar[[hyperparameter]] E <- inla.emarginal(function(x) c(fun(x), fun(x)^2), x0) sd <- sqrt(E[2] - E[1]^2) mean <- E[1] mt_tmp <- inla.tmarginal(fun, x0) dat_tmp <- inla.smarginal(mt_tmp) mode <- dat_tmp$x[which(dat_tmp$y == max(dat_tmp$y))] return(list(sd = sd, mean = mean, mode = mode)) } log_f_x_given_theta <- function(kappa, Q_x){ res <- determinant(Q_x, logarithm = T) res <- .5*res$modulus[1]*res$sign return(res) } log_f_x_given_eta_hat_and_theta <- function(kappa, Q_x_given_etaHat, N, Z, eta_hat, Q_etay, K){ mu_x_given_etaHat <- solve(a = Cholesky(Q_x_given_etaHat),b = b) determ <- determinant(Q_x_given_etaHat, logarithm = T) res <- -.5*t(mu_x_given_etaHat)%*%(Q_x_given_etaHat%*%mu_x_given_etaHat) res <- res + .5*determ$modulus[1]*determ$sign return(res) } calc_Q_x_given_etaHat <- function(Q_x, N, Q_etay){ Q_x_given_etaHat <- Q_x Q_x_given_etaHat[1:(4*N), 1:(4*N)] <- Q_x[1:(4*N), 1:(4*N)] + Q_etay return(Q_x_given_etaHat) } calc_Q_x <- function(kappa = k_st, Q_beta_psi, Q_beta_tau, Q_beta_xi,Q_beta_gamma, N, Z, d_spde){ Q_u_psi <- makeQ_u(s = exp(kappa$u_psi), rho = exp(kappa$v_psi), d_spde) Q_u_tau <- makeQ_u(s = exp(kappa$u_tau), rho = exp(kappa$v_tau), d_spde) Q_nu <- bdiag(Q_beta_psi,Q_u_psi,Q_beta_tau,Q_u_tau,Q_beta_xi,Q_beta_gamma) Q_epsilon <- bdiag(Diagonal(N,exp(kappa$kappa_psi)), Diagonal(N,exp(kappa$kappa_tau)), Diagonal(N,exp(kappa$kappa_xi)),Diagonal(N,exp(kappa$kappa_gamma))) K <- dim(Q_nu)[1] Q_x[1:(4*N), 1:(4*N)] <- Q_epsilon Q_x[1:K + 4*N,1:(4*N)] <- -t(Z)%*%Q_epsilon Q_x[1:(4*N), 1:K + 4*N] <- - (Q_epsilon %*% Z) Q_x[1:K + 4*N, 1:K + 4*N] <- Q_nu + t(Z)%*%Q_epsilon%*%Z return(Q_x) } ################################## Prior matrices for covariate coefficients ################################### betaVarPrior <- 10000 K <- 2*N_colsA + N_psi +N_tau +N_xi + N_gamma Q_beta_psi <- Diagonal(N_psi, 1/betaVarPrior) Q_beta_tau <- Diagonal(N_tau, 1/betaVarPrior) Q_beta_xi <- Diagonal(N_xi, 1/betaVarPrior) Q_beta_gamma <- Diagonal(N_gamma, 1/betaVarPrior) ################# get variance and mode for hyper parameters for proposal distribution ############################### tau_psi_0 <- get_mode_mean_sd_for_hyperparameter(mdl_sep_psi$mdl, function(x) log(x), "Precision for idx") tau_tau_0 <- get_mode_mean_sd_for_hyperparameter(mdl_sep_tau$mdl, function(x) log(x), "Precision for idx") tau_xi_0 <- get_mode_mean_sd_for_hyperparameter(mdl_sep_xi$mdl, function(x) log(x), "Precision for idx") tau_gamma_0 <- get_mode_mean_sd_for_hyperparameter(mdl_sep_gamma$mdl, function(x) log(x), "Precision for idx") rho_psi_0 <- get_mode_mean_sd_for_hyperparameter(mdl_sep_psi$mdl, function(x) log(x), "Range for s") rho_tau_0 <- get_mode_mean_sd_for_hyperparameter(mdl_sep_tau$mdl, function(x) log(x), "Range for s") sigma_psi_0 <- get_mode_mean_sd_for_hyperparameter(mdl_sep_psi$mdl, function(x) log(x), "Stdev for s") sigma_tau_0 <- get_mode_mean_sd_for_hyperparameter(mdl_sep_tau$mdl, function(x) log(x), "Stdev for s") # Number of stations N <- nrow(dt_mles) eta_hat <- matrix(c(dt_mles$psi, dt_mles$tau, dt_mles$kappa, dt_mles$gamma), nrow = 4 * N) ###### Make sigma_eta_y sigma_eta_y <- makeSigma_etay(dt = dt_mles) Q_etay <- solve(sigma_eta_y) # Mean and covariance matrix of the proposal distribution in the first loop kappa_0 <- c(tau_psi_0$mode, rho_psi_0$mode, sigma_psi_0$mode, tau_tau_0$mode, rho_tau_0$mode, sigma_tau_0$mode, tau_xi_0$mode, tau_gamma_0$mode) %>% as.matrix() # Might need to change the proposal distribution #load("proposalCovar.RData") # This is another option for a covariance matrix for the proposal distribution Sigma_kappa_0 <- diag(c(tau_psi_0$sd^2*4, rho_psi_0$sd^2, sigma_psi_0$sd^2, tau_tau_0$sd^2*2, rho_tau_0$sd^2, sigma_tau_0$sd^2, tau_xi_0$sd^2*0.7, tau_gamma_0$sd^2/2)*0.5 ) library(MASS) library(SparseM) #################################### Model fitting - Hyperparameters (One chain) ################## # Could also run more chains here parallel for example using mclapply from the parallel package N_samples <- 500 # Change this number to take more samples Q_x <- Matrix(0,nrow = 4*N+K, ncol = 4*N+K) B <- Matrix(0,nrow = 4*N, ncol = 4*N+K) B[1:(4*N),1:(4*N)] <- diag(1,4*N) b <- t(B)%*%(Q_etay%*%eta_hat) kappa_k <- mvrnorm(mu = kappa_0, Sigma = Sigma_kappa_0) kappa_mat <- matrix(NA, nrow = length(kappa_k), ncol = N_samples) kappa_k_is_kappa_star <- F accept <- 0 for(i in 1:N_samples){ kappa_star <- mvrnorm(mu = kappa_k, Sigma = Sigma_kappa_0) k_st <- list( kappa_psi = kappa_star[1], v_psi = kappa_star[2], u_psi = kappa_star[3], kappa_tau = kappa_star[4], v_tau = kappa_star[5], u_tau = kappa_star[6], kappa_xi = kappa_star[7], kappa_gamma = kappa_star[8] ) k_k <- list( kappa_psi = kappa_k[1], v_psi = kappa_k[2], u_psi = kappa_k[3], kappa_tau = kappa_k[4], v_tau = kappa_k[5], u_tau = kappa_k[6], kappa_xi = kappa_k[7], kappa_gamma = kappa_k[8] ) if(i == 1){ Q_x <- calc_Q_x(kappa = k_st, Q_beta_psi, Q_beta_tau, Q_beta_xi, Q_beta_gamma, N, Z, d_spde) Q_x_given_etaHat <- calc_Q_x_given_etaHat(Q_x = Q_x, N = N, Q_etay = Q_etay) l_x_etaHat_k_st <- log_f_x_given_eta_hat_and_theta(kappa = k_st, Q_x_given_etaHat = Q_x_given_etaHat, N = N, Z = Z, eta_hat = eta_hat, Q_etay = Q_etay,K = K) l_x_k_st <- log_f_x_given_theta(kappa = k_st, Q_x) l_prior_k_st <- log_prior_logTheta(k_st) Q_x <- calc_Q_x(kappa = k_k, Q_beta_psi, Q_beta_tau, Q_beta_xi, Q_beta_gamma, N, Z, d_spde) Q_x_given_etaHat <- calc_Q_x_given_etaHat(Q_x = Q_x, N = N, Q_etay = Q_etay) l_x_etaHat_k_k <- log_f_x_given_eta_hat_and_theta(kappa = k_k, Q_x_given_etaHat = Q_x_given_etaHat, N = N, Z = Z, eta_hat = eta_hat, Q_etay = Q_etay,K = K) l_x_k_k <- log_f_x_given_theta(kappa = k_k, Q_x) l_prior_k_k <- log_prior_logTheta(kappa = k_k) }else if(kappa_k_is_kappa_star){ Q_x <- calc_Q_x(kappa = k_st, Q_beta_psi, Q_beta_tau, Q_beta_xi, Q_beta_gamma, N, Z, d_spde) Q_x_given_etaHat <- calc_Q_x_given_etaHat(Q_x = Q_x, N = N, Q_etay = Q_etay) l_x_etaHat_k_k <- l_x_etaHat_k_st l_x_k_k <- l_x_k_st l_prior_k_k <- l_prior_k_st l_x_etaHat_k_st <- log_f_x_given_eta_hat_and_theta(kappa = k_st, Q_x_given_etaHat = Q_x_given_etaHat, N = N, Z = Z, eta_hat = eta_hat, Q_etay = Q_etay,K = K) l_x_k_st <- log_f_x_given_theta(kappa = k_st, Q_x) l_prior_k_st <- log_prior_logTheta(k_st) }else{ Q_x <- calc_Q_x(kappa = k_st, Q_beta_psi, Q_beta_tau, Q_beta_xi, Q_beta_gamma, N, Z, d_spde) Q_x_given_etaHat <- calc_Q_x_given_etaHat(Q_x = Q_x, N = N, Q_etay = Q_etay) l_x_etaHat_k_st <- log_f_x_given_eta_hat_and_theta(kappa = k_st, Q_x_given_etaHat = Q_x_given_etaHat, N = N, Z = Z, eta_hat = eta_hat, Q_etay = Q_etay,K = K) l_x_k_st <- log_f_x_given_theta(kappa = k_st, Q_x) l_prior_k_st <- log_prior_logTheta(k_st) } r <- l_prior_k_st-l_prior_k_k+l_x_k_st-l_x_k_k+l_x_etaHat_k_k-l_x_etaHat_k_st if(as.numeric(r) > log(runif(1,0,1))){ kappa_k <- kappa_star kappa_k_is_kappa_star = T accept <- accept + 1 }else{ kappa_k <- kappa_k kappa_k_is_kappa_star = F } kappa_mat[,i] <- kappa_k } accept/N_samples # Take first 20% as burn-in. burnIn <- 0.2 chain <- kappa_mat[,seq(burnIn*N_samples,N_samples,1)] sigma_psi <- sqrt(1/exp(chain[1,])) sigma_tau <- sqrt(1/exp(chain[4,])) sigma_xi <- sqrt(1/exp(chain[7,])) sigma_gamma <- sqrt(1/exp(chain[8,])) r_psi <- exp(chain[2,]) s_psi <- exp(chain[3,]) r_tau <- exp(chain[5,]) s_tau <- exp(chain[6,]) ############################ ############################ Spatial hyper for psi ############################ ############################ psi_hyper_sp <- data.frame( rho_psi = r_psi, s_psi = s_psi ) N_dim_dens <- 100 kd <- with(psi_hyper_sp, MASS::kde2d(s_psi, rho_psi, n = 100)) tmpDraslDt <- data.table() for(i in 1:N_dim_dens){ tmpDraslDt <- rbind(tmpDraslDt, data.table(z = kd$z[i,], x = rep(kd$x[i],N_dim_dens), y=kd$y)) } p1 <- ggplot(tmpDraslDt, aes(x, y, z = z))+ geom_raster(aes(fill = z)) + geom_contour(col = "white") + #xlim(c(0.22,0.4)) + ylim(c(NA,0.08)) + labs( x = expression(s[psi]), y = expression(rho[psi]), fill = "Density" ) + scale_fill_gradientn(colours = terrain.colors(10)) + theme_bw() long_hyper_psi_sp <- gather(psi_hyper_sp, key = Type, value = Value) long_hyper_psi_sp$Type <- factor(long_hyper_psi_sp$Type) levels(long_hyper_psi_sp$Type) <- c("rho[psi]", "s[psi]") p2 <- ggplot(long_hyper_psi_sp, aes(Value)) + geom_density(fill = "black", alpha = .4) + facet_wrap(~Type, scales = "free", labeller = label_parsed) + theme_bw() + labs(x = "", y = "Density") multiplot(p1, p2) ############################ ############################ Spatial hyper for tau ############################ ############################ tau_hyper_sp <- data.table( rho_tau = r_tau, s_tau = s_tau ) N_dim_dens <- 100 kd <- with(tau_hyper_sp, MASS::kde2d(s_tau, rho_tau, n = 100)) tmpDraslDt2 <- data.table() for(i in 1:N_dim_dens){ tmpDraslDt2 <- rbind(tmpDraslDt2, data.table(z = kd$z[i,], x = rep(kd$x[i],N_dim_dens), y=kd$y)) } p1 <- ggplot(tmpDraslDt2, aes(x, y, z = z))+ geom_raster(aes(fill = z)) + geom_contour(col = "white") + ylim(c(NA,0.16)) + xlim(c(NA,0.25)) + labs( x = expression(s[tau]), y = expression(rho[tau]), fill = "Density" ) + scale_fill_gradientn(colours = terrain.colors(10)) + theme_bw() long_hyper_tau_sp <- gather(tau_hyper_sp, key = Type, value = Value) long_hyper_tau_sp$Type <- factor(long_hyper_tau_sp$Type) levels(long_hyper_tau_sp$Type) <- c("rho[tau]", "s[tau]") p2 <- ggplot(long_hyper_tau_sp, aes(Value)) + geom_density(fill = "black", alpha = .4) + facet_wrap(~Type, scales = "free", labeller = label_parsed) + theme_bw() + labs(x = "", y = "Density") multiplot(p1, p2) ################################################## iid random effects ############################ ############################ model_error_hyper <- data.table( sigma_psi = sigma_psi, sigma_tau = sigma_tau, sigma_xi = sigma_xi, sigma_gamma = sigma_gamma ) long_model_error_hyper <- gather(model_error_hyper, key = Type, value = Value) long_model_error_hyper$Type <- factor(long_model_error_hyper$Type, levels = c("sigma_psi","sigma_tau","sigma_xi","sigma_gamma")) levels(long_model_error_hyper$Type) <- c("sigma[psi*epsilon]","sigma[tau*epsilon]","sigma[phi*epsilon]","sigma[gamma*epsilon]") ggplot(long_model_error_hyper %>% filter(!(Type == "sigma[gamma*epsilon]" & Value > 0.0015)), aes(Value)) + geom_density(fill = "black", alpha = .3) + facet_wrap(~Type, scales = "free", ncol = 2, labeller = label_parsed) + labs(x="",y="Density") + theme_bw() #################################### Latent parameter posterior samples #################################### N_x_loops <- dim(chain)[2] x_mat <- matrix(NA, nrow = K+4*N, ncol = N_x_loops) kappa_old <- rep(0,8) start <- proc.time() Q_x <- Matrix(0,nrow = 4*N+K, ncol = 4*N+K) B <- Matrix(0,nrow = 4*N, ncol = 4*N+K) B[1:(4*N),1:(4*N)] <- Diagonal(4*N, 1) b <- t(B)%*%(Q_etay%*%eta_hat) for(i in 1:N_x_loops){ k <- list( kappa_psi = chain[1,i], v_psi = chain[2,i], u_psi = chain[3,i], kappa_tau = chain[4,i], v_tau = chain[5,i], u_tau = chain[6,i], kappa_xi = chain[7,i], kappa_gamma = chain[8,i] ) Q_x <- calc_Q_x(kappa = k, Q_beta_psi = Q_beta_psi, Q_beta_tau = Q_beta_tau, Q_beta_xi = Q_beta_xi, Q_beta_gamma = Q_beta_gamma, N = N, Z = Z, d_spde = d_spde) Q_x_given_etaHat <- calc_Q_x_given_etaHat(Q_x = Q_x,N = N, Q_etay = Q_etay) mu_x_given_etaHat <- solve(a = Cholesky(Q_x_given_etaHat),b = b) x <- inla.qsample(n = 1, mu = mu_x_given_etaHat, Q = Q_x_given_etaHat) x_mat[,i] <- x } stop <- proc.time()-start # x_mat contains the posterior samples for the latent parameters ############################## Posterior samples for psi, tau, kappa and gamma ######## eta <- x_mat[1:(4*N),] psi <- eta[1:N,] tau <- eta[1:N + N,] kappa <- eta[1:N + 2*N,] gamma <- eta[1:N + 3*N,] ############################################## covariate coefficient results ############################################## # Posterior samples for the covariate coefficients and the spatial components nu <- x_mat[(4*N+1):nrow(x_mat),] beta_psi <- nu[1:N_psi,] u_psi <- nu[1:N_colsA + N_psi,] beta_tau <- nu[1:N_tau + N_psi + N_colsA,] u_tau <- nu[1:N_colsA + N_tau + N_psi + N_colsA,] beta_kappa <- nu[1:N_xi + N_colsA + N_tau + N_psi + N_colsA,] beta_gamma <- nu[1:N_gamma + N_xi + N_colsA + N_tau + N_psi + N_colsA,] # results for the covariate coefficients beta_psi_results <- data.frame( Covariate = colnames(X_psi), Mean = apply(beta_psi, 1, mean), Sd = apply(beta_psi, 1, sd), q_025 = apply(beta_psi, 1, quantile, probs = 0.025), q_50 = apply(beta_psi, 1, quantile, probs = 0.5), q_975 = apply(beta_psi, 1, quantile, probs = 0.975) ) beta_psi_results beta_tau_results <- data.frame( Covariate = colnames(X_tau), Mean = apply(beta_tau, 1, mean), Sd = apply(beta_tau, 1, sd), q_025 = apply(beta_tau, 1, quantile, probs = 0.025), q_50 = apply(beta_tau, 1, quantile, probs = 0.5), q_975 = apply(beta_tau, 1, quantile, probs = 0.975) ) beta_tau_results beta_kappa_results <- data.frame( Covariate = colnames(X_kappa), Mean = apply(beta_kappa, 1, mean), Sd = apply(beta_kappa, 1, sd), q_025 = apply(beta_kappa, 1, quantile, probs = 0.025), q_50 = apply(beta_kappa, 1, quantile, probs = 0.5), q_975 = apply(beta_kappa, 1, quantile, probs = 0.975) ) beta_kappa_results beta_gamma_results <- data.frame( Covariate = colnames(X_gamma), Mean = apply(beta_gamma, 1, mean), Sd = apply(beta_gamma, 1, sd), q_025 = apply(beta_gamma, 1, quantile, probs = 0.025), q_50 = apply(beta_gamma, 1, quantile, probs = 0.5), q_975 = apply(beta_gamma, 1, quantile, probs = 0.975) ) beta_gamma_results # Spatial fields # This gives us the value of the spatial field for psi and tau at each station location Au_psi <- A_psi %*% u_psi Au_tau <- A_tau %*% u_tau # Plot the spatial field on a map of the UK local.plot.field = function(field, mesh, xlim=c(-0.1,1), ylim=c(-0.1,1), ...){ stopifnot(length(field) == mesh$n) # error when using the wrong mesh proj = inla.mesh.projector(mesh, dims=c(300, 300)) # Can project from the mesh onto a 300x300 plotting grid field.proj = inla.mesh.project(proj, field) # Do the projection image.plot(list(x = proj$x, y=proj$y, z = field.proj), xlim = xlim, ylim = ylim, ...) } u_psi_m <- apply(u_psi, 1, mean) u_tau_m <- apply(u_tau, 1, mean) library(RColorBrewer) library(fields) rf <- colorRampPalette(rev(brewer.pal(11,'Spectral'))) # make colors r <- rf(64) colorTable<- designer.colors(20, c( "#5ab4ac","white", "#d8b365"), x = c(min(u_psi_m), 0, max(u_psi_m)) / (max(u_psi_m) -min(u_psi_m))) colorTable<- designer.colors(100, c( "#e66101","#fdb863","#b2abd2", "#5e3c99"), x = c(min(u_psi_m),quantile(u_psi_m, 0.25), 0, max(u_psi_m)) / (max(u_psi_m) -min(u_psi_m))) colorTable2<- designer.colors(100, c( "#e66101","#fdb863","#b2abd2", "#5e3c99"), x = c(min(u_tau_m),quantile(u_tau_m, 0.25), 0, max(u_tau_m)) / (max(u_tau_m) -min(u_tau_m))) # Get the outlines of Great Britain map_scaled <- convertCoords(dt = dt_mles)$map_scaled # Spatial field for psi local.plot.field(field = u_psi_m, mesh, col = colorTable) points(map_scaled$long, map_scaled$lat, pch = 20, cex=.2) points(coords[,1],coords[,2], pch = 20, col = "black", cex = .3) # Spatial field for tau local.plot.field(field = u_tau_m, mesh, col = colorTable2) points(map_scaled$long, map_scaled$lat, pch = 20, cex=.2) points(coords[,1],coords[,2], pch = 20, col = "black", cex = .3)
## Reading the Training data into R zs_train <- read.csv(".../Zsassociates_Ideatory/TrainingData.csv",header = T, stringsAsFactors = F) ## Removing the observations where the target variable is missing zs_train <- subset(zs_train, Labels != "NA") ## Summarizing missing data for all variables propmiss <- function(dataframe) { m <- sapply(dataframe, function(x) { data.frame(nmiss=sum(is.na(x)),n=length(x),propmiss=sum(is.na(x))/length(x)) }) d <- data.frame(t(m)) d <- sapply(d, unlist) d <- as.data.frame(d) d$variable <- row.names(d) row.names(d) <- NULL d <- cbind(d[ncol(d)],d[-ncol(d)]) return(d[order(d$propmiss), ]) } zs_missing <- propmiss(zs_train) ## Variables with less than 50% missing data are only retained in the dataset keep_var <- subset(zs_missing, propmiss <= 0.5, select = variable) zs_train_final <- zs_train[,names(zs_train) %in% keep_var[,1]] ## Creating a new data frame after removing the variables "Customer.ID" & "Labels" drop <- c("Customer.ID", "Labels") zs.rank <- zs_train_final[,!names(zs_train_final) %in% drop] ## Principle component analysis for dimension reduction ## Calculating the maximum likelihood estimates of the variance-covariance matrix of zs.rank library(mvnmle) covmat <- (mlest(zs.rank))$sigmahat ## Calcuting the eigenvalues and corresponding eigenvectors of the variance-covariance matrix library(Matrix) e <- eigen(covmat) ## Identifying the eigenvector corresponding to minimum eigenvalue last.vector <- e$vectors[,which.min(e$values)] last.vector[order(abs(last.vector))] ## Removing the variables with the highest loadings on last.vector (variables with highest absolute value of last.vector) d <- c("Variable_105", "Variable_91", "Variable_37", "Variable_189") zs_small <- zs_train_final[,!names(zs_train_final) %in% d] ## Applying Amelia algorithm with 10 iterations for missing data imputation and writing the output to a csv file library(Amelia) set.seed(123) am.zs <- amelia(x=zs_small, idvars = c("Labels","Customer.ID"), m=10) summary(am.zs) write.amelia(am.zs,file.stem = "zs_outdata",format="csv") ## Reading the final imputed output dataset into R zs_imputed <- read.csv(".../Zsassociates_Ideatory/zs_outdata10.csv",header = T, stringsAsFactors = F, strip.white = T) zs_imputed <- zs_imputed[,-1] ## Defining a variable transformation function where variables have negative values transform <- function(x) { sign(x) * abs(x)^(1/3) } ## Applying the transform function to imputed dataset zs_imputed[,2:38] <- as.data.frame(apply(zs_imputed[,2:38], 2, transform)) ## Converting the Target variable of the final transformed dataset to categorical/factor zs_imputed$Labels <- as.factor(zs_imputed$Labels) ## Fitting a random forest model library(randomForest) set.seed(123) zs.rf <- randomForest(Labels~.-Customer.ID, data = zs_imputed, ntree = 500, importance = T, do.trace=100) ## Fitting a svm model library(e1071) set.seed(123) zs.svm <- svm(Labels~.-Customer.ID, data = zs_imputed, probability = T) ## Reading the Evaluation data into R zs_eval <- read.csv(".../Zsassociates_Ideatory/EvaluationData.csv",header = T, stringsAsFactors = F) zs_eval$Labels <- NULL ## Retaining the same variables as in the training set zs_eval_final <- zs_eval[,names(zs_eval) %in% keep_var[,1]] zs_eval_small <- zs_eval_final[,!names(zs_eval_final) %in% d] ## Applying Amelia algorithm with 10 iterations for missing data imputation and writing the output to a csv file library(Amelia) set.seed(123) am.zs.eval <- amelia(x=zs_eval_small, idvar = "Customer.ID", m=10) summary(am.zs.eval) write.amelia(am.zs.eval,file.stem = "zs_eval_outdata",format="csv") ## Reading the final imputed output dataset into R zs_eval_imputed <- read.csv(".../Zsassociates_Ideatory/zs_eval_outdata10.csv",header = T, stringsAsFactors = F, strip.white = T) zs_eval_imputed <- zs_eval_imputed[,-1] ## Applying the transform function to imputed dataset zs_eval_imputed[,2:38] <- as.data.frame(apply(zs_eval_imputed[,2:38], 2, transform)) ## Predicting on the evaluation set zs_predict_rf <- predict(zs.rf, zs_eval_imputed[,2:38], type='prob') zs_predict_svm <- predict(zs.svm, zs_eval_imputed[,2:38], probability = T) ## Creating an ensemble model predict.final <- (0.45 * zs_predict_rf + 0.55 * zs_predict_svm) ## Converting the class probabilities to class labels predicted_Labels <- ifelse(predict.final > 0.4, 1, 0) zs_eval_imputed <- cbind(zs_eval_imputed, predicted_Labels) ## Final data for submission final_submission <- zs_eval_imputed[,c(1,39)]
/zshack.R
no_license
Debd8/ZS-Customer-Modeling-Challenge-2015
R
false
false
4,561
r
## Reading the Training data into R zs_train <- read.csv(".../Zsassociates_Ideatory/TrainingData.csv",header = T, stringsAsFactors = F) ## Removing the observations where the target variable is missing zs_train <- subset(zs_train, Labels != "NA") ## Summarizing missing data for all variables propmiss <- function(dataframe) { m <- sapply(dataframe, function(x) { data.frame(nmiss=sum(is.na(x)),n=length(x),propmiss=sum(is.na(x))/length(x)) }) d <- data.frame(t(m)) d <- sapply(d, unlist) d <- as.data.frame(d) d$variable <- row.names(d) row.names(d) <- NULL d <- cbind(d[ncol(d)],d[-ncol(d)]) return(d[order(d$propmiss), ]) } zs_missing <- propmiss(zs_train) ## Variables with less than 50% missing data are only retained in the dataset keep_var <- subset(zs_missing, propmiss <= 0.5, select = variable) zs_train_final <- zs_train[,names(zs_train) %in% keep_var[,1]] ## Creating a new data frame after removing the variables "Customer.ID" & "Labels" drop <- c("Customer.ID", "Labels") zs.rank <- zs_train_final[,!names(zs_train_final) %in% drop] ## Principle component analysis for dimension reduction ## Calculating the maximum likelihood estimates of the variance-covariance matrix of zs.rank library(mvnmle) covmat <- (mlest(zs.rank))$sigmahat ## Calcuting the eigenvalues and corresponding eigenvectors of the variance-covariance matrix library(Matrix) e <- eigen(covmat) ## Identifying the eigenvector corresponding to minimum eigenvalue last.vector <- e$vectors[,which.min(e$values)] last.vector[order(abs(last.vector))] ## Removing the variables with the highest loadings on last.vector (variables with highest absolute value of last.vector) d <- c("Variable_105", "Variable_91", "Variable_37", "Variable_189") zs_small <- zs_train_final[,!names(zs_train_final) %in% d] ## Applying Amelia algorithm with 10 iterations for missing data imputation and writing the output to a csv file library(Amelia) set.seed(123) am.zs <- amelia(x=zs_small, idvars = c("Labels","Customer.ID"), m=10) summary(am.zs) write.amelia(am.zs,file.stem = "zs_outdata",format="csv") ## Reading the final imputed output dataset into R zs_imputed <- read.csv(".../Zsassociates_Ideatory/zs_outdata10.csv",header = T, stringsAsFactors = F, strip.white = T) zs_imputed <- zs_imputed[,-1] ## Defining a variable transformation function where variables have negative values transform <- function(x) { sign(x) * abs(x)^(1/3) } ## Applying the transform function to imputed dataset zs_imputed[,2:38] <- as.data.frame(apply(zs_imputed[,2:38], 2, transform)) ## Converting the Target variable of the final transformed dataset to categorical/factor zs_imputed$Labels <- as.factor(zs_imputed$Labels) ## Fitting a random forest model library(randomForest) set.seed(123) zs.rf <- randomForest(Labels~.-Customer.ID, data = zs_imputed, ntree = 500, importance = T, do.trace=100) ## Fitting a svm model library(e1071) set.seed(123) zs.svm <- svm(Labels~.-Customer.ID, data = zs_imputed, probability = T) ## Reading the Evaluation data into R zs_eval <- read.csv(".../Zsassociates_Ideatory/EvaluationData.csv",header = T, stringsAsFactors = F) zs_eval$Labels <- NULL ## Retaining the same variables as in the training set zs_eval_final <- zs_eval[,names(zs_eval) %in% keep_var[,1]] zs_eval_small <- zs_eval_final[,!names(zs_eval_final) %in% d] ## Applying Amelia algorithm with 10 iterations for missing data imputation and writing the output to a csv file library(Amelia) set.seed(123) am.zs.eval <- amelia(x=zs_eval_small, idvar = "Customer.ID", m=10) summary(am.zs.eval) write.amelia(am.zs.eval,file.stem = "zs_eval_outdata",format="csv") ## Reading the final imputed output dataset into R zs_eval_imputed <- read.csv(".../Zsassociates_Ideatory/zs_eval_outdata10.csv",header = T, stringsAsFactors = F, strip.white = T) zs_eval_imputed <- zs_eval_imputed[,-1] ## Applying the transform function to imputed dataset zs_eval_imputed[,2:38] <- as.data.frame(apply(zs_eval_imputed[,2:38], 2, transform)) ## Predicting on the evaluation set zs_predict_rf <- predict(zs.rf, zs_eval_imputed[,2:38], type='prob') zs_predict_svm <- predict(zs.svm, zs_eval_imputed[,2:38], probability = T) ## Creating an ensemble model predict.final <- (0.45 * zs_predict_rf + 0.55 * zs_predict_svm) ## Converting the class probabilities to class labels predicted_Labels <- ifelse(predict.final > 0.4, 1, 0) zs_eval_imputed <- cbind(zs_eval_imputed, predicted_Labels) ## Final data for submission final_submission <- zs_eval_imputed[,c(1,39)]
# Check out this presentation for more documentation # https://www.slideshare.net/RsquaredIn/rmysql-tutorial-for-beginners #library needed to connect to MySQL library(RMySQL) library(ggplot2) #RStudio function that prompts for password. Security is always important. psswd <- .rs.askForPassword("Database Password:") #Define connection string con <- dbConnect(MySQL(), user='root',password=psswd, host='localhost', dbname='legos' ) #get information about the connection dbGetInfo(con) #list tables in database dbListTables(con) #list column in a table dbListFields(con,"sets") #import an entire table lego_sets <- dbReadTable(con,"sets") head(lego_sets) #plot the number of legos by year per set ggplot(data=lego_sets, aes(x=year, y=num_parts)) + geom_jitter(alpha=0.5, shape=1) #import the results of a SQL query avg_by_year <- dbGetQuery(con, "SELECT year, avg(num_parts) as avg_parts FROM sets GROUP BY year") head(avg_by_year) #function to compute lm equation lm_eqn <- function(df,x,y){ m <- lm(y ~ x, df); eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2, list(a = format(coef(m)[1], digits = 2), b = format(coef(m)[2], digits = 2), r2 = format(summary(m)$r.squared, digits = 3))) as.character(as.expression(eq)); } ggplot(data=avg_by_year, aes(x=year, y=avg_parts)) + geom_point(alpha=0.5, shape=16) + geom_smooth(method='lm',formula=y~x) + geom_text(x = 1970, y = 200, label = lm_eqn(avg_by_year,avg_by_year$year,avg_by_year$avg_parts), parse = TRUE) #for large queries, this can be done in different steps. #This allows you to process the results in chunks. very_big_sets_qry <- dbSendQuery(con, "SELECT * FROM sets WHERE num_parts>=1000") very_big_sets <- dbFetch(very_big_sets_qry) #write out data dbWriteTable(con, "big_sets", data.frame(big_sets, stringsAsFactors = F), overwrite=TRUE) #let's check and see if it's there #delete a table dbRemoveTable(con, "big_sets") #disconnect from the database dbDisconnect(con)
/RMySQL Example.R
no_license
raikon123/MySQL_Class
R
false
false
2,058
r
# Check out this presentation for more documentation # https://www.slideshare.net/RsquaredIn/rmysql-tutorial-for-beginners #library needed to connect to MySQL library(RMySQL) library(ggplot2) #RStudio function that prompts for password. Security is always important. psswd <- .rs.askForPassword("Database Password:") #Define connection string con <- dbConnect(MySQL(), user='root',password=psswd, host='localhost', dbname='legos' ) #get information about the connection dbGetInfo(con) #list tables in database dbListTables(con) #list column in a table dbListFields(con,"sets") #import an entire table lego_sets <- dbReadTable(con,"sets") head(lego_sets) #plot the number of legos by year per set ggplot(data=lego_sets, aes(x=year, y=num_parts)) + geom_jitter(alpha=0.5, shape=1) #import the results of a SQL query avg_by_year <- dbGetQuery(con, "SELECT year, avg(num_parts) as avg_parts FROM sets GROUP BY year") head(avg_by_year) #function to compute lm equation lm_eqn <- function(df,x,y){ m <- lm(y ~ x, df); eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2, list(a = format(coef(m)[1], digits = 2), b = format(coef(m)[2], digits = 2), r2 = format(summary(m)$r.squared, digits = 3))) as.character(as.expression(eq)); } ggplot(data=avg_by_year, aes(x=year, y=avg_parts)) + geom_point(alpha=0.5, shape=16) + geom_smooth(method='lm',formula=y~x) + geom_text(x = 1970, y = 200, label = lm_eqn(avg_by_year,avg_by_year$year,avg_by_year$avg_parts), parse = TRUE) #for large queries, this can be done in different steps. #This allows you to process the results in chunks. very_big_sets_qry <- dbSendQuery(con, "SELECT * FROM sets WHERE num_parts>=1000") very_big_sets <- dbFetch(very_big_sets_qry) #write out data dbWriteTable(con, "big_sets", data.frame(big_sets, stringsAsFactors = F), overwrite=TRUE) #let's check and see if it's there #delete a table dbRemoveTable(con, "big_sets") #disconnect from the database dbDisconnect(con)
## generate heatmap for Markov jumps library(ggplot2) library(dplyr) library(tidytree) library(reshape2) library(tidyr) library(lubridate) library(ggpubr) df<-read.table("seg1/jumpTimes.txt", header = TRUE, sep = "\t" ) state<-n_distinct(df$state) df$from_to = paste(df$from,"_",df$to) df <- df %>% mutate(time = 2018.147945 - as.numeric(time)) df$year <- format(date_decimal(df$time), "%Y") count<-df %>% group_by(from_to,year)%>% count()%>% filter(as.numeric(year)>=2015) count<-count%>% mutate(ave=n/state) count2<-cbind(count, read.table(text = as.character(count$from_to), sep = "_")) write.csv(count2,"PB2_MJ_edited.csv") count2<-read.csv("PB2_MJ_edited2.csv") # Heatmap order_f<-c("OB ","DD ","GU ","PO ","SB ") internal_jumps<-internal_jumps%>%filter(as.numeric(year)>=2015) internal_jumps$V1_f = factor(internal_jumps$V1, levels=c("OB ","DD ","GU ","PO ","SB ")) internal_jumps$year=factor(internal_jumps$year,levels=c("2015","2016","2017")) internal_jumps$segment=factor(internal_jumps$segment,levels=c("PB2","PB1","PA","NP","MP","NS")) ggplot(internal_jumps, aes(x =as.factor(year), y=from_to,fill= as.numeric(ave))) + geom_tile()+ scale_fill_gradient2(low = '#ffffd9', mid = '#7fcdbb', high = '#1f78b4',midpoint = 12.5,limits=c(0,25))+ theme_bw()+ xlab("year") + ylab("To")+ labs(fill="Number of Jumps")+ #facet_grid(rows = vars(V1_f),,scales="free")+ facet_grid(rows = vars(V1_f),cols=vars(segment),scales="free")+ scale_x_discrete(position = "top") str(count2) ################################################################################### ## wrap into function jump_to_hp<-function(file,mrsd){ df<-read.table(file, header = TRUE, sep = "\t" ) state<-n_distinct(df$state) df$from_to = paste(df$from,"_",df$to) df <- df %>% mutate(time = mrsd - as.numeric(time)) df$year <- format(date_decimal(df$time), "%Y") count<-df %>% group_by(from_to,year)%>% count()%>% filter(as.numeric(year)>= 2013 && as.numeric(year)<2018) count<-count%>% mutate(ave=n/state) count2<-cbind(count, read.table(text = as.character(count$from_to), sep = "_")) # p<-ggplot(count2, aes(x = V1, y=V2, fill= ave,group=year)) + # geom_tile()+ # scale_fill_gradient2(low="blue", high="red")+ # theme_classic()+ ## xlab("From") + # ylab("To")+ # labs(fill="Number of Jumps")+ # facet_grid(.~year,scales="free") return(count2) } seg4H1<-jump_to_hp("seg4H1/jumpTimes.txt",2018.150684931507) seg4H3<-jump_to_hp("seg4H3/jumpTimes.txt",2018.147945) seg4H5<-jump_to_hp("seg4H5/jumpTimes.txt",2017.90684) seg6N1<-jump_to_hp("seg6N1/jumpTimes.txt",2018.150684931507) seg6N2<-jump_to_hp("seg6N2/jumpTimes.txt",2017.9452054) seg6N8<-jump_to_hp("seg6N8/jumpTimes.txt",2018.147945) ## combine multiple df seg4H1$segment<-"H1" seg4H3$segment<-"H3" seg4H5$segment<-"H5" seg6N1$segment<-"N1" seg6N2$segment<-"N2" seg6N8$segment<-"N8" surface_jumps<-rbind(seg4H1,seg4H3,seg4H5,seg6N1,seg6N2,seg6N8) order <- c("H1","H3","H5","N1","N2","N8") order_f<-c("OB ","DD ","GU ","PO ","SB ") surface_jumps<-surface_jumps %>% mutate(V1 = factor(V1, levels=c("SB ","PO ","GU ","DD ","OB "))) surface_jumps$V1<-factor(surface_jumps$V1,levels=order_f) order_t<-c(" OB"," DD"," GU"," PO"," SB") ggplot(transform(surface_jumps,segment=factor(segment,levels=order)), aes(x=factor(V2,levels = order_t), y=V1, fill= ave)) + geom_tile()+ scale_fill_gradient2(low="blue", high="red")+ theme_bw()+ xlab("From") + ylab("To")+ labs(fill="Number of Jumps")+ facet_grid(segment~year,scales="free")+ scale_x_discrete(position = "top") ############################################################ ## internal segment #seg1<-jump_to_hp("seg1/jumpTimes.txt",2018.147945) seg1<-read.csv("PB2_MJ_edited2.csv") seg2<-jump_to_hp("seg2/jumpTimes.txt",2017.969863) seg3<-jump_to_hp("seg3/jumpTimes.txt",2017.969863) seg5<-jump_to_hp("seg5/jumpTimes.txt",2017.969863) seg7<-jump_to_hp("seg7/jumpTimes.txt",2017.969863) seg8<-jump_to_hp("seg8/jumpTimes.txt",2017.969863) ## combine multiple df seg1$segment<-"PB2" seg2$segment<-"PB1" seg3$segment<-"PA" seg5$segment<-"NP" seg7$segment<-"MP" seg8$segment<-"NS" internal_jumps<-rbind(seg1,seg2,seg3,seg5,seg7,seg8) order <- c("PB2","PB1","PA","NP","MP","NS") order_f<-c("SB ","PO ","GU ","DD ","OB ") order_t<-c(" OB"," DD"," GU"," PO"," SB") ggplot(transform(internal_jumps,segment=factor(segment,levels=order)), aes(x=factor(V2,levels = order_t), y=factor(V1,levels=order_f), fill= ave,group=year)) + geom_tile()+ scale_fill_gradient2(low="blue", high="red")+ theme_bw()+ xlab("To") + ylab("From")+ labs(fill="Number of Jumps")+ facet_grid(segment~year,scales="free")+ scale_x_discrete(position = "top")
/Analytical_Scripts/Markov_jumpshp.R
no_license
JianiC/ATL-flyway
R
false
false
4,722
r
## generate heatmap for Markov jumps library(ggplot2) library(dplyr) library(tidytree) library(reshape2) library(tidyr) library(lubridate) library(ggpubr) df<-read.table("seg1/jumpTimes.txt", header = TRUE, sep = "\t" ) state<-n_distinct(df$state) df$from_to = paste(df$from,"_",df$to) df <- df %>% mutate(time = 2018.147945 - as.numeric(time)) df$year <- format(date_decimal(df$time), "%Y") count<-df %>% group_by(from_to,year)%>% count()%>% filter(as.numeric(year)>=2015) count<-count%>% mutate(ave=n/state) count2<-cbind(count, read.table(text = as.character(count$from_to), sep = "_")) write.csv(count2,"PB2_MJ_edited.csv") count2<-read.csv("PB2_MJ_edited2.csv") # Heatmap order_f<-c("OB ","DD ","GU ","PO ","SB ") internal_jumps<-internal_jumps%>%filter(as.numeric(year)>=2015) internal_jumps$V1_f = factor(internal_jumps$V1, levels=c("OB ","DD ","GU ","PO ","SB ")) internal_jumps$year=factor(internal_jumps$year,levels=c("2015","2016","2017")) internal_jumps$segment=factor(internal_jumps$segment,levels=c("PB2","PB1","PA","NP","MP","NS")) ggplot(internal_jumps, aes(x =as.factor(year), y=from_to,fill= as.numeric(ave))) + geom_tile()+ scale_fill_gradient2(low = '#ffffd9', mid = '#7fcdbb', high = '#1f78b4',midpoint = 12.5,limits=c(0,25))+ theme_bw()+ xlab("year") + ylab("To")+ labs(fill="Number of Jumps")+ #facet_grid(rows = vars(V1_f),,scales="free")+ facet_grid(rows = vars(V1_f),cols=vars(segment),scales="free")+ scale_x_discrete(position = "top") str(count2) ################################################################################### ## wrap into function jump_to_hp<-function(file,mrsd){ df<-read.table(file, header = TRUE, sep = "\t" ) state<-n_distinct(df$state) df$from_to = paste(df$from,"_",df$to) df <- df %>% mutate(time = mrsd - as.numeric(time)) df$year <- format(date_decimal(df$time), "%Y") count<-df %>% group_by(from_to,year)%>% count()%>% filter(as.numeric(year)>= 2013 && as.numeric(year)<2018) count<-count%>% mutate(ave=n/state) count2<-cbind(count, read.table(text = as.character(count$from_to), sep = "_")) # p<-ggplot(count2, aes(x = V1, y=V2, fill= ave,group=year)) + # geom_tile()+ # scale_fill_gradient2(low="blue", high="red")+ # theme_classic()+ ## xlab("From") + # ylab("To")+ # labs(fill="Number of Jumps")+ # facet_grid(.~year,scales="free") return(count2) } seg4H1<-jump_to_hp("seg4H1/jumpTimes.txt",2018.150684931507) seg4H3<-jump_to_hp("seg4H3/jumpTimes.txt",2018.147945) seg4H5<-jump_to_hp("seg4H5/jumpTimes.txt",2017.90684) seg6N1<-jump_to_hp("seg6N1/jumpTimes.txt",2018.150684931507) seg6N2<-jump_to_hp("seg6N2/jumpTimes.txt",2017.9452054) seg6N8<-jump_to_hp("seg6N8/jumpTimes.txt",2018.147945) ## combine multiple df seg4H1$segment<-"H1" seg4H3$segment<-"H3" seg4H5$segment<-"H5" seg6N1$segment<-"N1" seg6N2$segment<-"N2" seg6N8$segment<-"N8" surface_jumps<-rbind(seg4H1,seg4H3,seg4H5,seg6N1,seg6N2,seg6N8) order <- c("H1","H3","H5","N1","N2","N8") order_f<-c("OB ","DD ","GU ","PO ","SB ") surface_jumps<-surface_jumps %>% mutate(V1 = factor(V1, levels=c("SB ","PO ","GU ","DD ","OB "))) surface_jumps$V1<-factor(surface_jumps$V1,levels=order_f) order_t<-c(" OB"," DD"," GU"," PO"," SB") ggplot(transform(surface_jumps,segment=factor(segment,levels=order)), aes(x=factor(V2,levels = order_t), y=V1, fill= ave)) + geom_tile()+ scale_fill_gradient2(low="blue", high="red")+ theme_bw()+ xlab("From") + ylab("To")+ labs(fill="Number of Jumps")+ facet_grid(segment~year,scales="free")+ scale_x_discrete(position = "top") ############################################################ ## internal segment #seg1<-jump_to_hp("seg1/jumpTimes.txt",2018.147945) seg1<-read.csv("PB2_MJ_edited2.csv") seg2<-jump_to_hp("seg2/jumpTimes.txt",2017.969863) seg3<-jump_to_hp("seg3/jumpTimes.txt",2017.969863) seg5<-jump_to_hp("seg5/jumpTimes.txt",2017.969863) seg7<-jump_to_hp("seg7/jumpTimes.txt",2017.969863) seg8<-jump_to_hp("seg8/jumpTimes.txt",2017.969863) ## combine multiple df seg1$segment<-"PB2" seg2$segment<-"PB1" seg3$segment<-"PA" seg5$segment<-"NP" seg7$segment<-"MP" seg8$segment<-"NS" internal_jumps<-rbind(seg1,seg2,seg3,seg5,seg7,seg8) order <- c("PB2","PB1","PA","NP","MP","NS") order_f<-c("SB ","PO ","GU ","DD ","OB ") order_t<-c(" OB"," DD"," GU"," PO"," SB") ggplot(transform(internal_jumps,segment=factor(segment,levels=order)), aes(x=factor(V2,levels = order_t), y=factor(V1,levels=order_f), fill= ave,group=year)) + geom_tile()+ scale_fill_gradient2(low="blue", high="red")+ theme_bw()+ xlab("To") + ylab("From")+ labs(fill="Number of Jumps")+ facet_grid(segment~year,scales="free")+ scale_x_discrete(position = "top")
source("ITC_data_process.R") # Se crea el directorio de salida dir.create("output", showWarnings=F) ITC.porindividuo <- data.frame( ID = ITC$ID, sexo = ITC$sexo, NS = rowSums(ITC[paste0("R",c(1,29,52,70,99,114,144,167,191,211,238,13,35,61,82,108,130,148,187,203,237,19,41,66,109,139,155,174,192,219,34,53,79,91,110,141,165,183,204,212))]), HA = rowSums(ITC[paste0("R",c(2,20,42,65,81,112,119,149,164,188,225,12,26,67,129,154,189,217,27,54,80,100,142,157,209,231,22,43,63,92,113,147,182,202,236))]), RD = rowSums(ITC[paste0("R",c(3,28,55,83,102,120,158,181,210,224,75,101,111,118,134,137,140,170,176,190,213,230,239,240,21,44,68,117,143,180,201,226,14,46,71,131,156,193))]), PE = rowSums(ITC[paste0("R",c(11,37,62,103,128,166,205,218))]), SD = rowSums(ITC[paste0("R",c(4,24,58,86,121,151,169,198,9,30,59,105,126,159,177,223,40,106,171,197,233,32,60,74,85,94,107,136,150,179,214,229,17,36,39,90,104,115,135,162,184,196,207,221))]), CO = rowSums(ITC[paste0("R",c(5,16,48,89,122,133,172,234,25,49,73,37,161,185,227,10,47,64,87,127,153,178,216,7,33,57,78,98,124,146,168,199,222,18,50,72,93,138,160,186,206,235))]), ST = rowSums(ITC[paste0("R",c(8,23,45,76,96,125,152,173,195,215,228,15,31,51,84,95,132,163,200,232,6,38,56,77,88,97,116,123,145,175,194,208,220))]) ) capture.output(ITC.porindividuo,file=paste0("output/ITCxIndividuo_",Sys.Date(),"txt"))
/ITC_por_individuo (1).R
no_license
azaleara/ITC
R
false
false
1,347
r
source("ITC_data_process.R") # Se crea el directorio de salida dir.create("output", showWarnings=F) ITC.porindividuo <- data.frame( ID = ITC$ID, sexo = ITC$sexo, NS = rowSums(ITC[paste0("R",c(1,29,52,70,99,114,144,167,191,211,238,13,35,61,82,108,130,148,187,203,237,19,41,66,109,139,155,174,192,219,34,53,79,91,110,141,165,183,204,212))]), HA = rowSums(ITC[paste0("R",c(2,20,42,65,81,112,119,149,164,188,225,12,26,67,129,154,189,217,27,54,80,100,142,157,209,231,22,43,63,92,113,147,182,202,236))]), RD = rowSums(ITC[paste0("R",c(3,28,55,83,102,120,158,181,210,224,75,101,111,118,134,137,140,170,176,190,213,230,239,240,21,44,68,117,143,180,201,226,14,46,71,131,156,193))]), PE = rowSums(ITC[paste0("R",c(11,37,62,103,128,166,205,218))]), SD = rowSums(ITC[paste0("R",c(4,24,58,86,121,151,169,198,9,30,59,105,126,159,177,223,40,106,171,197,233,32,60,74,85,94,107,136,150,179,214,229,17,36,39,90,104,115,135,162,184,196,207,221))]), CO = rowSums(ITC[paste0("R",c(5,16,48,89,122,133,172,234,25,49,73,37,161,185,227,10,47,64,87,127,153,178,216,7,33,57,78,98,124,146,168,199,222,18,50,72,93,138,160,186,206,235))]), ST = rowSums(ITC[paste0("R",c(8,23,45,76,96,125,152,173,195,215,228,15,31,51,84,95,132,163,200,232,6,38,56,77,88,97,116,123,145,175,194,208,220))]) ) capture.output(ITC.porindividuo,file=paste0("output/ITCxIndividuo_",Sys.Date(),"txt"))
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/plotter.R \name{plotter} \alias{plotter} \title{A plotter for decition tree models} \usage{ plotter(node, varz = c("name", "cost", "qol"), edgelabel = TRUE) } \arguments{ \item{node}{} \item{varz}{} \item{edgelabel}{} } \value{ \code{DiagrammeR} object } \description{ This is a simplified plotting utility that allows visual checking of decision tree models. By default, the node names, costs, HRQoLs are displayed as well as the edge probabilities. The node attributes to display can be specified in `varz`. The boolean `edgelabel` variable allows turning the edge labels off. } \author{ Pete Dodd }
/man/plotter.Rd
permissive
Diarmuid78/HEdtree
R
false
true
682
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/plotter.R \name{plotter} \alias{plotter} \title{A plotter for decition tree models} \usage{ plotter(node, varz = c("name", "cost", "qol"), edgelabel = TRUE) } \arguments{ \item{node}{} \item{varz}{} \item{edgelabel}{} } \value{ \code{DiagrammeR} object } \description{ This is a simplified plotting utility that allows visual checking of decision tree models. By default, the node names, costs, HRQoLs are displayed as well as the edge probabilities. The node attributes to display can be specified in `varz`. The boolean `edgelabel` variable allows turning the edge labels off. } \author{ Pete Dodd }
\name{msTreeKruskal} \alias{msTreeKruskal} \title{Minimum cost spanning tree with Kruskal's algorithm} \usage{ msTreeKruskal(nodes, arcs) } \arguments{ \item{nodes}{vector containing the nodes of the graph, identified by a number that goes from \eqn{1} to the order of the graph.} \item{arcs}{matrix with the list of arcs of the graph. Each row represents one arc. The first two columns contain the two endpoints of each arc and the third column contains their weights.} } \value{ \code{msTreeKruskal} returns a list with: \item{tree.nodes}{vector containing the nodes of the minimum cost spanning tree.} \item{tree.arcs}{matrix containing the list of arcs of the minimum cost spanning tree.} \item{stages}{number of stages required.} \item{stages.arcs}{stages in which each arc was added.} } \description{ \code{msTreeKruskal} computes a minimum cost spanning tree of an undirected graph with Kruskal's algorithm. } \details{ Kruskal's algorithm was published for first time in 1956 by mathematician Joseph Kruskal. This is a greedy algorithm that finds a minimum cost spanning tree in a connected weighted undirected graph by adding, without forming cycles, the minimum weight arc of the graph at each stage. } \references{ Kruskal, Joshep B. (1956), "On the Shortest Spanning Subtree of a Graph and the Traveling Salesman Problem", Proceedings of the American Mathematical Society, Vol. 7, No. 1 (Feb., 1956), pp. 48-50 } \seealso{ A more general function \link{getMinimumSpanningTree}. }
/man/msTreeKruskal.Rd
no_license
cran/optrees
R
false
false
1,509
rd
\name{msTreeKruskal} \alias{msTreeKruskal} \title{Minimum cost spanning tree with Kruskal's algorithm} \usage{ msTreeKruskal(nodes, arcs) } \arguments{ \item{nodes}{vector containing the nodes of the graph, identified by a number that goes from \eqn{1} to the order of the graph.} \item{arcs}{matrix with the list of arcs of the graph. Each row represents one arc. The first two columns contain the two endpoints of each arc and the third column contains their weights.} } \value{ \code{msTreeKruskal} returns a list with: \item{tree.nodes}{vector containing the nodes of the minimum cost spanning tree.} \item{tree.arcs}{matrix containing the list of arcs of the minimum cost spanning tree.} \item{stages}{number of stages required.} \item{stages.arcs}{stages in which each arc was added.} } \description{ \code{msTreeKruskal} computes a minimum cost spanning tree of an undirected graph with Kruskal's algorithm. } \details{ Kruskal's algorithm was published for first time in 1956 by mathematician Joseph Kruskal. This is a greedy algorithm that finds a minimum cost spanning tree in a connected weighted undirected graph by adding, without forming cycles, the minimum weight arc of the graph at each stage. } \references{ Kruskal, Joshep B. (1956), "On the Shortest Spanning Subtree of a Graph and the Traveling Salesman Problem", Proceedings of the American Mathematical Society, Vol. 7, No. 1 (Feb., 1956), pp. 48-50 } \seealso{ A more general function \link{getMinimumSpanningTree}. }
" @author: Zsofia Koma, UvA Aim: just fast export input: output: Fuctions: Example: " # Import required libraries library("lidR") library("rlas") #Import full_path="D:/Koma/Paper1_ReedStructure/TestWorkflow/justfortest/" filename="tile_00015.laz" setwd(full_path) start_time <- Sys.time() las = readLAS(filename) las_nonground = lasfilter(las, Classification != 2) writeLAS(las_nonground,paste(substr(filename, 1, nchar(filename)-4) ,"_nonground.las",sep="")) end_time <- Sys.time() print(end_time - start_time)
/R_process/justfastexport.R
no_license
komazsofi/myPhD_escience_analysis
R
false
false
523
r
" @author: Zsofia Koma, UvA Aim: just fast export input: output: Fuctions: Example: " # Import required libraries library("lidR") library("rlas") #Import full_path="D:/Koma/Paper1_ReedStructure/TestWorkflow/justfortest/" filename="tile_00015.laz" setwd(full_path) start_time <- Sys.time() las = readLAS(filename) las_nonground = lasfilter(las, Classification != 2) writeLAS(las_nonground,paste(substr(filename, 1, nchar(filename)-4) ,"_nonground.las",sep="")) end_time <- Sys.time() print(end_time - start_time)
########################################################### ##### cross-validation for log penalized regression ###### ########################################################### ## just an R loop that calls gamlr cv.gamlr <- function(x, y, nfold=5, foldid=NULL, verb=FALSE, cl=NULL, ...){ full <- gamlr(x,y, ...) fam <- full$family y <- checky(y,fam) nobs <- full$nobs if(is.null(foldid)){ nfold <- min(nfold,nobs) foldsize <- ceiling(nobs/nfold) foldid <- rep.int(1:nfold,times=foldsize)[sample.int(nobs)] } else stopifnot(length(foldid)==nobs) foldid <- factor(foldid) nfold <- nlevels(foldid) argl <- list(...) if(!is.null(argl$shift)) shift <- argl$shift lambda <- as.double(full$lambda) argl$lambda.start <- lambda[1] argl$nlambda <- length(lambda) argl$lambda.min.ratio <- tail(lambda,1)/lambda[1] ## remove any pre-calculated summaries argl$vxx <- argl$vxsum <- argl$vxy <- argl$xbar <- NULL oos <- matrix(Inf, nrow=nfold, ncol=argl$nlambda, dimnames=list(levels(foldid),names(lambda))) if(verb) cat("fold ") ## define the folddev function folddev <- function(k){ require(gamlr) train <- which(foldid!=k) if(!is.null(argl$shift)) argl$shift <- shift[train] suppressWarnings(fit <- do.call(gamlr, c(list(x=x[train,],y=y[train]), argl))) eta <- predict(fit, x[-train,,drop=FALSE], select=0) if(!is.null(argl$shift)) eta <- eta + shift[-train] dev <- apply(eta,2, function(e) mean(switch(fam, "gaussian" = (e-y[-train])^2, "binomial" = -2*(y[-train]*e - log(1+exp(e))), "poisson" = -2*(y[-train]*e - exp(e))))) if(fam=="poisson"){ satnllhd <- mean(ifelse(y[-train]>0, y[-train]*log(y[-train]), 0.0) - y[-train]) dev <- dev + 2*satnllhd } if(verb) cat(sprintf("%s,",k)) if(length(dev) < argl$nlambda) dev <- c(dev,rep(Inf,argl$nlambda-length(dev))) return(dev) } # apply the folddev function if(!is.null(cl)){ if (requireNamespace("parallel", quietly = TRUE)) { parallel::clusterExport(cl, c("x","y","foldid","argl","fam","verb"), envir=environment()) oos <- t(parallel::parSapply(cl,1:nfold,folddev)) } else { warning("cl is not NULL, but parallle package unavailable.") cl <- NULL } } if(is.null(cl)) oos <- t(sapply(1:nfold,folddev)) cvm <- apply(oos,2,mean) cvs <- apply(oos,2,sd)/sqrt(nfold-1) seg.min <- which.min(cvm) lambda.min = lambda[seg.min] cv1se <- (cvm[seg.min]+cvs[seg.min])-cvm seg.1se <- min((1:length(cvm))[cv1se>=0]) lambda.1se = lambda[seg.1se] if(verb) cat("done.\n") out <- list(gamlr=full, family=fam, nfold=nfold, foldid=foldid, cvm=cvm, cvs=cvs, seg.min=seg.min, seg.1se=seg.1se, lambda.min=lambda.min, lambda.1se=lambda.1se) class(out) <- "cv.gamlr" invisible(out) } ## S3 method functions plot.cv.gamlr <- function(x, select=TRUE, df=TRUE, ...){ argl = list(...) argl$x <- log(x$gamlr$lambda) argl$y <- x$cvm argl$type <- "n" if(is.null(argl$xlab)) argl$xlab="log lambda" if(is.null(argl$ylab)){ if(x$family=="gaussian") argl$ylab="mean squared error" else argl$ylab=sprintf("%s deviance",x$family) } if(is.null(argl$pch)) argl$pch=20 if(is.null(argl$col)) argl$col=4 cvlo <- x$cvm-x$cvs cvhi <- x$cvm+x$cvs if(is.null(argl$ylim)) argl$ylim=range(c(cvlo,cvhi),finite=TRUE) if(is.null(argl$xlim)) argl$xlim=range(argl$x[is.finite(argl$y)]) suppressWarnings(do.call(plot, argl)) segments(x0=argl$x, y0=cvlo, y1=cvhi, col="grey70") argl$type <- NULL suppressWarnings(do.call(points, argl)) if(select){ abline(v=log(x$lambda.min), lty=3, col="grey20") abline(v=log(x$lambda.1se), lty=3, col="grey20") } if(df){ dfi <- unique(round( seq(1,length(argl$x),length=ceiling(length(axTicks(1)))))) axis(3,at=argl$x[dfi], labels=round(x$gamlr$df[dfi],1),tick=FALSE, line=-.5) } } coef.cv.gamlr <- function(object, select=c("1se","min"), ...){ seg = paste("seg",match.arg(select),sep=".") coef(object$gamlr, select=object[[seg]]) } predict.cv.gamlr <- function(object, newdata, select=c("1se","min"), ...){ seg = paste("seg",match.arg(select),sep=".") predict.gamlr(object$gamlr, newdata, select=object[[seg]], ...) } summary.cv.gamlr <- function(object, ...){ print(object) return(data.frame( lambda=object$gamlr$lambda, par=diff(object$gamlr$b@p)+1, oos.r2=1-object$cvm/object$cvm[1])) } print.cv.gamlr <- function(x, ...){ cat("\n") cat(sprintf( "%d-fold %s cv.gamlr object", x$nfold, x$gamlr$family)) cat("\n\n") }
/R/cv.gamlr.R
no_license
Sandy4321/gamlr
R
false
false
4,869
r
########################################################### ##### cross-validation for log penalized regression ###### ########################################################### ## just an R loop that calls gamlr cv.gamlr <- function(x, y, nfold=5, foldid=NULL, verb=FALSE, cl=NULL, ...){ full <- gamlr(x,y, ...) fam <- full$family y <- checky(y,fam) nobs <- full$nobs if(is.null(foldid)){ nfold <- min(nfold,nobs) foldsize <- ceiling(nobs/nfold) foldid <- rep.int(1:nfold,times=foldsize)[sample.int(nobs)] } else stopifnot(length(foldid)==nobs) foldid <- factor(foldid) nfold <- nlevels(foldid) argl <- list(...) if(!is.null(argl$shift)) shift <- argl$shift lambda <- as.double(full$lambda) argl$lambda.start <- lambda[1] argl$nlambda <- length(lambda) argl$lambda.min.ratio <- tail(lambda,1)/lambda[1] ## remove any pre-calculated summaries argl$vxx <- argl$vxsum <- argl$vxy <- argl$xbar <- NULL oos <- matrix(Inf, nrow=nfold, ncol=argl$nlambda, dimnames=list(levels(foldid),names(lambda))) if(verb) cat("fold ") ## define the folddev function folddev <- function(k){ require(gamlr) train <- which(foldid!=k) if(!is.null(argl$shift)) argl$shift <- shift[train] suppressWarnings(fit <- do.call(gamlr, c(list(x=x[train,],y=y[train]), argl))) eta <- predict(fit, x[-train,,drop=FALSE], select=0) if(!is.null(argl$shift)) eta <- eta + shift[-train] dev <- apply(eta,2, function(e) mean(switch(fam, "gaussian" = (e-y[-train])^2, "binomial" = -2*(y[-train]*e - log(1+exp(e))), "poisson" = -2*(y[-train]*e - exp(e))))) if(fam=="poisson"){ satnllhd <- mean(ifelse(y[-train]>0, y[-train]*log(y[-train]), 0.0) - y[-train]) dev <- dev + 2*satnllhd } if(verb) cat(sprintf("%s,",k)) if(length(dev) < argl$nlambda) dev <- c(dev,rep(Inf,argl$nlambda-length(dev))) return(dev) } # apply the folddev function if(!is.null(cl)){ if (requireNamespace("parallel", quietly = TRUE)) { parallel::clusterExport(cl, c("x","y","foldid","argl","fam","verb"), envir=environment()) oos <- t(parallel::parSapply(cl,1:nfold,folddev)) } else { warning("cl is not NULL, but parallle package unavailable.") cl <- NULL } } if(is.null(cl)) oos <- t(sapply(1:nfold,folddev)) cvm <- apply(oos,2,mean) cvs <- apply(oos,2,sd)/sqrt(nfold-1) seg.min <- which.min(cvm) lambda.min = lambda[seg.min] cv1se <- (cvm[seg.min]+cvs[seg.min])-cvm seg.1se <- min((1:length(cvm))[cv1se>=0]) lambda.1se = lambda[seg.1se] if(verb) cat("done.\n") out <- list(gamlr=full, family=fam, nfold=nfold, foldid=foldid, cvm=cvm, cvs=cvs, seg.min=seg.min, seg.1se=seg.1se, lambda.min=lambda.min, lambda.1se=lambda.1se) class(out) <- "cv.gamlr" invisible(out) } ## S3 method functions plot.cv.gamlr <- function(x, select=TRUE, df=TRUE, ...){ argl = list(...) argl$x <- log(x$gamlr$lambda) argl$y <- x$cvm argl$type <- "n" if(is.null(argl$xlab)) argl$xlab="log lambda" if(is.null(argl$ylab)){ if(x$family=="gaussian") argl$ylab="mean squared error" else argl$ylab=sprintf("%s deviance",x$family) } if(is.null(argl$pch)) argl$pch=20 if(is.null(argl$col)) argl$col=4 cvlo <- x$cvm-x$cvs cvhi <- x$cvm+x$cvs if(is.null(argl$ylim)) argl$ylim=range(c(cvlo,cvhi),finite=TRUE) if(is.null(argl$xlim)) argl$xlim=range(argl$x[is.finite(argl$y)]) suppressWarnings(do.call(plot, argl)) segments(x0=argl$x, y0=cvlo, y1=cvhi, col="grey70") argl$type <- NULL suppressWarnings(do.call(points, argl)) if(select){ abline(v=log(x$lambda.min), lty=3, col="grey20") abline(v=log(x$lambda.1se), lty=3, col="grey20") } if(df){ dfi <- unique(round( seq(1,length(argl$x),length=ceiling(length(axTicks(1)))))) axis(3,at=argl$x[dfi], labels=round(x$gamlr$df[dfi],1),tick=FALSE, line=-.5) } } coef.cv.gamlr <- function(object, select=c("1se","min"), ...){ seg = paste("seg",match.arg(select),sep=".") coef(object$gamlr, select=object[[seg]]) } predict.cv.gamlr <- function(object, newdata, select=c("1se","min"), ...){ seg = paste("seg",match.arg(select),sep=".") predict.gamlr(object$gamlr, newdata, select=object[[seg]], ...) } summary.cv.gamlr <- function(object, ...){ print(object) return(data.frame( lambda=object$gamlr$lambda, par=diff(object$gamlr$b@p)+1, oos.r2=1-object$cvm/object$cvm[1])) } print.cv.gamlr <- function(x, ...){ cat("\n") cat(sprintf( "%d-fold %s cv.gamlr object", x$nfold, x$gamlr$family)) cat("\n\n") }
# Suppress R CMD check note #' @import data.table #' @import tidytable #' @import stringr NULL
/R/traumaR_package.R
permissive
mjkarlsen/traumaR
R
false
false
95
r
# Suppress R CMD check note #' @import data.table #' @import tidytable #' @import stringr NULL
library(DrugClust) ### Name: Enrichment_Proteins ### Title: Enrichment_Proteins ### Aliases: Enrichment_Proteins ### ** Examples #feature is the feature matrix # pamx is the result of the PAM function # and pamx$clustering gives the list assigning each element to a certain cluster #all_pathways<-Enrichment_Proteins(features,4,pamx$clustering)
/data/genthat_extracted_code/DrugClust/examples/Enrichment_Proteins.Rd.R
no_license
surayaaramli/typeRrh
R
false
false
352
r
library(DrugClust) ### Name: Enrichment_Proteins ### Title: Enrichment_Proteins ### Aliases: Enrichment_Proteins ### ** Examples #feature is the feature matrix # pamx is the result of the PAM function # and pamx$clustering gives the list assigning each element to a certain cluster #all_pathways<-Enrichment_Proteins(features,4,pamx$clustering)
library(here) library(RColorBrewer) library(VennDiagram) library(ggplot2) source(here("../src/ggplot_format.R")) #Import metadata meta_all <- read.csv(here("../doc/Amplicon/meta_NEW.csv"), row.names = 1) #Clean a bit meta_all$Treatment <- factor(meta_all$Treatment, levels = c("ctrl", "5NO", "25NO")) meta_all$Date <- factor(meta_all$Date, levels = c("5th.June", "24th.June", "6th.A ugust", "9th.October")) #Import count matrix count_mat <- read.csv(here("../data/Amplicon/count_mat_NEW.csv"), row.names = 1) ##### ONLY CONTROL SAMPLES ROOTS AND NEEDLES COMBINED control <- grepl("ctrl", meta_all$SampleID) count_mat_ctrl <- count_mat[,control] count_mat_ctrl <- count_mat_ctrl[rowSums(count_mat_ctrl)>0,] #Booleans to extract roots and needles roots <- grepl("root", meta_all$SampleID) needl <- grepl("needl", meta_all$SampleID) #Extract and filter root samples count_mat_r <- count_mat[,roots] count_mat_r <- count_mat_r[rowSums(count_mat_r)>0,] #Extract and filter needle samples count_mat_n <- count_mat[,needl] count_mat_n <- count_mat_n[rowSums(count_mat_n)>0,] ##Venn ##Control only count_mat_r_c <- count_mat_r[,grepl("ctrl", colnames(count_mat_r))] count_mat_r_c <- count_mat_r_c[rowSums(count_mat_r_c)>0,] count_mat_n_c <- count_mat_n[,grepl("ctrl", colnames(count_mat_n))] count_mat_n_c <- count_mat_n_c[rowSums(count_mat_n_c)>0,] list_its <- list() list_its[[1]] <- rownames(count_mat_n_c) list_its[[2]] <- rownames(count_mat_r_c) pal=brewer.pal(8,"Dark2") pdf(here("Figures/Fig2a_VennControl.pdf")) par(mfrow=c(1,1)) par(mar=c(0.5,0.5,0.5,0.5)) grid.newpage() futile.logger::flog.threshold(futile.logger::ERROR, name = "VennDiagramLogger") grid.draw(venn.diagram(list_its, filename=NULL, category.names = c("Needles","Roots"), fill=pal[1:2])) dev.off() ##Density curve without pseudocount #Extract log transformed counts count_mat_r_c_log1 <- cbind(tissue="Roots", logC=c(log10(data.matrix(count_mat_r_c)))) count_mat_n_c_log1 <- cbind(tissue="Needles", logC=c(log10(data.matrix(count_mat_n_c)))) count_mat_r_c_log1 <- as.data.frame(count_mat_r_c_log1) count_mat_r_c_log1$logC <- as.numeric(as.character(count_mat_r_c_log1$logC)) count_mat_n_c_log1 <- as.data.frame(count_mat_n_c_log1) count_mat_n_c_log1$logC <- as.numeric(as.character(count_mat_n_c_log1$logC)) ggplot()+ stat_density(geom = "line", data = count_mat_n_c_log1, aes(x = logC), col = brewer.pal(8, "Dark2")[1], size = 1.1, alpha = .7)+ stat_density(geom = "line", data = count_mat_r_c_log1, aes(x = logC), col = brewer.pal(8, "Dark2")[2], size = 1.1, alpha = .7)+ ggformat+ theme(axis.text.x = element_text(angle = 0), axis.title.x = element_text())+ xlab("log10(count)")+ ylab("Density")+ coord_cartesian(xlim = c(0, 4)) ggsave(here("Figures/Fig2a_density_ITS.pdf"), width = 3, height = 2.5) ##Density curve with pseudocount #Extract log transformed counts count_mat_r_c_log <- cbind(tissue="Roots", logC=c(log10(data.matrix(count_mat_r_c+1)))) count_mat_n_c_log <- cbind(tissue="Needles", logC=c(log10(data.matrix(count_mat_n_c+1)))) count_mat_r_c_log <- as.data.frame(count_mat_r_c_log) count_mat_r_c_log$logC <- as.numeric(as.character(count_mat_r_c_log$logC)) count_mat_n_c_log <- as.data.frame(count_mat_n_c_log) count_mat_n_c_log$logC <- as.numeric(as.character(count_mat_n_c_log$logC)) ggplot()+ stat_density(geom = "line", data = count_mat_n_c_log, aes(x = logC), col = brewer.pal(8, "Dark2")[1], size = 1.1, alpha = .7)+ stat_density(geom = "line", data = count_mat_r_c_log, aes(x = logC), col = brewer.pal(8, "Dark2")[2], size = 1.1, alpha = .7)+ ggformat+ theme(axis.text.x = element_text(angle = 0), axis.title.x = element_text())+ xlab("log10(count+1)")+ ylab("Density")+ coord_cartesian(xlim = c(0, 4)) ggsave(here("Figures/FigS2a_density_ITS.pdf"), width = 3, height = 2.5)
/analysis/Figure2a.R
permissive
andnischneider/its_workflow
R
false
false
4,197
r
library(here) library(RColorBrewer) library(VennDiagram) library(ggplot2) source(here("../src/ggplot_format.R")) #Import metadata meta_all <- read.csv(here("../doc/Amplicon/meta_NEW.csv"), row.names = 1) #Clean a bit meta_all$Treatment <- factor(meta_all$Treatment, levels = c("ctrl", "5NO", "25NO")) meta_all$Date <- factor(meta_all$Date, levels = c("5th.June", "24th.June", "6th.A ugust", "9th.October")) #Import count matrix count_mat <- read.csv(here("../data/Amplicon/count_mat_NEW.csv"), row.names = 1) ##### ONLY CONTROL SAMPLES ROOTS AND NEEDLES COMBINED control <- grepl("ctrl", meta_all$SampleID) count_mat_ctrl <- count_mat[,control] count_mat_ctrl <- count_mat_ctrl[rowSums(count_mat_ctrl)>0,] #Booleans to extract roots and needles roots <- grepl("root", meta_all$SampleID) needl <- grepl("needl", meta_all$SampleID) #Extract and filter root samples count_mat_r <- count_mat[,roots] count_mat_r <- count_mat_r[rowSums(count_mat_r)>0,] #Extract and filter needle samples count_mat_n <- count_mat[,needl] count_mat_n <- count_mat_n[rowSums(count_mat_n)>0,] ##Venn ##Control only count_mat_r_c <- count_mat_r[,grepl("ctrl", colnames(count_mat_r))] count_mat_r_c <- count_mat_r_c[rowSums(count_mat_r_c)>0,] count_mat_n_c <- count_mat_n[,grepl("ctrl", colnames(count_mat_n))] count_mat_n_c <- count_mat_n_c[rowSums(count_mat_n_c)>0,] list_its <- list() list_its[[1]] <- rownames(count_mat_n_c) list_its[[2]] <- rownames(count_mat_r_c) pal=brewer.pal(8,"Dark2") pdf(here("Figures/Fig2a_VennControl.pdf")) par(mfrow=c(1,1)) par(mar=c(0.5,0.5,0.5,0.5)) grid.newpage() futile.logger::flog.threshold(futile.logger::ERROR, name = "VennDiagramLogger") grid.draw(venn.diagram(list_its, filename=NULL, category.names = c("Needles","Roots"), fill=pal[1:2])) dev.off() ##Density curve without pseudocount #Extract log transformed counts count_mat_r_c_log1 <- cbind(tissue="Roots", logC=c(log10(data.matrix(count_mat_r_c)))) count_mat_n_c_log1 <- cbind(tissue="Needles", logC=c(log10(data.matrix(count_mat_n_c)))) count_mat_r_c_log1 <- as.data.frame(count_mat_r_c_log1) count_mat_r_c_log1$logC <- as.numeric(as.character(count_mat_r_c_log1$logC)) count_mat_n_c_log1 <- as.data.frame(count_mat_n_c_log1) count_mat_n_c_log1$logC <- as.numeric(as.character(count_mat_n_c_log1$logC)) ggplot()+ stat_density(geom = "line", data = count_mat_n_c_log1, aes(x = logC), col = brewer.pal(8, "Dark2")[1], size = 1.1, alpha = .7)+ stat_density(geom = "line", data = count_mat_r_c_log1, aes(x = logC), col = brewer.pal(8, "Dark2")[2], size = 1.1, alpha = .7)+ ggformat+ theme(axis.text.x = element_text(angle = 0), axis.title.x = element_text())+ xlab("log10(count)")+ ylab("Density")+ coord_cartesian(xlim = c(0, 4)) ggsave(here("Figures/Fig2a_density_ITS.pdf"), width = 3, height = 2.5) ##Density curve with pseudocount #Extract log transformed counts count_mat_r_c_log <- cbind(tissue="Roots", logC=c(log10(data.matrix(count_mat_r_c+1)))) count_mat_n_c_log <- cbind(tissue="Needles", logC=c(log10(data.matrix(count_mat_n_c+1)))) count_mat_r_c_log <- as.data.frame(count_mat_r_c_log) count_mat_r_c_log$logC <- as.numeric(as.character(count_mat_r_c_log$logC)) count_mat_n_c_log <- as.data.frame(count_mat_n_c_log) count_mat_n_c_log$logC <- as.numeric(as.character(count_mat_n_c_log$logC)) ggplot()+ stat_density(geom = "line", data = count_mat_n_c_log, aes(x = logC), col = brewer.pal(8, "Dark2")[1], size = 1.1, alpha = .7)+ stat_density(geom = "line", data = count_mat_r_c_log, aes(x = logC), col = brewer.pal(8, "Dark2")[2], size = 1.1, alpha = .7)+ ggformat+ theme(axis.text.x = element_text(angle = 0), axis.title.x = element_text())+ xlab("log10(count+1)")+ ylab("Density")+ coord_cartesian(xlim = c(0, 4)) ggsave(here("Figures/FigS2a_density_ITS.pdf"), width = 3, height = 2.5)
library(micEconCES) ### Name: summary.cesEst ### Title: Summarize Estimation of a CES Function ### Aliases: summary.cesEst print.summary.cesEst ### Keywords: models ### ** Examples data( germanFarms, package = "micEcon" ) # output quantity: germanFarms$qOutput <- germanFarms$vOutput / germanFarms$pOutput # quantity of intermediate inputs germanFarms$qVarInput <- germanFarms$vVarInput / germanFarms$pVarInput ## CES: Land & Labor cesLandLabor <- cesEst( "qOutput", c( "land", "qLabor" ), germanFarms ) # print summary results summary( cesLandLabor )
/data/genthat_extracted_code/micEconCES/examples/summary.cesEst.Rd.R
no_license
surayaaramli/typeRrh
R
false
false
589
r
library(micEconCES) ### Name: summary.cesEst ### Title: Summarize Estimation of a CES Function ### Aliases: summary.cesEst print.summary.cesEst ### Keywords: models ### ** Examples data( germanFarms, package = "micEcon" ) # output quantity: germanFarms$qOutput <- germanFarms$vOutput / germanFarms$pOutput # quantity of intermediate inputs germanFarms$qVarInput <- germanFarms$vVarInput / germanFarms$pVarInput ## CES: Land & Labor cesLandLabor <- cesEst( "qOutput", c( "land", "qLabor" ), germanFarms ) # print summary results summary( cesLandLabor )
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/tfsR-package.r \docType{package} \name{tfsR} \alias{tfsR} \alias{tfsR-package} \title{tfsR If you have/want to work with R using git repositories in TFS (either on-premises or via Visual Studio Online), this package saves you having to have Visual Studio installed on your machine.} \description{ ## Setup } \details{ You must have a username (often an email address or AD account) and password for connecting. That's basically it! NB - you can now use public acces tokens. ## Structure / Methodology The active components use a Team Project containing many git repositories - this means any backlogs etc that you might wish to use need to be implemented for the entire project. As such, if you want different backlogs and so forth, you will need to create projects via the GUI since no API command exists for the creation of projects. }
/man/tfsR.Rd
no_license
lockedata/tfsR
R
false
true
923
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/tfsR-package.r \docType{package} \name{tfsR} \alias{tfsR} \alias{tfsR-package} \title{tfsR If you have/want to work with R using git repositories in TFS (either on-premises or via Visual Studio Online), this package saves you having to have Visual Studio installed on your machine.} \description{ ## Setup } \details{ You must have a username (often an email address or AD account) and password for connecting. That's basically it! NB - you can now use public acces tokens. ## Structure / Methodology The active components use a Team Project containing many git repositories - this means any backlogs etc that you might wish to use need to be implemented for the entire project. As such, if you want different backlogs and so forth, you will need to create projects via the GUI since no API command exists for the creation of projects. }
## EI: CV Super Learner library(SuperLearner) library(parallel) library(doMC) options(mc.cores=80) # full simulated data set load("/data/markscan_authorized_users/bergquist/EI/df_sim_full.Rdata") data <- df_sim # if downloading data from github, will be in csv form # check the data summary(data) ## took this out because performed in SAS # check for duplicate rows # dupsdf <- data[duplicated(data),] # dim(dupsdf) # rm(dupsdf) # min and max for all variables besides unprofits max(data[,-1]) min(data[,-1]) # max and min for unprofits max(data[,1]) min(data[,1]) set.seed(27) # get rid of variables with no obs newdat <-data[, colSums(data != 0) > 0] dim(newdat) cSums<-colSums(newdat) # "screener" for taking out therapeutic class variables tgrp.fun <- function(X, ...){ whichvars <- c(rep.int(TRUE, ncol(X))) names(whichvars) <- colnames(X) tclsvars <- grep("tcls", names(X), value=T) whichvars[tclsvars] <- FALSE whichvars <- unname(whichvars) return(whichvars) } # lasso screener that always retains classes for HIV and MS drugs var.index <- c(which(colnames(newdat)=="tcls14"), which(colnames(newdat)=="tcls251")) screen.glmnet10 <- function(Y, X, family, alpha = 1, minscreen = 2, nfolds = 10, nlambda = 100,fixed.var.index=var.index,...) { # .SL.require('glmnet') if(!is.matrix(X)) { X <- model.matrix(~ -1 + ., X) } fitCV <- glmnet::cv.glmnet(x = X, y = Y, lambda = NULL, type.measure = 'deviance', nfolds = nfolds, family = family$family, alpha = alpha, nlambda = nlambda, pmax=10, parallel=T) whichVariable <- (as.numeric(coef(fitCV$glmnet.fit, s = fitCV$lambda.min))[-1] != 0) # the [-1] removes the intercept; taking the coefs from the fit w/ lambda that gives minimum cvm if (sum(whichVariable) < minscreen) { warning("fewer than minscreen variables passed the glmnet screen, increased lambda to allow minscreen variables") sumCoef <- apply(as.matrix(fitCV$glmnet.fit$beta), 2, function(x) sum((x != 0))) newCut <- which.max(sumCoef >= minscreen) whichVariable <- (as.matrix(fitCV$glmnet.fit$beta)[, newCut] != 0) } whichVariable[c(var.index)] <- TRUE return(whichVariable) } # lasso SL.glmnet1 <- function(Y, X, newX, family, obsWeights, id, alpha = 1, nfolds = 10, nlambda = 100, useMin = TRUE, ...) { #.SL.require('glmnet') # X must be a matrix, should we use model.matrix or as.matrix if(!is.matrix(X)) { X <- model.matrix(~ -1 + ., X) newX <- model.matrix(~ -1 + ., newX) } # now use CV to find lambda fitCV <- glmnet::cv.glmnet(x = X, y = Y, weights = obsWeights, lambda = NULL, type.measure = 'deviance', nfolds = nfolds, family = family$family, alpha = alpha, nlambda = nlambda, parallel=T) # two options for lambda, fitCV$lambda.min and fitCV$lambda.1se pred <- predict(fitCV$glmnet.fit, newx = newX, s = ifelse(useMin, fitCV$lambda.min, fitCV$lambda.1se), type = 'response') fit <- list(object = fitCV, useMin = useMin) class(fit) <- 'SL.glmnet' out <- list(pred = pred, fit = fit) return(out) } # ridge SL.glmnet0 <- function(Y, X, newX, family, obsWeights, id, alpha = 0, nfolds = 10, nlambda = 100, useMin = TRUE, ...) { #.SL.require('glmnet') # X must be a matrix, should we use model.matrix or as.matrix if(!is.matrix(X)) { X <- model.matrix(~ -1 + ., X) newX <- model.matrix(~ -1 + ., newX) } # now use CV to find lambda fitCV <- glmnet::cv.glmnet(x = X, y = Y, weights = obsWeights, lambda = NULL, type.measure = 'deviance', nfolds = nfolds, family = family$family, alpha = alpha, nlambda = nlambda, parallel=T) # two options for lambda, fitCV$lambda.min and fitCV$lambda.1se pred <- predict(fitCV$glmnet.fit, newx = newX, s = ifelse(useMin, fitCV$lambda.min, fitCV$lambda.1se), type = 'response') fit <- list(object = fitCV, useMin = useMin) class(fit) <- 'SL.glmnet' out <- list(pred = pred, fit = fit) return(out) } alg_screen <- list(c("SL.nnet", "All", "tgrp.fun", "screen.glmnet10"), c("SL.glmnet1", "All", "tgrp.fun", "screen.glmnet10"), c("SL.glm", "All", "tgrp.fun", "screen.glmnet10"), c("SL.glmnet0", "All", "tgrp.fun", "screen.glmnet10"), c("SL.rpart", "All", "tgrp.fun", "screen.glmnet10")) set.seed(99) start <- proc.time() fitSL.data.CV <- CV.SuperLearner(Y=newdat[,1],X=newdat[,-1], V=10, SL.library=alg_screen, verbose = TRUE, method = "method.NNLS", family = gaussian(), parallel="multicore") total <- proc.time()-start print(total) cvrisk.SL <- mean((newdat[,1]-fitSL.data.CV$SL.predict)^2) #CV risk for super learner print(cvrisk.SL) save(fitSL.data.CV, file="/data/markscan_authorized_users/bergquist/EI/fullCVfit_sim.Rdata") save(cvrisk.SL, file="/data/markscan_authorized_users/bergquist/EI/fullCVriskSL_sim.Rdata")
/unprofitability_CV_sim.R
no_license
mandixbw/unprofits
R
false
false
4,783
r
## EI: CV Super Learner library(SuperLearner) library(parallel) library(doMC) options(mc.cores=80) # full simulated data set load("/data/markscan_authorized_users/bergquist/EI/df_sim_full.Rdata") data <- df_sim # if downloading data from github, will be in csv form # check the data summary(data) ## took this out because performed in SAS # check for duplicate rows # dupsdf <- data[duplicated(data),] # dim(dupsdf) # rm(dupsdf) # min and max for all variables besides unprofits max(data[,-1]) min(data[,-1]) # max and min for unprofits max(data[,1]) min(data[,1]) set.seed(27) # get rid of variables with no obs newdat <-data[, colSums(data != 0) > 0] dim(newdat) cSums<-colSums(newdat) # "screener" for taking out therapeutic class variables tgrp.fun <- function(X, ...){ whichvars <- c(rep.int(TRUE, ncol(X))) names(whichvars) <- colnames(X) tclsvars <- grep("tcls", names(X), value=T) whichvars[tclsvars] <- FALSE whichvars <- unname(whichvars) return(whichvars) } # lasso screener that always retains classes for HIV and MS drugs var.index <- c(which(colnames(newdat)=="tcls14"), which(colnames(newdat)=="tcls251")) screen.glmnet10 <- function(Y, X, family, alpha = 1, minscreen = 2, nfolds = 10, nlambda = 100,fixed.var.index=var.index,...) { # .SL.require('glmnet') if(!is.matrix(X)) { X <- model.matrix(~ -1 + ., X) } fitCV <- glmnet::cv.glmnet(x = X, y = Y, lambda = NULL, type.measure = 'deviance', nfolds = nfolds, family = family$family, alpha = alpha, nlambda = nlambda, pmax=10, parallel=T) whichVariable <- (as.numeric(coef(fitCV$glmnet.fit, s = fitCV$lambda.min))[-1] != 0) # the [-1] removes the intercept; taking the coefs from the fit w/ lambda that gives minimum cvm if (sum(whichVariable) < minscreen) { warning("fewer than minscreen variables passed the glmnet screen, increased lambda to allow minscreen variables") sumCoef <- apply(as.matrix(fitCV$glmnet.fit$beta), 2, function(x) sum((x != 0))) newCut <- which.max(sumCoef >= minscreen) whichVariable <- (as.matrix(fitCV$glmnet.fit$beta)[, newCut] != 0) } whichVariable[c(var.index)] <- TRUE return(whichVariable) } # lasso SL.glmnet1 <- function(Y, X, newX, family, obsWeights, id, alpha = 1, nfolds = 10, nlambda = 100, useMin = TRUE, ...) { #.SL.require('glmnet') # X must be a matrix, should we use model.matrix or as.matrix if(!is.matrix(X)) { X <- model.matrix(~ -1 + ., X) newX <- model.matrix(~ -1 + ., newX) } # now use CV to find lambda fitCV <- glmnet::cv.glmnet(x = X, y = Y, weights = obsWeights, lambda = NULL, type.measure = 'deviance', nfolds = nfolds, family = family$family, alpha = alpha, nlambda = nlambda, parallel=T) # two options for lambda, fitCV$lambda.min and fitCV$lambda.1se pred <- predict(fitCV$glmnet.fit, newx = newX, s = ifelse(useMin, fitCV$lambda.min, fitCV$lambda.1se), type = 'response') fit <- list(object = fitCV, useMin = useMin) class(fit) <- 'SL.glmnet' out <- list(pred = pred, fit = fit) return(out) } # ridge SL.glmnet0 <- function(Y, X, newX, family, obsWeights, id, alpha = 0, nfolds = 10, nlambda = 100, useMin = TRUE, ...) { #.SL.require('glmnet') # X must be a matrix, should we use model.matrix or as.matrix if(!is.matrix(X)) { X <- model.matrix(~ -1 + ., X) newX <- model.matrix(~ -1 + ., newX) } # now use CV to find lambda fitCV <- glmnet::cv.glmnet(x = X, y = Y, weights = obsWeights, lambda = NULL, type.measure = 'deviance', nfolds = nfolds, family = family$family, alpha = alpha, nlambda = nlambda, parallel=T) # two options for lambda, fitCV$lambda.min and fitCV$lambda.1se pred <- predict(fitCV$glmnet.fit, newx = newX, s = ifelse(useMin, fitCV$lambda.min, fitCV$lambda.1se), type = 'response') fit <- list(object = fitCV, useMin = useMin) class(fit) <- 'SL.glmnet' out <- list(pred = pred, fit = fit) return(out) } alg_screen <- list(c("SL.nnet", "All", "tgrp.fun", "screen.glmnet10"), c("SL.glmnet1", "All", "tgrp.fun", "screen.glmnet10"), c("SL.glm", "All", "tgrp.fun", "screen.glmnet10"), c("SL.glmnet0", "All", "tgrp.fun", "screen.glmnet10"), c("SL.rpart", "All", "tgrp.fun", "screen.glmnet10")) set.seed(99) start <- proc.time() fitSL.data.CV <- CV.SuperLearner(Y=newdat[,1],X=newdat[,-1], V=10, SL.library=alg_screen, verbose = TRUE, method = "method.NNLS", family = gaussian(), parallel="multicore") total <- proc.time()-start print(total) cvrisk.SL <- mean((newdat[,1]-fitSL.data.CV$SL.predict)^2) #CV risk for super learner print(cvrisk.SL) save(fitSL.data.CV, file="/data/markscan_authorized_users/bergquist/EI/fullCVfit_sim.Rdata") save(cvrisk.SL, file="/data/markscan_authorized_users/bergquist/EI/fullCVriskSL_sim.Rdata")
library(R2jags) load("NBA2009.RData") rm(list = (ls()[ls() != "final"])) final = final[final$team == unique(final$team)[1] , ] players = final[ , grepl("Player",names(final))] players = players[ , names( apply(players,2,sum) != 0 )[apply(players,2,sum) != 0] ] lineup = final[ , grepl("lineup",names(final))] lineup = lineup[ , names( apply(lineup,2,sum) != 0 )[apply(lineup,2,sum) != 0] ] final = final[ , !grepl("Player",names(final))] final = final[ , !grepl("lineup",names(final))] final = cbind(final,players) final = cbind(final,lineup) result = final$result X = final[,-which(names(final) %in% c("result","filename","team"))] X = X[ , grepl("lineup",names(X))] lineupcount = names( apply(X,2,sum)[!apply(X,2,sum) > 19] ) final = final[ , - which(names(final) %in% lineupcount)] X = final[,-which(names(final) %in% c("result","filename","team"))] X = X[ , grepl("lineup",names(X))] loseem = apply(X , 1 , sum) != 0 final = final[loseem , ] X = final X = X[ , !grepl("lineup",names(X))] thePlayers = X X = X[,-which(names(X) %in% c("result","filename","team"))] n = nrow(X) p = ncol(X) modelJAGS <- "model { for(i in 1:n){ result[i] ~ dbern(theta[i]); logit(theta[i]) <- beta0 + inprod(X[i,],beta) } for (j in 1:p) { beta[j]~dnorm(0,0.001) } beta0 ~ dnorm(0,1); }" writeLines(modelJAGS,"Logistic.txt") data.jags <- c('result','X','n','p') parms <- c('beta0','beta') logisticReg.sim <- jags(data=data.jags,inits=NULL,parameters.to.save=parms,model.file="Logistic.txt",n.iter=10000,n.burnin=2000,n.chains=1,n.thin=1) sims <- as.mcmc(logisticReg.sim) players <- as.data.frame( as.matrix(sims) ) index = cbind( names(players)[grepl('beta\\[',names(players))] , as.numeric( gsub('\\]','',gsub('beta\\[','',names(players)[grepl('beta\\[',names(players))]))) ) index = index[order( as.numeric( index[,2] ) ) , ] newplayers = players[,c(index[,1] , names(players)[!grepl('beta\\[',names(players))] ) ] names(newplayers)[grepl("beta\\[",names(newplayers))] = names(X) X = final X = X[ , grepl("lineup",names(X))] theLineup = X n = nrow(X) p = ncol(X) modelJAGS <- "model { for(i in 1:n){ result[i] ~ dbern(theta[i]); logit(theta[i]) <- beta0 + inprod(X[i,],beta) } for (j in 1:p) { beta[j]~dnorm(0,0.001) } beta0 ~ dnorm(0,1); }" writeLines(modelJAGS,"Logistic.txt") data.jags <- c('result','X','n','p') parms <- c('beta0','beta') logisticReg.sim <- jags(data=data.jags,inits=NULL,parameters.to.save=parms,model.file="Logistic.txt",n.iter=10000,n.burnin=2000,n.chains=1,n.thin=1) sims <- as.mcmc(logisticReg.sim) lineups <- as.data.frame( as.matrix(sims) ) index = cbind( names(lineups)[grepl('beta\\[',names(lineups))] , as.numeric( gsub('\\]','',gsub('beta\\[','',names(lineups)[grepl('beta\\[',names(lineups))]))) ) index = index[order( as.numeric( index[,2] ) ) , ] newlineups = lineups[,c(index[,1] , names(lineups)[!grepl('beta\\[',names(lineups))] ) ] names(newlineups)[grepl("beta\\[",names(newlineups))] = names(X) # save.image("CHAINs.RData")
/RCODE/logistic.R
no_license
jamesyh/chemistry
R
false
false
3,070
r
library(R2jags) load("NBA2009.RData") rm(list = (ls()[ls() != "final"])) final = final[final$team == unique(final$team)[1] , ] players = final[ , grepl("Player",names(final))] players = players[ , names( apply(players,2,sum) != 0 )[apply(players,2,sum) != 0] ] lineup = final[ , grepl("lineup",names(final))] lineup = lineup[ , names( apply(lineup,2,sum) != 0 )[apply(lineup,2,sum) != 0] ] final = final[ , !grepl("Player",names(final))] final = final[ , !grepl("lineup",names(final))] final = cbind(final,players) final = cbind(final,lineup) result = final$result X = final[,-which(names(final) %in% c("result","filename","team"))] X = X[ , grepl("lineup",names(X))] lineupcount = names( apply(X,2,sum)[!apply(X,2,sum) > 19] ) final = final[ , - which(names(final) %in% lineupcount)] X = final[,-which(names(final) %in% c("result","filename","team"))] X = X[ , grepl("lineup",names(X))] loseem = apply(X , 1 , sum) != 0 final = final[loseem , ] X = final X = X[ , !grepl("lineup",names(X))] thePlayers = X X = X[,-which(names(X) %in% c("result","filename","team"))] n = nrow(X) p = ncol(X) modelJAGS <- "model { for(i in 1:n){ result[i] ~ dbern(theta[i]); logit(theta[i]) <- beta0 + inprod(X[i,],beta) } for (j in 1:p) { beta[j]~dnorm(0,0.001) } beta0 ~ dnorm(0,1); }" writeLines(modelJAGS,"Logistic.txt") data.jags <- c('result','X','n','p') parms <- c('beta0','beta') logisticReg.sim <- jags(data=data.jags,inits=NULL,parameters.to.save=parms,model.file="Logistic.txt",n.iter=10000,n.burnin=2000,n.chains=1,n.thin=1) sims <- as.mcmc(logisticReg.sim) players <- as.data.frame( as.matrix(sims) ) index = cbind( names(players)[grepl('beta\\[',names(players))] , as.numeric( gsub('\\]','',gsub('beta\\[','',names(players)[grepl('beta\\[',names(players))]))) ) index = index[order( as.numeric( index[,2] ) ) , ] newplayers = players[,c(index[,1] , names(players)[!grepl('beta\\[',names(players))] ) ] names(newplayers)[grepl("beta\\[",names(newplayers))] = names(X) X = final X = X[ , grepl("lineup",names(X))] theLineup = X n = nrow(X) p = ncol(X) modelJAGS <- "model { for(i in 1:n){ result[i] ~ dbern(theta[i]); logit(theta[i]) <- beta0 + inprod(X[i,],beta) } for (j in 1:p) { beta[j]~dnorm(0,0.001) } beta0 ~ dnorm(0,1); }" writeLines(modelJAGS,"Logistic.txt") data.jags <- c('result','X','n','p') parms <- c('beta0','beta') logisticReg.sim <- jags(data=data.jags,inits=NULL,parameters.to.save=parms,model.file="Logistic.txt",n.iter=10000,n.burnin=2000,n.chains=1,n.thin=1) sims <- as.mcmc(logisticReg.sim) lineups <- as.data.frame( as.matrix(sims) ) index = cbind( names(lineups)[grepl('beta\\[',names(lineups))] , as.numeric( gsub('\\]','',gsub('beta\\[','',names(lineups)[grepl('beta\\[',names(lineups))]))) ) index = index[order( as.numeric( index[,2] ) ) , ] newlineups = lineups[,c(index[,1] , names(lineups)[!grepl('beta\\[',names(lineups))] ) ] names(newlineups)[grepl("beta\\[",names(newlineups))] = names(X) # save.image("CHAINs.RData")
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/hiReadsProcessor.R \name{pairwiseAlignSeqs} \alias{pairwiseAlignSeqs} \title{Align a short pattern to variable length target sequences.} \usage{ pairwiseAlignSeqs( subjectSeqs = NULL, patternSeq = NULL, side = "left", qualityThreshold = 1, showStats = FALSE, bufferBases = 5, doRC = TRUE, returnUnmatched = FALSE, returnLowScored = FALSE, parallel = FALSE, ... ) } \arguments{ \item{subjectSeqs}{DNAStringSet object containing sequences to be searched for the pattern. This is generally bigger than patternSeq, and cases where subjectSeqs is smaller than patternSeq will be ignored in the alignment.} \item{patternSeq}{DNAString object or a sequence containing the query sequence to search. This is generally smaller than subjectSeqs.} \item{side}{which side of the sequence to perform the search: left, right or middle. Default is 'left'.} \item{qualityThreshold}{percent of patternSeq to match. Default is 1, full match.} \item{showStats}{toggle output of search statistics. Default is FALSE.} \item{bufferBases}{use x number of bases in addition to patternSeq length to perform the search. Beneficial in cases where the pattern has homopolymers or indels compared to the subject. Default is 5. Doesn't apply when side='middle'.} \item{doRC}{perform reverse complement search of the defined pattern. Default is TRUE.} \item{returnUnmatched}{return sequences which had no or less than 5\% match to the patternSeq. Default is FALSE.} \item{returnLowScored}{return sequences which had quality score less than the defined qualityThreshold. Default is FALSE.} \item{parallel}{use parallel backend to perform calculation with \code{\link{BiocParallel}}. Defaults to FALSE. If no parallel backend is registered, then a serial version is ran using \code{\link{SerialParam}}.} \item{...}{extra parameters for \code{\link{pairwiseAlignment}}} } \value{ \itemize{ \item IRanges object with starts, stops, and names of the aligned sequences. \item If returnLowScored or returnUnmatched = T, then a CompressedIRangesList where x[["hits"]] has the good scoring hits, x[["Rejected"]] has the failed to match qualityThreshold hits, and x[["Absent"]] has the hits where the aligned bit is <=10\% match to the patternSeq. } } \description{ Align a fixed length short pattern sequence (i.e. primers or adaptors) to subject sequences using \code{\link{pairwiseAlignment}}. This function uses default of type="overlap", gapOpening=-1, and gapExtension=-1 to align the patternSeq against subjectSeqs. One can adjust these parameters if prefered, but not recommended. This function is meant for aligning a short pattern onto large collection of subjects. If you are looking to align a vector sequence to subjects, then please use BLAT or see one of following \code{\link{blatSeqs}}, \code{\link{findAndRemoveVector}} } \note{ \itemize{ \item For qualityThreshold, the alignment score is calculated by (matches*2)-(mismatches+gaps) which programatically translates to round(nchar(patternSeq)*qualityThreshold)*2. \item Gaps and mismatches are weighed equally with value of -1 which can be overriden by defining extra parameters 'gapOpening' & 'gapExtension'. \item If qualityThreshold is 1, then it is a full match, if 0, then any match is accepted which is useful in searching linker sequences at 3' end. Beware, this function only searches for the pattern sequence in one orientation. If you are expecting to find the pattern in both orientation, you might be better off using BLAST/BLAT! \item If parallel=TRUE, then be sure to have a parallel backend registered before running the function. One can use any of the following \code{\link{MulticoreParam}} \code{\link{SnowParam}} } } \examples{ subjectSeqs <- c("CCTGAATCCTGGCAATGTCATCATC", "ATCCTGGCAATGTCATCATCAATGG", "ATCAGTTGTCAACGGCTAATACGCG", "ATCAATGGCGATTGCCGCGTCTGCA", "CCGCGTCTGCAATGTGAGGGCCTAA", "GAAGGATGCCAGTTGAAGTTCACAC") subjectSeqs <- DNAStringSet(xscat("AAAAAAAAAA", subjectSeqs)) pairwiseAlignSeqs(subjectSeqs, "AAAAAAAAAA", showStats=TRUE) pairwiseAlignSeqs(subjectSeqs, "AAATAATAAA", showStats=TRUE, qualityThreshold=0.5) } \seealso{ \code{\link{primerIDAlignSeqs}}, \code{\link{vpairwiseAlignSeqs}}, \code{\link{doRCtest}}, \code{\link{findAndTrimSeq}}, \code{\link{blatSeqs}}, \code{\link{findAndRemoveVector}} }
/man/pairwiseAlignSeqs.Rd
no_license
malnirav/hiReadsProcessor
R
false
true
4,414
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/hiReadsProcessor.R \name{pairwiseAlignSeqs} \alias{pairwiseAlignSeqs} \title{Align a short pattern to variable length target sequences.} \usage{ pairwiseAlignSeqs( subjectSeqs = NULL, patternSeq = NULL, side = "left", qualityThreshold = 1, showStats = FALSE, bufferBases = 5, doRC = TRUE, returnUnmatched = FALSE, returnLowScored = FALSE, parallel = FALSE, ... ) } \arguments{ \item{subjectSeqs}{DNAStringSet object containing sequences to be searched for the pattern. This is generally bigger than patternSeq, and cases where subjectSeqs is smaller than patternSeq will be ignored in the alignment.} \item{patternSeq}{DNAString object or a sequence containing the query sequence to search. This is generally smaller than subjectSeqs.} \item{side}{which side of the sequence to perform the search: left, right or middle. Default is 'left'.} \item{qualityThreshold}{percent of patternSeq to match. Default is 1, full match.} \item{showStats}{toggle output of search statistics. Default is FALSE.} \item{bufferBases}{use x number of bases in addition to patternSeq length to perform the search. Beneficial in cases where the pattern has homopolymers or indels compared to the subject. Default is 5. Doesn't apply when side='middle'.} \item{doRC}{perform reverse complement search of the defined pattern. Default is TRUE.} \item{returnUnmatched}{return sequences which had no or less than 5\% match to the patternSeq. Default is FALSE.} \item{returnLowScored}{return sequences which had quality score less than the defined qualityThreshold. Default is FALSE.} \item{parallel}{use parallel backend to perform calculation with \code{\link{BiocParallel}}. Defaults to FALSE. If no parallel backend is registered, then a serial version is ran using \code{\link{SerialParam}}.} \item{...}{extra parameters for \code{\link{pairwiseAlignment}}} } \value{ \itemize{ \item IRanges object with starts, stops, and names of the aligned sequences. \item If returnLowScored or returnUnmatched = T, then a CompressedIRangesList where x[["hits"]] has the good scoring hits, x[["Rejected"]] has the failed to match qualityThreshold hits, and x[["Absent"]] has the hits where the aligned bit is <=10\% match to the patternSeq. } } \description{ Align a fixed length short pattern sequence (i.e. primers or adaptors) to subject sequences using \code{\link{pairwiseAlignment}}. This function uses default of type="overlap", gapOpening=-1, and gapExtension=-1 to align the patternSeq against subjectSeqs. One can adjust these parameters if prefered, but not recommended. This function is meant for aligning a short pattern onto large collection of subjects. If you are looking to align a vector sequence to subjects, then please use BLAT or see one of following \code{\link{blatSeqs}}, \code{\link{findAndRemoveVector}} } \note{ \itemize{ \item For qualityThreshold, the alignment score is calculated by (matches*2)-(mismatches+gaps) which programatically translates to round(nchar(patternSeq)*qualityThreshold)*2. \item Gaps and mismatches are weighed equally with value of -1 which can be overriden by defining extra parameters 'gapOpening' & 'gapExtension'. \item If qualityThreshold is 1, then it is a full match, if 0, then any match is accepted which is useful in searching linker sequences at 3' end. Beware, this function only searches for the pattern sequence in one orientation. If you are expecting to find the pattern in both orientation, you might be better off using BLAST/BLAT! \item If parallel=TRUE, then be sure to have a parallel backend registered before running the function. One can use any of the following \code{\link{MulticoreParam}} \code{\link{SnowParam}} } } \examples{ subjectSeqs <- c("CCTGAATCCTGGCAATGTCATCATC", "ATCCTGGCAATGTCATCATCAATGG", "ATCAGTTGTCAACGGCTAATACGCG", "ATCAATGGCGATTGCCGCGTCTGCA", "CCGCGTCTGCAATGTGAGGGCCTAA", "GAAGGATGCCAGTTGAAGTTCACAC") subjectSeqs <- DNAStringSet(xscat("AAAAAAAAAA", subjectSeqs)) pairwiseAlignSeqs(subjectSeqs, "AAAAAAAAAA", showStats=TRUE) pairwiseAlignSeqs(subjectSeqs, "AAATAATAAA", showStats=TRUE, qualityThreshold=0.5) } \seealso{ \code{\link{primerIDAlignSeqs}}, \code{\link{vpairwiseAlignSeqs}}, \code{\link{doRCtest}}, \code{\link{findAndTrimSeq}}, \code{\link{blatSeqs}}, \code{\link{findAndRemoveVector}} }
% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/ggplot2.r \docType{data} \name{luv_colours} \alias{luv_colours} \title{\code{colors()} in Luv space.} \format{A data frame with 657 observations and 4 variables: \itemize{ \item{L,u,v}{Position in Luv colour space} \item{col}{Colour name} }} \usage{ luv_colours } \description{ All built-in \code{\link{colors}()} translated into Luv colour space. } \keyword{datasets}
/man/luv_colours.Rd
no_license
bbolker/ggplot2
R
false
false
456
rd
% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/ggplot2.r \docType{data} \name{luv_colours} \alias{luv_colours} \title{\code{colors()} in Luv space.} \format{A data frame with 657 observations and 4 variables: \itemize{ \item{L,u,v}{Position in Luv colour space} \item{col}{Colour name} }} \usage{ luv_colours } \description{ All built-in \code{\link{colors}()} translated into Luv colour space. } \keyword{datasets}
#Library library(caret) library(rpart.plot) #visualizing library(plyr) library(dplyr) library(vtreat) library(e1071) library(rbokeh) library(MLmetrics) #Set wd setwd("/Users/jlee/Documents/GitHub/HarvardSpringStudent2019/cases/National City Bank") options(scipen=999) #Read in the csv files #dataDictionary <- read.csv('dataDictionary.csv') #Data Dictionary ProspectiveCustomers <- read.csv('ProspectiveCustomers.csv') #New Customer Data #Supplemental Information CurrentCustomerMktgResults <- read.csv('training/CurrentCustomerMktgResults.csv') householdAxiomData <- read.csv('training/householdAxiomData.csv') householdCreditData <- read.csv('training/householdCreditData.csv') householdVehicleData <- read.csv('training/householdVehicleData.csv') #Prediction Set ProspectiveList <- ProspectiveCustomers %>% left_join(householdAxiomData, by = "HHuniqueID") %>% left_join(householdCreditData, by = "HHuniqueID") %>% left_join(householdVehicleData, by = "HHuniqueID") #Combine the Customer Base previousMarketingResults <- CurrentCustomerMktgResults %>% left_join(householdAxiomData, by = "HHuniqueID") %>% left_join(householdCreditData, by = "HHuniqueID") %>% left_join(householdVehicleData, by = "HHuniqueID") previousMarketingResults$Y_AccetpedOffer <- as.factor(previousMarketingResults$Y_AccetpedOffer) ####### ##EDA## ####### #29 Variables (including dependant variable) #"dataID" and "HHuniqueID" are NOT useful for prediction (internal IDs) #"CallStart" and "CallEnd" are NOT available in the Prospective Customer file #We can use 24 dependant variables #Communication - No correlation? 50/50 split for both cell vs telephone table(previousMarketingResults$Communication,previousMarketingResults$Y_AccetpedOffer) #LastContactDay - Certain days have higher probability of success? table(previousMarketingResults$LastContactDay,previousMarketingResults$Y_AccetpedOffer) #LastContactMonth - Certain months have higher activity table(previousMarketingResults$LastContactMonth,previousMarketingResults$Y_AccetpedOffer) #NoOfContacts - Negative correlation? table(previousMarketingResults$NoOfContacts,previousMarketingResults$Y_AccetpedOffer) #DaysPassed - Mostly blank, not useful? table(previousMarketingResults$DaysPassed,previousMarketingResults$Y_AccetpedOffer) #PrevAttempts - Negative correlation? table(previousMarketingResults$PrevAttempts,previousMarketingResults$Y_AccetpedOffer) #Outcome - Positive correlation table(previousMarketingResults$Outcome,previousMarketingResults$Y_AccetpedOffer) #headOfhouseholdGender - Similar results based on gender table(previousMarketingResults$headOfhouseholdGender,previousMarketingResults$Y_AccetpedOffer) #annualDonations - Hard to see from this point of view... Bucketing by $100s would be better table(as.numeric(gsub("\\$", "", previousMarketingResults$annualDonations)),previousMarketingResults$Y_AccetpedOffer) #EstRace - Some races more inclined to accept a loan - but fairly sparse in general and same with the Prospective Data table(previousMarketingResults$EstRace,previousMarketingResults$Y_AccetpedOffer) #PetsPurchases - No Correlation (roughly the same) table(previousMarketingResults$PetsPurchases,previousMarketingResults$Y_AccetpedOffer) #DigitalHabits_5_AlwaysOn - Slight negative correlation 42% -> 39% as always on increases table(previousMarketingResults$DigitalHabits_5_AlwaysOn,previousMarketingResults$Y_AccetpedOffer) #AffluencePurchases - No Correlation table(previousMarketingResults$AffluencePurchases,previousMarketingResults$Y_AccetpedOffer) #Age - Bell Curve? Some ages do seem to play a higher correlation table(previousMarketingResults$Age,previousMarketingResults$Y_AccetpedOffer) #Job - Some occupations are higher than others table(previousMarketingResults$Job,previousMarketingResults$Y_AccetpedOffer) #Marital - Married people more often take loans table(previousMarketingResults$Marital,previousMarketingResults$Y_AccetpedOffer) #Education - Tertiary more 50/50 table(previousMarketingResults$Education,previousMarketingResults$Y_AccetpedOffer) #DefaultOnRecord - Defaulted far less likely to take loans table(previousMarketingResults$DefaultOnRecord,previousMarketingResults$Y_AccetpedOffer) #RecentBalance - Hard to tell from this point of view table(previousMarketingResults$RecentBalance,previousMarketingResults$Y_AccetpedOffer) #HHInsurance - Strong impact table(previousMarketingResults$HHInsurance,previousMarketingResults$Y_AccetpedOffer) #CarLoan - Strong Impact table(previousMarketingResults$CarLoan,previousMarketingResults$Y_AccetpedOffer) #carMake - Some models are more common than others table(previousMarketingResults$carMake,previousMarketingResults$Y_AccetpedOffer) #carModel - Similar to above, but less cases per event... table(previousMarketingResults$carModel,previousMarketingResults$Y_AccetpedOffer) #carYr - Similar to the above table(previousMarketingResults$carYr,previousMarketingResults$Y_AccetpedOffer) #With the EDA above, I would like to remove a few variables from consideration: # 1) Communication 2) DaysPassed 3) headOfhouseholdGender 4) PetsPurchases 5) AffluencePurchases ############ ##Analysis## ############ #Define Variables for vtreat informativeVars <- c("LastContactDay", "LastContactMonth", "NoOfContacts", "PrevAttempts", "Outcome", "annualDonations","EstRace", "DigitalHabits_5_AlwaysOn", "Age", "Job", "Marital", "Education", "DefaultOnRecord", "RecentBalance", "HHInsurance", "CarLoan", "carMake", "carModel", "carYr") y1Target <- "Y_AccetpedOffer" y1Success <- 1 #Apply vtreat plan <- designTreatmentsC(previousMarketingResults, informativeVars, y1Target, y1Success) treatedData <- prepare(plan, previousMarketingResults) #Create Training and Test Datasets set.seed(1234) splitPercent <- round(nrow(treatedData) %*% .8) totalRecords <- 1:nrow(treatedData) idx <- sample(totalRecords, splitPercent) trainDat <- treatedData[idx,] testDat <- treatedData[-idx,] #Create a decision tree fit <- train(Y_AccetpedOffer ~. , #formula based data = trainDat, #data in #caret does "recursive partitioning (trees) method = "rpart", #Define a range for the CP to test tuneGrid = data.frame(cp = c(0.1, 0.01, 0.05, 0.07)), #ie don't split if there are less than 1 record left and only do a split if there are at least 2+ records control = rpart.control(minsplit = 1, minbucket = 2)) sum(complete.cases(trainDat)) plot(fit) # Plot a pruned tree prp(fit$finalModel, extra = 1) # Make some predictions on the training set trainCaret<-predict(fit, trainDat) confusionMatrix(trainCaret, trainDat$Y_AccetpedOffer) # Make some predictions on the test set, the Accuracy is 74.5% testCaret<-predict(fit,testDat) confusionMatrix(testCaret,testDat$Y_AccetpedOffer) # Save the model pth<-'carDecisionTree.rds' saveRDS(fit, pth) #Communication + #LastContactDay + #LastContactMonth + #NoOfContacts + #DaysPassed + #PrevAttempts + #Outcome + #headOfhouseholdGender + #annualDonations + #EstRace + #Maybe remove? #PetsPurchases + #DigitalHabits_5_AlwaysOn + #Maybe remove? #AffluencePurchases + #Age + #Job + #Marital + #Education + #DefaultOnRecord + #RecentBalance + #HHInsurance + #CarLoan + #carMake + #carModel + #carYr ############################# ##Evaluate Prospective List## ############################# treatedTrain <- trainDat treatedTest <- testDat treatedNew <- prepare(plan, ProspectiveList) #Create a 10 fold approach and aggregate the result of each "fold" partition crtl <- trainControl(method = "cv", number = 10, verboseIter = TRUE) finalFit <- train(as.factor(Y_AccetpedOffer) ~ ., data = treatedTrain, method="rpart", cp = 0.01, trControl = crtl) finalFit # We can use a cutoff value of 0.75 to determine who is likely to accept originalProbs <- predict(finalFit, treatedTest, type = 'prob') cutoffProbs <- ifelse(originalProbs[,2]>=0.75,1,0) table(cutoffProbs, treatedTest$Y_AccetpedOffer) #Final Accuracy with a Decision Tree is 68.75% Accuracy(treatedTest$Y_AccetpedOffer, cutoffProbs) # Analyze Prospective Customers newProbs <- predict(finalFit, treatedNew, type = 'prob') head(newProbs) table(ifelse(newProbs[,2]>=0.75,1,0)) # Organize data scoredProspects <- data.frame(id = 1:nrow(treatedNew), risk = newProbs[,1], successProb = newProbs[,2], HHuniqueID = ProspectiveList$HHuniqueID) # Sort by highest probability and examine scoredProspects<-scoredProspects[order(scoredProspects$successProb,decreasing = TRUE),] head(scoredProspects, 100)
/Harvard CSCI E-96/Case 2 (Modeling)/Case Study 2.R
no_license
jlee1991/R-Practice
R
false
false
9,010
r
#Library library(caret) library(rpart.plot) #visualizing library(plyr) library(dplyr) library(vtreat) library(e1071) library(rbokeh) library(MLmetrics) #Set wd setwd("/Users/jlee/Documents/GitHub/HarvardSpringStudent2019/cases/National City Bank") options(scipen=999) #Read in the csv files #dataDictionary <- read.csv('dataDictionary.csv') #Data Dictionary ProspectiveCustomers <- read.csv('ProspectiveCustomers.csv') #New Customer Data #Supplemental Information CurrentCustomerMktgResults <- read.csv('training/CurrentCustomerMktgResults.csv') householdAxiomData <- read.csv('training/householdAxiomData.csv') householdCreditData <- read.csv('training/householdCreditData.csv') householdVehicleData <- read.csv('training/householdVehicleData.csv') #Prediction Set ProspectiveList <- ProspectiveCustomers %>% left_join(householdAxiomData, by = "HHuniqueID") %>% left_join(householdCreditData, by = "HHuniqueID") %>% left_join(householdVehicleData, by = "HHuniqueID") #Combine the Customer Base previousMarketingResults <- CurrentCustomerMktgResults %>% left_join(householdAxiomData, by = "HHuniqueID") %>% left_join(householdCreditData, by = "HHuniqueID") %>% left_join(householdVehicleData, by = "HHuniqueID") previousMarketingResults$Y_AccetpedOffer <- as.factor(previousMarketingResults$Y_AccetpedOffer) ####### ##EDA## ####### #29 Variables (including dependant variable) #"dataID" and "HHuniqueID" are NOT useful for prediction (internal IDs) #"CallStart" and "CallEnd" are NOT available in the Prospective Customer file #We can use 24 dependant variables #Communication - No correlation? 50/50 split for both cell vs telephone table(previousMarketingResults$Communication,previousMarketingResults$Y_AccetpedOffer) #LastContactDay - Certain days have higher probability of success? table(previousMarketingResults$LastContactDay,previousMarketingResults$Y_AccetpedOffer) #LastContactMonth - Certain months have higher activity table(previousMarketingResults$LastContactMonth,previousMarketingResults$Y_AccetpedOffer) #NoOfContacts - Negative correlation? table(previousMarketingResults$NoOfContacts,previousMarketingResults$Y_AccetpedOffer) #DaysPassed - Mostly blank, not useful? table(previousMarketingResults$DaysPassed,previousMarketingResults$Y_AccetpedOffer) #PrevAttempts - Negative correlation? table(previousMarketingResults$PrevAttempts,previousMarketingResults$Y_AccetpedOffer) #Outcome - Positive correlation table(previousMarketingResults$Outcome,previousMarketingResults$Y_AccetpedOffer) #headOfhouseholdGender - Similar results based on gender table(previousMarketingResults$headOfhouseholdGender,previousMarketingResults$Y_AccetpedOffer) #annualDonations - Hard to see from this point of view... Bucketing by $100s would be better table(as.numeric(gsub("\\$", "", previousMarketingResults$annualDonations)),previousMarketingResults$Y_AccetpedOffer) #EstRace - Some races more inclined to accept a loan - but fairly sparse in general and same with the Prospective Data table(previousMarketingResults$EstRace,previousMarketingResults$Y_AccetpedOffer) #PetsPurchases - No Correlation (roughly the same) table(previousMarketingResults$PetsPurchases,previousMarketingResults$Y_AccetpedOffer) #DigitalHabits_5_AlwaysOn - Slight negative correlation 42% -> 39% as always on increases table(previousMarketingResults$DigitalHabits_5_AlwaysOn,previousMarketingResults$Y_AccetpedOffer) #AffluencePurchases - No Correlation table(previousMarketingResults$AffluencePurchases,previousMarketingResults$Y_AccetpedOffer) #Age - Bell Curve? Some ages do seem to play a higher correlation table(previousMarketingResults$Age,previousMarketingResults$Y_AccetpedOffer) #Job - Some occupations are higher than others table(previousMarketingResults$Job,previousMarketingResults$Y_AccetpedOffer) #Marital - Married people more often take loans table(previousMarketingResults$Marital,previousMarketingResults$Y_AccetpedOffer) #Education - Tertiary more 50/50 table(previousMarketingResults$Education,previousMarketingResults$Y_AccetpedOffer) #DefaultOnRecord - Defaulted far less likely to take loans table(previousMarketingResults$DefaultOnRecord,previousMarketingResults$Y_AccetpedOffer) #RecentBalance - Hard to tell from this point of view table(previousMarketingResults$RecentBalance,previousMarketingResults$Y_AccetpedOffer) #HHInsurance - Strong impact table(previousMarketingResults$HHInsurance,previousMarketingResults$Y_AccetpedOffer) #CarLoan - Strong Impact table(previousMarketingResults$CarLoan,previousMarketingResults$Y_AccetpedOffer) #carMake - Some models are more common than others table(previousMarketingResults$carMake,previousMarketingResults$Y_AccetpedOffer) #carModel - Similar to above, but less cases per event... table(previousMarketingResults$carModel,previousMarketingResults$Y_AccetpedOffer) #carYr - Similar to the above table(previousMarketingResults$carYr,previousMarketingResults$Y_AccetpedOffer) #With the EDA above, I would like to remove a few variables from consideration: # 1) Communication 2) DaysPassed 3) headOfhouseholdGender 4) PetsPurchases 5) AffluencePurchases ############ ##Analysis## ############ #Define Variables for vtreat informativeVars <- c("LastContactDay", "LastContactMonth", "NoOfContacts", "PrevAttempts", "Outcome", "annualDonations","EstRace", "DigitalHabits_5_AlwaysOn", "Age", "Job", "Marital", "Education", "DefaultOnRecord", "RecentBalance", "HHInsurance", "CarLoan", "carMake", "carModel", "carYr") y1Target <- "Y_AccetpedOffer" y1Success <- 1 #Apply vtreat plan <- designTreatmentsC(previousMarketingResults, informativeVars, y1Target, y1Success) treatedData <- prepare(plan, previousMarketingResults) #Create Training and Test Datasets set.seed(1234) splitPercent <- round(nrow(treatedData) %*% .8) totalRecords <- 1:nrow(treatedData) idx <- sample(totalRecords, splitPercent) trainDat <- treatedData[idx,] testDat <- treatedData[-idx,] #Create a decision tree fit <- train(Y_AccetpedOffer ~. , #formula based data = trainDat, #data in #caret does "recursive partitioning (trees) method = "rpart", #Define a range for the CP to test tuneGrid = data.frame(cp = c(0.1, 0.01, 0.05, 0.07)), #ie don't split if there are less than 1 record left and only do a split if there are at least 2+ records control = rpart.control(minsplit = 1, minbucket = 2)) sum(complete.cases(trainDat)) plot(fit) # Plot a pruned tree prp(fit$finalModel, extra = 1) # Make some predictions on the training set trainCaret<-predict(fit, trainDat) confusionMatrix(trainCaret, trainDat$Y_AccetpedOffer) # Make some predictions on the test set, the Accuracy is 74.5% testCaret<-predict(fit,testDat) confusionMatrix(testCaret,testDat$Y_AccetpedOffer) # Save the model pth<-'carDecisionTree.rds' saveRDS(fit, pth) #Communication + #LastContactDay + #LastContactMonth + #NoOfContacts + #DaysPassed + #PrevAttempts + #Outcome + #headOfhouseholdGender + #annualDonations + #EstRace + #Maybe remove? #PetsPurchases + #DigitalHabits_5_AlwaysOn + #Maybe remove? #AffluencePurchases + #Age + #Job + #Marital + #Education + #DefaultOnRecord + #RecentBalance + #HHInsurance + #CarLoan + #carMake + #carModel + #carYr ############################# ##Evaluate Prospective List## ############################# treatedTrain <- trainDat treatedTest <- testDat treatedNew <- prepare(plan, ProspectiveList) #Create a 10 fold approach and aggregate the result of each "fold" partition crtl <- trainControl(method = "cv", number = 10, verboseIter = TRUE) finalFit <- train(as.factor(Y_AccetpedOffer) ~ ., data = treatedTrain, method="rpart", cp = 0.01, trControl = crtl) finalFit # We can use a cutoff value of 0.75 to determine who is likely to accept originalProbs <- predict(finalFit, treatedTest, type = 'prob') cutoffProbs <- ifelse(originalProbs[,2]>=0.75,1,0) table(cutoffProbs, treatedTest$Y_AccetpedOffer) #Final Accuracy with a Decision Tree is 68.75% Accuracy(treatedTest$Y_AccetpedOffer, cutoffProbs) # Analyze Prospective Customers newProbs <- predict(finalFit, treatedNew, type = 'prob') head(newProbs) table(ifelse(newProbs[,2]>=0.75,1,0)) # Organize data scoredProspects <- data.frame(id = 1:nrow(treatedNew), risk = newProbs[,1], successProb = newProbs[,2], HHuniqueID = ProspectiveList$HHuniqueID) # Sort by highest probability and examine scoredProspects<-scoredProspects[order(scoredProspects$successProb,decreasing = TRUE),] head(scoredProspects, 100)
#:# libraries library(digest) library(mlr) library(OpenML) library(farff) #:# config set.seed(1) #:# data dataset <- getOMLDataSet(data.name = "analcatdata_supreme") head(dataset$data) #:# preprocessing head(dataset$data) #:# model task = makeRegrTask(id = "task", data = dataset$data, target = "Log_exposure") lrn = makeLearner("regr.svm", par.vals = list(kernel = "polynomial")) #:# hash #:# 51b8e2f48c66ac820cada52aa54d1483 hash <- digest(list(task, lrn)) hash #:# audit cv <- makeResampleDesc("CV", iters = 5) r <- mlr::resample(lrn, task, cv, measures = list(mse, rmse, mae, rsq)) ACC <- r$aggr ACC #:# session info sink(paste0("sessionInfo.txt")) sessionInfo() sink()
/models/openml_analcatdata_supreme/regression_Log_exposure/51b8e2f48c66ac820cada52aa54d1483/code.R
no_license
lukaszbrzozowski/CaseStudies2019S
R
false
false
681
r
#:# libraries library(digest) library(mlr) library(OpenML) library(farff) #:# config set.seed(1) #:# data dataset <- getOMLDataSet(data.name = "analcatdata_supreme") head(dataset$data) #:# preprocessing head(dataset$data) #:# model task = makeRegrTask(id = "task", data = dataset$data, target = "Log_exposure") lrn = makeLearner("regr.svm", par.vals = list(kernel = "polynomial")) #:# hash #:# 51b8e2f48c66ac820cada52aa54d1483 hash <- digest(list(task, lrn)) hash #:# audit cv <- makeResampleDesc("CV", iters = 5) r <- mlr::resample(lrn, task, cv, measures = list(mse, rmse, mae, rsq)) ACC <- r$aggr ACC #:# session info sink(paste0("sessionInfo.txt")) sessionInfo() sink()
\name{bear.JAGS} \alias{bear.JAGS} \title{ analysis of the Ft. Drum black bear data using JAGS } \description{ Function to analyze of the Ft. Drum black bear data with a range of possible covariate models using JAGS } \usage{ bear.JAGS(model=c('SCR0', 'SCR0exp', 'SCRt','SCRB','SCRb', 'SCRsex', 'SCRh'), n.chains, n.adapt, n.iter) } \details{ bear.JAGS allows you to run a spatial null model (SCR0), the null model with a negative exponential detection function (SCR0exp), time as a factor on detection (SCRt), a global and a local trap response model (SCRB and SCRb, respectively), a model with sex specific detection and movement (SCRsex), and a heterogeneity model with a logit-normal mixture on detection (SCRh). Model results are displayed and discussed in Ch9 of Royle et al. 2014. Spatial capture Recapture. } \value{ JAGS model output (for details, see the rjags manual, under coda.samples()) } \author{ Rahel Sollmann, Beth Gardner } \seealso{ %% ~~objects to See Also as \code{\link{secr.bear}}, ~~~ } \examples{ ##runs SCR model with global behavioral trap response on the Ft Drum bear data with 3 chains, 500 adaptive iterations an 2000 iterations out<-bear.JAGS(model='SCRB', n.chains=3, n.adapt=500, n.iter=2000) ##look at summary output summary(out) ## returns: Iterations = 501:2500 Thinning interval = 1 Number of chains = 3 Sample size per chain = 2000 1. Empirical mean and standard deviation for each variable, plus standard error of the mean: Mean SD Naive SE Time-series SE D 0.1907 0.01863 0.0002405 0.001370 N 578.3960 56.49120 0.7292982 4.155007 alpha0 -2.8001 0.23204 0.0029956 0.013962 alpha2 0.8887 0.23009 0.0029704 0.012137 psi 0.8886 0.08766 0.0011317 0.006407 sigma 1.9985 0.12876 0.0016622 0.006311 2. Quantiles for each variable: 2.5% 25% 50% 75% 97.5% D 0.1467 0.1781 0.1952 0.2061 0.2137 N 445.0000 540.0000 592.0000 625.0000 648.0000 alpha0 -3.2728 -2.9526 -2.7945 -2.6427 -2.3526 alpha2 0.4491 0.7264 0.8867 1.0441 1.3512 psi 0.6820 0.8300 0.9101 0.9600 0.9960 sigma 1.7654 1.9101 1.9918 2.0767 2.2753 } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ JAGS } \keyword{ covariate modeling }% __ONLY ONE__ keyword per line
/Rpackage/scrbook/man/bear.JAGS.rd
no_license
jaroyle/scrbook
R
false
false
2,397
rd
\name{bear.JAGS} \alias{bear.JAGS} \title{ analysis of the Ft. Drum black bear data using JAGS } \description{ Function to analyze of the Ft. Drum black bear data with a range of possible covariate models using JAGS } \usage{ bear.JAGS(model=c('SCR0', 'SCR0exp', 'SCRt','SCRB','SCRb', 'SCRsex', 'SCRh'), n.chains, n.adapt, n.iter) } \details{ bear.JAGS allows you to run a spatial null model (SCR0), the null model with a negative exponential detection function (SCR0exp), time as a factor on detection (SCRt), a global and a local trap response model (SCRB and SCRb, respectively), a model with sex specific detection and movement (SCRsex), and a heterogeneity model with a logit-normal mixture on detection (SCRh). Model results are displayed and discussed in Ch9 of Royle et al. 2014. Spatial capture Recapture. } \value{ JAGS model output (for details, see the rjags manual, under coda.samples()) } \author{ Rahel Sollmann, Beth Gardner } \seealso{ %% ~~objects to See Also as \code{\link{secr.bear}}, ~~~ } \examples{ ##runs SCR model with global behavioral trap response on the Ft Drum bear data with 3 chains, 500 adaptive iterations an 2000 iterations out<-bear.JAGS(model='SCRB', n.chains=3, n.adapt=500, n.iter=2000) ##look at summary output summary(out) ## returns: Iterations = 501:2500 Thinning interval = 1 Number of chains = 3 Sample size per chain = 2000 1. Empirical mean and standard deviation for each variable, plus standard error of the mean: Mean SD Naive SE Time-series SE D 0.1907 0.01863 0.0002405 0.001370 N 578.3960 56.49120 0.7292982 4.155007 alpha0 -2.8001 0.23204 0.0029956 0.013962 alpha2 0.8887 0.23009 0.0029704 0.012137 psi 0.8886 0.08766 0.0011317 0.006407 sigma 1.9985 0.12876 0.0016622 0.006311 2. Quantiles for each variable: 2.5% 25% 50% 75% 97.5% D 0.1467 0.1781 0.1952 0.2061 0.2137 N 445.0000 540.0000 592.0000 625.0000 648.0000 alpha0 -3.2728 -2.9526 -2.7945 -2.6427 -2.3526 alpha2 0.4491 0.7264 0.8867 1.0441 1.3512 psi 0.6820 0.8300 0.9101 0.9600 0.9960 sigma 1.7654 1.9101 1.9918 2.0767 2.2753 } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ JAGS } \keyword{ covariate modeling }% __ONLY ONE__ keyword per line
# Load tidyverse package ibrary(tidyverse) #Download files from website download.file("http://fmichonneau.github.io/2017-11-03-gwu/gapminder.csv", "data/gapminder.csv") gapminder <- read_csv("data/gapminder.csv") #Calculate the average life expectancy by continent # (save in a variable called life_exp_continent) life_exp_continent <- gapminder %>% group_by(continent) %>% summarize ( avg_lifeExp = mean(lifeExp) ) life_exp_continent # Calculate the life expectancy by year in Canada life_exp_canada <- gapminder %>% filter(country == "Canada") %>% select(country, year, lifeExp) life_exp_canada # Get the mean gdp per continent for the year 1972 avg_gdp <- gapminder %>% filter(year == 1972) %>% group_by(continent) %>% summarize ( mean_gdp = mean(gdpPercap) ) avg_gdp
/Script.R
no_license
jessica-o/gwu-gapminder
R
false
false
824
r
# Load tidyverse package ibrary(tidyverse) #Download files from website download.file("http://fmichonneau.github.io/2017-11-03-gwu/gapminder.csv", "data/gapminder.csv") gapminder <- read_csv("data/gapminder.csv") #Calculate the average life expectancy by continent # (save in a variable called life_exp_continent) life_exp_continent <- gapminder %>% group_by(continent) %>% summarize ( avg_lifeExp = mean(lifeExp) ) life_exp_continent # Calculate the life expectancy by year in Canada life_exp_canada <- gapminder %>% filter(country == "Canada") %>% select(country, year, lifeExp) life_exp_canada # Get the mean gdp per continent for the year 1972 avg_gdp <- gapminder %>% filter(year == 1972) %>% group_by(continent) %>% summarize ( mean_gdp = mean(gdpPercap) ) avg_gdp
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/general.R \name{distance_to_earth} \alias{distance_to_earth} \title{Distance to Earth with planetary aberration correction (effect of light-time and Earth's motion)} \usage{ distance_to_earth(jd, celestial_body) } \arguments{ \item{jd}{Julian day} \item{celestial_body}{celestial_body name as string: mercury, venus, mars, jupyter, saturn, moon, sun...} } \value{ distance to Earth } \description{ Distance to Earth with planetary aberration correction (effect of light-time and Earth's motion) } \examples{ distance_to_earth(julian_day(13.19,11,2028),"venus") }
/man/distance_to_earth.Rd
no_license
Susarro/arqastwb
R
false
true
643
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/general.R \name{distance_to_earth} \alias{distance_to_earth} \title{Distance to Earth with planetary aberration correction (effect of light-time and Earth's motion)} \usage{ distance_to_earth(jd, celestial_body) } \arguments{ \item{jd}{Julian day} \item{celestial_body}{celestial_body name as string: mercury, venus, mars, jupyter, saturn, moon, sun...} } \value{ distance to Earth } \description{ Distance to Earth with planetary aberration correction (effect of light-time and Earth's motion) } \examples{ distance_to_earth(julian_day(13.19,11,2028),"venus") }
source("global.R") for (nm in list.files("modules", pattern = "[.][Rr]$", recursive = TRUE)) { source(file.path("modules", nm)) } # ---------------------------------------------------------------------- # shinyUI( ui = bs4DashPage( old_school = FALSE, sidebar_collapsed = FALSE, controlbar_collapsed = FALSE, title = "UTAS - Initiative Tracking", # ---------------------------------------------------------------------- # navbar = bs4DashNavbar( skin = "light", status = "danger", border = T, sidebarIcon = "bars", controlbarIcon = "th", fixed = F, elevation = 5, opacity = 1, leftUi = tagList( uiOutput("firstButton") , uiOutput("secondButton") , uiOutput("thirdButton") , uiOutput("fourthButton") #, uiOutput("loadMarker") )), # ---------------------------------------------------------------------- # sidebar = bs4DashSidebar( skin = "light", status = "danger", title = "UTAS - Initiative Tracker", brandColor = "danger", url = "http://127.0.0.1:5276/", #url = verbatimTextOutput("loadMarker"), #src = "www/utas-logo-int.png", elevation = 5, opacity = 1, uiOutput("sideTilte"), bs4SidebarMenu( id = "leftBar", uiOutput("left_side_nav_buttons")) ), # ---------------------------------------------------------------------- # controlbar = bs4DashControlbar(disable =T), # ---------------------------------------------------------------------- # body = bs4DashBody( tags$head(tags$link(rel = "stylesheet", type = "text/css", href = "base.css")) , uiOutput("body") ) # ---------------------------------------------------------------------- # # ---------------------------------------------------------------------- # )# end fluidPage )# end shinyUI
/ui.R
permissive
linusmcm/in_track
R
false
false
2,260
r
source("global.R") for (nm in list.files("modules", pattern = "[.][Rr]$", recursive = TRUE)) { source(file.path("modules", nm)) } # ---------------------------------------------------------------------- # shinyUI( ui = bs4DashPage( old_school = FALSE, sidebar_collapsed = FALSE, controlbar_collapsed = FALSE, title = "UTAS - Initiative Tracking", # ---------------------------------------------------------------------- # navbar = bs4DashNavbar( skin = "light", status = "danger", border = T, sidebarIcon = "bars", controlbarIcon = "th", fixed = F, elevation = 5, opacity = 1, leftUi = tagList( uiOutput("firstButton") , uiOutput("secondButton") , uiOutput("thirdButton") , uiOutput("fourthButton") #, uiOutput("loadMarker") )), # ---------------------------------------------------------------------- # sidebar = bs4DashSidebar( skin = "light", status = "danger", title = "UTAS - Initiative Tracker", brandColor = "danger", url = "http://127.0.0.1:5276/", #url = verbatimTextOutput("loadMarker"), #src = "www/utas-logo-int.png", elevation = 5, opacity = 1, uiOutput("sideTilte"), bs4SidebarMenu( id = "leftBar", uiOutput("left_side_nav_buttons")) ), # ---------------------------------------------------------------------- # controlbar = bs4DashControlbar(disable =T), # ---------------------------------------------------------------------- # body = bs4DashBody( tags$head(tags$link(rel = "stylesheet", type = "text/css", href = "base.css")) , uiOutput("body") ) # ---------------------------------------------------------------------- # # ---------------------------------------------------------------------- # )# end fluidPage )# end shinyUI
## This is original code. Please refer to the README.md for the description test_x <- read.table("test/X_test.txt") train_x <- read.table("train/X_train.txt") test_sub <- read.table("test/subject_test.txt") train_sub <- read.table("train/subject_train.txt") test_y <- read.table("test/y_test.txt") train_y <- read.table("train/y_train.txt") features <- read.table("features.txt") colnames(test_x) <- features[,2] colnames(train_x) <- features[,2] test <- data.frame(Subject= test_sub[,1], Activity= test_y[,1], test_x[,grepl("*-(mean|std)",colnames(test_x))]) train <- data.frame(Subject= train_sub[,1], Activity= train_y[,1], train_x[,grepl("*-(mean|std)",colnames(train_x))]) dat <- rbind(test, train) act <- read.table("activity_labels.txt") dat <- merge(act,dat,by.x=1,by.y=2) colnames(dat)[2]="Activity" dat[1] <- NULL write.table(dat,file=file("tidy_data.txt","wb")) library(reshape2) dataMelt <- melt(dat, id=c("Activity","Subject"), measure.vars=colnames(dat)[3:81]) ActivityCast <- dcast(dataMelt, Activity ~ variable, mean) SubjectCast <- dcast(dataMelt, Subject ~ variable, mean)
/run_analysis.R
no_license
tgaurav10/tidy_data_set
R
false
false
1,092
r
## This is original code. Please refer to the README.md for the description test_x <- read.table("test/X_test.txt") train_x <- read.table("train/X_train.txt") test_sub <- read.table("test/subject_test.txt") train_sub <- read.table("train/subject_train.txt") test_y <- read.table("test/y_test.txt") train_y <- read.table("train/y_train.txt") features <- read.table("features.txt") colnames(test_x) <- features[,2] colnames(train_x) <- features[,2] test <- data.frame(Subject= test_sub[,1], Activity= test_y[,1], test_x[,grepl("*-(mean|std)",colnames(test_x))]) train <- data.frame(Subject= train_sub[,1], Activity= train_y[,1], train_x[,grepl("*-(mean|std)",colnames(train_x))]) dat <- rbind(test, train) act <- read.table("activity_labels.txt") dat <- merge(act,dat,by.x=1,by.y=2) colnames(dat)[2]="Activity" dat[1] <- NULL write.table(dat,file=file("tidy_data.txt","wb")) library(reshape2) dataMelt <- melt(dat, id=c("Activity","Subject"), measure.vars=colnames(dat)[3:81]) ActivityCast <- dcast(dataMelt, Activity ~ variable, mean) SubjectCast <- dcast(dataMelt, Subject ~ variable, mean)
#'@title Gets all supported conferences (current and historical) #' #'@description Gets all supported conferences (current and historical) #' #'@examples #' #'@export get_conferences <- function(){ rawConferences <- get_CFB_json_from_url('conferences') conferences <- data.frame(ConferenceId = rawConferences$id, ConferenceName = rawConferences$name, ConferenceFullName = rawConferences$short_name, ConferenceAbbr = rawConferences$abbreviation, stringsAsFactors = FALSE) return(conferences) }
/R/get_conferences.R
no_license
zmalosh/CollegeFootballDataR
R
false
false
533
r
#'@title Gets all supported conferences (current and historical) #' #'@description Gets all supported conferences (current and historical) #' #'@examples #' #'@export get_conferences <- function(){ rawConferences <- get_CFB_json_from_url('conferences') conferences <- data.frame(ConferenceId = rawConferences$id, ConferenceName = rawConferences$name, ConferenceFullName = rawConferences$short_name, ConferenceAbbr = rawConferences$abbreviation, stringsAsFactors = FALSE) return(conferences) }
add_three,-function(a,b,c){ return(a+b+c) }
/add_three.R
no_license
gsingsing/chem160module10
R
false
false
44
r
add_three,-function(a,b,c){ return(a+b+c) }
% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/expected_points_build.R \name{expected_points_build} \alias{expected_points_build} \title{Builds an Expected Points Model} \usage{ expected_points_build(plays, drives) } \arguments{ \item{plays}{the "play.csv" data frame for the years to use to build the model} \item{drives}{the "drive.csv" data frame} } \value{ a named vector where the names are the yardlines on the field and the values are the estimated point values associated with that spot. } \description{ Takes in play by play data and drive info to estimate the value of each spot on the field. The model is built using a B-spline regression model predicting the number of points scored on the drives based on the current field position. } \examples{ plays <- readin("play", 2014) drives <- readin("drive", 2014) epa_values <- expected_points_build(plays, drives) \dontrun{ggplot2::qplot(x = as.numeric(names(epa_values)), y = epa_values, xlab = "Distance From End Zone", ylab = "Expected Points", geom = "line", main = "Expected Points Model Results")} }
/man/expected_points_build.Rd
permissive
mattmills49/MELLS
R
false
false
1,105
rd
% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/expected_points_build.R \name{expected_points_build} \alias{expected_points_build} \title{Builds an Expected Points Model} \usage{ expected_points_build(plays, drives) } \arguments{ \item{plays}{the "play.csv" data frame for the years to use to build the model} \item{drives}{the "drive.csv" data frame} } \value{ a named vector where the names are the yardlines on the field and the values are the estimated point values associated with that spot. } \description{ Takes in play by play data and drive info to estimate the value of each spot on the field. The model is built using a B-spline regression model predicting the number of points scored on the drives based on the current field position. } \examples{ plays <- readin("play", 2014) drives <- readin("drive", 2014) epa_values <- expected_points_build(plays, drives) \dontrun{ggplot2::qplot(x = as.numeric(names(epa_values)), y = epa_values, xlab = "Distance From End Zone", ylab = "Expected Points", geom = "line", main = "Expected Points Model Results")} }
## ----header,echo=FALSE,results='hide'------------------------------------ library("knitr") opts_chunk$set(fig.width = 5.25, fig.height = 3.75, cache=FALSE) ## ----dsamp--------------------------------------------------------------- library("ggplot2") library("ggthemes") p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() + ggtitle("Cars") p2 <- ggplot(mtcars, aes(x = wt, y = mpg, colour = factor(gear))) + geom_point() + ggtitle("Cars") p3 <- p2 + facet_wrap(~ am) ## ----tufte-rangeframe---------------------------------------------------- p + geom_rangeframe() + theme_tufte() + scale_x_continuous(breaks = extended_range_breaks()(mtcars$wt)) + scale_y_continuous(breaks = extended_range_breaks()(mtcars$mpg)) ## ----tufteboxplot-------------------------------------------------------- p4 <- ggplot(mtcars, aes(factor(cyl), mpg)) p4 + theme_tufte(ticks=FALSE) + geom_tufteboxplot() ## ----tufteboxplot2------------------------------------------------------- p4 + theme_tufte(ticks=FALSE) + geom_tufteboxplot(median.type = "line") ## ----tufteboxplot3------------------------------------------------------- p4 + theme_tufte(ticks=FALSE) + geom_tufteboxplot(median.type = "line", whisker.type = 'point', hoffset = 0) ## ----tufteboxplot4------------------------------------------------------- p4 + theme_tufte(ticks=FALSE) + geom_tufteboxplot(median.type = "line", whisker.type = 'line', hoffset = 0, width = 3) ## ----economist----------------------------------------------------------- p2 + theme_economist() + scale_colour_economist() ## ----solarized-light----------------------------------------------------- p2 + theme_solarized() + scale_colour_solarized("blue") ## ----solarized-dark------------------------------------------------------ p2 + theme_solarized(light = FALSE) + scale_colour_solarized("red") ## ----solarized-alt------------------------------------------------------- p2 + theme_solarized_2(light = FALSE) + scale_colour_solarized("blue") ## ----stata--------------------------------------------------------------- p2 + theme_stata() + scale_colour_stata() ## ----excel1-------------------------------------------------------------- p2 + theme_excel() + scale_colour_excel() ## ----excel2-------------------------------------------------------------- ggplot(diamonds, aes(x = clarity, fill = cut)) + geom_bar() + scale_fill_excel() + theme_excel() ## ----igray--------------------------------------------------------------- p2 + theme_igray() ## ----fivethirtyeight----------------------------------------------------- p2 + geom_smooth(method = "lm", se = FALSE) + scale_color_fivethirtyeight("cyl") + theme_fivethirtyeight() ## ----tableau------------------------------------------------------------- p2 + theme_igray() + scale_colour_tableau() ## ----tableau-colorbind10------------------------------------------------- p2 + theme_igray() + scale_colour_tableau("colorblind10") ## ----few----------------------------------------------------------------- p2 + theme_few() + scale_colour_few() ## ----wsj----------------------------------------------------------------- p2 + theme_wsj() + scale_colour_wsj("colors6", "") ## ------------------------------------------------------------------------ p2 + theme_base() ## ------------------------------------------------------------------------ par(fg = "blue", bg = "gray", col.lab = "red", font.lab = 3) p2 + theme_par() ## ----gdocs--------------------------------------------------------------- p2 + theme_gdocs() + scale_color_gdocs() ## ----calc---------------------------------------------------------------- p2 + theme_calc() + scale_color_calc() ## ----pander-scatterplot-------------------------------------------------- p2 + theme_pander() + scale_colour_pander() ## ----pander-barplot------------------------------------------------------ ggplot(diamonds, aes(x = clarity, fill = cut)) + geom_bar() + theme_pander() + scale_fill_pander() ## ----hc-default---------------------------------------------------------- p2 + theme_hc() + scale_colour_hc() ## ----hc-darkunica-------------------------------------------------------- p2 + theme_hc(bgcolor = "darkunica") + scale_colour_hc("darkunica") ## ----dtemp--------------------------------------------------------------- dtemp <- data.frame(months = factor(rep(substr(month.name,1,3), 4), levels = substr(month.name,1,3)), city = rep(c("Tokyo", "New York", "Berlin", "London"), each = 12), temp = c(7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6, -0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5, -0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0, 3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8)) ## ----hc-default-line----------------------------------------------------- ggplot(dtemp, aes(x = months, y = temp, group = city, color = city)) + geom_line() + geom_point(size = 1.1) + ggtitle("Monthly Average Temperature") + theme_hc() + scale_colour_hc() ## ----hc-darkunica-line--------------------------------------------------- ggplot(dtemp, aes(x = months, y = temp, group = city, color = city)) + geom_line() + geom_point(size = 1.1) + ggtitle("Monthly Average Temperature") + theme_hc(bgcolor = "darkunica") + scale_fill_hc("darkunica") ## ----map,message=FALSE--------------------------------------------------- library("maps") us <- fortify(map_data("state"), region = "region") ggplot() + geom_map(data = us, map = us, aes(x = long, y = lat, map_id = region, group = group), fill = "white", color = "black", size = 0.25) + coord_map("albers", lat0 = 39, lat1 = 45) + theme_map()
/ggthemes/inst/doc/ggthemes.R
no_license
ingted/R-Examples
R
false
false
5,912
r
## ----header,echo=FALSE,results='hide'------------------------------------ library("knitr") opts_chunk$set(fig.width = 5.25, fig.height = 3.75, cache=FALSE) ## ----dsamp--------------------------------------------------------------- library("ggplot2") library("ggthemes") p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() + ggtitle("Cars") p2 <- ggplot(mtcars, aes(x = wt, y = mpg, colour = factor(gear))) + geom_point() + ggtitle("Cars") p3 <- p2 + facet_wrap(~ am) ## ----tufte-rangeframe---------------------------------------------------- p + geom_rangeframe() + theme_tufte() + scale_x_continuous(breaks = extended_range_breaks()(mtcars$wt)) + scale_y_continuous(breaks = extended_range_breaks()(mtcars$mpg)) ## ----tufteboxplot-------------------------------------------------------- p4 <- ggplot(mtcars, aes(factor(cyl), mpg)) p4 + theme_tufte(ticks=FALSE) + geom_tufteboxplot() ## ----tufteboxplot2------------------------------------------------------- p4 + theme_tufte(ticks=FALSE) + geom_tufteboxplot(median.type = "line") ## ----tufteboxplot3------------------------------------------------------- p4 + theme_tufte(ticks=FALSE) + geom_tufteboxplot(median.type = "line", whisker.type = 'point', hoffset = 0) ## ----tufteboxplot4------------------------------------------------------- p4 + theme_tufte(ticks=FALSE) + geom_tufteboxplot(median.type = "line", whisker.type = 'line', hoffset = 0, width = 3) ## ----economist----------------------------------------------------------- p2 + theme_economist() + scale_colour_economist() ## ----solarized-light----------------------------------------------------- p2 + theme_solarized() + scale_colour_solarized("blue") ## ----solarized-dark------------------------------------------------------ p2 + theme_solarized(light = FALSE) + scale_colour_solarized("red") ## ----solarized-alt------------------------------------------------------- p2 + theme_solarized_2(light = FALSE) + scale_colour_solarized("blue") ## ----stata--------------------------------------------------------------- p2 + theme_stata() + scale_colour_stata() ## ----excel1-------------------------------------------------------------- p2 + theme_excel() + scale_colour_excel() ## ----excel2-------------------------------------------------------------- ggplot(diamonds, aes(x = clarity, fill = cut)) + geom_bar() + scale_fill_excel() + theme_excel() ## ----igray--------------------------------------------------------------- p2 + theme_igray() ## ----fivethirtyeight----------------------------------------------------- p2 + geom_smooth(method = "lm", se = FALSE) + scale_color_fivethirtyeight("cyl") + theme_fivethirtyeight() ## ----tableau------------------------------------------------------------- p2 + theme_igray() + scale_colour_tableau() ## ----tableau-colorbind10------------------------------------------------- p2 + theme_igray() + scale_colour_tableau("colorblind10") ## ----few----------------------------------------------------------------- p2 + theme_few() + scale_colour_few() ## ----wsj----------------------------------------------------------------- p2 + theme_wsj() + scale_colour_wsj("colors6", "") ## ------------------------------------------------------------------------ p2 + theme_base() ## ------------------------------------------------------------------------ par(fg = "blue", bg = "gray", col.lab = "red", font.lab = 3) p2 + theme_par() ## ----gdocs--------------------------------------------------------------- p2 + theme_gdocs() + scale_color_gdocs() ## ----calc---------------------------------------------------------------- p2 + theme_calc() + scale_color_calc() ## ----pander-scatterplot-------------------------------------------------- p2 + theme_pander() + scale_colour_pander() ## ----pander-barplot------------------------------------------------------ ggplot(diamonds, aes(x = clarity, fill = cut)) + geom_bar() + theme_pander() + scale_fill_pander() ## ----hc-default---------------------------------------------------------- p2 + theme_hc() + scale_colour_hc() ## ----hc-darkunica-------------------------------------------------------- p2 + theme_hc(bgcolor = "darkunica") + scale_colour_hc("darkunica") ## ----dtemp--------------------------------------------------------------- dtemp <- data.frame(months = factor(rep(substr(month.name,1,3), 4), levels = substr(month.name,1,3)), city = rep(c("Tokyo", "New York", "Berlin", "London"), each = 12), temp = c(7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6, -0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5, -0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0, 3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8)) ## ----hc-default-line----------------------------------------------------- ggplot(dtemp, aes(x = months, y = temp, group = city, color = city)) + geom_line() + geom_point(size = 1.1) + ggtitle("Monthly Average Temperature") + theme_hc() + scale_colour_hc() ## ----hc-darkunica-line--------------------------------------------------- ggplot(dtemp, aes(x = months, y = temp, group = city, color = city)) + geom_line() + geom_point(size = 1.1) + ggtitle("Monthly Average Temperature") + theme_hc(bgcolor = "darkunica") + scale_fill_hc("darkunica") ## ----map,message=FALSE--------------------------------------------------- library("maps") us <- fortify(map_data("state"), region = "region") ggplot() + geom_map(data = us, map = us, aes(x = long, y = lat, map_id = region, group = group), fill = "white", color = "black", size = 0.25) + coord_map("albers", lat0 = 39, lat1 = 45) + theme_map()
#' Total pathway probability sample #' #' @param osNode Decision tree object. #' @param pathString Route from root to leaf. Node names separated by /. #' @param N.mc Number of samples. #' #' @return Vector of probabilities. #' @export #' #' @examples #' total_pathway_prob_sample <- function(osNode, pathString, N.mc = 2){ path_prob <- vector(mode = "double", length = N.mc) for (i in seq_len(N.mc)) { # sample p if (all(c("pmin", "pmax") %in% osNode$fields)) { rprob <- osNode$Get(sampleNodeUniform) osNode$Set(p = rprob) } all_path_probs <- calc_pathway_probs(osNode, FUN = "product") osNode$Set(path_probs = all_path_probs) path_prob[i] <- osNode$Get("path_probs", filterFun = function(x) x$pathString == pathString) } path_prob }
/R/total_pathway_prob_sample.R
no_license
n8thangreen/LTBIhospitalScreenACE
R
false
false
893
r
#' Total pathway probability sample #' #' @param osNode Decision tree object. #' @param pathString Route from root to leaf. Node names separated by /. #' @param N.mc Number of samples. #' #' @return Vector of probabilities. #' @export #' #' @examples #' total_pathway_prob_sample <- function(osNode, pathString, N.mc = 2){ path_prob <- vector(mode = "double", length = N.mc) for (i in seq_len(N.mc)) { # sample p if (all(c("pmin", "pmax") %in% osNode$fields)) { rprob <- osNode$Get(sampleNodeUniform) osNode$Set(p = rprob) } all_path_probs <- calc_pathway_probs(osNode, FUN = "product") osNode$Set(path_probs = all_path_probs) path_prob[i] <- osNode$Get("path_probs", filterFun = function(x) x$pathString == pathString) } path_prob }
suppressPackageStartupMessages(library(Seurat)) suppressPackageStartupMessages(library(stringr)) suppressPackageStartupMessages(library(argparse)) suppressPackageStartupMessages(library(dplyr)) suppressPackageStartupMessages(library(reshape2)) print("*** Configure Parameters ***") parser <- ArgumentParser(description='Process some tasks') parser$add_argument("--seurat", type="character", default="", help="the dataset to be used") parser$add_argument("--outdir", type="character", default="", help="the dataset to be used") args<-parser$parse_args() print("### Loading dataset") seurat<-readRDS(args$seurat) Idents(seurat)<-seurat$new_umap_clusters markers <- FindAllMarkers(seurat, only.pos = FALSE, test.use = "wilcox", min.pct = 0.2, pseudocount.use = 1 ) if(!dir.exists(args$outdir)){ dir.create(args$outdir,recursive=TRUE) } topn=markers%>%group_by(cluster)%>%top_n(70,wt=avg_logFC) saveRDS(markers,file.path(args$outdir,"new_markers.rds")) write.table(topn,file.path(args$outdir,"new_top70_markers.csv"),quote=F,row.names=F,sep=",")
/FindMarkers.R
no_license
RyanYip-Kat/CovID2019
R
false
false
1,257
r
suppressPackageStartupMessages(library(Seurat)) suppressPackageStartupMessages(library(stringr)) suppressPackageStartupMessages(library(argparse)) suppressPackageStartupMessages(library(dplyr)) suppressPackageStartupMessages(library(reshape2)) print("*** Configure Parameters ***") parser <- ArgumentParser(description='Process some tasks') parser$add_argument("--seurat", type="character", default="", help="the dataset to be used") parser$add_argument("--outdir", type="character", default="", help="the dataset to be used") args<-parser$parse_args() print("### Loading dataset") seurat<-readRDS(args$seurat) Idents(seurat)<-seurat$new_umap_clusters markers <- FindAllMarkers(seurat, only.pos = FALSE, test.use = "wilcox", min.pct = 0.2, pseudocount.use = 1 ) if(!dir.exists(args$outdir)){ dir.create(args$outdir,recursive=TRUE) } topn=markers%>%group_by(cluster)%>%top_n(70,wt=avg_logFC) saveRDS(markers,file.path(args$outdir,"new_markers.rds")) write.table(topn,file.path(args$outdir,"new_top70_markers.csv"),quote=F,row.names=F,sep=",")
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/methods-Trajectory.R \name{createTrajectoryMetaData} \alias{createTrajectoryMetaData} \title{Generate meta-data associated with this trajectory} \usage{ createTrajectoryMetaData(trajectory) } \arguments{ \item{trajectory}{Trajectory on which to operate} } \value{ metaData dataframe with meta-data } \description{ Creates a categorical variable mapping cells to edges and numeric variables for their position along edges }
/man/createTrajectoryMetaData.Rd
permissive
YosefLab/VISION
R
false
true
501
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/methods-Trajectory.R \name{createTrajectoryMetaData} \alias{createTrajectoryMetaData} \title{Generate meta-data associated with this trajectory} \usage{ createTrajectoryMetaData(trajectory) } \arguments{ \item{trajectory}{Trajectory on which to operate} } \value{ metaData dataframe with meta-data } \description{ Creates a categorical variable mapping cells to edges and numeric variables for their position along edges }
% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/dAktorzyGwiazdy.R \name{dAktorzyGwiazdy} \alias{dAktorzyGwiazdy} \title{Liczenie odleglosci dla aktorow bedacych gwiazdami} \usage{ dAktorzyGwiazdy(IDFilm1, IDFilm2, sciezkaDoBazy) } \arguments{ \item{IDFilm1}{- id pierwszego filmu} \item{IDFilm2}{- id drugiego filmu} \item{sciezkaDoBazy}{- sciezka do bazy filmow} } \value{ Funkcja zwraca wartosc liczbowa opisujaca odleglosc miedzy filmami. } \description{ Funkcja \code{dAktorzyGwiazdy} liczy odleglosc miedzy aktorami bedacymi gwiazdami z dwoch filmow z bazy } \details{ Funkcja wyciaga ID dwoch filmow z bazy. Jesli ktorys z nich nie ma aktorow bedacych gwiazdami odleglosc miedzy nimi wynosi 0.8, jesli tak nie jest miara jest liczona zgodnie z funkcja PorownajWektory. } \examples{ #Nie wywoluj jesli nie masz takiej bazy dAktorzyGwiazdy(4000,2461,"BazaFilmow.sql") dAktorzyGwiazdy(23456,2461,"BazaFilmow.sql") } \author{ Krzysztof Rudas }
/WyszynskaRudasIMDB/man/dAktorzyGwiazdy.Rd
no_license
Wyszynskak/Projekty
R
false
false
987
rd
% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/dAktorzyGwiazdy.R \name{dAktorzyGwiazdy} \alias{dAktorzyGwiazdy} \title{Liczenie odleglosci dla aktorow bedacych gwiazdami} \usage{ dAktorzyGwiazdy(IDFilm1, IDFilm2, sciezkaDoBazy) } \arguments{ \item{IDFilm1}{- id pierwszego filmu} \item{IDFilm2}{- id drugiego filmu} \item{sciezkaDoBazy}{- sciezka do bazy filmow} } \value{ Funkcja zwraca wartosc liczbowa opisujaca odleglosc miedzy filmami. } \description{ Funkcja \code{dAktorzyGwiazdy} liczy odleglosc miedzy aktorami bedacymi gwiazdami z dwoch filmow z bazy } \details{ Funkcja wyciaga ID dwoch filmow z bazy. Jesli ktorys z nich nie ma aktorow bedacych gwiazdami odleglosc miedzy nimi wynosi 0.8, jesli tak nie jest miara jest liczona zgodnie z funkcja PorownajWektory. } \examples{ #Nie wywoluj jesli nie masz takiej bazy dAktorzyGwiazdy(4000,2461,"BazaFilmow.sql") dAktorzyGwiazdy(23456,2461,"BazaFilmow.sql") } \author{ Krzysztof Rudas }
## Copyright 2013 Data Tactics Corporation ## ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the License. ## You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the License for the specific language governing permissions and ## limitations under the License. .accumEnv <- new.env() .onLoad <- function(libname,pkgname){ }
/package/R/zzz.R
permissive
DataTacticsCorp/raccumulo
R
false
false
668
r
## Copyright 2013 Data Tactics Corporation ## ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the License. ## You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the License for the specific language governing permissions and ## limitations under the License. .accumEnv <- new.env() .onLoad <- function(libname,pkgname){ }
## makeCacheMatrix: This function creates a special "matrix" object ## that can cache its inverse. # * setMatrix set the value of a matrix # * getMatrix get the value of a matrix # * cacheInverse get the cahced value (inverse of the matrix) # * getInverse get the cahced value (inverse of the matrix) makeCacheMatrix <- function(x = numeric()) { cache <- NULL setMatrix <- function(y) { x <<- y cahce <- NULL } getMatrix <- function(){ x } cacheInverse <- function(inverse) { cache <<- inverse } getInverse <- function() { cache } list(setMatrix = setMatrix, getMatrix = getMatrix, cacheInverse = cacheInverse, getInverse = getInverse) } ## cacheSolve: This function computes the inverse of the special ## "matrix" returned by makeCacheMatrix above. ## If the inverse has already been calculated (and the matrix has not changed), ## then the cachesolve should retrieve the inverse from the cache. cacheSolve <- function(x, ...) { inverse.cache <- x$getInverse() if(!is.null(inverse.cache)) { message("getting cached data") return(inverse.cache) } data.matrix <- x$getMatrix() inverse.cache <- solve(data.matrix) x$cacheInverse(inverse.cache) inverse.cache }
/makecachematrix.R
no_license
antoniom72/Programming-Assignment-2-Lexical-Scoping
R
false
false
1,254
r
## makeCacheMatrix: This function creates a special "matrix" object ## that can cache its inverse. # * setMatrix set the value of a matrix # * getMatrix get the value of a matrix # * cacheInverse get the cahced value (inverse of the matrix) # * getInverse get the cahced value (inverse of the matrix) makeCacheMatrix <- function(x = numeric()) { cache <- NULL setMatrix <- function(y) { x <<- y cahce <- NULL } getMatrix <- function(){ x } cacheInverse <- function(inverse) { cache <<- inverse } getInverse <- function() { cache } list(setMatrix = setMatrix, getMatrix = getMatrix, cacheInverse = cacheInverse, getInverse = getInverse) } ## cacheSolve: This function computes the inverse of the special ## "matrix" returned by makeCacheMatrix above. ## If the inverse has already been calculated (and the matrix has not changed), ## then the cachesolve should retrieve the inverse from the cache. cacheSolve <- function(x, ...) { inverse.cache <- x$getInverse() if(!is.null(inverse.cache)) { message("getting cached data") return(inverse.cache) } data.matrix <- x$getMatrix() inverse.cache <- solve(data.matrix) x$cacheInverse(inverse.cache) inverse.cache }
#!/usr/bin/env Rscript # Crear un data frame que contenga nombre edad y sexo nombre<-c("Melani","Adrian","Raymundo") edad<-c(22,21,21) sexo<-c("F","M","M") dataframePersona<-data.frame(nombre,edad,sexo) print(dataframePersona)
/ejemplos/dataframes.r
no_license
AdrianPardo99/r-course-1
R
false
false
230
r
#!/usr/bin/env Rscript # Crear un data frame que contenga nombre edad y sexo nombre<-c("Melani","Adrian","Raymundo") edad<-c(22,21,21) sexo<-c("F","M","M") dataframePersona<-data.frame(nombre,edad,sexo) print(dataframePersona)
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/RN_search_beta_by_E.R \name{RN_search_beta_by_E} \alias{RN_search_beta_by_E} \title{Search for beta} \usage{ RN_search_beta_by_E( E_max, min_half_life_seconds = NULL, max_half_life_seconds = NULL ) } \arguments{ \item{E_max}{maximum energy in MeV, default = 10} \item{min_half_life_seconds}{minimum half-life in seconds. Use multiplier as needed, e.g. 3 * 3600 for 3 hours. Default = NULL,} \item{max_half_life_seconds}{maximum half-life. See min_half_life_seconds.} } \value{ search results in order of half-life. Recommend assigning results to a viewable object, such as 'search_results' } \description{ Search for beta emission based on maximum energy and half-life. } \examples{ # Max beta at least 2 MeV search_results <- RN_search_beta_by_E(2) # Max beta at least 2 MeV and half-life between 1 s and 1 h search_results <- RN_search_beta_by_E(2, 1, 3600) # Max beta at least 1 MeV and half-life between 1 d and 2 d search_results <- RN_search_beta_by_E(1, 3600 * 24, 2 * 3600 * 24) } \seealso{ Other radionuclides: \code{\link{RN_Spec_Act}()}, \code{\link{RN_bin_screen_phot}()}, \code{\link{RN_index_screen}()}, \code{\link{RN_info}()}, \code{\link{RN_plot_search_results}()}, \code{\link{RN_plot_spectrum}()}, \code{\link{RN_save_spectrum}()}, \code{\link{RN_search_alpha_by_E}()}, \code{\link{RN_search_phot_by_E}()} } \concept{radionuclides}
/man/RN_search_beta_by_E.Rd
no_license
cran/radsafer
R
false
true
1,488
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/RN_search_beta_by_E.R \name{RN_search_beta_by_E} \alias{RN_search_beta_by_E} \title{Search for beta} \usage{ RN_search_beta_by_E( E_max, min_half_life_seconds = NULL, max_half_life_seconds = NULL ) } \arguments{ \item{E_max}{maximum energy in MeV, default = 10} \item{min_half_life_seconds}{minimum half-life in seconds. Use multiplier as needed, e.g. 3 * 3600 for 3 hours. Default = NULL,} \item{max_half_life_seconds}{maximum half-life. See min_half_life_seconds.} } \value{ search results in order of half-life. Recommend assigning results to a viewable object, such as 'search_results' } \description{ Search for beta emission based on maximum energy and half-life. } \examples{ # Max beta at least 2 MeV search_results <- RN_search_beta_by_E(2) # Max beta at least 2 MeV and half-life between 1 s and 1 h search_results <- RN_search_beta_by_E(2, 1, 3600) # Max beta at least 1 MeV and half-life between 1 d and 2 d search_results <- RN_search_beta_by_E(1, 3600 * 24, 2 * 3600 * 24) } \seealso{ Other radionuclides: \code{\link{RN_Spec_Act}()}, \code{\link{RN_bin_screen_phot}()}, \code{\link{RN_index_screen}()}, \code{\link{RN_info}()}, \code{\link{RN_plot_search_results}()}, \code{\link{RN_plot_spectrum}()}, \code{\link{RN_save_spectrum}()}, \code{\link{RN_search_alpha_by_E}()}, \code{\link{RN_search_phot_by_E}()} } \concept{radionuclides}
# 2018_technical_activity-data-calcs.R # Calculation of activity data projections for the 2018 Technical Reconsideration Proposal RIA ###### # Activity data projections datasets include the following information: # mp -- the model plant type being tracked # attrs -- attributes on mp # location -- state or region where the facility is located (for state program applicability) # vintage -- when the plant was established/created/modified for regulatory applicability purposes # year -- the projection year # fac_count -- count of facilities #### Activity data projection options ---------------- base_year <- 2014 year_range <- 2014:2025 #### READ IN summarized 2014 Completions Data from DrillingInfo wells analysis ------------- by_welltype_loc <- read_csv("data/comps-base-year.csv") %>% rename(by_pct = percent, by_count = n) %>% # translate into simpler mp-like names mutate(mp = case_when( WELLTYPE6 == "gas (GOR > 100,000)" ~ "gaswellcomp", WELLTYPE6 == "oil w/ assoc gas" ~ "oilassocgaswellcomp", WELLTYPE6 == "black oils (GOR < 300)" ~ "oilwellcomp", WELLTYPE6 == "low production -- gas" ~ "lp_gaswellcomp", WELLTYPE6 == "low production -- oil w/assoc gas" ~ "lp_oilassocgaswellcomp", WELLTYPE6 == "low production -- oil only" ~ "lp_oilwellcomp" )) %>% rename(location = LOCATION) %>% mutate(attrs = NA_character_) %>% select(mp, attrs, location, by_count) #### READ In AEO 2018 Drilling Series ----------- aeo18_drilling <- read_excel("data-raw/aeo2018_tab14_ongsupply.xlsx") %>% filter(`...1` == "OGS000:la_TotalLower48W") %>% select(`2014`:`2025`) %>% gather(YEAR, wells_drilled) %>% mutate(YEAR = as.numeric(YEAR), wells_drilled = as.numeric(wells_drilled) * 1000) %>% # AEO reports in thousands rename(aeo_wells_drilled = wells_drilled, year = YEAR) #### Projection of Completions --------------- ad_comps_proj <- expand(by_welltype_loc, nesting(mp, location), crossing(year_range)) %>% rename(year = year_range) %>% # Join AEO and 2014 completions data to the above structure arrange(year, mp, location) %>% left_join(by_welltype_loc, by = c("mp", "location")) %>% left_join(aeo18_drilling, by = "year") %>% # Multiply change in AEO wells drilled by 2014 completions information group_by(mp, location) %>% mutate(count = aeo_wells_drilled / (aeo_wells_drilled[year==2014] %ifempty% NA_real_) * by_count) %>% ungroup() %>% # Delete unnecessary columns used in prior calculation select(-by_count, -aeo_wells_drilled) %>% mutate(attrs = case_when( location == "AK-NS" ~ "AK-NS", TRUE ~ NA_character_)) %>% # Normalize column structure select(mp, attrs, location, year, count) ##### Calculate wellsites projection from completions projection ------------ wellsites_proj <- expand(ad_comps_proj, nesting(mp, attrs, location, year), crossing(year_index = year_range)) %>% rename(vintage = year) %>% left_join(ad_comps_proj, by = c("mp", "attrs", "location", "vintage"="year")) %>% filter(year_index >= vintage) %>% # change e.g., oilassocgascomp --> oilassocgaswellsite mutate(mp = str_replace(mp, "comp", "site")) %>% # Divide completions by 2 to get wellsites (average 2 wells per site) mutate(fac_count = count / 2) %>% rename(year = year_index) %>% select(mp, attrs, location, vintage, year, fac_count) %>% mutate(vintage = as.numeric(vintage)) ####### Calculate compressor station projections -------------- GHGI_stations <- tibble( mp = c("gbstation", "transstation", "storstation"), attrs = rep(NA_character_, 3), location = rep(NA_character_, 3), count_per_year = c(212, 36, 2) ) new_stations_proj <- expand(GHGI_stations, nesting(mp, attrs, location), crossing(vintage = year_range)) %>% left_join(GHGI_stations, by = c("mp", "attrs", "location")) %>% rename(fac_count = count_per_year) stations_proj <- expand(new_stations_proj, nesting(mp, attrs, location), crossing(vintage = year_range, year = year_range)) %>% left_join(new_stations_proj, by = c("mp", "attrs", "location", "vintage")) %>% filter(year >= vintage) ###### Calculate Additional activity data projections ---------- ###### Closed Vent Systems projections ---------------- # CVS design / infeasibility certification counts are estimated by a combination of estimates of storage tanks (which are driven by well counts that change each year) and a fixed addition of CVS associated with pumps and compressors. base_cvs <- tibble( mp = c("cert"), attrs = c(NA_character_), location = c(NA_character_), base_year_count = 18616, # storage tanks ~ wells, change per year fixed_count = 3794 + 8 + 18 # from 2018 GHGI; 87.5% of pumps, 10% of total recip compressors, 100% of wet seal centrifugal compressors ~ fixed per year ) new_cvs_proj <- expand(base_cvs, nesting(mp, attrs, location), crossing(vintage = year_range)) %>% # Join base year count and AEO drilling projection left_join(base_cvs, by = c("mp", "attrs", "location")) %>% left_join(aeo18_drilling, by = c("vintage"="year")) %>% mutate(year = vintage) %>% # Multiply change in AEO wells drilled by 2014 completions information group_by(mp, attrs, location) %>% mutate(fac_count = aeo_wells_drilled / (aeo_wells_drilled[vintage==2014] %ifempty% NA_real_) * base_year_count + fixed_count) %>% ungroup() %>% # Delete unnecessary columns used in prior calculation select(-base_year_count, -aeo_wells_drilled) %>% select(mp, attrs, location, vintage, year, fac_count) cvs_proj <- expand(new_cvs_proj, nesting(mp, attrs, location), crossing(vintage = year_range, year = year_range)) %>% left_join(select(new_cvs_proj, -year), by = c("mp", "attrs", "location", "vintage")) %>% filter(year >= vintage) ##### Drivers Summary ----- drivers_summary <- bind_rows( aeo18_drilling %>% mutate(mp = "AEO18 wells drilled") %>% rename(count = aeo_wells_drilled), ad_comps_proj %>% group_by(year) %>% summarize(count = sum(count)) %>% mutate(mp = "D.I. completions"), new_stations_proj %>% select(mp, year=vintage, count = fac_count), new_cvs_proj %>% select(mp, year, count=fac_count) ) ##### Assemble overall activity data projection of relevant facilities ---------------- ad_proj_2018_tech <- bind_rows(wellsites_proj, stations_proj, new_cvs_proj) rm(ad_comps_proj, aeo18_drilling, wellsites_proj, GHGI_stations, new_stations_proj, stations_proj, base_csv, new_cvs_proj, cvs_proj )
/scripts/2018_technical_activity-data-calcs.R
permissive
USEPA/ONG-NSPS-OOOOa-Technical-Reconsideration-Analysis
R
false
false
6,870
r
# 2018_technical_activity-data-calcs.R # Calculation of activity data projections for the 2018 Technical Reconsideration Proposal RIA ###### # Activity data projections datasets include the following information: # mp -- the model plant type being tracked # attrs -- attributes on mp # location -- state or region where the facility is located (for state program applicability) # vintage -- when the plant was established/created/modified for regulatory applicability purposes # year -- the projection year # fac_count -- count of facilities #### Activity data projection options ---------------- base_year <- 2014 year_range <- 2014:2025 #### READ IN summarized 2014 Completions Data from DrillingInfo wells analysis ------------- by_welltype_loc <- read_csv("data/comps-base-year.csv") %>% rename(by_pct = percent, by_count = n) %>% # translate into simpler mp-like names mutate(mp = case_when( WELLTYPE6 == "gas (GOR > 100,000)" ~ "gaswellcomp", WELLTYPE6 == "oil w/ assoc gas" ~ "oilassocgaswellcomp", WELLTYPE6 == "black oils (GOR < 300)" ~ "oilwellcomp", WELLTYPE6 == "low production -- gas" ~ "lp_gaswellcomp", WELLTYPE6 == "low production -- oil w/assoc gas" ~ "lp_oilassocgaswellcomp", WELLTYPE6 == "low production -- oil only" ~ "lp_oilwellcomp" )) %>% rename(location = LOCATION) %>% mutate(attrs = NA_character_) %>% select(mp, attrs, location, by_count) #### READ In AEO 2018 Drilling Series ----------- aeo18_drilling <- read_excel("data-raw/aeo2018_tab14_ongsupply.xlsx") %>% filter(`...1` == "OGS000:la_TotalLower48W") %>% select(`2014`:`2025`) %>% gather(YEAR, wells_drilled) %>% mutate(YEAR = as.numeric(YEAR), wells_drilled = as.numeric(wells_drilled) * 1000) %>% # AEO reports in thousands rename(aeo_wells_drilled = wells_drilled, year = YEAR) #### Projection of Completions --------------- ad_comps_proj <- expand(by_welltype_loc, nesting(mp, location), crossing(year_range)) %>% rename(year = year_range) %>% # Join AEO and 2014 completions data to the above structure arrange(year, mp, location) %>% left_join(by_welltype_loc, by = c("mp", "location")) %>% left_join(aeo18_drilling, by = "year") %>% # Multiply change in AEO wells drilled by 2014 completions information group_by(mp, location) %>% mutate(count = aeo_wells_drilled / (aeo_wells_drilled[year==2014] %ifempty% NA_real_) * by_count) %>% ungroup() %>% # Delete unnecessary columns used in prior calculation select(-by_count, -aeo_wells_drilled) %>% mutate(attrs = case_when( location == "AK-NS" ~ "AK-NS", TRUE ~ NA_character_)) %>% # Normalize column structure select(mp, attrs, location, year, count) ##### Calculate wellsites projection from completions projection ------------ wellsites_proj <- expand(ad_comps_proj, nesting(mp, attrs, location, year), crossing(year_index = year_range)) %>% rename(vintage = year) %>% left_join(ad_comps_proj, by = c("mp", "attrs", "location", "vintage"="year")) %>% filter(year_index >= vintage) %>% # change e.g., oilassocgascomp --> oilassocgaswellsite mutate(mp = str_replace(mp, "comp", "site")) %>% # Divide completions by 2 to get wellsites (average 2 wells per site) mutate(fac_count = count / 2) %>% rename(year = year_index) %>% select(mp, attrs, location, vintage, year, fac_count) %>% mutate(vintage = as.numeric(vintage)) ####### Calculate compressor station projections -------------- GHGI_stations <- tibble( mp = c("gbstation", "transstation", "storstation"), attrs = rep(NA_character_, 3), location = rep(NA_character_, 3), count_per_year = c(212, 36, 2) ) new_stations_proj <- expand(GHGI_stations, nesting(mp, attrs, location), crossing(vintage = year_range)) %>% left_join(GHGI_stations, by = c("mp", "attrs", "location")) %>% rename(fac_count = count_per_year) stations_proj <- expand(new_stations_proj, nesting(mp, attrs, location), crossing(vintage = year_range, year = year_range)) %>% left_join(new_stations_proj, by = c("mp", "attrs", "location", "vintage")) %>% filter(year >= vintage) ###### Calculate Additional activity data projections ---------- ###### Closed Vent Systems projections ---------------- # CVS design / infeasibility certification counts are estimated by a combination of estimates of storage tanks (which are driven by well counts that change each year) and a fixed addition of CVS associated with pumps and compressors. base_cvs <- tibble( mp = c("cert"), attrs = c(NA_character_), location = c(NA_character_), base_year_count = 18616, # storage tanks ~ wells, change per year fixed_count = 3794 + 8 + 18 # from 2018 GHGI; 87.5% of pumps, 10% of total recip compressors, 100% of wet seal centrifugal compressors ~ fixed per year ) new_cvs_proj <- expand(base_cvs, nesting(mp, attrs, location), crossing(vintage = year_range)) %>% # Join base year count and AEO drilling projection left_join(base_cvs, by = c("mp", "attrs", "location")) %>% left_join(aeo18_drilling, by = c("vintage"="year")) %>% mutate(year = vintage) %>% # Multiply change in AEO wells drilled by 2014 completions information group_by(mp, attrs, location) %>% mutate(fac_count = aeo_wells_drilled / (aeo_wells_drilled[vintage==2014] %ifempty% NA_real_) * base_year_count + fixed_count) %>% ungroup() %>% # Delete unnecessary columns used in prior calculation select(-base_year_count, -aeo_wells_drilled) %>% select(mp, attrs, location, vintage, year, fac_count) cvs_proj <- expand(new_cvs_proj, nesting(mp, attrs, location), crossing(vintage = year_range, year = year_range)) %>% left_join(select(new_cvs_proj, -year), by = c("mp", "attrs", "location", "vintage")) %>% filter(year >= vintage) ##### Drivers Summary ----- drivers_summary <- bind_rows( aeo18_drilling %>% mutate(mp = "AEO18 wells drilled") %>% rename(count = aeo_wells_drilled), ad_comps_proj %>% group_by(year) %>% summarize(count = sum(count)) %>% mutate(mp = "D.I. completions"), new_stations_proj %>% select(mp, year=vintage, count = fac_count), new_cvs_proj %>% select(mp, year, count=fac_count) ) ##### Assemble overall activity data projection of relevant facilities ---------------- ad_proj_2018_tech <- bind_rows(wellsites_proj, stations_proj, new_cvs_proj) rm(ad_comps_proj, aeo18_drilling, wellsites_proj, GHGI_stations, new_stations_proj, stations_proj, base_csv, new_cvs_proj, cvs_proj )
#' Mandelbrot convergence counts #' #' @param xlim,ylim The complex plane for which convergence counts #' should be calculated. #' @param resolution Number of bins along the real axis. The number #' of bins along the imaginary axis will be such #' that the aspect ratio is preserved. #' @param maxIter Maximum number of iterations per bin. #' @param tau A threshold; the radius when calling #' divergence (Mod(z) > tau). #' #' @return Returns an integer matrix of non-negative counts #' #' @author This \code{mandelbrot()} function was inspired by and #' adopted from similar GPL code of Martin Maechler (available #' from ftp://stat.ethz.ch/U/maechler/R/ on 2005-02-18 [sic!]). mandelbrot <- function(xlim=c(-2, 0.5), ylim=c(-1,1), resolution=400L, maxIter=200L, tau=2) { ## Validate arguments dx <- diff(xlim) dy <- diff(ylim) stopifnot(dx > 0, dy > 0) resolution <- as.integer(resolution) stopifnot(resolution > 0) maxIter <- as.integer(maxIter) stopifnot(maxIter > 0) ## The nx-by-ny bins nx <- resolution ny <- round((dy / dx) * resolution) ## Setup (x,y) bins x <- seq(from=xlim[1], to=xlim[2], length.out=nx) y <- seq(from=ylim[1], to=ylim[2], length.out=ny) ## By default, assume none of the elements will converge counts <- matrix(maxIter, nrow=ny, ncol=nx) dim <- dim(counts) ## But as a start, flag the to all be non-diverged nonDiverged <- rep(TRUE, times=nx*ny) idxOfNonDiverged <- seq_along(nonDiverged) ## Set of complex numbers to be investigated C <- outer(y, x, FUN=function(y,x) complex(real=x, imag=y)) ## SPEEDUP: The Mandelbrot sequence will only be calculated on the ## "remaining set" of complex numbers that yet hasn't diverged. sC <- C ## The Mandelbrot sequence of the "remaining" set Cr <- C ## The original complex number of the "remaining" set for (ii in seq_len(maxIter-1L)) { sC <- sC*sC + Cr ## Did any of the "remaining" points diverge? diverged <- (Mod(sC) > tau) if (any(diverged)) { ## Record at what iteration divergence occurred counts[idxOfNonDiverged[diverged]] <- ii ## Early stopping? keep <- which(!diverged) if (length(keep) == 0) break ## Drop from remain calculations idxOfNonDiverged <- idxOfNonDiverged[keep] nonDiverged[nonDiverged] <- !diverged ## Update the "remaining" set of complex numbers sC <- sC[keep] Cr <- Cr[keep] } } attr(counts, "params") <- list(xlim=xlim, ylim=ylim, nx=nx, ny=ny, maxIter=maxIter, resolution=resolution) counts } # mandelbrot() tiles <- function(n=getOption("R_FUTURE_DEMO_MANDELBROT_TILES", availableCores())) { if (n <= 4) { tiles <- c(2, 2) } else if (n <= 6) { tiles <- c(2, 3) } else if (n <= 9) { tiles <- c(3, 3) } else if (n <= 12) { tiles <- c(3, 4) } else if (n <= 16) { tiles <- c(4, 4) } else { tiles <- c(5, 5) } tiles } # tiles() library("future") library("listenv") library("graphics") ## Let's open an empty device already here if (interactive()) { dev.new(); plot.new() } n <- prod(tiles()) sizes <- 2 * 6^-seq(from=0,to=15,length.out=n) xs <- rep(0.28298899997142857, times=n) xs[1] <- xs[1] - 0.8 ys <- rep(-0.010, times=n) counts <- listenv() for (ii in seq_along(sizes)) { cat(sprintf("Mandelbrot tile #%d of %d ...\n", ii, length(sizes))) size <- sizes[ii] counts[[ii]] %<=% { cat(sprintf("Calculating tile #%d of %d ...\n", ii, length(sizes))) xlim <- xs[ii] + size/2 * c(-1,1) ylim <- ys[ii] + size/2 * c(-1,1) cat(sprintf(" xlim=c(%.16f,%.16f)\n", xlim[1], xlim[2])) cat(sprintf(" ylim=c(%.16f,%.16f)\n", ylim[1], ylim[2])) fit <- mandelbrot(xlim=xlim, ylim=ylim) cat(sprintf("Calculating tile #%d of %d ... done\n", ii, length(sizes))) fit } } ## Plot as each tile gets ready split.screen(rep(max(tiles()), times=2)) ## Square aspect ratio resolved <- logical(length(counts)) while (!all(resolved)) { for (ii in which(!resolved)) { if (!resolved(futureOf(counts[[ii]]))) next cat(sprintf("Plotting tile #%d of %d ...\n", ii, length(sizes))) screen(ii) opar <- par(mar=c(0,0,0,0)) img <- structure({ x <- counts[[ii]] maxIter <- attr(x, "params")$maxIter img <- hsv(h=x/maxIter, s=1, v=1) img[x == maxIter] <- "#000000" dim(img) <- dim(x) t(img) }, class="raster") plot(img) box(lwd=3) par(opar) resolved[ii] <- TRUE } # for (ii ...) ## Wait a bit before checking again if (!all(resolved)) Sys.sleep(1.0) } # while (...) close.screen() message("SUGGESTION: Try to rerun this demo after changing strategy for how futures are resolved, e.g. plan(lazy).\n")
/demo/mandelbrot.R
no_license
githubfun/future
R
false
false
4,784
r
#' Mandelbrot convergence counts #' #' @param xlim,ylim The complex plane for which convergence counts #' should be calculated. #' @param resolution Number of bins along the real axis. The number #' of bins along the imaginary axis will be such #' that the aspect ratio is preserved. #' @param maxIter Maximum number of iterations per bin. #' @param tau A threshold; the radius when calling #' divergence (Mod(z) > tau). #' #' @return Returns an integer matrix of non-negative counts #' #' @author This \code{mandelbrot()} function was inspired by and #' adopted from similar GPL code of Martin Maechler (available #' from ftp://stat.ethz.ch/U/maechler/R/ on 2005-02-18 [sic!]). mandelbrot <- function(xlim=c(-2, 0.5), ylim=c(-1,1), resolution=400L, maxIter=200L, tau=2) { ## Validate arguments dx <- diff(xlim) dy <- diff(ylim) stopifnot(dx > 0, dy > 0) resolution <- as.integer(resolution) stopifnot(resolution > 0) maxIter <- as.integer(maxIter) stopifnot(maxIter > 0) ## The nx-by-ny bins nx <- resolution ny <- round((dy / dx) * resolution) ## Setup (x,y) bins x <- seq(from=xlim[1], to=xlim[2], length.out=nx) y <- seq(from=ylim[1], to=ylim[2], length.out=ny) ## By default, assume none of the elements will converge counts <- matrix(maxIter, nrow=ny, ncol=nx) dim <- dim(counts) ## But as a start, flag the to all be non-diverged nonDiverged <- rep(TRUE, times=nx*ny) idxOfNonDiverged <- seq_along(nonDiverged) ## Set of complex numbers to be investigated C <- outer(y, x, FUN=function(y,x) complex(real=x, imag=y)) ## SPEEDUP: The Mandelbrot sequence will only be calculated on the ## "remaining set" of complex numbers that yet hasn't diverged. sC <- C ## The Mandelbrot sequence of the "remaining" set Cr <- C ## The original complex number of the "remaining" set for (ii in seq_len(maxIter-1L)) { sC <- sC*sC + Cr ## Did any of the "remaining" points diverge? diverged <- (Mod(sC) > tau) if (any(diverged)) { ## Record at what iteration divergence occurred counts[idxOfNonDiverged[diverged]] <- ii ## Early stopping? keep <- which(!diverged) if (length(keep) == 0) break ## Drop from remain calculations idxOfNonDiverged <- idxOfNonDiverged[keep] nonDiverged[nonDiverged] <- !diverged ## Update the "remaining" set of complex numbers sC <- sC[keep] Cr <- Cr[keep] } } attr(counts, "params") <- list(xlim=xlim, ylim=ylim, nx=nx, ny=ny, maxIter=maxIter, resolution=resolution) counts } # mandelbrot() tiles <- function(n=getOption("R_FUTURE_DEMO_MANDELBROT_TILES", availableCores())) { if (n <= 4) { tiles <- c(2, 2) } else if (n <= 6) { tiles <- c(2, 3) } else if (n <= 9) { tiles <- c(3, 3) } else if (n <= 12) { tiles <- c(3, 4) } else if (n <= 16) { tiles <- c(4, 4) } else { tiles <- c(5, 5) } tiles } # tiles() library("future") library("listenv") library("graphics") ## Let's open an empty device already here if (interactive()) { dev.new(); plot.new() } n <- prod(tiles()) sizes <- 2 * 6^-seq(from=0,to=15,length.out=n) xs <- rep(0.28298899997142857, times=n) xs[1] <- xs[1] - 0.8 ys <- rep(-0.010, times=n) counts <- listenv() for (ii in seq_along(sizes)) { cat(sprintf("Mandelbrot tile #%d of %d ...\n", ii, length(sizes))) size <- sizes[ii] counts[[ii]] %<=% { cat(sprintf("Calculating tile #%d of %d ...\n", ii, length(sizes))) xlim <- xs[ii] + size/2 * c(-1,1) ylim <- ys[ii] + size/2 * c(-1,1) cat(sprintf(" xlim=c(%.16f,%.16f)\n", xlim[1], xlim[2])) cat(sprintf(" ylim=c(%.16f,%.16f)\n", ylim[1], ylim[2])) fit <- mandelbrot(xlim=xlim, ylim=ylim) cat(sprintf("Calculating tile #%d of %d ... done\n", ii, length(sizes))) fit } } ## Plot as each tile gets ready split.screen(rep(max(tiles()), times=2)) ## Square aspect ratio resolved <- logical(length(counts)) while (!all(resolved)) { for (ii in which(!resolved)) { if (!resolved(futureOf(counts[[ii]]))) next cat(sprintf("Plotting tile #%d of %d ...\n", ii, length(sizes))) screen(ii) opar <- par(mar=c(0,0,0,0)) img <- structure({ x <- counts[[ii]] maxIter <- attr(x, "params")$maxIter img <- hsv(h=x/maxIter, s=1, v=1) img[x == maxIter] <- "#000000" dim(img) <- dim(x) t(img) }, class="raster") plot(img) box(lwd=3) par(opar) resolved[ii] <- TRUE } # for (ii ...) ## Wait a bit before checking again if (!all(resolved)) Sys.sleep(1.0) } # while (...) close.screen() message("SUGGESTION: Try to rerun this demo after changing strategy for how futures are resolved, e.g. plan(lazy).\n")
data<-read.table('household_power_consumption.txt',sep=';',header=T) date <- as.Date(data$Date,format='%d/%m/%Y') num <- as.character(date) num <- as.numeric(strftime(strptime(num,'%Y-%m-%d'),'%Y%m%d')) startDate <- as.numeric(strftime(strptime('2007-02-01','%Y-%m-%d'),'%Y%m%d')) endDate <- as.numeric(strftime(strptime('2007-02-02','%Y-%m-%d'),'%Y%m%d')) thurs <- num==startDate fri <- num==endDate x<- data$Time[thurs] y<- data$Global_active_power[thurs] day1 <- data$Date[thurs] dateTime <- paste(day1,x) x2<- data$Time[fri] y2<- data$Global_active_power[fri] day2 <- data$Date[fri] dateTime2 <- paste(day2,x2) totalData <- c(dateTime,dateTime2) totalY <- c(as.numeric(as.character(y)),as.numeric(as.character(y2))) png(filename='plot2.png',width=480,height=480) plot(strptime(totalData,format='%d/%m/%Y %H:%M:%S'),totalY,type='l',xlab='',ylab='Global Active Power (kilowatts)') dev.off()
/plot2.r
no_license
adamkcarter/ExData_Plotting1
R
false
false
902
r
data<-read.table('household_power_consumption.txt',sep=';',header=T) date <- as.Date(data$Date,format='%d/%m/%Y') num <- as.character(date) num <- as.numeric(strftime(strptime(num,'%Y-%m-%d'),'%Y%m%d')) startDate <- as.numeric(strftime(strptime('2007-02-01','%Y-%m-%d'),'%Y%m%d')) endDate <- as.numeric(strftime(strptime('2007-02-02','%Y-%m-%d'),'%Y%m%d')) thurs <- num==startDate fri <- num==endDate x<- data$Time[thurs] y<- data$Global_active_power[thurs] day1 <- data$Date[thurs] dateTime <- paste(day1,x) x2<- data$Time[fri] y2<- data$Global_active_power[fri] day2 <- data$Date[fri] dateTime2 <- paste(day2,x2) totalData <- c(dateTime,dateTime2) totalY <- c(as.numeric(as.character(y)),as.numeric(as.character(y2))) png(filename='plot2.png',width=480,height=480) plot(strptime(totalData,format='%d/%m/%Y %H:%M:%S'),totalY,type='l',xlab='',ylab='Global Active Power (kilowatts)') dev.off()
# The experiment is to execute Bayesian Variable Selection for linear regression models using Gibbs sampling # on the Ozone35 data set referenced in "Casella, G. and Moreno, E. (2006)<DOI:10.1198/016214505000000646> Objective Bayesian variable selection. Journal of the American Statistical Association, 101(473). # https://www.stat.washington.edu/courses/stat527/s14/readings/CasellaMoreno_JASA_2006.pdf # The data set has 35 variables # References # https://www.stat.washington.edu/courses/stat527/s14/readings/CasellaMoreno_JASA_2006.pdf # http://www.snn.ru.nl/~bertk/machinelearning/2290777.pdf # https://cran.r-project.org/web/packages/BayesVarSel/BayesVarSel.pdf # https://rdrr.io/cran/BayesVarSel/man/Bvs.html # http://blog.uclm.es/gonzalogarciadonato/files/2016/11/articleJSS_v2.pdf-english-revised-by-Neil4.pdf # install required packages # install.packages("ridge") # install.packages("BayesVarSel") # install.packages("BVS") # install.packages("tidyverse") # install.packages("caret") # install.packages("leaps") # install.packages("eqs2lavaan") # Load required libraries library(ridge) library(BayesVarSel) library(BVS) library(tidyverse) library(caret) library(leaps) library(glmnet) library(corrplot) library(dplyr) library(RColorBrewer) library(datasets) library(eqs2lavaan) # --------------------------------------------------------------------------------- # # ------------------------ Second Experiment on Ozone35 Data ------------------------ # # --------------------------------------------------------------------------------- # # Load Hald Dataset data(Ozone35) set.seed(123) Ozone35_orig = Ozone35 split <- round(nrow(Ozone35_orig) * 0.80) Ozone35_train = Ozone35_orig[1:split,] Ozone35_test = Ozone35_orig[(split + 1):nrow(Ozone35_orig), ] nrow(Ozone35_orig) nrow(Ozone35_train) nrow(Ozone35_test) # correlation plot M <-cor(Ozone35_train) corrplot(M, type="upper", order="hclust", col=brewer.pal(n=8, name="RdYlBu")) #5-fold cross-validated model: train.control <- trainControl(method = "cv", number = 5) Ozone35CV <- train(y ~ ., data=Ozone35_train, method="lm", trControl=train.control) finModel <- Ozone35CV$finalModel finModel predicts <- predict(finModel, Ozone35_test) summary(finModel) Ozone35_testcv = Ozone35_test Ozone35_testcv$fitted_values = predicts mean((Ozone35_testcv$y - Ozone35_testcv$fitted_values)^2) # 26.01848 # lasso regression x = model.matrix(y~., Ozone35_train) y = Ozone35_train$y set.seed(5678) lambda <- 10^seq(10, -2, length = 100) lasso.mod <- glmnet(x, y, alpha = 1, lambda = lambda) cv.out <- cv.glmnet(x, y, alpha = 1) plot(cv.out) bestlam <- cv.out$lambda.min bestlam #0.02236135 newx = model.matrix(y~., Ozone35_test) lasso.pred = predict(lasso.mod, s = bestlam, newx) mean((lasso.pred-Ozone35_test$y)^2) # 25.18038 lasso.coef = predict(lasso.mod, type = 'coefficients', s = bestlam) lasso.coef # Eliminates 13 Variables, 22 still remain # concole output #(Intercept) -2.175134e+01 #(Intercept) . #x4 . #x5 . #x6 . #x7 . #x8 1.110815e-03 #x9 1.625016e-02 #x10 . #x4.x4 7.547358e-07 #x4.x5 . #x4.x6 1.528497e-05 #x4.x7 . #x4.x8 . #x4.x9 . #x4.x10 . #x5.x5 -1.036284e-01 #x5.x6 . #x5.x7 -8.260029e-04 #x5.x8 . #x5.x9 1.327944e-02 #x5.x10 4.243334e-03 #x6.x6 -1.532618e-03 #x6.x7 3.122803e-03 #x6.x8 -2.340310e-05 #x6.x9 1.790178e-05 #x6.x10 6.912824e-05 #x7.x7 1.626493e-03 #x7.x8 -1.027678e-05 #x7.x9 -1.127902e-03 #x7.x10 -9.327268e-04 #x8.x8 . #x8.x9 2.172081e-06 #x8.x10 4.829100e-07 #x9.x9 -6.914419e-04 #x9.x10 -3.203076e-05 #x10.x10 4.012404e-05 # Using Gibbs Ozone35.GibbsBvs.fullmodel<- GibbsBvs(formula= y ~ ., data=Ozone35_train, prior.betas="gZellner", prior.models="Constant", n.iter=10000, init.model="Full", n.burnin=100, time.test = FALSE) summary(Ozone35.GibbsBvs.fullmodel) # Console Output #Inclusion Probabilities: # Incl.prob. HPM MPM #x4 0.1762 #x5 0.1581 #x6 0.2913 #x7 0.244 #x8 0.2192 #x9 0.236 #x10 0.32 * #x4.x4 0.1726 #x4.x5 0.1694 #x4.x6 0.3171 * #x4.x7 0.3398 * #x4.x8 0.234 #x4.x9 0.2545 #x4.x10 0.3535 #x5.x5 0.2386 #x5.x6 0.1423 #x5.x7 0.1639 #x5.x8 0.1394 #x5.x9 0.1959 #x5.x10 0.2037 #x6.x6 0.5369 * #x6.x7 0.5771 * #x6.x8 0.596 * * #x6.x9 0.1443 #x6.x10 0.135 #x7.x7 0.2443 #x7.x8 0.3684 #x7.x9 0.3711 #x7.x10 0.7776 * * #x8.x8 0.1298 #x8.x9 0.1792 #x8.x10 0.177 #x9.x9 0.5838 * #x9.x10 0.1118 #x10.x10 0.1565 #--- # Code: HPM stands for Highest posterior Probability Model and #MPM for Median Probability Model. #Results are estimates based on the visited models. # eliminitaes 30 variables, 5 remain # Reduced Model Ozone35.GibbsBvs.reducedmodel<- GibbsBvs(formula= y ~ x10+x4.x6+x4.x7+x6.x8+x7.x10, data=Ozone35_train, prior.betas="gZellner", prior.models="Constant", n.iter=10000, init.model="Full", n.burnin=100, time.test = FALSE) summary(Ozone35.GibbsBvs.reducedmodel) # Console Outout #Inclusion Probabilities: # Incl.prob. HPM MPM #x10 0.9941 * * #x4.x6 0.9938 * * #x4.x7 1 * * #x6.x8 0.999 * * #x7.x10 0.9979 * * # --- # Code: HPM stands for Highest posterior Probability Model and #MPM for Median Probability Model. #Results are estimates based on the visited models. # Linear regression with reduced coeff. lm.Ozone35.reducemodel = lm(y ~ x10+x4.x6+x4.x7+x6.x8+x7.x10, Ozone35_train) summary(lm.Ozone35.reducemodel) # Console Output # Residuals: # Min 1Q Median 3Q Max #-10.5613 -2.7565 -0.2178 2.7089 12.9488 # Estimate Std. Error t value Pr(>|t|) #(Intercept) -1.823e+01 3.155e+00 -5.778 4.92e-08 *** # x10 9.811e-02 2.343e-02 4.187 5.04e-05 *** # x4.x6 1.889e-05 4.690e-06 4.029 9.28e-05 *** # x4.x7 8.016e-05 8.555e-06 9.371 < 2e-16 *** # x6.x8 -1.894e-05 4.037e-06 -4.691 6.54e-06 *** # x7.x10 -1.949e-03 4.141e-04 -4.706 6.15e-06 *** # --- # Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 #Residual standard error: 4.247 on 136 degrees of freedom #Multiple R-squared: 0.7477, Adjusted R-squared: 0.7384 #F-statistic: 80.6 on 5 and 136 DF, p-value: < 2.2e-16 lm.Ozone35.reducemodel.predictions = predict(lm.Ozone35.reducemodel, Ozone35_test) lm.Ozone35.reducemodel.predictions mean((lm.Ozone35.reducemodel.predictions-Ozone35_test$y)^2) #18.58677
/MATH Paper GiibsVS Ozone35 Dataset.R
no_license
arjuna12009/Variable-selection-via-Gibbs-sampling
R
false
false
7,460
r
# The experiment is to execute Bayesian Variable Selection for linear regression models using Gibbs sampling # on the Ozone35 data set referenced in "Casella, G. and Moreno, E. (2006)<DOI:10.1198/016214505000000646> Objective Bayesian variable selection. Journal of the American Statistical Association, 101(473). # https://www.stat.washington.edu/courses/stat527/s14/readings/CasellaMoreno_JASA_2006.pdf # The data set has 35 variables # References # https://www.stat.washington.edu/courses/stat527/s14/readings/CasellaMoreno_JASA_2006.pdf # http://www.snn.ru.nl/~bertk/machinelearning/2290777.pdf # https://cran.r-project.org/web/packages/BayesVarSel/BayesVarSel.pdf # https://rdrr.io/cran/BayesVarSel/man/Bvs.html # http://blog.uclm.es/gonzalogarciadonato/files/2016/11/articleJSS_v2.pdf-english-revised-by-Neil4.pdf # install required packages # install.packages("ridge") # install.packages("BayesVarSel") # install.packages("BVS") # install.packages("tidyverse") # install.packages("caret") # install.packages("leaps") # install.packages("eqs2lavaan") # Load required libraries library(ridge) library(BayesVarSel) library(BVS) library(tidyverse) library(caret) library(leaps) library(glmnet) library(corrplot) library(dplyr) library(RColorBrewer) library(datasets) library(eqs2lavaan) # --------------------------------------------------------------------------------- # # ------------------------ Second Experiment on Ozone35 Data ------------------------ # # --------------------------------------------------------------------------------- # # Load Hald Dataset data(Ozone35) set.seed(123) Ozone35_orig = Ozone35 split <- round(nrow(Ozone35_orig) * 0.80) Ozone35_train = Ozone35_orig[1:split,] Ozone35_test = Ozone35_orig[(split + 1):nrow(Ozone35_orig), ] nrow(Ozone35_orig) nrow(Ozone35_train) nrow(Ozone35_test) # correlation plot M <-cor(Ozone35_train) corrplot(M, type="upper", order="hclust", col=brewer.pal(n=8, name="RdYlBu")) #5-fold cross-validated model: train.control <- trainControl(method = "cv", number = 5) Ozone35CV <- train(y ~ ., data=Ozone35_train, method="lm", trControl=train.control) finModel <- Ozone35CV$finalModel finModel predicts <- predict(finModel, Ozone35_test) summary(finModel) Ozone35_testcv = Ozone35_test Ozone35_testcv$fitted_values = predicts mean((Ozone35_testcv$y - Ozone35_testcv$fitted_values)^2) # 26.01848 # lasso regression x = model.matrix(y~., Ozone35_train) y = Ozone35_train$y set.seed(5678) lambda <- 10^seq(10, -2, length = 100) lasso.mod <- glmnet(x, y, alpha = 1, lambda = lambda) cv.out <- cv.glmnet(x, y, alpha = 1) plot(cv.out) bestlam <- cv.out$lambda.min bestlam #0.02236135 newx = model.matrix(y~., Ozone35_test) lasso.pred = predict(lasso.mod, s = bestlam, newx) mean((lasso.pred-Ozone35_test$y)^2) # 25.18038 lasso.coef = predict(lasso.mod, type = 'coefficients', s = bestlam) lasso.coef # Eliminates 13 Variables, 22 still remain # concole output #(Intercept) -2.175134e+01 #(Intercept) . #x4 . #x5 . #x6 . #x7 . #x8 1.110815e-03 #x9 1.625016e-02 #x10 . #x4.x4 7.547358e-07 #x4.x5 . #x4.x6 1.528497e-05 #x4.x7 . #x4.x8 . #x4.x9 . #x4.x10 . #x5.x5 -1.036284e-01 #x5.x6 . #x5.x7 -8.260029e-04 #x5.x8 . #x5.x9 1.327944e-02 #x5.x10 4.243334e-03 #x6.x6 -1.532618e-03 #x6.x7 3.122803e-03 #x6.x8 -2.340310e-05 #x6.x9 1.790178e-05 #x6.x10 6.912824e-05 #x7.x7 1.626493e-03 #x7.x8 -1.027678e-05 #x7.x9 -1.127902e-03 #x7.x10 -9.327268e-04 #x8.x8 . #x8.x9 2.172081e-06 #x8.x10 4.829100e-07 #x9.x9 -6.914419e-04 #x9.x10 -3.203076e-05 #x10.x10 4.012404e-05 # Using Gibbs Ozone35.GibbsBvs.fullmodel<- GibbsBvs(formula= y ~ ., data=Ozone35_train, prior.betas="gZellner", prior.models="Constant", n.iter=10000, init.model="Full", n.burnin=100, time.test = FALSE) summary(Ozone35.GibbsBvs.fullmodel) # Console Output #Inclusion Probabilities: # Incl.prob. HPM MPM #x4 0.1762 #x5 0.1581 #x6 0.2913 #x7 0.244 #x8 0.2192 #x9 0.236 #x10 0.32 * #x4.x4 0.1726 #x4.x5 0.1694 #x4.x6 0.3171 * #x4.x7 0.3398 * #x4.x8 0.234 #x4.x9 0.2545 #x4.x10 0.3535 #x5.x5 0.2386 #x5.x6 0.1423 #x5.x7 0.1639 #x5.x8 0.1394 #x5.x9 0.1959 #x5.x10 0.2037 #x6.x6 0.5369 * #x6.x7 0.5771 * #x6.x8 0.596 * * #x6.x9 0.1443 #x6.x10 0.135 #x7.x7 0.2443 #x7.x8 0.3684 #x7.x9 0.3711 #x7.x10 0.7776 * * #x8.x8 0.1298 #x8.x9 0.1792 #x8.x10 0.177 #x9.x9 0.5838 * #x9.x10 0.1118 #x10.x10 0.1565 #--- # Code: HPM stands for Highest posterior Probability Model and #MPM for Median Probability Model. #Results are estimates based on the visited models. # eliminitaes 30 variables, 5 remain # Reduced Model Ozone35.GibbsBvs.reducedmodel<- GibbsBvs(formula= y ~ x10+x4.x6+x4.x7+x6.x8+x7.x10, data=Ozone35_train, prior.betas="gZellner", prior.models="Constant", n.iter=10000, init.model="Full", n.burnin=100, time.test = FALSE) summary(Ozone35.GibbsBvs.reducedmodel) # Console Outout #Inclusion Probabilities: # Incl.prob. HPM MPM #x10 0.9941 * * #x4.x6 0.9938 * * #x4.x7 1 * * #x6.x8 0.999 * * #x7.x10 0.9979 * * # --- # Code: HPM stands for Highest posterior Probability Model and #MPM for Median Probability Model. #Results are estimates based on the visited models. # Linear regression with reduced coeff. lm.Ozone35.reducemodel = lm(y ~ x10+x4.x6+x4.x7+x6.x8+x7.x10, Ozone35_train) summary(lm.Ozone35.reducemodel) # Console Output # Residuals: # Min 1Q Median 3Q Max #-10.5613 -2.7565 -0.2178 2.7089 12.9488 # Estimate Std. Error t value Pr(>|t|) #(Intercept) -1.823e+01 3.155e+00 -5.778 4.92e-08 *** # x10 9.811e-02 2.343e-02 4.187 5.04e-05 *** # x4.x6 1.889e-05 4.690e-06 4.029 9.28e-05 *** # x4.x7 8.016e-05 8.555e-06 9.371 < 2e-16 *** # x6.x8 -1.894e-05 4.037e-06 -4.691 6.54e-06 *** # x7.x10 -1.949e-03 4.141e-04 -4.706 6.15e-06 *** # --- # Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 #Residual standard error: 4.247 on 136 degrees of freedom #Multiple R-squared: 0.7477, Adjusted R-squared: 0.7384 #F-statistic: 80.6 on 5 and 136 DF, p-value: < 2.2e-16 lm.Ozone35.reducemodel.predictions = predict(lm.Ozone35.reducemodel, Ozone35_test) lm.Ozone35.reducemodel.predictions mean((lm.Ozone35.reducemodel.predictions-Ozone35_test$y)^2) #18.58677
library(glmnet) mydata = read.table("../../../../TrainingSet/FullSet/Classifier/haematopoietic.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.3,family="gaussian",standardize=TRUE) sink('./haematopoietic_043.txt',append=TRUE) print(glm$glmnet.fit) sink()
/Model/EN/Classifier/haematopoietic/haematopoietic_043.R
no_license
esbgkannan/QSMART
R
false
false
364
r
library(glmnet) mydata = read.table("../../../../TrainingSet/FullSet/Classifier/haematopoietic.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.3,family="gaussian",standardize=TRUE) sink('./haematopoietic_043.txt',append=TRUE) print(glm$glmnet.fit) sink()
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/cMSY_funs.R \name{plotcMSY6} \alias{plotcMSY6} \title{plotcMSY6 plots out a summary of the Catch-MSY results in 6 graphs} \usage{ plotcMSY6(cMSY, catch, label = NA) } \arguments{ \item{cMSY}{the list from running summcMSY on the output from run_cMSY} \item{catch}{the catch in each year} \item{label}{simply a text label for the y-axes; default = NA} } \value{ nothing, but it does generate a plot to the screen } \description{ plotcMSY6 generates 6 graphs illustrating the array of rK parameter combinations and whether they were successful or not. That plot is coloured by how many trajectories across the initial depletion range were successful. } \examples{ \dontrun{ data(invert) fish <- invert$fish glb <- invert$glb reps <- 5000 # one would run at least 20000, preferably more answer <- run_cMSY(fish,glb,n=reps,sigpR=0.04) summcMSY <- summarycMSY(answer,fish,final=FALSE) plotcMSY6(summcMSY,fish[,"catch"],label=glb$spsname) summcMSY <- summarycMSY(answer,fish,final=TRUE) str(summcMSY,max.level=1) plotcMSY6(summcMSY,fish[,"catch"],label=glb$spsname) } }
/man/plotcMSY6.Rd
no_license
haddonm/datalowSA
R
false
true
1,197
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/cMSY_funs.R \name{plotcMSY6} \alias{plotcMSY6} \title{plotcMSY6 plots out a summary of the Catch-MSY results in 6 graphs} \usage{ plotcMSY6(cMSY, catch, label = NA) } \arguments{ \item{cMSY}{the list from running summcMSY on the output from run_cMSY} \item{catch}{the catch in each year} \item{label}{simply a text label for the y-axes; default = NA} } \value{ nothing, but it does generate a plot to the screen } \description{ plotcMSY6 generates 6 graphs illustrating the array of rK parameter combinations and whether they were successful or not. That plot is coloured by how many trajectories across the initial depletion range were successful. } \examples{ \dontrun{ data(invert) fish <- invert$fish glb <- invert$glb reps <- 5000 # one would run at least 20000, preferably more answer <- run_cMSY(fish,glb,n=reps,sigpR=0.04) summcMSY <- summarycMSY(answer,fish,final=FALSE) plotcMSY6(summcMSY,fish[,"catch"],label=glb$spsname) summcMSY <- summarycMSY(answer,fish,final=TRUE) str(summcMSY,max.level=1) plotcMSY6(summcMSY,fish[,"catch"],label=glb$spsname) } }
#' Find triples with dependent edges for RFCI dep.triple <- function (suffStat, indepTest, alpha, sepset, apag, unshTripl, unshVect, trueVstruct, verbose = FALSE) { p <- nrow(apag) for (k in seq_len(ncol(unshTripl))) { if (trueVstruct[k]) { x <- unshTripl[1, k] y <- unshTripl[2, k] z <- unshTripl[3, k] SepSet <- setdiff(unique(c(sepset[[x]][[z]], sepset[[z]][[x]])), y) nSep <- length(SepSet) if (verbose) cat("\nTriple:", x, y, z, "and sepSet (of size", nSep, ") ", SepSet, "\n") if (nSep != 0) { x. <- min(x, y) y. <- max(x, y) y_ <- min(y, z) z_ <- max(y, z) del1 <- FALSE if (indepTest(x, y, SepSet, suffStat) >= alpha) { del1 <- TRUE done <- FALSE ord <- 0L while (!done && ord < nSep) { ord <- ord + 1L S.j <- if (ord == 1 && nSep == 1) matrix(SepSet, 1, 1) else combn(SepSet, ord) for (i in seq_len(ncol(S.j))) { pval <- indepTest(x, y, S.j[, i], suffStat) if (verbose) cat("x=", x, " y=", y, "S=", S.j[, i], ": pval =", pval, "\n") if (pval >= alpha) { apag[x, y] <- apag[y, x] <- 0 sepset[[x]][[y]] <- sepset[[y]][[x]] <- S.j[, i] done <- TRUE break } } } indM <- which((apag[x, ] == 1 & apag[, x] == 1) & (apag[y, ] == 1 & apag[, y] == 1)) indM <- setdiff(indM, c(x, y, z)) for (m in indM) { unshTripl <- cbind(unshTripl, c(x., m, y.)) unshVect <- c(unshVect, triple2numb(p, x., m, y.)) trueVstruct <- c(trueVstruct, TRUE) } indQ <- which((apag[x, ] == 1 & apag[, x] == 1) & (apag[y, ] == 0 & apag[, y] == 0)) indQ <- setdiff(indQ, c(x, y, z)) for (q in indQ) { delTripl <- unshVect == (if (q < y) triple2numb(p, q, x, y) else triple2numb(p, y, x, q)) if (any(delTripl)) trueVstruct[which.max(delTripl)] <- FALSE } indR <- which((apag[x, ] == 0 & apag[, x] == 0) & (apag[y, ] == 1 & apag[, y] == 1)) indR <- setdiff(indR, c(x, y, z)) for (r in indR) { delTripl <- unshVect == (if (r < x) triple2numb(p, r, y, x) else triple2numb(p, x, y, r)) if (any(delTripl)) trueVstruct[which.max(delTripl)] <- FALSE } } del2 <- FALSE if (indepTest(z, y, SepSet, suffStat) >= alpha) { del2 <- TRUE Done <- FALSE Ord <- 0L while (!Done && Ord < nSep) { Ord <- Ord + 1L S.j <- if (Ord == 1 && nSep == 1) matrix(SepSet, 1, 1) else combn(SepSet, Ord) for (i in seq_len(ncol(S.j))) { pval <- indepTest(z, y, S.j[, i], suffStat) if (verbose) cat("x=", z, " y=", y, " S=", S.j[, i], ": pval =", pval, "\n") if (pval >= alpha) { apag[z, y] <- apag[y, z] <- 0 sepset[[z]][[y]] <- sepset[[y]][[z]] <- S.j[, i] Done <- TRUE break } } } indM <- which((apag[z, ] == 1 & apag[, z] == 1) & (apag[y, ] == 1 & apag[, y] == 1)) indM <- setdiff(indM, c(x, y, z)) for (m in indM) { unshTripl <- cbind(unshTripl, c(y_, m, z_)) unshVect <- c(unshVect, triple2numb(p, y_, m, z_)) trueVstruct <- c(trueVstruct, TRUE) } indQ <- which((apag[z, ] == 1 & apag[, z] == 1) & (apag[y, ] == 0 & apag[, y] == 0)) indQ <- setdiff(indQ, c(x, y, z)) for (q in indQ) { delTripl <- unshVect == (if (q < y) triple2numb(p, q, z, y) else triple2numb(p, y, z, q)) if (any(delTripl)) trueVstruct[which.max(delTripl)] <- FALSE } indR <- which((apag[z, ] == 0 & apag[, z] == 0) & (apag[y, ] == 1 & apag[, y] == 1)) indR <- setdiff(indR, c(x, y, z)) for (r in indR) { delTripl <- unshVect == (if (r < z) triple2numb(p, r, y, z) else triple2numb(p, z, y, r)) if (any(delTripl)) trueVstruct[which.max(delTripl)] <- FALSE } } if (any(del1, del2)) trueVstruct[k] <- FALSE } } } list(triple = unshTripl, vect = unshVect, sepset = sepset, apag = apag, trueVstruct = trueVstruct) }
/R/dep_triple.R
no_license
ericstrobl/F2CI
R
false
false
5,303
r
#' Find triples with dependent edges for RFCI dep.triple <- function (suffStat, indepTest, alpha, sepset, apag, unshTripl, unshVect, trueVstruct, verbose = FALSE) { p <- nrow(apag) for (k in seq_len(ncol(unshTripl))) { if (trueVstruct[k]) { x <- unshTripl[1, k] y <- unshTripl[2, k] z <- unshTripl[3, k] SepSet <- setdiff(unique(c(sepset[[x]][[z]], sepset[[z]][[x]])), y) nSep <- length(SepSet) if (verbose) cat("\nTriple:", x, y, z, "and sepSet (of size", nSep, ") ", SepSet, "\n") if (nSep != 0) { x. <- min(x, y) y. <- max(x, y) y_ <- min(y, z) z_ <- max(y, z) del1 <- FALSE if (indepTest(x, y, SepSet, suffStat) >= alpha) { del1 <- TRUE done <- FALSE ord <- 0L while (!done && ord < nSep) { ord <- ord + 1L S.j <- if (ord == 1 && nSep == 1) matrix(SepSet, 1, 1) else combn(SepSet, ord) for (i in seq_len(ncol(S.j))) { pval <- indepTest(x, y, S.j[, i], suffStat) if (verbose) cat("x=", x, " y=", y, "S=", S.j[, i], ": pval =", pval, "\n") if (pval >= alpha) { apag[x, y] <- apag[y, x] <- 0 sepset[[x]][[y]] <- sepset[[y]][[x]] <- S.j[, i] done <- TRUE break } } } indM <- which((apag[x, ] == 1 & apag[, x] == 1) & (apag[y, ] == 1 & apag[, y] == 1)) indM <- setdiff(indM, c(x, y, z)) for (m in indM) { unshTripl <- cbind(unshTripl, c(x., m, y.)) unshVect <- c(unshVect, triple2numb(p, x., m, y.)) trueVstruct <- c(trueVstruct, TRUE) } indQ <- which((apag[x, ] == 1 & apag[, x] == 1) & (apag[y, ] == 0 & apag[, y] == 0)) indQ <- setdiff(indQ, c(x, y, z)) for (q in indQ) { delTripl <- unshVect == (if (q < y) triple2numb(p, q, x, y) else triple2numb(p, y, x, q)) if (any(delTripl)) trueVstruct[which.max(delTripl)] <- FALSE } indR <- which((apag[x, ] == 0 & apag[, x] == 0) & (apag[y, ] == 1 & apag[, y] == 1)) indR <- setdiff(indR, c(x, y, z)) for (r in indR) { delTripl <- unshVect == (if (r < x) triple2numb(p, r, y, x) else triple2numb(p, x, y, r)) if (any(delTripl)) trueVstruct[which.max(delTripl)] <- FALSE } } del2 <- FALSE if (indepTest(z, y, SepSet, suffStat) >= alpha) { del2 <- TRUE Done <- FALSE Ord <- 0L while (!Done && Ord < nSep) { Ord <- Ord + 1L S.j <- if (Ord == 1 && nSep == 1) matrix(SepSet, 1, 1) else combn(SepSet, Ord) for (i in seq_len(ncol(S.j))) { pval <- indepTest(z, y, S.j[, i], suffStat) if (verbose) cat("x=", z, " y=", y, " S=", S.j[, i], ": pval =", pval, "\n") if (pval >= alpha) { apag[z, y] <- apag[y, z] <- 0 sepset[[z]][[y]] <- sepset[[y]][[z]] <- S.j[, i] Done <- TRUE break } } } indM <- which((apag[z, ] == 1 & apag[, z] == 1) & (apag[y, ] == 1 & apag[, y] == 1)) indM <- setdiff(indM, c(x, y, z)) for (m in indM) { unshTripl <- cbind(unshTripl, c(y_, m, z_)) unshVect <- c(unshVect, triple2numb(p, y_, m, z_)) trueVstruct <- c(trueVstruct, TRUE) } indQ <- which((apag[z, ] == 1 & apag[, z] == 1) & (apag[y, ] == 0 & apag[, y] == 0)) indQ <- setdiff(indQ, c(x, y, z)) for (q in indQ) { delTripl <- unshVect == (if (q < y) triple2numb(p, q, z, y) else triple2numb(p, y, z, q)) if (any(delTripl)) trueVstruct[which.max(delTripl)] <- FALSE } indR <- which((apag[z, ] == 0 & apag[, z] == 0) & (apag[y, ] == 1 & apag[, y] == 1)) indR <- setdiff(indR, c(x, y, z)) for (r in indR) { delTripl <- unshVect == (if (r < z) triple2numb(p, r, y, z) else triple2numb(p, z, y, r)) if (any(delTripl)) trueVstruct[which.max(delTripl)] <- FALSE } } if (any(del1, del2)) trueVstruct[k] <- FALSE } } } list(triple = unshTripl, vect = unshVect, sepset = sepset, apag = apag, trueVstruct = trueVstruct) }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/guardduty_operations.R \name{guardduty_disassociate_from_master_account} \alias{guardduty_disassociate_from_master_account} \title{Disassociates the current GuardDuty member account from its administrator account} \usage{ guardduty_disassociate_from_master_account(DetectorId) } \arguments{ \item{DetectorId}{[required] The unique ID of the detector of the GuardDuty member account.} } \value{ An empty list. } \description{ Disassociates the current GuardDuty member account from its administrator account. } \section{Request syntax}{ \preformatted{svc$disassociate_from_master_account( DetectorId = "string" ) } } \keyword{internal}
/cran/paws.security.identity/man/guardduty_disassociate_from_master_account.Rd
permissive
TWarczak/paws
R
false
true
716
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/guardduty_operations.R \name{guardduty_disassociate_from_master_account} \alias{guardduty_disassociate_from_master_account} \title{Disassociates the current GuardDuty member account from its administrator account} \usage{ guardduty_disassociate_from_master_account(DetectorId) } \arguments{ \item{DetectorId}{[required] The unique ID of the detector of the GuardDuty member account.} } \value{ An empty list. } \description{ Disassociates the current GuardDuty member account from its administrator account. } \section{Request syntax}{ \preformatted{svc$disassociate_from_master_account( DetectorId = "string" ) } } \keyword{internal}
library(data.table) library(FeatureHashing) library(xgboost) library(dplyr) library(Matrix) train=fread('redhat_data_new/act_train.csv') %>% as.data.frame() test=fread('redhat_data_new/act_test.csv') %>% as.data.frame() #people data frame people=fread('redhat_data_new/people.csv') %>% as.data.frame() people$char_1<-NULL #unnecessary duplicate to char_2 names(people)[2:length(names(people))]=paste0('people_',names(people)[2:length(names(people))]) p_logi <- names(people)[which(sapply(people, is.logical))] for (col in p_logi) set(people, j = col, value = as.numeric(people[[col]])) #reducing group_1 dimension people$people_group_1[people$people_group_1 %in% names(which(table(people$people_group_1)==1))]='group unique' #reducing char_10 dimension unique.char_10= rbind( select(train,people_id,char_10), select(train,people_id,char_10)) %>% group_by(char_10) %>% summarize(n=n_distinct(people_id)) %>% filter(n==1) %>% select(char_10) %>% as.matrix() %>% as.vector() train$char_10[train$char_10 %in% unique.char_10]='type unique' test$char_10[test$char_10 %in% unique.char_10]='type unique' d1 <- merge(train, people, by = "people_id", all.x = T) d2 <- merge(test, people, by = "people_id", all.x = T) Y <- d1$outcome d1$outcome <- NULL row.train=nrow(train) gc() D=rbind(d1,d2) D$i=1:dim(D)[1] ###uncomment this for CV run #set.seed(120) #unique_p <- unique(d1$people_id) #valid_p <- unique_p[sample(1:length(unique_p), 40000)] #valid <- which(d1$people_id %in% valid_p) #model <- (1:length(d1$people_id))[-valid] test_activity_id=test$activity_id rm(train,test,d1,d2);gc() char.cols=c('activity_category','people_group_1', 'char_1','char_2','char_3','char_4','char_5','char_6','char_7','char_8','char_9','char_10', 'people_char_2','people_char_3','people_char_4','people_char_5','people_char_6','people_char_7','people_char_8','people_char_9') for (f in char.cols) { if (class(D[[f]])=="character") { levels <- unique(c(D[[f]])) D[[f]] <- as.numeric(factor(D[[f]], levels=levels)) } } D.sparse= cBind(sparseMatrix(D$i,D$activity_category), sparseMatrix(D$i,D$people_group_1), sparseMatrix(D$i,D$char_1), sparseMatrix(D$i,D$char_2), sparseMatrix(D$i,D$char_3), sparseMatrix(D$i,D$char_4), sparseMatrix(D$i,D$char_5), sparseMatrix(D$i,D$char_6), sparseMatrix(D$i,D$char_7), sparseMatrix(D$i,D$char_8), sparseMatrix(D$i,D$char_9), sparseMatrix(D$i,D$people_char_2), sparseMatrix(D$i,D$people_char_3), sparseMatrix(D$i,D$people_char_4), sparseMatrix(D$i,D$people_char_5), sparseMatrix(D$i,D$people_char_6), sparseMatrix(D$i,D$people_char_7), sparseMatrix(D$i,D$people_char_8), sparseMatrix(D$i,D$people_char_9) ) D.sparse= cBind(D.sparse, D$people_char_10, D$people_char_11, D$people_char_12, D$people_char_13, D$people_char_14, D$people_char_15, D$people_char_16, D$people_char_17, D$people_char_18, D$people_char_19, D$people_char_20, D$people_char_21, D$people_char_22, D$people_char_23, D$people_char_24, D$people_char_25, D$people_char_26, D$people_char_27, D$people_char_28, D$people_char_29, D$people_char_30, D$people_char_31, D$people_char_32, D$people_char_33, D$people_char_34, D$people_char_35, D$people_char_36, D$people_char_37, D$people_char_38, D$binay_sum) train.sparse=D.sparse[1:row.train,] test.sparse=D.sparse[(row.train+1):nrow(D.sparse),] # Hash train to sparse dmatrix X_train dtrain <- xgb.DMatrix(train.sparse, label = Y) dtest <- xgb.DMatrix(test.sparse) param <- list(objective = "binary:logistic", eval_metric = "auc", booster = "gblinear", eta = 0.02, subsample = 0.7, colsample_bytree = 0.7, min_child_weight = 0, max_depth = 10) ###uncomment this for CV run # #dmodel <- xgb.DMatrix(train.sparse[model, ], label = Y[model]) #dvalid <- xgb.DMatrix(train.sparse[valid, ], label = Y[valid]) # #set.seed(120) #m1 <- xgb.train(data = dmodel # , param # , nrounds = 500 # , watchlist = list(valid = dvalid, model = dmodel) # , early.stop.round = 20 # , nthread=11 # , print_every_n = 10) #[300] valid-auc:0.979167 model-auc:0.990326 set.seed(120) m2 <- xgb.train(data = dtrain, param, nrounds = 305, watchlist = list(train = dtrain), print_every_n = 10) # Predict out <- predict(m2, dtest) sub <- data.frame(activity_id = test_activity_id, outcome = out) write.csv(sub, file = "model_sub_98035.csv", row.names = F) #0.98035
/raddar-xgboost.R
permissive
kmkping/redhad_business_data
R
false
false
4,975
r
library(data.table) library(FeatureHashing) library(xgboost) library(dplyr) library(Matrix) train=fread('redhat_data_new/act_train.csv') %>% as.data.frame() test=fread('redhat_data_new/act_test.csv') %>% as.data.frame() #people data frame people=fread('redhat_data_new/people.csv') %>% as.data.frame() people$char_1<-NULL #unnecessary duplicate to char_2 names(people)[2:length(names(people))]=paste0('people_',names(people)[2:length(names(people))]) p_logi <- names(people)[which(sapply(people, is.logical))] for (col in p_logi) set(people, j = col, value = as.numeric(people[[col]])) #reducing group_1 dimension people$people_group_1[people$people_group_1 %in% names(which(table(people$people_group_1)==1))]='group unique' #reducing char_10 dimension unique.char_10= rbind( select(train,people_id,char_10), select(train,people_id,char_10)) %>% group_by(char_10) %>% summarize(n=n_distinct(people_id)) %>% filter(n==1) %>% select(char_10) %>% as.matrix() %>% as.vector() train$char_10[train$char_10 %in% unique.char_10]='type unique' test$char_10[test$char_10 %in% unique.char_10]='type unique' d1 <- merge(train, people, by = "people_id", all.x = T) d2 <- merge(test, people, by = "people_id", all.x = T) Y <- d1$outcome d1$outcome <- NULL row.train=nrow(train) gc() D=rbind(d1,d2) D$i=1:dim(D)[1] ###uncomment this for CV run #set.seed(120) #unique_p <- unique(d1$people_id) #valid_p <- unique_p[sample(1:length(unique_p), 40000)] #valid <- which(d1$people_id %in% valid_p) #model <- (1:length(d1$people_id))[-valid] test_activity_id=test$activity_id rm(train,test,d1,d2);gc() char.cols=c('activity_category','people_group_1', 'char_1','char_2','char_3','char_4','char_5','char_6','char_7','char_8','char_9','char_10', 'people_char_2','people_char_3','people_char_4','people_char_5','people_char_6','people_char_7','people_char_8','people_char_9') for (f in char.cols) { if (class(D[[f]])=="character") { levels <- unique(c(D[[f]])) D[[f]] <- as.numeric(factor(D[[f]], levels=levels)) } } D.sparse= cBind(sparseMatrix(D$i,D$activity_category), sparseMatrix(D$i,D$people_group_1), sparseMatrix(D$i,D$char_1), sparseMatrix(D$i,D$char_2), sparseMatrix(D$i,D$char_3), sparseMatrix(D$i,D$char_4), sparseMatrix(D$i,D$char_5), sparseMatrix(D$i,D$char_6), sparseMatrix(D$i,D$char_7), sparseMatrix(D$i,D$char_8), sparseMatrix(D$i,D$char_9), sparseMatrix(D$i,D$people_char_2), sparseMatrix(D$i,D$people_char_3), sparseMatrix(D$i,D$people_char_4), sparseMatrix(D$i,D$people_char_5), sparseMatrix(D$i,D$people_char_6), sparseMatrix(D$i,D$people_char_7), sparseMatrix(D$i,D$people_char_8), sparseMatrix(D$i,D$people_char_9) ) D.sparse= cBind(D.sparse, D$people_char_10, D$people_char_11, D$people_char_12, D$people_char_13, D$people_char_14, D$people_char_15, D$people_char_16, D$people_char_17, D$people_char_18, D$people_char_19, D$people_char_20, D$people_char_21, D$people_char_22, D$people_char_23, D$people_char_24, D$people_char_25, D$people_char_26, D$people_char_27, D$people_char_28, D$people_char_29, D$people_char_30, D$people_char_31, D$people_char_32, D$people_char_33, D$people_char_34, D$people_char_35, D$people_char_36, D$people_char_37, D$people_char_38, D$binay_sum) train.sparse=D.sparse[1:row.train,] test.sparse=D.sparse[(row.train+1):nrow(D.sparse),] # Hash train to sparse dmatrix X_train dtrain <- xgb.DMatrix(train.sparse, label = Y) dtest <- xgb.DMatrix(test.sparse) param <- list(objective = "binary:logistic", eval_metric = "auc", booster = "gblinear", eta = 0.02, subsample = 0.7, colsample_bytree = 0.7, min_child_weight = 0, max_depth = 10) ###uncomment this for CV run # #dmodel <- xgb.DMatrix(train.sparse[model, ], label = Y[model]) #dvalid <- xgb.DMatrix(train.sparse[valid, ], label = Y[valid]) # #set.seed(120) #m1 <- xgb.train(data = dmodel # , param # , nrounds = 500 # , watchlist = list(valid = dvalid, model = dmodel) # , early.stop.round = 20 # , nthread=11 # , print_every_n = 10) #[300] valid-auc:0.979167 model-auc:0.990326 set.seed(120) m2 <- xgb.train(data = dtrain, param, nrounds = 305, watchlist = list(train = dtrain), print_every_n = 10) # Predict out <- predict(m2, dtest) sub <- data.frame(activity_id = test_activity_id, outcome = out) write.csv(sub, file = "model_sub_98035.csv", row.names = F) #0.98035
# Changes in the experience of child death throughout the Demographic # Transition (horizontal axis, proxied by life expectancy) in different # regions of the world. (A-F) Association between the fraction of a # woman's offspring expected to live longer than her and the cohort # life expectancy for the woman's cohort. The panels show country-level # trajectories by UN SDG region. # The figure adresses the question of where there is a relationship # between progress on the demographic transition and expossure to # offspring mortality. # In other words, do female cohorts in countries more advanced towards the demographic transition # lose a smaller share of their children? # If so, then the experience of child death does really decline with the demographic transition, # as Livi Bacci suggested. # 0. Parameters ---- lower_year <- 1950 upper_year <- 1999 # 0.2. Draft paper and presentation format (large) width <- 13 height <- 11 base_size <- 14 region_line_size <- 1 point_size <- 0.25 # 1. X = TFR or ex ---- # Progression towards the DT can be approximated b ylooking at either TFR or ex # 1.1. Cohort ex ==== ex_df <- LTCB %>% filter(dplyr::between(Cohort, lower_year, upper_year)) %>% # filter() %>% filter(Age == 0) %>% select(country = Country, cohort = Cohort, ex) # 1.2. Cohort TFR ==== ctfr <- ASFRC %>% filter(dplyr::between(Cohort, lower_year, upper_year)) %>% group_by(country, Cohort) %>% summarise(tfr = sum(ASFR)/1000) %>% ungroup %>% rename(cohort = Cohort) # 2. Y = E[CD]/TFR ---- expected <- ecl_ctfr %>% dplyr::mutate(cohort = as.numeric(cohort)) %>% filter(dplyr::between(cohort, lower_year, upper_year)) %>% mutate(share = 1 - (value / tfr)) # 3. Merge all ---- ecl_ctfr_ex <- merge( expected , ex_df , by = c("cohort", "country") , all.x = T , all.y = F ) %>% mutate(cohort = as.numeric(cohort)) %>% select(country, region, cohort, cl = value, tfr, ex, share) # 4. Plot ---- # 4.1. By ex ==== p_ecl_ex <- ecl_ctfr_ex %>% filter(!region %in% regions_to_remove) %>% mutate(region = plyr::mapvalues(region, from = regions_long, to = regions_short)) %>% ggplot(aes(x = ex, y = share)) + geom_point( aes(colour = cohort) , size = point_size ) + scale_y_continuous("Fraction of TFR expected to outlive mother") + scale_x_continuous("Life expectancy in cohort of women") + scale_color_gradient("Woman's birth cohort", low = "red", high = "blue", breaks = c(1950, 1975, 1999)) + # facet_grid(. ~ cohort) + facet_wrap(. ~ region) + theme_bw() + theme( legend.position = "bottom" ) p_ecl_ex ggsave(paste0("../../Output/figS4.pdf"), p_ecl_ex, width = width, height = height, units = "cm") # NOT RUN: # 4.2. By TFR ==== # # p_ecl_tfr <- # ecl_ctfr_ex %>% # filter(!region %in% regions_to_remove) %>% # mutate(region = plyr::mapvalues(region, from = regions_long, to = regions_short)) %>% # ggplot(aes(x = tfr, y = share)) + # geom_point( # aes(colour = cohort) # , size = point_size # ) + # scale_y_continuous("Fraction of TFR expected to outlive mother") + # scale_x_continuous("Cohort Total Fertility Rate") + # scale_color_gradient("Woman's birth cohort", low = "red", high = "blue", breaks = c(1950, 1975, 1999)) + # # facet_grid(. ~ cohort) + # facet_wrap(. ~ region) + # theme_bw() + # theme( # legend.position = "bottom" # ) # # p_ecl_tfr # # ggsave(paste0("../../Output/figS4a.pdf"), p_ecl_tfr, width = width, height = height, units = "cm")
/R/D_Supplementary/7 - FigS4.R
permissive
timriffe/code_review_MPIDR
R
false
false
3,572
r
# Changes in the experience of child death throughout the Demographic # Transition (horizontal axis, proxied by life expectancy) in different # regions of the world. (A-F) Association between the fraction of a # woman's offspring expected to live longer than her and the cohort # life expectancy for the woman's cohort. The panels show country-level # trajectories by UN SDG region. # The figure adresses the question of where there is a relationship # between progress on the demographic transition and expossure to # offspring mortality. # In other words, do female cohorts in countries more advanced towards the demographic transition # lose a smaller share of their children? # If so, then the experience of child death does really decline with the demographic transition, # as Livi Bacci suggested. # 0. Parameters ---- lower_year <- 1950 upper_year <- 1999 # 0.2. Draft paper and presentation format (large) width <- 13 height <- 11 base_size <- 14 region_line_size <- 1 point_size <- 0.25 # 1. X = TFR or ex ---- # Progression towards the DT can be approximated b ylooking at either TFR or ex # 1.1. Cohort ex ==== ex_df <- LTCB %>% filter(dplyr::between(Cohort, lower_year, upper_year)) %>% # filter() %>% filter(Age == 0) %>% select(country = Country, cohort = Cohort, ex) # 1.2. Cohort TFR ==== ctfr <- ASFRC %>% filter(dplyr::between(Cohort, lower_year, upper_year)) %>% group_by(country, Cohort) %>% summarise(tfr = sum(ASFR)/1000) %>% ungroup %>% rename(cohort = Cohort) # 2. Y = E[CD]/TFR ---- expected <- ecl_ctfr %>% dplyr::mutate(cohort = as.numeric(cohort)) %>% filter(dplyr::between(cohort, lower_year, upper_year)) %>% mutate(share = 1 - (value / tfr)) # 3. Merge all ---- ecl_ctfr_ex <- merge( expected , ex_df , by = c("cohort", "country") , all.x = T , all.y = F ) %>% mutate(cohort = as.numeric(cohort)) %>% select(country, region, cohort, cl = value, tfr, ex, share) # 4. Plot ---- # 4.1. By ex ==== p_ecl_ex <- ecl_ctfr_ex %>% filter(!region %in% regions_to_remove) %>% mutate(region = plyr::mapvalues(region, from = regions_long, to = regions_short)) %>% ggplot(aes(x = ex, y = share)) + geom_point( aes(colour = cohort) , size = point_size ) + scale_y_continuous("Fraction of TFR expected to outlive mother") + scale_x_continuous("Life expectancy in cohort of women") + scale_color_gradient("Woman's birth cohort", low = "red", high = "blue", breaks = c(1950, 1975, 1999)) + # facet_grid(. ~ cohort) + facet_wrap(. ~ region) + theme_bw() + theme( legend.position = "bottom" ) p_ecl_ex ggsave(paste0("../../Output/figS4.pdf"), p_ecl_ex, width = width, height = height, units = "cm") # NOT RUN: # 4.2. By TFR ==== # # p_ecl_tfr <- # ecl_ctfr_ex %>% # filter(!region %in% regions_to_remove) %>% # mutate(region = plyr::mapvalues(region, from = regions_long, to = regions_short)) %>% # ggplot(aes(x = tfr, y = share)) + # geom_point( # aes(colour = cohort) # , size = point_size # ) + # scale_y_continuous("Fraction of TFR expected to outlive mother") + # scale_x_continuous("Cohort Total Fertility Rate") + # scale_color_gradient("Woman's birth cohort", low = "red", high = "blue", breaks = c(1950, 1975, 1999)) + # # facet_grid(. ~ cohort) + # facet_wrap(. ~ region) + # theme_bw() + # theme( # legend.position = "bottom" # ) # # p_ecl_tfr # # ggsave(paste0("../../Output/figS4a.pdf"), p_ecl_tfr, width = width, height = height, units = "cm")
library("MASS") mp <- polr(Sat ~ Infl, weights = Freq, data = housing) library("mlt") s <- as.basis(~ Infl, data = housing, remove_intercept = TRUE) r <- as.basis(housing$Sat) #r <- as.basis(~ Sat, data = housing, remove_intercept = TRUE, # contrasts.arg = list(Sat = function(n) # contr.treatment(n, base = 3)), # ui = diff(diag(2)), ci = 0) m <- ctm(r, shift = s, todist = "Logi") mod <- mlt(m, data = housing, weights = housing$Freq) logLik(mp) logLik(mod) coef(mp) mp$zeta coef(mod) sqrt(diag(vcov(mp))) sqrt(diag(vcov(mod)))
/mlt/tests/polr-Ex.R
no_license
ingted/R-Examples
R
false
false
583
r
library("MASS") mp <- polr(Sat ~ Infl, weights = Freq, data = housing) library("mlt") s <- as.basis(~ Infl, data = housing, remove_intercept = TRUE) r <- as.basis(housing$Sat) #r <- as.basis(~ Sat, data = housing, remove_intercept = TRUE, # contrasts.arg = list(Sat = function(n) # contr.treatment(n, base = 3)), # ui = diff(diag(2)), ci = 0) m <- ctm(r, shift = s, todist = "Logi") mod <- mlt(m, data = housing, weights = housing$Freq) logLik(mp) logLik(mod) coef(mp) mp$zeta coef(mod) sqrt(diag(vcov(mp))) sqrt(diag(vcov(mod)))
# Random Forest Classification # Importing the dataset dataset = read.csv('Social_Network_Ads.csv') dataset = dataset[3:5] # Encoding the target feature as factor dataset$Purchased = factor(dataset$Purchased, levels = c(0, 1)) # Splitting the dataset into the Training set and Test set # install.packages('caTools') library(caTools) set.seed(123) split = sample.split(dataset$Purchased, SplitRatio = 0.75) training_set = subset(dataset, split == TRUE) test_set = subset(dataset, split == FALSE) # Feature Scaling training_set[-3] = scale(training_set[-3]) test_set[-3] = scale(test_set[-3]) # Fitting Random Forest Classifier to the Training set library(randomForest) classifier = randomForest(x = training_set[-3], y = training_set$Purchased, ntree = 500) # Predicting the Test set results y_pred = predict(classifier, newdata = test_set[-3]) # Making the Confusion Matrix cm = table(test_set[, 3], y_pred) # Visualising the Training set results library(ElemStatLearn) set = training_set X1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01) X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01) grid_set = expand.grid(X1, X2) colnames(grid_set) = c('Age', 'EstimatedSalary') y_grid = predict(classifier, newdata = grid_set) plot(set[, -3], main = 'Random Forest Classifier (Training set)', xlab = 'Age', ylab = 'Estimated Salary', xlim = range(X1), ylim = range(X2)) contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE) points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'springgreen3', 'tomato')) points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3')) # Visualising the Test set results library(ElemStatLearn) set = test_set X1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01) X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01) grid_set = expand.grid(X1, X2) colnames(grid_set) = c('Age', 'EstimatedSalary') y_grid = predict(classifier, newdata = grid_set) plot(set[, -3], main = 'Random Forest Classifier (Test set)', xlab = 'Age', ylab = 'Estimated Salary', xlim = range(X1), ylim = range(X2)) contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE) points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'springgreen3', 'tomato')) points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3'))
/Part 3 - Classification/Section 18 - Random Forest Classification/my_random_forest_classification.R
no_license
AfzalivE/ML-A-to-Z
R
false
false
2,439
r
# Random Forest Classification # Importing the dataset dataset = read.csv('Social_Network_Ads.csv') dataset = dataset[3:5] # Encoding the target feature as factor dataset$Purchased = factor(dataset$Purchased, levels = c(0, 1)) # Splitting the dataset into the Training set and Test set # install.packages('caTools') library(caTools) set.seed(123) split = sample.split(dataset$Purchased, SplitRatio = 0.75) training_set = subset(dataset, split == TRUE) test_set = subset(dataset, split == FALSE) # Feature Scaling training_set[-3] = scale(training_set[-3]) test_set[-3] = scale(test_set[-3]) # Fitting Random Forest Classifier to the Training set library(randomForest) classifier = randomForest(x = training_set[-3], y = training_set$Purchased, ntree = 500) # Predicting the Test set results y_pred = predict(classifier, newdata = test_set[-3]) # Making the Confusion Matrix cm = table(test_set[, 3], y_pred) # Visualising the Training set results library(ElemStatLearn) set = training_set X1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01) X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01) grid_set = expand.grid(X1, X2) colnames(grid_set) = c('Age', 'EstimatedSalary') y_grid = predict(classifier, newdata = grid_set) plot(set[, -3], main = 'Random Forest Classifier (Training set)', xlab = 'Age', ylab = 'Estimated Salary', xlim = range(X1), ylim = range(X2)) contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE) points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'springgreen3', 'tomato')) points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3')) # Visualising the Test set results library(ElemStatLearn) set = test_set X1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01) X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01) grid_set = expand.grid(X1, X2) colnames(grid_set) = c('Age', 'EstimatedSalary') y_grid = predict(classifier, newdata = grid_set) plot(set[, -3], main = 'Random Forest Classifier (Test set)', xlab = 'Age', ylab = 'Estimated Salary', xlim = range(X1), ylim = range(X2)) contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE) points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'springgreen3', 'tomato')) points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3'))
hingeError = function(W,X,Y) { misclassf = 0 totalError = 0 for(i in 1:nrow(X)) { tmp = Y[i]*(W %*% X[i,]) if(tmp <= 0) misclassf = misclassf + 1 totalError = totalError - tmp } c(misclassf,totalError/nrow(X)) } stochastic_gradient = function(W,X,Y) { delta = rep(0,ncol(X)) i = sample(1:nrow(X),1) if(Y[i]*(W %*% X[i,]) <= 0) delta = - Y[i]* X[i,] delta } stochastic_gradient_descent = function(X,Y, learningRate, iterations) { W = rep(0,ncol(X)) W_trace = W error_trace = hingeError(W,X,Y) for(iter in 1:iterations) { grad = stochastic_gradient(W,X,Y) W = W - (learningRate * grad) error_current = hingeError(W, X, Y) W_trace = rbind(W_trace, W) error_trace = rbind(error_trace,error_current) } list(W_trace,error_trace) } display.trace = function(solution) { solution[[1]] solution[[2]] } plot.trace = function(X, Y, solution, iterations) { plot(X[,2],X[,3],col=ifelse(Y == -1,"yellow","blue"),xlab="v1",ylab="v2",main="Perceptron") weights = solution[[1]] for (i in 2:iterations) { W = weights[i,] abline(-W[1]/W[3], -W[2]/W[3], col=rgb(0.9,0,0,0.4)) } abline(-W[1]/W[3], -W[2]/W[3], col="green", lwd=4) misclass = solution[[2]] plot(1:(iterations+1),misclass[,1],col="blue",xlab="Iterations",ylab="error",main="Convergence") # w1 = seq(-2, 4, 1) # w2 = seq(-2, 4, 1) # err = outer(w1,w2,hingeError,weights,X,Y) # # persp3D(w1, w2, err[,1], xlab="w1", ylab="w2", zlab="error",col = ramp.col(n = 50, col = c("#FF033E", "#FFBF00", "#FF7E00", "#08E8DE", "#00FFFF", "#03C03C"), alpha = .1), border = "#808080", theta = -90, phi = 10, colkey = FALSE) # contour3D(b, m, z = 0, colvar = err, col = c("#FF7E00", "#FF033E"), alpha = .3, add = TRUE, colkey = FALSE) # points3D(solution$intercept,solution$slope , solution$error, pch = 20, col = 'red', add = TRUE) # } setwd("C:\\Users\\Thimma Reddy\\Documents\\GitHub\\datascience\\datasets") data = read.csv("iris-train.csv", header = TRUE) dim(data) str(data) X = data.frame(v0=rep(1,nrow(data)),data$v1,data$v2) Y = data$target X = as.matrix(X) stepsize = 1 iterations = 3000 solution = stochastic_gradient_descent(X, Y, stepsize, iterations) display.trace(solution) plot.trace(X,Y,solution,iterations)
/2016/10-Classification models/perceptron model/perceptron-stochasticGD.R
no_license
rajesh2win/datascience
R
false
false
2,290
r
hingeError = function(W,X,Y) { misclassf = 0 totalError = 0 for(i in 1:nrow(X)) { tmp = Y[i]*(W %*% X[i,]) if(tmp <= 0) misclassf = misclassf + 1 totalError = totalError - tmp } c(misclassf,totalError/nrow(X)) } stochastic_gradient = function(W,X,Y) { delta = rep(0,ncol(X)) i = sample(1:nrow(X),1) if(Y[i]*(W %*% X[i,]) <= 0) delta = - Y[i]* X[i,] delta } stochastic_gradient_descent = function(X,Y, learningRate, iterations) { W = rep(0,ncol(X)) W_trace = W error_trace = hingeError(W,X,Y) for(iter in 1:iterations) { grad = stochastic_gradient(W,X,Y) W = W - (learningRate * grad) error_current = hingeError(W, X, Y) W_trace = rbind(W_trace, W) error_trace = rbind(error_trace,error_current) } list(W_trace,error_trace) } display.trace = function(solution) { solution[[1]] solution[[2]] } plot.trace = function(X, Y, solution, iterations) { plot(X[,2],X[,3],col=ifelse(Y == -1,"yellow","blue"),xlab="v1",ylab="v2",main="Perceptron") weights = solution[[1]] for (i in 2:iterations) { W = weights[i,] abline(-W[1]/W[3], -W[2]/W[3], col=rgb(0.9,0,0,0.4)) } abline(-W[1]/W[3], -W[2]/W[3], col="green", lwd=4) misclass = solution[[2]] plot(1:(iterations+1),misclass[,1],col="blue",xlab="Iterations",ylab="error",main="Convergence") # w1 = seq(-2, 4, 1) # w2 = seq(-2, 4, 1) # err = outer(w1,w2,hingeError,weights,X,Y) # # persp3D(w1, w2, err[,1], xlab="w1", ylab="w2", zlab="error",col = ramp.col(n = 50, col = c("#FF033E", "#FFBF00", "#FF7E00", "#08E8DE", "#00FFFF", "#03C03C"), alpha = .1), border = "#808080", theta = -90, phi = 10, colkey = FALSE) # contour3D(b, m, z = 0, colvar = err, col = c("#FF7E00", "#FF033E"), alpha = .3, add = TRUE, colkey = FALSE) # points3D(solution$intercept,solution$slope , solution$error, pch = 20, col = 'red', add = TRUE) # } setwd("C:\\Users\\Thimma Reddy\\Documents\\GitHub\\datascience\\datasets") data = read.csv("iris-train.csv", header = TRUE) dim(data) str(data) X = data.frame(v0=rep(1,nrow(data)),data$v1,data$v2) Y = data$target X = as.matrix(X) stepsize = 1 iterations = 3000 solution = stochastic_gradient_descent(X, Y, stepsize, iterations) display.trace(solution) plot.trace(X,Y,solution,iterations)
library(shiny) library(shinythemes) library(markdown) library(dplyr) library(tm) library(NLP) shinyUI( navbarPage("Next Word Predict", theme = shinytheme("spacelab"), tabPanel("Home", fluidPage( titlePanel("Home"), sidebarLayout( sidebarPanel( textInput("userInput", "Enter a word or phrase:", value = "", placeholder = "Enter text here"), br(), sliderInput("numPredictions", "Number of Predictions:", value = 1.0, min = 1.0, max = 3.0, step = 1.0) ), mainPanel( h4("Input text"), verbatimTextOutput("userSentence"), br(), h4("Predicted words"), verbatimTextOutput("prediction1"), verbatimTextOutput("prediction2"), verbatimTextOutput("prediction3") ) ) ) ), tabPanel("About", h3("About Next Word Predict"), br(), div("Next Word Predict is a Shiny app that uses a text prediction algorithm to predict the next word(s) based on text entered by a user.", br(), br(), "The predicted next word will be shown when the app detects that you have finished typing one or more words. When entering text, please allow a few seconds for the output to appear.", br(), br(), "Use the slider tool to select up to three next word predictions. The top prediction will be shown first followed by the second and third likely next words.", br(), br(), ) ) ))
/ui.R
no_license
Moveke/Word-Prediction-App
R
false
false
2,660
r
library(shiny) library(shinythemes) library(markdown) library(dplyr) library(tm) library(NLP) shinyUI( navbarPage("Next Word Predict", theme = shinytheme("spacelab"), tabPanel("Home", fluidPage( titlePanel("Home"), sidebarLayout( sidebarPanel( textInput("userInput", "Enter a word or phrase:", value = "", placeholder = "Enter text here"), br(), sliderInput("numPredictions", "Number of Predictions:", value = 1.0, min = 1.0, max = 3.0, step = 1.0) ), mainPanel( h4("Input text"), verbatimTextOutput("userSentence"), br(), h4("Predicted words"), verbatimTextOutput("prediction1"), verbatimTextOutput("prediction2"), verbatimTextOutput("prediction3") ) ) ) ), tabPanel("About", h3("About Next Word Predict"), br(), div("Next Word Predict is a Shiny app that uses a text prediction algorithm to predict the next word(s) based on text entered by a user.", br(), br(), "The predicted next word will be shown when the app detects that you have finished typing one or more words. When entering text, please allow a few seconds for the output to appear.", br(), br(), "Use the slider tool to select up to three next word predictions. The top prediction will be shown first followed by the second and third likely next words.", br(), br(), ) ) ))
\name{plot.envelope} \alias{plot.envelope} \title{Plot a Simulation Envelope} \description{ Plot method for the class \code{"envelope"}. } \usage{ \method{plot}{envelope}(x, \dots, main) } \arguments{ \item{x}{ An object of class \code{"envelope"}, containing the variables to be plotted or variables from which the plotting coordinates can be computed. } \item{main}{Main title for plot.} \item{\dots}{ Extra arguments passed to \code{\link{plot.fv}}. } } \value{ Either \code{NULL}, or a data frame giving the meaning of the different line types and colours. } \details{ This is the \code{plot} method for the class \code{"envelope"} of simulation envelopes. Objects of this class are created by the command \code{\link{envelope}}. This plot method is currently identical to \code{\link{plot.fv}}. Its default behaviour is to shade the region between the upper and lower envelopes in a light grey colour. To suppress the shading and plot the upper and lower envelopes as curves, set \code{shade=NULL}. To change the colour of the shading, use the argument \code{shadecol} which is passed to \code{\link{plot.fv}}. See \code{\link{plot.fv}} for further information on how to control the plot. } \examples{ data(cells) E <- envelope(cells, Kest, nsim=19) plot(E) plot(E, sqrt(./pi) ~ r) } \seealso{ \code{\link{envelope}}, \code{\link{plot.fv}} } \author{Adrian Baddeley \email{Adrian.Baddeley@uwa.edu.au} \url{http://www.maths.uwa.edu.au/~adrian/} and Rolf Turner \email{r.turner@auckland.ac.nz} } \keyword{spatial} \keyword{hplot}
/man/plot.envelope.Rd
no_license
cuulee/spatstat
R
false
false
1,618
rd
\name{plot.envelope} \alias{plot.envelope} \title{Plot a Simulation Envelope} \description{ Plot method for the class \code{"envelope"}. } \usage{ \method{plot}{envelope}(x, \dots, main) } \arguments{ \item{x}{ An object of class \code{"envelope"}, containing the variables to be plotted or variables from which the plotting coordinates can be computed. } \item{main}{Main title for plot.} \item{\dots}{ Extra arguments passed to \code{\link{plot.fv}}. } } \value{ Either \code{NULL}, or a data frame giving the meaning of the different line types and colours. } \details{ This is the \code{plot} method for the class \code{"envelope"} of simulation envelopes. Objects of this class are created by the command \code{\link{envelope}}. This plot method is currently identical to \code{\link{plot.fv}}. Its default behaviour is to shade the region between the upper and lower envelopes in a light grey colour. To suppress the shading and plot the upper and lower envelopes as curves, set \code{shade=NULL}. To change the colour of the shading, use the argument \code{shadecol} which is passed to \code{\link{plot.fv}}. See \code{\link{plot.fv}} for further information on how to control the plot. } \examples{ data(cells) E <- envelope(cells, Kest, nsim=19) plot(E) plot(E, sqrt(./pi) ~ r) } \seealso{ \code{\link{envelope}}, \code{\link{plot.fv}} } \author{Adrian Baddeley \email{Adrian.Baddeley@uwa.edu.au} \url{http://www.maths.uwa.edu.au/~adrian/} and Rolf Turner \email{r.turner@auckland.ac.nz} } \keyword{spatial} \keyword{hplot}
create_game_status_from_simple <- function(simple_gs, track_id, STG_TRACK, STG_TRACK_PIECE) { new_track <- create_track_table(track_id, STG_TRACK_PIECE, STG_TRACK) #set positions new_track[, CYCLER_ID := as.integer(CYCLER_ID)] sscols_simple <- simple_gs[, .(CYCLER_NEW = CYCLER_ID, SQUARE_ID)] join_simple <- sscols_simple[new_track, on = "SQUARE_ID"] join_simple[, CYCLER_ID := ifelse(!is.na(CYCLER_NEW), CYCLER_NEW, CYCLER_ID)] join_simple[, CYCLER_NEW := NULL] #new_track[SQUARE_ID %in% simple_gs[, SQUARE_ID], CYCLER_ID := simple_gs[, CYCLER_ID]] #new_track[CYCLER_ID > 0] return(join_simple) }
/scripts/solution/create_game_status_from_simple.R
no_license
Laurigit/flAImme_client
R
false
false
604
r
create_game_status_from_simple <- function(simple_gs, track_id, STG_TRACK, STG_TRACK_PIECE) { new_track <- create_track_table(track_id, STG_TRACK_PIECE, STG_TRACK) #set positions new_track[, CYCLER_ID := as.integer(CYCLER_ID)] sscols_simple <- simple_gs[, .(CYCLER_NEW = CYCLER_ID, SQUARE_ID)] join_simple <- sscols_simple[new_track, on = "SQUARE_ID"] join_simple[, CYCLER_ID := ifelse(!is.na(CYCLER_NEW), CYCLER_NEW, CYCLER_ID)] join_simple[, CYCLER_NEW := NULL] #new_track[SQUARE_ID %in% simple_gs[, SQUARE_ID], CYCLER_ID := simple_gs[, CYCLER_ID]] #new_track[CYCLER_ID > 0] return(join_simple) }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/avg_oc_wr_ne.r \name{avg_oc_wr_ne} \alias{avg_oc_wr_ne} \title{Single Arm Average Operating Characteristics} \usage{ avg_oc_wr_ne( N_e, true_RR_c = NULL, delta, delta_power, confidence, e_a = 0.5, e_b = 0.5, h_a = 0.5, h_b = 0.5, RR_h = NULL, N_h = NULL, hist_RR_c = NULL, alpha_c, beta_c, trues = seq(0, 1, 0.001), adapt = 1, plot = T, coresnum = NULL, legend = T, legend.pos = "topleft" ) } \arguments{ \item{N_e}{Sample Size in the experimental group. Can be either a single value or a vector.} \item{true_RR_c}{Default value is NULL. If specified, will be used in the generated plots, indicating the true achieved decision power and decision type 1 error. If not specified, will be set to either RR_h or hist_RR_c, depending on which was specified by the user.} \item{delta}{Required superiority to make a "GO" decision. Corresponds to \eqn{\delta}.} \item{delta_power}{Superiority, at which decision power will be evaluated. Corresponds to \eqn{\bar{\delta}}{\delta bar}.} \item{confidence}{Required confidence to make "GO" decision. Corresponds to \eqn{\gamma}{\gamma}.} \item{e_a}{Alpha parameter of Beta Prior Distribution for the experimental response rate. Corresponds to \eqn{\alpha_e}{\alpha e}. Default is \eqn{\frac{1}{2}}{1/2}.} \item{e_b}{Beta parameter of Beta Prior Distribution for the experimental response rate. Corresponds to \eqn{\beta_e}{\beta e}. Default is \eqn{\frac{1}{2}}{1/2}.} \item{h_a}{Alpha parameter of Beta Prior Distribution for the historical control response rate. Corresponds to \eqn{\alpha_h}{\alpha h}. Only needs to be specified, if RR_h and N_h are also specified. Default is \eqn{\frac{1}{2}}{1/2}.} \item{h_b}{Beta parameter of Beta Prior Distribution for the historical control response rate. Corresponds to \eqn{\beta_h}{\beta h}. Only needs to be specified, if RR_h and N_h are also specified. Default is \eqn{\frac{1}{2}}{1/2}.} \item{RR_h}{Historical control response rate. Corresponds to \eqn{p_h}{p h}. If specified together with N_h, function will use setting 2 from pdf.} \item{N_h}{Historical control sample size. Corresponds to \eqn{n_h}{n h}. If specified together with RR_h, function will use setting 2 from pdf.} \item{hist_RR_c}{Point estimate of historical control repsonse rate. Corresponds to \eqn{\hat{p_h}}{p h hat}. If specified, while RR_h and N_h are not specified, function will use setting 1 from pdf.} \item{alpha_c}{Alpha parameter of Beta Distribution for the control response rate used to calculate average operating characteristics. Corresponds to \eqn{\alpha_c}{\alpha c}.} \item{beta_c}{Beta parameter of Beta Distribution for the control response rate used to calculate average operating characteristics. Corresponds to \eqn{\beta_c}{\beta c}.} \item{trues}{Sequence of true control response rates and experimental response rates, at which the Probability to Go will be computed. Default is seq(0,1,0.01) to ensure continuous plots and accurate results.} \item{adapt}{Level of adapting of experimental control rate to account for patient selection bias from phase II to phase III. Corresponds to \eqn{\xi}{\xi}. Default is 1, so no adapting.} \item{plot}{Plots yes or no. Default is TRUE.} \item{coresnum}{Number of cores used for parallel computing, in case N_e is a vector. Default is the number of total cores - 1.} \item{legend}{Logical; whether or not to include legend in plot. Default is TRUE.} \item{legend.pos}{Position of legend. Default is "topleft".} } \value{ Either a vector containing the average decision power and average alpha (if N_e has length 1), or a matrix containing the average decision power and average decision alpha (if N_e has length > 1), where every row corresponds to one value of N_e. } \description{ Function for calculating the average operating characteristics of two single arm bayesian designs for early gating with respect to the sample size in the experimental group and possible historical data. } \examples{ # Setting 1 avg_oc_wr_ne( N_e = 50, delta = 0.08, delta_power = 0.13, confidence = 0.6, hist_RR_c = 0.5, alpha_c = 15, beta_c = 13 ) # Setting 2 avg_oc_wr_ne( N_e = 50, delta = 0.08, delta_power = 0.13, confidence = 0.6, RR_h = 0.5, N_h = 50, alpha_c = 15, beta_c = 13 ) }
/man/avg_oc_wr_ne.Rd
no_license
cran/earlygating
R
false
true
4,371
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/avg_oc_wr_ne.r \name{avg_oc_wr_ne} \alias{avg_oc_wr_ne} \title{Single Arm Average Operating Characteristics} \usage{ avg_oc_wr_ne( N_e, true_RR_c = NULL, delta, delta_power, confidence, e_a = 0.5, e_b = 0.5, h_a = 0.5, h_b = 0.5, RR_h = NULL, N_h = NULL, hist_RR_c = NULL, alpha_c, beta_c, trues = seq(0, 1, 0.001), adapt = 1, plot = T, coresnum = NULL, legend = T, legend.pos = "topleft" ) } \arguments{ \item{N_e}{Sample Size in the experimental group. Can be either a single value or a vector.} \item{true_RR_c}{Default value is NULL. If specified, will be used in the generated plots, indicating the true achieved decision power and decision type 1 error. If not specified, will be set to either RR_h or hist_RR_c, depending on which was specified by the user.} \item{delta}{Required superiority to make a "GO" decision. Corresponds to \eqn{\delta}.} \item{delta_power}{Superiority, at which decision power will be evaluated. Corresponds to \eqn{\bar{\delta}}{\delta bar}.} \item{confidence}{Required confidence to make "GO" decision. Corresponds to \eqn{\gamma}{\gamma}.} \item{e_a}{Alpha parameter of Beta Prior Distribution for the experimental response rate. Corresponds to \eqn{\alpha_e}{\alpha e}. Default is \eqn{\frac{1}{2}}{1/2}.} \item{e_b}{Beta parameter of Beta Prior Distribution for the experimental response rate. Corresponds to \eqn{\beta_e}{\beta e}. Default is \eqn{\frac{1}{2}}{1/2}.} \item{h_a}{Alpha parameter of Beta Prior Distribution for the historical control response rate. Corresponds to \eqn{\alpha_h}{\alpha h}. Only needs to be specified, if RR_h and N_h are also specified. Default is \eqn{\frac{1}{2}}{1/2}.} \item{h_b}{Beta parameter of Beta Prior Distribution for the historical control response rate. Corresponds to \eqn{\beta_h}{\beta h}. Only needs to be specified, if RR_h and N_h are also specified. Default is \eqn{\frac{1}{2}}{1/2}.} \item{RR_h}{Historical control response rate. Corresponds to \eqn{p_h}{p h}. If specified together with N_h, function will use setting 2 from pdf.} \item{N_h}{Historical control sample size. Corresponds to \eqn{n_h}{n h}. If specified together with RR_h, function will use setting 2 from pdf.} \item{hist_RR_c}{Point estimate of historical control repsonse rate. Corresponds to \eqn{\hat{p_h}}{p h hat}. If specified, while RR_h and N_h are not specified, function will use setting 1 from pdf.} \item{alpha_c}{Alpha parameter of Beta Distribution for the control response rate used to calculate average operating characteristics. Corresponds to \eqn{\alpha_c}{\alpha c}.} \item{beta_c}{Beta parameter of Beta Distribution for the control response rate used to calculate average operating characteristics. Corresponds to \eqn{\beta_c}{\beta c}.} \item{trues}{Sequence of true control response rates and experimental response rates, at which the Probability to Go will be computed. Default is seq(0,1,0.01) to ensure continuous plots and accurate results.} \item{adapt}{Level of adapting of experimental control rate to account for patient selection bias from phase II to phase III. Corresponds to \eqn{\xi}{\xi}. Default is 1, so no adapting.} \item{plot}{Plots yes or no. Default is TRUE.} \item{coresnum}{Number of cores used for parallel computing, in case N_e is a vector. Default is the number of total cores - 1.} \item{legend}{Logical; whether or not to include legend in plot. Default is TRUE.} \item{legend.pos}{Position of legend. Default is "topleft".} } \value{ Either a vector containing the average decision power and average alpha (if N_e has length 1), or a matrix containing the average decision power and average decision alpha (if N_e has length > 1), where every row corresponds to one value of N_e. } \description{ Function for calculating the average operating characteristics of two single arm bayesian designs for early gating with respect to the sample size in the experimental group and possible historical data. } \examples{ # Setting 1 avg_oc_wr_ne( N_e = 50, delta = 0.08, delta_power = 0.13, confidence = 0.6, hist_RR_c = 0.5, alpha_c = 15, beta_c = 13 ) # Setting 2 avg_oc_wr_ne( N_e = 50, delta = 0.08, delta_power = 0.13, confidence = 0.6, RR_h = 0.5, N_h = 50, alpha_c = 15, beta_c = 13 ) }
library(rpart) pima_data <- read.table("DataSet.csv", header=TRUE, sep=",") summary(pima_data) summary(pima_data$Result) sort(pima_data$BP) pima_data$Result <- factor(pima_data$Result) summary(pima_data$Result) #Pregnancy hist(pima_data$Pregnant,plot = TRUE, right = FALSE, labels = FALSE, main = "Pima Histo_Preg") no <- table(pima_data$Pregnant) barplot(no, main="Pregnancy Bar_Distribution") #Glucose hist(pima_data$Glucose,plot = TRUE, right = FALSE, labels = FALSE, main = "Pima Histo_Glucose") no <- table(pima_data$Glucose) barplot(no, main="Glucose Bar_Distribution") #BP hist(pima_data$BP,plot = TRUE, right = FALSE, labels = FALSE, main = "Pima Histo_BP") no <- table(pima_data$BP) barplot(no, main="BP Bar_Distribution") #Thickness hist(pima_data$Thickness,plot = TRUE, right = FALSE, labels = FALSE, main = "Pima Histo_Thickness") no <- table(pima_data$Thickness) barplot(no, main="Thickness Bar_Distribution") #Insulin hist(pima_data$Insulin,plot = TRUE, right = FALSE, labels = FALSE, main = "Pima Histo_Insulin") no <- table(pima_data$Insulin) barplot(no, main="Insulin Bar_Distribution") #BMI hist(pima_data$BMI,plot = TRUE, right = FALSE, labels = FALSE, main = "Pima Histo_BMI") no <- table(pima_data$BMI) barplot(no, main="BMI Bar_Distribution") #Pedigree hist(pima_data$Pedigree,plot = TRUE, right = FALSE, labels = FALSE, main = "Pima Histo_Pedigree") no <- table(pima_data$Pedigree) barplot(no, main="Pedigree Bar_Distribution") #Age hist(pima_data$Age,plot = TRUE, right = FALSE, labels = FALSE, main = "Pima Histo_Age") no <- table(pima_data$Age) barplot(no, main="Age Bar_Distribution") pima_data$Result<-as.numeric(as.character(pima_data$Result)) cor(pima_data, use="complete.obs") max = 0 a = 0 b = 0 for(x in 1:8) { for(y in (x+1):8) { if( x != y) { temp <- cor(pima_data[x], pima_data[y]) if( max < temp[1]) { max <- temp[1] a <- x b <- y } } } } colName <- colnames(pima_data) cat('Max correlation is between',colName[a],'and',colName[b], 'attribute: ',max)
/Classification Problem/Data Analysis/DataAnalysis.R
no_license
iamtusharbhatia/Machine-Learning
R
false
false
2,079
r
library(rpart) pima_data <- read.table("DataSet.csv", header=TRUE, sep=",") summary(pima_data) summary(pima_data$Result) sort(pima_data$BP) pima_data$Result <- factor(pima_data$Result) summary(pima_data$Result) #Pregnancy hist(pima_data$Pregnant,plot = TRUE, right = FALSE, labels = FALSE, main = "Pima Histo_Preg") no <- table(pima_data$Pregnant) barplot(no, main="Pregnancy Bar_Distribution") #Glucose hist(pima_data$Glucose,plot = TRUE, right = FALSE, labels = FALSE, main = "Pima Histo_Glucose") no <- table(pima_data$Glucose) barplot(no, main="Glucose Bar_Distribution") #BP hist(pima_data$BP,plot = TRUE, right = FALSE, labels = FALSE, main = "Pima Histo_BP") no <- table(pima_data$BP) barplot(no, main="BP Bar_Distribution") #Thickness hist(pima_data$Thickness,plot = TRUE, right = FALSE, labels = FALSE, main = "Pima Histo_Thickness") no <- table(pima_data$Thickness) barplot(no, main="Thickness Bar_Distribution") #Insulin hist(pima_data$Insulin,plot = TRUE, right = FALSE, labels = FALSE, main = "Pima Histo_Insulin") no <- table(pima_data$Insulin) barplot(no, main="Insulin Bar_Distribution") #BMI hist(pima_data$BMI,plot = TRUE, right = FALSE, labels = FALSE, main = "Pima Histo_BMI") no <- table(pima_data$BMI) barplot(no, main="BMI Bar_Distribution") #Pedigree hist(pima_data$Pedigree,plot = TRUE, right = FALSE, labels = FALSE, main = "Pima Histo_Pedigree") no <- table(pima_data$Pedigree) barplot(no, main="Pedigree Bar_Distribution") #Age hist(pima_data$Age,plot = TRUE, right = FALSE, labels = FALSE, main = "Pima Histo_Age") no <- table(pima_data$Age) barplot(no, main="Age Bar_Distribution") pima_data$Result<-as.numeric(as.character(pima_data$Result)) cor(pima_data, use="complete.obs") max = 0 a = 0 b = 0 for(x in 1:8) { for(y in (x+1):8) { if( x != y) { temp <- cor(pima_data[x], pima_data[y]) if( max < temp[1]) { max <- temp[1] a <- x b <- y } } } } colName <- colnames(pima_data) cat('Max correlation is between',colName[a],'and',colName[b], 'attribute: ',max)
# library(faoebx5) # library(data.table) get_hs_masterfile <- function(local = T){ if (local == T) { hs_masterfile <- readRDS("data/hs_masterfile.rds") return(hs_masterfile) } SetEBXCredentials(username = "Fishery-SOAP", password = 'W8EqZpDM4YBMKsrq') ##-- ISSCFC table ---- isscfc <- ReadEBXCodeList(sdmx_name = "CL_FI_COMMODITY_ISSCFC") isscfc <- isscfc[, list(Identifier, ISSCFC = Code, NameEn)] ##-- HS 2017 ---- gr_hs17 <- ReadEBXGroup(sdmx_name = "HCL_FI_COMMODITY_HS17L3_ISSCFC") gr_hs17 <- gr_hs17[ISSCFCmapping == 'true', ] hs17 <- ReadEBXCodeList(sdmx_name = "CL_FI_COMMODITY_HS2017_L3") map17 <- merge(gr_hs17[, 1:2, with = F], hs17, by.x = "Group", by.y = "Identifier") map17 <- map17[, list(Group, Member, HS_Code = Code)] map17 <- merge(map17, isscfc, by.x = "Member", by.y = "Identifier") map17[, hsrep := 2017] ##-- HS 2012 ---- gr_hs12 <- ReadEBXGroup(sdmx_name = "HCL_FI_COMMODITY_HS12L3_ISSCFC") hs12 <- ReadEBXCodeList(sdmx_name = "CL_FI_COMMODITY_HS2012_L3") map12 <- merge(gr_hs12[, 1:2, with = F], hs12, by.x = "Group", by.y = "Identifier") map12 <- map12[, list(Group, Member, HS_Code = Code)] map12 <- merge(map12, isscfc, by.x = "Member", by.y = "Identifier") map12[, hsrep := 2012] ##-- HS 2007 ---- gr_hs07 <- ReadEBXGroup(sdmx_name = "HCL_FI_COMMODITY_HS07L3_ISSCFC") hs07 <- ReadEBXCodeList(sdmx_name = "CL_FI_COMMODITY_HS2007_L3") map07 <- merge(gr_hs07[, 1:2, with = F], hs07, by.x = "Group", by.y = "Identifier") map07 <- map07[, list(Group, Member, HS_Code = Code)] map07 <- merge(map07, isscfc, by.x = "Member", by.y = "Identifier") map07[, hsrep := 2007] ##-- HS 2002 ---- gr_hs02 <- ReadEBXGroup(sdmx_name = "HCL_FI_COMMODITY_HS02L3_ISSCFC") hs02 <- ReadEBXCodeList(sdmx_name = "CL_FI_COMMODITY_HS2002_L3") map02 <- merge(gr_hs02[, 1:2, with = F], hs02, by.x = "Group", by.y = "Identifier") map02 <- map02[, list(Group, Member, HS_Code = Code)] map02 <- merge(map02, isscfc, by.x = "Member", by.y = "Identifier") map02[, hsrep := 2002] ##-- HS 1996 ---- gr_hs96 <- ReadEBXGroup(sdmx_name = "HCL_FI_COMMODITY_HS96L3_ISSCFC") hs96 <- ReadEBXCodeList(sdmx_name = "CL_FI_COMMODITY_HS1996_L3") map96 <- merge(gr_hs96[, 1:2, with = F], hs96, by.x = "Group", by.y = "Identifier") map96 <- map96[, list(Group, Member, HS_Code = Code)] map96 <- merge(map96, isscfc, by.x = "Member", by.y = "Identifier") map96[, hsrep := 1996] ##-- HS 1992 ---- gr_hs92 <- ReadEBXGroup(sdmx_name = "HCL_FI_COMMODITY_HS92L3_ISSCFC") hs92 <- ReadEBXCodeList(sdmx_name = "CL_FI_COMMODITY_HS1992_L3") map92 <- merge(gr_hs92[, 1:2, with = F], hs92, by.x = "Group", by.y = "Identifier") map92 <- map92[, list(Group, Member, HS_Code = Code)] map92 <- merge(map92, isscfc, by.x = "Member", by.y = "Identifier") map92[, hsrep := 1992] ##-- HS Master file ---- hs_masterfile <- rbindlist(list(map92, map96, map02, map07, map12, map17), use.names = T) rm(list = c('map92', 'map96', 'map02', 'map07', 'map12', 'map17')) rm(list = c('hs92', 'hs96', 'hs02', 'hs07', 'hs12', 'hs17', 'isscfc')) rm(list = c('gr_hs92', 'gr_hs96', 'gr_hs02', 'gr_hs07', 'gr_hs12', 'gr_hs17')) hs_masterfile[, hs := stringr::str_pad(gsub("\\.", "", HS_Code), width = 12, side = "right", pad = "0")] hs_rep <- paste0("H", 0:5) names(hs_rep) <- as.character(c(1992, 1996, 2002, 2007, 2012, 2017)) hs_masterfile[, hsrep := hs_rep[as.character(hsrep)]] # hs_masterfile_full <- copy(hs_masterfile) # hs_masterfile <- hs_masterfile[, list(hs, hsrep, faocode_hs6 = ISSCFC)] return(hs_masterfile) }
/shinyFisheriesTrade_prod/functions/get_hs_masterfile.R
permissive
SWS-Methodology/faoFisheriesTrade
R
false
false
3,812
r
# library(faoebx5) # library(data.table) get_hs_masterfile <- function(local = T){ if (local == T) { hs_masterfile <- readRDS("data/hs_masterfile.rds") return(hs_masterfile) } SetEBXCredentials(username = "Fishery-SOAP", password = 'W8EqZpDM4YBMKsrq') ##-- ISSCFC table ---- isscfc <- ReadEBXCodeList(sdmx_name = "CL_FI_COMMODITY_ISSCFC") isscfc <- isscfc[, list(Identifier, ISSCFC = Code, NameEn)] ##-- HS 2017 ---- gr_hs17 <- ReadEBXGroup(sdmx_name = "HCL_FI_COMMODITY_HS17L3_ISSCFC") gr_hs17 <- gr_hs17[ISSCFCmapping == 'true', ] hs17 <- ReadEBXCodeList(sdmx_name = "CL_FI_COMMODITY_HS2017_L3") map17 <- merge(gr_hs17[, 1:2, with = F], hs17, by.x = "Group", by.y = "Identifier") map17 <- map17[, list(Group, Member, HS_Code = Code)] map17 <- merge(map17, isscfc, by.x = "Member", by.y = "Identifier") map17[, hsrep := 2017] ##-- HS 2012 ---- gr_hs12 <- ReadEBXGroup(sdmx_name = "HCL_FI_COMMODITY_HS12L3_ISSCFC") hs12 <- ReadEBXCodeList(sdmx_name = "CL_FI_COMMODITY_HS2012_L3") map12 <- merge(gr_hs12[, 1:2, with = F], hs12, by.x = "Group", by.y = "Identifier") map12 <- map12[, list(Group, Member, HS_Code = Code)] map12 <- merge(map12, isscfc, by.x = "Member", by.y = "Identifier") map12[, hsrep := 2012] ##-- HS 2007 ---- gr_hs07 <- ReadEBXGroup(sdmx_name = "HCL_FI_COMMODITY_HS07L3_ISSCFC") hs07 <- ReadEBXCodeList(sdmx_name = "CL_FI_COMMODITY_HS2007_L3") map07 <- merge(gr_hs07[, 1:2, with = F], hs07, by.x = "Group", by.y = "Identifier") map07 <- map07[, list(Group, Member, HS_Code = Code)] map07 <- merge(map07, isscfc, by.x = "Member", by.y = "Identifier") map07[, hsrep := 2007] ##-- HS 2002 ---- gr_hs02 <- ReadEBXGroup(sdmx_name = "HCL_FI_COMMODITY_HS02L3_ISSCFC") hs02 <- ReadEBXCodeList(sdmx_name = "CL_FI_COMMODITY_HS2002_L3") map02 <- merge(gr_hs02[, 1:2, with = F], hs02, by.x = "Group", by.y = "Identifier") map02 <- map02[, list(Group, Member, HS_Code = Code)] map02 <- merge(map02, isscfc, by.x = "Member", by.y = "Identifier") map02[, hsrep := 2002] ##-- HS 1996 ---- gr_hs96 <- ReadEBXGroup(sdmx_name = "HCL_FI_COMMODITY_HS96L3_ISSCFC") hs96 <- ReadEBXCodeList(sdmx_name = "CL_FI_COMMODITY_HS1996_L3") map96 <- merge(gr_hs96[, 1:2, with = F], hs96, by.x = "Group", by.y = "Identifier") map96 <- map96[, list(Group, Member, HS_Code = Code)] map96 <- merge(map96, isscfc, by.x = "Member", by.y = "Identifier") map96[, hsrep := 1996] ##-- HS 1992 ---- gr_hs92 <- ReadEBXGroup(sdmx_name = "HCL_FI_COMMODITY_HS92L3_ISSCFC") hs92 <- ReadEBXCodeList(sdmx_name = "CL_FI_COMMODITY_HS1992_L3") map92 <- merge(gr_hs92[, 1:2, with = F], hs92, by.x = "Group", by.y = "Identifier") map92 <- map92[, list(Group, Member, HS_Code = Code)] map92 <- merge(map92, isscfc, by.x = "Member", by.y = "Identifier") map92[, hsrep := 1992] ##-- HS Master file ---- hs_masterfile <- rbindlist(list(map92, map96, map02, map07, map12, map17), use.names = T) rm(list = c('map92', 'map96', 'map02', 'map07', 'map12', 'map17')) rm(list = c('hs92', 'hs96', 'hs02', 'hs07', 'hs12', 'hs17', 'isscfc')) rm(list = c('gr_hs92', 'gr_hs96', 'gr_hs02', 'gr_hs07', 'gr_hs12', 'gr_hs17')) hs_masterfile[, hs := stringr::str_pad(gsub("\\.", "", HS_Code), width = 12, side = "right", pad = "0")] hs_rep <- paste0("H", 0:5) names(hs_rep) <- as.character(c(1992, 1996, 2002, 2007, 2012, 2017)) hs_masterfile[, hsrep := hs_rep[as.character(hsrep)]] # hs_masterfile_full <- copy(hs_masterfile) # hs_masterfile <- hs_masterfile[, list(hs, hsrep, faocode_hs6 = ISSCFC)] return(hs_masterfile) }
#require("RPostgreSQL") library(MASS) library(leaps) library(gvlma) library(car) library(ggplot2) library(gclus) ################################################ ################## LOAD DATA ################### ################################################ # Set working directory to the path containing Fall 2017 data sources. # Many of the required Fall 2017 files can be found at Z:\BNC\PBL development project\data\2018_SLERD_Paper_Analysis # Each semester, data from Khan Academy, Peer Grade and Moodle Activity must be pulled from their respoective places. SVNData<-if(grepl("BiancaClavio", getwd())){'C:/Users/BiancaClavio/Documents/SVN/01Projects/'} else {"/Users/Brian/PBL/Paper"} setwd(SVNData) # Load SSP scores dfSSPGrades<-read.csv("SSPgradesTestAAL 02-10.csv", header = TRUE, fill=TRUE, sep = ",", check.names=FALSE, stringsAsFactors=FALSE) # Load Midterm/Final grades dfAALMidGrades<-read.csv("15-02-2018_GPRO-overview-MT-exam.csv", header = TRUE, fill=TRUE, sep = ",", check.names=FALSE, stringsAsFactors=FALSE) # Load SA grades # contains Student id number for merging with dfSAGrades<-read.csv("15-02-2018_GPRO-gradebook.csv", header = TRUE, fill=TRUE, sep = ",", check.names=FALSE, stringsAsFactors=FALSE) # Load Peer Grade grades dfPeerGrade<-read.csv("15-02-2018_Peer_Grade_course_overall_stats_data.csv", header = TRUE, fill=TRUE, sep = ",", check.names=FALSE, stringsAsFactors=FALSE) # Load Khan Academy exercises (106 exercises) # Found on website under "Progress by Skill" # Waring: Comes from Khan with extra white spaces. dfKhan<-read.csv("15-02-2018_Khan_data.csv", header = TRUE, fill=TRUE, sep = ",", check.names=FALSE, stringsAsFactors=FALSE) # Load Khan student user name and email pairs # This file is only necessary if not all students use their student email address as # their Khan academy user name. If necessary, this file will need to be manually updated every semester. #dfKhanID<-read.csv("khan_id_new.csv", header = TRUE, fill=TRUE, sep = ",", check.names=FALSE, stringsAsFactors=FALSE) # Load merge file containing, student name, email address and ID # Manually constructed. This will be necessary each semester if, for example, # students use a Khan Academy user name which differs from their student name or email address. dfKhanID<-read.csv("all_merge.csv", header = TRUE, fill=TRUE, sep = ",", check.names=FALSE, stringsAsFactors=FALSE) # Load SSP questions (111 questions into 14 topic categories) questions<-read.csv("QuestionsOverview.csv", header = TRUE, fill=TRUE, sep = ",", check.names=FALSE, stringsAsFactors=FALSE) # 1-9, 10-15, 16-23, 24-33, 34-45, 46-50, 51-56, 57-61, 62-64, 65-74, 75-87, 88-92, 93-97, 98-111 # demographics,attitudeEdu,reasonsUni,eduChoice,hsBehav,hsTrust,belongUncert,grit,growth,selfControl,personalTrait,acadAbility,studyHours,viewMedia # Load Tutoring invitees dfInvitees<-read.csv("tutoringInvitees.csv", header = FALSE, fill=TRUE, sep = ",", check.names=FALSE, stringsAsFactors=FALSE) # Load Dropout data # Currently not enough dropouts for classification. #dfDropOuts<-read.csv("dropout-Feb2018-Q999.csv", header = TRUE, fill=TRUE, sep = ",", check.names=FALSE, stringsAsFactors=FALSE) #dfDropOuts<-dfDropOuts[dfDropOuts$'Status'!="active",] ################################################ # Load Moodle Activity Data (online) # Moodle Activity data is located in a PostgreSQL database that must be accessed # using a login code (provided below) from Hendrik and an AAU connection. # (see the next section for loading Moodle Activity Data while offline.) # For online access of the PostgreSQL database through R: # # create a connection to the database server # load the PostgreSQL driver # drv <- dbDriver("PostgreSQL") # # create a connection to the PostgreSQL database (must be on AAU network) # activityDataCon <- dbConnect(drv, dbname = "activity_data", # host = "md-db-test.moodle.aau.dk", port = 5432, # user = "hk", password = "=cD58BEtUE") # # check for the existence of tables # dbExistsTable(activityDataCon, "analyse_mdl_course") # dbExistsTable(activityDataCon, "analyse_mdl_logstore_standard_log") # dbExistsTable(activityDataCon, "analyse_mdl_user") # # # query the data from PostgreSQL # dfCourseData <- dbGetQuery(activityDataCon, "SELECT * from analyse_mdl_course") # dfLogData <- dbGetQuery(activityDataCon, "SELECT * from analyse_mdl_logstore_standard_log") # dfUserData <- dbGetQuery(activityDataCon, "SELECT * from analyse_mdl_user") ################################################ # Load Moodle Activity data (offline) # Warning: No headers # Second column of moodleUserData (Student ID) is used to match SA to Moodle activity data #moodleCourseData<-read.csv("analyse_mdl_course.csv", header = FALSE, fill=TRUE, sep = ",", check.names=FALSE, stringsAsFactors=FALSE) #moodleLogData<-read.csv("analyse_mdl_logstore_standard_log.csv", header = FALSE, fill=TRUE, sep = ",", check.names=FALSE, stringsAsFactors=FALSE) #moodleUserData<-read.csv("analyse_mdl_user.csv", header = FALSE, fill=TRUE, sep = ",", check.names=FALSE, stringsAsFactors=FALSE) # Have not found a way yet to link Moodle activity to all other data, # so it will be excluded from this analysis. ################################################ ################# CLEAN DATA ################### ################################################ # Clean data sources (i.e., remove incomplete entries or irrelevant columns and reshape) # Retain "Email address" as student ID used for merging # # SSP # Remove students who did not finish the survey dfSSPGrades<-dfSSPGrades[(dfSSPGrades$"State"=="Finished"), ] # Rename column colnames(dfSSPGrades)[10] <- "SSP score" # Shorten using all SSP questions alldfSSPGrades<-dfSSPGrades[,c(5,10:121)] # Midterm grades # Name columns dfCPHMidGrades<-dfAALMidGrades[(dfAALMidGrades$"education"=="CPH"), ] dfAALMidGrades<-dfAALMidGrades[(dfAALMidGrades$"education"!="CPH"), ] # Shorten dfCPHMidGrades<-dfCPHMidGrades[,c(1,2,3,5)] dfAALMidGrades<-dfAALMidGrades[,c(1,2,3,5)] # Make "education" predictors/groups # PDP students get removed later because they did not do SSP index<-dfAALMidGrades$"education" == "MEA" dfAALMidGrades$"education"[index]<-1 index<-dfAALMidGrades$"education" == "PDP" dfAALMidGrades$"education"[index]<-0 # Remove AAL invalid entries loc <- apply(dfAALMidGrades[,c(3,4)],1,function(row) "-" %in% row) dfAALMidGrades<-dfAALMidGrades[!loc,] loc <- apply(dfAALMidGrades[,c(3,4)],1,function(row) "" %in% row) dfAALMidGrades<-dfAALMidGrades[!loc,] # Remove CPH invalid entries loc <- apply(dfCPHMidGrades[,c(3,4)],1,function(row) "-" %in% row) dfCPHMidGrades<-dfCPHMidGrades[!loc,] loc <- apply(dfCPHMidGrades[,c(3,4)],1,function(row) "" %in% row) dfCPHMidGrades<-dfCPHMidGrades[!loc,] # Rename first column colnames(dfAALMidGrades)[1] <- "ID number" colnames(dfCPHMidGrades)[1] <- "ID number" # SA # Subset only grades saTest<-dfSAGrades[,c(7,8,9,10,11,12,13,15,16,17,18,19)] # Make non-attempts NA saTest[saTest=="-"] <- NA # Compute SA total average saTest<-as.data.frame(lapply(saTest, as.numeric)) saRowAvg<-rowMeans(saTest, na.rm = TRUE, dims = 1) # Create a column of SA attempts saTest[!is.na(saTest)] <- 1 saTest[is.na(saTest)] <- 0 saNumComp<-rowSums(as.data.frame(lapply(saTest,as.numeric))) # Subset all relevant columns dfSAGrades<-dfSAGrades[,c(6,7,8,9,10,11,12,13,15,16,17,18,19)] # Add column of SA attempts dfSAGrades<-cbind(dfSAGrades,saRowAvg,saNumComp) # Remove tmp user dfSAGrades<-dfSAGrades[!grepl("tmpuser",dfSAGrades$'Email address'),] # Subset only total average and number of attempts # Not doing this would provide more variables (i.e., grades) but would punish non-attempts with zeros. # Because SA was not mandatory, we use number of attempts as a predictor instead of giving zeros for non-attempts. dfSAGrades<-dfSAGrades[,c(1,14,15)] # Give students who did not attempt SA a total average of zero. # This similarly punishes students who did not do SA (might be students who are re-taking exam?) is.nan.data.frame <- function(x) do.call(cbind, lapply(x, is.nan)) dfSAGrades[is.nan(dfSAGrades)] <- 0 # Peer Grade # By student email and shorten (Peer Grade changed column name of "hand-in score" to "Submission score") # Mandatory assignments AALpeerGrade<-dfPeerGrade[,c('student_email','Submission score','feedback score','combined score')] # change column name to match others colnames(AALpeerGrade)[1] <- c("Email address") # Khan Academy #Sys.setlocale('LC_ALL','C') # required for reading non-unicode characters # Format Khan Academy data from Long to Wide and convert student user ID occurrences # in "Not Started", "Started" and "Completed" columns to numerical 0, 1 and 2, respectively. # For each column, split list of student user ID names by hidden carriage return inserted from Khan Academy # Not started column s <- strsplit(dfKhan$"Not Started", split = "\n") x<-data.frame(V1 = rep(dfKhan$"Exercise", sapply(s, length)), V2 = unlist(s)) x$"Not Started" <- rep(0,nrow(x)) colnames(x) <- c("Exercise", "Student Name","Completed") # Started column s <- strsplit(dfKhan$"Started", split = "\n") y<-data.frame(V1 = rep(dfKhan$"Exercise", sapply(s, length)), V2 = unlist(s)) y$"Started" <- rep(1,nrow(y)) colnames(y) <- c("Exercise", "Student Name","Completed") # Completed column s <- strsplit(dfKhan$"Completed", split = "\n") z<-data.frame(V1 = rep(dfKhan$"Exercise", sapply(s, length)), V2 = unlist(s)) z$"Completed" <- rep(2,nrow(z)) colnames(z) <- c("Exercise", "Student Name", "Completed") # Join columns and reshape to wide format joinedKhan<-rbind(x,y,z) joinedKhan<-reshape(joinedKhan, idvar = "Student Name", timevar = "Exercise", direction = "wide") # Remove duplicates # Not sure how a student user name could occur more than once but it did in Fall 2017 joinedKhan<-joinedKhan[!duplicated(joinedKhan[,1]),] # Remove Teachers # In subsequent semesters this may or may not be necessary. joinedKhan<-joinedKhan[!grepl("hendrik",joinedKhan$'Student Name'),] # 106 Khan assignments # Count number of completed Khan assignments for each student and store in "KhanCount" column # Like SA, Khan Academny assignments were nto mandatory so we consider number of attempts instead of assigning zeros to non-attempts. joinedKhan$"KhanCount" <- apply(joinedKhan, 1, function(x) sum(x==2)) # Tutoring invitees # The students below atended at least one tutoring session. dfAttendees = data.frame(c('vroua17@student.aau.dk','jlnc17@student.aau.dk','avafai17@student.aau.dk','nneuma17@student.aau.dk','jsimon16@student.aau.dk','fnje17@student.aau.dk','mepo17@student.aau.dk','evalbe17@student.aau.dk','nrux17@student.aau.dk')) colnames(dfAttendees) <- c("Email address") ################################################ # Merge all data sources created above # SA and Midterm saTest<-merge(dfKhanID,dfSAGrades,by="Email address") # 11 students or staff not considered (check with command below) # students were not on the list or did not take the final exam (drop outs?) # 99 total AAL students who did SA and Midterm dfComplete<-merge(saTest,dfAALMidGrades,by="ID number") # Midterm and Khan dfComplete<-merge(dfComplete,joinedKhan,by="Student Name",all.x=TRUE) # Shorten dfComplete<-dfComplete[,c(1:8,115)] # Some students did not create a Khan Academy account (they will not be in the Khan database) # so replace those students who have NA in KhanCount with zeros # These student get removed later because they did not do Peer Grade dfComplete[is.na(dfComplete)]<-0 # Peer Grade dfComplete<-merge(dfComplete,AALpeerGrade,by='Email address',all.x=TRUE) # Optional: remove students retaking the course. Peer Grade was not required for # these students and none of them did it dfComplete<-dfComplete[complete.cases(dfComplete), ] # If we don't delete these students above, we can replace their PG scores with zeros. #dfComplete[is.na(dfComplete)]<-0 # Otherwise, all students are now those not retaking the course. # SSP dfComplete<-merge(dfComplete,alldfSSPGrades,by='Email address',all.x=TRUE) # Remove all incomplete entries leaves only 72 students # This removes all PDP students dfComplete<-dfComplete[complete.cases(dfComplete), ] # Alternatively, we can zero all NAs and consider all 99 students who took the final exam #dfComplete[is.na(dfComplete)]<-0 ################################################ # Add factors for pass or fail Final exam # Can be used for plotting e.g., how often passing students attempted Khan Academy. dfComplete$"pass/fail"[dfComplete$"Exam"<64] <- 0 dfComplete$"pass/fail"[dfComplete$"Exam">=64] <- 1 # An additional predictor of programming experience was found to be significant. # SSP Questions 33 and 78 avgProgExp<-as.data.frame(cbind(dfComplete$"Q. 33 /0.09",dfComplete$"Q. 78 /0.09")) avgProgExp<-rowMeans(as.data.frame(lapply(avgProgExp,as.numeric))) dfComplete[, "Avg. Prog. Exp."] <- avgProgExp # Add column containing tutoring invitees and attendees # Can be used for plotting. # 0 = not invited, 1 = invited, 2 = invited and attended dfComplete$"Tutoring"<-as.numeric(dfComplete$"Email address" %in% dfInvitees[,]) dfComplete$"Tutoring"[dfComplete$"Email address" %in% dfAttendees[,]]<-2 # Final clean # Non attempts in SSP set to zero dfComplete[is.na(dfComplete)]<-0 dfComplete[dfComplete=='-']<-0 ################################################ ################## ANALYSIS #################### ################################################ # Linear model: Final exam ~ Mid term grade is used as the base model # The adjusted r-squared value in the base model is compared to subsequent # models to determine any improvement. # # Extract Final exam drops <- c("Exam") examScores<-dfComplete[,drops] dfComplete<-dfComplete[ , !(names(dfComplete) %in% drops)] ################################################ # Initial Base model - FE ~ MT base1<-lm(as.numeric(examScores) ~ as.numeric(dfComplete$'mid-term'),na.action=na.omit) # base model adjusted r-squared value init_result<-summary(base1)$adj.r.squared ################################################ # By predictors excluding SSP single questions inputData<-as.data.frame(lapply(dfComplete[,c(4,5,8,9,12)], as.numeric)) # Step-wise multiple linear regression fit<-lm(as.numeric(examScores) ~ as.numeric(dfComplete$'mid-term') + .,data=inputData,na.action=na.omit) step<-stepAIC(fit, direction="both") step$anova # display results summary(step) # Best model is the addition of KhanCount to the base model # Using AIC, t value and p value as the measure # Notable absences are Peer Grade, saNumComp, saRowAvg. # Compare best model to base fit<-lm(as.numeric(examScores) ~ as.numeric(dfComplete$'mid-term') + as.numeric(dfComplete$'KhanCount'),na.action=na.omit) summary(fit) anova(base1,fit) # Significantly different than base model # This becomes our new base model. ################################################ # New Base model - FE ~ MT + KhanCount base2<-lm(as.numeric(examScores) ~ as.numeric(dfComplete$'mid-term') + as.numeric(dfComplete$'KhanCount'),na.action=na.omit) # base model adjusted r-squared value init_result<-summary(base2)$adj.r.squared ################################################ # By SSP category # Category question ranges # 1-9, 10-15, 16-23, 24-33, 34-45, 46-50, 51-56, 57-61, 62-64, 65-74, 75-87, 88-92, 93-97, 98-111 # Column ranges in "dfComplete" for the 14 SSP categories # 13-21, 22-27, 28-35, 36-45, 46-57, 58-62, 63-68, 69-73, 74-76, 77-86, 87-99, 100-104, 105-109, 110-123 demographics<-rowMeans(as.data.frame(lapply(dfComplete[,13:21], as.numeric))) attitudeEdu<-rowMeans(as.data.frame(lapply(dfComplete[,22:27], as.numeric))) reasonsUni<-rowMeans(as.data.frame(lapply(dfComplete[,28:35], as.numeric))) eduChoice<-rowMeans(as.data.frame(lapply(dfComplete[,36:45], as.numeric))) hsBehav<-rowMeans(as.data.frame(lapply(dfComplete[,46:57], as.numeric))) hsTrust<-rowMeans(as.data.frame(lapply(dfComplete[,58:62], as.numeric))) belongUncert<-rowMeans(as.data.frame(lapply(dfComplete[,63:68], as.numeric))) grit<-rowMeans(as.data.frame(lapply(dfComplete[,69:73], as.numeric))) growth<-rowMeans(as.data.frame(lapply(dfComplete[,74:76], as.numeric))) selfControl<-rowMeans(as.data.frame(lapply(dfComplete[,77:86], as.numeric))) personalTrait<-rowMeans(as.data.frame(lapply(dfComplete[,87:99], as.numeric))) acadAbility<-rowMeans(as.data.frame(lapply(dfComplete[,100:104], as.numeric))) studyHours<-rowMeans(as.data.frame(lapply(dfComplete[,105:109], as.numeric))) viewMedia<-rowMeans(as.data.frame(lapply(dfComplete[,110:123], as.numeric))) test<-cbind(demographics,attitudeEdu,reasonsUni,eduChoice,hsBehav,hsTrust,belongUncert,grit,growth,selfControl,personalTrait,acadAbility,studyHours,viewMedia) # Step-wise multiple linear regression by SSP category # Use new base model fit<-lm(as.numeric(examScores) ~ as.numeric(dfComplete$'mid-term') + as.numeric(dfComplete$'KhanCount') + demographics + attitudeEdu + reasonsUni + eduChoice + hsBehav + hsTrust + belongUncert + grit + growth + selfControl + personalTrait + acadAbility + studyHours + viewMedia,na.action=na.omit) step<-stepAIC(fit, direction="both") step$anova # display results summary(step) # Possibly try regsubsets() (below). # 4 significant category predictors (in addition to midterm and KhanCount) # Using AIC, t value and p value as the measure # personalTrait, hsTrust, reasonsUni, selfControl, # Construct new model based on the best 4 categories fit<-lm(as.numeric(examScores) ~ as.numeric(dfComplete$'mid-term') + as.numeric(dfComplete$'KhanCount') + personalTrait + hsTrust + reasonsUni + selfControl,na.action=na.omit) summary(fit) # Compare to new base model anova(base2,fit) # Significantly different than new base model. # Now to test whether by SSP category or SSP question is better... ################################################ # By SSP single question # Throwing an infinity error when using stepAIC() (with any direction). # This is because the number of X variables exceeds the number of observations (i.e., students). # Possibly use Lasso or regsubsets(). # Using regsubsets, for example, results in a different set of significant predictors. # Therefore, we have to manually test each SSP question. inputData<-as.data.frame(lapply(dfComplete[,c(13:123)], as.numeric)) # Remove columns containing all zeros #inputData<-inputData[,-(which(colSums(inputData) == 0))] #inputData<-inputData*100 # Possibly use regsubset() for model selection #best.subset <- regsubsets(as.numeric(examScores)~., inputData, nvmax=5, really.big=T) #best.subset.summary <- summary(best.subset) #best.subset.summary$outmat #best.subset.by.adjr2 <- which.max(best.subset.summary$adjr2) #best.subset.by.adjr2 #best.subset.by.cp <- which.min(best.subset.summary$cp) #best.subset.by.cp #best.subset.by.bic <- which.min(best.subset.summary$bic) #best.subset.by.bic # Manual model selection results<-numeric(111) pvalues<-numeric(111) for (i in 1:111){ pred<-as.numeric(inputData[,i]) # Add to Base2 model x<-lm(as.numeric(examScores) ~ as.numeric(dfComplete$'mid-term') + as.numeric(dfComplete$'KhanCount') + pred,na.action=na.omit) y<-summary(x)$adj.r.squared results[i]<-y xx<-summary(x) pvalues[i]<-pf(xx$fstatistic[1], xx$fstatistic[2], xx$fstatistic[3], lower.tail = FALSE) } # Find most significant SSP single questions x<-order(results, decreasing=TRUE) top<-which(results[x]>init_result) best<-x[top] # 42 SSP individual questions significantly improve the Base 2 model # Only the top 5 improve the model collectively # 82 22 107 60 48 (not used, see below) fit<-lm(as.numeric(examScores) ~ as.numeric(dfComplete$'mid-term') + as.numeric(dfComplete$'KhanCount') + as.numeric(dfComplete$"Q. 82 /0.09") + as.numeric(dfComplete$"Q. 22 /0.09") + as.numeric(dfComplete$"Q. 107 /0.09") + as.numeric(dfComplete$"Q. 60 /0.09") + as.numeric(dfComplete$"Q. 48 /0.09"),na.action=na.omit) summary(fit) # Compare to new Base 2 model anova(base2,fit) ################################################ # Compare SSP category model to SSP question model fit1<-lm(as.numeric(examScores) ~ as.numeric(dfComplete$'mid-term') + as.numeric(dfComplete$'KhanCount') + personalTrait + hsTrust + reasonsUni + selfControl,na.action=na.omit) fit2<-lm(as.numeric(examScores) ~ as.numeric(dfComplete$'mid-term') + as.numeric(dfComplete$'KhanCount') + as.numeric(dfComplete$"Q. 82 /0.09") + as.numeric(dfComplete$"Q. 22 /0.09") + as.numeric(dfComplete$"Q. 107 /0.09") + as.numeric(dfComplete$"Q. 60 /0.09") + as.numeric(dfComplete$"Q. 48 /0.09"),na.action=na.omit) summary(fit1) summary(fit2) # Anova probably not appropriate to compare these two models. #anova(fit1,fit2) # Model using SSP questions (fit2) is better when considering adjusted r-squared. ################################################ # Does adding Avg. Prog. Exp. improve the SSP questions model? # Yes, it does. fit<-lm(as.numeric(examScores) ~ as.numeric(dfComplete$'mid-term') + as.numeric(dfComplete$'KhanCount') + as.numeric(dfComplete$'Avg. Prog. Exp.') + as.numeric(dfComplete$"Q. 82 /0.09") + as.numeric(dfComplete$"Q. 22 /0.09") + as.numeric(dfComplete$"Q. 107 /0.09") + as.numeric(dfComplete$"Q. 60 /0.09") + as.numeric(dfComplete$"Q. 48 /0.09"),na.action=na.omit) summary(fit) # Does it change which SSP questions are now significant? # Yes, and the resulting model is better. # New base model - FE ~ MT + KhanCount + Avg. Prog. Exp. base3<-lm(as.numeric(examScores) ~ as.numeric(dfComplete$'mid-term') + as.numeric(dfComplete$'KhanCount') + as.numeric(dfComplete$'Avg. Prog. Exp.'),na.action=na.omit) ################################################ # Re-test SSP questions using new Base 3 model inputData<-as.data.frame(lapply(dfComplete[,c(13:123)], as.numeric)) # Manual model selection results<-numeric(111) pvalues<-numeric(111) for (i in 1:111){ pred<-as.numeric(inputData[,i]) # New Base3 model x<-lm(as.numeric(examScores) ~ as.numeric(dfComplete$'mid-term') + as.numeric(dfComplete$'KhanCount') + as.numeric(dfComplete$'Avg. Prog. Exp.') + pred,na.action=na.omit) y<-summary(x)$adj.r.squared results[i]<-y xx<-summary(x) pvalues[i]<-pf(xx$fstatistic[1], xx$fstatistic[2], xx$fstatistic[3], lower.tail = FALSE) } # Find most significant SSP single questions x<-order(results, decreasing=TRUE) top<-which(results[x]>init_result) best<-x[top] # New set of significant SSP questions # 82 60 50 22 107 # These correspond to SSP categories: personalTrait, growth, hsTrust, attitudeEdu and viewMedia. # This is the final and best model modelFinal<-lm(as.numeric(examScores) ~ as.numeric(dfComplete$'mid-term') + as.numeric(dfComplete$'KhanCount') + as.numeric(dfComplete$'Avg. Prog. Exp.') + as.numeric(dfComplete$"Q. 82 /0.09") + as.numeric(dfComplete$"Q. 60 /0.09") + as.numeric(dfComplete$"Q. 50 /0.09") + as.numeric(dfComplete$"Q. 22 /0.09") + as.numeric(dfComplete$"Q. 107 /0.09"),na.action=na.omit) summary(modelFinal) # Does this change when adding Peer Grade? # It does slightly improve (adjusted r-squared) but it # was not originally selected for using stepAIC(). ################################################ # Test to confirm the final model is appropriate. modelFinal<-lm(as.numeric(examScores) ~ as.numeric(dfComplete$'mid-term') + as.numeric(dfComplete$'KhanCount') + as.numeric(dfComplete$'Avg. Prog. Exp.') + as.numeric(dfComplete$"Q. 82 /0.09") + as.numeric(dfComplete$"Q. 60 /0.09") + as.numeric(dfComplete$"Q. 50 /0.09") + as.numeric(dfComplete$"Q. 22 /0.09") + as.numeric(dfComplete$"Q. 107 /0.09"),na.action=na.omit) summary(modelFinal) mean(modelFinal$residuals) plot(density(resid(modelFinal))) qqnorm(resid(modelFinal)) qqline(resid(modelFinal)) plot(modelFinal) # Perceived problem with Homoscedasticity # Looking at the Residuals vs Fitted plot, # the fitted line is not straight. # Automated test contradicts this, so okay. gvlma(modelFinal) # Manual check # Outliers c<-cooks.distance(modelFinal) plot(c, pch="*", cex=2, main="Influential Observations by Cooks distance") abline(h = 4*mean(c, na.rm=T), col="red") # No autocorrelation acf(modelFinal$residuals) # Correlation of variables to residuals cor.test(as.numeric(dfComplete$"Q. 107 /0.09"), modelFinal$residuals) #crPlots(fit) #ncvTest(fit) # Multicollinearity vif(modelFinal) sqrt(vif(modelFinal)) > 2 # Normaility of residuals qqPlot(modelFinal, main="QQ Plot") # sresid <- studres(modelFinal) hist(sresid, freq=FALSE, main="Distribution of Studentized Residuals") xfit<-seq(min(sresid),max(sresid),length=40) yfit<-dnorm(xfit) lines(xfit, yfit) ################################################ ################## PLOTTING #################### ################################################ # Final Model modelFinal<-lm(as.numeric(examScores) ~ as.numeric(dfComplete$'mid-term') + as.numeric(dfComplete$'KhanCount') + as.numeric(dfComplete$'Avg. Prog. Exp.') + as.numeric(dfComplete$"Q. 82 /0.09") + as.numeric(dfComplete$"Q. 60 /0.09") + as.numeric(dfComplete$"Q. 50 /0.09") + as.numeric(dfComplete$"Q. 22 /0.09") + as.numeric(dfComplete$"Q. 107 /0.09"),na.action=na.omit) summary(modelFinal) plot(modelFinal) # Correlation plot matrix inputData<-dfComplete[,c('mid-term','KhanCount','Avg. Prog. Exp.',"Q. 82 /0.09","Q. 60 /0.09","Q. 50 /0.09","Q. 22 /0.09","Q. 107 /0.09")] inputData<-cbind(examScores,inputData) test<-melt(inputData,id.vars='examScores') ggplot(test) + geom_jitter(aes(value,examScores, colour=variable),) + geom_smooth(aes(value,examScores, colour=variable), method=lm, se=FALSE) + facet_wrap(~variable,scales="free_x") + labs(x = "...", y = "...") # Scatter plot matrix #pairs(~as.numeric(dfComplete$'mid-term') + as.numeric(dfComplete$'KhanCount') + as.numeric(dfComplete$'Avg. Prog. Exp.'),data=dfComplete,main="") # Correlation plot matrix dta<-cbind(as.numeric(examScores),as.numeric(dfComplete$'mid-term'), as.numeric(dfComplete$'KhanCount'),as.numeric(dfComplete$'Avg. Prog. Exp.')) dta.r <- abs(cor(dta)) # correlations dta.col <- dmat.color(dta.r) # colors dta.o <- order.single(dta.r) cpairs(dta, dta.o, panel.colors=dta.col, gap=.5, main="..." ) # AAL and CPH linear models for FE ~ MT # Use all AAL and all CPH students inputData<-as.data.frame(cbind(as.numeric(dfAALMidGrades[,2]),as.numeric(dfAALMidGrades[,3]),as.numeric(dfAALMidGrades[,4]))) colnames(inputData)[1]<-"Education" colnames(inputData)[2]<-"Midterm" colnames(inputData)[3]<-"FinalExam" ggplot(inputData, aes(x=Midterm, y=FinalExam,group=1,color=Education)) + geom_point(shape=1) + #ylim(10.0, 90.0) + # set limits geom_smooth(method=lm) inputData<-as.data.frame(cbind(as.numeric(dfCPHMidGrades[,3]),as.numeric(dfCPHMidGrades[,4]))) colnames(inputData)[1]<-"Midterm" colnames(inputData)[2]<-"FinalExam" ggplot(inputData, aes(x=Midterm, y=FinalExam,group=1)) + geom_point(shape=1) + #xlim(0.0, 100.0) + # set limits geom_smooth(method=lm) # AAL students Final Exam against saNumComp and KhanCount by pass/fail # Not significant SAComp<-as.numeric(dfComplete$"saNumComp") FinalExam<-as.numeric(examScores) Passing<-as.factor(dfComplete$"pass/fail") ggplot(dfComplete, aes(x=SAComp, y=FinalExam,group=1,color=Passing)) + geom_point(shape=1) + #ylim(10.0, 90.0) + # set limits geom_smooth(method=lm) # Significant KhanAttempt<-as.numeric(dfComplete$"KhanCount") FinalExam<-as.numeric(examScores) Passing<-as.factor(dfComplete$"pass/fail") ggplot(dfComplete, aes(x=KhanAttempt, y=FinalExam,group=1,color=Passing)) + geom_point(shape=1) + #ylim(10.0, 90.0) + # set limits geom_smooth(method=lm)
/docs/GPRO/Linear_models_for_paper.R
no_license
bclavio/stats-on-grades
R
false
false
27,579
r
#require("RPostgreSQL") library(MASS) library(leaps) library(gvlma) library(car) library(ggplot2) library(gclus) ################################################ ################## LOAD DATA ################### ################################################ # Set working directory to the path containing Fall 2017 data sources. # Many of the required Fall 2017 files can be found at Z:\BNC\PBL development project\data\2018_SLERD_Paper_Analysis # Each semester, data from Khan Academy, Peer Grade and Moodle Activity must be pulled from their respoective places. SVNData<-if(grepl("BiancaClavio", getwd())){'C:/Users/BiancaClavio/Documents/SVN/01Projects/'} else {"/Users/Brian/PBL/Paper"} setwd(SVNData) # Load SSP scores dfSSPGrades<-read.csv("SSPgradesTestAAL 02-10.csv", header = TRUE, fill=TRUE, sep = ",", check.names=FALSE, stringsAsFactors=FALSE) # Load Midterm/Final grades dfAALMidGrades<-read.csv("15-02-2018_GPRO-overview-MT-exam.csv", header = TRUE, fill=TRUE, sep = ",", check.names=FALSE, stringsAsFactors=FALSE) # Load SA grades # contains Student id number for merging with dfSAGrades<-read.csv("15-02-2018_GPRO-gradebook.csv", header = TRUE, fill=TRUE, sep = ",", check.names=FALSE, stringsAsFactors=FALSE) # Load Peer Grade grades dfPeerGrade<-read.csv("15-02-2018_Peer_Grade_course_overall_stats_data.csv", header = TRUE, fill=TRUE, sep = ",", check.names=FALSE, stringsAsFactors=FALSE) # Load Khan Academy exercises (106 exercises) # Found on website under "Progress by Skill" # Waring: Comes from Khan with extra white spaces. dfKhan<-read.csv("15-02-2018_Khan_data.csv", header = TRUE, fill=TRUE, sep = ",", check.names=FALSE, stringsAsFactors=FALSE) # Load Khan student user name and email pairs # This file is only necessary if not all students use their student email address as # their Khan academy user name. If necessary, this file will need to be manually updated every semester. #dfKhanID<-read.csv("khan_id_new.csv", header = TRUE, fill=TRUE, sep = ",", check.names=FALSE, stringsAsFactors=FALSE) # Load merge file containing, student name, email address and ID # Manually constructed. This will be necessary each semester if, for example, # students use a Khan Academy user name which differs from their student name or email address. dfKhanID<-read.csv("all_merge.csv", header = TRUE, fill=TRUE, sep = ",", check.names=FALSE, stringsAsFactors=FALSE) # Load SSP questions (111 questions into 14 topic categories) questions<-read.csv("QuestionsOverview.csv", header = TRUE, fill=TRUE, sep = ",", check.names=FALSE, stringsAsFactors=FALSE) # 1-9, 10-15, 16-23, 24-33, 34-45, 46-50, 51-56, 57-61, 62-64, 65-74, 75-87, 88-92, 93-97, 98-111 # demographics,attitudeEdu,reasonsUni,eduChoice,hsBehav,hsTrust,belongUncert,grit,growth,selfControl,personalTrait,acadAbility,studyHours,viewMedia # Load Tutoring invitees dfInvitees<-read.csv("tutoringInvitees.csv", header = FALSE, fill=TRUE, sep = ",", check.names=FALSE, stringsAsFactors=FALSE) # Load Dropout data # Currently not enough dropouts for classification. #dfDropOuts<-read.csv("dropout-Feb2018-Q999.csv", header = TRUE, fill=TRUE, sep = ",", check.names=FALSE, stringsAsFactors=FALSE) #dfDropOuts<-dfDropOuts[dfDropOuts$'Status'!="active",] ################################################ # Load Moodle Activity Data (online) # Moodle Activity data is located in a PostgreSQL database that must be accessed # using a login code (provided below) from Hendrik and an AAU connection. # (see the next section for loading Moodle Activity Data while offline.) # For online access of the PostgreSQL database through R: # # create a connection to the database server # load the PostgreSQL driver # drv <- dbDriver("PostgreSQL") # # create a connection to the PostgreSQL database (must be on AAU network) # activityDataCon <- dbConnect(drv, dbname = "activity_data", # host = "md-db-test.moodle.aau.dk", port = 5432, # user = "hk", password = "=cD58BEtUE") # # check for the existence of tables # dbExistsTable(activityDataCon, "analyse_mdl_course") # dbExistsTable(activityDataCon, "analyse_mdl_logstore_standard_log") # dbExistsTable(activityDataCon, "analyse_mdl_user") # # # query the data from PostgreSQL # dfCourseData <- dbGetQuery(activityDataCon, "SELECT * from analyse_mdl_course") # dfLogData <- dbGetQuery(activityDataCon, "SELECT * from analyse_mdl_logstore_standard_log") # dfUserData <- dbGetQuery(activityDataCon, "SELECT * from analyse_mdl_user") ################################################ # Load Moodle Activity data (offline) # Warning: No headers # Second column of moodleUserData (Student ID) is used to match SA to Moodle activity data #moodleCourseData<-read.csv("analyse_mdl_course.csv", header = FALSE, fill=TRUE, sep = ",", check.names=FALSE, stringsAsFactors=FALSE) #moodleLogData<-read.csv("analyse_mdl_logstore_standard_log.csv", header = FALSE, fill=TRUE, sep = ",", check.names=FALSE, stringsAsFactors=FALSE) #moodleUserData<-read.csv("analyse_mdl_user.csv", header = FALSE, fill=TRUE, sep = ",", check.names=FALSE, stringsAsFactors=FALSE) # Have not found a way yet to link Moodle activity to all other data, # so it will be excluded from this analysis. ################################################ ################# CLEAN DATA ################### ################################################ # Clean data sources (i.e., remove incomplete entries or irrelevant columns and reshape) # Retain "Email address" as student ID used for merging # # SSP # Remove students who did not finish the survey dfSSPGrades<-dfSSPGrades[(dfSSPGrades$"State"=="Finished"), ] # Rename column colnames(dfSSPGrades)[10] <- "SSP score" # Shorten using all SSP questions alldfSSPGrades<-dfSSPGrades[,c(5,10:121)] # Midterm grades # Name columns dfCPHMidGrades<-dfAALMidGrades[(dfAALMidGrades$"education"=="CPH"), ] dfAALMidGrades<-dfAALMidGrades[(dfAALMidGrades$"education"!="CPH"), ] # Shorten dfCPHMidGrades<-dfCPHMidGrades[,c(1,2,3,5)] dfAALMidGrades<-dfAALMidGrades[,c(1,2,3,5)] # Make "education" predictors/groups # PDP students get removed later because they did not do SSP index<-dfAALMidGrades$"education" == "MEA" dfAALMidGrades$"education"[index]<-1 index<-dfAALMidGrades$"education" == "PDP" dfAALMidGrades$"education"[index]<-0 # Remove AAL invalid entries loc <- apply(dfAALMidGrades[,c(3,4)],1,function(row) "-" %in% row) dfAALMidGrades<-dfAALMidGrades[!loc,] loc <- apply(dfAALMidGrades[,c(3,4)],1,function(row) "" %in% row) dfAALMidGrades<-dfAALMidGrades[!loc,] # Remove CPH invalid entries loc <- apply(dfCPHMidGrades[,c(3,4)],1,function(row) "-" %in% row) dfCPHMidGrades<-dfCPHMidGrades[!loc,] loc <- apply(dfCPHMidGrades[,c(3,4)],1,function(row) "" %in% row) dfCPHMidGrades<-dfCPHMidGrades[!loc,] # Rename first column colnames(dfAALMidGrades)[1] <- "ID number" colnames(dfCPHMidGrades)[1] <- "ID number" # SA # Subset only grades saTest<-dfSAGrades[,c(7,8,9,10,11,12,13,15,16,17,18,19)] # Make non-attempts NA saTest[saTest=="-"] <- NA # Compute SA total average saTest<-as.data.frame(lapply(saTest, as.numeric)) saRowAvg<-rowMeans(saTest, na.rm = TRUE, dims = 1) # Create a column of SA attempts saTest[!is.na(saTest)] <- 1 saTest[is.na(saTest)] <- 0 saNumComp<-rowSums(as.data.frame(lapply(saTest,as.numeric))) # Subset all relevant columns dfSAGrades<-dfSAGrades[,c(6,7,8,9,10,11,12,13,15,16,17,18,19)] # Add column of SA attempts dfSAGrades<-cbind(dfSAGrades,saRowAvg,saNumComp) # Remove tmp user dfSAGrades<-dfSAGrades[!grepl("tmpuser",dfSAGrades$'Email address'),] # Subset only total average and number of attempts # Not doing this would provide more variables (i.e., grades) but would punish non-attempts with zeros. # Because SA was not mandatory, we use number of attempts as a predictor instead of giving zeros for non-attempts. dfSAGrades<-dfSAGrades[,c(1,14,15)] # Give students who did not attempt SA a total average of zero. # This similarly punishes students who did not do SA (might be students who are re-taking exam?) is.nan.data.frame <- function(x) do.call(cbind, lapply(x, is.nan)) dfSAGrades[is.nan(dfSAGrades)] <- 0 # Peer Grade # By student email and shorten (Peer Grade changed column name of "hand-in score" to "Submission score") # Mandatory assignments AALpeerGrade<-dfPeerGrade[,c('student_email','Submission score','feedback score','combined score')] # change column name to match others colnames(AALpeerGrade)[1] <- c("Email address") # Khan Academy #Sys.setlocale('LC_ALL','C') # required for reading non-unicode characters # Format Khan Academy data from Long to Wide and convert student user ID occurrences # in "Not Started", "Started" and "Completed" columns to numerical 0, 1 and 2, respectively. # For each column, split list of student user ID names by hidden carriage return inserted from Khan Academy # Not started column s <- strsplit(dfKhan$"Not Started", split = "\n") x<-data.frame(V1 = rep(dfKhan$"Exercise", sapply(s, length)), V2 = unlist(s)) x$"Not Started" <- rep(0,nrow(x)) colnames(x) <- c("Exercise", "Student Name","Completed") # Started column s <- strsplit(dfKhan$"Started", split = "\n") y<-data.frame(V1 = rep(dfKhan$"Exercise", sapply(s, length)), V2 = unlist(s)) y$"Started" <- rep(1,nrow(y)) colnames(y) <- c("Exercise", "Student Name","Completed") # Completed column s <- strsplit(dfKhan$"Completed", split = "\n") z<-data.frame(V1 = rep(dfKhan$"Exercise", sapply(s, length)), V2 = unlist(s)) z$"Completed" <- rep(2,nrow(z)) colnames(z) <- c("Exercise", "Student Name", "Completed") # Join columns and reshape to wide format joinedKhan<-rbind(x,y,z) joinedKhan<-reshape(joinedKhan, idvar = "Student Name", timevar = "Exercise", direction = "wide") # Remove duplicates # Not sure how a student user name could occur more than once but it did in Fall 2017 joinedKhan<-joinedKhan[!duplicated(joinedKhan[,1]),] # Remove Teachers # In subsequent semesters this may or may not be necessary. joinedKhan<-joinedKhan[!grepl("hendrik",joinedKhan$'Student Name'),] # 106 Khan assignments # Count number of completed Khan assignments for each student and store in "KhanCount" column # Like SA, Khan Academny assignments were nto mandatory so we consider number of attempts instead of assigning zeros to non-attempts. joinedKhan$"KhanCount" <- apply(joinedKhan, 1, function(x) sum(x==2)) # Tutoring invitees # The students below atended at least one tutoring session. dfAttendees = data.frame(c('vroua17@student.aau.dk','jlnc17@student.aau.dk','avafai17@student.aau.dk','nneuma17@student.aau.dk','jsimon16@student.aau.dk','fnje17@student.aau.dk','mepo17@student.aau.dk','evalbe17@student.aau.dk','nrux17@student.aau.dk')) colnames(dfAttendees) <- c("Email address") ################################################ # Merge all data sources created above # SA and Midterm saTest<-merge(dfKhanID,dfSAGrades,by="Email address") # 11 students or staff not considered (check with command below) # students were not on the list or did not take the final exam (drop outs?) # 99 total AAL students who did SA and Midterm dfComplete<-merge(saTest,dfAALMidGrades,by="ID number") # Midterm and Khan dfComplete<-merge(dfComplete,joinedKhan,by="Student Name",all.x=TRUE) # Shorten dfComplete<-dfComplete[,c(1:8,115)] # Some students did not create a Khan Academy account (they will not be in the Khan database) # so replace those students who have NA in KhanCount with zeros # These student get removed later because they did not do Peer Grade dfComplete[is.na(dfComplete)]<-0 # Peer Grade dfComplete<-merge(dfComplete,AALpeerGrade,by='Email address',all.x=TRUE) # Optional: remove students retaking the course. Peer Grade was not required for # these students and none of them did it dfComplete<-dfComplete[complete.cases(dfComplete), ] # If we don't delete these students above, we can replace their PG scores with zeros. #dfComplete[is.na(dfComplete)]<-0 # Otherwise, all students are now those not retaking the course. # SSP dfComplete<-merge(dfComplete,alldfSSPGrades,by='Email address',all.x=TRUE) # Remove all incomplete entries leaves only 72 students # This removes all PDP students dfComplete<-dfComplete[complete.cases(dfComplete), ] # Alternatively, we can zero all NAs and consider all 99 students who took the final exam #dfComplete[is.na(dfComplete)]<-0 ################################################ # Add factors for pass or fail Final exam # Can be used for plotting e.g., how often passing students attempted Khan Academy. dfComplete$"pass/fail"[dfComplete$"Exam"<64] <- 0 dfComplete$"pass/fail"[dfComplete$"Exam">=64] <- 1 # An additional predictor of programming experience was found to be significant. # SSP Questions 33 and 78 avgProgExp<-as.data.frame(cbind(dfComplete$"Q. 33 /0.09",dfComplete$"Q. 78 /0.09")) avgProgExp<-rowMeans(as.data.frame(lapply(avgProgExp,as.numeric))) dfComplete[, "Avg. Prog. Exp."] <- avgProgExp # Add column containing tutoring invitees and attendees # Can be used for plotting. # 0 = not invited, 1 = invited, 2 = invited and attended dfComplete$"Tutoring"<-as.numeric(dfComplete$"Email address" %in% dfInvitees[,]) dfComplete$"Tutoring"[dfComplete$"Email address" %in% dfAttendees[,]]<-2 # Final clean # Non attempts in SSP set to zero dfComplete[is.na(dfComplete)]<-0 dfComplete[dfComplete=='-']<-0 ################################################ ################## ANALYSIS #################### ################################################ # Linear model: Final exam ~ Mid term grade is used as the base model # The adjusted r-squared value in the base model is compared to subsequent # models to determine any improvement. # # Extract Final exam drops <- c("Exam") examScores<-dfComplete[,drops] dfComplete<-dfComplete[ , !(names(dfComplete) %in% drops)] ################################################ # Initial Base model - FE ~ MT base1<-lm(as.numeric(examScores) ~ as.numeric(dfComplete$'mid-term'),na.action=na.omit) # base model adjusted r-squared value init_result<-summary(base1)$adj.r.squared ################################################ # By predictors excluding SSP single questions inputData<-as.data.frame(lapply(dfComplete[,c(4,5,8,9,12)], as.numeric)) # Step-wise multiple linear regression fit<-lm(as.numeric(examScores) ~ as.numeric(dfComplete$'mid-term') + .,data=inputData,na.action=na.omit) step<-stepAIC(fit, direction="both") step$anova # display results summary(step) # Best model is the addition of KhanCount to the base model # Using AIC, t value and p value as the measure # Notable absences are Peer Grade, saNumComp, saRowAvg. # Compare best model to base fit<-lm(as.numeric(examScores) ~ as.numeric(dfComplete$'mid-term') + as.numeric(dfComplete$'KhanCount'),na.action=na.omit) summary(fit) anova(base1,fit) # Significantly different than base model # This becomes our new base model. ################################################ # New Base model - FE ~ MT + KhanCount base2<-lm(as.numeric(examScores) ~ as.numeric(dfComplete$'mid-term') + as.numeric(dfComplete$'KhanCount'),na.action=na.omit) # base model adjusted r-squared value init_result<-summary(base2)$adj.r.squared ################################################ # By SSP category # Category question ranges # 1-9, 10-15, 16-23, 24-33, 34-45, 46-50, 51-56, 57-61, 62-64, 65-74, 75-87, 88-92, 93-97, 98-111 # Column ranges in "dfComplete" for the 14 SSP categories # 13-21, 22-27, 28-35, 36-45, 46-57, 58-62, 63-68, 69-73, 74-76, 77-86, 87-99, 100-104, 105-109, 110-123 demographics<-rowMeans(as.data.frame(lapply(dfComplete[,13:21], as.numeric))) attitudeEdu<-rowMeans(as.data.frame(lapply(dfComplete[,22:27], as.numeric))) reasonsUni<-rowMeans(as.data.frame(lapply(dfComplete[,28:35], as.numeric))) eduChoice<-rowMeans(as.data.frame(lapply(dfComplete[,36:45], as.numeric))) hsBehav<-rowMeans(as.data.frame(lapply(dfComplete[,46:57], as.numeric))) hsTrust<-rowMeans(as.data.frame(lapply(dfComplete[,58:62], as.numeric))) belongUncert<-rowMeans(as.data.frame(lapply(dfComplete[,63:68], as.numeric))) grit<-rowMeans(as.data.frame(lapply(dfComplete[,69:73], as.numeric))) growth<-rowMeans(as.data.frame(lapply(dfComplete[,74:76], as.numeric))) selfControl<-rowMeans(as.data.frame(lapply(dfComplete[,77:86], as.numeric))) personalTrait<-rowMeans(as.data.frame(lapply(dfComplete[,87:99], as.numeric))) acadAbility<-rowMeans(as.data.frame(lapply(dfComplete[,100:104], as.numeric))) studyHours<-rowMeans(as.data.frame(lapply(dfComplete[,105:109], as.numeric))) viewMedia<-rowMeans(as.data.frame(lapply(dfComplete[,110:123], as.numeric))) test<-cbind(demographics,attitudeEdu,reasonsUni,eduChoice,hsBehav,hsTrust,belongUncert,grit,growth,selfControl,personalTrait,acadAbility,studyHours,viewMedia) # Step-wise multiple linear regression by SSP category # Use new base model fit<-lm(as.numeric(examScores) ~ as.numeric(dfComplete$'mid-term') + as.numeric(dfComplete$'KhanCount') + demographics + attitudeEdu + reasonsUni + eduChoice + hsBehav + hsTrust + belongUncert + grit + growth + selfControl + personalTrait + acadAbility + studyHours + viewMedia,na.action=na.omit) step<-stepAIC(fit, direction="both") step$anova # display results summary(step) # Possibly try regsubsets() (below). # 4 significant category predictors (in addition to midterm and KhanCount) # Using AIC, t value and p value as the measure # personalTrait, hsTrust, reasonsUni, selfControl, # Construct new model based on the best 4 categories fit<-lm(as.numeric(examScores) ~ as.numeric(dfComplete$'mid-term') + as.numeric(dfComplete$'KhanCount') + personalTrait + hsTrust + reasonsUni + selfControl,na.action=na.omit) summary(fit) # Compare to new base model anova(base2,fit) # Significantly different than new base model. # Now to test whether by SSP category or SSP question is better... ################################################ # By SSP single question # Throwing an infinity error when using stepAIC() (with any direction). # This is because the number of X variables exceeds the number of observations (i.e., students). # Possibly use Lasso or regsubsets(). # Using regsubsets, for example, results in a different set of significant predictors. # Therefore, we have to manually test each SSP question. inputData<-as.data.frame(lapply(dfComplete[,c(13:123)], as.numeric)) # Remove columns containing all zeros #inputData<-inputData[,-(which(colSums(inputData) == 0))] #inputData<-inputData*100 # Possibly use regsubset() for model selection #best.subset <- regsubsets(as.numeric(examScores)~., inputData, nvmax=5, really.big=T) #best.subset.summary <- summary(best.subset) #best.subset.summary$outmat #best.subset.by.adjr2 <- which.max(best.subset.summary$adjr2) #best.subset.by.adjr2 #best.subset.by.cp <- which.min(best.subset.summary$cp) #best.subset.by.cp #best.subset.by.bic <- which.min(best.subset.summary$bic) #best.subset.by.bic # Manual model selection results<-numeric(111) pvalues<-numeric(111) for (i in 1:111){ pred<-as.numeric(inputData[,i]) # Add to Base2 model x<-lm(as.numeric(examScores) ~ as.numeric(dfComplete$'mid-term') + as.numeric(dfComplete$'KhanCount') + pred,na.action=na.omit) y<-summary(x)$adj.r.squared results[i]<-y xx<-summary(x) pvalues[i]<-pf(xx$fstatistic[1], xx$fstatistic[2], xx$fstatistic[3], lower.tail = FALSE) } # Find most significant SSP single questions x<-order(results, decreasing=TRUE) top<-which(results[x]>init_result) best<-x[top] # 42 SSP individual questions significantly improve the Base 2 model # Only the top 5 improve the model collectively # 82 22 107 60 48 (not used, see below) fit<-lm(as.numeric(examScores) ~ as.numeric(dfComplete$'mid-term') + as.numeric(dfComplete$'KhanCount') + as.numeric(dfComplete$"Q. 82 /0.09") + as.numeric(dfComplete$"Q. 22 /0.09") + as.numeric(dfComplete$"Q. 107 /0.09") + as.numeric(dfComplete$"Q. 60 /0.09") + as.numeric(dfComplete$"Q. 48 /0.09"),na.action=na.omit) summary(fit) # Compare to new Base 2 model anova(base2,fit) ################################################ # Compare SSP category model to SSP question model fit1<-lm(as.numeric(examScores) ~ as.numeric(dfComplete$'mid-term') + as.numeric(dfComplete$'KhanCount') + personalTrait + hsTrust + reasonsUni + selfControl,na.action=na.omit) fit2<-lm(as.numeric(examScores) ~ as.numeric(dfComplete$'mid-term') + as.numeric(dfComplete$'KhanCount') + as.numeric(dfComplete$"Q. 82 /0.09") + as.numeric(dfComplete$"Q. 22 /0.09") + as.numeric(dfComplete$"Q. 107 /0.09") + as.numeric(dfComplete$"Q. 60 /0.09") + as.numeric(dfComplete$"Q. 48 /0.09"),na.action=na.omit) summary(fit1) summary(fit2) # Anova probably not appropriate to compare these two models. #anova(fit1,fit2) # Model using SSP questions (fit2) is better when considering adjusted r-squared. ################################################ # Does adding Avg. Prog. Exp. improve the SSP questions model? # Yes, it does. fit<-lm(as.numeric(examScores) ~ as.numeric(dfComplete$'mid-term') + as.numeric(dfComplete$'KhanCount') + as.numeric(dfComplete$'Avg. Prog. Exp.') + as.numeric(dfComplete$"Q. 82 /0.09") + as.numeric(dfComplete$"Q. 22 /0.09") + as.numeric(dfComplete$"Q. 107 /0.09") + as.numeric(dfComplete$"Q. 60 /0.09") + as.numeric(dfComplete$"Q. 48 /0.09"),na.action=na.omit) summary(fit) # Does it change which SSP questions are now significant? # Yes, and the resulting model is better. # New base model - FE ~ MT + KhanCount + Avg. Prog. Exp. base3<-lm(as.numeric(examScores) ~ as.numeric(dfComplete$'mid-term') + as.numeric(dfComplete$'KhanCount') + as.numeric(dfComplete$'Avg. Prog. Exp.'),na.action=na.omit) ################################################ # Re-test SSP questions using new Base 3 model inputData<-as.data.frame(lapply(dfComplete[,c(13:123)], as.numeric)) # Manual model selection results<-numeric(111) pvalues<-numeric(111) for (i in 1:111){ pred<-as.numeric(inputData[,i]) # New Base3 model x<-lm(as.numeric(examScores) ~ as.numeric(dfComplete$'mid-term') + as.numeric(dfComplete$'KhanCount') + as.numeric(dfComplete$'Avg. Prog. Exp.') + pred,na.action=na.omit) y<-summary(x)$adj.r.squared results[i]<-y xx<-summary(x) pvalues[i]<-pf(xx$fstatistic[1], xx$fstatistic[2], xx$fstatistic[3], lower.tail = FALSE) } # Find most significant SSP single questions x<-order(results, decreasing=TRUE) top<-which(results[x]>init_result) best<-x[top] # New set of significant SSP questions # 82 60 50 22 107 # These correspond to SSP categories: personalTrait, growth, hsTrust, attitudeEdu and viewMedia. # This is the final and best model modelFinal<-lm(as.numeric(examScores) ~ as.numeric(dfComplete$'mid-term') + as.numeric(dfComplete$'KhanCount') + as.numeric(dfComplete$'Avg. Prog. Exp.') + as.numeric(dfComplete$"Q. 82 /0.09") + as.numeric(dfComplete$"Q. 60 /0.09") + as.numeric(dfComplete$"Q. 50 /0.09") + as.numeric(dfComplete$"Q. 22 /0.09") + as.numeric(dfComplete$"Q. 107 /0.09"),na.action=na.omit) summary(modelFinal) # Does this change when adding Peer Grade? # It does slightly improve (adjusted r-squared) but it # was not originally selected for using stepAIC(). ################################################ # Test to confirm the final model is appropriate. modelFinal<-lm(as.numeric(examScores) ~ as.numeric(dfComplete$'mid-term') + as.numeric(dfComplete$'KhanCount') + as.numeric(dfComplete$'Avg. Prog. Exp.') + as.numeric(dfComplete$"Q. 82 /0.09") + as.numeric(dfComplete$"Q. 60 /0.09") + as.numeric(dfComplete$"Q. 50 /0.09") + as.numeric(dfComplete$"Q. 22 /0.09") + as.numeric(dfComplete$"Q. 107 /0.09"),na.action=na.omit) summary(modelFinal) mean(modelFinal$residuals) plot(density(resid(modelFinal))) qqnorm(resid(modelFinal)) qqline(resid(modelFinal)) plot(modelFinal) # Perceived problem with Homoscedasticity # Looking at the Residuals vs Fitted plot, # the fitted line is not straight. # Automated test contradicts this, so okay. gvlma(modelFinal) # Manual check # Outliers c<-cooks.distance(modelFinal) plot(c, pch="*", cex=2, main="Influential Observations by Cooks distance") abline(h = 4*mean(c, na.rm=T), col="red") # No autocorrelation acf(modelFinal$residuals) # Correlation of variables to residuals cor.test(as.numeric(dfComplete$"Q. 107 /0.09"), modelFinal$residuals) #crPlots(fit) #ncvTest(fit) # Multicollinearity vif(modelFinal) sqrt(vif(modelFinal)) > 2 # Normaility of residuals qqPlot(modelFinal, main="QQ Plot") # sresid <- studres(modelFinal) hist(sresid, freq=FALSE, main="Distribution of Studentized Residuals") xfit<-seq(min(sresid),max(sresid),length=40) yfit<-dnorm(xfit) lines(xfit, yfit) ################################################ ################## PLOTTING #################### ################################################ # Final Model modelFinal<-lm(as.numeric(examScores) ~ as.numeric(dfComplete$'mid-term') + as.numeric(dfComplete$'KhanCount') + as.numeric(dfComplete$'Avg. Prog. Exp.') + as.numeric(dfComplete$"Q. 82 /0.09") + as.numeric(dfComplete$"Q. 60 /0.09") + as.numeric(dfComplete$"Q. 50 /0.09") + as.numeric(dfComplete$"Q. 22 /0.09") + as.numeric(dfComplete$"Q. 107 /0.09"),na.action=na.omit) summary(modelFinal) plot(modelFinal) # Correlation plot matrix inputData<-dfComplete[,c('mid-term','KhanCount','Avg. Prog. Exp.',"Q. 82 /0.09","Q. 60 /0.09","Q. 50 /0.09","Q. 22 /0.09","Q. 107 /0.09")] inputData<-cbind(examScores,inputData) test<-melt(inputData,id.vars='examScores') ggplot(test) + geom_jitter(aes(value,examScores, colour=variable),) + geom_smooth(aes(value,examScores, colour=variable), method=lm, se=FALSE) + facet_wrap(~variable,scales="free_x") + labs(x = "...", y = "...") # Scatter plot matrix #pairs(~as.numeric(dfComplete$'mid-term') + as.numeric(dfComplete$'KhanCount') + as.numeric(dfComplete$'Avg. Prog. Exp.'),data=dfComplete,main="") # Correlation plot matrix dta<-cbind(as.numeric(examScores),as.numeric(dfComplete$'mid-term'), as.numeric(dfComplete$'KhanCount'),as.numeric(dfComplete$'Avg. Prog. Exp.')) dta.r <- abs(cor(dta)) # correlations dta.col <- dmat.color(dta.r) # colors dta.o <- order.single(dta.r) cpairs(dta, dta.o, panel.colors=dta.col, gap=.5, main="..." ) # AAL and CPH linear models for FE ~ MT # Use all AAL and all CPH students inputData<-as.data.frame(cbind(as.numeric(dfAALMidGrades[,2]),as.numeric(dfAALMidGrades[,3]),as.numeric(dfAALMidGrades[,4]))) colnames(inputData)[1]<-"Education" colnames(inputData)[2]<-"Midterm" colnames(inputData)[3]<-"FinalExam" ggplot(inputData, aes(x=Midterm, y=FinalExam,group=1,color=Education)) + geom_point(shape=1) + #ylim(10.0, 90.0) + # set limits geom_smooth(method=lm) inputData<-as.data.frame(cbind(as.numeric(dfCPHMidGrades[,3]),as.numeric(dfCPHMidGrades[,4]))) colnames(inputData)[1]<-"Midterm" colnames(inputData)[2]<-"FinalExam" ggplot(inputData, aes(x=Midterm, y=FinalExam,group=1)) + geom_point(shape=1) + #xlim(0.0, 100.0) + # set limits geom_smooth(method=lm) # AAL students Final Exam against saNumComp and KhanCount by pass/fail # Not significant SAComp<-as.numeric(dfComplete$"saNumComp") FinalExam<-as.numeric(examScores) Passing<-as.factor(dfComplete$"pass/fail") ggplot(dfComplete, aes(x=SAComp, y=FinalExam,group=1,color=Passing)) + geom_point(shape=1) + #ylim(10.0, 90.0) + # set limits geom_smooth(method=lm) # Significant KhanAttempt<-as.numeric(dfComplete$"KhanCount") FinalExam<-as.numeric(examScores) Passing<-as.factor(dfComplete$"pass/fail") ggplot(dfComplete, aes(x=KhanAttempt, y=FinalExam,group=1,color=Passing)) + geom_point(shape=1) + #ylim(10.0, 90.0) + # set limits geom_smooth(method=lm)
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/search_shards.R \name{search_shards} \alias{search_shards} \title{Search shards.} \usage{ search_shards(index = NULL, raw = FALSE, routing = NULL, preference = NULL, local = NULL, ...) } \arguments{ \item{index}{One or more indeces} \item{raw}{If \code{TRUE} (default), data is parsed to list. If \code{FALSE}, then raw JSON} \item{routing}{A character vector of routing values to take into account when determining which shards a request would be executed against.} \item{preference}{Controls a preference of which shard replicas to execute the search request on. By default, the operation is randomized between the shard replicas. See \link{preference} for a list of all acceptable values.} \item{local}{(logical) Whether to read the cluster state locally in order to determine where shards are allocated instead of using the Master node's cluster state.} \item{...}{Curl args passed on to \code{\link[httr:GET]{httr::GET()}}} } \description{ Search shards. } \examples{ \dontrun{ search_shards(index = "plos") search_shards(index = c("plos","gbif")) search_shards(index = "plos", preference='_primary') search_shards(index = "plos", preference='_shards:2') library('httr') search_shards(index = "plos", config=verbose()) } } \references{ \url{https://www.elastic.co/guide/en/elasticsearch/reference/current/search-shards.html} }
/man/search_shards.Rd
permissive
dpmccabe/elastic
R
false
true
1,418
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/search_shards.R \name{search_shards} \alias{search_shards} \title{Search shards.} \usage{ search_shards(index = NULL, raw = FALSE, routing = NULL, preference = NULL, local = NULL, ...) } \arguments{ \item{index}{One or more indeces} \item{raw}{If \code{TRUE} (default), data is parsed to list. If \code{FALSE}, then raw JSON} \item{routing}{A character vector of routing values to take into account when determining which shards a request would be executed against.} \item{preference}{Controls a preference of which shard replicas to execute the search request on. By default, the operation is randomized between the shard replicas. See \link{preference} for a list of all acceptable values.} \item{local}{(logical) Whether to read the cluster state locally in order to determine where shards are allocated instead of using the Master node's cluster state.} \item{...}{Curl args passed on to \code{\link[httr:GET]{httr::GET()}}} } \description{ Search shards. } \examples{ \dontrun{ search_shards(index = "plos") search_shards(index = c("plos","gbif")) search_shards(index = "plos", preference='_primary') search_shards(index = "plos", preference='_shards:2') library('httr') search_shards(index = "plos", config=verbose()) } } \references{ \url{https://www.elastic.co/guide/en/elasticsearch/reference/current/search-shards.html} }
id <- 1 lat <- 0 long <- 0 time <- 0 currentpos <- 0 mincurr <- sample(1:40,1) minnext <- 0 maxcurr <- sample(40:80,1) maxnext <- 0 #df[i,1] <- id #df[i,2] <- lat #df[i,3] <- long #df[i,4] <- time #df[i,6] <- mincurr #df[i,7] <- minnext #df[i,8] <- maxcurr #df[i,9] <- maxnext #df[i,10] <- min #df[i,11] <- max df <- data.frame(id,lat,long,time,mincurr,minnext,maxcurr,maxnext) colnames(df) <- c("id", "lat","long","time","mincurr","minnext","maxcurr","maxnext","min","max") values <- c("high","low","medium") Long <- c(40.79798, 40.7942, 40.79166, 40.78526, 40.78199, 40.77946, 40.7762, 40.76822, 40.76692, 40.76573, 40.76512, 40.76741, 40.77245, 40.77701, 40.78409, 40.78792, 40.79174, 40.79686, 40.79821, 40.7994, 40.76683, 40.77026, 40.77911, 40.779, 40.78335, 40.79039, 40.79525) Lat <- c(-73.96003, -73.96282, -73.96468, -73.96928, -73.97167, -73.97349, -73.9759, -73.9814, -73.97901, -73.97618, -73.97302, -73.97076, -73.96702, -73.96378, -73.95857, -73.95579, -73.95299, -73.94968, -73.95251, -73.95538, -73.9721, -73.97524, -73.96906, -73.96238 ,-73.96397, -73.95983, -73.95562) # midnight to 5am for (i in 1:1440){ n <- sample(1:27,1) v <- sample(1:3,1) v <- values[v] if (i < 300){ id <- sample(1:65,1) lat <- Long[n] long <- Lat[n] time <- i currentpos <- (i/(i+1)) mincurr <- sample(1:40,1) minnext <- 0 maxcurr <- sample(40:80,1) maxnext <- 0 min <- 0 max <- 0 count <- sample(1:80,1) df[i,1] <- id df[i,2] <- lat df[i,3] <- long df[i,4] <- time df[i,5] <- mincurr df[i,6] <- minnext df[i,7] <- maxcurr df[i,8] <- maxnext } else if(i > 300 && i < 601){ id <- sample(1:65,1) lat <- Long[n] long <- Lat[n] time <- i currentpos <- (i/(i+1)) if (v == "low"){ mincurr <- sample(20:40,1) minnext <- 0 maxcurr <- sample(60:80,1) maxnext <- 0 min <- 0 max <- 0 }else if(v == "medium"){ mincurr <- sample(60:40,1) minnext <- 0 maxcurr <- sample(80:120,1) maxnext <- 0 min <- 0 max <- 0 }else{ mincurr <- sample(80:100,1) minnext <- 0 maxcurr <- sample(100:200,1) maxnext <- 0 min <- 0 max <- 0} #count <- sample(1:80,1) df[i,1] <- id df[i,2] <- lat df[i,3] <- long df[i,4] <- time df[i,5] <- mincurr df[i,6] <- minnext df[i,7] <- maxcurr df[i,8] <- maxnext } else if(i > 601 && i < 841){ id <- sample(1:65,1) lat <- Long[n] long <- Lat[n] time <- i currentpos <- (i/(i+1)) if (v == "low"){ mincurr <- sample(20:40,1) minnext <- 0 maxcurr <- sample(60:80,1) maxnext <- 0 min <- 0 max <- 0 }else if(v == "medium"){ mincurr <- sample(60:40,1) minnext <- 0 maxcurr <- sample(80:120,1) maxnext <- 0 min <- 0 max <- 0 }else{ mincurr <- sample(80:100,1) minnext <- 0 maxcurr <- sample(100:200,1) maxnext <- 0 min <- 0 max <- 0} #count <- sample(1:80,1) df[i,1] <- id df[i,2] <- lat df[i,3] <- long df[i,4] <- time df[i,5] <- mincurr df[i,6] <- minnext df[i,7] <- maxcurr df[i,8] <- maxnext } else if(i > 841 && i < 1141){ id <- sample(1:65,1) lat <- Long[n] long <- Lat[n] time <- i currentpos <- (i/(i+1)) if (v == "low"){ mincurr <- sample(20:40,1) minnext <- 0 maxcurr <- sample(60:80,1) maxnext <- 0 min <- 0 max <- 0 }else if(v == "medium"){ mincurr <- sample(60:40,1) minnext <- 0 maxcurr <- sample(80:120,1) maxnext <- 0 min <- 0 max <- 0 }else{ mincurr <- sample(80:100,1) minnext <- 0 maxcurr <- sample(100:200,1) maxnext <- 0 min <- 0 max <- 0} #count <- sample(1:80,1) df[i,1] <- id df[i,2] <- lat df[i,3] <- long df[i,4] <- time df[i,5] <- mincurr df[i,6] <- minnext df[i,7] <- maxcurr df[i,8] <- maxnext } else if(i <= 1400){ id <- sample(1:65,1) lat <- Long[n] long <- Lat[n] time <- i currentpos <- (i/(i+1)) mincurr <- sample(1:40,1) minnext <- 0 maxcurr <- sample(40:80,1) maxnext <- 0 min <- 0 max <- 0 #count <- sample(1:80,1) df[i,1] <- id df[i,2] <- lat df[i,3] <- long df[i,4] <- time df[i,5] <- mincurr df[i,6] <- minnext df[i,7] <- maxcurr df[i,8] <- maxnext } } for (i in 1:1439){ currentpos <- (i/(i+1)) df[i,6] <- abs((df[i,5] - df[i+1,5]))*currentpos df[i+1,5] <- abs((df[i,5] - df[i+1,5]))*currentpos df[i,8] <- abs((df[i,7] - df[i+1,7]))*currentpos df[i+1,7] <- abs((df[i,7] - df[i+1,7]))*currentpos } library(ggplot2) count <- df$min ggplot(data=df, aes(x=df$time, y=df$mincurr, group=1)) + geom_line() write.csv(df,'Fridayweekdayvalues.csv')
/scripts/WeekendGenerateUpdated.R
no_license
damiandiaz212/JPM-ChaseCode4Good
R
false
false
4,919
r
id <- 1 lat <- 0 long <- 0 time <- 0 currentpos <- 0 mincurr <- sample(1:40,1) minnext <- 0 maxcurr <- sample(40:80,1) maxnext <- 0 #df[i,1] <- id #df[i,2] <- lat #df[i,3] <- long #df[i,4] <- time #df[i,6] <- mincurr #df[i,7] <- minnext #df[i,8] <- maxcurr #df[i,9] <- maxnext #df[i,10] <- min #df[i,11] <- max df <- data.frame(id,lat,long,time,mincurr,minnext,maxcurr,maxnext) colnames(df) <- c("id", "lat","long","time","mincurr","minnext","maxcurr","maxnext","min","max") values <- c("high","low","medium") Long <- c(40.79798, 40.7942, 40.79166, 40.78526, 40.78199, 40.77946, 40.7762, 40.76822, 40.76692, 40.76573, 40.76512, 40.76741, 40.77245, 40.77701, 40.78409, 40.78792, 40.79174, 40.79686, 40.79821, 40.7994, 40.76683, 40.77026, 40.77911, 40.779, 40.78335, 40.79039, 40.79525) Lat <- c(-73.96003, -73.96282, -73.96468, -73.96928, -73.97167, -73.97349, -73.9759, -73.9814, -73.97901, -73.97618, -73.97302, -73.97076, -73.96702, -73.96378, -73.95857, -73.95579, -73.95299, -73.94968, -73.95251, -73.95538, -73.9721, -73.97524, -73.96906, -73.96238 ,-73.96397, -73.95983, -73.95562) # midnight to 5am for (i in 1:1440){ n <- sample(1:27,1) v <- sample(1:3,1) v <- values[v] if (i < 300){ id <- sample(1:65,1) lat <- Long[n] long <- Lat[n] time <- i currentpos <- (i/(i+1)) mincurr <- sample(1:40,1) minnext <- 0 maxcurr <- sample(40:80,1) maxnext <- 0 min <- 0 max <- 0 count <- sample(1:80,1) df[i,1] <- id df[i,2] <- lat df[i,3] <- long df[i,4] <- time df[i,5] <- mincurr df[i,6] <- minnext df[i,7] <- maxcurr df[i,8] <- maxnext } else if(i > 300 && i < 601){ id <- sample(1:65,1) lat <- Long[n] long <- Lat[n] time <- i currentpos <- (i/(i+1)) if (v == "low"){ mincurr <- sample(20:40,1) minnext <- 0 maxcurr <- sample(60:80,1) maxnext <- 0 min <- 0 max <- 0 }else if(v == "medium"){ mincurr <- sample(60:40,1) minnext <- 0 maxcurr <- sample(80:120,1) maxnext <- 0 min <- 0 max <- 0 }else{ mincurr <- sample(80:100,1) minnext <- 0 maxcurr <- sample(100:200,1) maxnext <- 0 min <- 0 max <- 0} #count <- sample(1:80,1) df[i,1] <- id df[i,2] <- lat df[i,3] <- long df[i,4] <- time df[i,5] <- mincurr df[i,6] <- minnext df[i,7] <- maxcurr df[i,8] <- maxnext } else if(i > 601 && i < 841){ id <- sample(1:65,1) lat <- Long[n] long <- Lat[n] time <- i currentpos <- (i/(i+1)) if (v == "low"){ mincurr <- sample(20:40,1) minnext <- 0 maxcurr <- sample(60:80,1) maxnext <- 0 min <- 0 max <- 0 }else if(v == "medium"){ mincurr <- sample(60:40,1) minnext <- 0 maxcurr <- sample(80:120,1) maxnext <- 0 min <- 0 max <- 0 }else{ mincurr <- sample(80:100,1) minnext <- 0 maxcurr <- sample(100:200,1) maxnext <- 0 min <- 0 max <- 0} #count <- sample(1:80,1) df[i,1] <- id df[i,2] <- lat df[i,3] <- long df[i,4] <- time df[i,5] <- mincurr df[i,6] <- minnext df[i,7] <- maxcurr df[i,8] <- maxnext } else if(i > 841 && i < 1141){ id <- sample(1:65,1) lat <- Long[n] long <- Lat[n] time <- i currentpos <- (i/(i+1)) if (v == "low"){ mincurr <- sample(20:40,1) minnext <- 0 maxcurr <- sample(60:80,1) maxnext <- 0 min <- 0 max <- 0 }else if(v == "medium"){ mincurr <- sample(60:40,1) minnext <- 0 maxcurr <- sample(80:120,1) maxnext <- 0 min <- 0 max <- 0 }else{ mincurr <- sample(80:100,1) minnext <- 0 maxcurr <- sample(100:200,1) maxnext <- 0 min <- 0 max <- 0} #count <- sample(1:80,1) df[i,1] <- id df[i,2] <- lat df[i,3] <- long df[i,4] <- time df[i,5] <- mincurr df[i,6] <- minnext df[i,7] <- maxcurr df[i,8] <- maxnext } else if(i <= 1400){ id <- sample(1:65,1) lat <- Long[n] long <- Lat[n] time <- i currentpos <- (i/(i+1)) mincurr <- sample(1:40,1) minnext <- 0 maxcurr <- sample(40:80,1) maxnext <- 0 min <- 0 max <- 0 #count <- sample(1:80,1) df[i,1] <- id df[i,2] <- lat df[i,3] <- long df[i,4] <- time df[i,5] <- mincurr df[i,6] <- minnext df[i,7] <- maxcurr df[i,8] <- maxnext } } for (i in 1:1439){ currentpos <- (i/(i+1)) df[i,6] <- abs((df[i,5] - df[i+1,5]))*currentpos df[i+1,5] <- abs((df[i,5] - df[i+1,5]))*currentpos df[i,8] <- abs((df[i,7] - df[i+1,7]))*currentpos df[i+1,7] <- abs((df[i,7] - df[i+1,7]))*currentpos } library(ggplot2) count <- df$min ggplot(data=df, aes(x=df$time, y=df$mincurr, group=1)) + geom_line() write.csv(df,'Fridayweekdayvalues.csv')
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/gaterSVM.R \name{gaterSVM} \alias{gaterSVM} \title{Mixture SVMs with gater function} \usage{ gaterSVM( x, y, m, c = 1, max.iter, hidden = 5, learningrate = 0.01, threshold = 0.01, stepmax = 100, seed = NULL, valid.x = NULL, valid.y = NULL, valid.metric = NULL, verbose = FALSE, ... ) } \arguments{ \item{x}{the nxp training data matrix. Could be a matrix or an object that can be transformed into a matrix object.} \item{y}{a response vector for prediction tasks with one value for each of the n rows of \code{x}. For classification, the values correspond to class labels and can be a 1xn matrix, a simple vector or a factor. For regression, the values correspond to the values to predict, and can be a 1xn matrix or a simple vector.} \item{m}{the number of experts} \item{c}{a positive constant controlling the upper bound of the number of samples in each subset.} \item{max.iter}{the number of iterations} \item{hidden}{the number of neurons on the hidden layer} \item{learningrate}{the learningrate for the back propagation} \item{threshold}{neural network stops training once all gradient is below the threshold} \item{stepmax}{the maximum iteration of the neural network training process} \item{seed}{the random seed. Set it to \code{NULL} to randomize the model.} \item{valid.x}{the mxp validation data matrix.} \item{valid.y}{if provided, it will be used to calculate the validation score with \code{valid.metric}} \item{valid.metric}{the metric function for the validation result. By default it is the accuracy for classification. Customized metric is acceptable.} \item{verbose}{a logical value indicating whether to print information of training.} \item{...}{other parameters passing to \code{neuralnet}} } \value{ \itemize{ \item \code{expert} a list of svm experts \item \code{gater} the trained neural network model \item \code{valid.pred} the validation prediction \item \code{valid.score} the validation score \item \code{valid.metric} the validation metric \item \code{time} a list object recording the time consumption for each steps. } } \description{ Implementation of Collobert, R., Bengio, S., and Bengio, Y. "A parallel mixture of SVMs for very large scale problems. Neural computation". } \examples{ data(svmguide1) svmguide1.t = as.matrix(svmguide1[[2]]) svmguide1 = as.matrix(svmguide1[[1]]) gaterSVM.model = gaterSVM(x = svmguide1[,-1], y = svmguide1[,1], hidden = 10, seed = 0, m = 10, max.iter = 1, learningrate = 0.01, threshold = 1, stepmax = 100, valid.x = svmguide1.t[,-1], valid.y = svmguide1.t[,1], verbose = FALSE) table(gaterSVM.model$valid.pred,svmguide1.t[,1]) gaterSVM.model$valid.score }
/man/gaterSVM.Rd
no_license
hetong007/SwarmSVM
R
false
true
2,826
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/gaterSVM.R \name{gaterSVM} \alias{gaterSVM} \title{Mixture SVMs with gater function} \usage{ gaterSVM( x, y, m, c = 1, max.iter, hidden = 5, learningrate = 0.01, threshold = 0.01, stepmax = 100, seed = NULL, valid.x = NULL, valid.y = NULL, valid.metric = NULL, verbose = FALSE, ... ) } \arguments{ \item{x}{the nxp training data matrix. Could be a matrix or an object that can be transformed into a matrix object.} \item{y}{a response vector for prediction tasks with one value for each of the n rows of \code{x}. For classification, the values correspond to class labels and can be a 1xn matrix, a simple vector or a factor. For regression, the values correspond to the values to predict, and can be a 1xn matrix or a simple vector.} \item{m}{the number of experts} \item{c}{a positive constant controlling the upper bound of the number of samples in each subset.} \item{max.iter}{the number of iterations} \item{hidden}{the number of neurons on the hidden layer} \item{learningrate}{the learningrate for the back propagation} \item{threshold}{neural network stops training once all gradient is below the threshold} \item{stepmax}{the maximum iteration of the neural network training process} \item{seed}{the random seed. Set it to \code{NULL} to randomize the model.} \item{valid.x}{the mxp validation data matrix.} \item{valid.y}{if provided, it will be used to calculate the validation score with \code{valid.metric}} \item{valid.metric}{the metric function for the validation result. By default it is the accuracy for classification. Customized metric is acceptable.} \item{verbose}{a logical value indicating whether to print information of training.} \item{...}{other parameters passing to \code{neuralnet}} } \value{ \itemize{ \item \code{expert} a list of svm experts \item \code{gater} the trained neural network model \item \code{valid.pred} the validation prediction \item \code{valid.score} the validation score \item \code{valid.metric} the validation metric \item \code{time} a list object recording the time consumption for each steps. } } \description{ Implementation of Collobert, R., Bengio, S., and Bengio, Y. "A parallel mixture of SVMs for very large scale problems. Neural computation". } \examples{ data(svmguide1) svmguide1.t = as.matrix(svmguide1[[2]]) svmguide1 = as.matrix(svmguide1[[1]]) gaterSVM.model = gaterSVM(x = svmguide1[,-1], y = svmguide1[,1], hidden = 10, seed = 0, m = 10, max.iter = 1, learningrate = 0.01, threshold = 1, stepmax = 100, valid.x = svmguide1.t[,-1], valid.y = svmguide1.t[,1], verbose = FALSE) table(gaterSVM.model$valid.pred,svmguide1.t[,1]) gaterSVM.model$valid.score }
rm(list = ls(all=T)) graphics.off() library(here) library(data.table) library(tidyverse) library(xlsx) library(tdr) #tdStats library(Metrics) library(ggthemes) library(extrafont) library(likert) setwd(paste0(here(),"/Data/Ishii/")) wd = read.xlsx("Fluxomics.xlsx", 1) conditions = colnames(wd)[-c(1,2)] conditions[1] = "D = 0.1/h" conditions[2] = "D = 0.4/h" conditions[3] = "D = 0.5/h" conditions[4] = "D = 0.7/h" fluxes = as.character(wd[,1]) wtflux = wd[,2] M = wd[,-c(1,2)] setwd(paste0(here(),"/Simulations/Ishii/RT_PCR_Relaxed_DFBA//")) Md = read.xlsx("Results.xlsx",1, header = F) Pd = read.xlsx("Results.xlsx",2, header = F) Rd = read.xlsx("Results.xlsx",3, header = F) MRatio = M/wtflux MRatio = as.matrix(MRatio) MRatio[is.nan(MRatio)] = 0 MRatio[which(MRatio==Inf)] = 100 MRatio[which(MRatio==-Inf)] = 0.001 m1 = c() m2 = c() m3 = c() m4 = c() m5 = c() m6 = c() for (i in 1:length(conditions)) { sim = Pd[,i] exp = Md[,i] m1[i] = tryCatch(tdStats(sim, exp, functions= c("nrmse")) , error = function(e) NA) m2[i] = tryCatch(sim %*% exp / (norm(as.matrix(sim), type = "2") * norm(as.matrix(exp), type = "2")), error = function(e) NA) s_Md = as.numeric(exp) sel = which(abs(s_Md)>median(abs(s_Md))) sel2 = which(abs(s_Md)>quantile(abs(s_Md),0.75)) s_Md[s_Md>0] = 1; s_Md[s_Md<0] = -1; s_Pd = as.numeric(sim) s_Pd[s_Pd>0] = 1; s_Pd[s_Pd<0] = -1; m3[i] = accuracy(s_Md,s_Pd) m4[i] = accuracy(s_Md[sel], s_Pd[sel]) m5[i] = accuracy(s_Md[sel2], s_Pd[sel2]) m6[i] = summary(lm(MRatio[,i]~Rd[,i]))$r.squared } data <- data.frame( condition=rep(conditions,3), group=c(rep('NRMSE', length(conditions)), rep("\u03c1", length(conditions)),rep('Sign Acc', length(conditions))) , value= c(m1, m2,m3)) data$test = "dFBA" rm(list= ls()[!(ls() %in% c('data'))]) graphics.off() library(data.table) library(tidyverse) library(xlsx) library(tdr) #tdStats library(Metrics) library(ggthemes) library(extrafont) library(likert) setwd(paste0(here(),"/Data/Ishii/")) wd = read.xlsx("Fluxomics.xlsx", 1) conditions = colnames(wd)[-c(1,2)] conditions[1] = "D = 0.1/h" conditions[2] = "D = 0.4/h" conditions[3] = "D = 0.5/h" conditions[4] = "D = 0.7/h" fluxes = as.character(wd[,1]) wtflux = wd[,2] M = wd[,-c(1,2)] setwd(paste0(here(),"/Simulations/Ishii/RT_PCR_Stringent_DFBA/")) Md = read.xlsx("Results.xlsx",1, header = F) Pd = read.xlsx("Results.xlsx",2, header = F) Rd = read.xlsx("Results.xlsx",3, header = F) MRatio = M/wtflux MRatio = as.matrix(MRatio) MRatio[is.nan(MRatio)] = 0 MRatio[which(MRatio==Inf)] = 100 MRatio[which(MRatio==-Inf)] = 0.001 m1 = c() m2 = c() m3 = c() m4 = c() m5 = c() m6 = c() for (i in 1:length(conditions)) { sim = Pd[,i] exp = Md[,i] m1[i] = tryCatch(tdStats(sim, exp, functions= c("nrmse")) , error = function(e) NA) m2[i] = tryCatch(sim %*% exp / (norm(as.matrix(sim), type = "2") * norm(as.matrix(exp), type = "2")), error = function(e) NA) s_Md = as.numeric(exp) sel = which(abs(s_Md)>median(abs(s_Md))) sel2 = which(abs(s_Md)>quantile(abs(s_Md),0.75)) s_Md[s_Md>0] = 1; s_Md[s_Md<0] = -1; s_Pd = as.numeric(sim) s_Pd[s_Pd>0] = 1; s_Pd[s_Pd<0] = -1; m3[i] = accuracy(s_Md,s_Pd) m4[i] = accuracy(s_Md[sel], s_Pd[sel]) m5[i] = accuracy(s_Md[sel2], s_Pd[sel2]) m6[i] = summary(lm(MRatio[,i]~Rd[,i]))$r.squared } data2 <- data.frame( condition=rep(conditions,3), group=c(rep('NRMSE', length(conditions)), rep("\u03c1", length(conditions)),rep('Sign Acc', length(conditions))) , value= c(m1, m2,m3)) data2$test = "REMI" rm(list= ls()[!(ls() %in% c('data', 'data2', 'conditions'))]) dat = rbind(data,data2) dat$test = factor(dat$test, levels = c("dFBA", "REMI")) dat$group = factor(dat$group, levels = c("NRMSE","\u03c1", "Sign Acc")) cols = c("#FF9E4A", "#2d6d66") setwd(paste0(here(),"/Plotting/Ishii/")) tiff('RelaxedvStringent.tiff', units="px", width=(700*3), height=(450*3), res=300) p <- ggplot(dat, aes(x = test, y = value, fill= test)) + geom_boxplot(outlier.size = 2) + stat_boxplot(geom = "errorbar",width = 0.4,size = 0.75) + geom_boxplot(lwd=0.55) + theme_bw(base_size = 12) + facet_grid(.~group)+ theme(strip.text.x = element_text(angle = 0, family = "Calibri", face = "bold", size = 16))+ theme(panel.spacing =unit(0.5, "lines"), panel.border = element_rect(color = "#476b6b", fill = NA, size = 1.5), strip.background = element_rect(color = "#476b6b", size = 1.5, fill = "#d6dce4"))+ #theme(strip.text.x = element_blank())+ #theme(panel.spacing =unit(0.5, "lines")) + scale_fill_manual(values = cols) + theme(legend.position = "none") + #ylim(-1,1) + xlab("") + ylab("") + ylim(-0.5,1) + theme(axis.ticks.y = element_line(size=1,color='#476b6b')) + theme(axis.ticks.x = element_blank()) + theme(axis.title = element_text(size = 20, family = "Calibri", face = "bold")) + theme(axis.text.y = element_text(size=18, family = "Calibri", face = "bold"), axis.text.x = element_blank()) p dev.off() data$group = factor(data$group, levels = c("NRMSE","\u03c1", "Sign Acc")) m1 = split(data, data$group) m1 = sapply(1:length(m1), function(x) mean(m1[[x]]$value,na.rm=T)) data2$group = factor(data2$group, levels = c("NRMSE","\u03c1", "Sign Acc")) m2 = split(data2, data2$group) m2 = sapply(1:length(m2), function(x) mean(m2[[x]]$value,na.rm=T)) m1 m2
/Plotting/Ishii/RelaxedvStringent.R
permissive
CABSEL/DeltaFBA
R
false
false
5,576
r
rm(list = ls(all=T)) graphics.off() library(here) library(data.table) library(tidyverse) library(xlsx) library(tdr) #tdStats library(Metrics) library(ggthemes) library(extrafont) library(likert) setwd(paste0(here(),"/Data/Ishii/")) wd = read.xlsx("Fluxomics.xlsx", 1) conditions = colnames(wd)[-c(1,2)] conditions[1] = "D = 0.1/h" conditions[2] = "D = 0.4/h" conditions[3] = "D = 0.5/h" conditions[4] = "D = 0.7/h" fluxes = as.character(wd[,1]) wtflux = wd[,2] M = wd[,-c(1,2)] setwd(paste0(here(),"/Simulations/Ishii/RT_PCR_Relaxed_DFBA//")) Md = read.xlsx("Results.xlsx",1, header = F) Pd = read.xlsx("Results.xlsx",2, header = F) Rd = read.xlsx("Results.xlsx",3, header = F) MRatio = M/wtflux MRatio = as.matrix(MRatio) MRatio[is.nan(MRatio)] = 0 MRatio[which(MRatio==Inf)] = 100 MRatio[which(MRatio==-Inf)] = 0.001 m1 = c() m2 = c() m3 = c() m4 = c() m5 = c() m6 = c() for (i in 1:length(conditions)) { sim = Pd[,i] exp = Md[,i] m1[i] = tryCatch(tdStats(sim, exp, functions= c("nrmse")) , error = function(e) NA) m2[i] = tryCatch(sim %*% exp / (norm(as.matrix(sim), type = "2") * norm(as.matrix(exp), type = "2")), error = function(e) NA) s_Md = as.numeric(exp) sel = which(abs(s_Md)>median(abs(s_Md))) sel2 = which(abs(s_Md)>quantile(abs(s_Md),0.75)) s_Md[s_Md>0] = 1; s_Md[s_Md<0] = -1; s_Pd = as.numeric(sim) s_Pd[s_Pd>0] = 1; s_Pd[s_Pd<0] = -1; m3[i] = accuracy(s_Md,s_Pd) m4[i] = accuracy(s_Md[sel], s_Pd[sel]) m5[i] = accuracy(s_Md[sel2], s_Pd[sel2]) m6[i] = summary(lm(MRatio[,i]~Rd[,i]))$r.squared } data <- data.frame( condition=rep(conditions,3), group=c(rep('NRMSE', length(conditions)), rep("\u03c1", length(conditions)),rep('Sign Acc', length(conditions))) , value= c(m1, m2,m3)) data$test = "dFBA" rm(list= ls()[!(ls() %in% c('data'))]) graphics.off() library(data.table) library(tidyverse) library(xlsx) library(tdr) #tdStats library(Metrics) library(ggthemes) library(extrafont) library(likert) setwd(paste0(here(),"/Data/Ishii/")) wd = read.xlsx("Fluxomics.xlsx", 1) conditions = colnames(wd)[-c(1,2)] conditions[1] = "D = 0.1/h" conditions[2] = "D = 0.4/h" conditions[3] = "D = 0.5/h" conditions[4] = "D = 0.7/h" fluxes = as.character(wd[,1]) wtflux = wd[,2] M = wd[,-c(1,2)] setwd(paste0(here(),"/Simulations/Ishii/RT_PCR_Stringent_DFBA/")) Md = read.xlsx("Results.xlsx",1, header = F) Pd = read.xlsx("Results.xlsx",2, header = F) Rd = read.xlsx("Results.xlsx",3, header = F) MRatio = M/wtflux MRatio = as.matrix(MRatio) MRatio[is.nan(MRatio)] = 0 MRatio[which(MRatio==Inf)] = 100 MRatio[which(MRatio==-Inf)] = 0.001 m1 = c() m2 = c() m3 = c() m4 = c() m5 = c() m6 = c() for (i in 1:length(conditions)) { sim = Pd[,i] exp = Md[,i] m1[i] = tryCatch(tdStats(sim, exp, functions= c("nrmse")) , error = function(e) NA) m2[i] = tryCatch(sim %*% exp / (norm(as.matrix(sim), type = "2") * norm(as.matrix(exp), type = "2")), error = function(e) NA) s_Md = as.numeric(exp) sel = which(abs(s_Md)>median(abs(s_Md))) sel2 = which(abs(s_Md)>quantile(abs(s_Md),0.75)) s_Md[s_Md>0] = 1; s_Md[s_Md<0] = -1; s_Pd = as.numeric(sim) s_Pd[s_Pd>0] = 1; s_Pd[s_Pd<0] = -1; m3[i] = accuracy(s_Md,s_Pd) m4[i] = accuracy(s_Md[sel], s_Pd[sel]) m5[i] = accuracy(s_Md[sel2], s_Pd[sel2]) m6[i] = summary(lm(MRatio[,i]~Rd[,i]))$r.squared } data2 <- data.frame( condition=rep(conditions,3), group=c(rep('NRMSE', length(conditions)), rep("\u03c1", length(conditions)),rep('Sign Acc', length(conditions))) , value= c(m1, m2,m3)) data2$test = "REMI" rm(list= ls()[!(ls() %in% c('data', 'data2', 'conditions'))]) dat = rbind(data,data2) dat$test = factor(dat$test, levels = c("dFBA", "REMI")) dat$group = factor(dat$group, levels = c("NRMSE","\u03c1", "Sign Acc")) cols = c("#FF9E4A", "#2d6d66") setwd(paste0(here(),"/Plotting/Ishii/")) tiff('RelaxedvStringent.tiff', units="px", width=(700*3), height=(450*3), res=300) p <- ggplot(dat, aes(x = test, y = value, fill= test)) + geom_boxplot(outlier.size = 2) + stat_boxplot(geom = "errorbar",width = 0.4,size = 0.75) + geom_boxplot(lwd=0.55) + theme_bw(base_size = 12) + facet_grid(.~group)+ theme(strip.text.x = element_text(angle = 0, family = "Calibri", face = "bold", size = 16))+ theme(panel.spacing =unit(0.5, "lines"), panel.border = element_rect(color = "#476b6b", fill = NA, size = 1.5), strip.background = element_rect(color = "#476b6b", size = 1.5, fill = "#d6dce4"))+ #theme(strip.text.x = element_blank())+ #theme(panel.spacing =unit(0.5, "lines")) + scale_fill_manual(values = cols) + theme(legend.position = "none") + #ylim(-1,1) + xlab("") + ylab("") + ylim(-0.5,1) + theme(axis.ticks.y = element_line(size=1,color='#476b6b')) + theme(axis.ticks.x = element_blank()) + theme(axis.title = element_text(size = 20, family = "Calibri", face = "bold")) + theme(axis.text.y = element_text(size=18, family = "Calibri", face = "bold"), axis.text.x = element_blank()) p dev.off() data$group = factor(data$group, levels = c("NRMSE","\u03c1", "Sign Acc")) m1 = split(data, data$group) m1 = sapply(1:length(m1), function(x) mean(m1[[x]]$value,na.rm=T)) data2$group = factor(data2$group, levels = c("NRMSE","\u03c1", "Sign Acc")) m2 = split(data2, data2$group) m2 = sapply(1:length(m2), function(x) mean(m2[[x]]$value,na.rm=T)) m1 m2
# covariates # #look ok # gene counts # path <- "/Users/bheavner/Desktop/AMP-AD_MayoPilot_UFL-Mayo-ISB_IlluminaHiSeq2000_dIPFC_Rush-Broad-SS_gene_id_counts.txt" newpath <- "/Users/bheavner/Desktop/AMP-AD_MayoPilot_UFL-Mayo-ISB_IlluminaHiSeq2000_dIPFC_Rush-Broad-SS_GeneCounts.txt" geneCounts <- read.table(path, header = TRUE, check.names = FALSE) write.table(geneCounts, newpath, quote = FALSE, sep = " ", row.names = TRUE, col.names = NA) system(paste("gzip", newpath, sep = " ")) ### normalized genecounts ## path <- "/Users/bheavner/Desktop/AMP-AD_SampleSwap_UFL-Mayo-ISB_IlluminaHiSeq2000_dIPFC_Rush-Broad-SS_geneCounts_normalized.txt" geneCounts <- read.table(path, header = TRUE, check.names = FALSE) #fix colnames to agree with covariates colnames(geneCounts) <- sub('X', '', colnames(geneCounts)) write.table(format(geneCounts, scientific = FALSE, digits = 5), path, quote = FALSE, sep = "\t", row.names = TRUE, col.names = NA) system(paste("gzip", path, sep = " ")) ### transcript counts ## path2 <- "/Users/bheavner/Desktop/AMP-AD_SampleSwap_UFL-Mayo-ISB_IlluminaHiSeq2000_dIPFC_Rush-Broad-SS_TranscriptCounts.txt" transcriptCounts <- read.table(path2, header = TRUE, check.names = FALSE) write.table(transcriptCounts, path2, quote = FALSE, sep = " ", row.names = TRUE, col.names = NA) system(paste("gzip", path2, sep = " ")) ## normalized transcript counts ## path <- "/Users/bheavner/Desktop/AMP-AD_SampleSwap_UFL-Mayo-ISB_IlluminaHiSeq2000_dIPFC_Rush-Broad-SS_TranscriptCounts_Normalized.txt" transcriptCounts <- read.table(path, header = TRUE, check.names = FALSE) #fix colnames to agree with covariates colnames(transcriptCounts) <- sub('X', '', colnames(transcriptCounts)) write.table(format(transcriptCounts, scientific = FALSE, digits = 5), path, quote = FALSE, sep = "\t", row.names = TRUE, col.names = NA) system(paste("gzip", path, sep = " "))
/may_2015_release/Rush-Broad_SS_work/checkingFormatting.R
no_license
bheavner/amp_working
R
false
false
1,915
r
# covariates # #look ok # gene counts # path <- "/Users/bheavner/Desktop/AMP-AD_MayoPilot_UFL-Mayo-ISB_IlluminaHiSeq2000_dIPFC_Rush-Broad-SS_gene_id_counts.txt" newpath <- "/Users/bheavner/Desktop/AMP-AD_MayoPilot_UFL-Mayo-ISB_IlluminaHiSeq2000_dIPFC_Rush-Broad-SS_GeneCounts.txt" geneCounts <- read.table(path, header = TRUE, check.names = FALSE) write.table(geneCounts, newpath, quote = FALSE, sep = " ", row.names = TRUE, col.names = NA) system(paste("gzip", newpath, sep = " ")) ### normalized genecounts ## path <- "/Users/bheavner/Desktop/AMP-AD_SampleSwap_UFL-Mayo-ISB_IlluminaHiSeq2000_dIPFC_Rush-Broad-SS_geneCounts_normalized.txt" geneCounts <- read.table(path, header = TRUE, check.names = FALSE) #fix colnames to agree with covariates colnames(geneCounts) <- sub('X', '', colnames(geneCounts)) write.table(format(geneCounts, scientific = FALSE, digits = 5), path, quote = FALSE, sep = "\t", row.names = TRUE, col.names = NA) system(paste("gzip", path, sep = " ")) ### transcript counts ## path2 <- "/Users/bheavner/Desktop/AMP-AD_SampleSwap_UFL-Mayo-ISB_IlluminaHiSeq2000_dIPFC_Rush-Broad-SS_TranscriptCounts.txt" transcriptCounts <- read.table(path2, header = TRUE, check.names = FALSE) write.table(transcriptCounts, path2, quote = FALSE, sep = " ", row.names = TRUE, col.names = NA) system(paste("gzip", path2, sep = " ")) ## normalized transcript counts ## path <- "/Users/bheavner/Desktop/AMP-AD_SampleSwap_UFL-Mayo-ISB_IlluminaHiSeq2000_dIPFC_Rush-Broad-SS_TranscriptCounts_Normalized.txt" transcriptCounts <- read.table(path, header = TRUE, check.names = FALSE) #fix colnames to agree with covariates colnames(transcriptCounts) <- sub('X', '', colnames(transcriptCounts)) write.table(format(transcriptCounts, scientific = FALSE, digits = 5), path, quote = FALSE, sep = "\t", row.names = TRUE, col.names = NA) system(paste("gzip", path, sep = " "))
testlist <- list(A = structure(c(2.31584307392677e+77, 9.53818252170339e+295, 1.22810536108211e+146, 1.03590399489545e-304, 0), .Dim = c(5L, 1L)), B = structure(0, .Dim = c(1L, 1L))) result <- do.call(multivariance:::match_rows,testlist) str(result)
/multivariance/inst/testfiles/match_rows/AFL_match_rows/match_rows_valgrind_files/1613116243-test.R
no_license
akhikolla/updatedatatype-list3
R
false
false
251
r
testlist <- list(A = structure(c(2.31584307392677e+77, 9.53818252170339e+295, 1.22810536108211e+146, 1.03590399489545e-304, 0), .Dim = c(5L, 1L)), B = structure(0, .Dim = c(1L, 1L))) result <- do.call(multivariance:::match_rows,testlist) str(result)
# example data frame set.seed(33) expr <- data.frame(EnsemblID=c("A", "B", "B", "C", "C", "C", "A", "B", "A", "C", "D"), sample1=rnorm(11), sample2=rnorm(11), sample3=rnorm(11)) probes2genes <- function(expr) { expr2 <- aggregate(expr[,-1], by=list(Gene=as.factor(expr$EnsemblID)), FUN=median) print(dim(expr)) print(dim(expr2)) good.index <- c() for (profile in seq_along(expr$EnsemblID)) { if(profile%%100==0) {print(profile)} gene <- as.numeric(expr[profile, 2:ncol(expr)]) median <- as.numeric(expr2[expr2$Gene == expr$EnsemblID[profile], 2:ncol(expr2)]) # print(gene) # print(median) # print(cor.test(gene, median)$estimate) if (cor.test(gene, median)$estimate > 0.5) { # just >0.7 because I want the correlation to act one direction good.index <- c(good.index, profile) } } print("second round") expr <- expr[good.index, ] expr2 <- aggregate(expr[,-1], by=list(Gene=as.factor(expr$EnsemblID)), FUN=median) expr$EnsemblID good.index <- c() for (profile in seq_along(expr$EnsemblID)) { gene <- as.numeric(expr[profile, 2:ncol(expr)]) median <- as.numeric(expr2[expr2$Gene == expr$EnsemblID[profile], 2:ncol(expr2)]) # print(gene) # print(median) # print(cor.test(gene, median)$estimate) if (cor.test(gene, median)$estimate > 0.5) { # just >0.7 because I want the correlation to act one direction good.index <- c(good.index, profile) } } print(nrow(expr)==length(good.index)) return(expr2) } expr.final <- probes2genes(expr)
/aracne/scripts/probes2genes.R
no_license
antass/REAGENT
R
false
false
1,606
r
# example data frame set.seed(33) expr <- data.frame(EnsemblID=c("A", "B", "B", "C", "C", "C", "A", "B", "A", "C", "D"), sample1=rnorm(11), sample2=rnorm(11), sample3=rnorm(11)) probes2genes <- function(expr) { expr2 <- aggregate(expr[,-1], by=list(Gene=as.factor(expr$EnsemblID)), FUN=median) print(dim(expr)) print(dim(expr2)) good.index <- c() for (profile in seq_along(expr$EnsemblID)) { if(profile%%100==0) {print(profile)} gene <- as.numeric(expr[profile, 2:ncol(expr)]) median <- as.numeric(expr2[expr2$Gene == expr$EnsemblID[profile], 2:ncol(expr2)]) # print(gene) # print(median) # print(cor.test(gene, median)$estimate) if (cor.test(gene, median)$estimate > 0.5) { # just >0.7 because I want the correlation to act one direction good.index <- c(good.index, profile) } } print("second round") expr <- expr[good.index, ] expr2 <- aggregate(expr[,-1], by=list(Gene=as.factor(expr$EnsemblID)), FUN=median) expr$EnsemblID good.index <- c() for (profile in seq_along(expr$EnsemblID)) { gene <- as.numeric(expr[profile, 2:ncol(expr)]) median <- as.numeric(expr2[expr2$Gene == expr$EnsemblID[profile], 2:ncol(expr2)]) # print(gene) # print(median) # print(cor.test(gene, median)$estimate) if (cor.test(gene, median)$estimate > 0.5) { # just >0.7 because I want the correlation to act one direction good.index <- c(good.index, profile) } } print(nrow(expr)==length(good.index)) return(expr2) } expr.final <- probes2genes(expr)
#' @export #' @title Unpacks a Site Tool #' #' @description #' Processes a submitted Site Tool (in .xlsx format) by identifying integrity #' issues, checking data against DATIM validations, and extracting data. #' #' @param d Datapackr object as passed from unPackTool. #' #' @return d #' unPackSiteTool <- function(d) { # Determine country uids if (is.na(d$info$country_uids)) { d$info$country_uids <- unPackCountryUIDs(submission_path = d$keychain$submission_path, tool = d$info$tool) } # Check integrity of tabs d <- checkStructure(d) # Unpack the Targets d <- unPackSheets(d) # Tag Data Pack name & Country Names/uids d$info$datapack_name <- readxl::read_excel( d$keychain$submission_path, sheet = "Home", range = "B20") %>% names() site_uids <- d$data$targets %>% dplyr::pull(site_uid) %>% unique() %>% paste0(collapse = ",") countries <- datapackr::api_call("organisationUnits") %>% datapackr::api_filter("organisationUnitGroups.name:eq:Country") %>% datapackr::api_filter(paste0("children.id:in:[",site_uids,"]")) %>% datapackr::api_fields("id,name") %>% datapackr::api_get() d$info$country_names <- countries$name d$info$country_uids <- countries$id # Derive non-Site Tool targets d$data$targets <- deriveTargets(d$data$targets, type = "Site Tool") d <- packForDATIM(d, type = "Site") return(d) }
/R/unPackSiteTool.R
no_license
AdeBaddest/datapackr
R
false
false
1,436
r
#' @export #' @title Unpacks a Site Tool #' #' @description #' Processes a submitted Site Tool (in .xlsx format) by identifying integrity #' issues, checking data against DATIM validations, and extracting data. #' #' @param d Datapackr object as passed from unPackTool. #' #' @return d #' unPackSiteTool <- function(d) { # Determine country uids if (is.na(d$info$country_uids)) { d$info$country_uids <- unPackCountryUIDs(submission_path = d$keychain$submission_path, tool = d$info$tool) } # Check integrity of tabs d <- checkStructure(d) # Unpack the Targets d <- unPackSheets(d) # Tag Data Pack name & Country Names/uids d$info$datapack_name <- readxl::read_excel( d$keychain$submission_path, sheet = "Home", range = "B20") %>% names() site_uids <- d$data$targets %>% dplyr::pull(site_uid) %>% unique() %>% paste0(collapse = ",") countries <- datapackr::api_call("organisationUnits") %>% datapackr::api_filter("organisationUnitGroups.name:eq:Country") %>% datapackr::api_filter(paste0("children.id:in:[",site_uids,"]")) %>% datapackr::api_fields("id,name") %>% datapackr::api_get() d$info$country_names <- countries$name d$info$country_uids <- countries$id # Derive non-Site Tool targets d$data$targets <- deriveTargets(d$data$targets, type = "Site Tool") d <- packForDATIM(d, type = "Site") return(d) }
library(sensitivity) library(tidyverse) library(dplyr) library(foreach) library(doParallel) source(here::here("R", "MPA_model.R")) source(here::here("R", "sensitivity.R")) MPA.mat <- read.csv(here::here("inputs", "MPA.matrix.csv")) mrate <- read.csv(here::here("raw_data", "mrate.csv")) price <- read.csv(here::here("raw_data", "MarketPrice.csv"))%>% merge(mrate, by="Name") pts <- read.csv(here::here("inputs","ref_pts.csv"))%>% merge(price, by="Name")%>% mutate (r.sd = (r.hi-r)/2, k.sd = (k.hi-k)/2, msy.sd = (msy.hi-msy)/2, bmsy.sd= (bmsy.hi-bmsy)/2, b.sd = (b_hi-b)/2, f.sd = (f_hi-f)/2, fmsy.sd= (fmsy_hi-fmsy)/2) nsamples <- 200 r_k_viables <- read.csv(here::here("inputs", "r_k_viables.csv"))%>%filter(Name=="Atrina", Adjusted=="IUU") sens <- pts[1,] # create our two samples for Sobel r_k <- r_k_viables %>% sample_n(nsamples) ps1 = cbind.data.frame(r=r_k$viable_r, k=r_k$viable_k, msy=rnorm(nsamples,mean=sens$msy, sd=sens$msy.sd), bmsy=rnorm(nsamples,mean=sens$bmsy, sd=sens$bmsy.sd), b=rnorm(nsamples,mean=sens$b, sd=sens$b.sd), f=rnorm(nsamples,mean=sens$f, sd=sens$f.sd), fmsy=rnorm(nsamples,mean=sens$fmsy, sd=sens$fmsy.sd), p=runif(min=sens$p.lo, max=sens$p.hi, n=nsamples), mrate=runif(min=0, max=1, n=nsamples)) r_k <- r_k_viables %>% sample_n(nsamples) ps2 <- cbind.data.frame(r=r_k$viable_r, k=r_k$viable_k, msy=rnorm(nsamples,mean=sens$msy, sd=sens$msy.sd), bmsy=rnorm(nsamples,mean=sens$bmsy, sd=sens$bmsy.sd), b=rnorm(nsamples,mean=sens$b, sd=sens$b.sd), f=rnorm(nsamples,mean=sens$f, sd=sens$f.sd), fmsy=rnorm(nsamples,mean=sens$fmsy, sd=sens$fmsy.sd), p=runif(min=sens$p.lo, max=sens$p.hi, n=nsamples), mrate=runif(min=0, max=1, n=nsamples)) sens_micro <- sobol2007(model = NULL, ps1, ps2, nboot = 100) nsim=nrow(sens_micro$X) #Loop through nsamples of parameters start<- Sys.time() mycluster <- makeCluster(4) registerDoParallel(mycluster) results <- foreach (r = 1:nsim, .combine = "rbind", .packages = c("dplyr", "foreach", "doParallel")) %dopar% { inputs <- econ_sens_funs(Name=sens$Name, Adjusted=sens$Adjusted, parms=sens_micro$X[r,]) #Calculates BAU BAU <-MPA.Model(Name = inputs$Name, Adjusted=inputs$Adjusted, r=inputs$r, K=inputs$k, B=inputs$b, Fishing=inputs$f, years=65, MPA.mat=MPA.mat, mrate=inputs$mrate, MSY=inputs$msy, bmsy=inputs$bmsy, fmsy=inputs$fmsy, p=inputs$p, c=inputs$c, profit.msy=inputs$profit.msy, start.year=0) BAU<- BAU%>% plyr::rename(c("Catch"="BAU_C", "Biomass"="BAU_B","Biomass_MPA"="BAU_B_MPA", "PV"="BAU_PV"))%>% select(Name, Adjusted, Year, BAU_C, BAU_B, BAU_B_MPA, BAU_PV) #Calculates scenario scenarios<- MPA.Model(Name = inputs$Name, Adjusted=inputs$Adjusted, r=inputs$r, K=inputs$k, B=inputs$b, Fishing=inputs$f, years=50, MPA.mat=MPA.mat, mrate=inputs$mrate, MSY=inputs$msy, bmsy=inputs$bmsy, fmsy=inputs$fmsy, p=inputs$p, c=inputs$c, profit.msy=inputs$profit.msy, start.year=2015) payoff <- sens_payoff(BAU = BAU, scenarios = scenarios) return(payoff) } stopCluster(mycluster) end<- Sys.time() end-start payoff<- results[,4] #conert Inf to 99999? sens_micro<- tell(sens_micro, payoff) as.data.frame(sens_micro$S) sens_micro$T tmp = cbind.data.frame(sens_micro$X, pop12=sens_micro$y) ggplot(tmp, aes(p12, pop12))+geom_point()+labs(x="Survivability of 1 to older",y="pop after 12 months") pars <- pse::tell(pars, t(res[,4:6]), res.names=c("Transition_period", "Payoff_preriod", "B_per_50")) pse::plotscatter(pars, col="blue", cex=5) pse::plotprcc(pars) pars$prcc pse::plotecdf(pars) end<- Sys.time() end-start
/scripts/Sensitivity.R
no_license
sjcruz/delayed_management
R
false
false
4,027
r
library(sensitivity) library(tidyverse) library(dplyr) library(foreach) library(doParallel) source(here::here("R", "MPA_model.R")) source(here::here("R", "sensitivity.R")) MPA.mat <- read.csv(here::here("inputs", "MPA.matrix.csv")) mrate <- read.csv(here::here("raw_data", "mrate.csv")) price <- read.csv(here::here("raw_data", "MarketPrice.csv"))%>% merge(mrate, by="Name") pts <- read.csv(here::here("inputs","ref_pts.csv"))%>% merge(price, by="Name")%>% mutate (r.sd = (r.hi-r)/2, k.sd = (k.hi-k)/2, msy.sd = (msy.hi-msy)/2, bmsy.sd= (bmsy.hi-bmsy)/2, b.sd = (b_hi-b)/2, f.sd = (f_hi-f)/2, fmsy.sd= (fmsy_hi-fmsy)/2) nsamples <- 200 r_k_viables <- read.csv(here::here("inputs", "r_k_viables.csv"))%>%filter(Name=="Atrina", Adjusted=="IUU") sens <- pts[1,] # create our two samples for Sobel r_k <- r_k_viables %>% sample_n(nsamples) ps1 = cbind.data.frame(r=r_k$viable_r, k=r_k$viable_k, msy=rnorm(nsamples,mean=sens$msy, sd=sens$msy.sd), bmsy=rnorm(nsamples,mean=sens$bmsy, sd=sens$bmsy.sd), b=rnorm(nsamples,mean=sens$b, sd=sens$b.sd), f=rnorm(nsamples,mean=sens$f, sd=sens$f.sd), fmsy=rnorm(nsamples,mean=sens$fmsy, sd=sens$fmsy.sd), p=runif(min=sens$p.lo, max=sens$p.hi, n=nsamples), mrate=runif(min=0, max=1, n=nsamples)) r_k <- r_k_viables %>% sample_n(nsamples) ps2 <- cbind.data.frame(r=r_k$viable_r, k=r_k$viable_k, msy=rnorm(nsamples,mean=sens$msy, sd=sens$msy.sd), bmsy=rnorm(nsamples,mean=sens$bmsy, sd=sens$bmsy.sd), b=rnorm(nsamples,mean=sens$b, sd=sens$b.sd), f=rnorm(nsamples,mean=sens$f, sd=sens$f.sd), fmsy=rnorm(nsamples,mean=sens$fmsy, sd=sens$fmsy.sd), p=runif(min=sens$p.lo, max=sens$p.hi, n=nsamples), mrate=runif(min=0, max=1, n=nsamples)) sens_micro <- sobol2007(model = NULL, ps1, ps2, nboot = 100) nsim=nrow(sens_micro$X) #Loop through nsamples of parameters start<- Sys.time() mycluster <- makeCluster(4) registerDoParallel(mycluster) results <- foreach (r = 1:nsim, .combine = "rbind", .packages = c("dplyr", "foreach", "doParallel")) %dopar% { inputs <- econ_sens_funs(Name=sens$Name, Adjusted=sens$Adjusted, parms=sens_micro$X[r,]) #Calculates BAU BAU <-MPA.Model(Name = inputs$Name, Adjusted=inputs$Adjusted, r=inputs$r, K=inputs$k, B=inputs$b, Fishing=inputs$f, years=65, MPA.mat=MPA.mat, mrate=inputs$mrate, MSY=inputs$msy, bmsy=inputs$bmsy, fmsy=inputs$fmsy, p=inputs$p, c=inputs$c, profit.msy=inputs$profit.msy, start.year=0) BAU<- BAU%>% plyr::rename(c("Catch"="BAU_C", "Biomass"="BAU_B","Biomass_MPA"="BAU_B_MPA", "PV"="BAU_PV"))%>% select(Name, Adjusted, Year, BAU_C, BAU_B, BAU_B_MPA, BAU_PV) #Calculates scenario scenarios<- MPA.Model(Name = inputs$Name, Adjusted=inputs$Adjusted, r=inputs$r, K=inputs$k, B=inputs$b, Fishing=inputs$f, years=50, MPA.mat=MPA.mat, mrate=inputs$mrate, MSY=inputs$msy, bmsy=inputs$bmsy, fmsy=inputs$fmsy, p=inputs$p, c=inputs$c, profit.msy=inputs$profit.msy, start.year=2015) payoff <- sens_payoff(BAU = BAU, scenarios = scenarios) return(payoff) } stopCluster(mycluster) end<- Sys.time() end-start payoff<- results[,4] #conert Inf to 99999? sens_micro<- tell(sens_micro, payoff) as.data.frame(sens_micro$S) sens_micro$T tmp = cbind.data.frame(sens_micro$X, pop12=sens_micro$y) ggplot(tmp, aes(p12, pop12))+geom_point()+labs(x="Survivability of 1 to older",y="pop after 12 months") pars <- pse::tell(pars, t(res[,4:6]), res.names=c("Transition_period", "Payoff_preriod", "B_per_50")) pse::plotscatter(pars, col="blue", cex=5) pse::plotprcc(pars) pars$prcc pse::plotecdf(pars) end<- Sys.time() end-start
## extract.autopls.R Functions to extract values from an autopls object predicted <- function (object) { ## valid object? if (class (object) != 'autopls') stop ('needs object of class autopls') ## Get nlv lv <- get.lv (object) ## Get Yval Yval <- object$validation$pred [,,lv] return (Yval) } fitted.autopls <- function (object, ...) { lv <- get.lv (object) class (object) <- 'mvr' object$fitted.values [,,lv] } coef.autopls <- function (object, intercept = FALSE, ...) { lv <- get.lv (object) class (object) <- 'mvr' rc <- coef (object, ncomp = lv, intercept = intercept) nam <- rownames (rc) out <- as.vector (unlist (rc)) names (out) <- nam out } coef.slim <- function (object, intercept = FALSE, ...) { rc <- object$coefficients if (intercept) rc <- c(object$slimobj$intercept, rc) rc } residuals.autopls <- function (object, ...) { lv <- get.lv (object) class (object) <- 'mvr' residuals (object) [,,lv] } scores.autopls <- function (object, ...) { lv <- get.lv (object) class (object) <- 'mvr' scores (object) [,lv] } loadings.autopls <- function (object, ...) { lv <- get.lv (object) class (object) <- 'mvr' loadings (object) [,lv] } get.lv <- function (object) { if (class (object) == 'autopls') return (object$metapls$current.lv) if (class (object) == 'slim') return (object$current.lv) } get.iter <- function (object) { if (class (object) == 'autopls') return (object$metapls$current.iter) if (class (object) == 'slim') return (object$current.iter) } slim <- function (object) { nobj <- list (coefficients = coef (object), method = object$method, scale = object$scale, call = object$metapls$call, predictors = object$predictors, metapls = list (current.iter = get.iter (object), current.lv = get.lv (object), preprocessing = object$metapls$preprocessing, scaling = object$metapls$scaling, val = object$metapls$val), slimobj = list (intercept = coef (object, intercept = TRUE) [1], r2 = R2 (object, 'all'), rmse = RMSEP (object, 'all'), N = length (object$metapls$Y))) class (nobj) <- 'slim' return (nobj) }
/autopls/R/extract.autopls.R
no_license
ingted/R-Examples
R
false
false
2,568
r
## extract.autopls.R Functions to extract values from an autopls object predicted <- function (object) { ## valid object? if (class (object) != 'autopls') stop ('needs object of class autopls') ## Get nlv lv <- get.lv (object) ## Get Yval Yval <- object$validation$pred [,,lv] return (Yval) } fitted.autopls <- function (object, ...) { lv <- get.lv (object) class (object) <- 'mvr' object$fitted.values [,,lv] } coef.autopls <- function (object, intercept = FALSE, ...) { lv <- get.lv (object) class (object) <- 'mvr' rc <- coef (object, ncomp = lv, intercept = intercept) nam <- rownames (rc) out <- as.vector (unlist (rc)) names (out) <- nam out } coef.slim <- function (object, intercept = FALSE, ...) { rc <- object$coefficients if (intercept) rc <- c(object$slimobj$intercept, rc) rc } residuals.autopls <- function (object, ...) { lv <- get.lv (object) class (object) <- 'mvr' residuals (object) [,,lv] } scores.autopls <- function (object, ...) { lv <- get.lv (object) class (object) <- 'mvr' scores (object) [,lv] } loadings.autopls <- function (object, ...) { lv <- get.lv (object) class (object) <- 'mvr' loadings (object) [,lv] } get.lv <- function (object) { if (class (object) == 'autopls') return (object$metapls$current.lv) if (class (object) == 'slim') return (object$current.lv) } get.iter <- function (object) { if (class (object) == 'autopls') return (object$metapls$current.iter) if (class (object) == 'slim') return (object$current.iter) } slim <- function (object) { nobj <- list (coefficients = coef (object), method = object$method, scale = object$scale, call = object$metapls$call, predictors = object$predictors, metapls = list (current.iter = get.iter (object), current.lv = get.lv (object), preprocessing = object$metapls$preprocessing, scaling = object$metapls$scaling, val = object$metapls$val), slimobj = list (intercept = coef (object, intercept = TRUE) [1], r2 = R2 (object, 'all'), rmse = RMSEP (object, 'all'), N = length (object$metapls$Y))) class (nobj) <- 'slim' return (nobj) }
#' Class \code{"vineCopula"} #' #' A class representing vine copulas in a object oriented implementations. Many #' functions go back to the package \code{\link{VineCopula-package}} #' #' #' @name vineCopula-class #' @aliases vineCopula-class fitCopula,vineCopula-method #' @docType class #' @section Objects from the Class: Objects can be created by calls of the form #' \code{new("vineCopula", ...)} or through the function #' \code{\link{vineCopula}}. #' @author Benedikt Graeler #' @seealso \code{\link{RVineMatrix}} from package #' \code{\link{VineCopula-package}} #' @references Aas, K., C. Czado, A. Frigessi, and H. Bakken (2009). #' Pair-copula constructions of multiple dependence Insurance: Mathematics and #' Economics 44 (2), 182-198. #' @keywords classes #' @examples #' #' showClass("vineCopula") #' NULL validVineCopula = function(object) { dim <- object@dimension if( dim <= 2) return("Number of dimension too small (>2).") if(length(object@copulas)!=(dim*(dim-1)/2)) return("Number of provided copulas does not match given dimension.") if(!any(unlist(lapply(object@copulas,function(x) is(x,"copula"))))) return("Not all provided copulas in your list are indeed copulas.") return (TRUE) } setOldClass("RVineMatrix") setClass("vineCopula", representation = representation(copulas="list", dimension="integer", RVM="RVineMatrix"), prototype = prototype(RVM=structure(list(),class="RVineMatrix")), validity = validVineCopula, contains = list("copula") ) # constructor #' Constructor of the Class \code{\linkS4class{vineCopula}}. #' #' Constructs an instance of the \code{\linkS4class{vineCopula}} class. #' #' #' @param RVM An object of class \code{RVineMatrix} generated from #' \code{\link{RVineMatrix}} in the package \code{\link{VineCopula-package}} or #' an integer (e.g. \code{4L}) defining the dimension (an independent C-vine of #' this dimension will be constructed). #' @param type A predefined type if only the dimension is provided and ignored #' otherwise, the default is a canonical vine #' @return An instance of the \code{\linkS4class{vineCopula}} class. #' @author Benedikt Graeler #' @references Aas, K., C. Czado, A. Frigessi, and H. Bakken (2009). #' Pair-copula constructions of multiple dependence Insurance: Mathematics and #' Economics 44 (2), 182-198. #' @keywords mulitvariate distribution #' @examples #' #' # a C-vine of independent copulas #' vine <- vineCopula(4L, "CVine") #' #' library(copula) #' library(lattice) #' #' cloud(V1 ~ V2 + V3, as.data.frame(rCopula(500, vine))) #' #' @export vineCopula vineCopula <- function (RVM, type="CVine") { # RVM <- 4L if (is.integer(RVM)) {# assuming a dimension stopifnot(type %in% c("CVine","DVine")) if (type=="CVine") RVM <- C2RVine(1:RVM,rep(0,RVM*(RVM-1)/2),rep(0,RVM*(RVM-1)/2)) if (type=="DVine") RVM <- D2RVine(1:RVM,rep(0,RVM*(RVM-1)/2),rep(0,RVM*(RVM-1)/2)) } stopifnot(class(RVM)=="RVineMatrix") ltr <- lower.tri(RVM$Matrix) copDef <- cbind(RVM$family[ltr], RVM$par[ltr], RVM$par2[ltr]) copulas <- rev(apply(copDef,1, function(x) { copulaFromFamilyIndex(x[1],x[2],x[3]) })) new("vineCopula", copulas=copulas, dimension = as.integer(nrow(RVM$Matrix)), RVM=RVM, parameters = numeric(), param.names = character(), param.lowbnd = numeric(), param.upbnd = numeric(), fullname = paste("RVine copula family.")) } showVineCopula <- function(object) { dim <- object@dimension cat(object@fullname, "\n") cat("Dimension: ", dim, "\n") cat("Represented by the following",dim*(dim-1)/2, "copulas:\n") for (i in 1:length(object@copulas)) { cat(" ", class(object@copulas[[i]]), "with parameter(s)", object@copulas[[i]]@parameters, "\n") } } setMethod("show", signature("vineCopula"), showVineCopula) ## density ## dRVine <- function(u, copula, log=FALSE) { RVM <- copula@RVM vineLoglik <- RVineLogLik(u, RVM, separate=TRUE)$loglik if(log) return(vineLoglik) else return(exp(vineLoglik)) } setMethod("dCopula", signature("numeric","vineCopula"), function(u, copula, log, ...) { dRVine(matrix(u, ncol=copula@dimension), copula, log, ...) }) setMethod("dCopula", signature("matrix","vineCopula"), dRVine) setMethod("dCopula", signature("data.frame","vineCopula"), function(u, copula, log, ...) { dRVine(as.matrix(u), copula, log, ...) }) ## simulation rRVine <- function(n, copula) { RVM <- copula@RVM RVineSim(n, RVM) } setMethod("rCopula", signature("numeric","vineCopula"), rRVine) # fitting using RVine fitVineCop <- function(copula, data, method=list(StructureSelect=FALSE, indeptest=FALSE)) { stopifnot(copula@dimension==ncol(data)) if("familyset" %in% names(method)) familyset <- method[["familyset"]] else familyset <- NA if("indeptest" %in% names(method)) indept <- method[["indeptest"]] else indept <- FALSE if("StructureSelect" %in% names(method)) { if(method[["StructureSelect"]]) vineCop <- vineCopula(RVineStructureSelect(data, familyset, indeptest=indept)) else vineCop <- vineCopula(RVineCopSelect(data, familyset, copula@RVM$Matrix, indeptest=indept)) } else { vineCop <- vineCopula(RVineCopSelect(data, familyset, copula@RVM$Matrix, indeptest=indept)) } return(new("fitCopula", estimate = vineCop@parameters, var.est = matrix(NA), method = paste(names(method), method, sep="=", collapse=", "), loglik = RVineLogLik(data, vineCop@RVM)$loglik, fitting.stats=list(convergence = as.integer(NA)), nsample = nrow(data), copula=vineCop)) } setMethod("fitCopula", signature=signature("vineCopula"), fitVineCop)
/R/vineCopulas.R
no_license
digideskio/VineCopula
R
false
false
6,057
r
#' Class \code{"vineCopula"} #' #' A class representing vine copulas in a object oriented implementations. Many #' functions go back to the package \code{\link{VineCopula-package}} #' #' #' @name vineCopula-class #' @aliases vineCopula-class fitCopula,vineCopula-method #' @docType class #' @section Objects from the Class: Objects can be created by calls of the form #' \code{new("vineCopula", ...)} or through the function #' \code{\link{vineCopula}}. #' @author Benedikt Graeler #' @seealso \code{\link{RVineMatrix}} from package #' \code{\link{VineCopula-package}} #' @references Aas, K., C. Czado, A. Frigessi, and H. Bakken (2009). #' Pair-copula constructions of multiple dependence Insurance: Mathematics and #' Economics 44 (2), 182-198. #' @keywords classes #' @examples #' #' showClass("vineCopula") #' NULL validVineCopula = function(object) { dim <- object@dimension if( dim <= 2) return("Number of dimension too small (>2).") if(length(object@copulas)!=(dim*(dim-1)/2)) return("Number of provided copulas does not match given dimension.") if(!any(unlist(lapply(object@copulas,function(x) is(x,"copula"))))) return("Not all provided copulas in your list are indeed copulas.") return (TRUE) } setOldClass("RVineMatrix") setClass("vineCopula", representation = representation(copulas="list", dimension="integer", RVM="RVineMatrix"), prototype = prototype(RVM=structure(list(),class="RVineMatrix")), validity = validVineCopula, contains = list("copula") ) # constructor #' Constructor of the Class \code{\linkS4class{vineCopula}}. #' #' Constructs an instance of the \code{\linkS4class{vineCopula}} class. #' #' #' @param RVM An object of class \code{RVineMatrix} generated from #' \code{\link{RVineMatrix}} in the package \code{\link{VineCopula-package}} or #' an integer (e.g. \code{4L}) defining the dimension (an independent C-vine of #' this dimension will be constructed). #' @param type A predefined type if only the dimension is provided and ignored #' otherwise, the default is a canonical vine #' @return An instance of the \code{\linkS4class{vineCopula}} class. #' @author Benedikt Graeler #' @references Aas, K., C. Czado, A. Frigessi, and H. Bakken (2009). #' Pair-copula constructions of multiple dependence Insurance: Mathematics and #' Economics 44 (2), 182-198. #' @keywords mulitvariate distribution #' @examples #' #' # a C-vine of independent copulas #' vine <- vineCopula(4L, "CVine") #' #' library(copula) #' library(lattice) #' #' cloud(V1 ~ V2 + V3, as.data.frame(rCopula(500, vine))) #' #' @export vineCopula vineCopula <- function (RVM, type="CVine") { # RVM <- 4L if (is.integer(RVM)) {# assuming a dimension stopifnot(type %in% c("CVine","DVine")) if (type=="CVine") RVM <- C2RVine(1:RVM,rep(0,RVM*(RVM-1)/2),rep(0,RVM*(RVM-1)/2)) if (type=="DVine") RVM <- D2RVine(1:RVM,rep(0,RVM*(RVM-1)/2),rep(0,RVM*(RVM-1)/2)) } stopifnot(class(RVM)=="RVineMatrix") ltr <- lower.tri(RVM$Matrix) copDef <- cbind(RVM$family[ltr], RVM$par[ltr], RVM$par2[ltr]) copulas <- rev(apply(copDef,1, function(x) { copulaFromFamilyIndex(x[1],x[2],x[3]) })) new("vineCopula", copulas=copulas, dimension = as.integer(nrow(RVM$Matrix)), RVM=RVM, parameters = numeric(), param.names = character(), param.lowbnd = numeric(), param.upbnd = numeric(), fullname = paste("RVine copula family.")) } showVineCopula <- function(object) { dim <- object@dimension cat(object@fullname, "\n") cat("Dimension: ", dim, "\n") cat("Represented by the following",dim*(dim-1)/2, "copulas:\n") for (i in 1:length(object@copulas)) { cat(" ", class(object@copulas[[i]]), "with parameter(s)", object@copulas[[i]]@parameters, "\n") } } setMethod("show", signature("vineCopula"), showVineCopula) ## density ## dRVine <- function(u, copula, log=FALSE) { RVM <- copula@RVM vineLoglik <- RVineLogLik(u, RVM, separate=TRUE)$loglik if(log) return(vineLoglik) else return(exp(vineLoglik)) } setMethod("dCopula", signature("numeric","vineCopula"), function(u, copula, log, ...) { dRVine(matrix(u, ncol=copula@dimension), copula, log, ...) }) setMethod("dCopula", signature("matrix","vineCopula"), dRVine) setMethod("dCopula", signature("data.frame","vineCopula"), function(u, copula, log, ...) { dRVine(as.matrix(u), copula, log, ...) }) ## simulation rRVine <- function(n, copula) { RVM <- copula@RVM RVineSim(n, RVM) } setMethod("rCopula", signature("numeric","vineCopula"), rRVine) # fitting using RVine fitVineCop <- function(copula, data, method=list(StructureSelect=FALSE, indeptest=FALSE)) { stopifnot(copula@dimension==ncol(data)) if("familyset" %in% names(method)) familyset <- method[["familyset"]] else familyset <- NA if("indeptest" %in% names(method)) indept <- method[["indeptest"]] else indept <- FALSE if("StructureSelect" %in% names(method)) { if(method[["StructureSelect"]]) vineCop <- vineCopula(RVineStructureSelect(data, familyset, indeptest=indept)) else vineCop <- vineCopula(RVineCopSelect(data, familyset, copula@RVM$Matrix, indeptest=indept)) } else { vineCop <- vineCopula(RVineCopSelect(data, familyset, copula@RVM$Matrix, indeptest=indept)) } return(new("fitCopula", estimate = vineCop@parameters, var.est = matrix(NA), method = paste(names(method), method, sep="=", collapse=", "), loglik = RVineLogLik(data, vineCop@RVM)$loglik, fitting.stats=list(convergence = as.integer(NA)), nsample = nrow(data), copula=vineCop)) } setMethod("fitCopula", signature=signature("vineCopula"), fitVineCop)
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/data.R \docType{data} \name{nytcovstate} \alias{nytcovstate} \title{NYT COVID-19 data for the US states, current as of Friday, December 4, 2020} \format{ A tibble with 15,194 rows and 5 columns \describe{ \item{date}{Date in YYYY-MM-DD format (date)} \item{state}{State name (character)} \item{fips}{State FIPS code (character)} \item{cases}{Cumulative N reported cases} \item{deaths}{Cumulative N reported deaths} } } \source{ The New York Times \url{https://github.com/nytimes/covid-19-data}. For details on the methods and limitations see \url{https://github.com/nytimes/covid-19-data}. } \usage{ nytcovstate } \description{ A dataset containing US state-level data on COVID-19, collected by the New York Times. } \details{ Table: Data summary\tabular{ll}{ \tab \cr Name \tab nytcovstate \cr Number of rows \tab 15194 \cr Number of columns \tab 5 \cr _______________________ \tab \cr Column type frequency: \tab \cr Date \tab 1 \cr character \tab 2 \cr numeric \tab 2 \cr ________________________ \tab \cr Group variables \tab None \cr } \strong{Variable type: Date}\tabular{lrrlllr}{ skim_variable \tab n_missing \tab complete_rate \tab min \tab max \tab median \tab n_unique \cr date \tab 0 \tab 1 \tab 2020-01-21 \tab 2020-12-03 \tab 2020-07-18 \tab 318 \cr } \strong{Variable type: character}\tabular{lrrrrrrr}{ skim_variable \tab n_missing \tab complete_rate \tab min \tab max \tab empty \tab n_unique \tab whitespace \cr state \tab 0 \tab 1 \tab 4 \tab 24 \tab 0 \tab 55 \tab 0 \cr fips \tab 0 \tab 1 \tab 2 \tab 2 \tab 0 \tab 55 \tab 0 \cr } \strong{Variable type: numeric}\tabular{lrrrrrrrrrl}{ skim_variable \tab n_missing \tab complete_rate \tab mean \tab sd \tab p0 \tab p25 \tab p50 \tab p75 \tab p100 \tab hist \cr cases \tab 0 \tab 1 \tab 81830.86 \tab 150326.1 \tab 1 \tab 3137.5 \tab 23559.5 \tab 96794.25 \tab 1310534 \tab ▇▁▁▁▁ \cr deaths \tab 0 \tab 1 \tab 2481.02 \tab 4956.4 \tab 0 \tab 67.0 \tab 593.0 \tab 2573.00 \tab 34346 \tab ▇▁▁▁▁ \cr } } \keyword{datasets}
/man/nytcovstate.Rd
permissive
Jupikajej/covdata
R
false
true
2,157
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/data.R \docType{data} \name{nytcovstate} \alias{nytcovstate} \title{NYT COVID-19 data for the US states, current as of Friday, December 4, 2020} \format{ A tibble with 15,194 rows and 5 columns \describe{ \item{date}{Date in YYYY-MM-DD format (date)} \item{state}{State name (character)} \item{fips}{State FIPS code (character)} \item{cases}{Cumulative N reported cases} \item{deaths}{Cumulative N reported deaths} } } \source{ The New York Times \url{https://github.com/nytimes/covid-19-data}. For details on the methods and limitations see \url{https://github.com/nytimes/covid-19-data}. } \usage{ nytcovstate } \description{ A dataset containing US state-level data on COVID-19, collected by the New York Times. } \details{ Table: Data summary\tabular{ll}{ \tab \cr Name \tab nytcovstate \cr Number of rows \tab 15194 \cr Number of columns \tab 5 \cr _______________________ \tab \cr Column type frequency: \tab \cr Date \tab 1 \cr character \tab 2 \cr numeric \tab 2 \cr ________________________ \tab \cr Group variables \tab None \cr } \strong{Variable type: Date}\tabular{lrrlllr}{ skim_variable \tab n_missing \tab complete_rate \tab min \tab max \tab median \tab n_unique \cr date \tab 0 \tab 1 \tab 2020-01-21 \tab 2020-12-03 \tab 2020-07-18 \tab 318 \cr } \strong{Variable type: character}\tabular{lrrrrrrr}{ skim_variable \tab n_missing \tab complete_rate \tab min \tab max \tab empty \tab n_unique \tab whitespace \cr state \tab 0 \tab 1 \tab 4 \tab 24 \tab 0 \tab 55 \tab 0 \cr fips \tab 0 \tab 1 \tab 2 \tab 2 \tab 0 \tab 55 \tab 0 \cr } \strong{Variable type: numeric}\tabular{lrrrrrrrrrl}{ skim_variable \tab n_missing \tab complete_rate \tab mean \tab sd \tab p0 \tab p25 \tab p50 \tab p75 \tab p100 \tab hist \cr cases \tab 0 \tab 1 \tab 81830.86 \tab 150326.1 \tab 1 \tab 3137.5 \tab 23559.5 \tab 96794.25 \tab 1310534 \tab ▇▁▁▁▁ \cr deaths \tab 0 \tab 1 \tab 2481.02 \tab 4956.4 \tab 0 \tab 67.0 \tab 593.0 \tab 2573.00 \tab 34346 \tab ▇▁▁▁▁ \cr } } \keyword{datasets}
library(mongolite) library(jsonlite) m <- mongo("users", url = "mongodb://127.0.0.1:27017/mydb") result <- m$find('{}') toJSON(result)
/example/getData.R
permissive
apaichon/rxcute
R
false
false
135
r
library(mongolite) library(jsonlite) m <- mongo("users", url = "mongodb://127.0.0.1:27017/mydb") result <- m$find('{}') toJSON(result)
y <- c(0.00844905448652788,-0.00504879865436605,0.00384615268860546,0.0214293914558992,0.0232839389540449,0.0299121323429455,0.037929328538964,0.0212773984472849,0.0270006018185058,0.0140346711715057,0.0112575217306222,0.0109290705321903,0.00885396831725505,0.00349666585229444,0.00236272591159805,0.000973236086552198,0.0038835000263977,-0.00045288231567433,0.0196473295718213,0.00946080850422915,0.0112360732669257,0.00117118433761707,0.0181931828441741,0.0261393882030352,0.00797523057437033,0.0103805802278299,0.00102805601884839,0.0121423868257255,0.0136988443581618,-0.00370222792120147,0.0180545215605451,0.0158007445313437,0.00493828164058252,0.00517869582362316,-0.00764478831881652,0.0163268932874288,0.00726102423704722,-0.0191951645920371,0.00135203102445294,0.0105821093305369,0.00161812333041045,-0.00221610989906376,0.00544452271118292,0.0128104233856403,0.00792397173089165,0.00317662125770344,0.0171365771930149,0.0138251049918425,0.0121305505685076,0.0109338371002675,0.00105132509076258,0.0014880955127019,0.016955806146556,-0.00333028989666486,-0.00179980563436475,0.0095064701308285,0.0101376682844552,0.00947584230546425,0.0140211447248867,0.00980400009662086,0.0110881246904664,0.0162381708431379,0.00961360895668308,0.00802679894945291,0.00928388631000798,0.0101169774642052,0.00884403517704637,0.00966813847305525,0.00639388367525573,0.000103261522609621,0.000533884086711645,0.0132871299954331,0.0155912107432541,0.0145713278135854,0.0110867688006139,0.0131817367020646,0.0212022076506031,0.00706423430637546,0.00854753116573761,0.0142411976775678,0.0190481949706944,0.0151617430647947,0.0170550754091731,0.0228429587090599,0.0274557520447654,0.0264244321843404,0.0195147486584831,0.0145351396191131,0.0166948785721703,0.00923963144859794,0.0224203685142349,0.0257874502057387,0.0185846056856334,0.0222739735666356,0.0214722812477185,0.0358579525232807,0.0416313834758135,0.0485323461922063,0.0309426125903717,0.0459165989737005,0.059515650122699,0.0811647817310722,0.0493763472194563,0.0356186790234685,0.0367678608789195,0.0266673169265613,0.0294365225999917,0.0460103056488332,0.0505673588211266,0.03430957601553,0.0226226190699194,0.0154778877023167,0.018345313325685,0.0178327965494397,0.0244341357802717,0.0172756554004234,0.0321743570278561,0.0267465059845203,0.072052765407577,0.0286118473932619,0.0473115932904111,0.0476589558588506,0.0283462500655419,0.0190315906164793,0.0244504006677975,0.0387816301941518,0.0248700352276362,0.0243422367363619,0.0173385271622735,0.0232646260176713,0.0120010100385709,0.00765728445192693,0.00495199997397222,0.012725448519325,0.0196367663747411,0.0114817150006719,0.00586377075379119,0.0128263136879202,0.015764819641339,0.0124005131984548,0.0125746558779243,0.0268797663676002,0.00918901754538872,0.00491401480242892,0.00686002066616354,0.00661489209183639,0.00727207694915535,0.0126885933190888,0.0116327023754623,0.00957624526078913,0.0082107849419403,0.0107161278768428,0.00483326218801938,0.0175719935723567,0.0202754753545044,0.0202212772472334,0.0162458446655789,0.0219954787795547,0.0157780062516547,0.0196335798779765,0.0175957618903793,0.0392123740767577,0.0227793019512109,0.015492176615771,0.00536605350463848,0.0149308220794474,0.0107309634350358,0.00964041578217412,0.00515275339565591,0.0148187052139855,0.00553083420129443,0.00430725719758041,-0.0064678630074857,0.00948709158384862,0.00908487078584699,0.00353232440754514,0.00140944350323391,0.0112024499512261,0.00694180217217735,0.00620477688688315,0.00889502956886812,0.0119752766503259,0.00892201227781033,0.00133333353086407,0.00531562713438749,0.00626251095861683,0.00821142593121795,0.00586129974999139,0.00582714500919312,0.00657891231616468,0.0157648196413382,0.00817357584064116,0.00312597941329251,0.0123034078957472,0.00930904184708261,0.00426699824499099,-0.00426699824499099,0.0046857104400285,0.00685404713404161,0.0072202479734873,0.00418786134047444,0.0120882837924579,0.00800695506396689,0.00641588669190707,-0.00116346726329741,0.005899411810082,0.00682487785429178,-0.00115008638323744) w <- 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,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,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,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,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,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1) x <- c(-2.2733,-2.27923,-2.28217,-2.29389,-2.29244,-2.29679,-2.26554,-2.26263,-2.26554,-2.27277,-2.27565,-2.28281,-2.28992,-2.29557,-2.30119,-2.31647,-2.31923,-2.32197,-2.33017,-2.32882,-2.32867,-2.33945,-2.34613,-2.35276,-2.33577,-2.34227,-2.35002,-2.35694,-2.36321,-2.36945,-2.37565,-2.37688,-2.37812,-2.38304,-2.38916,-2.39402,-2.40007,-2.40488,-2.40848,-2.418,-2.42273,-2.42861,-2.42022,-2.42836,-2.41979,-2.43353,-2.43693,-2.44144,-2.44819,-2.45489,-2.46043,-2.47906,-2.46993,-2.47531,-2.47958,-2.48278,-2.49125,-2.5111,-2.49068,-2.36244,-2.38163,-2.22413,-2.23295,-2.17118,-2.18521,-2.19538,-2.20454,-2.2238,-2.23467,-2.2543,-2.12563,-2.14028,-2.0172,-2.03374,-2.05324,-2.09113,-2.13211,-2.15126,-2.16142,-2.16717,-2.17575,-2.18988,-2.20174,-2.16044,-2.17337,-2.18614,-2.19146,-2.21053,-2.22155,-2.22669,-2.21563,-2.2296,-2.24277,-2.24149,-2.25546,-2.26865,-2.28819,-2.29857,-2.31403,-2.27793,-2.27276,-2.28103,-2.30422,-2.37907,-2.38798,-2.39993,-2.40771,-2.41541,-2.4254,-2.42642,-2.44464,-2.46516,-2.4702,-2.47181,-2.47277,-2.4817,-2.4839,-2.49199,-2.46234,-2.46781,-2.47149,-2.46097,-2.43544,-2.4037,-2.39928,-2.21877,-2.17031,-2.18043,-2.19534,-2.21525,-2.22842,-2.22932,-2.26553,-2.23386,-2.23143,-2.19198,-2.20149,-2.19055,-2.20962,-2.22383,-2.24191,-2.26151,-2.28343,-2.27503,-2.25608,-2.26334,-2.14853,-2.16142,-2.18046,-2.17278,-2.12764,-2.08353,-2.09376,-2.11463,-2.11156,-2.14585,-2.18258,-2.22489,-2.21789,-2.1956,-2.19549,-2.15888,-2.16484,-2.14381,-2.12799,-2.13736,-2.14175,-2.14568,-2.18382,-2.17457,-2.17909,-2.13288,-2.13733,-2.13973,-2.11977,-2.12496,-2.12963,-2.13316,-2.13693,-2.13956,-2.13897,-2.16459,-2.15645,-2.15973,-2.16443,-2.16476,-2.16338,-2.16459,-2.17074,-2.15016,-2.15394,-2.15359) n <- 192
/data.R/fig07_01.data.R
permissive
enguang2/stan-statespace
R
false
false
6,170
r
y <- c(0.00844905448652788,-0.00504879865436605,0.00384615268860546,0.0214293914558992,0.0232839389540449,0.0299121323429455,0.037929328538964,0.0212773984472849,0.0270006018185058,0.0140346711715057,0.0112575217306222,0.0109290705321903,0.00885396831725505,0.00349666585229444,0.00236272591159805,0.000973236086552198,0.0038835000263977,-0.00045288231567433,0.0196473295718213,0.00946080850422915,0.0112360732669257,0.00117118433761707,0.0181931828441741,0.0261393882030352,0.00797523057437033,0.0103805802278299,0.00102805601884839,0.0121423868257255,0.0136988443581618,-0.00370222792120147,0.0180545215605451,0.0158007445313437,0.00493828164058252,0.00517869582362316,-0.00764478831881652,0.0163268932874288,0.00726102423704722,-0.0191951645920371,0.00135203102445294,0.0105821093305369,0.00161812333041045,-0.00221610989906376,0.00544452271118292,0.0128104233856403,0.00792397173089165,0.00317662125770344,0.0171365771930149,0.0138251049918425,0.0121305505685076,0.0109338371002675,0.00105132509076258,0.0014880955127019,0.016955806146556,-0.00333028989666486,-0.00179980563436475,0.0095064701308285,0.0101376682844552,0.00947584230546425,0.0140211447248867,0.00980400009662086,0.0110881246904664,0.0162381708431379,0.00961360895668308,0.00802679894945291,0.00928388631000798,0.0101169774642052,0.00884403517704637,0.00966813847305525,0.00639388367525573,0.000103261522609621,0.000533884086711645,0.0132871299954331,0.0155912107432541,0.0145713278135854,0.0110867688006139,0.0131817367020646,0.0212022076506031,0.00706423430637546,0.00854753116573761,0.0142411976775678,0.0190481949706944,0.0151617430647947,0.0170550754091731,0.0228429587090599,0.0274557520447654,0.0264244321843404,0.0195147486584831,0.0145351396191131,0.0166948785721703,0.00923963144859794,0.0224203685142349,0.0257874502057387,0.0185846056856334,0.0222739735666356,0.0214722812477185,0.0358579525232807,0.0416313834758135,0.0485323461922063,0.0309426125903717,0.0459165989737005,0.059515650122699,0.0811647817310722,0.0493763472194563,0.0356186790234685,0.0367678608789195,0.0266673169265613,0.0294365225999917,0.0460103056488332,0.0505673588211266,0.03430957601553,0.0226226190699194,0.0154778877023167,0.018345313325685,0.0178327965494397,0.0244341357802717,0.0172756554004234,0.0321743570278561,0.0267465059845203,0.072052765407577,0.0286118473932619,0.0473115932904111,0.0476589558588506,0.0283462500655419,0.0190315906164793,0.0244504006677975,0.0387816301941518,0.0248700352276362,0.0243422367363619,0.0173385271622735,0.0232646260176713,0.0120010100385709,0.00765728445192693,0.00495199997397222,0.012725448519325,0.0196367663747411,0.0114817150006719,0.00586377075379119,0.0128263136879202,0.015764819641339,0.0124005131984548,0.0125746558779243,0.0268797663676002,0.00918901754538872,0.00491401480242892,0.00686002066616354,0.00661489209183639,0.00727207694915535,0.0126885933190888,0.0116327023754623,0.00957624526078913,0.0082107849419403,0.0107161278768428,0.00483326218801938,0.0175719935723567,0.0202754753545044,0.0202212772472334,0.0162458446655789,0.0219954787795547,0.0157780062516547,0.0196335798779765,0.0175957618903793,0.0392123740767577,0.0227793019512109,0.015492176615771,0.00536605350463848,0.0149308220794474,0.0107309634350358,0.00964041578217412,0.00515275339565591,0.0148187052139855,0.00553083420129443,0.00430725719758041,-0.0064678630074857,0.00948709158384862,0.00908487078584699,0.00353232440754514,0.00140944350323391,0.0112024499512261,0.00694180217217735,0.00620477688688315,0.00889502956886812,0.0119752766503259,0.00892201227781033,0.00133333353086407,0.00531562713438749,0.00626251095861683,0.00821142593121795,0.00586129974999139,0.00582714500919312,0.00657891231616468,0.0157648196413382,0.00817357584064116,0.00312597941329251,0.0123034078957472,0.00930904184708261,0.00426699824499099,-0.00426699824499099,0.0046857104400285,0.00685404713404161,0.0072202479734873,0.00418786134047444,0.0120882837924579,0.00800695506396689,0.00641588669190707,-0.00116346726329741,0.005899411810082,0.00682487785429178,-0.00115008638323744) w <- 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,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,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,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,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,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1) x <- c(-2.2733,-2.27923,-2.28217,-2.29389,-2.29244,-2.29679,-2.26554,-2.26263,-2.26554,-2.27277,-2.27565,-2.28281,-2.28992,-2.29557,-2.30119,-2.31647,-2.31923,-2.32197,-2.33017,-2.32882,-2.32867,-2.33945,-2.34613,-2.35276,-2.33577,-2.34227,-2.35002,-2.35694,-2.36321,-2.36945,-2.37565,-2.37688,-2.37812,-2.38304,-2.38916,-2.39402,-2.40007,-2.40488,-2.40848,-2.418,-2.42273,-2.42861,-2.42022,-2.42836,-2.41979,-2.43353,-2.43693,-2.44144,-2.44819,-2.45489,-2.46043,-2.47906,-2.46993,-2.47531,-2.47958,-2.48278,-2.49125,-2.5111,-2.49068,-2.36244,-2.38163,-2.22413,-2.23295,-2.17118,-2.18521,-2.19538,-2.20454,-2.2238,-2.23467,-2.2543,-2.12563,-2.14028,-2.0172,-2.03374,-2.05324,-2.09113,-2.13211,-2.15126,-2.16142,-2.16717,-2.17575,-2.18988,-2.20174,-2.16044,-2.17337,-2.18614,-2.19146,-2.21053,-2.22155,-2.22669,-2.21563,-2.2296,-2.24277,-2.24149,-2.25546,-2.26865,-2.28819,-2.29857,-2.31403,-2.27793,-2.27276,-2.28103,-2.30422,-2.37907,-2.38798,-2.39993,-2.40771,-2.41541,-2.4254,-2.42642,-2.44464,-2.46516,-2.4702,-2.47181,-2.47277,-2.4817,-2.4839,-2.49199,-2.46234,-2.46781,-2.47149,-2.46097,-2.43544,-2.4037,-2.39928,-2.21877,-2.17031,-2.18043,-2.19534,-2.21525,-2.22842,-2.22932,-2.26553,-2.23386,-2.23143,-2.19198,-2.20149,-2.19055,-2.20962,-2.22383,-2.24191,-2.26151,-2.28343,-2.27503,-2.25608,-2.26334,-2.14853,-2.16142,-2.18046,-2.17278,-2.12764,-2.08353,-2.09376,-2.11463,-2.11156,-2.14585,-2.18258,-2.22489,-2.21789,-2.1956,-2.19549,-2.15888,-2.16484,-2.14381,-2.12799,-2.13736,-2.14175,-2.14568,-2.18382,-2.17457,-2.17909,-2.13288,-2.13733,-2.13973,-2.11977,-2.12496,-2.12963,-2.13316,-2.13693,-2.13956,-2.13897,-2.16459,-2.15645,-2.15973,-2.16443,-2.16476,-2.16338,-2.16459,-2.17074,-2.15016,-2.15394,-2.15359) n <- 192
# Coursera: Practical Machine learning # Script from course commented by Alexander Buschle rm(list = ls()) # Week 2 - Lecture 8 - Prediction with Regression #### # Example: Old faithful eruptions #### library(caret) data(faithful) set.seed(333) inTrain <- createDataPartition(y = faithful$waiting, p = 0.5, list = FALSE) trainFaith <- faithful[inTrain, ] testFaith <- faithful[-inTrain, ] head(trainFaith) # eruptions waiting # 1 3.600 79 # 3 3.333 74 # 5 4.533 85 # 6 2.883 55 # 7 4.700 88 # 8 3.600 85 # Eruption duration versus waiting time #### plot(trainFaith$waiting, trainFaith$eruptions, pch = 19, col = "blue", xlab = "Waiting", ylab = "Duration") # Fit a linear model #### lm1 <- lm(eruptions ~ waiting, data = trainFaith) # outcome (eruptions) is what you want to predict # ~: the tilde sign says that you predict the outcome as a function of everything right of the tilde # data: tells the programm which data to use summary(lm1) # Call: # lm(formula = eruptions ~ waiting, data = trainFaith) # Residuals: # Min 1Q Median 3Q Max # -1.26990 -0.34789 0.03979 0.36589 1.05020 # # Coefficients: # | # V <-------- the estimates are the important points when it is about prediction # Estimate Std. Error t value Pr(>|t|) # (Intercept) -1.792739 0.227869 -7.867 1.04e-12 *** # waiting 0.073901 0.003148 23.474 < 2e-16 *** # # --- # Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 # # Residual standard error: 0.495 on 135 degrees of freedom # Multiple R-squared: 0.8032, Adjusted R-squared: 0.8018 # F-statistic: 551 on 1 and 135 DF, p-value: < 2.2e-16 # Easier to read summary is this: lm1 # Call: # lm(formula = eruptions ~ waiting, data = trainFaith) # # Coefficients: # (Intercept) waiting # -1.7927 0.0739 # (Intercept) in Estimate is the b0 constant # waiting is the b1 constant # Model fit #### plot(trainFaith$waiting, trainFaith$eruptions, pch = 19, col = "blue", xlab = "Waiting", ylab = "Duration") lines(trainFaith$waiting, lm1$fitted.values, lwd = 3) # Predict a new value #### coef(lm1)[1] + coef(lm1)[2] * 80 # or lm1$coefficients[1] + lm1$coefficients[2] * 80 # (Intercept) # 4.119307 # automated newdata <- data.frame(waiting = 80) predict(lm1, newdata) # Plot predictions – training and test #### par(mfrow = c(1,2)) plot(trainFaith$waiting, trainFaith$eruptions, pch = 19, col = "blue", xlab = "Waiting", ylab = "Duration") lines(trainFaith$waiting, predict(lm1), lwd = 3) plot(testFaith$waiting, testFaith$eruptions, pch = 19, col = "blue", xlab = "Waiting", ylab = "Duration") lines(testFaith$waiting, predict(lm1, newdata = testFaith), lwd = 3) # Get training set/ test set errors #### # Calculate RMSE on training sqrt(sum((lm1$fitted.values - trainFaith$eruptions)^2)) # [1] 5.75186 # Calculate RMSE on test sqrt(sum((predict(lm1, newdata = testFaith) - testFaith$eruptions)^2)) # [1] 5.838559 # Prediction intervals #### par(mfrow = c(1,1)) pred1 <- predict(lm1, newdata = testFaith, interval = "prediction") ord <- order(testFaith$waiting) plot(testFaith$waiting, testFaith$eruptions, pch = 19, col = "blue") matlines(testFaith$waiting[ord], pred1[ord, ], type = "l", col = c(1,2,2), lty = c(1,1,1), lwd = 3) # Same process with caret modFit <- train(eruptions ~ waiting, data = trainFaith, method = "lm") # outcome: eruptions # predictor: wainting # data: data set, on which to build it on # method: linear modelling summary(modFit$finalModel) # Call: # lm(formula = .outcome ~ ., data = dat) # # Residuals: # Min 1Q Median 3Q Max # -1.26990 -0.34789 0.03979 0.36589 1.05020 # # Coefficients: # | # V <- here is about the same result like for our hand made one # Estimate Std. Error t value Pr(>|t|) # (Intercept) -1.792739 0.227869 -7.867 1.04e-12 *** # waiting 0.073901 0.003148 23.474 < 2e-16 *** # --- # Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 # # Residual standard error: 0.495 on 135 degrees of freedom # Multiple R-squared: 0.8032, Adjusted R-squared: 0.8018 # F-statistic: 551 on 1 and 135 DF, p-value: < 2.2e-16 # also interesting modFit # Linear Regression # # 137 samples # 1 predictor # # No pre-processing # Resampling: Bootstrapped (25 reps) # Summary of sample sizes: 137, 137, 137, 137, 137, 137, ... # Resampling results: # # RMSE Rsquared MAE # 0.5043234 0.7976798 0.4092342 # # Tuning parameter 'intercept' was held constant at a value of TRUE
/R_Practical_Machine_Learning_Coursera/2nd_Week/Week_2_lecture_8_Predicting_with_Regression.R
no_license
DrBuschle/Machine_Learning
R
false
false
4,777
r
# Coursera: Practical Machine learning # Script from course commented by Alexander Buschle rm(list = ls()) # Week 2 - Lecture 8 - Prediction with Regression #### # Example: Old faithful eruptions #### library(caret) data(faithful) set.seed(333) inTrain <- createDataPartition(y = faithful$waiting, p = 0.5, list = FALSE) trainFaith <- faithful[inTrain, ] testFaith <- faithful[-inTrain, ] head(trainFaith) # eruptions waiting # 1 3.600 79 # 3 3.333 74 # 5 4.533 85 # 6 2.883 55 # 7 4.700 88 # 8 3.600 85 # Eruption duration versus waiting time #### plot(trainFaith$waiting, trainFaith$eruptions, pch = 19, col = "blue", xlab = "Waiting", ylab = "Duration") # Fit a linear model #### lm1 <- lm(eruptions ~ waiting, data = trainFaith) # outcome (eruptions) is what you want to predict # ~: the tilde sign says that you predict the outcome as a function of everything right of the tilde # data: tells the programm which data to use summary(lm1) # Call: # lm(formula = eruptions ~ waiting, data = trainFaith) # Residuals: # Min 1Q Median 3Q Max # -1.26990 -0.34789 0.03979 0.36589 1.05020 # # Coefficients: # | # V <-------- the estimates are the important points when it is about prediction # Estimate Std. Error t value Pr(>|t|) # (Intercept) -1.792739 0.227869 -7.867 1.04e-12 *** # waiting 0.073901 0.003148 23.474 < 2e-16 *** # # --- # Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 # # Residual standard error: 0.495 on 135 degrees of freedom # Multiple R-squared: 0.8032, Adjusted R-squared: 0.8018 # F-statistic: 551 on 1 and 135 DF, p-value: < 2.2e-16 # Easier to read summary is this: lm1 # Call: # lm(formula = eruptions ~ waiting, data = trainFaith) # # Coefficients: # (Intercept) waiting # -1.7927 0.0739 # (Intercept) in Estimate is the b0 constant # waiting is the b1 constant # Model fit #### plot(trainFaith$waiting, trainFaith$eruptions, pch = 19, col = "blue", xlab = "Waiting", ylab = "Duration") lines(trainFaith$waiting, lm1$fitted.values, lwd = 3) # Predict a new value #### coef(lm1)[1] + coef(lm1)[2] * 80 # or lm1$coefficients[1] + lm1$coefficients[2] * 80 # (Intercept) # 4.119307 # automated newdata <- data.frame(waiting = 80) predict(lm1, newdata) # Plot predictions – training and test #### par(mfrow = c(1,2)) plot(trainFaith$waiting, trainFaith$eruptions, pch = 19, col = "blue", xlab = "Waiting", ylab = "Duration") lines(trainFaith$waiting, predict(lm1), lwd = 3) plot(testFaith$waiting, testFaith$eruptions, pch = 19, col = "blue", xlab = "Waiting", ylab = "Duration") lines(testFaith$waiting, predict(lm1, newdata = testFaith), lwd = 3) # Get training set/ test set errors #### # Calculate RMSE on training sqrt(sum((lm1$fitted.values - trainFaith$eruptions)^2)) # [1] 5.75186 # Calculate RMSE on test sqrt(sum((predict(lm1, newdata = testFaith) - testFaith$eruptions)^2)) # [1] 5.838559 # Prediction intervals #### par(mfrow = c(1,1)) pred1 <- predict(lm1, newdata = testFaith, interval = "prediction") ord <- order(testFaith$waiting) plot(testFaith$waiting, testFaith$eruptions, pch = 19, col = "blue") matlines(testFaith$waiting[ord], pred1[ord, ], type = "l", col = c(1,2,2), lty = c(1,1,1), lwd = 3) # Same process with caret modFit <- train(eruptions ~ waiting, data = trainFaith, method = "lm") # outcome: eruptions # predictor: wainting # data: data set, on which to build it on # method: linear modelling summary(modFit$finalModel) # Call: # lm(formula = .outcome ~ ., data = dat) # # Residuals: # Min 1Q Median 3Q Max # -1.26990 -0.34789 0.03979 0.36589 1.05020 # # Coefficients: # | # V <- here is about the same result like for our hand made one # Estimate Std. Error t value Pr(>|t|) # (Intercept) -1.792739 0.227869 -7.867 1.04e-12 *** # waiting 0.073901 0.003148 23.474 < 2e-16 *** # --- # Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 # # Residual standard error: 0.495 on 135 degrees of freedom # Multiple R-squared: 0.8032, Adjusted R-squared: 0.8018 # F-statistic: 551 on 1 and 135 DF, p-value: < 2.2e-16 # also interesting modFit # Linear Regression # # 137 samples # 1 predictor # # No pre-processing # Resampling: Bootstrapped (25 reps) # Summary of sample sizes: 137, 137, 137, 137, 137, 137, ... # Resampling results: # # RMSE Rsquared MAE # 0.5043234 0.7976798 0.4092342 # # Tuning parameter 'intercept' was held constant at a value of TRUE
#' Create bed file of CpG or GpC motifs #' #' @param genomeFile String with path to fasta file with genome sequence #' @param CGorGC String with motif to be found (either "CG" or "GC") #' @return A bed file with locations of the C in all occurrences of this motif on both strands will be written to #' the same directory as genomeFile with the extension .CpG.bed or .GpC.bed #' #' @export makeCGorGCbed<-function(genomeFile,CGorGC) { if (! CGorGC %in% c("CG","GC")) { print("The variable 'CGorGC' must have the value 'CG' or 'GC'") } genome<-Biostrings::readDNAStringSet(genomeFile) Cmotifs<-Biostrings::vmatchPattern(CGorGC,genome) # create gr for Cs on positive strand gr<-GenomicRanges::GRanges(seqnames=S4Vectors::Rle(names(Cmotifs),sapply(Cmotifs,length)), ranges=unlist(Cmotifs), strand="+") allGR<-gr # create gr for Cs on negative strand gr<-GenomicRanges::GRanges(seqnames=S4Vectors::Rle(names(Cmotifs),sapply(Cmotifs,length)), ranges=unlist(Cmotifs), strand="-") allGR<-c(allGR,gr) # resize to cover only Cs allGR<-GenomicRanges::resize(allGR,width=1,fix=ifelse(CGorGC=="CG","start","end")) allGR<-GenomicRanges::sort(allGR,ignore.strand=T) #export as bed file to genomeFile directory outDir<-dirname(genomeFile) outFile<-gsub("fa",paste0(CGorGC,".bed"),basename(genomeFile)) rtracklayer::export.bed(allGR,con=paste0(outDir,"/",outFile)) } #' Extract methylation matrix from alignment file #' #' @param bamFile String with path to bam file with alignments of reads to genome #' @param genomeFile String with path to fasta file with genome sequence #' @param bedFile String with path to .bed file with locations of Cs to be evaluated #' @param region Genomic range of region for which to extract reads. It can also #' be a string denoting the region, e.g. "X:8069396-8069886" #' @param samtoolsPath Path to samtools executable (default="") if not in unix $PATH #' @param maxDepth Maximum number of reads to take for a given region (default=10,000) #' @return A matrix with reads as row names and C positions as column names. #' Every position in matrix has a value of 0 (non-converted C = methylated), 1 (converted C (T) = not methylated) or NA (undetermined) #' #' @export getReadMatrix<-function(bamFile, genomeFile, bedFile, region, samtoolsPath="", maxDepth=10000) { if (class(region)=="GRanges") { region<-paste0(GenomeInfoDb::seqnames(region), ":", IRanges::start(region), "-", IRanges::end(region)) } # use samtools mpileup to call C methylation tab<-system(paste0(samtoolsPath, "samtools mpileup -f ", genomeFile, " -l ", bedFile, " -r ", region, " --output-QNAME --max-depth ", maxDepth, " --min-BQ 8 ", " --ff UNMAP,QCFAIL ", bamFile),intern=T) #tab<-Rsamtools::pileup(file=bamFile,max_depth=maxDepth,min_base_quality=8,) if (length(tab)>0) { # convert output to data frame tab<-lapply(tab,strsplit,"\t") tab<-lapply(1:length(tab),function(x){t(tab[[x]][[1]])}) tab<-as.data.frame(do.call(rbind,tab),stringsAsFactors=F) colnames(tab)<-c("chr","start","ref","count","matches","BQ","reads") # make empty matrix of reads x C positions allReads<-unique(sort(unlist(sapply(tab$reads,strsplit,split=","),use.names=FALSE))) allPos<-tab$start mat<-matrix(data=NA,nrow=length(allReads),ncol=length(allPos)) colnames(mat)<-allPos rownames(mat)<-allReads # scroll through tab to extract methylation values in strand aware way for (line in 1:nrow(tab)) { df<-pileupToConversionStatus(tab[line,]) m1<-mat[df$reads,df$pos] m2<-df$Cconv mat[df$reads,df$pos]<-ifelse(is.na(m1), ifelse(is.na(m2), NA, m2), ifelse(is.na(m2), m1, (m1 + m2))) } } else { mat<-NULL } return(mat) } #' Extract methylation calls from single line of pileup file #' #' @param pileupLine One line data frame from pileup file. Columns have been named: c("chr","start","ref","count","matches","BQ","reads") #' @return A data frame with C position, read name and C conversion call 0 (not converted (C) = methylated), 1 (converted (T) = not methylated) #' @export pileupToConversionStatus<-function(pileupLine) { # if read matches forward strand match<-parseMatchString(pileupLine$matches) if(nchar(match)!=pileupLine$count) { "problem with match string" } df=NULL posConv=NULL posUnconv=NULL if (pileupLine$ref=="c" | pileupLine$ref=="C") { matchList<-stringr::str_locate_all(match,"[\\.,]")[[1]] if(dim(matchList)[1]>0) { posConv<-rep(pileupLine$start,dim(matchList)[1]) readsConv<-unlist(strsplit(pileupLine$reads,","))[matchList[,1]] } matchList<-stringr::str_locate_all(match,"[Tt]")[[1]] if(dim(matchList)[1]>0) { posUnconv<-rep(pileupLine$start,dim(matchList)[1]) readsUnconv<-unlist(strsplit(pileupLine$reads,","))[matchList[,1]] } } # if read matches reverse strand if (pileupLine$ref=="g" | pileupLine$ref=="G") { matchList<-stringr::str_locate_all(match,"[\\.,]")[[1]] if(dim(matchList)[1]>0) { posConv<-rep(pileupLine$start,dim(matchList)[1]) readsConv<-unlist(strsplit(pileupLine$reads,","))[matchList[,1]] } matchList<-stringr::str_locate_all(match,"[aA]")[[1]] if(dim(matchList)[1]>0) { posUnconv<-rep(pileupLine$start,dim(matchList)[1]) readsUnconv<-unlist(strsplit(pileupLine$reads,","))[matchList[,1]] } } #prepare df for export first<-TRUE if (!is.null(posConv)) { convdf<-data.frame(pos=posConv,reads=readsConv,Cconv=0,stringsAsFactors=F) df<-convdf first<-FALSE } if (!is.null(posUnconv)) { unconvdf<-data.frame(pos=posUnconv,reads=readsUnconv,Cconv=1,stringsAsFactors=F) if (first==FALSE) { df<-rbind(df,unconvdf) } else { df<-unconvdf } } return(df) } # a dot stands for a match to the reference base on the forward strand, # a comma for a match on the reverse strand, a '>' or '<' for a reference skip, # ACGTN for a mismatch on the forward strand and # acgtn for a mismatch on the reverse strand. # \\+[0-9]+[ACGTNacgtn]+ indicates there is an insertion between this reference position and the next reference position # -[0-9]+[ACGTNacgtn]+ represents a deletion from the reference # * does not add character # $ indicates end of read, it adds one character and should be removed # ^ indicates a read start mark followed by mapping quality. two characters should be removed # +[1-9]+[] #' Clean up match string from pileup file #' #' @param match Match string from pileup file. #' @return A cleaned up match string with no indels or start/end line info parseMatchString<-function(match) { match<-gsub("\\$","",match) # remove end of read mark match<-gsub("\\^.?","",match) # remove start of read mark + read qual char indelCount<-stringr::str_extract_all(match,"[0-9]+")[[1]] for (i in indelCount) { # remove indel info around match m<-paste0("[\\+-]",i,".{",i,"}") match<-stringr::str_replace(match,m,"") } return(match) } #' Convert methylation matrix to genomic ranges #' #' @param mat Methylation matrix with reads x Cposition #' @param gr GRanges object for which the methylation matrix was made #' @return genomic ranges of Cpositions with mcols containing the reads as columns #' @export matToGR<-function(mat,gr) { matgr<-GenomicRanges::GRanges(seqnames=GenomeInfoDb::seqnames(gr), IRanges::IRanges(start=as.integer(colnames(mat)),width=1), strand="*") GenomicRanges::mcols(matgr)<-t(mat) return(matgr) } #' Check if vector is only NAs #' @param vec Vector of values to be checked #' @examples #' allNAs(c(NA, NA, NA)) #' allNAs(c(NA,1,NA)) #' allNAs(c(1,2,3)) #' allNAs(c()) #' @return boolean TRUE or FALSE #' @export allNAs<-function(vec) { if (sum(is.na(vec)) == length(vec)) { returnVal=TRUE } else { returnVal=FALSE } return(returnVal) } #' Combine CG and GC methylation matrices #' #' Methylation matrices are tricky to merge because: #' #' 1. Forward and reverse reads will have methylation calls at different positions #' even if they are part of the same motif because the C is shifted by 1 between #' the two strands. Therefore we "destrand" the reads by averaging all methylation #' calls within the same motif (and ingoring NAs). The genomic positions in the final merged #' matrix will be on the position of the 1st bp of the motif for CG motifs and the genomic #' position of the 2nd bp of the motif for GC motifs. #' #' 2. GCG/CGC motifs will have methylation calls from three Cs and it is not clear #' whether the middle C should be part of one motif or the other. Therefore we consider #' such triplets as a single motif and average the methylation calls from all three Cs. #' The genomic position used in the final merged matrix will be that of the middle bp #' of the motif. #' #' 3. Longer GCGC/CGCG runs have multiple overlapping motifs layered within them. To deal #' with that we split these runs into 2-3bp motifs. If the length of the run is an even #' number, it is split into doublets and considered as simple CG or GC motifs. If the #' length of the run is an odd number, one triplet is created, and the rest is split into #' doublets. This creates a set of unique non-overlapping motifs in the genome that are either #' CG or GC 2bp motifs, or a GCG/CGC 2bp motif. This unique set is created before hand #' with the nanodsmf::findGenomeMotifs function and can be stored in a RDS file. Doublet #' and triplet motifs created from the run are treated the same as isolated doublet and triplet #' motifs, as described in points 1. and 2. above. #' #' @param matCG Methylation matrix (reads x positons) of C positions within CG motifs #' @param matGC Methylation matrix (reads x positons) of C positions within GC motifs #' @param regionGR GRanges object of region used to make methylation matrices #' @param genomeMotifGR GRanges object with all unique non-overlapping CG/GC/GCGorCGC motifs in genome #' @return Merged methylation matrix #' @export combineCGandGCmatrices<-function(matCG,matGC,regionGR,genomeMotifGR){ if (!is.null(matCG) & !is.null(matGC)) { # convert matCG and matGC to genomic ranges with transposed matrix (positions x reads) matCGgr<-matToGR(matCG,regionGR) matGCgr<-matToGR(matGC,regionGR) #subset genomeMotifGR by regionGR to get motifs that should be present in the matrices regGCCG<-IRanges::subsetByOverlaps(genomeMotifGR,regionGR,ignore.strand=TRUE) # get vector of read names for each gr CGreads<-colnames(GenomicRanges::mcols(matCGgr)) GCreads<-colnames(GenomicRanges::mcols(matGCgr)) # use genomeMotifGR subset to "destrand" CG and GC calls by summing positions within motifs cg<-grangesutils::applyGRonGR(regGCCG,matCGgr,CGreads,sum,na.rm=T) gc<-grangesutils::applyGRonGR(regGCCG,matGCgr,GCreads,sum,na.rm=T) # ensure no value in the matrix exceeds 1 maxval1<-function(m1){ ifelse(is.na(m1), NA, ifelse(m1>1, 1, m1)) } GenomicRanges::mcols(cg)[,2:dim(GenomicRanges::mcols(cg))[2]]<- data.table::as.data.table(maxval1(as.matrix(GenomicRanges::mcols(cg)[,2:dim(GenomicRanges::mcols(cg))[2]]))) GenomicRanges::mcols(gc)[,2:dim(GenomicRanges::mcols(gc))[2]]<- data.table::as.data.table(maxval1(as.matrix(GenomicRanges::mcols(gc)[,2:dim(GenomicRanges::mcols(gc))[2]]))) # find gr that overlap between cg and gc calls ol<-IRanges::findOverlaps(cg,gc) if (length(ol)>=1) { # find reads that are in both grs (GCGorCGC motifs) idxCGinGC<-CGreads %in% GCreads idxGCinCG<-GCreads %in% CGreads # average values from both matrices at these overlapping sites (NAs are ignored, but # kept if no real values is found) m1<-as.matrix(GenomicRanges::mcols(cg)[S4Vectors::queryHits(ol),CGreads[idxCGinGC]]) m2<-as.matrix(GenomicRanges::mcols(gc)[S4Vectors::subjectHits(ol),GCreads[idxGCinCG]]) mAvr<-ifelse(is.na(m1), ifelse(is.na(m2), NA, m2), ifelse(is.na(m2), m1, (m1 + m2)/2)) GenomicRanges::mcols(cg)[S4Vectors::queryHits(ol),CGreads[idxCGinGC]]<-tibble::as_tibble(mAvr) # make nonoverlapping combined list allGR<-c(cg,gc[-S4Vectors::subjectHits(ol)]) } else { allGR<-c(cg,gc) } # shrink gr to single bp CG1bp<-GenomicRanges::resize(allGR[allGR$context=="HCG"],width=1,fix="start") GC1bp<-GenomicRanges::resize(allGR[allGR$context=="GCH"],width=1,fix="end") GCGorCGC1bp<-GenomicRanges::resize(allGR[allGR$context=="GCGorCGC"],width=1,fix="center") # combine and sort allGR<-GenomicRanges::sort(c(CG1bp,GC1bp,GCGorCGC1bp)) # convert back to matrix readNum<-dim(GenomicRanges::mcols(allGR))[2]-1 # don't include the "context" column convMat<-t(as.matrix(GenomicRanges::mcols(allGR)[,2:(readNum+1)])) colnames(convMat)<-GenomicRanges::start(allGR) # remove reads with aboslutly no methylation info convMat<-convMat[rowSums(is.na(convMat))!=dim(convMat)[2],] } else { convMat<-NULL } return(convMat) } #' Get methylation frequency genomic ranges #' #' Takes MethylDackel methylation call bedgraph files for CpG CHH and CHG motifs and creates genomic ranges for CG, GC and all other Cs. Output is a list of these three genomic ranges objects. #' #' @param baseFileName base file name used in MethylDackel extract command (assumes _CpG.bedgraph, _CHH.bedgraph and _CHG.bedgraph extensions were later added by MethylDackel) #' @param pathToMethCalls Path to folder in which MethylDackel output is found #' @param motifFile Path to GRanges object with all unique CG/GC/GCGorCGC motifs in genome #' @param minDepth Minimum read depth. Positions with fewer than this number are discarded (default=5) #' @return Named list with CG, GC and C genomic ranges with metadata about methylation. #' @export getMethFreqGR<-function(baseFileName,pathToMethCalls,motifFile,minDepth=5) { # get genome motifs gnmMotifs<-readRDS(motifFile) GCmotifs<-gnmMotifs[gnmMotifs$context=="GCH"] CGmotifs<-gnmMotifs[gnmMotifs$context=="HCG"] GCGmotifs<-gnmMotifs[gnmMotifs$context=="GCGorCGC"] # make sure the path variable is set pathToMethCalls<-gsub("/$","",pathToMethCalls) if (! exists("pathToMethCalls")) {pathToMethCalls="."} # read in methyldackel output files methCG<-rtracklayer::import(paste0(pathToMethCalls,"/",baseFileName,"_CpG.bedGraph"),format="bedGraph") colnames(GenomicRanges::mcols(methCG))<-c("methPercent","methylated","nonMethylated") methCG$readDepth<-rowSums(cbind(methCG$methylated,methCG$nonMethylated)) methCG<-methCG[methCG$readDepth>minDepth] methCHH<-rtracklayer::import(paste0(pathToMethCalls,"/", baseFileName,"_CHH.bedGraph"),format="bedGraph") colnames(GenomicRanges::mcols(methCHH))<-c("methPercent","methylated","nonMethylated") methCHG<-rtracklayer::import(paste0(pathToMethCalls,"/", baseFileName,"_CHG.bedGraph"),format="bedGraph") colnames(GenomicRanges::mcols(methCHG))<-c("methPercent","methylated","nonMethylated") methNonCG<-GenomicRanges::sort(c(methCHH,methCHG)) # create methGC ol4<-IRanges::findOverlaps(methNonCG,GCmotifs) ol5<-IRanges::findOverlaps(methNonCG,GCGmotifs) GCidx<-c(S4Vectors::queryHits(ol4),S4Vectors::queryHits(ol5)) methGC<-GenomicRanges::sort(methNonCG[GCidx]) methGC$readDepth<-rowSums(cbind(methGC$methylated,methGC$nonMethylated)) methGC<-methGC[methGC$readDepth>minDepth] # create methC methC<-methNonCG[-GCidx] methC$readDepth<-rowSums(cbind(methC$methylated,methC$nonMethylated)) methC<-methC[methC$readDepth>minDepth] return(list(CG=methCG,GC=methGC,C=methC)) } #' Convert Genomic ranges list to long data frame for plotting #' #' Methylation frequency data stored in a list(by sample) of list (by C context) of genomic ranges is extracted into a data frame. By specifying a context type ("CG","GC" or "C") this type of data is extracted for all samples listed in "samples" can converted to a dataframe. #' #' @param methFreqGR A list (by sample) of a list (by C context) of genomic ranges for cytosine methylation frquency #' @param samples a vector of sample names for which to extract the data #' @param Ctype The type of sequence context for the cytosine _("CG","GC" or "C") #' @return A long-form data frame with methylation frequency and counts at different sites in different samples #' @export grlToDf<-function(methFreqGR,samples,Ctype) { first<-TRUE for (sampleName in samples) { df<-as.data.frame(methFreqGR[[sampleName]][[Ctype]]) df$sampleName<-sampleName if (first==FALSE) { alldf<-rbind(alldf,df) } else { alldf<-df first<-FALSE } } alldf$sampleName<-factor(alldf$sampleName) return(alldf) } #' Convert Genomic ranges list to single genomic range with sample methylation and total counts in metadata #' #' genomic ranges for CG and GC positions in each samples are combined and sorted. Then genomic ranges #' from different samples are merged together putting methylation frequency (_M) and total read counts (_T) for each sample in the metadata. #' #' @param methFreqGR A list (by sample) of a list (by C context) of genomic ranges for cytosine methylation frquency #' @param samples a vector of sample names for which to extract the data #' @return A genomic ranges wtih all CG and GC positions found in the samples. The metadata columns contain methylation frequency (_M) and total read count (_T) for each sample #' @export combineCGGCgr<-function(methFreqGR,samples) { first<-TRUE for (sampleName in samples) { cg<-methFreqGR[[sampleName]][["CG"]] gc<-methFreqGR[[sampleName]][["GC"]] cggc<-GenomicRanges::sort(c(cg,gc)) fractionMeth<-cggc$methylated/cggc$readDepth readDepth<-cggc$readDepth GenomicRanges::mcols(cggc)<-NULL GenomicRanges::mcols(cggc)[,paste0(sampleName,"_M")]<-fractionMeth GenomicRanges::mcols(cggc)[,paste0(sampleName,"_T")]<-readDepth if (first==FALSE) { allcggc<-GenomicRanges::merge(allcggc,cggc,all=T) } else { allcggc<-cggc first<-FALSE } } return(allcggc) } #' Find bisulfite conversion rate of Cs in non-methylated context #' #' Use bedfile with positons of Cs that are in non-methylated context to obtain stats #' about the number of informative Cs and conversion status of Cs per read #' #' @param bamFile String with path to bam file with alignments of reads to genome #' @param genomeFile String with path to fasta file with genome sequence #' @param bedFileC String with path to .bed file with locations of Cs to be evaluated (for forward strand calls) #' @param bedFileG String with path to .bed file with locations of Gs to be evaluated (for reverse strand calls) #' @param regionGR Genomic range of region for which to extract reads. It can #' also be a string denoting the region, e.g. "X:8069396-8069886" #' @param samtoolsPath Path to samtools executable (default="") if not in unix $PATH #' @return A data frame with the names of the reads, the count of the number of informative Cs #' per region (not NAs), the maximum number of possible Cs in the regon, and #' the fraction of the informative Cs which have been bisulfite converted #' @export poorBisulfiteConversion<-function(bamFile,genomeFile,bedFileC,bedFileG, regionGR,samtoolsPath="") { # calls on forward strand matC<-getReadMatrix(bamFile, genomeFile, bedFileC, regionGR, samtoolsPath) dfc<-data.frame(reads=row.names(matC),stringsAsFactors=F) dfc$informativeCs<-rowSums(!is.na(matC)) dfc$totalCs<-dim(matC)[2] dfc$fractionConverted<-rowMeans(matC,na.rm=T) # calls on reverse strand matG<-getReadMatrix(bamFile, genomeFile, bedFileG, regionGR, samtoolsPath) dfg<-data.frame(reads=row.names(matG),stringsAsFactors=F) dfg$informativeCs<-rowSums(!is.na(matG)) dfg$totalCs<-dim(matG)[2] dfg$fractionConverted<-rowMeans(matG,na.rm=T) #choose highest for each read (calls of 0, or close to 0 will be produced if reads on other strand from bedfile) df<-merge(dfc,dfg,by=c("reads"),all=TRUE) df[is.na(df)]<-0 keepDFC<-df$fractionConverted.x>=df$fractionConverted.y df[!keepDFC,c("informativeCs.x","totalCs.x","fractionConverted.x")]<- df[!keepDFC,c("informativeCs.y","totalCs.y","fractionConverted.y")] df[,c("informativeCs.y","totalCs.y","fractionConverted.y")]<-NULL colnames(df)<-gsub("\\.x","",colnames(df)) return(df) } #' Make directories #' #' @param path String with path to where the directories should be made #' @param dirNameList Vector of strings with names of directories to create (can include multilevel directories) #' @return Creates the directories listed in dirNameList #' @examples #' makeDirs(path=".",dirNameList=c("/txt","/rds/sample1")) #' @export makeDirs<-function(path,dirNameList=c()) { for (d in dirNameList) { if (!dir.exists(paste0(path,"/",d))){ # for alignments dir.create(paste0(path,"/",d), recursive=TRUE, showWarnings=FALSE) } } } #' Extract list of methylation matrices #' #' Input requires a sampleTable with two columns: FileName contains the path to #' a bam file of aligned sequences. SampleName contains the name of the sample. #' The function will return a table of all matrix-files for all samples and all #' regions listed in regionGRs, together with some info about the matrices. #' Matrices contain values between 0 (not methylated) and 1 (methylated), or NA (undefined) #' @param sampleTable Table with FileName column listing the full path to bam files belonging to the samples listed in the SampleName column #' @param genomeFile String with path to fasta file with genome sequence #' @param regionGRs A genomic regions object with all regions for which matrices should be extracted. The metadata columns must contain a column called "ID" with a unique ID for that region. #' @param regionType A collective name for this list of regions (e.g TSS or amplicons) #' @param genomeMotifGR A GenomicRanges object with a unique set of non-overlapping CG, GC and GCGorCGC sites #' @param minConversionRate Minimal fraction of Cs from a non-methylation context that must be converted to Ts for the read to be included in the final matrix (default=0.8) #' @param maxNAfraction Maximual fraction of CpG/GpC positions that can be undefined (default=0.2) #' Note that since making the matrix is a time-consuming process, the reads are #' not removed from the matrix using this threshold, so that a different #' threshold can be used at a later time, but it is used to give an idea of the #' read quality in the summary table of the matrices. #' @param bedFilePrefix The full path and prefix of the bed file for C, G, CG and GC positions in the genome (i.e path and name of the file without the ".C.bed",".G.bed", ".CG.bed" or ".GC.bed" suffix). Defulat is NULL and assumes the bed file are in the same location as the genome sequence file. #' @param path Path for output. "plots", "csv" and "rds" directories will be created here. Default is current directory. #' @param convRatePlots Boolean value: should bisulfite conversion rate plots be created for each region? (default=FALSE) #' @param nThreads number of threads for parallelisation #' @param samtoolsPath Path to samtools executable (default="") if not in unix $PATH #' @param overwriteMatrixLog Should matrixLog file be overwritten (in case of #' change in analysis or data), or should already computed matrices be used and #' script skips to next matrix (in case of premature termination of analysis) #' (default=FALSE) #' @return A list (by sample) of lists (by regions) of methylation matrices #' @export getSingleMoleculeMatrices<-function(sampleTable, genomeFile, regionGRs, regionType, genomeMotifGR, minConversionRate=0.8, maxNAfraction=0.2, bedFilePrefix=NULL, path=".", convRatePlots=FALSE, nThreads=1, samtoolsPath="", overwriteMatrixLog=FALSE) { totalCs<-informativeCs<-fractionConverted<-i<-NULL #create pathnames to bedfiles if (is.null(bedFilePrefix)){ bedFilePrefix=gsub("\\.fa","", genomeFile) } bedFileC=paste0(bedFilePrefix,".C.bed") bedFileG=paste0(bedFilePrefix,".G.bed") bedFileCG=paste0(bedFilePrefix,".CG.bed") bedFileGC=paste0(bedFilePrefix,".GC.bed") # make output directories makeDirs(path,c("csv", paste0("rds/methMats_",regionType))) if (convRatePlots==TRUE) { makeDirs(path,c("plots/informCs", "plots/convRate")) } samples<-sampleTable$SampleName addSampleName<-ifelse(length(unique(samples))==1,paste0("_",samples[1]),"") matrixLog<-getMatrixLog(paste0(path,"/csv/MatrixLog_",regionType, addSampleName,"_log.csv")) #print(matrixLog) for (currentSample in samples) { print(currentSample) bamFile<-sampleTable$FileName[sampleTable$SampleName==currentSample] #lists to collect plots for all regions in a particular sample if (convRatePlots==TRUE) { informativeCsPlots=vector() conversionRatePlots=vector() } sink(type="message") clst<-parallel::makeCluster(nThreads) doParallel::registerDoParallel(clst) cat("number of workers:") cat(foreach::getDoParWorkers(),sep="\n") sink() pmatrixLog<-foreach::foreach(i=1:length(regionGRs), .combine=rbind, .errorhandling="remove", .packages=c("GenomicRanges", "S4Vectors")) %dopar% { #for (i in seq_along(regionGRs)) { # find appropriate line of matrixLog, and check if data already exists regionGR<-regionGRs[i] logLine<-data.frame(regionNum=i,filename=NA,sample=currentSample, region=regionGR$ID, numCGpos=NA, numGCpos=NA, numUniquePos=NA, CGreads=NA, GCreads=NA, methMatReads=NA, goodConvReads=NA, fewNAreads=NA,stringsAsFactors=F) alreadyDone<-(currentSample %in% matrixLog$sample & regionGR$ID %in% matrixLog$region) #j<-which(matrixLog$sample==currentSample & matrixLog$region==regionGR$ID) if(!alreadyDone | overwriteMatrixLog==T){ # get C conversion matrices matCG<-getReadMatrix(bamFile, genomeFile, bedFileCG, regionGR, samtoolsPath) matGC<-getReadMatrix(bamFile, genomeFile, bedFileGC, regionGR, samtoolsPath) convMat<-combineCGandGCmatrices(matCG,matGC,regionGR,genomeMotifGR) if(! is.null(dim(convMat))) { # combine CG and GC matrices and change conversion=1 to methylation=1 methMat<-1-convMat # record number of reads in the matrices logLine[1,"numCGpos"]<-ifelse(!is.null(dim(matCG)[2]), dim(matCG)[2], 0) logLine[1,"numGCpos"]<-ifelse(!is.null(dim(matGC)[2]), dim(matGC)[2], 0) logLine[1,"numUniquePos"]<-ifelse(!is.null(dim(methMat)[2]), dim(methMat)[2], 0) logLine[1,"CGreads"]<-ifelse(!is.null(dim(matCG)[1]), dim(matCG)[1], 0) logLine[1,"GCreads"]<-ifelse(!is.null(dim(matGC)[1]), dim(matGC)[1], 0) logLine[1,"methMatReads"]<-ifelse(!is.null(dim(methMat)[1]), dim(methMat)[1], 0) # get bisulfite conversion stats for Cs in non-methylated context df<-poorBisulfiteConversion(bamFile, genomeFile, bedFileC, bedFileG, regionGR, samtoolsPath) removeReads<-df[df$fractionConverted<minConversionRate,"reads"] methMat<-methMat[!(rownames(methMat) %in% removeReads),] logLine[1,"goodConvReads"]<-ifelse(!is.null(dim(methMat)[1]), dim(methMat)[1],0) # if (is.null(dim(methMat))) { # next; # } if (convRatePlots==TRUE) { ## plot histogram of number informative Cs per read p<-ggplot2::ggplot(df,ggplot2::aes(x=informativeCs/totalCs)) + ggplot2::geom_histogram() + ggplot2::ggtitle(paste0(regionGR$ID, " Informative Cs per read (totalCs: ", df$totalCs[1]," )")) # save to file plotName<-paste0(path,"/plots/informCs/infC_", regionType, "_", currentSample,"_", regionGR$ID, ".pdf") ggplot2::ggsave(plotName, plot=p, device="pdf", width=7.25, height=5, units="cm") informativeCsPlots<-c(informativeCsPlots,plotName) ## plot histogram of number of bisulfite converted Cs per read as ## fraction of informative Cs p<-ggplot2::ggplot(df,ggplot2::aes(x=fractionConverted)) + ggplot2::geom_histogram() + ggplot2::xlim(c(0,1)) + ggplot2::ggtitle(paste0(regionGR$ID, " Bisulfite converted Cs per read out of informative Cs")) + ggplot2::geom_vline(xintercept=minConversionRate, col="red", linetype="dashed") # save to file plotName<-paste0(path,"/plots/convRate/convR_", regionType, "_", currentSample,"_",regionGR$ID, ".pdf") ggplot2::ggsave(plotName, plot=p, device="pdf", width=7.25, height=5, units="cm") conversionRatePlots<-c(conversionRatePlots,plotName) } # count reads that do not cover at least 1-maxNAfraction of the cytosines logLine[1,"fewNAreads"]<-sum(rowMeans(is.na(methMat))<maxNAfraction) sink(type="message") cat(paste(i,regionType,currentSample,regionGR$ID,sep=" "),sep="\n") #cat(paste("path is: ",path),sep="\n") sink() matName<-paste0(path,"/rds/methMats_", regionType,"/", currentSample, "_", regionGR$ID, ".rds") saveRDS(methMat,file=matName) logLine[1,"filename"]<-matName # write intermediate data to file so that if it crashes one can restart sink(file=paste0(path, "/csv/MatrixLog_", regionType, addSampleName, "_log.csv"), append=TRUE, type="output") cat(paste(logLine,collapse=","), sep="\n") sink() #utils::write.csv(logLine,paste0(path, "/csv/MatrixLog_", regionType, # addSampleName, ".csv"), # quote=F, row.names=F) } #print(matrixLog[j,]) logLine } } parallel::stopCluster(clst) print(pmatrixLog) if (convRatePlots==TRUE) { #TODO:combine PDF function } } #tidy and sort pmatrixLog pmatrixLog<-rbind(matrixLog,pmatrixLog) pmatrixLog<-pmatrixLog[rowSums(!is.na(pmatrixLog))>0,] pmatrixLog<-pmatrixLog[order(pmatrixLog$regionNum),] # write file with final data utils::write.csv(pmatrixLog,paste0(path, "/csv/MatrixLog_", regionType, addSampleName, ".csv"), quote=F, row.names=F) #file.remove(paste0(path, "/csv/MatrixLog_", regionType, # addSampleName, "_log.csv")) return(pmatrixLog) } #' Read in an existing matrixLog, or create a new one #' #' Input requires matrixLog file name with correct path. If file exists it will be read #' in, otherwise an empty data.frame will be created with the correct number of fields #' for the samples (samples) and the regions (regionGRs). Teh function returns this #' matrixLog data.frame #' @param matrixLogFile Name of matrix log file complete with relative or absolut path #' @return A data frame with columns to record data about the single molecule matrices getMatrixLog<-function(matrixLogFile){ if (file.exists(matrixLogFile) & file.info(matrixLogFile)$size>0) { # this allows restarting matrixLog<-utils::read.csv(matrixLogFile, stringsAsFactors=F, header=T, row.names=NULL) } else { writeLines(paste(c("regionNum","filename","sample","region","numCGpos", "numGCpos","numUniquePos","CGreads","GCreads", "methMatReads","goodConvReads", "fewNAreads"), collapse=","), con=matrixLogFile) #log table to record number of reads in matrix at various steps matrixLog<-data.frame(regionNum=NA, filename=NA,sample=NA, region=NA, numCGpos=NA, numGCpos=NA, numUniquePos=NA, CGreads=NA, GCreads=NA, methMatReads=NA, goodConvReads=NA, fewNAreads=NA, stringsAsFactors=F) } return(matrixLog) }
/R/bam2methMats.R
no_license
jsemple19/methMatrix
R
false
false
33,404
r
#' Create bed file of CpG or GpC motifs #' #' @param genomeFile String with path to fasta file with genome sequence #' @param CGorGC String with motif to be found (either "CG" or "GC") #' @return A bed file with locations of the C in all occurrences of this motif on both strands will be written to #' the same directory as genomeFile with the extension .CpG.bed or .GpC.bed #' #' @export makeCGorGCbed<-function(genomeFile,CGorGC) { if (! CGorGC %in% c("CG","GC")) { print("The variable 'CGorGC' must have the value 'CG' or 'GC'") } genome<-Biostrings::readDNAStringSet(genomeFile) Cmotifs<-Biostrings::vmatchPattern(CGorGC,genome) # create gr for Cs on positive strand gr<-GenomicRanges::GRanges(seqnames=S4Vectors::Rle(names(Cmotifs),sapply(Cmotifs,length)), ranges=unlist(Cmotifs), strand="+") allGR<-gr # create gr for Cs on negative strand gr<-GenomicRanges::GRanges(seqnames=S4Vectors::Rle(names(Cmotifs),sapply(Cmotifs,length)), ranges=unlist(Cmotifs), strand="-") allGR<-c(allGR,gr) # resize to cover only Cs allGR<-GenomicRanges::resize(allGR,width=1,fix=ifelse(CGorGC=="CG","start","end")) allGR<-GenomicRanges::sort(allGR,ignore.strand=T) #export as bed file to genomeFile directory outDir<-dirname(genomeFile) outFile<-gsub("fa",paste0(CGorGC,".bed"),basename(genomeFile)) rtracklayer::export.bed(allGR,con=paste0(outDir,"/",outFile)) } #' Extract methylation matrix from alignment file #' #' @param bamFile String with path to bam file with alignments of reads to genome #' @param genomeFile String with path to fasta file with genome sequence #' @param bedFile String with path to .bed file with locations of Cs to be evaluated #' @param region Genomic range of region for which to extract reads. It can also #' be a string denoting the region, e.g. "X:8069396-8069886" #' @param samtoolsPath Path to samtools executable (default="") if not in unix $PATH #' @param maxDepth Maximum number of reads to take for a given region (default=10,000) #' @return A matrix with reads as row names and C positions as column names. #' Every position in matrix has a value of 0 (non-converted C = methylated), 1 (converted C (T) = not methylated) or NA (undetermined) #' #' @export getReadMatrix<-function(bamFile, genomeFile, bedFile, region, samtoolsPath="", maxDepth=10000) { if (class(region)=="GRanges") { region<-paste0(GenomeInfoDb::seqnames(region), ":", IRanges::start(region), "-", IRanges::end(region)) } # use samtools mpileup to call C methylation tab<-system(paste0(samtoolsPath, "samtools mpileup -f ", genomeFile, " -l ", bedFile, " -r ", region, " --output-QNAME --max-depth ", maxDepth, " --min-BQ 8 ", " --ff UNMAP,QCFAIL ", bamFile),intern=T) #tab<-Rsamtools::pileup(file=bamFile,max_depth=maxDepth,min_base_quality=8,) if (length(tab)>0) { # convert output to data frame tab<-lapply(tab,strsplit,"\t") tab<-lapply(1:length(tab),function(x){t(tab[[x]][[1]])}) tab<-as.data.frame(do.call(rbind,tab),stringsAsFactors=F) colnames(tab)<-c("chr","start","ref","count","matches","BQ","reads") # make empty matrix of reads x C positions allReads<-unique(sort(unlist(sapply(tab$reads,strsplit,split=","),use.names=FALSE))) allPos<-tab$start mat<-matrix(data=NA,nrow=length(allReads),ncol=length(allPos)) colnames(mat)<-allPos rownames(mat)<-allReads # scroll through tab to extract methylation values in strand aware way for (line in 1:nrow(tab)) { df<-pileupToConversionStatus(tab[line,]) m1<-mat[df$reads,df$pos] m2<-df$Cconv mat[df$reads,df$pos]<-ifelse(is.na(m1), ifelse(is.na(m2), NA, m2), ifelse(is.na(m2), m1, (m1 + m2))) } } else { mat<-NULL } return(mat) } #' Extract methylation calls from single line of pileup file #' #' @param pileupLine One line data frame from pileup file. Columns have been named: c("chr","start","ref","count","matches","BQ","reads") #' @return A data frame with C position, read name and C conversion call 0 (not converted (C) = methylated), 1 (converted (T) = not methylated) #' @export pileupToConversionStatus<-function(pileupLine) { # if read matches forward strand match<-parseMatchString(pileupLine$matches) if(nchar(match)!=pileupLine$count) { "problem with match string" } df=NULL posConv=NULL posUnconv=NULL if (pileupLine$ref=="c" | pileupLine$ref=="C") { matchList<-stringr::str_locate_all(match,"[\\.,]")[[1]] if(dim(matchList)[1]>0) { posConv<-rep(pileupLine$start,dim(matchList)[1]) readsConv<-unlist(strsplit(pileupLine$reads,","))[matchList[,1]] } matchList<-stringr::str_locate_all(match,"[Tt]")[[1]] if(dim(matchList)[1]>0) { posUnconv<-rep(pileupLine$start,dim(matchList)[1]) readsUnconv<-unlist(strsplit(pileupLine$reads,","))[matchList[,1]] } } # if read matches reverse strand if (pileupLine$ref=="g" | pileupLine$ref=="G") { matchList<-stringr::str_locate_all(match,"[\\.,]")[[1]] if(dim(matchList)[1]>0) { posConv<-rep(pileupLine$start,dim(matchList)[1]) readsConv<-unlist(strsplit(pileupLine$reads,","))[matchList[,1]] } matchList<-stringr::str_locate_all(match,"[aA]")[[1]] if(dim(matchList)[1]>0) { posUnconv<-rep(pileupLine$start,dim(matchList)[1]) readsUnconv<-unlist(strsplit(pileupLine$reads,","))[matchList[,1]] } } #prepare df for export first<-TRUE if (!is.null(posConv)) { convdf<-data.frame(pos=posConv,reads=readsConv,Cconv=0,stringsAsFactors=F) df<-convdf first<-FALSE } if (!is.null(posUnconv)) { unconvdf<-data.frame(pos=posUnconv,reads=readsUnconv,Cconv=1,stringsAsFactors=F) if (first==FALSE) { df<-rbind(df,unconvdf) } else { df<-unconvdf } } return(df) } # a dot stands for a match to the reference base on the forward strand, # a comma for a match on the reverse strand, a '>' or '<' for a reference skip, # ACGTN for a mismatch on the forward strand and # acgtn for a mismatch on the reverse strand. # \\+[0-9]+[ACGTNacgtn]+ indicates there is an insertion between this reference position and the next reference position # -[0-9]+[ACGTNacgtn]+ represents a deletion from the reference # * does not add character # $ indicates end of read, it adds one character and should be removed # ^ indicates a read start mark followed by mapping quality. two characters should be removed # +[1-9]+[] #' Clean up match string from pileup file #' #' @param match Match string from pileup file. #' @return A cleaned up match string with no indels or start/end line info parseMatchString<-function(match) { match<-gsub("\\$","",match) # remove end of read mark match<-gsub("\\^.?","",match) # remove start of read mark + read qual char indelCount<-stringr::str_extract_all(match,"[0-9]+")[[1]] for (i in indelCount) { # remove indel info around match m<-paste0("[\\+-]",i,".{",i,"}") match<-stringr::str_replace(match,m,"") } return(match) } #' Convert methylation matrix to genomic ranges #' #' @param mat Methylation matrix with reads x Cposition #' @param gr GRanges object for which the methylation matrix was made #' @return genomic ranges of Cpositions with mcols containing the reads as columns #' @export matToGR<-function(mat,gr) { matgr<-GenomicRanges::GRanges(seqnames=GenomeInfoDb::seqnames(gr), IRanges::IRanges(start=as.integer(colnames(mat)),width=1), strand="*") GenomicRanges::mcols(matgr)<-t(mat) return(matgr) } #' Check if vector is only NAs #' @param vec Vector of values to be checked #' @examples #' allNAs(c(NA, NA, NA)) #' allNAs(c(NA,1,NA)) #' allNAs(c(1,2,3)) #' allNAs(c()) #' @return boolean TRUE or FALSE #' @export allNAs<-function(vec) { if (sum(is.na(vec)) == length(vec)) { returnVal=TRUE } else { returnVal=FALSE } return(returnVal) } #' Combine CG and GC methylation matrices #' #' Methylation matrices are tricky to merge because: #' #' 1. Forward and reverse reads will have methylation calls at different positions #' even if they are part of the same motif because the C is shifted by 1 between #' the two strands. Therefore we "destrand" the reads by averaging all methylation #' calls within the same motif (and ingoring NAs). The genomic positions in the final merged #' matrix will be on the position of the 1st bp of the motif for CG motifs and the genomic #' position of the 2nd bp of the motif for GC motifs. #' #' 2. GCG/CGC motifs will have methylation calls from three Cs and it is not clear #' whether the middle C should be part of one motif or the other. Therefore we consider #' such triplets as a single motif and average the methylation calls from all three Cs. #' The genomic position used in the final merged matrix will be that of the middle bp #' of the motif. #' #' 3. Longer GCGC/CGCG runs have multiple overlapping motifs layered within them. To deal #' with that we split these runs into 2-3bp motifs. If the length of the run is an even #' number, it is split into doublets and considered as simple CG or GC motifs. If the #' length of the run is an odd number, one triplet is created, and the rest is split into #' doublets. This creates a set of unique non-overlapping motifs in the genome that are either #' CG or GC 2bp motifs, or a GCG/CGC 2bp motif. This unique set is created before hand #' with the nanodsmf::findGenomeMotifs function and can be stored in a RDS file. Doublet #' and triplet motifs created from the run are treated the same as isolated doublet and triplet #' motifs, as described in points 1. and 2. above. #' #' @param matCG Methylation matrix (reads x positons) of C positions within CG motifs #' @param matGC Methylation matrix (reads x positons) of C positions within GC motifs #' @param regionGR GRanges object of region used to make methylation matrices #' @param genomeMotifGR GRanges object with all unique non-overlapping CG/GC/GCGorCGC motifs in genome #' @return Merged methylation matrix #' @export combineCGandGCmatrices<-function(matCG,matGC,regionGR,genomeMotifGR){ if (!is.null(matCG) & !is.null(matGC)) { # convert matCG and matGC to genomic ranges with transposed matrix (positions x reads) matCGgr<-matToGR(matCG,regionGR) matGCgr<-matToGR(matGC,regionGR) #subset genomeMotifGR by regionGR to get motifs that should be present in the matrices regGCCG<-IRanges::subsetByOverlaps(genomeMotifGR,regionGR,ignore.strand=TRUE) # get vector of read names for each gr CGreads<-colnames(GenomicRanges::mcols(matCGgr)) GCreads<-colnames(GenomicRanges::mcols(matGCgr)) # use genomeMotifGR subset to "destrand" CG and GC calls by summing positions within motifs cg<-grangesutils::applyGRonGR(regGCCG,matCGgr,CGreads,sum,na.rm=T) gc<-grangesutils::applyGRonGR(regGCCG,matGCgr,GCreads,sum,na.rm=T) # ensure no value in the matrix exceeds 1 maxval1<-function(m1){ ifelse(is.na(m1), NA, ifelse(m1>1, 1, m1)) } GenomicRanges::mcols(cg)[,2:dim(GenomicRanges::mcols(cg))[2]]<- data.table::as.data.table(maxval1(as.matrix(GenomicRanges::mcols(cg)[,2:dim(GenomicRanges::mcols(cg))[2]]))) GenomicRanges::mcols(gc)[,2:dim(GenomicRanges::mcols(gc))[2]]<- data.table::as.data.table(maxval1(as.matrix(GenomicRanges::mcols(gc)[,2:dim(GenomicRanges::mcols(gc))[2]]))) # find gr that overlap between cg and gc calls ol<-IRanges::findOverlaps(cg,gc) if (length(ol)>=1) { # find reads that are in both grs (GCGorCGC motifs) idxCGinGC<-CGreads %in% GCreads idxGCinCG<-GCreads %in% CGreads # average values from both matrices at these overlapping sites (NAs are ignored, but # kept if no real values is found) m1<-as.matrix(GenomicRanges::mcols(cg)[S4Vectors::queryHits(ol),CGreads[idxCGinGC]]) m2<-as.matrix(GenomicRanges::mcols(gc)[S4Vectors::subjectHits(ol),GCreads[idxGCinCG]]) mAvr<-ifelse(is.na(m1), ifelse(is.na(m2), NA, m2), ifelse(is.na(m2), m1, (m1 + m2)/2)) GenomicRanges::mcols(cg)[S4Vectors::queryHits(ol),CGreads[idxCGinGC]]<-tibble::as_tibble(mAvr) # make nonoverlapping combined list allGR<-c(cg,gc[-S4Vectors::subjectHits(ol)]) } else { allGR<-c(cg,gc) } # shrink gr to single bp CG1bp<-GenomicRanges::resize(allGR[allGR$context=="HCG"],width=1,fix="start") GC1bp<-GenomicRanges::resize(allGR[allGR$context=="GCH"],width=1,fix="end") GCGorCGC1bp<-GenomicRanges::resize(allGR[allGR$context=="GCGorCGC"],width=1,fix="center") # combine and sort allGR<-GenomicRanges::sort(c(CG1bp,GC1bp,GCGorCGC1bp)) # convert back to matrix readNum<-dim(GenomicRanges::mcols(allGR))[2]-1 # don't include the "context" column convMat<-t(as.matrix(GenomicRanges::mcols(allGR)[,2:(readNum+1)])) colnames(convMat)<-GenomicRanges::start(allGR) # remove reads with aboslutly no methylation info convMat<-convMat[rowSums(is.na(convMat))!=dim(convMat)[2],] } else { convMat<-NULL } return(convMat) } #' Get methylation frequency genomic ranges #' #' Takes MethylDackel methylation call bedgraph files for CpG CHH and CHG motifs and creates genomic ranges for CG, GC and all other Cs. Output is a list of these three genomic ranges objects. #' #' @param baseFileName base file name used in MethylDackel extract command (assumes _CpG.bedgraph, _CHH.bedgraph and _CHG.bedgraph extensions were later added by MethylDackel) #' @param pathToMethCalls Path to folder in which MethylDackel output is found #' @param motifFile Path to GRanges object with all unique CG/GC/GCGorCGC motifs in genome #' @param minDepth Minimum read depth. Positions with fewer than this number are discarded (default=5) #' @return Named list with CG, GC and C genomic ranges with metadata about methylation. #' @export getMethFreqGR<-function(baseFileName,pathToMethCalls,motifFile,minDepth=5) { # get genome motifs gnmMotifs<-readRDS(motifFile) GCmotifs<-gnmMotifs[gnmMotifs$context=="GCH"] CGmotifs<-gnmMotifs[gnmMotifs$context=="HCG"] GCGmotifs<-gnmMotifs[gnmMotifs$context=="GCGorCGC"] # make sure the path variable is set pathToMethCalls<-gsub("/$","",pathToMethCalls) if (! exists("pathToMethCalls")) {pathToMethCalls="."} # read in methyldackel output files methCG<-rtracklayer::import(paste0(pathToMethCalls,"/",baseFileName,"_CpG.bedGraph"),format="bedGraph") colnames(GenomicRanges::mcols(methCG))<-c("methPercent","methylated","nonMethylated") methCG$readDepth<-rowSums(cbind(methCG$methylated,methCG$nonMethylated)) methCG<-methCG[methCG$readDepth>minDepth] methCHH<-rtracklayer::import(paste0(pathToMethCalls,"/", baseFileName,"_CHH.bedGraph"),format="bedGraph") colnames(GenomicRanges::mcols(methCHH))<-c("methPercent","methylated","nonMethylated") methCHG<-rtracklayer::import(paste0(pathToMethCalls,"/", baseFileName,"_CHG.bedGraph"),format="bedGraph") colnames(GenomicRanges::mcols(methCHG))<-c("methPercent","methylated","nonMethylated") methNonCG<-GenomicRanges::sort(c(methCHH,methCHG)) # create methGC ol4<-IRanges::findOverlaps(methNonCG,GCmotifs) ol5<-IRanges::findOverlaps(methNonCG,GCGmotifs) GCidx<-c(S4Vectors::queryHits(ol4),S4Vectors::queryHits(ol5)) methGC<-GenomicRanges::sort(methNonCG[GCidx]) methGC$readDepth<-rowSums(cbind(methGC$methylated,methGC$nonMethylated)) methGC<-methGC[methGC$readDepth>minDepth] # create methC methC<-methNonCG[-GCidx] methC$readDepth<-rowSums(cbind(methC$methylated,methC$nonMethylated)) methC<-methC[methC$readDepth>minDepth] return(list(CG=methCG,GC=methGC,C=methC)) } #' Convert Genomic ranges list to long data frame for plotting #' #' Methylation frequency data stored in a list(by sample) of list (by C context) of genomic ranges is extracted into a data frame. By specifying a context type ("CG","GC" or "C") this type of data is extracted for all samples listed in "samples" can converted to a dataframe. #' #' @param methFreqGR A list (by sample) of a list (by C context) of genomic ranges for cytosine methylation frquency #' @param samples a vector of sample names for which to extract the data #' @param Ctype The type of sequence context for the cytosine _("CG","GC" or "C") #' @return A long-form data frame with methylation frequency and counts at different sites in different samples #' @export grlToDf<-function(methFreqGR,samples,Ctype) { first<-TRUE for (sampleName in samples) { df<-as.data.frame(methFreqGR[[sampleName]][[Ctype]]) df$sampleName<-sampleName if (first==FALSE) { alldf<-rbind(alldf,df) } else { alldf<-df first<-FALSE } } alldf$sampleName<-factor(alldf$sampleName) return(alldf) } #' Convert Genomic ranges list to single genomic range with sample methylation and total counts in metadata #' #' genomic ranges for CG and GC positions in each samples are combined and sorted. Then genomic ranges #' from different samples are merged together putting methylation frequency (_M) and total read counts (_T) for each sample in the metadata. #' #' @param methFreqGR A list (by sample) of a list (by C context) of genomic ranges for cytosine methylation frquency #' @param samples a vector of sample names for which to extract the data #' @return A genomic ranges wtih all CG and GC positions found in the samples. The metadata columns contain methylation frequency (_M) and total read count (_T) for each sample #' @export combineCGGCgr<-function(methFreqGR,samples) { first<-TRUE for (sampleName in samples) { cg<-methFreqGR[[sampleName]][["CG"]] gc<-methFreqGR[[sampleName]][["GC"]] cggc<-GenomicRanges::sort(c(cg,gc)) fractionMeth<-cggc$methylated/cggc$readDepth readDepth<-cggc$readDepth GenomicRanges::mcols(cggc)<-NULL GenomicRanges::mcols(cggc)[,paste0(sampleName,"_M")]<-fractionMeth GenomicRanges::mcols(cggc)[,paste0(sampleName,"_T")]<-readDepth if (first==FALSE) { allcggc<-GenomicRanges::merge(allcggc,cggc,all=T) } else { allcggc<-cggc first<-FALSE } } return(allcggc) } #' Find bisulfite conversion rate of Cs in non-methylated context #' #' Use bedfile with positons of Cs that are in non-methylated context to obtain stats #' about the number of informative Cs and conversion status of Cs per read #' #' @param bamFile String with path to bam file with alignments of reads to genome #' @param genomeFile String with path to fasta file with genome sequence #' @param bedFileC String with path to .bed file with locations of Cs to be evaluated (for forward strand calls) #' @param bedFileG String with path to .bed file with locations of Gs to be evaluated (for reverse strand calls) #' @param regionGR Genomic range of region for which to extract reads. It can #' also be a string denoting the region, e.g. "X:8069396-8069886" #' @param samtoolsPath Path to samtools executable (default="") if not in unix $PATH #' @return A data frame with the names of the reads, the count of the number of informative Cs #' per region (not NAs), the maximum number of possible Cs in the regon, and #' the fraction of the informative Cs which have been bisulfite converted #' @export poorBisulfiteConversion<-function(bamFile,genomeFile,bedFileC,bedFileG, regionGR,samtoolsPath="") { # calls on forward strand matC<-getReadMatrix(bamFile, genomeFile, bedFileC, regionGR, samtoolsPath) dfc<-data.frame(reads=row.names(matC),stringsAsFactors=F) dfc$informativeCs<-rowSums(!is.na(matC)) dfc$totalCs<-dim(matC)[2] dfc$fractionConverted<-rowMeans(matC,na.rm=T) # calls on reverse strand matG<-getReadMatrix(bamFile, genomeFile, bedFileG, regionGR, samtoolsPath) dfg<-data.frame(reads=row.names(matG),stringsAsFactors=F) dfg$informativeCs<-rowSums(!is.na(matG)) dfg$totalCs<-dim(matG)[2] dfg$fractionConverted<-rowMeans(matG,na.rm=T) #choose highest for each read (calls of 0, or close to 0 will be produced if reads on other strand from bedfile) df<-merge(dfc,dfg,by=c("reads"),all=TRUE) df[is.na(df)]<-0 keepDFC<-df$fractionConverted.x>=df$fractionConverted.y df[!keepDFC,c("informativeCs.x","totalCs.x","fractionConverted.x")]<- df[!keepDFC,c("informativeCs.y","totalCs.y","fractionConverted.y")] df[,c("informativeCs.y","totalCs.y","fractionConverted.y")]<-NULL colnames(df)<-gsub("\\.x","",colnames(df)) return(df) } #' Make directories #' #' @param path String with path to where the directories should be made #' @param dirNameList Vector of strings with names of directories to create (can include multilevel directories) #' @return Creates the directories listed in dirNameList #' @examples #' makeDirs(path=".",dirNameList=c("/txt","/rds/sample1")) #' @export makeDirs<-function(path,dirNameList=c()) { for (d in dirNameList) { if (!dir.exists(paste0(path,"/",d))){ # for alignments dir.create(paste0(path,"/",d), recursive=TRUE, showWarnings=FALSE) } } } #' Extract list of methylation matrices #' #' Input requires a sampleTable with two columns: FileName contains the path to #' a bam file of aligned sequences. SampleName contains the name of the sample. #' The function will return a table of all matrix-files for all samples and all #' regions listed in regionGRs, together with some info about the matrices. #' Matrices contain values between 0 (not methylated) and 1 (methylated), or NA (undefined) #' @param sampleTable Table with FileName column listing the full path to bam files belonging to the samples listed in the SampleName column #' @param genomeFile String with path to fasta file with genome sequence #' @param regionGRs A genomic regions object with all regions for which matrices should be extracted. The metadata columns must contain a column called "ID" with a unique ID for that region. #' @param regionType A collective name for this list of regions (e.g TSS or amplicons) #' @param genomeMotifGR A GenomicRanges object with a unique set of non-overlapping CG, GC and GCGorCGC sites #' @param minConversionRate Minimal fraction of Cs from a non-methylation context that must be converted to Ts for the read to be included in the final matrix (default=0.8) #' @param maxNAfraction Maximual fraction of CpG/GpC positions that can be undefined (default=0.2) #' Note that since making the matrix is a time-consuming process, the reads are #' not removed from the matrix using this threshold, so that a different #' threshold can be used at a later time, but it is used to give an idea of the #' read quality in the summary table of the matrices. #' @param bedFilePrefix The full path and prefix of the bed file for C, G, CG and GC positions in the genome (i.e path and name of the file without the ".C.bed",".G.bed", ".CG.bed" or ".GC.bed" suffix). Defulat is NULL and assumes the bed file are in the same location as the genome sequence file. #' @param path Path for output. "plots", "csv" and "rds" directories will be created here. Default is current directory. #' @param convRatePlots Boolean value: should bisulfite conversion rate plots be created for each region? (default=FALSE) #' @param nThreads number of threads for parallelisation #' @param samtoolsPath Path to samtools executable (default="") if not in unix $PATH #' @param overwriteMatrixLog Should matrixLog file be overwritten (in case of #' change in analysis or data), or should already computed matrices be used and #' script skips to next matrix (in case of premature termination of analysis) #' (default=FALSE) #' @return A list (by sample) of lists (by regions) of methylation matrices #' @export getSingleMoleculeMatrices<-function(sampleTable, genomeFile, regionGRs, regionType, genomeMotifGR, minConversionRate=0.8, maxNAfraction=0.2, bedFilePrefix=NULL, path=".", convRatePlots=FALSE, nThreads=1, samtoolsPath="", overwriteMatrixLog=FALSE) { totalCs<-informativeCs<-fractionConverted<-i<-NULL #create pathnames to bedfiles if (is.null(bedFilePrefix)){ bedFilePrefix=gsub("\\.fa","", genomeFile) } bedFileC=paste0(bedFilePrefix,".C.bed") bedFileG=paste0(bedFilePrefix,".G.bed") bedFileCG=paste0(bedFilePrefix,".CG.bed") bedFileGC=paste0(bedFilePrefix,".GC.bed") # make output directories makeDirs(path,c("csv", paste0("rds/methMats_",regionType))) if (convRatePlots==TRUE) { makeDirs(path,c("plots/informCs", "plots/convRate")) } samples<-sampleTable$SampleName addSampleName<-ifelse(length(unique(samples))==1,paste0("_",samples[1]),"") matrixLog<-getMatrixLog(paste0(path,"/csv/MatrixLog_",regionType, addSampleName,"_log.csv")) #print(matrixLog) for (currentSample in samples) { print(currentSample) bamFile<-sampleTable$FileName[sampleTable$SampleName==currentSample] #lists to collect plots for all regions in a particular sample if (convRatePlots==TRUE) { informativeCsPlots=vector() conversionRatePlots=vector() } sink(type="message") clst<-parallel::makeCluster(nThreads) doParallel::registerDoParallel(clst) cat("number of workers:") cat(foreach::getDoParWorkers(),sep="\n") sink() pmatrixLog<-foreach::foreach(i=1:length(regionGRs), .combine=rbind, .errorhandling="remove", .packages=c("GenomicRanges", "S4Vectors")) %dopar% { #for (i in seq_along(regionGRs)) { # find appropriate line of matrixLog, and check if data already exists regionGR<-regionGRs[i] logLine<-data.frame(regionNum=i,filename=NA,sample=currentSample, region=regionGR$ID, numCGpos=NA, numGCpos=NA, numUniquePos=NA, CGreads=NA, GCreads=NA, methMatReads=NA, goodConvReads=NA, fewNAreads=NA,stringsAsFactors=F) alreadyDone<-(currentSample %in% matrixLog$sample & regionGR$ID %in% matrixLog$region) #j<-which(matrixLog$sample==currentSample & matrixLog$region==regionGR$ID) if(!alreadyDone | overwriteMatrixLog==T){ # get C conversion matrices matCG<-getReadMatrix(bamFile, genomeFile, bedFileCG, regionGR, samtoolsPath) matGC<-getReadMatrix(bamFile, genomeFile, bedFileGC, regionGR, samtoolsPath) convMat<-combineCGandGCmatrices(matCG,matGC,regionGR,genomeMotifGR) if(! is.null(dim(convMat))) { # combine CG and GC matrices and change conversion=1 to methylation=1 methMat<-1-convMat # record number of reads in the matrices logLine[1,"numCGpos"]<-ifelse(!is.null(dim(matCG)[2]), dim(matCG)[2], 0) logLine[1,"numGCpos"]<-ifelse(!is.null(dim(matGC)[2]), dim(matGC)[2], 0) logLine[1,"numUniquePos"]<-ifelse(!is.null(dim(methMat)[2]), dim(methMat)[2], 0) logLine[1,"CGreads"]<-ifelse(!is.null(dim(matCG)[1]), dim(matCG)[1], 0) logLine[1,"GCreads"]<-ifelse(!is.null(dim(matGC)[1]), dim(matGC)[1], 0) logLine[1,"methMatReads"]<-ifelse(!is.null(dim(methMat)[1]), dim(methMat)[1], 0) # get bisulfite conversion stats for Cs in non-methylated context df<-poorBisulfiteConversion(bamFile, genomeFile, bedFileC, bedFileG, regionGR, samtoolsPath) removeReads<-df[df$fractionConverted<minConversionRate,"reads"] methMat<-methMat[!(rownames(methMat) %in% removeReads),] logLine[1,"goodConvReads"]<-ifelse(!is.null(dim(methMat)[1]), dim(methMat)[1],0) # if (is.null(dim(methMat))) { # next; # } if (convRatePlots==TRUE) { ## plot histogram of number informative Cs per read p<-ggplot2::ggplot(df,ggplot2::aes(x=informativeCs/totalCs)) + ggplot2::geom_histogram() + ggplot2::ggtitle(paste0(regionGR$ID, " Informative Cs per read (totalCs: ", df$totalCs[1]," )")) # save to file plotName<-paste0(path,"/plots/informCs/infC_", regionType, "_", currentSample,"_", regionGR$ID, ".pdf") ggplot2::ggsave(plotName, plot=p, device="pdf", width=7.25, height=5, units="cm") informativeCsPlots<-c(informativeCsPlots,plotName) ## plot histogram of number of bisulfite converted Cs per read as ## fraction of informative Cs p<-ggplot2::ggplot(df,ggplot2::aes(x=fractionConverted)) + ggplot2::geom_histogram() + ggplot2::xlim(c(0,1)) + ggplot2::ggtitle(paste0(regionGR$ID, " Bisulfite converted Cs per read out of informative Cs")) + ggplot2::geom_vline(xintercept=minConversionRate, col="red", linetype="dashed") # save to file plotName<-paste0(path,"/plots/convRate/convR_", regionType, "_", currentSample,"_",regionGR$ID, ".pdf") ggplot2::ggsave(plotName, plot=p, device="pdf", width=7.25, height=5, units="cm") conversionRatePlots<-c(conversionRatePlots,plotName) } # count reads that do not cover at least 1-maxNAfraction of the cytosines logLine[1,"fewNAreads"]<-sum(rowMeans(is.na(methMat))<maxNAfraction) sink(type="message") cat(paste(i,regionType,currentSample,regionGR$ID,sep=" "),sep="\n") #cat(paste("path is: ",path),sep="\n") sink() matName<-paste0(path,"/rds/methMats_", regionType,"/", currentSample, "_", regionGR$ID, ".rds") saveRDS(methMat,file=matName) logLine[1,"filename"]<-matName # write intermediate data to file so that if it crashes one can restart sink(file=paste0(path, "/csv/MatrixLog_", regionType, addSampleName, "_log.csv"), append=TRUE, type="output") cat(paste(logLine,collapse=","), sep="\n") sink() #utils::write.csv(logLine,paste0(path, "/csv/MatrixLog_", regionType, # addSampleName, ".csv"), # quote=F, row.names=F) } #print(matrixLog[j,]) logLine } } parallel::stopCluster(clst) print(pmatrixLog) if (convRatePlots==TRUE) { #TODO:combine PDF function } } #tidy and sort pmatrixLog pmatrixLog<-rbind(matrixLog,pmatrixLog) pmatrixLog<-pmatrixLog[rowSums(!is.na(pmatrixLog))>0,] pmatrixLog<-pmatrixLog[order(pmatrixLog$regionNum),] # write file with final data utils::write.csv(pmatrixLog,paste0(path, "/csv/MatrixLog_", regionType, addSampleName, ".csv"), quote=F, row.names=F) #file.remove(paste0(path, "/csv/MatrixLog_", regionType, # addSampleName, "_log.csv")) return(pmatrixLog) } #' Read in an existing matrixLog, or create a new one #' #' Input requires matrixLog file name with correct path. If file exists it will be read #' in, otherwise an empty data.frame will be created with the correct number of fields #' for the samples (samples) and the regions (regionGRs). Teh function returns this #' matrixLog data.frame #' @param matrixLogFile Name of matrix log file complete with relative or absolut path #' @return A data frame with columns to record data about the single molecule matrices getMatrixLog<-function(matrixLogFile){ if (file.exists(matrixLogFile) & file.info(matrixLogFile)$size>0) { # this allows restarting matrixLog<-utils::read.csv(matrixLogFile, stringsAsFactors=F, header=T, row.names=NULL) } else { writeLines(paste(c("regionNum","filename","sample","region","numCGpos", "numGCpos","numUniquePos","CGreads","GCreads", "methMatReads","goodConvReads", "fewNAreads"), collapse=","), con=matrixLogFile) #log table to record number of reads in matrix at various steps matrixLog<-data.frame(regionNum=NA, filename=NA,sample=NA, region=NA, numCGpos=NA, numGCpos=NA, numUniquePos=NA, CGreads=NA, GCreads=NA, methMatReads=NA, goodConvReads=NA, fewNAreads=NA, stringsAsFactors=F) } return(matrixLog) }
\docType{data} \name{koçlar} \alias{koçlar} \title{Takım koçları tablosu} \format{3.504 satır ve 10 sütundan oluşan bir data.frame \describe{ \item{oyuncu}{Özgün oyuncu kodu} \item{yıl}{Yıl} \item{takım}{Takım kodu (faktör)} \item{lig}{Lig kodu (faktör) (AA, AL, FL, NL, PL, UA)} \item{koçluk_sırası}{Koçluk sıralamasındaki yeri. Takımı tüm sezon tek başına yönetirse 0. Aksi takdirde, koçun yönetim sıralamasında nerede göründüğünü gösterir (birinci koç için 1, ikinci koç için 2 vs.)} \item{yönetilen_oyun}{Yönettiği oyun sayısı} \item{galibiyet}{Galibiyet sayısı} \item{mağlubiyet}{Mağlubiyet sayısı} \item{sıralama}{Yıl sonu elde edilen takım sıralaması} \item{oyuncu_koç}{Koçun aynı anda hem takımı yönetip hem de sahada oyuncu olması faktörü. \code{E} evet, \code{H} hayır} }} \usage{koçlar} \description{Takım koçlarının başında olduğu takımlar hakkında bilgiler ve bu takımlar için yıllara göre bazı temel istatistikler.} \seealso{\code{\link[Lahman]{Managers}}} \keyword{datasets}
/man/koclar.rd
permissive
botan/veriler
R
false
false
1,074
rd
\docType{data} \name{koçlar} \alias{koçlar} \title{Takım koçları tablosu} \format{3.504 satır ve 10 sütundan oluşan bir data.frame \describe{ \item{oyuncu}{Özgün oyuncu kodu} \item{yıl}{Yıl} \item{takım}{Takım kodu (faktör)} \item{lig}{Lig kodu (faktör) (AA, AL, FL, NL, PL, UA)} \item{koçluk_sırası}{Koçluk sıralamasındaki yeri. Takımı tüm sezon tek başına yönetirse 0. Aksi takdirde, koçun yönetim sıralamasında nerede göründüğünü gösterir (birinci koç için 1, ikinci koç için 2 vs.)} \item{yönetilen_oyun}{Yönettiği oyun sayısı} \item{galibiyet}{Galibiyet sayısı} \item{mağlubiyet}{Mağlubiyet sayısı} \item{sıralama}{Yıl sonu elde edilen takım sıralaması} \item{oyuncu_koç}{Koçun aynı anda hem takımı yönetip hem de sahada oyuncu olması faktörü. \code{E} evet, \code{H} hayır} }} \usage{koçlar} \description{Takım koçlarının başında olduğu takımlar hakkında bilgiler ve bu takımlar için yıllara göre bazı temel istatistikler.} \seealso{\code{\link[Lahman]{Managers}}} \keyword{datasets}
#### Intro to R: working with dataframes #### #### Before class #### # share url to hackmd # share Dropbox script to this week's content #### Objectives #### # review previous week's material # Today: # importing data into R # working with data frames # subsetting data frames # manipulating factors #### Reading in data #### # review opening project in RStudio # project organization # remind that folders and directories are synonymous # tie into the strength of RStudio projects # directories for: data, figures, intermediate or results # describe use of buttons to make new directories # making a directory dir.create("data") # overview of tidy data principles # appropriate composition of data into tables still isn't commonly taught! # columns: variables # rows: observations # one piece of info per cell # csv: comma separated values (other things besides commas can have separators too though) # download data from url download.file("https://raw.githubusercontent.com/fredhutchio/R_intro/master/extra/clinical.csv", "data/clinical.csv") # describe how to tell if you can use a URL to download data files # can't download using Dropbox URLs # reading in data and saving to object clinical <- read.csv("data/clinical.csv") # recall object clinical # view in tab View(clinical) # describe where data came from and give brief overview of metadata: TCGA clinical data from different cancer types # show script used to produce data # note data in tab can't be edited! # note missing data # reading in data files formatted differently ?read.csv # read.csv is one of a family of commands to import data # explore other options for importing data ## Challenge: download, inspect, and import the following data files (smaller set of data from same clinical set) # example1: https://raw.githubusercontent.com/fredhutchio/R_intro/master/extra/clinical.tsv # read.delim # example2: https://raw.githubusercontent.com/fredhutchio/R_intro/master/extra/clinical.txt # read.table(header=TRUE) # can also read into R straight from URL using read.csv, but better practice to download data file for reference #### Data frames #### # data frames: tabular/spreadsheet data # table where columns are vectors all of same length # columns contain single type of data (characters, integers, factors) # inspect data frames # assess size of data frame dim(clinical) # preview content head(clinical) # show first few rows tail(clinical) # show last few rows # view names names(clinical) # column names rownames(clinical) # row names (only numbers here) # summarize str(clinical) # structure of object summary(clinical) # summary statistics by column ## Challenge: What is the class, how many rows/columns, how many types of cancer (disease)? #### Subsetting data frames #### # rows, columns # extract first column clinical[ , 1] clinical[1] ## Challenge: what is the difference in results between the last two lines of code? # extract first row, first column clinical[1,1] # extract single row clinical[1, ] # extract a range of cells clinical[1:3, 2] # rows 1 to 3, second column # exclude certain data subsets clinical[ , -1] # exclude first column clinical[-c(1:100), ] # exclude first 100 rows # save extracted data to new object test_clinical <- clinical[1:20, ] # extract columns by name clinical["tumor_stage"] # result is data.frame clinical[ , "tumor_stage"] # results in vector clinical[["tumor_stage"]] # results in vector clinical$tumor_stage # results in vector # reference exploring different types of subsetting: https://davetang.org/muse/2013/08/16/double-square-brackets-in-r/ #### BREAK #### ## Challenge: code as many different ways possible to extract the column days_to_death ## Challenge: extract the first 6 rows for only age at diagnosis and days to death ## Challenge: calculate the range and mean for cigarettes per day #### Factors #### # factors represent categorical data # predefined sets of values (levels), in alphabetical order # stored as integers with labels # can be ordered or unordered # create factor sex <- factor(c("male", "female", "female", "male")) levels(sex) # show levels nlevels(sex) # count levels # show current sex # reorder (may be necessary if order matters) sex <- factor(sex, levels = c("male", "female")) # show reordered sex # converting factors as.character(sex) # renaming factors plot(clinical$race) # plot data (may need to resize the window) race <- clinical$race # save data to object levels(race) # show levels of factor # rename factor levels(race)[2] <- "Asian" race # show revised data # replace race in data frame clinical$race <- race # replot with corrected names plot(clinical$race) ## Challenge: replace "not reported" in ethnicity and race with NA # do a Google search to find additional strategies for renaming missing data #### Extra: creating a simple data frame without importing data #### # create individual vectors cancer <- c("lung", "prostate", "breast") metastasis <- c("yes", "no", "yes") cases <- c(30, 50, 100) # combine vectors example_df1 <- data.frame(cancer, metastasis, cases) str(example_df1) # create vectors and combine at once example_df2 <- data.frame(cancer = c("lung", "prostate", "breast"), metastasis = c("yes", "no", "yes"), cases = c(30, 50, 100), stringsAsFactors = FALSE) # determines whether character or factor str(example_df2) #### Wrapping up #### # review objectives # direct towards practice questions (linked in HackMD) # preview next week's objectives # install tools for next week: install.packages("tidyverse")
/week2.R
permissive
kmussar/R_intro
R
false
false
5,594
r
#### Intro to R: working with dataframes #### #### Before class #### # share url to hackmd # share Dropbox script to this week's content #### Objectives #### # review previous week's material # Today: # importing data into R # working with data frames # subsetting data frames # manipulating factors #### Reading in data #### # review opening project in RStudio # project organization # remind that folders and directories are synonymous # tie into the strength of RStudio projects # directories for: data, figures, intermediate or results # describe use of buttons to make new directories # making a directory dir.create("data") # overview of tidy data principles # appropriate composition of data into tables still isn't commonly taught! # columns: variables # rows: observations # one piece of info per cell # csv: comma separated values (other things besides commas can have separators too though) # download data from url download.file("https://raw.githubusercontent.com/fredhutchio/R_intro/master/extra/clinical.csv", "data/clinical.csv") # describe how to tell if you can use a URL to download data files # can't download using Dropbox URLs # reading in data and saving to object clinical <- read.csv("data/clinical.csv") # recall object clinical # view in tab View(clinical) # describe where data came from and give brief overview of metadata: TCGA clinical data from different cancer types # show script used to produce data # note data in tab can't be edited! # note missing data # reading in data files formatted differently ?read.csv # read.csv is one of a family of commands to import data # explore other options for importing data ## Challenge: download, inspect, and import the following data files (smaller set of data from same clinical set) # example1: https://raw.githubusercontent.com/fredhutchio/R_intro/master/extra/clinical.tsv # read.delim # example2: https://raw.githubusercontent.com/fredhutchio/R_intro/master/extra/clinical.txt # read.table(header=TRUE) # can also read into R straight from URL using read.csv, but better practice to download data file for reference #### Data frames #### # data frames: tabular/spreadsheet data # table where columns are vectors all of same length # columns contain single type of data (characters, integers, factors) # inspect data frames # assess size of data frame dim(clinical) # preview content head(clinical) # show first few rows tail(clinical) # show last few rows # view names names(clinical) # column names rownames(clinical) # row names (only numbers here) # summarize str(clinical) # structure of object summary(clinical) # summary statistics by column ## Challenge: What is the class, how many rows/columns, how many types of cancer (disease)? #### Subsetting data frames #### # rows, columns # extract first column clinical[ , 1] clinical[1] ## Challenge: what is the difference in results between the last two lines of code? # extract first row, first column clinical[1,1] # extract single row clinical[1, ] # extract a range of cells clinical[1:3, 2] # rows 1 to 3, second column # exclude certain data subsets clinical[ , -1] # exclude first column clinical[-c(1:100), ] # exclude first 100 rows # save extracted data to new object test_clinical <- clinical[1:20, ] # extract columns by name clinical["tumor_stage"] # result is data.frame clinical[ , "tumor_stage"] # results in vector clinical[["tumor_stage"]] # results in vector clinical$tumor_stage # results in vector # reference exploring different types of subsetting: https://davetang.org/muse/2013/08/16/double-square-brackets-in-r/ #### BREAK #### ## Challenge: code as many different ways possible to extract the column days_to_death ## Challenge: extract the first 6 rows for only age at diagnosis and days to death ## Challenge: calculate the range and mean for cigarettes per day #### Factors #### # factors represent categorical data # predefined sets of values (levels), in alphabetical order # stored as integers with labels # can be ordered or unordered # create factor sex <- factor(c("male", "female", "female", "male")) levels(sex) # show levels nlevels(sex) # count levels # show current sex # reorder (may be necessary if order matters) sex <- factor(sex, levels = c("male", "female")) # show reordered sex # converting factors as.character(sex) # renaming factors plot(clinical$race) # plot data (may need to resize the window) race <- clinical$race # save data to object levels(race) # show levels of factor # rename factor levels(race)[2] <- "Asian" race # show revised data # replace race in data frame clinical$race <- race # replot with corrected names plot(clinical$race) ## Challenge: replace "not reported" in ethnicity and race with NA # do a Google search to find additional strategies for renaming missing data #### Extra: creating a simple data frame without importing data #### # create individual vectors cancer <- c("lung", "prostate", "breast") metastasis <- c("yes", "no", "yes") cases <- c(30, 50, 100) # combine vectors example_df1 <- data.frame(cancer, metastasis, cases) str(example_df1) # create vectors and combine at once example_df2 <- data.frame(cancer = c("lung", "prostate", "breast"), metastasis = c("yes", "no", "yes"), cases = c(30, 50, 100), stringsAsFactors = FALSE) # determines whether character or factor str(example_df2) #### Wrapping up #### # review objectives # direct towards practice questions (linked in HackMD) # preview next week's objectives # install tools for next week: install.packages("tidyverse")
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/cache_rds.R \name{write_cache} \alias{write_cache} \title{Write objects to the website template cache folder} \usage{ write_cache(object, cache_folder = "_cache", ...) } \arguments{ \item{object}{object to save.} \item{cache_folder}{defaults to `_cache` subfolder.} \item{...}{Additional parameters passed to `readr::write_rds()` such as compression arguments.} } \value{ `write_cache()` returns the input object invisibly } \description{ Use this function to store objects as rds files in a standardised location and speed up knitting. }
/man/write_cache.Rd
no_license
koncina/bs2site
R
false
true
619
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/cache_rds.R \name{write_cache} \alias{write_cache} \title{Write objects to the website template cache folder} \usage{ write_cache(object, cache_folder = "_cache", ...) } \arguments{ \item{object}{object to save.} \item{cache_folder}{defaults to `_cache` subfolder.} \item{...}{Additional parameters passed to `readr::write_rds()` such as compression arguments.} } \value{ `write_cache()` returns the input object invisibly } \description{ Use this function to store objects as rds files in a standardised location and speed up knitting. }
source('install_and_load_required_packages.R') source('load_pm25_emissions_data.R') MakePlot3 <- function() { file.name <- 'plot3.png' if (file.exists(file.name)) { file.remove(file.name) } baltimore.city.fips <- '24510' baltimore.city.emissions.by.year <- summary.scc.pm25.data %>% filter(fips == baltimore.city.fips) %>% group_by(year, type) %>% summarise(Emissions = sum(Emissions)) baltimore.city.emissions.by.year.types <- unique(baltimore.city.emissions.by.year$type) ggplot(baltimore.city.emissions.by.year, aes(year, Emissions)) + facet_wrap(~type) + ggtitle('Baltimore City, Maryland, PM2.5 Emissions of different types, by year') + scale_x_continuous(breaks = unique(baltimore.city.emissions.by.year$year)) + geom_point() + theme(panel.spacing.x = unit(2, 'lines')) ggsave(file.name) } MakePlot3()
/course_project_2/plot3.R
no_license
marcusmonteiro/exploratory_data_analysis
R
false
false
869
r
source('install_and_load_required_packages.R') source('load_pm25_emissions_data.R') MakePlot3 <- function() { file.name <- 'plot3.png' if (file.exists(file.name)) { file.remove(file.name) } baltimore.city.fips <- '24510' baltimore.city.emissions.by.year <- summary.scc.pm25.data %>% filter(fips == baltimore.city.fips) %>% group_by(year, type) %>% summarise(Emissions = sum(Emissions)) baltimore.city.emissions.by.year.types <- unique(baltimore.city.emissions.by.year$type) ggplot(baltimore.city.emissions.by.year, aes(year, Emissions)) + facet_wrap(~type) + ggtitle('Baltimore City, Maryland, PM2.5 Emissions of different types, by year') + scale_x_continuous(breaks = unique(baltimore.city.emissions.by.year$year)) + geom_point() + theme(panel.spacing.x = unit(2, 'lines')) ggsave(file.name) } MakePlot3()
library(shiny) library(tidyverse) library(here) library(lubridate) # Load data ---- load(file = "rows.Rdata") match_details <- read_delim("group_matches.txt", delim = "\t", locale = locale("fi")) scorers_results <- read_delim("scorers_results.txt", delim = "\t", locale = locale("fi")) group_results <- read_delim("group_results.txt", delim = "\t", locale = locale("fi")) # Clean data ---- # Matchday match_details <- match_details %>% mutate(match = paste0(home, "-", away), date = dmy(date)) # Group points points_group <- matches %>% gather(veikkaaja, veikkaus, 2:ncol(.)) %>% right_join(group_results) %>% mutate(points = if_else(veikkaus == result, 1, 0)) group_points_t <- points_group %>% select(match, points, veikkaaja) %>% spread(veikkaaja, points) %>% left_join(match_details %>% select(match, group), by = "match") %>% left_join(group_results, by = "match") %>% relocate(group, match, result) %>% arrange(group, match) # Rounds result_round16 <- read_lines("round16.txt") result_round8 <- read_lines("round8.txt") result_round4 <- read_lines("round4.txt") round16_points <- round16 %>% gather(veikkaaja, veikkaus, 1:ncol(.)) %>% mutate(points = if_else(veikkaus %in% result_round16, 1, 0)) round16_points_t <- round16_points %>% spread(veikkaaja, points) %>% filter(veikkaus %in% result_round16) %>% replace(is.na(.), 0) round8_points <- round8 %>% gather(veikkaaja, veikkaus, 1:ncol(.)) %>% mutate(points = if_else(veikkaus %in% result_round8, 1, 0)) round8_points_t <- round8_points %>% spread(veikkaaja, points) %>% filter(veikkaus %in% result_round8) %>% replace(is.na(.), 0) round4_points <- round4 %>% gather(veikkaaja, veikkaus, 1:ncol(.)) %>% mutate(points = if_else(veikkaus %in% result_round4, 1, 0)) round4_points_t <- round4_points %>% spread(veikkaaja, points) %>% filter(veikkaus %in% result_round4) %>% replace(is.na(.), 0) # Scorers points_scorers <- scorers %>% gather(veikkaaja, player) %>% left_join(scorers_results, by = "player") %>% mutate(points = 0.5 * goals) %>% select(veikkaaja, player, goals, points) points_scorers_t <- points_scorers %>% group_by(player) %>% summarise( goals = unique(goals, na.rm = TRUE), points = 0.5 * goals, veikkaajat = paste0(veikkaaja, collapse = ", ") ) %>% replace_na(list(goals = 0, points = 0)) %>% arrange(-goals) top_scorer_results <- scorers_results %>% filter(goals == max(goals)) %>% mutate(points = 3) points_top_scorer <- top_scorer %>% gather(veikkaaja, player) %>% left_join(top_scorer_results, by = "player") %>% replace_na(list(goals = 0, points = 0)) %>% select(veikkaaja, player, goals, points) # Veikkaajat veikkaaja_gp <- points_group %>% left_join(match_details %>% select(match, group), by = "match") %>% group_by(veikkaaja, group) %>% summarise(points = sum(points)) %>% rename(osio = "group") veikkaaja_rounds <- bind_rows( round16_points %>% mutate(osio = "round16"), round8_points %>% mutate(osio = "round8"), round4_points %>% mutate(osio = "round4") ) %>% group_by(veikkaaja, osio) %>% summarise(points = sum(points, na.rm = TRUE)) veikkaaja_scorers <- points_scorers %>% group_by(veikkaaja) %>% summarise(points = 0.5 * sum(goals, na.rm = TRUE)) %>% mutate(osio = "maalintekijät") veikkaaja_top_scorer <- points_top_scorer %>% mutate(osio = "maalikuningas") %>% select(veikkaaja, points, osio) veikkaaja_points <- bind_rows(veikkaaja_gp, veikkaaja_rounds, veikkaaja_scorers, veikkaaja_top_scorer) # Plot theme ---- theme_fig <- theme_minimal() + theme( axis.text.x = element_text( angle = 90, vjust = 0.5, hjust = 1 ), panel.grid.major.x = element_blank(), legend.position = "top", plot.title = element_text(size = 16, hjust = 0, face = "bold"), axis.title = element_text(size = 13), axis.text = element_text(size = 13), plot.margin = unit(c(0.25, 0.25, 0.25, 0.25), "cm") ) # Plot guess ---- plot_teams <- function(df, title){ df %>% gather(player, teams) %>% group_by(teams) %>% summarise(veikkaukset = n()) %>% arrange(veikkaukset) %>% mutate(teams = as.factor(teams)) %>% ggplot(aes(x = reorder(teams, veikkaukset), y = veikkaukset)) + geom_bar(stat = 'identity', fill = "lightblue") + ylim(0, 13) + theme_fig + labs(x = NULL, title = title) } plot_to16 <- round16 %>% plot_teams("Joukkueet neljännesvälieriin") plot_to8 <- round8 %>% plot_teams("Joukkueet puolivälieriin") plot_to4 <- round4 %>% plot_teams("Joukkueet välieriin") plot_final <- final %>% plot_teams("Joukkueet finaaliin") plot_winner <- winner %>% plot_teams("Voittaja") plot_scorers <- scorers %>% plot_teams("Maalintekijät") plot_top_scorer <- top_scorer %>% plot_teams("Maalikuningas") # Plot results ---- blues <- c("#5FB9D5", "#7AC6DC", "#8ACDE0", "#A2D9E7", "#B3E2EB", "#DDE8E9") reds <- c("#ff4c4c", "#ff7f7f") greens <- c("#a4fba6", "#4ae54a", "#30cb00") #, "#0f9200", "#006203") veikkaaja_points <- veikkaaja_points %>% mutate( osio = as_factor(osio), osio = fct_relevel( osio, "maalikuningas", "maalintekijät", "round4", "round8", "round16", "Group A", "Group B", "Group C", "Group D", "Group E", "Group F" ) ) veikkaaja_total_points <- veikkaaja_points %>% group_by(veikkaaja) %>% summarise(points = sum(points)) p_veikkaajat <- veikkaaja_points %>% ggplot(aes( x = reorder(veikkaaja, points), y = points, fill = osio, label = points )) + geom_bar(stat = 'identity') + scale_fill_manual(values = c(reds, greens, blues)) + #geom_text(stat = 'identity', # position = position_stack(vjust = .5), # size = 4) + theme_fig + labs(x = NULL, title = "Veikkauksen pistetilanne:") + geom_text( data = veikkaaja_total_points, aes( x = reorder(veikkaaja, points), y = points, fill = NULL, label = points ), nudge_y = 5, size = 4.5, fontface = "bold" ) # Shiny ---- ui <- navbarPage( 'EM-skaba 2021', id = 'mainNav', tabPanel( 'Pisteet', value = 'Pisteet', fluidPage( tags$hr(), plotOutput("p_veikkaajat"), tags$hr(), tags$strong('Pisteet alkulohkon peleistä:'), fluidRow(column(12, tableOutput('group_points_t'))), tags$hr(), tags$strong('Pisteet maalintekijöistä:'), fluidRow(column(12, tableOutput('points_scorers_t'))), tags$hr(), tags$strong('Pisteet neljännesvälierät:'), fluidRow(column(12, tableOutput('round16_points_t'))), tags$hr(), tags$strong('Pisteet puolivälierät:'), fluidRow(column(12, tableOutput('round8_points_t'))), tags$hr(), tags$strong('Pisteet Välierät:'), fluidRow(column(12, tableOutput('round4_points_t'))), ) ), tabPanel( 'Veikkaukset', value = 'Veikkaus', fluidPage( tags$hr(), tags$strong('Lohkopelit:'), fluidRow(column(12, tableOutput('matches'))), tags$hr(), tags$strong('Neljännesvälierät:'), fluidRow(column(12, tableOutput('round16'))), tags$hr(), tags$strong('Puolivälierät:'), fluidRow(column(12, tableOutput('round8'))), tags$hr(), tags$strong('Välierät:'), fluidRow(column(12, tableOutput('round4'))), tags$hr(), tags$strong('Finaali:'), fluidRow(column(12, tableOutput('final'))), tags$hr(), tags$strong('Mestari:'), fluidRow(column(12, tableOutput('winner'))), tags$hr(), tags$strong('Maalintekijät:'), fluidRow(column(12, tableOutput('scorers'))), tags$hr(), tags$strong('Maalikuningas:'), fluidRow(column(12, tableOutput('top_scorer'))) ) ), tabPanel( 'Yhteenvedot veikkauksista', value = 'Yhteenveto', fluidPage( tags$hr(), plotOutput("plot1"), tags$hr(), plotOutput("plot2"), tags$hr(), plotOutput("plot3"), tags$hr(), plotOutput("plot4"), tags$hr(), plotOutput("plot5"), tags$hr(), plotOutput("plot6"), tags$hr(), plotOutput("plot7"), ) ), tags$head( tags$style( 'body{min-height: 600px; height: auto; max-width: 1200px; margin: auto;} .bottomSpacer{height: 100px;} .btn{background-color: steelblue; color: white;}' ) ) ) server <- function(input, output, session) { # first page output$matches <- renderTable(matches, align = "c") output$round16 <- renderTable(round16, align = "c") output$round8 <- renderTable(round8, align = "c") output$round4 <- renderTable(round4, align = "c") output$final <- renderTable(final, align = "c") output$winner <- renderTable(winner, align = "c") output$scorers <- renderTable(scorers, align = "c") output$top_scorer <- renderTable(top_scorer, align = "c") output$matchday <- renderTable(matchday, align = "c") output$group_points_t <- renderTable(group_points_t, align = "c") output$round16_points_t <- renderTable(round16_points_t, align = "c") output$round8_points_t <- renderTable(round8_points_t, align = "c") output$round4_points_t <- renderTable(round4_points_t, align = "c") output$points_scorers_t <- renderTable(points_scorers_t, align = "l") output$plot1 <- renderPlot({ plot_to16 }) output$plot2 <- renderPlot({ plot_to8 }) output$plot3 <- renderPlot({ plot_to4 }) output$plot4 <- renderPlot({ plot_final }) output$plot5 <- renderPlot({ plot_winner }) output$plot6 <- renderPlot({ plot_scorers }) output$plot7 <- renderPlot({ plot_top_scorer }) output$p_veikkaajat <- renderPlot({ p_veikkaajat }) } # Run the application shinyApp(ui = ui, server = server)
/app.R
no_license
pitkakirahvi/euro2021_results
R
false
false
10,418
r
library(shiny) library(tidyverse) library(here) library(lubridate) # Load data ---- load(file = "rows.Rdata") match_details <- read_delim("group_matches.txt", delim = "\t", locale = locale("fi")) scorers_results <- read_delim("scorers_results.txt", delim = "\t", locale = locale("fi")) group_results <- read_delim("group_results.txt", delim = "\t", locale = locale("fi")) # Clean data ---- # Matchday match_details <- match_details %>% mutate(match = paste0(home, "-", away), date = dmy(date)) # Group points points_group <- matches %>% gather(veikkaaja, veikkaus, 2:ncol(.)) %>% right_join(group_results) %>% mutate(points = if_else(veikkaus == result, 1, 0)) group_points_t <- points_group %>% select(match, points, veikkaaja) %>% spread(veikkaaja, points) %>% left_join(match_details %>% select(match, group), by = "match") %>% left_join(group_results, by = "match") %>% relocate(group, match, result) %>% arrange(group, match) # Rounds result_round16 <- read_lines("round16.txt") result_round8 <- read_lines("round8.txt") result_round4 <- read_lines("round4.txt") round16_points <- round16 %>% gather(veikkaaja, veikkaus, 1:ncol(.)) %>% mutate(points = if_else(veikkaus %in% result_round16, 1, 0)) round16_points_t <- round16_points %>% spread(veikkaaja, points) %>% filter(veikkaus %in% result_round16) %>% replace(is.na(.), 0) round8_points <- round8 %>% gather(veikkaaja, veikkaus, 1:ncol(.)) %>% mutate(points = if_else(veikkaus %in% result_round8, 1, 0)) round8_points_t <- round8_points %>% spread(veikkaaja, points) %>% filter(veikkaus %in% result_round8) %>% replace(is.na(.), 0) round4_points <- round4 %>% gather(veikkaaja, veikkaus, 1:ncol(.)) %>% mutate(points = if_else(veikkaus %in% result_round4, 1, 0)) round4_points_t <- round4_points %>% spread(veikkaaja, points) %>% filter(veikkaus %in% result_round4) %>% replace(is.na(.), 0) # Scorers points_scorers <- scorers %>% gather(veikkaaja, player) %>% left_join(scorers_results, by = "player") %>% mutate(points = 0.5 * goals) %>% select(veikkaaja, player, goals, points) points_scorers_t <- points_scorers %>% group_by(player) %>% summarise( goals = unique(goals, na.rm = TRUE), points = 0.5 * goals, veikkaajat = paste0(veikkaaja, collapse = ", ") ) %>% replace_na(list(goals = 0, points = 0)) %>% arrange(-goals) top_scorer_results <- scorers_results %>% filter(goals == max(goals)) %>% mutate(points = 3) points_top_scorer <- top_scorer %>% gather(veikkaaja, player) %>% left_join(top_scorer_results, by = "player") %>% replace_na(list(goals = 0, points = 0)) %>% select(veikkaaja, player, goals, points) # Veikkaajat veikkaaja_gp <- points_group %>% left_join(match_details %>% select(match, group), by = "match") %>% group_by(veikkaaja, group) %>% summarise(points = sum(points)) %>% rename(osio = "group") veikkaaja_rounds <- bind_rows( round16_points %>% mutate(osio = "round16"), round8_points %>% mutate(osio = "round8"), round4_points %>% mutate(osio = "round4") ) %>% group_by(veikkaaja, osio) %>% summarise(points = sum(points, na.rm = TRUE)) veikkaaja_scorers <- points_scorers %>% group_by(veikkaaja) %>% summarise(points = 0.5 * sum(goals, na.rm = TRUE)) %>% mutate(osio = "maalintekijät") veikkaaja_top_scorer <- points_top_scorer %>% mutate(osio = "maalikuningas") %>% select(veikkaaja, points, osio) veikkaaja_points <- bind_rows(veikkaaja_gp, veikkaaja_rounds, veikkaaja_scorers, veikkaaja_top_scorer) # Plot theme ---- theme_fig <- theme_minimal() + theme( axis.text.x = element_text( angle = 90, vjust = 0.5, hjust = 1 ), panel.grid.major.x = element_blank(), legend.position = "top", plot.title = element_text(size = 16, hjust = 0, face = "bold"), axis.title = element_text(size = 13), axis.text = element_text(size = 13), plot.margin = unit(c(0.25, 0.25, 0.25, 0.25), "cm") ) # Plot guess ---- plot_teams <- function(df, title){ df %>% gather(player, teams) %>% group_by(teams) %>% summarise(veikkaukset = n()) %>% arrange(veikkaukset) %>% mutate(teams = as.factor(teams)) %>% ggplot(aes(x = reorder(teams, veikkaukset), y = veikkaukset)) + geom_bar(stat = 'identity', fill = "lightblue") + ylim(0, 13) + theme_fig + labs(x = NULL, title = title) } plot_to16 <- round16 %>% plot_teams("Joukkueet neljännesvälieriin") plot_to8 <- round8 %>% plot_teams("Joukkueet puolivälieriin") plot_to4 <- round4 %>% plot_teams("Joukkueet välieriin") plot_final <- final %>% plot_teams("Joukkueet finaaliin") plot_winner <- winner %>% plot_teams("Voittaja") plot_scorers <- scorers %>% plot_teams("Maalintekijät") plot_top_scorer <- top_scorer %>% plot_teams("Maalikuningas") # Plot results ---- blues <- c("#5FB9D5", "#7AC6DC", "#8ACDE0", "#A2D9E7", "#B3E2EB", "#DDE8E9") reds <- c("#ff4c4c", "#ff7f7f") greens <- c("#a4fba6", "#4ae54a", "#30cb00") #, "#0f9200", "#006203") veikkaaja_points <- veikkaaja_points %>% mutate( osio = as_factor(osio), osio = fct_relevel( osio, "maalikuningas", "maalintekijät", "round4", "round8", "round16", "Group A", "Group B", "Group C", "Group D", "Group E", "Group F" ) ) veikkaaja_total_points <- veikkaaja_points %>% group_by(veikkaaja) %>% summarise(points = sum(points)) p_veikkaajat <- veikkaaja_points %>% ggplot(aes( x = reorder(veikkaaja, points), y = points, fill = osio, label = points )) + geom_bar(stat = 'identity') + scale_fill_manual(values = c(reds, greens, blues)) + #geom_text(stat = 'identity', # position = position_stack(vjust = .5), # size = 4) + theme_fig + labs(x = NULL, title = "Veikkauksen pistetilanne:") + geom_text( data = veikkaaja_total_points, aes( x = reorder(veikkaaja, points), y = points, fill = NULL, label = points ), nudge_y = 5, size = 4.5, fontface = "bold" ) # Shiny ---- ui <- navbarPage( 'EM-skaba 2021', id = 'mainNav', tabPanel( 'Pisteet', value = 'Pisteet', fluidPage( tags$hr(), plotOutput("p_veikkaajat"), tags$hr(), tags$strong('Pisteet alkulohkon peleistä:'), fluidRow(column(12, tableOutput('group_points_t'))), tags$hr(), tags$strong('Pisteet maalintekijöistä:'), fluidRow(column(12, tableOutput('points_scorers_t'))), tags$hr(), tags$strong('Pisteet neljännesvälierät:'), fluidRow(column(12, tableOutput('round16_points_t'))), tags$hr(), tags$strong('Pisteet puolivälierät:'), fluidRow(column(12, tableOutput('round8_points_t'))), tags$hr(), tags$strong('Pisteet Välierät:'), fluidRow(column(12, tableOutput('round4_points_t'))), ) ), tabPanel( 'Veikkaukset', value = 'Veikkaus', fluidPage( tags$hr(), tags$strong('Lohkopelit:'), fluidRow(column(12, tableOutput('matches'))), tags$hr(), tags$strong('Neljännesvälierät:'), fluidRow(column(12, tableOutput('round16'))), tags$hr(), tags$strong('Puolivälierät:'), fluidRow(column(12, tableOutput('round8'))), tags$hr(), tags$strong('Välierät:'), fluidRow(column(12, tableOutput('round4'))), tags$hr(), tags$strong('Finaali:'), fluidRow(column(12, tableOutput('final'))), tags$hr(), tags$strong('Mestari:'), fluidRow(column(12, tableOutput('winner'))), tags$hr(), tags$strong('Maalintekijät:'), fluidRow(column(12, tableOutput('scorers'))), tags$hr(), tags$strong('Maalikuningas:'), fluidRow(column(12, tableOutput('top_scorer'))) ) ), tabPanel( 'Yhteenvedot veikkauksista', value = 'Yhteenveto', fluidPage( tags$hr(), plotOutput("plot1"), tags$hr(), plotOutput("plot2"), tags$hr(), plotOutput("plot3"), tags$hr(), plotOutput("plot4"), tags$hr(), plotOutput("plot5"), tags$hr(), plotOutput("plot6"), tags$hr(), plotOutput("plot7"), ) ), tags$head( tags$style( 'body{min-height: 600px; height: auto; max-width: 1200px; margin: auto;} .bottomSpacer{height: 100px;} .btn{background-color: steelblue; color: white;}' ) ) ) server <- function(input, output, session) { # first page output$matches <- renderTable(matches, align = "c") output$round16 <- renderTable(round16, align = "c") output$round8 <- renderTable(round8, align = "c") output$round4 <- renderTable(round4, align = "c") output$final <- renderTable(final, align = "c") output$winner <- renderTable(winner, align = "c") output$scorers <- renderTable(scorers, align = "c") output$top_scorer <- renderTable(top_scorer, align = "c") output$matchday <- renderTable(matchday, align = "c") output$group_points_t <- renderTable(group_points_t, align = "c") output$round16_points_t <- renderTable(round16_points_t, align = "c") output$round8_points_t <- renderTable(round8_points_t, align = "c") output$round4_points_t <- renderTable(round4_points_t, align = "c") output$points_scorers_t <- renderTable(points_scorers_t, align = "l") output$plot1 <- renderPlot({ plot_to16 }) output$plot2 <- renderPlot({ plot_to8 }) output$plot3 <- renderPlot({ plot_to4 }) output$plot4 <- renderPlot({ plot_final }) output$plot5 <- renderPlot({ plot_winner }) output$plot6 <- renderPlot({ plot_scorers }) output$plot7 <- renderPlot({ plot_top_scorer }) output$p_veikkaajat <- renderPlot({ p_veikkaajat }) } # Run the application shinyApp(ui = ui, server = server)
var.strata <- function(strata, y = NULL, rh = strata$args$rh, rh.postcorr = FALSE, model=c("none", "loglinear", "linear", "random"), model.control = list()) { ### Fonction externe : voir fiche d'aide pour la documentation # Validation des arguments et initialisation de variables # (Ls, takenone, certain, nmodel, beta, sig2, ph, gamma, epsilon, rhL) : call.ext <- match.call() out <- valid_args(obj_fct = as.list(environment()), call.ext) # Variables que valid_args tire de strata Ls <- out$Ls; takenone <- out$takenone; certain <- out$certain; L <- out$L; rhL <- out$rhL; # Variables relatives au model nmodel <- out$nmodel; beta <- out$beta; sig2 <- out$sig2; ph <- out$ph; pcertain <- out$pcertain; gamma <- out$gamma; epsilon <- out$epsilon; # Variable pour la sortie : liste des arguments args <- out$args; # Initialisation de variables tirées de strata : ##### ÉTAPE TRÈS IMPORTANTE x <- if (!is.null(call.ext$y)) y else strata$args$x # Si y a été donné en entrée, on doit faire les calculs sur y plutôt que x, alors on modifie x ##### N <- length(x) ## Nombre total d'observations Nc <- length(certain) Nnoc <- N - Nc ## nombre d'observations sans la strate certain (dans le vecteur xnoc) xnoc <- if (is.null(certain)) x else x[-certain] ## observations sans la strate certain strata.rhL <- if (takenone > 0) c(rep(1,length(takenone), strata$args$rh)) else strata$args$rh stratumIDnoc <- if (is.null(certain)) strata$stratumID else as.numeric(as.character(strata$stratumID[-certain])) Nh <- strata$Nh bias.penalty <- if(is.null(strata$args$bias.penalty)) 1 else strata$args$bias.penalty # Initialisation de quelques simples stat calculées sur les données (EX, EX2, EYc) out <- init_stat(obj_fct = as.list(environment())) EX <- out$EX; EX2 <- out$EX2; EYc <- out$EYc; # Calcul des moments anticipées moments <- .C("get_momentY_C", as.double(xnoc), as.integer(stratumIDnoc), as.integer(Nnoc), as.integer(Nh), as.integer(L), as.integer(Nc), as.double(EYc), as.integer(takenone), as.integer(nmodel), as.double(beta), as.double(sig2), as.double(ph), as.double(gamma), as.double(epsilon), as.double(EX), as.double(EX2), EYh = as.double(rep(0,L)), VYh = as.double(rep(0,L)), phih = as.double(rep(0,L)), psih = as.double(rep(0,L)), TY = as.double(0), TAY = as.double(0), NAOK = TRUE, PACKAGE="stratification") EYh <- moments$EYh VYh <- moments$VYh TY <- moments$TY TAY <- moments$TAY # Ajustement à postériori pour la non-réponse, si demandé et si CV cible if (rh.postcorr && !is.null(strata$args$n)){ warning("no posterior correction for non-response is available for stratified design with a target n") dopostcorr <- FALSE ## Si le plan d'échantillonnage comporte un n cible, celui-ci ne serait plus atteint si on appliquait ## notre correction à postériori pour non-réponse qui gonfle les nh. On ne le fait donc pas. } else { dopostcorr <- rh.postcorr } nhnonint <- if (dopostcorr) strata$nhnonint*strata.rhL/rhL else strata$nhnonint nh <- if (dopostcorr) pmin(ceiling(nhnonint), Nh) else strata$nh ## Remarque : Ici, on n'arrondit pas nh de la meme façon que dans le reste du package. # Pour le calcul d'autres valeurs pour la sortie n <- get_n(nhcalcul = nh, obj_fct = as.list(environment())) RRMSE <- NA ## car on veut que get_stat_out fasse le calcul du RRMSE out_stat <- get_stat_out(obj_fct = as.list(environment())) # Sortie des résultats out <- list(nh=nh, n=n, nhnonint=nhnonint, certain.info = c(Nc = Nc, meanc = EYc), meanh = EYh, varh = VYh, mean=TY/N) out <- c(out, out_stat) out <- c(out, list(call = call.ext, date = date(), args = args)) class(out) <- "var.strata" return(out) } print.var.strata <- function(x,...) { # Section des arguments fournis cat("Given arguments:\n") cat("strata = "); print(x$call$strata) if (!is.null(x$args$y)) { cat("y = "); print(x$call$y) } cat("rh.postcorr =",x$args$rh.postcorr) if (is.null(x$args$y)) { cat("\nmodel =",x$args$model) nparam <- length(x$args$model.control) if (nparam>0) { cat(" : ") for (i in 1:nparam) { cat(names(x$args$model.control)[i],"=",x$args$model.control[[i]]) if (i<nparam) cat(" , ") } } } # Section du tableau de stratification takenone <- if (is.null(x$args$strata$args$takenone)) 0 else x$args$strata$args$takenone L<-x$args$strata$args$L+takenone rh <- if(takenone==0) x$args$rh else c(NA,x$args$rh) ph <- c(x$args$model.control$ptakenone,x$args$model.control$ph,x$args$model.control$pcertain) type <- ifelse(x$nh == 0, "take-none", ifelse(x$nh == x$args$strata$Nh, "take-all", "take-some")) tableau<-data.frame(rep("|",L),type,rh,x$args$strata$Nh,x$nh,x$nh/x$args$strata$Nh,rep("|",L),x$meanh,x$varh, stringsAsFactors=FALSE) colnames(tableau) <- c("|","type","rh","Nh","nh","fh","|","E(Y)","Var(Y)") if(!is.null(x$args$strata$args$certain)) { tableau <- rbind(tableau, list("|","certain",1,x$certain.info["Nc"],x$certain.info["Nc"],1,"|",x$certain.info["meanc"],NA)) } tableau<-rbind(tableau,c(NA,NA,NA,sum(tableau$Nh),x$n,x$n/sum(tableau$Nh),NA,NA,NA)) rownames(tableau) <- if(!is.null(x$args$strata$args$certain)) c(paste("stratum",1:L),"","Total") else c(paste("stratum",1:L),"Total") if (identical(x$args$model,"loglinear")) tableau<-cbind("ph"=c(ph,NA),tableau) tableau[,unlist(lapply(tableau,is.numeric))]<-round(tableau[,unlist(lapply(tableau,is.numeric))],2) ### Correction pour afficher correctement les NA tableauc<-format(tableau) for (i in 1:(dim(tableauc)[1]-1)) tableauc[i,] <- ifelse(substr(tableauc[i,],nchar(tableauc[i,])-1,nchar(tableauc[i,]))=="NA","-",tableauc[i,]) tableauc[dim(tableauc)[1],] <- ifelse(substr(tableauc[dim(tableauc)[1],],nchar(tableauc[dim(tableauc)[1],])-1, nchar(tableauc[dim(tableauc)[1],]))=="NA","",tableauc[dim(tableauc)[1],]) ### Fin de la correction cat("\n\nStrata information:\n") print(tableauc,na.print="") cat("\nTotal sample size:",x$n,"\n") cat("Anticipated population mean:",x$mean,"\n") # Section sur les moments anticipés sortie <- if (is.null(x$args$strata$args$takenone)) 1 else { if(0==x$args$strata$args$takenone) 2 else 3 } if (sortie%in%c(1,2)) { cat("Anticipated CV:",x$RRMSE,"\n") if (2==sortie) cat("Note: CV=RRMSE (Relative Root Mean Squared Error) because takenone=0.\n") } else { est<-cbind(x$relativebias,x$propbiasMSE,x$RRMSE,x$args$strata$args$CV) dimnames(est) <- if(length(est)==4) list(" ",c("relative bias","prop bias MSE","RRMSE","target RRMSE")) else list(" ",c("relative bias","prop bias MSE","RRMSE")) cat("\nAnticipated moments of the estimator:\n") print.default(est, print.gap = 2, quote = FALSE, right=TRUE) } }
/stratification/R/var.strata.R
no_license
ingted/R-Examples
R
false
false
7,231
r
var.strata <- function(strata, y = NULL, rh = strata$args$rh, rh.postcorr = FALSE, model=c("none", "loglinear", "linear", "random"), model.control = list()) { ### Fonction externe : voir fiche d'aide pour la documentation # Validation des arguments et initialisation de variables # (Ls, takenone, certain, nmodel, beta, sig2, ph, gamma, epsilon, rhL) : call.ext <- match.call() out <- valid_args(obj_fct = as.list(environment()), call.ext) # Variables que valid_args tire de strata Ls <- out$Ls; takenone <- out$takenone; certain <- out$certain; L <- out$L; rhL <- out$rhL; # Variables relatives au model nmodel <- out$nmodel; beta <- out$beta; sig2 <- out$sig2; ph <- out$ph; pcertain <- out$pcertain; gamma <- out$gamma; epsilon <- out$epsilon; # Variable pour la sortie : liste des arguments args <- out$args; # Initialisation de variables tirées de strata : ##### ÉTAPE TRÈS IMPORTANTE x <- if (!is.null(call.ext$y)) y else strata$args$x # Si y a été donné en entrée, on doit faire les calculs sur y plutôt que x, alors on modifie x ##### N <- length(x) ## Nombre total d'observations Nc <- length(certain) Nnoc <- N - Nc ## nombre d'observations sans la strate certain (dans le vecteur xnoc) xnoc <- if (is.null(certain)) x else x[-certain] ## observations sans la strate certain strata.rhL <- if (takenone > 0) c(rep(1,length(takenone), strata$args$rh)) else strata$args$rh stratumIDnoc <- if (is.null(certain)) strata$stratumID else as.numeric(as.character(strata$stratumID[-certain])) Nh <- strata$Nh bias.penalty <- if(is.null(strata$args$bias.penalty)) 1 else strata$args$bias.penalty # Initialisation de quelques simples stat calculées sur les données (EX, EX2, EYc) out <- init_stat(obj_fct = as.list(environment())) EX <- out$EX; EX2 <- out$EX2; EYc <- out$EYc; # Calcul des moments anticipées moments <- .C("get_momentY_C", as.double(xnoc), as.integer(stratumIDnoc), as.integer(Nnoc), as.integer(Nh), as.integer(L), as.integer(Nc), as.double(EYc), as.integer(takenone), as.integer(nmodel), as.double(beta), as.double(sig2), as.double(ph), as.double(gamma), as.double(epsilon), as.double(EX), as.double(EX2), EYh = as.double(rep(0,L)), VYh = as.double(rep(0,L)), phih = as.double(rep(0,L)), psih = as.double(rep(0,L)), TY = as.double(0), TAY = as.double(0), NAOK = TRUE, PACKAGE="stratification") EYh <- moments$EYh VYh <- moments$VYh TY <- moments$TY TAY <- moments$TAY # Ajustement à postériori pour la non-réponse, si demandé et si CV cible if (rh.postcorr && !is.null(strata$args$n)){ warning("no posterior correction for non-response is available for stratified design with a target n") dopostcorr <- FALSE ## Si le plan d'échantillonnage comporte un n cible, celui-ci ne serait plus atteint si on appliquait ## notre correction à postériori pour non-réponse qui gonfle les nh. On ne le fait donc pas. } else { dopostcorr <- rh.postcorr } nhnonint <- if (dopostcorr) strata$nhnonint*strata.rhL/rhL else strata$nhnonint nh <- if (dopostcorr) pmin(ceiling(nhnonint), Nh) else strata$nh ## Remarque : Ici, on n'arrondit pas nh de la meme façon que dans le reste du package. # Pour le calcul d'autres valeurs pour la sortie n <- get_n(nhcalcul = nh, obj_fct = as.list(environment())) RRMSE <- NA ## car on veut que get_stat_out fasse le calcul du RRMSE out_stat <- get_stat_out(obj_fct = as.list(environment())) # Sortie des résultats out <- list(nh=nh, n=n, nhnonint=nhnonint, certain.info = c(Nc = Nc, meanc = EYc), meanh = EYh, varh = VYh, mean=TY/N) out <- c(out, out_stat) out <- c(out, list(call = call.ext, date = date(), args = args)) class(out) <- "var.strata" return(out) } print.var.strata <- function(x,...) { # Section des arguments fournis cat("Given arguments:\n") cat("strata = "); print(x$call$strata) if (!is.null(x$args$y)) { cat("y = "); print(x$call$y) } cat("rh.postcorr =",x$args$rh.postcorr) if (is.null(x$args$y)) { cat("\nmodel =",x$args$model) nparam <- length(x$args$model.control) if (nparam>0) { cat(" : ") for (i in 1:nparam) { cat(names(x$args$model.control)[i],"=",x$args$model.control[[i]]) if (i<nparam) cat(" , ") } } } # Section du tableau de stratification takenone <- if (is.null(x$args$strata$args$takenone)) 0 else x$args$strata$args$takenone L<-x$args$strata$args$L+takenone rh <- if(takenone==0) x$args$rh else c(NA,x$args$rh) ph <- c(x$args$model.control$ptakenone,x$args$model.control$ph,x$args$model.control$pcertain) type <- ifelse(x$nh == 0, "take-none", ifelse(x$nh == x$args$strata$Nh, "take-all", "take-some")) tableau<-data.frame(rep("|",L),type,rh,x$args$strata$Nh,x$nh,x$nh/x$args$strata$Nh,rep("|",L),x$meanh,x$varh, stringsAsFactors=FALSE) colnames(tableau) <- c("|","type","rh","Nh","nh","fh","|","E(Y)","Var(Y)") if(!is.null(x$args$strata$args$certain)) { tableau <- rbind(tableau, list("|","certain",1,x$certain.info["Nc"],x$certain.info["Nc"],1,"|",x$certain.info["meanc"],NA)) } tableau<-rbind(tableau,c(NA,NA,NA,sum(tableau$Nh),x$n,x$n/sum(tableau$Nh),NA,NA,NA)) rownames(tableau) <- if(!is.null(x$args$strata$args$certain)) c(paste("stratum",1:L),"","Total") else c(paste("stratum",1:L),"Total") if (identical(x$args$model,"loglinear")) tableau<-cbind("ph"=c(ph,NA),tableau) tableau[,unlist(lapply(tableau,is.numeric))]<-round(tableau[,unlist(lapply(tableau,is.numeric))],2) ### Correction pour afficher correctement les NA tableauc<-format(tableau) for (i in 1:(dim(tableauc)[1]-1)) tableauc[i,] <- ifelse(substr(tableauc[i,],nchar(tableauc[i,])-1,nchar(tableauc[i,]))=="NA","-",tableauc[i,]) tableauc[dim(tableauc)[1],] <- ifelse(substr(tableauc[dim(tableauc)[1],],nchar(tableauc[dim(tableauc)[1],])-1, nchar(tableauc[dim(tableauc)[1],]))=="NA","",tableauc[dim(tableauc)[1],]) ### Fin de la correction cat("\n\nStrata information:\n") print(tableauc,na.print="") cat("\nTotal sample size:",x$n,"\n") cat("Anticipated population mean:",x$mean,"\n") # Section sur les moments anticipés sortie <- if (is.null(x$args$strata$args$takenone)) 1 else { if(0==x$args$strata$args$takenone) 2 else 3 } if (sortie%in%c(1,2)) { cat("Anticipated CV:",x$RRMSE,"\n") if (2==sortie) cat("Note: CV=RRMSE (Relative Root Mean Squared Error) because takenone=0.\n") } else { est<-cbind(x$relativebias,x$propbiasMSE,x$RRMSE,x$args$strata$args$CV) dimnames(est) <- if(length(est)==4) list(" ",c("relative bias","prop bias MSE","RRMSE","target RRMSE")) else list(" ",c("relative bias","prop bias MSE","RRMSE")) cat("\nAnticipated moments of the estimator:\n") print.default(est, print.gap = 2, quote = FALSE, right=TRUE) } }
# (c) 2013-2016 Oasis LMF Ltd. Software provided for early adopter evaluation only. # define user Admin # Server side script for accessing the Company User List for Flamingo in association with OASIS LMF ############################################## Global Variables ##################################### UserID <- -1 # when no user is selected user ID is reset to -1 CULdata <- 0 useradminflg <<- "" ############################################### functions ########################################### checkuapermissions <- function(){ res <- NULL query <- paste0("exec dbo.getResourceModeUser ", user_id, ", 905") res <- execute_query(query) return(res) } # populates the options for the dropdown (sinputcompany) select input (All option not included) getcomplist <- function() { res <- NULL #res <- execute_query(paste("select CompanyName, CompanyID from dbo.Company where deleted = 0")) res <- execute_query(paste("exec dbo.getCompanies")) rows <- nrow(res) if (rows > 0) { s_options2 <- list() s_options2[[("Select Company")]] <- ("0") for (i in 1:rows){ s_options2[[paste(sprintf("%s", res[i, 2]))]] <- paste0(sprintf("%s", res[i, 1])) } return(s_options2) } return(res) } # populates the options for the dropdown (sinputSecurity) select input (All option included) getsecuritylist <- function() { res <- NULL #res <- execute_query(paste("select SecurityGroupID, SecurotyGroupName from dbo.SecurityGroup")) res <- execute_query(paste("exec dbo.getSecurityGroups")) rows <- nrow(res) if (rows > 0) { s_options2 <- list() s_options2[[("All")]] <- ("0") for (i in 1:rows){ s_options2[[paste(sprintf("%s", res[i, 2]))]] <- paste0(sprintf("%s", res[i, 1])) } return(s_options2) } return(res) } # populates the toptions for the dropdown (sinputOasisID) select input (All option not included) getoasisidlist <- function() { res <- NULL res <- execute_query(paste("select OasisUserID, OasisUserName from dbo.OasisUser")) rows <- nrow(res) if (rows > 0) { s_options2 <- list() s_options2[[("Select Oasis User ID")]] <- ("0") for (i in 1:rows){ s_options2[[paste(sprintf("%s", res[i, 2]))]] <- paste0(sprintf("%s", res[i, 1])) } return(s_options2) } return(res) } # draw company user list table with custom format options, queries the database every time to update its dataset drawCULtable <- function(){ query <- NULL query <- paste0("exec dbo.getUsersForCompany") CULdata <<- NULL CULdata <<- execute_query(query) datatable( CULdata, rownames = TRUE, filter = "none", selection = "single", colnames = c('Row Number' = 1), options = list( columnDefs = list(list(visible = FALSE, targets = 0)), #autoWidth=TRUE, rowCallback = JS('function(nRow, aData, iDisplayIndex, iDisplayIndexFull) { ////$("th").css("background-color", "#F5A9BC"); $("th").css("text-align", "center"); $("td", nRow).css("font-size", "12px"); $("td", nRow).css("text-align", "center"); }') ) ) } # draw User Securtiy Group table with custom format options, queries the database every time to update its dataset drawUSGtable <- function(){ query <- NULL USGdata <<- NULL query <- paste("exec dbo.getSecurityGroupsForUser ", UserID) USGdata <<- execute_query(query) datatable( USGdata, rownames = TRUE, selection = "none", colnames = c('Row Number' = 1), options = list( autoWidth=TRUE, columnDefs = list(list(visible = FALSE, targets = 0)), rowCallback = JS('function(nRow, aData, iDisplayIndex, iDisplayIndexFull) { //$("th").css("background-color", "#F5A9BC"); $("th").css("text-align", "center"); $("td", nRow).css("font-size", "12px"); $("td", nRow).css("text-align", "center"); }'), search = list(caseInsensitive = TRUE), processing=0, pageLength = 10) ) } # draw User License table with custom format options, quries the database every time to update dataset drawULtable <- function(){ query <- NULL CUAULdata <<- NULL query <- paste("exec dbo.getUserLicenses ", UserID) CUAULdata <<- execute_query(query) datatable( CUAULdata, rownames = TRUE, selection = "none", colnames = c('Row Number' = 1), options = list( autoWidth = TRUE, scrollX = TRUE, columnDefs = list(list(visible = FALSE, targets = 0)), rowCallback = JS('function(nRow, aData, iDisplayIndex, iDisplayIndexFull) { //$("th").css("background-color", "#F5A9BC"); $("th").css("text-align", "center"); $("td", nRow).css("font-size", "12px"); $("td", nRow).css("text-align", "center"); }'), search = list(caseInsensitive = TRUE), processing=0, pageLength = 10) ) } # queries the database to retrieve department login and password details for selected user, # only used once hence Deptdata is not global getDeptdata <- function(){ query <- NULL res <- NULL query <- paste("exec dbo.getUserDepartment ", UserID) res <- execute_query(query) return(res) } # Function to clear the information fields on the left hand side, # resets UserID global variable to -1 clearFields <- function(){ UserID <<- -1 updateTextInput(session, "tinputUserName", value = "") updateSelectInput(session, "sinputCompany", selected = c("Select Company"= 0)) updateTextInput(session, "tinputDepartment", value = "") updateTextInput(session, "tinputLogin", value = "") updateTextInput(session, "tinputPassword", value = "") } ############################################## Permission Checking ################################ observe({ input$ua if(input$ua == "defineuser"){ permission <- checkuapermissions() if(identical(permission[,1], character(0))){ info("You do not have the required permissions to view this page") gotoua() } else{ if(permission[1,1] == "CRUD"){ shinyjs::enable("abuttonnewUser") shinyjs::enable("abuttonuserupdate") shinyjs::enable("abuttonuserdelete") shinyjs::enable("abuttonusersecurity") shinyjs::enable("abuttonuseroasis") } else if(permission[1,1] == "R"){ shinyjs::disable("abuttonnewUser") shinyjs::disable("abuttonuserupdate") shinyjs::disable("abuttonuserdelete") shinyjs::disable("abuttonusersecurity") shinyjs::disable("abuttonuseroasis") } else{ info("Neither CRUD nor R") } } } }) ############################################### Draw Tables ########################################### #Render Company user list data when the page is loaded, calls the drawCULtable function output$tablecompanyuserlist <- DT::renderDataTable({ input$ua if (input$ua == "defineuser") { complist <- getcomplist() updateSelectInput(session, "sinputCompany", choices = complist, selected = c("Select Company" = 0)) securitylist <- getsecuritylist() updateSelectInput(session, "sinputSecurity", choices = securitylist, selected = c("All" = 0)) oasisidlist <- getoasisidlist() updateSelectInput(session, "sinputOasisID", choices = oasisidlist, selected = c("Select Oasis User ID" = 0)) shinyjs::hide("usgroups") shinyjs::hide("ulicenses") clearFields() drawCULtable() } }) ######################################################## Text Input Updating ############################ # updates the details on the left hand side every time a row is clicked # uses the list of rows selected to attain row index # row index is used to access data in table and render it to the left hand side observe({ input$tablecompanyuserlist_rows_selected if (input$ua == "defineuser") { if(length(input$tablecompanyuserlist_rows_selected) > 0){ UserID <<- CULdata[input$tablecompanyuserlist_rows_selected, 3] updateTextInput(session, "tinputID", value = UserID) updateTextInput(session, "tinputUserName", value = CULdata[input$tablecompanyuserlist_rows_selected, 4]) updateSelectInput(session, "sinputCompany", selected = CULdata[(input$tablecompanyuserlist_rows_selected),1]) Deptdata <- {getDeptdata()} updateTextInput(session, "tinputDepartment", value = Deptdata[[3]]) updateTextInput(session, "tinputLogin", value = Deptdata[[1]]) updateTextInput(session, "tinputPassword", value = Deptdata[[2]]) output$tableusersecuritygroups <- DT::renderDataTable({drawUSGtable()}) shinyjs::show("ulicenses") output$tableuserlicenses <- DT::renderDataTable({drawULtable()}) shinyjs::show("usgroups") }else{ shinyjs::hide("usgroups") shinyjs::hide("ulicenses") clearFields() } }}) ########################################## User Create / Update / Delete ################################### # onclick of create button onclick("abuttonnewUser", { useradminflg <<- "C" clearFields() }) # cancel new user # clears the fields, hides confirm cancel, shows CRUD buttons onclick("abuttonusercancel",{ toggleModal(session, "useradmincrtupmodal", toggle = "close") clearFields() output$tablecompanyuserlist <- DT::renderDataTable({drawCULtable()}) }) #on click of update button onclick("abuttonuserupdate", { if(length(input$tablecompanyuserlist_rows_selected) > 0){ useradminflg <<- "U" toggleModal(session, "useradmincrtupmodal", toggle = "open") } else{ info("Please select a user to update details.") } }) #on click of submit button in pop-up to create/update onclick("abuttonusersubmit",{ res <- NULL if (useradminflg == "C"){ query <- paste0("exec dbo.CreateNewUser", " [",input$tinputUserName,"]", ", ","[",input$sinputCompany, "]", ", ","[", input$tinputLogin, "]", ", ","[", input$tinputPassword, "]", ", ","[", input$tinputDepartment,"]") res <- execute_query(query) if (is.null(res)) { info(paste("Failed to create new user - ", input$tinputUserName)) }else{ info(paste("User ", input$tinputUserName, " created. User id: ", res)) } }else{ if (useradminflg == "U"){ query <- paste0("exec dbo.updateUser", " '",UserID,"'", ", ","'",input$tinputUserName,"'", ", ","'",input$sinputCompany, "'", ", ","'", input$tinputLogin, "'", ", ","'", input$tinputPassword, "'", ", ","'", input$tinputDepartment,"'") res <- execute_query(query) if (is.null(res)) { info(paste("Failed to update user - ",input$tinputUserName)) }else{ info(paste("User -", input$tinputUserName, " updated.")) } }} useradminflg <<- "" toggleModal(session, "useradmincrtupmodal", toggle = "close") output$tablecompanyuserlist <- DT::renderDataTable({drawCULtable()}) }) #onclick of delete button onclick("abuttonuserdelete", { if(length(input$tablecompanyuserlist_rows_selected) > 0){ toggleModal(session, "userdelmodal", toggle = "open") } else{ info("Please select a user to delete") } }) #onclick of cancel delete button onclick("abuttonucanceldel", { toggleModal(session, "userdelmodal", toggle = "close") output$tablecompanyuserlist <- DT::renderDataTable({drawCULtable()}) }) #onclick of confirm delete button onclick("abuttonuconfirmdel",{ query <- paste0("exec dbo.deleteUser", " '",CULdata[input$tablecompanyuserlist_rows_selected, 3],"'") res <- execute_query(query) if (is.null(res)) { info(paste("Failed to delete user - ", CULdata[input$tablecompanyuserlist_rows_selected, 4])) }else{ info(paste("User -", CULdata[input$tablecompanyuserlist_rows_selected, 4], " deleted.")) } clearFields() toggleModal(session, "userdelmodal", toggle = "close") output$tablecompanyuserlist <- DT::renderDataTable({drawCULtable()}) }) ##################################################### Security Group Add/Delete ############################################# #onclick of add/remove security button onclick("abuttonusersecurity", { if(length(input$tablecompanyuserlist_rows_selected) > 0){ securitylist <- getsecuritylist() updateSelectInput(session, "sinputSecurity", choices = securitylist, selected = c("All" = 0)) toggleModal(session, "usersecuritymodal", toggle = "open") } else{ info("Please select a user to add security group") } }) #onclick of add security button in pop-up onclick("abuttonaddsecurity", { query <- paste0("exec dbo.addSecurityGroup", " '",UserID,"'", ", ","'",input$sinputSecurity,"'") res <- execute_query(query) output$tableusersecuritygroups <- DT::renderDataTable({ if (length(input$tablecompanyuserlist_rows_selected) > 0) { drawUSGtable() } }) toggleModal(session, "usersecuritymodal", toggle = "close") }) #onclick of remove security button onclick("abuttonrmvsecurity", { query <- paste0("exec dbo.removeSecurityGroup", " '",UserID,"'", ", ","'",input$sinputSecurity,"'") execute_query(query) output$tableusersecuritygroups <- DT::renderDataTable({ if (length(input$tablecompanyuserlist_rows_selected) > 0) { drawUSGtable() } }) toggleModal(session, "usersecuritymodal", toggle = "close") }) ################################# Oasis User Id (License) Add/Delete ############################################ #onclick of add/remove license button onclick("abuttonuseroasis", { if(length(input$tablecompanyuserlist_rows_selected) > 0){ oasisidlist <- getoasisidlist() updateSelectInput(session, "sinputOasisID", choices = oasisidlist, selected = c("Select Oasis User ID" = 0)) toggleModal(session, "userlicensemodal", toggle = "open") } else{ info("Please select a user to add license") } }) #onclick of add license button in pop-up onclick("abuttonaddoasisid", { query <- paste0("exec dbo.addUserLicense", " '",UserID,"'", ", ","'",input$sinputOasisID,"'") execute_query(query) output$tableuserlicenses <- DT::renderDataTable({ input$tablecompanyuserlist_rows_selected if (length(input$tablecompanyuserlist_rows_selected) > 0){ drawULtable() } }) toggleModal(session, "userlicensemodal", toggle = "close") }) #onclick of remove license button in pop-up onclick("abuttonrmvoasisid", { query <- paste0("exec dbo.removeUserLicense", " '",UserID,"'", ", ","'",input$sinputOasisID,"'") execute_query(query) output$tableuserlicenses <- DT::renderDataTable({ input$tablecompanyuserlist_rows_selected if (length(input$tablecompanyuserlist_rows_selected) > 0){ drawULtable() } }) toggleModal(session, "userlicensemodal", toggle = "close") }) ####################################################### Export to Excel #################################################### #User List output$CUACULdownloadexcel <- downloadHandler( filename ="companyuserlist.csv", content = function(file) { write.csv(CULdata, file)} ) #User Security Groups output$CUAUUSGdownloadexcel <- downloadHandler( filename ="usersecuritygroups.csv", content = function(file) { write.csv(USGdata, file)} ) #User Licenses output$CUAULdownloadexcel <- downloadHandler( filename ="userlicenses.csv", content = function(file) { write.csv(CUAULdata, file)} )
/BFE_RShiny/defineUserAdmin_server.R
no_license
kulprasanna/oasislmf
R
false
false
15,610
r
# (c) 2013-2016 Oasis LMF Ltd. Software provided for early adopter evaluation only. # define user Admin # Server side script for accessing the Company User List for Flamingo in association with OASIS LMF ############################################## Global Variables ##################################### UserID <- -1 # when no user is selected user ID is reset to -1 CULdata <- 0 useradminflg <<- "" ############################################### functions ########################################### checkuapermissions <- function(){ res <- NULL query <- paste0("exec dbo.getResourceModeUser ", user_id, ", 905") res <- execute_query(query) return(res) } # populates the options for the dropdown (sinputcompany) select input (All option not included) getcomplist <- function() { res <- NULL #res <- execute_query(paste("select CompanyName, CompanyID from dbo.Company where deleted = 0")) res <- execute_query(paste("exec dbo.getCompanies")) rows <- nrow(res) if (rows > 0) { s_options2 <- list() s_options2[[("Select Company")]] <- ("0") for (i in 1:rows){ s_options2[[paste(sprintf("%s", res[i, 2]))]] <- paste0(sprintf("%s", res[i, 1])) } return(s_options2) } return(res) } # populates the options for the dropdown (sinputSecurity) select input (All option included) getsecuritylist <- function() { res <- NULL #res <- execute_query(paste("select SecurityGroupID, SecurotyGroupName from dbo.SecurityGroup")) res <- execute_query(paste("exec dbo.getSecurityGroups")) rows <- nrow(res) if (rows > 0) { s_options2 <- list() s_options2[[("All")]] <- ("0") for (i in 1:rows){ s_options2[[paste(sprintf("%s", res[i, 2]))]] <- paste0(sprintf("%s", res[i, 1])) } return(s_options2) } return(res) } # populates the toptions for the dropdown (sinputOasisID) select input (All option not included) getoasisidlist <- function() { res <- NULL res <- execute_query(paste("select OasisUserID, OasisUserName from dbo.OasisUser")) rows <- nrow(res) if (rows > 0) { s_options2 <- list() s_options2[[("Select Oasis User ID")]] <- ("0") for (i in 1:rows){ s_options2[[paste(sprintf("%s", res[i, 2]))]] <- paste0(sprintf("%s", res[i, 1])) } return(s_options2) } return(res) } # draw company user list table with custom format options, queries the database every time to update its dataset drawCULtable <- function(){ query <- NULL query <- paste0("exec dbo.getUsersForCompany") CULdata <<- NULL CULdata <<- execute_query(query) datatable( CULdata, rownames = TRUE, filter = "none", selection = "single", colnames = c('Row Number' = 1), options = list( columnDefs = list(list(visible = FALSE, targets = 0)), #autoWidth=TRUE, rowCallback = JS('function(nRow, aData, iDisplayIndex, iDisplayIndexFull) { ////$("th").css("background-color", "#F5A9BC"); $("th").css("text-align", "center"); $("td", nRow).css("font-size", "12px"); $("td", nRow).css("text-align", "center"); }') ) ) } # draw User Securtiy Group table with custom format options, queries the database every time to update its dataset drawUSGtable <- function(){ query <- NULL USGdata <<- NULL query <- paste("exec dbo.getSecurityGroupsForUser ", UserID) USGdata <<- execute_query(query) datatable( USGdata, rownames = TRUE, selection = "none", colnames = c('Row Number' = 1), options = list( autoWidth=TRUE, columnDefs = list(list(visible = FALSE, targets = 0)), rowCallback = JS('function(nRow, aData, iDisplayIndex, iDisplayIndexFull) { //$("th").css("background-color", "#F5A9BC"); $("th").css("text-align", "center"); $("td", nRow).css("font-size", "12px"); $("td", nRow).css("text-align", "center"); }'), search = list(caseInsensitive = TRUE), processing=0, pageLength = 10) ) } # draw User License table with custom format options, quries the database every time to update dataset drawULtable <- function(){ query <- NULL CUAULdata <<- NULL query <- paste("exec dbo.getUserLicenses ", UserID) CUAULdata <<- execute_query(query) datatable( CUAULdata, rownames = TRUE, selection = "none", colnames = c('Row Number' = 1), options = list( autoWidth = TRUE, scrollX = TRUE, columnDefs = list(list(visible = FALSE, targets = 0)), rowCallback = JS('function(nRow, aData, iDisplayIndex, iDisplayIndexFull) { //$("th").css("background-color", "#F5A9BC"); $("th").css("text-align", "center"); $("td", nRow).css("font-size", "12px"); $("td", nRow).css("text-align", "center"); }'), search = list(caseInsensitive = TRUE), processing=0, pageLength = 10) ) } # queries the database to retrieve department login and password details for selected user, # only used once hence Deptdata is not global getDeptdata <- function(){ query <- NULL res <- NULL query <- paste("exec dbo.getUserDepartment ", UserID) res <- execute_query(query) return(res) } # Function to clear the information fields on the left hand side, # resets UserID global variable to -1 clearFields <- function(){ UserID <<- -1 updateTextInput(session, "tinputUserName", value = "") updateSelectInput(session, "sinputCompany", selected = c("Select Company"= 0)) updateTextInput(session, "tinputDepartment", value = "") updateTextInput(session, "tinputLogin", value = "") updateTextInput(session, "tinputPassword", value = "") } ############################################## Permission Checking ################################ observe({ input$ua if(input$ua == "defineuser"){ permission <- checkuapermissions() if(identical(permission[,1], character(0))){ info("You do not have the required permissions to view this page") gotoua() } else{ if(permission[1,1] == "CRUD"){ shinyjs::enable("abuttonnewUser") shinyjs::enable("abuttonuserupdate") shinyjs::enable("abuttonuserdelete") shinyjs::enable("abuttonusersecurity") shinyjs::enable("abuttonuseroasis") } else if(permission[1,1] == "R"){ shinyjs::disable("abuttonnewUser") shinyjs::disable("abuttonuserupdate") shinyjs::disable("abuttonuserdelete") shinyjs::disable("abuttonusersecurity") shinyjs::disable("abuttonuseroasis") } else{ info("Neither CRUD nor R") } } } }) ############################################### Draw Tables ########################################### #Render Company user list data when the page is loaded, calls the drawCULtable function output$tablecompanyuserlist <- DT::renderDataTable({ input$ua if (input$ua == "defineuser") { complist <- getcomplist() updateSelectInput(session, "sinputCompany", choices = complist, selected = c("Select Company" = 0)) securitylist <- getsecuritylist() updateSelectInput(session, "sinputSecurity", choices = securitylist, selected = c("All" = 0)) oasisidlist <- getoasisidlist() updateSelectInput(session, "sinputOasisID", choices = oasisidlist, selected = c("Select Oasis User ID" = 0)) shinyjs::hide("usgroups") shinyjs::hide("ulicenses") clearFields() drawCULtable() } }) ######################################################## Text Input Updating ############################ # updates the details on the left hand side every time a row is clicked # uses the list of rows selected to attain row index # row index is used to access data in table and render it to the left hand side observe({ input$tablecompanyuserlist_rows_selected if (input$ua == "defineuser") { if(length(input$tablecompanyuserlist_rows_selected) > 0){ UserID <<- CULdata[input$tablecompanyuserlist_rows_selected, 3] updateTextInput(session, "tinputID", value = UserID) updateTextInput(session, "tinputUserName", value = CULdata[input$tablecompanyuserlist_rows_selected, 4]) updateSelectInput(session, "sinputCompany", selected = CULdata[(input$tablecompanyuserlist_rows_selected),1]) Deptdata <- {getDeptdata()} updateTextInput(session, "tinputDepartment", value = Deptdata[[3]]) updateTextInput(session, "tinputLogin", value = Deptdata[[1]]) updateTextInput(session, "tinputPassword", value = Deptdata[[2]]) output$tableusersecuritygroups <- DT::renderDataTable({drawUSGtable()}) shinyjs::show("ulicenses") output$tableuserlicenses <- DT::renderDataTable({drawULtable()}) shinyjs::show("usgroups") }else{ shinyjs::hide("usgroups") shinyjs::hide("ulicenses") clearFields() } }}) ########################################## User Create / Update / Delete ################################### # onclick of create button onclick("abuttonnewUser", { useradminflg <<- "C" clearFields() }) # cancel new user # clears the fields, hides confirm cancel, shows CRUD buttons onclick("abuttonusercancel",{ toggleModal(session, "useradmincrtupmodal", toggle = "close") clearFields() output$tablecompanyuserlist <- DT::renderDataTable({drawCULtable()}) }) #on click of update button onclick("abuttonuserupdate", { if(length(input$tablecompanyuserlist_rows_selected) > 0){ useradminflg <<- "U" toggleModal(session, "useradmincrtupmodal", toggle = "open") } else{ info("Please select a user to update details.") } }) #on click of submit button in pop-up to create/update onclick("abuttonusersubmit",{ res <- NULL if (useradminflg == "C"){ query <- paste0("exec dbo.CreateNewUser", " [",input$tinputUserName,"]", ", ","[",input$sinputCompany, "]", ", ","[", input$tinputLogin, "]", ", ","[", input$tinputPassword, "]", ", ","[", input$tinputDepartment,"]") res <- execute_query(query) if (is.null(res)) { info(paste("Failed to create new user - ", input$tinputUserName)) }else{ info(paste("User ", input$tinputUserName, " created. User id: ", res)) } }else{ if (useradminflg == "U"){ query <- paste0("exec dbo.updateUser", " '",UserID,"'", ", ","'",input$tinputUserName,"'", ", ","'",input$sinputCompany, "'", ", ","'", input$tinputLogin, "'", ", ","'", input$tinputPassword, "'", ", ","'", input$tinputDepartment,"'") res <- execute_query(query) if (is.null(res)) { info(paste("Failed to update user - ",input$tinputUserName)) }else{ info(paste("User -", input$tinputUserName, " updated.")) } }} useradminflg <<- "" toggleModal(session, "useradmincrtupmodal", toggle = "close") output$tablecompanyuserlist <- DT::renderDataTable({drawCULtable()}) }) #onclick of delete button onclick("abuttonuserdelete", { if(length(input$tablecompanyuserlist_rows_selected) > 0){ toggleModal(session, "userdelmodal", toggle = "open") } else{ info("Please select a user to delete") } }) #onclick of cancel delete button onclick("abuttonucanceldel", { toggleModal(session, "userdelmodal", toggle = "close") output$tablecompanyuserlist <- DT::renderDataTable({drawCULtable()}) }) #onclick of confirm delete button onclick("abuttonuconfirmdel",{ query <- paste0("exec dbo.deleteUser", " '",CULdata[input$tablecompanyuserlist_rows_selected, 3],"'") res <- execute_query(query) if (is.null(res)) { info(paste("Failed to delete user - ", CULdata[input$tablecompanyuserlist_rows_selected, 4])) }else{ info(paste("User -", CULdata[input$tablecompanyuserlist_rows_selected, 4], " deleted.")) } clearFields() toggleModal(session, "userdelmodal", toggle = "close") output$tablecompanyuserlist <- DT::renderDataTable({drawCULtable()}) }) ##################################################### Security Group Add/Delete ############################################# #onclick of add/remove security button onclick("abuttonusersecurity", { if(length(input$tablecompanyuserlist_rows_selected) > 0){ securitylist <- getsecuritylist() updateSelectInput(session, "sinputSecurity", choices = securitylist, selected = c("All" = 0)) toggleModal(session, "usersecuritymodal", toggle = "open") } else{ info("Please select a user to add security group") } }) #onclick of add security button in pop-up onclick("abuttonaddsecurity", { query <- paste0("exec dbo.addSecurityGroup", " '",UserID,"'", ", ","'",input$sinputSecurity,"'") res <- execute_query(query) output$tableusersecuritygroups <- DT::renderDataTable({ if (length(input$tablecompanyuserlist_rows_selected) > 0) { drawUSGtable() } }) toggleModal(session, "usersecuritymodal", toggle = "close") }) #onclick of remove security button onclick("abuttonrmvsecurity", { query <- paste0("exec dbo.removeSecurityGroup", " '",UserID,"'", ", ","'",input$sinputSecurity,"'") execute_query(query) output$tableusersecuritygroups <- DT::renderDataTable({ if (length(input$tablecompanyuserlist_rows_selected) > 0) { drawUSGtable() } }) toggleModal(session, "usersecuritymodal", toggle = "close") }) ################################# Oasis User Id (License) Add/Delete ############################################ #onclick of add/remove license button onclick("abuttonuseroasis", { if(length(input$tablecompanyuserlist_rows_selected) > 0){ oasisidlist <- getoasisidlist() updateSelectInput(session, "sinputOasisID", choices = oasisidlist, selected = c("Select Oasis User ID" = 0)) toggleModal(session, "userlicensemodal", toggle = "open") } else{ info("Please select a user to add license") } }) #onclick of add license button in pop-up onclick("abuttonaddoasisid", { query <- paste0("exec dbo.addUserLicense", " '",UserID,"'", ", ","'",input$sinputOasisID,"'") execute_query(query) output$tableuserlicenses <- DT::renderDataTable({ input$tablecompanyuserlist_rows_selected if (length(input$tablecompanyuserlist_rows_selected) > 0){ drawULtable() } }) toggleModal(session, "userlicensemodal", toggle = "close") }) #onclick of remove license button in pop-up onclick("abuttonrmvoasisid", { query <- paste0("exec dbo.removeUserLicense", " '",UserID,"'", ", ","'",input$sinputOasisID,"'") execute_query(query) output$tableuserlicenses <- DT::renderDataTable({ input$tablecompanyuserlist_rows_selected if (length(input$tablecompanyuserlist_rows_selected) > 0){ drawULtable() } }) toggleModal(session, "userlicensemodal", toggle = "close") }) ####################################################### Export to Excel #################################################### #User List output$CUACULdownloadexcel <- downloadHandler( filename ="companyuserlist.csv", content = function(file) { write.csv(CULdata, file)} ) #User Security Groups output$CUAUUSGdownloadexcel <- downloadHandler( filename ="usersecuritygroups.csv", content = function(file) { write.csv(USGdata, file)} ) #User Licenses output$CUAULdownloadexcel <- downloadHandler( filename ="userlicenses.csv", content = function(file) { write.csv(CUAULdata, file)} )