blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
327
content_id
stringlengths
40
40
detected_licenses
listlengths
0
91
license_type
stringclasses
2 values
repo_name
stringlengths
5
134
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
46 values
visit_date
timestamp[us]date
2016-08-02 22:44:29
2023-09-06 08:39:28
revision_date
timestamp[us]date
1977-08-08 00:00:00
2023-09-05 12:13:49
committer_date
timestamp[us]date
1977-08-08 00:00:00
2023-09-05 12:13:49
github_id
int64
19.4k
671M
star_events_count
int64
0
40k
fork_events_count
int64
0
32.4k
gha_license_id
stringclasses
14 values
gha_event_created_at
timestamp[us]date
2012-06-21 16:39:19
2023-09-14 21:52:42
gha_created_at
timestamp[us]date
2008-05-25 01:21:32
2023-06-28 13:19:12
gha_language
stringclasses
60 values
src_encoding
stringclasses
24 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
7
9.18M
extension
stringclasses
20 values
filename
stringlengths
1
141
content
stringlengths
7
9.18M
d19423a3f0ffc7c81089c2801e61104c4dd0d550
8454ae80dbf8aabab2d6efd630e19657a89443cb
/run_analysis.R
78707ef7563867b5dc78d0f018bdf240c2b3c1cf
[ "LicenseRef-scancode-public-domain" ]
permissive
cdsk/cleanHAR
62223f709c3e1f93ac60cb9f5b8c1ec6abf2f66a
7ea00f80827bd952f10ff56608801aca1a90782f
refs/heads/master
2016-09-03T06:43:20.631494
2015-04-26T19:47:34
2015-04-26T19:47:34
34,541,021
0
0
null
null
null
null
UTF-8
R
false
false
3,284
r
run_analysis.R
# Step 1: Merge the training and the test sets to create one data set. # Read features for descriptive variable names features <- read.table('features.txt') # some feature names have brackets "()", which when used as col.names get replaced with ".", which does not look good. # so we strip the brackets for aesthetic reasons col_names <- gsub("\\(\\)","",as.character(features[,2])) # We also fix some obviously bad naming from the original dataset col_names <- gsub('BodyBody','Body',col_names) # read training data sets, giving descriptive names for all columns subject_train <- read.table('train/subject_train.txt', col.names = 'subject') x_train <- read.table('train/X_train.txt', col.names = col_names) y_train <- read.table('train/y_train.txt', col.names = 'activity_id') # read test data sets subject_test <- read.table('test/subject_test.txt', col.names = 'subject') x_test <- read.table('test/X_test.txt', col.names = col_names) y_test <- read.table('test/y_test.txt', col.names = 'activity_id') # merge the training and the test sets to create one data set: # first merge the columns of training and test data sets respectively train <- cbind(subject_train, y_train, x_train) test <- cbind(subject_test, y_test, x_test) # then merge the rows of training and test data sets one_data_set <- rbind(train, test) # Step 2: Extract only the measurements on the mean and standard deviation for each measurement. # grep features for std and mean measurements # Note the "\\(" selects only measurements labelled mean() (i.e. with brackets), other measurements labelled mean but without don't come with corresponding standard deviation, so we choose to ignore them here mean_and_std_column_indexes <- grep('std|mean\\(', features[,2]) # we define the columns to extract from one_data_set. # need to add two added columns (subject and y) and an offset of 2 to the mean_and_std_column_indexes because of the two added columns at the beginning of the data frame columns_to_extract <- c(1, 2, mean_and_std_column_indexes + 2) filtered_data_set <- one_data_set[,columns_to_extract] # Step 3: Use descriptive activity names to name the activities in the data set # read activity labels activity_labels <- read.table('activity_labels.txt', col.names = c('activity_id','activity_name')) # merge data set with activity labels by activity_id (column activity_id exists in both tables) tidy_data_set <- merge(filtered_data_set, activity_labels) # Step 4: Appropriately label the data set with descriptive variable names. # Already done in Step 1 when reading the data tables using col.names # Step 5: # From the data set in step 4, create a second, independent tidy data set with the average of each variable for each activity and each subject. # Group the data set by subject and activity group_by <- list(Subject = tidy_data_set$subject, Activity = tidy_data_set$activity_name) # calculate the aggregate mean on grouped measurements result <- aggregate(tidy_data_set[3:68], group_by, mean) # finally order the result first by subject, then by activity result <- result[order(result[1],result[2]),] # and write result to a file write.table(result, file = "result.txt", row.names = FALSE) # you can read the file back in with: # > result <- read.table('result.txt', header = TRUE)
797c6b83029dca476fb6c7319481af67da472848
2ad78a2c1408410dec2de67530b6c68de4600b64
/Other files/maps.R
8fa16e7e48527dfc95c41d1dec94a965148e1629
[]
no_license
esmailansari/StatisticalAnalysis
0e03070d2ddb6a4bcf4425dc6f633ba95c8b0190
5ba82b2b38aada314d92d3953775757a95aee100
refs/heads/master
2021-01-09T20:45:04.682701
2014-08-11T06:01:16
2014-08-11T06:01:16
61,708,554
0
1
null
null
null
null
UTF-8
R
false
false
979
r
maps.R
rm(list=ls()) library(maps) library(ggplot2) library(ggmap) mydata <- read.csv("Well-Test summary.csv", header=TRUE) data<-mydata mydata <- mydata[mydata$long<0,] names(mydata)[names(mydata)=="Flow.Rate..BPD."]="Flow_Rate" states <- map_data("county","louisiana") #p <- ggplot(states, aes(long, lat)) + # geom_polygon(aes(group=group), colour='black',alpha=0.6) p <- ggplot() p <- p + geom_polygon( data=states, aes(x=long, y=lat, group = group),colour="white") #p <- p + theme(panel.grid.minor = element_line(colour="white", size=0.5))# + #scale_x_discrete(minor_breaks = seq(-94, -89, 0.2)) + #scale_y_discrete(minor_breaks = seq(29, 33, 0.2)) p <- p + geom_jitter(data=mydata, aes(x=long, y=lat, size = mydata$Permeability..mD., color="coral1"),label=rownames(mydata)) + theme(legend.position="none") #+ scale_size(name="Total enrollment") #p <- p + geom_text( data=mydata, aes(x=long, y=lat, label=rownames(mydata), colour="gold2", size=4 )) print(p) #gglocator(1)
376680a7af452afa6984eb6eb0cab7cd04633d08
3cf6e0763707036cacff70d7a4886ebec23593ca
/Chapter6lab2.R
6566047fc23b4f77d06b12e60056669bfb9742d6
[]
no_license
Lucky-Peter-Okonun/Stochastic-Project
dc2d4485fbefa270b092bcfaf57c24fd4df58ff7
ba3e85b3db6fd61d6cfa62bbf22e6187e116296a
refs/heads/master
2022-09-06T05:51:02.533224
2020-05-26T06:49:01
2020-05-26T06:49:01
null
0
0
null
null
null
null
UTF-8
R
false
false
11,471
r
Chapter6lab2.R
setwd("C:/Users/peter/Desktop/Stochasticlabcourse2Datasets") install.packages("splines") library(tidyverse) library(splines) library(nlme) #Question(6a) stem.cell.data = read.table("stemcell.txt", col.names = "order") #Implement a function that fits a regression spline for f regression.spline = function(Y, X, k, deg){ # Y = response, X = covariate, k = number of knots and deg, degree of spline = order - 1 of spline m = deg + 1 #order #Determine knots (as a vector) = equidistant partion of domain of X knots = seq(min(X), max(X), length.out = k+2) knots = c(min(X) - (m-1):1 , knots, max(X) + 1:(m-1)) N = spline.des(knots, X, ord = m)$design #Basis matrix for B-splines #Calculating least squares of Y as fitted by N for beta beta = lm(Y ~ N - 1)$coefficients # We utilize -1 to expunge the intercept #Definition of regression spline now f.hat = function(x){ n = spline.des(knots, x, ord = m, outer.ok = TRUE)$design as.numeric(n %*% beta) } return(f.hat) } #Now we fix the spline degree to 2 and estimate f with four different number of knots Y = stem.cell.data$order X = seq(10, 1440, 10) # Measurements of the order parameter every 10 minutes for 24 hours #Estimating splines for f for different number of knots f.fit.knot1 = regression.spline(Y, X, 4, deg = 2) f.fit.knot2 = regression.spline(Y, X, 15, deg = 2) f.fit.knot3 = regression.spline(Y, X, 23, deg = 2) f.fit.knot4 = regression.spline(Y, X, 30, deg = 2) #We create dataframes for the plots here Time = seq(10, 1440, 1) df1 = data.frame(x = Time, y = f.fit.knot1(Time)) df2 = data.frame(x = Time, y = f.fit.knot2(Time)) df3 = data.frame(x = Time, y = f.fit.knot3(Time)) df4 = data.frame(x = Time, y = f.fit.knot4(Time)) spline1 = ggplot(data = data.frame(x = X, y = Y), aes(x = x, y = y)) + geom_point(alpha = 0.4) + geom_line(data = df1, aes(color = "4")) + geom_line(data = df2, aes(color = "15")) + geom_line(data = df3, aes(color = "23")) + geom_line(data = df4, aes(color = "30")) + scale_colour_manual(name = "Number \nof \nKnots", values = c("maroon", "darkblue", "black", "yellow")) + xlab("Time(minutes)") + ylab("Order Parameter") + theme_classic(base_size = 12) + theme(legend.key = element_rect(fill = "white", colour = "gray")) + ggtitle("Regression Spline with Degree 2 for Four Different Knots") spline1 #Estimating f with number of knots as 4 and splines of degrees 1, 2, 3, 4 f.fit.deg1 = regression.spline(Y, X, 4, deg = 1) f.fit.deg2 = regression.spline(Y, X, 4, deg = 2) f.fit.deg3 = regression.spline(Y, X, 4, deg = 3) f.fit.deg4 = regression.spline(Y, X, 4, deg = 4) #We create dataframes for these 4 spline of degrees df5 = data.frame(x = Time, y = f.fit.deg1(Time)) df6 = data.frame(x = Time, y = f.fit.deg2(Time)) df7 = data.frame(x = Time, y = f.fit.deg3(Time)) df8 = data.frame(x = Time, y = f.fit.deg4(Time)) spline2 = ggplot(data = data.frame(x = X, y = Y), aes(x = x, y = y)) + geom_point(alpha = 0.4) + geom_line(data = df5, aes(color = "1")) + geom_line(data = df6, aes(color = "2")) + geom_line(data = df7, aes(color = "3")) + geom_line(data = df8, aes(color = "4")) + scale_colour_manual(name = "Degree", values = c("maroon", "darkblue", "black", "yellow")) + xlab("Time(minutes)") + ylab("Order Parameter") + theme_classic(base_size = 12) + theme(legend.key = element_rect(fill = "white", colour = "gray")) + ggtitle("Regression Spline with Number of Knots 4 for Four Degrees of 1, 2, 3 & 4") spline2 #Question(6b) #A function that estimates the optimal number of equidistant knots with GCV GCV = function(k, deg){ f.fitted = regression.spline(Y, X, k, deg = deg) f.fitted = f.fitted(X) a = norm(Y - f.fitted, type = "2") n = length(Y) res = (a**2)/(1 - k/n)**2 return(res) } #Vectorizing the GCV now GCV = Vectorize(GCV, vectorize.args = c("k")) #Optimise over k for degrees 1 to 4 max.k = 50 optimal.k.deg1 = which(GCV(1:max.k, deg = 1) == min(GCV(1:max.k, deg = 1))) optimal.k.deg2 = which(GCV(1:max.k, deg = 2) == min(GCV(1:max.k, deg = 2))) optimal.k.deg3 = which(GCV(1:max.k, deg = 3) == min(GCV(1:max.k, deg = 3))) optimal.k.deg4 = which(GCV(1:max.k, deg = 4) == min(GCV(1:max.k, deg = 4))) df.optimal.k = data.frame(deg1 = optimal.k.deg1, deg2 = optimal.k.deg2, deg3 = optimal.k.deg3, deg4 = optimal.k.deg4) row.names(df.optimal.k) = "Optimal GCV knot number" df.optimal.k #Calculating fits with GCV knots number, for degrees 1 to 4 f.fit.GCV1 = regression.spline(Y, X, k = optimal.k.deg1, deg = 1) f.fit.GCV2 = regression.spline(Y, X, k = optimal.k.deg2, deg = 2) f.fit.GCV3 = regression.spline(Y, X, k = optimal.k.deg3, deg = 3) f.fit.GCV4 = regression.spline(Y, X, k = optimal.k.deg4, deg = 4) #Dataframes to enable plotting of fits in one plot df9 = data.frame(x = Time, y = f.fit.GCV1(Time)) df10 = data.frame(x = Time, y = f.fit.GCV2(Time)) df11 = data.frame(x = Time, y = f.fit.GCV3(Time)) df12 = data.frame(x = Time, y = f.fit.GCV4(Time)) spline3= ggplot(data = data.frame(x = X, y = Y), aes(x = x, y = y)) + geom_point(alpha = 0.4) + geom_line(data = df9, aes(color = "1")) + geom_line(data = df10, aes(color = "2")) + geom_line(data = df11, aes(color = "3")) + geom_line(data = df12, aes(color = "4")) + scale_colour_manual(name = "Degree", values = c("maroon", "darkblue", "black", "yellow")) + xlab("Time(minutes)") + ylab("Order Parameter") + theme_classic(base_size = 12) + theme(legend.key = element_rect(fill = "white", colour = "gray")) + ggtitle("Regression Splines with Number of Knots from GCV for Four Degrees of 1, 2, 3 & 4") spline3 #Question(c) #Now we update the regression spline's function to accommodate the autoregressive process #of order one autoregressive.spline = function(Y, X, k, deg){ #Y = response, X = covariate, k = number of knots, deg, degree of spline = order-1 of spline m = deg + 1 #order #Determine knot points (equidistant partion of domain of X) knots = seq(min(X), max(X), length.out = k+2) knots = c(min(X) - (m-1):1 , knots, max(X) + 1:(m-1)) #Basis matrix of B-splines N = spline.des(knots, X, ord = m)$design # Implement autoregressive process of order 1 to the fit ("rescale the fit") a = 0.55 n = length(Y) R = toeplitz(a**(0:(n-1))) R.inverse = solve(R) NRN = t(N) %*% R.inverse %*% N NRY = t(N) %*% R.inverse %*% Y M = solve(NRN) %*% NRY #Regression spline f.hat = function(x){ n = spline.des(knots, x, ord = m, outer.ok = TRUE)$design #B-splines evaluated at x as.numeric(n %*% M) } return(f.hat) } #Now we update the GCV's function to accommodate the autoregressive process of order one autoregressive.GCV = function(k, deg){ f.fitted = autoregressive.spline(Y, X, k, deg = deg) f.fitted = f.fitted(X) a = 0.55 n = length(Y) R = toeplitz(a**(0:(n-1))) R.inverse = solve(R) aux = t(Y - f.fitted) %*% R.inverse %*% (Y - f.fitted) n = length(Y) res = aux/(1 - k/n)**2 return(res) } autoregressive.GCV = Vectorize(autoregressive.GCV, vectorize.args = c("k")) # Optimise over k for degrees 1 to 4 for the updated model optimal.k.deg1.AR = which(autoregressive.GCV(1:max.k, deg = 1) == min(autoregressive.GCV(1:max.k, deg = 1))) optimal.k.deg2.AR = which(autoregressive.GCV(1:max.k, deg = 2) == min(autoregressive.GCV(1:max.k, deg = 2))) optimal.k.deg3.AR = which(autoregressive.GCV(1:max.k, deg = 3) == min(autoregressive.GCV(1:max.k, deg = 3))) optimal.k.deg4.AR = which(autoregressive.GCV(1:max.k, deg = 4) == min(autoregressive.GCV(1:max.k, deg = 4))) df.optimal.k.AR = data.frame(deg1 = optimal.k.deg1.AR, deg2 = optimal.k.deg2.AR, deg3 = optimal.k.deg3.AR, deg4 = optimal.k.deg4.AR) row.names(df.optimal.k.AR) = "Optimal GCV knot number (autoregressive)" df.optimal.k.AR #Calculating the estimators with number of knots from the updated GCV for degrees 1 to 4 f.fit.autoregressive1 = autoregressive.spline(Y, X, k = optimal.k.deg1.AR, deg = 1) f.fit.autoregressive2 = autoregressive.spline(Y, X, k = optimal.k.deg2.AR, deg = 2) f.fit.autoregressive3 = autoregressive.spline(Y, X, k = optimal.k.deg3.AR, deg = 3) f.fit.autoregressive4 = autoregressive.spline(Y, X, k = optimal.k.deg4.AR, deg = 4) #We obtain datafraes to enable us plot df13 = data.frame(x = Time, y = f.fit.autoregressive1(Time)) df14 = data.frame(x = Time, y = f.fit.autoregressive2(Time)) df15 = data.frame(x = Time, y = f.fit.autoregressive3(Time)) df16 = data.frame(x = Time, y = f.fit.autoregressive4(Time)) spline4 = ggplot(data = data.frame(x = X, y = Y), aes(x = x, y = y)) + geom_point(alpha = 0.4) + geom_line(data = df13, aes(color = "1")) + geom_line(data = df14, aes(color = "2")) + geom_line(data = df15, aes(color = "3")) + geom_line(data = df16, aes(color = "4")) + scale_colour_manual(name = "Degree", values = c("maroon", "darkblue", "black", "yellow")) + xlab("Time(minutes)") + ylab("Order Parameter") + theme_classic(base_size = 12) + theme(legend.key = element_rect(fill = "white", colour = "gray")) + ggtitle("Regression Splines with Autoregressives Updates") spline4 #Fitting parametric model of polynomial degree 4 model1 = gls(Y ~ X + I(X**2) + I(X**3) + I(X**4), correlation = corAR1(0.55)) polynomial.fit1 = function(x){ as.numeric(model1$coefficients %*% x**(0:4)) } polynomial.fit1 = Vectorize(polynomial.fit1) spline5 = ggplot(data = data.frame(x = X, y = Y), aes(x = x, y = y)) + geom_point(alpha = 0.3) + geom_line(data = df13, aes(color = "Degree 1")) + geom_line(data = df14, aes(color = "Degree 2")) + geom_line(data = df15, aes(color = "Degree 3")) + geom_line(data = df16, aes(color = "Degree 4")) + stat_function(fun = polynomial.fit1, aes(color = "4")) + scale_colour_manual(name = "Parametric \nFit Degree 4", values = c("maroon", "darkblue", "black", "yellow", "green")) + xlab("Time(minutes)") + ylab("Order Parameter") + theme_classic(base_size = 12) + theme(legend.key = element_rect(fill = "white", colour = "gray19")) + ggtitle("Model of Order Parameter of Polynomial Degree 4") spline5 # For degrees 3 and 5 model2 = gls(Y ~ X + I(X**2) + I(X**3), correlation = corAR1(0.55)) model3 = gls(Y ~ X + I(X**2) + I(X**3) + I(X**4) + I(X**5), correlation = corAR1(0.55)) polynomial.fit2 = function(x){ as.numeric(model2$coefficients %*% x**(0:3)) } polynomial.fit3 = function(x){ as.numeric(model3$coefficients %*% x**(0:5)) } polynomial.fit2 = Vectorize(polynomial.fit2) polynomial.fit3 = Vectorize(polynomial.fit3) spline6 = ggplot(data = data.frame(x = X, y = Y), aes(x = x, y = y)) + geom_point(alpha = 0.3) + stat_function(fun = polynomial.fit1, aes(color = "4")) + stat_function(fun = polynomial.fit2, aes(color = "3")) + stat_function(fun = polynomial.fit3, aes(color = "5")) + scale_colour_manual(name = "Parametric \nFit Degree", values = c("maroon", "darkblue", "yellow")) + xlab("Time(minutes)") + ylab("Order Parameter") + theme_classic(base_size = 12) + theme(legend.key = element_rect(fill = "white", colour = "gray19")) + ggtitle("Model of Order Parameter of Polynomial Degrees 3, 4 & 5") spline6
0651c8848217fd82a04268f6b701b0a89b6b8dc8
a515e8676ecc1407e04cdb552ee4067b1790b66b
/arealOverlapr/R/herfindahl_new.R
8af77d3c6e47e47ae33a89f42cb6955b5aed60df
[]
no_license
jcuriel-unc/arealOverlapR
d989283b721c8aacb162ab6683ab682f8ffee281
2fe97898e84f53caaa7e11de4f6ef59db0278494
refs/heads/main
2023-07-30T05:18:29.835003
2021-09-14T04:43:38
2021-09-14T04:43:38
406,219,963
0
0
null
null
null
null
UTF-8
R
false
false
2,955
r
herfindahl_new.R
#' Calculate the herfindahl index of the first level of geography #' #' This function takes the raw output of the weight_overlap function (also part of the arealOverlapr pkg), and calculates the #' population overlap between two levels of geography, and the demographic information of interest from census data. #' @param overlap_dyad_output The outputted data frame from the overlap_dyad_creatr function #' @param shp_atom The atomic unit of geography shpfile that will be used to calculate the spatial weights by population #' @param id1 The ID field (chr) from the first shpfile of interest. #' @param id2 The ID field (chr) from the second shpfile of interest. #' @param census_fields The string vector of other population fields of interest referring to census data that should be caclulated, #' which amounts to the raw weighted number of the individuals part of the demographic in question residing within the overlap of the #' two shpfile polygons of interest #' @return The data frame with the dyadic population overlap between the first and second shapefiles. The following are the values: #' \itemize{ #' \item id1 = The renamed id field from the first shpfile #' \item herf_index = The Herfindahl index, a measure of the diversity of shp2 units within the shp1 file. The scale ranges from 0 #' for complete heterogeneity and division across shp2 polygons, and 1 for complete homogeneity and nestedness within a single #' shp2 polygon. #' \item eff_num = The effective number of shp2 polygonal units within the shp1 polygons. This is the inverse of the Herfindahl #' index. #' } #' @export #' @examples #' #' zctas <- arealOverlapr::zctas #' cbg_oh <- arealOverlapr::cbg_oh #' oh_sen <- arealOverlapr::oh_sen #' test_overlap <-weight_overlap(shp1 = zctas, shp_atom = cbg_oh, shp2 = oh_sen, pop_field = "POP2010") #' test_output <- overlap_dyad_creatr(test_overlap, id1="ZCTA5CE10",id2="id", census_fields = c("WHITE","BLACK","MALES")) #' test_herf <- herfindahl_new(test_output,"pop_wt", "id1") #' ) herfindahl_new <- function(overlap_dyad_output, pop_field, id1){ ##step 0: rename fields colnames(overlap_dyad_output)[names(overlap_dyad_output)==pop_field] <- "pop_wt" colnames(overlap_dyad_output)[names(overlap_dyad_output)==id1] <- "id1" ##step 1: get pop summarized by shp1 overlap_dyad_output <- overlap_dyad_output %>% group_by(id1) %>% mutate(pop_shp1=sum(pop_wt)) ##step 2: get proportions for dyad, squared overlap_dyad_output$dyad_prop_shp2 <- (overlap_dyad_output$pop_wt/overlap_dyad_output$pop_shp1)^2 ##step 3: summarise and get herfindahl index by zip code shp1_herfindahl <- aggregate(overlap_dyad_output$dyad_prop_shp2, list(id1=overlap_dyad_output$id1), FUN="sum") ##rename second col colnames(shp1_herfindahl)[2] <- "herf_index" ##step 4: Get the effective number shp1_herfindahl$eff_num <- 1/shp1_herfindahl$herf_index }
46136e5066b6986dfb21353c7ca24332e4102b89
7040c5658e743cc2061a1c5e31597f27c20234c8
/R/02a_tidy_senate.R
8b6cbac00a5d36364ca0aa9a9845807a071379e3
[]
no_license
davidluizrusso/midterms2018
40e520d2c3ec845327d2b3adec9255bef5275f52
a13e32ca964acd98f8c3faa01600e274df3cc4b1
refs/heads/master
2020-03-22T14:47:54.831409
2018-07-23T03:14:38
2018-07-23T03:14:38
140,206,178
0
0
null
null
null
null
UTF-8
R
false
false
999
r
02a_tidy_senate.R
# 01 -------------------- Load packages library(tidyverse) library(data.table) library(purrrlyr) library(voteogram) ### 02 -------------------- Set directories raw_data <- "input/raw" processed_data <- "input/processed" ### 03 -------------------- Read raw senate data raw_senate <- data.table::fread(paste(raw_data, "us_senate_raw.csv", sep = "/")) %>% dplyr::mutate(sort_name = sapply(strsplit(Incumbent, " "), '[', 1)) ### 04 -------------------- Get current party for each senator senate <- voteogram::roll_call("senate", 115, 2, 162)$votes %>% dplyr::select(member_name, sort_name, party, state_abbrev) ### 05 -------------------- Feature engineering processed_senate <- raw_senate %>% dplyr::left_join(dplyr::select(senate, sort_name, party), by = "sort_name") %>% dplyr::mutate(party = ifelse(grepl("Cochran", Incumbent), "R", party)) ### 06 -------------------- Write processed data to disk data.table::fwrite(processed_senate, paste(processed_data, "senate.csv", sep = '/'))
4ea27a13b293ed2b92498d31e9adc6b9f44f7980
4834724ced99f854279c2745790f3eba11110346
/man/screen_for_duplicate_individuals.Rd
41cf472d31facc35f35f9b462867309bf1376caf
[]
no_license
mdavy86/polymapR
1c6ac5016f65447ac40d9001388e1e9b4494cc55
6a308769f3ad97fc7cb54fb50e2b898c6921ddf9
refs/heads/master
2021-01-25T12:37:09.046608
2018-02-13T17:07:35
2018-02-13T17:07:35
123,487,219
0
1
null
null
null
null
UTF-8
R
false
true
1,428
rd
screen_for_duplicate_individuals.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/exported_functions.R \name{screen_for_duplicate_individuals} \alias{screen_for_duplicate_individuals} \title{Screen for duplicate individuals} \usage{ screen_for_duplicate_individuals(dosage_matrix, cutoff = NULL, plot_cor = T, log = NULL) } \arguments{ \item{dosage_matrix}{An integer matrix with markers in rows and individuals in columns.} \item{cutoff}{Correlation coefficient cut off. At this correlation coefficient, individuals are merged. If NULL user input will be asked after plotting.} \item{plot_cor}{Logical. Should correlation coefficients be plotted? Can be memory/CPU intensive with high number of individuals.} \item{log}{Character string specifying the log filename to which standard output should be written. If NULL log is send to stdout.} } \value{ A matrix similar to dosage_matrix, with merged duplicate individuals. } \description{ \code{screen_for_duplicate_individuals} identifies and merges duplicate individuals. } \examples{ data("segregating_data") dupscreened<-screen_for_duplicate_individuals(dosage_matrix=segregating_data, cutoff=0.9, plot_cor=TRUE) \dontrun{ #user input: data("segregating_data") screen_for_duplicate_individuals(dosage_matrix=segregating_data, plot_cor=TRUE) } }
57b4f70675bc1b02a214a82c474f8fb823ff70ae
d0b8c297d95bbea604542c2ef565ac5f71cd3cd6
/man/reg_dist.Rd
df4b969c65074e1a3d1fa385f4e3ad2ffae33dd5
[]
no_license
dicook/nullabor
80397dd412af96ffbb132359e1dacc30e7cae347
771670a486cbb750ba69f178eb22bc4d6604e3c6
refs/heads/master
2022-07-20T14:45:21.185860
2022-07-05T13:47:22
2022-07-05T13:47:22
8,078,886
55
12
null
2022-07-05T13:11:47
2013-02-07T18:35:43
R
UTF-8
R
false
true
1,268
rd
reg_dist.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/distances.r \name{reg_dist} \alias{reg_dist} \title{Distance based on the regression parameters} \usage{ reg_dist(X, PX, nbins = 1, intercept = TRUE, scale = TRUE) } \arguments{ \item{X}{a data.frame with two variables, the first column giving the explanatory variable and the second column giving the response variable} \item{PX}{another data.frame with two variables, the first column giving the explanatory variable and the second column giving the response variable} \item{nbins}{number of bins on the x-direction, by default nbins = 1} \item{intercept}{include the distances between intercepts?} \item{scale}{logical value: should the variables be scaled before computing regression coefficients?} } \value{ distance between X and PX } \description{ Dataset X is binned into 5 bins in x-direction. A regression line is fitted to the data in each bin and the regression coefficients are noted. Same is done for dataset PX. An euclidean distance is calculated between the two sets of regression parameters. If the relationship between X and PX looks linear, number of bins should be equal to 1. } \examples{ with(mtcars, reg_dist(data.frame(wt, mpg), data.frame(sample(wt), mpg))) }
7ff9d4ee575c763b42f2ccd02af213121e8252a5
d716c7fda467f195ac4ed3c27940186612673636
/Analytical CRM/Code/ACRM code.R
4f0c35e29dce5efd834f3a97357ac343f390cc77
[]
no_license
rohandongare-nci/Projects
2eda693514e950c30fe485cef42ea897fac58f33
eeb425ab130058d4f4ea124825347cc9071ccc66
refs/heads/master
2020-07-11T03:43:44.870276
2019-11-17T16:26:30
2019-11-17T16:26:30
204,437,606
0
0
null
null
null
null
UTF-8
R
false
false
8,232
r
ACRM code.R
#brief analysis of the underlying data library(scales) library(plyr) library(tidyverse) library(data.table) library(gridExtra) library(arules) library(ggplot2) customer_data<-read.csv("C:/Users/rohan/OneDrive/Desktop/1.ACRM-Proposal/train.csv") names(customer_data)<-c("u_id","p_id","gender","age","occupation","city_number","stay_in_current_city_years","marital_status"," product_category_1"," product_category_2","product_category_3","purchase") levels(customer_data$city_number) customer_data$city_number<-revalue(customer_data$city_number, c("A"="city_1", "B"="city_2", "C"="city_3")) #general descriptive statistics summary(customer_data) levels(customer_data$age) levels(customer_data$stay_in_current_city_years) #checking for missing values sapply(customer_data, function(x) sum(is.na(x))) customer_data[is.na(customer_data)]<-0 #checking unique values lapply(customer_data, function(x)length(unique(x))) #which gender shopped the most cust_gender = customer_data %>% select(gender,u_id) %>% group_by(u_id) %>% distinct() summary(user_gender) gender<-cust_gender$gender gender_plot = ggplot(data = cust_gender) + g eom_bar(mapping = aes(x = gender, y = ..count.., fill = gender)) +labs(title = 'Customer Gender') plot(gender_plot) #Finding Top Customers and their gender customer_purchases = customer_data %>%select(purchase,u_id,gender) %>% group_by(u_id) %>% arrange(u_id) %>% summarise(Purchase_value_total = sum(purchase)) head(customer_purchases) #arranging customers in descending order of purchases top_customers <- customer_purchases[order(-customer_purchases$Purchase_value_total),] head(top_customers) gender2 = customer_data %>% select(gender,u_id) %>% group_by(u_id) %>%arrange(u_id) %>% distinct() purchase_and_gender<- full_join(top_customers,gender2,by="u_id") #top 200 customers with gender top_customer_with_gender<-head(purchase_and_gender,200) summary(top_customer_with_gender) head(top_customer_with_gender) top_200_plot = ggplot(data = top_customer_with_gender) + geom_bar(mapping = aes(x = gender, y =..count.., fill = gender)) +labs(title = 'Top 200 customers') plot(top_200_plot) #AVerage spending of customers by gender avg_spending = purchase_and_gender %>% group_by(gender) %>% summarize(C = n(), purchases = sum(Purchase_value_total), Avg = purchases/C) print(avg_spending) avg_spend = ggplot(data = avg_spending) + geom_bar(mapping = aes(x = gender, y =Avg, fill = gender), stat = 'identity') +labs(title = 'Average Spending By Gender') plot(avg_spend) #Segregation of customers according to age/which age bracket spends the most cust_age = customer_data %>% select(age,u_id,purchase) %>% distinct() %>% count(age) age_purchases = customer_data %>%select(purchase,u_id,age) %>% group_by(age) %>% arrange(age) %>% summarise(PurchaseS_value_total = sum(purchase)) head(age_purchases) age_purchase<- ggplot(data = age_purchases) + geom_bar(mapping =aes(x = age, y =PurchaseS_value_total, fill = age), stat = 'identity') +labs(title = 'Average spending by age bracket') plot(age_purchase) a<-age_purchases$PurchaseS_value_total[3] b<-age_purchases$PurchaseS_value_total[4]/sum(age_purchases$PurchaseS_value_total) #/sum(age_purchases$PurchaseS_value_total) #which products were sold the most and who bought them most_sold_products = customer_data %>% count(p_id, sort = TRUE) TopProducts = head(most_sold_products, 10) TopProducts Top_selling_products = customer_data[customer_data$p_id == 'P00025442'| customer_data$p_id =='P00265242'| customer_data$p_id =='P00110742', ] head(Top_selling_products) #gender/age top_product_age<-Top_selling_products %>%select(purchase,u_id,gender,age) %>% group_by(u_id) %>% arrange(u_id) %>% summarise(Purchase_value_total2 = sum(purchase)) age2 = Top_selling_products %>% select(age,u_id) %>% group_by(u_id) %>%arrange(u_id) %>% distinct() top_age_product<-full_join(top_product_age,age2,by="u_id") head(top_age_product) top_products_by_age<- ggplot(data = top_age_product) + geom_bar(mapping = aes(x = age, y =Purchase_value_total2, fill = age), stat = 'identity') +labs(title = 'Age Distribution Of Customers Who Bought the Most Popular Products By Age') plot(top_products_by_age) #now gender top_product_gender<-Top_selling_products %>%select(purchase,u_id,gender,age) %>% group_by(u_id) %>% arrange(u_id) %>% summarise(Purchase_value_total3 = sum(purchase)) gender3 = Top_selling_products %>% select(gender,u_id) %>% group_by(u_id) %>%arrange(u_id) %>% distinct() top_gender<-full_join(top_product_gender,gender3,by="u_id") top_gender_product<-ggplot(data = top_gender) + geom_bar(mapping = aes(x = gender, y =Purchase_value_total3, fill = gender), stat = 'identity') +labs(title = 'Customers Who Bought the Most Popular Products By Gender') plot(top_gender_product) #which city do most customers come from ? cust_loc = customer_data %>% select(u_id, city_number,purchase)%>% distinct() head(cust_loc) loc_plot = ggplot(data = cust_loc) + geom_bar(color = "black", mapping = aes(x = city_number, y = ..count.., fill = city_number)) + labs(title = 'Which City Do Most Customers Come From?') plot(loc_plot) summary(cust_loc) #which city spends the most? library(dplyr) city_1<-filter(customer_data,city_number=="A") city1_sum<-sum(city_1$purchase) city_2<-filter(customer_data,city_number=="B") city2_sum<-sum(city_2$purchase) city_3<-filter(customer_data,city_number=="C") city3_sum<-sum(city_3$purchase) #creating a new dataframe City_Purchase<-c(city1_sum,city2_sum,city3_sum) City_Number<-c("City_1","City_2","City_3") city_purchase_final<-data.frame(City_Number,City_Purchase) city_purchase_final city_purchase_plot = ggplot(data = city_purchase_final) + geom_bar(color = "black", mapping = aes(x = City_Number, y = City_Purchase, fill = City_Number), stat = 'identity') + labs(title = 'Which City Spends The Most?') plot(city_purchase_plot) #marital status and occupation m_status = customer_data%>%select(u_id, marital_status) %>% group_by(u_id) %>% distinct() ms_plot<- ggplot(data = m_status)+geom_bar(color="black", mapping=aes(x=marital_status,y=..count..,fill=marital_status)) +labs(title = "Purchases By Marital Status") plot(ms_plot) m_status$marital_status<-as.character(marital_status$marital_status) occupation = customer_data %>% select(u_id, occupation) %>% group_by(u_id) %>% distinct() occupation_purchase<-full_join(occupation,customer_purchases,by="u_id") summary(occupation_purchase) occupation_purchase_summary<-occupation_purchase %>% group_by(occupation) %>% dplyr::summarise(Purchase_Amount = sum(Purchase_value_total)) occupation_plot<-ggplot(data = occupation_purchase_summary)+geom_bar(color="black",stat="identity", mapping = aes(x=occupation,y=Purchase_Amount,fill=occupation))+ scale_x_discrete(name="Occupation", breaks = seq(0,20, by = 1),labels=c("0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20")) plot(occupation_plot,las=2) chi2 = chisq.test(customer_data, correct=F) c(chi2$statistic, chi2$p.value) cor(rank(customer_data$purchase), rank(customer_data$age)) #Apriori library(arules) library(tidyverse) product_sparse<-customer_data %>% select(u_id,p_id)%>% group_by(u_id) %>% arrange(u_id) sparse_matrix_products = product_sparse %>% dplyr::mutate(id = row_number()) %>% spread(u_id, p_id) %>% t() head(sparse_matrix_products) sparse_matrix_products = sparse_matrix_products[-1,] write.csv(customers_products, file = 'C:/Users/rohan/OneDrive/Desktop/1.ACRM-Proposal/sparse_matrix_products.csv') customer_product_data = read.transactions('C:/Users/rohan/OneDrive/Desktop/1.ACRM-Proposal/customers_products.csv', sep = ',', rm.duplicates = TRUE) summary(customer_product_data) itemFrequencyPlot(customer_product_data,topN=15, type="absolute") rules_customer_product = apriori(data = customer_product_data, parameter = list(support = 0.00678, confidence = 0.88, maxtime = 0)) inspect(sort(rules_customer_product, by = 'lift')) library(arulesViz) plot(rules_customer_product, method = 'graph') rules_customer_product_2 = apriori(data = customer_product_data, parameter = list(support = 0.00678, confidence = 0.85, maxtime = 0)) inspect(sort(rules_customer_product_2, by = 'lift')) 40/5892
ee1460d81af14f6e295f0999bd3fe64c2c764c5b
e158e9992ab1d0510134ecc123aac7220c612df0
/tests/testthat/test_getBM.R
bc4db147976232b4e8778c7c5a168cf841cc46dc
[]
no_license
grimbough/biomaRt
a7e2a88276238e71898ea70fcf5ac82e1e043afe
8626e95387ef269ccc355dbf767599c9dc4d6600
refs/heads/master
2023-08-28T13:03:08.141211
2022-11-01T14:38:39
2022-11-01T14:38:39
101,400,172
26
8
null
2022-05-17T08:10:51
2017-08-25T12:08:50
R
UTF-8
R
false
false
2,482
r
test_getBM.R
cache <- file.path(tempdir(), "biomart_cache_test") Sys.setenv(BIOMART_CACHE = cache) ensembl <- Mart(biomart = "ensembl", dataset = "hsapiens_gene_ensembl", host = "www.ensembl.org", attributes = data.frame( name = c("chromosome_name", "ensembl_gene_id"), description = c("Chromosome/scaffold name", "Gene stable ID") ), filters = data.frame( name = c("affy_hg_u133a_2", "chromosome_name", "transcript_tsl"), description = c("AFFY HG U133A 2 probe ID(s) [e.g. 211600_at]", "Chromosome/scaffold name", "Transcript Support Level (TSL)"), type = c("id_list", "text", "boolean"), options = c("[]", "[1,2,3,4,CHR_HG1_PATCH]", "[only,excluded]") ) ) test_that("getBM() gives appropriate error messages", { expect_error(getBM(), "You must provide a valid Mart object") mart_with_no_dataset <- Mart(biomart = "ensembl") expect_error(getBM(mart = mart_with_no_dataset), "No dataset selected, please select a dataset first") expect_error(getBM(mart = ensembl), "Argument 'attributes' must be specified") expect_error(getBM(mart = ensembl, attributes = "ensembl_gene_id", filters = list("chromosome_name")), "Argument 'filters' must be a named list when sent as a list") }) test_that("getBMlist removal message is shown", { expect_error(getBMlist(), class = "defunctError") }) test_that("getBM returns sensible things", { skip_if_not_installed('mockery') mockery::stub(getBM, '.submitQueryXML', 'Gene stable ID\tChromosome/scaffold name\nENSG01\t13\nENSG02\t15\nENSG03\t17\n' ) expect_is(getBM(mart = ensembl, attributes = c("ensembl_gene_id", "chromosome_name")), "data.frame") expect_warning(getBM(mart = ensembl, attributes = c("ensembl_gene_id", "chromosome_name"), filters = list(chromosome_name = c(1)), values = "1"), "Argument 'values' should not be used when argument 'filters' is a list and will be ignored") })
ee6c2d224f18ca502d739d8a9e46e13ba128cad0
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/mixsep/examples/mixsep.Rd.R
7351571c0fca216228d829891313ba573b3e7488
[]
no_license
surayaaramli/typeRrh
d257ac8905c49123f4ccd4e377ee3dfc84d1636c
66e6996f31961bc8b9aafe1a6a6098327b66bf71
refs/heads/master
2023-05-05T04:05:31.617869
2019-04-25T22:10:06
2019-04-25T22:10:06
null
0
0
null
null
null
null
UTF-8
R
false
false
337
r
mixsep.Rd.R
library(mixsep) ### Name: mixsep ### Title: DNA mixture separation ### Aliases: mixsep ### ** Examples ## The file wang.csv in the installation directory may be used for exemplification. ## The 'wang.csv' is located in the folder quoted below: cat(paste(find.package("mixsep"),"data",sep=.Platform$file.sep)) ## Not run: mixsep()
6a97a30d67f95f909bd68745f2c4c61cabad20c8
04583a6fb37f2060e71836220bf8a012f2f53cc7
/businesscase.R
32fbbe26613f5902908910f2a23945e4576b03f5
[]
no_license
Kedarsf/R
b2cc345fc011f5bdc0d57a5fdfabafd04be41678
5d19e4148208ba31d8251d50a92183534f3484a4
refs/heads/master
2021-04-29T12:16:38.544422
2018-03-26T18:58:40
2018-03-26T18:58:40
121,726,286
0
0
null
null
null
null
UTF-8
R
false
false
7,960
r
businesscase.R
getwd() dataset<-read.csv("C:/Users/Admin/Documents/Python_Module_Day_16.2_Network_Intrusion_Train_data.csv") View(dataset) # data processing class(dataset$class) summary(dataset) colSums(is.na(dataset)) #removing irrelavent columns dataset$is_host_login<-NULL dataset$num_outbound_cmds<-NULL #Convert nominal variables to numeric codes such as flag, protocol type, service levels(dataset$service)<-1:70 levels(dataset$flag)<-1:11 levels(dataset$protocol_type)<-1:3 #levels(dataset$class)<-1:2 summary(dataset) # normalising the data normalise <- function(dataset, na.rm = TRUE){ ranx <- range(dataset, na.rm = T) (dataset - ranx[1]) / diff(ranx) } apply(dataset[,c(1,5,6,10,13,16,17,21,22,30,31)],2,normalise) #install.packages('rpart') library(rpart) model1<-glm(class~.,family = binomial(link = 'logit'),data = dataset) summary(model1) model2<-glm(class~duration+service+flag+src_bytes+dst_bytes+land+hot+num_failed_logins+logged_in+num_compromised+num_root+is_guest_login+count+srv_count+serror_rate+srv_serror_rate+rerror_rate+srv_rerror_rate+same_srv_rate+diff_srv_rate+srv_diff_host_rate+dst_host_count+dst_host_srv_count+dst_host_same_srv_rate+dst_host_diff_srv_rate+dst_host_same_src_port_rate+dst_host_srv_diff_host_rate+dst_host_serror_rate+dst_host_srv_rerror_rate+dst_host_srv_serror_rate+dst_host_rerror_rate,family = binomial(link = 'logit'),data = dataset) summary(model2) model3<-glm(class~duration+service+flag+src_bytes+dst_bytes+land+hot+num_failed_logins+logged_in+num_compromised+num_root+is_guest_login+count+srv_count+serror_rate+srv_serror_rate+rerror_rate+srv_rerror_rate+same_srv_rate+diff_srv_rate+srv_diff_host_rate+dst_host_count+dst_host_srv_count+dst_host_same_srv_rate+dst_host_same_src_port_rate+dst_host_srv_diff_host_rate+dst_host_srv_serror_rate+dst_host_rerror_rate,family = binomial(link = 'logit'),data = dataset) summary(model3) # we will choose model 3 #reading the validation data set dataset2<-read.csv("Python_Module_Day_16.4_Network_Intrusion_Validate_data.csv") summary(dataset2) View(dataset2) # data processing class(dataset2$class) summary(dataset2) colSums(is.na(dataset2)) #dataset2ind<-dataset2[,-40] #View(dataset2ind) #dataset2dep<-dataset2$class #View(dataset2dep) #removing irrelavent columns dataset2$num_outbound_cmds<-NULL dataset2$is_host_login<-NULL #Convert nominal variables to numeric codes such as flag, protocol type, service levels(dataset2$service)<-1:70 levels(dataset2$flag)<-1:11 levels(dataset2$protocol_type)<-1:3 #levels(dataset2$class)<-1:2 summary(dataset2) # normalising the data normalise <- function(dataset2, na.rm = TRUE){ ranx <- range(dataset2, na.rm = T) (dataset2 - ranx[1]) / diff(ranx) } apply(dataset2[,c(1,5,6,10,13,16,17,21,22,30,31)],2,normalise) #validating our model using validationset ypred <- predict(model3,newdata=dataset2,type='response') ypred <- ifelse(ypred>=0.5,1,0) summary(ypred) #confusion matrix cm<-table(ypred,dataset2$class) cm #accuracy function acc<-function(cm){ Totp<-cm[2,1]+cm[2,2] TP<-cm[2,2] c<-TP/Totp c } acc(cm) #testing the validated model on the test data dataset3<-read.csv("Python_Module_Day_16.3_Network_Intrusion_Test_data.csv") View(dataset3) colSums(is.na(dataset3)) #removing irrelavent columns dataset3$num_outbound_cmds<-NULL dataset3$is_host_login<-NULL #Convert nominal variables to numeric codes such as flag, protocol type, service levels(dataset3$service)<-1:70 levels(dataset3$flag)<-1:11 levels(dataset3$protocol_type)<-1:3 #levels(dataset3$class)<-1:2 summary(dataset3) # normalising the data normalise <- function(dataset3, na.rm = TRUE){ ranx <- range(dataset3, na.rm = T) (dataset3 - ranx[1]) / diff(ranx) } apply(dataset3[,c(1,5,6,10,13,16,17,21,22,30,31)],2,normalise) #validating our model using validationset class <- predict(model3,newdata=dataset3,type='response') class <- ifelse(class>=0.5,"normal","anomaly") summary(class) dataset3<-cbind(dataset3,class) View(dataset3) library(ROCR) #plotting auc curve pr<- prediction(ypred,dataset2$class) prf<-performance(pr,measure="tpr",x.measure="fpr") auc10<- performance(pr,measure="auc") auc10<-auc10@y.values[[1]] auc10 plot(prf) #decision tree for train data ClassifierD<-rpart(formula=class~., data=dataset) #decision tree for test dataset #decision tree plot(ClassifierD,uniform=TRUE,cex=0.8) text(ClassifierD, use.n=TRUE, all=TRUE) #Calculating accuracy using DT y_predD =predict(ClassifierD, newdata=dataset2, type = 'class') y_predD<- ifelse(y_predD=="normal",1,0) CFD= table(y_predD,dataset2$class) AccuracyD<-acc(CFD) AccuracyD library(ROCR) #plotting auc curve pr_DT<- prediction(y_predD,dataset2$class) prf<-performance(pr,measure="tpr",x.measure="fpr") auc<- performance(pr,measure="auc") auc2<-auc@y.values[[1]] auc2 plot(prf) # support vector machine library(e1071) classifier1<-svm(formula=class~.,data = dataset,type='C-classification',kernel='linear') classifier2<-svm(formula=class~.,data = dataset,type='C-classification',kernel='radial') classifier3<-svm(formula=class~.,data = dataset,type='C-classification',kernel='sigmoid') classifier4<-svm(formula=class~.,data = dataset,type='C-classification',kernel='polynomial') #Calculating accuracy using SVM y_pred1 = predict(classifier1, newdata =dataset2) y_pred1<- ifelse(y_pred1=="normal",1,0) y_pred2 = predict(classifier2, newdata = dataset2) y_pred2<- ifelse(y_pred2=="normal",1,0) y_pred3 = predict(classifier3, newdata = dataset2) y_pred3<- ifelse(y_pred3=="normal",1,0) y_pred4 = predict(classifier4, newdata = dataset2) y_pred4<- ifelse(y_pred4=="normal",1,0) # Making the Confusion Matrix #Confusion Matrix CFL<-table(y_pred1,dataset2$class) CFR<-table(y_pred2,dataset2$class) CFS<-table(y_pred3,dataset2$class) CFP<-table(y_pred4,dataset2$class) #Accuracy AccL<-Acc(CFL) AccL AccR<-Acc(CFR) AccR AccS<-Acc(CFS) AccS AccP<-Acc(CFP) AccP #building the auc curve #model1 pr_1<- prediction(y_pred1,dataset2$class) prf<-performance(pr_1,measure="tpr",x.measure="fpr") auc<- performance(pr_1,measure="auc") auc3<-auc@y.values[[1]] auc3 plot(prf) #model 2 pr_2<- prediction(y_pred2,dataset2$class) prf<-performance(pr_2,measure="tpr",x.measure="fpr") auc<- performance(pr_2,measure="auc") auc4<-auc@y.values[[1]] auc4 plot(prf) #model 3 pr_3<- prediction(y_pred3,dataset2$class) prf<-performance(pr_3,measure="tpr",x.measure="fpr") auc<- performance(pr_3,measure="auc") auc4<-auc@y.values[[1]] auc4 plot(prf) #model 4 pr_4<- prediction(y_pred4,dataset2$class) prf<-performance(pr_4,measure="tpr",x.measure="fpr") auc<- performance(pr_4,measure="auc") auc5<-auc@y.values[[1]] auc5 plot(prf) #naive bayes library(e1071) classifier5<-naiveBayes(class~.,data = dataset) #predicting the model y_pred5<-predict(classifier5,newdata = dataset2[-40]) y_pred5<- ifelse(y_pred5=="normal",1,0) #confusion matrix cm<-table(y_pred5,dataset2[,40]) cm #accuracy of model acc(cm) # getting auc for naive bayes pr_5<- prediction(y_pred5,dataset2$class) prf<-performance(pr_5,measure="tpr",x.measure="fpr") auc<- performance(pr_5,measure="auc") auc6<-auc@y.values[[1]] auc6 plot(prf) #knn model library(class) y_pred6<-knn(train = dataset[,-40],test = dataset2[,-40],cl=dataset$class,k=200,prob=TRUE) y_pred6<- ifelse(y_pred6=="normal",1,0) #confusion matrix cm<-table(y_pred6,dataset2[,40]) cm #accuracy of model acc(cm) #getting auc for knn pr_6<- prediction(y_pred6,dataset2$class) prf<-performance(pr_6,measure="tpr",x.measure="fpr") auc<- performance(pr_6,measure="auc") auc7<-auc@y.values[[1]] auc7 plot(prf) getwd()
617bb16001b82ac55dd09d8dec07f74166246509
9e6884df4d8f0e26355026761393e3bb47c4b7e8
/mcri/LIHC.R
406a3e4605c87127febfc4120199768e28ac6199
[]
no_license
Shicheng-Guo/GscRbasement
f965ecc6e191175f371aa1edeae81e5c545f1759
8d599bed0dd8b61b455f97965c0f4bed5aae2e96
refs/heads/master
2022-05-01T09:20:23.072449
2022-03-13T18:46:04
2022-03-13T18:46:04
62,922,944
1
1
null
null
null
null
UTF-8
R
false
false
6,126
r
LIHC.R
################################################################################################################# ################################################################################################################# ################################################################################################################# id2phen4<-function(filename){ library("stringr") as.array(str_extract(filename,"TCGA-[0-9|a-z|A-Z]*-[0-9|a-z|A-Z]*-[0-9]*")) } id2phen3<-function(filename){ library("stringr") as.array(str_extract(filename,"TCGA-[0-9|a-z|A-Z]*-[0-9|a-z|A-Z]*")) } id2bin<-function(filename){ library("stringr") filename<-as.array(str_extract(filename,"TCGA-[0-9|a-z|A-Z]*-[0-9|a-z|A-Z]*-[0-9]*")) as.numeric(lapply(strsplit(filename,"-"),function(x) x[4])) } RawNARemove<-function(data,missratio=0.3){ threshold<-(missratio)*ncol(data) NaRaw<-which(apply(data,1,function(x) sum(is.na(x))>=threshold)) zero<-which(apply(data,1,function(x) all(x==0))==T) NaRAW<-c(NaRaw,zero) if(length(NaRAW)>0){ output<-data[-NaRAW,] }else{ output<-data; } output } RawZeroRemove<-function(data,missratio=0.5){ threshold<-(missratio)*ncol(data) NaRaw<-which(apply(data,1,function(x) sum(is.na(x))>=threshold)) zero<-which(apply(data,1,function(x) sum(x==0)>=threshold)) NaRAW<-c(NaRaw,zero) if(length(NaRAW)>0){ output<-data[-NaRAW,] }else{ output<-data; } output } ################################################################################################################# ################################################################################################################# ################################################################################################################# setwd("~/hpc/methylation/Pancancer/RNA-seq") TCGAProjects=c("BLCA","BRCA","CESC","CHOL","COAD","ESCA","GBM","HNSC","KICH","KIRC","KIRP","LIHC","LUAD","LUSC","PAAD","PCPG","PRAD","READ","SARC","STAD","THCA","THYM","UCEC") TCGAProjects=c("HNSC","KICH","KIRC","KIRP","LIHC","LUAD","LUSC","PAAD","PCPG","PRAD","READ","SARC","STAD","THCA","THYM","UCEC") for(TCGAProject in TCGAProjects){ library("metafor") library("survival") library("survminer") print(TCGAProject) load("rnaseqdata.pancancer.RData") phen1=read.table("/home/guosa/hpc/methylation/TCGA-clinical-11093.tsv",header = T,sep="\t") phen2=read.table("/home/guosa/hpc/methylation/Pancancer/RNA-seq/File_metadata2.txt",header = T,sep="\t") phen<-data.frame(phen2,phen1[match(phen2$cases.0.case_id,phen1$case_id),]) phen$file_name=gsub(".gz","",phen$file_name) colnames(rnaseqdata)<-unlist(lapply(strsplit(colnames(rnaseqdata),"/"),function(x) x[2])) phen<-phen[match(colnames(rnaseqdata),phen$file_name),] phen1<-id2phen4(phen$cases.0.samples.0.submitter_id) phen2<-id2phen3(phen$cases.0.samples.0.submitter_id) phen3<-id2bin(phen$cases.0.samples.0.submitter_id) phen$bin=phen3 include<-which(c(phen$bin==1 | phen$bin==11)) phen<-phen[include,] input<-rnaseqdata[,include] phen$id=id2phen4(phen$cases.0.samples.0.submitter_id) dim(phen) dim(input) input[1:5,1:5] phen[1:5,1:5] colnames(input)<-phen$id Seq<-paste(phen$project_id,phen$bin,sep="-") data<-input i=500 Seq<-paste(phen$project_id,phen$bin,sep="-") mean<-tapply(as.numeric(data[i,]),Seq,function(x) mean(x,na.rm=T)) sd<-tapply(as.numeric(data[i,]),Seq,function(x) sd(x,na.rm=T)) num<-tapply(as.numeric(data[i,]),Seq,function(x) length(x)) exclude<-names(which(table(unlist(lapply(strsplit(names(mean),"-"),function(x) x[2])))<2)) exclude <-grep(paste(exclude,collapse="|"),phen$project_id) phen<-phen[-exclude,] input<-input[,-exclude] phen$id=id2phen4(phen$cases.0.samples.0.submitter_id) colnames(input)<-phen$id input<-log(input+1,2) input<-RawNARemove(input) input<-RawZeroRemove(input) Seq<-paste(phen$project_id,phen$bin,sep="-") SEL<-grep(TCGAProject,Seq) input<-input[,SEL] Seq<-Seq[SEL] yphen<-abs(as.numeric(as.factor(Seq))-2) rlt<-c() for(i in 1:nrow(input)){ fit<-summary(glm(yphen~input[i,]))$coefficients[2,] rlt<-rbind(rlt,fit) } rownames(rlt)<-rownames(input) rlt2<-read.table(file="TCGA-Pancancer-RNAseq-FPKM-UQ.Meta.diff.txt",sep="\t",head=T,row.names=1) ENST2Symbol<-read.table("https://raw.githubusercontent.com/Shicheng-Guo/AnnotationDatabase/master/ENSG.ENST.ENSP.Symbol.hg19.bed") ENSG<-unlist(lapply(strsplit(as.character(rownames(rlt)),split="[.]"),function(x) x[1])) Symbol<-ENST2Symbol[match(ENSG,ENST2Symbol$V7),5] OS<-read.table("https://raw.githubusercontent.com/Shicheng-Guo/HowtoBook/master/TCGA/OverallSurvivalTime.txt",head=T,sep="\t") input<-input[,which(id2bin(colnames(input))==1)] newdata<-input[,na.omit(match(OS$submitter_id,id2phen3(colnames(input))))] colnames(newdata)<-id2phen3(colnames(newdata)) phen<-OS[match(colnames(newdata),OS$submitter_id),] head(phen) phen$censored<-as.numeric(! phen$censored) phen$week=phen$time/7 head(phen) ENST2Symbol<-read.table("https://raw.githubusercontent.com/Shicheng-Guo/AnnotationDatabase/master/ENSG.ENST.ENSP.Symbol.hg19.bed") ENSG<-unlist(lapply(strsplit(as.character(rownames(newdata)),split="[.]"),function(x) x[1])) Symbol<-ENST2Symbol[match(ENSG,ENST2Symbol$V7),5] HR<-c() for(i in 1:nrow(newdata)){ dat<-data.frame(Rna=newdata[i,],phen) dat$Rna[dat$Rna<=median(dat$Rna)]<-0 dat$Rna[dat$Rna>median(dat$Rna)]<-1 hr<-summary(coxph(Surv(week,censored)~Rna,dat))$coefficients[1,] HR<-rbind(HR,hr) print(i) } rownames(HR)=rownames(newdata) NewRltHR<-cbind(rlt,rlt2,Symbol,HR) New<-subset(NewRltHR,NewRltHR[,4]<10^-10 & NewRltHR[,7]<10^-10 & NewRltHR[,17]<10^-2 & NewRltHR[,1]*NewRltHR[,6]>0 & NewRltHR[,1]*NewRltHR[,13]>0) filename1=paste("~/hpc/methylation/TCGA_",TCGAProject,"_FPKM-UQ.DGE_OS_HR_PanDiff.Sig.txt",sep="") filename2=paste("~/hpc/methylation/TCGA_",TCGAProject,"_FPKM-UQ.DGE_OS_HR_PanDiff.All.txt",sep="") write.table(New,file=filename1,sep="\t",quote=F,col.names=NA,row.names=T) write.table(NewRltHR,file=filename2,sep="\t",quote=F,col.names=NA,row.names=T) }
00eb7b63fa4e7a0c42c50c3998b4821446644587
f12a2eabf3ff3dfadf73bbc7b01cb739719d858e
/plot/hist.R
e0070c33f2135f358aae0961dda4aec152b8068f
[]
no_license
matthewangbin/R
6048a0aeb2517fcdcb8ed27c9515cb6d4a4fe12c
b94518711bdb42d49edf43d8477dafda7715943e
refs/heads/master
2021-07-21T14:20:18.585703
2017-10-18T12:06:11
2017-10-18T12:06:11
null
0
0
null
null
null
null
UTF-8
R
false
false
502
r
hist.R
par(mfrow=c(2,2)) hist(mtcars$mpg) hist(mtcars$mpg, breaks=12, col="red", xlab="MPG", main="hist") hist(mtcars$mpg,freq=FALSE,breaks=12,col="red",xlab="MPG",main="hist rug") rug(jitter(mtcars$mpg)) lines(density(mtcars$mpg),col="blue",lwd=2) x<-mtcars$mpg h<-hist(x,breaks = 12,col="red",xlab="MPG",main="Hist with curve") xfit<-seq(min(x),max(x),length=40) yfit<-dnorm(xfit,mean=mean(x),sd=sd(x)) yfit<-yfit*diff(h$mids[1:2])*length(x) lines(xfit,yfit,col="blue",lwd=2) box()
04ad0da51a6535a2a6ac93090405e65e88470752
f4f85dc89eee48b21ade859d848ac1d7360a2482
/Lab6/main.R
430425ffc1cf03215c11fe0863ced0bd386a5d88
[]
no_license
stefan-matcovici/Special-Chapters-Of-Artificial-Intelligence
e4998f31b140c0057b21f254e6abbfbb7c982658
35878dcc41237dea8f8eab0bced5ba5fbc12c81e
refs/heads/master
2020-04-02T04:04:19.424664
2019-01-21T22:33:51
2019-01-21T22:33:51
153,998,432
1
0
null
null
null
null
UTF-8
R
false
false
1,564
r
main.R
notes = read.table("swiss.tsv",header=TRUE) normFunc = function(x){(x-mean(x, na.rm = T))/sd(x, na.rm = T)} get_variance_covariance_matrix = function(data, func_to_apply) { dims = length(data) no_instances = nrow(data) m = matrix(nrow = dims, ncol = dims, dimnames = list(names(data), names(data))) normalised_data = apply(data, 2, func_to_apply) for (row_no in c(1:dims)) { row1 = normalised_data[ ,row_no] for (col_no in c(row_no:dims)) { row2 = normalised_data[ ,col_no] covariance = (t(row1) %*% row2) / (no_instances - 1) m[row_no, col_no] = covariance m[col_no, row_no] = covariance } } m } variance_covariance_matrix = get_variance_covariance_matrix(notes, normFunc) initial_variance = sum(diag(variance_covariance_matrix)) # cov(notes) eigen_computation = eigen(variance_covariance_matrix) q = eigen_computation$vectors spectral_decomposition = t(q) %*% variance_covariance_matrix %*% q pca = as.matrix(notes) %*% q variations = diag(spectral_decomposition) all_variation = sum(variations) print(initial_variance - all_variation) print(cumsum(variations/all_variation)) plot(c(1:6), cumsum(variations/all_variation), type="l", xlab="principal components no", ylab="cumulative variation", lwd=3) title("scree plot") q = prcomp(notes) library(devtools) install_github("vqv/ggbiplot") library(ggbiplot) ggbiplot(q, obs.scale = 1, var.scale = 1 , ellipse = TRUE, circle = TRUE) + scale_color_discrete(name = '') + theme(legend.direction = 'horizontal', legend.position = 'top') q
89a6139f4e26aa84c0113cd5fb03f0cd5863f128
ae69f22a8bdcc712dbac8057504b7044bb57ace9
/man/tag-import.Rd
4c0ca7c13cb26a90d742c65b1b99a4cca53ba664
[]
no_license
kashenfelter/roxygen3
4fa4c61031bc3f0826ffb025eacf4751e79c6325
5ebffd6f41913e4737e71fb42dc5295170c8eadc
refs/heads/master
2020-03-13T22:43:13.212468
2013-11-30T13:38:15
2013-11-30T13:38:15
null
0
0
null
null
null
null
UTF-8
R
false
false
1,083
rd
tag-import.Rd
% Built by roxygen3 0.1 \docType{class} \name{ImportClassesFromTag-class} \alias{ImportClassesFromTag-class} \alias{ImportFromTag-class} \alias{ImportMethodsFromTag-class} \alias{ImportTag-class} \title{Namespace: tags for importing functions.} \description{ By and large, \code{@autoImports} should be the only imports tag that you need to use. It automatically generates the necessary \code{importFrom} statements to import all external functions used by this function. See \code{\link{auto_imports}} for more implementation details. } \details{ If there is a conflict, use \code{tag_importFrom} to resolve it. You can do \code{@importFrom base function} - this is not normally allowed in the \file{NAMESPACE}, but roxygen3 will simply ignore it, but still use it when resolving conflicts. You must have the packages declared in \code{DESCRIPTION} Imports. } \keyword{classes} \section{Tag Usage}{ \preformatted{ #' @importClassesFrom package fun1 fun2 #' @importFrom package function1 function2 #' @importMethodsFrom package fun1 fun2 #' @import package1 package2 package3 } }
2ffba0a8cec2b09c1d8db8f605aa62be95c1c8d1
7b842e47b36c5eccaee6b71c77e22519b49c0168
/tests/testthat/test-parseCategorical.R
7c0b83810bea4087422340d66693c4739ccada0c
[]
no_license
cran/geoknife
5dc92ca0aa7e7afe2afac3fd848e3b7fc99c07c4
e6dba004a958f5954317cfcd7faaec1d8d094ae9
refs/heads/master
2023-07-20T09:34:10.506446
2023-07-06T07:00:12
2023-07-06T07:00:12
48,080,629
0
0
null
null
null
null
UTF-8
R
false
false
1,176
r
test-parseCategorical.R
context("parse categorical") test_that("internal parsing works", { local.file <- system.file('extdata','csv_categorical_multifeature.csv', package = 'geoknife') output <- parseCategorical(local.file, delim = ',') expect_equal(output[['Driftless Area']][output$category=='Sample Count' & output$variable == 'housing_classes_iclus_a1_2010'], 4735427) expect_equal(output[['Wyoming Basin']][output$category=='3' & output$variable == 'housing_classes_iclus_a1_2100'], 0.0006708306) expect_is(output, 'data.frame') }) test_that('result works for categorical', { testthat::skip_on_cran() cancel() knife <- webprocess(algorithm = list('Categorical Coverage Fraction'="gov.usgs.cida.gdp.wps.algorithm.FeatureCategoricalGridCoverageAlgorithm"), wait=TRUE) library(sp) Sr1 = Polygon(cbind(c(-89,-89.2,-89.3,-89.2,-89),c(42,42.1,42,41.9,42))) Srs1 = Polygons(list(Sr1), "sample.poly") expect_warning( stencil <- simplegeom(Srl = list(Srs1), proj4string = CRS("+proj=longlat +datum=WGS84"))) job <- geoknife(stencil, 'iclus', knife) # SLOW!!! expect_is(result(job), 'data.frame') cancel(job) })
005efff80279ba81d7b38a731cd9292abf4bd190
fcc13976b8952fedec00b0c5d4520edc6d5103b9
/R/matchApp.R
d3d6422f63ef96ba6b978a1c87ab90404fff0a76
[]
no_license
anngvu/DIVE
851173b4515ab4fd8c26e171158aa17f079785db
e80d254fc4be2c4a3c12f4a1b4507beff3fe3663
refs/heads/master
2023-07-26T00:30:07.924714
2021-09-08T15:04:34
2021-09-08T15:04:34
173,828,093
0
0
null
null
null
null
UTF-8
R
false
false
7,426
r
matchApp.R
#' Shiny app UI for matching application #' #' Shiny app UI for matching application #' #' The application UI puts together multiple module components to enable #' exploration and matching of two different but same-type datasets. #' It places a \code{customDatasetInput} component for a user-uploaded input dataset in the top left #' and a \code{dataSubsetInput} component to allow selection of the match pool in the top right. #' The bottom half is a tab panel with tabs dynamically shown for a matching interface, #' result table and result plots. #' #' @param id Character ID for specifying namespace, see \code{shiny::\link[shiny]{NS}}. #' @param CSS Optional, location to an alternate CSS stylesheet to set look and feel of the module. #' @param refname Optional, name of the reference dataset. #' @param addonUI Optional, ui module function to display addon components. #' @param addontab If addonUI is given, should also give a name for the tab hosting addon ui components. #' @import shiny #' @export matchAppUI <- function(id, CSS = system.file("www/", "app.css", package = "DIVE"), refname = NULL, addonUI = NULL, addontab = "") { ns <- NS(id) fluidPage(theme = shinythemes::shinytheme("paper"), if(!is.null(CSS)) includeCSS(CSS), fluidRow(class = "matchAppUI-panel", column(1), column(11, div(class = "card-panel input-panel", div(class = "panel-header", "External set"), customDatasetInput(ns("CohortX"))), div(class = "card-panel input-panel", div(class = "panel-header", "Reference set"), dataSubsetInput(ns("ref"), label = refname))) ), fluidRow(style = "margin-top: 50px; margin-bottom: 100px;", column(1), column(10, if(is.null(addonUI)) { tabsetPanel(id = ns("tabs")) } else { tabsetPanel(id = ns("tabs"), tabPanel(addontab, addonUI(ns("addon")))) } ) ) ) } #' Shiny app server for matching and exploration of two datasets #' #' Shiny app server for matching and exploration of two datasets #' #' This server function puts together modular components to #' implement the whole interaction of the matching application with several defaults #' to facilitate quick startup. #' Though originally conceived for matching and exploration of patient cohort datasets, #' this could be adapted to matchable data in other domains, such as geographic sampling sites, etc. #' This app module can also be viewed as a starting template to help #' compose a new matching app with a sufficiently different layout or functionality. #' #' @param id Character ID for specifying namespace, see \code{shiny::\link[shiny]{NS}}. #' @param refname Name of the reference dataset, used for labels. Defaults to "Reference Cohort". #' @param refdata Reference dataset that can be matched against in whole or in part, i.e. the match pool. #' @param customdata A name for the appended colum to user-uploaded input data. #' This depends on the type of data expected. "Cohort" is the provided default for cohort-matching application. #' See \code{\link{customDatasetServer}}. #' @param defaultvalue Default attribute value to append to user-uploaded input data. #' "CohortX" is the provided default for cohort-matching application. See \code{\link{customDatasetServer}}. #' @inheritParams dataSubsetServer #' @inheritParams dataUploadServer #' @inheritParams matchLinkServer #' @inheritParams matchResultServer #' @inheritParams matchPlotServer #' @import shiny #' @export matchAppServer <- function(id, refname = "Reference Cohort", refdata, subsetv, subsets, customdata = "Cohort", defaultvalue = "CohortX", vars, guess = NULL, informd = system.file("info/cohort_exchange.Rmd", package = "DIVE"), appdata = NULL) { moduleServer(id, function(input, output, session) { reference <- dataSubsetServer(id = "ref", dataset = refdata, subsetv = subsetv, subsets = subsets) newcohort <- customDatasetServer(id = "CohortX", customdata = customdata, defaultvalue = defaultvalue, checkFun = checkCohortData, informd = informd, appdata = appdata) # Cross-checking for internal matching where newcohort includes ids in reference refcohort <- reactive({ excludePresent(data1 = newcohort(), data2 = reference()) }) parameters <- matchLinkServer(id = "params", refdata = refcohort, inputdata = newcohort, vars = vars, guess = guess) results <- matchResultServer(id = "results", refdata = refcohort, inputdata = newcohort, params = parameters, sourcecol = customdata) explore <- matchPlotServer(id = "explore", s1data = refcohort, s2data = newcohort, results = results, ignorev = customdata) #-- Output tabs display logic ------------------------------------------------------------------------------------------# # Need to keep track of first upload since previous implementation of removing and adding new tabs # results in puzzling behavior where one must click twice on run to get results. # (vs. currently adding tab if it's the first interaction and showing/hiding for all subsequent) userfirst <- reactiveValues(upload = TRUE, result = TRUE) observeEvent(newcohort(), { if(userfirst$upload) { appendTab("tabs", select = T, tabPanel("Match parameters", matchLinkUI(session$ns("params")))) userfirst$upload <- FALSE } else { showTab("tabs", "Match parameters", select = T) hideTab("tabs", "Match results") removeTab("tabs", "Explore") } appendTab("tabs", tabPanel("Explore", matchPlotUI(session$ns("explore"), s1label = refname, s2label = defaultvalue))) }) observeEvent(results$matchtable, { if(userfirst$result) { insertTab("tabs", select = T, target = "Match parameters", position = "after", tabPanel("Match results", matchResultOutput(session$ns("results")))) userfirst$result <- FALSE } else { showTab("tabs", "Match results", select = T) } }) }) } #' Launch Shiny app for matching between two datasets #' #' Wrapper to launch app at console #' #' @param ns Optional namespace for app, passed into server module. #' @param ... Parameters passed into server module. #' @export matchApp <- function(ns = NULL, ...) { ui <- matchAppUI(ns) server <- matchAppServer(ns, ...) shinyApp(ui = ui, server = server) }
68f22f3136050dd830b85227ebfcf28fb8c83854
721982360f9c53e73a393b76803d8cf859e511d3
/cachematrix.R
214d8671793970c5d9a387ea163c747b44e4a808
[]
no_license
imhere81/ProgrammingAssignment2
23c1d23ad28540ac78e9f77e8ab62128e79dcc19
4919755c668e251f10a966ad1b5be45af9aee7a3
refs/heads/master
2020-04-13T07:35:52.775849
2018-12-25T08:03:09
2018-12-25T08:03:09
163,056,231
0
0
null
2018-12-25T07:06:43
2018-12-25T07:06:43
null
UTF-8
R
false
false
1,007
r
cachematrix.R
## Put comments here that give an overall description of what your ## This function creates a special "matrix" object that can cache its inverse. ## Write a short comment describing this function makeCacheMatrix <- function(x = matrix()) { inverseMatrix <- NULL set <- function (y){ x<<-y inverseMatrix<<-NULL } get <- function () x setInverse <- function (inv_) x<<- inv_ getInverse <- function ( ) inverseMatrix list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) } ## his function computes the inverse of the special "matrix" returned by makeCacheMatrix above cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' inverseMatrix <- x$getInverse() if(!is.null(inverseMatrix)){ message("Getting the Cached Information!!") return(inverseMatrix) } result <- x$get() inverseMatrix <- solve(result) x$setInverse(inverseMatrix) inverseMatrix }
a619f5f2f9113ce48d085b2aef71c92e7d4ad02c
0d746f48f8aef6c9f80f968b60c8d8134ef4b5af
/produceFinalPlot_local.R
1ffa28761456b0feb7b04d83b4b5d6b7605bb3a8
[]
no_license
wan9c9/carx-zeger
6f4a46cbfdb49655947227e51edf0f56281c04dd
778984945ea57e1a7c7410c542f203f15ec87cd2
refs/heads/master
2021-01-10T01:35:07.394658
2015-10-09T16:16:09
2015-10-09T16:16:09
43,728,509
0
0
null
null
null
null
UTF-8
R
false
false
1,955
r
produceFinalPlot_local.R
source("simulation_setting.R") generateCL <- F if(generateCL){ library(carx) nObs <- 100000 simData <- carxSim(nObs=nObs,prmtrAR=prmtrAR,prmtrX=prmtrX,sigmaEps=sigma,lcl=lcl,ucl=ucl,seed=0) cr <- c(0.01,0.05,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8) ucl <- quantile(simData$y,1-cr/2) lcl <- quantile(simData$y,cr/2) abscl <- round((ucl+abs(lcl))/2,2) save(abscl,file="abscl.RData") save(abscl,file="abscl.txt") } source("./simulation_setting.R") n <- 100 crs <- c(1,5,10,20,30,40,50) rslt <- matrix(nrow=length(crs),ncol=1+4) timeStats <- matrix(nrow=length(crs),ncol=1+4) i<- 1 for( i in 1:length(crs)) { ind_result_dir <- sprintf("./sim_result/n_%04d_cr_%02d/",nObs,as.integer(crs[i])) load(paste0(ind_result_dir,"mseRatio.RData")) rslt[i,-1] <- mseRatio rslt[i,1] <- crs[i]/100 if(i == 1) colnames(rslt) <- c("cr",names(mseRatio)) load(paste0(ind_result_dir,"timeStat.RData")) timeStats[i,] <- c(crs[i]/100,c(timeStat)) if(i == 1) colnames(timeStats) <- c("cr","m_wc","m_zb","sd_wc","sd_zb") i <- i + 1 } setEPS() postscript(paste0("msePlot_n",nObs,".eps")) ylim <- range(rslt[,-1]) plot(rslt[,"cr"],rslt[,"X1"],ylim=ylim,xlab="Censoring rate", ylab="MSE ratio (WC/ZB)",type="l",lty=1) grid() lines(rslt[,"cr"],rslt[,"X2"],lty=2) lines(rslt[,"cr"],rslt[,"AR1"],lty=3) lines(rslt[,"cr"],rslt[,"sigma"],lty=4) legend("topleft", c(expression(beta[1]), expression(beta[2]), expression(psi[1]), expression(sigma) ) , lty=c(1,2,3,4)) dev.off() setEPS() postscript(paste0("timeStats_n",nObs,".eps")) ylim <- range(timeStats[,-1]) plot(timeStats[,"cr"],timeStats[,"m_zb"],log="y",type="l",ylim=ylim,lty=1, xlab="Censoring rate", ylab="Mean time per estimation") grid() lines(timeStats[,"cr"],timeStats[,"m_wc"],lty=2) #lines(rslt[,"cr"],rslt[,"AR1"],ylim=c(0,1),lty=3) #lines(rslt[,"cr"],rslt[,"sigma"],ylim=c(0,1),lty=4) legend("topleft", c("ZB","WC"), lty=c(1,2) ) dev.off()
bfbaf7211db8d6fc1a410b0afea0b53d3ad619d5
bc7cb0d6281727d4283b8635143cec8e1c864287
/man/print.GGM_bootstrap.Rd
3b757125fd33e59c4b1b936727837f02672de155
[]
no_license
josue-rodriguez/GGMnonreg
e8cfb3e1db1c96c226e91705642227cf4a3ee7eb
33ecd010df57525411261a08005a4d2f946327d3
refs/heads/master
2021-01-02T00:30:37.231210
2020-01-27T20:45:52
2020-01-27T20:45:52
null
0
0
null
null
null
null
UTF-8
R
false
true
473
rd
print.GGM_bootstrap.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/GGMboot.R \name{print.GGM_bootstrap} \alias{print.GGM_bootstrap} \title{Print method for a \code{GGM_bootstrap} object} \usage{ \method{print}{GGM_bootstrap}(x, ...) } \arguments{ \item{x}{An object of class \code{GGM_bootstrap}} \item{...}{currently ignored} } \description{ Print method for a \code{GGM_bootstrap} object } \examples{ X <- GGMnonreg::ptsd[, 1:5] fit <- GGM_bootstrap(X) fit }
ab7f47a2bca5f9180c26124ff6c9fd0bd6aa87fc
27751c39e222146224a3c4d2c11cd698aea256f8
/script/modelling.R
bfb142a60c44a3b90d55a826252d244744665d98
[]
no_license
lucastancm96/uom2020_dissertation
bf5b1faf2d04e64fda50a6f5f2be6e7169086516
3b60b1e61c5c8a61576bd2f1306102585c5c9e09
refs/heads/master
2022-12-15T16:11:17.115863
2020-09-16T07:51:12
2020-09-16T07:51:12
295,961,606
0
0
null
null
null
null
UTF-8
R
false
false
2,639
r
modelling.R
library(olsrr) library(MASS) library(nnet) modtrain_ch <- read.csv("csv_data/Wellcome/modtrain_ch.csv") modtest_ch <- read.csv("csv_data/Wellcome/modtest_ch.csv") modtrain_ch$AGE for (i in colnames(modtrain_ch)){ modtrain_ch$i <- factor(modtrain_ch$i, levels=sort(unique(modtrain_ch$i))) } class(modtrain_ch$AGE) lr <- multinom(VAC_LVL ~ AGE_CAT + GEN + EDU + LIV_AR + RGN + SUBJ_HHI + CTRY_INC + EMP_STAT, data=modtrain_ch) summary(lr) z <- summary(lr)$coefficients/summary(lr)$standard.errors p <- (1 - pnorm(abs(z), 0, 1)) * 2 p lr <- mlogit() #********** Testing ********** # Train modtrain_ch$VAC_LVL <- factor(modtrain_ch$VAC_LVL, levels=sort(unique(modtrain_ch$VAC_LVL))) modtrain_ch$AGE_CAT <- factor(modtrain_ch$AGE_CAT, levels=sort(unique(modtrain_ch$AGE_CAT))) modtrain_ch$GEN <- factor(modtrain_ch$GEN, levels=sort(unique(modtrain_ch$GEN))) modtrain_ch$EDU <- factor(modtrain_ch$EDU, levels=sort(unique(modtrain_ch$EDU))) modtrain_ch$LIV_AR <- factor(modtrain_ch$LIV_AR, levels=sort(unique(modtrain_ch$LIV_AR))) modtrain_ch$RGN <- factor(modtrain_ch$RGN, levels=sort(unique(modtrain_ch$RGN))) var <- c('VAC_LVL', 'AGE_CAT', 'GEN', 'EDU') partial_modtrain_ch <- modtrain_ch[var] # Test modtest_ch$VAC_LVL <- factor(modtest_ch$VAC_LVL, levels=sort(unique(modtest_ch$VAC_LVL))) modtest_ch$AGE_CAT <- factor(modtest_ch$AGE_CAT, levels=sort(unique(modtest_ch$AGE_CAT))) modtest_ch$GEN <- factor(modtest_ch$GEN, levels=sort(unique(modtest_ch$GEN))) modtest_ch$EDU <- factor(modtest_ch$EDU, levels=sort(unique(modtest_ch$EDU))) modtest_ch$LIV_AR <- factor(modtest_ch$LIV_AR, levels=sort(unique(modtest_ch$LIV_AR))) modtest_ch$RGN <- factor(modtest_ch$RGN, levels=sort(unique(modtest_ch$RGN))) partial_modtest_ch <- modtest_ch[var] lr <- multinom(VAC_LVL ~ ., data=partial_modtrain_ch) summary(lr) predicted_scores <- predict (lr, partial_modtest_ch, "probs") # predict on new data predicted_class <- predict (lr, partial_modtest_ch) mean(as.character(predicted_class) != as.character(partial_modtest_ch$VAC_LVL)) #********** Variables *********** # 'SC_KNOWL', 'UND_SCSCI', 'SC_DZ', 'SC_POET', 'SC_PS', 'SC_SS', 'SC_UNI', # 'SCINFO_30D', 'MDHINFO_30D', 'SC_INT', 'MDH_INT', 'CONF_NGO', # 'CONF_HOSP', 'TRU_NEIGHB', 'TRU_SCI', 'TRU_JO', 'TRU_HCW', s'TRU_NGOPPL', # 'TRU_TH', 'TRU_SC', 'TRUSCI_ACCINFO', 'TRUSCIUNI_BEN', 'TRUSCIUNI_HON', # 'TRUSCICOM_BEN', 'TRUSCICOM_HON', 'SCI_BENPPL', 'SCI_BENRESP', # 'SCTECH_IMPRLIFE', 'SCTECH_JOBS', 'TRU_PPLADV', 'TRU_HCWADV', 'VAC_LVL', # 'CH_RVAC', 'TRUSCI_IDX', 'TRUSCI_LVL', 'VW_SC', 'AGE', 'AGE_CAT', 'GEN', # 'EDU', 'LIV_AR', 'RGN', 'SUBJ_HHI', 'CTRY_INC', 'EMP_STAT'
a26d02c10021459330d632d93779a4176df884e2
e0b87eb63633d601f3e9e23e35b62b72835f091c
/man/nl.lts.Rd
9d16b70f6cc23824a2e7ed84b39788ea804c514e
[]
no_license
Allisterh/nlr
7737c85aa80485f5173469d2479d89be72c427ba
7f45b89f1748d356af588920b6f7ae2a5269f80d
refs/heads/master
2022-04-02T20:53:11.162698
2019-07-31T11:40:02
2019-07-31T11:40:02
null
0
0
null
null
null
null
UTF-8
R
false
false
1,654
rd
nl.lts.Rd
\name{nl.lts} \alias{nl.lts} \title{ Compute (LTS) Least Trimmed Square Estimate. } \description{ LTS is minimizing trimmed sum of squares. } \usage{ nl.lts(formula, data, start, h = NULL, control = nlr.control()) } \arguments{ \item{formula}{ \code{\link{nl.form}} object of the nonlinear model function. } \item{data}{ List of data used in predictor and response. } \item{start}{ List of parameter starting value. } \item{h}{ Percentage of trimming the residuals, if omited the default 25\% will be used. } \item{control}{ \code{\link{nlr.control}} options, will be submited to least square \code{\link{nlsqr}} function. } } \details{ LTS trimme \code{h} percent of residuals first then compute the least square estimate, and final parameter estimate is the one minimize the sum of squares of errors. } \value{ \code{\link{nl.fitt}} object of fitted model parameter. } \references{ Riazoshams H, Midi H, and Ghilagaber G, 2018,. Robust Nonlinear Regression, with Application using R, Joh Wiley and Sons. } \author{ Hossein Riazoshams, May 2014. Email: \email{riazihosein@gmail.com} URL \url{http://www.riazoshams.com/nlr/} } \note{ The result data returnd in fitted object is trimmed data. } \seealso{ \code{\link{nl.form}}, \code{\link{nl.fitt}} } \examples{ data=list(xr=Weights$Date,yr=Weights$Weight) fit<- nl.lts(nlrobj1[[14]],data=data,start=list(p1=1000,p2=42,p3=.11)) fit$parameters } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{Least Square Estimae} \keyword{Least Trimmed Square}
9fbf98d89a86e847c678b1ec5546884096a35708
3c0531db5f30de38f06b8dffd741c3e13a94eeb5
/code/old/code_01_clean-saved-google-sheet.R
bab34836921e66cf6c209d98bc5bd3dcde3fb640
[]
no_license
spoicts/ccweedmeta-analysis
df206efcbfd9d88f378e91b2aaf45eaeea28b2ba
63abef61a9a66d92fb604fc73626f798f4ae85ee
refs/heads/master
2023-05-08T23:19:39.195889
2021-06-01T20:42:55
2021-06-01T20:42:55
null
0
0
null
null
null
null
UTF-8
R
false
false
9,881
r
code_01_clean-saved-google-sheet.R
############################# ## # Author: Gina Nichols # # Date Created: Oct 19 # # Date last modified: Oct 23 2018 - by Gina, fix 0s # June 7 2019 - (Gina) use googledrive package instead of googlesheets # added cc_type2 (2 categories of cc types) # Aug 9 2019 - Gina, moved everything into cybox # Sept 6 2019 - Made cleaning google sheet it's own code # SEpt 9 2019 - eliminated MAT and MAP bc they are crap, fixed dates # Sept 17 - trying to indicate where dates were estimated, not working!!!!!!!! # Oct 2 - figured out dates. Looking at yield vs term-plant gap # Dec 16 2019 - eliminated one outlier in bioLRR, changed to second lowest value # Jan 2 2020 - cleaning up one last time # Feb 25 2020 - ok seriousy cleaning it, making it ready for datashare # # # Purpose: Clean data # If both the ctl and cc biomass/density values are 0, change to 1s # Eliminate other comparisons w/0s # Create 'master' database to use in all subsequent analyses # # Inputs: rd_cc-database # # Outputs: td_cc-database-clean # # NOtes: There are no 0s (?) # Removing one outlier that drastically changed cc_bio vs LRR estimates due to very low LRR # # ############################## rm(list=ls()) library(tidyverse) library(readxl) #--to read excel files library(naniar) #--allows you to replace . with NA library(lubridate) #--for dates library(janitor) #--to clean things datraw <- read_csv("_rawdata/rd_cc-database.csv") dat <- datraw %>% mutate(exp_type = str_remove_all(exp_type, " "), exp_type = str_remove_all(exp_type, "-"), cc_spec = str_replace_all(cc_spec, "/", "+")) %>% mutate(cc_pMNTH = str_sub(cc_pMNTH, 1, 3), crop_pMNTH = str_sub(crop_pMNTH, 1, 3), cc_termMNTH = str_sub(cc_termMNTH, 1, 3)) %>% mutate(cc_termMETH = ifelse(cc_termMETH == "mowed", "mowing", cc_termMETH), cc_termMETH = ifelse(cc_termMETH == "rolling", "roller crimper", cc_termMETH), cc_termMETH = ifelse(cc_termMETH == "winterkill", "winter kill", cc_termMETH), cc_termMETH = ifelse(cc_termMETH == "chopping", "mowing", cc_termMETH)) # make clean for datashare ------------------------------------------------ #--fix exp_types datshare <- dat %>% clean_names() summary(as.numeric(datshare$cc_p_den_kgha)) levels(as.factor(datshare$cc_term_meth)) datshare %>% select(cc_term_mnth) %>% distinct() tibble(var_names = names(datshare)) %>% write_csv("_datashare/cover-crop-weed-database-varnames.csv") # Wrangle dates -------------------------------------------------- dat1 <- dat %>% select(-MAT, -MAP, -cc_pMNTH, cc_termMNTH, -crop_pMNTH) %>% #--cover crop planting dates mutate( # indicate you are estimating cc_pest = case_when( (is.na(cc_pDOM) & !is.na(cc_pMNTH2)) ~ "Y"), # if there is a month but no date, assign it as 15 cc_pDOM = ifelse( (is.na(cc_pDOM) & !is.na(cc_pMNTH2)), 15, cc_pDOM), # paste things to make a date ccpl_lubdate = ifelse(!is.na(cc_pDOM), paste(cc_pMNTH2, cc_pDOM, "2018", sep = "/"), NA), ccpl_lubdate = mdy(ccpl_lubdate), ccpl_doy = yday(ccpl_lubdate)) %>% select(-cc_pMNTH2, -cc_pDOM, -cc_pDATE) %>% #--cover crop termination dates mutate( # indicate you are estimating cc_termest = case_when( (is.na(cc_termDOM) & !is.na(cc_termMNTH2)) ~ "Y"), # if there is a month but no date, assign it as 1 cc_termDOM = ifelse( (is.na(cc_termDOM) & !is.na(cc_termMNTH2)), 1, cc_termDOM), # paste things to make a date ccterm_lubdate = ifelse(!is.na(cc_termDOM), paste(cc_termMNTH2, cc_termDOM, "2019", sep = "/"), NA), ccterm_lubdate = mdy(ccterm_lubdate), ccterm_doy = yday(ccterm_lubdate)) %>% select(-cc_termMNTH2, -cc_termDOM) %>% #--crop planting dates mutate( # indicate you are estimating crop_pest = case_when( (is.na(crop_pDOM) & !is.na(crop_pMNTH2)) ~ "Y"), # if there is a month but no date, assign it as 30 crop_pDOM = ifelse( (is.na(crop_pDOM) & !is.na(crop_pMNTH2)), 30, crop_pDOM), # paste things to make a date croppl_lubdate = ifelse(!is.na(crop_pDOM), paste(crop_pMNTH2, crop_pDOM, "2019", sep = "/"), NA), croppl_lubdate = mdy(croppl_lubdate), croppl_doy = yday(croppl_lubdate)) %>% select(-crop_pMNTH2, -crop_pDOM) # Address 0s -------------------------------------------------------------- dat_no0s <- dat1 %>% # Identify pairs of 0s (there are currently none) mutate(repl_1den = ifelse( (ccden == 0 & ctlden == 0), "yes", "no"), repl_1bio = ifelse( (ccbio == 0 & ctlbio == 0), "yes", "no")) %>% # Replace pairs of 0s w/1s mutate(ccden = ifelse(repl_1den == "yes", 1, ccden), ctlden = ifelse(repl_1den == "yes", 1, ctlden), ccbio = ifelse(repl_1bio == "yes", 1, ccbio), ctlbio = ifelse(repl_1bio == "yes", 1, ctlbio)) %>% # Identify single 0s mutate(removeme = ifelse( (ccden == 0 & ctlden !=0), "yes", NA), removeme = ifelse( (ctlden == 0 & ccden !=0), "yes", removeme), removeme = ifelse( (ccbio == 0 & ctlbio !=0), "yes", removeme), removeme = ifelse( (ctlbio == 0 & ccbio !=0), "yes", removeme)) %>% filter(is.na(removeme)) # Calculate log response ratios ------------------------------------------- dat_LRR <- dat_no0s %>% # Calculate LRR mutate(bioLRR = log(ccbio / ctlbio), denLRR = log(ccden / ctlden), yieldLRR = log(cc_yield_kgha / ctl_yield_kgha) ) # Change cc_type to 2 cats ------------------------------------------------ dat_LRR2 <- dat_LRR %>% mutate(cc_type2 = recode(cc_type, brassica = "non-grass", legume = "non-grass", mix = "non-grass")) # Get days between plantings ------------------------------------------------ dat_LRR3 <- dat_LRR2 %>% mutate(cc_growdays = time_length( interval(ymd(ccpl_lubdate), ymd(ccterm_lubdate)), "day"), termgap_days = time_length( interval(ymd(ccterm_lubdate), ymd(croppl_lubdate)), "day") ) %>% rename(ccterm_meth = cc_termMETH2, ccpl_meth = cc_pMETH, ccpl_den_kgha = cc_pDEN_kgha) %>% mutate(wgt = (reps * reps) / (reps + reps)) %>% select(obs_no, study, pub_reference, pub_year, loc_state, lat, long, reps, wgt, aridity_index, OM_pct, soil_type, cc_type, cc_type2, cropsys_tillage, msmt_season, msmt_planting, weed_group, ccpl_den_kgha, ccpl_lubdate, ccpl_doy, cc_pest, ccterm_lubdate, ccterm_doy, cc_termest, ccterm_meth, crop_follow, crop_pest, croppl_lubdate, croppl_doy, cc_bio_kgha, cc_growdays, termgap_days, bioLRR, denLRR, yieldLRR) # Get ccbio in Mgha ------------------------------------------------ tdat <- dat_LRR3 %>% mutate(cc_bio_Mgha = cc_bio_kgha / 1000) # look at termination methods --------------------------------------------- # I hate them, but leave them tdat %>% group_by(ccterm_meth) %>% summarise(n = n()) # Change the one biomass outlier to next lowest value ----------------------------- secondmin <- tdat %>% filter(obs_no == 145) %>% select(bioLRR) %>% pull() tdat %>% filter(obs_no == 76) tdat <- tdat %>% mutate(bioLRR = ifelse(obs_no == 76, secondmin, bioLRR)) tdat %>% filter(obs_no == 76) tdat %>% select(bioLRR) %>% arrange(bioLRR) # density is fine # Write to my folder ------------------------------------------------- write_csv(tdat, "_tidydata/td_cc-database-clean.csv") tdat_long <- tdat %>% #select(-yieldLRR) %>% gather(bioLRR, denLRR, key = "resp", value = "LRR") %>% mutate(resp = recode(resp, "bioLRR" = "bio", "denLRR" = "den")) %>% filter(!is.na(LRR)) write_csv(tdat_long, "_tidydata/td_cc-database-clean-long.csv") tdat_long %>% group_by(resp, cc_termest) %>% summarise(n = n()) # get unique studies ------------------------------------------------------ tdat %>% select(pub_reference) %>% unique() %>% write_csv("_rawdata/rd_unique-studies.csv") # biomasses for rafa ------------------------------------------------------ tdat %>% filter(cc_type2 == "grass") %>% select(loc_state, lat, long, ccpl_doy, ccterm_doy, croppl_doy, cc_bio_kgha) %>% distinct() %>% write_csv("_tidydata/td_for-rafa.csv") # explore for summarising in paper ---------------------------------------- tdat_long %>% #filter(cc_type == "brassica") %>% ggplot(aes(cc_type, LRR)) + geom_point() + facet_grid(resp~.) tdat_long %>% filter(cc_termest == "Y") tdat_long %>% filter(resp == "den") %>% filter(LRR < 0) %>% ggplot(aes(cc_bio_kgha)) + geom_histogram() tdat_long %>% filter(resp == "den") %>% filter(LRR < 0) %>% filter(cc_bio_kgha <10) # categoricals tdat_long %>% mutate_if(is.character, as.factor) %>% group_by(resp, crop_follow) %>% summarise(n = n()) tdat %>% filter(!is.na(yieldLRR)) %>% summarise(n = n()) # continuous tdat_long %>% group_by(resp) %>% summarise(min = min(cc_bio_kgha, na.rm = T), max = max(cc_bio_kgha, na.rm = T))
e5c183fe2724f68f9ded013f018d0fcb124ba406
54164e00cb9fd4036f0add100a925ff92267f210
/R/SEM_Course/SEMwordsLavaanScript.R
48513508db3f7c9b635a389d0e8e0483a8d3d505
[]
no_license
antovich/UC-Davis
14714d30eff4aacc1bee9fd7e6097d480960fdff
b6a4018b2103330726f3d2dfc1cfae5948160733
refs/heads/master
2022-03-13T11:50:33.974130
2019-11-25T20:53:19
2019-11-25T20:53:19
119,594,149
0
0
null
null
null
null
UTF-8
R
false
false
43,198
r
SEMwordsLavaanScript.R
data = read.table('/Users/Dylan/Graduate School/Coursework/PSC205C Struct Eq Model/Final Project/Correlation Table.csv', sep = ',') rownames(data) = c('MLU','WordRoot','RDLSComp','RDLSExpress','ELI','VABSComm','Gender','VABSSoc','MomWordRoot','MomMLU','MomVerb','Personality','ParentAtt','ParentKnow','SES') colnames(data) = c('MLU','WordRoot','RDLSComp','RDLSExpress','ELI','VABSComm','Gender','VABSSoc','MomWordRoot','MomMLU','MomVerb', 'Personality','ParentAtt','ParentKnow','SES') library(lavaan) data = as.matrix(data) # Converting correlations to covariances dataSDs = c(0.31, 14.28, 1.13, 1.02, 107.83, 11.83, 0.50, 8.18, 32.55, 0.63, 12.66, 9.15, 0.44, 0.05, 10.25) data1 = cor2cov(data,dataSDs) # Model 1 Measurement (Initial Model From Borenstein et al) LVP1.lv = 'MomVocab =~ 1*MomMLU + MomWordRoot ChildVocab =~ 1*MLU + WordRoot + RDLSComp + RDLSExpress + ELI + VABSComm MomVocab ~~ MomVocab ChildVocab ~~ ChildVocab MLU ~~ MLU WordRoot ~~ WordRoot RDLSComp ~~ RDLSComp RDLSExpress ~~ RDLSExpress ELI ~~ ELI VABSComm ~~ VABSComm MomWordRoot ~~ MomWordRoot MomMLU ~~ 0*MomMLU MomVocab ~~ ChildVocab' fit.LVP1.lv = lavaan(model=LVP1.lv, sample.cov = data1, sample.nobs=120, fixed.x=FALSE) summary(fit.LVP1.lv) fitMeasures(fit.LVP1.lv, fit.measures = 'all') # lavaan (0.5-12) converged normally after 124 iterations # # Number of observations 120 # # Estimator ML # Minimum Function Test Statistic 69.597 # Degrees of freedom 20 # P-value (Chi-square) 0.000 # # Parameter estimates: # # Information Expected # Standard Errors Standard # # Estimate Std.err Z-value P(>|z|) # Latent variables: # MomVocab =~ # MomMLU 1.000 # MomWordRoot 27.383 4.000 6.847 0.000 # ChildVocab =~ # MLU 1.000 # WordRoot 93.897 24.353 3.856 0.000 # RDLSComp 4.329 1.365 3.172 0.002 # RDLSExpress 7.995 2.000 3.998 0.000 # ELI 851.739 212.800 4.003 0.000 # VABSComm 80.164 20.643 3.883 0.000 # # Covariances: # MomVocab ~~ # ChildVocab 0.001 0.007 0.122 0.903 # # Variances: # MomVocab 0.394 0.051 # ChildVocab 0.013 0.006 # MLU 0.083 0.011 # WordRoot 90.580 13.290 # RDLSComp 1.029 0.136 # RDLSExpress 0.222 0.046 # ELI 2344.440 506.943 # VABSComm 57.412 8.606 # MomWordRoot 755.539 97.540 # MomMLU 0.000 # # # fitMeasures(fit.LVP1.lv, fit.measures = 'all') # fmin chisq df pvalue baseline.chisq baseline.df # 0.290 69.597 20.000 0.000 434.751 28.000 # baseline.pvalue cfi tli nnfi rfi nfi # 0.000 0.878 0.829 0.829 0.776 0.840 # pnfi ifi rni logl unrestricted.logl npar # 0.600 0.880 0.878 -2591.784 -2556.985 16.000 # aic bic ntotal bic2 rmsea rmsea.ci.lower # 5215.567 5260.167 120.000 5209.583 0.144 0.108 # rmsea.ci.upper rmsea.pvalue rmr rmr_nomean srmr srmr_nomean # 0.181 0.000 96.875 96.875 0.083 0.083 # cn_05 cn_01 gfi agfi pgfi mfi # 55.158 65.772 0.883 0.789 0.491 0.813 # ecvi # 0.847 # Model 2 Structural (Initial Model From Borenstein et al) LVP2.lv = 'MomVocab =~ 1*MomMLU + MomWordRoot ChildVocab =~ 1*MLU + WordRoot + RDLSComp + RDLSExpress + ELI + VABSComm MomVocab ~~ MomVocab ChildVocab ~~ ChildVocab MLU ~~ MLU WordRoot ~~ WordRoot RDLSComp ~~ RDLSComp RDLSExpress ~~ RDLSExpress ELI ~~ ELI VABSComm ~~ VABSComm MomWordRoot ~~ MomWordRoot MomMLU ~~ MomMLU MomVerb ~~ MomVerb SES~~SES VABSSoc ~~ VABSSoc Personality ~~ Personality ParentAtt ~~ ParentAtt ParentKnow ~~ ParentKnow MomVocab ~ ChildVocab MomVerb ~ MomVocab SES ~ MomVocab Personality ~ MomVocab VABSSoc ~ MomVocab ParentAtt ~ MomVocab ParentKnow ~ MomVocab MomVerb ~ ChildVocab SES ~ ChildVocab Personality ~ ChildVocab ParentAtt ~ ChildVocab ParentKnow ~ ChildVocab SES ~~ MomVerb MomVerb ~ ParentKnow SES ~ ParentKnow ELI ~~ VABSComm RDLSExpress ~~ RDLSComp' fit.LVP2.lv = lavaan(model=LVP2.lv, sample.cov = data1, sample.nobs=120, fixed.x=FALSE) summary(fit.LVP2.lv) fitMeasures(fit.LVP2.lv, fit.measures = 'all') modindices(fit.LVP2.lv) #lavaan (0.5-12) converged normally after 257 iterations # # Number of observations 120 # # Estimator ML # Minimum Function Test Statistic 156.869 # Degrees of freedom 66 # P-value (Chi-square) 0.000 # #Parameter estimates: # # Information Expected # Standard Errors Standard # # Estimate Std.err Z-value P(>|z|) #Latent variables: # MomVocab =~ # MomMLU 1.000 # MomWordRoot 39.628 7.886 5.025 0.000 # ChildVocab =~ # MLU 1.000 # WordRoot 91.119 22.397 4.068 0.000 # RDLSComp 4.007 1.273 3.148 0.002 # RDLSExpress 7.810 1.853 4.214 0.000 # ELI 777.518 185.968 4.181 0.000 # VABSComm 70.776 17.779 3.981 0.000 # #Regressions: # MomVocab ~ # ChildVocab 0.315 0.491 0.643 0.520 # MomVerb ~ # MomVocab 10.668 3.103 3.438 0.001 # SES ~ # MomVocab 8.070 2.482 3.251 0.001 # Personality ~ # MomVocab -1.949 1.829 -1.066 0.287 # VABSSoc ~ # MomVocab 4.490 1.686 2.662 0.008 # ParentAtt ~ # MomVocab 0.098 0.087 1.132 0.258 # ParentKnow ~ # MomVocab 0.037 0.011 3.435 0.001 # MomVerb ~ # ChildVocab -3.025 9.639 -0.314 0.754 # SES ~ # ChildVocab 9.950 8.161 1.219 0.223 # Personality ~ # ChildVocab 12.208 7.819 1.561 0.118 # ParentAtt ~ # ChildVocab 0.832 0.395 2.107 0.035 # ParentKnow ~ # ChildVocab 0.073 0.041 1.764 0.078 # MomVerb ~ # ParentKnow 18.517 24.868 0.745 0.457 # SES ~ # ParentKnow 7.293 20.214 0.361 0.718 # #Covariances: # MomVerb ~~ # SES 14.227 10.432 1.364 0.173 # ELI ~~ # VABSComm 150.951 64.304 2.347 0.019 # RDLSComp ~~ # RDLSExpress 0.029 0.060 0.492 0.622 # #Variances: # MomVocab 0.264 0.065 # ChildVocab 0.014 0.007 # MLU 0.081 0.011 # WordRoot 85.667 13.067 # RDLSComp 1.041 0.141 # RDLSExpress 0.176 0.053 # ELI 3044.099 628.440 # VABSComm 68.463 10.482 # MomWordRoot 633.108 108.910 # MomMLU 0.128 0.047 # MomVerb 124.105 17.606 # SES 83.272 11.657 # VABSSoc 60.995 8.088 # Personality 80.133 10.413 # ParentAtt 0.179 0.023 # ParentKnow 0.002 0.000 # # fitMeasures(fit.LVP2.lv, fit.measures = 'all') # fmin chisq df pvalue baseline.chisq baseline.df # 0.654 156.869 66.000 0.000 614.109 91.000 # baseline.pvalue cfi tli nnfi rfi nfi # 0.000 0.826 0.760 0.760 0.648 0.745 # pnfi ifi rni logl unrestricted.logl npar # 0.540 0.834 0.826 -4208.098 -4129.664 39.000 # aic bic ntotal bic2 rmsea rmsea.ci.lower # 8494.197 8602.909 120.000 8479.610 0.107 0.086 # rmsea.ci.upper rmsea.pvalue rmr rmr_nomean srmr srmr_nomean # 0.129 0.000 62.202 62.202 0.113 0.113 # cn_05 cn_01 gfi agfi pgfi mfi # 66.760 74.151 0.866 0.787 0.544 0.685 # ecvi # 1.957 # Model 3 Structural (MY ALTERNATE MODEL) LVP3.lv = 'MomVocab =~ 1*MomMLU + MomWordRoot ChildVocab =~ 1*MLU + WordRoot + RDLSComp + RDLSExpress + ELI + VABSComm MomVocab ~~ MomVocab ChildVocab ~~ ChildVocab MLU ~~ MLU WordRoot ~~ WordRoot RDLSComp ~~ RDLSComp RDLSExpress ~~ RDLSExpress ELI ~~ ELI VABSComm ~~ VABSComm MomWordRoot ~~ MomWordRoot MomMLU ~~ 0*MomMLU MomVerb ~~ MomVerb SES ~~ SES VABSSoc ~~ VABSSoc Personality ~~ Personality ParentAtt ~~ ParentAtt ParentKnow ~~ ParentKnow Gender ~~ Gender MomVocab ~ ChildVocab MomVerb ~ ChildVocab SES ~ ChildVocab Gender ~ ChildVocab VABSSoc ~ ChildVocab Personality ~ ChildVocab ParentAtt ~ MomVocab ParentKnow ~ MomVocab SES ~ ParentKnow Personality ~ VABSSoc SES ~~ MomVerb ELI ~~ VABSComm RDLSExpress ~~ RDLSComp WordRoot ~~ MLU MomWordRoot ~~ MomMLU' fit.LVP3.lv = lavaan(model=LVP3.lv, sample.cov = data1, sample.nobs=120, fixed.x=FALSE) summary(fit.LVP3.lv, standardized = TRUE) fitMeasures(fit.LVP3.lv, fit.measures = 'all') #lavaan (0.5-12) converged normally after 269 iterations # # Number of observations 120 # # Estimator ML # Minimum Function Test Statistic 184.905 # Degrees of freedom 83 # P-value (Chi-square) 0.000 # #Parameter estimates: # # Information Expected # Standard Errors Standard # # Estimate Std.err Z-value P(>|z|) #Latent variables: # MomVocab =~ # MomMLU 1.000 # MomWordRoot 50.379 14.639 3.441 0.001 # ChildVocab =~ # MLU 1.000 # WordRoot 97.684 25.129 3.887 0.000 # RDLSComp 4.691 1.540 3.045 0.002 # RDLSExpress 8.372 2.239 3.739 0.000 # ELI 891.495 238.511 3.738 0.000 # VABSComm 83.057 22.960 3.617 0.000 # #Regressions: # MomVocab ~ # ChildVocab 0.357 0.506 0.706 0.480 # MomVerb ~ # ChildVocab 5.699 11.377 0.501 0.616 # SES ~ # ChildVocab 14.014 9.587 1.462 0.144 # Gender ~ # ChildVocab 1.497 0.576 2.599 0.009 # VABSSoc ~ # ChildVocab 37.672 11.719 3.215 0.001 # Personality ~ # ChildVocab 7.742 9.584 0.808 0.419 # ParentAtt ~ # MomVocab 0.062 0.057 1.097 0.273 # ParentKnow ~ # MomVocab 0.023 0.007 3.374 0.001 # SES ~ # ParentKnow 25.988 17.418 1.492 0.136 # Personality ~ # VABSSoc 0.151 0.117 1.288 0.198 # #Covariances: # MomVerb ~~ # SES 35.062 11.827 2.965 0.003 # ELI ~~ # VABSComm 75.139 60.925 1.233 0.217 # RDLSComp ~~ # RDLSExpress 0.019 0.059 0.317 0.751 # MLU ~~ # WordRoot 0.593 0.282 2.101 0.036 # MomMLU ~~ # MomWordRoot -9.051 5.543 -1.633 0.103# # #Variances: # MomVocab 0.392 0.051 # ChildVocab 0.011 0.006 # MLU 0.084 0.011 # WordRoot 92.898 13.741 # RDLSComp 1.014 0.137 # RDLSExpress 0.229 0.053 # ELI 2425.078 603.201 # VABSComm 59.749 9.926 # MomWordRoot 49.266 546.134 # MomMLU 0.000 # MomVerb 158.568 20.476 # SES 97.800 12.656 # VABSSoc 50.096 6.694 # Personality 79.816 10.314 # ParentAtt 0.190 0.025 # ParentKnow 0.002 0.000 # Gender 0.222 0.029 # # fitMeasures(fit.LVP3.lv, fit.measures = 'all') # fmin chisq df pvalue baseline.chisq baseline.df # 0.770 184.905 83.000 0.000 639.822 105.000 # baseline.pvalue cfi tli nnfi rfi nfi # 0.000 0.809 0.759 0.759 0.634 0.711 # pnfi ifi rni logl unrestricted.logl npar # 0.562 0.817 0.809 -4295.853 -4203.400 37.000 # aic bic ntotal bic2 rmsea rmsea.ci.lower # 8665.706 8768.844 120.000 8651.867 0.101 0.082 # rmsea.ci.upper rmsea.pvalue rmr rmr_nomean srmr srmr_nomean # 0.121 0.000 40.766 40.766 0.111 0.111 # cn_05 cn_01 gfi agfi pgfi mfi # 69.316 76.201 0.829 0.753 0.573 0.654 # ecvi # 2.158 # modindices(fit.LVP3.lv) # lhs op rhs mi epc sepc.lv sepc.all sepc.nox #1 MomVocab =~ MomMLU NA NA NA NA NA #2 MomVocab =~ MomWordRoot 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #3 MomVocab =~ MLU 0.125 0.013 0.008 2.700000e-02 2.700000e-02 #4 MomVocab =~ WordRoot 3.673 -2.531 -1.588 -1.120000e-01 -1.120000e-01 #5 MomVocab =~ RDLSComp 5.546 0.316 0.199 1.760000e-01 1.760000e-01 #6 MomVocab =~ RDLSExpress 6.942 -0.208 -0.130 -1.280000e-01 -1.280000e-01 #7 MomVocab =~ ELI 3.050 13.469 8.450 7.900000e-02 7.900000e-02 #8 MomVocab =~ VABSComm 0.249 0.517 0.324 2.800000e-02 2.800000e-02 #9 ChildVocab =~ MomMLU 4.185 -1.161 -0.124 -1.980000e-01 -1.980000e-01 #10 ChildVocab =~ MomWordRoot 1.219 30.072 3.217 9.900000e-02 9.900000e-02 #11 ChildVocab =~ MLU NA NA NA NA NA #12 ChildVocab =~ WordRoot 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #13 ChildVocab =~ RDLSComp 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #14 ChildVocab =~ RDLSExpress 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #15 ChildVocab =~ ELI 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #16 ChildVocab =~ VABSComm 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #17 MomMLU ~~ MomMLU 2.865 1.271 1.271 3.230000e+00 3.230000e+00 #18 MomMLU ~~ MomWordRoot 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #19 **MomMLU ~~ MLU 6.529 0.034 0.034 1.770000e-01 1.770000e-01 #20 **MomMLU ~~ WordRoot 22.629 -2.246 -2.246 -2.520000e-01 -2.520000e-01 #21 MomMLU ~~ RDLSComp 1.305 0.055 0.055 7.800000e-02 7.800000e-02 #22 MomMLU ~~ RDLSExpress 2.956 -0.048 -0.048 -7.500000e-02 -7.500000e-02 #23 MomMLU ~~ ELI 0.979 2.698 2.698 4.000000e-02 4.000000e-02 #24 MomMLU ~~ VABSComm 1.624 0.473 0.473 6.400000e-02 6.400000e-02 #25 MomWordRoot ~~ MomWordRoot 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #26**MomWordRoot ~~ MLU 6.366 -1.767 -1.767 -1.770000e-01 -1.770000e-01 #27**MomWordRoot ~~ WordRoot 10.633 80.154 80.154 1.740000e-01 1.740000e-01 #28 MomWordRoot ~~ RDLSComp 0.752 2.177 2.177 6.000000e-02 6.000000e-02 #29 MomWordRoot ~~ RDLSExpress 0.231 -0.693 -0.693 -2.100000e-02 -2.100000e-02 #30 MomWordRoot ~~ ELI 0.122 49.591 49.591 1.400000e-02 1.400000e-02 #31 MomWordRoot ~~ VABSComm 1.553 -24.068 -24.068 -6.300000e-02 -6.300000e-02 #32 MLU ~~ MLU 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #33 MLU ~~ WordRoot 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #34 MLU ~~ RDLSComp 0.295 0.014 0.014 4.100000e-02 4.100000e-02 #35 MLU ~~ RDLSExpress 1.585 0.020 0.020 6.400000e-02 6.400000e-02 #36 MLU ~~ ELI 0.946 -1.519 -1.519 -4.600000e-02 -4.600000e-02 #37 MLU ~~ VABSComm 0.289 -0.109 -0.109 -3.000000e-02 -3.000000e-02 #38 WordRoot ~~ WordRoot 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #39 WordRoot ~~ RDLSComp 7.482 -2.654 -2.654 -1.660000e-01 -1.660000e-01 #40 WordRoot ~~ RDLSExpress 9.883 2.501 2.501 1.730000e-01 1.730000e-01 #41 WordRoot ~~ ELI 0.146 -25.933 -25.933 -1.700000e-02 -1.700000e-02 #42 WordRoot ~~ VABSComm 0.039 -1.522 -1.522 -9.000000e-03 -9.000000e-03 #43 RDLSComp ~~ RDLSComp 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #44 RDLSComp ~~ RDLSExpress 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #45 **RDLSComp ~~ ELI 1.251 7.181 7.181 5.900000e-02 5.900000e-02 #46 RDLSComp ~~ VABSComm 0.758 -0.651 -0.651 -4.900000e-02 -4.900000e-02 #47 RDLSExpress ~~ RDLSExpress 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #48 RDLSExpress ~~ ELI 0.107 -1.833 -1.833 -1.700000e-02 -1.700000e-02 #49 RDLSExpress ~~ VABSComm 0.805 -0.529 -0.529 -4.400000e-02 -4.400000e-02 #50 ELI ~~ ELI 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #51 ELI ~~ VABSComm 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #52 VABSComm ~~ VABSComm 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #53 MomVerb ~~ MomVerb 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #54 MomVerb ~~ SES 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #55 MomVerb ~~ Gender 3.431 -0.969 -0.969 -1.540000e-01 -1.540000e-01 #56 MomVerb ~~ VABSSoc 2.281 11.988 11.988 1.170000e-01 1.170000e-01 #57 MomVerb ~~ Personality 3.351 -17.932 -17.932 -1.560000e-01 -1.560000e-01 #58 MomVerb ~~ ParentAtt 0.175 0.202 0.202 3.600000e-02 3.600000e-02 #59 MomVerb ~~ ParentKnow 2.259 0.081 0.081 1.290000e-01 1.290000e-01 #60 SES ~~ SES 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #61 SES ~~ Gender 1.406 0.488 0.488 9.700000e-02 9.700000e-02 #62 SES ~~ VABSSoc 1.021 6.306 6.306 7.700000e-02 7.700000e-02 #63 SES ~~ Personality 0.002 -0.346 -0.346 -4.000000e-03 -4.000000e-03 #64 SES ~~ ParentAtt 0.044 0.080 0.080 1.800000e-02 1.800000e-02 #65 **SES ~~ ParentKnow 5.963 -0.301 -0.301 -5.990000e-01 -5.990000e-01 #66 Gender ~~ Gender 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #67 Gender ~~ VABSSoc 1.835 -0.422 -0.422 -1.040000e-01 -1.040000e-01 #68 Gender ~~ Personality 0.223 0.182 0.182 4.000000e-02 4.000000e-02 #69 Gender ~~ ParentAtt 0.374 -0.012 -0.012 -5.300000e-02 -5.300000e-02 #70 Gender ~~ ParentKnow 0.057 0.000 0.000 2.000000e-02 2.000000e-02 #71 VABSSoc ~~ VABSSoc 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #72 VABSSoc ~~ Personality NA NA NA NA NA #73 **VABSSoc ~~ ParentAtt 1.899 0.394 0.394 1.100000e-01 1.100000e-01 #74 VABSSoc ~~ ParentKnow 0.149 0.012 0.012 2.900000e-02 2.900000e-02 #75 Personality ~~ Personality 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #76 Personality ~~ ParentAtt 3.232 -0.636 -0.636 -1.590000e-01 -1.590000e-01 #77 Personality ~~ ParentKnow 0.001 0.001 0.001 3.000000e-03 3.000000e-03 #78 ParentAtt ~~ ParentAtt 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #79 ParentAtt ~~ ParentKnow 0.156 0.001 0.001 3.400000e-02 3.400000e-02 #80 ParentKnow ~~ ParentKnow 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #81 MomVocab ~~ MomVocab 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #82 MomVocab ~~ ChildVocab NA NA NA NA NA #83 ChildVocab ~~ ChildVocab 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #84 MomVocab ~ MomVerb 15.233 0.016 0.026 3.230000e-01 3.230000e-01 #85 MomVocab ~ SES 11.968 0.019 0.030 3.030000e-01 3.030000e-01 #86 MomVocab ~ Gender 2.665 -0.181 -0.288 -1.430000e-01 -1.430000e-01 #87 MomVocab ~ VABSSoc 5.056 0.017 0.027 2.180000e-01 2.180000e-01 #88 MomVocab ~ Personality 5.056 0.093 0.148 1.352000e+00 1.352000e+00 #89 MomVocab ~ ParentAtt 7.048 -5.963 -9.504 -4.164000e+00 -4.164000e+00 #90 MomVocab ~ ParentKnow 5.150 -46.538 -74.180 -3.694000e+00 -3.694000e+00 #91 MomVocab ~ ChildVocab 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #92 **MomVerb ~ MomVocab 9.569 4.959 3.111 2.470000e-01 2.470000e-01 #93 MomVerb ~ SES 6.354 2.242 2.242 1.794000e+00 1.794000e+00 #94 MomVerb ~ Gender 3.431 -4.359 -4.359 -1.720000e-01 -1.720000e-01 #95 MomVerb ~ VABSSoc 2.281 0.239 0.239 1.550000e-01 1.550000e-01 #96 MomVerb ~ Personality 3.797 -0.238 -0.238 -1.730000e-01 -1.730000e-01 #97 MomVerb ~ ParentAtt 0.497 1.774 1.774 6.200000e-02 6.200000e-02 #98 MomVerb ~ ParentKnow 6.354 58.211 58.211 2.300000e-01 2.300000e-01 #99 MomVerb ~ ChildVocab 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #100 SES ~ MomVocab 5.963 3.189 2.001 1.980000e-01 1.980000e-01 #101 SES ~ MomVerb NA NA NA NA NA #102 SES ~ Gender 1.406 2.194 2.194 1.080000e-01 1.080000e-01 #103 SES ~ VABSSoc 1.021 0.126 0.126 1.020000e-01 1.020000e-01 #104 SES ~ Personality 0.030 -0.017 -0.017 -1.500000e-02 -1.500000e-02 #105 SES ~ ParentAtt 0.184 0.849 0.849 3.700000e-02 3.700000e-02 #106 SES ~ ParentKnow 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #107 SES ~ ChildVocab 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #108 Gender ~ MomVocab 2.665 -0.102 -0.064 -1.290000e-01 -1.290000e-01 #109 Gender ~ MomVerb 2.506 -0.005 -0.005 -1.380000e-01 -1.380000e-01 #110 Gender ~ SES 0.417 0.003 0.003 5.700000e-02 5.700000e-02 #111 Gender ~ VABSSoc 1.835 -0.008 -0.008 -1.380000e-01 -1.380000e-01 #112 Gender ~ Personality 0.216 0.002 0.002 4.100000e-02 4.100000e-02 #113 Gender ~ ParentAtt 0.580 -0.075 -0.075 -6.600000e-02 -6.600000e-02 #114 Gender ~ ParentKnow 0.097 -0.270 -0.270 -2.700000e-02 -2.700000e-02 #115 Gender ~ ChildVocab 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #116 VABSSoc ~ MomVocab 5.056 2.141 1.343 1.650000e-01 1.650000e-01 #117 VABSSoc ~ MomVerb 3.497 0.098 0.098 1.510000e-01 1.510000e-01 #118 VABSSoc ~ SES 2.653 0.107 0.107 1.330000e-01 1.330000e-01 #119 VABSSoc ~ Gender 1.835 -1.901 -1.901 -1.160000e-01 -1.160000e-01 #120 VABSSoc ~ Personality 5.056 -1.432 -1.432 -1.607000e+00 -1.607000e+00 #121 **VABSSoc ~ ParentAtt 2.506 2.370 2.370 1.270000e-01 1.270000e-01 #122 VABSSoc ~ ParentKnow 1.245 14.701 14.701 9.000000e-02 9.000000e-02 #123 **VABSSoc ~ ChildVocab 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #124 Personality ~ MomVocab 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #125 Personality ~ MomVerb 3.691 -0.124 -0.124 -1.710000e-01 -1.710000e-01 #126 Personality ~ SES 0.331 -0.047 -0.047 -5.200000e-02 -5.200000e-02 #127 Personality ~ Gender 0.223 0.818 0.818 4.500000e-02 4.500000e-02 #128 Personality ~ VABSSoc 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #129**Personality ~ ParentAtt 3.232 -3.337 -3.337 -1.600000e-01 -1.600000e-01 #130 Personality ~ ParentKnow 0.001 0.593 0.593 3.000000e-03 3.000000e-03 #131 Personality ~ ChildVocab 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #132 ParentAtt ~ MomVocab 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #133 ParentAtt ~ MomVerb 0.387 0.002 0.002 5.700000e-02 5.700000e-02 #134 ParentAtt ~ SES 0.579 0.003 0.003 6.900000e-02 6.900000e-02 #135 ParentAtt ~ Gender 0.055 0.019 0.019 2.100000e-02 2.100000e-02 #136 ParentAtt ~ VABSSoc 5.906 0.012 0.012 2.210000e-01 2.210000e-01 #137 ParentAtt ~ Personality 1.326 -0.005 -0.005 -1.050000e-01 -1.050000e-01 #138 ParentAtt ~ ParentKnow 0.156 0.329 0.329 3.700000e-02 3.700000e-02 #139 **ParentAtt ~ ChildVocab 7.048 1.040 0.111 2.540000e-01 2.540000e-01 #140 ParentKnow ~ MomVocab 0.000 0.000 0.000 0.000000e+00 0.000000e+00 #141 ParentKnow ~ MomVerb 1.899 0.000 0.000 1.190000e-01 1.190000e-01 #142 ParentKnow ~ SES 0.039 0.000 0.000 -3.900000e-02 -3.900000e-02 #143 ParentKnow ~ Gender 0.839 0.008 0.008 7.900000e-02 7.900000e-02 #144 ParentKnow ~ VABSSoc 1.954 0.001 0.001 1.210000e-01 1.210000e-01 #145 ParentKnow ~ Personality 0.195 0.000 0.000 3.800000e-02 3.800000e-02 #146 ParentKnow ~ ParentAtt 0.156 0.004 0.004 3.400000e-02 3.400000e-02 #147**ParentKnow ~ ChildVocab 5.150 0.096 0.010 2.060000e-01 2.060000e-01 #148 ChildVocab ~ MomVocab NA NA NA NA NA #149 ChildVocab ~ MomVerb 4524.938 -1919726.407 -17947037.651 -2.262608e+08 -2.262608e+08 #150 ChildVocab ~ SES 5.150 0.019 0.175 1.770000e+00 1.770000e+00 #151 ChildVocab ~ Gender NA NA NA NA NA #152 ChildVocab ~ VABSSoc 2952.395 -2192982.857 -20501643.239 -1.670032e+08 -1.670032e+08 #153 ChildVocab ~ Personality NA NA NA NA NA #154 ChildVocab ~ ParentAtt 7.048 0.062 0.584 2.560000e-01 2.560000e-01 #155 ChildVocab ~ ParentKnow 5.150 0.487 4.555 2.270000e-01 2.270000e-01 # Model 4 Structural (Borenstein et al. Final Model) LVP4.lv = 'MomVocab =~ 1*MomMLU + MomWordRoot ChildVocab =~ 1*MLU + WordRoot + RDLSComp + RDLSExpress + ELI + VABSComm MomVocab ~~ MomVocab ChildVocab ~~ ChildVocab MLU ~~ MLU WordRoot ~~ WordRoot RDLSComp ~~ RDLSComp RDLSExpress ~~ RDLSExpress ELI ~~ ELI VABSComm ~~ VABSComm MomWordRoot ~~ MomWordRoot MomMLU ~~ MomMLU MomVerb ~~ MomVerb SES ~~ SES VABSSoc ~~ VABSSoc Personality ~~ Personality ParentAtt ~~ ParentAtt ParentKnow ~~ ParentKnow Gender ~~ Gender MomVocab ~ ChildVocab MomVocab ~ RDLSComp MomVocab ~ VABSComm MomVocab ~ ELI MomVocab ~ VABSSoc Personality ~ VABSSoc Personality ~ ELI MomVerb ~ ParentKnow MomVerb ~ MomVocab ParentAtt ~ VABSSoc ParentAtt ~ ChildVocab ParentKnow ~ MomVocab VABSSoc ~ ChildVocab Gender ~ ChildVocab SES ~ MomVocab SES ~~ MomVerb VABSSoc ~~ VABSComm WordRoot ~~ MLU' fit.LVP4.lv = lavaan(model=LVP4.lv, sample.cov = data1, sample.nobs=120, fixed.x=FALSE) summary(fit.LVP4.lv) fitMeasures(fit.LVP4.lv, fit.measures = 'all') #lavaan (0.5-12) converged normally after 287 iterations # # Number of observations 120 # # Estimator ML # Minimum Function Test Statistic 117.608 # Degrees of freedom 79 # P-value (Chi-square) 0.003 # #Parameter estimates: # # Information Expected # Standard Errors Standard # # Estimate Std.err Z-value P(>|z|) #Latent variables: # MomVocab =~ # MomMLU 1.000 # MomWordRoot 38.007 7.589 5.008 0.000 # ChildVocab =~ # MLU 1.000 # WordRoot 103.485 27.833 3.718 0.000 # RDLSComp 4.915 1.659 2.963 0.003 # RDLSExpress 8.825 2.479 3.559 0.000 # ELI 956.630 268.322 3.565 0.000 # VABSComm 89.973 25.832 3.483 0.000 # #Regressions: # MomVocab ~ # ChildVocab -5.999 2.828 -2.121 0.034 # RDLSComp 0.136 0.051 2.642 0.008 # VABSComm 0.011 0.008 1.360 0.174 # ELI 0.004 0.002 2.443 0.015 # VABSSoc 0.012 0.008 1.560 0.119 # Personality ~ # VABSSoc 0.128 0.110 1.161 0.246 # ELI 0.011 0.008 1.360 0.174 # MomVerb ~ # ParentKnow 14.459 23.839 0.607 0.544 # MomVocab 10.475 3.052 3.432 0.001 # ParentAtt ~ # VABSSoc 0.009 0.005 1.571 0.116 # ChildVocab 0.752 0.499 1.507 0.132 # ParentKnow ~ # MomVocab 0.039 0.011 3.590 0.000 # VABSSoc ~ # ChildVocab 38.070 12.533 3.037 0.002 # Gender ~ # ChildVocab 1.620 0.629 2.576 0.010 # SES ~ # MomVocab 8.373 2.218 3.774 0.000 # #Covariances: # MomVerb ~~ # SES 14.180 10.448 1.357 0.175 # VABSComm ~~ # VABSSoc 18.798 5.774 3.255 0.001 # MLU ~~ # WordRoot 0.656 0.281 2.339 0.019 # #Variances: # MomVocab 0.185 0.058 # ChildVocab 0.010 0.006 # MLU 0.085 0.011 # WordRoot 92.974 13.376 # RDLSComp 1.020 0.135 # RDLSExpress 0.237 0.046 # ELI 2194.951 497.197 # VABSComm 56.204 8.474 # MomWordRoot 653.811 106.367 # MomMLU 0.119 0.044 # MomVerb 124.956 17.553 # SES 84.928 11.801 # VABSSoc 51.570 6.869 # Personality 79.203 10.225 # ParentAtt 0.176 0.023 # ParentKnow 0.002 0.000 # Gender 0.221 0.029 # # # fitMeasures(fit.LVP4.lv, fit.measures = 'all') # fmin chisq df pvalue baseline.chisq baseline.df # 0.490 117.608 79.000 0.003 639.822 105.000 # baseline.pvalue cfi tli nnfi rfi nfi # 0.000 0.928 0.904 0.904 0.756 0.816 # pnfi ifi rni logl unrestricted.logl npar # 0.614 0.931 0.928 -4262.204 -4203.400 41.000 # aic bic ntotal bic2 rmsea rmsea.ci.lower # 8606.408 8720.696 120.000 8591.073 0.064 0.038 # rmsea.ci.upper rmsea.pvalue rmr rmr_nomean srmr srmr_nomean # 0.087 0.172 27.269 27.269 0.071 0.071 # cn_05 cn_01 gfi agfi pgfi mfi # 103.798 114.405 0.895 0.840 0.589 0.851 # ecvi # 1.663 # Model 5 Structural (MY ADJUSTED ALTERNATE MODEL) LVP5.lv = 'MomVocab =~ 1*MomMLU + MomWordRoot ChildVocab =~ 1*MLU + WordRoot + RDLSComp + RDLSExpress + ELI + VABSComm MomVocab ~~ MomVocab ChildVocab ~~ ChildVocab MLU ~~ MLU WordRoot ~~ WordRoot RDLSComp ~~ RDLSComp RDLSExpress ~~ RDLSExpress ELI ~~ ELI VABSComm ~~ VABSComm MomWordRoot ~~ MomWordRoot MomMLU ~~ MomMLU MomVerb ~~ MomVerb SES ~~ SES VABSSoc ~~ VABSSoc Personality ~~ Personality ParentAtt ~~ ParentAtt ParentKnow ~~ ParentKnow Gender ~~ Gender MomVocab ~ ChildVocab VABSSoc ~ ChildVocab Gender ~ ChildVocab MomVerb ~ MomVocab VABSSoc ~ MomVocab ParentKnow ~ MomVocab SES ~ MomVocab Personality ~ VABSSoc ParentAtt ~ VABSSoc WordRoot ~~ MLU MomWordRoot ~~ MomMLU MomWordRoot ~~ MLU MomWordRoot ~~ WordRoot MomMLU ~~ MLU MomMLU ~~ WordRoot' fit.LVP5.lv = lavaan(model=LVP5.lv, sample.cov = data1, sample.nobs=120, fixed.x=FALSE) summary(fit.LVP5.lv, standardized = TRUE) fitMeasures(fit.LVP5.lv, fit.measures = 'all') modindices(fit.LVP5.lv) #lavaan (0.5-12) converged normally after 208 iterations # # Number of observations 120 # # Estimator ML # Minimum Function Test Statistic 114.029 # Degrees of freedom 82 # P-value (Chi-square) 0.011 # #Parameter estimates:# # # Information Expected # Standard Errors Standard # # Estimate Std.err Z-value P(>|z|) Std.lv Std.all #Latent variables: # MomVocab =~ # MomMLU 1.000 0.402 0.647 # MomWordRoot 39.385 7.880 4.998 0.000 15.830 0.487 # ChildVocab =~ # MLU 1.000 0.108 0.348 # WordRoot 89.132 21.474 4.151 0.000 9.633 0.696 # RDLSComp 4.633 1.477 3.136 0.002 0.501 0.445 # RDLSExpress 8.063 2.107 3.826 0.000 0.871 0.858 # ELI 904.955 234.492 3.859 0.000 97.801 0.911 # VABSComm 86.374 22.911 3.770 0.000 9.335 0.792 # #Regressions: # MomVocab ~ # ChildVocab 0.785 0.480 1.637 0.102 0.211 0.211 # VABSSoc ~ # ChildVocab 35.485 11.030 3.217 0.001 3.835 0.471 # Gender ~ # ChildVocab 1.426 0.553 2.577 0.010 0.154 0.310 # MomVerb ~ # MomVocab 18.508 4.496 4.116 0.000 7.439 0.590 # VABSSoc ~ # MomVocab 4.658 2.099 2.219 0.026 1.872 0.230 # ParentKnow ~ # MomVocab 0.056 0.016 3.562 0.000 0.023 0.453 # SES ~ # MomVocab 13.009 3.370 3.861 0.000 5.229 0.512 # Personality ~ # VABSSoc 0.201 0.100 2.005 0.045 0.201 0.180 # ParentAtt ~ # VABSSoc 0.013 0.005 2.708 0.007 0.013 0.240 # #Covariances: # MLU ~~ # WordRoot 0.669 0.288 2.325 0.020 0.669 0.231 # MomMLU ~~ # MomWordRoot 4.334 1.965 2.206 0.027 4.334 0.322 # MomWordRoot ~~ # MLU -0.940 0.814 -1.154 0.248 -0.940 -0.114 # WordRoot 29.157 28.757 1.014 0.311 29.157 0.103 # MomMLU ~~ # MLU 0.012 0.015 0.850 0.395 0.012 0.090 # WordRoot -1.784 0.540 -3.305 0.001 -1.784 -0.378 # #Variances: # MomVocab 0.154 0.050 0.955 0.955 # ChildVocab 0.012 0.006 1.000 1.000 # MLU 0.085 0.011 0.085 0.879 # WordRoot 98.984 13.993 98.984 0.516 # RDLSComp 1.016 0.134 1.016 0.802 # RDLSExpress 0.272 0.048 0.272 0.264 # ELI 1965.332 468.520 1965.332 0.170 # VABSComm 51.647 7.923 51.647 0.372 # MomWordRoot 804.870 130.294 804.870 0.763 # MomMLU 0.225 0.046 0.225 0.582 # MomVerb 103.599 18.250 103.599 0.652 # SES 76.849 11.989 76.849 0.738 # VABSSoc 45.111 6.200 45.111 0.680 # Personality 80.335 10.371 80.335 0.968 # ParentAtt 0.181 0.023 0.181 0.942 # ParentKnow 0.002 0.000 0.002 0.795 # Gender 0.224 0.029 0.224 0.904 # fitMeasures(fit.LVP5.lv, fit.measures = 'all') # fmin chisq df pvalue baseline.chisq baseline.df # 0.475 114.029 82.000 0.011 639.822 105.000 # baseline.pvalue cfi tli nnfi rfi nfi # 0.000 0.940 0.923 0.923 0.772 0.822 # pnfi ifi rni logl unrestricted.logl npar # 0.642 0.943 0.940 -4260.415 -4203.400 38.000 # aic bic ntotal bic2 rmsea rmsea.ci.lower # 8596.830 8702.754 120.000 8582.616 0.057 0.028 # rmsea.ci.upper rmsea.pvalue rmr rmr_nomean srmr srmr_nomean # 0.081 0.310 27.778 27.778 0.075 0.075 # cn_05 cn_01 gfi agfi pgfi mfi # 110.592 121.701 0.894 0.844 0.611 0.875 # ecvi # 1.584
2b6961451f97b4638aa34cf5d13ba6f8115b7ab4
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/gginference/examples/ggchisqtest.Rd.R
4837cc5b2d213b19604a7e533a452a899f0566fb
[]
no_license
surayaaramli/typeRrh
d257ac8905c49123f4ccd4e377ee3dfc84d1636c
66e6996f31961bc8b9aafe1a6a6098327b66bf71
refs/heads/master
2023-05-05T04:05:31.617869
2019-04-25T22:10:06
2019-04-25T22:10:06
null
0
0
null
null
null
null
UTF-8
R
false
false
599
r
ggchisqtest.Rd.R
library(gginference) ### Name: ggchisqtest ### Title: Plot for Pearson's Chi-squared Test for Count Data ### Aliases: ggchisqtest ### ** Examples ## Chi-squared test for given probabilities x <- c(A = 20, B = 15, C = 25) chisq_test <- chisq.test(x) chisq_test ggchisqtest(chisq_test) x <- c(10, 86, 45, 38, 10) p <- c(0.10, 0.40, 0.20, 0.20, 0.10) chisq_test2 <- chisq.test(x, p = p) chisq_test2 ggchisqtest(chisq_test2) ## Pearson's Chi-squared test library(MASS) sex_smoke <- table(survey$Sex, survey$Smoke) chisq_test3 <- chisq.test(sex_smoke) chisq_test3 ggchisqtest(chisq_test3)
2e6f24c2422051e818148c986d04a953069b53e1
de153ab23bbaf97d45adb6c0489ff8d76b120b0e
/man/summary.td.Rd
23d09d22c70710eb3c0692d61d7e5a1746803918
[]
no_license
petersteiner/tempdisagg
22c9bcaa93be9bdd51c99ad6d0b007c9224db545
d0b125b73c10b253c96671d33c586053becdbea7
refs/heads/master
2021-01-18T06:20:50.159703
2013-06-17T06:03:08
2013-06-17T06:03:08
null
0
0
null
null
null
null
UTF-8
R
false
false
1,697
rd
summary.td.Rd
\name{summary.td} \alias{print.summary.td} \alias{summary.td} \title{Summary of a Temporal Disaggregation} \usage{ \method{summary}{td} (object, ...) \method{print}{summary.td} (x, digits = max(3, getOption("digits") - 3), signif.stars = getOption("show.signif.stars"), ...) } \arguments{ \item{object}{an object of class \code{"td"}, usually, a result of a call to \code{\link{td}}.} \item{x}{an object of class \code{"summary.td"}, usually, a result of a call to \code{summary.td}.} \item{digits}{the number of significant digits to use when printing.} \item{signif.stars}{logical. If \code{TRUE}, 'significance stars' are printed for each coefficient.} \item{\dots}{further arguments passed to or from other methods.} } \value{ \code{summary.td} returns a list containing the summary statistics included in \code{object}, and computes the following additional statistics: \item{n_l}{number of low frequency observations} \item{n}{number of high frequency observations} \item{sigma}{standard deviation of the regression} \item{ar_l}{empirical auto-correlation of the low frequency series} \item{coefficients}{a named matrix containing coefficients, standard deviations, t-values and p-values} The \code{print} method prints the summary output in a similar way as the method for \code{"lm"}. } \description{ \code{summary} method for class "td". } \examples{ data(swisspharma) mod1 <- td(sales.a ~ imports.q + exports.q) summary(mod1) mod2 <- td(sales.a ~ 0, to = "quarterly", method = "uniform") summary(mod2) } \seealso{ \code{\link{td}} for the main function for temporal disaggregation. } \keyword{models} \keyword{ts,}
4d4192b0423e39ab399871c5462260e8910e944b
45e79381152047a7777d50271e38c726013be682
/man/updateExperimentSampleRawData.Rd
3112b0b78b9c59a73d4c9b2f202cbf4c0c3ea012
[]
no_license
ceparman/Core5.3
e13530d3fd7a457ee39935400766badddc5120bd
de8f6e946ca159332979807eba997b5efbf123d4
refs/heads/master
2020-03-23T08:08:06.929458
2019-02-06T14:24:36
2019-02-06T14:24:36
141,309,256
1
0
null
null
null
null
UTF-8
R
false
true
1,397
rd
updateExperimentSampleRawData.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/updateExperimentSampleRawData.R \name{updateExperimentSampleRawData} \alias{updateExperimentSampleRawData} \title{updateExperimentSampleRawData - Update experiment sample raw data.} \usage{ updateExperimentSampleRawData(coreApi, experimentContainerBarcode, cellNum, values, useVerbose = FALSE) } \arguments{ \item{coreApi}{coreApi object with valid jsessionid} \item{experimentContainerBarcode}{User provided barcode as a character string} \item{cellNum}{cell (well) number of container} \item{values}{assay attributes as a list of key-values pairs} \item{useVerbose}{Use verbose communication for debugging} } \value{ RETURN returns a list $entity contains entity information, $response contains the entire http response } \description{ \code{updateExperimentSampleRawData} Update experiment sample assay raw data. } \details{ \code{updateExperimentSampleRawData} Update experiment sample raw data. } \examples{ \dontrun{ api<-CoreAPI("PATH TO JSON FILE") login<- CoreAPIV2::authBasic(api) response<-updateExperimentSampleRawData(login$coreApi,"contBarcode",cellNum=1, values = list(DATA_VALUE = 100 ,CI_ACCEPT = FALSE) updatedEntity <- response$entity CoreAPIV2::logOut(login$coreApi ) response<- CoreAPI::authBasic(coreApi) } } \author{ Craig Parman ngsAnalytics, ngsanalytics.com }
97715259741f1ca1e772d942e33c5eb73042ae6a
9d3b03b16cb2cedbbfa1b293640d47dae62e8b2b
/FilesForCVPaper/Microplastics_CVSummary_2022_03_22.R
8a5ca2cbff277865e2436efdcc1fbfed0eb5a1ae
[]
no_license
pmpk20/PhDPilotSurvey
98e9d408a6a8ad8dd5232cefaa86b5c274838ef3
7941aa6f92bbcb4d314c78a35d6b8ad0cb9edfe9
refs/heads/master
2022-08-17T23:28:15.422613
2022-07-13T22:20:45
2022-07-13T22:20:45
237,419,458
0
0
null
null
null
null
UTF-8
R
false
false
13,578
r
Microplastics_CVSummary_2022_03_22.R
#### Willingness-to-pay for precautionary control of microplastics, a comparison of hybrid choice models. Paper #### ## Function: Includes all models ## Author: Dr Peter King (p.m.king@kent.ac.uk) ## Last change: 22/03/2022 ## TODO: add CV code #------------------------------- #### Replication Information #### #------------------------------- # R version 4.0.2 (2020-06-22) # RStudio Version 1.3.959 # Platform: x86_64-w64-mingw32/x64 (64-bit) # Package information: # stats graphics grDevices utils datasets methods base # Rcpp_1.0.5 BiocManager_1.30.10 compiler_4.0.2 RSGHB_1.2.2 # prettyunits_1.1.1 miscTools_0.6-26 tools_4.0.2 digest_0.6.25 # pkgbuild_1.0.8 lattice_0.20-41 Matrix_1.2-18 cli_2.0.2 # rstudioapi_0.11 maxLik_1.4-4 mvtnorm_1.1-1 SparseM_1.78 # xfun_0.15 coda_0.19-4 MatrixModels_0.4-1 grid_4.0.2 # glue_1.4.1 R6_2.4.1 randtoolbox_1.30.1 processx_3.4.2 # fansi_0.4.1 callr_3.4.3 ps_1.3.3 mcmc_0.9-7 # MASS_7.3-51.6 assertthat_0.2.1 mnormt_2.0.2 xtable_1.8-4 # numDeriv_2016.8-1.1 Deriv_4.1.0 quantreg_5.55 sandwich_2.5-1 # tinytex_0.24 MCMCpack_1.4-9 rngWELL_0.10-6 tmvnsim_1.0-2 # crayon_1.3.4 zoo_1.8-8 apollo_0.2.1 #------------------------------- #### Setup: #### #------------------------------- library(DCchoice) FullSurvey2 <- data.frame(read.csv("FullSurvey2.csv")) #------------------------------- #### Question One: Bid-Only #### #------------------------------- ## Estimation: Q1_SBDCModel_BidOnly <- sbchoice(Q6ResearchResponse ~ 1 | Q6Bid, data = FullSurvey2,dist="logistic") Q1_SBDCModel_BidOnly_WTP <- krCI(Q1_SBDCModel_BidOnly) summary(Q1_SBDCModel_BidOnly) ## WTP (Median): Q1_SBDCModel_BidOnly_WTP$out[4,1] ## Range: cbind(Q1_SBDCModel_BidOnly_WTP$out[4,2],Q1_SBDCModel_BidOnly_WTP$out[4,3]) ## N: nrow(FullSurvey2) ## AIC: AIC(Q1_SBDCModel_BidOnly) ## R2: summary(Q1_SBDCModel_BidOnly)$adjpsdR2 ## LogLik: logLik(Q1_SBDCModel_BidOnly) #------------------------------- #### Question One: Covariates #### #------------------------------- ## Estimation: Q1_SBDCModel_Covariates <- sbchoice(Q6ResearchResponse ~ Q1Gender + Q2Age + Q3Distance + Q16BP + Q18Charity +Q6ResearchCertainty + Q21Experts + IncomeDummy +Q20Consequentiality| Q6Bid, data = FullSurvey2,dist="normal") Q1_SBDCModel_Covariates_WTP <- krCI(Q1_SBDCModel_Covariates) summary(Q1_SBDCModel_Covariates) ## WTP (Median): Q1_SBDCModel_Covariates_WTP$out[4,1] ## Range: cbind(Q1_SBDCModel_Covariates_WTP$out[4,2],Q1_SBDCModel_Covariates_WTP$out[4,3]) ## N: nrow(FullSurvey2) ## AIC: AIC(Q1_SBDCModel_Covariates) BIC(Q1_SBDCModel_Covariates) ## R2: summary(Q1_SBDCModel_Covariates)$adjpsdR2 ## LogLik: logLik(Q1_SBDCModel_Covariates) #------------------------------- #### Question One: Bid-Only Order 0 #### #------------------------------- Order0 <- FullSurvey2[FullSurvey2$Order==0,] ## Estimation: Q1_SBDCModel_BidOnly_Order0 <- sbchoice(Q6ResearchResponse ~ 1 | Q6Bid, data = Order0,dist="logistic") Q1_SBDCModel_BidOnly_Order0_WTP <- krCI(Q1_SBDCModel_BidOnly_Order0) summary(Q1_SBDCModel_BidOnly_Order0) ## WTP (Median): Q1_SBDCModel_BidOnly_Order0_WTP$out[4,1] ## Range: cbind(Q1_SBDCModel_BidOnly_Order0_WTP$out[4,2],Q1_SBDCModel_BidOnly_Order0_WTP$out[4,3]) ## N: nrow(FullSurvey2) ## AIC: AIC(Q1_SBDCModel_BidOnly_Order0) ## R2: summary(Q1_SBDCModel_BidOnly_Order0)$adjpsdR2 ## LogLik: logLik(Q1_SBDCModel_BidOnly_Order0) #------------------------------- #### Question One: Bid-Only Order 1 #### #------------------------------- Order1 <- FullSurvey2[FullSurvey2$Order==1,] ## Estimation: Q1_SBDCModel_BidOnly_Order1 <- sbchoice(Q6ResearchResponse ~ 1 | Q6Bid, data = Order1,dist="logistic") Q1_SBDCModel_BidOnly_Order1_WTP <- krCI(Q1_SBDCModel_BidOnly_Order1) summary(Q1_SBDCModel_BidOnly_Order1) ## WTP (Median): Q1_SBDCModel_BidOnly_Order1_WTP$out[4,1] ## Range: cbind(Q1_SBDCModel_BidOnly_Order1_WTP$out[4,2],Q1_SBDCModel_BidOnly_Order1_WTP$out[4,3]) ## N: nrow(FullSurvey2) ## AIC: AIC(Q1_SBDCModel_BidOnly_Order1) ## R2: summary(Q1_SBDCModel_BidOnly_Order1)$adjpsdR2 ## LogLik: logLik(Q1_SBDCModel_BidOnly_Order1) #------------------------------- #### Question One:Hybrid-Choice #### #------------------------------- Q1_HCM <- readRDS("Q6ICLV_2022_03_21_model.rds") AIC(Q1_HCM) logLik(Q1_HCM) #------------------------------- #### Question Two: Bid-Only #### #------------------------------- ## Estimation: Q2_SBDCModel_BidOnly <- sbchoice(Q7TreatmentResponse ~ 1 | Q7Bid, data = FullSurvey2,dist="logistic") Q2_SBDCModel_BidOnly_WTP <- krCI(Q2_SBDCModel_BidOnly) summary(Q2_SBDCModel_BidOnly) ## WTP (Median): Q2_SBDCModel_BidOnly_WTP$out[4,1] ## Range: cbind(Q2_SBDCModel_BidOnly_WTP$out[4,2],Q2_SBDCModel_BidOnly_WTP$out[4,3]) ## N: nrow(FullSurvey2) ## AIC: AIC(Q2_SBDCModel_BidOnly) ## R2: summary(Q2_SBDCModel_BidOnly)$adjpsdR2 ## LogLik: logLik(Q2_SBDCModel_BidOnly) #------------------------------- #### Question Two: Covariates #### #------------------------------- ## Estimation: Q2_SBDCModel_Covariates <- sbchoice(Q7TreatmentResponse ~ Q1Gender + Q2Age + Q3Distance + Q16BP + Q18Charity +Q7TreatmentCertainty + Q21Experts + IncomeDummy +Q20Consequentiality| Q7Bid, data = FullSurvey2,dist="normal") Q2_SBDCModel_Covariates_WTP <- krCI(Q2_SBDCModel_Covariates) summary(Q2_SBDCModel_Covariates) ## WTP (Median): Q2_SBDCModel_Covariates_WTP$out[4,1] ## Range: cbind(Q2_SBDCModel_Covariates_WTP$out[4,2],Q2_SBDCModel_Covariates_WTP$out[4,3]) ## N: nrow(FullSurvey2) ## AIC: AIC(Q2_SBDCModel_Covariates) BIC(Q2_SBDCModel_Covariates) ## R2: summary(Q2_SBDCModel_Covariates)$adjpsdR2 ## LogLik: logLik(Q2_SBDCModel_Covariates) #------------------------------- #### Question Two: Bid-Only Order 0 #### #------------------------------- Order0 <- FullSurvey2[FullSurvey2$Order==0,] ## Estimation: Q2_SBDCModel_BidOnly_Order0 <- sbchoice(Q7TreatmentResponse ~ 1 | Q7Bid, data = Order0,dist="logistic") Q2_SBDCModel_BidOnly_Order0_WTP <- krCI(Q2_SBDCModel_BidOnly_Order0) summary(Q2_SBDCModel_BidOnly_Order0) ## WTP (Median): Q2_SBDCModel_BidOnly_Order0_WTP$out[4,1] ## Range: cbind(Q2_SBDCModel_BidOnly_Order0_WTP$out[4,2],Q2_SBDCModel_BidOnly_Order0_WTP$out[4,3]) ## N: nrow(FullSurvey2) ## AIC: AIC(Q2_SBDCModel_BidOnly_Order0) ## R2: summary(Q2_SBDCModel_BidOnly_Order0)$adjpsdR2 ## LogLik: logLik(Q2_SBDCModel_BidOnly_Order0) #------------------------------- #### Question Two: Bid-Only Order 1 #### #------------------------------- Order1 <- FullSurvey2[FullSurvey2$Order==1,] ## Estimation: Q2_SBDCModel_BidOnly_Order1 <- sbchoice(Q7TreatmentResponse ~ 1 | Q7Bid, data = Order1,dist="logistic") Q2_SBDCModel_BidOnly_Order1_WTP <- krCI(Q2_SBDCModel_BidOnly_Order1) summary(Q2_SBDCModel_BidOnly_Order1) ## WTP (Median): Q2_SBDCModel_BidOnly_Order1_WTP$out[4,1] ## Range: cbind(Q2_SBDCModel_BidOnly_Order1_WTP$out[4,2],Q2_SBDCModel_BidOnly_Order1_WTP$out[4,3]) ## N: nrow(FullSurvey2) ## AIC: AIC(Q2_SBDCModel_BidOnly_Order1) ## R2: Order0 <- FullSurvey2[FullSurvey2$Order==0,] ## Estimation: Q2_SBDCModel_BidOnly_Order0 <- sbchoice(Q7TreatmentResponse ~ 1 | Q7Bid, data = Order0,dist="logistic") Q2_SBDCModel_BidOnly_Order0_WTP <- krCI(Q2_SBDCModel_BidOnly_Order0) summary(Q2_SBDCModel_BidOnly_Order0) ## WTP (Median): Q2_SBDCModel_BidOnly_Order0_WTP$out[4,1] ## Range: cbind(Q2_SBDCModel_BidOnly_Order0_WTP$out[4,2],Q2_SBDCModel_BidOnly_Order0_WTP$out[4,3]) ## N: nrow(FullSurvey2) ## AIC: AIC(Q2_SBDCModel_BidOnly_Order0) ## R2: summary(Q2_SBDCModel_BidOnly_Order0)$adjpsdR2 ## LogLik: logLik(Q2_SBDCModel_BidOnly_Order0) #------------------------------- #### Question Two: Bid-Only Order 1 #### #------------------------------- Order1 <- FullSurvey2[FullSurvey2$Order==1,] ## Estimation: Q2_SBDCModel_BidOnly_Order1 <- sbchoice(Q7TreatmentResponse ~ 1 | Q7Bid, data = Order1,dist="logistic") Q2_SBDCModel_BidOnly_Order1_WTP <- krCI(Q2_SBDCModel_BidOnly_Order1) summary(Q2_SBDCModel_BidOnly_Order1) ## WTP (Median): Q2_SBDCModel_BidOnly_Order1_WTP$out[4,1] ## Range: cbind(Q2_SBDCModel_BidOnly_Order1_WTP$out[4,2],Q2_SBDCModel_BidOnly_Order1_WTP$out[4,3]) ## N: nrow(FullSurvey2) ## AIC: AIC(Q2_SBDCModel_BidOnly_Order1) ## R2: summary(Q2_SBDCModel_BidOnly_Order1)$adjpsdR2 ## LogLik: logLik(Q2_SBDCModel_BidOnly_Order1) summary(Q2_SBDCModel_BidOnly_Order1)$adjpsdR2 ## LogLik: logLik(Q2_SBDCModel_BidOnly_Order1) #------------------------------- #### Question Two:Hybrid-Choice #### #------------------------------- Q2_HCM <- readRDS("Q7ICLV_2022_03_21_model.rds") AIC(Q2_HCM) logLik(Q2_HCM) #------------------------------- #### Fitting individual-level WTP here #### #------------------------------- #### Median #### Q6_SBDCModel_WTP <- data.frame(apply(FullSurvey2, 1, function(i) c(krCI(Q6_SBDCModel,individual = data.frame(Q1Gender = FullSurvey2$Q1Gender[i], Q2Age = FullSurvey2$Q2Age[i], Q3Distance = FullSurvey2$Q3Distance[i],Q4Trips = FullSurvey2$Q4Trips[i], Q16BP = FullSurvey2$Q16BP[i],Q18Charity = FullSurvey2$Q18Charity[i],Q21Experts = FullSurvey2$Q21Experts[i],Q22Education = FullSurvey2$Q22Education[i], Q23Employment = FullSurvey2$Q23Employment[i], Q24AIncome = FullSurvey2$Q24AIncome[i],Timing=FullSurvey2$Timing[i]))$out[1,1]))) Q7_SBDCModel_WTP <- data.frame(apply(FullSurvey2, 1, function(i) c(krCI(Q7_SBDCModel,individual = data.frame(Q1Gender = FullSurvey2$Q1Gender[i], Q2Age = FullSurvey2$Q2Age[i], Q3Distance = FullSurvey2$Q3Distance[i],Q4Trips = FullSurvey2$Q4Trips[i], Q16BP = FullSurvey2$Q16BP[i],Q18Charity = FullSurvey2$Q18Charity[i],Q21Experts = FullSurvey2$Q21Experts[i],Q22Education = FullSurvey2$Q22Education[i], Q23Employment = FullSurvey2$Q23Employment[i], Q24AIncome = FullSurvey2$Q24AIncome[i],Timing=FullSurvey2$Timing[i]))$out[1,1]))) saveRDS(Q6_SBDCModel_WTP,"Q6_SBDCModel_WTP.rds") saveRDS(Q7_SBDCModel_WTP,"Q7_SBDCModel_WTP.rds") #### Lower Bounds #### Q6_SBDCModel_WTP_Lower <- data.frame("Q1WTP"=apply(FullSurvey2, 1, function(i) c(krCI(Q6_SBDCModel,individual = data.frame(Q1Gender = FullSurvey2$Q1Gender[i], Q2Age = FullSurvey2$Q2Age[i], Q3Distance = FullSurvey2$Q3Distance[i],Q4Trips = FullSurvey2$Q4Trips[i], Q16BP = FullSurvey2$Q16BP[i],Q18Charity = FullSurvey2$Q18Charity[i],Q21Experts = FullSurvey2$Q21Experts[i],Q22Education = FullSurvey2$Q22Education[i], Q23Employment = FullSurvey2$Q23Employment[i], Q24AIncome = FullSurvey2$Q24AIncome[i],Timing=FullSurvey2$Timing[i]))$out[1,2]))) Q7_SBDCModel_WTP_Lower <- data.frame(apply(FullSurvey2, 1, function(i) c(krCI(Q7_SBDCModel,individual = data.frame(Q1Gender = FullSurvey2$Q1Gender[i], Q2Age = FullSurvey2$Q2Age[i], Q3Distance = FullSurvey2$Q3Distance[i],Q4Trips = FullSurvey2$Q4Trips[i], Q16BP = FullSurvey2$Q16BP[i],Q18Charity = FullSurvey2$Q18Charity[i],Q21Experts = FullSurvey2$Q21Experts[i],Q22Education = FullSurvey2$Q22Education[i], Q23Employment = FullSurvey2$Q23Employment[i], Q24AIncome = FullSurvey2$Q24AIncome[i],Timing=FullSurvey2$Timing[i]))$out[1,2]))) saveRDS(Q6_SBDCModel_WTP_Lower,"Q6_SBDCModel_WTP_Lower.rds") saveRDS(Q7_SBDCModel_WTP_Lower,"Q7_SBDCModel_WTP_Lower") #### Upper Bounds #### Q6_SBDCModel_WTP_Upper <- data.frame(apply(FullSurvey2, 1, function(i) c(krCI(Q6_SBDCModel,individual = data.frame(Q1Gender = FullSurvey2$Q1Gender[i], Q2Age = FullSurvey2$Q2Age[i], Q3Distance = FullSurvey2$Q3Distance[i],Q4Trips = FullSurvey2$Q4Trips[i], Q16BP = FullSurvey2$Q16BP[i],Q18Charity = FullSurvey2$Q18Charity[i],Q21Experts = FullSurvey2$Q21Experts[i],Q22Education = FullSurvey2$Q22Education[i], Q23Employment = FullSurvey2$Q23Employment[i], Q24AIncome = FullSurvey2$Q24AIncome[i],Timing=FullSurvey2$Timing[i]))$out[1,3]))) Q7_SBDCModel_WTP_Upper <- data.frame(apply(FullSurvey2, 1, function(i) c(krCI(Q7_SBDCModel,individual = data.frame(Q1Gender = FullSurvey2$Q1Gender[i], Q2Age = FullSurvey2$Q2Age[i], Q3Distance = FullSurvey2$Q3Distance[i],Q4Trips = FullSurvey2$Q4Trips[i], Q16BP = FullSurvey2$Q16BP[i],Q18Charity = FullSurvey2$Q18Charity[i],Q21Experts = FullSurvey2$Q21Experts[i],Q22Education = FullSurvey2$Q22Education[i], Q23Employment = FullSurvey2$Q23Employment[i], Q24AIncome = FullSurvey2$Q24AIncome[i],Timing=FullSurvey2$Timing[i]))$out[1,3]))) saveRDS(Q6_SBDCModel_WTP_Upper,"Q6_SBDCModel_WTP_Upper.rds") saveRDS(Q7_SBDCModel_WTP_Upper,"Q7_SBDCModel_WTP_Upper.rds") #### End Of Script ####
18fbca60b97e14c43570d8e16d15d76af4ae5eca
a47ce30f5112b01d5ab3e790a1b51c910f3cf1c3
/B_analysts_sources_github/pablobarbera/Rfacebook/getEvents.R
0304a0d9a6be5033fa434bbeabd622d9dc351be3
[]
no_license
Irbis3/crantasticScrapper
6b6d7596344115343cfd934d3902b85fbfdd7295
7ec91721565ae7c9e2d0e098598ed86e29375567
refs/heads/master
2020-03-09T04:03:51.955742
2018-04-16T09:41:39
2018-04-16T09:41:39
128,578,890
5
0
null
null
null
null
UTF-8
R
false
false
1,559
r
getEvents.R
#' @rdname getEvents #' @export #' #' @title #' Extract list of events from a public Facebook page or group #' #' @description #' \code{getEvents} retrieves event information from a public Facebook group or page. #' #' @author #' Pablo Barbera \email{pbarbera@@usc.edu} #' @seealso \code{\link{getPage}}, \code{\link{fbOAuth}} #' #' @param page Facebook ID for the group or page. #' #' @param token Either a temporary access token created at #' \url{https://developers.facebook.com/tools/explorer} or the OAuth token #' created with \code{fbOAuth}. #' #' @param api API version. e.g. "v2.8". \code{NULL} is the default. #' #' @examples \dontrun{ #' load("fb_oauth") #' ## Downloading events from Playa Vista Farmers' Market #' events <- getEvents(page="playavistaFM", token=fb_oauth) #' } getEvents <- function(page, token, api="v2.9"){ url <- paste0('https://graph.facebook.com/', page, '?fields=events{description,name,start_time,end_time,place,id,attending_count,', 'declined_count,maybe_count,noreply_count}') # making query content <- callAPI(url=url, token=token, api=api) l <- length(content$events$data); cat(l, "events ") ## retrying 3 times if error was found error <- 0 while (length(content$error_code)>0){ cat("Error!\n") Sys.sleep(0.5) error <- error + 1 content <- callAPI(url=url, token=token, api=api) if (error==3){ stop(content$error_msg) } } if (length(content$events$data)==0){ message("No public events were found") return(data.frame()) } df <- eventDataToDF(content$events$data) return(df) }
5f8f0426562dea45bd4458f6e159b26fbf2948ed
6700f9cb775b64f532952045b72eeeba097d4e7f
/R/taxmap--class.R
3ede0c4c90784a0362d1c53db016c04b317fd87a
[ "MIT" ]
permissive
grunwald/taxa
c3c24a19d1b3844df0dd6d7dee8e51f87859743a
9f58cd83afb793797c362d18a48b0d77f5a931ad
refs/heads/master
2021-01-20T12:48:54.723730
2017-05-03T23:56:40
2017-05-03T23:56:40
null
0
0
null
null
null
null
UTF-8
R
false
false
26,003
r
taxmap--class.R
#' Taxmap class #' #' @export #' @param ... Any number of object of class [hierarchy()] or character vectors. #' @param data A list of tables with data associated with the taxa. #' @return An `R6Class` object of class [taxmap()] #' #' @details on initialize, function sorts the taxon list based on rank (if rank #' information is available), see [ranks_ref] for the reference rank names and #' orders #' #' @template taxmapegs taxmap <- function(..., data = NULL) { Taxmap$new(..., data = data) } Taxmap <- R6::R6Class( "Taxmap", inherit = Taxonomy, public = list( data = list(), funcs = list(), initialize = function(..., data = list(), funcs = list()) { # Call `taxonomy` constructor super$initialize(...) # Make sure `data` is in the right format and add to object self$data <- validate_taxmap_data(data, self$input_ids) # Make sure `funcs` is in the right format and add to object self$funcs <- validate_taxmap_funcs(funcs) }, print = function(indent = "", max_rows = 3, max_items = 3, max_width = getOption("width") - 10) { # Call `taxonomy` print method taxonomy_output <- paste0( paste0(capture.output(super$print(indent = indent)), collapse = "\n"), "\n" ) cat(gsub(taxonomy_output, pattern = "Taxonomy", replacement = "Taxmap")) # Print a subset of each item, up to a max number, then just print names cat(paste0(" ", length(self$data), " data sets:\n")) if (length(self$data) > 0) { for (i in 1:min(c(max_items, length(self$data)))) { print_item(self$data[[i]], name = names(self$data[i]), max_rows = max_rows, max_width = max_width, prefix = " ") } if (length(self$data) > max_items) { cat(paste0(" And ", length(self$data) - max_items, " more data sets:")) limited_print(names(self$data)[(max_items + 1):length(self$data)]) } } # Print the names of functions cat(paste0(" ", length(self$funcs), " functions:\n")) limited_print(names(self$funcs)) invisible(self) }, # Returns the names of things to be accessible using non-standard evaluation all_names = function(tables = TRUE, funcs = TRUE, others = TRUE, builtin_funcs = TRUE, warn = FALSE) { output <- c() # Add functions included in the package if (builtin_funcs) { output <- c(output, private$nse_accessible_funcs) } # Get column names in each table, removing 'taxon_id' is_table <- vapply(self$data, is.data.frame, logical(1)) if (tables && length(self$data[is_table]) > 0) { table_col_names <- unlist(lapply(self$data[is_table], colnames)) names(table_col_names) <- paste0("data$", rep(names(self$data[is_table]), vapply(self$data[is_table], ncol, integer(1)))) table_col_names <- table_col_names[table_col_names != "taxon_id"] output <- c(output, table_col_names) } # Get other object names in data is_other <- !is_table if (others && length(self$data[is_other]) > 0) { other_names <- names(self$data[is_other]) names(other_names) <- rep("data", length(other_names)) output <- c(output, other_names) } # Get function names if (funcs && length(self$funcs) > 0) { func_names <- names(self$funcs) names(func_names) <- rep("funcs", length(func_names)) output <- c(output, func_names) } # Check for duplicates if (warn) { duplicated_names <- unique(output[duplicated(output)]) if (length(duplicated_names) > 0) { warning(paste0("The following names are used more than once: ", paste0(duplicated_names, collapse = ", "))) } } # Add the name to the name of the name and return names(output) <- paste0(names(output), ifelse(names(output) == "", "", "$"), output) return(output) }, # Looks for names of data in a expression for use with NSE names_used = function(...) { decompose <- function(x) { if (class(x) %in% c("call", "(", "{")) { return(lapply(1:length(x), function(i) decompose(x[[i]]))) } else { return(as.character(x)) } } expressions <- lapply(lazyeval::lazy_dots(...), function(x) x$expr) if (length(expressions) == 0) { return(character(0)) } else { names_used <- unlist(lapply(1:length(expressions), function(i) decompose(expressions[[i]]))) my_names <- self$all_names() return(my_names[my_names %in% names_used]) } }, # Get data by name get_data = function(name = NULL, ...) { # Get default if name is NULL if (is.null(name)) { name = self$all_names(...) } # Check that names provided are valid my_names <- self$all_names(...) if (any(unknown <- !name %in% my_names)) { stop(paste0("Cannot find the following data: ", paste0(name[unknown], collapse = ", "), "\n ", "Valid choices include: ", paste0(my_names, collapse = ", "), "\n ")) } # Format output name <- my_names[match(name, my_names)] output <- lapply(names(name), function(x) eval(parse(text = paste0("self$", x)))) names(output) <- name # Run any functions and return their results instead is_func <- vapply(output, is.function, logical(1)) output[is_func] <- lapply(output[is_func], function(f) { if (length(formals(f)) == 0) { return(f()) } else { return(f(self)) } }) return(output) }, # Get a list of all data in an expression used with non-standard evaluation data_used = function(...) { my_names_used <- self$names_used(...) self$get_data(my_names_used) }, obs = function(data, subset = NULL, recursive = TRUE, simplify = FALSE) { # Parse arguments subset <- format_taxon_subset(names(self$taxa), subset) if (length(data) == 1 && # data is name/index of dataset in object (data %in% names(self$data) || is.integer(data))) { obs_taxon_ids <- extract_taxon_ids(self$data[[data]]) } else { obs_taxon_ids <- extract_taxon_ids(data) } # Get observations of taxa if (is.logical(recursive) && recursive == FALSE) { recursive = 0 } if (recursive || is.numeric(recursive)) { my_subtaxa <- self$subtaxa(subset = unname(subset), recursive = recursive, include_input = TRUE, return_type = "index") #unname is neede for some reason.. something to look into... } else { my_subtaxa <- subset } obs_taxon_index <- match(obs_taxon_ids, self$taxon_ids()) obs_key <- split(seq_along(obs_taxon_ids), obs_taxon_index) output <- stats::setNames( lapply(my_subtaxa,function(x) unname(unlist(obs_key[as.character(x)]))), names(subset) ) is_null <- vapply(output, is.null, logical(1)) output[is_null] <- lapply(1:sum(is_null), function(x) numeric(0)) # Reduce dimensionality if (simplify) { output <- unique(unname(unlist(output))) } return(output) }, filter_taxa = function(..., subtaxa = FALSE, supertaxa = FALSE, taxonless = FALSE, reassign_obs = TRUE, reassign_taxa = TRUE, invert = FALSE) { # non-standard argument evaluation selection <- lazyeval::lazy_eval(lazyeval::lazy_dots(...), data = self$data_used(...)) # convert taxon_ids to logical is_char <- vapply(selection, is.character, logical(1)) selection[is_char] <- lapply(selection[is_char], function(x) self$taxon_ids() %in% x) # convert indexes to logical is_index <- vapply(selection, is.numeric, logical(1)) selection[is_index] <- lapply(selection[is_index], function(x) 1:nrow(self$edge_list) %in% x) # combine filters selection <- Reduce(`&`, selection) # default to all taxa if no selection is provided if (is.null(selection)) { selection <- rep(TRUE, length(self$taxon_ids())) } # Get taxa of subset if (is.logical(subtaxa) && subtaxa == FALSE) { subtaxa = 0 } if (is.logical(supertaxa) && supertaxa == FALSE) { supertaxa = 0 } taxa_subset <- unique(c(which(selection), self$subtaxa(subset = selection, recursive = subtaxa, return_type = "index", include_input = FALSE, simplify = TRUE), self$supertaxa(subset = selection, recursive = supertaxa, return_type = "index", na = FALSE, simplify = TRUE, include_input = FALSE) )) # Invert selection if (invert) { taxa_subset <- (1:nrow(self$edge_list))[-taxa_subset] } # Reassign taxonless observations reassign_obs <- parse_possibly_named_logical( reassign_obs, self$data, default = formals(self$filter_taxa)$reassign_obs ) process_one <- function(data_index) { reassign_one <- function(parents) { included_parents <- parents[parents %in% taxa_subset] return(self$taxon_ids()[included_parents[1]]) } # Get the taxon ids of the current object if (is.null((data_taxon_ids <- get_data_taxon_ids(self$data[[data_index]])))) { return(NULL) # if there is no taxon id info, dont change anything } # Generate replacement taxon ids to_reassign <- ! data_taxon_ids %in% self$taxon_ids()[taxa_subset] supertaxa_key <- self$supertaxa( subset = unique(data_taxon_ids[to_reassign]), recursive = TRUE, simplify = FALSE, include_input = FALSE, return_type = "index", na = FALSE ) reassign_key <- vapply(supertaxa_key, reassign_one, character(1)) new_data_taxon_ids <- reassign_key[data_taxon_ids[to_reassign]] # Replace taxon ids if (is.data.frame(self$data[[data_index]])) { self$data[[data_index]][to_reassign, "taxon_id"] <- new_data_taxon_ids } else { names(self$data[[data_index]])[to_reassign] <- new_data_taxon_ids } } unused_output <- lapply(seq_along(self$data)[reassign_obs], process_one) # Reassign subtaxa if (reassign_taxa) { reassign_one <- function(parents) { included_parents <- parents[parents %in% taxa_subset] return(self$taxon_ids()[included_parents[1]]) } to_reassign <- ! self$edge_list$from %in% self$taxon_ids()[taxa_subset] supertaxa_key <- self$supertaxa( subset = unique(self$taxon_ids()[to_reassign]), recursive = TRUE, simplify = FALSE, include_input = FALSE, return_type = "index", na = FALSE) reassign_key <- vapply(supertaxa_key, reassign_one, character(1) ) self$edge_list[to_reassign, "from"] <- reassign_key[self$taxon_ids()[to_reassign]] } # Remove taxonless observations taxonless <- parse_possibly_named_logical( taxonless, self$data, default = formals(self$filter_taxa)$taxonless ) process_one <- function(my_index) { # Get the taxon ids of the current object if (is.null((data_taxon_ids <- get_data_taxon_ids(self$data[[my_index]])))) { return(NULL) # if there is no taxon id info, dont change anything } obs_subset <- data_taxon_ids %in% self$taxon_ids()[taxa_subset] private$remove_obs(dataset = my_index, indexes = obs_subset, unname_only = taxonless[my_index]) } unused_output <- lapply(seq_along(self$data), process_one) # Remove filtered taxa self$taxa <- self$taxa[self$taxon_ids()[taxa_subset]] self$edge_list <- self$edge_list[taxa_subset, , drop = FALSE] self$edge_list[! self$edge_list$from %in% self$taxon_ids(), "from"] <- as.character(NA) return(self) }, filter_obs = function(target, ..., unobserved = TRUE) { # Check that the target data exists private$check_dataset_name(target) # non-standard argument evaluation selection <- lazyeval::lazy_eval(lazyeval::lazy_dots(...), data = self$data_used(...)) # If no selection is supplied, match all rows if (length(selection) == 0) { selection <- list(seq_len(nrow(self$data[[target]]))) } # convert taxon_ids to indexes is_char <- vapply(selection, is.character, logical(1)) if (sum(is_char) > 0) { stop(paste("observation filtering with taxon IDs is not currently", "supported. If you want to filter observation by taxon IDs,", "use something like: `obj$data$my_target$taxon_ids %in%", "my_subset`")) } # convert logical to indexes is_logical <- vapply(selection, is.logical, logical(1)) selection[is_logical] <- lapply(selection[is_logical], which) # combine filters intersect_with_dups <-function(a, b) { rep(sort(intersect(a, b)), pmin(table(a[a %in% b]), table(b[b %in% a]))) } selection <- Reduce(intersect_with_dups, selection) # Remove observations data_taxon_ids <- get_data_taxon_ids(self$data[[target]]) private$remove_obs(dataset = target, indexes = selection) # Remove unobserved taxa if (! unobserved & ! is.null(data_taxon_ids)) { unobserved_taxa <- self$supertaxa(unique(data_taxon_ids[-selection]), na = FALSE, recursive = TRUE, simplify = TRUE, include_input = TRUE, return_type = "index") taxa_to_remove <- 1:nrow(self$edge_list) %in% unobserved_taxa & vapply(self$obs(target), length, numeric(1)) == 0 self$taxa <- self$taxa[self$taxon_ids()[! taxa_to_remove]] self$edge_list <- self$edge_list[! taxa_to_remove, , drop = FALSE] self$edge_list[! self$edge_list$from %in% self$taxon_ids(), "from"] <- as.character(NA) } return(self) }, select_obs = function(target, ...) { # Check that the target data exists private$check_dataset_name(target) # Check that the target is a table if (! is.data.frame(self$data[[target]])) { stop(paste0('The dataset "', target, '" is not a table, so columns cannot be selected.')) } self$data[[target]] <- dplyr::bind_cols(self$data[[target]][ , c("taxon_id"), drop = FALSE], dplyr::select(self$data[[target]], ...)) return(self) }, mutate_obs = function(target, ...) { # Check that the target data exists private$check_dataset_name(target) # Check that the target is a table if (! is.data.frame(self$data[[target]])) { stop(paste0('The dataset "', target, '" is not a table, so columns cannot be selected.')) } data_used <- self$data_used(...) unevaluated <- lazyeval::lazy_dots(...) for (index in seq_along(unevaluated)) { new_col <- lazyeval::lazy_eval(unevaluated[index], data = data_used) # Allow this col to be used in evaluating the next cols data_used <- c(data_used, new_col) self$data[[target]][[names(new_col)]] <- new_col[[1]] } return(self) }, transmute_obs = function(target, ...) { # Check that the target data exists private$check_dataset_name(target) # Check that the target is a table if (! is.data.frame(self$data[[target]])) { stop(paste0('The dataset "', target, '" is not a table, so columns cannot be selected.')) } if ("taxon_id" %in% colnames(self$data[[target]])) { result <- list(taxon_id = self$data[[target]]$taxon_id) } else { result <- list() } data_used <- self$data_used(...) unevaluated <- lazyeval::lazy_dots(...) for (index in seq_along(unevaluated)) { new_col <- lazyeval::lazy_eval(unevaluated[index], data = data_used) # Allow this col to be used in evaluating the next cols data_used <- c(data_used, new_col) result[[names(new_col)]] <- new_col[[1]] } self$data[[target]] <- tibble::as_tibble(result) return(self) }, arrange_obs = function(target, ...) { # Check that the target data exists private$check_dataset_name(target) # Sort observations data_used <- self$data_used(...) data_used <- data_used[! names(data_used) %in% names(self$data[[target]])] if (is.data.frame(self$data[[target]])) { # if it is a table if (length(data_used) == 0) { self$data[[target]] <- dplyr::arrange(self$data[[target]], ...) } else { target_with_extra_cols <- dplyr::bind_cols(data_used, self$data[[target]]) self$data[[target]] <- dplyr::arrange(target_with_extra_cols, ...)[, -seq_along(data_used)] } } else { # if it is a list or vector dummy_table <- data.frame(index = seq_along(self$data[[target]])) if (length(data_used)!= 0) { dummy_table <- dplyr::bind_cols(data_used, dummy_table) } dummy_table <- dplyr::arrange(dummy_table, ...) self$data[[target]] <- self$data[[target]][dummy_table$index] } return(self) }, arrange_taxa = function(...) { data_used <- self$data_used(...) data_used <- data_used[! names(data_used) %in% names(self$edge_list)] if (length(data_used) == 0) { self$edge_list <- dplyr::arrange(self$edge_list, ...) } else { target_with_extra_cols <- dplyr::bind_cols(data_used, self$edge_list) self$edge_list <- dplyr::arrange(target_with_extra_cols, ...)[, -seq_along(data_used)] } return(self) }, sample_n_obs = function(target, size, replace = FALSE, taxon_weight = NULL, obs_weight = NULL, use_supertaxa = TRUE, collapse_func = mean, ...) { # Check that the target data exists private$check_dataset_name(target) # non-standard argument evaluation data_used <- eval(substitute(self$data_used(taxon_weight, obs_weight))) taxon_weight <- lazyeval::lazy_eval(lazyeval::lazy(taxon_weight), data = data_used) obs_weight <- lazyeval::lazy_eval(lazyeval::lazy(obs_weight), data = data_used) # Get length of target if (is.data.frame(self$data[[target]])) { target_length <- nrow(self$data[[target]]) } else { target_length <- length(self$data[[target]]) } # Calculate taxon component of taxon weights if (is.null(taxon_weight)) { obs_taxon_weight <- rep(1, target_length) } else { obs_index <- match(get_data_taxon_ids(self$data[[target]]), self$taxon_ids()) my_supertaxa <- self$supertaxa(recursive = use_supertaxa, simplify = FALSE, include_input = TRUE, return_type = "index", na = FALSE) taxon_weight_product <- vapply( my_supertaxa, function(x) collapse_func(taxon_weight[x]), numeric(1) ) obs_taxon_weight <- taxon_weight_product[obs_index] } obs_taxon_weight <- obs_taxon_weight / sum(obs_taxon_weight) # Calculate observation component of observation weights if (is.null(obs_weight)) { obs_weight <- rep(1, target_length) } obs_weight <- obs_weight / sum(obs_weight) # Combine observation and taxon weight components combine_func <- prod weight <- mapply(obs_taxon_weight, obs_weight, FUN = function(x, y) combine_func(c(x,y))) weight <- weight / sum(weight) # Sample observations sampled_rows <- sample.int(target_length, size = size, replace = replace, prob = weight) self$filter_obs(target, sampled_rows, ...) }, sample_frac_obs = function(target, size, replace = FALSE, taxon_weight = NULL, obs_weight = NULL, use_supertaxa = TRUE, collapse_func = mean, ...) { # Get length of target if (is.data.frame(self$data[[target]])) { target_length <- nrow(self$data[[target]]) } else { target_length <- length(self$data[[target]]) } self$sample_n_obs(target = target, size = size * target_length, replace = replace, taxon_weight = taxon_weight, obs_weight = obs_weight, use_supertaxa = use_supertaxa, collapse_func = collapse_func, ...) }, sample_n_taxa = function(size, taxon_weight = NULL, obs_weight = NULL, obs_target = NULL, use_subtaxa = TRUE, collapse_func = mean, ...) { # non-standard argument evaluation data_used <- eval(substitute(self$data_used(taxon_weight, obs_weight))) taxon_weight <- lazyeval::lazy_eval(lazyeval::lazy(taxon_weight), data = data_used) obs_weight <- lazyeval::lazy_eval(lazyeval::lazy(obs_weight), data = data_used) # Calculate observation component of taxon weights if (is.null(obs_weight)) { taxon_obs_weight <- rep(1, nrow(self$edge_list)) } else { if (is.null(obs_target)) { stop(paste("If the option `obs_weight` is used, then `obs_target`", "must also be defined.")) } my_obs <- self$obs(obs_target, recursive = use_subtaxa, simplify = FALSE) taxon_obs_weight <- vapply(my_obs, function(x) collapse_func(obs_weight[x]), numeric(1)) } taxon_obs_weight <- taxon_obs_weight / sum(taxon_obs_weight) # Calculate taxon component of taxon weights if (is.null(taxon_weight)) { taxon_weight <- rep(1, nrow(self$edge_list)) } taxon_weight <- taxon_weight / sum(taxon_weight) # Combine observation and taxon weight components combine_func <- prod weight <- mapply(taxon_weight, taxon_obs_weight, FUN = function(x, y) combine_func(c(x,y))) weight <- weight / sum(weight) # Sample observations sampled_rows <- sample.int(nrow(self$edge_list), size = size, replace = FALSE, prob = weight) self$filter_taxa(sampled_rows, ...) }, sample_frac_taxa = function(size = 1, taxon_weight = NULL, obs_weight = NULL, obs_target = NULL, use_subtaxa = TRUE, collapse_func = mean, ...) { self$sample_n_taxa(size = size * nrow(self$edge_list), taxon_weight = taxon_weight, obs_weight = obs_weight, obs_target = obs_target, use_subtaxa = use_subtaxa, collapse_func = collapse_func, ...) }, n_obs = function(target) { vapply(self$obs(target, recursive = TRUE, simplify = FALSE), length, numeric(1)) }, n_obs_1 = function(target) { vapply(self$obs(target, recursive = FALSE, simplify = FALSE), length, numeric(1)) } ), private = list( nse_accessible_funcs = c("taxon_names", "taxon_ids", "n_supertaxa", "n_subtaxa", "n_subtaxa_1"), check_dataset_name = function(target) { if (! target %in% names(self$data)) { stop(paste0("The target `", target, "` is not the name of a data set.", " Valid targets include: ", paste0(names(self$data), collapse = ", "))) } }, # Remove observations from a particular dataset or just remove the taxon ids remove_obs = function(dataset, indexes, unname_only = FALSE) { if (unname_only) { if (is.data.frame(self$data[[dataset]])) { self$data[[dataset]][! indexes, "taxon_id"] <- as.character(NA) } else { names(self$data[[dataset]])[! indexes] <- as.character(NA) } } else { if (is.data.frame(self$data[[dataset]])) { self$data[[dataset]] <- self$data[[dataset]][indexes, , drop = FALSE] } else { self$data[[dataset]] <- self$data[[dataset]][indexes] } } } ) )
7a988f6220a5332f58bfd612818a5cdd70d6dd32
90f2d605da66140e9068e8f301e61c88a5504d99
/R/microclimate_model_WP.R
e34a3b59d16dd761b9db795921d763d1cd959ec3
[]
no_license
dhduncan/Rabbit_abundance
2f90709b0ed49371869c175cd869aae9e9991161
41fb341e91031a8da330471e8f561758e831efb4
refs/heads/master
2020-06-13T08:45:23.548188
2020-02-26T05:46:52
2020-02-26T05:46:52
194,604,180
0
1
null
2019-07-25T11:52:26
2019-07-01T05:16:51
R
UTF-8
R
false
false
6,536
r
microclimate_model_WP.R
########################################################################### ## 01 - Microclimate model for WNP ########## ########################################################################### ## Background: # Set up version of the microclimate model for and ... ## Required output: Want to feed into model of rabbit abundance, soil moisture/potential plant growth (??), # Interested in variation between transects + variation through time. ################################################################################# # Set-up ######################################## ################################################################################# install.packages('microclima') devtools::install_github('mrke/NicheMapR') library(NicheMapR) library(lubridate) ################################################################################# # Parameters ######################################## ################################################################################# # Simulation settings loc<-c(143.463718, -37.431736) ystart<-2016 yfinish<-2017 # Env parameters for simulation Usrhyt<-0.1 minshade<-0 maxshade<-30 cap=1 # add organic layer of soil at top? See 2014 microclim paper for discussion. # soil mositure runmoist<-1 # run soil moisture model? If have yes best to add burn in time before period of interest. LAI = 0.1 #leaf area index, used to partition traspiration/evaporation from PET #microclima.LAI = 0 # leaf area index, used by package microclima for radiation calcs - need to look into these #microclima.LOR = 1 # leaf orientation for package microclima radiation calcs - need to look into these #Source of env data opendap = 0 # opendap = 1, query met grids via opendap - not sure if this works?? dailywind = 0 # 0 = no, 1 = yes, will get error if don't have access to data and try to run with it on microclima = 1 # Use microclima and elevatr package to adjust solar radiation for terrain? 1=yes, 0=no soildata = 1 # Extract emissivities from gridded data? 1=yes, 0=no soilgrids = 1 # query soilgrids.org database for soil hydraulic properties? terrain = 1 # Use 250m resolution terrain data? 1=yes, 0=no ################################################################################# # Run model ######################################## ################################################################################# setwd("~/Students/Dave_WP") micro <- micro_aust(loc = loc, ystart=ystart, yfinish=yfinish, Usrhyt = Usrhyt, minshade=minshade, maxshade=maxshade,cap=cap, LAI=LAI, runmoist=runmoist,opendap = opendap, dailywind = dailywind, microclima = microclima, soildata=soildata, soilgrids = soilgrids, terrain=terrain, write_input=1) metout<-as.data.frame(micro$metout) shadmet<-as.data.frame(micro$shadmet) soil<-as.data.frame(micro$soil) shadsoil<-as.data.frame(micro$shadsoil) soilmoist<-as.data.frame(micro$soilmoist) ## metout$dates<-seq(dmy_hm(paste0("01/01/",ystart,"00:00")), dmy_hm(paste0("31/12/",yfinish,"23:00")), by="hour") shadmet$dates<-soil$dates<-shadsoil$dates<-metout$dates ################################################################################# # Old code to run model - query databases ###################################### ################################################################################# ystart <- 2016 # start year yfinish <- 2017 # end year nyears<-yfinish-ystart+1 # integer, number of years for which to run the microclimate model stD<-paste0(ystart,"-01-01 00:00:00") # start date endD<-paste0(yfinish,"-12-31 23:00:00") # end date dates<-seq(ymd_hms(stD),ymd_hms(endD),by='hours') #### STEP 1: Run microclimate model #### ## Run the micro_aust function for each site. longlat<-c(142.04, -35.38) # Wyperfield Usrhyt <- 0.1 # m minshade <- 0 # min simulated shade # maxshade <- 30 # max simulated shade # LAI <- 0.1 # increased from default 0.1, reduce water in soil REFL <- 0.20 #Not used if soildata=1 soildata <- 1 soiltype <- 6 # Not used if soildata=1. Use http://www.asris.csiro.au/mapping/viewer.html if you want to confirm soil type ERR = 1 RUF <- 0.004 # Default SLE <- 0.98 #Not used if soildata=1 Thcond <- 2.5 # soil minerals thermal conductivity (W/mC) defult = 2.5 SpecHeat <- 870 Density = 2560 DEP <- c(0., 1., 2.5, 7.5, 10, 20., 40., 60., 100., 200.) # Soil nodes (cm) - set to match logger depths ## Get depth-specific soil properties #set source to wherever you extract depth-specific soil properties from source("C:/Users/nbriscoe/OneDrive - The University of Melbourne/Documents/Students/Will/Microclimate_modelling/soil_hydro.R") #get this file? #option to extract these properties? - Nat to look into prevdir<-getwd() setwd('Y:') cmd<-paste("R --no-save --args ",loc[1]," ",loc[2]," < extract.R",sep='') system(cmd) soilpro<-read.csv('data.csv') setwd(prevdir) soilpro[,1]<-c(2.5,7.5,22.5,45,80,150) colnames(soilpro)[1] <- 'depth' #pedotransfer functions soil.hydro<-soil.hydro(soilpro = as.data.frame(soilpro), DEP = DEP) PE<-soil.hydro$PE BB<-soil.hydro$BB BD<-soil.hydro$BD KS<-soil.hydro$KS BulkDensity <- BD[seq(1,19,2)]*1000 #soil bulk density, kg/m3 # search through observed textures and find the nearest match to Campell and Norman's Table 9.1 stypes<-NULL for(m in 1:nrow(soilpro)){ ssq<-(CampNormTbl9_1[,2]-soilpro[m,4]/100)^2 + (CampNormTbl9_1[,3]-soilpro[m,3]/100)^2 stypes[m]<-which(ssq==min(ssq)) } # produce a table of the qualitative soil profile soils<-as.character(CampNormTbl9_1[,1]) profile<-as.data.frame(cbind(soilpro[,1],soils[stypes]), stringsAsFactors=FALSE) profile[,1]<-as.numeric(profile[,1]) colnames(profile)<-c("depth","soiltype") print(profile) ### run microclimate model ## cap is organic surface layer depth and maxpool is water pooling depth micro_02<-micro_aust(loc = longlat, LAI = LAI, ystart = ystart, yfinish = yfinish, runmoist=1, maxshade=maxshade, minshade=minshade, evenrain=0,Usrhyt = Usrhyt, DEP = DEP, spatial = "W:/", ERR = 1,dailywind=FALSE, opendap=0, cap=cap, soildata=soildata,Thcond=Thcond,Density=Density, SpecHeat=SpecHeat, maxpool=10, PE=PE, BB=BB, BD=BD, KS=KS, BulkDensity=BulkDensity, RUF=RUF, write_input=1) # Run model + save parameters
32748cd9d2070650280dfaaa0d19e6329d7097bd
0ae69401a429092c5a35afe32878e49791e2d782
/trinker-lexicon-4c5e22b/man/freq_first_names.Rd
0e0389fb47fb9cf2093c27c6bc49a919c0e6d977
[]
no_license
pratyushaj/abusive-language-online
8e9156d6296726f726f51bead5b429af7257176c
4fc4afb1d524c8125e34f12b4abb09f81dacd50d
refs/heads/master
2020-05-09T20:37:29.914920
2019-06-10T19:06:30
2019-06-10T19:06:30
181,413,619
3
0
null
2019-06-05T17:13:22
2019-04-15T04:45:06
Jupyter Notebook
UTF-8
R
false
true
641
rd
freq_first_names.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/freq_first_names.R \docType{data} \name{freq_first_names} \alias{freq_first_names} \title{Frequent U.S. First Names} \format{A data frame with 5494 rows and 3 variables} \usage{ data(freq_first_names) } \description{ A dataset containing frequent first names based on the 1990 U.S. census. } \details{ \itemize{ \item Name. A first name \item prop. The proportion within the sex \item sex. The sex corresponding to the name } } \references{ https://www.census.gov/topics/population/genealogy/data/1990_census/1990_census_namefiles.html } \keyword{datasets}
58c36aca71e35693eb982ab7e4ef7195a961770b
c443333be002d4399402e6bf5a6740c1b617a242
/script.R
da5ed33385d4843174586fee8804423ce0d98e55
[]
no_license
borjaeg/TextMiningWithR
efce679b3f396b1eb60076d1180466b351f5e0c3
1ba3b3d0e6f8e25852b2b2ef04ced23be62b00c3
refs/heads/master
2021-01-20T20:56:24.642083
2014-05-22T22:26:36
2014-05-22T22:26:36
20,040,281
1
0
null
null
null
null
UTF-8
R
false
false
277
r
script.R
cname <- file.path(".") # Assuming this directory stores your files ;-) cname dir(cname) # list of files length(dir(cname)) # list length library(tm) # if you don't have it -> install.packages("tm") docs <- Corpus(DirSource(cname) # Creating an object Corpus summary(docs)
591fbd85766f6af614665552230b406a01a67f53
4f1835dc48cfe6b079a1fa53ce9a2029b3f228d2
/man/bamWriter.Rd
c3ed6a2a8d07a7536cdb61199261016f7f993894
[ "Artistic-2.0" ]
permissive
lmjakt/rbamtools_wokai_mj
28d57eea979da1f31c291a1e0b726f983f0556c0
42fc387692ecf01a57e3b9c9cf15873259ece464
refs/heads/master
2021-01-01T15:55:16.853906
2015-03-11T05:26:12
2015-03-11T05:26:12
27,465,315
0
0
null
null
null
null
UTF-8
R
false
false
2,228
rd
bamWriter.Rd
\name{bamWriter} \alias{bamWriter} \title{bamWriter: Opening a file connection to a BAM file for writing access.} % - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - % % Description % - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - % \description{The bamWriter function takes a \code{bamHeader} object and a filename and returns an object of class 'bamWriter' which represents a writing connection to a BAM-file} \usage{ bamWriter(x,filename) } \arguments{ \item{x}{An instance of class bamHeader.} \item{filename}{Filename of BAM-file to be opened for writing.} } \author{Wolfgang Kaisers} % - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - % % Examples % - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - % \examples{ # +++++++++++++++++++++++++++++++++++++++++++++++ # In this example, we copy some complex (i.e. interesting) aligns # into a new BAM file bam<-system.file("extdata", "accepted_hits.bam", package="rbamtools") idx<-paste(bam,"bai",sep=".") # +++++++++++++++++++++++++++++++++++++++++++++++ # Open BAM file and read complex aligns from chr1 reader<-bamReader(bam) loadIndex(reader,idx) coords<-as.integer(c(0,0,249250621)) range<-bamRange(reader,coords,complex=TRUE) bamClose(reader) # +++++++++++++++++++++++++++++++++++++++++++++++ # +++++++++++++++++++++++++++++++++++++++++++++++ # Create bamHeader from scratch bh<-new("bamHeaderText") headl<-new("headerLine") setVal(headl,"SO","coordinate") dict<-new("refSeqDict") addSeq(dict,SN="chr1",LN=249250621) dict prog<-new("headerProgram") setVal(prog,"ID","1") setVal(prog,"PN","tophat") setVal(prog,"CL","tophat -p8 --library-type fr-unstranded hs_ucsc rna033.fastq") setVal(prog,"VN","2.0.0") bh<-bamHeaderText(head=headl,dict=dict,prog=prog) \dontrun{getHeaderText(bh)} header<-bamHeader(bh) # +++++++++++++++++++++++++++++++++++++++++++++++ # +++++++++++++++++++++++++++++++++++++++++++++++ # Copy aligns in range into new BAM file \dontrun{ writer<-bamWriter(header,"chr1_complex.bam") bamSave(writer,range,refid=0) bamClose(writer) } # +++++++++++++++++++++++++++++++++++++++++++++++ } \keyword{bamWriter} \keyword{bamAlign}
0e01b3fed6fe3e148961aa4f1619c7bc3cf7ef02
3315a8c52ca024f8fb5137db69b0939ec1591a30
/20201208_day_8/exercise_2.R
4bb9be5a3086e5372d880eefc45a9f7870888886
[]
no_license
ericwburden/advent_of_code_2020
693a6bf39efd6ba39e3e8324d9c11b0e6ba67066
fffb37c579a9161baeff3be1dff802fc2b91ab6d
refs/heads/master
2023-04-07T02:21:14.948499
2021-01-02T20:00:49
2021-01-02T20:00:49
326,261,321
0
0
null
null
null
null
UTF-8
R
false
false
5,009
r
exercise_2.R
#' **--- Part Two ---** #' #' After some careful analysis, you believe that exactly one instruction is #' corrupted. #' #' Somewhere in the program, either a jmp is supposed to be a nop, or a nop is #' supposed to be a jmp. (No acc instructions were harmed in the corruption of #' this boot code.) #' #' The program is supposed to terminate by attempting to execute an instruction #' immediately after the last instruction in the file. By changing exactly one #' jmp or nop, you can repair the boot code and make it terminate correctly. #' #' For example, consider the same program from above: #' #' ``` #' nop +0 #' acc +1 #' jmp +4 #' acc +3 #' jmp -3 #' acc -99 #' acc +1 #' jmp -4 #' acc +6 #' `` #' #' If you change the first instruction from nop +0 to jmp +0, it would create a #' single-instruction infinite loop, never leaving that instruction. If you #' change almost any of the jmp instructions, the program will still eventually #' find another jmp instruction and loop forever. #' #' However, if you change the second-to-last instruction (from jmp -4 to nop -4), #' the program terminates! The instructions are visited in this order: #' #' ``` #' nop +0 | 1 #' acc +1 | 2 #' jmp +4 | 3 #' acc +3 | #' jmp -3 | #' acc -99 | #' acc +1 | 4 #' nop -4 | 5 #' acc +6 | 6 #' ``` #' #' After the last instruction (acc +6), the program terminates by attempting to #' run the instruction below the last instruction in the file. With this change, #' after the program terminates, the accumulator contains the value 8 (acc +1, #' acc +1, acc +6). #' #' Fix the program so that it terminates normally by changing exactly one jmp #' (to nop) or nop (to jmp). What is the value of the accumulator after the #' program terminates? source('exercise_1.R') # Simulation Approach ---------------------------------------------------------- adjust_instructions <- function(fail_profile, instructions) { for (line in rev(fail_profile$run_lines)) { test_instructions <- instructions current_fun <- instructions[[line]]$name if (current_fun == 'jmp') { test_instructions[[line]]$name <- 'nop' } if (current_fun == 'nop') { test_instructions[[line]]$name <- 'jmp' } new_profile <- profile_instructions(test_instructions) if (new_profile$successfully_completed) { print(paste0('It was ', line, '!')) return(new_profile) } } new_profile } instructions <- parse_instructions(real_input) fail_profile <- profile_instructions(instructions) new_profile <- adjust_instructions(fail_profile, instructions) answer1 <- new_profile$accumulator # Graph Approach --------------------------------------------------------------- # Helper function, adds edges from 'jmp' vertices as if they were 'nop' # vertices and adds edges to 'nop' vertices as if they were 'jmp' vertices flip_instruction <- function(i, instr_graph) { v <- V(instr_graph)[[i]] if (v$name == 'jmp') { # Add an edge connecting to the next vertex in sequence mod_graph <- add_edges(instr_graph, c(i, i+1)) } if (v$name == 'nop') { # Add an edge connection to the next vertex based on `shift` value mod_graph <- add_edges(instr_graph, c(i, i + v$shift)) } mod_graph } get_path_to_end <- function(instr_graph) { # Get the vertex indices for the longest path starting at index 1, # AKA the indexes for all the vertices that can be reached from the # starting point steps <- subcomponent(instr_graph, 1, mode = 'out') # Reachable vertices for (i in rev(steps)) { # Stepping backwards if (instructions[[i]]$name %in% c('jmp', 'nop')) { # Flip the instruction at index `i` then test whether the 'end' vertex # is reachable from the first vertex. If so, return the accumulator value test_graph <- flip_instruction(i, instr_graph) path <- all_simple_paths(test_graph, 1, 'end', mode = 'out') if (length(path) > 0) { plot(test_graph, vertex.size = 25, margin = 0) return(path[[1]]) } } } } instructions <- parse_instructions(test_input) instr_graph <- instructions_to_graph(instructions) path_to_end <- get_path_to_end(instr_graph) answer2 <- sum(path_to_end$acc) # Brute Graph Approach --------------------------------------------------------- instructions <- parse_instructions(test_input) instr_graph <- instructions_to_graph(instructions) jmp_vertices <- V(instr_graph)[V(instr_graph)$name == 'jmp'] new_edges <- map2(jmp_vertices, jmp_vertices + 1, ~ c(.x, .y)) mod_graph <- add_edges(instr_graph, unlist(new_edges)) nop_vertices <- V(instr_graph)[V(instr_graph)$name == 'nop'] vals <- map_int(instructions, ~ .x$arg) shifted_nops <- nop_vertices + vals[nop_vertices] new_edges <- map2(nop_vertices, shifted_nops, ~ c(.x, .y)) mod_graph <- add_edges(mod_graph, unlist(new_edges)) paths <- all_simple_paths(mod_graph, 1, 'end', mode = 'out') shortest_path <- paths[[which.min(lengths(paths))]] answer3 <- sum(shortest_path$acc)
7649241e17439922953c7e08086341a63c129e17
6855ac1106597ae48483e129fda6510354efa2bd
/man/is_html_output.Rd
cd27c468d9934a592db2b301ebd130e118796bfc
[ "MIT" ]
permissive
rOpenGov/iotables
ad73aae57b410396995635d1c432744c06db32db
91cfdbc1d29ac6fe606d3a0deecdb4c90e7016b9
refs/heads/master
2022-10-02T13:03:54.563374
2022-09-24T11:47:20
2022-09-24T11:47:20
108,267,715
19
8
NOASSERTION
2021-12-17T15:09:35
2017-10-25T12:35:47
R
UTF-8
R
false
true
230
rd
is_html_output.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/is_html_output.R \name{is_html_output} \alias{is_html_output} \title{Check if HTML output is required} \description{ Check if HTML output is required }
4be4f35944d176f664ff23f656a45d0e822f5389
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/rchie/examples/from_aml.Rd.R
5b766805faf7ce4098fd6aa21fe9db81ddf7f79f
[]
no_license
surayaaramli/typeRrh
d257ac8905c49123f4ccd4e377ee3dfc84d1636c
66e6996f31961bc8b9aafe1a6a6098327b66bf71
refs/heads/master
2023-05-05T04:05:31.617869
2019-04-25T22:10:06
2019-04-25T22:10:06
null
0
0
null
null
null
null
UTF-8
R
false
false
489
r
from_aml.Rd.R
library(rchie) ### Name: from_aml ### Title: Import ArchieML data from a string, file, or URL ### Aliases: from_aml from_archie ### ** Examples from_aml(aml = "key: value") from_aml("http://archieml.org/test/1.0/arrays.1.aml") ## No test: ## Not run: ##D # See source at: ##D # https://drive.google.com/open?id=1oYHXxvzscBBSBhd6xg5ckUEZo3tLytk9zY0VV_Y7SGs ##D library(googledrive) ##D from_aml(as_id("1oYHXxvzscBBSBhd6xg5ckUEZo3tLytk9zY0VV_Y7SGs")) ## End(Not run)## End(No test)
4507285c6e67c4189197b9bacbc71a6f6b79c774
57744ab6fedc2d4b8719fc51dce84e10189a0a7f
/rrdfqbcrnd0/R/GetObservationsWithDescriptionSparqlQuery.R
23acbd9c89bdfb4e0620468bda570204cc6789e8
[]
no_license
rjsheperd/rrdfqbcrnd0
3e808ccd56ccf0b26c3c5f80bec9e4d1c83e4f84
f7131281d5e4a415451dbd08859fac50d9b8a46d
refs/heads/master
2023-04-03T01:00:46.279742
2020-05-04T19:10:43
2020-05-04T19:10:43
null
0
0
null
null
null
null
UTF-8
R
false
false
1,926
r
GetObservationsWithDescriptionSparqlQuery.R
##' SPARQL query for dimensions and attributes from RDF data cube in workbook format ##' @param forsparqlprefix PREFIX part of SPARQL query ##' @param domainName domainName for the RRDF cube ##' @param dimensions dimensions ##' @param attributes attributes ##' @return SPARQL query ##' ##' @export GetObservationsWithDescriptionSparqlQuery<- function( forsparqlprefix, domainName, dimensions, attributes ) { cube.observations.rq<- paste( forsparqlprefix, "select * where {", "\n", "?s a qb:Observation ;", "\n", ## TODO: better way of using label ## "rdfs:label ?olabel;", "\n", paste("qb:dataSet", paste0( "ds:", "dataset", "-", domainName), " ;", sep=" ", collapse="\n"), "\n", paste0( dimensions, " ", sub("crnd-dimension:", "?", dimensions), ";", collapse="\n"), "\n", paste0( attributes, " ", sub("crnd-attribute:", "?", attributes), ";", collapse="\n"), "\n", "crnd-measure:measure ?measure . \n", paste0( "optional{ ", sub("crnd-dimension:", "?", dimensions), " ", "skos:prefLabel", " ", sub("crnd-dimension:", "?", dimensions), "value" , " . ", "}", collapse="\n"), "\n", paste0( "optional{ ", dimensions, " ", "rdfs:label", " ", sub("crnd-dimension:", "?", dimensions), "label" , " . ", "}", collapse="\n"), "\n", paste0( "BIND( IRI(", dimensions, ")", " as", " ", sub("crnd-dimension:", "?", dimensions), "IRI" , ")", collapse="\n"), "\n", "BIND( IRI( ?s ) AS ?measureIRI)", "\n", "} ", ## TODO(mja) Make more clever way of sorting ## "ORDER BY ?olabel", "\n" ) cube.observations.rq }
7a44ff13caae344851ea3765d95cfdc4e26fd1b7
984715b21609050a656ada7d75732dd4bab65231
/plot4.R
c45c45382d715b9fa65646a125975f36989d9b4d
[]
no_license
sagarchaki1/ExpData_Project2
7fd4fe8692b710f29aff5801cf8f61991f208ac8
5fafe077718c66880fc9231546b2836b5f877f9b
refs/heads/master
2021-01-10T04:34:53.776047
2015-11-18T20:24:30
2015-11-18T20:24:30
46,444,765
0
0
null
null
null
null
UTF-8
R
false
false
753
r
plot4.R
setwd("~/Nandini/Coursera/Specialization_Data Science/4.Exploratory Data Analysis/Project2") ## Reading Data into R NEI <- readRDS("summarySCC_PM25.rds") ## 6497651 rows SCC <- readRDS("Source_Classification_Code.rds") ##11717 rows m <- merge(NEI,SCC,by="SCC",all.x=TRUE) ## 6497651 #as.factor(m$year) # fetch all records with Short.Name == Coal coalMatches <- grepl("coal", m$Short.Name, ignore.case=TRUE) coal_data <- m[coalMatches, ] ##53400 rows em_year <- aggregate(Emissions ~ year, coal_data, sum) png("plot4.png") p <- ggplot(em_year, aes(factor(year), Emissions)) p <- p + geom_bar(stat="identity") + xlab("year") + ylab("Emissions (tons)") + ggtitle("Total Emissions from coal sources across United States") print(p) dev.off()
af19cfcfe6cd7d0ea38a5e72c0897b389430842c
a55a7ba419e1df082287bfdb39a15a503f630bbf
/5-distribucion-normal-en-R-la-regla-empirica-y-la-funcion-rnorm.R
46f41a119bba34b4860578e24be85727a45b31e7
[ "CC0-1.0" ]
permissive
cghv94/medidas-de-dispersion-en-R
d18acfefb9fc2b3702fecb643d03245be50a81a6
bdf64eb65ae2b68ce6c881acef4a431933a41cad
refs/heads/master
2022-12-23T05:35:16.732867
2020-09-30T13:49:26
2020-09-30T13:49:26
299,912,201
2
0
null
null
null
null
UTF-8
R
false
false
505
r
5-distribucion-normal-en-R-la-regla-empirica-y-la-funcion-rnorm.R
# UNIVERSIDAD NACIONAL AUTÓNOMA DE MÉXICO # Facultad de Economía # Estadística 2020-2 # Profesor: Cesar Hernández # Medidas de dispersión # Distribución normal en R: la regla empírica y la función rnorm() normal <- rnorm(10000) mean(normal) sd(normal) hist(normal, probability = T) lines(density(normal), col = "red", lwd = 3) plot(normal) abline(h = c(-1,0,1), col = "green", lwd = 3) abline(h = c(-2,2), col = "orange", lwd = 3) abline(h = c(-3,3), col = "red", lwd = 3)
c6641f7b81ba15b670be2dc79e4c24b05ce51c6c
ab2784ac467525cf52daeb0adb03fb87cf19894b
/common/.xic2jpg.R
2f90861ff77765f83b2eb238103b3bd6c927b229
[]
no_license
WangHong007/Diamond
454e5d7d4375d833414ac6962c1fbc49b3de6fa9
3252fe1cf97416679d0e57ba3f86690500397d63
refs/heads/master
2023-03-21T09:23:07.074506
2021-03-16T14:00:34
2021-03-16T14:00:34
null
0
0
null
null
null
null
UTF-8
R
false
false
3,898
r
.xic2jpg.R
Args <- commandArgs() path=Args[6] out.wid=10 out.hei=4 out.cnt=TOTAL_RUN_COUNT wanted_exp=c(1:out.cnt) library(ggplot2) library(showtext) library(reshape2) font.add("DejaVu Sans","/data/gpfs02/jhan/software/dejavu/DejaVuSans.ttf") showtext.auto() ## automatically use showtext for new devices) theme(text=element_text(family="DejaVu Sans")) # 修改geom_text的字体 geom_text(family="DejaVu Sans") #file="C:/Users/dot/Desktop/draw_xic/sp_A2AKX3_SETX_MOUSE-(Acetyl)STC(Carbamidomethyl)C(Carbamidomethyl)WC(Carbamidomethyl)TPGGSSTIDVLKR-2" draw_tr=function(file){ data <- read.delim(paste(file,".txt",sep = ""), header=FALSE, stringsAsFactors=FALSE) lines = readLines(paste(file,".info.txt",sep = ""), n = 3) #deal info exp_num=as.numeric(strsplit(lines,"\t")[[1]]) exp_size=length(exp_num) mz=as.numeric(strsplit(lines,"\t")[[2]]) mz_size=length(mz) peak=as.numeric(strsplit(lines,"\t")[[3]]) peak[20]=5 #deal data data=data[,-dim(data)[2]] data_len1=dim(data)[1] data_len2=dim(data)[2] # get ms1 and ms2 data #ms1_rt=data[1,] #ms1_int=data[2,] ms2_rt=data[3,] ms2_int=data[c(4:data_len1),] #row.names(ms2_int)=mz # deal peak peak_info=NA exp_num_peak=NA for(i in c(1:exp_size)){ if(peak[i*2]>0){ peak_info=c(peak_info,(sum(exp_num[0:(i-1)])+c((peak[i*2-1]+1-1):(peak[i*2-1]+peak[i*2]+1)))) exp_num_peak=c(exp_num_peak,peak[i*2]+2) }else{ exp_num_peak=c(exp_num_peak,0) } } peak_info=peak_info[-1] exp_num_peak=exp_num_peak[-1] # get peak info # ms1_rt_peak=data[1,peak_info] # ms1_int_peak=data[2,peak_info] ms2_rt_peak=data[3,peak_info] ms2_int_peak=data[c(4:data_len1),peak_info] #row.names(ms2_int_peak)=mz max_y=max(ms2_int_peak)*1.0 # ms1_ms2_rate=max(ms1_int_peak)/max(ms2_int_peak)/0.8 ms1_ms2_rate=1.0 exp_name=data.frame(exp=wanted_exp,name=wanted_exp) rate=ms1_ms2_rate #ms1_int=ms1_int/rate exp=NA for(i in c(1:exp_size)){ exp=c(exp,rep(i,exp_num[i])) } exp=exp[-1] # ms1=data.frame(exp=exp,rt=drop(as.matrix(ms1_rt[1,])),int=drop(as.matrix(ms1_int[1,]))) ms2=data.frame(exp=exp,rt=drop(as.matrix(ms2_rt[1,]))) ms2=cbind(ms2,t(ms2_int)) long_ms2=melt(ms2,id.vars=c("exp","rt")) long_ms2=long_ms2[which(long_ms2$exp %in% wanted_exp),] # ms1=ms1[which(ms1$exp %in% wanted_exp),] long_ms2=merge(long_ms2,exp_name) long_ms2=data.frame(exp=long_ms2$name,rt=long_ms2$rt,variable=long_ms2$variable,value=long_ms2$value) # ms1=merge(ms1,exp_name) # ms1=data.frame(exp=ms1$name,rt=ms1$rt,int=ms1$int) ggplot()+ geom_line(data=long_ms2, aes(rt, value, colour = variable)) + #geom_point(data=long_ms2, aes(rt, value, colour = variable),size=1,shape=20) + facet_grid(exp~.,margins=F,scales="free_y")+ scale_y_continuous(limits=c(0, max_y))+ ggtitle(sub(".+?-","",file,perl = T)) + xlab("Retention time (s)") + ylab("Intensity")+ theme(text = element_text(size = 12, face = "plain",family="DejaVu Sans"), plot.title=element_text(size = 12, face = "plain",family="DejaVu Sans"), legend.text=element_text(size = 8, face = "plain",family="DejaVu Sans"), axis.text=element_text(size = 10, face = "plain",family="DejaVu Sans"),axis.text.x=element_text(angle = 0), axis.title.x=element_text(vjust=-0.2),axis.title.y=element_text(vjust=1))+ scale_colour_discrete(name="Product ions m/z",labels=as.character(mz)) } files=list.files(path,"*.info.txt") files=sub(".info.txt","",files) files library(parallel) cl <- makeCluster(detectCores(),type="FORK") parLapply(cl,files,function(f){ draw_tr(paste(path,f,sep = "")) ggsave(paste(path,f,".png",sep = ""),width=out.wid,height=out.cnt*out.hei,units="in",dpi=300,limitsize=FALSE) #f }) stopCluster(cl)
aa93f5fe7f85d099d33f895d6de1e996c26bc0a7
2c485b1c2f39fc3c269c6f578e21d698dcec63e6
/man/stratify.Rd
cfa02c5ea85c7fdfcd8025584ded8c6e635f6735
[]
no_license
aalfons/simFrame
002f47cad078c93dec24c4c9fab4893e7bb56922
23314f0b1f6632560e0d95dc568f708f3c1286a9
refs/heads/master
2021-12-23T10:23:44.587577
2021-11-23T12:46:58
2021-11-23T12:46:58
6,717,992
1
1
null
null
null
null
UTF-8
R
false
false
858
rd
stratify.Rd
\name{stratify} \Rdversion{1.1} \docType{methods} \alias{stratify} \alias{stratify-methods} \alias{stratify,data.frame,BasicVector-method} \title{Stratify data} \description{Generic function for stratifying data.} \usage{ stratify(x, design) } \arguments{ \item{x}{the \code{data.frame} to be stratified.} \item{design}{a character, logical or numeric vector specifying the variables (columns) to be used for stratification.} } \value{ An object of class \code{"Strata"}. } \section{Methods}{ \describe{ \item{\code{x = "data.frame", design = "BasicVector"}}{stratify data according to the variables (columns) given by \code{design}.} } } \author{Andreas Alfons} \seealso{ \code{"\linkS4class{Strata}"} } \examples{ data(eusilcP) strata <- stratify(eusilcP, c("region", "gender")) summary(strata) } \keyword{manip} \keyword{methods}
65be512331314dcb92935b99b629d16db7365fec
d822abc520852e465ea2c65b0c216c6a4bdf94bc
/R/abetadms__datatable_to_matrix.R
6284aba30674a0f031c1a76d5dab0d7c288467fe
[ "MIT" ]
permissive
lehner-lab/abetadms
2bbf50ba9a8c40031b7962526b7b9ac8aebce47d
6a6bcc92d5047048ffd86f7767e5495d2cea4502
refs/heads/master
2021-04-13T12:41:20.380605
2020-04-06T18:53:35
2020-04-06T18:53:35
249,164,119
0
1
null
null
null
null
UTF-8
R
false
false
1,408
r
abetadms__datatable_to_matrix.R
#' abetadms__datatable_to_matrix #' #' Convert data.table to matrix for heatmap plotting (single AA mutants only). #' #' @param input_dt input data.table (required) #' @param variable_name name of variable to use for heatmap cells (defaut:"fitness") #' #' @return a matrix for heamtmap plotting #' @export abetadms__datatable_to_matrix <- function( input_dt, variable_name="fitness" ){ aa_obj <- Biostrings::AAString("GAVLMIFYWKRHDESTCNQP") aa_list <- Biostrings::AMINO_ACID_CODE[strsplit(as.character(aa_obj), NULL)[[1]]] aa_list["*"] <- "X" #Only single AA mutants input_df <- as.data.frame(input_dt) dms_1aa <- input_df[input_df$Nmut_aa==1,] #Absolute position # dms_1aa$Pos_abs <- as.numeric(substr(dms_1aa$mut_code, 2, 4)) #WT sequence wt_seq <- unique(dms_1aa[order(dms_1aa[,"Pos_abs"]),c("WT_AA", "Pos_abs")])[,"WT_AA"] #Construct heatmap matrix heat_mat <- matrix(nrow = length(aa_list), ncol = max(dms_1aa$Pos_abs)-min(dms_1aa$Pos_abs)+1) rownames(heat_mat) <- names(aa_list) colnames(heat_mat) <- min(dms_1aa$Pos_abs):max(dms_1aa$Pos_abs) for(aa_pos in min(dms_1aa$Pos_abs):max(dms_1aa$Pos_abs)){ for(aa_id in names(aa_list)){ temp_index <- which(dms_1aa$Pos_abs==aa_pos & dms_1aa$Mut==aa_id) if(length(temp_index)==1){ heat_mat[aa_id,as.character(aa_pos)] <- dms_1aa[temp_index,variable_name] } } } return(heat_mat) }
ef9fce0d5bfcbef4119c911f5ec1ea44df2d7b94
01403da4a494341c935b2af9ac9da1caa160e8e3
/man/auc_gradient.Rd
e3a7d0374f0e0bb35f93a41fc9131367d226e3de
[ "MIT" ]
permissive
sachsmc/pseudoloss
d71e1a87bd50e4588d41c517a838f56d1a6854b1
c7629db9d5aea4c7e2169432f31cb84c1df8eb06
refs/heads/master
2020-06-17T22:11:00.565749
2019-07-09T20:08:17
2019-07-09T20:08:17
196,075,345
0
0
null
null
null
null
UTF-8
R
false
true
633
rd
auc_gradient.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/roc.R \name{auc_gradient} \alias{auc_gradient} \title{Gradient of the ramp pseudo AUC} \usage{ auc_gradient(X, pseus, rampfunc = smoothramp, d.rampfunc = d.smoothramp) } \arguments{ \item{X}{numeric vector of predictions} \item{pseus}{matrix of pseudo observations} \item{rampfunc}{Ramp function} \item{d.rampfunc}{first derivative of ramp function} } \description{ Gradient of the AUC using the specified ramp function and the first derivative of the ramp. Returns the gradient with respect to the prediction vector. This is for use with xgboost. }
ebfe0e31ffe81df52465503082074a2598e9b65e
29585dff702209dd446c0ab52ceea046c58e384e
/RnavGraph/R/SettingClasses.R
d0aa94a6e3ab24aa7943df12f74d16493d9736ba
[]
no_license
ingted/R-Examples
825440ce468ce608c4d73e2af4c0a0213b81c0fe
d0917dbaf698cb8bc0789db0c3ab07453016eab9
refs/heads/master
2020-04-14T12:29:22.336088
2016-07-21T14:01:14
2016-07-21T14:01:14
null
0
0
null
null
null
null
UTF-8
R
false
false
2,912
r
SettingClasses.R
## ## Classes with Color-, Interaction- & Display-Settings ######################################################## ## TODO: Eventually also save tk2d settings here setClass( Class = "ColorSettings", representation = representation( background = "character", bullet = "character", bulletActive = "character", nodes = "character", nodesActive = "character", adjNodes = "character", adjNodesActive = "character", notVisitedEdge = "character", visitedEdge = "character", edgeActive = "character", labels = "character", labelsActive = "character", adjLabels = "character", adjLabelsActive = "character", path = "character" ), prototype=list( background = "white", bullet = "#fdfd96", ## Pastel Yellow bulletActive = "#ff6961", ## Pastel Red nodes = "#444444", ## Gray nodesActive = "#03C03C", ## Pastel Dark Green adjNodes = "#FFB347", ## Pastel Orange adjNodesActive = "#ff6961", ## Pastel Red notVisitedEdge = "#444444", ## Gray visitedEdge ="#CFCFC4", ## Pastel Gray edgeActive = "#03C03C", ## Pastel Dark Green labels = "#444444", ## Gray labelsActive = "#03C03C", ## Pastel Dark Green adjLabels = "#ff8f00", ## Princeton Orange adjLabelsActive ="#ff6961", ## Pastel Red path = "#c23b22" ## Pastel Dark Red ) ) setClass( Class = "InteractionSettings", representation = representation( NSteps = "numeric", animationTime = "numeric", dragSelectRadius = "numeric", labelDistRadius = "numeric" ), prototype = list( NSteps = 50, animationTime = 0.1, dragSelectRadius = 15, labelDistRadius = 30 ) ) setClass( Class = "DisplaySettings", representation = representation( bulletRadius = "numeric", nodeRadius = "numeric", lineWidth = "numeric", highlightedLineWidth = "numeric" ), prototype = list( bulletRadius = 15, nodeRadius = 10, lineWidth = 2, highlightedLineWidth = 4 ) ) setClass( Class = "Tk2dDisplay", representation = representation( bg = "character", brush_colors = "character", brush_color = "character", linked = "logical" ), prototype = list( bg = "white", ## RColorBrewer qualitative, 9 classes, color scheme: Set1 brush_colors = c('#377EB8', '#4DAF4A', '#984EA3', '#FF7F00', '#FFFF33', '#A65628', '#F781BF', '#999999', '#E41A1C'), brush_color = "magenta", linked = TRUE ) ) setClass( Class = "NG_Settings", representation = representation( color = "ColorSettings", interaction = "InteractionSettings", display = "DisplaySettings", tk2d = "Tk2dDisplay" ), prototype = list( color = new('ColorSettings'), interaction = new("InteractionSettings"), display = new("DisplaySettings"), tk2d = new("Tk2dDisplay") ) )
8bfbc245cd1245e5d3ab925def5fbba695b546ca
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/XBRL/examples/xbrlDoAll.Rd.R
b0233613929ab2467012e77ba9c8845fce70da1f
[]
no_license
surayaaramli/typeRrh
d257ac8905c49123f4ccd4e377ee3dfc84d1636c
66e6996f31961bc8b9aafe1a6a6098327b66bf71
refs/heads/master
2023-05-05T04:05:31.617869
2019-04-25T22:10:06
2019-04-25T22:10:06
null
0
0
null
null
null
null
UTF-8
R
false
false
681
r
xbrlDoAll.Rd.R
library(XBRL) ### Name: xbrlDoAll ### Title: Function to do all required work on an XBRL instance and its ### associated DTS. ### Aliases: xbrlDoAll ### Keywords: XBRL high-level ### ** Examples ## Not run: ##D ## Setting stringsAsFactors = FALSE is highly recommended ##D ## to avoid data frames to create factors from character vectors. ##D options(stringsAsFactors = FALSE) ##D ##D ## XBRL instance file to be analyzed, accessed ##D ## directly from SEC website: ##D inst <- "https://www.sec.gov/Archives/edgar/data/21344/000002134413000050/ko-20130927.xml" ##D ##D xbrl.vars <- xbrlDoAll(inst, cache.dir="XBRLcache", prefix.out="out", verbose=TRUE) ## End(Not run)
dd3e17a29e31fbdc040082b7494631c229194365
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/entropy/examples/entropy.empirical.Rd.R
35c60e97b0e980422d2499a848f295e5ad939239
[]
no_license
surayaaramli/typeRrh
d257ac8905c49123f4ccd4e377ee3dfc84d1636c
66e6996f31961bc8b9aafe1a6a6098327b66bf71
refs/heads/master
2023-05-05T04:05:31.617869
2019-04-25T22:10:06
2019-04-25T22:10:06
null
0
0
null
null
null
null
UTF-8
R
false
false
1,078
r
entropy.empirical.Rd.R
library(entropy) ### Name: entropy.empirical ### Title: Empirical Estimators of Entropy and Mutual Information and ### Related Quantities ### Aliases: freqs.empirical entropy.empirical KL.empirical chi2.empirical ### mi.empirical chi2indep.empirical ### Keywords: univar ### ** Examples # load entropy library library("entropy") # a single variable # observed counts for each bin y = c(4, 2, 3, 0, 2, 4, 0, 0, 2, 1, 1) # empirical frequencies freqs.empirical(y) # empirical estimate of entropy entropy.empirical(y) # example with two variables # observed counts for two random variables y1 = c(4, 2, 3, 1, 10, 4) y2 = c(2, 3, 7, 1, 4, 3) # empirical Kullback-Leibler divergence KL.empirical(y1, y2) # half of the empirical chi-squared statistic 0.5*chi2.empirical(y1, y2) ## joint distribution example # contingency table with counts for two discrete variables y2d = rbind( c(1,2,3), c(6,5,4) ) # empirical estimate of mutual information mi.empirical(y2d) # half of the empirical chi-squared statistic of independence 0.5*chi2indep.empirical(y2d)
371c01f98b2f9635afef255dccbe260c594c01c3
cd50b67ec9bf2bb26661c87704880c936f7726c5
/ThesisChap3Plots.R
092dbb76815674653624196c82bf4a04b1d6ec6b
[]
no_license
sampeel/detectionSim
3ec37880725d40f2ec458720a732f8087e6cc5e6
7fc144d1763f70996cf627db88adfb2642a2c400
refs/heads/master
2022-11-27T02:55:15.633421
2020-08-06T23:42:48
2020-08-06T23:42:48
285,687,803
0
0
null
null
null
null
UTF-8
R
false
false
56,818
r
ThesisChap3Plots.R
# Set working directory. setwd("/perm_storage/home/sampeel/chap2/sim2") # Load packages and source files. library(codetools) library(raster) library(spatstat) library(multispeciesPP) # Github: sampeel version (not wfithian) library(sp) library(rgeos) library(parallel) library(vioplot) library(RColorBrewer) library(fields, quietly = TRUE) source("bglm.r") source("cellsObj.r") source("dataObj.r") source("domainObj.r") source("estimateCoeffsNew.R") source("plotLayers.r") source("plottingObj.r") source("resultsObject.r") source("scenariosObject.r") source("settingsObj.r") source("simFuncs.r") source("surveysObj.r") source("utils.r") # Re-load results (if needed) retLst <- loadScenariosResults(scenariosDir, nameResultsFile = "Results") scenariosObj <- retLst$scenariosObj scenariosObj$scenariosDir <- scenariosDir # #--------------------------- # # Figure 1 - Scale (intercept) issue # #--------------------------- # # # Setup ... # # numRuns <- 5000 # scenariosDir <- paste0(getwd(), "/", "Output-SpatialGear-runs", format(numRuns)) # gearUseStrategyPA <- "covar" # numPA <- 3500 # numClusters <- 0 # deltaMultiplier <- 0.0 # gammaMultiplier <- 1.0 # zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) # scenariosPrettyNames <- as.character(format(zetaMultiplier)) # xAxisTitle <- expression("gear difference " * (zeta^x)) # # # Run experiment # expLst <- runExperiment(scenariosDir, numRuns, # gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, # numClusters = numClusters, deltaMultiplier = deltaMultiplier, # gammaMultiplier = gammaMultiplier, # zetaMultiplier = zetaMultiplier, # scenariosPrettyNames = scenariosPrettyNames, # xAxisTitle = xAxisTitle) # # # # Plot figure. # whichExperiment <- paste0(getwd(), "/", "Output-SpatialGear-runs", format(numRuns)) # xAxisTitle <- expression("gear difference " * (zeta^x)) # plotStatisticsComparisons(whichExperiment, whichStats=c(1,2,3), # whichCoeffs = list(1,NULL,NULL), whichSpecies=NULL, # plotSDMs = c("PA","MsPP","Gear"), # xAxisTitle = xAxisTitle, # plotDevice = "png", plotWidth = 12, plotHeight = 12, # plotDir=paste0(whichExperiment,"/Plots"), fileName = "figure1", # columnHeadings = c(expression(alpha[k]), # expression(lambda[ck]), # expression(Sigma[c]*lambda[ck])), # accuracyPrecision = "accuracy") #--------------------------- # Appendix - number of samples #--------------------------- # Experiment 1 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppNumSamps/", "Output-RandomGear-nPA3500-runs", format(numRuns)) gearUseStrategyPA <- "rand" numPA <- 3500 numClusters <- 0 deltaMultiplier <- 0.0 gammaMultiplier <- 1.1 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, deltaMultiplier = deltaMultiplier, gammaMultiplier = gammaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle, doExp = FALSE, doStats = FALSE) # Experiment 2 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppNumSamps/", "Output-RandomGear-nPA2500-runs", format(numRuns)) gearUseStrategyPA <- "rand" numPA <- 2500 numClusters <- 0 deltaMultiplier <- 0.0 gammaMultiplier <- 1.1 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, deltaMultiplier = deltaMultiplier, gammaMultiplier = gammaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle, doExp = FALSE, doStats = FALSE) # Experiment 3 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppNumSamps/", "Output-RandomGear-nPA1500-runs", format(numRuns)) gearUseStrategyPA <- "rand" numPA <- 1500 numClusters <- 0 deltaMultiplier <- 0.0 gammaMultiplier <- 1.1 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, deltaMultiplier = deltaMultiplier, gammaMultiplier = gammaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle, doExp = FALSE, doStats = FALSE) # Experiment 4 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppNumSamps/", "Output-RandomGear-nPA500-runs", format(numRuns)) gearUseStrategyPA <- "rand" numPA <- 500 numClusters <- 0 deltaMultiplier <- 0.0 gammaMultiplier <- 1.1 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, deltaMultiplier = deltaMultiplier, gammaMultiplier = gammaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle, doExp = FALSE, doStats = FALSE) # Make figure 2. experimentDirs <- c(paste0(getwd(),"/Paper/AppNumSamps/Output-RandomGear-nPA3500-runs5000"), paste0(getwd(),"/Paper/AppNumSamps/Output-RandomGear-nPA2500-runs5000"), paste0(getwd(),"/Paper/AppNumSamps/Output-RandomGear-nPA1500-runs5000"), paste0(getwd(),"/Paper/AppNumSamps/Output-RandomGear-nPA500-runs5000")) experimentNames <- c(expression(n[samp] == 3500),expression(n[samp] == 2500), expression(n[samp] == 1500),expression(n[samp] == 500)) columnHeadings <- experimentNames plotDir <- paste0(getwd(),"/Paper/Main") xAxisTitle <- expression("gear difference " * (zeta^x)) plotTheseSDMs = c("PA","MsPP","Gear") # Statistic 1b: difference between true and estimated beta_1 coefficient. plotExperimentComparisons(experimentDirs, 1, whichCoeffs = c(2), plotSDMs = plotTheseSDMs, plotDevice = "png", plotDir = plotDir, #ylimVals = c(0,0.5,0,5), plotWidth = 15.8, plotHeight = 12, # plotWidth = 12, plotHeight = 12, fileName = "randNumPAComparisonBeta1", xAxisTitle = xAxisTitle, columnHeadings = columnHeadings, accuracyPrecision = "accuracy") # Make figure 1. whichExperiment <- paste0(getwd(),"/Paper/AppNumSamps/Output-RandomGear-nPA3500-runs5000") xAxisTitle <- expression("gear difference " * (zeta^x)) plotDir <- paste0(getwd(),"/Paper/Main") plotStatisticsComparisons(whichExperiment, whichStats=c(1,2,3), whichCoeffs = list(1,NULL,NULL), whichSpecies=NULL, plotSDMs = c("PA","MsPP","Gear"), xAxisTitle = xAxisTitle, plotDevice = "png", plotWidth = 12, plotHeight = 12, plotDir = plotDir, fileName = "scaleComparisonFig1", columnHeadings = c(expression(alpha[k]), expression(lambda[ck]), expression(Sigma[c]*lambda[ck])), accuracyPrecision = "accuracy") # Experiment 5 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppNumSamps/", "Output-SpatialGear-nPA3500-runs", format(numRuns)) gearUseStrategyPA <- "covar" numPA <- 3500 numClusters <- 0 deltaMultiplier <- 0.0 gammaMultiplier <- 1.1 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, deltaMultiplier = deltaMultiplier, gammaMultiplier = gammaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle, doExp = FALSE, doStats = FALSE) # Experiment 6 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppNumSamps/", "Output-SpatialGear-nPA2500-runs", format(numRuns)) gearUseStrategyPA <- "covar" numPA <- 2500 numClusters <- 0 deltaMultiplier <- 0.0 gammaMultiplier <- 1.1 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, deltaMultiplier = deltaMultiplier, gammaMultiplier = gammaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle, doExp = FALSE, doStats = FALSE) # Experiment 7 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppNumSamps/", "Output-SpatialGear-nPA1500-runs", format(numRuns)) gearUseStrategyPA <- "covar" numPA <- 1500 numClusters <- 0 deltaMultiplier <- 0.0 gammaMultiplier <- 1.1 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, deltaMultiplier = deltaMultiplier, gammaMultiplier = gammaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle, doExp = FALSE, doStats = FALSE) # Experiment 8 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppNumSamps/", "Output-SpatialGear-nPA500-runs", format(numRuns)) gearUseStrategyPA <- "covar" numPA <- 500 numClusters <- 0 deltaMultiplier <- 0.0 gammaMultiplier <- 1.1 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, deltaMultiplier = deltaMultiplier, gammaMultiplier = gammaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle, doExp = FALSE, doStats = FALSE) # Make figure 3 experimentDirs <- c(paste0(getwd(),"/Paper/AppNumSamps/Output-SpatialGear-nPA3500-runs5000"), paste0(getwd(),"/Paper/AppNumSamps/Output-SpatialGear-nPA2500-runs5000"), paste0(getwd(),"/Paper/AppNumSamps/Output-SpatialGear-nPA1500-runs5000"), paste0(getwd(),"/Paper/AppNumSamps/Output-SpatialGear-nPA500-runs5000")) experimentNames <- c(expression(n[samp] == 3500),expression(n[samp] == 2500), expression(n[samp] == 1500),expression(n[samp] == 500)) columnHeadings <- experimentNames plotDir <- paste0(getwd(),"/Paper/Main") xAxisTitle <- expression("gear difference " * (zeta^x)) plotTheseSDMs = c("PA","MsPP","Gear") # Statistic 1b: difference between true and estimated beta_1 coefficient. plotExperimentComparisons(experimentDirs, 1, whichCoeffs = c(2), plotSDMs = plotTheseSDMs, plotDevice = "png", plotDir = plotDir, #ylimVals = c(0,0.5,0,5), plotWidth = 15.8, plotHeight = 12, # plotWidth = 12, plotHeight = 12, fileName = "spatialNumPAComparisonBeta1", xAxisTitle = xAxisTitle, columnHeadings = columnHeadings, accuracyPrecision = "accuracy") #--------------------------- # App - Sampling bias #--------------------------- # Experiment 1 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppSampBias/Output-RandomGear-Bias0-runs", format(numRuns)) gearUseStrategyPA <- "rand" numPA <- 3500 numClusters <- 0 gammaMultiplier <- 1.1 deltaMultiplier <- 0.0 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, useSDMs = c("PA","MsPP","Gear"), gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, gammaMultiplier = gammaMultiplier, deltaMultiplier = deltaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle) # Experiment 2 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppSampBias/Output-RandomGear-Bias1-runs", format(numRuns)) gearUseStrategyPA <- "rand" numPA <- 3500 numClusters <- 0 gammaMultiplier <- 1.1 deltaMultiplier <- 1.0 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, useSDMs = c("PA","MsPP","Gear"), gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, gammaMultiplier = gammaMultiplier, deltaMultiplier = deltaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle) # Experiment 3 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppSampBias/Output-RandomGear-Bias2-runs", format(numRuns)) gearUseStrategyPA <- "rand" numPA <- 3500 numClusters <- 0 gammaMultiplier <- 1.1 deltaMultiplier <- 2.0 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, useSDMs = c("PA","MsPP","Gear"), gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, gammaMultiplier = gammaMultiplier, deltaMultiplier = deltaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle) # Make combined figure. experimentDirs <- c(paste0(getwd(),"/Paper/AppSampBias/Output-RandomGear-Bias0-runs5000"), paste0(getwd(),"/Paper/AppSampBias/Output-RandomGear-Bias1-runs5000"), paste0(getwd(),"/Paper/AppSampBias/Output-RandomGear-Bias2-runs5000")) experimentNames <- c(expression(delta^x == 0),expression(delta^x == 1),expression(delta^x == 2)) columnHeadings <- experimentNames plotDir <- paste0(getwd(),"/Paper/Main") xAxisTitle <- expression("gear difference " * (zeta^x)) plotTheseSDMs = c("PA","MsPP","Gear") # Statistic 1b: difference between true and estimated beta_1 coefficient. plotExperimentComparisons(experimentDirs, 1, whichCoeffs = c(2), plotSDMs = plotTheseSDMs, plotDevice = "png", plotDir = plotDir, #ylimVals = c(0,0.5,0,5), plotWidth = 12, plotHeight = 12, fileName = "randomSampBiasComparisonBeta1", xAxisTitle = xAxisTitle, columnHeadings = columnHeadings, accuracyPrecision = "accuracy") # Experiment 4 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppSampBias/Output-SpatialGear-Bias0-runs", format(numRuns)) gearUseStrategyPA <- "covar" numPA <- 3500 numClusters <- 0 gammaMultiplier <- 1.1 deltaMultiplier <- 0.0 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, useSDMs = c("PA","MsPP","Gear"), gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, gammaMultiplier = gammaMultiplier, deltaMultiplier = deltaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle, doExp = FALSE, doStats = FALSE) # Experiment 5 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppSampBias/Output-SpatialGear-Bias1-runs", format(numRuns)) gearUseStrategyPA <- "covar" numPA <- 3500 numClusters <- 0 gammaMultiplier <- 1.1 deltaMultiplier <- 1.0 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, useSDMs = c("PA","MsPP","Gear"), gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, gammaMultiplier = gammaMultiplier, deltaMultiplier = deltaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle, doExp = FALSE, doStats = FALSE) # Experiment 6 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppSampBias/Output-SpatialGear-Bias2-runs", format(numRuns)) gearUseStrategyPA <- "covar" numPA <- 3500 numClusters <- 0 gammaMultiplier <- 1.1 deltaMultiplier <- 2.0 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, useSDMs = c("PA","MsPP","Gear"), gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, gammaMultiplier = gammaMultiplier, deltaMultiplier = deltaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle, doExp = FALSE, doStats = FALSE) # Make combined figure. experimentDirs <- c(paste0(getwd(),"/Paper/AppSampBias/Output-SpatialGear-Bias0-runs5000"), paste0(getwd(),"/Paper/AppSampBias/Output-SpatialGear-Bias1-runs5000"), paste0(getwd(),"/Paper/AppSampBias/Output-SpatialGear-Bias2-runs5000")) experimentNames <- c(expression(delta^x == 0),expression(delta^x == 1),expression(delta^x == 2)) columnHeadings <- experimentNames plotDir <- paste0(getwd(),"/Paper/Main") xAxisTitle <- expression("gear difference " * (zeta^x)) plotTheseSDMs = c("PA","MsPP","Gear") # Statistic 1b: difference between true and estimated beta_1 coefficient. plotExperimentComparisons(experimentDirs, 1, whichCoeffs = c(2), plotSDMs = plotTheseSDMs, plotDevice = "png", plotDir = plotDir, #ylimVals = c(0,0.5,0,5), plotWidth = 12, plotHeight = 12, fileName = "spatialSampBiasComparisonBeta1", xAxisTitle = xAxisTitle, columnHeadings = columnHeadings, accuracyPrecision = "accuracy") #--------------------------- # App multiple surveys #--------------------------- # Experiment 1 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppSurveys/Output-RandomGearClust-nPA500-runs", format(numRuns)) gearUseStrategyPA <- "rand" numPA <- 500 numClusters <- 10 deltaMultiplier <- 0.0 gammaMultiplier <- 1.1 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, deltaMultiplier = deltaMultiplier, gammaMultiplier = gammaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle, doExp = FALSE, doStats = FALSE) # Experiment 2 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppSurveys/Output-RandomGearClust-nPA1500-runs", format(numRuns)) gearUseStrategyPA <- "rand" numPA <- 1500 numClusters <- 10 deltaMultiplier <- 0.0 gammaMultiplier <- 1.1 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, deltaMultiplier = deltaMultiplier, gammaMultiplier = gammaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle, doExp = FALSE, doStats = FALSE) # Experiment 3 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppSurveys/Output-RandomGearClust-nPA2500-runs", format(numRuns)) gearUseStrategyPA <- "rand" numPA <- 2500 numClusters <- 10 deltaMultiplier <- 0.0 gammaMultiplier <- 1.1 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, deltaMultiplier = deltaMultiplier, gammaMultiplier = gammaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle, doExp = FALSE, doStats = FALSE) # Experiment 4 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppSurveys/Output-RandomGearClust-nPA3500-runs", format(numRuns)) gearUseStrategyPA <- "rand" numPA <- 3500 numClusters <- 10 deltaMultiplier <- 0.0 gammaMultiplier <- 1.1 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, deltaMultiplier = deltaMultiplier, gammaMultiplier = gammaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle, doExp = FALSE, doStats = FALSE) # Make combined plot. experimentDirs <- c(paste0(getwd(),"/Paper/AppSurveys/Output-RandomGearClust-nPA3500-runs5000"), paste0(getwd(),"/Paper/AppSurveys/Output-RandomGearClust-nPA2500-runs5000"), paste0(getwd(),"/Paper/AppSurveys/Output-RandomGearClust-nPA1500-runs5000"), paste0(getwd(),"/Paper/AppSurveys/Output-RandomGearClust-nPA500-runs5000")) experimentNames <- c(expression(n[samp] == 3500),expression(n[samp] == 2500), expression(n[samp] == 1500),expression(n[samp] == 500)) columnHeadings <- experimentNames plotDir <- paste0(getwd(),"/Paper/Main") xAxisTitle <- expression("gear difference " * (zeta^x)) plotTheseSDMs = c("PA","MsPP","Gear") # Statistic 1b: difference between true and estimated beta_1 coefficient. plotExperimentComparisons(experimentDirs, 1, whichCoeffs = c(2), plotSDMs = plotTheseSDMs, plotDevice = "png", plotDir = plotDir, #ylimVals = c(0,0.5,0,5), plotWidth = 15.8, plotHeight = 12, # plotWidth = 12, plotHeight = 12, fileName = "randNumPAwClustComparisonBeta1", xAxisTitle = xAxisTitle, columnHeadings = columnHeadings, accuracyPrecision = "accuracy") # Experiment 5 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppSurveys/Output-SpatialGearClust-nPA500-runs", format(numRuns)) gearUseStrategyPA <- "covar" numPA <- 500 numClusters <- 10 deltaMultiplier <- 0.0 gammaMultiplier <- 1.1 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, deltaMultiplier = deltaMultiplier, gammaMultiplier = gammaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle, doExp = FALSE, doStats = FALSE) # Experiment 6 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppSurveys/Output-SpatialGearClust-nPA1500-runs", format(numRuns)) gearUseStrategyPA <- "covar" numPA <- 1500 numClusters <- 10 deltaMultiplier <- 0.0 gammaMultiplier <- 1.1 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, deltaMultiplier = deltaMultiplier, gammaMultiplier = gammaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle, doExp = FALSE, doStats = FALSE) # Experiment 7 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppSurveys/Output-SpatialGearClust-nPA2500-runs", format(numRuns)) gearUseStrategyPA <- "covar" numPA <- 2500 numClusters <- 10 deltaMultiplier <- 0.0 gammaMultiplier <- 1.1 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, deltaMultiplier = deltaMultiplier, gammaMultiplier = gammaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle, doExp = FALSE, doStats = FALSE) # Experiment 8 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppSurveys/Output-SpatialGearClust-nPA3500-runs", format(numRuns)) gearUseStrategyPA <- "covar" numPA <- 3500 numClusters <- 10 deltaMultiplier <- 0.0 gammaMultiplier <- 1.1 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, deltaMultiplier = deltaMultiplier, gammaMultiplier = gammaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle, doExp = FALSE, doStats = FALSE) # Make combined plot. experimentDirs <- c(paste0(getwd(),"/Paper/AppSurveys/Output-SpatialGearClust-nPA3500-runs5000"), paste0(getwd(),"/Paper/AppSurveys/Output-SpatialGearClust-nPA2500-runs5000"), paste0(getwd(),"/Paper/AppSurveys/Output-SpatialGearClust-nPA1500-runs5000"), paste0(getwd(),"/Paper/AppSurveys/Output-SpatialGearClust-nPA500-runs5000")) experimentNames <- c(expression(n[samp] == 3500),expression(n[samp] == 2500), expression(n[samp] == 1500),expression(n[samp] == 500)) columnHeadings <- experimentNames plotDir <- paste0(getwd(),"/Paper/Main") xAxisTitle <- expression("gear difference " * (zeta^x)) plotTheseSDMs = c("PA","MsPP","Gear") # Statistic 1b: difference between true and estimated beta_1 coefficient. plotExperimentComparisons(experimentDirs, 1, whichCoeffs = c(2), plotSDMs = plotTheseSDMs, plotDevice = "png", plotDir = plotDir, #ylimVals = c(0,0.5,0,5), plotWidth = 15.8, plotHeight = 12, # plotWidth = 12, plotHeight = 12, fileName = "spatialNumPAwClustComparisonBeta1", xAxisTitle = xAxisTitle, columnHeadings = columnHeadings, accuracyPrecision = "accuracy") #--------------------------- # Number of PO random (with 2 x bias) #--------------------------- # Experiment 1 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppNumPOObs/Output-RandomGearBias-nPO10-runs", format(numRuns)) gearUseStrategyPA <- "rand" numPA <- 3500 numClusters <- 0 deltaMultiplier <- 2.0 gammaMultiplier <- 1.0 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, deltaMultiplier = deltaMultiplier, gammaMultiplier = gammaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle) # Experiment 2 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppNumPOObs/Output-RandomGearBias-nPO11-runs", format(numRuns)) gearUseStrategyPA <- "rand" numPA <- 3500 numClusters <- 0 deltaMultiplier <- 2.0 gammaMultiplier <- 1.1 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, deltaMultiplier = deltaMultiplier, gammaMultiplier = gammaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle, doExp=FALSE, doStats=FALSE) # Experiment 3 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppNumPOObs/Output-RandomGearBias-nPO12-runs", format(numRuns)) gearUseStrategyPA <- "rand" numPA <- 3500 numClusters <- 0 deltaMultiplier <- 2.0 gammaMultiplier <- 1.2 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, deltaMultiplier = deltaMultiplier, gammaMultiplier = gammaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle) # Experiment 4 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppNumPOObs/Output-RandomGearBias-nPO13-runs", format(numRuns)) gearUseStrategyPA <- "rand" numPA <- 3500 numClusters <- 0 deltaMultiplier <- 2.0 gammaMultiplier <- 1.3 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, deltaMultiplier = deltaMultiplier, gammaMultiplier = gammaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle) # Make combined plot. experimentDirs <- c(paste0(getwd(),"/Paper/AppNumPOObs/Output-RandomGearBias-nPO10-runs5000"), paste0(getwd(),"/Paper/AppNumPOObs/Output-RandomGearBias-nPO11-runs5000"), paste0(getwd(),"/Paper/AppNumPOObs/Output-RandomGearBias-nPO12-runs5000"), paste0(getwd(),"/Paper/AppNumPOObs/Output-RandomGearBias-nPO13-runs5000")) experimentNames <- c(expression(delta^x == 0),expression(delta^x == 1),expression(delta^x == 2)) experimentNames <- c(expression(gamma^x == 1.0),expression(gamma^x == 1.1), expression(gamma^x == 1.2),expression(gamma^x == 1.3)) columnHeadings <- experimentNames plotDir <- paste0(getwd(),"/Paper/Main") xAxisTitle <- expression("gear difference " * (zeta^x)) plotTheseSDMs = c("PA","MsPP","Gear") # Statistic 1b: difference between true and estimated beta_1 coefficient. plotExperimentComparisons(experimentDirs, 1, whichCoeffs = c(2), plotSDMs = plotTheseSDMs, plotDevice = "png", plotDir = plotDir, #ylimVals = c(0,0.5,0,5), plotWidth = 15.8, plotHeight = 12, # plotWidth = 12, plotHeight = 12, fileName = "randNumPOComparisonBeta1", xAxisTitle = xAxisTitle, columnHeadings = columnHeadings, accuracyPrecision = "accuracy") # Experiment 5 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppNumPOObs/Output-SpatialGearBias-nPO10-runs", format(numRuns)) gearUseStrategyPA <- "covar" numPA <- 3500 numClusters <- 0 deltaMultiplier <- 2.0 gammaMultiplier <- 1.0 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, deltaMultiplier = deltaMultiplier, gammaMultiplier = gammaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle) # Experiment 6 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppNumPOObs/Output-SpatialGearBias-nPO11-runs", format(numRuns)) gearUseStrategyPA <- "covar" numPA <- 3500 numClusters <- 0 deltaMultiplier <- 2.0 gammaMultiplier <- 1.1 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, deltaMultiplier = deltaMultiplier, gammaMultiplier = gammaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle) # Experiment 7 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppNumPOObs/Output-SpatialGearBias-nPO12-runs", format(numRuns)) gearUseStrategyPA <- "covar" numPA <- 3500 numClusters <- 0 deltaMultiplier <- 2.0 gammaMultiplier <- 1.2 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, deltaMultiplier = deltaMultiplier, gammaMultiplier = gammaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle) # Experiment 8 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppNumPOObs/Output-SpatialGearBias-nPO13-runs", format(numRuns)) gearUseStrategyPA <- "covar" numPA <- 3500 numClusters <- 0 deltaMultiplier <- 2.0 gammaMultiplier <- 1.3 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, deltaMultiplier = deltaMultiplier, gammaMultiplier = gammaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle) # Make combined plot. experimentDirs <- c(paste0(getwd(),"/Paper/AppNumPOObs/Output-SpatialGearBias-nPO10-runs5000"), paste0(getwd(),"/Paper/AppNumPOObs/Output-SpatialGearBias-nPO11-runs5000"), paste0(getwd(),"/Paper/AppNumPOObs/Output-SpatialGearBias-nPO12-runs5000"), paste0(getwd(),"/Paper/AppNumPOObs/Output-SpatialGearBias-nPO13-runs5000")) experimentNames <- c(expression(delta^x == 0),expression(delta^x == 1),expression(delta^x == 2)) experimentNames <- c(expression(gamma^x == 1.0),expression(gamma^x == 1.1), expression(gamma^x == 1.2),expression(gamma^x == 1.3)) columnHeadings <- experimentNames plotDir <- paste0(getwd(),"/Paper/Main") xAxisTitle <- expression("gear difference " * (zeta^x)) plotTheseSDMs = c("PA","MsPP","Gear") # Statistic 1b: difference between true and estimated beta_1 coefficient. plotExperimentComparisons(experimentDirs, 1, whichCoeffs = c(2), plotSDMs = plotTheseSDMs, plotDevice = "png", plotDir = plotDir, #ylimVals = c(0,0.5,0,5), plotWidth = 15.8, plotHeight = 12, # plotWidth = 12, plotHeight = 12, fileName = "spatialNumPOComparisonBeta1", xAxisTitle = xAxisTitle, columnHeadings = columnHeadings, accuracyPrecision = "accuracy") #--------------------------- # Ratio of PA to PO (with 2 x bias & 10 surveys) #--------------------------- # Experiment 1 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppRatio/Output-RandomGearBias-hPAhPO-runs", format(numRuns)) gearUseStrategyPA <- "rand" numPA <- 3500 numClusters <- 10 deltaMultiplier <- 2.0 gammaMultiplier <- 1.0 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, deltaMultiplier = deltaMultiplier, gammaMultiplier = gammaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle) # Experiment 2 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppRatio/Output-RandomGearBias-lPAhPO-runs", format(numRuns)) gearUseStrategyPA <- "rand" numPA <- 500 numClusters <- 10 deltaMultiplier <- 2.0 gammaMultiplier <- 1.0 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, deltaMultiplier = deltaMultiplier, gammaMultiplier = gammaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle) # Experiment 3 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppRatio/Output-RandomGearBias-hPAlPO-runs", format(numRuns)) gearUseStrategyPA <- "rand" numPA <- 3500 numClusters <- 10 deltaMultiplier <- 2.0 gammaMultiplier <- 1.3 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, deltaMultiplier = deltaMultiplier, gammaMultiplier = gammaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle) # Experiment 4 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppRatio/Output-RandomGearBias-lPAlPO-runs", format(numRuns)) gearUseStrategyPA <- "rand" numPA <- 500 numClusters <- 10 deltaMultiplier <- 2.0 gammaMultiplier <- 1.3 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, deltaMultiplier = deltaMultiplier, gammaMultiplier = gammaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle) # Make combined plot. experimentDirs <- c(paste0(getwd(),"/Paper/AppRatio/Output-RandomGearBias-hPAhPO-runs5000"), paste0(getwd(),"/Paper/AppRatio/Output-RandomGearBias-lPAhPO-runs5000"), paste0(getwd(),"/Paper/AppRatio/Output-RandomGearBias-hPAlPO-runs5000"), paste0(getwd(),"/Paper/AppRatio/Output-RandomGearBias-lPAlPO-runs5000")) experimentNames <- c(expression(list(n[samp] == 3500,gamma^x == 1.0)), expression(list(n[samp] == 500,gamma^x == 1.0)), expression(list(n[samp] == 3500,gamma^x == 1.3)), expression(list(n[samp] == 500,gamma^x == 1.3))) columnHeadings <- experimentNames plotDir <- paste0(getwd(),"/Paper/Main") xAxisTitle <- expression("gear difference " * (zeta^x)) plotTheseSDMs = c("PA","MsPP","Gear") # Statistic 1b: difference between true and estimated beta_1 coefficient. plotExperimentComparisons(experimentDirs, 1, whichCoeffs = c(2), plotSDMs = plotTheseSDMs, plotDevice = "png", plotDir = plotDir, #ylimVals = c(0,0.5,0,5), plotWidth = 15.8, plotHeight = 12, # plotWidth = 12, plotHeight = 12, fileName = "randRatioComparisonBeta1", xAxisTitle = xAxisTitle, columnHeadings = columnHeadings, accuracyPrecision = "accuracy") # Experiment 5 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppRatio/Output-SpatialGearBias-hPAhPO-runs", format(numRuns)) gearUseStrategyPA <- "covar" numPA <- 3500 numClusters <- 10 deltaMultiplier <- 2.0 gammaMultiplier <- 1.0 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, deltaMultiplier = deltaMultiplier, gammaMultiplier = gammaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle) # Experiment 6 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppRatio/Output-SpatialGearBias-lPAhPO-runs", format(numRuns)) gearUseStrategyPA <- "covar" numPA <- 500 numClusters <- 10 deltaMultiplier <- 2.0 gammaMultiplier <- 1.0 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, deltaMultiplier = deltaMultiplier, gammaMultiplier = gammaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle) # Experiment 7 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppRatio/Output-SpatialGearBias-hPAlPO-runs", format(numRuns)) gearUseStrategyPA <- "covar" numPA <- 3500 numClusters <- 10 deltaMultiplier <- 2.0 gammaMultiplier <- 1.3 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, deltaMultiplier = deltaMultiplier, gammaMultiplier = gammaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle) # Experiment 8 Setup ... numRuns <- 5000 scenariosDir <- paste0(getwd(), "/Paper/AppRatio/Output-SpatialGearBias-lPAlPO-runs", format(numRuns)) gearUseStrategyPA <- "covar" numPA <- 500 numClusters <- 10 deltaMultiplier <- 2.0 gammaMultiplier <- 1.3 zetaMultiplier <- seq(from=0.0, to=2.0, by=0.5) scenariosPrettyNames <- as.character(format(zetaMultiplier)) xAxisTitle <- expression("gear difference " * (zeta^x)) # Run experiment expLst <- runExperiment(scenariosDir, numRuns, gearUseStrategyPA = gearUseStrategyPA, numPA = numPA, numClusters = numClusters, deltaMultiplier = deltaMultiplier, gammaMultiplier = gammaMultiplier, zetaMultiplier = zetaMultiplier, scenariosPrettyNames = scenariosPrettyNames, xAxisTitle = xAxisTitle) # Make combined plot. experimentDirs <- c(paste0(getwd(),"/Paper/AppRatio/Output-SpatialGearBias-hPAhPO-runs5000"), paste0(getwd(),"/Paper/AppRatio/Output-SpatialGearBias-lPAhPO-runs5000"), paste0(getwd(),"/Paper/AppRatio/Output-SpatialGearBias-hPAlPO-runs5000"), paste0(getwd(),"/Paper/AppRatio/Output-SpatialGearBias-lPAlPO-runs5000")) experimentNames <- c(expression(list(n[samp] == 3500,gamma^x == 1.0)), expression(list(n[samp] == 500,gamma^x == 1.0)), expression(list(n[samp] == 3500,gamma^x == 1.3)), expression(list(n[samp] == 500,gamma^x == 1.3))) columnHeadings <- experimentNames plotDir <- paste0(getwd(),"/Paper/Main") xAxisTitle <- expression("gear difference " * (zeta^x)) plotTheseSDMs = c("PA","MsPP","Gear") # Statistic 1b: difference between true and estimated beta_1 coefficient. plotExperimentComparisons(experimentDirs, 1, whichCoeffs = c(2), plotSDMs = plotTheseSDMs, plotDevice = "png", plotDir = plotDir, #ylimVals = c(0,0.5,0,5), plotWidth = 15.8, plotHeight = 12, # plotWidth = 12, plotHeight = 12, fileName = "spatialRatioComparisonBeta1", xAxisTitle = xAxisTitle, columnHeadings = columnHeadings, accuracyPrecision = "accuracy") #-------------------------------------------------------------- # Map plots to demonstrate gear effect for one species example! #-------------------------------------------------------------- ### Plot to show difference between true species dist and MsPP SDM estimated (but without scale). # Look at just sample bias experiment (with no other degradations). spatialGearExpDir <- paste0(getwd(), "/Output-SpatialGear-runs5000") # Load results and plotting object (just simpler to use functions already written for this object) tmp <- load(paste0(spatialGearExpDir,"/Data/Results.RData")) # Worst species for beta1 coefficient worstSpecies <- names(sort(abs(statsObj$stats[[1]]$avg["2.0", ,"MsPP",2]),decreasing = TRUE))[1] # Get coastline polygon. load(paste0("../Data/Coastlines/southOceanPoly.RData")) coastPoly <- cm1 rm(cm1) if ( ! compareCRS(coastPoly@proj4string, simObj$proj) ) { # Project first, then set. coastPoly <- spTransform(coastPoly, simObj$proj) } # Make figure. NB: this is different to figure in draft 2 as have added exp(meanEstAlpha) to cell values. plotNames <- c(expression(zeta^x == 0.0), expression(zeta^x == 1.0), expression(zeta^x == 2.0)) rlPlot <- plotScenarioMaps(spatialGearExpDir, worstSpecies, "MsPP", c("ZMult0.0","ZMult1.0","ZMult2.0"), plotDevice = "png", plotDir = paste0(spatialGearExpDir,"/Plots"), plotWidth = 10.7, coastLine = coastPoly, colLand="lightgrey", nameLand = "Antarctica", posNameLand = c(-700,-100), useValues="intensity", fileName = "mapDiffTrueSpatialGearMsPP", plotNames = plotNames, plotDiff=TRUE, useAlpha=FALSE, colNA = "slategray1", zlim=c(-1.0,1.0)) #-------------------------------------------------------------- # Random and biased gear assignment example plot. #-------------------------------------------------------------- # Data files to use for example gear assignment plots. dataFile <- paste0("/ZMult0.0/DataDumps/DataExample-run1.RData") expDirs <- c(paste0(getwd(),"/Paper/AppNumSamps/Output-RandomGear-nPA3500-runs5000"), paste0(getwd(),"/Paper/AppNumSamps/Output-SpatialGear-nPA3500-runs5000"), paste0(getwd(),"/Paper/AppSurveys/Output-RandomGearClust-nPA3500-runs5000"), paste0(getwd(),"/Paper/AppSurveys/Output-SpatialGearClust-nPA3500-runs5000")) plotTitles <- c("Random gear assignment (Exp No. 1.R.1)", "Biased gear assignment (Exp No. 1.B.1)", "Random gear assignment (Exp No. 3.R.1)", "Biased gear assignment (Exp No. 3.B.1)") # Plot settings nPlots <- length(expDirs) colours <- colourBlindRGB() if ( length(expDirs) >= length(colours) ) stop("Not enough colours defined to plot this many lines on one plot.") pchSymbols <- c(NA,1:(length(expDirs)-1)) ltyLines <- rep("solid", times=length(colours)) yRange <- NULL nGears <- 3 densities <- array(data=vector(mode="list",length=(nGears+1)*nPlots), dim = c(nGears+1, nPlots), dimnames = list(c("All", paste0("g",1:3)),paste0("plot",1:nPlots))) maxDensityGear <- 0 nGearPlot <- matrix(0, nrow=nGears, ncol=nPlots) for ( p in 1:nPlots ) { # Load and format sample info ... tmp <- load(paste0(expDirs[p],dataFile)) xy <- surveyObj$xy gears <- surveyObj$gears nGears <- surveyObj$numGears surveyBath <- cellObj$covars[surveyObj$rowsInCells,1] # Get the density function for all the environment values. allBath <- cellObj$covars[ ,1] densities[1,p][[1]] <- density(allBath) # Get the densities for the survey environment values per gear. for ( g in 1:nGears ) { indGear <- which(gears == g) nGearPlot[g,p] <- length(indGear) densities[g+1,p][[1]] <- density(surveyBath[indGear]) maxDensityGear <- max(densities[g+1,p][[1]]$y, maxDensityGear) } # Get the required range for all plots. xRange <- range(densities[1,p][[1]]$x) yRange <- range(c(densities[1,p][[1]]$y, maxDensityGear, yRange)) } # Which device are we printing to? plotDevice = "png" if ( plotDevice == "RStudioGD" ) { # plot to the R studio plot window. plotToFile <- FALSE } else { fileName <- makeFileName("GearTypeDensities", paste0(getwd(),"/Paper/Main"), plotDevice) argList <- list(filename = fileName, width = 15.75, height = 15.75, units = "cm", res = 600) do.call(plotDevice, argList) plotToFile <- TRUE } # Plots ... opar <- par(mfrow = c(2,2), mar=c(3.6,3.6,2.1,0.5), cex=0.66, cex.main=0.9) for ( p in 1:nPlots ) { # Plot bathymetry density. plot(densities[1,p][[1]]$x, densities[1,p][[1]]$y, ylim=yRange, type="l", col=colours[1], lty=ltyLines[1], main=plotTitles[p], xlab="", ylab="") title(xlab="centred bathymetry", ylab = "density", line=2.5) abline(list(h=0.0), lty="dotted") # Add gear densities. for ( g in 1:nGears ) { x <- densities[g+1,p][[1]]$x y <- densities[g+1,p][[1]]$y lines(x, y, col=colours[g+1], lty=ltyLines[g+1]) # Plot symbols on lines (not all as too messy) numX <- length(x) pts <- seq(from=1, to=numX, by=50) + g*10 # offset so symbols aren't all in same place. numPts <- length(pts) pts[numPts] <- min(pts[numPts], numX) # make sure the last value isn't too large. points(x[pts], y[pts], col=colours[g+1], pch=pchSymbols[g+1]) } # Add legend. legend("topleft", legend=c("all cells", paste0("gear ", 1:nGears)), col=colours[1:(nGears+1)], lty=ltyLines[1:(nGears+1)], pch=pchSymbols[1:(nGears+1)]) # Add second legend. # legend("topright", legend=paste0("gear ", 1:nGears, " = ", nGearPlot[ ,p]), bty="n", # title = "No. samples using:") } par(opar) if ( plotToFile ) dev.off()
d5e7a57ee18c63980c33e9db4271e4c668109498
dbeaba5b84c9b9091c3b96def43ac44a95a878df
/R/obcp.R
9eca946e5a9bbbfea1303014a8931f04f35f12d2
[]
no_license
timkaye11/obcp
3fe4e5d663c12f7240ceafdfc65cec2858eae3b0
acb9c4c02a23daeac4f8b8325fd278ad15bdf2bc
refs/heads/master
2021-01-23T10:44:49.499555
2015-01-27T04:43:31
2015-01-27T04:43:31
29,788,284
0
0
null
null
null
null
UTF-8
R
false
false
5,262
r
obcp.R
obcp_output <- structure(list(), class = "obcp_output") #' #' Performs the algorithm outlined in the paper by Adams and MacKay. #' #' Input must be a vector. The function outputs relevant data from the simulation, including the r_t table #' #' @param data A vector of data to be analyzed. Must be a one-dimensional time series #' @param mu0 The prior for mu. The default is set to 0, but it may not be suitable for all data #' @param kappa0 The prior for kappa. The default is set to 1. #' @param alpha0 The prior for alpha in the inverse-gamma distribution #' @param beta0 The prior for beta in the inverse-gamma distribution #' #' @keywords online, bayesian, changepoint, normal-inverse-gamma #' @return a S3 object containing the r_t, maxes, and other information. #' @export #' @examples #' output <- obcp(data, mu=0, kappa=2, alpha=2, beta=4) #' summary(output) obcp <- function(data, mu0, kappa0, alpha0, beta0) { # for referencing data size t <- length(data) # parameters for the normal-inverse-gamma distribution mu <- mu0 kappa <- kappa0 alpha <- alpha0 beta <- beta0 # matrix containing the run length probabilities (r_t) R <- matrix(0, nrow=t+1, ncol=t+1) # at t=1, the run length is definitely 1. Initialize table R[1,1] <- 1 # keep track of the maximum probabilities maxes <- rep(0, t+1) for (i in 1:t) { # the predictive posterior distribution for each new data observation under each of the params pred_post <- dt_ls(data[i], 2*alpha, mu, beta*(kappa+1)/(alpha*kappa)) # calculate the hazard function for this interval H <- hazard_func(i, 100) # calculate the growth probability (step 4 in Algorithm 1) R[2:(i+1), i+1] <- R[1:i, i] * pred_post * (1-H) # calculate the changepoint probability (step 5 in Algorithm 1) # this is the probability that there was an observed changepoint R[1, i+1] <- sum( R[1:i, i] * pred_post * H ) # normalize run length probability - improves accuracy R[,i+1] = R[,i+1] / sum(R[,i+1]) # update the sufficient statistics (parameters) - Step 8 in Alg 1 mu_new = c(mu0, (kappa*mu + data[i]) / (kappa + 1)) kappa_new <- c(kappa0, kappa + 1) alpha_new <- c(alpha0, alpha + 0.5) beta_new <- c(beta0, beta + (kappa *(data[i]-mu)^2) / (2*(kappa+1))) mu <- mu_new kappa <- kappa_new alpha <- alpha_new beta <- beta_new # store the max value maxes[i] <- which(R[,i] == max(R[,i])) } #print(R) coeffs <- list(mu=mu, kappa=kappa, alpha=alpha, beta=beta) output <- list(data=data, maxes=maxes, coeffs=coeffs, r_t=R, t=t, last_col=R[,t+1]) return (structure(output, class="obcp_output")) } #' Add new data to the online bayesian changepoint detection model. Used to add new incoming data to the #' original model. #' #' Given a new data input, the posterior estimate is calculated, as well as the probability of a changepoint. The #' posterior is updated and the max value is recorded in the obcp object. #' #' @param obcp The output of the original obcp algorithm #' @param data the data to be added to the model #' @keywords online, data, add data #' @export #' @examples #' model <- obcp(data, 0, 1, 1, 1) #' new_data <- c(24.4, 25.5, 26.6) #' sapply(new_data, function(x) { add_data(model, x) }) #' model #' add_data <- function(obcp, data) { if (length(data) > 1) { stop("data must be 1 observation")} if (length(obcp$last_col) < 20) { stop("it is recommended that you have at least 20 obs")} coeffs <- obcp$coeffs mu <- coeffs$mu kappa <- coeffs$kappa alpha <- coeffs$alpha beta <- coeffs$beta # calculate posterior pred_post <- dt_ls(data, 2*alpha, mu, beta*(kappa+1)/(alpha*kappa)) # for changepoint detection last_col <- obcp$last_col t <- length(last_col) probs <- rep(0, t+1) # growth probability probs[2:(t+1)] <- last_col * pred_post * (1-H) # changepoint probability probs[1] <- sum( last_col * pred_post * H) # update the sufficient statistics (parameters) - Step 8 in Alg 1 mu_new = c(mu0, (kappa*mu + data) / (kappa + 1)) kappa_new <- c(kappa0, kappa + 1) alpha_new <- c(alpha0, alpha + 0.5) beta_new <- c(beta0, beta + (kappa *(data-mu)^2) / (2*(kappa+1))) obcp$coeffs$mu <<- mu_new obcp$coeffs$kappa <<- kappa_new obcp$coeffs$alpha <<- alpha_new obcp$coeffs$beta <<- beta_new obcp$maxes <<- c(obcp$maxes, which(probs == max(probs))) obcp$last_col <<- probs obcp$data <<- append(obcp$data, data) return (obcp) } #' Find where the changepoints occured. #' #' Detects the location of the changepoints from the data points that the model has seen so far #' #' @param obcp the online bayesian changepoint detection model #' @param num the number of changepoints to detect. sorted by p-value #' @keywords find, changepoints #' @export #' @examples #' model <- obcp(data, 0, 1, 1, 1) #' # finds the top three changepoints #' find_changepoints(model, 3) find_changepoints <- function(obcp, num) { maxes <- obcp$maxes if (num > length(maxes)) stop("the number of changepoints cannot be longer than the data observed") diffed <- diff(maxes) sort_diff <- sort(diffed) locs <- match(sort_diff[1:num], diffed) return (locs) }
cd74d0ca29c7994ec11623f411eb4f3356a55e24
faaa3f61425d5ab0bac36c1a4c7911d28d4c3479
/1.R_Courses/Introduction_to_importing_Data_in_R/4.Reproducible_Excel_work_with_XLConnect.r
f8c5014fbfea78adb0fe5989324c9e20b5e3ced3
[]
no_license
satyamchaturvedi/datacamp
7650ad87a53f3f43e205065236ba26c5fc68f86e
c0e9736f765a28e436c1d70be3e08ca8cc4c52b7
refs/heads/main
2023-04-10T01:00:45.415983
2021-04-16T16:00:55
2021-04-16T16:00:55
null
0
0
null
null
null
null
UTF-8
R
false
false
5,152
r
4.Reproducible_Excel_work_with_XLConnect.r
# Connect to a workbook When working with XLConnect, the first step will be to load a workbook in your R session with loadWorkbook(); this function will build a "bridge" between your Excel file and your R session. In this and the following exercises, you will continue to work with urbanpop.xlsx, containing urban population data throughout time. The Excel file is available in your current working directory. # urbanpop.xlsx is available in your working directory # Load the XLConnect package library(XLConnect) # Build connection to urbanpop.xlsx: my_book my_book <- loadWorkbook("urbanpop.xlsx") # Print out the class of my_book class(my_book) ------ # List and read Excel sheets Just as readxl and gdata, you can use XLConnect to import data from Excel file into R. To list the sheets in an Excel file, use getSheets(). To actually import data from a sheet, you can use readWorksheet(). Both functions require an XLConnect workbook object as the first argument. Youll again be working with urbanpop.xlsx. The my_book object that links to this Excel file has already been created. # XLConnect is already available # Build connection to urbanpop.xlsx my_book <- loadWorkbook("urbanpop.xlsx") # List the sheets in my_book getSheets(my_book) # Import the second sheet in my_book readWorksheet(my_book, sheet = 2) ----- # Customize readWorksheet To get a clear overview about urbanpop.xlsx without having to open up the Excel file, you can execute the following code: my_book <- loadWorkbook("urbanpop.xlsx") sheets <- getSheets(my_book) all <- lapply(sheets, readWorksheet, object = my_book) str(all) Suppose were only interested in urban population data of the years 1968, 1969 and 1970. The data for these years is in the columns 3, 4, and 5 of the second sheet. Only selecting these columns will leave us in the dark about the actual countries the figures belong to. # XLConnect is already available # Build connection to urbanpop.xlsx my_book <- loadWorkbook("urbanpop.xlsx") # Import columns 3, 4, and 5 from second sheet in my_book: urbanpop_sel urbanpop_sel <- readWorksheet(my_book, sheet = 2,startCol = 3,endCol = 5) # Import first column from second sheet in my_book: countries countries <- readWorksheet(my_book, sheet = 2, startCol = 1,endCol = 1) # cbind() urbanpop_sel and countries together: selection selection <- cbind(countries,urbanpop_sel) ----- # Add worksheet Where readxl and gdata were only able to import Excel data, XLConnects approach of providing an actual interface to an Excel file makes it able to edit your Excel files from inside R. In this exercise, you'll create a new sheet. In the next exercise, you'll populate the sheet with data, and save the results in a new Excel file. Youll continue to work with urbanpop.xlsx. The my_book object that links to this Excel file is already available. # XLConnect is already available # Build connection to urbanpop.xlsx my_book <- loadWorkbook("urbanpop.xlsx") # Add a worksheet to my_book, named "data_summary" createSheet(my_book,name="data_summary") # Use getSheets() on my_book getSheets(my_book) ----- # Populate worksheet The first step of creating a sheet is done; lets populate it with some data now! summ, a data frame with some summary statistics on the two Excel sheets is already coded so you can take it from there. # XLConnect is already available # Build connection to urbanpop.xlsx my_book <- loadWorkbook("urbanpop.xlsx") # Add a worksheet to my_book, named "data_summary" createSheet(my_book, "data_summary") # Create data frame: summ sheets <- getSheets(my_book)[1:3] dims <- sapply(sheets, function(x) dim(readWorksheet(my_book, sheet = x)), USE.NAMES = FALSE) summ <- data.frame(sheets = sheets, nrows = dims[1, ], ncols = dims[2, ]) # Add data in summ to "data_summary" sheet writeWorksheet(my_book,summ,sheet="data_summary") # Save workbook as summary.xlsx saveWorkbook(my_book,"summary.xlsx") ----- # Renaming sheets Come to think of it, "data_summary" is not an ideal name. As the summary of these excel sheets is always data-related, you simply want to name the sheet "summary". The code to build a connection to "urbanpop.xlsx" and create my_book is already provided for you. It refers to an Excel file with 4 sheets: the three data sheets, and the "data_summary" sheet. # Build connection to urbanpop.xlsx: my_book my_book <- loadWorkbook("urbanpop.xlsx") # Rename "data_summary" sheet to "summary" renameSheet(my_book,"data_summary","summary") # Print out sheets of my_book getSheets(my_book) # Save workbook to "renamed.xlsx" saveWorkbook(my_book,"renamed.xlsx") ----- # Removing sheets After presenting the new Excel sheet to your peers, it appears not everybody is a big fan. Why summarize sheets and store the info in Excel if all the information is implicitly available? To hell with it, just remove the entire fourth sheet! # Load the XLConnect package library(XLConnect) # Build connection to renamed.xlsx: my_book my_book <- loadWorkbook("renamed.xlsx") # Remove the fourth sheet removeSheet(my_book,sheet=4) # Save workbook to "clean.xlsx" saveWorkbook(my_book,"clean.xlsx") -----
e7f3e545ed3c91a2a9c7a75555dac6676f115617
3451121d029597d1e68a5d79c9f4695bb4265b21
/test_userManage/dataToXts.R
137f40b0000b78ab6c78bf50729e3fc9ce7e1790
[]
no_license
ashther/shinyApp
922b0f9dd2798db7eb45fbf29cc46d6f26dc8c89
6f8e572734acd2ef93ad8d6c629154e26f3d5701
refs/heads/master
2021-01-16T23:33:14.673884
2016-12-05T02:58:11
2016-12-05T02:58:11
53,815,165
0
0
null
2016-07-28T00:05:45
2016-03-14T00:22:15
R
UTF-8
R
false
false
23,061
r
dataToXts.R
hourly_new <- xts(hourly_login$new, order.by = hourly_login$date_time) names(hourly_new) <- 'new' hourly_active <- xts(hourly_login$active, order.by = hourly_login$date_time) names(hourly_active) <- 'active' hourly_log_in <- xts(hourly_login$login, order.by = hourly_login$date_time) names(hourly_log_in) <- 'login' daily_new <- xts(daily_login$new, order.by = daily_login$date_time) names(daily_new) <- 'new' daily_active <- xts(daily_login$active, order.by = daily_login$date_time) names(daily_active) <- 'active' daily_log_in <- xts(daily_login$login, order.by = daily_login$date_time) names(daily_log_in) <- 'login' daily_retention <- xts(daily_login$retention, order.by = daily_login$date_time) names(daily_retention) <- 'retention' daily_freq_5p <- xts(daily_login$freq_5p, order.by = daily_login$date_time) names(daily_freq_5p) <- '5+' daily_freq_5 <- xts(daily_login$freq_5, order.by = daily_login$date_time) names(daily_freq_5) <- '5' daily_freq_4 <- xts(daily_login$freq_4, order.by = daily_login$date_time) names(daily_freq_4) <- '4' daily_freq_3 <- xts(daily_login$freq_3, order.by = daily_login$date_time) names(daily_freq_3) <- '3' daily_freq_2 <- xts(daily_login$freq_2, order.by = daily_login$date_time) names(daily_freq_2) <- '2' daily_freq_1 <- xts(daily_login$freq_1, order.by = daily_login$date_time) names(daily_freq_1) <- '1' weekly_new <- xts(weekly_login$new, order.by = weekly_login$date_time) names(weekly_new) <- 'new' weekly_active <- xts(weekly_login$active, order.by = weekly_login$date_time) names(weekly_active) <- 'active' weekly_log_in <- xts(weekly_login$login, order.by = weekly_login$date_time) names(weekly_log_in) <- 'login' weekly_retention <- xts(weekly_login$retention, order.by = weekly_login$date_time) names(weekly_retention) <- 'retention' monthly_new <- xts(monthly_login$new, order.by = monthly_login$date_time) names(monthly_new) <- 'new' monthly_active <- xts(monthly_login$active, order.by = monthly_login$date_time) names(monthly_active) <- 'active' monthly_log_in <- xts(monthly_login$login, order.by = monthly_login$date_time) names(monthly_log_in) <- 'login' monthly_retention <- xts(monthly_login$retention, order.by = monthly_login$date_time) names(monthly_retention) <- 'retention' # ============================================================================= hourly_calendar_new_activity <- xts(hourly_calendar$new_activity, order.by = hourly_calendar$date_time) names(hourly_calendar_new_activity) <- 'new_activity' hourly_calendar_new_user <- xts(hourly_calendar$new_user, order.by = hourly_calendar$date_time) names(hourly_calendar_new_user) <- 'new_user' daily_calendar_new_activity <- xts(daily_calendar$new_activity, order.by = daily_calendar$date_time) names(daily_calendar_new_activity) <- 'new_activity' daily_calendar_new_user <- xts(daily_calendar$new_user, order.by = daily_calendar$date_time) names(daily_calendar_new_user) <- 'new_user' weekly_calendar_new_activity <- xts(weekly_calendar$new_activity, order.by = weekly_calendar$date_time) names(weekly_calendar_new_activity) <- 'new_activity' weekly_calendar_new_user <- xts(weekly_calendar$new_user, order.by = weekly_calendar$date_time) names(weekly_calendar_new_user) <- 'new_user' monthly_calendar_new_activity <- xts(monthly_calendar$new_activity, order.by = monthly_calendar$date_time) names(monthly_calendar_new_activity) <- 'new_activity' monthly_calendar_new_user <- xts(monthly_calendar$new_user, order.by = monthly_calendar$date_time) names(monthly_calendar_new_user) <- 'new_user' # ============================================================================= hourly_cooperation_new_company <- xts(hourly_cooperation$new_company, order.by = hourly_cooperation$date_time) names(hourly_cooperation_new_company) <- 'new_company' hourly_cooperation_new_project <- xts(hourly_cooperation$new_project, order.by = hourly_cooperation$date_time) names(hourly_cooperation_new_project) <- 'new_project' hourly_cooperation_active_user <- xts(hourly_cooperation$active_user, order.by = hourly_cooperation$date_time) names(hourly_cooperation_active_user) <- 'active_user' hourly_cooperation_new_view <- xts(hourly_cooperation$new_view, order.by = hourly_cooperation$date_time) names(hourly_cooperation_new_view) <- 'new_view' hourly_cooperation_new_collect <- xts(hourly_cooperation$new_collect, order.by = hourly_cooperation$date_time) names(hourly_cooperation_new_collect) <- 'new_collect' hourly_cooperation_new_apply <- xts(hourly_cooperation$new_apply, order.by = hourly_cooperation$date_time) names(hourly_cooperation_new_apply) <- 'new_apply' daily_cooperation_new_company <- xts(daily_cooperation$new_company, order.by = daily_cooperation$date_time) names(daily_cooperation_new_company) <- 'new_company' daily_cooperation_new_project <- xts(daily_cooperation$new_project, order.by = daily_cooperation$date_time) names(daily_cooperation_new_project) <- 'new_project' daily_cooperation_active_user <- xts(daily_cooperation$active_user, order.by = daily_cooperation$date_time) names(daily_cooperation_active_user) <- 'active_user' daily_cooperation_new_view <- xts(daily_cooperation$new_view, order.by = daily_cooperation$date_time) names(daily_cooperation_new_view) <- 'new_view' daily_cooperation_new_collect <- xts(daily_cooperation$new_collect, order.by = daily_cooperation$date_time) names(daily_cooperation_new_collect) <- 'new_collect' daily_cooperation_new_apply <- xts(daily_cooperation$new_apply, order.by = daily_cooperation$date_time) names(daily_cooperation_new_apply) <- 'new_apply' weekly_cooperation_new_company <- xts(weekly_cooperation$new_company, order.by = weekly_cooperation$date_time) names(weekly_cooperation_new_company) <- 'new_company' weekly_cooperation_new_project <- xts(weekly_cooperation$new_project, order.by = weekly_cooperation$date_time) names(weekly_cooperation_new_project) <- 'new_project' weekly_cooperation_active_user <- xts(weekly_cooperation$active_user, order.by = weekly_cooperation$date_time) names(weekly_cooperation_active_user) <- 'active_user' weekly_cooperation_new_view <- xts(weekly_cooperation$new_view, order.by = weekly_cooperation$date_time) names(weekly_cooperation_new_view) <- 'new_view' weekly_cooperation_new_collect <- xts(weekly_cooperation$new_collect, order.by = weekly_cooperation$date_time) names(weekly_cooperation_new_collect) <- 'new_collect' weekly_cooperation_new_apply <- xts(weekly_cooperation$new_apply, order.by = weekly_cooperation$date_time) names(weekly_cooperation_new_apply) <- 'new_apply' monthly_cooperation_new_company <- xts(monthly_cooperation$new_company, order.by = monthly_cooperation$date_time) names(monthly_cooperation_new_company) <- 'new_company' monthly_cooperation_new_project <- xts(monthly_cooperation$new_project, order.by = monthly_cooperation$date_time) names(monthly_cooperation_new_project) <- 'new_project' monthly_cooperation_active_user <- xts(monthly_cooperation$active_user, order.by = monthly_cooperation$date_time) names(monthly_cooperation_active_user) <- 'active_user' monthly_cooperation_new_view <- xts(monthly_cooperation$new_view, order.by = monthly_cooperation$date_time) names(monthly_cooperation_new_view) <- 'new_view' monthly_cooperation_new_collect <- xts(monthly_cooperation$new_collect, order.by = monthly_cooperation$date_time) names(monthly_cooperation_new_collect) <- 'new_collect' monthly_cooperation_new_apply <- xts(monthly_cooperation$new_apply, order.by = monthly_cooperation$date_time) names(monthly_cooperation_new_apply) <- 'new_apply' # ============================================================================= hourly_hr_new_user <- xts(hourly_hr$new_user, order.by = hourly_hr$date_time) names(hourly_hr_new_user) <- 'new_user' hourly_hr_new_company <- xts(hourly_hr$new_company, order.by = hourly_hr$date_time) names(hourly_hr_new_company) <- 'new_company' hourly_hr_new_recruitment <- xts(hourly_hr$new_recruitment, order.by = hourly_hr$date_time) names(hourly_hr_new_recruitment) <- 'new_recruitment' hourly_hr_update_recruitment <- xts(hourly_hr$update_recruitment, order.by = hourly_hr$date_time) names(hourly_hr_update_recruitment) <- 'update_recruitment' hourly_hr_jobseekers_operation <- xts(hourly_hr$jobseekers_operation, order.by = hourly_hr$date_time) names(hourly_hr_jobseekers_operation) <- 'jobseekers_operation' hourly_hr_hr_operation <- xts(hourly_hr$hr_operation, order.by = hourly_hr$date_time) names(hourly_hr_hr_operation) <- 'hr_operation' daily_hr_new_user <- xts(daily_hr$new_user, order.by = daily_hr$date_time) names(daily_hr_new_user) <- 'new_user' daily_hr_new_company <- xts(daily_hr$new_company, order.by = daily_hr$date_time) names(daily_hr_new_company) <- 'new_company' daily_hr_new_recruitment <- xts(daily_hr$new_recruitment, order.by = daily_hr$date_time) names(daily_hr_new_recruitment) <- 'new_recruitment' daily_hr_update_recruitment <- xts(daily_hr$update_recruitment, order.by = daily_hr$date_time) names(daily_hr_update_recruitment) <- 'update_recruitment' daily_hr_jobseekers_operation <- xts(daily_hr$jobseekers_operation, order.by = daily_hr$date_time) names(daily_hr_jobseekers_operation) <- 'jobseekers_operation' daily_hr_hr_operation <- xts(daily_hr$hr_operation, order.by = daily_hr$date_time) names(daily_hr_hr_operation) <- 'hr_operation' weekly_hr_new_user <- xts(weekly_hr$new_user, order.by = weekly_hr$date_time) names(weekly_hr_new_user) <- 'new_user' weekly_hr_new_company <- xts(weekly_hr$new_company, order.by = weekly_hr$date_time) names(weekly_hr_new_company) <- 'new_company' weekly_hr_new_recruitment <- xts(weekly_hr$new_recruitment, order.by = weekly_hr$date_time) names(weekly_hr_new_recruitment) <- 'new_recruitment' weekly_hr_update_recruitment <- xts(weekly_hr$update_recruitment, order.by = weekly_hr$date_time) names(weekly_hr_update_recruitment) <- 'update_recruitment' weekly_hr_jobseekers_operation <- xts(weekly_hr$jobseekers_operation, order.by = weekly_hr$date_time) names(weekly_hr_jobseekers_operation) <- 'jobseekers_operation' weekly_hr_hr_operation <- xts(weekly_hr$hr_operation, order.by = weekly_hr$date_time) names(weekly_hr_hr_operation) <- 'hr_operation' monthly_hr_new_user <- xts(monthly_hr$new_user, order.by = monthly_hr$date_time) names(monthly_hr_new_user) <- 'new_user' monthly_hr_new_company <- xts(monthly_hr$new_company, order.by = monthly_hr$date_time) names(monthly_hr_new_company) <- 'new_company' monthly_hr_new_recruitment <- xts(monthly_hr$new_recruitment, order.by = monthly_hr$date_time) names(monthly_hr_new_recruitment) <- 'new_recruitment' monthly_hr_update_recruitment <- xts(monthly_hr$update_recruitment, order.by = monthly_hr$date_time) names(monthly_hr_update_recruitment) <- 'update_recruitment' monthly_hr_jobseekers_operation <- xts(monthly_hr$jobseekers_operation, order.by = monthly_hr$date_time) names(monthly_hr_jobseekers_operation) <- 'jobseekers_operation' monthly_hr_hr_operation <- xts(monthly_hr$hr_operation, order.by = monthly_hr$date_time) names(monthly_hr_hr_operation) <- 'hr_operation' # ============================================================================= hourly_quick_chat_active_circle <- xts(hourly_quick_chat$active_circle, order.by = hourly_quick_chat$date_time) names(hourly_quick_chat_active_circle) <- 'active_circle' hourly_quick_chat_message <- xts(hourly_quick_chat$message, order.by = hourly_quick_chat$date_time) names(hourly_quick_chat_message) <- 'message' hourly_quick_chat_active_user <- xts(hourly_quick_chat$active_user, order.by = hourly_quick_chat$date_time) names(hourly_quick_chat_active_user) <- 'active_user' daily_quick_chat_active_circle <- xts(daily_quick_chat$active_circle, order.by = daily_quick_chat$date_time) names(daily_quick_chat_active_circle) <- 'active_circle' daily_quick_chat_message <- xts(daily_quick_chat$message, order.by = daily_quick_chat$date_time) names(daily_quick_chat_message) <- 'message' daily_quick_chat_active_user <- xts(daily_quick_chat$active_user, order.by = daily_quick_chat$date_time) names(daily_quick_chat_active_user) <- 'active_user' weekly_quick_chat_active_circle <- xts(weekly_quick_chat$active_circle, order.by = weekly_quick_chat$date_time) names(weekly_quick_chat_active_circle) <- 'active_circle' weekly_quick_chat_message <- xts(weekly_quick_chat$message, order.by = weekly_quick_chat$date_time) names(weekly_quick_chat_message) <- 'message' weekly_quick_chat_active_user <- xts(weekly_quick_chat$active_user, order.by = weekly_quick_chat$date_time) names(weekly_quick_chat_active_user) <- 'active_user' monthly_quick_chat_active_circle <- xts(monthly_quick_chat$active_circle, order.by = monthly_quick_chat$date_time) names(monthly_quick_chat_active_circle) <- 'active_circle' monthly_quick_chat_message <- xts(monthly_quick_chat$message, order.by = monthly_quick_chat$date_time) names(monthly_quick_chat_message) <- 'message' monthly_quick_chat_active_user <- xts(monthly_quick_chat$active_user, order.by = monthly_quick_chat$date_time) names(monthly_quick_chat_active_user) <- 'active_user' # ============================================================================= hourly_schedule_new_course <- xts(hourly_schedule$new_course, order.by = hourly_schedule$date_time) names(hourly_schedule_new_course) <- 'new_course' hourly_schedule_new_user <- xts(hourly_schedule$new_user, order.by = hourly_schedule$date_time) names(hourly_schedule_new_user) <- 'new_user' hourly_schedule_active_user <- xts(hourly_schedule$active_user, order.by = hourly_schedule$date_time) names(hourly_schedule_active_user) <- 'active_user' hourly_schedule_new_file <- xts(hourly_schedule$new_file, order.by = hourly_schedule$date_time) names(hourly_schedule_new_file) <- 'new_file' hourly_schedule_oepration <- xts(hourly_schedule$operation, order.by = hourly_schedule$date_time) names(hourly_schedule_oepration) <- 'operation' daily_schedule_new_course <- xts(daily_schedule$new_course, order.by = daily_schedule$date_time) names(daily_schedule_new_course) <- 'new_course' daily_schedule_new_user <- xts(daily_schedule$new_user, order.by = daily_schedule$date_time) names(daily_schedule_new_user) <- 'new_user' daily_schedule_active_user <- xts(daily_schedule$active_user, order.by = daily_schedule$date_time) names(daily_schedule_active_user) <- 'active_user' daily_schedule_new_file <- xts(daily_schedule$new_file, order.by = daily_schedule$date_time) names(daily_schedule_new_file) <- 'new_file' daily_schedule_operation <- xts(daily_schedule$operation, order.by = daily_schedule$date_time) names(daily_schedule_operation) <- 'operation' weekly_schedule_new_course <- xts(weekly_schedule$new_course, order.by = weekly_schedule$date_time) names(weekly_schedule_new_course) <- 'new_course' weekly_schedule_new_user <- xts(weekly_schedule$new_user, order.by = weekly_schedule$date_time) names(weekly_schedule_new_user) <- 'new_user' weekly_schedule_active_user <- xts(weekly_schedule$active_user, order.by = weekly_schedule$date_time) names(weekly_schedule_active_user) <- 'active_user' weekly_schedule_new_file <- xts(weekly_schedule$new_file, order.by = weekly_schedule$date_time) names(weekly_schedule_new_file) <- 'new_file' weekly_schedule_oepration <- xts(weekly_schedule$operation, order.by = weekly_schedule$date_time) names(weekly_schedule_oepration) <- 'operation' monthly_schedule_new_course <- xts(monthly_schedule$new_course, order.by = monthly_schedule$date_time) names(monthly_schedule_new_course) <- 'new_course' monthly_schedule_new_user <- xts(monthly_schedule$new_user, order.by = monthly_schedule$date_time) names(monthly_schedule_new_user) <- 'new_user' monthly_schedule_active_user <- xts(monthly_schedule$active_user, order.by = monthly_schedule$date_time) names(monthly_schedule_active_user) <- 'active_user' monthly_schedule_new_file <- xts(monthly_schedule$new_file, order.by = monthly_schedule$date_time) names(monthly_schedule_new_file) <- 'new_file' monthly_schedule_oepration <- xts(monthly_schedule$operation, order.by = monthly_schedule$date_time) names(monthly_schedule_oepration) <- 'operation' # ============================================================================= hourly_trade_new_sell_info <- xts(hourly_trade$new_sell_info, order.by = hourly_trade$date_time) names(hourly_trade_new_sell_info) <- 'new_sell_info' hourly_trade_new_buy_info <- xts(hourly_trade$new_buy_info, order.by = hourly_trade$date_time) names(hourly_trade_new_buy_info) <- 'new_buy_info' hourly_trade_active_seller <- xts(hourly_trade$active_seller, order.by = hourly_trade$date_time) names(hourly_trade_active_seller) <- 'active_seller' hourly_trade_active_buyer <- xts(hourly_trade$active_buyer, order.by = hourly_trade$date_time) names(hourly_trade_active_buyer) <- 'active_buyer' hourly_trade_active_trader <- xts(hourly_trade$active_trader, order.by = hourly_trade$date_time) names(hourly_trade_active_trader) <- 'active_trader' daily_trade_new_sell_info <- xts(daily_trade$new_sell_info, order.by = daily_trade$date_time) names(daily_trade_new_sell_info) <- 'new_sell_info' daily_trade_new_buy_info <- xts(daily_trade$new_buy_info, order.by = daily_trade$date_time) names(daily_trade_new_buy_info) <- 'new_buy_info' daily_trade_active_seller <- xts(daily_trade$active_seller, order.by = daily_trade$date_time) names(daily_trade_active_seller) <- 'active_seller' daily_trade_active_buyer <- xts(daily_trade$active_buyer, order.by = daily_trade$date_time) names(daily_trade_active_buyer) <- 'active_buyer' daily_trade_active_trader <- xts(daily_trade$active_trader, order.by = daily_trade$date_time) names(daily_trade_active_trader) <- 'active_trader' weekly_trade_new_sell_info <- xts(weekly_trade$new_sell_info, order.by = weekly_trade$date_time) names(weekly_trade_new_sell_info) <- 'new_sell_info' weekly_trade_new_buy_info <- xts(weekly_trade$new_buy_info, order.by = weekly_trade$date_time) names(weekly_trade_new_buy_info) <- 'new_buy_info' weekly_trade_active_seller <- xts(weekly_trade$active_seller, order.by = weekly_trade$date_time) names(weekly_trade_active_seller) <- 'active_seller' weekly_trade_active_buyer <- xts(weekly_trade$active_buyer, order.by = weekly_trade$date_time) names(weekly_trade_active_buyer) <- 'active_buyer' weekly_trade_active_trader <- xts(weekly_trade$active_trader, order.by = weekly_trade$date_time) names(weekly_trade_active_trader) <- 'active_trader' monthly_trade_new_sell_info <- xts(monthly_trade$new_sell_info, order.by = monthly_trade$date_time) names(monthly_trade_new_sell_info) <- 'new_sell_info' monthly_trade_new_buy_info <- xts(monthly_trade$new_buy_info, order.by = monthly_trade$date_time) names(monthly_trade_new_buy_info) <- 'new_buy_info' monthly_trade_active_seller <- xts(monthly_trade$active_seller, order.by = monthly_trade$date_time) names(monthly_trade_active_seller) <- 'active_seller' monthly_trade_active_buyer <- xts(monthly_trade$active_buyer, order.by = monthly_trade$date_time) names(monthly_trade_active_buyer) <- 'active_buyer' monthly_trade_active_trader <- xts(monthly_trade$active_trader, order.by = monthly_trade$date_time) names(monthly_trade_active_trader) <- 'active_trader' # ============================================================================= hourly_train_new_company <- xts(hourly_train$new_company, order.by = hourly_train$date_time) names(hourly_train_new_company) <- 'new_company' hourly_train_new_course <- xts(hourly_train$new_course, order.by = hourly_train$date_time) names(hourly_train_new_course) <- 'new_course' hourly_train_active_user <- xts(hourly_train$active_user, order.by = hourly_train$date_time) names(hourly_train_active_user) <- 'active_user' hourly_train_new_view <- xts(hourly_train$new_view, order.by = hourly_train$date_time) names(hourly_train_new_view) <- 'new_view' hourly_train_new_collect <- xts(hourly_train$new_collect, order.by = hourly_train$date_time) names(hourly_train_new_collect) <- 'new_collect' hourly_train_new_apply <- xts(hourly_train$new_apply, order.by = hourly_train$date_time) names(hourly_train_new_apply) <- 'new_apply' hourly_train_new_contact <- xts(hourly_train$new_contact, order.by = hourly_train$date_time) names(hourly_train_new_contact) <- 'new_contact' daily_train_new_company <- xts(daily_train$new_company, order.by = daily_train$date_time) names(daily_train_new_company) <- 'new_company' daily_train_new_course <- xts(daily_train$new_course, order.by = daily_train$date_time) names(daily_train_new_course) <- 'new_course' daily_train_active_user <- xts(daily_train$active_user, order.by = daily_train$date_time) names(daily_train_active_user) <- 'active_user' daily_train_new_view <- xts(daily_train$new_view, order.by = daily_train$date_time) names(daily_train_new_view) <- 'new_view' daily_train_new_collect <- xts(daily_train$new_collect, order.by = daily_train$date_time) names(daily_train_new_collect) <- 'new_collect' daily_train_new_apply <- xts(daily_train$new_apply, order.by = daily_train$date_time) names(daily_train_new_apply) <- 'new_apply' daily_train_new_contact <- xts(daily_train$new_contact, order.by = daily_train$date_time) names(daily_train_new_contact) <- 'new_contact' weekly_train_new_company <- xts(weekly_train$new_company, order.by = weekly_train$date_time) names(weekly_train_new_company) <- 'new_company' weekly_train_new_course <- xts(weekly_train$new_course, order.by = weekly_train$date_time) names(weekly_train_new_course) <- 'new_course' weekly_train_active_user <- xts(weekly_train$active_user, order.by = weekly_train$date_time) names(weekly_train_active_user) <- 'active_user' weekly_train_new_view <- xts(weekly_train$new_view, order.by = weekly_train$date_time) names(weekly_train_new_view) <- 'new_view' weekly_train_new_collect <- xts(weekly_train$new_collect, order.by = weekly_train$date_time) names(weekly_train_new_collect) <- 'new_collect' weekly_train_new_apply <- xts(weekly_train$new_apply, order.by = weekly_train$date_time) names(weekly_train_new_apply) <- 'new_apply' weekly_train_new_contact <- xts(weekly_train$new_contact, order.by = weekly_train$date_time) names(weekly_train_new_contact) <- 'new_contact' monthly_train_new_company <- xts(monthly_train$new_company, order.by = monthly_train$date_time) names(monthly_train_new_company) <- 'new_company' monthly_train_new_course <- xts(monthly_train$new_course, order.by = monthly_train$date_time) names(monthly_train_new_course) <- 'new_course' monthly_train_active_user <- xts(monthly_train$active_user, order.by = monthly_train$date_time) names(monthly_train_active_user) <- 'active_user' monthly_train_new_view <- xts(monthly_train$new_view, order.by = monthly_train$date_time) names(monthly_train_new_view) <- 'new_view' monthly_train_new_collect <- xts(monthly_train$new_collect, order.by = monthly_train$date_time) names(monthly_train_new_collect) <- 'new_collect' monthly_train_new_apply <- xts(monthly_train$new_apply, order.by = monthly_train$date_time) names(monthly_train_new_apply) <- 'new_apply' monthly_train_new_contact <- xts(monthly_train$new_contact, order.by = monthly_train$date_time) names(monthly_train_new_contact) <- 'new_contact'
c8f4834ce2a7ec0766516d0eb1caa18f5f0a3d4a
429f8f159ece1946d26feec2934b022ed34be214
/fpem01/R/create_regional_results.R
61f5abc5668d7b596d7336c3dc93d4644064f7f3
[]
no_license
an-h-tran/testrepo
a38da0ee9a9fff0168c74abf354fb0cfa3a146df
76c19988e96f5bbbcc750339e936e0643e1e5d6c
refs/heads/master
2020-04-06T11:04:33.075047
2018-11-18T23:41:18
2018-11-18T23:41:18
157,402,771
0
0
null
null
null
null
UTF-8
R
false
false
1,175
r
create_regional_results.R
#' Summarize Regional Samples Function #' #' Summarize regional samples into points estimates (median), and #' uncertainty intervals (lower and upper given by the 2.5th and 97.5th percentiles #' of the sample, respectively) #' #' @param samples tibble or data frame with iso-year-samples-region-population counts #' (iso refers to country iso, variable names for samples include "samp") #' #' @return tibble with region-year-median-lower-upper #' @export #' #' @examples #' create_regional_results(tribble( #' ~iso, ~ year, ~ sample1, ~ sample2, ~region, ~population_ct, #' 4, 1990, 0.3, 0.4, "Southern Asia", 2025079, #' 4, 1991, 0.5, 0.6, "Southern Asia", 2069776, #' 858, 2020, 0.7, 0.9, "South America", 440817)) #' create_regional_results <- function(samples){ samples %>% gather(key ="sample", value ="value", contains("sample")) %>% group_by (region, year, sample) %>% summarize ("weighted_mean" = weighted.mean(value, population_ct))%>% summarize(median = quantile(weighted_mean, 0.5, na.rm=TRUE), lower = quantile(weighted_mean, 0.025, na.rm=TRUE), upper = quantile(weighted_mean, 0.975, na.rm=TRUE)) }
f09dbd8b09f03cdb6bee87ff913e9d662bab9b27
2b438ee1d8f9bdb0e9372c5a4970623afa2c6015
/Hclustering_University.R
96929c91cb0b006b8d04e860614a4c796d7d47a1
[]
no_license
anurag149/Anurag-Kumar-Tiwari
0fde3b8decbb418db7d8e9bd6c97bf0a6cff91e0
00a2b5f727cd925bb32b61cb28a4a78e5da91237
refs/heads/master
2021-02-11T18:10:10.174876
2020-04-28T14:28:36
2020-04-28T14:28:36
244,517,995
0
0
null
null
null
null
UTF-8
R
false
false
982
r
Hclustering_University.R
# Load the data set input = read.csv("E:/Day Wise/Day 18 Data Mining - Unsupervised (Clustering)/Data/Universities_Clustering.csv") summary(input) normalize<-function(x){ return ( (x-min(x))/(max(x)-min(x))) } normalized_data<-as.data.frame(lapply(input[,2:7],normalize)) summary(normalized_data) normalized_data <- scale(input[,2:7]) #excluding the university name columnbefore normalizing summary(normalized_data) d <- dist(normalized_data, method = "euclidean")# distance matrix fit <- hclust(d, method="complete") ?hclust ?dist plot(fit) # display dendrogram plot(fit, hang=-1) groups <- cutree(fit, k=3) # cut tree into 3 clusters ?cutree rect.hclust(fit, k=3, border="red") ?rect.hclust membership<-as.matrix(groups) final <- data.frame(input, membership) final1 <- final[,c(ncol(final),1:(ncol(final)-1))] aggregate(input[,2:7], by=list(final$membership), FUN=mean) ?write.xlsx write.csv(final1, file="final.csv") getwd()
379758a63813b21f9c5c18e26487d7c4b181e645
914b474ae1536940fed953c14659ec3b3c1ca2e2
/man/SaveDOEtoJMP.Rd
4fe477d30474fdf09cb92ce67e4f83a68aeef7d0
[]
no_license
neuhier/rospd
74a16cd4b2cbce36fd954272e9eba157bb076f2a
503b6e9fcbf856559e53507312f1d03370f75c8c
refs/heads/master
2020-04-01T20:14:33.460189
2018-10-29T14:23:37
2018-10-29T14:23:37
153,595,141
1
0
null
null
null
null
UTF-8
R
false
true
642
rd
SaveDOEtoJMP.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/SaveDOEtoJMP.R \name{SaveDOEtoJMP} \alias{SaveDOEtoJMP} \title{Function to export a DOE stored in an object of class \code{\link{doeDesign-class}} to JMP.} \usage{ SaveDOEtoJMP(doe, filepath) } \arguments{ \item{doe}{A list of DOEs that are being exported.} \item{filepath}{A character representing the path to store the JMP script.} } \description{ This function generates a JMP script that will produce a data table with the most relevant information about the DOE. That includes the design table and model and the factor attributes as well. }
13415018f5739bd307c24bdc56b10d54b3a91ac1
698196156a26603cce7d9abc5368591d0826d3ad
/man/vapour_create.Rd
5bd661230c9757b6104ddc0c293a960e5d859337
[]
no_license
hypertidy/vapour
9a61e903ad66ee269381703c22964ae53c85129d
35139e0ebf98e932496f4826ee90b069508cc1f7
refs/heads/main
2023-08-18T03:43:32.659491
2023-07-20T05:19:38
2023-07-20T05:19:38
98,496,053
82
9
null
2023-02-14T03:50:28
2017-07-27T05:08:36
R
UTF-8
R
false
true
2,344
rd
vapour_create.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/00_read_block.R \name{vapour_create} \alias{vapour_create} \alias{vapour_create_options} \title{Create raster file} \usage{ vapour_create_options(driver = "GTiff") vapour_create( filename, driver = "GTiff", extent = c(-180, 180, -90, 90), dimension = c(2048, 1024), projection = "OGC:CRS84", n_bands = 1L, overwrite = FALSE, datatype = "Float32", options = vapour_create_options(driver) ) } \arguments{ \item{driver}{GDAL driver to use (GTiff is default, and recommended)} \item{filename}{filename/path to create} \item{extent}{xmin,xmax,ymin,ymax 4-element vector} \item{dimension}{dimension of the output, X * Y} \item{projection}{projection of the output, best to use a full WKT but any string accepted} \item{n_bands}{number of bands in the output, default is 1} \item{overwrite}{not TRUE by default} \item{datatype}{the name of a GDAL datatype ('Float32', 'Int64', etc)} \item{options}{character vector of creation of options for the driver in use \code{c('COMPRESS=DEFLATE')} note how these are constructed (no '-co' element)} } \value{ the file path that was created } \description{ This is in an incomplete interface to raster writing, for exploring. } \details{ If GeoTIFF is used (\code{driver = "GTiff"}, recommended) then the output is tiled 512x512, and has DEFLATE compression, and is sparse when created (no values are initiated, so the file is tiny). Note that there is no restriction on where you can read or write from, the responsibility is yours. There is no auto driver detection done for the file format, it's up to you to set the file extension \emph{and} the driver. File is created using CreateCopy from a VRT in memory. This is so that we can instantiate COG layer with 'driver = "COG"'. Please note that performance is best for GTiff itself, with 'SPARSE_OK=YES'. We don't yet know how to instantiate a large COG with overviews. There are default creation options set for COG and GTiff drivers, see 'vapour_create_options(driver "GTiff")' for what those are. } \examples{ tfile <- tempfile(fileext = ".tif") if (!file.exists(tfile)) { vapour_create(tfile, extent = c(-1, 1, -1, 1) * 1e6, dimension = c(128, 128), projection = "+proj=laea") file.remove(tfile) } }
ae3d90a256e80bdb5fed1b1a98c52dffab073907
b860de1ae4f3033fabfef4c8c22b94db59083b16
/codes_DESeq2/GBS_GBSrec.R
ab0884f2aa09ef030bf77b0ee664f774adedb565
[]
no_license
washingtoncandeia/DESeq_IMT
98452fbd9436567f7a061d5ff03f38324304cfb7
32dade178c49140ac3aba404534b4ea751a5ef54
refs/heads/master
2020-03-28T17:54:54.914902
2019-11-02T06:15:57
2019-11-02T06:15:57
148,835,008
0
0
null
null
null
null
UTF-8
R
false
false
6,223
r
GBS_GBSrec.R
##---------------------------------------- # IMT # GBS Vs GBS recuperados com Controls # Data: 31/10/2019 # Washington C. Araujo # GSEA - fgsea Bioconductor ##---------------------------------------- library(DESeq2) library(edgeR) library(dplyr) library(plyr) library(clusterProfiler) library(org.Hs.eg.db) library(ggplot2) source("cooltable.R") #function to retrieve Up and Down genes at clusterprofiler data # 1. Carregar o arquivo de contagem de genes (featurecounts): countdata <- read.table("featureCounts_out.txt", header=TRUE, row.names=1, check.names = FALSE, stringsAsFactors=F) # 2. Remover os cromossomos sexuais, na coluna de cromossomos. countdata_sex <-countdata[!(countdata$Chr %in% c("X","Y")), ] # 3. Remover as 5 primeiras colunas, que não serão usadas. countdata <- countdata_sex[ ,6:ncol(countdata_sex)] rm(countdata_sex) # 4. Manter os nomes das amostras, sem a extensão .BAM. colnames(countdata) <- gsub("\\.[sb]am$", "", colnames(countdata)) # 5. Filtrar amostras. countdata <- countdata %>% dplyr::select(grep("01.", names(countdata)), #GBS grep("02.", names(countdata)), #GBS grep("04.", names(countdata)), #GBS grep("13.", names(countdata)), #GBS grep("14.", names(countdata)), #GBS grep("25.", names(countdata)), #GBS grep("09.", names(countdata)), #GBS_rec_pair grep("07.", names(countdata)), #GBS_rec_pair grep("16.", names(countdata)), #GBS_rec_pair grep("30.", names(countdata)), #GBS_rec_pair grep("27.", names(countdata)), #GBS_rec grep("28.", names(countdata)), #GBS_rec grep("08.", names(countdata)), #GBS_rec grep("38.", names(countdata)), #GBS_rec grep("39.", names(countdata)), #GBS_rec grep("10.", names(countdata)), #control grep("11.", names(countdata)), #control grep("19.", names(countdata)), #control grep("20.", names(countdata)), #control grep("33.", names(countdata)), #control grep("34.", names(countdata)) #control ) countdata <- as.matrix(countdata) # 6. Condition - especificar replicatas e grupos. (condition <- factor(c(rep("GBS",48), # n=6 rep("GBS_REC",72), # n=7 rep("CTL",48) # n=6 ) ) ) # 7. Gerar o coldata. (coldata <- data.frame(row.names=colnames(countdata), condition)) # 8. Gerar entradas para DESeq. dds <- DESeqDataSetFromMatrix(countData=countdata, colData=coldata, design=~condition) # 9. Juntar as 8 replicatas de cada amostra. dds$sample <- factor(c(rep("01.lane", 8), rep("02.lane", 8), rep("04.lane", 8), rep("13.lane", 8), rep("14.lane", 8), rep("25.lane", 8), rep("09.lane",8), rep("07.lane",8), rep("16.lane",8), rep("30.lane",8), rep("27.lane",8), rep("28.lane",8), rep("08.lane",8), rep("38.lane",8), rep("39.lane",8), rep("10.lane",8), rep("11.lane",8), rep("19.lane",8), rep("20.lane",8), rep("33.lane",8), rep("34.lane",8) ) ) ### Observação: n Total x 8 dds$run <- paste0("run",1:168) ddsColl <- collapseReplicates(dds, dds$sample, dds$run, renameCols = TRUE) # 10. Filtrar por counts insignificantes. keep <- rowSums(counts(dds)) >= 10 dds <- dds[keep,] rm(keep) # 11. Rodar Real&Oficial dds <- DESeq(ddsColl) # 12. Criar objeto rld, que transforma os dados para log2FC. # Scale/fator para minimizar diferenças entre amostras. rld <- rlogTransformation(dds) # 13. Gerar PCA. pca <- plotPCA(rld, ntop = nrow(counts(dds)),returnData=F) # 14. Visualizar a PCA. pca # 15. Extrair os resultados da análise de DE. contr_GBS_GBSrec <- as.data.frame(results(dds, contrast=c('condition','GBS','GBS_REC'))) ###----------------------- GSEA - Arquivo 1 --------------------- # Criar csv para fgsea para contr_GBS_GBSrec: write.csv(contr_GBS_GBSrec, 'contr_GBS_vs_GBSrec_GSEA_2019.csv') ###--------------------------------------------------------------- # 16. Criar uma nova coluna com os nomes (SYMBOLS) dos genes. contr_GBS_GBSrec$genes <- rownames(contr_GBS_GBSrec) # 17. Remoção de NAs na coluna de padj. contr_GBS_GBSrec$padj[is.na(contr_GBS_GBSrec$padj)] <- 1 DEGs_GBS_zika <- subset(contr_GBS_GBSrec, padj <= 0.05 & abs(log2FoldChange) > 1) # 18.Volcanoplot with(as.data.frame(contr_GBS_GBSrec[!(-log10(contr_GBS_GBSrec$padj) == 0), ]), plot(log2FoldChange,-log10(padj), pch=16, axes=T, xlim = c(-6,6), ylim = c(0,4), xlab = NA, ylab = "-Log10(Pvalue-Adjusted)", main = "GBS vs GBS Recuperados" ) ) with(subset(subset(as.data.frame(contr_GBS_GBSrec), padj <= 0.05), log2FoldChange <= -1), points(log2FoldChange,-log10(padj), pch=21, col="black",bg = "#69B1B7")) with(subset(subset(as.data.frame(contr_GBS_GBSrec), padj <= 0.05), log2FoldChange >= 1), points(log2FoldChange,-log10(padj),pch=21, col="black",bg = "tomato3")) abline(h=1.3,col="green", lty = 2, cex= 3) abline(v=1,col="green", lty = 2, cex= 3) abline(v=-1,col="green", lty = 2, cex= 3)
68041c0db0b586216790ab38cadf1ca278eab450
2099a2b0f63f250e09f7cd7350ca45d212e2d364
/DUC-Dataset/Summary_p100_R/D092.AP900625-0036.html.R
9d540b71e104ddf058d453f9a94cd514caf8d6f7
[]
no_license
Angela7126/SLNSumEval
3548301645264f9656b67dc807aec93b636778ef
b9e7157a735555861d2baf6c182e807e732a9dd6
refs/heads/master
2023-04-20T06:41:01.728968
2021-05-12T03:40:11
2021-05-12T03:40:11
366,429,744
3
0
null
null
null
null
UTF-8
R
false
false
879
r
D092.AP900625-0036.html.R
<html> <head> <meta name="TextLength" content="SENT_NUM:3, WORD_NUM:104"> </head> <body bgcolor="white"> <a href="#0" id="0">The Saudi-based 46-member Organization of the Islamic Conference, an umbrella organization for the world's estimated one billion Moslems, issued an ``urgent appeal to the international community and especially Islamic countries and organizations to hasten with emergency aid for the Iranians ...'' AmeriCares, a private U.S. relief organization based in New Canaan, Conn., flew in the 42 tons pounds of supplies that arrived Sunday.</a> <a href="#1" id="1">Tehran radio said Sunday that 68 relief aircraft had landed at Tehran's Mehrabad airport during a 24-hour period.</a> <a href="#2" id="2">In Lebanon, the Iranian-backed Hezbollah, or Party of God, said its members were donating 10 percent of their salaries to help the victims.</a> </body> </html>
22694fd2a789c6ecb4b76bae3699ce42cda30c1e
a9ea4af2a95308527784b7df5d3c645a3b5e7d89
/man/check_dependencies.Rd
249b1322100345cc66371aa87d75f017e92e1012
[]
no_license
haukelicht/politicaltweets
3c7edee7c9fc46923fc696544f6a9ce8f832ece9
368922e91ceb0043d4dd2bfc6432699ad74a5a38
refs/heads/master
2023-06-26T08:50:58.499169
2023-06-15T13:12:23
2023-06-15T13:12:23
271,348,425
2
0
null
null
null
null
UTF-8
R
false
true
276
rd
check_dependencies.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/utils.R \name{check_dependencies} \alias{check_dependencies} \title{Check dependencies} \usage{ check_dependencies(pkgs) } \value{ } \description{ Check if package dependencies are all installed }
f93976c64e216a563ca39c5e1b919cc3dad8b4b7
669872ed6a31695b754a6386abcf46c479412dce
/more_experiments.R
b6fd7aedcd9557cfad4858319b0432a6a47a5805
[]
no_license
kapelner/CovBalAndRandExpDesign
766afe315cc8a124521f648668ef105460444250
61e55753a93c42fc2a55d3cef2ac39ad8104a142
refs/heads/master
2021-07-18T01:10:57.494188
2019-01-18T01:57:34
2019-01-18T01:57:34
141,571,668
1
0
null
null
null
null
UTF-8
R
false
false
4,614
r
more_experiments.R
####calculate some Frob norm sq: r = 10000 rd = initGreedyExperimentalDesignObject(X, r, wait = TRUE, objective = "mahal_dist", num_cores = 4) res = resultsGreedySearch(rd, max_vectors = r) all_vecs_opt = res$ending_indicTs r = 10000 rd = initGreedyExperimentalDesignObject(X, r, wait = TRUE, objective = "mahal_dist", num_cores = 4) res = resultsGreedySearch(rd, max_vectors = r) all_vecs_mid = res$ending_indicTs #make one section random prob_randomize = 0.01 length_randomize = 2 for (m in 1 : r){ indicT = all_vecs_mid[, m] for (i_w in length_randomize : n){ if (rbinom(1, 1, prob_randomize) == 1 & sum(indicT[(i_w - length_randomize) : i_w]) == length_randomize / 2){ indicT[(i_w - length_randomize) : i_w] = sample(indicT[(i_w - length_randomize) : i_w]) } } all_vecs_mid[, m] = indicT } num_match = 10000 all_vecs_match = matrix(NA, nrow = n, ncol = num_match) for (m in 1 : num_match){ indicT = array(NA, n) for (i_w in seq(2, n, by = 2)){ indicT[c(i_w - 1, i_w)] = sample(c(0, 1)) } all_vecs_match[, m] = indicT } all_vecs_rand = t(complete_randomization_with_forced_balanced(n, num_match)) all_vecs_rand[all_vecs_rand == -1] = 0 all_vecs = cbind(all_vecs_opt, all_vecs_opt2, all_vecs_match, all_vecs_rand) all_vecs = cbind(all_vecs_mid) all_vecs = cbind(all_vecs_mid, all_vecs_opt, all_vecs_match, all_vecs_rand) all_mahal_obj = apply(all_vecs, 2, function(w){compute_objective_val(X, w, objective = "mahal_dist")}) all_vecs = all_vecs[, order(all_mahal_obj)] all_mahal_obj_sort_log10 = sort(log10(all_mahal_obj)) hist(all_mahal_obj_sort_log10, br = 1000) ##now create a representative sample num_per_order_of_mag = 200 round_all_mahal_obj_sort_log10 = round(all_mahal_obj_sort_log10) all_vecs_rep = matrix(NA, nrow = n, ncol = 0) for (level_log in min(round_all_mahal_obj_sort_log10) : max(round_all_mahal_obj_sort_log10)){ idx = which(round_all_mahal_obj_sort_log10 == level_log) if (length(idx) > num_per_order_of_mag){ idx = sample(idx, num_per_order_of_mag) } all_vecs_rep = cbind(all_vecs_rep, all_vecs[, idx]) } all_mahal_obj_rep = apply(all_vecs_rep, 2, function(w){compute_objective_val(X, w, objective = "mahal_dist")}) all_vecs_rep = all_vecs_rep[, order(all_mahal_obj_rep)] all_mahal_obj_rep = sort(all_mahal_obj_rep) hist(log10(all_mahal_obj_rep), br = 1000) quantile(all_mahal_obj_rep, seq(0, 1, by = 0.1)) num_rep_vecs = ncol(all_vecs_rep) pct_num_rep_vecs = (1 : num_rep_vecs) / num_rep_vecs min_criterions_sigma_z_i = list() sigma_zs = c(0.1, 0.3, 1, 3, 10) for (sigma_z in sigma_zs){ if (sigma_z == sigma_zs[1]){ R_terms = array(NA, num_rep_vecs) B1_terms = array(NA, num_rep_vecs) B2_terms = array(NA, num_rep_vecs) } criterion_values = array(NA, num_rep_vecs) for (i in seq(1, num_rep_vecs, by = 10)){ if (sigma_z == sigma_zs[1]){ sigma_w_optimals = matrix(0, n, n) for (j in 1 : i){ w = all_vecs_rep[, j] w[w == 0] = -1 sigma_w_optimals = sigma_w_optimals + 1 / i * w %*% t(w) } R_terms[i] = sum(eigen(sigma_w_optimals)$values^2) B1_terms[i] = t(X) %*% sigma_w_optimals %*% X B2_terms[i] = t(X) %*% sigma_w_optimals %*% sigma_w_optimals %*% X } criterion_values[i] = 1 / n^2 * (B1_terms[i] + n * sigma_z^2 + 2 * sqrt(2 * sigma_z^4 * R_terms[i] + 4 * sigma_z^2 * B2_terms[i])) } B1_terms[seq(1, num_rep_vecs, by = 10)] B2_terms[seq(1, num_rep_vecs, by = 10)] R_terms[seq(1, num_rep_vecs, by = 10)] criterion_values[seq(1, num_rep_vecs, by = 10)] sigma_z = as.character(sigma_z) min(criterion_values, na.rm = TRUE) min_criterions_sigma_z_i[[sigma_z]] = which(criterion_values == min(criterion_values, na.rm = TRUE)) / num_rep_vecs ggplot(data.frame(pct_vecs = pct_num_rep_vecs, B1 = B1_terms)) + geom_point(aes(pct_vecs, B1), col = "red") + geom_vline(xintercept = min_criterions_sigma_z_i[[sigma_z]], col = "black") ggplot(data.frame(pct_vecs = pct_num_rep_vecs, B2 = B2_terms)) + geom_point(aes(pct_vecs, B2), col = "red") + geom_vline(xintercept = min_criterions_sigma_z_i[[sigma_z]], col = "black") ggplot(data.frame(pct_vecs = pct_num_rep_vecs, R = R_terms)) + ylim(0, 1000) + geom_point(aes(pct_vecs, R), col = "blue") + geom_vline(xintercept = min_criterions_sigma_z_i[[sigma_z]], col = "black") ggplot(data.frame(pct_vecs = pct_num_rep_vecs, tail_criterion = criterion_values)) + # ylim(0, 0.07) + geom_point(aes(pct_vecs, tail_criterion), col = "purple") + geom_vline(xintercept = min_criterions_sigma_z_i[[sigma_z]], col = "black") }
6a41af5bca29a09b8ce4290337df052b68260e76
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/gamclass/vignettes/figs3.R
0353b9f474be766ed5902f0240504b7c026e4abf
[]
no_license
surayaaramli/typeRrh
d257ac8905c49123f4ccd4e377ee3dfc84d1636c
66e6996f31961bc8b9aafe1a6a6098327b66bf71
refs/heads/master
2023-05-05T04:05:31.617869
2019-04-25T22:10:06
2019-04-25T22:10:06
null
0
0
null
null
null
null
UTF-8
R
false
false
17,070
r
figs3.R
## ----setup, cache=FALSE, echo=FALSE----------------------------------- library(knitr) options(replace.assign=FALSE,width=72) opts_chunk$set(fig.path='figs/infer-', cache.path='cache/infer-', fig.align='center', dev='pdf', fig.width=3.5, fig.height=3.5, fig.show='hold', par=TRUE, tidy=FALSE, comment=NA) knit_hooks$set(par=function(before, options, envir){ if (before && options$fig.show!='none') par(mar=c(4,4,1.6,.1), font.main=1, cex.lab=.95,cex.axis=.9,mgp=c(2,.7,0), tcl=-.3) par(options$pars) }, crop=hook_pdfcrop) pdf.options(pointsize=12) oldopt <- options(digits=4) ## ----figControl------------------------------------------------------- # To include the figures, change `showFigs <- FALSE` # to `showFigs <- TRUE` in the source `.Rnw` file, # and regenerate the PDF. # showFigs <- FALSE ## ----fig3_1, eval=TRUE, echo=TRUE------------------------------------- fig3.1 <- function (x=fCatBwt){ lattice::stripplot(jitter(x), pch='|', xlab="Weight (kg)", aspect=0.25, col="black", border="gray") } ## ----fig3_2, eval=TRUE, echo=TRUE------------------------------------- fig3.2 <- function(x=fCatBwt){ opar <- par(mfrow=c(2,2), xpd=TRUE, mar=c(3.6,3.1,3.6,1.1), mgp=c(2.25, 0.5, 0)) hist(x, labels=TRUE, xlim=c(2, 3), xlab="Height (cm)", main="", xpd=TRUE) title(main="A: Frequency histogram", adj=0, line=1.5, cex.main=1.05) hist(x, labels=TRUE, xlim=c(2,3), xlab="Weight (kg)", main="", freq=FALSE, xpd=TRUE) title(main="B: Density histogram", adj=0, line=1.5, cex.main=1.05) par(xpd=FALSE) hist(x, xlim=c(2,3), xlab="Weight (kg)", main="", freq=FALSE) axis(1) lines(density(x), xlab="Weight (kg)", col="gray40") title(main="C: Histogram, density is overlaid", adj=0, line=1.5, cex.main=1.05) plot(density(x), xlim=c(2,3), xlab="Height (cm)", main="", sub="", bty="l", type="l") av <- mean(x) sdev <- sd(x) xval <- pretty(c(2,3), n=40) lines(xval, dnorm(xval, mean=av, sd=sdev), lty=2, col="gray40") title(main="D: Density curve estimate", adj=0, line=1.5, cex.main=1.05) par(opar) par(mfrow=c(1,1)) } ## ----fig3_3, eval=TRUE, echo=TRUE------------------------------------- fig3.3 <- function (x=fCatBwt, plotit=TRUE){ av <- mean(x); sdev <- sd(x); sampsize <- length(x) simmat <- cbind(x, matrix(rnorm(sampsize*5, mean=av, sd=sdev), ncol=5)) simdf <- as.data.frame(simmat) names(simdf) <- c("Source", paste("normal", 1:5, sep="")) simdf <- stack(simdf) names(simdf) <- c("height", "Sample") denplotSimple <- densityplot(~height, groups=Sample, data=simdf, xlab="Body weight (kg)") denplotn <- update(denplotSimple, scales=list(tck=0.5), main=list(expression(plain("A: Simulation (Densities)")), cex.title=0.9, x=0.05, just="left"), par.settings=simpleTheme(lty=1:6)) bwpltBasic <- bwplot(Sample ~ height, data=simdf, xlab="Body weight (kg)", auto.key=list(columns=3)) bwplotn <- update(bwpltBasic, scales=list(tck=0.5), main=list(expression(plain("B: Simulation (Boxplots)")), cex.title=0.9, x=0.05, just="left")) if(plotit){ print(denplotn, position=c(0,0,0.5,1)) print(bwplotn, position=c(0.5,0,1,1),newpage=FALSE) } invisible(list(denplotn, bwplotn)) } ## ----fig3_4, eval=TRUE, echo=TRUE------------------------------------- fig3.4 <- function (x=fCatBwt, plotit=TRUE) { sampsize <- length(x) bootmat <- cbind(x, matrix(0, ncol=5, nrow=sampsize)) for(i in 2:6) bootmat[,i] <- sample(x, replace=TRUE) colnames(bootmat) <- c("Source", paste("normal", 1:5, sep="")) bootdf <- stack(as.data.frame(bootmat)) names(bootdf) <- c("height", "Sample") denplotSimple <- densityplot(~ height, groups=Sample, data=bootdf, xlab="Body weight (kg)") legendA <- expression(plain("A: Bootstrap (Densities)")) denplot <- update(denplotSimple, scales=list(tck=0.5), main=list(legendA, x=0.05, just="left"), cex.title=0.9, par.settings=simpleTheme(lty=1:6)) bwpltBasic <- bwplot(Sample ~ height, data=bootdf, xlab="Body weight (kg)", auto.key=list(columns=3)) legendB <- expression(plain("B: Bootstrap (Boxplots)")) bwplot <- update(bwpltBasic, scales=list(tck=0.5), main=list(legendB, x=0.05, just="left"), cex.title=0.9) if(plotit){ print(denplot, position=c(0,0,0.5,1)) print(bwplot, position=c(0.5,0,1,1),newpage=FALSE) } invisible(list(denplot, bwplot)) } ## ----fig3_5, eval=TRUE, echo=TRUE------------------------------------- fig3.5 <- function () { opar <- par(mgp=c(2,.75,0), mfrow=c(1,2)) curve(dnorm(x), from = -3, to = 3, ylab=expression("dnorm("*italic(x)*")"), xlab=expression("Normal deviate "*italic(x))) curve(pnorm(x), from = -3, to = 3, ylab=expression("pnorm("*italic(x)*")"), xlab=expression("Normal deviate "*italic(x))) par(opar) } ## ----fig3_6, eval=TRUE, echo=TRUE------------------------------------- fig3.6 <- function (){ heights <- na.omit(subset(survey, Sex=="Female")$Height) plot(density(heights), bty="l", main="", cex.axis=1.15, cex.lab=1.15) av <- mean(heights); sdev <- sd(heights) abline(v=c(av-sdev, av, av+sdev), col="gray", lty=c(2,1,2)) ## Show fitted normal curve xval <- pretty(heights, n=40) normal_den <- dnorm(xval, mean=av, sd=sdev) lines(xval, normal_den, col="gray40", lty=2) ytop <- par()$usr[4]-0.25*par()$cxy[2] text(c(av-sdev, av+sdev), ytop, labels=c("mean-SD","mean+SD"), col="gray40", xpd=TRUE) } ## ----fig3_7, eval=TRUE, echo=TRUE------------------------------------- fig3.7 <- function (wts=fCatBwt){ opar <- par(pty="s") qqnorm(wts) par(opar) } ## ----fig3_8, eval=TRUE, echo=TRUE------------------------------------- fig3.8 <- function (wts=fCatBwt) { opar <- par(mfrow=c(1,2), mar=c(2.1, 3.6, 3.6,2.6), mgp=c(2.25, 0.5,0)) av <- numeric(1000) for (i in 1:1000) av[i] <- mean(rnorm(47, mean=2.36, sd=0.27)) avdens <- density(av) xval <- pretty(c(2.36-3*0.27, 2.36+3*0.27), 50) den <- dnorm(xval, mean=2.36, sd=0.27) plot(xval, den, type="l", xlab="", xlim=c(1.5, 3.75), ylab="Density", ylim=c(0,max(avdens$y)), col="gray", lwd=2, lty=2) lines(avdens) mtext(side=3, line=0.75, "A: Simulation (from a normal distribution)", adj=0) legend("bottomright", legend=c("Source", "Sampling\ndistribution\nof mean"), col=c("gray", "black"), lty=c(2,1), lwd=c(2,1), bty="n", y.intersp=0.75, inset=c(0,0.2), cex=0.8) av <- numeric(1000) for (i in 1:1000) av[i] <- mean(sample(wts, size=length(wts), replace=TRUE)) avdens <- density(av) plot(density(wts), ylim=c(0, max(avdens$y)), xlab="", ylab="Density", xlim=c(1.5, 3.75), col="gray", lwd=2, lty=2, main="") lines(avdens) mtext(side=3, line=0.75, "B: Bootstrap samples (resample sample)", adj=0) legend("bottomright", legend=c("Source", "Sampling\ndistribution\nof mean"), col=c("gray", "black"), lty=c(2,1), lwd=c(2,1), bty="n", y.intersp=0.75, inset=c(0,0.2), cex=0.8) par(opar) par(mfrow=c(1,1)) } ## ----fig3_9, eval=TRUE, echo=TRUE------------------------------------- fig3.9 <- function () { xleft <- 0:3; xrt <- 1:4 ybot <- rep(0,4); ytop <- rep(1,4) - 0.05 opar <- par(mar=rep(0.1,4)) plot(c(0,5), c(-1,4), xlab="", ylab="", axes=F, type="n") for(i in 0:3){ i1 <- i+1 rect(xleft, ybot+i, xrt, ytop+i) xli <- xleft[i+1]; xri <- xrt[i+1]; yboti <- (ybot+i)[i+1]; ytopi <- (ytop+i)[i+1] rect(xli, yboti, xri, ytopi, col="gray80") text(0.5*(xli+xri), 0.5*(yboti+ytopi), "TEST") text(0.5*(xleft[-i1]+xrt[-i1]), 0.5*(ybot[-i1]+ytop[-i1])+i, "Training") text(4+strwidth("TE"), i+0.475, paste("Fold", i1), adj=0) } } ## ----fig3_10, eval=TRUE, echo=TRUE------------------------------------ fig3.10 <- function (dset=cuckoos, plotit=TRUE) { parset1 <- lattice::simpleTheme(pch=1:6, alpha=0.8) plt1 <- lattice::xyplot(length ~ breadth, groups=species, data=dset, par.settings=parset1, aspect=1, scales=list(tck=0.5), auto.key=list(columns=2, alpha=1), main=grid::textGrob("A:", x=unit(.025, "npc"), y = unit(.25, "npc"), just="left", gp=gpar(cex=1)) ) Species <- factor(c(rep("other", 5), "wren")[unclass(cuckoos$species)]) parset2 <- lattice::simpleTheme(pch=c(0,6), alpha=0.8, col=trellis.par.get()$superpose.symbol$col[c(7,6)]) plt2 <- lattice::xyplot(length ~ breadth, groups=Species, data=dset, par.settings=parset2, aspect=1, ylab="", scales=list(tck=0.25), auto.key=list(columns=1, alpha=1), main=grid::textGrob("B:", x=unit(.05, "npc"), y = unit(.25, "npc"), just="left", gp=grid::gpar(cex=1)) ) plt2 <- update(plt2, par.settings=list(layout.heights=list(key.top=1.5))) if(plotit){ print(plt1, position=c(0,0,0.515,1)) print(plt2, position=c(0.485,0,1,1), newpage=FALSE) } invisible(list(plt1, plt2)) } ## ----fig3_11, eval=TRUE, echo=TRUE------------------------------------ fig3.11 <- function (dset=cuckoos) { parset <- list(dot.symbol=list(pch=1, alpha=0.6)) dotwren <- dotplot(species %in% "wren" ~ length, data=dset, scales=list(y=list(labels=c("Other", "Wren"))), par.settings=parset, xlab="Length (mm)") dotwren } ## ----fig3_12, eval=TRUE, echo=TRUE------------------------------------ fig3.12 <- function(dset=cuckoos) { avdiff <- numeric(100) for(i in 1:100){ avs <- with(dset, sapply(split(length, species %in% "wren"), function(x)mean(sample(x, replace=TRUE)))) avdiff[i] <- avs[1] - avs[2] # FALSE (non-wren) minus TRUE (wren) } xtxt <- paste("Means of bootstrap samples of length difference,\n", "non-wren - wren (mm)") dotdiff <- dotplot(~ avdiff, xlab=xtxt, par.settings=list(dot.symbol=list(pch=1, alpha=0.6))) dotdiff } ## ----fig3_13, eval=TRUE, echo=TRUE------------------------------------ fig3.13 <- function (dset=mcats) { xyplot(Hwt ~ Bwt, data=dset, type=c("p","r")) } ## ----fig3_14, eval=TRUE, echo=TRUE------------------------------------ fig3.14 <- function(dset=mcats) { mcats.lm <- lm(Hwt ~ Bwt, data=dset) res <- resid(mcats.lm) plot(density(res), main="") rug(res, col="gray") } ## ----fig3_15, eval=TRUE, echo=TRUE------------------------------------ fig3.15 <- function(dset=mcats, nrepeats=100) { bootmat <- bootreg(formula = Hwt ~ Bwt, data = dset, nboot = nrepeats) bootdf <- as.data.frame(bootmat) names(bootdf) <- c("Intercept","Slope") colr <- adjustcolor(rep("black",3), alpha.f=0.25) if(packageVersion('car') < '3.0.0'){ scatterplot(Slope ~ Intercept, col=colr, data=bootdf, boxplots="xy", reg.line=NA, smooth=FALSE)} else scatterplot(Slope ~ Intercept, col=colr, data=bootdf, boxplots="xy", regLine=FALSE, smooth=FALSE) } ## ----fig3_16, eval=TRUE, echo=TRUE------------------------------------ fig3.16 <- function (dset=mcats, plotit=TRUE, nrepeats=100) { bootmat <- bootreg(formula = Hwt ~ Bwt, data = dset[-97, ], nboot = nrepeats) bootdf0 <- as.data.frame(bootmat) names(bootdf0) <- c("Intercept","Slope") gphA <- xyplot(Slope ~ Intercept, data=bootdf0, alpha=0.25, main=paste("A:", nrepeats, "bootstrap samples"), cex.title=1.1) simmat <- simreg(formula = Hwt ~ Bwt, data=dset[-97, ], nsim=nrepeats) simdf <- as.data.frame(simmat) names(simdf) <- c("Intercept","Slope") gphB <- xyplot(Slope ~ Intercept, data=simdf, alpha=0.25, main=paste("B:", nrepeats, "simulations"), cex.title=1.1) if(plotit){ print(gphA, position=c(0,0,0.515,1)) print(gphB, position=c(0.485,0,1,1), newpage=FALSE) } invisible(list(gphA, gphB)) } ## ----fig3-pkgs, warning=FALSE, message=FALSE-------------------------- pkgs <- c("lattice","DAAG","gamclass","MASS","car","grid") z <- sapply(pkgs, require, character.only=TRUE, warn.conflicts=FALSE, quietly=TRUE) if(any(!z)){ notAvail <- paste(names(z)[!z], collapse=", ") print(paste("The following packages should be installed:", notAvail)) } ## ----get-data, eval=TRUE---------------------------------------------- msg <- "Data object 'cats', from 'MASS', may not be available" if(!requireNamespace("MASS"))print(msg) else { mcats <- subset(MASS::cats, Sex=="M") fcats <- subset(MASS::cats, Sex=="F") fCatBwt <- na.omit(fcats[, "Bwt"]) } if(!exists("cuckoos")){ msg <- "Cannot find either 'cuckoos' or 'DAAG::cuckoos'," if(requireNamespace("DAAG"))cuckoos <- DAAG::cuckoos else print(msg) } ## ----fig3_1x, eval=showFigs, echo=TRUE, fig.width=4.5, fig.height=2.5, out.width="0.75\\textwidth"---- # if(exists('fCatBwt'))fig3.1() else # print("Object 'fCatBwt' is not available; get from 'MASS::cats'") ## ----fig3_2x, eval=showFigs, echo=TRUE, fig.width=5.5, fig.height=5.5, out.width="0.8\\textwidth"---- # if(exists('fCatBwt'))fig3.2() else # print("Object 'fCatBwt' is not available; get from 'MASS::cats'") ## ----fig3_3x, eval=showFigs, echo=TRUE, fig.width=6, fig.height=3, out.width="0.8\\textwidth"---- # if(exists('fCatBwt'))fig3.3() else # print("Object 'fCatBwt' is not available; get from 'MASS::cats'") ## ----fig3_4x, eval=showFigs, echo=TRUE, fig.width=6, fig.height=3, out.width="0.8\\textwidth"---- # if(exists('fCatBwt'))fig3.4() else # print("Object 'fCatBwt' is not available; get from 'MASS::cats'") ## ----fig3_5x, eval=showFigs, echo=TRUE, fig.width=6, fig.height=3.25, out.width="0.8\\textwidth"---- # fig3.5() ## ----fig3_6x, eval=showFigs, echo=TRUE, fig.width=4.5, fig.height=3.5, out.width="0.55\\textwidth"---- # fig3.6() ## ----fig3_7x, eval=showFigs, echo=TRUE, out.width="0.5\\textwidth"---- # if(exists("fCatBwt"))fig3.7() else # print("Object 'fCatBwt' was not found; get from 'MASS::cats'") ## ----fig3_8x, eval=showFigs, echo=TRUE, fig.width=8, fig.height=3.5, out.width="0.98\\textwidth"---- # if(exists("fCatBwt"))fig3.8() else # print("Object 'fCatBwt' was not found; get from 'MASS::cats'") ## ----fig3_9x, eval=showFigs, echo=TRUE, fig.width=4, fig.height=3, out.width="0.6\\textwidth"---- # fig3.9() ## ----fig3_10x, eval=showFigs, echo=TRUE, fig.width=6, fig.height=3.5, out.width="0.97\\textwidth"---- # if(exists("cuckoos"))fig3.10() else # print("Object 'cuckoos' was not found; get 'DAAG::cuckoos'") ## ----fig3_11x, eval=showFigs, echo=TRUE, fig.width=4.5, fig.height=2.5, out.width="0.6\\textwidth"---- # if(exists("cuckoos"))fig3.11() else # print("Object 'cuckoos' was not found; get 'DAAG::cuckoos'") ## ----fig3_12x, eval=showFigs, echo=TRUE, fig.width=4.5, fig.height=2.5, out.width="0.6\\textwidth"---- # if(exists("cuckoos"))fig3.12() else # print("Object 'cuckoos' was not found; get 'DAAG::cuckoos'") ## ----fig3_13x, eval=showFigs, echo=TRUE, fig.width=4, fig.height=4, out.width="0.55\\textwidth"---- # if(exists('mcats'))fig3.13() else # print("Object 'mcats' was not found; subset from 'MASS::cats'") ## ----fig3_14x, eval=showFigs, echo=TRUE, fig.width=3.5, fig.height=3, out.width="0.5\\textwidth"---- # if(exists('mcats'))fig3.14() else # print("Object 'mcats' was not found; subset from 'MASS::cats'") ## ----fig3_15x, eval=showFigs, echo=TRUE, out.width="0.6\\textwidth"---- # if(!require(car)){ # print("Figure 3.15 requires the 'car' package") # return("The 'car' package needs to be installed.") # } # if(exists("mcats"))fig3.15(nrepeats=100) else # print("Object 'mcats' was not found; subset from 'MASS::cats'") ## ----fig3_16x, eval=showFigs, echo=TRUE, fig.width=6.5, fig.height=3.25, out.width="0.97\\textwidth"---- # if(exists('mcats'))fig3.16() else # print("Object 'mcats' was not found; subset from 'MASS::cats'")
45a54ab53683289f40c89519aac5b2d70ccc04ba
5bb2c8ca2457acd0c22775175a2722c3857a8a16
/man/ATT.Rd
9a900ec48e9a0e67392b50bea1f90fee60330390
[]
no_license
IQSS/Zelig
d65dc2a72329e472df3ca255c503b2e1df737d79
4774793b54b61b30cc6cfc94a7548879a78700b2
refs/heads/master
2023-02-07T10:39:43.638288
2023-01-25T20:41:12
2023-01-25T20:41:12
14,958,190
115
52
null
2023-01-25T20:41:13
2013-12-05T15:57:10
R
UTF-8
R
false
true
949
rd
ATT.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/wrappers.R \name{ATT} \alias{ATT} \title{Compute simulated (sample) average treatment effects on the treated from a Zelig model estimation} \usage{ ATT(object, treatment, treated = 1, num = NULL) } \arguments{ \item{object}{an object of class Zelig} \item{treatment}{character string naming the variable that denotes the treatment and non-treated groups.} \item{treated}{value of \code{treatment} variable indicating treatment} \item{num}{number of simulations to run. Default is 1000.} } \description{ Compute simulated (sample) average treatment effects on the treated from a Zelig model estimation } \examples{ library(dplyr) data(sanction) z.att <- zelig(num ~ target + coop + mil, model = "poisson", data = sanction) \%>\% ATT(treatment = "mil") \%>\% get_qi(qi = "ATT", xvalue = "TE") } \author{ Christopher Gandrud }
adee61a3cc41ef9c7f07b1166460dd75c2622760
13af613761463c204117fed1faa169b474f49d28
/R/save_dye_screen_model_plots.R
713b0cd8307cbce6d5fe8ee89ea5e393d47779b2
[ "MIT" ]
permissive
taiawu/dsfworld_package
22908b87af3add64b45f7ddde772d4e6a83cc582
e564d25cc5e8a60a87774e04ed23147c1033e964
refs/heads/master
2023-08-24T20:58:26.263206
2021-11-07T23:04:18
2021-11-07T23:04:18
342,920,918
0
0
null
null
null
null
UTF-8
R
false
false
33,382
r
save_dye_screen_model_plots.R
# small adjustments to get these functions package-ready ########## YOU NEED TO UPDATE CONVERT HEIGHTS AND PULL ASSIGNMENTS IN DSFWORLD # YOU ADDED .... ARGUMENTS TO THESE AND THEY NEED TO HAVE THEM TO WORK ##---------------- for utils.R in dsfworld package ------ #' Extract layout from labeled plate data #' #' Ultimately, probably belongs in utils.R or the like. Use \code{extract_plate_layout} to generate a plate layout object from labeled data. #' #' @param data a tibble containing labeled dsf data #' @param .auto_detect a boolean. If TRUE, attempts to automatically identify which columns contain layout information based on the number of unique values provided per well (layout columns have only one value per well; data columns have one per measurement). Defaults to TRUE. #' @param .extract_well a boolean. If TRUE, extracts the "well" component from a column which contains well, e.g. "A1_FAM", will extract "A1" #' @param .extract_well_into a character vector, passed directly to the "into" argument of tidyr::separate, if .extract_well is TRUE. Gives the names of the pieces into which the column named in the .var_col argument will be separated. Defaults to c("well", "channel_f", "type") #' @param .extract_sep a string, passed directl yto the "sep" argument to tidyr::separate, if .extract_well is TRUE. Gives the separator between components; defaults to "_" #' @param .var_col a string, giving the name of the column in the provided /code{data} containing unqiue trace identifiers. Defaults to "variable". This column is used to get well names, if .extract_well_into is TRUE. #' @param .well_col a string, giving the name of the column containing well names, if any. #' @param .keep_manual a characer vector which, if if .auto_detect = FALSE, gives the names of all column (other than well), which are to be kept and put in the final layout. #' @param .respect_grouping a boolean, defaults to FALSE, on whether or not to respect grouping of input \code{data}. Defaults to FALSE. #' @param ... additional named arguments, not passed to anything, but used to allow the passage of ... arguments to this function from upstream, while ignoring and ... arguments from upstream which do not match arguments in this function. #' #' @return a plate layout tibble, as described in \code{read_plate_layout} #' #' @export extract_plate_layout <- # given a tibble of labeld data, extract just the layout function(data, # tibble of cleaned data .auto_detect = TRUE, # bool--drop all columns with the most unique values? .extract_well = TRUE, .extract_well_into = c("well", "channel_f", "type"), .extract_sep = "_", .var_col = "variable", .well_col = "well", # name of the column which will be called as well .keep_manual = c("dye_conc_uM", "channel_f", "dye", "type", "exp_num", "identity"), .respect_grouping = FALSE, ... # ignore non-matching arguments passed via .. from upstream ) { if (.respect_grouping == FALSE) { data <- data %>% dplyr::ungroup() } if(.extract_well) { data <- data %>% tidyr::separate({{ .var_col }}, into = .extract_well_into, sep = .extract_sep, remove = FALSE) %>% dplyr::select(-tidyselect::any_of(.extract_well_into[.extract_well_into != "well"])) # remove additional pieces } if(.auto_detect) { layout_cols <- data %>% dplyr::group_by(.data[[.var_col]]) %>% # each trace dplyr::summarise(dplyr::across(.cols = tidyselect::everything(), dplyr::n_distinct)) %>% # has only one value per layout variable dplyr::select(where(~!any(. > 1))) %>% # see utils::globalVariables() below--where() is not exported from tidyselect names() } else { layout_cols <- .keep_manual } layout <- data %>% dplyr::select(tidyselect::any_of(c(.well_col, layout_cols))) %>% dplyr::distinct() } # known issue as of # https://community.rstudio.com/t/where-is-not-an-exported-object-from-namespace-tidyselect/74911 # points to https://github.com/r-lib/tidyselect/issues/201#issuecomment-650547846 # > checking dependencies in R code ... NOTE # Missing or unexported object: ‘tidyselect::where’ # where() is not yet exported from tidyselect # per lionel's comment Aug 18 202 in the github thread # lionel "globalVariables() is often the right and correct answer to static analysis problems with NSE functions." # this issue was closed, but note it's getting mentioned in thread active as of "this month" August 2021 # https://github.com/r-lib/tidyselect/issues/244 # but note that they're just pointing folks back to the original github issue, where the recommendations are still to use the globalVariables() approach utils::globalVariables("where") # example useage # layout <- extract_plate_layout(tidied_screen) ##---------------- for one of the modeling .R scrips in dsfworld ------- #' Extract model tmas #' #' Starting from a tibble containing dsfworld fit information, use \code{extract_model_tmas} to pull just resulting tmas into a tidy tibble. Probably belongs somewhere in the fitting function scripts, ultimately. #' #' @param by_var_fit a tibble, as output by \code{add_model_fits}. #' @param .var_col a string, giving the name of the column in \code{by_var_fit} containing the unique-identifier for each dataset. Defaults to ".var" #' @param .model_name_col a string, giving the name of the column in \code{by_var_fit} containing the name of the fitted model used to find a given tma. Defaults to "model_name" #' @param .model_tma_col a string, giving the name of the column in \code{by_var_fit} containing the tma resulting from the model fitting and tma extraction. Defaults to "model_tma". #' #' @return a tibble of apparent melting temperatures, comprising four columns #' \itemize{ #' \item \strong{.var} character, giving the unique dataset identifier for each DSF trace. #' \item \strong{model_name} character, giving the name of the model from which the given values and tmas were found, e.g. "model_1", "model_2" #' \item \strong{which_value} character, giving the specific component for a given value, e.g. "sigmoid_1", "sigmoid_2" #' \item \strong{tma} numeric, the value of the calculated tma in reference to normalized Temperatures. #' } #' @export extract_model_tmas <- function(by_var_fit, .var_col = ".var", .model_name_col = "model_name", .model_tma_col = "model_tma") { # by_var_fit %>% str() # grouped_df [1,152 × 9] (S3: grouped_df/tbl_df/tbl/data.frame) # $ .var : chr [1:1152] "A1_FAM_protein" "A2_FAM_protein" "A3_FAM_protein" "A12_FAM_protein" ... # $ model_name: chr [1:1152] "model_1" "model_1" "model_1" "model_1" ... # $ data :List of 1152 out <- by_var_fit %>% dplyr::select(tidyselect::any_of(c(.var_col, .model_name_col, .model_tma_col))) %>% tidyr::unnest(cols = c({{ .model_tma_col }})) %>% dplyr::ungroup() # out %>% str() # tibble [2,259 × 4] (S3: tbl_df/tbl/data.frame) # $ .var : chr [1:2259] "A1_FAM_protein" "A2_FAM_protein" "A3_FAM_protein" "A12_FAM_protein" ... # $ model_name : chr [1:2259] "model_1" "model_1" "model_1" "model_1" ... # $ which_value: chr [1:2259] "sigmoid_1" "sigmoid_1" "sigmoid_1" "sigmoid_1" ... # $ tma : num [1:2259] 0.432 0.268 0.283 0.462 0 ... } # example useage # model_tmas <- extract_model_tmas(by_var_fit) #' Combine raw and modeled data #' #' Use \code{join_with_preds} to combine raw data with the values predicted by a given model fit. #' #' @param tidied_for_tmas a grouped, nested tibble, as returned by \code{tidy_for_tmas} #' @param by_var_fit a grouped, nested tibble, as returned by \code{add_model_fits} #' @param .join_by a string, giving the name of the column shared between \code{tidied_for_tmas} and \code{by_var_fit}, by which data can be mapped between the two. Should be renamed, since the final combination of the tibbles is done with bind_rows(), not join_by(). Defaults to ".var". #' @param .var_col a string, giving the name of the column shared between \code{tidied_for_tmas} and \code{by_var_fit}, which uniquely identifies each individual dataset. Defaults to ".var". #' @param .model_name_col a string, giving the name of the column in which the fitted model is specified by name (e.g. "model_1", "model_2" . . . ). Defaults to "model_name". #' @param .fit_data_col a string, giving the name of the column in \code{by_var_fit} containing nested tibbles of fitted data. Defaults to "data",. #' @param .tidied_data_col a string, giving the name of the column in \code{tidied_for_tmas} containing nested tibbles of raw data. Defaults to "data". #' @param .temp_col_raw a string, giving the name of the columns shared between \code{tidied_for_tmas} and \code{by_var_fit}, containing raw Temperatures. Defaults to "Temperature #' @param .value_norm_col_raw a string, giving the name of the column in \code{tidied_for_tmas} containing normalized RFU data. #' @param .value_col_pred a string, giving the name of the column in \code{by_var_fit} containing predicted and reconstructed values. Defaults to "value" #' @param .keep_cols_from_raw a character vector, containing names of the columns to be carried through into the final output tibble from \code{tidied_for_tmas}. Defaults to c("Temperature_norm", "value_norm"). #' @param .rescale_raw_temps a boolean, defaults to FALSE, giving whether or not the supplied column name to \code{.temp_col_raw} should be normalized in a 0 to 1 range to match the always-normalized Temperature_norm used in fitting. #' @param ... additional arguments, not passed to anything internal here, but allows for the function to recieve named arguments from upstream functions while ignoring arguments passed with ... which match nothing in this function. #' #' @return a tibble of five columns #' \itemize{ #' \item \strong{.var} character, giving the unique dataset identifier for each DSF trace. #' \item \strong{Temperature_norm} numeric, giving the normalized Temperature for a given value #' \item \strong{value} numeric, giving either the normalized raw RFU, a prediction from a fitted model to that normalized raw data, or individual component extract from the model prediction. #' \item \strong{which_value} character, describing which of the possible values types corresponding to a given value in the \code{value} column. e.g. "raw" (normalized raw RFU), "pred" (full model prediction), "resid" (residuals from the model prediction) #' \item \strong{model_name} character, giving the name of the model which was fit, and from which the predictions have been extracted. e.g. "model_1", "model_2" ... For the rows corresponding to raw data, modle_name is NA. #' } #' #' @export join_with_preds <- # rejoin predictions and raw data after model fitting function(tidied_for_tmas, # tidied raw data by_var_fit, # model fitting results .join_by = ".var", # str chr .var_col = ".var", # str chr .model_name_col = "model_name", # str chr .fit_data_col = "data", # str chr .tidied_data_col = "data", # name of the data col to unnest in raw .temp_col_raw = "Temperature", # name of the Temperature col in raw data .value_norm_col_raw = "value_norm", # name of the value_norm col in raw data .value_col_pred = "value", .keep_cols_from_raw = c("Temperature_norm", "value_norm"), .rescale_raw_temps = FALSE, # if TRUE, adds Temperature_norm col to raw data ...) { #------------ inputs # tidied_for_tmas %>% str() # grouped_df [3,696 × 2] (S3: grouped_df/tbl_df/tbl/data.frame) ## NESTED # $ .var: chr [1:3696] "A1_FAM_protein" "A2_FAM_protein" "A3_FAM_protein" "A4_FAM_protein" ... # $ data:List of 3696 # by_var_fit %>% str() # grouped_df [1,152 × 9] (S3: grouped_df/tbl_df/tbl/data.frame) # $ .var : chr [1:1152] "A1_FAM_protein" "A2_FAM_protein" "A3_FAM_protein" "A12_FAM_protein" ... # $ model_name: chr [1:1152] "model_1" "model_1" "model_1" "model_1" ... # $ data :List of 1152 if(.rescale_raw_temps) { tidied_for_tmas <- tidied_for_tmas %>% dplyr::mutate(!!.tidied_data_col := purrr::map({{ .tidied_data_col }}), function(df) df %>% dplyr::mutate( "Temperature_norm" = scales::rescale({{ .temp_col_raw }}))) } # extract predictions preds <- by_var_fit %>% dplyr::ungroup() %>% dplyr::select(tidyselect::any_of(c(.var_col, .model_name_col, .fit_data_col) )) %>% tidyr::unnest(cols = c(.data[[.fit_data_col]])) %>% dplyr::rename(!!.join_by := .data[[.var_col]]) # match to raw for joining #------------ structures for documentation # preds %>% str() # grouped_df [357,980 × 5] (S3: grouped_df/tbl_df/tbl/data.frame) # $ variable : chr [1:357980] "A1_FAM_protein" "A1_FAM_protein" "A1_FAM_protein" "A1_FAM_protein" ... # $ model_name : chr [1:357980] "model_1" "model_1" "model_1" "model_1" ... # $ Temperature_norm: num [1:357980] 0 0 0.0145 0.0145 0.029 ... # $ which_value : chr [1:357980] "resid" "pred" "resid" "pred" ... # $ value : num [1:357980] 3.44e-01 1.41e-14 3.81e-01 4.09e-14 3.89e-01 ... # - attr(*, "groups")= tibble [192 × 2] (S3: tbl_df/tbl/data.frame) raw <- tidied_for_tmas %>% dplyr::ungroup() %>% tidyr::unnest(cols = c(.data[[.tidied_data_col]])) %>% dplyr::select(tidyselect::any_of(c(.join_by, .keep_cols_from_raw))) %>% dplyr::rename(!!.value_col_pred := .data[[.value_norm_col_raw]]) %>% dplyr::mutate("which_value" = "raw") out <- dplyr::bind_rows(raw, preds) # out %>% str() # tibble [616,700 × 5] (S3: tbl_df/tbl/data.frame) # $ .var : chr [1:616700] "A1_FAM_protein" "A1_FAM_protein" "A1_FAM_protein" "A1_FAM_protein" ... # $ Temperature_norm: num [1:616700] 0 0.0145 0.029 0.0435 0.058 ... # $ value : num [1:616700] 0.935 0.947 1 0.945 0.883 ... # $ which_value : chr [1:616700] "raw" "raw" "raw" "raw" ... # $ model_name : chr [1:616700] NA NA NA NA ... } # example use # raw_and_pred <- join_with_preds(tidied_for_tmas, by_var_fit) #' Tidy model data for plotting #' #' Ultimately, may not export this function. #' #' Use \code{tidy_for_plot} to prepare raw and predicted data for plotting. #' #' @param tidied_for_tmas a tibble of raw data, as returned by \code{tidy_for_tmas} #' @param by_var_fit a tibble of fit results, as returned by \code{add_model_fits} #' @param layout a tibble of plate layout information, as returned by \code{read_plate_layout} or \code{extract_plate_layout} #' @param .var_col a string, giving the name of the column in both \code{tidy_for_tmas} and \code{by_var_fit} giving identical unqiue identifiers fo a given dataset. Defaults to ".var" #' @param .model_name_col a string, giving the name of column in \code{by_var_fit} which gives the name of the fitted model, e.g. "model_1". Defaults to "model_name". #' @param .hit_filt_col a string, giving the name of the column which is created here through a \code{unite()} operation, and later matched to hit calls. Defaults to "dye_channel_f" #' @param .hit_filt_components a character vector of length 2, giving the columns in \code{tidied_for_tmas} to join (in the given order) to create the column which will bear the name given in \code{.hit_filt_col}, with an underscore separator. Defaults to c("dye", "channel_f"). #' @param ... additional arguments, not passed to anything internal here, but allows for the function to recieve named arguments from upstream functions while ignoring arguments passed with ... which match nothing in this function. #' #' @return a tibble, rady for passing to downstream plotting functions. #' #' @export tidy_for_plot <- # re-joins raw and fitting prediction data and laouts for plotting function(tidied_for_tmas, # as output by by_var_fit, # as output by add_model_fits, must contain column.var, model_name, model_tma layout, # layout, often extracted from raw_df # layout <- extract_plate_layout(raw_df, ...) .var_col = ".var", .model_name_col = "model_name", .hit_filt_col = "dye_channel_f", .hit_filt_components = c("dye", "channel_f"), ...) { fitted_vars <- by_var_fit[[.var_col]] %>% unique() df <- # keep only the traces that were fit tidied_for_tmas %>% dplyr::filter(.data[[.var_col]] %in% fitted_vars) %>% join_with_preds(., by_var_fit, ...) %>% # add "which_value" col dplyr::left_join(., layout, by = .var_col) %>% # add layout info used for plotting downstream tidyr::unite(".var_which_val", c(.data[[.var_col]], # from user .data$which_value), # always "which_value", via join_with_preds remove = FALSE) %>% tidyr::unite(!!.hit_filt_col, c(.data[[.hit_filt_components[[1]]]], # typically dye .data[[.hit_filt_components[[2]]]]), # typically channel_f remove = FALSE) } #' Plot raw and predicted data together, with Tmas #' #' use \code{plot_with_preds} to generate a plot displaying the results of model fitting. In a better version of this function, would likely be refactored alongside its wrappers, \code{plot_analyzed_hits()} and \code{save_model_figure()}. #' #' @param raw_and_pred a tibble, as returned by \code{join_with_preds} #' @param tma_df a tibble, as returend by \code{extract_model_tmas} #' @param .var_col a string, giving the name of the column in both \code{tidy_for_tmas} and \code{by_var_fit} giving identical unqiue identifiers fo a given dataset. Defaults to ".var" #' @param .var_which_val_col a string, giving the name of the column in \code{raw_and_pred} which further specifies the unique datasets into individaul value types, e.g. "A1_FAM_raw", "A1_FAM_sigmoid_1", etc. Passed to ggplot(aes(group = )), to define unique datasets for all geoms used in this plot. #' @param .which_value_col a string, giving the name of the column in \code{raw_and_pred} giving the value type--e.g. "sigmoid_1", "sigmoid_2", etc. Passed to aes(fill = ) argument of geom_ribbon; used to shade the reconstructed sigmoids and reconstructed initial fluroescence omponents differently. #' @param .model_name_col a string, giving the name of column in \code{raw_and_pred} which gives the name of the fitted model, e.g. "model_1". Defaults to "model_name". #' @param .Temperature_norm_col a string, giving the name of the column in \code{raw_and_pred} containing normalized Temperatures. Used as the x values / x axis in the returned plot. #' @param .value_col a string, giving the name of the column in \code{raw_and_pred} containing y values, regardless of value type. Used as the y axis / y values in the returned plot. #' @param .tma_col a string, giving the name of the column in \code{tma_df} ctaining the apparent melting temperatures extracted from the fits. Note that these must correspond to the normalized Temperature, unless the predictions and raw data have been mapped onto raw Temperature before the creation of this plot. #' @param .fill_scale a named character vector, passed directly to the \code{values} argument of \code{scale_color_manual}. Determines the shading colors used in the reconstructed fit components. Defaults to c("sigmoid_1" = "#4AA267", "sigmoid_2" = "#4AA267", "sigmoid_3" = "#4AA267", "initial_1" = "darkgrey") #' @param .point_size a number, passed to geom_point(size = ), the geom used to display the raw data. Defaults to 0.1 #' @param .point_alpha a number, passed to geom_point(alpha = ), the geom used to display the raw data. Defaults to 0.2. #' @param .point_color a string of a quoted color name, passed to geom_point(color = ), the geom used to display the raw data. Defaults to "black". #' @param .pred_line_color a string of a quoted color name, passed to geom_line(color = ), the geom used to display the full model prediction. Defaults to "black". #' @param .vline_color a string of a quoted color name, passed to geom_vline(color = ), the geom used to display tmas. Defaults to "black" #' @param .vline_size a number, passed to geom_vline(size = ), the geom used to display tmas. Defaults to 0.2 #' @param .line_size a number, passed to geom_line(size = ), the geom used to display the full model prediction. Defaults to 0.3 #' @param .line_alpha a number, passed to geom_line(alpha = ), the geom used to display the full model prediction. Defaults to 0.8 #' @param .ribbon_alpha a number, passed to geom_ribbon(alpha = ), the geom used to display the individual reconstructed model components. Defaults to 0.3 #' @param .ribbon_color a string of a quoted color name, passed to geom_ribbon(color = ), the geom used to display the full model prediction. Defaults to NA, but if assigned, will appear as a line on the top of the shaded regions. #' @param ... additional arguments, not passed to anything internal here, but allows for the function to recieve named arguments from upstream functions while ignoring arguments passed with ... which match nothing in this function. IN a better version of this function, these arguments be passed to \code{theme_screen_austere()} within this function. #' #' @return a minimal ggplot2 plot object for the given data, without faceting, fixed dimensions, or cutom labels. #' #' @export plot_with_preds <- function(raw_and_pred, tma_df, .var_col = ".var", .var_which_val_col = ".var_which_val", .which_value_col = "which_value", .model_name_col = "model_name", .Temperature_norm_col = "Temperature_norm", .value_col = "value", .tma_col = "tma", .fill_scale = c("sigmoid_1" = "#4AA267", "sigmoid_2" = "#4AA267", "sigmoid_3" = "#4AA267", "initial_1" = "darkgrey"), .point_size = 0.1, .point_alpha = 0.2, .point_color = "black", .pred_line_color = "black", .vline_color = "black", .vline_size = 0.2, .line_size = 0.3, .line_alpha = 0.8, .ribbon_alpha = 0.3, .ribbon_color = NA, ...) { raw <- raw_and_pred %>% dplyr::filter(.data[[.which_value_col]] == "raw") %>% dplyr::select(-.data[[.model_name_col]]) pred <- raw_and_pred %>% dplyr::filter(.data[[.which_value_col]] == "pred") components <- raw_and_pred %>% dplyr::filter(! .data[[.which_value_col]] %in% c("pred", "raw", "resid")) p <- pred %>% ggplot2::ggplot(ggplot2::aes(x = .data[[.Temperature_norm_col]], y = .data[[.value_col]], group = .data[[.var_which_val_col]]) # .var, + which component ) + ggplot2::geom_vline(data = tma_df, ggplot2::aes(xintercept = .data[[.tma_col]]), color = .vline_color, size = .vline_size) + ggplot2::geom_point(data = raw, size = .point_size, alpha = .point_alpha, color = .point_color) + ggplot2::geom_line(data = pred, color = .pred_line_color, size = .line_size, alpha = .line_alpha, linetype = "solid") + ggplot2::geom_ribbon( data = components, ggplot2::aes(ymin = 0, ymax = .data[[.value_col]], fill = .data[[.which_value_col]] ), alpha = .ribbon_alpha, color = .ribbon_color) + ggplot2::scale_fill_manual( values = .fill_scale) + dsfworld::theme_screen_austere() # # list("plot" = p, # "raw" = raw, # "pred" = pred, # "components" = components, # "raw_and_pred" = raw_and_pred) } #' Plot #' #' A wrapper function for \code{plot_with_preds}; \code{plot_analyzed_hits} uses an additional input tibble to filter the plotted data to include only hits, and adds custom plot titles. In a better version of this function, would likely be refactored alongside \code{plot_with_preds()} and \code{save_model_figure()}. #' #' #' @param tidied_for_plot a tibble of raw data, as returned by \code{tidy_for_tmas} #' @param hits_by_channel a tibble, as expected by \code{pull_assigned}, containing assignments matching to values found in \code{tidied_fot_plot}, in the column specifided through the \code{.dye_channel_col} argument. #' @param model_tmas a tibble, as returned by \code{extract_model_tmas} #' @param .dye_channel_col a string, giving the name of the column in \code{tidied_for_plot} containing information on which hits were called, e.g. "dye_channel_f", which typically contains values in the format <dye_name>_<channel_name>, e.g. "T004_FAM". #' @param .plot_assignment a string, passed to \code{pull_assigned}; all values with this assignment in \code{hits_by_channel} will appear in the output plot. #' @param .var_col a string, giving the name of the column in both \code{tidy_for_tmas} and \code{by_var_fit} giving identical unqiue identifiers fo a given dataset. Defaults to ".var" #' @param ... additional arguments, passed to \code{plot_with_preds()}. #' #' @return a ggplot2 object, as returned by \code{plot_with_preds}, for a defined subset of the data, and with a plot title. #' #' @export plot_analyzed_hits <- function(tidied_for_plot, hits_by_channel, model_tmas, .dye_channel_col = "dye_channel_f", .plot_assignment = "hit", .var_col = ".var", ...) { titles <- make_figure_title(tidied_for_plot) hits <- pull_assigned(hits_by_channel, assignment = .plot_assignment, # usually "hit" .dye_col = .dye_channel_col) for_plot_hits <- tidied_for_plot %>% dplyr::filter(.data[[.dye_channel_col]] %in% hits) for_plot_tmas <- model_tmas %>% dplyr::filter(.data[[.var_col]] %in% for_plot_hits[[.var_col]]) %>% dplyr::left_join(for_plot_hits, by = .data[[.var_col]]) # add other cols, e.g. those used for faceting print("The message Joining, by = <> (usually .var, model_name, which_value), is generated within plot_analyzed_hits(), when labeling the tma data so that it will facet correctly. Address this in a later version of the function; the printing is unsettling and this introduces a potentil source of silent failure." ) p <- plot_with_preds(for_plot_hits, for_plot_tmas, ...) } #' Save a figure displaying raw data, fits, and tmas. Use reasonable dimensions. #' #' A wrapper function for adding facets, calculating dimenstions, and saving with a consistent name. In a better version of this function, would likely be refactored alongside \code{plot_with_preds()} and \code{plot_analyzed_hits()}. Calls on \code{save_stacked_plot()} to do so. #' #' @param tidied_for_tmas a grouped, nested tibble, as returned by \code{tidy_for_tmas} #' @param by_var_fit a tibble, as output by \code{add_model_fits}. #' @param tidied_screen a tibble, as returned by \code{tidy_dye_screen()} #' @param hits_by_channel a tibble containing hit assignments, as expected by \code{pull_assigned()} #' @param extract_figure_title a boolean; if TRUE, both saved name and plot title are extracted from the given data via \code{make_figure_title()} #' @param extract_layout_from_tidied a boolean; if TRUE, the experimental layout is extracted from \code{tidied_screen} via \code{extract_plate_layout}, and the unique-identifier column of the output layout is named ".var" #' @param extract_tmas_from_by_var_fit a boolean; if TRUE, the tmas applied to the plots are extracted directly from \code{by_var_fit}. This is usually done in a single operation, and it's not clear exactly why one would set this to FALSE unless avoid that additional operation was important, and the model tma values had already been calculated and stored elsewhere. #' @param layout if extract_layout_from_tidied is FALSE, a tibble containig a layout, as returned by \code{read_plate_layout} or \code{extract_plate_layout}. Gets passed to \code{tidy_for_plot()} in this function. #' @param model_tmas if extract_tmas_from_by_var_fit is FALSE, a tibble containing the extracted model tmas, formatted to match the output of \code{extract_model_tmas()}. #' @param .well_col_layout a string, giving the name of the column containing well names in \code{tidied_for_tmas}, which is renamed ".var" if extract_layout_from_tidied = TRUE. #' @param .grid_margin_ratio a number, passed to \code{convert_heights()}, estimating the height ratio between a full panel (including, e.g. axis ticks and labels), and the fixed panel size. #' @param ... additional named parameters, passed to the functions: \code{extract_plate_layout()}, \code{join_with_preds()}, \code{tidied_for_plot()}, \code{plot_analyzed_hits()}, \code{force_panel_sizing()}, and \code{save_stacked_plots()} #' #' @return if assigned, the final figure object. regardless of assignment, a saved figure, with names, directories, and file types as dictated by \code{save_stacked_plots()}. Uses \code{save_stacked_plots()} defaults, unless these arguments are overwritten by passing new named values for them to this function. #' #' @export save_model_figure <- function(tidied_for_tmas, # as generated by tidy_for_tmas by_var_fit, # as greated by add_model_fits tidied_screen, # a layout, or a tibble with layout info hits_by_channel, # a tibble containing the hits, called by channel extract_figure_title = TRUE, extract_layout_from_tidied = TRUE, # boolean, if FALSE, user can supply extract_tmas_from_by_var_fit = TRUE, # boolean, if FALSE, user can supply layout = NULL, # linked to extract_layout_from_tidied; user supplies here model_tmas = NULL, # linked to extract_tmas_from_by_var_fit; user supplies here .well_col_layout = "variable", .grid_margin_ratio = 215/110, ... # passed to join_with_preds, tidy_for_plot, and/or plot_analyzed_hits ) { if (extract_layout_from_tidied) { layout <- extract_plate_layout(tidied_screen, .well_col = .well_col_layout, .extract_well = FALSE, ...) %>% dplyr::rename(".var" = .data[[.well_col_layout]]) } if (extract_tmas_from_by_var_fit) { model_tmas <- extract_model_tmas(by_var_fit) } if (extract_figure_title) { fig_titles <- make_figure_title(tidied_screen) } raw_and_pred <- join_with_preds(tidied_for_tmas, by_var_fit, ...) tidied_for_plot <- # homoegenize column names and join tidy_for_plot(tidied_for_tmas, by_var_fit, layout, ...) p_hits <- # facet by model, only hits plot_analyzed_hits(tidied_for_plot, hits_by_channel, model_tmas, ...) + ggplot2::facet_wrap(ggplot2::vars(.data$dye_channel_f, .data$model_name), scales = "free", ncol = 6) + ggplot2::labs(fill = "Component type", x = "Normalized Temperature", y = "Normalized RFU", subtitle = "Fits and Tmas for hits") + ggplot2::theme(aspect.ratio = 1/1.618, plot.title = element_text(hjust = 0), plot.subtitle = element_text(hjust = 0)) + force_panel_sizing(...) hits <- hits_by_channel %>% dplyr::filter(.data$assignment == "hit") %>% dplyr::pull(.data$dye_channel_f) save_height <- convert_heights(.paneled_by = hits, facet_type = "grid", .grid_margin_ratio = .grid_margin_ratio, .title_height_add = 0.3) save_stacked_plots(.plot_list = list(p_hits), .figure_titles = fig_titles, .plot_heights = c(save_height), .default_width = 6, .save_suffix = "with_model_preds", .default_title_height = 0.5, ...) out <- p_hits }
a8f7948c7b4457062db935ac488e6689d45f16d0
0a906cf8b1b7da2aea87de958e3662870df49727
/blorr/inst/testfiles/blr_pairs_cpp/libFuzzer_blr_pairs_cpp/blr_pairs_cpp_valgrind_files/1609955489-test.R
0ff23cb7bfade501653a3c941860429b3add36fb
[]
no_license
akhikolla/updated-only-Issues
a85c887f0e1aae8a8dc358717d55b21678d04660
7d74489dfc7ddfec3955ae7891f15e920cad2e0c
refs/heads/master
2023-04-13T08:22:15.699449
2021-04-21T16:25:35
2021-04-21T16:25:35
360,232,775
0
0
null
null
null
null
UTF-8
R
false
false
502
r
1609955489-test.R
testlist <- list(x = c(5.48663231711981e-310, -5.15273908896653e-36, -6.95715257111252e+306, NaN, NaN, NaN, NaN, NaN, 1.00496080469151e+180, -7.72435253122689e-84, 8.59674223763769e-322, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), y = numeric(0)) result <- do.call(blorr:::blr_pairs_cpp,testlist) str(result)
a09553538ea28a59233527c39e44bf1ff2ba1361
eabc282325f21a7b4fec1cc043915a1cb44ad7c1
/R/SplitUplift.R
5e9af5cb714f603c8b372128473a214c13afbdf0
[]
no_license
cran/tools4uplift
40a588fdad2bfa0f4e3c65a3a240ca53105eb9df
79b2da4daf80855f3078b9ddcf3f6d80be78279c
refs/heads/master
2021-06-19T14:03:02.472105
2021-01-06T15:50:02
2021-01-06T15:50:02
164,908,475
0
0
null
null
null
null
UTF-8
R
false
false
946
r
SplitUplift.R
SplitUplift <- function(data, p, group){ # Splits the data with respect to uplift distribution. # # Args: # data: a data frame containing the treatment, the outcome and the predictors. # p: The desired sample size. p is a value between 0 and 1 expressed as a decimal, # it is set to be proportional to the number of observations per group. # group: Your grouping variables. Generally, for uplift modelling, this should be # a vector of treatment and response variables names, e.g. c("treat", "y"). # # Returns: # The training and validation data sets. data$ID = seq(1:nrow(data)) train <- data %>% group_by(paste(group, collapse = ',')) %>% sample_frac(p) train <- as.data.frame(train[,-ncol(train)]) valid <- data %>% anti_join(train, by = "ID") dataSplit <- list(train[,-ncol(train)], valid[,-ncol(valid)]) class(dataSplit) <- "SplitUplift" return(dataSplit) } # END FUN
18f1d6dd93df7ed74a7c2e1669757382b619b1bc
617bd80da2f7f605ab580dfc54465c2a83c84f8e
/acutecare_nordic_ocde.R
1574296d5fafa2c34c68528e85555167c12ccf28
[]
no_license
wemigliari/governance
65997565f0aca84dc1f61bb2075dffc390ad0a52
ebb58e6ccfe27f981cf7c0d6a06ce304452f3c4c
refs/heads/master
2023-07-05T11:57:48.998839
2021-08-13T21:13:20
2021-08-13T21:13:20
263,469,120
1
0
null
2021-01-13T23:22:21
2020-05-12T22:46:13
R
UTF-8
R
false
false
1,878
r
acutecare_nordic_ocde.R
library(dplyr) library(readxl) setwd("/Users/wemigliari/Documents/R/tabelas") getwd() # Have a look at the following webpage to change csv into xlsx # http://help.snapizzi.com/en/articles/1089773-split-csv-data-into-different-columns ac_ocde <- read_xlsx("/Users/wemigliari/Documents/R/tabelas/hb_ocde.xlsx") ac_ocde1 <- ac_ocde%>%filter(SUBJECT == "ACUTE") ac_ocde1 <- data.frame(ac_ocde1) # Fisrt, convert the data table into data frame ac_ocde1[,7] <- sapply(ac_ocde1[,7], as.numeric) ### Plotting plot(ac_ocde1$TIME, ac_ocde1$Value, pch = 6, col = "steelblue") library(plotly) library(RColorBrewer) plot_ly(ac_ocde1, x = ~TIME, y = ~Value, text = ~LOCATION, type = 'scatter', mode = 'markers', marker = list(size = ~Value/2, opacity = 0.5), color = ~LOCATION, colors = colorRampPalette(brewer.pal(10,"Reds"))(42))%>% layout(title = 'Hospital beds. Total per 1,000 inhabitants, 2019 or latest available, OCDE', xaxis = list(title = "", gridcolor = 'rgb(255, 255, 255)'), yaxis = list(title = "Hospital Beds", gridcolor = 'rgb(255, 255, 255)'), showlegend = TRUE) ### nordics <- c("SWE", "DNK", "NOR", "FIN") ac_ocde2 <- ac_ocde1%>%filter(LOCATION %in% nordics) class(ac_ocde2) ac_ocde2 <- data.frame(ac_ocde2) # Fisrt, convert the data table into data frame ### Plotting plot_ly(ac_ocde2, x = ~TIME, y = ~Value, text = ~LOCATION, type = 'scatter', mode = 'lines', marker = list(size = ~Value, opacity = 0.5), color = ~LOCATION, colors = colorRampPalette(brewer.pal(4,"Dark2"))(4))%>% layout(title = 'Hospital beds, Acute. Total per 1,000 inhabitants, 2019 or latest available, OCDE', xaxis = list(title = ""), size = 0.7, yaxis = list(title = "Hospital Beds"), size = 0.7, showlegend = TRUE, legend = list(font = list(size = 10)))
d0590966e980af16a3b7212a553b365a525855e1
e7d6f4c26535a283b2a705ad95dbc5cdf175d86c
/Code/singleGridboxCombine.R
c025a884123f8b1331c1bbd06c94b4bbc51c3338
[]
no_license
nlenssen/cruInvestigation
8d7d79a4d71abe73d6a8ce17bed146c9f0b4e0d2
af2792166ffdf24c059d831b09094f0d0fb3e560
refs/heads/master
2020-03-29T20:23:02.846434
2018-10-09T01:27:06
2018-10-09T01:27:06
150,309,760
0
0
null
null
null
null
UTF-8
R
false
false
8,894
r
singleGridboxCombine.R
source("Code/namelist.Rnl") ## Parameters # Papua New Guinea # targetLon <- 142.8 # targetLat <- -5.6 # title <- "FMA Precipitation for Papua New Guinea" # plotDes <- 'PNG' # sInd <- 3 # Ethiopia # targetLon <- 40.7 # targetLat <- 8 # title <- "JAS Precipitation for Ethiopia" # plotDes <- 'ETH' # sInd <- 8 # DRC targetLon <- 23.5 targetLat <- -1 title <- "OND Precipitation for DRC" plotDes <- 'DRC' sInd <- 11 # NYC targetLon <- -74 targetLat <- 41 title <- "MAM Precipitation for NYC" plotDes <- 'NYC' sInd <- 4 ############################################################################### # Load in the relevant PPT Data from CRU ############################################################################### # load in the ncdf metadata handle <- nc_open(sprintf('%s/Raw/%s',ddir,pptFile)) lon <- ncvar_get(handle,'lon') lat <- ncvar_get(handle,'lat') xInd <- which.min(abs(lon-targetLon)) yInd <- which.min(abs(lat-targetLat)) # set up all of the necessary time objects to properly subset the data time <- ncvar_get(handle,'time') tFull <- seq(1901,endYear+1,length=length(time)+1)[1:length(time)] year <- floor(tFull) month <- rep(1:12,length(time)/12) fullTimeMat <- cbind(year,month) # subset based on starting year and make all of the necessary time objects timeInds <- which(year >= startYear) timeMat <- fullTimeMat[timeInds,] # grab the ppt monthly time series for the single location ppt <- ncvar_get(handle, 'pre', start=c(xInd,yInd,timeInds[1]), count=c(1,1,length(timeInds)) ) counts <- ncvar_get(handle, 'stn', start=c(xInd,yInd,timeInds[1]), count=c(1,1,length(timeInds)) ) nc_close(handle) # get the ppt series arranged all pretty pptMonthly <- matrix(ppt,ncol=12,byrow=T) pptSeasonal <- seasonalSum12(ppt,tYear) countsMonthly <- matrix(counts,ncol=12,byrow=T) countsSeasonal <- seasonalSum12(counts,tYear) ############################################################################### # Load in the relevant PPT Data from CHIRPS ############################################################################### tYear2 <- 1981:2018 # load in the ncdf metadata handle <- nc_open(sprintf('%s/Raw/%s',ddir,'CHIRPS.mon.0.5x0.5.1981.2018.nc')) lon2 <- ncvar_get(handle,'X') lat2 <- ncvar_get(handle,'Y') # set up all of the necessary time objects to properly subset the data time2 <- ncvar_get(handle,'T') nYears2 <- ceiling(length(time2)/12) tFull2 <- seq(1981,by=1/12,length=length(time2)) year2 <- floor(tFull2) month2 <- rep(1:12,ceiling(length(time2)/12))[1:length(time2)] timeMat2 <- cbind(year2,month2) # figure out which gridbox corresponds xInd2 <- which(lon2 == lon[xInd]) yInd2 <- which(lat2 == lat[yInd]) # check some data things testField <- ncvar_get(handle, 'precipitation', start=c(1,1,1), count=c(-1,-1,1)) # grab the ppt monthly time series for the single location ppt2 <- ncvar_get(handle, 'precipitation', start=c(xInd2,yInd2,1), count=c(1,1,-1) ) #clean ppt2[ppt2<0 | ppt2 > 10000] <- NA nc_close(handle) # add NAs as needed ppt2Full <- c(ppt2,rep(NA,12 - length(time2) %%12)) # get the ppt series arranged all pretty pptMonthly2 <- matrix(ppt2Full,ncol=12,byrow=T) pptSeasonal2 <- seasonalSum12(ppt2Full,tYear2) ############################################################################### # Plot up the two series and think about how to combine ############################################################################### # get the series and time objs cruSeries <- pptSeasonal[,sInd] cruTime <- as.numeric(labels(cruSeries)) chirpsSeries <- pptSeasonal2[,sInd] chirpsTime <- as.numeric(labels(chirpsSeries)) # build climatologies cruClimYears <- 1961:1990 chirpsClimYears <- 1982:2011 cruClimInds <- which(cruTime %in% cruClimYears) chirpsClimInds <- which(chirpsTime %in% chirpsClimYears) cruClim <- mean(cruSeries[cruClimInds],na.rm=T) chirpsClim <- mean(chirpsSeries[chirpsClimInds],na.rm=T) cruTerc <- quantile(cruSeries[cruClimInds],probs=c(1/3,2/3)) chirpsTerc <- quantile(chirpsSeries[chirpsClimInds], probs=c(1/3,2/3)) xr <- range(cruTime,chirpsTime,na.rm=T) yr <- range(cruSeries,chirpsSeries,na.rm=T) # Plot the raw information pdf(sprintf('%s/raw_%s.pdf',plotdir,plotDes),10,7) plot(cruTime,cruSeries,type='l',xlim=xr,ylim=yr,main=title,lwd=2, xlab='Year', ylab='Precipitation (mm/season)') points(cruTime,rep(cruClim,length(cruTime)),type='l',col='black',lwd=1.5) points(cruTime,rep(cruTerc[1],length(cruTime)),type='l',col='black',lwd=1.5,lty=3) points(cruTime,rep(cruTerc[2],length(cruTime)),type='l',col='black',lwd=1.5,lty=3) points(chirpsTime,chirpsSeries,type='l',col='blue',lwd=2) points(chirpsTime,rep(chirpsClim,length(chirpsTime)),type='l',col='blue',lwd=1.5) points(chirpsTime,rep(chirpsTerc[1],length(chirpsTime)), type='l',col='blue',lwd=1.5,lty=3) points(chirpsTime,rep(chirpsTerc[2],length(chirpsTime)), type='l',col='blue',lwd=1.5,lty=3) par(new=TRUE) plot(cruTime,countsSeasonal[,sInd],col='red',type='l', lty=2, xaxt="n", yaxt="n",ylab="", xlab="",ylim=c(0,35)) legend('topleft', c('CRU TS4.01', 'CHIRPS'), lwd=2, col=c('black', 'blue')) dev.off() # normalize the series individually and see how they line up # using a gaussian standardization which is probably not good (should be gamma probably) cruSd <- sd(cruSeries[which(cruTime %in% cruClimYears)],na.rm=T) chirpsSD <- sd(chirpsSeries[which(chirpsTime %in% chirpsClimYears)],na.rm=T) cruNormal <- (cruSeries- cruClim)/cruSd chirpsNormal <- (chirpsSeries - chirpsClim)/chirpsSD cruTercNormal <- (cruTerc - cruClim)/cruSd chirpsTercNormal <- (chirpsTerc - chirpsClim)/chirpsSD xr <- range(cruTime,chirpsTime) ymax <- max(abs(cruNormal),abs(chirpsNormal),na.rm=T) yr <- c(-ymax, ymax) pdf(sprintf('%s/standarized_%s.pdf',plotdir,plotDes),10,7) plot(cruTime,cruNormal,type='l',xlim=xr,ylim=yr,main=title,lwd=2, xlab='Year', ylab='Normalized Precipitation (sigma/season)') points(chirpsTime,chirpsNormal,type='l',col='blue',lwd=2) points(cruTime,rep(cruTercNormal[1],length(cruTime)), type='l',col='black',lwd=1.5,lty=3) points(cruTime,rep(cruTercNormal[2],length(cruTime)), type='l',col='black',lwd=1.5,lty=3) points(chirpsTime,rep(chirpsTercNormal[1],length(chirpsTime)), type='l',col='blue',lwd=1.5,lty=3) points(chirpsTime,rep(chirpsTercNormal[2],length(chirpsTime)), type='l',col='blue',lwd=1.5,lty=3) abline(h=0) countsNormal <- (countsSeasonal[,sInd])/sd(countsSeasonal[,sInd]) points(cruTime,countsNormal,col='red',type='l',lty=2) legend('topleft', c('CRU TS4.01', 'CHIRPS'), lwd=2, col=c('black', 'blue')) dev.off() ############################################################################### # Estimate the underlying Gamma? distributions of the two series ############################################################################### # get the full fit object for each gammaCru <- gammaFit(cruSeries[cruClimInds]) gaussCru <- normalFit(cruSeries[cruClimInds]) gammaQuantCru <- quantile(gammaCru,probs=c(1/3,2/3)) gaussQuantCru <- quantile(gaussCru,probs=c(1/3,2/3)) cruQuantiles <- rbind(cruTerc, quantile(gammaCru,probs=c(1/3,2/3))$quantiles, quantile(gaussCru,probs=c(1/3,2/3))$quantiles) gammaChirps <- gammaFit(chirpsSeries[chirpsClimInds]) gaussChirps <- normalFit(chirpsSeries[chirpsClimInds]) chirpsQuantiles <- rbind(chirpsTerc, quantile(gammaChirps,probs=c(1/3,2/3))$quantiles, quantile(gaussChirps,probs=c(1/3,2/3))$quantiles) colnames(cruQuantiles) <- colnames(chirpsQuantiles) <- c('1/3','2/3') rownames(cruQuantiles) <- rownames(chirpsQuantiles) <- c('empirical','gamma','normal') # do a quick visual check of the two fits using the builtin plotting functions # included in firdistrplus compareDistPlot(gammaCru,gaussCru) compareDistPlot(gammaChirps,gaussChirps) # look at an annotated qq plot where I include the various qqcomp(list(gammaCru,gaussCru),legendtext=c('gamma', 'normal')) abline(v=cruQuantiles[1,]) abline(v=cruQuantiles[2,],col='red') abline(v=cruQuantiles[3,],col='green',lty=2) qqcomp(list(gammaChirps,gaussChirps),legendtext=c('gamma', 'normal')) abline(v=chirpsQuantiles[1,]) abline(v=chirpsQuantiles[2,],col='red') abline(v=chirpsQuantiles[3,],col='green',lty=2) ############################################################################### # Explore error in tercile assessment ############################################################################### # compute the empirical exceedences using the climatologies empiricalExceed <- compareExceedences(cruSeries, chirpsSeries, cruTime, chirpsTime, cruTerc, chirpsTerc) gammaExceed <- compareExceedences(cruSeries, chirpsSeries, cruTime, chirpsTime, cruQuantiles[2,], chirpsQuantiles[2,]) gaussExceed <- compareExceedences(cruSeries, chirpsSeries, cruTime, chirpsTime, cruQuantiles[3,], chirpsQuantiles[3,]) # Not great news, not really sure how to interpret right now
c8772f0f913db64e1c04b4bc35ab6177691407ce
f8e58a4b8ee11502f1b07c08e93ae96de19574e1
/R/update.setup.R
c309dfaba68a1af6f6a778d5e93fb07a3fe6df2b
[]
no_license
cran/ARTP2
648609beb0d95088aabe373208f0070e8bc4a863
3d4401daa50050ac020c4612a2b819913bd2f549
refs/heads/master
2021-01-15T15:25:21.875869
2018-11-30T20:30:03
2018-11-30T20:30:03
51,500,259
0
1
null
null
null
null
UTF-8
R
false
false
815
r
update.setup.R
update.setup <- function(setup, nperm, lambda, nthread){ if(!is.null(nperm)){ setup$options$nperm <- nperm } if(!is.null(nthread)){ setup$options$nthread <- nthread } # hyper-threading is off. Convenient for NIH biowulf users # mightbe unnecessary for others setup$options$nthread <- min(setup$options$nthread, detectCores()); if(is.null(lambda)){ lambda <- 1.0 }else{ setup$options$lambda <- setup$options$lambda * lambda for(i in 1:length(setup$norm.stat$V)){ setup$norm.stat$V[[i]] <- setup$norm.stat$V[[i]] / lambda setup$norm.stat$score0[[i]] <- setup$norm.stat$score0[[i]] / lambda } } tmp <- .C("check_nthread", nthread = as.integer(setup$options$nthread), PACKAGE = "ARTP2") setup$options$nthread <- tmp$nthread setup }
9a89cb3905af81bc3f6b15362938081a039b9388
a68c66075f3ffa0db6103f0c9e8529eb6fa85e62
/man/pisa.school.Rd
2d8071f70cabd31ed17656cd5b2eb50069fa14ba
[]
no_license
cognitivepsychology/pisa
f9d41bcc7b2e75d60bcd27b9399e5ff6e4bf8766
ae58e6d59351b924b3e6388eb0ca5884257d966d
refs/heads/master
2021-01-18T09:08:50.072826
2013-02-16T01:33:41
2013-02-16T01:33:41
null
0
0
null
null
null
null
UTF-8
R
false
false
733
rd
pisa.school.Rd
\docType{data} \name{pisa.school} \alias{pisa.school} \title{School results of the 2009 Programm of International Student Assessment.} \format{a data frame with 17,145 ovservations of 247 variables.} \source{ Organization for Economic Co-operation and Development } \description{ School results from the 2009 Programme of International Student Assessment (PISA) as provided by the Organization for Economic Co-operation and Development (OECD). See \url{http://www.pisa.oecd.org/} for more information including the code book. } \references{ Organisation for Economic Co-operation and Development (2009). Programme for International Student Assessment (PISA). \url{http://www.pisa.oecd.org/} } \keyword{datasets}
791fe4174f9a7f2e71df937addcf68e7b87dcf00
5342d6679da825c1b13da3c496d9c89c33c7896a
/nexis-api.R
e7f19fa887d53dacc489a67f6fd2e6a8204f09e9
[]
no_license
chiuyt19/nexis-uni
eafc2a62c47d80b73599bd663570f66f5723a84b
2a65b21dfdef67cd39cb2003dd4604864faca52f
refs/heads/master
2021-09-02T07:03:14.073831
2017-12-31T07:57:15
2017-12-31T07:57:15
115,653,447
0
0
null
null
null
null
UTF-8
R
false
false
1,421
r
nexis-api.R
library(dplyr) library(httr) library(jsonlite) library(RCurl) library(XML) base.url <-"http://advance.lexis.com/api/search?" basic.url<-"http://advance.lexis.com/api/" #login authentication using RCurl loginurl = "https://signin.lexisnexis.com/lnaccess/app/signin?back=https%3A%2F%2Fadvance.lexis.com%3A443%2Fnexis-uni&aci=nu" loginurl ="advance.lexis.com" #pars=list(ID="chiuyt19",Password="Chiu27905639@",submitButton = "Sign In") pars=list(ID="chiuyt19",Password="Chiu27905639@") agent ="Mozilla/5.0" curl=getCurlHandle() curlSetOpt(cookiejar="cookies.txt",useragent= agent, followlocation = TRUE, curl=curl) html=postForm(loginurl, .params=pars, curl=curl, style="POST") html=getURL(url.full, curl=curl) doc = htmlParse(html, asText=TRUE) #Chinese unicorn firm with 256 news article in the GUI search search.term <- "UrWork" #for terms with spaces, add "%20" to replace in the search query.params<- paste0("q=", search.term) url.full <- paste0(base.url, query.params,"&collection=news&qlang=bool&context=1516831") #http://advance.lexis.com/api/search?{search-terms}&{collection}&{qlang}&(context) #eg. http://advance.lexis.com/api/search?q=burden%20of%20proof&collection=cases&qlang=bool&context=1516831 #qlang = language optional collection = content type optional response <- GET(url.full) #the API is not REST API but uses cookie body<-content(response,"text") body = htmlParse(html, asText=TRUE)
9fdf58b5c281d050dc908214c85bfa649c315673
99237ab7194403104ebced3219bb766f578a231c
/plot2.R
6f84f945a4bfeeef859b430918ab4d9f9f06ac6a
[]
no_license
guerined/ExData_Plotting1
d10ff9192e5a2c3f0498cef3ae8c45c9c9ad5b1a
31b6df4d99f1589d95acf1f99a2a787298e4242f
refs/heads/master
2021-01-18T20:35:42.340719
2015-12-11T13:52:58
2015-12-11T13:52:58
47,827,198
0
0
null
2015-12-11T13:06:31
2015-12-11T13:06:31
null
UTF-8
R
false
false
439
r
plot2.R
data <- read.table("household_power_consumption.txt", header=TRUE, sep=";", stringsAsFactors = FALSE, dec=".") extract <- data[data$Date %in% c("1/2/2007","2/2/2007"),] active_power <- as.numeric(extract$Global_active_power) date <-strptime(paste(extract$Date, extract$Time, sep=" "), "%d/%m/%Y %H:%M:%S") png("plot2.png", height=480, width=480) plot(date, active_power, type="l",xlab=" ", ylab="Global Active Power (kilowatts)") dev.off()
f2426f12b7edad0e96ea7fd1a09e0d56c3108025
334145f4753d39c1024d6e4f256d30ee50fe657e
/inst/tests/test.TSDistances.R
807dcdb7b6072cbad070882f6219ac07bf3f0a23
[]
no_license
cran/TSdist
6aaefaefd78c37fbfb07efe164cdb44c19fc2f53
d28f6f0c3aa4c5004caf33724b5c7fc064846553
refs/heads/master
2022-09-15T21:13:30.275246
2022-08-31T08:40:02
2022-08-31T08:40:02
19,747,325
5
6
null
null
null
null
UTF-8
R
false
false
559
r
test.TSDistances.R
context("TSDistances") test_that("The TSDistances function is checked", { x <- cumsum(rnorm(100)) y <- x # If x and y are given as ts objects x1 <- as.ts(x) x2 <- as.ts(y) expect_equal(TSDistances(x1, x2, "euclidean"), 0) # If x and y are given as zoo objects x1 <- as.zoo(x) x2 <- as.zoo(y) expect_equal(TSDistances(x1, x2, "euclidean"), 0) # If x and y are given as xts objects data(zoo.series1) x1 <- as.xts(zoo.series1) x2 <- as.xts(zoo.series1) expect_equal(TSDistances(x1, x2, "euclidean"), 0) })
62e744f85a4f73d6fbef300c4f38dd65f52b0022
4640be0f41a18abd7453670d944e094a36e4181d
/man/phylo_generate_uncertainty.Rd
5c7ffa657e91344ff9364be2da5179db34062786
[]
no_license
gitter-badger/datelife
534059d493b186030f0c2507ce8b35027d120dec
94d93bb4e6cecd0884afe99571bf96b291454899
refs/heads/master
2020-06-16T22:49:58.916722
2019-06-20T16:25:11
2019-06-20T16:25:11
null
0
0
null
null
null
null
UTF-8
R
false
true
2,786
rd
phylo_generate_uncertainty.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/uncertainty.R \name{phylo_generate_uncertainty} \alias{phylo_generate_uncertainty} \title{Function to generate uncertainty in branch lengths using a lognormal} \usage{ phylo_generate_uncertainty(phy, size = 100, uncertainty_method = "other", age_distribution = "uniform", age_sd = NULL, age_var = 0.1, age_scale = 0, alpha = 0.025, rescale = TRUE, verbose = FALSE) } \arguments{ \item{phy}{The input tree} \item{size}{A numeric vector indicating the number of samples to be generated.} \item{uncertainty_method}{A character vector specifying the method to generate uncertainty. mrbayes is default.} \item{age_distribution}{A character string specifying the type of calibration. Only "fixed" and "uniform" are implemented for now. \describe{ \item{fixed}{ The age given in ncalibration will be used as fixed age. } \item{lognormal}{The age given in ncalibration will be used as mean age. The standard deviation can be provided. # still need to add this option. By default, a 95 CI sd is used. } \item{uniform}{The age given in ncalibration will be used as mean age. Where min_age = 0.9 * mean age, and max_age = 1.1 * mean age. } }} \item{age_sd}{The standard deviation around the age to use for generating the uncertainty. If not a numeric value, var will be used to calculate it.} \item{age_var}{The variance to calculate age_sd and generate unvcertainty.} \item{age_scale}{How to scale sd by the depth of the node. If 0, same sd for all. If not, older nodes have more uncertainty} \item{alpha}{The significance level on uncertainty to generate. By default 0.025} \item{rescale}{Boolean. If true, observed age will be rescaled each round.} \item{verbose}{Boolean. If TRUE, it gives printed updates to the user.} } \value{ A phylo or multiPhylo object with the same topology as phy but different branch lengths } \description{ Function to generate uncertainty in branch lengths using a lognormal } \details{ If you want to change the size of sampled trees you do not need to run mrbayes again. Just use sample_trees("mrbayes_trees_file_directory", size = new_size) and you will get a multiPhylo object with a new tree sample. } \examples{ # generate uncertainty over feline species SDM chronogram # load data data(felid_sdm) # by default, generates a sample of 100 trees with var = 0.1 unc <- phylo_generate_uncertainty(felid_sdm$phy) length(unc) # ltt plot: max_age <- max(sapply(unc, ape::branching.times)) ape::ltt.plot(phy = unc[[1]], xlim = c(-max_age, 0), col = "#cce5ff50") for (i in 2:100){ ape::ltt.lines(phy = unc[[i]], col = "#cce5ff50") } ape::ltt.lines(felid_sdm$phy, col = "red") title(c("fake uncertainty", "in Felidae SDM chronogram")) }
7b595536fc52baeee764a9cea7501acbb72f61e7
7b3ac93640ea8576ce89cf7b33e7ae87907ae855
/RScripts/iv-playing.R
7a83114df743eb796543b98fa1f501ad32ba9150
[]
no_license
oleg-gunchenko/finance
8fa0b395e0556fd0d749dd1ce3e45b2e0e859230
ba3dabd233ec26e19bea2e7b808a2296411340a9
refs/heads/master
2023-06-17T15:47:23.282641
2020-03-03T21:32:41
2020-03-03T21:32:41
null
0
0
null
null
null
null
UTF-8
R
false
false
620
r
iv-playing.R
library(readxl) riData <- read_excel("D:/Work/finance/RScripts/data/RIZ8-ru.xlsx") ri <- riData[!is.na(riData$`Цена последней сделки`), ]$`Цена первой сделки` par(mfrow=c(3,1)) plot(ri, type = "line") ri <- rev(ri) size = 2 count = length(ri) - size sigmas = array(count) for (i in 1:count) { sigmas[i] = sd(ri[1:size]) size = size + 1 } plot(sigmas, type = "line") ssize = 2 scount = length(sigmas) - ssize ssigmas = array(scount) for (i in 1:scount) { ssigmas[i] = sd(sigmas[1:ssize]) ssize = ssize + 1 } plot(ssigmas, type = "line")
42ad44c8025e05f552a942ed8431f06a718dbdc9
700d8121a4e3a9fc4c31e015db643758cb843569
/man/mapGenomeBuilds.Rd
65e0885938ec7cc257cbdcd173dab7262629ec84
[]
no_license
Bioconductor/GenomeInfoDb
727c90f03c289f692999860a12077775f4d65317
9dba03f8d2a4f76732e2b12beac7c0ee3230a693
refs/heads/devel
2023-08-09T21:33:11.074781
2023-06-20T21:40:39
2023-06-20T21:40:39
102,149,975
14
15
null
2023-03-13T17:45:24
2017-09-01T20:19:20
R
UTF-8
R
false
false
2,561
rd
mapGenomeBuilds.Rd
\name{mapGenomeBuilds} \alias{mapGenomeBuilds} \alias{genomeBuilds} \alias{listOrganisms} \title{Mapping between UCSC and Ensembl Genome Builds} \description{ \code{genomeBuilds} lists the available genomes for a given species while \code{mapGenomeBuilds} maps between UCSC and Ensemble genome builds. } \usage{ genomeBuilds(organism, style = c("UCSC", "Ensembl")) mapGenomeBuilds(genome, style = c("UCSC", "Ensembl")) listOrganisms() } \arguments{ \item{organism}{A character vector of common names or organism} \item{genome}{A character vector of genomes equivalent to UCSC version or Ensembl Assemblies} \item{style}{A single value equivalent to "UCSC" or "Ensembl" specifying the output genome} } \details{ \code{genomeBuilds} lists the currently available genomes for a given list of organisms. The genomes can be shown as "UCSC" or "Ensembl" IDs determined by \code{style}. \code{organism} must be specified as a character vector and match common names (i.e "Dog", "Mouse") or organism name (i.e "Homo sapiens", "Mus musculus") . A list of available organisms can be shown using \code{listOrganisms()}. \code{mapGenomeBuilds} provides a mapping between "UCSC" builds and "Ensembl" builds. \code{genome} must be specified as a character vector and match either a "UCSC" ID or an "Ensembl" Id. \code{genomeBuilds} can be used to get a list of available build Ids for a given organism. NA's may be present in the output. This would occur when the current genome build removed a previously defined genome for an organism. In both functions, if \code{style} is not specified, "UCSC" is used as default. } \value{A data.frame of builds for a given organism or genome in the specified \code{style}. If \code{style == "UCSC"}, ucscID, ucscDate and ensemblID are given. If \code{style == "Ensembl"}, ensemblID, ensemblVersion, ensemblDate, and ucscID are given. The opposing ID is given so that it is possible to distinguish between many-to-one mappings.} \references{ UCSC genome builds \url{https://genome.ucsc.edu/FAQ/FAQreleases.html} Ensembl genome builds \url{http://useast.ensembl.org/info/website/archives/assembly.html} } \author{ Valerie Obenchain \email{Valerie.Obenchain@roswellpark.org} and Lori Shepherd \email{Lori.Shepherd@roswellpark.org}} \examples{ listOrganisms() genomeBuilds("mouse") genomeBuilds(c("Mouse", "dog", "human"), style="Ensembl") mapGenomeBuilds(c("canFam3", "GRCm38", "mm9")) mapGenomeBuilds(c("canFam3", "GRCm38", "mm9"), style="Ensembl") }
93d819e1e3eee0b51972be08aad15c318476b752
7f055060c92c6d4aba080868e34075d2bd4fbd87
/demo/country-contributions.R
b95853e9a7a4bb36f82975c27e9c8aaaeb7bc6e0
[]
no_license
mjaeugster/ISIPTA
502a56216c42d9227486b4b67d734c480f74b906
f783172117c09f72afd926039b80d87d3c40926e
refs/heads/master
2020-05-20T11:10:12.824284
2015-07-02T21:08:36
2015-07-02T21:08:36
1,785,281
2
2
null
null
null
null
UTF-8
R
false
false
1,985
r
country-contributions.R
### Number of contributions by year and country. library("ISIPTA") library("rworldmap") demo("authors-locations", package = "ISIPTA", verbose = FALSE, echo = FALSE, ask = FALSE) data("papers_authors", package = "ISIPTA") data("authors_locations", package = "ISIPTA") papers_authors_locations <- merge(papers_authors, authors_locations, all = TRUE) ## Countries per paper: papers_countries <- ddply(papers_authors_locations, .(id), function(x) { ac <- t(as.matrix(table(x$country_code))) data.frame(year = x$year[1], id = x$id[1], nauthors = nrow(x), as.data.frame(ac)) }) ## Country contributions per paper: papers_country_contributions <- cbind(papers_countries[, 1:3], papers_countries[, -(1:3)] / papers_countries[, 3]) ## Country contributions per year: t3 <- daply(papers_country_contributions, .(year), function(x) { colSums(x[, -(1:3)]) }) t3 ### Visualization by region and by year: ############################# data("countryRegions", package = "rworldmap") t3melt <- melt(t3, varnames = c("year", "country_code")) t3melt$region <- countryRegions[match(t3melt$country_code, countryRegions$ISO2), "GEO3major"] t3melt$region <- t3melt$region[, drop = TRUE] t3melt$year <- ordered(t3melt$year) t3melt <- ddply(t3melt, .(year, region), numcolwise(sum)) ggplot(t3melt, aes(year, value, group = region, colour = region)) + geom_point() + geom_line() ### Visualization of authors locations versus country contributions: # t23melt <- rbind(cbind(t2melt, what = "Unique authors"), cbind(t3melt, what = "Contributions")) ggplot(t23melt, aes(year, value, group = region, colour = region)) + geom_point() + geom_line() + facet_grid(. ~ what)
125544863e2d7d77aa9b937839d9a9ae392854cf
c1cf4de1c09cb9c16d374c177717041c5b220c90
/tests/DEPRECATED.lazy.R
9e8e59b32feef917b675b0b9a6bcc4c83f366f07
[]
no_license
nikolayvoronchikhin/future
dd3e7b6713980bda16048a29fcc8685c7ece1f3b
d2cb5f421d0c7a75a99d44c70cb536bb5f09e94f
refs/heads/master
2021-01-25T06:44:50.313780
2017-05-26T07:48:06
2017-05-26T07:48:06
null
0
0
null
null
null
null
UTF-8
R
false
false
511
r
DEPRECATED.lazy.R
source("incl/start.R") message("*** lazy() - defunct ...") res <- tryCatch({f <- lazy({ 42L })}, warning = identity) stopifnot(inherits(res, "warning")) res <- tryCatch({ plan(lazy) }, warning = identity) stopifnot(inherits(res, "warning")) res <- tryCatch({ plan(list(lazy)) }, warning = identity) stopifnot(inherits(res, "warning")) #res <- tryCatch({ # f <- LazyFuture() #}, warning = identity) #stopifnot(inherits(res, "warning")) message("*** lazy() - defunct ... DONE") source("incl/end.R")
332358d477ef4a979797ee3c721aa62ff191df17
f0cfb9e8215a2479502b5ed90790a1b52bd9884f
/R/LKPACK/EX3-10.R
b5be8daff451cfbd665c8ede9d8a4253f11b4cbc
[ "MIT" ]
permissive
yanliangs/in-all-likelihood
f2f580445a48f675d548ee38fc565b1b804ed25b
6638bec8bb4dde7271adb5941d1c66e7fbe12526
refs/heads/master
2023-07-15T09:31:16.294980
2020-04-17T01:58:35
2020-04-17T01:58:35
null
0
0
null
null
null
null
UTF-8
R
false
false
1,259
r
EX3-10.R
par(mfrow=c(2,2)) x <- c(0.88,1.07,1.27,1.54,1.91,2.27,3.84,4.5,4.64,9.41) n<- length(x) fun0<- function(mu,sigma){ a<- -n/2*log(sigma^2) - (sum(x^2) - 2*mu*sum(x) + n*mu^2)/(2*sigma^2) -a } ll<-NULL np<-20 mu<- seq(mean(x)-3,mean(x)+3,len=np) sx<- sqrt(var(x)) sigma<- seq(sx/2.5,sx*2,len=np) ll2<- outer(mu,sigma,'fun0') like2<- exp(min(ll2)-ll2) contour(mu,sigma^2,like2,xlab=expression(mu), ylab=expression(sigma^2), level=c(.1,.3,.5,.7,.9)) title(expression('(a) Likelihood contour')) # for (i in 1:np){ # li<- ms(~fun0(mu[i],phi),start=list(phi=2))$value # ll<- c(ll,li) # } # like<- exp(min(ll)-ll) # profile likelihood # like<- apply(like2,1,max) np<-100 mu<- seq(mean(x)-3,mean(x)+3,len=np) for (i in 1:np){ shat2<- sum((x-mu[i])^2)/n lli <- -n/2 *log(shat2) ll<- c(ll,lli) } like<- exp(ll-max(ll)) plot(mu,like,xlab=expression(mu),ylab='Likelihood',type='n') lines(mu,like,lwd=.3) abline(h=.15) title(expression(paste('(b) Likelihood of ',mu))) ll<- fun0(mu,sigma=1) like<- exp(min(ll)-ll) lines(mu,like,lty='dotted',lwd=1.52) se <- sqrt(var(x)*(n-1)/n)/sqrt(n) xbar<- mean(x) elike <- dnorm(xbar,mean=mu,sd=se) elike<- elike/max(elike) lines(mu,elike,lty=2)
c790de0b7281f9601cebe7377f189b8d05e52cec
f0ba683353c4e3faf242e56c84defda4972686e1
/R/cv_kfold_split_file.R
ad60162960dc93ce5678464c5845ac4fc97ac292
[ "MIT" ]
permissive
epongpipat/eepR
bf567c666eef0417b0dece4088ec95697f02cdba
970c4699db1e005cabd282e903706239033c7b02
refs/heads/main
2023-04-01T22:44:23.247733
2023-03-28T17:42:07
2023-03-28T17:42:07
205,262,495
1
0
null
null
null
null
UTF-8
R
false
false
1,640
r
cv_kfold_split_file.R
#' cv_kfold_split_file #' #' @param x_path #' @param y_path #' @param k_fold #' @param out_dir #' #' @return #' @export #' #' @examples cv_kfold_split_file <- function(x_path, y_path, k_fold, out_dir) { stop_if_dne(x_path) stop_if_dne(y_path) n_pad <- 3 k_fold_pad <- str_pad(k_fold, n_pad, "left", 0) x <- read.csv(x_path) y <- read.csv(y_path) if (dim(x)[1] != dim(y)[1]) { stop(glue("number of rows in x {dim(x)[1]} and y {dim(y)[1]} do not match.")) } mkdir_if_dne(out_dir) out_file <- glue("{out_dir}/x.csv") stop_if_e(out_file) file.copy(x_path, out_file) out_file <- glue("{out_dir}/y.csv") stop_if_e(out_file) file.copy(y_path, out_file) for (i in 1:k_fold) { tryCatch2({ i_pad <- str_pad(i, n_pad, "left", 0) cv_out_dir <- glue("{out_dir}/cv-kfold-{k_fold_pad}-{i_pad}") mkdir_if_dne(cv_out_dir) n_fold <- ceiling(dim(x)[1]/k_fold) cv_idx <- rep(1:k_fold, each = n_fold, length.out = dim(x)[1]) x_train <- x[cv_idx != i, ] x_test <- x[cv_idx == i, ] y_train <- y[cv_idx != i, ] y_test <- y[cv_idx == i, ] out_path <- glue("{cv_out_dir}/x_train.csv") stop_if_e(out_path) write.csv(x_train, out_path, row.names = F) out_path <- glue("{cv_out_dir}/x_test.csv") stop_if_e(out_path) write.csv(x_test, out_path, row.names = F) out_path <- glue("{cv_out_dir}/y_train.csv") stop_if_e(out_path) write.csv(y_train, out_path, row.names = F) out_path <- glue("{cv_out_dir}/y_test.csv") stop_if_e(out_path) write.csv(y_test, out_path, row.names = F) }) } }
a89fa1e1fb96be08b1163b87a8ba1fc1c166350e
151545238b797b070372d34b3aca05fd97083d38
/Random_Playlist_Shuffle.R
26c23995e9573b4cdc86077b01308aaa917375f8
[]
no_license
leventkayin/Random_Playlist_Shuffle
bfb35aa47550a194a9d67aee6ff1875495317dea
16c4a5790d391969a2210fb294f212f9f17d80d2
refs/heads/master
2020-03-23T23:16:09.183492
2018-07-25T00:30:19
2018-07-25T00:30:19
142,225,668
0
0
null
null
null
null
UTF-8
R
false
false
1,457
r
Random_Playlist_Shuffle.R
### Simple Fisher - Yates algorithm to Shuffle Songs and Why its not ideal # We create a random playlist of some number songs we also randomly assign them genres from A to D number_songs = 20 songs = seq(1,number_songs) genres = round(runif(number_songs,min = 1,max = 4)) genres = replace(genres, genres == 1,"A") genres = replace(genres, genres == 2,"B") genres = replace(genres, genres == 3,"C") genres = replace(genres, genres == 4,"D") genres playlist = cbind.data.frame(songs,genres) playlist_length = length(playlist[,1]) shuffled_playlist = playlist for (i in seq(1,playlist_length-1)) { j = sample(x = seq(1,i), size = 1) shuffled_playlist[c(i,j),1] = shuffled_playlist[c(j,i),1] } # Just by looking at individual songs it looks like the shuffle worked library(ggplot2) p1 = qplot(y = shuffled_playlist[,1], x = seq(1,number_songs),geom = "point", main = c("Shuffled Song Positions"),xlab = "Position",ylab = "Song Number") p1 # But if we add the genres to the mix we can see a problem appearing, songs from the same genre keep repeating # You can run the code a several times and will see that the same problem keeps reappearing p2 = qplot(x = shuffled_playlist[,1], y = seq.int(1,1,length.out = number_songs), geom = "point",color = shuffled_playlist[,2], main = "Shuffled Song Genres",xlab = "Position",ylab = "") + geom_point(size = 5) + guides(color = guide_legend(title = "Genres")) p2
7a8bbb4087b8dbba3d7fd73c64e4782eff418fde
a9a9af4f010a883720f70391d2af66f437cb15c3
/man/create_database_structure.Rd
5664afdf0f86045d8c5ab37f04d16f8d291887f8
[]
no_license
kalden/spartanDB
ad4162c78ef54170c21c08a8a7a822fafc457636
bc698715cdce55f593e806ac0c537c3f2d59ac7a
refs/heads/master
2020-03-26T23:32:14.724243
2019-02-20T11:05:17
2019-02-20T11:05:17
145,549,860
0
0
null
null
null
null
UTF-8
R
false
true
712
rd
create_database_structure.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/database_table_setup.R \name{create_database_structure} \alias{create_database_structure} \title{Creates all required databases for storing experiments using a simulator} \usage{ create_database_structure(dblink, parameters, measures) } \arguments{ \item{dblink}{A link to the database in which this table is being created} \item{parameters}{The parameters of the simulation that are being analysed} \item{measures}{The measures of the simulation that are being assessed} } \description{ Takes a connection to a mysql database and creates all the tables required for storing results of all experiments conducted using a simulator }
3fd9fc0c5e618308f1173a80625067077c9389d9
a40d7e8eb79b6f532ad833595f049cba3701f323
/Lab 7 MvLA LDA&QDA.R
fdac06daffddc45610d06c8587833f4a22570d84
[]
no_license
haskinsm/R-projects
4837fd598256776a0c1a9b6b77b6e9da1263193a
19a1668cc0ad7a529ce32b65002a25bb83651099
refs/heads/master
2023-08-14T14:38:26.502301
2021-10-20T17:23:54
2021-10-20T17:23:54
299,654,042
1
0
null
null
null
null
UTF-8
R
false
false
8,144
r
Lab 7 MvLA LDA&QDA.R
library(MASS) salmon = read.table("https://www.scss.tcd.ie/~arwhite/Teaching/STU33011/salmon.txt", header = TRUE) salmon plot(salmon[,-1], col = as.factor(salmon[,1])) library(ellipse) plot(salmon[,c(2,3)], col = as.factor(salmon[, 1]), xlim=c(50,190), ylim=c(290,530)) lines(ellipse(cov(salmon[c(1:50), c(2, 3)]), centre = colMeans(salmon[c(1:50), c(2, 3)]),level = c(0.5))) lines(ellipse(cov(salmon[c(51:100), c(2, 3)]), centre = colMeans(salmon[c(51:100), c(2, 3)]), level = 0.5), col = 2) ## Linear Discriminant Analysis (LDA) ##Before we use LDA, we need to split the data into training, and test sets. ##(Why don’t we need a validation set?) For this example we will try an 80:20 split. strain <- salmon[c(1:40, 51:90), ] stest <- salmon[c(41:50, 91:100),] ## We can then train our classifier: lsol <- lda(strain[, c(2, 3)], grouping = strain[,1]) lsol$prior lsol$means ## lsol$prior provides the prior probability of group membership that is used in the analysis, ## which by default is taken to be the class proportions in the training data. The second section ## provides the estimated group means for each of the two groups. You should be able to verify both ## of these calculations. ## Note that the pooled covariance matrix used to perform LDA is not provided. You can find this ## manually by calculating the following: ## Σ= (N1−1)Σ1+(N2−1)Σ2 / N1+N2−2. ## In the above Σ is the estimated common covariance matrix, Σi is the estimated covariance matrix ## for specific group i, whilst Ni is the number of data points in group i. ## To estimate the covariance matrices for both subsets of salmon data, enter the following: alaska_salmon <- strain[strain == "Alaska", c(2,3)] canada_salmon <- strain[strain == "Canada", c(2,3)] n_alaska <- length(alaska_salmon) n_canada <- length(canada_salmon) single_cov_num <- ((n_alaska - 1) * cov (alaska_salmon) + (n_canada - 1) * cov(canada_salmon) ) single_cov <- single_cov_num / ( length(strain[, 1]) - 2) single_cov ## Remember from lectures that the classification rule for LDA is: ## log(P(k|x)/P(l|x))=log(πk/πl)+log(f(x|k)/f(x|l)). ## The multivariate normal assumption with common covariance then leads to the following: ## log(f(x|k)/f(x|l))=xTΣ^−1(μk−μl) −1/2(μTkΣ−1μk−μTlΣ−1μl) ## ⇒log(f(x|k)f(x|l))={x−12(μk+μl)}TΣ−1(μk−μl). ##Not formatted correctly here ## The term 1/2(μk+μl) gives the average of the group means, and so x−1/2(μk+μl) gives the ## difference of the observation to this value. Assuming the prior probabilities are equal, ## (x−1/2(μk+μl))TΣ^−1(μk−μl) determines the classification by whether it is positive or negative. ## (In this case, a positive value indicates membership to Group k). ## As well as providing information about prior probalilities and group means, calling lsol ## directly provides information regarding the coefficients of linear discriminants ## (use lsol$scaling to call this directly): lsol lsol$scaling ## These are a (scaled) version of Σ−1(μk−μl), and hence can be used for classifying a new observation. ## Note that it is the second class, here Canada, that is associated with group k in the output. ?lda ##The scaling value of the lda object gives the loadings (also called the slopes, coefficients, or weights) ##of each variable on each discriminant function. predict(lsol, c(120, 380)) ## Determine the classification for an observation with a Freshwater recording of 120 and a Marine recording of 380 predict(lsol, stest[, c(2, 3)]) ##To automatically predict the test data set enter: predict(lsol, stest[, c(2, 3)])$class ##Gets how the points were classified using knn stest[, c(1)] ##Gets the actual classifications class_agree = table(stest[, c(1)], predict(lsol, stest[, c(2, 3)])$class) sum_agree <- sum(diag(class_agree)) sum_agree Perc_misclass = (nrow(stest) - sum_agree) / nrow(stest) ##0% misclassification Perc_misclass ## Cross-Validation ## Rather than splitting the data into training and test sets (or training, test, ## and validation sets when different models are being considered), an alternative technique ## for measuring the performance of the model is to perform cross-validation. ## For the lda function this is achieved by incorporating the argument CV=TRUE: lsol_cv <- lda(salmon[,c(2,3)], grouping = salmon[, 1], CV = TRUE) lsol_cv ## In order to visualise the performance of LDA under cross-validation we can produce a plot ## of the following form: plot(salmon[, c(2, 3)], col = as.factor(salmon[, 1]), pch = as.numeric(lsol_cv$class)) ## The above command plots the two numeric variables of the salmon data with colouring being ## determined by true classification and symbols being determined by the resulting classification ## of `leave-one-out’ LDA. How many misclassified points do you notice? 6 I think ## Quadratic Discriminant Analysis ## The function qda within the package MASS performs quadratic discriminant analysis. ## Remember the difference between QDA and LDA is that the former permits each group ## distribution to have its own covariance matrix, whilst the latter assumes a common ## covariance matrix for all group distributions. The usage of qda the same as lda: qsol <- qda(strain[, c(2,3)], grouping = strain[, 1]) qsol predict(qsol, stest[, c(2, 3)]) ## Again you will notice in an 80:20 training:testing split we have achieved 100% correct ## classification. The output returned from by qsol provides details of the prior probability ## of group membership (again determined by the proportion of data points classified in that ## group by default), and the mean vectors for each group. To find the covariances for the two ## groups enter the following: cov (alaska_salmon) cov (canada_salmon) ## assess the performance of QDA for the salmon data set under cross-validation and produce a plot of your results. qsolCV <- qda(salmon[, c(2,3)], grouping = salmon[, 1], CV = TRUE) ##CV = True => Cross Validation qsolCV salmon[, c(2, 3)] class_agree = table(salmon[, c(1)], qsolCV$class) ##Seems like you dont need to use predict function with CV sum_agree <- sum(diag(class_agree)) sum_agree Perc_misclass = (nrow(salmon) - sum_agree) / nrow(salmon) ##0% misclassification Perc_misclass ## 8% misclass plot(salmon[, c(2, 3)], col = as.factor(salmon[, 1]), pch = as.numeric(qsolCV$class)) ##Compare the performance of LDA and QDA under a 50:25:25 training:validation:testing split of ## the salmon data set. This means you should use 50% of the data to train both models, 25% of ## the data to assess which model appears to be the better classifier, and a further 25% of the ## data to more accurately assess the true classification rate of the better model. Sal_train = salmon[c(1:25, 51:75), ] ## 25 + 25 = 50 Sal_test = salmon[c(26:38, 76:87), ] ## Cant split remaining 50 evenly-> test(13Alaskan, 12Canadian) Sal_acc = salmon[c(39:50, 88:100), ] ## acc(12Alaskan, 13Canadian) lda_sol = lda(Sal_train[, c(2, 3)], grouping = Sal_train[,1]) predict(lda_sol, Sal_test[, c(2, 3)])$class class_agree = table(Sal_test[, c(1)], predict(lda_sol, Sal_test[, c(2, 3)])$class) sum_agree <- sum(diag(class_agree)) sum_agree Perc_misclass = (nrow(Sal_test) - sum_agree) / nrow(Sal_test) ##0% misclassification Perc_misclass ##0% qda_sol = qda(Sal_train[, c(2,3)], grouping = Sal_train[,1]) predict(qda_sol, Sal_test[, c(2,3)])$class class_agree = table(Sal_test[, c(1)], predict(qda_sol, Sal_test[, c(2, 3)])$class) sum_agree <- sum(diag(class_agree)) sum_agree Perc_misclass = (nrow(Sal_test) - sum_agree) / nrow(Sal_test) ##0% misclassification Perc_misclass ##4% ##Im being lazy here copy and pasting so be careful to run right bits first ##So lda appears to be better as it misclassifies 0% of the points. predict(lda_sol, Sal_acc[, c(2, 3)])$class class_agree = table(Sal_acc[, c(1)], predict(lda_sol, Sal_acc[, c(2, 3)])$class) sum_agree <- sum(diag(class_agree)) sum_agree Perc_misclass = (nrow(Sal_acc) - sum_agree) / nrow(Sal_acc) ##0% misclassification Perc_misclass ##0%
df1bda4b7b37b617852eb048dc7c66c977c21bb8
34f5bbe3b9612d75982babb1287c813e90f50abe
/cachematrix.R
2280a5b52aad1ad1ff7d1540353bd8aab5dd6e05
[]
no_license
llozovaya/ProgrammingAssignment2
fb1f735ecd2bd6d5e138375fbae14d0f26191198
8b6eae797d85d1800d17d59edb8d36f6027bcb85
refs/heads/master
2021-01-12T22:19:11.864392
2015-01-25T11:55:33
2015-01-25T11:55:33
29,790,099
0
0
null
2015-01-24T20:14:54
2015-01-24T20:14:54
null
UTF-8
R
false
false
1,188
r
cachematrix.R
## ## ## A function creating a special object CacheMatrix ## consisting of four functions which are: ## get - get the value of the object, which is square invertible matrix ## set set the value to the object ## getinverse - get the inverse matrix if it was calculated, otherwise NULL ## setinverse - set the inverse matrix makeCacheMatrix <- function(x = matrix()) { inv <- NULL set <- function(m) { x <<- m inv <<- NULL } get <- function() x setinverse <- function(inverse) { inv <<- inverse } getinverse <- function() inv list(set = set, get = get, setinverse = setinverse, getinverse = getinverse) } ## A function calculating the inverse of the object CacheMatrix. ## It checks if the inverse value was calculated. If it was it returns this value. ## Otherwise it calculates the inverse matrix of the argument data, sets it ## the inverse value cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' inv <- x$getinverse() if (!is.null(inv)) { message("Getting cached data") return (inv) } inv <- solve(x$get(), ...) x$setinverse(inv) inv }
b0e31fb07871c064d2fe2b1505a1986b11aa6040
c9240ed6ccaf9fa8532aff8a2a2683c2a342f047
/Baseline Code/3.movingAverage.R
eef19b1c277850e20dd6698e568d3443a827ab31
[]
no_license
greycloak85/CO2Reader
8907207657a2b950edb994ff040cb6eb3efd2f67
d51beb5afd0ff45bca0747c23fe72c58069ed015
refs/heads/master
2021-01-19T11:45:14.261870
2015-11-12T02:20:39
2015-11-12T02:20:39
40,512,285
0
0
null
null
null
null
UTF-8
R
false
false
5,391
r
3.movingAverage.R
require(reshape2) require(ggplot2) require(plyr) require(zoo) require(caTools) # Plotting Parameters plotsize = 1200 # pixels golden = 1.618 # ratio res = 150 # Check machine and set path appropriately if(Sys.info()["nodename"] == 'Turing.local'){ setwd('/Users/rhy/Dropbox/Work/Meemir/Respirion/Analysis/Rich Code') } else if (Sys.info()["nodename"] == 'Richs-MacBook-Air.local'){ setwd('/Users/Rich_Yaxley/Dropbox (Personal)/Work/Meemir/Respirion/Analysis/Rich Code') } df <- read.csv(file='co2.csv', header=T) '''2015-03-26 Meemir meeting We need to smooth the data to numerically differentiate. Maybe average a small number of neighboring points and walk up. Or, Jim suggested Smoothing with wavelets. Also, need to smooth the unknown dataset Try taking several 1-min chunks rather than 0-3000 epoch Calculate the mean trough to peak values. Drop the peak to trough values. Predicting the unknown dataset Rolling window of 3 to 4 breaths ''' # Smooth data test x <- df$red[200000:200530] plot(x, col='black', cex=1.4) lines(runmean(x,5), col='red', lwd = 5) lines(runquantile(x, 9, probs=0.5), col='blue', lwd=3) # runmed = Running medians # lines(runmed(x,11), col='green', lwd = 3) # lines(runmed(x,9), col='blue') # lines(smooth(x, kind='3RS3R', twiceit=T), col='purple') # lines(smooth.spline(x), col='green') # Smooth data with running mean df$green.s <- NA df$blue.s <- NA df$red.s <- NA df$clear.s <- NA for(run in unique(df$run)){ df[which(df$run==run), ]$green.s <- runmean(df[which(df$run==run), ]$green, 5) df[which(df$run==run), ]$red.s <- runmean(df[which(df$run==run), ]$red, 5) df[which(df$run==run), ]$blue.s <- runmean(df[which(df$run==run), ]$blue, 5) df[which(df$run==run), ]$clear.s <- runmean(df[which(df$run==run), ]$clear, 5) } # # Test moving average # ts <- zoo(r) # tsmean <- rollapply(ts[ ,c('green','blue','red','clear')], width=timepoints, # by=1, fill = NA, align = 'right', by.column = TRUE, # FUN=function(y){ as.numeric(y)[timepoints] - mean(as.numeric(y))} ) # # # Test moving average on subset of data from one run # timepoints <- 240 # 240 * 5 = 1200 timepoints (1200/60) = 20 s # testrun <- 3 # r <- subset(df, run==testrun) # r <- subset(r, runtime > 0 & runtime < 1000) # ts <- zoo(r) # tsmean <- rollapply(ts[ ,c('green','blue','red','clear')], width=timepoints, # by=1, fill = NA, align = 'right', by.column = TRUE, # FUN=function(y){ as.numeric(y)[timepoints] - mean(as.numeric(y))} ) # z <- as.data.frame(tsmean) # r$green.avg <- z$green # r$blue.avg <- z$blue # r$red.avg <- z$red # r$clear.avg <- z$clear # # # Melt all color variables into one "channel" column # r.m <- melt(r, id.vars=c('run','runtime','conc','resp'), # measure.vars = c('green','blue','red','clear','green.avg','blue.avg', # 'red.avg','clear.avg'), # variable.name = 'channel', value.name='intensity') # # fname <- paste("Plots/Line-Intensity-x-Color-Moving-Window-Run", testrun, ".png", sep='') # ggplot(data=r.m, aes(x=runtime, y=intensity, group=channel, color=channel )) + # geom_line(size=1) + facet_grid(channel~.,scales = "free_y") # dev.copy(png, fname, height=plotsize/golden, width=plotsize, res=res) # dev.off() # # # Melt the green and green.average variablesonly # r.m <- melt(r, id.vars=c('run','runtime','conc','resp'), # measure.vars = c('green','green.avg'), # variable.name = 'channel', value.name='intensity') # # fname <- paste("Plots/Line-Intensity-x-Color-Moving-Window-Run", testrun, "-green-only.png", sep='') # r.m <- subset(r.m, runtime > 20 & runtime < 40) # ggplot(data=r.m, aes(x=runtime, y=intensity, group=channel, color=channel )) + # geom_line(size=1) + facet_grid(channel~.,scales = "free_y") # dev.copy(png, fname, height=plotsize/golden, width=plotsize, res=res) # dev.off() # Generate a moving window average for every run timepoints <- 1200 # 240 * 5 = 1200 timepoints (1200/60 samples/sec) = 20 s df.m <- data.frame() #NULL system.time( for(i in unique(df$run)){ print(i) dfsub <- subset(df, run==i) dfsub <- subset(dfsub, runtime >= 0 & runtime < 3000) # subset of samples ts <- zoo(dfsub) #I put the na.rm=TRUE in the mean() below to cleanly handle NAs -- Jim # tsmean <- rollapply(ts[ ,c('green.s','blue.s','red.s','clear.s')], width=timepoints, # by=1, align = 'right', by.column = TRUE, fill = NA, # FUN=function(x){ as.numeric(x)[timepoints] - mean(as.numeric(x),na.rm=TRUE)}) tsmean <- rollapply(ts[ ,c('green.s','blue.s','red.s','clear.s')], width=timepoints, by=1, align = 'center', by.column = TRUE, fill = NA, FUN=function(x){ as.numeric(x)[timepoints] - median(as.numeric(x),na.rm=TRUE)}) z <- as.data.frame(tsmean) dfsub$green.avg <- z$green dfsub$blue.avg <- z$blue dfsub$red.avg <- z$red dfsub$clear.avg <- z$clear df.m <- rbind(df.m, dfsub) # Save each moving average to a var assign(paste('m.r', i, sep=''), dfsub) } ) write.csv(df.m, file="co2-moving-window-average-0-3000s-median.csv", row.names=F)
3c4706fd6bb54863e5c39a74c84badec63c7d6cd
90613c1a502a34ecbe3901237c8720d98cfa7e8e
/R/plot.select.parfm.R
372f2b2b66b91012a7249a5fe526d4b382233a57
[]
no_license
cran/parfm
48345c471ca26c6000d72dbe10b8446a63b5ca01
da8a1afaed7160d0b3ed3b254be27c015e52ba9b
refs/heads/master
2023-01-24T09:09:45.168377
2023-01-17T21:40:02
2023-01-17T21:40:02
17,698,226
0
3
null
null
null
null
UTF-8
R
false
false
3,466
r
plot.select.parfm.R
################################################################################ # Plot of objects of class 'select.parfm' # ################################################################################ # # # # # # # Date: December 22, 2011 # # Last modification on: December 2, 2016 # ################################################################################ plot.select.parfm <- function(x, mar=c(2.5, 2, 1.5, .5), ty = 'b', ...){ par(mfrow=c(1, 3)) ### --- AIC --- ### par(mar=mar) plot(0,0, ty="n", xlab="", ylab="", main="AIC", xaxt="n", ylim=c(min(x$AIC, na.rm=TRUE) * .9975, max(x$AIC, na.rm=TRUE) * 1.0025), xlim=c(.5, ncol(x$AIC) + .5), cex.lab=1.5) abline(v=1:ncol(x$AIC), col="grey") mtext(c(none="No", gamma="Ga", ingau="IG", possta="PS", lognor="LN")[colnames(x$AIC)], side=1, at=1:ncol(x$AIC), padj=1) for (i in 1:nrow(x$AIC)) points( (1:ncol(x$AIC)), x$AIC[i, ], pch = 19 + i, cex = 1.5, ty = ty, bg = i) ### --- names --- ### par(mar=mar) plot(0:2, 0:2, xaxt = "n", yaxt = "n", bty = "n", ann = FALSE, ty = "n") legend("top", #c(.3, 1.7), c(1, 1.75), title = 'Baseline', c(exponential = "exponential", weibull = "Weibull", inweibull = "inverse Weibull", gompertz = "Gompertz", loglogistic = "loglogistic", lognormal = "logNormal", logskewnormal = "logSkewNormal")[rownames(x$AIC)], pch = {if(ty == 'l') NULL else 19 + 1:nrow(x$AIC)}, pt.bg = 1:nrow(x$AIC), bg = "white", bty = "n", lty = ifelse(ty == 'p', 0, 1), ncol = 1, cex = 1.5, xjust = .5) legend("bottom", #c(0, 2), c(.25, 1), yjust=1, title = 'Frailty distribution', mapply(paste, c(none="No", gamma="Ga", ingau="IG", possta="PS", lognor="LN")[colnames(x$AIC)], c(none="no frailty", gamma="gamma", ingau="inverse Gaussian", possta="positive stable", lognor="lognormal")[colnames(x$AIC)], sep=" = "), bg="white", bty="n", ncol=1, cex=1.5, xjust=.5) ### --- end names --- ### ### --- BIC --- ### par(mar=mar) plot(0,0, ty="n", xlab="", ylab="", main="BIC", xaxt="n", ylim=c(min(x$BIC, na.rm=TRUE) * .9975, max(x$BIC, na.rm=TRUE) * 1.0025), xlim=c(.5, ncol(x$BIC) + .5), cex.lab=1.5) abline(v=1:ncol(x$BIC), col="grey") mtext(c(none="No", gamma="Ga", ingau="IG", possta="PS", lognor="LN")[colnames(x$BIC)], side=1, at=1:ncol(x$BIC), padj=1) for (i in 1:nrow(x$BIC)) points( (1:ncol(x$BIC)), x$BIC[i, ], pch = 19 + i, cex = 1.5, ty = ty, bg = i) }
0e9d741306f1b3d48d521792df59c7baabf3bccf
1c9f01369c0a3b63ab38b5dada9e20186b3a307b
/reference_datasets/2020_Anderson/code/02-extract_filtered_signatures.R
c3a0b84a05aee0c3900154092a9a438480d2b905
[]
no_license
fungenomics/G34-gliomas
751fba1ceec1198a503485b265d2cf67601d0822
a399f4e19045f81000f19b8e15b0b9b3d3639e3b
refs/heads/master
2023-04-06T15:57:33.556507
2022-09-16T15:59:53
2022-09-16T15:59:53
266,608,930
0
0
null
null
null
null
UTF-8
R
false
false
3,958
r
02-extract_filtered_signatures.R
# Selin Jessa # 2020-07-07 # # Here I will get 100-gene signatures for the clusters, filtered # based on gene stats library(tidyr) library(dplyr) library(glue) library(readr) library(magrittr) library(ggplot2) library(purrr) out <- "../processed_data/02" # Load gene annotation anno <- readr::read_tsv("../../../sjessa/from_hydra/single_cell/2019-02_revision1/input/gene_annotation_with_homologous_mice_genes.txt") # Get markers from paper supplementary, and add cell type labels markers <- readxl::read_xlsx("../data/Table_S1_cluster_markers.xlsx", sheet = 1) labels <- readxl::read_xlsx("../data/Table_S2_cluster_labels_and_counts.xlsx") %>% dplyr::select(Cluster_num = Cluster, Label = `Cell-type Annotation`) %>% dplyr::mutate(Cluster = paste0(Cluster_num, "-", Label)) %>% select(-Label) # Add the full cell type name markers <- markers %>% left_join(labels, by = c("cluster" = "Cluster_num")) %>% dplyr::rename(mmusculus_external_gene_id = gene) # Annotate the genes with mouse/human homologs and ENSEMBL IDs markers_anno <- markers %>% left_join(select(anno, hsapiens_external_gene_id, mmusculus_external_gene_id, hsapiens_ensembl_gene_id, mmusculus_ensembl_gene_id = mmusculus_homolog_ensembl_gene), by = c("mmusculus_external_gene_id")) %>% distinct(Cluster, mmusculus_external_gene_id, .keep_all = TRUE) # Save the table of annotated markers write_tsv(markers_anno, glue("{out}-markers.annotated.tsv")) # Filter to positive LFC markers; rank by adj pval, and take the top 100 # as we did for the Nat Genet 2019 paper filterMarkers <- function(markers, gene_col, sp = "mm", n_top = 100) { gene_col <- rlang::enquo(gene_col) markers %>% { if (sp == "mm") dplyr::filter(., !grepl("Rps|Rpl|Mrps|Mrpl", !!gene_col)) else dplyr::filter(., !grepl("RPS|RPL|MRPS|MRPL", !!gene_col)) } %>% group_by(Cluster) %>% dplyr::filter(avg_logFC > 0) %>% arrange(p_val_adj) %>% dplyr::slice(1:n_top) %>% ungroup() } # Do the filtering sigs <- markers_anno %>% filterMarkers(mmusculus_external_gene_id, sp = "mm") # Check # markers per cluster sort(table(sigs$Cluster)) # Filter out signatures with < 80 genes and clusters with < 100 cells (enough_genes <- sigs %>% count(Cluster) %>% filter(n >= 70) %>% pull(Cluster)) sigs2 <- sigs %>% filter(Cluster %in% enough_genes) # Sanity check sort(table(sigs2$Cluster)) sigs2_qc <- sigs2 %>% group_by(Cluster) %>% summarise(median_logFC = median(avg_logFC), n_gene_FC_above_1.5 = sum(avg_logFC > log2(1.5))) %>% arrange(median_logFC) %T>% readr::write_tsv(glue("{out}-sigs_qc.tsv")) sigs2_qc %>% mutate(Cluster = factor(Cluster, levels = unique(.$Cluster))) %>% gather(key = "stat", value = "value", 2:length(.)) %>% ggplot(aes(x = Cluster, y = value)) + geom_bar(aes(fill = Cluster), stat = "identity", width = 0.8) + facet_wrap(~ stat, ncol = 2, scales = "free_x") + coord_flip() + theme_bw() + theme(legend.position = "none") # Get signatures where the median LFC is at least 0.75, also filters out a couple # clusters where the # genes w/ FC > 1.5 is low keep <- sigs2_qc %>% filter(median_logFC > 0.75) %>% pull(Cluster) sigs3 <- sigs2 %>% filter(Cluster %in% keep) # Extract the signatures, filter NA values signatures <- list("hg_sym" = split(sigs3, f = sigs3$Cluster) %>% map(~ pull(.x, hsapiens_external_gene_id) %>% .[!is.na(.)]), "mm_sym" = split(sigs3, f = sigs3$Cluster) %>% map(~ pull(.x, mmusculus_external_gene_id) %>% .[!is.na(.)]), "hg_ens" = split(sigs3, f = sigs3$Cluster) %>% map(~ pull(.x, hsapiens_ensembl_gene_id) %>% .[!is.na(.)]), "mm_ens" = split(sigs3, f = sigs3$Cluster) %>% map(~ pull(.x, mmusculus_ensembl_gene_id) %>% .[!is.na(.)])) saveRDS(signatures, file = glue("{out}-cluster_gene_signatures.Rds"))
55eb3447c9641ea53034f9a88bbe0e3933a9623b
5d7740f555e642a7679cc91ffa31193993fd911b
/R/wwratio.R
7c56ac4c8cd6439ab8bbfb4f0aa1c8f24c2f9a1f
[]
no_license
cran/WWR
c75c0ea6b965f15502c5a616525b3de5a87c55fe
827c382cd8e4834d87dcd236619e883a81de74c4
refs/heads/master
2021-01-22T05:47:06.752627
2017-10-25T02:40:18
2017-10-25T02:40:18
81,703,172
0
0
null
null
null
null
UTF-8
R
false
false
2,121
r
wwratio.R
wwratio<-function(y1,y2,d1,d2,z,wty1=1,wty2=1){ d1<-ifelse(d1==0 | d1==1, d1,NA) if (sum(is.na(d1))>0) stop("The event indicator 'd1' only takes values 0 and 1") d2<-ifelse(d2==0 | d2==1, d2,NA) if (sum(is.na(d2))>0) stop("The event indicator 'd2' only takes values 0 and 1") z<-ifelse(z==0 | z==1, z,NA) if (sum(is.na(z))>0) stop("The group indicator 'z' only takes values 0 and 1") if(sum(is.na(y1))>0|sum(is.na(y2))>0|sum(is.na(d1))>0|sum(is.na(d2))>0|sum(is.na(z))>0) stop("Please check missing data.") maxlen<-max(length(y1),length(y2),length(d1),length(d2),length(z)) minlen<-min(length(y1),length(y2),length(d1),length(d2),length(z)) if(maxlen>minlen) stop("Please check the lengths of the data.") n1<-sum(z==1) n0<-sum(z==0) if (n1==0|n0==0) stop("Neither group can be emepty") n<-length(y1) w2<-l2<-w1<-l1<-0.0 ay1<-rank(y1,ties.method="min") ay2<-rank(y2,ties.method="min") da<-cbind(ay1,ay2,d1,d2,z) db<-da[order(ay2,ay1,d2,d1,z),] stat<-vstat<-rep(1,3) abc1<-.Fortran("wwrnullb",as.integer(n),as.integer(db[,1]),as.integer(db[,2]),as.integer(db[,3]),as.integer(db[,4]),as.integer(db[,5]), as.integer(wty1),as.integer(wty2),stat=as.double(stat),vstat=as.double(vstat), w2=as.double(w2),l2=as.double(l2),w1=as.double(w1),l1=as.double(l1)) wd<-abc1$stat[1];wr<-abc1$stat[2];wp<-abc1$stat[3] vd<-abc1$vstat[1];vr<-abc1$vstat[2];vp<-abc1$vstat[3] td<-n^(-3/2)*wd/sqrt(vd);pd<-2*(1-pnorm(abs(td))) tr<-sqrt(n)*log(wr)/sqrt(vr);pr<-2*(1-pnorm(abs(tr))) tp<-sqrt(n)*log(wp)/sqrt(vp);pp<-2*(1-pnorm(abs(tp))) w2<-abc1$w2;l2<-abc1$l2;w1<-abc1$w1;l1<-abc1$l1 cwindex<-c(w2,w1)/(w2+w1+l2+l1) clindex<-c(l2,l1)/(w2+w1+l2+l1) me<-list(n1=n1,n0=n0,n=n,wty1=wty1,wty2=wty2,totalw=(w2+w1),totall=(l2+l1), tw=c(w2,w1),tl=c(l2,l1),xp=c(w2,w1)/c(l2,l1), cwindex=cwindex,clindex=clindex, wr=wr,vr=vr,tr=tr,pr=pr,wd=wd,vd=vd,td=td,pd=pd,wp=wp,vp=vp,tp=tp,pp=pp) class(me)<-append(class(me),"WWR") return(me) }
82a8bc633609c92e9b729f591dfdbedef1f19a13
1f2927efec55a43423d1b2ebdd5ddc18a0a0a3f0
/R/readSprint.R
e4be0d2e156a8fd88afe34fd1f7c72dca62ca086
[]
no_license
spkal/SprintData
f8b9a2d0444ca59eef07d2a27ff1c7fde4ce8cfb
ff7bb5530bf2042824bb0cbadae676c0fc9443d0
refs/heads/master
2021-01-10T21:21:31.713901
2015-10-21T01:50:23
2015-10-21T01:50:23
26,692,102
0
0
null
null
null
null
UTF-8
R
false
false
346
r
readSprint.R
"readSprint" <- function(file = system.file("data/sprint.txt", package="SprintData")) { sprintData <- read.table(file, sep=" ", header=TRUE, stringsAsFactors=FALSE) sprintData$Date <- with(sprintData, as.Date(paste(Year, Month, "15", sep="-"), format="%Y-%b-%d")) sprintData$User <- as.factor(sprintData$User) sprintData }
a940c009c5102d554d09f93d3461b26169ac75a8
36cbe94e3be91c4143a66dfec5d6135a95ae11d5
/Module 7 Assignment.R
bbbec7fdc1f6552452b7bb26cc3fa726d3e68020
[]
no_license
jonathanrprogramming/Module-7-Assignment
12342c22e81c01a2f517aa8677d637cb0f582126
43950da90df5f695988d312d3ea8b7b8939ae710
refs/heads/master
2021-04-27T10:38:38.938631
2018-02-22T22:07:44
2018-02-22T22:07:44
122,541,093
0
0
null
null
null
null
UTF-8
R
false
false
274
r
Module 7 Assignment.R
install.packages("statesRcontiguous") shapefile_details .S3methods(generic.function = "statesRcontiguous") .S4methods(generic.function = "statesRcontiguous") showMethods("statesRcontiguous") typeof("statesRcontiguous") methods(generic.function = "statesRcontiguous")
baea905d5a759550d21903c45864c974031d9564
cc4697514888cddee1b02031b2bce93787979be3
/man/informed_ds.Rd
1c2f0c9998d2f0123dca1740cbaf4489a867c734
[]
no_license
straussed/DynaRankR
8d2cff9b2cb16630ba42bc66a2a55907a4a35f30
5d1d53767671d515917ff7026675144b060d2161
refs/heads/master
2020-04-09T06:25:20.698096
2020-02-13T14:33:37
2020-02-13T14:33:37
160,111,557
1
0
null
null
null
null
UTF-8
R
false
true
5,555
rd
informed_ds.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/informed_ds.R \name{informed_ds} \alias{informed_ds} \title{David's Score method informed by prior information} \usage{ informed_ds(contestants, convention, initial.ranks = NULL, interactions) } \arguments{ \item{contestants}{A dataframe with the identities of the contestants for each study period along with the relevant data for adding them to the hierarchy. There should be one row per contestant per study period. Periods should appear in chronological order. The dataframe should contain the following columns: \describe{ \item{period}{Study period.} \item{id}{Identity of contestant.} \item{convention1}{The primary convention by which new individuals are added to the hierarchy. Interpretation of this column varies depending on the value of the \strong{convention} argument. If \strong{convention} = none, this column is optional.} \item{convention2}{Optional. The secondary data for resolving ties in convention1. Interpretation of this column varies depending on the value of the \strong{convention} argument.} }} \item{convention}{A flag determining how new individuals are added to the hierarchy. The value of this flag influences how the convention1 and convention2 columns of the \strong{contestants} argument are interpreted. Currently this function supports five options: \describe{ \item{none}{The standard David's Score procedure (using Dij) is run. Individuals are not added according to prior information and scores are calculated independently for each period.} \item{mri}{New contestants are added to the hierarchy according to maternal rank inheritance with youngest ascendancy. \strong{convention1} should be a vector of mother identities for each contestant. \strong{convention2} should be an optional vector of intra-litter ranks (lower numbers = higher rank) for resolving the order of contestants from the same mother joining the hierarchy in the same study period.} \item{tenure}{New contestants are added to the hierarchy according their tenure in the group. \strong{convention1} should be a vector of dates on which each contestant joined the group. \strong{convention2} should be an optional vector of numerical data for resolving ties in convention1 (e.g., body size). Higher values are considered higher rank.} \item{age}{New contestants are added to the hierarchy according their age (older = higher rank). \strong{convention1} should be a vector of birthdates or numerical age classes. \strong{convention2} should be an optional vector of numerical data for resolving ties in convention1 (e.g., body size). Higher values are considered higher rank.} \item{phys_attr}{New contestants are added to the hierarchy according to some physical attribute (larger value = higher rank). \strong{convention1} should be a vector of numerical attribute measurements. \strong{convention2} should be an optional vector of numerical data for resolving ties in convention1. Higher values are considered higher rank.} }} \item{initial.ranks}{The initial ordering of individuals for the first study period. Required if using maternal rank inheritance as the convention. For other conventions, if initial.ranks is not specified, the order determined by convention1 is used to create the initial order.} \item{interactions}{A dataframe of interaction data with the following columns: \describe{ \item{winner}{Identities of winners.} \item{loser}{Identities of losers.} \item{period}{Study period in which interactions occurred.}}} } \value{ Produces a dataframe with the following columns: \describe{ \item{period}{Study period.} \item{id}{Identity of contestant.} \item{score}{David's Score of contestant.} \item{rank}{Ordinal rank of contestant in study period. Lower numbers equal higher rank.} \item{stan.rank}{Rank of contestant standardized for group size. Values range from 1 (highest rank) to -1 (lowest rank).} \item{old.order}{Identity of contestants arranged in the previous order (the order they were in before updating the order based on observations from the current study period).}} } \description{ Use David's Score method to infer a dominance hierarchy over multiple study periods. New contestants are added according to the convention specified by the user. Scores are calculated using Dij and are normalized. Full description of the addition of new individuals is described in Strauss & Holekamp (in revision). To run the original David's Score procedure, use convention flag 'none'. } \examples{ ##Informed ds female.ranks <- informed_ds(contestants = C.crocuta.female$contestants, convention = 'mri', initial.ranks = C.crocuta.female$initial.ranks, interactions = C.crocuta.female$interactions) ##Standard ds female.ranks <- informed_ds(contestants = C.crocuta.female$contestants, convention = 'none', interactions = C.crocuta.female$interactions) } \references{ Strauss ED & Holekamp KE (in revision). Journal of Animal Ecology. de Vries H, Stevens JMG, Vervaecke H (2006). Animal Behavior. }
0bb5179b3e10084c366a25ca7bf539d5b84a6b10
357c61695c0b2885916745226b5d0dc7408766c0
/BAMMtools/man/plot.bammshifts.Rd
a264c8a38be52869d5abed4437f50d9e874b1cdf
[]
no_license
macroevolution/bammtools
62b4f9c6dd20ea37d1df6b7dd75d10967a8f3e75
07a17d8260a9e17419ca4bbc27687b4b6a7164be
refs/heads/master
2022-11-22T15:11:11.336582
2022-11-11T17:08:43
2022-11-11T17:08:43
17,520,404
7
7
null
2016-05-05T21:09:28
2014-03-07T16:42:06
R
UTF-8
R
false
true
4,186
rd
plot.bammshifts.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/plot.bammshifts.R \name{plot.bammshifts} \alias{plot.bammshifts} \title{Plot distinct rate shift configurations on a phylogeny} \usage{ \method{plot}{bammshifts}( x, ephy, method = "phylogram", pal = "RdYlBu", rank = NULL, index = NULL, spex = "s", legend = TRUE, add.freq.text = TRUE, logcolor = FALSE, breaksmethod = "linear", color.interval = NULL, JenksSubset = 20000, ... ) } \arguments{ \item{x}{An object of class \code{bammshifts}.} \item{ephy}{An object of class \code{bammdata}.} \item{method}{A character string for which plotting method to use. "phylogram" uses rectangular coordinates. "polar" uses polar coordinates.} \item{pal}{The color palette to use in \code{plot.bammdata}.} \item{rank}{The rank of the core shift configuration to plot. For the default (\code{NULL}) a random configuration is chosen.} \item{index}{The posterior sample to plot. For the default (\code{NULL}) a random sample is chosen.} \item{spex}{A character string indicating what type of macroevolutionary rates should be plotted. "s" (default) indicates speciation rates, "e" indicates extinction rates, and 'netdiv' indicates net diversification rates. Ignored if \code{ephy$type = "trait"}.} \item{legend}{Logical indicating whether to plot a legend.} \item{add.freq.text}{A logical indicating whether the frequency of each sampled shift configuration should be added to each plot.} \item{logcolor}{Logical. Should colors be plotted on a log scale.} \item{breaksmethod}{Method used for determining color breaks. See help file for \code{\link{assignColorBreaks}}.} \item{color.interval}{Min and max value for the mapping of rates. One of the two values can be \code{NA}. See details in \code{\link{plot.bammdata}} for further details.} \item{JenksSubset}{If \code{breaksmethod = "jenks"}, the number of regularly-spaced samples to subset from the full rates vector. Only relevant for large datasets. See help file for \code{\link{assignColorBreaks}}.} \item{\dots}{Other arguments to \code{plot.bammdata}.} } \description{ Plots a random distinct rate shift configuration sampled by \code{BAMM} on a phylogeny. } \details{ A rate shift configuration is the set of nodes of the phylogeny where a shift occurs in the macroevolutionary rate dynamic of diversification or trait evolution. Each posterior sample is a potentially distinct rate shift configuration. Different configurations may imply different macroevolutionary scenarios. This function helps visualize the different distinct rate shift configurations sampled by \code{BAMM}. A core shift configuration is defined by a set of nodes that have shift probabilities that are substantially elevated relative to what you expect under the prior alone. These core configurations are inferred in \code{\link{distinctShiftConfigurations}}. It is almost certain that more than one core shift configuration will be sampled by \code{BAMM}. Moreover, each core shift configuration may contain many subconfigurations. A subconfiguration contains the core shift node configuration and zero or more additional shift nodes that occur with low marginal probability. Points are added to the branches subtending the nodes of each rate configuration. The size of the point is proportional to the marginal probability that a shift occurs on a specific branch. If the instantaneous rate at a shift's origin represents an initial increase above the ancestral instantaneous rate the point is red. If the instantaneous rate at a shift's origin represents an initial decrease below the ancestral instantaneous rate the point is blue. } \examples{ data(whales, events.whales) ed <- getEventData(whales, events.whales, burnin=0.25, nsamples=500) sc <- distinctShiftConfigurations(ed, expectedNumberOfShifts = 1, threshold = 5) plot(sc, ed) } \references{ \url{http://bamm-project.org/} } \seealso{ \code{\link{distinctShiftConfigurations}}, \code{\link{plot.bammdata}} } \author{ Mike Grundler, Dan Rabosky }
f45cfea07b35e8d5af3585c8b1710088c1d2a48b
a2d515e45407c9f916b5272895a841196bce4286
/R/parseJSON.R
eb914a17dba0575cd00a5cb4cd16535ee3be3ce2
[]
no_license
kbroman/jsonlite
8a12345540ac46f05650687d848dc3a94004b599
14e251c72b557c670b288da4bdfa4d72ad58fd06
refs/heads/master
2021-01-21T09:34:59.883238
2014-12-31T01:25:36
2014-12-31T01:25:36
19,478,270
0
1
null
null
null
null
UTF-8
R
false
false
84
r
parseJSON.R
#' @useDynLib jsonlite R_parse parseJSON <- function(txt) { .Call(R_parse, txt) }
13dfe5a29654d3b26a59157a27f80182bdf1821c
7a95abd73d1ab9826e7f2bd7762f31c98bd0274f
/meteor/inst/testfiles/ET0_ThornthwaiteWilmott/AFL_ET0_ThornthwaiteWilmott/ET0_ThornthwaiteWilmott_valgrind_files/1615831110-test.R
90c6df98a0b60bfd9585314b446643486782bdf8
[]
no_license
akhikolla/updatedatatype-list3
536d4e126d14ffb84bb655b8551ed5bc9b16d2c5
d1505cabc5bea8badb599bf1ed44efad5306636c
refs/heads/master
2023-03-25T09:44:15.112369
2021-03-20T15:57:10
2021-03-20T15:57:10
349,770,001
0
0
null
null
null
null
UTF-8
R
false
false
611
r
1615831110-test.R
testlist <- list(doy = numeric(0), latitude = numeric(0), temp = c(8.3440061638964e-309, 1.56898425373334e+82, 8.96970809549085e-158, -1.3258495253834e-113, 2.79620616433656e-119, -6.80033518839696e+41, -7.91405836153987e+269, -7.9140592507382e+269, -7.9140592507382e+269, -1.18078903777427e-90, 1.86807199752012e+112, -5.58551357556946e+160, 2.00994342527714e-162, 1.81541609400943e-79, 7.89363005545926e+139, -2.10365634323144e-251, -5.82209879268833e+157, 1.94331168136796e+185, -2.93324078524665e-41, 1.36445664752896e-317, 0)) result <- do.call(meteor:::ET0_ThornthwaiteWilmott,testlist) str(result)
78272e3533a53b3f3d61cadef368c336ff013410
a503831b442aef5547d47849a59465b26bf087c2
/man/sieve.mm.Rd
499fea6f8df98cebc32d6503a5fc10730def00a4
[]
no_license
dtavern/grainsizeR
a5e99f70c6b845fdf5d44c11381a8a6900062b9e
75554d0c0ba8daeb84f81fcf598e83111c1d1d30
refs/heads/master
2021-01-20T11:16:50.129819
2017-04-12T07:16:05
2017-04-12T07:16:05
83,947,562
5
1
null
null
null
null
UTF-8
R
false
true
536
rd
sieve.mm.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/sieve_mm.R \name{sieve.mm} \alias{sieve.mm} \title{Sieve data (mm)} \usage{ sieve.mm(x, sieve_sizes = c(8, 11, 16, 22.6, 32, 45, 64, 90, 128, 180, 256, 360, 512, 1024)) } \arguments{ \item{x}{a list of grain size measurements} \item{sieve_sizes}{a vector containing desired sieve sizes in order of ascending size} } \value{ a dataframe of sieve sizes and associated counts of particles sieved at that size } \description{ Sieve data (mm) } \examples{ }
eb2e33f5271656125fcc577b32bbcb8986426542
0805436e0fdb8e9d28b0ce697af48baaead7b27b
/R/search_layers.R
d77676489ec639da0c66cff181d66151ce04ad79
[]
no_license
jjvanderwal/ALA4R
44f5c22f4da825bdb37cce7a6c30beeea5fd0dc8
69d3b9d6ebeeb62dac6df13655e4b38bcd761db6
refs/heads/master
2016-09-06T17:00:03.724946
2014-09-14T00:38:39
2014-09-14T00:38:39
15,890,257
2
0
null
null
null
null
UTF-8
R
false
false
3,439
r
search_layers.R
#' Search for environmental and contextual data layers #' #' @author Atlas of Living Australia \email{support@@ala.org.au} #' @references \url{http://api.ala.org.au/} \url{http://spatial.ala.org.au/layers} #' #' @param query text string: optional search term against layer metadata. Only layers that include this term in their metadata will be returned. #' @param type string: either "all" (all possible layers; default), "grids" (gridded environmental layers), or "shapes" (contextual shapefile layers) #' @param output_format string: controls the print method for the returned object. Either "complete" (the complete data structure is displayed), or "simple" (a simplified version is displayed). Note that the complete data structure exists in both cases: this option only controls what is displayed when the object is printed to the console. The default output format is "simple" #' @return A data frame of results. The contents (column names) of the data frame will vary depending on the details of the search and the results #' #' @examples #' search_layers(type="all") #' search_layers(type="grids",query="income") #' l=search_layers(type="shapes",query="coral",output_format="simple") #' str(l) #' @export search_layers = function(query,type="all",output_format="simple") { assert_that(is.string(type)) type=match.arg(tolower(type),c("all","grids","shapes")) if (!missing(query)) { assert_that(is.string(query)) } assert_that(is.character(output_format)) output_format=match.arg(tolower(output_format),c("simple","complete")) base_url = 'http://spatial.ala.org.au/ws/layers' ## define the base url if (type %in% c("grids","shapes")) { base_url=paste(base_url,type,sep='/') } out = cached_get(url=base_url,type="json") ## download all data if (!missing(query)) { out=out[grepl(query,out$name,ignore.case=TRUE) | grepl(query,out$description,ignore.case=TRUE),] } ## change id from numeric to "elxxx" or "clxxx" as appropriate for environmental/contextual if (!empty(out)) { out$id=paste(substr(tolower(out$type),1,1),"l",out$id,sep="") } ## change variable names for consistency names(out)=rename_variables(names(out),type="layers") ## change "name" to "shortName", "displayname" to "name" so as to match ala_fields("layers") names(out)[names(out)=="name"]="shortName" names(out)[names(out)=="displayname"]="name" ## remove some columns that are unlikely to be of value here xcols=setdiff(names(out),unwanted_columns("layers")) out=subset(out,select=xcols) ## reorder columns, for minor convenience xcols=names(out) firstcols=intersect(c("name","id","type","description"),xcols) xcols=c(firstcols,setdiff(xcols,firstcols)) out=subset(out,select=xcols) attr(out,"output_format")=output_format class(out)=c("search_layers",class(out)) ## add the search_names class if (empty(out) && ala_config()$warn_on_empty) { warning("no matching records were returned") } out } #' @S3method print search_layers "print.search_layers" <- function(x, ...) { cols=names(x) if (identical(attr(x,"output_format"),"simple")) { cols=intersect(c("name","id","description","type","notes","environmentalvalueunits","licence_notes","licence_link","notes"),cols) } m=as.matrix(format.data.frame(x[,cols],na.encode=FALSE)) print(m) invisible(x) }
605d6b9b22e828f77c9064f75fd61ca29eaac139
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/copBasic/examples/sectionCOP.Rd.R
e43349375d986b235a9196b323e8ddfe267e5b90
[]
no_license
surayaaramli/typeRrh
d257ac8905c49123f4ccd4e377ee3dfc84d1636c
66e6996f31961bc8b9aafe1a6a6098327b66bf71
refs/heads/master
2023-05-05T04:05:31.617869
2019-04-25T22:10:06
2019-04-25T22:10:06
null
0
0
null
null
null
null
UTF-8
R
false
false
3,157
r
sectionCOP.Rd.R
library(copBasic) ### Name: sectionCOP ### Title: The Sections or Derivative of the Sections of a Copula ### Aliases: sectionCOP ### Keywords: visualization diagnostics copula section ### ** Examples ## Not run: ##D # EXAMPLE 1, plot the v=0.55 section and then u=0.55 section, which will overlay ##D # the other because the PSP is a symmetrical copula ##D tmp <- sectionCOP(0.55, cop=PSP, ylab="COPULA SECTIONS", lwd=5, col=2) ##D tmp <- sectionCOP(0.55, cop=PSP, wrtV=TRUE, ploton=FALSE, lwd=2, col=3) ##D # now add the v=0.85 section and the u=0.85, again overlay each other ##D tmp <- sectionCOP(0.85, cop=PSP, ploton=FALSE, lwd=5, col=2, lty=2) ##D tmp <- sectionCOP(0.85, cop=PSP, wrtV=TRUE, ploton=FALSE, lwd=2, col=3, lty=2)# ## End(Not run) ## Not run: ##D # EXAMPLE 2, v=0.35 section and derivative (the conditional distribution) function ##D tmp <- sectionCOP(0.35, cop=PSP, ylab="COPULA SECTIONS OR DERIV.", lwd=5, col=3) ##D tmp <- sectionCOP(0.35, cop=PSP, dercop=TRUE, ploton=FALSE, col=3) ##D # The thin green line represents the cumulative distribution function conditional ##D # on u = 0.35 from the derCOP function. Then see Example 3 ## End(Not run) ## Not run: ##D # EXAMPLE 3 (random selection commented out) ##D #para <- list(cop1=PLACKETTcop, cop2=PLACKETTcop, alpha=runif(1), beta=runif(1), ##D # para1=10^runif(1,min=-4, max=0), para2=10^runif(1,min= 0, max=4)) ##D para <- list(cop1=PLACKETTcop, cop2=PLACKETTcop, alpha=0.7, beta=0.22, ##D para1=0.0155, para2=214.4) ##D txts <- c("Alpha=", round(para$alpha, digits=4), ##D "; Beta=", round(para$beta, digits=4), ##D "; Theta1=", round(para$para1[1], digits=5), ##D "; Theta2=", round(para$para2[1], digits=2)) ##D layout(matrix(1:2,byrow=TRUE)) ##D D <- simCOP(n=1000, cop=composite2COP, para=para, cex=0.5, col=rgb(0,0,0,0.2), pch=16) ##D mtext(paste(txts,collapse="")) ##D #f <- c(runif(1),runif(1)) ##D f <- c(0.2,0.9) # RED is the horizontal section and BLACK is the vertical section ##D segments(f[1],0,f[1],1, col=2, lwd=2); segments(0,f[2],1,f[2], lwd=2) ##D ftxt <- c("Sections (thick) and derivatives (thin) at ", f, " nonexceed. prob.") ##D tmp <- sectionCOP(f[1],cop=composite2COP,para=para, col=2, lwd=4) ##D tmp <- sectionCOP(f[1],cop=composite2COP,para=para, dercop=TRUE, ploton=FALSE, col=2) ##D tmp <- sectionCOP(f[2],cop=composite2COP,para=para,wrtV=TRUE,ploton=FALSE,lwd=4) ##D tmp <- sectionCOP(f[2],cop=composite2COP,para=para,wrtV=TRUE,ploton=FALSE,dercop=TRUE) ##D mtext(paste(ftxt, collapse="")) ##D # The thin lines are the CDFs conditional on the respective values of "f". Carefully ##D # compare the point densities along and near the sections in the top plot to the ##D # respective shapes of the CDFs in the bottom plot. If the bottom plot were rotated ##D # 90 degrees clockwise and then reflected top to bottom, the conditional quantile ##D # function QDF results. Reflection is needed because, by convention, QDFs are monotonic ##D # increasing to right---functions derCOPinv() and derCOPinv2() provide the CDF inversion. ## End(Not run)
84547ee73535c307eca4e4c920970a7a4ce1e275
fcc93b4a49a38af62678c0017025f492eb4c2ade
/man/x.Rd
92fd889314063154711ce02490f359c2e889e15f
[]
no_license
FaridaBenchalal/MIXCLUSTERING
0b335d1e668914420add7cefc56ea663a71a515b
b00c4644d0c05b106e8f73a5a93bcb815a0ff238
refs/heads/main
2023-03-29T07:22:56.440859
2021-03-22T13:21:34
2021-03-22T13:21:34
348,022,407
0
0
null
null
null
null
UTF-8
R
false
false
1,338
rd
x.Rd
\name{x} \alias{x} \docType{data} \title{ %% ~~ data name/kind ... ~~ DataFrame stadard of R, which represents cars } \description{ %% ~~ A concise (1-5 lines) description of the dataset. ~~ DataFrame of carts wich containts continious and categorical features } \usage{data("x")} \format{ A data frame with 32 observations on the following 11 variables. \describe{ \item{\code{mpg}}{a numeric vector} \item{\code{cyl}}{a numeric vector} \item{\code{disp}}{a numeric vector} \item{\code{hp}}{a numeric vector} \item{\code{drat}}{a numeric vector} \item{\code{wt}}{a numeric vector} \item{\code{qsec}}{a numeric vector} \item{\code{vs}}{a factor with levels \code{0} \code{1}} \item{\code{am}}{a factor with levels \code{0} \code{1}} \item{\code{gear}}{a factor with levels \code{3} \code{4} \code{5}} \item{\code{carb}}{a numeric vector} } } \details{ %% ~~ If necessary, more details than the __description__ above ~~ } \source{ %% ~~ reference to a publication or URL from which the data were obtained ~~ } \references{ %% ~~ possibly secondary sources and usages ~~ } \examples{ data(x) x <- mtcars x$vs = as.factor(x$vs) x$am = as.factor(x$am) x$gear = as.factor(x$gear) ## maybe str(x) ; plot(x) ... } \keyword{datasets}
10a1a382be832452d8f5f4c4e8a78c47e5007781
e271452da9d73b3f9a4cadfc1858f7f4dfff3130
/server.r
4a11be903edea6bf6c3d88f96512ae8c07d0cb96
[ "MIT" ]
permissive
simecek/GFRcalc
1ba0fef60921d3f5b2de970ab36a18a2e700f9db
fbd0cb179f5f4e5a9a9ba255f8789264dc4b0d8f
refs/heads/master
2021-06-01T20:50:57.500492
2017-08-07T09:22:45
2017-08-07T09:22:45
38,074,484
1
2
null
2017-10-25T17:35:38
2015-06-25T21:12:23
R
UTF-8
R
false
false
4,853
r
server.r
library(shiny) library(readxl) library(ggplot2) source("helpers.R") options(stringsAsFactors = FALSE) max_plots <- 16 shinyServer(function(input, output) { # read data file file.upload <- reactive({ inFile <- input$GFRfile if (!is.null(inFile)) { # if any file name is given ext <- tools::file_ext(inFile$name) file.rename(inFile$datapath, paste(inFile$datapath, ext, sep=".")) # dirty hack, see issue 85 output <- read_excel(paste(inFile$datapath, ext, sep="."), sheet=2, col_names = FALSE) output <- output[!is.na(output[,1]),] # remove NA rows if (!is.character(output[,1])) { # if animal IDs missing, add them animalID <- rep(LETTERS, each=length(unique(output[,1])))[1:nrow(output)] output <- cbind(animalID, output) } output <- output[,1:5] # only 5 columns matters names(output) <- c("Animal", "Time", "M1", "M2", "M3") # adding information about animals - should be on sheet 3 animal.table <- read_excel(paste(inFile$datapath, ext, sep="."), sheet=3, col_names = FALSE)[2:4,-1] attr(output, "animals") <- t(animal.table) output } else { NULL } }) output$check <- renderText({dt <- file.upload(); check.format(dt)}) output$contents <- renderTable({ dt <- file.upload() if (!is.null(dt) & check.format(dt)=="") { # everything ok # info about animals given? if not add them animals <- unique(dt$Animal) animal.table <- attr(dt, "animals") results <- NULL for (a in animals) { tmp <- subset(dt, Animal==a) tmp <- tmp[order(tmp$Time),] # very rough outlier detection tmp[-1,c("M1","M2","M3")][outlier.detect(tmp[-1,], 5)] <- NA tmp$mean <- rowMeans(tmp[,c("M1","M2","M3")], na.rm=TRUE) start <- 2 # skip first observation tmp2 <- tmp[start:nrow(tmp),] fit1 <- oneexp(y=tmp2$mean,x=tmp2$Time) fit2 <- twoexp(y=tmp2$mean,x=tmp2$Time) fit3 <- linint(y=tmp2$mean,x=tmp2$Time) fit4 <- twoexp.approx(y=tmp2$mean,x=tmp2$Time) inj.volume <- as.numeric(animal.table[animals==a,3]) newrow <- data.frame(Animal = a, MouseId = animal.table[animals==a,1], Weight = as.numeric(animal.table[animals==a,2]), "Injected Volume" = inj.volume, "C2" = input$dilution*inj.volume*tmp$mean[1]*ifelse(is.null(fit2), NA, coef(fit2)[2]*coef(fit2)[4]/(coef(fit2)[1]*coef(fit2)[4]+coef(fit2)[2]*coef(fit2)[3])), "2xC1" = ifelse(is.null(fit4),NA,input$dilution*inj.volume*tmp$mean[1]/fit4), "C1" = input$dilution*inj.volume*tmp$mean[1]*ifelse(is.null(fit1), NA, coef(fit1)[2]/coef(fit1)[1]), "PL" = ifelse(is.null(fit3), NA, input$dilution*inj.volume*tmp$mean[1]/fit3), "Sigma.C2" = ifelse(is.null(fit2),NA,as.integer(round(summary(fit2)$sigma))), nNA = sum(is.na(tmp2[,c("M1","M2","M3")])), check.names = FALSE) results <- rbind(results, newrow) } if (!input$Animal) results$"Animal" <- NULL if (!input$MouseId) results$"MouseId" <- NULL if (!input$Weight) results$"Weight" <- NULL if (!input$InjectedVolume) results$"Injected Volume" <- NULL if (!input$GFR2) results$"C2" <- NULL if (!input$GFR4) results$"2xC1" <- NULL if (!input$GFR1) results$"C1" <- NULL if (!input$GFR3) results$"PL" <- NULL if (!input$Sigma.C2) results$"Sigma.C2" <- NULL if (!input$nNA) results$"nNA" <- NULL rownames(results) <- NULL return(results) } else { return (NULL) } }, digits=1, include.rownames=FALSE) output$plots <- renderUI({ dt <- file.upload() if (!is.null(dt) & check.format(dt)=="") { # everything ok plot_output_list <- lapply(1:length(unique(dt[,1])), function(i) { plotname <- paste0("plot", i) plotOutput(plotname, height = 390, width = 520) }) # Convert the list to a tagList - this is necessary for the list of items # to display properly. do.call(tagList, plot_output_list) } }) for (i in 1:max_plots) { # Need local so that each item gets its own number. Without it, the value # of i in the renderPlot() will be the same across all instances, because # of when the expression is evaluated. local({ my_i <- i plotname <- paste0("plot", my_i) output[[plotname]] <- renderPlot({make.plot(file.upload(), my_i)}) }) } })
5647238a9b22f6d2ee5c0cbf30f529c8d0bdb9c4
bfb0dd605dbe9a50903dc13ea49b04edb027a868
/man/MGWRConfig-class.Rd
576b7f0c2278332e4d3ff232ab93e4668dad141d
[]
no_license
GWmodel-Lab/GWmodel3
6492b18e70d7ab58076acd9ad7bdb58a7e40c2bf
42e756431500fb84fc777594c80bca78a2de0f02
refs/heads/master
2023-08-09T15:33:12.321389
2023-07-25T11:18:30
2023-07-25T11:18:30
567,957,637
0
1
null
2023-09-14T15:35:53
2022-11-19T02:05:58
R
UTF-8
R
false
true
1,227
rd
MGWRConfig-class.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/class-MGWRConfig.R \docType{class} \name{MGWRConfig-class} \alias{MGWRConfig-class} \alias{MGWRConfig} \title{An S4 class to set Multiscale GWR configurations} \description{ An S4 class to set Multiscale GWR configurations } \section{Slots}{ \describe{ \item{\code{bw}}{Bandwidth value.} \item{\code{adaptive}}{Whether the bandwidth value is adaptive or not.} \item{\code{kernel}}{Kernel function used.} \item{\code{longlat}}{Whether the coordinates.} \item{\code{p}}{Power of the Minkowski distance, default to 2, i.e., Euclidean distance.} \item{\code{theta}}{Angle in radian to roate the coordinate system, default to 0.} \item{\code{centered}}{A logical vector of length equalling to the number of predictors, and note intercept is not included; if the element is TRUE, the corresponding predictor will be centered.} \item{\code{optim_bw}}{Whether optimize bandwidth after selecting models. Avaliable values are \code{no}, \code{AIC}, and \code{CV}. If \code{no} is specified, the bandwidth specified by argument \code{bw} is used in calibrating selected models.} \item{\code{optim_threshold}}{Threshold of bandwidth optimization.} }}
b0da43909b9807836fddf9b4e8d3cc3b9f4d8c65
75070d4917747396abce56e5cce8047b4556541b
/R/STEP3_FIGURES/estimate_first_stage_fd.R
64784893f6264579a81b00ade0e32c98660c624b
[]
no_license
abhradeepmaiti/orthoml
f8744ea5dee1a2d536706acbf3dd75dd11bb0735
70b6de67cd258f0e23e58033bdd295c9a455de5f
refs/heads/master
2023-03-17T13:49:37.449417
2021-03-16T16:51:38
2021-03-16T16:51:38
null
0
0
null
null
null
null
UTF-8
R
false
false
2,164
r
estimate_first_stage_fd.R
rm(list=ls()) # set directoryname directoryname<-"/n/tata/orthoml/" setwd(directoryname) library(tidyverse) library(gamlr) library(xtable) library(glmnet) categorynames = c("Drinks", "Dairy","NonEdible","Snacks") source(paste0(directoryname,"/R/FirstStage.R")) treat_name="logpr" outcome_name="logsls" for (categoryname in categorynames) { ### load data my_data<-read.csv(paste0(directoryname,"/processed_data/",categoryname,".csv")) colnames(my_data)[colnames(my_data)=="X"]<-"RowID" my_data$RowID<-as.character(my_data$RowID) my_data$logpr<-my_data$logprice-my_data$logprice_lag my_data$logsls<-my_data$logsales-my_data$logsales_lag my_data$logprice_lag_fd<-my_data$logprice_lag - my_data$logprice_lag_2 my_data$logsales_lag_fd<-my_data$logsales_lag - my_data$logsales_lag_2 #inds_train<-(1:dim(my_data)[1])[(my_data$year==2013 & my_data$week<=8) + (my_data$year==2012)>=1] # subset_inds<-inds_test<-setdiff( (1:dim(my_data)[1]),inds_train) ### estimate first stage in levels lag.names<-grep("_lag",colnames(my_data),value=TRUE) level_names<-setdiff(grep("Level",colnames(my_data),value=TRUE ),grep("_Name",colnames(my_data),value=TRUE )) first_stage_price_formula<-as.formula(paste0("logpr~(Level1+Level2+Level3)*(", paste(c("logprice_lag_fd"),collapse="+"), ")")) first_stage_sales_formula<-as.formula(paste0("logsls~(Level1+Level2+Level3)*(", paste(c("logprice_lag_fd","logsales_lag_fd"),collapse="+"), ")")) fs<-first_stage_1d(treat=my_data[,treat_name], outcome=my_data[,outcome_name], first_stage_price_formula=first_stage_price_formula, first_stage_sales_formula=first_stage_sales_formula, inds_train=inds_train ) write.csv(data.frame(treat_res=fs$treat,outcome_res=fs$outcome),paste0(directoryname,"/processed_data/first_stage_fd/FirstStage",categoryname,".csv")) ### estimate first stage in first differences }
32bae5e70606e7b78cc0dfde7800b1e5fc2d4520
98b3a030e1d594ed130e656cbe9eecf0cedaf212
/tests/testthat/test-assertions_v13.R
a742b51663b14f90016106b28915c912a29049bf
[ "MIT" ]
permissive
mrc-ide/drjacoby
a45b44db7ec43c2fb1924ce571ad17032477dfe5
476d94f3eb7357f8e2278834c0af04afd772cf69
refs/heads/master
2023-07-21T09:04:43.435509
2022-02-10T09:37:00
2022-02-10T09:37:00
184,567,263
16
6
MIT
2023-05-24T10:30:53
2019-05-02T11:12:41
R
UTF-8
R
false
false
23,230
r
test-assertions_v13.R
#------------------------------------------------ test_that("nice_format working correctly", { expect_true(nice_format(NULL) == "") expect_true(nice_format(5) == "5") expect_true(nice_format(1:5) == "{1, 2, 3, 4, 5}") expect_equal(nice_format(c("foo", "bar")), "{foo, bar}") }) #------------------------------------------------ test_that("assert_null working correctly", { expect_true(assert_null(NULL)) expect_error(assert_null(5)) }) #------------------------------------------------ test_that("assert_non_null working correctly", { expect_true(assert_non_null(5)) expect_error(assert_non_null(NULL)) }) #------------------------------------------------ test_that("assert_NA working correctly", { expect_true(assert_NA(NA)) expect_true(assert_NA(rep(NA, 5))) expect_error(assert_NA(NULL)) expect_error(assert_NA(Inf)) expect_error(assert_NA(1:5)) }) #------------------------------------------------ test_that("assert_non_NA working correctly", { expect_true(assert_non_NA(NULL)) expect_true(assert_non_NA(Inf)) expect_true(assert_non_NA(1:5)) expect_error(assert_non_NA(NA)) expect_error(assert_non_NA(rep(NA, 5))) }) #------------------------------------------------ test_that("assert_atomic correctly", { expect_true(assert_atomic(TRUE)) expect_true(assert_atomic(1)) expect_true(assert_atomic(seq(0,5,0.5))) expect_true(assert_atomic(0i)) expect_true(assert_atomic("foo")) expect_true(assert_atomic(raw(8))) expect_true(assert_atomic(matrix(0,3,3))) expect_error(assert_atomic(list(1:5))) expect_error(assert_atomic(data.frame(1:5))) }) #------------------------------------------------ test_that("assert_single correctly", { expect_true(assert_single(TRUE)) expect_true(assert_single(1)) expect_true(assert_single("foo")) expect_error(assert_single(NULL)) expect_error(assert_single(1:5)) expect_error(assert_single(list(0))) expect_error(assert_single(matrix(0,3,3))) expect_error(assert_single(data.frame(0))) }) #------------------------------------------------ test_that("assert_string working correctly", { expect_true(assert_string("foo")) expect_true(assert_string(c("foo", "bar"))) expect_error(assert_string(NULL)) expect_error(assert_string(5)) expect_error(assert_string(1:5)) }) #------------------------------------------------ test_that("assert_single_string working correctly", { expect_true(assert_single_string("foo")) expect_error(assert_single_string(NULL)) expect_error(assert_single_string(c("foo", "bar"))) expect_error(assert_single_string(5)) expect_error(assert_single_string(1:5)) }) #------------------------------------------------ test_that("assert_logical working correctly", { expect_true(assert_logical(TRUE)) expect_true(assert_logical(c(TRUE, FALSE))) expect_error(assert_logical(NULL)) expect_error(assert_logical("TRUE")) expect_error(assert_logical(5)) expect_error(assert_logical(1:5)) }) #------------------------------------------------ test_that("assert_single_logical working correctly", { expect_true(assert_single_logical(TRUE)) expect_error(assert_single_logical(NULL)) expect_error(assert_single_logical(c(TRUE, FALSE))) expect_error(assert_single_logical("TRUE")) expect_error(assert_single_logical(5)) expect_error(assert_single_logical(1:5)) }) #------------------------------------------------ test_that("assert_numeric working correctly", { expect_true(assert_numeric(5)) expect_true(assert_numeric(-5:5)) expect_error(assert_numeric(NULL)) expect_error(assert_numeric("foo")) expect_error(assert_numeric(c(1, "foo"))) }) #------------------------------------------------ test_that("assert_single_numeric working correctly", { expect_true(assert_single_numeric(5)) expect_error(assert_single_numeric(-5:5)) expect_error(assert_single_numeric(NULL)) expect_error(assert_single_numeric("foo")) expect_error(assert_single_numeric(c(1, "foo"))) }) #------------------------------------------------ test_that("assert_int working correctly", { expect_true(assert_int(5)) expect_true(assert_int(-5)) expect_true(assert_int(-5:5)) expect_true(assert_int(c(a = 5))) expect_error(assert_int(NULL)) expect_error(assert_int(0.5)) expect_error(assert_int("foo")) expect_error(assert_int(c(5,"foo"))) }) #------------------------------------------------ test_that("assert_single_int working correctly", { expect_true(assert_single_int(5)) expect_true(assert_single_int(-5)) expect_error(assert_single_int(-5:5)) expect_error(assert_single_int(NULL)) expect_error(assert_single_int(0.5)) expect_error(assert_single_int("foo")) expect_error(assert_single_int(c(5,"foo"))) }) #------------------------------------------------ test_that("assert_pos working correctly", { expect_true(assert_pos(5)) expect_true(assert_pos(seq(1, 5, 0.5))) expect_true(assert_pos(seq(0, 5, 0.5), zero_allowed = TRUE)) expect_error(assert_pos(NULL)) expect_error(assert_pos(-5)) expect_error(assert_pos(seq(-1, -5, -0.5))) expect_error(assert_pos(seq(0, 5, 0.5), zero_allowed = FALSE)) expect_error(assert_pos(seq(-5, 5, 0.5), zero_allowed = TRUE)) expect_error(assert_pos("foo")) }) #------------------------------------------------ test_that("assert_single_pos working correctly", { expect_true(assert_single_pos(5)) expect_error(assert_single_pos(seq(1, 5, 0.5))) expect_error(assert_single_pos(seq(0, 5, 0.5), zero_allowed = TRUE)) expect_error(assert_single_pos(NULL)) expect_error(assert_single_pos(-5)) expect_error(assert_single_pos(seq(-1, -5, -0.5))) expect_error(assert_single_pos(seq(0, 5, 0.5), zero_allowed = FALSE)) expect_error(assert_single_pos(seq(-5, 5, 0.5), zero_allowed = TRUE)) expect_error(assert_single_pos("foo")) }) #------------------------------------------------ test_that("assert_pos_int working correctly", { expect_true(assert_pos_int(5)) expect_true(assert_pos_int(0, zero_allowed = TRUE)) expect_true(assert_pos_int(1:5)) expect_true(assert_pos_int(0:5, zero_allowed = TRUE)) expect_error(assert_pos_int(NULL)) expect_error(assert_pos_int(-5)) expect_error(assert_pos_int(-1:-5)) expect_error(assert_pos_int(0:5, zero_allowed = FALSE)) expect_error(assert_pos_int(-5:5, zero_allowed = TRUE)) expect_error(assert_pos_int("foo")) }) #------------------------------------------------ test_that("assert_single_pos_int working correctly", { expect_true(assert_single_pos_int(5)) expect_true(assert_single_pos_int(0, zero_allowed = TRUE)) expect_error(assert_single_pos_int(1:5)) expect_error(assert_single_pos_int(0:5, zero_allowed = TRUE)) expect_error(assert_single_pos_int(NULL)) expect_error(assert_single_pos_int(-5)) expect_error(assert_single_pos_int(-1:-5)) expect_error(assert_single_pos_int(0:5, zero_allowed = FALSE)) expect_error(assert_single_pos_int(-5:5, zero_allowed = TRUE)) expect_error(assert_single_pos_int("foo")) }) #------------------------------------------------ test_that("assert_single_bounded working correctly", { expect_true(assert_single_bounded(0.5)) expect_true(assert_single_bounded(5, left = 0, right = 10)) expect_true(assert_single_bounded(0, inclusive_left = TRUE)) expect_true(assert_single_bounded(1, inclusive_right = TRUE)) expect_error(assert_single_bounded(NULL)) expect_error(assert_single_bounded(1:5)) expect_error(assert_single_bounded(5)) expect_error(assert_single_bounded(0, inclusive_left = FALSE)) expect_error(assert_single_bounded(1, inclusive_right = FALSE)) expect_error(assert_single_bounded("foo")) }) #------------------------------------------------ test_that("assert_vector working correctly", { expect_true(assert_vector(1)) expect_true(assert_vector(1:5)) expect_error(assert_vector(NULL)) expect_error(assert_vector(matrix(5,3,3))) expect_error(assert_vector(list(1:5, 1:10))) expect_error(assert_vector(data.frame(1:5, 2:6))) }) #------------------------------------------------ test_that("assert_vector_numeric working correctly", { expect_true(assert_vector_numeric(1)) expect_true(assert_vector_numeric(1:5)) expect_error(assert_vector_numeric(NULL)) expect_error(assert_vector_numeric(c("a", "b"))) expect_error(assert_vector_numeric(matrix(5,3,3))) expect_error(assert_vector_numeric(list(1:5, 1:10))) expect_error(assert_vector_numeric(data.frame(1:5, 2:6))) }) #------------------------------------------------ test_that("assert_vector_int working correctly", { expect_true(assert_vector_int(1)) expect_true(assert_vector_int(1:5)) expect_error(assert_vector_int(NULL)) expect_error(assert_vector_int(c("a", "b"))) expect_error(assert_vector_int(c(0.5, 1.5))) expect_error(assert_vector_int(matrix(5,3,3))) expect_error(assert_vector_int(list(1:5, 1:10))) expect_error(assert_vector_int(data.frame(1:5, 2:6))) }) #------------------------------------------------ test_that("assert_vector_pos_int working correctly", { expect_true(assert_vector_pos_int(1)) expect_true(assert_vector_pos_int(1:5)) expect_error(assert_vector_pos_int(NULL)) expect_error(assert_vector_pos_int(c("a", "b"))) expect_error(assert_vector_pos_int(c(0.5, 1.5))) expect_error(assert_vector_pos_int(-2:2)) expect_error(assert_vector_pos_int(matrix(5,3,3))) expect_error(assert_vector_pos_int(list(1:5, 1:10))) expect_error(assert_vector_pos_int(data.frame(1:5, 2:6))) }) #------------------------------------------------ test_that("assert_vector_pos working correctly", { expect_true(assert_vector_pos(1)) expect_true(assert_vector_pos(1:5)) expect_error(assert_vector_pos(NULL)) expect_error(assert_vector_pos(c("a", "b"))) expect_error(assert_vector_pos(-1)) expect_error(assert_vector_pos(matrix(5,3,3))) expect_error(assert_vector_pos(list(1:5, 1:10))) expect_error(assert_vector_pos(data.frame(1:5, 2:6))) }) #------------------------------------------------ test_that("assert_vector_bounded working correctly", { expect_true(assert_vector_bounded(1)) expect_true(assert_vector_bounded(seq(0,1,0.1))) expect_error(assert_vector_bounded(NULL)) expect_error(assert_vector_bounded(c("a", "b"))) expect_error(assert_vector_bounded(-1)) expect_error(assert_vector_bounded(matrix(5,3,3))) expect_error(assert_vector_bounded(list(1:5, 1:10))) expect_error(assert_vector_bounded(data.frame(1:5, 2:6))) }) #------------------------------------------------ test_that("assert_vector_string working correctly", { expect_true(assert_vector_string("foo")) expect_true(assert_vector_string(c("foo","bar"))) expect_error(assert_vector_string(1)) expect_error(assert_vector_string(NULL)) }) #------------------------------------------------ test_that("assert_matrix working correctly", { expect_true(assert_matrix(matrix(NA,1,1))) expect_true(assert_matrix(matrix(5,3,3))) expect_error(assert_matrix(NULL)) expect_error(assert_matrix(5)) expect_error(assert_matrix(1:5)) expect_error(assert_matrix(list(1:5, 1:10))) expect_error(assert_matrix(data.frame(1:5, 2:6))) }) #------------------------------------------------ test_that("assert_matrix_numeric working correctly", { expect_true(assert_matrix_numeric(matrix(5,3,3))) expect_error(assert_matrix_numeric(NULL)) expect_error(assert_matrix_numeric(5)) expect_error(assert_matrix_numeric(1:5)) expect_error(assert_matrix_numeric(list(1:5, 1:10))) expect_error(assert_matrix_numeric(data.frame(1:5, 2:6))) expect_error(assert_matrix_numeric(matrix("4", 1, 1))) expect_error(assert_matrix_numeric(matrix(NA,1,1))) }) #------------------------------------------------ test_that("assert_list working correctly", { expect_true(assert_list(list(1:5))) expect_true(assert_list(data.frame(x = 1:5))) expect_error(assert_list(NULL)) expect_error(assert_list(5)) expect_error(assert_list(1:5)) expect_error(assert_list(matrix(NA, 3, 3))) }) #------------------------------------------------ test_that("assert_named working correctly", { expect_true(assert_named(c(x = 5))) expect_true(assert_named(list(x = "foo"))) expect_true(assert_named(data.frame(x = "foo", y = "bar"))) expect_error(assert_named(NULL)) expect_error(assert_named(5)) expect_error(assert_named(matrix(NA, 3, 3))) }) #------------------------------------------------ test_that("assert_list_named working correctly", { expect_true(assert_list_named(list(a = 1:5))) expect_true(assert_list_named(data.frame(x = 1:5))) expect_error(assert_list_named(list(1:5))) expect_error(assert_list_named(NULL)) expect_error(assert_list_named(5)) expect_error(assert_list_named(1:5)) expect_error(assert_list_named(matrix(NA, 3, 3))) }) #------------------------------------------------ test_that("assert_dataframe working correctly", { expect_true(assert_dataframe(data.frame(x = 1:5))) expect_error(assert_dataframe(NULL)) expect_error(assert_dataframe(5)) expect_error(assert_dataframe(1:5)) expect_error(assert_dataframe(list(1:5))) expect_error(assert_dataframe(matrix(NA, 3, 3))) }) #------------------------------------------------ test_that("assert_class working correctly", { expect_true(assert_class(NULL, "NULL")) expect_true(assert_class(data.frame(1:5), "data.frame")) expect_error(assert_class(NULL, "foo")) expect_error(assert_class(data.frame(1:5), "foo")) }) #------------------------------------------------ test_that("assert_limit working correctly", { expect_true(assert_limit(c(0,1))) expect_true(assert_limit(c(-10,10))) expect_error(assert_limit(NULL)) expect_error(assert_limit(1:5)) expect_error(assert_limit(1)) expect_error(assert_limit(c(2,1))) expect_error(assert_limit("foo")) }) #------------------------------------------------ test_that("assert_eq working correctly", { expect_true(assert_eq(5,5)) expect_true(assert_eq(1:5,1:5)) expect_true(assert_eq("foo","foo")) expect_true(assert_eq(c(a = 5), c(b = 5))) expect_error(assert_eq(NULL,5)) expect_error(assert_eq(5,NULL)) expect_error(assert_eq(NULL,NULL)) expect_error(assert_eq(4,5)) expect_error(assert_eq(1:4,1:5)) expect_error(assert_eq("foo","bar")) }) #------------------------------------------------ test_that("assert_neq working correctly", { expect_true(assert_neq(4,5)) expect_true(assert_neq(2:6,1:5)) expect_true(assert_neq("foo","bar")) expect_error(assert_neq(NULL,5)) expect_error(assert_neq(5,NULL)) expect_error(assert_neq(NULL,NULL)) expect_error(assert_neq(5,5)) expect_error(assert_neq(1:5,1:5)) expect_error(assert_neq("foo","foo")) }) #------------------------------------------------ test_that("assert_gr working correctly", { expect_true(assert_gr(5,4)) expect_true(assert_gr(1:5,0)) expect_true(assert_gr(2:6,1:5)) expect_error(assert_gr(NULL,5)) expect_error(assert_gr(5,NULL)) expect_error(assert_gr(NULL,NULL)) expect_error(assert_gr(3,3)) expect_error(assert_gr(3,4)) expect_error(assert_gr(1:4,1:5)) }) #------------------------------------------------ test_that("assert_greq working correctly", { expect_true(assert_greq(5,4)) expect_true(assert_greq(5,5)) expect_true(assert_greq(1:5,0)) expect_true(assert_greq(2:6,1:5)) expect_true(assert_greq(1:5,1:5)) expect_error(assert_greq(NULL,5)) expect_error(assert_greq(5,NULL)) expect_error(assert_greq(NULL,NULL)) expect_error(assert_greq(3,4)) expect_error(assert_greq(1:4,1:5)) }) #------------------------------------------------ test_that("assert_le working correctly", { expect_true(assert_le(4,5)) expect_true(assert_le(1:5,9)) expect_true(assert_le(2:6,3:7)) expect_error(assert_le(NULL,5)) expect_error(assert_le(5,NULL)) expect_error(assert_le(NULL,NULL)) expect_error(assert_le(3,3)) expect_error(assert_le(4,3)) expect_error(assert_le(1:4,1:5)) }) #------------------------------------------------ test_that("assert_leq working correctly", { expect_true(assert_leq(4,5)) expect_true(assert_leq(4,4)) expect_true(assert_leq(1:5,9)) expect_true(assert_leq(2:6,2:6)) expect_error(assert_leq(NULL,5)) expect_error(assert_leq(5,NULL)) expect_error(assert_leq(NULL,NULL)) expect_error(assert_leq(4,3)) expect_error(assert_leq(2:6,1:5)) }) #------------------------------------------------ test_that("assert_bounded working correctly", { expect_true(assert_bounded(seq(0, 1, 0.1))) expect_true(assert_bounded(seq(-5, 5, 0.1), left = -5, right = 5)) expect_error(assert_bounded(NULL)) expect_error(assert_bounded(seq(0, 1, 0.1), left = 0.1)) expect_error(assert_bounded(seq(0, 1, 0.1), right = 0.9)) expect_error(assert_bounded(0, left = 0, inclusive_left = FALSE)) expect_error(assert_bounded(1, right = 1, inclusive_right = FALSE)) expect_error(assert_bounded("foo")) }) #------------------------------------------------ test_that("assert_in working correctly", { expect_true(assert_in(3, 3)) expect_true(assert_in(3, 1:5)) expect_true(assert_in("foo", c("foo", "bar"))) expect_error(assert_in(NULL, 5)) expect_error(assert_in(5, NULL)) expect_error(assert_in(NULL, NULL)) expect_error(assert_in(1:5, 1:4)) expect_error(assert_in("foo", c("bar", "roo"))) }) #------------------------------------------------ test_that("assert_not_in working correctly", { expect_true(assert_not_in(3, 4)) expect_true(assert_not_in(1:5, 6:10)) expect_true(assert_not_in("foo", c("bar", "roo"))) expect_error(assert_not_in(NULL, 5)) expect_error(assert_not_in(5, NULL)) expect_error(assert_not_in(NULL, NULL)) expect_error(assert_not_in(1:5, 5:10)) expect_error(assert_not_in("foo", c("foo", "bar"))) }) #------------------------------------------------ test_that("assert_length working correctly", { expect_true(assert_length(1:3, 3)) expect_true(assert_length(3, 1)) expect_true(assert_length(matrix(NA,3,4), 12)) expect_error(assert_length(1:3, NULL)) expect_error(assert_length(NULL, 1:3)) expect_error(assert_length(NULL, NULL)) expect_error(assert_length(3, 2)) expect_error(assert_length(1:3, 2)) expect_error(assert_length(matrix(NA,3,4), 9)) }) #------------------------------------------------ test_that("assert_same_length working correctly", { expect_true(assert_same_length(1:3, c("a", "b", "c"))) expect_error(assert_same_length(NULL)) expect_error(assert_same_length(1:3, c("a", "b"))) }) #------------------------------------------------ test_that("assert_same_length_multiple working correctly", { expect_true(assert_same_length_multiple(1:3, c("a", "b", "c"), list("foo", 1, 0.5))) expect_true(assert_same_length_multiple(NULL)) expect_error(assert_same_length_multiple(1:3, c("a", "b"))) }) #------------------------------------------------ test_that("assert_2d working correctly", { expect_true(assert_2d(matrix(NA,3,3))) expect_true(assert_2d(matrix(NA,0,0))) expect_true(assert_2d(data.frame(1:3,1:3))) expect_error(assert_2d(NULL)) expect_error(assert_2d(5)) expect_error(assert_2d(array(NA, dim = c(2,3,4)))) }) #------------------------------------------------ test_that("assert_nrow working correctly", { expect_true(assert_nrow(matrix(NA,3,3), 3)) expect_true(assert_nrow(data.frame(1:5,1:5), 5)) expect_error(assert_nrow(NULL, 3)) expect_error(assert_nrow(3, NULL)) expect_error(assert_nrow(NULL, NULL)) expect_error(assert_nrow(5, 1)) expect_error(assert_nrow(data.frame(1:5,1:5), 4)) }) #------------------------------------------------ test_that("assert_ncol working correctly", { expect_true(assert_ncol(matrix(NA,3,3), 3)) expect_true(assert_ncol(data.frame(1:5,1:5), 2)) expect_error(assert_ncol(NULL, 3)) expect_error(assert_ncol(3, NULL)) expect_error(assert_ncol(NULL, NULL)) expect_error(assert_ncol(5, 1)) expect_error(assert_ncol(data.frame(1:5,1:5), 3)) }) #------------------------------------------------ test_that("assert_dim working correctly", { expect_true(assert_dim(matrix(NA,3,3), c(3,3))) expect_true(assert_dim(data.frame(1:5,1:5), c(5,2))) expect_error(assert_dim(NULL, 3)) expect_error(assert_dim(3, NULL)) expect_error(assert_dim(NULL, NULL)) expect_error(assert_dim(5, 1)) expect_error(assert_dim(data.frame(1:5,1:5), c(3,2))) expect_error(assert_dim(data.frame(1:5,1:5), c(5,3))) }) #------------------------------------------------ test_that("assert_square_matrix working correctly", { expect_true(assert_square_matrix(matrix(0, 3, 3))) expect_error(assert_square_matrix(NULL)) expect_error(assert_square_matrix(matrix(0, 2, 3))) expect_error(assert_square_matrix(1)) expect_error(assert_square_matrix(1:5)) expect_error(assert_square_matrix("foo")) }) #------------------------------------------------ test_that("assert_symmetric_matrix working correctly", { m0 <- matrix(1:16, 4, 4) m1 <- m0 + t(m0) expect_true(assert_symmetric_matrix(m1)) expect_error(assert_symmetric_matrix(NULL)) expect_error(assert_symmetric_matrix(m0)) expect_error(assert_symmetric_matrix(1)) expect_error(assert_symmetric_matrix(1:5)) expect_error(assert_symmetric_matrix("foo")) }) #------------------------------------------------ test_that("assert_noduplicates working correctly", { expect_true(assert_noduplicates(5)) expect_true(assert_noduplicates(1:5)) expect_true(assert_noduplicates(c("foo", "bar"))) expect_true(assert_noduplicates(NULL)) expect_error(assert_noduplicates(c(1,1,2))) expect_error(assert_noduplicates(c("foo", "bar", "foo"))) }) #------------------------------------------------ test_that("assert_file_exists working correctly", { DESCRIPTION_location <- system.file("DESCRIPTION", package = 'drjacoby', mustWork = TRUE) expect_true(assert_file_exists(DESCRIPTION_location)) expect_error(assert_file_exists(NULL)) expect_error(assert_file_exists(4)) expect_error(assert_file_exists("foobar")) }) #------------------------------------------------ test_that("assert_increasing working correctly", { expect_true(assert_increasing(1)) expect_true(assert_increasing(rep(1,5))) expect_true(assert_increasing(-5:5)) expect_error(assert_increasing(NULL)) expect_error(assert_increasing(5:-5)) expect_error(assert_increasing("foo")) }) #------------------------------------------------ test_that("assert_decreasing working correctly", { expect_true(assert_decreasing(1)) expect_true(assert_decreasing(rep(1,5))) expect_true(assert_decreasing(5:-5)) expect_error(assert_decreasing(NULL)) expect_error(assert_decreasing(-5:5)) expect_error(assert_decreasing("foo")) })