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
cdb9c0fe2922832106b99617747ccf897e0d95c4
1e7503a32f037d8e4826d66911f7a96950841690
/R/emigration_map.R
0f60afc46efe8d962c9e752d590b9629e9a6dcd0
[ "Apache-2.0" ]
permissive
willettk/nobel
bd7dcf6c1bdaee9839cafe684c5cc97147dacee7
df7dd5f48735e84425e5eb2c62aac0d54636e9a9
refs/heads/master
2021-01-19T18:17:32.077865
2018-08-16T01:54:07
2018-08-16T01:54:07
68,550,062
0
0
null
null
null
null
UTF-8
R
false
false
2,433
r
emigration_map.R
# Function for drawing arrows on paths arrowLine <- function(x, y, color,N=2){ lengths <- c(0, sqrt(diff(x)^2 + diff(y)^2)) l <- cumsum(lengths) tl <- l[length(l)] el <- seq(0, to=tl, length=N+1)[-1] for(ii in el){ int <- findInterval(ii, l) xx <- x[int:(int+1)] yy <- y[int:(int+1)] ## points(xx,yy, col="grey", cex=0.5) dx <- diff(xx) dy <- diff(yy) new.length <- ii - l[int] segment.length <- lengths[int+1] ratio <- new.length / segment.length xend <- x[int] + ratio * dx yend <- y[int] + ratio * dy #points(xend,yend, col="white", pch=19) arrows(x[int], y[int], xend, yend, length=0.1,col=color) } } # Limits for certain zooms on continents xlim_europe <- c(-25, 45) ylim_europe <- c(35, 71) # Create palette for paths based on counts pal <- colorRampPalette(c("#f2f2f2","green")) colors <- pal(100) maxcnt <- max(nobel$cnt) # Generate map map('world',col='#787878',fill=TRUE,bg='black',lwd=0.20,xlim=xlim_europe,ylim=ylim_europe) # Sort by count so most common paths are on top nobel <- nobel[order(nobel$cnt),] # Loop over unique paths for (j in 1:length(nobel$lon1)) { # Compute great circle inter<-gcIntermediate(c(nobel$lon1[j],nobel$lat1[j]),c(nobel$lon2[j],nobel$lat2[j]),n=500,addStartEnd=TRUE,breakAtDateLine=TRUE) colindex <- round( (nobel$cnt[j] / maxcnt) * length(colors) ) # Break line if it crosses International Date Line; draw in two pieces if(length(inter)==2){ lines(inter[[1]],col=colors[colindex],lwd=1.2) lines(inter[[2]],col=colors[colindex],lwd=1.2) } # Draw single line if it doesn't cross IDL else{ lines(inter,col=colors[colindex],lwd=1.2) arrowLine(inter[,1],inter[,2],colors[colindex]) } } # Laureates who died in their birth country or are not dead # load file nobel_points <- read.table('../data/points_r.csv',header=TRUE) nobel_points <- nobel_points[order(nobel_points$cnt),] # Loop over unique points for (j in 1:length(nobel_points$lon1)) { size_points <- log10(nobel_points$cnt[j]) + 1 points(x=nobel_points$lon1[j],y=nobel_points$lat1[j],pch=21,col="orange",cex=size_points) } # title title(main='Nobel laureate emigration patterns',col.main="white",sub="1901-2013",col.sub="white") # legend legend(60, -15, c("1", "10", "100"), col = "orange", text.col = "black", pch = 21, y.intersp=1.3,cex = 0.8, pt.cex=c(1,2,3), bg = "gray90")
b9102d6ccb093f91da0feacb54c695969551f67b
11e7058fe6c009ff63b7977c6d5fd3ae426c817d
/f20-IBEVAR/figure20.R
49cb13fc72c9a24a92407cee0b275fe46e1336d6
[]
no_license
energy-modelling-toolkit/figures-JRC-report-power-system-and-climate-variability
77d37a835761e28d6d59002c164ee88d67793e26
ef4e431d2de5dc3d31c5e82af4edec3c1f9b1e41
refs/heads/master
2022-05-27T15:29:33.119267
2020-04-30T10:57:22
2020-04-30T10:57:22
259,654,008
0
0
null
null
null
null
UTF-8
R
false
false
1,089
r
figure20.R
# This code has been used to generate the figures in the following report: # De Felice, M., Busch, S., Kanellopoulos, K., Kavvadias, K. and Hidalgo Gonzalez, I., # Power system flexibility in a variable climate, # ISBN 978-92-76-18183-5 (online), doi:10.2760/75312 (online) # This code is released under Creative Commons Attribution 4.0 International (CC BY 4.0) licence # (https://creativecommons.org/licenses/by/4.0/). library(tidyverse) library(ggrepel) toplot <- read_csv("data_figure20.csv") g <- ggplot(toplot, aes(x = `Hydro-power`, y = `Solar & Wind`)) + geom_point(aes(fill = intensity, size = cost_per_mwh), pch = 21 ) + geom_text_repel( aes(label = label), point.padding = unit(1, "lines"), box.padding = unit(0.3, "lines"), segment.size = 0.5, force = 1, segment.color = "grey50", nudge_y = ifelse(toplot$id == 1996, -3, 5), size = 2.5 ) + theme_light() + scale_size_continuous(name = "EUR/MWh") + scale_fill_viridis_c(name = expression(gCO[2] / kWh)) ggsave(filename = "figure20.png", width = 6 * 1.3, height = 3.2 * 1.3)
f2e1f9ad8357419e58a8810ff35f7613d891f891
1b7d9b59fbc41a83f204a7678ae1e9837a1aea22
/scripts/XX_centre_of_gravity_plots.R
610108438aff03e49bfc1e5c88a3cc93ca9c9d87
[]
no_license
HelloMckenna/WKFISHDISH
3ea6b1c5bdf5f112a4d7337d617330b8569748d2
d170b6848814e5c3617b8a658f22c42088e5a577
refs/heads/master
2021-01-19T06:20:10.065618
2016-12-01T09:30:52
2016-12-01T09:30:52
null
0
0
null
null
null
null
UTF-8
R
false
false
1,791
r
XX_centre_of_gravity_plots.R
# ------------------------------------- # # Fit density surface for each species and survey # # ------------------------------------- source("scripts/header.R") # read in spatial datasets load("input/spatial_model_data.rData") if (!dir.exists("figures")) dir.create("figures") plot.report <- function(df) { if (nrow(df$data[[1]]) == 0) return(NULL) layout(matrix(c(1,1,2,3), 2, 2, byrow = TRUE), heights = c(1.5,1)) plot(df$statrec[[1]], main = paste0(df$species, " ",df$Survey, " Q", df$Quarter), border = grey(0.5, alpha=0.5)) #plot(area, border = grey(0.7, alpha=0.5), add = TRUE) pdat <- df %>% unnest(data) %>% unnest(cg, cg_ci) lines(pdat$y, pdat$x) years <- pdat$Year - min(pdat$Year) + 1 nyears <- max(years) cols <- colorRampPalette(c("cyan", "magenta"))(nyears) points(pdat$y, pdat$x, col = cols[years], pch = 16) plot(pdat$Year, pdat$x, type = "l", ylim = range(pdat$x, pdat$x.ciu, pdat$x.cil), axes = FALSE, ylab = "Latitude", xlab = "Year") points(pdat$Year, pdat$x) lines(pdat$Year, pdat$x.cil, lty = 2) lines(pdat$Year, pdat$x.ciu, lty = 2) axis(1); axis(2, las = 1); box(bty="l") plot(pdat$Year, pdat$y, type = "l", ylim = range(pdat$y, pdat$y.ciu, pdat$y.cil), axes = FALSE, ylab = "Longitude", xlab = "Year") points(pdat$Year, pdat$y) lines(pdat$Year, pdat$y.cil, lty = 2) lines(pdat$Year, pdat$y.ciu, lty = 2) axis(1); axis(2, las = 1); box(bty="l") } selected.species <- "Norway Pout" for (selected.species in unique(getControlTable()$Species)) { load(paste0("output/", selected.species, "_centre_gravity.rData")) # plot pdf(paste0("figures/", selected.species, "_centre_gravity.pdf"), onefile = TRUE, paper = "a4") tmp <- sapply(1:nrow(data), function(i) plot.report(data[i,])) dev.off() }
187305c19ff8a3cdca0dc24db0dabd72c428e3a8
bb48af2d119db733039cacc40b5c2ad75565edbb
/01Data/ETL_dominant_race.R
c94f349ffdd663166c7c01b62a25903ecd425fdf
[]
no_license
CannataUTDV/s17dvfinalproject-dvproject5-wilczek-lopez-perez-pant
5253f9df17d21c833e78cabd4e23147792b57c3e
f44c70a977eab274e22769c7c595cc9a32c4583c
refs/heads/master
2021-01-20T04:50:36.757034
2017-05-02T17:17:58
2017-05-02T17:17:58
89,740,812
0
0
null
null
null
null
UTF-8
R
false
false
1,772
r
ETL_dominant_race.R
require(readr) require(plyr) # Set the Working Directory to the 00 Doc folder file_path = "../01Data/dominant_race.csv" df <- readr::read_csv(file_path) print(head(df)) measures <- c() dimensions <- setdiff(names(df), measures) # Get rid of special characters in each column. for(n in names(df)) { df[n] <- data.frame(lapply(df[n], gsub, pattern="[^ -~]",replacement= "")) } na2emptyString <- function (x) { x[is.na(x)] <- "" return(x) } if( length(dimensions) > 0) { for(d in dimensions) { # Get rid of " and ' in dimensions. df[d] <- data.frame(lapply(df[d], gsub, pattern="[\"']",replacement= "")) # Change & to and in dimensions. #put spaces between lowercase and upercase eg. NorthAmerica -> North America df[d] <- data.frame(lapply(df[d], gsub, pattern="([a-z])([A-Z])",replacement= "\\1 \\2")) #Korea,Republicof -> Republic of Korea df[d] <- data.frame(lapply(df[d], gsub, pattern="Korea,Republicof",replacement= "Republic of Korea")) # Bosniaand Herzegovina -> Bosnia and Herzegovina df[d] <- data.frame(lapply(df[d], gsub, pattern="and ",replacement= " and ")) } } na2zero <- function (x) { x[is.na(x)] <- 0 return(x) } # Get rid of all characters in measures except for numbers, the - sign, and period.dimensions, and change NA to 0. if( length(measures) > 1) { for(m in measures) { df[m] <- data.frame(lapply(df[m], gsub, pattern="[^--.0-9]",replacement= "")) #df[m] <- data.frame(lapply(df[m], na2zero)) df[m] <- data.frame(lapply(df[m], function(x) as.numeric(as.character(x)))) # This is needed to turn measures back to numeric because gsub turns them into strings. } } write.csv(df, file="../01Data/dominant_race.csv", row.names=FALSE, na = "NA") print(head(df))
3844f3218339aec6015a12baa5ac3e60740f5faa
bc2f20832f789add3a32d76c0df09ce0ee6158e2
/R/help.R
ad90ab75e2b80eed1d1eac2933e851174cf2db70
[]
no_license
ehsanx/matchingWeight
c8f35b7a2545d7dfd67ec04e5847fe9bb7f98cb7
d6fa1db9fa69dd8eba66d509d7c14ba12cda6dc3
refs/heads/master
2021-01-03T19:20:16.214997
2014-08-26T18:39:10
2014-08-26T18:39:10
null
0
0
null
null
null
null
UTF-8
R
false
false
479
r
help.R
##################################################################################################### # Package documentation ##################################################################################################### #' @title ggrfsrc package for smooth plotting of \code{\link{randomForestSRC}} objects. #' #' @description ggrfsrc is an add on package for \code{\link{randomForestSRC}}. #' #' #' @docType package #' @name ggrfsrc-package #' ################ NULL
d316e4204a505b19820f1149aa05580840995444
681241d52b64bbe04ac45dc474aea2e07c4a399b
/run_analysis.R
4aad581dfd94e61abe093fb3c26fe4845b3f8933
[]
no_license
dirkpadfield/getting_and_cleaning_data
6b53c817284bc49787e823e79e3493e8bc9e382e
195ec85f1f57df33fd82a67a6c6ad816cd4dbe7f
refs/heads/master
2020-06-04T15:03:23.527765
2015-08-23T08:41:14
2015-08-23T08:41:14
41,239,385
0
0
null
null
null
null
UTF-8
R
false
false
2,751
r
run_analysis.R
library(dplyr) # This code reads a set of data and labels that are stored in multiple files and joins them together into a coherent dataframe. # It also summarizes a subset of the columns to generate a tidy dataset. # Merge the training and the test sets to create one data set. # Read the train data X_train <- read.csv("UCI HAR Dataset/train/X_train.txt",header=FALSE,sep="") y_train <- read.csv("UCI HAR Dataset/train/y_train.txt",header=FALSE) # Read the test data X_test <- read.csv("UCI HAR Dataset/test/X_test.txt",header=FALSE,sep="") y_test <- read.csv("UCI HAR Dataset/test/y_test.txt",header=FALSE) # Merge the datasets together by rows data <- rbind(X_train,X_test) # Merge the activities by rows activities <- rbind(y_train,y_test) activities <- activities[[1]] # Read the column names feature_names <- read.csv("UCI HAR Dataset/features.txt",header=FALSE,sep="") feature_names <- as.character(feature_names$V2) # Extract only the measurements on the mean and standard deviation for each measurement. # Get the columns that have the word "mean" mean_columns <- grep("mean",feature_names) # Get the columns that have the word "std" std_columns <- grep("std",feature_names) # We sort the column numbers so that the order is the same as in the original data col_numbers = sort(c(mean_columns,std_columns)) feature_names = feature_names[col_numbers] data <- data[,col_numbers] # Appropriately label the data set with descriptive variable names. # We use the feature_names as the labels for the variable names. colnames(data) <- feature_names # Use descriptive activity names to name the activities in the data set # Read the activity labels activity_labels <- read.csv("UCI HAR Dataset/activity_labels.txt",header=FALSE,sep="") activity_labels <- as.character(activity_labels$V2) # Add the activities to the dataframe data <- mutate(data,activities = factor(activities,labels = activity_labels)) # 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. # Read the subject data. subject_train <- read.csv("UCI HAR Dataset/train/subject_train.txt",header=FALSE) subject_test <- read.csv("UCI HAR Dataset/test/subject_test.txt",header=FALSE) subjects <- rbind(subject_train,subject_test) subjects <- subjects[[1]] # Add the subjects to the dataframe data <- mutate(data,subjects = factor(subjects)) # Create the tidy_data using the summarize_each function from dplyr tidy_data = data %>% group_by(activities,subjects) %>% summarise_each(funs(mean)) # Write out the table write.table(tidy_data,file="tidy_data.txt",row.name=FALSE) # Read the table back in to view the result tidy_data <- read.table("tidy_data.txt", header = TRUE) View(tidy_data)
42d0f987ba5fb2ca2ba9f168663c87b1126b6b64
b5a1fdc3a50b2a87fd0cf26042b108727730afbf
/PlotVacantVsTotalUnitsV2.R
0427825126903c1477c2c3ea146963860550a626
[]
no_license
drjanieforbes/VacanciesVisualization
0000c7a17ddf555e67787963e7539b10ba7380f9
0fa15df6b44ad764e34c777e358f7c9747ffbff1
refs/heads/master
2020-05-25T15:14:53.642111
2017-03-30T19:19:05
2017-03-30T19:19:05
84,943,112
0
0
null
null
null
null
UTF-8
R
false
false
20,706
r
PlotVacantVsTotalUnitsV2.R
# ################################################################## # Author: Dolores Jane Forbes # # Date: 03/10/2017 # # Email: dolores.j.forbes@census.gov # # File: PlotVacantVsTotalUnitsV2.R Version 2 # # Branch: Geographic Research & Innovation Staff/Geography # # ################################################################## # # Using R version 3.2.2 (2015-08-14) -- "Fire Safety" # # This file reads summary files generated from a Python script: # ProcessHUDfilesForVizWithFnV2.py # # The summary files consist of residential vacancy statistics # at multiple scales: national, state, county, and census tract. # # This script opens and reads each of these files, and generates # tables of statistics based on percentages. Each of the scales # is then visualized as a time series of percentage statistics. # # ################################################################## # # Modules: # # 1) Checks/sets the working directory # 2) Opens each of the separate scale summary files: # national.csv # state.csv # county.csv # tract.csv # # ################################################################## # ################################################################## # load libraries # ################################################################## library(foreign) library(plotly) # ################################################################## # environment settings # ################################################################## options(scipen=999) # ################################################################## # constants # ################################################################## NUMTRACTS = 73767 # ################################################################## # check to see if working directory has already been set # ################################################################## # version for on site work #if(!getwd() == "T:/$$JSL/Janie/Private/VacantHouses") { # oldwd = getwd() # setwd("T:/$$JSL/Janie/Private/VacantHouses") #} # version for telework site (home) if(!getwd() == "C:/CensusProjs/HUDData/VacantHouses") { oldwd = getwd() setwd("C:/CensusProjs/HUDData/VacantHouses") } # ################################################################## # process the national level file # ################################################################## national.data <- read.csv(file="./HUD/national.csv", header=TRUE, sep=",") # create empty list my.vector = list() # create empty data frame my.df <- data.frame(matrix(ncol = ncol(national.data)-1, nrow = nrow(national.data))) colnames(my.df) <- c("Month.Year", "VAC_3_RESpc", "VAC_3_6_RESpc", "VAC_6_12_RESpc", "VAC_12_24_RESpc", "VAC_24_36_RESpc", "VAC_36_RESpc", "AVG_DAYS_VAC", "RES_VACpc", "AMS_RES") for (i in 1:nrow(national.data)) { my.vector <- as.character(national.data$Month.Year[i]) if (national.data$totalAllRES_VAC[i] != 0) { my.vector <- c(my.vector, (national.data$totalAllVAC_3_RES[i] / national.data$totalAllRES_VAC[i]), (national.data$totalAllVAC_3_6_R[i] / national.data$totalAllRES_VAC[i]), (national.data$totalAllVAC_6_12R[i] / national.data$totalAllRES_VAC[i]), (national.data$totalAllVAC_12_24R[i] / national.data$totalAllRES_VAC[i]), (national.data$totalAllVAC_24_36R[i] / national.data$totalAllRES_VAC[i]), (national.data$totalAllVAC_36_RES[i] / national.data$totalAllRES_VAC[i]), (national.data$totalAllAVG_VAC_R[i]), # calculated in Python # using a constant!!!!! # (sum(national.data$totalAllAVG_VAC_R[i])/NUMTRACTS), (national.data$totalAllRES_VAC[i] / national.data$totalAllAMS_RES[i]), (national.data$totalAllAMS_RES[i])) } else { my.vector <- c(my.vector,0,0,0,0,0,0, #sum(national.data$totalAllAVG_VAC_R[i])/73767,0,0) national.data$totalAllAVG_VAC_R[i],0,0) } # append to the data frame my.df[i,] <- my.vector # reset the vector to empty my.vector = list() } head(my.df) # ################################################################## # plot the national level file # ################################################################## trace1 <- list( x = as.numeric(my.df$VAC_3_RESpc)*100, y = my.df$Month.Year, marker = list(color = "rgb(17, 78, 166)"), name = "0-3 mo", orientation = "h", type = "bar", uid = "063b98", xsrc = "Dreamshot:4231:b631ec", ysrc = "Dreamshot:4231:b4bc0c" ) trace2 <- list( x = as.numeric(my.df$VAC_3_6_RESpc)*100, y = my.df$Month.Year, marker = list(color = "rgb(41, 128, 171)"), name = "3-6 mo", orientation = "h", type = "bar", uid = "d2ea67", xsrc = "Dreamshot:4231:9a1926", ysrc = "Dreamshot:4231:b4bc0c" ) trace3 <- list( x = as.numeric(my.df$VAC_6_12_RESpc)*100, y = my.df$Month.Year, marker = list(color = "rgb(104, 157, 46)"), name = "6-12 mo", orientation = "h", type = "bar", uid = "5e63a2", xsrc = "Dreamshot:4231:2ec534", ysrc = "Dreamshot:4231:b4bc0c" ) trace4 <- list( x = as.numeric(my.df$VAC_12_24_RESpc)*100, y = my.df$Month.Year, marker = list(color = "rgb(36, 118, 23)"), name = "12-24 mo", orientation = "h", type = "bar", uid = "24f079", xsrc = "Dreamshot:4231:c7663a", ysrc = "Dreamshot:4231:b4bc0c" ) trace5 <- list( x = as.numeric(my.df$VAC_24_36_RESpc)*100, y = my.df$Month.Year, marker = list(color = "rgb(169, 140, 31)"), name = "24-36 mo", orientation = "h", type = "bar", uid = "ae6448", xsrc = "Dreamshot:4231:8f7c41", ysrc = "Dreamshot:4231:b4bc0c" ) trace6 <- list( x = as.numeric(my.df$VAC_36_RESpc)*100, y = my.df$Month.Year, marker = list(color = "rgb(178, 81, 28)"), name = "36+ mo", orientation = "h", type = "bar", uid = "173fcb", xsrc = "Dreamshot:4231:a324f1", ysrc = "Dreamshot:4231:b4bc0c" ) data <- list(trace1, trace2, trace3, trace4, trace5, trace6) layout <- list( # changed autosize to TRUE here autosize = TRUE, bargap = 0.05, bargroupgap = 0.15, barmode = "stack", boxgap = 0.3, boxgroupgap = 0.3, boxmode = "overlay", dragmode = "zoom", font = list( color = "rgb(255, 255, 255)", family = "'Open sans', verdana, arial, sans-serif", size = 12 ), height = 700, hidesources = FALSE, hovermode = "x", legend = list( x = 1.11153846154, y = 1.01538461538, bgcolor = "rgba(255, 255, 255, 0)", bordercolor = "rgba(0, 0, 0, 0)", borderwidth = 1, font = list( color = "", family = "", size = 0 ), traceorder = "normal", xanchor = "auto", yanchor = "auto" ), margin = list( r = 80, t = 100, autoexpand = TRUE, b = 80, l = 100, pad = 0 ), paper_bgcolor = "rgb(67, 67, 67)", plot_bgcolor = "rgb(67, 67, 67)", separators = ".,", showlegend = TRUE, smith = FALSE, title = "National Level (United States)<br>Percent Units Vacant by Length of Time", titlefont = list( color = "rgb(255, 255, 255)", family = "", size = 0 ), width = 700, xaxis = list( anchor = "y", autorange = TRUE, autotick = TRUE, domain = c(0, 1), dtick = 20, exponentformat = "e", gridcolor = "#ddd", gridwidth = 1, linecolor = "#000", linewidth = 1, mirror = FALSE, nticks = 0, overlaying = FALSE, position = 0, range = c(0, 105.368421053), rangemode = "normal", showexponent = "all", showgrid = FALSE, showline = FALSE, showticklabels = TRUE, tick0 = 0, tickangle = "auto", tickcolor = "#000", tickfont = list( color = "", family = "", size = 0 ), ticklen = 5, ticks = "", tickwidth = 1, title = "<br><i>Data Source: Housing & Urban Development</i>", titlefont = list( color = "", family = "", size = 0 ), type = "linear", zeroline = FALSE, zerolinecolor = "#000", zerolinewidth = 1 ), yaxis = list( anchor = "x", autorange = TRUE, autotick = TRUE, # added this so that the order is preserved on the output categoryorder = "trace", domain = c(0, 1), dtick = 1, exponentformat = "e", gridcolor = "#ddd", gridwidth = 1, linecolor = "#000", linewidth = 1, mirror = FALSE, nticks = 0, overlaying = FALSE, position = 0, range = c(-0.5, 23.5), rangemode = "normal", showexponent = "all", showgrid = FALSE, showline = FALSE, showticklabels = TRUE, tick0 = 0, tickangle = "auto", tickcolor = "#000", tickfont = list( color = "", family = "", size = 0 ), ticklen = 5, ticks = "", tickwidth = 1, title = "", titlefont = list( color = "", family = "", size = 0 ), type = "category", zeroline = FALSE, zerolinecolor = "#000", zerolinewidth = 1 ) ) p <- plot_ly(width=layout$width,height=layout$height) p <- add_trace(p, x=trace1$x, y=trace1$y, marker=trace1$marker, name=trace1$name, orientation=trace1$orientation, type=trace1$type, uid=trace1$uid, xsrc=trace1$xsrc, ysrc=trace1$ysrc) p <- add_trace(p, x=trace2$x, y=trace2$y, marker=trace2$marker, name=trace2$name, orientation=trace2$orientation, type=trace2$type, uid=trace2$uid, xsrc=trace2$xsrc, ysrc=trace2$ysrc) p <- add_trace(p, x=trace3$x, y=trace3$y, marker=trace3$marker, name=trace3$name, orientation=trace3$orientation, type=trace3$type, uid=trace3$uid, xsrc=trace3$xsrc, ysrc=trace3$ysrc) p <- add_trace(p, x=trace4$x, y=trace4$y, marker=trace4$marker, name=trace4$name, orientation=trace4$orientation, type=trace4$type, uid=trace4$uid, xsrc=trace4$xsrc, ysrc=trace4$ysrc) p <- add_trace(p, x=trace5$x, y=trace5$y, marker=trace5$marker, name=trace5$name, orientation=trace5$orientation, type=trace5$type, uid=trace5$uid, xsrc=trace5$xsrc, ysrc=trace5$ysrc) p <- add_trace(p, x=trace6$x, y=trace6$y, marker=trace6$marker, name=trace6$name, orientation=trace6$orientation, type=trace6$type, uid=trace6$uid, xsrc=trace6$xsrc, ysrc=trace6$ysrc) #p <- add_trace(p, x=trace7$x, y=trace7$y, marker=trace7$marker, name=trace7$name, orientation=trace7$orientation, type=trace7$type, uid=trace7$uid, xsrc=trace7$xsrc, ysrc=trace7$ysrc) # removed 'bargroupgap', 'boxgap', 'boxgroupgap', 'boxmode' (deprecated?) p <- layout(p, autosize=layout$autosize, bargap=layout$bargap, barmode=layout$barmode, dragmode=layout$dragmode, font=layout$font, hidesources=layout$hidesources, hovermode=layout$hovermode, legend=layout$legend, margin=layout$margin, paper_bgcolor=layout$paper_bgcolor, plot_bgcolor=layout$plot_bgcolor, separators=layout$separators, showlegend=layout$showlegend, smith=layout$smith, title=layout$title, titlefont=layout$titlefont, xaxis=layout$xaxis, yaxis=layout$yaxis) p # ################################################################## # process the state level file # ################################################################## state.data <- read.csv(file="./HUD/state.csv", header=TRUE, quote = "\"", sep=",") # create empty list my.vector = list() # create empty data frame my.df <- data.frame(matrix(ncol = ncol(state.data), nrow = nrow(state.data))) colnames(my.df) <- c("Month.Year", "GEOID", "VAC_3_RESpc", "VAC_3_6_RESpc", "VAC_6_12_RESpc", "VAC_12_24_RESpc", "VAC_24_36_RESpc", "VAC_36_RESpc", "AVG_DAYS_VAC", "RES_VACpc", "AMS_RES") for (state.data$GEOID %in% as.factor(state.data$GEOID)): print(i) my.vector <- as.character(state.data$Month.Year[i]) if (state.data$totalAllRES_VAC[i] != 0) { my.vector <- c(my.vector, (state.data$totalAllVAC_3_RES[i] / state.data$totalAllRES_VAC[i]), (state.data$totalAllVAC_3_6_R[i] / state.data$totalAllRES_VAC[i]), (state.data$totalAllVAC_6_12R[i] / state.data$totalAllRES_VAC[i]), (state.data$totalAllVAC_12_24R[i] / state.data$totalAllRES_VAC[i]), (state.data$totalAllVAC_24_36R[i] / state.data$totalAllRES_VAC[i]), (state.data$totalAllVAC_36_RES[i] / state.data$totalAllRES_VAC[i]), (state.data$totalAllAVG_VAC_R[i]), # calculated in Python # using a constant!!!!! # (sum(state.data$totalAllAVG_VAC_R[i])/NUMTRACTS), (state.data$totalAllRES_VAC[i] / state.data$totalAllAMS_RES[i]), (state.data$totalAllAMS_RES[i])) } else { my.vector <- c(my.vector,0,0,0,0,0,0, #sum(state.data$totalAllAVG_VAC_R[i])/73767,0,0) state.data$totalAllAVG_VAC_R[i],0,0) } # append to the data frame my.df[i,] <- my.vector # reset the vector to empty my.vector = list() } head(my.df) # ################################################################## # plot the state level file # ################################################################## trace1 <- list( x = as.numeric(my.df$VAC_3_RESpc)*100, y = my.df$Month.Year, marker = list(color = "rgb(17, 78, 166)"), name = "0-3 mo", orientation = "h", type = "bar", uid = "063b98", xsrc = "Dreamshot:4231:b631ec", ysrc = "Dreamshot:4231:b4bc0c" ) trace2 <- list( x = as.numeric(my.df$VAC_3_6_RESpc)*100, y = my.df$Month.Year, marker = list(color = "rgb(41, 128, 171)"), name = "3-6 mo", orientation = "h", type = "bar", uid = "d2ea67", xsrc = "Dreamshot:4231:9a1926", ysrc = "Dreamshot:4231:b4bc0c" ) trace3 <- list( x = as.numeric(my.df$VAC_6_12_RESpc)*100, y = my.df$Month.Year, marker = list(color = "rgb(104, 157, 46)"), name = "6-12 mo", orientation = "h", type = "bar", uid = "5e63a2", xsrc = "Dreamshot:4231:2ec534", ysrc = "Dreamshot:4231:b4bc0c" ) trace4 <- list( x = as.numeric(my.df$VAC_12_24_RESpc)*100, y = my.df$Month.Year, marker = list(color = "rgb(36, 118, 23)"), name = "12-24 mo", orientation = "h", type = "bar", uid = "24f079", xsrc = "Dreamshot:4231:c7663a", ysrc = "Dreamshot:4231:b4bc0c" ) trace5 <- list( x = as.numeric(my.df$VAC_24_36_RESpc)*100, y = my.df$Month.Year, marker = list(color = "rgb(169, 140, 31)"), name = "24-36 mo", orientation = "h", type = "bar", uid = "ae6448", xsrc = "Dreamshot:4231:8f7c41", ysrc = "Dreamshot:4231:b4bc0c" ) trace6 <- list( x = as.numeric(my.df$VAC_36_RESpc)*100, y = my.df$Month.Year, marker = list(color = "rgb(178, 81, 28)"), name = "36+ mo", orientation = "h", type = "bar", uid = "173fcb", xsrc = "Dreamshot:4231:a324f1", ysrc = "Dreamshot:4231:b4bc0c" ) data <- list(trace1, trace2, trace3, trace4, trace5, trace6) layout <- list( # changed autosize to TRUE here autosize = TRUE, bargap = 0.05, bargroupgap = 0.15, barmode = "stack", boxgap = 0.3, boxgroupgap = 0.3, boxmode = "overlay", dragmode = "zoom", font = list( color = "rgb(255, 255, 255)", family = "'Open sans', verdana, arial, sans-serif", size = 12 ), height = 700, hidesources = FALSE, hovermode = "x", legend = list( x = 1.11153846154, y = 1.01538461538, bgcolor = "rgba(255, 255, 255, 0)", bordercolor = "rgba(0, 0, 0, 0)", borderwidth = 1, font = list( color = "", family = "", size = 0 ), traceorder = "normal", xanchor = "auto", yanchor = "auto" ), margin = list( r = 80, t = 100, autoexpand = TRUE, b = 80, l = 100, pad = 0 ), paper_bgcolor = "rgb(67, 67, 67)", plot_bgcolor = "rgb(67, 67, 67)", separators = ".,", showlegend = TRUE, smith = FALSE, title = "National Level (United States)<br>Percent Units Vacant by Length of Time", titlefont = list( color = "rgb(255, 255, 255)", family = "", size = 0 ), width = 700, xaxis = list( anchor = "y", autorange = TRUE, autotick = TRUE, domain = c(0, 1), dtick = 20, exponentformat = "e", gridcolor = "#ddd", gridwidth = 1, linecolor = "#000", linewidth = 1, mirror = FALSE, nticks = 0, overlaying = FALSE, position = 0, range = c(0, 105.368421053), rangemode = "normal", showexponent = "all", showgrid = FALSE, showline = FALSE, showticklabels = TRUE, tick0 = 0, tickangle = "auto", tickcolor = "#000", tickfont = list( color = "", family = "", size = 0 ), ticklen = 5, ticks = "", tickwidth = 1, title = "<br><i>Data Source: Housing & Urban Development</i>", titlefont = list( color = "", family = "", size = 0 ), type = "linear", zeroline = FALSE, zerolinecolor = "#000", zerolinewidth = 1 ), yaxis = list( anchor = "x", autorange = TRUE, autotick = TRUE, # added this so that the order is preserved on the output categoryorder = "trace", domain = c(0, 1), dtick = 1, exponentformat = "e", gridcolor = "#ddd", gridwidth = 1, linecolor = "#000", linewidth = 1, mirror = FALSE, nticks = 0, overlaying = FALSE, position = 0, range = c(-0.5, 23.5), rangemode = "normal", showexponent = "all", showgrid = FALSE, showline = FALSE, showticklabels = TRUE, tick0 = 0, tickangle = "auto", tickcolor = "#000", tickfont = list( color = "", family = "", size = 0 ), ticklen = 5, ticks = "", tickwidth = 1, title = "", titlefont = list( color = "", family = "", size = 0 ), type = "category", zeroline = FALSE, zerolinecolor = "#000", zerolinewidth = 1 ) ) p <- plot_ly(width=layout$width,height=layout$height) p <- add_trace(p, x=trace1$x, y=trace1$y, marker=trace1$marker, name=trace1$name, orientation=trace1$orientation, type=trace1$type, uid=trace1$uid, xsrc=trace1$xsrc, ysrc=trace1$ysrc) p <- add_trace(p, x=trace2$x, y=trace2$y, marker=trace2$marker, name=trace2$name, orientation=trace2$orientation, type=trace2$type, uid=trace2$uid, xsrc=trace2$xsrc, ysrc=trace2$ysrc) p <- add_trace(p, x=trace3$x, y=trace3$y, marker=trace3$marker, name=trace3$name, orientation=trace3$orientation, type=trace3$type, uid=trace3$uid, xsrc=trace3$xsrc, ysrc=trace3$ysrc) p <- add_trace(p, x=trace4$x, y=trace4$y, marker=trace4$marker, name=trace4$name, orientation=trace4$orientation, type=trace4$type, uid=trace4$uid, xsrc=trace4$xsrc, ysrc=trace4$ysrc) p <- add_trace(p, x=trace5$x, y=trace5$y, marker=trace5$marker, name=trace5$name, orientation=trace5$orientation, type=trace5$type, uid=trace5$uid, xsrc=trace5$xsrc, ysrc=trace5$ysrc) p <- add_trace(p, x=trace6$x, y=trace6$y, marker=trace6$marker, name=trace6$name, orientation=trace6$orientation, type=trace6$type, uid=trace6$uid, xsrc=trace6$xsrc, ysrc=trace6$ysrc) #p <- add_trace(p, x=trace7$x, y=trace7$y, marker=trace7$marker, name=trace7$name, orientation=trace7$orientation, type=trace7$type, uid=trace7$uid, xsrc=trace7$xsrc, ysrc=trace7$ysrc) # removed 'bargroupgap', 'boxgap', 'boxgroupgap', 'boxmode' (deprecated?) p <- layout(p, autosize=layout$autosize, bargap=layout$bargap, barmode=layout$barmode, dragmode=layout$dragmode, font=layout$font, hidesources=layout$hidesources, hovermode=layout$hovermode, legend=layout$legend, margin=layout$margin, paper_bgcolor=layout$paper_bgcolor, plot_bgcolor=layout$plot_bgcolor, separators=layout$separators, showlegend=layout$showlegend, smith=layout$smith, title=layout$title, titlefont=layout$titlefont, xaxis=layout$xaxis, yaxis=layout$yaxis) p
5e0451b3340bd721e9209efbecac7ba3a302b3b8
2f4ac698e45acd2509a7a2cfb6444ed44f07129a
/code/search.r
9f12c7d4941512b9998e94fd824fd10366bd9379
[]
no_license
lebebr01/software_pop
63d506c5fda2aad64bf4dce4689c8e40c6ddd110
d3b75c9778c27c43a9e7a2c63f1f4979f6fae1ce
refs/heads/main
2021-07-30T04:37:05.625566
2021-07-20T18:31:26
2021-07-20T18:31:26
218,545,723
0
0
null
null
null
null
UTF-8
R
false
false
10,138
r
search.r
library(pdfsearch) # ------------------------- # Setup soft_keywords <- c('SPSS Statistics', ' R ', 'SAS', 'STATA', 'MATLAB', 'Statistica ', 'Statsoft', 'Java', 'Hadoop', 'Python', 'Minitab', 'Systat', 'JMP', 'SPSS Modeler', 'Tableau', 'Scala', 'Julia', 'Azure Machine', 'Mplus', 'LISREL', 'AMOS', 'BILOG', 'BILOG-MG', 'R-project', 'R project', 'Multilog', 'PARSCALE', 'IRT PRO', 'HLM[0-9]', 'HLM [0-9]', 'SAS Institute', 'SPSS', 'CRAN', 'R software', 'R core team', 'M-Plus', 'RStudio') soft_ignore <- c(FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE) # ------------------------- # AERJ keyword_results_aerj <- keyword_directory(directory = 'C:/Users/bleb/Documents/AERJ.Data/PDF', keyword = soft_keywords, surround_lines = FALSE, ignore_case = soft_ignore, full_names = TRUE, recursive = TRUE, max_search = NULL) keyword_results_aerj$journal <- 'AERJ' save(keyword_results_aerj, file = 'C:/Users/bleb/OneDrive - University of Iowa/JournalArticlesInProgress/software_pop/data/keyword_aerj_v2.rda') # ------------------------- # EEPA keyword_results_eepa <- keyword_directory(directory = 'C:/Users/bleb/Documents/EEPA.Data/PDF', keyword = soft_keywords, surround_lines = FALSE, ignore_case = soft_ignore, split_pdf = TRUE, full_names = TRUE, recursive = TRUE, max_search = NULL) keyword_results_eepa$journal <- 'EEPA' save(keyword_results_eepa, file = 'C:/Users/bleb/OneDrive - University of Iowa/JournalArticlesInProgress/software_pop/data/keyword_eepa_v2.rda') # ------------------------- # JEE keyword_results_jee <- keyword_directory(directory = 'C:/Users/bleb/Documents/JEE.Data/PDF', keyword = soft_keywords, surround_lines = FALSE, ignore_case = soft_ignore, full_names = TRUE, recursive = TRUE, max_search = NULL) keyword_results_jee$journal <- 'JEE' save(keyword_results_jee, file = 'C:/Users/bleb/OneDrive - University of Iowa/JournalArticlesInProgress/software_pop/data/keyword_jee_v2.rda') # ------------------------- # am_j_pol_sci keyword_results_am_j_pol_sci <- keyword_directory(directory = 'C:/Users/bleb/Documents/am_j_pol_sci.Data/PDF', keyword = soft_keywords, split_pdf = TRUE, surround_lines = FALSE, ignore_case = soft_ignore, full_names = TRUE, recursive = TRUE, max_search = NULL) keyword_results_am_j_pol_sci$journal <- 'am_j_pol_sci' save(keyword_results_am_j_pol_sci, file = 'C:/Users/bleb/OneDrive - University of Iowa/JournalArticlesInProgress/software_pop/data/keyword_am_j_pol_sci_v2.rda') # ------------------------- # economic journal keyword_results_ej <- keyword_directory(directory = 'C:/Users/bleb/Documents/ej.Data/PDF', keyword = soft_keywords, surround_lines = FALSE, ignore_case = soft_ignore, full_names = TRUE, recursive = TRUE, max_search = NULL) keyword_results_ej$journal <- 'ej' save(keyword_results_ej, file = 'C:/Users/bleb/OneDrive - University of Iowa/JournalArticlesInProgress/software_pop/data/keyword_ej_v2.rda') # ------------------------- # educational researcher keyword_results_er <- keyword_directory(directory = 'C:/Users/bleb/Documents/ER.Data/PDF', keyword = soft_keywords, split_pdf = TRUE, surround_lines = FALSE, ignore_case = soft_ignore, full_names = TRUE, recursive = TRUE, max_search = NULL) keyword_results_er$journal <- 'er' save(keyword_results_er, file = 'C:/Users/bleb/OneDrive - University of Iowa/JournalArticlesInProgress/software_pop/data/keyword_er_v2.rda') # ------------------------- # HE keyword_results_he <- keyword_directory(directory = 'C:/Users/bleb/Documents/HE.Data/PDF', keyword = soft_keywords, surround_lines = FALSE, ignore_case = soft_ignore, full_names = TRUE, recursive = TRUE, max_search = NULL) keyword_results_he$journal <- 'he' save(keyword_results_he, file = 'C:/Users/bleb/OneDrive - University of Iowa/JournalArticlesInProgress/software_pop/data/keyword_he_v2.rda') # ------------------------- # pol_sci_quar keyword_results_pol_sci_quar <- keyword_directory(directory = 'C:/Users/bleb/Documents/pol_sci_quar.Data/PDF', keyword = soft_keywords, surround_lines = FALSE, ignore_case = soft_ignore, full_names = TRUE, recursive = TRUE, max_search = NULL) keyword_results_pol_sci_quar$journal <- 'pol_sci_quar' save(keyword_results_pol_sci_quar, file = 'C:/Users/bleb/OneDrive - University of Iowa/JournalArticlesInProgress/software_pop/data/keyword_pol_sci_quar_v2.rda') # ------------------------- # pub_policy_admin keyword_results_pub_policy_admin <- keyword_directory(directory = 'C:/Users/bleb/Documents/pub_policy_admin.Data/PDF', keyword = soft_keywords, surround_lines = FALSE, ignore_case = soft_ignore, full_names = TRUE, recursive = TRUE, max_search = NULL) keyword_results_pub_policy_admin$journal <- 'pub_policy_admin' save(keyword_results_pub_policy_admin, file = 'C:/Users/bleb/OneDrive - University of Iowa/JournalArticlesInProgress/software_pop/data/keyword_pub_policy_admin_v2.rda') # ------------------------- # SE keyword_results_SE <- keyword_directory(directory = 'C:/Users/bleb/Documents/SE.Data/PDF', keyword = soft_keywords, split_pdf = TRUE, surround_lines = FALSE, ignore_case = soft_ignore, full_names = TRUE, recursive = TRUE, max_search = NULL) keyword_results_SE$journal <- 'SE' save(keyword_results_SE, file = 'C:/Users/bleb/OneDrive - University of Iowa/JournalArticlesInProgress/software_pop/data/keyword_SE_v2.rda') # ------------------------- # public_policy keyword_results_public_policy <- keyword_directory(directory = 'C:/Users/bleb/Documents/public_policy.Data/PDF', keyword = soft_keywords, surround_lines = FALSE, ignore_case = soft_ignore, full_names = TRUE, recursive = TRUE, max_search = NULL) keyword_results_public_policy$journal <- 'public_policy' save(keyword_results_public_policy, file = 'C:/Users/bleb/OneDrive - University of Iowa/JournalArticlesInProgress/software_pop/data/keyword_public_policy_v2.rda') # ------------------------- # American Economic Journal keyword_results_aej_ae <- keyword_directory(directory = 'C:/Users/bleb/Documents/aej_ae.Data/PDF', keyword = soft_keywords, surround_lines = FALSE, ignore_case = soft_ignore, full_names = TRUE, recursive = TRUE, max_search = NULL) keyword_results_aej_ae$journal <- 'aej_ae' save(keyword_results_aej_ae, file = 'C:/Users/bleb/OneDrive - University of Iowa/JournalArticlesInProgress/software_pop/data/keyword_aej_ae_v2.rda')
2d6260e50cdae9e98d922d9070219de8992d5ce2
cedc620c85b5f34eb2ea5c1aa4b79354e7a57d21
/man/plotPart.Rd
24837c0e587b1f39214ad5f2782e38963fa3b990
[]
no_license
AntonGagin/nanop
35ba062587376eb351c63dcf6a94f5bcb2a4ff96
56211a00fecac9d95cb620189bfb72934ee4b750
refs/heads/master
2021-01-15T22:57:55.806166
2015-09-25T17:23:10
2015-09-25T17:23:10
33,210,645
0
0
null
null
null
null
UTF-8
R
false
false
3,590
rd
plotPart.Rd
\name{plotPart} \Rdversion{1.1} \alias{plotPart} \title{Draws a three-dimensional scatterplot} \description{Function to visualize a nanoparticle using \href{http://CRAN.R-project.org/package=rgl}{rgl} package.} \usage{ plotPart(nanop, radius=0.4, legend=TRUE, col=NA, box=FALSE, play=FALSE, atoms=NA, miller=NA, lattice=c(4.08)) } \arguments{ \item{nanop}{numeric matrix in which each row gives the coordinates of an atomic position in the nanoparticle. If nanop is not an object returned by \code{\link{simPart}} or \code{\link{displacePart}} attributes \code{nAtomTypes}, \code{atomType}, \code{r}, \code{sym}, and \code{symShell} must be set manually; see \code{\link{simPart}}. } \item{radius}{numeric vector or single value. Each atom on a plot is represented by a sphere. \code{radius} defines the sphere radius (radii).} \item{legend}{logical indicating whether to print plot legend.} \item{col}{numeric vector defining colours to be used for plotted items. If vector \code{col} length does not correspond to number of atom types within the particle then standard colouring scheme is used. } \item{box}{logical indicating whether to draw box and axes.} \item{play}{logical. If \code{TRUE} animation with constantly rotating particle is played.} \item{atoms}{character. If not \code{NA} specifies atoms to be displayed, see details.} \item{miller}{numeric vector, specifies Miller indices. If not \code{NA} only the plane in a particle core described by given indices is displayed. Should be given in a form \code{c(h, k, l)} for the non-hexagonal symmetry and \code{c(h, k, i, l)} for the hexagonal symmetry. Should be specified together with \code{lattice} parameter.} \item{lattice}{numeric vector indicating particle core lattice parameters. Should be given in the same form as in \code{\link{simPart}}.} } \value{a vector of object IDs.} \details{ If only core (shell) atoms of a specific type to be plotted \code{atoms} should be set up to \code{"core X"} or \code{"shell X"}, respectively. Character describing atom type \code{"X"} can be taken from attributes(part)$atomsCore or attributes(part)$atomsShell. } \examples{ ## rgl library demands graphical terminal to be available ## uncoment all plotPart() calls for 3D visualization ## simulate particle Au <- createAtom("Cu") Au$name <- "Au" Pd <- createAtom("Cu") Pd$name <- "Pd" part <- simPart(atoms=list(Au), atomsShell=list(Pd), rcore=8) ## 3d scatter plot #plotPart(part, col=c(2,4)) ## increase number of atom types within the particle: Zn <- createAtom("Zn") S <- createAtom("S") part <- simPart(atoms=list(Zn ,S), atomsShell=list(Au), r=14, rcore=12, sym="hcp", symShell="fcc", latticep=c(4.3, 7.04), latticepShell=4.08) ## 3d scatter plot #plotPart(part, col=c(2,4,3)) ## play animation: #plotPart(part, col=c(2,4,3), play=TRUE) ## plot only shell particles #plotPart(part, col=c(2,4,3), atoms="shell Au", play=TRUE) part <- simPart(atoms=list(Zn ,S),r=20, sym="hcp", latticep=c(4.3, 7.04)) ## display plane normal to z-axis: #plotPart(part, miller=c(0, 0, 0 ,1), lattice=c(4.3, 7.04)) ##S atoms: #plotPart(part, miller=c(0, 0, 0 ,1), lattice=c(4.3, 7.04), # atoms = "core S") ## save picture in a file using rgl function: #rgl.snapshot( filename = "plane0001 S atoms.png") Na <- createAtom("Na") Cl <- createAtom("Cl") part <- simPart(atoms=list(Na,Cl), sym="fcc") #plotPart(part, miller=c(1,0,1), box=TRUE, lattice=c(4.08)) ## plot only Na atoms: #plotPart(part, miller=c(1,0,1), box=TRUE, lattice=c(4.08), # atoms = "core Na") } \keyword{visualization}
2498684b3c4bee68abb050012c3f24d829499f7f
e869c00a1e32dd8bc304ceb9e9843e87db91752c
/R/conformal_mapping_code_circlepack.R
493c186c580f28ce0e52e73e539fca2f7c6ff3b1
[ "MIT" ]
permissive
rdinnager/Australia_as_a_circle
68246e7a078181182fa545423dfeb2ff3073157a
5a96a48d5ffab35c98a05975f35bd643d7981dab
refs/heads/master
2021-07-12T19:25:59.362236
2020-10-08T11:15:44
2020-10-08T11:15:44
212,463,175
0
0
null
null
null
null
UTF-8
R
false
false
5,271
r
conformal_mapping_code_circlepack.R
library(rnaturalearth) library(sf) library(maps) library(rmapshaper) library(tidyverse) library(ggplot2) library(ggrepel) library(ggforce) library(distances) library(spdep) library(packcircles) Oz_cities <- world.cities %>% dplyr::filter(country.etc == "Australia", pop > 1000000 | name == "Darwin" | name == "Canberra") %>% sf::st_as_sf(coords = c("long", "lat"), crs = 4326) %>% sf::st_transform(3112) ## Geoscience Australia Lambert Oz_coast <- rnaturalearth::ne_states("Australia", returnclass = "sf") %>% dplyr::filter(code_hasc %in% c("AU.NT", "AU.WA", "AU.CT", "AU.NS", "AU.SA", "AU.VI", "AU.QL")) %>% rmapshaper::ms_filter_islands(1e+14) %>% ## get only mainland Australia rmapshaper::ms_simplify(0.05) %>% ## aggressive simplification to reduce number if 'insets' sf::st_union() %>% sf::st_transform(3112) ## Geoscience Australia Lambert oz <- ggplot(Oz_coast ) + geom_sf(fill = "grey20") + geom_sf(data = Oz_cities, colour = "red", size = 3) + theme_minimal() oz + ggrepel::geom_label_repel( data = Oz_cities, aes(label = name, geometry = geometry), stat = "sf_coordinates", min.segment.length = 0, segment.color = "red", force = 3, direction = "both", max.iter = 50000, nudge_x = 10000, nudge_y = -10000 ) #geom_sf_label(data = Oz_cities, aes(label = name)) + ## We start our circle packing by generating a hexagonal grid on our polygon cellsize <- 100000 hexes <- Oz_coast %>% sf::st_make_grid(cellsize = cellsize, square = FALSE) oz + geom_sf(data = hexes, colour = "white", alpha = 0.6, fill = NA) ## Now we generate circles at each hexagon vertice and centre hex_vert <- Oz_coast %>% sf::st_make_grid(cellsize = cellsize, square = FALSE, what = "polygons") %>% sf::st_cast("POINT") %>% lwgeom::st_snap_to_grid(25) hex_cents <- Oz_coast %>% sf::st_make_grid(cellsize = cellsize, square = FALSE, what = "centers") %>% sf::st_centroid() %>% lwgeom::st_snap_to_grid(25) circ_cents <- c(hex_vert, hex_cents) circ_coords <- circ_cents %>% sf::st_coordinates() %>% dplyr::as_tibble() %>% dplyr::distinct() rad <- (hexes[[1]] %>% sf::st_cast("LINESTRING") %>% sf::st_length()) / 12 oz + ggforce::geom_circle(data = circ_coords, aes(x0 = X, y0 = Y, r = rad), colour = "white") ## Now remove circles with centres outside coast circle_centres <- circ_cents %>% sf::st_as_sf() %>% dplyr::distinct() %>% sf::st_intersection(Oz_coast) ggplot(circle_centres %>% sf::st_coordinates() %>% dplyr::as_tibble(), aes(x0 = X, y0 = Y, r = rad)) + geom_circle() + coord_equal() + theme_minimal() ## Now make a network of tangent circles, discard any not tangent to at least 3 others circle_dists <- circle_centres %>% sf::st_coordinates() %>% distances::distances() closest <- circle_dists %>% distances::nearest_neighbor_search(8) # index <- closest[ , 1] find_tangent_indices <- function(index, rad) { dists <- distances::distance_columns(circle_dists, index, closest[ , index]) rownames(dists)[dists < (2.1 * rad)] %>% as.integer() } tangents <- purrr::map(seq_len(ncol(closest)), ~find_tangent_indices(.x, rad)) class(tangents) <- "nb" tangent_mat <- spdep::nb2mat(tangents, style = "B") nnum <- sapply(tangents, length) - 1 sum(nnum > 6) sum(nnum < 3) ## remove circles with less than 3 tangent circles num_less <- sum(nnum < 3) while(num_less != 0) { circle_centres <- circle_centres[!nnum < 3, ] circle_dists <- circle_centres %>% sf::st_coordinates() %>% distances::distances() closest <- circle_dists %>% distances::nearest_neighbor_search(8) tangents <- purrr::map(seq_len(ncol(closest)), ~find_tangent_indices(.x, rad)) nnum <- sapply(tangents, length) - 1 num_less <- sum(nnum < 3) } sum(nnum < 3) sum(nnum > 6) ggplot(circle_centres %>% sf::st_coordinates() %>% dplyr::as_tibble(), aes(x0 = X, y0 = Y, r = rad)) + geom_circle() + coord_equal() + theme_minimal() nnet <- lapply(seq_along(tangents), function(x) tangents[[x]][tangents[[x]] != x]) pnts <- circle_centres[nnet[[1]], ] %>% sf::st_coordinates() order_points <- function(pnts, clockwise = FALSE) { cent <- apply(pnts, 2, mean) pnts2 <- t(t(pnts) - cent) angles <- atan2(pnts2[ , 2], pnts2[ , 1]) if(clockwise) { indices <- order(angles, decreasing = TRUE) } else { indices <- order(angles) } } coords <- circle_centres %>% sf::st_coordinates() all_pnts <- lapply(nnet, function(x) coords[x, ]) nnet <- lapply(seq_along(all_pnts), function(x) nnet[[x]][order_points(all_pnts[[x]])]) nnet <- lapply(seq_along(nnet), function(x) c(x, nnet[[x]])) internal <- nnet[sapply(nnet, length) == 7] external <- dplyr::tibble(id = which(sapply(nnet, length) < 7), radius = 10000) test <- circleGraphLayout(internal, external) ggplot(test[test$radius != 10000, ], aes(x0 = x, y0 = y, r = radius)) + geom_circle() + theme_minimal() ggplot(test, aes(x0 = x, y0 = y, r = radius)) + geom_circle() + theme_minimal()
e5d32990a22c82a1f5c15542f43099a1048710ec
905ff318e8e26ab8121cef57034e08e459ff041f
/man/sq_numbers_cpp_tbb.Rd
b0d536558ce04323e399f6e25fb2c07e56a4546d
[]
no_license
thijsjanzen/enviDiv
1442568cf490ba3bdd55bafe85c6f89f0f417e47
a67953d35b08eaa305896d4dd799c3b911bb0f5c
refs/heads/master
2021-06-28T13:40:22.413730
2020-09-09T06:29:45
2020-09-09T06:29:45
171,687,841
0
0
null
2019-09-05T11:30:48
2019-02-20T14:26:57
R
UTF-8
R
false
true
380
rd
sq_numbers_cpp_tbb.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/RcppExports.R \name{sq_numbers_cpp_tbb} \alias{sq_numbers_cpp_tbb} \title{test multithreaded works!} \usage{ sq_numbers_cpp_tbb(n, num_threads) } \arguments{ \item{n}{size of vector} \item{num_threads}{number of threads} } \value{ vector of squared numbers } \description{ test multithreaded works! }
2e0fac7256d1a1b863a47ee3519e39952ececbdc
bfd0a3a3e84a6e8cb4f2806ddaf1dd771529cf31
/R/gradethis.R
86a397fded41ec3ce462251b6cfa2271a03a1fd8
[]
no_license
DataScienceProjectsJapan/tutorialR4DS
e4964d1fae6b3f5d211640336da5f91d1efccbe7
6306130615f91add472afd73a1eff72a8f9145e9
refs/heads/main
2023-07-16T05:58:27.700536
2021-08-31T04:28:27
2021-08-31T04:28:27
394,162,367
0
0
null
null
null
null
UTF-8
R
false
false
238
r
gradethis.R
```{r delay-check} gradethis::grade_this_code(correct = "Good work! Shortly we will learn an alternative way to construct a new variable with the mutate() function", incorrect = "Not quite. {code_feedback()} {random_encouragement()}") ```
dfec3ea47ea8fe5263729d0f4981ef5accbd4857
032d5b16e6d9afa5d08cae5e4121b4f2e5e161f6
/map_event.R
0200b0e26c186e0f86e11a7b0da45e3da4d20678
[]
no_license
tysonwepprich/photovoltinism
93d3dca661f97a3bb559c791b3bb7a90670eef67
7c951f4983570bbf9f7c894f887ce57ea2e096a1
refs/heads/master
2022-11-21T21:26:12.152840
2022-11-03T21:54:03
2022-11-03T21:54:03
100,308,351
0
0
null
null
null
null
UTF-8
R
false
false
6,724
r
map_event.R
# Make pest event maps # given a degree-day value, plot date it occurs by raster # could also extract distribution of dates by shapefile polygons library(sp) library(rgdal) library(raster) library(ggplot2) library(viridis) library(mapdata) library(dplyr) library(tidyr) library(geofacet) theme_set(theme_bw(base_size = 16)) # library(gridExtra) # library(grid) gdd_cutoff <- 100 source('CDL_funcs.R') region_param <- "EAST" years <- c(2014:2017) gdd_files <- paste0("dailygdd_", years, "_", region_param, ".grd") REGION <- assign_extent(region_param = region_param) states <- map_data("state", xlim = c(REGION@xmin, REGION@xmax), ylim = c(REGION@ymin, REGION@ymax), lforce = "e") names(states)[1:2] <- c("x", "y") GDD <- brick(gdd_files[1]) template <- GDD[[1]] template[!is.na(template)] <- 0 template <- crop(template, REGION) dflist <- list() for (yr in years){ filename <- gdd_files[grep(pattern = yr, x = gdd_files, fixed = TRUE)] res <- brick(filename) # fix NA problem, just assigned as zero res <- res + template # template is all zeros and NA accum <- calc(res, fun = cumsum) accum <- calc(accum, fun = function(x) {min(which(x >= gdd_cutoff))}) df <- as.data.frame(accum, xy=TRUE) names(df)[3] <- "doy" df$doy[-which(is.finite(df$doy))] <- NA df$year <- yr dflist[[length(dflist)+1]] <- df } resdf <- dplyr::bind_rows(dflist) resdf <- resdf %>% group_by(year) %>% mutate(date = format(as.Date(doy, origin=as.Date(paste0((year[1] - 1), "-12-31"))), format = "%m-%d"), week = lubridate::week(as.Date(doy, origin=as.Date(paste0((year[1] - 1), "-12-31"))))) plt <- ggplot(resdf, aes(x, y)) + geom_raster(aes(fill = week)) + scale_fill_viridis(na.value = "white") + geom_polygon(data = states, aes(group = group), fill = NA, color = "black", size = .1) + facet_wrap(~year, nrow = 2) + coord_fixed(1.3) plt # extract by sites sites <- data.frame(ID = c("Corvallis, OR", "Richland, WA", "JB Lewis-McChord, WA", "Palermo, CA", "Ephrata, WA", "Yakima Training Center, WA", "Camp Rilea, OR", "Ft Drum, NY", "West Point, NY", "Kellogg LTER, MI", "The Wilds, OH", "Duluth, MN", "Coeburn, VA", "Mountain Home AFB, ID", "Quantico MCB, VA", "Hanscom AFB, MA", "Ft Bragg, NC", "Ogden, UT", "Buckley AFB, CO", "S Portland, OR", "Sutherlin, OR", "Bellingham, WA", "Wentzville, MO"), x = c(-123.263, -119.283, -122.53, -121.625360, -119.555424, -120.461073, -123.934759, -75.763566, -73.962210, -85.402260, -81.733314, -92.158597, -82.466417, -115.865101, -77.311254, -71.276231, -79.083248, -112.052908, -104.752266, -122.658887, -123.315854, -122.479482, -90.852), y = c(44.564, 46.275, 47.112, 39.426829, 47.318546, 46.680138, 46.122867, 44.055684, 41.388456, 42.404749, 39.829447, 46.728247, 36.943103, 43.044083, 38.513995, 42.457068, 35.173401, 41.252509, 39.704018, 45.470532, 43.387721, 48.756105, 38.816)) dflist <- list() for (yr in years){ filename <- gdd_files[grep(pattern = yr, x = gdd_files, fixed = TRUE)] res <- brick(filename) # fix NA problem, just assigned as zero res <- res + template # template is all zeros and NA accum <- calc(res, fun = cumsum) accum <- calc(accum, fun = function(x) {min(which(x >= gdd_cutoff))}) e <- raster::extract(accum, sites[, c(2:3)], buffer=1000, fun = mean, na.rm = TRUE) df <- sites df$doy <- e df$year <- yr dflist[[length(dflist)+1]] <- df } resdf <- dplyr::bind_rows(dflist) resdf <- resdf %>% filter(complete.cases(.)) %>% group_by(year) %>% mutate(date = as.Date(doy, origin=as.Date("2000-12-31"))) plt <- ggplot(resdf, aes(x = reorder(ID, date), y = date, color = as.factor(year))) + geom_jitter(size = 3, width = .15) + scale_y_date(date_breaks = "1 week", date_labels = "%b-%d") + coord_flip() + ggtitle("Date when 100 degree-days recorded for Galerucella") plt ggsave(filename = "Galerucella_100DD_EAST.png", plot = plt, device = "png", width = 15, height = 8, units = "in") # Map range of GDD at different sites, 100-150DD dates cutoffday <- 55 # when PRISM observations switch to forecasts # Add new predictions for current year preddf <- gdddf %>% filter(complete.cases(.), year != 2018) %>% mutate(yday = as.numeric(yday)) %>% arrange(yday) %>% group_by(ID, yday) %>% summarise(DD = mean(DD)) %>% filter(yday > cutoffday) %>% mutate(year = "2018+5yrmean") # replace predictions after cutoff day obs <- gdddf %>% select(-x, -y) %>% mutate(yday = as.numeric(yday)) %>% filter(complete.cases(.), year == 2018, yday <= cutoffday) %>% mutate(year = "2018+5yrmean") preds <- bind_rows(preddf, obs) gdddf$year <- as.factor(as.character(gdddf$year)) levels(gdddf$year)[6] <- "2018+10yrmean" resdf <- gdddf %>% select(-x, -y) %>% filter(complete.cases(.)) %>% mutate(yday = as.numeric(yday)) %>% bind_rows(preds) %>% arrange(yday) %>% group_by(year, ID) %>% mutate(AccumDD = cumsum(DD)) %>% filter(AccumDD >= 100) %>% filter(AccumDD <= 150) %>% filter(row_number() == 1L | row_number() == n()) %>% mutate(date = as.Date(yday, origin=as.Date("2000-12-31")), bound = c("start", "end")) %>% dplyr::select(ID, year, date, bound) %>% tidyr::spread(bound, date) %>% # filter(ID %in% levels(gdddf$ID)[c(1, 3, 4, 5, 10, 12, 15, 16, 17, 21, 22, 25, 26, 28, 30)]) %>% # East and West filter(ID %in% levels(gdddf$ID)[c(1, 3, 5, 10, 15, 17, 21, 22, 25, 26, 30)]) %>% # Just NW sites group_by(ID) %>% mutate(meanstart = mean(start)) theme_set(theme_bw(base_size = 16)) plt <- ggplot(resdf, aes(x = reorder(ID, meanstart), ymin = start, ymax = end, group = as.factor(year), color = as.factor(year))) + # geom_jitter(size = 3, width = .15) + geom_linerange(position = position_dodge(width = .6), size = 2) + scale_color_viridis(discrete = TRUE, name = "Year", option = "D") + scale_y_date(date_breaks = "1 week", date_labels = "%b-%d") + coord_flip() + ggtitle("Date range for Galerucella overwintering adult emergence (100-150 degree-days)") + xlab("Sites ordered by\nmean start of emergence") + guides(color = guide_legend(reverse=TRUE)) plt ggsave(filename = "Galerucella_daterange.png", plot = plt, device = "png", width = 15, height = 8, units = "in")
789c1ba001b444e9e7f78ee96e6b232fee4a5f40
a04b9f8edf6be22aa7ee7c6222bbb32cc6443b40
/lib/helpers.R
a634b448fb17e7214ecdeb2d6bbaf4581ae19676
[]
no_license
whasew/rstanPK
560d8d74e3478135ef89782ae1c3c2e6fc2f9902
063b619c6565ac7846dbbbc402ef6f572b2c5d0d
refs/heads/master
2021-01-01T20:42:33.982641
2015-04-11T08:14:45
2015-04-11T08:14:45
33,406,646
0
0
null
null
null
null
UTF-8
R
false
false
943
r
helpers.R
f2n<-function(f) as.numeric(levels(f))[f] geomSeries <- function(base, max) { base^(0:floor(log(max, base))) } cumulationFactor<-function(tstar,k,n,tau) (1-exp(-n*k*tau))/(1-exp(-k*tau)) bateman<-function(Dose,time,fm,ka,CL,V,n=1,tau=24){ K<-CL/V tstar<-time-(n-1)*tau cumulationFactor(tstar,k,n,tau) fm*ka*Dose/(ka-K)/V*(exp(-K*time)-exp(-ka*time)) } xyLogscale <- function (lims = c(1e-04, 1000),labAdd=NULL) { labels <- c(1:9) * rep(10^c(-4:5), rep(9, 10)) labels <- labels[labels >= lims[1] & labels <= lims[2]] if (!is.null(labAdd)) labels<-sort(c(labels,labAdd)) at <- log10(labels) sel10 <- round(at - round(at), 6)==0 if(!is.null(labAdd)) { att<-(at-log10(labAdd)) selAdd <- round(att - round(att), 6)==0 } else selAdd <-rep(FALSE,length(labels)) sel<-labels%in%c(labels[sel10],labels[selAdd]) if (sum(sel) > 1) labels[!sel] <- "" list(log = TRUE, at = 10^at, labels = labels) }
fcbdfc0aee8df06c82d4269ff38209d985649526
f4563b000f2db75daae46b5653d6afc0a432907f
/life-exp-across-canada.R
e8c484a384b46c178ce10e3325d399a5fb13bddc
[]
no_license
emily-gong/hackseq18_project8
22e529ef9923f783a41cb4a9bb6405113078a2b2
851d35c14a83cdc31bfc91c37f5eeb89076aa50d
refs/heads/master
2020-04-01T06:19:45.419001
2018-10-14T21:38:32
2018-10-14T21:38:32
152,943,150
0
0
null
null
null
null
UTF-8
R
false
false
894
r
life-exp-across-canada.R
library(data.table) library(ggplot2) library(plotly) data <- fread("data/life_data_sep_avg.csv", sep = ",") lifeExp <- data[data$Element == "Life expectancy (in years) at age x (ex)" & data$Sex == "Both" & data$GEO == "Canada",] Age <- lifeExp[,lifeExp$Age_group] LifeExp <- lifeExp[,lifeExp$AVG_VALUE] Year <- lifeExp[,lifeExp$YEAR] p <- plot_ly( x = Age, y = LifeExp, frame = Year, type = 'scatter', mode = 'lines' ) %>% layout( title = "Life Expectancy in Canada (1980-2016)", xaxis = list( type = "linear", title = "Age" ), yaxis = list( title = "Life Expectancy" ) ) p <- p %>% animation_opts( 1000, easing = "elastic", redraw = FALSE ) p <- p %>% animation_button( x = 1, xanchor = "right", y = 0, yanchor = "bottom" ) p chart_link = api_create(p, filename="Life-Expectancy-In-Canada") chart_link
4209d9220848a959d72f6c3091bc01e80a8a8af3
3da145d8919a361f83ea04184d80c21c253ac981
/LogisticRegression.R
26d558f327f78984a353db5ac02a90e32fa64cc3
[]
no_license
AJaafer/ML-Benchmark
5c0b66416d96f8c722d3a2c3ec2f0cc94cd35455
457364f39737589ef54337c5a3c73b9abdf18754
refs/heads/master
2020-03-07T09:44:49.666028
2018-03-30T10:30:01
2018-03-30T10:30:01
127,415,225
0
0
null
null
null
null
UTF-8
R
false
false
779
r
LogisticRegression.R
train=german_credit_dataset[-1,-1] train$Good<- factor(train$Good, levels = c("1", "2"), labels = c("0", "1")) install.packages('caTools') library(caTools) set.seed(88) split <- sample.split(train$Good, SplitRatio = 0.75) #get training and test data dresstrain <- subset(train, split == TRUE) dresstest <- subset(train, split == FALSE) #logistic regression model View(dresstrain) model <- glm (Good ~ ., data = dresstrain, family=binomial(link="logit")) summary(model) predict <- predict(model, type = 'response') #confusion matrix table(dresstrain$Good, predict > 0.5) #ROCR Curve install.packages("ROCR") library(ROCR) ROCRpred <- prediction(predict, dresstrain$Good) ROCRperf <- performance(ROCRpred, 'tpr','fpr') plot(ROCRperf, colorize = TRUE, text.adj = c(-0.2,1.7))
a0928912fff2e6659098ab27e06e1148e9405ca4
c77734e81fec57e93f2b264e0367a90d3dba288f
/first.R
b2a231f037ab619f14c1997bc52da7349c515745
[]
no_license
jfxu/Rcode
c6c01d44b15c7ae1959c36b0166c5918dbe2b60f
2ebe98cdde2ccd82ca2876604237d49d50ae976d
refs/heads/master
2020-04-08T10:30:05.754569
2015-04-13T21:42:44
2015-04-13T21:42:44
14,380,981
0
0
null
null
null
null
UTF-8
R
false
false
44
r
first.R
### A simple test for GitHub set.seed(1942)
93e6762e0926a247620e0a85acc55897a0329418
c5c1c9c8ebfc5a50de7550b67fad878666540336
/jpg_convert.R
b1f99feb3fa28346cfb5fbb0f8bf8660bd440417
[]
no_license
IngridLimaS/RGB
a2efbf18bebbc6e38a368e4c8b15c7805867dcc4
9f5090c2fe7cf97b5a958dc8b09d09e0a6a2b1ac
refs/heads/main
2023-06-20T11:11:45.290975
2021-07-19T16:15:26
2021-07-19T16:15:26
377,680,618
0
2
null
2021-06-19T18:29:40
2021-06-17T02:19:22
R
ISO-8859-1
R
false
false
842
r
jpg_convert.R
################################################ # D: Converter jpg em tiff # Autor: Victor Leandro-silva, Ingrid Lima # Criação: 19-06-2021 # Última edição: 21-06-2021 ################################################ #dir setwd("C:/Users/ingri/Documents/GitHub/RGB/imagem_para_cor") getwd() dir() #package library(imager) library(ggplot2) # Lista imagens dentro da pasta ti <- dir(pattern = ".jpg") ti i <- 1 #Conversão while (i < 328) { setwd("C:/Users/ingri/Documents/GitHub/RGB/imagem_para_cor") #diretório com imagens JPEG d <- load.image(ti[i]) plot(d) thmb <- resize(d) setwd("C:/Users/ingri/Documents/imagens_tif") #Lugar onde vai salvar as imagens p <- raster::plot(thmb) tiff(p, filename = ti[i]) #cria um tiff vazia dev.off() i <- i + 1 # pasta para salvar os tiff }
07bcb82fbc5213b5c432800e73d6daa3e3958d3c
0500ba15e741ce1c84bfd397f0f3b43af8cb5ffb
/cran/paws.machine.learning/man/sagemaker_create_transform_job.Rd
904959c131d54b8af8f2b1477b86a3185ce91eed
[ "Apache-2.0" ]
permissive
paws-r/paws
196d42a2b9aca0e551a51ea5e6f34daca739591b
a689da2aee079391e100060524f6b973130f4e40
refs/heads/main
2023-08-18T00:33:48.538539
2023-08-09T09:31:24
2023-08-09T09:31:24
154,419,943
293
45
NOASSERTION
2023-09-14T15:31:32
2018-10-24T01:28:47
R
UTF-8
R
false
true
5,292
rd
sagemaker_create_transform_job.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/sagemaker_operations.R \name{sagemaker_create_transform_job} \alias{sagemaker_create_transform_job} \title{Starts a transform job} \usage{ sagemaker_create_transform_job( TransformJobName, ModelName, MaxConcurrentTransforms = NULL, ModelClientConfig = NULL, MaxPayloadInMB = NULL, BatchStrategy = NULL, Environment = NULL, TransformInput, TransformOutput, DataCaptureConfig = NULL, TransformResources, DataProcessing = NULL, Tags = NULL, ExperimentConfig = NULL ) } \arguments{ \item{TransformJobName}{[required] The name of the transform job. The name must be unique within an Amazon Web Services Region in an Amazon Web Services account.} \item{ModelName}{[required] The name of the model that you want to use for the transform job. \code{ModelName} must be the name of an existing Amazon SageMaker model within an Amazon Web Services Region in an Amazon Web Services account.} \item{MaxConcurrentTransforms}{The maximum number of parallel requests that can be sent to each instance in a transform job. If \code{MaxConcurrentTransforms} is set to \code{0} or left unset, Amazon SageMaker checks the optional execution-parameters to determine the settings for your chosen algorithm. If the execution-parameters endpoint is not enabled, the default value is \code{1}. For more information on execution-parameters, see \href{https://docs.aws.amazon.com/sagemaker/latest/dg/your-algorithms-batch-code.html#your-algorithms-batch-code-how-containe-serves-requests}{How Containers Serve Requests}. For built-in algorithms, you don't need to set a value for \code{MaxConcurrentTransforms}.} \item{ModelClientConfig}{Configures the timeout and maximum number of retries for processing a transform job invocation.} \item{MaxPayloadInMB}{The maximum allowed size of the payload, in MB. A \emph{payload} is the data portion of a record (without metadata). The value in \code{MaxPayloadInMB} must be greater than, or equal to, the size of a single record. To estimate the size of a record in MB, divide the size of your dataset by the number of records. To ensure that the records fit within the maximum payload size, we recommend using a slightly larger value. The default value is \code{6} MB. The value of \code{MaxPayloadInMB} cannot be greater than 100 MB. If you specify the \code{MaxConcurrentTransforms} parameter, the value of \code{(MaxConcurrentTransforms * MaxPayloadInMB)} also cannot exceed 100 MB. For cases where the payload might be arbitrarily large and is transmitted using HTTP chunked encoding, set the value to \code{0}. This feature works only in supported algorithms. Currently, Amazon SageMaker built-in algorithms do not support HTTP chunked encoding.} \item{BatchStrategy}{Specifies the number of records to include in a mini-batch for an HTTP inference request. A \emph{record} is a single unit of input data that inference can be made on. For example, a single line in a CSV file is a record. To enable the batch strategy, you must set the \code{SplitType} property to \code{Line}, \code{RecordIO}, or \code{TFRecord}. To use only one record when making an HTTP invocation request to a container, set \code{BatchStrategy} to \code{SingleRecord} and \code{SplitType} to \code{Line}. To fit as many records in a mini-batch as can fit within the \code{MaxPayloadInMB} limit, set \code{BatchStrategy} to \code{MultiRecord} and \code{SplitType} to \code{Line}.} \item{Environment}{The environment variables to set in the Docker container. We support up to 16 key and values entries in the map.} \item{TransformInput}{[required] Describes the input source and the way the transform job consumes it.} \item{TransformOutput}{[required] Describes the results of the transform job.} \item{DataCaptureConfig}{Configuration to control how SageMaker captures inference data.} \item{TransformResources}{[required] Describes the resources, including ML instance types and ML instance count, to use for the transform job.} \item{DataProcessing}{The data structure used to specify the data to be used for inference in a batch transform job and to associate the data that is relevant to the prediction results in the output. The input filter provided allows you to exclude input data that is not needed for inference in a batch transform job. The output filter provided allows you to include input data relevant to interpreting the predictions in the output from the job. For more information, see \href{https://docs.aws.amazon.com/sagemaker/latest/dg/batch-transform-data-processing.html}{Associate Prediction Results with their Corresponding Input Records}.} \item{Tags}{(Optional) An array of key-value pairs. For more information, see \href{https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html#allocation-what}{Using Cost Allocation Tags} in the \emph{Amazon Web Services Billing and Cost Management User Guide}.} \item{ExperimentConfig}{} } \description{ Starts a transform job. A transform job uses a trained model to get inferences on a dataset and saves these results to an Amazon S3 location that you specify. See \url{https://www.paws-r-sdk.com/docs/sagemaker_create_transform_job/} for full documentation. } \keyword{internal}
1ee3142089ef3966e9375faaaa980b709005056d
6929d12941949f290d98379913048ee93143e491
/man/string_to_numeric.Rd
38ed353c9671f7038a1b778ae36571b7f04f3d20
[ "MIT" ]
permissive
srmatth/value.investing
9aeaaa476e7731a6cf5a6012f4c0ae38f016dc42
720dbd7ba4f38c2ca896515d72cb2bfa4009582d
refs/heads/master
2023-07-19T04:06:13.679639
2021-09-18T16:46:33
2021-09-18T16:46:33
275,306,180
0
0
null
null
null
null
UTF-8
R
false
true
482
rd
string_to_numeric.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/fct_webscrape_utils.R \name{string_to_numeric} \alias{string_to_numeric} \title{String to Dollar} \usage{ string_to_numeric(x) } \arguments{ \item{x}{a vector of character strings that represent abbreviated dollar amounts} } \value{ a double vector of the same length as the input vector } \description{ Converts a numeric string (such as '53.5B') to its corresponding numeric value (eg. 53500000000) }
32e13db96a956fa7a97129b2215c76bb0c22dd65
0b1b048bc2c5efd33c7eadfd72862f758f9e2447
/scripts/build_sqlit.R
bedc87454201b846f4acca91e1a28764aa374e45
[]
no_license
biopig/chip-seq.snakemake
1b7a634683f87a42823f4611fe67edc2cc852b77
c2a9871266fea18561a216a24ce333c70ea69575
refs/heads/master
2020-04-28T17:01:32.922982
2019-11-24T12:38:25
2019-11-24T12:38:25
175,431,386
0
0
null
null
null
null
UTF-8
R
false
false
960
r
build_sqlit.R
#使用genomicfeatures来构建txdb对象,首先就是安装对应的包 if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager") BiocManager::install("GenomicFeatures", version = "3.8") BiocManager::install("biomaRt", version = "3.8") library("GenomicFeatures") library("biomaRt") library("httr") #in china will get error for the internel library("curl") #in china will get error for the internel #列出可用的数据库的 listMarts() listMarts(host = "http://plants.ensembl.org") #查找数据库中所有的植物的物种 mart<-useMart(biomart = "plants_mart",host = "http://plants.ensembl.org") datasets <- listDatasets(mart) datasets$dataset #下载数据 maize_txdb<-makeTxDbFromBiomart(biomart = "plants_mart",dataset = "zmays_eg_gene",host = "http://plants.ensembl.org") #保存数据 saveDb(maize_txdb, file="maize_v4_2018_11.sqlite") #载入 maize_txdb <- loadDb("maize_v4_2018_11.sqlite")
933e0de847e7a3f8e7fa4d9f3eeb256ac53143a1
c843f06528d8512f85cdd8a29337c567125604c9
/supplement_paper/Rscripts/IMG_GenBank_Datasets/IMG_tvt_selection.R
557644f22d305978212e945efa4a79c3aa382df0
[ "MIT" ]
permissive
JakubBartoszewicz/DeePaC
0f036f8e729135cf2d06e1efbac6dca4dfd08ab2
eab1be09df6bc0bdc7a015c48a5d9636ed9516e5
refs/heads/master
2023-08-05T02:24:22.441187
2022-12-21T10:48:45
2022-12-21T10:48:45
199,677,945
3
2
MIT
2023-07-06T23:35:37
2019-07-30T15:23:09
Jupyter Notebook
UTF-8
R
false
false
9,795
r
IMG_tvt_selection.R
set.seed(0) library(stringr) date.postfix.img <- "_fungi" random.best <- FALSE ambiguous.species <- FALSE # no of folds to generate k <- 9 validation_percent <- 0.1 test_percent <- 0.1 fold_names <- paste0("fold", 1:k) download_format = ".fna" # no of folds to download k_download <- 1 # generate urls urls <- TRUE IMG.all <- readRDS(paste0("IMG_assemblies",date.postfix.img,".rds")) if (!ambiguous.species) { IMG.all$Ambiguous <- FALSE } IMG.all$assembly_level <- factor(IMG.all$assembly_level,levels(IMG.all$assembly_level), ordered = TRUE) IMG.all$assembly_accession <- as.character(IMG.all$assembly_accession) Species_HP <- as.character(unique(IMG.all$Species[which(IMG.all$Pathogenic == TRUE & IMG.all$Ambiguous == FALSE)])) Species_NP <- as.character(unique(IMG.all$Species[which(IMG.all$Pathogenic == FALSE & IMG.all$Ambiguous == FALSE)])) Species <- c(Species_HP, Species_NP) ### tvt IMG.all[,fold_names] <- "" IMG.all$subset <- "" Species_HP_test_manual <- c("Candida auris", "Aspergillus fumigatus") Species_NP_test_manual <- c("Pyricularia oryzae", "Batrachochytrium dendrobatidis") Species_HP_test <- sample(Species_HP, ceiling(test_percent*length(Species_HP))-length(Species_HP_test_manual)) Species_HP_test <- c(Species_HP_test_manual, Species_HP_test) Species_NP_test <- sample(Species_NP, ceiling(test_percent*length(Species_NP))-length(Species_NP_test_manual)) Species_NP_test <- c(Species_NP_test_manual, Species_NP_test) IMG.all[IMG.all$Species %in% Species_HP_test,fold_names] <- "test" IMG.all[IMG.all$Species %in% Species_NP_test,fold_names] <- "test" Species_test <- c(Species_HP_test,Species_NP_test) Species_HP_done <- Species_HP_test Species_NP_done <- Species_NP_test SampleStrains <- function(SpeciesList, LabelsList, IMGdata, Prefix, fold=1){ # get strains Accessions <- lapply(SpeciesList, function(QuerySpecies){ IMGdata[IMGdata$Species == QuerySpecies,"assembly_accession"] }) names(Accessions) <- SpeciesList RandomStrain.Accession <- sapply(Accessions, function(Species) { Species[sample(1:length(Species),1)] }) IMGdata$subset[match(RandomStrain.Accession,IMGdata$assembly_accession)] <- "selected" if (fold<2){ saveRDS(RandomStrain.Accession,file.path(paste(Prefix,"Strains.rds", sep="") )) } else { saveRDS(RandomStrain.Accession,file.path(paste(Prefix,"Strains_", fold, ".rds", sep="") )) } # save label information names(LabelsList) <- RandomStrain.Accession if (fold<2){ saveRDS(LabelsList, file.path(paste(Prefix,"Labels.rds", sep="") )) } else { saveRDS(LabelsList, file.path(paste(Prefix,"Labels_", fold, ".rds", sep="") )) } return(IMGdata) } SampleBestStrains <- function(){ ### sample strains assembly_level <- sapply(Species, function(s){min(IMG.all$assembly_level[IMG.all$Species == s])}) names(assembly_level) <- Species IMG.all$subset[as.character(IMG.all$assembly_level) == as.character(assembly_level[IMG.all$Species])] <- "candidate" IMG.all$subset[!(as.character(IMG.all$assembly_level) == as.character(assembly_level[IMG.all$Species]))] <- "other" selected_assemblies <- sapply(Species, function(s){candidate_assemblies <- IMG.all[IMG.all$Species == s & IMG.all$subset == "candidate", "assembly_accession"]; return(candidate_assemblies[sample(1:length(candidate_assemblies),1)]) }) IMG.all$subset[IMG.all$assembly_accession %in% selected_assemblies] <- "selected" } if(!random.best & !ambiguous.species){ Labels_test <- c(rep(T,length(Species_HP_test)),rep(F,length(Species_NP_test))) IMG.all <- SampleStrains(Species_test, Labels_test, IMG.all, "Test") } Species_HP_trainval <- setdiff(Species_HP,Species_HP_done) Species_NP_trainval <- setdiff(Species_NP,Species_NP_done) fold_val_sizes_HP <- sapply(1:k, function(i) {floor(length(Species_HP_trainval)/k)}) if(length(Species_HP_trainval) %% k > 0){ fold_val_sizes_HP[1:(length(Species_HP_trainval) %% k)] <- fold_val_sizes_HP[1:(length(Species_HP_trainval) %% k)] + 1 } fold_val_sizes_NP <- sapply(1:k, function(i) {floor(length(Species_NP_trainval)/k)}) if(length(Species_NP_trainval) %% k > 0){ fold_val_sizes_NP[1:(length(Species_NP_trainval) %% k)] <- fold_val_sizes_NP[1:(length(Species_NP_trainval) %% k)] + 1 } for (i in 1:k) { Species_HP_trainval <- setdiff(Species_HP,Species_HP_done) Species_NP_trainval <- setdiff(Species_NP,Species_NP_done) Species_HP_training <- sample(Species_HP_trainval, length(Species_HP_trainval) - fold_val_sizes_HP[i]) Species_NP_training <- sample(Species_NP_trainval, length(Species_NP_trainval) - fold_val_sizes_NP[i]) Species_HP_validation <- setdiff(Species_HP_trainval,Species_HP_training) Species_NP_validation <- setdiff(Species_NP_trainval,Species_NP_training) IMG.all[IMG.all$Species %in% Species_HP_training,fold_names[i]] <- "train" IMG.all[IMG.all$Species %in% Species_NP_training,fold_names[i]] <- "train" IMG.all[IMG.all$Species %in% Species_HP_validation,fold_names[i]] <- "val" IMG.all[IMG.all$Species %in% Species_NP_validation,fold_names[i]] <- "val" if (i<k){ # if validation here, training in other folds IMG.all[IMG.all$Species %in% Species_HP_validation,fold_names[(i+1):k]] <- "train" IMG.all[IMG.all$Species %in% Species_NP_validation,fold_names[(i+1):k]] <- "train" } Species_HP_done <- c(Species_HP_done, Species_HP_validation) Species_NP_done <- c(Species_NP_done, Species_NP_validation) if(!random.best & !ambiguous.species & i==1){ Species_training <- c(Species_HP_training,Species_NP_training) Labels_training <- c(rep(T,length(Species_HP_training)),rep(F,length(Species_NP_training))) Species_validation <- c(Species_HP_validation,Species_NP_validation) Labels_validation <- c(rep(T,length(Species_HP_validation)),rep(F,length(Species_NP_validation))) IMG.all <- SampleStrains(Species_training, Labels_training, IMG.all, "Training") IMG.all <- SampleStrains(Species_validation, Labels_validation, IMG.all, "Validation") } } ### sample strains if(random.best){ SampleBestStrains() } if (ambiguous.species) { IMG.all$subset <- "selected" } IMG.all[, grep(pattern = "\\.orig", x = colnames(IMG.all))] <- NULL selected <- IMG.all[IMG.all$subset == "selected",] # only folds to download if(k>1 & k_download<k){ for (fold_name in fold_names[(1+k_download):length(fold_names)]) { selected[,fold_name] <- NULL } } # Save data for backup if (!ambiguous.species) { IMG.all$Ambiguous <- NULL } saveRDS(IMG.all, paste0("IMG_all_folds", date.postfix.img, ".rds")) saveRDS(selected, paste0("IMG_", k_download, "_folds", date.postfix.img, ".rds")) if(urls){ # Save urls for downloading urls.test.HP <- sapply(as.character(selected$ftp_path[selected$fold1=="test" & selected$Pathogenic]), function(f){name <- unlist(strsplit(as.character(f), split = "/")); name <- name[length(name)]; return(paste0(f, "/", name, "_genomic", download_format, ".gz"))}) writeLines(urls.test.HP, con = paste0("urls.test.HP", download_format, ".txt")) urls.test.NP <- sapply(as.character(selected$ftp_path[selected$fold1=="test" & !selected$Pathogenic]), function(f){name <- unlist(strsplit(as.character(f), split = "/")); name <- name[length(name)]; return(paste0(f, "/", name, "_genomic", download_format, ".gz"))}) writeLines(urls.test.NP, con = paste0("urls.test.NP", download_format, ".txt")) for (i in 1:k_download) { urls.train.HP <- sapply(as.character(selected$ftp_path[selected[,paste0("fold", i)]=="train" & selected$Pathogenic]), function(f){name <- unlist(strsplit(as.character(f), split = "/")); name <- name[length(name)]; return(paste0(f, "/", name, "_genomic", download_format, ".gz"))}) urls.val.HP <- sapply(as.character(selected$ftp_path[selected[,paste0("fold", i)]=="val" & selected$Pathogenic]), function(f){name <- unlist(strsplit(as.character(f), split = "/")); name <- name[length(name)]; return(paste0(f, "/", name, "_genomic", download_format, ".gz"))}) writeLines(urls.train.HP, con = paste0("urls.train.HP.", fold_names[i], download_format, ".txt")) writeLines(urls.val.HP, con = paste0("urls.val.HP.", fold_names[i], download_format, ".txt")) urls.train.NP <- sapply(as.character(selected$ftp_path[selected[,paste0("fold", i)]=="train" & !selected$Pathogenic]), function(f){name <- unlist(strsplit(as.character(f), split = "/")); name <- name[length(name)]; return(paste0(f, "/", name, "_genomic", download_format, ".gz"))}) urls.val.NP <- sapply(as.character(selected$ftp_path[selected[,paste0("fold", i)]=="val" & !selected$Pathogenic]), function(f){name <- unlist(strsplit(as.character(f), split = "/")); name <- name[length(name)]; return(paste0(f, "/", name, "_genomic", download_format, ".gz"))}) writeLines(urls.train.NP, con = paste0("urls.train.NP.", fold_names[i], download_format, ".txt")) writeLines(urls.val.NP, con = paste0("urls.val.NP.", fold_names[i], download_format, ".txt")) } # Save urls for downloading ALL TRAINING STRAINS for (i in 1:k_download) { urls.all.train.HP <- sapply(as.character(IMG.all$ftp_path[IMG.all[,paste0("fold", i)]=="train" & IMG.all$Pathogenic]), function(f){name <- unlist(strsplit(as.character(f), split = "/")); name <- name[length(name)]; return(paste0(f, "/", name, "_genomic", download_format, ".gz"))}) writeLines(urls.all.train.HP, con = paste0("urls.all.train.HP.", fold_names[i], download_format, ".txt")) urls.all.train.NP <- sapply(as.character(IMG.all$ftp_path[IMG.all[,paste0("fold", i)]=="train" & !IMG.all$Pathogenic]), function(f){name <- unlist(strsplit(as.character(f), split = "/")); name <- name[length(name)]; return(paste0(f, "/", name, "_genomic", download_format, ".gz"))}) writeLines(urls.all.train.NP, con = paste0("urls.all.train.NP.", fold_names[i], download_format, ".txt")) } }
c95bd768365e1eb211872663e2e9d64014c00403
7b1c749b93cde9572c32af65a34d86f708dac114
/TP2/acp.R
37ce87c232e503277b9a951c7dd10f0894e835fb
[]
no_license
slebastard/PISA_Results_Analysis
5dfb996ac897c2c8e9fbf208515684ca8fe02807
11afe131bd44effb1caecd7cdab9c743399b051f
refs/heads/master
2021-01-10T04:13:06.763735
2016-03-11T12:10:18
2016-03-11T12:10:18
51,708,109
0
0
null
null
null
null
UTF-8
R
false
false
1,445
r
acp.R
rm(list = ls()) graphics.off() Voitures <- read.table("emissions.csv", sep = ";", row.names = 1, header = TRUE) Voitures <- na.omit(Voitures) quant = Voitures[,1:9] qual = Voitures[,10:11] print(Voitures) pairs(quant) acp = princomp(quant, cor = T, scores = T) summary(acp) valp = acp $ sdev^2 dev.new() plot(valp, type = "b") scores = acp $ scores print(scores) dev.new() plot(scores[, 1], scores[, 2], type = "n") text(scores[,1], scores[,2], labels = row.names(quant), cex = 0.5) loadings = acp $ loadings print(loadings) corr1 = loadings[, 1]*sqrt(valp[1]) corr2 = loadings[, 2]*sqrt(valp[2]) dev.new() plot(corr1, corr2, xlim = c(-1, 1), ylim = c(-1, 1), asp = 1, type = "n") text(corr1, corr2, labels = colnames(quant), cex = 0.5) symbols(0, 0, circles = 1, inches = F, add = T) #Retracer les voitures dans le plan u1, u2 en mettant les noms des modèles d'une couleur qui caractérise leur carburant. dev.new() plot(scores[, 1], scores[, 2], type = "n") text(scores[,1], scores[,2], labels = row.names(quant), cex = 0.5, col = ifelse(Voitures[, 11] == "EH", "green", ifelse(Voitures[, 11] == "ES", "black", "blue"))) #Placer le symbole LUXE au barycentre des positions des véhicules de type luxe. posx = 0 posy = 0 num = 0 for (i in 1:length(Voitures[, 10])) { if (Voitures[i, 10] == "LUXE") { num = num + 1 posx = posx + scores[i, 1] posy = posy + scores[i, 2] } } text(posx/num, posy/num, labels = "LUXE", cex = 1)
a91f3c734ff461f953e11487fdcf9c3d5d04284a
2b41bcab679bc4569261f22f0024a5e727e4f59f
/rnbl3_prophetX_Hols_clean.R
8895b073211da99f46487c413463e9f89119789e
[]
no_license
akuppam/timeS
f86b5afe7d4f64be2d502322f36870e1bafba6af
9299f1cedb0039a01e4afe4392f88ffdb40f2af1
refs/heads/master
2021-09-08T14:38:07.123880
2021-09-02T20:57:30
2021-09-02T20:57:30
147,609,389
1
0
null
null
null
null
UTF-8
R
false
false
8,866
r
rnbl3_prophetX_Hols_clean.R
# ---------------------- # Prophet Model w/ regressors # propherX # ---------------------- library(corrplot) library(plotly) library(prophet) library(tidyverse) library(bsts) library(prophet) library(dplyr) library(ggplot2) # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- setwd("/users/akuppam/documents/Data/RoverData/") DF <- read.csv("rnbl2agg.csv") #DF <- read.csv("UK-paid.csv") DF <- mutate(DF, ds = as.Date(date)) # adding regressors library(dplyr) colnames(DF) <- c("date","region","marketing","visits","br","inq","gb","cb","y","ss","ts","listings","ds") pdat <- data.frame(ds=DF$ds, y=DF$y, visits=DF$visits, br=DF$br, listings=DF$listings, inq=DF$inq) pfdat <- data.frame(ds=max(DF$ds) + 1:365) pvisits <- DF %>% dplyr::select(ds,y=visits) %>% prophet() %>% predict(pfdat) pbr <- DF %>% dplyr::select(ds,y=br) %>% prophet() %>% predict(pfdat) plistings <- DF %>% dplyr::select(ds,y=listings) %>% prophet() %>% predict(pfdat) pinq <- DF %>% dplyr::select(ds,y=inq) %>% prophet() %>% predict(pfdat) fdat <- data.frame(ds=pfdat$ds, visits=pvisits$yhat, br=pbr$yhat, listings=plistings$yhat, inq=pinq$yhat) # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- library(dplyr) major <- data_frame( holiday = 'majorH', ds = as.Date(c('2017-01-01', '2017-05-29', '2017-07-04', '2017-09-04', '2017-11-23', '2017-12-25', '2018-01-01', '2018-05-28', '2018-07-04', '2018-09-03', '2018-11-22', '2018-12-25')), lower_window = 0, upper_window = 1 ) minor <- data_frame( holiday = 'minorH', ds = as.Date(c('2017-01-16', '2017-02-20', '2017-10-09', '2018-01-15', '2018-02-19', '2018-10-08')), lower_window = 0, upper_window = 1 ) holidays <- bind_rows(major, minor) # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- fit6 <- prophet(holidays = holidays) %>% fit.prophet(pdat) forecast <- predict(fit6, fdat) fpred <- predict(fit6) fpred$ds <- as.Date(fpred$ds) fpred <- pdat %>% left_join(fpred,by="ds") fpred$resid <- fpred$y - fpred$yhat dfprophet <- c(fpred$yhat, forecast$yhat) mape_prophet <- mean(abs((pdat$y - fpred$yhat)/pdat$y)) # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- fit6 <- prophet(holidays = holidays) %>% add_regressor('visits') %>% fit.prophet(pdat) forecast <- predict(fit6, fdat) fpred <- predict(fit6) fpred$ds <- as.Date(fpred$ds) fpred <- pdat %>% left_join(fpred,by="ds") fpred$resid <- fpred$y - fpred$yhat dfprophet_visits <- c(fpred$yhat, forecast$yhat) mape_prophet_visits <- mean(abs((pdat$y - fpred$yhat)/pdat$y)) # ------------------- # ------------------- fit6 <- prophet(holidays = holidays) %>% add_regressor('br') %>% fit.prophet(pdat) forecast <- predict(fit6, fdat) fpred <- predict(fit6) fpred$ds <- as.Date(fpred$ds) fpred <- pdat %>% left_join(fpred,by="ds") fpred$resid <- fpred$y - fpred$yhat dfprophet_br <- c(fpred$yhat, forecast$yhat) mape_prophet_br <- mean(abs((pdat$y - fpred$yhat)/pdat$y)) # ------------------- # ------------------- fit6 <- prophet(holidays = holidays) %>% add_regressor('visits') %>% add_regressor('br') %>% fit.prophet(pdat) forecast <- predict(fit6, fdat) fpred <- predict(fit6) dfprophet_vibr <- c(fpred$yhat, forecast$yhat) mape_prophet_vibr <- mean(abs((pdat$y - fpred$yhat)/pdat$y)) # ------------------- # ------------------- fit6 <- prophet(holidays = holidays) %>% add_regressor('visits') %>% add_regressor('br') %>% add_regressor('listings') %>% fit.prophet(pdat) forecast <- predict(fit6, fdat) fpred <- predict(fit6) dfprophet_vibrli <- c(fpred$yhat, forecast$yhat) mape_prophet_vibrli <- mean(abs((pdat$y - fpred$yhat)/pdat$y)) # ------------------- fit6 <- prophet(holidays = holidays) %>% add_regressor('br') %>% add_regressor('listings') %>% fit.prophet(pdat) forecast <- predict(fit6, fdat) fpred <- predict(fit6) dfprophet_brli <- c(fpred$yhat, forecast$yhat) mape_prophet_brli <- mean(abs((pdat$y - fpred$yhat)/pdat$y)) # ------------------- prophet_plot_components(fit6, forecast) plot_forecast_component(fit6, forecast, 'majorH') plot_forecast_component(fit6, forecast, 'minorH') # just checking the contribution of majorH, minorH on bookings forecast %>% dplyr::select(ds, majorH, minorH) %>% filter(abs(majorH + minorH) > 0) %>% tail(10) # ---------------------------------------------------- # ---------------------------------------------------- # ---------------------------------------------------- # ############################## # ----------------------------- # SES, ARIMA, HW # ----------------------------- # ############################## library(forecast) library(ggplot2) library(dplyr) library(tidyr) # ------------------------------------------- # Make the 'y' variables to a ts object rnb <- ts(DF$y, start=2016,freq=365) str(rnb) # ------------------------------------------- # Exponential Smoothing using state space approach ## STLF Exponential smoothing st_ets <- stlf(rnb, method="ets", h=365)$mean write.csv(st_ets, "1_st_ets.csv") # ------------------------------------------- fit_ets <- ets(rnb)$fitted fit_ets_fc <- forecast(fit_ets, h=365) write.csv(fit_ets_fc, "1_fit_ets.csv") # Note - there are slight differences between stlf/ets and ets() # ------------------------------------------- # ------------------------------------------- # HoltWinters rnbAlphaBetaGamma <- HoltWinters(rnb) fit_hw_fc <- forecast(rnbAlphaBetaGamma, h=365) write.csv(fit_hw_fc, "11_fit_hw.csv") # ------------------------------------------- # ------------------------------------------- ## Auto.Arima rnb_arima <- auto.arima(DF[,9]) # ALWAYS INPUT RAW DATA THAT IS 'NOT' A ts() object arimaorder(rnb_arima) ## STLM - apply Auto.Arima model to data fit <- stlm(rnb, modelfunction=Arima, order=arimaorder(rnb_arima)) fit_arima_fc <- forecast(fit, h=365) write.csv(fit_arima_fc, "6_rnb_arima_pred_fc.csv") # ------------------------------------------- # ------------------------------------------- # Compute MAPES df_mape <- data.frame(rnb, fit_arima_fc$fitted, fit_hw_fc$fitted) mape_arima <- mean(abs((df_mape$rnb - df_mape$fit_arima_fc.fitted)/df_mape$rnb)) df_mape_hw <- df_mape[366:nrow(df_mape),] mape_hw <- mean(abs((df_mape_hw$rnb - df_mape_hw$fit_hw_fc.fitted)/df_mape_hw$rnb)) # Output MAPES by Model library(dplyr) mapes_by_model_Hols <- data_frame( ts_model = c('prophet','prophet_br','prophet_brli','prophet_vibr', 'prophet_vibrli','prophet_visits', 'hw','arima'), mape = c(mape_prophet,mape_prophet_br,mape_prophet_brli,mape_prophet_vibr, mape_prophet_vibrli,mape_prophet_visits, mape_hw,mape_arima) ) # ------------------------------------------- # ------------------------------------------- # Plot forecasts from different methods df_rnb <- c(rnb, rep(NA,365)) df1 <- c(rnb, st_ets) df6 <- c(fit_arima_fc$fitted, fit_arima_fc$mean) # Using 'forecast()' function: mean = forecasts (n=120); fitted = backcasts (n=998) df11 <- c(fit_hw_fc$fitted, fit_hw_fc$mean) dfreal <- c(DF$y, rep(NA,365)) df_all <- data.frame(dfreal,dfprophet,dfprophet_visits,dfprophet_br,dfprophet_vibr,dfprophet_vibrli,df1,df6,df11) names(df_all) <- c("real","prophet","prophet_visits","prophet_br","prophet_vibr","prophet_vibrli","ets","arima","hw") write.csv(df_all, "df_all_agg.csv") # adding date as index df_all1 <- data.frame(dates=seq(from=(as.POSIXct(strftime("2016-01-01"))), length.out = nrow(df_all), by="days"), data = df_all) dfplot <- df_all1 %>% gather(key, value, -dates) jpeg("real vs all models.jpg", height=4.25, width=5.5, res=200, units = "in") ggplot(dfplot, mapping = aes(x = dates, y = value, color = key) ) + geom_line() + ggtitle("real vs all models") dev.off() # ----- forecasts ONLY ----------- df_all_f <- df_all[999:nrow(df_all),] # adding date as index df_all1 <- data.frame(dates=seq(from=(as.POSIXct(strftime("2018-09-25"))), length.out = nrow(df_all_f), by="days"), data = df_all_f) dfplot <- df_all1 %>% gather(key, value, -dates) jpeg("real vs all models - forecasts ONLY.jpg", height=4.25, width=5.5, res=200, units = "in") ggplot(dfplot, mapping = aes(x = dates, y = value, color = key) ) + geom_line() + ggtitle("real vs all models - forecasts ONLY") dev.off()
0319039bd1e3865fc7164ec8009a483161a1187c
ea4fed8707dc916aa765137de316ce428ba29a06
/h.R
c473a628050d18a13874a7eff426cfbf5a236d20
[]
no_license
troywu666/R
475fb38ec8bff948dc3117fddda2466a2f9a3982
62fdc26feddd71ae5b19f12a9772a09693ccc0d1
refs/heads/master
2020-07-19T00:30:55.700466
2019-09-12T14:07:06
2019-09-12T14:07:06
206,342,799
0
0
null
null
null
null
UTF-8
R
false
false
76
r
h.R
x <- 0 x[1] <- 1 i <- 1 while (x[1]<100) {i=i+1;x[i]= x[i-1]+2} print(x)
b2cc09c8cfc2a10eac76cccf8a1d32a8f27bad50
837369fea4392c7429f3fe2ab8d2119b1b7013e2
/plot3.R
d021972d9a08b6a67ff6cfcb985e2f127a655175
[]
no_license
shadowmoon1988/ExData_Plotting1
7d0c1a8ac543bf81ff74dbb48aba602d41b0670c
c9a99f30c4a414f216756fcb50ce046ea409caaf
refs/heads/master
2021-01-15T17:20:51.337941
2016-02-04T08:50:20
2016-02-04T08:50:20
51,030,906
0
0
null
2016-02-03T21:11:57
2016-02-03T21:11:57
null
UTF-8
R
false
false
613
r
plot3.R
library(data.table) data <- fread("household_power_consumption.txt",header=TRUE,na.strings="?") data[,Date:=as.Date(Date,format="%d/%m/%Y")] data <-data[data$Date>=as.Date("2007-02-01")&data$Date<=as.Date("2007-02-02"),] t <- strptime(paste(data$Date,data$Time),format="%Y-%m-%d %H:%M:%S") png(file="plot3.png",width=480,height=480) plot(t,data$Sub_metering_1,type="l",xlab="",ylab="Energy sub metering") lines(t,data$Sub_metering_2,col="red") lines(t,data$Sub_metering_3,col="blue") legend("topright", col=c("black","red","blue"), legend=c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"),lty=1) dev.off()
b82a6780389e7c3d5c48fe04d3c839e6222c7f76
7c8b9c6b91d344acb7f3dd8212d3a8ec23488a9f
/App/HTMLR/input.R
2624c7a33d7b84f6ee8f004a9230992a2b5fc662
[ "MIT" ]
permissive
dnordgren/Finance-O-Tron
d69cd014a6e8a2e541191f5323f0aebeed0128ed
22a98a1a4f39ad67d9a87fef73ac8bf760e1b10e
refs/heads/master
2021-05-30T01:20:28.192056
2014-12-11T05:33:06
2014-12-11T05:33:06
26,923,922
0
0
null
null
null
null
UTF-8
R
false
false
918
r
input.R
actionButtonHalf <- function(inputId, value){ tags$button(id = inputId, type="button", style="margin-top:10px", class = "btn btn-primary action-button shiny-bound-input", value) } actionButtonRow <- function(inputId, value){ div(tags$button(id = inputId, type="button", class = "btn btn-primary action-button shiny-bound-input", value)) } disableInputSmall <- function(session){ session$sendCustomMessage(type="jsCode", list(code= "$('.input-small').attr('disabled',true)")) } enableInputSmall <- function(session){ session$sendCustomMessage(type="jsCode", list(code= "$('.input-small').attr('disabled',false)")) } disableUIElement <- function(id, session){ session$sendCustomMessage(type="jsCode", list(code=paste0("$('#",id,"').attr('disabled',true)"))) } enableUIElement <- function(id, session){ session$sendCustomMessage(type="jsCode", list(code=paste0("$('#",id,"').attr('disabled',false)"))) }
40934dbb3f6e26060a7bea6546c14c757311970c
0ad1708efc25df24d2243f75d0fa54b920b2b1bb
/man/bootstrapThresholds.Rd
8db07e25c6d6bfb0296753e0f34751d110f155c4
[]
no_license
pearcedom/survivALL
6cdc6112394b02904170e71c5ce49dd21ec3881a
efcbf6ba09cc90b8b14ee7e7491d5963b7298241
refs/heads/master
2021-01-15T23:22:20.393168
2018-05-24T14:52:04
2018-05-24T14:52:04
99,936,011
1
0
null
null
null
null
UTF-8
R
false
true
1,013
rd
bootstrapThresholds.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/bootstrapThresholds.R \name{bootstrapThresholds} \alias{bootstrapThresholds} \title{Calculate per-separation point hazard ratio thresholds} \usage{ bootstrapThresholds(bs_dfr, n_sd = 1.96) } \arguments{ \item{bs_dfr}{A matrix of bootstrapped hazard ratio computations as ordered by a random measurement vector. Typically consisting of 5-10,000 repeat samplings} \item{n_sd}{The number of standard deviations used to define threshold width. 95% of random hazard ratio values fall within the thresholds with a standard deviation of 1.96} } \value{ A dataframe of per-separation point mean, upper and lower thresholds } \description{ Calculate per-separation point hazard ratio thresholds } \examples{ data(nki_subset) library(Biobase) library(magrittr) library(ggplot2) #simulate example HR bootstrapped data bs_dfr <- matrix(rnorm(150000), ncol = 1000, nrow = 150) #calculate thresholds thresholds <- bootstrapThresholds(bs_dfr) }
1e9a98eaa4a067f6b3f2ac0b1f251e268f3220f6
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/BiocInstaller/examples/packageGroups.Rd.R
fc9a18aa55e9b0b525116804661b1d5ecea92e06
[]
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
692
r
packageGroups.Rd.R
library(BiocInstaller) ### Name: Package Groups ### Title: Convenience functions to return package names associated with ### Bioconductor publications. ### Aliases: biocases_group RBioinf_group monograph_group all_group ### Keywords: environment ### ** Examples ## Get the names of packages used in the book ## "Bioconductor Case Studies": biocases_group() ## Get the names of packages used in the book ## "R Programming for Bioinformatics": RBioinf_group() ## Get the names of packages used in the monograph ## "Bioinformatics and Computational Biology Solutions ## Using R and Bioconductor": monograph_group() ## Get the names of all Bioconductor software packages all_group()
709f3f60829b13de181eab81a91f1a21d82a513f
3b62ffa02efef29b8bbaa9041d74a1ee72b4807a
/man/rhrIsopleths.Rd
7faea9f927249663631cd174e4f3dccdd6fb1fad
[]
no_license
jmsigner/rhr
52bdb94af6a02c7b10408a1dce549aff4d100709
7b8d1b2dbf984082aa543fe54b1fef31a7853995
refs/heads/master
2021-01-17T09:42:32.243262
2020-06-22T14:24:00
2020-06-22T14:24:00
24,332,931
0
0
null
null
null
null
UTF-8
R
false
true
562
rd
rhrIsopleths.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/rhrIsopleths.R \name{rhrIsopleths} \alias{rhrIsopleths} \title{Isopleths of Home Range Estimate} \usage{ rhrIsopleths(x, ...) } \arguments{ \item{x}{Instance of \code{RhrEst}.} \item{...}{see details.} } \value{ \code{SpatialPolygonsDataFrame} } \description{ Function to retrieve isopleths of a home range estimate. } \details{ Probabilistic estimators take (i.e. kernel density estimates) take an additional argument, \code{levels}, that determines which isopleth are returned. }
feaf9e264bb125dc958d46dd50e04ff2bea51db2
6519538b5837012573465ce9471b053622fe0830
/ZOL851/Elise_Zipkin/notes/ggplot2_demo.R
ebcb2a12a6c02107da316fd754dcd6c5fb8ac955
[]
no_license
pvaelli/Advanced_Statistics
926e4229918d3a50ceebeefdf4469e2173c08c95
27b628b0355f9c4d8f2e1648a33aa1ec21b230c5
refs/heads/master
2021-08-29T20:18:27.970826
2017-12-14T22:54:20
2017-12-14T22:54:20
null
0
0
null
null
null
null
UTF-8
R
false
false
3,848
r
ggplot2_demo.R
install.packages("ggplot2") library("ggplot2") diamonds # sample dataset present in ggplot2 library summary(diamonds) help(diamonds) # can only do this because it's a sample dataset ggplot(diamonds, aes(x=carat, y=price)) + geom_point() #(dataset, aesthetics, ) + layers for plot() ggplot(diamonds, aes(x=carat, y=price, color=clarity)) + geom_point() #(dataset, aesthetics, adding color coding) + layers for plot() ggplot(diamonds, aes(x=carat, y=price, color=cut)) + geom_point() #(dataset, aesthetics, adding color coding) + layers for plot() ggplot(diamonds, aes(x=carat, y=price, color=clarity, size=cut)) + geom_point() #(dataset, aesthetics, adding color coding) + layers for plot() ggplot(diamonds, aes(x=carat, y=price, color=clarity, size=cut)) + geom_point(alpha=0.3) #(dataset, aesthetics, adding color coding) + layers for plot() ggplot(diamonds, aes(x=carat, y=price)) + geom_point() + geom_smooth() #(dataset, aesthetics, adding color coding) + layers for plot() ggplot(diamonds, aes(x=carat, y=price)) + geom_point() + geom_smooth(se=FALSE) #(dataset, aesthetics, adding color coding) + layers for plot() ggplot(diamonds, aes(x=carat, y=price, color=clarity)) + geom_point() + geom_smooth(se=FALSE) #(dataset, aesthetics, adding color coding) + layers for plot() ggplot(diamonds, aes(x=carat, y=price, color=clarity)) + geom_smooth(se=FALSE) #(dataset, aesthetics, adding color coding) + layers for plot() ggplot(diamonds, aes(x=carat, y=price, color=clarity)) + geom_point() + geom_smooth(se=FALSE) + ggtitle("Colors so many !!") #(dataset, aesthetics, adding color coding) + layers for plot() ggplot(diamonds, aes(x=carat, y=price, color=clarity)) + geom_point() + geom_smooth(se=FALSE) + ggtitle("Colors so many !!") + xlab("Weight (carats)") + ylab("Price (dollars)")#(dataset, aesthetics, adding color coding) + layers for plot() # these lines are getting really long. here's a trick: plot <- ggplot(diamonds, aes(x=carat, y=price, color=cut)) plot <- plot + geom_point() plot <- plot + ggtitle("Colors so many !!!") plot <- plot + xlab("Weight (carats)") + ylab("Price (dollars)") plot <- plot + xlim(0,2) + ylim(0, 10000) plot <- plot + scale_y_log10() plot # Histograms ggplot(diamonds, aes(x=price)) + geom_histogram() # by default each bin is 30 ggplot(diamonds, aes(x=price)) + geom_histogram(binwidth=2000) ggplot(diamonds, aes(x=price)) + geom_histogram(binwidth=200) ggplot(diamonds, aes(x=price)) + geom_histogram(binwidth=200) +facet_wrap(~clarity) ggplot(diamonds, aes(x=price)) + geom_histogram(binwidth=200) +facet_wrap(~clarity, scale="free_y") # can add this last part to change the y scaling. Good for looking at shape of distribution; otherwise all y axes are identical across plots ggplot(diamonds, aes(x=price, fill=cut)) + geom_histogram() # this could be useful for microbial abundance bar plots! # Density plots ggplot(diamonds, aes(x=price)) + geom_density() ggplot(diamonds, aes(x=price, color=cut)) + geom_density() ggplot(diamonds, aes(x=price, fill=cut)) + geom_density() ggplot(diamonds, aes(x=price, fill=cut)) + geom_density(alpha=0.3) # Boxplots ggplot(diamonds, aes(x=color, y=price)) + geom_boxplot() ggplot(diamonds, aes(x=color, y=price)) + geom_boxplot() + scale_y_log10() # Violin plots ggplot(diamonds, aes(x=color, y=price)) + geom_violin() ggplot(diamonds, aes(x=color, y=price)) + geom_violin() + scale_y_log10() # bar plots ggplot(diamonds, aes(x=cut)) + geom_bar() plot <- ggplot(diamonds, aes(x=color, fill=cut)) + geom_bar() # stacked vs adjacent (next code) ggplot(diamonds, aes(x=color, fill=cut)) + geom_bar(position = "dodge") x <- 0:5 y <- x * 3000 model <- data.frame(x,y) ggplot(diamonds, aes(x=carat, y=price)) + geom_point() + geom_line(data=model, x=x, y=y) ggsave(filename="pretty.pdf", plot) # can do .png or .jpeg etc.
2523f67aaa5b137bdfb806ebd6d00516ade1fe3a
e8dc4d4a4988126f8beedd9b8e920c8c0468df7a
/INPUT/script_gene.r
9e166255410674f973d442cc2c0d8ebf9537f373
[]
no_license
marta-coronado/master-thesis
ca5ddc36a1637487e4b0ad7872b1f65ce84cd466
a0a1c19c3bd4b9a21f00731af7c7996d921cc13c
refs/heads/master
2021-01-01T18:34:43.007019
2014-05-30T14:50:35
2014-05-30T14:50:35
null
0
0
null
null
null
null
UTF-8
R
false
false
8,872
r
script_gene.r
library(car) library(lattice) library(ppcor) library(pls) rm(list = ls()) #data<-read.table(file="GENE",header=TRUE,sep="\t") #data<-read.table(file="GENE.SHORTINTRON.65",header=TRUE,sep="\t") data<-read.table(file="GENE.SHORTINTRON.65_8-30",header=TRUE,sep="\t") data <- na.omit(data) data <- subset(data,comeron_100kb > 0) nrow(data) data <- subset(data,chr == "2L") data <- subset(data,chr == "2R") data <- subset(data,chr == "3L") data <- subset(data,chr == "3R") data <- subset(data,chr == "X") data <- subset(data,chr != "X") m <- data[["mdmel_0f"]]+data[["mdmel_4f"]]+data[["mdmel_2f"]] k4f <- (data[["div_4f"]])/(data[["mdyak_4f"]]) k0f <- (data[["div_0f"]])/(data[["mdyak_0f"]]) k0f <- (data[["div_0f"]]+1)/(data[["mdyak_0f"]]) kins <- (data[["div_ins"]])/(data[["mdyak_ins"]]) ### ASSESSIN COEVOLUTION ### gene <- data.frame( Transcripts = data[["num_transcripts"]], Exons = data[["num_exons"]], m = m, Distance = data[["distance"]], Breadth = data[["bias_dev"]], Expression = data[["max_dev"]], Ki = kins, AAsubstitutions = k0f, Mutation = k4f, #Chr_state = data[["state"]], #Chr_domain = data[["domain"]], #Chromosome = data[["chr"]], Recombination=(data[["comeron_100kb"]]), mess_com = (data[["num_transcripts"]]/data[["num_exons"]]) ) gene <- na.omit(gene) nrow(gene) spcor(gene,method=c("spearman")) Transcripts = data[["num_transcripts"]] Exons = data[["num_exons"]] Distance = data[["distance"]] Breadth = data[["bias_dev"]] Expression = data[["max_dev"]] AAsubstitutions = k0f Mutation = k4f Chr_state = data[["state"]] Chr_domain = data[["domain"]] Chromosome = data[["chr"]] Recombination=(data[["comeron_100kb"]]) mess_com = (data[["num_transcripts"]]/data[["num_exons"]]) ### Distance ### summary(data[["distance"]]) quantile(data[["distance"]],(0:3)/3) density = cut(data[["distance"]],c(0,554,1979,140000)) with(data,tapply(m,density,sum)) summary(density) boxplot(k0f~density,outline=F,xlab="Distance",ylab="Ka") abline(h=median(k0f),col="black") cor.test(k0f,data[["distance"]],method="spearman") cor.test(data[["distance"]],m,method="spearman") cor.test(k0f,m,method="spearman") cor.test(k0f,data[["distance"]]/(m/data[["num_exons"]]),method="spearman") kruskal.test(k0f~density) ### Size ### summary(m) quantile(m,(0:3)/3) m_factor = cut(m,c(0,888,1743,55353)) summary(m_factor) with(data,tapply(m,m_factor,sum)) boxplot(k0f~m_factor,outline=F,xlab="Gene Size",ylab="Ka") abline(h=median(k0f),col="black") cor.test(k0f,m,method="spearman") kruskal.test(k0f~m_factor) ### Transcripts ### quantile(data$num_transcripts,(0:3)/3) hist(data$num_transcripts,breaks=100,xlim=c(0,20)) summary(data[["num_transcripts"]]) with(data,tapply(m,data[["num_transcripts"]],sum)) num_transcripts_factor = cut(data[["num_transcripts"]],c(0,1,2,75)) summary(num_transcripts_factor) with(data,tapply(m,num_transcripts_factor,sum)) boxplot(k0f~num_transcripts_factor,outline=F,xlab="Number of Transcripts/Gene",ylab="Ka") boxplot(k0f~data$num_transcripts,outline=F,xlab="Number of Transcripts/Gene",ylab="Ka") abline(h=median(k0f),col="black") cor.test(k0f,data$num_transcripts,method="spearman") kruskal.test(k0f~num_transcripts_factor) ### Exons ### quantile(data$num_exons,(0:3)/3) hist(data$num_exons,breaks=100,xlim=c(0,20)) summary(data[["num_exons"]]) with(data,tapply(m,data[["num_exons"]],sum)) num_exons_factor = cut(data[["num_exons"]],c(0,3,8,114)) summary(num_exons_factor) with(data,tapply(m,num_exons_factor,sum)) boxplot(k0f~num_exons_factor,outline=F,xlab="Number of Exons/Gene",ylab="Ka") boxplot(k0f~data$num_exons,outline=F,xlab="Number of Exons/Gene",ylab="Ka") abline(h=median(k0f),col="black") cor.test(k0f,data$num_exons,method="spearman") kruskal.test(k0f~num_exons_factor) ### Messenger Complexity ### plot(data[["num_transcripts"]],data[["num_exons"]]) quantile(data[["num_transcripts"]]/data[["num_exons"]],(0:3)/3) summary(data[["num_transcripts"]]/data[["num_exons"]]) hist(data[["num_transcripts"]]/data[["num_exons"]]) mess_com = cut(data[["num_transcripts"]]/data[["num_exons"]],c(0,0.33,0.66,8)) tapply(m,mess_com,sum) summary(mess_com) boxplot(k0f~mess_com,outline=F,xlab="Messenger Complexity",ylab="Ka") abline(h=median(k0f),col="black") boxplot(data[["num_exons"]]~mess_com,outline=F,xlab="Messenger Complexity",ylab="#Exons") boxplot(data[["num_transcripts"]]~mess_com,outline=F,xlab="Messenger Complexity",ylab="#mRNAs") cor.test(k0f,data[["num_transcripts"]]/data[["num_exons"]],method="spearman") cor.test(data[["num_transcripts"]],data[["num_exons"]],method="spearman") kruskal.test(k0f~mess_com) ### Expression ### plot(data[["bias_dev"]],data[["max_dev"]]) summary(data[["max_dev"]]) quantile(data[["max_dev"]],(0:3)/3) expression_factor = cut(data[["max_dev"]],c(0,1.477,1.87,4.4)) summary(expression_factor) tapply(m,expression_factor,sum) boxplot(k0f~expression_factor,outline=F,xlab="Expression",ylab="Ka") abline(h=median(k0f),col="black") cor.test(k0f,data[["max_dev"]],method="spearman") kruskal.test(k0f~expression_factor) ### Breadth ### summary(data[["bias_dev"]]) quantile(data[["bias_dev"]],(0:3)/3) breadth_factor = cut(data[["bias_dev"]],c(0,0.27,0.54,1)) summary(breadth_factor) tapply(m,breadth_factor,sum) boxplot(k0f~breadth_factor,outline=F,xlab="Expression Breadth",ylab="Ka") abline(h=median(k0f),col="black") cor.test(k0f,data[["bias_dev"]],method="spearman") kruskal.test(k0f~breadth_factor) ### Chromosome ### tapply(m,data[["chr"]],sum) summary(data[["chr"]]) boxplot(k0f~data[["chr"]],outline=F,xlab="Chromosome",ylab="Ka") ### Chromatin State and Chromatin Domain ### tapply(m,data[["state"]],sum) tapply(m,data[["domain"]],sum) summary(data[["state"]]) summary(data[["domain"]]) boxplot(k0f~data[["state"]],outline=F,xlab="Chromatin State",ylab="Ka") boxplot(k0f~data[["domain"]],outline=F,xlab="Chromatin Domain",ylab="Ka") ### Recombination ### summary(data[["comeron_100kb"]]) quantile(data[["comeron_100kb"]],(0:3)/3) recombination_factor = cut(data[["comeron_100kb"]],c(0,1.44,2.89,15)) summary(recombination_factor) tapply(m,recombination_factor,sum) boxplot(k0f~recombination_factor,outline=F,xlab="Recombination Rate",ylab="Ka") abline(h=median(k0f),col="black") cor.test(k0f,data[["comeron_100kb"]],method="spearman") kruskal.test(k0f~recombination_factor) ### mutation 4f ### summary(k4f) quantile(k4f,(0:3)/3) mutation_factor = cut(k4f,c(0,0.16,0.20,0.75)) summary(mutation_factor) tapply(m,mutation_factor,sum) boxplot(k0f~mutation_factor,outline=F,xlab="Mutation Rate",ylab="Ka") abline(h=median(k0f),col="black") cor.test(k0f,k4f,method="spearman") kruskal.test(k0f~mutation_factor) ### mutation ins ### summary(kins) quantile(kins,(0:3)/3) mutation_factor = cut(kins,c(0,0.18,0.25,0.7)) summary(mutation_factor) tapply(m,mutation_factor,sum) boxplot(k0f~mutation_factor,outline=F,xlab="Mutation Rate",ylab="Ka") abline(h=median(k0f),col="black") cor.test(k0f,kins,method="spearman") kruskal.test(k0f~mutation_factor) ##### THETA ##### var = 1 cal = 0 dom = 0 lines = 128 while (var < lines) { cal = 1/var dom = dom + cal var = var + 1 } dom #5.4, media harmónica K_watterson <- (data[["seg_ins"]])/(data[["mdmel_ins"]]) watterson = K_watterson/dom head(watterson) summary(watterson) quantile(watterson ,(0:3)/3) watterson_factor = cut(watterson,c(0,0.005,0.013,0.087)) summary(watterson_factor) tapply(m,watterson_factor,sum) boxplot(k0f~watterson_factor,outline=F,xlab="Watterson estimator",ylab="Ka") abline(h=median(k0f),col="black") cor.test(k0f,watterson,method="spearman") kruskal.test(k0f~watterson_factor) qplot(Chr_domain,Recombination, geom=("boxplot"),fill=Chromosome, binwidth=3) + xlab("Chromatin domain") + ylab("Recombination") + scale_fill_brewer(type="seq", palette=3) + theme(axis.title=element_text(face="bold",size="12", color="black"), legend.position="right") + ggtitle("R")
93a05d081ad0c132c736464c565ed6fd6a5f02a5
3ee266f78c11d751c94a0d8ca3d77bc216e4f621
/code/2-prep_names.R
6006b5e0d8f9d9e6651e2fb207c54285a4325c1e
[]
no_license
sakho3600/names_eval
c59a3a2b40e5d1947d38a83c981b56286a3e701b
41f81ee5e9015db27489b49515a52e1125f89471
refs/heads/master
2020-05-09T22:54:35.115245
2017-09-14T15:31:59
2017-09-14T15:31:59
null
0
0
null
null
null
null
UTF-8
R
false
false
4,769
r
2-prep_names.R
rm(list = ls()) gc() # Cole Tanigawa-Lau # Sun Jul 16 10:21:19 2017 # Description: Prepare name strings from 2007 and late-2012 voter registers. library(data.table) library(stringr) library(dplyr) library(multidplyr) library(parallel) library(babynames) source("code/functions.R") # Clean up 2012 name strings with various methods ---- vr12 <- readRDS("data/vr12.rds") # Concatenate common US baby names to remove when cleaning # (these names won't be informative) # Retain common Muslim, which will be helpful in guessing ethnicity comm_muslim <- c(agrep("mohammed", x = babynames$name, ignore.case = TRUE, value = TRUE), agrep("abdul", x = babynames$name, ignore.case = TRUE, value = TRUE), agrep("hussein", x = babynames$name, ignore.case = TRUE, value = TRUE), agrep("fatima", x = babynames$name, ignore.case = TRUE, value = TRUE), agrep("sumaiya", x = babynames$name, ignore.case = TRUE, value = TRUE), "Ayesha", "Aisha", "Farah", "Omar", "Issa", "Hamza", "Ali", "Ibrahim") %>% unique() # Retains roughly 1.7% of unique names, about 78% of the original amount of occurences bnames <- filter(babynames, prop > 6e-4, ! name %in% comm_muslim )$name %>% unique() %>% toupper() # Intialize cluster for parallel processing, split across polling station IDs ---- vr12p <- partition(vr12, psid12) cluster_copy(vr12p, clean_func) cluster_copy(vr12p, bnames) cluster_library(vr12p, "dplyr") # Clean first, middle, and last names first, then paste together later vr12p2 <- group_by(vr12p, psid12) %>% do(first = clean_func(.$FIRST_NAME) %>% str_split("\\s") %>% unlist(), middle = clean_func(.$MIDDLE_NAME) %>% str_split("\\s") %>% unlist(), last = clean_func(.$SURNAME) %>% str_split("\\s") %>% unlist() ) # Build vector of (split) names according to polling station vr12p3 <- group_by(vr12p2, psid12) %>% do(., first = unlist(.$first), middle = unlist(.$middle), last = unlist(.$last), fullname = unlist(c(.$first, .$middle, .$last)), name = unlist(c(.$middle, .$last)) ) # Remove baby names vr12p4 <- group_by(vr12p3, psid12) %>% do(., first = unlist(.$first), middle = unlist(.$middle), last = unlist(.$last), fullname = unlist(.$fullname), name = unlist(.$name), rm_bnames = unlist(.$fullname)[which(! unlist(.$fullname) %in% bnames)] ) # Collect all 2012 names in a single tibble and save ----- vr12_names <- data.table(collect(vr12p4)) # Apply clean_func() once more to all columns, just in case for(jj in 2:ncol(vr12_names)) set(vr12_names, j = jj, value = mclapply(vr12_names[[jj]], clean_func, mc.cores = 6)) saveRDS(vr12_names, "data/vr12_names.rds") # vr12_names <- readRDS("data/vr12_names.rds") # Clear up some memory rm(vr12, vr12p, vr12p2, vr12p3, vr12p4) gc() # Clean 2007 name strings ----- vr07 <- readRDS("data/VR07dt.Rdata") vr07p <- partition(vr07, id07) cluster_copy(vr07p, clean_func) cluster_copy(vr07p, bnames) cluster_library(vr07p, "dplyr") cluster_library(vr07p, "stringr") # Clean first, middle, and last names first, then paste together later vr07p2 <- group_by(vr07p, id07) %>% do(first = str_extract(clean_func(.$oth), "^[A-Z]+") %>% unlist(), middle = gsub(clean_func(.$oth), patt = "^[A-Z]+ ", repl = "", perl = TRUE ) %>% str_split("\\s") %>% unlist(), last = clean_func(.$sur) %>% str_split("\\s") %>% unlist() ) # Build vector of (split) names according to polling station vr07p3 <- group_by(vr07p2, id07) %>% do(., first = unlist(.$first), middle = unlist(.$middle), last = unlist(.$last), fullname = unlist(c(.$first, .$middle, .$last)), name = unlist(c(.$middle, .$last) ) ) # Remove baby names vr07p4 <- group_by(vr07p3, id07) %>% do(., first = unlist(.$first), middle = unlist(.$middle), last = unlist(.$last), fullname = unlist(.$fullname), name = unlist(.$name), rm_bnames = unlist(.$fullname)[which(! unlist(.$fullname) %in% bnames)] ) # Collect names and save vr07_names <- collect(vr07p4) # Apply clean_func() once more to all columns, just in case system.time(for(jj in 2:ncol(vr07_names)) set(vr07_names, j = jj, value = mclapply(vr07_names[[jj]], clean_func, mc.cores = 6))) saveRDS(vr07_names, "data/vr07_names.rds")
6262fbc021a023a846913384a83d44f48ee54179
aba4026c593dc205b2b12735ec51427d0a1d1bd1
/LFR_Data_Genration_File.R
daa527c258709884fb064cc518fd05bf63d6f109
[]
no_license
Adnanbukhari123/SMA
023256d2ad59ae7c9de8188a0947133df298c187
a4a77795b2053aee370f272f2245597292b46bed
refs/heads/main
2023-08-22T00:46:46.737724
2021-11-01T13:38:56
2021-11-01T13:38:56
423,462,535
0
0
null
null
null
null
UTF-8
R
false
false
2,243
r
LFR_Data_Genration_File.R
library(ggplot2) library(igraph) library(writexl) library(readxl) config_df = as.data.frame(read_excel("SMA_Project/Configurations.xlsx")) col_names <- c( "SNO","FileNO","n","pt", "n0", "mu","multilevel_community_modularity","walktrap_community_modularity", "infomap_community_modularity", "louvain_community_modularity", "label_pop_community_modularity", "fast_community_modularity", "multilevel_community_size","walktrap_community_size", "infomap_community_size", "louvain_community_size", "label_pop_community_size", "fast_community_size", "clustering_coefficient", "average_path_length","number_of_nodes") get_modularity_LFR<-function(){ for(folder_name in c("LFR")){ full_path = paste("/home/adnan/Documents/",folder_name,'/',sep="") df = data.frame(matrix(nrow = 0, ncol = length(col_names))) colnames(df) = col_names for(file_number in 1:375){ print(paste("File number", file_number)) graph <- read.graph(paste(full_path,file_number,'.gml', sep=""), format=c('gml')) wc <- multilevel.community(graph) walktrap_community <- cluster_walktrap(graph) infomap_community <- cluster_infomap(graph) louvain_community <- cluster_louvain(graph) label_pop_community <-cluster_label_prop(graph) fast_greedy_community<-cluster_fast_greedy(graph) df[nrow(df) + 1,] <- c(file_number, paste(file_number,'.gml',sep=""), 0,0,0,0,modularity(wc), modularity(walktrap_community), modularity(infomap_community), modularity(louvain_community), modularity(label_pop_community), modularity(fast_greedy_community),length(wc), length(walktrap_community), length(infomap_community), length(louvain_community), length(label_pop_community), length(fast_greedy_community), transitivity(graph),average.path.length(graph),vcount(graph)) } df['n']= config_df['n'] df['pt']= config_df['pt'] df['n0']=config_df['n0'] df['mu']=config_df['mu'] write_xlsx(df, paste("/home/adnan/Documents/",folder_name,'.xlsx', sep='')) } return (df) } df_LFR = get_modularity_LFR()
324030ecf95d22a10732a183e8b8a8d06c37f240
595a4ead5c1d7761c429d9dde8f3c84e5a6e99ca
/R/power_ftest.R
ca940231072dc598753a3d6138fc4497feb4852d
[ "MIT" ]
permissive
arcaldwell49/Superpower
163804ae7682be43c3f7241671948bc73f1706ea
ed624538f6b28d9243720994b3428edfe80b8bfa
refs/heads/master
2023-02-16T19:24:16.312351
2023-02-11T00:20:47
2023-02-11T00:20:47
206,843,269
60
17
NOASSERTION
2023-02-10T23:41:36
2019-09-06T17:28:44
HTML
UTF-8
R
false
false
5,309
r
power_ftest.R
#' Power Calculations for an F-test #' #' Compute power of test or determine parameters to obtain target power. Inspired by the pwr.f2.test function in the pwr package, but allows for varying noncentrality parameter estimates for a more liberal (default in pwr.f2.test) or conservative (default in this function) estimates (see Aberson, Chapter 5, pg 72). #' #' @param num_df degrees of freedom for numerator #' @param den_df degrees of freedom for denominator #' @param cohen_f Cohen's f effect size. Note: this is the sqrt(f2) if you are used to using pwr.f2.test #' @param alpha_level Alpha level used to determine statistical significance. #' @param beta_level Type II error probability (power/100-1) #' @param liberal_lambda Logical indicator of whether to use the liberal (cohen_f^2\*(num_df+den_df)) or conservative (cohen_f^2\*den_df) calculation of the noncentrality (lambda) parameter estimate. Default is FALSE. #' #' @return #' num_df = degrees of freedom for numerator, #' den_df = degrees of freedom for denominator, #' cohen_f = Cohen's f effect size, #' alpha_level = Type 1 error probability, #' beta_level = Type 2 error probability, #' power = Power of test (1-beta_level\*100%), #' lambda = Noncentrality parameter estimate (default = cohen_f^2\*den_df, liberal = cohen_f^2\*(num_df+den_df)) #' #' @examples #' design_result <- ANOVA_design(design = "2b", #' n = 65, #' mu = c(0,.5), #' sd = 1, #' plot = FALSE) #' x1 = ANOVA_exact2(design_result, verbose = FALSE) #' ex = power.ftest(num_df = x1$anova_table$num_df, #' den_df = x1$anova_table$den_df, #' cohen_f = x1$main_result$cohen_f, #' alpha_level = 0.05, #' liberal_lambda = FALSE) #' @section References: #' Cohen, J. (1988). Statistical power analysis for the behavioral sciences (2nd ed.). Hillsdale,NJ: Lawrence Erlbaum. #' Aberson, C. (2019). Applied Power Analysis for the Behavioral Sciences (2nd ed.). New York,NY: Routledge. #' @importFrom stats uniroot optimize #' @export #' power.ftest <- function(num_df = NULL, den_df = NULL, cohen_f = NULL, alpha_level = Superpower_options("alpha_level"), beta_level = NULL, liberal_lambda = Superpower_options("liberal_lambda")) { #if (sum(sapply(list(num_df, den_df, cohen_f, beta_level, alpha_level), is.null)) != # 1) { # stop("exactly one of num_df, den_df, cohen_f, beta_level, and alpha_level must be NULL") #} if (!is.null(cohen_f)) { if (any(cohen_f < 0)) { stop("cohen_f must be positive") } } if (!is.null(num_df) && any(num_df < 1)) { stop("degree of freedom num_df for numerator must be at least 1") } if (!is.null(den_df) && any(den_df < 1)) { stop("degree of freedom den_df for denominator must be at least 1") } if (!is.null(alpha_level) && !is.numeric(alpha_level) || any(0 > alpha_level | alpha_level > 1)) { stop(sQuote("alpha_level"), " must be numeric in [0, 1]") } if (!is.null(beta_level) && !is.numeric(beta_level) || any(0 > beta_level | beta_level > 1)) { stop(sQuote("beta_level"), " must be numeric in [0, 1].") } if (liberal_lambda == TRUE) { p.body <- quote({ pf(qf(alpha_level, num_df, den_df, lower.tail = FALSE), num_df, den_df, cohen_f^2 * (num_df+den_df+1), lower.tail = FALSE) }) } else { p.body <- quote({ pf(qf(alpha_level, num_df, den_df, lower.tail = FALSE), num_df, den_df, cohen_f^2 * (den_df), lower.tail = FALSE) }) } if (!is.null(beta_level)){ pow = 1 - beta_level } if (is.null(beta_level)){ pow <- eval(p.body) } else if (is.null(num_df)) { p.body2 = p.body[2] p.body2 = gsub("alpha_level", alpha_level, p.body2) p.body2 = gsub("den_df", den_df, p.body2) p.body2 = gsub("cohen_f", cohen_f, p.body2) num_df = optimize(f = function(num_df) { abs(eval(parse(text=paste(p.body2)))-pow) }, c(0,1000))$min #num_df <- uniroot(function(num_df) eval(p.body) - pow, c(1, 100))$root } else if (is.null(den_df)) { den_df <- uniroot(function(den_df) eval(p.body) - pow, c(1 + 1e-10, 1e+09))$root } else if (is.null(cohen_f)) { cohen_f <- uniroot(function(cohen_f) eval(p.body) - pow, c(1e-07, 1e+07))$root } else if (is.null(alpha_level)) { alpha_level <- uniroot(function(alpha_level) eval(p.body) - pow, c(1e-10, 1 - 1e-10))$root } else { stop("internal error: exactly one of num_df, den_df, cohen_f, beta_level, and alpha_level must be NULL") } power_final = pow * 100 beta_level = 1 - pow METHOD <- "Power Calculation for F-test" structure(list(num_df = num_df, den_df = den_df, cohen_f = cohen_f, alpha_level = alpha_level, beta_level = beta_level, power = power_final, method = METHOD), class = "power.htest") }
bb6235a4ef8c6afb10ac8116835842fbe8904340
642d338221f44aad742b39230cffcbc297f48306
/R/getANTsRData.R
51a3ef9f194471840fb2b7de34269e8858d304b0
[]
no_license
stnava/itkImageR
3577ccb5785893c510f6e0fabd6a68d5d6c095a2
8b218e81d8e3cc642c8891a4eb4c43dc941cf870
refs/heads/master
2016-09-05T14:29:26.851337
2013-11-25T22:53:34
2013-11-25T22:53:34
null
0
0
null
null
null
null
UTF-8
R
false
false
2,260
r
getANTsRData.R
getANTsRData <- function(fileid, usefixedlocation = FALSE) { library(tools) myusage <- "usage: getANTsRData(fileid = whatever , usefixedlocation = TRUE )" if (missing(fileid)) { print(myusage) return(NULL) } # ch2b = brodmann ch2a = aal mnib = brodmann mnia = all mnit = tracts myurl <- switch(fileid, r16 = "http://placid.nlm.nih.gov/download?items=10764", r64 = "http://placid.nlm.nih.gov/download?items=10765", KK = "http://placid.nlm.nih.gov/download?items=10766", ADNI = "http://placid.nlm.nih.gov/download?folders=238", K1 = "http://www.nitrc.org/frs/downloadlink.php/2201", BT = "http://placid.nlm.nih.gov/download?items=10767", AB = "http://placid.nlm.nih.gov/download?items=10753", ch2 = "http://placid.nlm.nih.gov/download?items=10778", ch2b = "http://placid.nlm.nih.gov/download?items=10780", ch2a = "http://placid.nlm.nih.gov/download?items=10784", mni = "http://placid.nlm.nih.gov/download?items=10785", mnib = "http://placid.nlm.nih.gov/download?items=10787", mnia = "http://placid.nlm.nih.gov/download?items=10786", mnit = "http://placid.nlm.nih.gov/download?items=11660") myext <- ".nii.gz" if (fileid == "ADNI" | fileid == "K1") myext <- ".zip" tdir <- tempdir() # for temporary storage tfn <- tempfile(pattern = "antsr", tmpdir = tdir, fileext = myext) # for temporary storage if (usefixedlocation == TRUE) { tdir <- system.file(package = "ANTsR") # for a fixed location tfn <- paste(tdir, "/html/", fileid, myext, sep = "") # for a fixed location } if (!file.exists(tfn)) download.file(myurl, tfn) if (fileid == "ADNI" | fileid == "K1") { unzip(tfn) return(tfn) } # could use md5sum mymd5 <- switch(fileid, r16 = "37aaa33029410941bf4affff0479fa18", r64 = "8a629ee7ea32013c76af5b05f880b5c6", KK = "397a773658558812e91c03bbb29334bb", BT = "eb1f8ee2bba81fb80fed77fb459600f0", AB = "d38b04c445772db6e4ef3d2f34787d67", ch2 = "501c45361cf92dadd007bee55f02e053", ch2b = "5db6c10eb8aeabc663d10e010860465f", ch2a = "caf2d979a7d9c86f515a5bc447856e7c", mnit = "dab456335a4bfa2b3bc31e9882699ee9") if (!is.null(mymd5)) if (md5sum(tfn) != mymd5) { print("checksum failure") return(NULL) } return(tfn) }
3430d7113a927cbb3161afbecf972cb4e5d2451a
21d326b9b3f7acc825ee422e58a20ab1bfc4ab57
/ui.R
51205d1927973bdb5222f3ffed5c4ebeafcd1d83
[]
no_license
jiayi9/diagrammer
8a9c0d01886bb0e5fb642f6757f4fd8af61ca485
549935c04e23b2d356b13d7783406e379f1ccf87
refs/heads/master
2020-03-21T07:15:47.304190
2018-06-22T07:34:45
2018-06-22T07:34:45
138,270,521
0
0
null
null
null
null
UTF-8
R
false
false
182
r
ui.R
library(shiny) shinyUI(fluidPage( navbarPage("Analytics", tabPanel("Example", DiagrammeR::grVizOutput("CHART",height = 700) ) ) ))
7717f7bd52965fc0e76407c14506b2e2b982c3cf
6aed7b75c2bb33695908366e0faa14dfa42e5b35
/R/code/total_entropy_utility.R
646154d4c116cbeb323f3087f3eae573028886fd
[]
no_license
ebonilla/sequential_design_for_predator_prey_experiments
e026f1e876302d2f37f6c4443a5fb1cef4271522
adc76644a203b922b6a586b0e0dafd393934ce6d
refs/heads/master
2022-07-11T11:46:56.192525
2020-05-13T04:07:33
2020-05-13T04:07:33
null
0
0
null
null
null
null
UTF-8
R
false
false
2,679
r
total_entropy_utility.R
#-----------------------------------------------------------------------------------------------# # Script Name: total_entropy_utility # # Author: Hayden Moffat # # email: hayden.moffat@hdr.qut.edu.au # # # # This R script determines the next design point from the discrete design space which maximises # # the total entropy utility. # # # # #-----------------------------------------------------------------------------------------------# Nt <- Nmin:Nmax # possible designs utility <- matrix(0, length(Nt), 1) # initialise utility values for (j in 1:length(Nt)){ log_wsum = matrix(0, K, Nt[j]+1) B <- matrix(0, K, Nt[j]+1) for (mod in 1:K){ # Compute the log likelihood for each of the possible y values using the set of particles from model mod parameters <- find_parameters(theta[,,mod], Nt[j], time, models[mod]) y <- 0:Nt[j] llh <- log_lik(y, Nt[j], parameters[,1], parameters[,2], models[mod]) # Calculate the log likelihood of observing the datapoint [Nt(j), y] log_w_hat <- log(W[,mod]) + llh # updated log unnormalised weights of particles if y was the new observation log_wsum[mod,] = logsumexp(log_w_hat,1) log_W_hat = sweep(log_w_hat, 2, log_wsum[mod,]) # updated log normalised weights b = llh * exp(log_W_hat) # multiply log likelihood by normalised weights b[is.nan(b)] <- 0 B[mod,] = colSums(b) rm(parameters, y, llh, log_w_hat, log_W_hat) } log_Z_n = log_Z - logsumexp(log_Z,0) # normalised evidence log_p_y = logsumexp(sweep(t(log_wsum), 2, log_Z_n, FUN = '+'), 2) # posterior predictive probabilities log_p_y = as.matrix(log_p_y - logsumexp(log_p_y,0), ncol = 1) # normalised posterior predictive probabilities # Determine the expected utility utility[j] = exp(log_Z_n)%*% matrix(rowSums(exp(log_wsum) * B), ncol = 1) - (t(log_p_y) %*% exp(log_p_y)) rm(log_wsum, B, b, log_p_y, log_Z_n) } # Display the optimal design point idx = which(utility == max(utility)) cat(paste0('Optimal design point at ', Nt[idx])) data[i,1] <- Nt[idx]
80a8fd787dfd93ac3a41f33c7772cad69a765b8a
10c2c5d15f68e6b01aea824e8515083faee9d77c
/R/plot.PAM.R
9dca37d96373f6299118660a79ddf39d10a7d2b0
[]
no_license
cran/PAMhm
0d285b078cb745a32e6a09355bba0af6ff9f8a56
af3755892dc8e20d5a98d41b653cd061495ee479
refs/heads/master
2023-07-27T13:12:33.167946
2021-09-06T06:50:02
2021-09-06T06:50:02
403,674,607
0
0
null
null
null
null
UTF-8
R
false
false
2,735
r
plot.PAM.R
#' @noRd plot.PAM <- function (clust, what, res.folder = ".", cols = "bwr", trim = NULL, winsorize.mat = TRUE, autoadj = TRUE, pdf.width = 13, pdf.height = 10, labelwidth = 0.6, labelheight = 0.25, reorder = c(TRUE, TRUE), r.cex = 0.5, c.cex = 1, PDF = TRUE, PNG = FALSE, main = NULL, file = main, shiny = FALSE) { if (autoadj) { adj.l <- plotAdjust(clust$dat) } else { adj.l <- list(pdf.width = pdf.width, pdf.height = pdf.height, labelwidth = labelwidth, labelheight = labelheight, r.cex = r.cex, c.cex = c.cex) } if (is.null(file)) { filename.pam <- paste("PAM clustering of", what) } else { filename.pam <- file } if (shiny) { make_heatmap(clust, what, cols = cols, trim = trim, winsorize.mat = winsorize.mat, pdf.width = adj.l$pdf.width, pdf.height = adj.l$pdf.height, labelwidth=adj.l$labelwidth, labelheight=adj.l$labelheight, reorder=reorder, r.cex=adj.l$r.cex, c.cex=adj.l$c.cex, project.folder = res.folder, main=main) } else { if (PDF) { pdf.name <- file.path(res.folder, paste(filename.pam, ".pdf", sep="")) pdf(pdf.name, width=adj.l$pdf.width, height=adj.l$pdf.height) invisible(make_heatmap(clust, what, cols = cols, trim = trim, winsorize.mat = winsorize.mat, labelwidth=adj.l$labelwidth, labelheight=adj.l$labelheight, reorder=reorder, r.cex=adj.l$r.cex, c.cex=adj.l$c.cex, main=main)) dev.off() } if (PNG) { png.name <- file.path(res.folder, paste(filename.pam, ".png", sep="")) png(png.name, width=adj.l$pdf.width, height=adj.l$pdf.height, units="in") make_heatmap(clust, what, cols = cols, trim = trim, winsorize.mat = winsorize.mat, pdf.width = adj.l$pdf.width, pdf.height = adj.l$pdf.height, labelwidth=adj.l$labelwidth, labelheight=adj.l$labelheight, reorder=reorder, r.cex=adj.l$r.cex, c.cex=adj.l$c.cex, project.folder = res.folder, PNG = TRUE, main=main) if (all(unlist(plyr::llply(png.name, is.null)))) { png.name <- NULL } if (!PDF) { return(png.name) } } if (!PDF && !PNG) { make_heatmap(clust, what, cols = cols, trim = trim, winsorize.mat = winsorize.mat, pdf.width = adj.l$pdf.width, pdf.height = adj.l$pdf.height, labelwidth=adj.l$labelwidth, labelheight=adj.l$labelheight, reorder=reorder, r.cex=adj.l$r.cex, c.cex=adj.l$c.cex, project.folder = res.folder, main=main) return() } if (PDF) { return(pdf.name) } else { return(NULL) } } }
546068f9b11295f72bd23c5ccbabbbed6a78b617
91ae8c92263dacf2d0072d434e64171e6a77e143
/chapter 14.4.4.1 exercise.r
3f9b13de3721d208dbe6c11f1bdd9d9911f9bd87
[]
no_license
lawrencekurniawan/r4ds
da41599a37a7fa5a1646aec8a0298d220faefaaa
bdcd898302c69ea774886ef5cf533763b2d419e2
refs/heads/master
2020-05-23T23:06:12.466441
2017-03-14T16:34:10
2017-03-14T16:34:10
84,798,748
0
1
null
2017-03-13T08:39:06
2017-03-13T07:53:58
null
UTF-8
R
false
false
750
r
chapter 14.4.4.1 exercise.r
library(tidyverse) library(stringr) #q1 regex <- "(the) ([A-z]+)" #replace (the) with (number) to find that there is 0 match has_number <- sentences %>% str_subset(regex) %>% head(10) str_view_all(has_number, regex) #below is alternative with tibble to generate both the sentence and the match in the same tibble tibble(sentence = sentences) %>% tidyr::extract(sentence, c("word", "number"), regex, remove = FALSE) #q2 regex2 <- "([A-z]+)\\'([A-z]*)" tibble(sentence = sentences) %>% tidyr::extract( sentence, c("before", "after"), regex2, remove = FALSE ) #the str_subset way has_apostrophe <- str_subset(sentences, regex2) str_view_all(has_apostrophe, regex2)
0715582457c5bb228d458bbb7c0cfc1724c5decc
21327fc1d5030fc4bb69e6505b66b471290fae5e
/overrideTestValue.R
e3b3c81658b3aecf493fae7c94e2cd72237418e7
[]
no_license
sportebois/Rbash
995f6c6aac874cde109c7ae661d76cc49d005421
de809e643055f4856c5175bb44e71bdb4f4d53f3
refs/heads/master
2021-01-10T03:42:28.372645
2016-03-14T01:23:53
2016-03-14T01:23:53
53,816,427
0
0
null
null
null
null
UTF-8
R
false
false
105
r
overrideTestValue.R
#overrideTestValue.R print("sourcing 'overideTest2Value.R'") options(test2="defaultTest2InOverrideFile")
2011e6901bbabf2271f98a787171e3b7ca092f57
a0971d0f9a66d32318e2f1eb98ea2b4766288839
/man/projMat.Rd
43da5adfc86ed2de438577945a31e3370649241f
[]
no_license
cran/infoDecompuTE
cd4ed6500b6fc3353cb87af1c63f3f400aca3e33
be77a310872650b7c2eba1bfb811d6f261b65d82
refs/heads/master
2020-06-06T21:24:21.145140
2020-03-28T08:10:02
2020-03-28T08:10:02
17,696,778
0
0
null
null
null
null
UTF-8
R
false
true
429
rd
projMat.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/projMat.R \name{projMat} \alias{projMat} \title{Construct a Projection Matrix} \usage{ projMat(X) } \arguments{ \item{X}{a square matrix.} } \value{ A square matrix. } \description{ Compute the projection matrix from a square matrix. } \examples{ m = matrix(1, nrow = 10, ncol = 3) projMat(m) } \author{ Kevin Chang }
9b69690039461a2f9c69877991f60a002fabba8f
7e06448831ee45fef970b6f705e08b1de01911e1
/Basic R_1/GraficosTarea.R
a6d35fd9f4a58163c34a56c8749a0cb3d31f3fc7
[]
no_license
ejgarcia1991/UniversityProjects
e9a3e5cfbcbdfe06a5ff11ba4eb5f54daa7faeca
334aa97058c6f17a183ad48ab289e1bb22488060
refs/heads/main
2023-02-18T06:27:01.277050
2021-01-19T16:09:05
2021-01-19T16:09:05
330,946,626
0
0
null
null
null
null
UTF-8
R
false
false
2,260
r
GraficosTarea.R
#Ejercicio 1 #Mostrar graficamente la informacion correspondiente a summary(iris[1:4]). #Pista: uso de boxplot boxplot(iris[1:4]) #Ejercicio 2 #Rellenar una matriz nrow = 200, ncol = 4, con numero aleatorios cada #columna, supongamos que son las tasas de exito en clasificacion #correspondiente a 4 algoritmos distintos. Pintar una grafica con las curvas de cada, #identificando cada uno de los algoritmos con su leyenda. m<- matrix(sample(1:10000,800),200,4) opar <- par(no.readonly = TRUE) plot(m[,1],type="l",col="red") lines(m[,2],col="blue") lines(m[,3],col="brown") lines(m[,4]) legend(x=160, y=10000,legend=c("alg1","alg2","alg3","alg4"), lty=c(1,2,3,4), col=c("red", "blue","brown","black")) #Ejercicio 3 #Ejecuta las siguientes instrucciones: library(MASS); str(quine); xtabs(~ Age,data=quine); #prop.table(xtabs(~ Age,data=quine)) Haz un grafico compuesto, con #dos graficas de barras correspondientes a xtabs y prop.table, la frecuencia #absoluta y frecuencia relativa de las edades. library(MASS) str(quine) d1<-xtabs(~ Age,data=quine) d2<-prop.table(xtabs(~ Age,data=quine)) opar<-par(no.readonly=TRUE) par(mfrow = c(1,2)) barplot(xtabs(~ Age,data=quine),main="Frecuencia absoluta") barplot(prop.table(xtabs(~ Age,data=quine)), main="Frecuencia relativa") par(opar) #Ejercicio 4 #Representa la misma informacion anterior mediante graficas tipo pie y #dotchart con tıtulo. En pie, fija colores y sentido horario. library(MASS) str(quine) d1<-xtabs(~ Age,data=quine) d2<-prop.table(xtabs(~ Age,data=quine)) opar<-par(no.readonly=TRUE) par(mfrow = c(2,2)) dotchart(d1,main="Frecuencia absoluta") dotchart(d2, main="Frecuencia relativa") pie(d1,clockwise = TRUE,col = c("red","blue","brown","black"),main="Frecuencia absoluta") pie(d2,clockwise = TRUE,col = c("red","blue","brown","black"), main="Frecuencia relativa") par(opar) #Ejercicio 5 #Sea un dataset cars, representar los puntos dist vs speed, esto es, el #atributo dist en ordenadas. Sea m, m = lm(speed~dist, data=cars) el #resultado de aplicar un ajuste mediante regresion lineal. El valor resultado #es una recta en forma pinta la lınea de ajuste del modelo m, en rojo. Pista: abline. library(CARS) m<-lm(speed~dist,data=cars) plot(cars$dist,cars$speed) abline(m,col="red") read_
14a40675214aa9e86b11ede969d57ec20a3606cc
9ad4b4acb8bd2b54fd7b82526df75c595bc614f7
/Plot/PlotEloRD_PBMC_Umap.R
9ae7d567452dae904210d767b9f3ae3bbc111480
[]
no_license
sylvia-science/Ghobrial_EloRD
f27d2ff20bb5bbb90aa6c3a1d789c625540fbc42
041da78479433ab73335b09ed69bfdf6982e7acc
refs/heads/master
2023-03-31T14:46:27.999296
2021-04-02T15:09:49
2021-04-02T15:09:49
301,811,184
0
0
null
null
null
null
UTF-8
R
false
false
8,632
r
PlotEloRD_PBMC_Umap.R
library(wesanderson) library(RColorBrewer) library(scico) library(pals) library(nord) library(palettetown) # Plot EloRD_PBMC_noNPBMC Umaps folder = paste0('/home/sujwary/Desktop/scRNA/Output/Harmony/Batch_Sample_Kit/Cluster/PCA30/res3/Plots/Paper/EloRD_PBMC/') data_harmony_run_label_remove = data_harmony_run_label_remove[, !(Idents(data_harmony_run_label_remove) == 'T-cell' & data_harmony_run_label_remove@reductions[["umap"]]@cell.embeddings[,2] < 2.5)] data_harmony_run_label_remove = data_harmony_run_label_remove[, !(Idents(data_harmony_run_label_remove) == 'CD8+ T-cell' & data_harmony_run_label_remove@reductions[["umap"]]@cell.embeddings[,2] < 2.5)] data_harmony_run_label_remove = data_harmony_run_label_remove[, !(Idents(data_harmony_run_label_remove) == 'Plasma cell' & data_harmony_run_label_remove@reductions[["umap"]]@cell.embeddings[,1] > -5)] plot = DimPlot(data_harmony_run_label_remove,pt.size = 0.7, reduction = "umap",label = TRUE,label.size = 3) print(plot) num_cluster = length(unique(Idents(data_harmony_run_label_remove))) values = colorRampPalette(brewer.pal(12, "Accent"))(num_cluster) values = colorRampPalette(wes_palette("Zissou1"))(num_cluster) values = scico(num_cluster, palette = 'roma') values = as.vector(ocean.delta(num_cluster)) values = rainbow(num_cluster) # Bright but not horrible values = colorRampPalette(brewer.pal(11, "Paired"))(num_cluster) # Nice pastel feel values = colorRampPalette(brewer.pal(8, "Dark2"))(num_cluster) # Too spooky str = '_nolabel' str = '' labelTF = T values = hsv(seq(0, 1 - 1/num_cluster,length.out = num_cluster), .8, .85) folder = paste0('/home/sujwary/Desktop/scRNA/Output/Harmony/Batch_Sample_Kit/Cluster/PCA30/res3/Plots/Paper/EloRD_PBMC/') dir.create(folder, recursive = T) pathName <- paste0(folder,'ClusterUmapAll_PBMC_','hsv',str,'.pdf') pdf(file=pathName, width = 8,height = 6) fontSize = 12 plot = DimPlot(data_harmony_run_label_remove,pt.size = 0.7, reduction = "umap",label = labelTF, cols =values, shape.by = NULL) plot = plot + theme( legend.title = element_text( size = fontSize), legend.text = element_text( size = fontSize)) plot = plot +theme(axis.text=element_text(size=fontSize), axis.title=element_text(size=fontSize,face="bold")) print(plot) dev.off() values = colorRampPalette(brewer.pal(11, "Paired"))(num_cluster) # Nice pastel feel pathName <- paste0(folder,'ClusterUmapAll_PBMC_','Paired',str,'.pdf') pdf(file=pathName, width = 8,height = 6) fontSize = 12 plot = DimPlot(data_harmony_run_label_remove,pt.size = 0.7, reduction = "umap",label = labelTF, cols =values,shape.by = NULL, raster = F) plot = plot + theme( legend.title = element_text( size = fontSize), legend.text = element_text( size = fontSize)) plot = plot +theme(axis.text=element_text(size=fontSize), axis.title=element_text(size=fontSize,face="bold")) print(plot) dev.off() ############### # T Cell ############### str = '_nolabel' str = '' labelTF = T for (i in 1:40){ pokedex(10*i, 10) } Ident_order = c('Naive CD8+ T-cell', 'Naive CD4+ T-cell','IFN+ CD4+ T-cell','TSCM','Stim Naive CD4+ T-cell', 'cTreg','eTreg','CD4+ TCM','TRM','Th2','Th17','aTh17','CCL5+ CD4+ T-cell', 'CD8+ TCM','GZMK+ CD8+ T-cell','GZMK+ CCL3+ CCL4+ CD8+ T-cell','GZMH+ GZMB+ CD8+ T-cell','TEMRA') all(Ident_order %in% unique(Idents(data_run_subset_label) )) data_idents = unique(Idents(data_run_subset_label)) Ident_order[!(Ident_order %in%data_idents )] data_idents[!(data_idents %in%Ident_order )] data_run_subset_label_remove = data_run_subset_label[,Idents(data_run_subset_label) %in% Ident_order] plot = DimPlot(data_run_subset_label_remove,pt.size = 0.7, reduction = "umap",label = TRUE,label.size = 3) print(plot) Idents(data_run_subset_label_remove) = factor(as.character(Idents(data_run_subset_label_remove)),Ident_order) num_cluster = length(unique(Idents(data_run_subset_label_remove))) color1 = 'kingdra' values1 = colorRampPalette(ichooseyou(pokemon = color1, spread = NULL))(6) color2 = 'mewtwo' values2 = colorRampPalette(ichooseyou(pokemon = color2, spread = NULL))(6) values3 = colorRampPalette(ichooseyou(pokemon = 'magcargo', spread = NULL))(5) values = c(values1,values2,values3) pathName <- paste0(folder,'ClusterUmap_Tcell_',color1,'_',color2,str,'.pdf') pdf(file=pathName, width = 8,height = 8) fontSize = 8 plot = DimPlot(data_run_subset_label_remove,pt.size = 0.5, reduction = "umap",label = labelTF, cols =values) plot = plot + theme( legend.title = element_text( size = fontSize), legend.text = element_text( size = fontSize)) plot = plot +theme(axis.text=element_text(size=fontSize), axis.title=element_text(size=fontSize,face="bold")) print(plot) dev.off() ################################ ### Monocytes ################################# str = '_nolabel' str = '' labelTF = T Ident_order = c('cDC1','cDC2', 'sDC', 'SELL+ CD14+ Mono','sMono','TGFb1+ CD14+ Mono', 'IFN+ Mono','CD14+ CD16+ Mono','CD16+ Mono') all(Ident_order %in% unique(Idents(data_run_subset_label) )) data_idents = unique(Idents(data_run_subset_label)) Ident_order[!(Ident_order %in%data_idents )] data_idents[!(data_idents %in%Ident_order )] Ident_order[!(Ident_order %in% unique(Idents(data_run_subset_label_remove) ))] data_run_subset_label_remove = data_run_subset_label[,Idents(data_run_subset_label) %in% Ident_order] plot = DimPlot(data_run_subset_label_remove,pt.size = 0.7, reduction = "umap",label = TRUE,label.size = 3) print(plot) #tmp = unique(Idents(data_run_subset_label_remove))[3] Idents(data_run_subset_label_remove) = factor(as.character(Idents(data_run_subset_label_remove)),Ident_order) num_cluster = length(unique(Idents(data_run_subset_label_remove))) color1 = 'venonat' values1 = colorRampPalette(ichooseyou(pokemon = color1, spread = NULL))(3) color2 = 'girafarig' values2 = colorRampPalette(ichooseyou(pokemon = color2, spread = NULL))(6) #values2 = values2[!(values2 %in% c('#F8F8F8'))] values = c(values1,values2) #color1 = 'magcargo' #values1 = colorRampPalette(ichooseyou(pokemon = color1, spread = NULL))(num_cluster) #values = values1 pathName <- paste0(folder,'ClusterUmap_Mono_',color1,'_',color2,str,'.pdf') pdf(file=pathName, width = 8,height = 6) fontSize = 12 plot = DimPlot(data_run_subset_label_remove,pt.size = 0.5, reduction = "umap",label = labelTF, cols =values) plot = plot + theme( legend.title = element_text( size = fontSize), legend.text = element_text( size = fontSize)) plot = plot +theme(axis.text=element_text(size=fontSize), axis.title=element_text(size=fontSize,face="bold")) print(plot) dev.off() ######################### ## NK ######################### str = '_EloRD_PBMC' labelTF = T Ident_order = c('CD56bright','aCCL3+ CD56dim','NFkB-high','cCD56dim','Tgd') all(Ident_order %in% unique(Idents(data_run_subset_label) )) data_idents = unique(Idents(data_run_subset_label)) Ident_order[!(Ident_order %in%data_idents )] data_idents[!(data_idents %in%Ident_order )] Ident_order[!(Ident_order %in% unique(Idents(data_run_subset_label_remove) ))] data_run_subset_label_remove = data_run_subset_label[,Idents(data_run_subset_label) %in% Ident_order] plot = DimPlot(data_run_subset_label_remove,pt.size = 0.7, reduction = "umap",label = TRUE,label.size = 3) print(plot) #tmp = unique(Idents(data_run_subset_label_remove))[3] Idents(data_run_subset_label_remove) = factor(as.character(Idents(data_run_subset_label_remove)),Ident_order) num_cluster = length(unique(Idents(data_run_subset_label_remove))) color1 = 'magmar' values1 = colorRampPalette(ichooseyou(pokemon = color1, spread = NULL))(5) values = c(values1) #color1 = 'magcargo' #values1 = colorRampPalette(ichooseyou(pokemon = color1, spread = NULL))(num_cluster) #values = values1 pathName <- paste0(folder,'ClusterUmap_NK_',color1,str,'.pdf') pdf(file=pathName, width = 8,height = 6) fontSize = 12 plot = DimPlot(data_run_subset_label_remove,pt.size = 0.5, reduction = "umap",label = labelTF, cols =values) plot = plot + theme( legend.title = element_text( size = fontSize), legend.text = element_text( size = fontSize)) plot = plot +theme(axis.text=element_text(size=fontSize), axis.title=element_text(size=fontSize,face="bold")) print(plot) dev.off()
746cd6094d78acef6684c00019f79bdc80982b88
ebfa2d15c93474e0118f8bec9987d135c45bf42d
/format_process_data.R
a3d03d6f6af9ed5e3cf22b0d10df8441ec145834
[]
no_license
daviinada/dashboard_precipitacao
983ce5aa48203fd5b3d746e6f041e62626750097
bc76e174e0fb13efd1698550a51a18e11ea08461
refs/heads/master
2020-03-16T04:00:13.074074
2018-05-08T12:59:22
2018-05-08T12:59:22
132,500,676
0
0
null
null
null
null
UTF-8
R
false
false
5,686
r
format_process_data.R
library(ggplot2) library(dplyr) library(tidyr) library(readxl) library(lubridate) library(plotly) library(heatmaply) library(qgraph) library(highcharter) library(dygraphs) library(d3heatmap) setwd('/home/toshi/Desktop/work_butanta/dashboard_precipitacao/') raw_data <- read_excel(path = 'tabela_precipitacao_tome_acu.xlsx') raw_data <- as.data.frame(raw_data) head(raw_data) firstup <- function(x) { substr(x, 1, 1) <- toupper(substr(x, 1, 1)) x } raw_data_gather <- raw_data %>% gather(key= month, value= precipitation_mm, -day, -year) %>% mutate(month_numeric = match(firstup(month), month.abb), date = ymd(paste(year, month_numeric, day, sep = '-'))) str(raw_data_gather) # Cleaning miss values raw_data_gather$precipitation_mm[ which(raw_data_gather$precipitation_mm == '0') ] <- NA raw_data_gather$precipitation_mm[ which(raw_data_gather$precipitation_mm == '-') ] <- NA raw_data_gather$precipitation_mm <- as.numeric(raw_data_gather$precipitation_mm) # Formating data raw_data_gather$day <- as.factor(raw_data_gather$day) raw_data_gather$month <- as.factor(raw_data_gather$month) raw_data_gather$year <- as.factor(raw_data_gather$year) head(raw_data_gather) order_month <- unique(as.character(raw_data_gather$month)) # Remover linhas com NA na data (nao existem por conta do mes) raw_data_gather <- raw_data_gather[ -which(is.na(raw_data_gather$date)), ] # Mean precipitation per months per rain days preciptation_per_month_per_rain_days <- raw_data_gather %>% group_by(year, month) %>% summarise(days_rain_month = sum(!is.na(precipitation_mm)), mean_precip_in_rain_days = sum(precipitation_mm, na.rm = TRUE)/ sum(!is.na(precipitation_mm))) # Dias de chuva por mes preciptation_per_month_per_rain_days %>% ggplot(aes(x=factor(month, levels = order_month), y=days_rain_month, col=year, group=year )) + geom_line() + geom_point() preciptation_per_month_per_rain_days %>% ggplot(aes(x=factor(month, levels = order_month), y=days_rain_month, col=year, group=year )) + geom_line() + geom_point() + facet_wrap(~year) # Precipitacao media por mes raw_data_gather %>% group_by(year, month) %>% summarise(mean_precip = mean(precipitation_mm, na.rm = TRUE)) %>% ggplot(aes(x=factor(month, levels = order_month), y=mean_precip, col=year, group=year )) + geom_line() + geom_point() # Precipitacao toal por mes raw_data_gather %>% group_by(year, month) %>% summarise(total_precip = sum(precipitation_mm, na.rm = TRUE)) %>% ggplot(aes(x=factor(month, levels = order_month), y=total_precip, col=year, group=year )) + geom_line() + geom_point() # Precipitacao toal por mes raw_data_gather %>% group_by(year, month) %>% summarise(total_precip = sum(precipitation_mm, na.rm = TRUE)) %>% ggplot(aes(x=factor(month, levels = order_month), y=total_precip, col=year, group=year )) + geom_line() + geom_point() + facet_wrap(~year) # boxplot precipitacao mensao ao logo de todos os anos raw_data_gather %>% ggplot(aes(x=factor(month, levels = order_month), y=precipitation_mm, fill=year)) + geom_boxplot() # boxplot precipitacao mensal geral raw_data_gather %>% ggplot(aes(x=factor(month, levels = order_month), y=precipitation_mm, fill=month)) + geom_boxplot() hclust_df <- preciptation_per_month_per_rain_days %>% mutate(var = paste(year, month, sep = '_')) %>% ungroup() %>% select(days_rain_month, mean_precip_in_rain_days, var) %>% as.data.frame() rownames(hclust_df) <- hclust_df$var hclust_df <- hclust_df[ ,c(1,2)] boxplot(hclust_df[ ,1]) boxplot(hclust_df[ ,2]) # Remover o outlier, esta causando problema! hclust_df <- subset(hclust_df, hclust_df[,2] < max(hclust_df[,2])) # scale data to mean=0, sd=1 and convert to matrix hclust_df_scaled <- as.matrix(scale(hclust_df)) heatmaply(t(hclust_df_scaled), k_col = 10 ) d3heatmap(hclust_df, scale="column", colors="Blues") library(dygraphs) library(xts) df_dygraph <- preciptation_per_month_per_rain_days %>% ungroup() %>% select(year, month, mean_precip_in_rain_days) %>% spread(year, mean_precip_in_rain_days) # df_dygraph <- as.data.frame(df_dygraph) # df_dygraph <- df_dygraph[ ,-1] library("viridisLite") cols <- viridis(3) cols <- substr(cols, 0, 7) m_order <- c(unique(as.character(raw_data_gather$month))) # sorting month in correct order df_dygraph <- df_dygraph %>% mutate(month = factor(month, levels = m_order)) %>% arrange(factor(month, levels = m_order) ) hc <- highchart() %>% hc_xAxis(categories = df_dygraph$month) %>% hc_add_series(name = "2001", data = df_dygraph$`2001`) %>% hc_add_series(name = "2002", data = df_dygraph$`2002`) %>% hc_add_series(name = "2003", data = df_dygraph$`2003`) %>% hc_add_series(name = "2004", data = df_dygraph$`2004`) %>% hc_add_series(name = "2005", data = df_dygraph$`2005`) %>% hc_add_series(name = "2006", data = df_dygraph$`2006`) %>% hc_add_series(name = "2007", data = df_dygraph$`2007`) %>% hc_add_series(name = "2008", data = df_dygraph$`2008`) %>% hc_add_series(name = "2009", data = df_dygraph$`2009`) %>% hc_add_series(name = "2010", data = df_dygraph$`2010`) %>% hc_add_series(name = "2011", data = df_dygraph$`2011`) %>% hc_add_series(name = "2012", data = df_dygraph$`2012`) %>% hc_add_series(name = "2013", data = df_dygraph$`2013`) %>% hc_add_series(name = "2014", data = df_dygraph$`2014`) %>% hc_add_series(name = "2015", data = df_dygraph$`2015`) %>% hc_add_series(name = "2016", data = df_dygraph$`2016`) hc str(citytemp)
bbd8507ac796c5acaf468b76c7965a86c54fe35f
8062b05ae60f135948d94eb8576845cfd49872a4
/man/fuzzyBHexact.Rd
acafa2ced76b768f0c8e23122e17f959615fbdee
[]
no_license
cran/fuzzyFDR
4c40bf07e4085af2e4ca348f7658186138bc8768
20eea638d935915d825bd6245dc2514de950c546
refs/heads/master
2016-09-11T04:03:10.368045
2007-10-16T00:00:00
2007-10-16T00:00:00
null
0
0
null
null
null
null
UTF-8
R
false
false
1,474
rd
fuzzyBHexact.Rd
\name{fuzzyBHexact} \alias{fuzzyBHexact} \title{Exact calculation of fuzzy decision rules (Benjamini and Hochberg FDR)} \description{ Exact calculation of fuzzy decision rules for multiple testing. Controls the FDR (false discovery rate) using the Benjamini and Hochberg method. } \usage{ fuzzyBHexact(pvals, pprev, alpha = 0.05, tol = 1e-05, q.myuni = T, dp = 20) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{pvals}{ observed discrete p-values} \item{pprev}{ previously attainable p-values under the null distribution} \item{alpha}{ significance level of the FDR procedure} \item{tol}{ tolerance for my.match and my.unique} \item{q.myuni}{ logical. Use my.match instead of match?} \item{dp}{ no. decimal places to round p-values to} } \details{ my.match and my.unique may be used instead of match and unique if there is a problem with calculating the unique set of p-values (sometimes a problem with very small p-values) } \value{ Data frame containing the p-values and previously attainable p-values input to the function, and the tau (fuzzy decision rule) output. Also contains the minimum and maximum ranks over allocations for each p-value. } \references{ Kulinsakaya and Lewin (2007).} \author{ Alex Lewin } \examples{ data(example1) names(example1) fuzzyBHexact(example1$pvals,example1$pprev,alpha=0.05) data(example2) names(example2) fuzzyBHexact(example2$pvals,example2$pprev,alpha=0.05) } \keyword{ htest }
8ce35dc5be702f7dba6d17b2eec7b9c42425e08e
4bd7d7f4ea836ea8ff61f6ca66df766cb9ac831d
/Derby Horse Sentiment Analysis.R
bb690ddf6ddf934c6c8c5f67d50200d613df145e
[]
no_license
nick-holt/kentuckyderby144
7c26e6728eff9b5e42196f1e1fb57e5b5d45fd10
53389279b7c02328720c0f0cb28f530f3e6817f8
refs/heads/master
2020-03-15T12:29:26.910759
2018-05-04T13:54:42
2018-05-04T13:54:42
132,145,309
0
0
null
null
null
null
UTF-8
R
false
false
6,428
r
Derby Horse Sentiment Analysis.R
# 2018 Kentucky Derby (144th) - Social Listening Analytics Visualization Demo # libraries library(tidyverse) # read in data derby <- read_csv("derby_book_2018.csv") colnames(derby) <- tolower(str_replace_all(colnames(derby), " ", "_")) colnames(derby) <- str_replace_all(colnames(derby), "_tweets", "") # reorder horse factor by post position derby$horse <- factor(derby$horse, levels = c(derby$horse)) # gather tweet volume data into long format and capitalize sentiment tags derby_clean <- derby %>% gather(positive, negative, neutral, key = "sentiment", value = "tweet_count") %>% mutate(sentiment = str_to_title(sentiment)) # x axis helper functions from: https://jcarroll.com.au/2016/06/03/images-as-x-axis-labels-updated/ library(cowplot) # convert spaces in horse names into line breaks addline_format <- function(x,...){ gsub('\\s','\n',x) } # plot tweet volume and sentiment by horse (arranged by post position) with coord flip (tall plot) plot <- ggplot(arrange(derby_clean), aes(x = horse, y = tweet_count, fill = factor(sentiment, levels = c("Positive", "Neutral", "Negative")))) + geom_bar(stat = "identity", width=0.9) + scale_fill_manual(values = c("#4D7B18", "#C5B4A0", "#B6121B")) + theme_classic() + coord_flip()+ # tall plot xlab("Tweet Volume\n") + guides(fill = guide_legend(title = "Sentiment")) + theme(axis.text.y = element_text(angle = 0, size = 8, face = "bold"), legend.position = c(.93, .8), axis.line=element_blank(), axis.ticks = element_blank(), axis.text.x=element_blank(), axis.title = element_blank()) + geom_text(aes(horse, tweets_in_last_week, label = current_odds, fill = NULL, face = "bold"), data = derby, position = position_dodge(width = .9), hjust = -.5) + ylab("\nHorse") + scale_y_continuous(expand = c(0, 0), limits = c(0, 3250)) #+ #scale_x_discrete(breaks=unique(derby$horse), #labels=addline_format(unique(derby$horse))) # read in images for x axis library(magick) pimage <- axis_canvas(plot, axis = 'y') + draw_image("Firenze Fire.jpg", y = 0, x = 0.5, scale = 1) + draw_image("Free Drop Billy.jpg", y = 1.5, scale = 1) + draw_image("Promises Fulfilled.jpg", y = 2.5, scale = 1) + draw_image("Flameaway.jpg", y = 3.5, scale = 1) + draw_image("Audible.jpg", y = 4.5, scale = 1) + draw_image("Good Magic.jpg", y = 5.5, scale = 1) + draw_image("Justify.jpg", y = 6.5, scale = 1) + draw_image("Lone Sailor.jpg", y = 7.5, scale = 1) + draw_image("Hofburg.jpg", y = 8.5, scale = 1) + draw_image("My Boy Jack.jpg", y = 9.5, scale = 1) + draw_image("Bolt d'oro.jpg", y = 10.5, scale = 1) + draw_image("Enticed.jpg", y = 11.5, scale = 1) + draw_image("Bravazo.jpg", y = 12.5, scale = 1) + draw_image("Mendelssohn.jpg", y = 13.5, scale = 1) + draw_image("Instilled Regard.jpg", y = 14.5, scale = 1) + draw_image("Magnum Moon.jpg", y = 15.5, scale = 1) + draw_image("Solomini.jpg", y = 16.5, scale = 1) + draw_image("Vino Rosso.jpg", y = 17.5, scale = 1) + draw_image("Noble Indy.jpg", y = 18.5, scale = 1) + draw_image("Combatant.jpg", y = 19.5, scale = 1) + draw_image("Blended Citizen.jpg", y = 20.5, scale = 1) # overlay jockey silk images ggdraw(insert_yaxis_grob(plot, pimage, position = "left")) # wide plot plot <- ggplot(arrange(derby_clean), aes(x = horse, y = tweet_count, fill = factor(sentiment, levels = c("Positive", "Neutral", "Negative")))) + geom_bar(stat = "identity", width=0.9) + scale_fill_manual(values = c("#4D7B18", "#C5B4A0", "#B6121B")) + theme_classic() + ylab("Tweet Volume\n") + guides(fill = guide_legend(title = "Tweet\nSentiment")) + theme(axis.text.x = element_text(angle = 0, size = 6, face = "bold"), legend.position = c(.93, .8), legend.text = element_text(size = 8), legend.title = element_text(size = 8), axis.title.y = element_text(size = 8), axis.line=element_blank(), axis.ticks = element_blank(), axis.text.y=element_blank(), axis.title.x = element_blank()) + geom_text(aes(horse, tweets_in_last_week, label = current_odds, fill = NULL), data = derby, position = position_dodge(width = .9), vjust = -.5) + xlab("\nHorse") + scale_y_continuous(expand = c(0, 0), limits = c(0, 3250)) + scale_x_discrete(breaks=unique(derby$horse), labels=addline_format(unique(derby$horse))) pimage <- axis_canvas(plot, axis = 'x') + draw_image("Firenze Fire.jpg", x = 0.5, y = 0, scale = 0.9) + draw_image("Free Drop Billy.jpg", x = 1.5, scale = 0.9) + draw_image("Promises Fulfilled.jpg", x = 2.5, scale = 0.9) + draw_image("Flameaway.jpg", x = 3.5, scale = 0.9) + draw_image("Audible.jpg", x = 4.5, scale = 0.9) + draw_image("Good Magic.jpg", x = 5.5, scale = 0.9) + draw_image("Justify.jpg", x = 6.5, scale = 0.9) + draw_image("Lone Sailor.jpg", x = 7.5, scale = 0.9) + draw_image("Hofburg.jpg", x = 8.5, scale = 0.9) + draw_image("My Boy Jack.jpg", x = 9.5, scale = 0.9) + draw_image("Bolt d'oro.jpg", x = 10.5, scale = 0.9) + draw_image("Enticed.jpg", x = 11.5, scale = 0.9) + draw_image("Bravazo.jpg", x = 12.5, scale = 0.9) + draw_image("Mendelssohn.jpg", x = 13.5, scale = 0.9) + draw_image("Instilled Regard.jpg", x = 14.5, scale = 0.9) + draw_image("Magnum Moon.jpg", x = 15.5, scale = 0.9) + draw_image("Solomini.jpg", x = 16.5, scale = 0.9) + draw_image("Vino Rosso.jpg", x = 17.5, scale = 0.9) + draw_image("Noble Indy.jpg", x = 18.5, scale = 0.9) + draw_image("Combatant.jpg", x = 19.5, scale = 0.9) + draw_image("Blended Citizen.jpg", x = 20.5, scale = 0.9) png(file="HorsePlot.png",width=3600,height=1200,res=300) ggdraw(insert_xaxis_grob(plot, pimage, position = "bottom")) dev.off()
e86eb252fe5c4851fa4106e088f5061728e415c1
6bd5b97104280c2f2d80fd233923dcd8cb4b2304
/run_intcode.R
c21d9fa6efb60865e9856baee3d897bf4480b3a8
[]
no_license
cettt/Advent_of_Code2019
0982fce90118faed23d212beae9dfe304cfde6e0
2d467a0120624fc37b721581286a8c3486c9ab51
refs/heads/master
2023-02-15T12:42:13.475154
2021-01-03T14:46:44
2021-01-03T20:20:09
326,495,655
0
0
null
null
null
null
UTF-8
R
false
false
2,474
r
run_intcode.R
#this is the base function for running intcode and can be usesd starting on Day 9 # z is the intcode programm (usually the problem input) # input_fun is a function which generates an based on previous outputs run_intcode <- function(z, input_fun = function(output) 1, o_fun = NULL, j = 1L, base = 0L, ...) { cls <- function(x) if (!is.na(x)) x else 0L# own coalesce function find_para_val <- function(para_id, j) { #para is either 1 or 2. .inst <- floor(z[j] / 100) #this is the instruction without the opcode mode <- floor((.inst %% 10^(para_id)) / 10^(para_id - 1)) .base <- if (mode == 2) base else 0 if (mode == 1) return(cls(z[j + para_id])) #immediate mode else return(cls(z[cls(z[j + para_id]) + 1L + .base])) #postion mode resp. relative mode } output <- NULL run <- TRUE while (run) { opcode <- z[j] %% 100L #first two digits contain the opcode if (!opcode %in% c(3L, 99L)) { para1 <- find_para_val(1L, j) if (!opcode %in% c(4L, 9L)) para2 <- find_para_val(2L, j) } dummy_base <- if (z[j] >= 2e4) base else 0L #check if output is if in relative mode if (opcode == 1L) { #addition, multiplication z[z[j + 3L] + 1L + dummy_base] <- para1 + para2 j <- j + 4L } else if (opcode == 2L) { #addition, multiplication z[z[j + 3L] + 1L + dummy_base] <- para1 * para2 j <- j + 4L } else if (opcode == 3L) { #input dummy_base <- if (z[j] %% 1e3L >= 200L) base else 0L inp <- input_fun(output, ...) if (!is.null(inp)) { z[z[j + 1L] + 1L + dummy_base] <- inp j <- j + 2L } else { return(list(intcode = z, j = j, base = base, output = output)) } } else if (opcode == 4L) { #output output <- c(output, para1) j <- j + 2L } else if (opcode == 5L) { #jump if true/false j <- if (para1 != 0L) para2 + 1L else j + 3L } else if (opcode == 6L) { #jump if true/false j <- if (para1 == 0L) para2 + 1L else j + 3L } else if (opcode == 7L) { #less than z[z[j + 3L] + 1L + dummy_base] <- (para1 < para2) j <- j + 4L } else if (opcode == 8L) { #less than z[z[j + 3L] + 1L + dummy_base] <- (para1 == para2) j <- j + 4L } else if (opcode == 9L) { #rebase base <- base + para1 j <- j + 2L } else if (opcode == 99L) break # stop } if (is.null(o_fun)) output else o_fun(output) }
7acff1dd2235cca33c15cd50a06829df15102bcc
2bec5a52ce1fb3266e72f8fbeb5226b025584a16
/lsbclust/man/summary.int.lsbclust.Rd
8cfdfa49bfce8ea574dbaa58f5be4cb8425c8de8
[]
no_license
akhikolla/InformationHouse
4e45b11df18dee47519e917fcf0a869a77661fce
c0daab1e3f2827fd08aa5c31127fadae3f001948
refs/heads/master
2023-02-12T19:00:20.752555
2020-12-31T20:59:23
2020-12-31T20:59:23
325,589,503
9
2
null
null
null
null
UTF-8
R
false
true
511
rd
summary.int.lsbclust.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/summary.int.lsbclust.R \name{summary.int.lsbclust} \alias{summary.int.lsbclust} \title{Summary Method for Class "int.lsbclust"} \usage{ \method{summary}{int.lsbclust}(object, digits = 3, ...) } \arguments{ \item{object}{An object of class 'int.lsbclust'.} \item{digits}{The number of digits in the printed output.} \item{\dots}{Unimplemented.} } \description{ Some goodness-of-fit diagnostics are provided for all three margins. }
0b5c8275ddfbc9452d0b6391f769dfe9323ab493
3e5abd06979afc7b8da873831279ea6739b37961
/man/report_get.Rd
7a65e1bd57b51941a1089803c9f0bfe1408774bf
[]
no_license
isabella232/crowdflower
f0f704669cc29d7713ee94687b260b1f88ec04c5
6d545e8d2106fdaf3b1c44ac5bfcfc0f9ec89a1b
refs/heads/master
2022-04-11T02:24:55.272712
2017-08-28T16:12:25
2017-08-28T16:12:25
null
0
0
null
null
null
null
UTF-8
R
false
true
2,537
rd
report_get.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/report_get.R \name{report_get} \alias{report_get} \alias{report_regenerate} \title{Generate and retrieve job results} \usage{ report_get(id, report_type = c("full", "aggregated", "json", "gold_report", "workset", "source"), csv_args = list(stringsAsFactors = FALSE, check.names = FALSE), verbose = TRUE, ...) report_regenerate(id, report_type = c("full", "aggregated", "json", "gold_report", "workset", "source"), verbose = TRUE, ...) } \arguments{ \item{id}{A character string containing an ID for job.} \item{report_type}{Type of report} \item{csv_args}{A list of arguments passed to \code{\link[utils]{read.csv}} when \code{report_type = 'source'}.} \item{verbose}{A logical indicating whether to print additional information about the request.} \item{...}{Additional arguments passed to \code{\link{cf_query}}.} } \value{ If \code{report_type = 'json'}, a list. Otherwise a data.frame. } \description{ Results } \details{ \code{report_get} regenerates one of six types of reports within a job. Here is how they are described by Crowdflower: \itemize{ \item \code{full}: Returns the Full report containing every judgment. \item \code{aggregated}: Returns the Aggregated report containing the aggregated response for each row. \item \code{json}: Returns the JSON report containing the aggregated response, as well as the individual judgments, for the first 50 rows. \item \code{gold_report}: Returns the Test Question report. \item \code{workset}: Returns the Contributor report. \item \code{source}: Returns a CSV of the source data uploaded to the job. } Where possible, the package tries to return a data.frame of the results. } \examples{ \dontrun{ # create new job f1 <- system.file("templates/instructions1.html", package = "crowdflower") f2 <- system.file("templates/cml1.xml", package = "crowdflower") j <- job_create(title = "Job Title", instructions = readChar(f1, nchars = 1e8L), cml = readChar(f2, nchars = 1e8L)) # add data d <- data.frame(variable = 1:3) job_add_data(id = j, data = d) # launch job job_launch(id = j) # get results for job report_regenerate(id = j, report_type = "full") report_get(id = j, report_type = "full") # delete job job_delete(j) } } \references{ \href{https://success.crowdflower.com/hc/en-us/articles/202703425-CrowdFlower-API-Requests-Guide#report_get}{Crowdflower API documentation} } \seealso{ \code{\link{cf_account}} } \keyword{data} \keyword{jobs}
3c36df9ac1a4c9918fc0f39156dae71d0437edd8
302d026524486f0ad386599fac8dd4f57278ba38
/man/modelSetPredictors.Rd
5aadc8b6f601c7d9f133d1ab0905078ab7c43927
[ "CC0-1.0", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
cwhitman/GenEst
96d72e50eafe5e71c25a230c8046f80e152b1963
7c84c887b3f671fa8786eee8077512b8d80b7883
refs/heads/master
2020-03-30T18:03:28.168191
2018-10-11T07:04:03
2018-10-11T07:04:03
151,481,672
0
0
NOASSERTION
2018-10-03T21:17:44
2018-10-03T21:17:44
null
UTF-8
R
false
true
424
rd
modelSetPredictors.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/model_utility_functions.R \name{modelSetPredictors} \alias{modelSetPredictors} \title{Determine the predictors for a whole model set} \usage{ modelSetPredictors(modelSet) } \arguments{ \item{modelSet}{model set} } \value{ vector of the predictors from a model set } \description{ Determine the predictors for a whole model set }
333c1f107c270f305d3fa001f731e2acaa586f18
f3dbe1612c0e80886df0e2fd02a444b5f7d5efa9
/man/LVMMCOR.Rd
b7066053c1749de1a59c92e0c2e70aad27647d58
[]
no_license
cran/LVMMCOR
072778f2546f565290c4187ad3c22dda48b36d94
e6958dbf94bd6807c418efb20c03578236e59131
refs/heads/master
2021-01-13T02:11:53.987968
2013-05-10T00:00:00
2013-05-10T00:00:00
null
0
0
null
null
null
null
UTF-8
R
false
false
3,172
rd
LVMMCOR.Rd
\name{LVMMCOR} \alias{LVMMCOR} \title{ A Latent Variable Model for Mixed Continuous and Ordinal Responses. } \description{ A model for mixed ordinal and continuous responses is presented where the heteroscedasticity of the variance of the continuous response is also modeled. In this model ordinal response can be dependent on the continuous response. The aim is to use an approach similar to that of Heckman (1978) for the joint modelling of the ordinal and continuous responses. With this model, the dependence between responses can be taken into account by the correlation between errors in the models for continuous and ordinal responses. } \usage{ LVMMCOR(ini = NA, X, y, z, p, q, ...) } \arguments{ \item{ini}{Initial values} \item{X}{Design matrix} \item{z}{Continuous responses} \item{y}{Ordinal responses with three levels} \item{p}{Order of dimension of continuous responses} \item{q}{Order of dimension of ordinal responses} \item{\dots}{Other arguments}} \details{ Models for LVMMCOR are specified symbolically. A typical model has the form response1 ~ terms and response2 ~ terms where response1and response2 are the (numeric) ordinal and continuous responses vector and terms is a series of terms which specifies a linear predictor for responses. A terms specification of the form first + second indicates all the terms in first together with all the terms in second with duplicates removed. A specification of the form first:second indicates the set of terms obtained by taking the interactions of all terms in first with all terms in second. The specification first*second indicates the cross of first and second. This is the same as first + second + first:second. } \value{ \item{Continuous Response}{Coefficient of continuous response} \item{Variance of Continuous Response}{Variance of continuous response} \item{Ordinal Response}{Coefficient of ordinal response} \item{Cut points}{Cut points for ordinal response} \item{Correlation}{Coefficient of continuous response} \item{Hessian}{Hessian matrix} \item{convergence}{An integer code. 0 indicates successful convergence} } \references{ Bahrami Samani, E., Ganjali, M. and Khodaddadi, A. (2008). A Latent Variable Model for Mixed Continuous and Ordinal Responses. Journal of Statistical Theory and Applications. 7(3):337-349. } \author{ Bahrami Samani and Nourallah Tazikeh Miyandarreh } \note{ Supportted by Shahid Beheshti University } \seealso{ \code{\link{nlminb}},\code{\link{fdHess}} } \examples{ data("Bahrami") gender<-Bahrami$ GENDER age<-Bahrami$AGE duration <-Bahrami$ DURATION y<-Bahrami$ STEATOS z<-Bahrami$ BMI sbp<-Bahrami$ SBP X=cbind(gender,age,duration ,sbp) P<-lm(z~X)[[1]] names(P)<-paste("Con_",names(P),sep="") Q<-polr(factor(y)~X)[[1]] names(Q)<-paste("Ord_",names(Q),sep="") W=c(cor(y,z),polr(factor(y)~X)[[2]],var(z)) names(W)=c("Corr","cut_point1","cut_point2","Variance of Continous Response") ini=c(P,Q,W) p=5; q=4; LVMMCOR(ini,X=X,y=y,z=z,p=p,q=q) ## The function is currently defined as structure(function (x, ...) UseMethod("LVMMCOR"), class = "LVMMCOR") } \keyword{regression}
cf4a3b37191dfb287c84b5aef4561a3056782e20
dfb18d1b4608c4404cc291a5232692abe04ca230
/R/phase.zg.R
dae84e40c2e2da00ab99a9d775a80495ae116f11
[]
no_license
sugam72-os/dendRoAnalyst-1
0d2fb30336cc7fa287eb428472347a711bd6aaf9
9b009f909dddbbba0837f6e2aa18b97f0b2e17c8
refs/heads/master
2022-11-13T16:15:10.604682
2020-07-03T18:00:07
2020-07-03T18:00:07
285,296,186
1
0
null
2020-08-05T13:28:24
2020-08-05T13:28:23
null
UTF-8
R
false
false
14,954
r
phase.zg.R
#' @title Application of the zero-growth approach to calculate different phases, their duration and to plot them. #' #' @description This function analyses data using the zero-growth approach. Initially, it divides the data in two categories: 1) Tree water deficiency (TWD), i.e. the reversible shrinkage and expansion of the tree stem when the current reading is below the previous maximum and, 2) Increment (GRO), the irreversible expansion of the stem when the current reading is above the previous maximum. Then it calculates the TWD for each data point as the difference between the modelled "growth line" and the observed measurement. See \href{https://doi.org/10.1111/nph.13995}{Zweifel et. al.,(2016) } for details. #' #' @references Zweifel R, Haeni M, Buchmann N, Eugster W (2016) Are trees able to grow in periods of stem shrinkage? New Phytol 211:839–849. https://doi.org/10.1111/nph.13995 #' #' @param df dataframe with first column containing date and time in the format \code{yyyy-mm-dd HH:MM:SS}. It should contain data with constant temporal resolution for best results. #' #' @param TreeNum numerical value indicating the tree to be analysed. E.g. '1' refers to the first dendrometer data column in \emph{df}. #' #' @param outputplot logical, to \code{plot} the phase diagram. #' #' @param days array with initial and final day for plotting. E.g. \emph{c(a,b)}, where a = initial date and b = final date. #' #' @param linearCol color for the modelled curve. #' #' @param twdCol color for the TWD curve. #' #' @param twdFill filling method for the area under the TWD curve. Equivalent to \code{density} argument of the \code{\link[graphics:polygon]{polygon}} function in the \pkg{graphics} package of R. Default value is \code{NULL}. #' #' @param twdFillCol color to fill the area under the TWD curve. #' #' @param xlab string, x label of the \code{plot}. #' #' @param ylab1 string, y label of the upper \code{plot}. #' #' @param ylab2 string, y label of the lower \code{plot}. #' #' @param twdYlim numeric, to define the limit of the y-axis of the lower plot. Default is \code{NULL}, which automatically adjusts the y-axis limit. #' #' @param cex.lab numeric, for the size of the axis labels. Default is \code{NULL}. #' #' @param cex.axis numeric, for the size of the axis tick labels. Default is \code{NULL}. #' #' @param font.lab numeric, for the font type of the axis labels. Default is \code{NULL}. #' #' @param font.axis numeric, for the font type of the axis tick labels. Default is \code{NULL}. #' #' @param col.axis color names, for the color of the axis tick labels. Default is \code{NULL}. #' #' @param col.lab color names, for the color of the axis labels. Default is \code{NULL}. #' #' #' @return A list of two dataframes. The first dataframe \emph{ZG_cycle} contains the cyclic phases along with various statistics and the second dataframe \emph{ZG_phase} with assigned phases for each data point.The contents of \emph{ZG_cycle} are: #' \tabular{llll}{ #' \strong{Columns}\tab\tab \strong{Description}\cr #' \code{DOY}\tab\tab Day of year for the corresponding phase.\cr #' \code{Phase}\tab\tab TWD for tree water deficit and GRO for irreversible expansion.\cr #' \code{start}\tab\tab Time when the corresponding phase starts.\cr #' \code{end}\tab\tab Time when the corresponding phase ends.\cr #' \code{Duration_h}\tab\tab Duration of the corresponding phase in hours.\cr #' \code{Magnitude}\tab\tab Radial/circumferential change in millimeters.\cr #' \code{rate}\tab\tab Rate of Radial/circumferential change in micrometers per hour.\cr #' \code{Max.twd}\tab\tab Maximum TWD recorded for the corresponding TWD phase.\cr #' \code{Max.twd.time}\tab\tab Time of occurrence of maximum TWD value for each TWD phase.\cr #' \code{Avg.twd}\tab\tab Average of TWD values for each TWD phase.\cr #' \code{STD.twd}\tab\tab Standard deviation of TWD values for each TWD phase. #' } #' #' @examples library(dendRoAnalyst) #' data(gf_nepa17) #' zg.phase<-phase.zg(df=gf_nepa17, TreeNum=1, outputplot=TRUE, days=c(150,160)) #' head(zg.phase[[1]],10) #' head(zg.phase[[2]],10) #' #' @importFrom grDevices rgb #' #' @importFrom graphics abline axis axis.POSIXct box legend lines mtext par points polygon rect text plot #' #' @importFrom stats approx median na.exclude na.omit sd #' #' @export phase.zg<-function(df, TreeNum, outputplot, days, linearCol='#2c7fb8',twdCol='#636363',twdFill=NULL,twdFillCol='#f03b20',xlab='DOY',ylab1='Stem size variation [mm]',ylab2='TWD [mm]',twdYlim=NULL, cex.axis=NULL, cex.lab=NULL, font.lab=NULL, col.lab=NULL, font.axis=NULL, col.axis=NULL){ temp13<-df dm<-TreeNum+1 data<-temp13[,c(1,dm)] dm<-2 a<-NULL b<-NULL temp<-as.POSIXct(strptime(data[,1], "%Y-%m-%d %H:%M:%S"), tz='UTC') if(is.na(as.POSIXct(temp[1], format = '%Y-%m-%d %H:%M:%S'))){ stop('Date not in the right format') } data$doy<-as.integer(format(strptime(temp, format = '%Y-%m-%d %H:%M:%S'), '%j')) data$yr<-as.integer(format(strptime(temp, format = '%Y-%m-%d %H:%M:%S'), '%y')) y1<-unique(data$yr) if(length(y1)>1){ data$doy2<-data$doy d<-max(which(data$doy==ifelse(y1[1]%%4==0,366,365))) data$doy2[(d+1):nrow(data)]<-data$doy2[(d+1):nrow(data)]+data$doy2[d] } #require(pspline) ############################ reso_den<-function(input_time){ time1<-input_time reference<-time1[1] time_min<-as.integer(difftime(time1,reference, units = "mins")) diff_time<-diff(time_min) diff2_time<-unique(diff_time) reso<-mean(diff2_time) if(isTRUE(length(diff2_time>1))==T){ print(diff2_time) warning('Warning: The temporal resolution of dendrometer data is not consistent, For better result, please use dendrometer data with consistent resolution. There may be NA values in the dataset.') #cat(paste('Mean temporal resolution is :', round(reso),' minutes.')) }else{ reso<-mean(diff2_time) #cat(paste('Temporal resolution is :', round(reso),' minutes.')) return(round(reso)) } } ##################################################### ######################### r.denro<-reso_den(temp) ############################ y<-c() for(i in 1:nrow(data)){ if(isTRUE(data[,dm][i+1]-data[,dm][i]>0)==TRUE & isTRUE(max(data[,dm][1:i], na.rm = T)<data[,dm][i+1])==TRUE){ y[i+1]<-3 }else{ if(isTRUE(data[,dm][i+1]-data[,dm][i]>0)==TRUE){ y[i+1]<-2 }else{ y[i+1]<-1 } } } data$y<-y[1:length(y)-1] ########################################################## data$phs<-data$y zg_ph<-data$y zg_ph[zg_ph==2|zg_ph==1]<-'TWD' zg_ph[zg_ph==3]<-'GRO' data$y<-zg_ph ########################################## x<-which(data$y=='GRO') dp.3.time<-data[,dm][x] y.3<-na.exclude(data[,dm][x]) ap.all<-approx(c(1,x[1]),c(y.3[1],y.3[1]),xout =1:(x[1]-1))$y for(i in 2:length(x)){ ap<-approx(c(x[(i-1)],x[i]),c(y.3[(i-1)],y.3[i]),xout =x[(i-1)]:(x[i]-1)) #lines(x[i]:(x[i+1]-1), ap$y) ap.all<-c(ap.all,ap$y[1:length(ap$y)]) } if(x[length(x)]!=nrow(data)){ ap.all2<-approx(c(x[length(x)],nrow(data)),c(y.3[length(y.3)],y.3[length(y.3)]),xout =x[length(x)]:nrow(data))$y }else{ #ap.all2=approx(c(x[length(x)-1],nrow(data)),c(y.3[length(y.3)-1],y.3[length(y.3)]),xout =x[length(x)-1]:nrow(data))$y n<-which(zg_ph=='TWD') n1<-n[length(n)] ap.all2<-data[,dm][(n1+1):nrow(data)] } ap.all<-c(ap.all, ap.all2) data$twd<-data[,dm]-ap.all data$strght.line<-ap.all #Calculating different phases in ZG method gr.ph<-c() doy<-c() magn<-c() for(i in 1:nrow(data)){ if(isTRUE(data$y[i]==data$y[i+1])==TRUE & isTRUE((i+1)-i==1)==TRUE){ next } else{ doy<-c(doy, i) gr.ph<-c(gr.ph,data$y[i]) magn<-c(magn,data[,dm][i]) } } mx.twd1<-c() avg.twd1<-c() s.twd1<-c() md.twd1<-c() mn.twd1<-c() d.min1<-c() d.max1<-c() for(i in 2:length(x)){ df<-data[x[i-1]:x[(i)],] mx.twd1<-c(mx.twd1, max(df$twd,na.rm = T)) mn.twd1<-c(mn.twd1, min(df$twd,na.rm = T)) avg.twd1<-c(avg.twd1, mean(df$twd, na.rm = T)) s.twd1<-c(s.twd1, sd(df$twd, na.rm = T)) md.twd1<-c(md.twd1, median(df$twd, na.rm = T)) t.mn<-subset(df,df$twd==min(df$twd, na.rm = T)) d.min1<-c(d.min1, strftime(t.mn[1,1], format = '%Y-%m-%d %H:%M:%S')) t.mx<-subset(df,df$twd==max(df$twd, na.rm = T)) d.max1<-c(d.max1, strftime(t.mx[1,1], format = '%Y-%m-%d %H:%M:%S')) } df2<-data[(x[length(x)]+1):nrow(data),] mx.twd<-c(mx.twd1, max(df2$twd,na.rm = T)) mn.twd<-c(mn.twd1, min(df2$twd,na.rm = T)) avg.twd<-c(avg.twd1, mean(df2$twd, na.rm = T)) s.twd<-c(s.twd1, sd(df2$twd, na.rm = T)) md.twd<-c(md.twd1, median(df2$twd, na.rm = T)) t.mn<-subset(df2,df2$twd==min(df2$twd, na.rm = T)) d.min<-c(d.min1, strftime(t.mn[1,1], format = '%Y-%m-%d %H:%M:%S')) t.mx<-subset(df2,df2$twd==max(df2$twd, na.rm = T)) d.max<-c(d.max1, strftime(t.mx[1,1], format = '%Y-%m-%d %H:%M:%S')) xyz<-data.frame(d.max,mx.twd, d.min, mn.twd, avg.twd, s.twd, md.twd) s<-subset(xyz, xyz$mn.twd!=0) abc<-data.frame(doy) strt_time<-c() for (i in 1:nrow(abc)){ strt_time[i]<-strftime(data[,1][abc$doy[i]], format = '%Y-%m-%d %H:%M:%S') } abc$doy<-NULL abc$DOY<-as.integer(format(strptime(strt_time, format = '%Y-%m-%d %H:%M:%S'), '%j')) abc$Phases<-gr.ph abc<-na.omit(abc) abc$start<-strt_time[1:length(strt_time)-1] abc$end<-strt_time[2:(length(strt_time))] abc$Duration_h<-round(as.numeric(difftime(strptime(abc$end, format = '%Y-%m-%d %H:%M:%S'), strptime(abc$start, format = '%Y-%m-%d %H:%M:%S'), units = 'hours')),1) abc$magnitude<-as.numeric(round(diff(magn),8)) abc$rate<-(abc$magnitude/abc$Duration_h)*1000 ######################################################## data$tm=data[,1] twd12=data$twd tp<-abc$start[abc$Phases=='TWD'] ep<-abc$end[abc$Phases=='TWD'] twd.loc=which(abc$Phases=='TWD') max.t=c() max.tm=c() mn.t=c() sd.t=c() for(q in 1:length(tp)){ r= as.numeric(which(data$tm==tp[q])) t= as.numeric(which(data$tm==ep[q])) f=data[r:t,] max.t=c(max.t, min(f$twd)) d=which(f$twd==min(f$twd)) max.tm=c(max.tm,strftime(f[,1][d[length(d)]], format = '%Y-%m-%d %H:%M:%S') ) mn.t=c(mn.t,mean(f$twd, na.rm=T)) sd.t=c(sd.t,sd(f$twd, na.rm=T)) } #print(f) abc$Max.twd<-NA abc$Max.twd[twd.loc]<- -max.t abc$Max.twd.time<-NA abc$Max.twd.time[twd.loc]<-strftime(max.tm, format = '%Y-%m-%d %H:%M:%S') abc$Avg.twd<-NA abc$Avg.twd[twd.loc]<- -mn.t abc$STD.twd<-NA abc$STD.twd[twd.loc]<- sd.t ####################################################### #abc2<-abc[order(abc$Phases, decreasing = T),] #abc2$Max.twd<-NA #abc2$Max.twd[1:length(s$mx.twd)]<- -s$mn.twd #abc2$Max.twd.time<-NA #abc2$Max.twd.time[1:length(s$mx.twd)]<-strftime(s$d.min, format = '%Y-%m-%d %H:%M:%S') #abc2$Avg.twd<-NA #abc2$Avg.twd[1:length(s$mx.twd)]<- -s$avg.twd #abc2$STD.twd<-NA #abc2$STD.twd[1:length(s$mx.twd)]<- s$s.twd #abc<-abc2[order(as.numeric(row.names(abc2)), decreasing = F),] abc$rate[abc$Phases=='TWD']<-NA abc$magnitude[abc$Phases=='TWD']<-NA ################################################################### ################Plotting######################################### if(outputplot==TRUE){ if(days[2]>days[1]){ a1<-as.numeric(which(data$doy==days[1]&data$yr==y1[1])) b1<-as.numeric(which(data$doy==days[2]&data$yr==y1[1])) }else{ if(length(y1)<=1|length(y1)>=3){ warning('WARNING: days[1] > days[2] not valid in this case. The plot is not possible.') }else{ a1<-as.numeric(which(data$doy==days[1]&data$yr==y1[1]))############ b1<-as.numeric(which(data$doy2==(days[2]+data$doy[d])&data$yr==y1[2])) } } #a1<-which(data$doy==days[1]) #b1<-which(data$doy==days[2]) a1_mn<-min(a1) b1_mx<-max(b1) c1<-days[2]-days[1] data2<-data[a1_mn:b1_mx,] xloc<-seq(a1_mn,b1_mx,(1440/r.denro)) xloc2<-c() xloc4<-c() for(i in 1:length(xloc)){ xloc2<-c(xloc2,data$doy[xloc[i]]) xloc4<-c(xloc4,data$yr[xloc[i]]) } tw.mn<-ifelse(is.null(twdYlim),min(data2$twd, na.rm = T),twdYlim) opar <- par(no.readonly =TRUE) on.exit(par(opar)) par(mfrow=c(2,1)) par(mar=c(0, 4.1, 5, 4.1), xpd=F) plot(x=row.names(data2), y=data2[,dm], type='l', col='grey25', xlab = '', ylab = ylab1, xaxt='none',cex.lab=ifelse(is.null(cex.lab),1,cex.lab), cex.axis=ifelse(is.null(cex.axis),1,cex.axis),font.axis=ifelse(is.null(font.axis),1,font.axis), col.axis=ifelse(is.null(col.axis),'black',col.axis), font.lab=ifelse(is.null(font.lab),1,font.lab), col.lab=ifelse(is.null(col.lab),'black',col.lab)) #abline(v=xloc, col='lightgray',lty=2, lwd=0.5) lines(row.names(data2), data2$strght.line, col=linearCol, lwd=1.25) axis(3, at = xloc, xloc2, las=3, cex.axis=ifelse(is.null(cex.axis),1,cex.axis),font.axis=ifelse(is.null(font.axis),1,font.axis), col.axis=ifelse(is.null(col.axis),'black',col.axis)) par(mar=c(5.1, 4.1, 0, 4.1)) plot(x=row.names(data2), y=data2$twd, col='red', type='n', ylab = '', xlab = xlab,yaxt='n',xaxt='n', ylim = c(tw.mn,0),cex.lab=ifelse(is.null(cex.lab),1,cex.lab), cex.axis=ifelse(is.null(cex.axis),1,cex.axis),font.axis=ifelse(is.null(font.axis),1,font.axis), col.axis=ifelse(is.null(col.axis),'black',col.axis), font.lab=ifelse(is.null(font.lab),1,font.lab), col.lab=ifelse(is.null(col.lab),'black',col.lab)) polygon(c(row.names(data2)[1], row.names(data2), row.names(data2)[length(row.names(data2))]), c(0, data2$twd, 0), col=twdFillCol, border = twdCol, density = twdFill) lines(row.names(data2), data2$twd) #lines() abline(h=0, col='blue', lwd=1) axis(4, at = seq(0,tw.mn,(tw.mn*0.25)), round(seq(0,-tw.mn,-tw.mn*0.25),2), las=3, cex.axis=ifelse(is.null(cex.axis),1,cex.axis),font.axis=ifelse(is.null(font.axis),1,font.axis), col.axis=ifelse(is.null(col.axis),'black',col.axis)) axis(1, at = xloc, xloc2, las=3, cex.axis=ifelse(is.null(cex.axis),1,cex.axis),font.axis=ifelse(is.null(font.axis),1,font.axis), col.axis=ifelse(is.null(col.axis),'black',col.axis)) mtext(ylab2, side = 4, line = 2.5,cex=ifelse(is.null(cex.lab),1,cex.lab),font=ifelse(is.null(font.lab),1,font.lab), col=ifelse(is.null(col.lab),'black',col.lab)) box() #legend('top',inset=c(0,-0.1), legend = c('Shrinkage','Expansion','Increment'), col = c('red','blue','green'), pch = 16, ncol = 3, box.lty = 0) } ################################################################ data3<-data.frame('Time'=data[,1],'Phases'=data$y,'TWD'=-data$twd) return(list(ZG_cycle=abc, ZG_phase=data3)) }
0043ba3fa23a9645aaed2ce2b789b2f38df43c6a
21d829fe665a3177c03b2020c581399a51a1ba6c
/scripts/20181027_sfs_generation/new_sfs.R
cd4103e383082ff736bd703bfd088a983e5afa74
[ "MIT" ]
permissive
AndersenLab/sfs-dfe
1cd88ca511d4cc5bcf8fa5fc3f1c2bb64387817a
1c466e0fb8c96c8823238af90cac0909d3b8011c
refs/heads/master
2021-10-08T05:04:44.974223
2018-12-07T23:04:17
2018-12-07T23:04:17
105,313,149
0
1
null
2017-10-02T13:04:26
2017-09-29T20:14:25
Python
UTF-8
R
false
false
3,271
r
new_sfs.R
#!/usr/bin/env Rscript library(tidyverse) library(glue) multi_dfe_out <- function(df, fname) { writeLines( c( nrow(df) - 1, paste(df$Selected, collapse =" "), paste(df$Neutral, collapse =" ") ), con = glue::glue(fname), sep = "\n" ) } # writing function process_sfs <- function(neut, sel, n_strains) { # c_regions <- gsub(".tsv", "", strsplit(neut, split = "_")[[1]][4]) n_deets <- strsplit(neut, split = "_")[[1]][3] s_deets <- gsub(".tsv", "",strsplit(sel, split = "_SELECTED_")[[1]][2]) save_name <- glue::glue("{n_deets}_{s_deets}") af_df <- data.frame(DERIVED_AF = round(seq(0,1,by = 1/n_strains), digits = 5)) neutral_sites <- data.table::fread(neut, col.names = c("CHROM","POS","AA","GT","COUNT","AA_CLASS")) %>% dplyr::group_by(CHROM,POS) %>% dplyr::mutate(allele_counts = sum(COUNT)) %>% dplyr::rowwise() %>% dplyr::mutate(ALLELE_AF = COUNT/allele_counts) %>% dplyr::mutate(DERIVED_AF = ifelse(AA_CLASS == "ANCESTOR" && ALLELE_AF == 1, 0, ifelse(AA_CLASS == "DERIVED", round(ALLELE_AF,digits = 5), NA))) %>% na.omit() %>% dplyr::group_by(DERIVED_AF) %>% dplyr::summarise(Neutral = n()) %>% dplyr::left_join(af_df, ., by = "DERIVED_AF") selected_sites <- data.table::fread(sel, col.names = c("CHROM","POS","AA","GT","COUNT","AA_CLASS")) %>% dplyr::group_by(CHROM,POS) %>% dplyr::mutate(allele_counts = sum(COUNT)) %>% dplyr::rowwise() %>% dplyr::mutate(ALLELE_AF = COUNT/allele_counts) %>% dplyr::mutate(DERIVED_AF = ifelse(AA_CLASS == "ANCESTOR" && ALLELE_AF == 1, 0, ifelse(AA_CLASS == "DERIVED", round(ALLELE_AF,digits = 5), NA))) %>% na.omit() %>% dplyr::group_by(DERIVED_AF) %>% dplyr::summarise(Selected = n()) %>% dplyr::left_join(af_df, ., by = "DERIVED_AF") sfs_df <- dplyr::left_join(neutral_sites, selected_sites , by = "DERIVED_AF") # Replace NAs with 0 sfs_df[is.na(sfs_df)] <- 0 # save file multi_dfe_out(df = sfs_df, fname = glue::glue("{save_name}.sfs")) # plot sfs_plot <- sfs_df%>% tidyr::gather(SITES, COUNTS, -DERIVED_AF) %>% dplyr::group_by(SITES) %>% dplyr::mutate(frq = COUNTS/sum(COUNTS)) %>% ggplot()+ aes(x = DERIVED_AF, y = frq, color = SITES)+ geom_line()+ theme_bw(15)+ labs(x = "Derived AF", y = "Frequency") ggsave(sfs_plot, filename = glue::glue("{save_name}.pdf"), height = 6, width = 8) } # prep file names neutral <- grep("NEUTRAL", list.files(), value = T) neutral_arms <- grep("ARMS", neutral, value = T) neutral_centers <- grep("CENTERS", neutral, value = T) neutral_genome <- grep("GENOME", neutral, value = T) selected <- grep("SELECTED", list.files(), value = T) selected_arms <- grep("ARMS", selected, value = T) selected_centers <- grep("CENTERS", selected, value = T) selected_genome <- grep("GENOME", selected, value = T) for(nt_f in 1:length(neutral_genome)) { for(st_f in 1:length(selected_genome)) { process_sfs(neutral_genome[nt_f], selected_genome[st_f], 239) process_sfs(neutral_arms[nt_f], selected_arms[st_f], 239) process_sfs(neutral_centers[nt_f], selected_centers[st_f], 239) } }
ae7d21104a57d6de91faaeb308e18d7b260011f9
439322912321e742e7f92374ecb76c76743984cb
/R/generics.R
0f8c2074053df7a02ae67bcbb021801731d3275d
[ "MIT" ]
permissive
vbaliga/univariateML
62d2c00017b93f2e1ed8357dd5d9062cf66744cd
0410647e2528dc61fa7b7b7cce95273777059baf
refs/heads/master
2020-09-11T19:04:44.904257
2019-11-24T19:12:20
2019-11-24T19:12:20
222,160,994
0
0
NOASSERTION
2019-11-16T21:23:07
2019-11-16T21:23:07
null
UTF-8
R
false
false
5,529
r
generics.R
#' Wrangles arguments for use in the plot, lines and points functions. #' #' @param x The input data. #' @param range Range of the data. #' @param points Boolean; should points be plotted by default? #' @keywords internal plot_wrangler = function(x, range, points = FALSE, ...) { if(is.null(range)) { if(abs(attr(x, "support")[1]) + abs(attr(x, "support")[2]) < Inf) { limits = attr(x, "support") } else if (abs(attr(x, "support")[1]) == 0 & abs(attr(x, "support")[2]) == Inf) { limits = c(0, qml(0.99, x)) } else { limits = qml(c(0.01, 0.99), x) } range = seq(limits[1], limits[2], length.out = 1000) } defaults = list(type = if(points) "p" else "l", main = paste0(attr(x, "model"), " model"), ylab = "Density", xlab = "x", lwd = 1) args = listmerge(x = defaults, y = list(...)) args$x = range args$y = dml(args$x, x) args } #' Plot, Lines and Points Methods for Maximum Likelihood Estimates #' #' The \code{plot}, \code{lines}, and \code{points} methods for \code{univariateML} objects. #' #' @export #' @param x a \code{univariateML} object. #' @param range range of \code{x} values to plot, i.e. \code{c(lower, upper)}. #' @param ... parameters passed to \code{plot}, \code{lines}, or \code{points}. #' @return An invisible copy of \code{x}. #' @examples #' plot(mlweibull(datasets::precip), main = "Annual Precipitation in US Cities") #' lines(mlgamma(datasets::precip), lty = 2) #' rug(datasets::precip) #' @export #' plot.univariateML = function(x, range = NULL, ...) { args = plot_wrangler(x, range, points = FALSE, ...) do.call(graphics::plot, args) invisible(x) } #' @export #' @rdname plot.univariateML lines.univariateML = function(x, range = NULL, ...) { args = plot_wrangler(x, range, points = FALSE, ...) do.call(graphics::lines, args) invisible(x) } #' @export #' @rdname plot.univariateML points.univariateML = function(x, range = NULL, ...) { args = plot_wrangler(x, range, points = TRUE, ...) do.call(graphics::points, args) invisible(x) } #' @export logLik.univariateML = function(object, ...) { val = attr(object, "logLik") attr(val, "nobs") = attr(object, "n") attr(val, "df") = length(object) class(val) = "logLik" val } #' @export coef.univariateML = function(object, ...) { stats::setNames(as.numeric(object), names(object)) } #' @export summary.univariateML = function(object, ...) { data.name = deparse(as.list(attr(object, "call"))$x) digits = list(...)$digits cat("\nMaximum likelihood for the", attr(object, "model"), "model \n", "\nCall: ", deparse(attr(object, "call")), "\n\nEstimates: \n") print.default(format(object, digits = digits), print.gap = 2L, quote = FALSE) cat("\nData: ", data.name, " (", attr(object, "n"), " obs.)\n", "Support: (", attr(object, "support")[1], ", ", attr(object, "support")[2], ")\n", "Density: ", attr(object, "density"), "\n", "Log-likelihood: ", attr(object, "logLik"), "\n", sep = "") invisible(object) } #' @export print.univariateML = function(x, ...) { digits = list(...)$digits if(is.null(digits)) digits = 4 cat("Maximum likelihood estimates for the", attr(x, "model"), "model \n") print.default(format(x, digits = digits), print.gap = 2L, quote = FALSE) invisible(x) } #' Confidence Intervals for Maximum Likelihood Estimates #' #' Computes a confidence interval for one or more parameters in a \code{unvariateML} #' object. #' #' \code{confint.univariateML} is a wrapper for \code{\link{bootstrapml}} that computes #' confidence intervals for the main parameters of \code{object}. The main parameters of \code{object} are #' the members of \code{names(object)}. For instance,the main parameters of an object obtained from \code{mlnorm} are \code{mean} and \code{sd}. #' The confidence intervals are parametric bootstrap percentile intervals with limits \code{(1-level)/2} and \code{1 - (1-level)}. #' #' @param object An object of class \code{univariateML}. #' @param parm Vector of strings; the parameters to calculate a confidence #' interval for. Each parameter must be a member of \code{names(object)}. #' @param level The confidence level. #' @param Nreps Number of bootstrap iterations. Passed to \code{\link{bootstrapml}}. #' @param ... Additional arguments passed to \code{\link{bootstrapml}}. #' @return A matrix or vector with columns giving lower and upper confidence #' limits for each parameter in \code{parm}. #' @seealso \code{\link[stats]{confint}} for the generic function and \code{\link{bootstrapml}} for the #' function used to calculate the confidence intervals. #' @export #' @examples #' object = mlinvgauss(airquality$Wind) #' confint(object) # 95% confidence interval for mean and shape #' confint(object, "mean") # 95% confidence interval for the mean parameter #' # confint(object, "variance") # Fails since 'variance isn't a main parameter. confint.univariateML = function(object, parm = NULL, level = 0.95, Nreps = 1000, ...) { if(is.null(parm)) parm = names(object) assertthat::assert_that(all(parm %in% names(object)), msg = "'parm' must contain valid parameter names or be NULL") indices = which(names(object) %in% parm) map = function(x) x[indices] probs = c((1 - level)/2, 1 - (1 - level)/2) bootstrapml(object, map = map, probs = probs, Nreps = Nreps, ...) }
387489689298a4d8d3c426c2a857a3d4ae3119dd
6c71e2f04573abc8498a6ba1303413c088bbaec8
/Evaluacion.R
deb98bb034248a455cd492d4ccc1d3b3d336d742
[]
no_license
Jgallo-R/TareaClase05
f8c86375a11086c5d20d96fed7529661ffc3e72a
51d243b84c18056983cdd9b999ab9862af98d4c1
refs/heads/master
2022-11-10T22:35:18.667881
2020-06-21T01:45:15
2020-06-21T01:45:15
273,814,931
0
0
null
null
null
null
ISO-8859-1
R
false
false
17,237
r
Evaluacion.R
############################################# EVALUACION ########################################## # Describir modelos AR(2), graficarlos para valores diferentes # de los argumentos (ar=c(p1,p2)) #AR(2) AR2 <- arima.sim(model=list(order=c(2,0,0), ar=c(0.1,0.2)), n=100, sd=0.1) #Probar varias combinaciones de p1 y p2, graficas las series de tiempo # simularlas y sus correspondientes funciones de autocorrelacion simple # y funciones de autocorrelacion parcial # repetir lo mismo con los procesos MA ############################################## SOLUCION ###################################### ### Cargamos las librerias necesarias library(ggplot2) library(tseries) library(forecast) library(quantmod) ######################################## Para N=100 (N GRANDE)########################################### ##1.-Simulando Modelo AR(2) #Para que el proceso sea estacionario se debe cumplir: # -1 < phi(2) < 1 ó phi(1) + phi(2)< 1 ó phi(2)-phi(1)< 1 # Con este criterio generemos algunos coeficientes phi(1)y phi(2) #definimos la semilla set.seed(999) ##Generamos los modelos con diferentes valores de phi1 y phi2 con valores altos, bajos y negativos AR2.1 <- arima.sim(n = 100 , model = list(order = c(2,0,0) , ar=c(0.1,0.2) , sd=0.1)) AR2.2 <- arima.sim(n = 100 , model = list(order = c(2,0,0) , ar=c(-0.1,0.2) , sd=0.1)) AR2.3 <- arima.sim(n = 100 , model = list(order = c(2,0,0) , ar=c(0.1,-0.2) , sd=0.1)) AR2.4 <- arima.sim(n = 100 , model = list(order = c(2,0,0) , ar=c(-0.1,-0.2) , sd=0.1)) AR2.5 <- arima.sim(n = 100, model = list(order = c(2,0,0) , ar=c(0.1,0.8) , sd=0.1)) AR2.6 <- arima.sim(n = 100,model = list(order = c(2,0,0) , ar=c(-0.1,0.8) , sd=0.1)) AR2.7 <- arima.sim(n = 100, model = list(order = c(2,0,0) , ar=c(0.1,-0.8) , sd=0.1)) AR2.8 <- arima.sim(n = 100, model = list(order = c(2,0,0) , ar=c(-0.1,-0.8) , sd=0.1)) AR2.9 <- arima.sim(n = 100, model = list(order = c(2,0,0) , ar=c(0.8,0.1) , sd=0.1)) AR2.10 <- arima.sim(n = 100, model = list(order = c(2,0,0) , ar=c(-0.8,0.1) , sd=0.1)) AR2.11 <- arima.sim(n = 100, model = list(order = c(2,0,0) , ar=c(0.8,-0.1) , sd=0.1)) AR2.12 <- arima.sim(n = 100, model = list(order = c(2,0,0) , ar=c(-0.8,-0.1) , sd=0.1)) # grafiquemos estas series de tiempo simuladas graphics.off() par(mfrow = c(3,4)) ylm <- c(min(AR2.1, AR2.2, AR2.3, AR2.4, AR2.5, AR2.6, AR2.7, AR2.8, AR2.9, AR2.10, AR2.11, AR2.12) , max(AR2.1, AR2.2, AR2.3, AR2.4, AR2.5, AR2.6, AR2.7, AR2.8, AR2.9, AR2.10, AR2.11, AR2.12)) plot.ts(AR2.1, ylim = ylm, main = "AR(2) phi[1] = 0.1 y phi[2] = 0.2") plot.ts(AR2.2, ylim = ylm, main = "AR(2) phi[1] = -0.1 y phi[2] = 0.2") plot.ts(AR2.3, ylim = ylm, main = "AR(2) phi[1] = 0.1 y phi[2] = -0.2") plot.ts(AR2.4, ylim = ylm, main = "AR(2) phi[1] = -0.1 y phi[2] = -0.2") plot.ts(AR2.5, ylim = ylm, main = "AR(2) phi[1] = 0.1 y phi[2] = 0.8") plot.ts(AR2.6, ylim = ylm, main = "AR(2) phi[1] = -0.1 y phi[2] = 0.8") plot.ts(AR2.7, ylim = ylm, main = "AR(2) phi[1] = 0.1 y phi[2] = -0.8") plot.ts(AR2.8, ylim = ylm, main = "AR(2) phi[1] = -0.1 y phi[2] = -0.8") plot.ts(AR2.9, ylim = ylm, main = "AR(2) phi[1] = 0.8 y phi[2] = 0.1") plot.ts(AR2.10, ylim = ylm, main = "AR(2) phi[1] = -0.8 y phi[2] = 0.1") plot.ts(AR2.11, ylim = ylm, main = "AR(2) phi[1] = 0.8 y phi[2] = -0.1") plot.ts(AR2.12, ylim = ylm, main = "AR(2) phi[1] = -0.8 y phi[2] = -0.1") ##Graficamos las AFC (Funciones de autocorrelacion simples) para el AR(2) graphics.off() par(mfrow = c(3,4)) acf(AR2.1,main="AR(2) phi[1] = 0.1 y phi[2] = 0.2") acf(AR2.2,main="AR(2) phi[1] = -0.1 y phi[2] = 0.2") acf(AR2.3,main="AR(2) phi[1] = 0.1 y phi[2] = -0.2") acf(AR2.4,main="AR(2) phi[1] = -0.1 y phi[2] = -0.2") acf(AR2.5,main="AR(2) phi[1] = 0.1 y phi[2] = 0.8") acf(AR2.6,main="AR(2) phi[1] = -0.1 y phi[2] = 0.8") acf(AR2.7,main="AR(2) phi[1] = 0.1 y phi[2] = -0.8") acf(AR2.8,main="AR(2) phi[1] = -0.1 y phi[2] = -0.8") acf(AR2.9,main="AR(2) phi[1] = 0.8 y phi[2] = 0.1") acf(AR2.10,main="AR(2) phi[1] = -0.8 y phi[2] = 0.1") acf(AR2.11,main="AR(2) phi[1] = 0.8 y phi[2] = -0.1") acf(AR2.12,main="AR(2) phi[1] = -0.8 y phi[2] = -0.1") ##Graficamos las PAFC (Funciones de autocorrelacion simples) para el AR(2) graphics.off() par(mfrow = c(3,4)) pacf(AR2.1,main="phi[1] = 0.1 y phi[2] = 0.2") pacf(AR2.2,main="phi[1] = -0.1 y phi[2] = 0.2") pacf(AR2.3,main="phi[1] = 0.1 y phi[2] = -0.2") pacf(AR2.4,main="phi[1] = -0.1 y phi[2] = -0.2") pacf(AR2.5,main="phi[1] = 0.1 y phi[2] = 0.8") pacf(AR2.6,main="phi[1] = -0.1 y phi[2] = 0.8") pacf(AR2.7,main="phi[1] = 0.1 y phi[2] = -0.8") pacf(AR2.8,main="phi[1] = -0.1 y phi[2] = -0.8") pacf(AR2.9,main="phi[1] = 0.8 y phi[2] = 0.1") pacf(AR2.10,main="phi[1] = -0.8 y phi[2] = 0.1") pacf(AR2.11,main="phi[1] = 0.8 y phi[2] = -0.1") pacf(AR2.12,main="phi[1] = -0.8 y phi[2] = -0.1") ##1.-Simulando Modelo MA(2) # Los Modelos MA siempre son estacionarios #definimos la semilla set.seed(999) ##Generamos los modelos con diferentes valores de phi1 y phi2 con valores altos, bajos y negativos MA2.1 <- arima.sim(n = 100 , model = list(order = c(0,0,2) , ma=c(0.1,0.2) , sd=0.1)) MA2.2 <- arima.sim(n = 100 , model = list(order = c(0,0,2) , ma=c(-0.1,0.2) , sd=0.1)) MA2.3 <- arima.sim(n = 100 , model = list(order = c(0,0,2) , ma=c(0.1,-0.2) , sd=0.1)) MA2.4 <- arima.sim(n = 100 , model = list(order = c(0,0,2) , ma=c(-0.1,-0.2) , sd=0.1)) MA2.5 <- arima.sim(n = 100, model = list(order = c(0,0,2) , ma=c(0.1,0.8) , sd=0.1)) MA2.6 <- arima.sim(n = 100,model = list(order = c(0,0,2) , ma=c(-0.1,0.8) , sd=0.1)) MA2.7 <- arima.sim(n = 100, model = list(order = c(0,0,2) , ma=c(0.1,-0.8) , sd=0.1)) MA2.8 <- arima.sim(n = 100, model = list(order = c(0,0,2) , ma=c(-0.1,-0.8) , sd=0.1)) MA2.9 <- arima.sim(n = 100, model = list(order = c(0,0,2) , ma=c(0.8,0.1) , sd=0.1)) MA2.10 <- arima.sim(n = 100, model = list(order = c(0,0,2) , ma=c(-0.8,0.1) , sd=0.1)) MA2.11 <- arima.sim(n = 100, model = list(order = c(0,0,2) , ma=c(0.8,-0.1) , sd=0.1)) MA2.12 <- arima.sim(n = 100, model = list(order = c(0,0,2) , ma=c(-0.8,-0.1) , sd=0.1)) # grafiquemos estas series de tiempo simuladas grathetacs.off() par(mfrow = c(3,4)) ylm <- c(min(MA2.1, MA2.2, MA2.3, MA2.4, MA2.5, MA2.6, MA2.7, MA2.8, MA2.9, MA2.10, MA2.11, MA2.12) , max(MA2.1, MA2.2, MA2.3, MA2.4, MA2.5, MA2.6, MA2.7, MA2.8, MA2.9, MA2.10, MA2.11, MA2.12)) plot.ts(MA2.1, ylim = ylm, main = "MA(2) theta[1] = 0.1 y theta[2] = 0.2") plot.ts(MA2.2, ylim = ylm, main = "MA(2) theta[1] = -0.1 y theta[2] = 0.2") plot.ts(MA2.3, ylim = ylm, main = "MA(2) theta[1] = 0.1 y theta[2] = -0.2") plot.ts(MA2.4, ylim = ylm, main = "MA(2) theta[1] = -0.1 y theta[2] = -0.2") plot.ts(MA2.5, ylim = ylm, main = "MA(2) theta[1] = 0.1 y theta[2] = 0.8") plot.ts(MA2.6, ylim = ylm, main = "MA(2) theta[1] = -0.1 y theta[2] = 0.8") plot.ts(MA2.7, ylim = ylm, main = "MA(2) theta[1] = 0.1 y theta[2] = -0.8") plot.ts(MA2.8, ylim = ylm, main = "MA(2) theta[1] = -0.1 y theta[2] = -0.8") plot.ts(MA2.9, ylim = ylm, main = "MA(2) theta[1] = 0.8 y theta[2] = 0.1") plot.ts(MA2.10, ylim = ylm, main = "MA(2) theta[1] = -0.8 y theta[2] = 0.1") plot.ts(MA2.11, ylim = ylm, main = "MA(2) theta[1] = 0.8 y theta[2] = -0.1") plot.ts(MA2.12, ylim = ylm, main = "MA(2) theta[1] = -0.8 y theta[2] = -0.1") ##Graficamos las AFC (Funciones de autocorrelacion simples) grathetacs.off() par(mfrow = c(3,4)) acf(MA2.1,main="ACF MA(2) theta[1] = 0.1 y theta[2] = 0.2") acf(MA2.2,main="ACF MA(2) theta[1] = -0.1 y theta[2] = 0.2") acf(MA2.3,main="ACF MA(2) theta[1] = 0.1 y theta[2] = -0.2") acf(MA2.4,main="ACF MA(2) theta[1] = -0.1 y theta[2] = -0.2") acf(MA2.5,main="ACF MA(2) theta[1] = 0.1 y theta[2] = 0.8") acf(MA2.6,main="ACF MA(2) theta[1] = -0.1 y theta[2] = 0.8") acf(MA2.7,main="ACF MA(2) theta[1] = 0.1 y theta[2] = -0.8") acf(MA2.8,main="ACF MA(2) theta[1] = -0.1 y theta[2] = -0.8") acf(MA2.9,main="ACF MA(2) theta[1] = 0.8 y theta[2] = 0.1") acf(MA2.10,main="ACF MA(2) theta[1] = -0.8 y theta[2] = 0.1") acf(MA2.11,main="ACF MA(2) theta[1] = 0.8 y theta[2] = -0.1") acf(MA2.12,main="ACF MA(2) theta[1] = -0.8 y theta[2] = -0.1") ##Graficamos las PAFC (Funciones de autocorrelacion simples) grathetacs.off() par(mfrow = c(3,4)) pacf(MA2.1,main="PACF theta[1] = 0.1 y theta[2] = 0.2") pacf(MA2.2,main="PACF theta[1] = -0.1 y theta[2] = 0.2") pacf(MA2.3,main="PACF theta[1] = 0.1 y theta[2] = -0.2") pacf(MA2.4,main="PACF theta[1] = -0.1 y theta[2] = -0.2") pacf(MA2.5,main="PACF theta[1] = 0.1 y theta[2] = 0.8") pacf(MA2.6,main="PACF theta[1] = -0.1 y theta[2] = 0.8") pacf(MA2.7,main="PACF theta[1] = 0.1 y theta[2] = -0.8") pacf(MA2.8,main="PACF theta[1] = -0.1 y theta[2] = -0.8") pacf(MA2.9,main="PACF theta[1] = 0.8 y theta[2] = 0.1") pacf(MA2.10,main="PACF theta[1] = -0.8 y theta[2] = 0.1") pacf(MA2.11,main="PACF theta[1] = 0.8 y theta[2] = -0.1") pacf(MA2.12,main="PACF theta[1] = -0.8 y theta[2] = -0.1") ######################################## Para N=30 (N PEQUEÑO)########################################### ##1.-Simulando Modelo AR(2) #Para que el proceso sea estacionario se debe cumplir: # -1 < phi(2) < 1 ó phi(1) + phi(2)< 1 ó phi(2)-phi(1)< 1 # Con este criterio generemos algunos coeficientes phi(1)y phi(2) #definimos la semilla set.seed(999) ##Generamos los modelos con diferentes valores de phi1 y phi2 con valores altos, bajos y negativos AR2.1 <- arima.sim(n = 30 , model = list(order = c(2,0,0) , ar=c(0.1,0.2) , sd=0.1)) AR2.2 <- arima.sim(n = 30 , model = list(order = c(2,0,0) , ar=c(-0.1,0.2) , sd=0.1)) AR2.3 <- arima.sim(n = 30 , model = list(order = c(2,0,0) , ar=c(0.1,-0.2) , sd=0.1)) AR2.4 <- arima.sim(n = 30 , model = list(order = c(2,0,0) , ar=c(-0.1,-0.2) , sd=0.1)) AR2.5 <- arima.sim(n = 30, model = list(order = c(2,0,0) , ar=c(0.1,0.8) , sd=0.1)) AR2.6 <- arima.sim(n = 30,model = list(order = c(2,0,0) , ar=c(-0.1,0.8) , sd=0.1)) AR2.7 <- arima.sim(n = 30, model = list(order = c(2,0,0) , ar=c(0.1,-0.8) , sd=0.1)) AR2.8 <- arima.sim(n = 30, model = list(order = c(2,0,0) , ar=c(-0.1,-0.8) , sd=0.1)) AR2.9 <- arima.sim(n = 30, model = list(order = c(2,0,0) , ar=c(0.8,0.1) , sd=0.1)) AR2.10 <- arima.sim(n = 30, model = list(order = c(2,0,0) , ar=c(-0.8,0.1) , sd=0.1)) AR2.11 <- arima.sim(n = 30, model = list(order = c(2,0,0) , ar=c(0.8,-0.1) , sd=0.1)) AR2.12 <- arima.sim(n = 30, model = list(order = c(2,0,0) , ar=c(-0.8,-0.1) , sd=0.1)) # grafiquemos estas series de tiempo simuladas graphics.off() par(mfrow = c(3,4)) ylm <- c(min(AR2.1, AR2.2, AR2.3, AR2.4, AR2.5, AR2.6, AR2.7, AR2.8, AR2.9, AR2.10, AR2.11, AR2.12) , max(AR2.1, AR2.2, AR2.3, AR2.4, AR2.5, AR2.6, AR2.7, AR2.8, AR2.9, AR2.10, AR2.11, AR2.12)) plot.ts(AR2.1, ylim = ylm, main = "AR(2) phi[1] = 0.1 y phi[2] = 0.2") plot.ts(AR2.2, ylim = ylm, main = "AR(2) phi[1] = -0.1 y phi[2] = 0.2") plot.ts(AR2.3, ylim = ylm, main = "AR(2) phi[1] = 0.1 y phi[2] = -0.2") plot.ts(AR2.4, ylim = ylm, main = "AR(2) phi[1] = -0.1 y phi[2] = -0.2") plot.ts(AR2.5, ylim = ylm, main = "AR(2) phi[1] = 0.1 y phi[2] = 0.8") plot.ts(AR2.6, ylim = ylm, main = "AR(2) phi[1] = -0.1 y phi[2] = 0.8") plot.ts(AR2.7, ylim = ylm, main = "AR(2) phi[1] = 0.1 y phi[2] = -0.8") plot.ts(AR2.8, ylim = ylm, main = "AR(2) phi[1] = -0.1 y phi[2] = -0.8") plot.ts(AR2.9, ylim = ylm, main = "AR(2) phi[1] = 0.8 y phi[2] = 0.1") plot.ts(AR2.10, ylim = ylm, main = "AR(2) phi[1] = -0.8 y phi[2] = 0.1") plot.ts(AR2.11, ylim = ylm, main = "AR(2) phi[1] = 0.8 y phi[2] = -0.1") plot.ts(AR2.12, ylim = ylm, main = "AR(2) phi[1] = -0.8 y phi[2] = -0.1") ##Graficamos las AFC (Funciones de autocorrelacion simples) para el AR(2) graphics.off() par(mfrow = c(3,4)) acf(AR2.1,main="AR(2) phi[1] = 0.1 y phi[2] = 0.2") acf(AR2.2,main="AR(2) phi[1] = -0.1 y phi[2] = 0.2") acf(AR2.3,main="AR(2) phi[1] = 0.1 y phi[2] = -0.2") acf(AR2.4,main="AR(2) phi[1] = -0.1 y phi[2] = -0.2") acf(AR2.5,main="AR(2) phi[1] = 0.1 y phi[2] = 0.8") acf(AR2.6,main="AR(2) phi[1] = -0.1 y phi[2] = 0.8") acf(AR2.7,main="AR(2) phi[1] = 0.1 y phi[2] = -0.8") acf(AR2.8,main="AR(2) phi[1] = -0.1 y phi[2] = -0.8") acf(AR2.9,main="AR(2) phi[1] = 0.8 y phi[2] = 0.1") acf(AR2.10,main="AR(2) phi[1] = -0.8 y phi[2] = 0.1") acf(AR2.11,main="AR(2) phi[1] = 0.8 y phi[2] = -0.1") acf(AR2.12,main="AR(2) phi[1] = -0.8 y phi[2] = -0.1") ##Graficamos las PAFC (Funciones de autocorrelacion simples) para el AR(2) graphics.off() par(mfrow = c(3,4)) pacf(AR2.1,main="phi[1] = 0.1 y phi[2] = 0.2") pacf(AR2.2,main="phi[1] = -0.1 y phi[2] = 0.2") pacf(AR2.3,main="phi[1] = 0.1 y phi[2] = -0.2") pacf(AR2.4,main="phi[1] = -0.1 y phi[2] = -0.2") pacf(AR2.5,main="phi[1] = 0.1 y phi[2] = 0.8") pacf(AR2.6,main="phi[1] = -0.1 y phi[2] = 0.8") pacf(AR2.7,main="phi[1] = 0.1 y phi[2] = -0.8") pacf(AR2.8,main="phi[1] = -0.1 y phi[2] = -0.8") pacf(AR2.9,main="phi[1] = 0.8 y phi[2] = 0.1") pacf(AR2.10,main="phi[1] = -0.8 y phi[2] = 0.1") pacf(AR2.11,main="phi[1] = 0.8 y phi[2] = -0.1") pacf(AR2.12,main="phi[1] = -0.8 y phi[2] = -0.1") ##1.-Simulando Modelo MA(2) # Los Modelos MA siempre son estacionarios #definimos la semilla set.seed(999) ##Generamos los modelos con diferentes valores de phi1 y phi2 con valores altos, bajos y negativos MA2.1 <- arima.sim(n = 30 , model = list(order = c(0,0,2) , ma=c(0.1,0.2) , sd=0.1)) MA2.2 <- arima.sim(n = 30 , model = list(order = c(0,0,2) , ma=c(-0.1,0.2) , sd=0.1)) MA2.3 <- arima.sim(n = 30 , model = list(order = c(0,0,2) , ma=c(0.1,-0.2) , sd=0.1)) MA2.4 <- arima.sim(n = 30 , model = list(order = c(0,0,2) , ma=c(-0.1,-0.2) , sd=0.1)) MA2.5 <- arima.sim(n = 30, model = list(order = c(0,0,2) , ma=c(0.1,0.8) , sd=0.1)) MA2.6 <- arima.sim(n = 30,model = list(order = c(0,0,2) , ma=c(-0.1,0.8) , sd=0.1)) MA2.7 <- arima.sim(n = 30, model = list(order = c(0,0,2) , ma=c(0.1,-0.8) , sd=0.1)) MA2.8 <- arima.sim(n = 30, model = list(order = c(0,0,2) , ma=c(-0.1,-0.8) , sd=0.1)) MA2.9 <- arima.sim(n = 30, model = list(order = c(0,0,2) , ma=c(0.8,0.1) , sd=0.1)) MA2.10 <- arima.sim(n = 30, model = list(order = c(0,0,2) , ma=c(-0.8,0.1) , sd=0.1)) MA2.11 <- arima.sim(n = 30, model = list(order = c(0,0,2) , ma=c(0.8,-0.1) , sd=0.1)) MA2.12 <- arima.sim(n = 30, model = list(order = c(0,0,2) , ma=c(-0.8,-0.1) , sd=0.1)) # grafiquemos estas series de tiempo simuladas grathetacs.off() par(mfrow = c(3,4)) ylm <- c(min(MA2.1, MA2.2, MA2.3, MA2.4, MA2.5, MA2.6, MA2.7, MA2.8, MA2.9, MA2.10, MA2.11, MA2.12) , max(MA2.1, MA2.2, MA2.3, MA2.4, MA2.5, MA2.6, MA2.7, MA2.8, MA2.9, MA2.10, MA2.11, MA2.12)) plot.ts(MA2.1, ylim = ylm, main = "MA(2) theta[1] = 0.1 y theta[2] = 0.2") plot.ts(MA2.2, ylim = ylm, main = "MA(2) theta[1] = -0.1 y theta[2] = 0.2") plot.ts(MA2.3, ylim = ylm, main = "MA(2) theta[1] = 0.1 y theta[2] = -0.2") plot.ts(MA2.4, ylim = ylm, main = "MA(2) theta[1] = -0.1 y theta[2] = -0.2") plot.ts(MA2.5, ylim = ylm, main = "MA(2) theta[1] = 0.1 y theta[2] = 0.8") plot.ts(MA2.6, ylim = ylm, main = "MA(2) theta[1] = -0.1 y theta[2] = 0.8") plot.ts(MA2.7, ylim = ylm, main = "MA(2) theta[1] = 0.1 y theta[2] = -0.8") plot.ts(MA2.8, ylim = ylm, main = "MA(2) theta[1] = -0.1 y theta[2] = -0.8") plot.ts(MA2.9, ylim = ylm, main = "MA(2) theta[1] = 0.8 y theta[2] = 0.1") plot.ts(MA2.10, ylim = ylm, main = "MA(2) theta[1] = -0.8 y theta[2] = 0.1") plot.ts(MA2.11, ylim = ylm, main = "MA(2) theta[1] = 0.8 y theta[2] = -0.1") plot.ts(MA2.12, ylim = ylm, main = "MA(2) theta[1] = -0.8 y theta[2] = -0.1") ##Graficamos las AFC (Funciones de autocorrelacion simples) grathetacs.off() par(mfrow = c(3,4)) acf(MA2.1,main="ACF MA(2) theta[1] = 0.1 y theta[2] = 0.2") acf(MA2.2,main="ACF MA(2) theta[1] = -0.1 y theta[2] = 0.2") acf(MA2.3,main="ACF MA(2) theta[1] = 0.1 y theta[2] = -0.2") acf(MA2.4,main="ACF MA(2) theta[1] = -0.1 y theta[2] = -0.2") acf(MA2.5,main="ACF MA(2) theta[1] = 0.1 y theta[2] = 0.8") acf(MA2.6,main="ACF MA(2) theta[1] = -0.1 y theta[2] = 0.8") acf(MA2.7,main="ACF MA(2) theta[1] = 0.1 y theta[2] = -0.8") acf(MA2.8,main="ACF MA(2) theta[1] = -0.1 y theta[2] = -0.8") acf(MA2.9,main="ACF MA(2) theta[1] = 0.8 y theta[2] = 0.1") acf(MA2.10,main="ACF MA(2) theta[1] = -0.8 y theta[2] = 0.1") acf(MA2.11,main="ACF MA(2) theta[1] = 0.8 y theta[2] = -0.1") acf(MA2.12,main="ACF MA(2) theta[1] = -0.8 y theta[2] = -0.1") ##Graficamos las PAFC (Funciones de autocorrelacion simples) grathetacs.off() par(mfrow = c(3,4)) pacf(MA2.1,main="PACF theta[1] = 0.1 y theta[2] = 0.2") pacf(MA2.2,main="PACF theta[1] = -0.1 y theta[2] = 0.2") pacf(MA2.3,main="PACF theta[1] = 0.1 y theta[2] = -0.2") pacf(MA2.4,main="PACF theta[1] = -0.1 y theta[2] = -0.2") pacf(MA2.5,main="PACF theta[1] = 0.1 y theta[2] = 0.8") pacf(MA2.6,main="PACF theta[1] = -0.1 y theta[2] = 0.8") pacf(MA2.7,main="PACF theta[1] = 0.1 y theta[2] = -0.8") pacf(MA2.8,main="PACF theta[1] = -0.1 y theta[2] = -0.8") pacf(MA2.9,main="PACF theta[1] = 0.8 y theta[2] = 0.1") pacf(MA2.10,main="PACF theta[1] = -0.8 y theta[2] = 0.1") pacf(MA2.11,main="PACF theta[1] = 0.8 y theta[2] = -0.1") pacf(MA2.12,main="PACF theta[1] = -0.8 y theta[2] = -0.1")
7b8202045d93426ffd7b40a2dd36d0f7525f25e4
e4b5596f5dc9dd0b1408ee2a72d5274eb97fc0a5
/Course2/week3/w3.R
4b6b2bc55651f0c14d06ce1bbd7c686c84be3a16
[]
no_license
luuduytung/statistics-with-r-coursera
145cd0541fb1b4e0de24526cc9e40ed0df261708
bee573560badb61500cbb713f2a131c7250bfda8
refs/heads/master
2020-03-31T13:43:06.435476
2018-10-09T23:15:55
2018-10-09T23:15:55
152,266,738
0
0
null
null
null
null
UTF-8
R
false
false
701
r
w3.R
library(statsr) library(dplyr) library(ggplot2) data(nc) str(nc) summary(nc$gained) ggplot(data = nc,aes(x=habit,y=weight))+geom_boxplot() nc %>% group_by(habit) %>% summarise(x_bar = mean(weight)) nc %>% group_by(habit) %>% summarise(nb = n()) inference(y = weight, x = habit, data = nc, statistic = "mean", type = "ht", null = 0, alternative = "twosided", method = "theoretical") inference(y=weight, x=habit,data=nc,statistic="mean",type="ci",method="theoretical") inference(y = weight, x = habit, data = nc, statistic = "mean", type = "ci", method = "theoretical", order = c("smoker","nonsmoker")) nc %>% group_by(mature) %>% summarise(x_max = max(mage),x_min=min(mage))
5bf7b4c19cf2a235720371db10bfa3cd8a6fafba
5e2726e2ea5bff209473d757bce76ac20e4bd17a
/fishy_hz.R
b755ed47382b3540f834f67f7b658a1d52735569
[]
no_license
julievdh/FHL
f8170d01300897b2d4a0359883ca7830ec24d917
ad68e1d2615b8f09a84090a1d3de9de6cc04679b
refs/heads/master
2020-04-24T17:48:22.110459
2018-05-27T16:04:29
2018-05-27T16:04:29
38,321,517
0
0
null
null
null
null
UTF-8
R
false
false
6,801
r
fishy_hz.R
# look at fin beat stuff.... # David L Miller 5 December 2017 hz <- read.csv("FishVO2Hz.csv") # make codes for the speeds hz$speedcode <- "H" hz$speedcode[hz$speed == 0.5] <- "L" hz$speedcode[hz$speed == 1.5] <- "M" # speeds set at 0.5, 1.5 and then the max that got data for both turbulent # and laminar flows. (Measured in bodylengths/s of course) library(ggplot2) # quick visualisation p <- ggplot(hz) + #geom_point(aes(x=speed, y=VO2minBac, colour=cond)) + geom_point(aes(x=PecHz, y=VO2minBac, colour=cond)) + theme_minimal() + facet_wrap(~Fish) print(p) # let's fit a GAM! library(mgcv) # this is fitting a model that says: # O2 varies as a function of pectoral hz, but we should estimate a different # curve for each condition. We also think that fish acts like a random effect b_pec <- gam(VO2minBac~s(PecHz, cond, bs="fs") + s(Fish, bs="re"), data=hz, method="REML") # check this model gam.check(b_pec) # looks like there might be a minor issue with heteroskedasticity? probably not # worth worrying about (top right). Looks like the model predicts well (bottom # right). Residuals look normal enough (left side). Text output shows that we let # our model be wiggly enough summary(b_pec) # v. high % deviance explained, maybe the fish random effect is not super-relevant # but we can include anyway as we think there is between-fish variability # now to make predictions, make a grid of values with all the pectoral hz we need # plus values for the condition and fish preddat <- expand.grid(PecHz = seq(0.5, 3.5, by=0.1), cond = c("T", "L"), Fish = unique(hz$Fish)) # make predictions, also predict the standard error pr <- predict(b_pec, preddat, type="response", se=TRUE) preddat$VO2minBac <- pr$fit # generate the CIs preddat$upper <- pr$fit + 2*pr$se.fit preddat$lower <- pr$fit - 2*pr$se.fit # what does that look like? p <- ggplot(hz) + geom_line(aes(x=PecHz, y=VO2minBac, colour=cond, group=cond), data=preddat) + geom_line(aes(x=PecHz, y=upper, colour=cond, group=cond), linetype=2, data=preddat) + geom_line(aes(x=PecHz, y=lower, colour=cond, group=cond), linetype=2, data=preddat) + geom_text(aes(x=PecHz, y=VO2minBac, colour=cond, label=speedcode)) + scale_colour_brewer(type="qual") + theme_minimal() + labs(x="Pectoral Hz", colour="Condition") + facet_wrap(~Fish, nrow=2) print(p) # ignore fish and predict excluding the fish random effect preddat <- expand.grid(PecHz = seq(0.5, 3.5, by=0.1), cond = c("T", "L"), Fish="F5") pr <- predict(b_pec, preddat, type="response", se=TRUE, exclude="s(Fish)") preddat$VO2minBac <- pr$fit preddat$upper <- pr$fit + 2*pr$se.fit preddat$lower <- pr$fit - 2*pr$se.fit # what does that look like? p <- ggplot(hz) + geom_line(aes(x=PecHz, y=VO2minBac, colour=cond, group=cond), data=preddat) + geom_line(aes(x=PecHz, y=upper, colour=cond, group=cond), linetype=2, data=preddat) + geom_line(aes(x=PecHz, y=lower, colour=cond, group=cond), linetype=2, data=preddat) + geom_text(aes(x=PecHz, y=VO2minBac, colour=cond, label=speedcode)) + scale_colour_brewer(type="qual") + theme_minimal() + labs(x="Pectoral Hz", colour="Condition") print(p) # what about caudal fin? # quick visualisation p <- ggplot(hz) + geom_point(aes(x=CaudHz, y=VO2minBac, colour=cond)) + theme_minimal() + facet_wrap(~Fish) print(p) # try the same kind of model as above for the caudal? # need to reduce k (smooth complexity) as we don't have many unique values b_caud <- gam(VO2minBac~s(CaudHz, cond, bs="fs", k=5) + s(Fish, bs="re"), data=hz, method="REML") # model check summary(b_caud) # less deviance explained than before and less wiggly effects? plot(b_caud) # do we believe that O2 is n-shaped in caudal hz? preddat <- expand.grid(CaudHz = seq(0, 5, by=0.1), cond = c("T", "L"), Fish = unique(hz$Fish)) preddat$VO2minBac <- predict(b_caud, preddat, type="response") p <- ggplot(hz) + geom_line(aes(x=CaudHz, y=VO2minBac, colour=cond, group=cond), data=preddat) + geom_text(aes(x=CaudHz, y=VO2minBac, colour=cond, label=speedcode)) + scale_colour_brewer(type="qual") + theme_minimal() + labs(x="Caudal Hz", colour="Condition")# + # facet_wrap(~Fish, nrow=2) print(p) per <- read.csv("FHL_periodicity.csv") per$condition <- as.factor(per$condition) # try the same kind of model as above for the caudal? # need to reduce k (smooth complexity) as we don't have many unique values b_pery <- gam(yfreq~s(speed, condition, bs="fs", k=5) + s(fish, bs="re"), data=per, method="REML") # model check summary(b_caud) # less deviance explained than before and less wiggly effects? plot(b_caud) # do we believe that O2 is n-shaped in caudal hz? preddat <- expand.grid(CaudHz = seq(0, 5, by=0.1), cond = c("T", "L"), Fish = unique(hz$Fish)) preddat$VO2minBac <- predict(b_caud, preddat, type="response") p <- ggplot(hz) + geom_line(aes(x=CaudHz, y=VO2minBac, colour=cond, group=cond), data=preddat) + geom_text(aes(x=CaudHz, y=VO2minBac, colour=cond, label=speedcode)) + scale_colour_brewer(type="qual") + theme_minimal() + labs(x="Pectoral Hz", colour="Condition") + facet_wrap(~Fish, nrow=2) print(p) per <- read.csv("FHL_periodicity.csv") # add condition code per$Flow <- "L" per$Flow[per$condition == 1] <- "L" per$Flow[per$condition == 0] <- "T" per$Flow <- as.factor(per$Flow) p <- ggplot(per) + geom_point(aes(x=speed, y=zfreq,colour=condition), data=per) + scale_colour_manual(values=c("red", "blue")) + scale_shape_manual(values=c(17, 16))+ theme_minimal() + labs(y="z-frequency", x = "Speed BL/s", colour="Condition") print(p) modr <- nlme(zfreq~a+b*speed, fixed = a+b~Flow, random = a~1|fish, start=c(0, 0.5), data=per) # FANCY MODELS # #b_use <- gam(VO2minBac~s(PecHz, CaudHz, cond, # bs="fs", k=10, xt="tp") + # s(Fish, bs="re"), # data=hz, method="REML") # # # #par(mfrow=c(1,2)) #hist(hz$PecHz) #hist(hz$CaudHz) # # # #preddat <- expand.grid(PecHz = seq(0, 3.5, len=100), # CaudHz = seq(0, 5, len=100), # cond = c("T", "L"), # Fish = unique(hz$Fish)) # #preddat$VO2minBac <- predict(b_use, preddat, type="response", exclude="s(Fish)") # # ## YIKES plotting # #pred_yikes <- preddat # # #library(viridis) # #p <- ggplot(pred_yikes) + # geom_tile(aes(x=PecHz, y=CaudHz, fill=VO2minBac)) + # geom_point(aes(x=PecHz, y=CaudHz), data=hz) + # theme_minimal() + # scale_fill_viridis() + # coord_equal() + # facet_wrap(~cond) # #print(p) # # #
7a6df44812890c492ab702c67fa9c78695e5e0eb
2704ea941fbbd3f3e0a9ac7cf03b03111429b46c
/man/WRRnnls.Rd
6a7732d93db041ce972266dc2c2740f12a032d07
[ "Apache-2.0" ]
permissive
olangsrud/experimentalRpackage
6b43daf72e56069161ec36605c548f4a628f72f9
a897f1f608af62c8fafb2a51d8f06a0764902a85
refs/heads/master
2021-09-24T23:05:52.640787
2021-09-16T13:54:19
2021-09-16T13:54:19
215,278,537
0
0
null
null
null
null
UTF-8
R
false
true
2,503
rd
WRRnnls.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/WeightedRidgeRegression.R \name{WRRnnls} \alias{WRRnnls} \alias{WRRginv} \alias{WRRglmnet} \title{Special weighted and ridge penalized regression} \usage{ WRRnnls(x, y, xExact = NULL, yExact = NULL, wExact = 1000, lambda = 1e-04^2) WRRginv(x, y, xExact = NULL, yExact = NULL, wExact = 1000, lambda = 1e-04^2) WRRglmnet( x, y, xExact = NULL, yExact = NULL, wExact = 1000, lambda = exp(((2 * 12):(-17 * 2))/2), intercept = FALSE, standardize = FALSE, thresh = 1e-10, lower.limits = 0, ... ) } \arguments{ \item{x}{Input matrix, each row is an ordinary observation} \item{y}{Ordinary response observation (vector or matrix)} \item{xExact}{Input matrix, each row is a highly weighted observation} \item{yExact}{Highly weighted response observation (vector or matrix)} \item{wExact}{Weight for highly weighted observations} \item{lambda}{Ridge regression penalty parameter (sequence when glmnet)} \item{intercept}{glmnet parameter} \item{standardize}{glmnet parameter} \item{thresh}{glmnet parameter} \item{lower.limits}{glmnet parameter} \item{...}{Further glmnet parameters} } \value{ Output from \code{\link{nnls}}, \code{\link{glmnet}} or coefficient estimate calculated using \code{\link{ginv}} } \description{ By using \code{\link{nnls}}, \code{\link{ginv}} or \code{\link{glmnet}} } \examples{ x <- cbind(1:11, -11:-1, c(1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2)) y <- matrix(5 - sin(2 * (1:11)), dimnames = list(NULL, "y")) x1 <- x[1:9, ] x2 <- x[10:11, ] y1 <- y[1:9, , drop = FALSE] y2 <- y[10:11, , drop = FALSE] # Generalized inverse estimation ginvCoef <- WRRginv(x1, y1, x2, y2) # Non-negative estimation by nnls # Coefficients in output element x nnlsCoef <- WRRnnls(x1, y1, x2, y2)$x # Non-negative estimation by glmnet # Take out best fit from matrix of coefficients gn <- WRRglmnet(x1, y1, x2, y2) glmnetCoef <- coef(gn)[-1, which.max(gn$dev.ratio), drop = FALSE] # Another estimation by glmnet (not non-negative) # Take out best fit from matrix of coefficients gnInf <- WRRglmnet(x1, y1, x2, y2, lower.limits = -Inf) glmnetCoefInf <- coef(gnInf)[-1, which.max(gn$dev.ratio), drop = FALSE] # All coefficients coef4 <- as.matrix(cbind(ginvCoef, nnlsCoef, glmnetCoef, glmnetCoefInf)) colnames(coef4) <- c("ginv", "nnls", "glmnet", "glmnetInf") print(coef4) # Original y and fitted values. Close fit for last two observation. cbind(y, x \%*\% coef4) } \author{ Øyvind Langsrud }
62fb70eec3304d108affe82f1b87bd16941285a4
94e33777e055bf71f867bd158d25f76d75e01bcc
/R/read_SegmentDirectory.R
e23be11eb673f46a524dd8dbc1c1fc001d812a48
[]
no_license
norgardp/psd4
305bd8094815dca6cf55f276e5b6d37f29ecb82c
5b8a291c6b4e072d463876b4e88d771256e98783
refs/heads/master
2022-09-24T15:13:36.762092
2020-06-03T20:25:59
2020-06-03T20:25:59
269,189,048
0
0
null
null
null
null
UTF-8
R
false
false
703
r
read_SegmentDirectory.R
read_SegmentDirectory = function(dname, dets=NA, type) { initial_directory = getwd(); setwd(dname); # Determine if some or all detectors are to be included in the return list detectors = dir(pattern = "det[0-9]{2}.raw"); if( (length(dets) > 1) & !any(is.na(dets)) ) { desired_detectors = sapply(1:length(dets), function(i) sprintf("det%02d.raw", dets[i])); detectors = detectors[sapply(1:length(desired_detectors), function(i) grep(detectors, pattern=desired_detectors[i]))]; } retval = list(); retval[['segment']] = dname; retval = do.call(c, list(retval, lapply(1:length(detectors), function(i) read_DetectorData(detectors[i], type) ))); setwd(initial_directory); return(retval); }
a6801b1c5bd2f6afb10f8c1affb9f35582eb44ed
74fa8fe5f0d5568fcde60e569463469a8d172190
/man/get_mentioned_gkg_gcams.Rd
5904086f05252f99f459b4f89ef9b2a423ac9e59
[]
no_license
raj0926/gdeltr2
d3d792affdef8230a4cf4a86cbc15aecad07b670
398a97a64bebac6a1662da2fcb5d5b65f33c2f2b
refs/heads/master
2020-12-25T11:21:05.914927
2016-06-05T18:30:59
2016-06-05T18:30:59
60,638,860
2
0
null
2016-06-07T19:02:54
2016-06-07T19:02:52
R
UTF-8
R
false
true
403
rd
get_mentioned_gkg_gcams.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/gdelt_event_gkg.R \name{get_mentioned_gkg_gcams} \alias{get_mentioned_gkg_gcams} \title{Returns GCAM codes from a gkg data frame} \usage{ get_mentioned_gkg_gcams(gdelt_data, merge_gcam_codes = F, filter_na = T, return_wide = F) } \arguments{ \item{return_wide}{} } \description{ Returns GCAM codes from a gkg data frame }
64370aeb15a3cf2c0f9bb62c71d1d16df2bc1210
96de9c558793e8a9d88406d4848112d28b9f3a8b
/server.R
7b914930651d81002e5883b05fdf6a68af9258c8
[]
no_license
xujz4f/Shiny-Application-and-Reproducible-Pitch
7226f126636b25bbe2269fe98a3108051311f824
493d4ee739ce0ea0886087037a2b891a6fd66664
refs/heads/master
2021-01-21T06:39:34.742869
2017-02-27T04:30:07
2017-02-27T04:30:07
83,268,320
0
0
null
null
null
null
UTF-8
R
false
false
221
r
server.R
library(datasets) function(input, output) { output$phonePlot <- renderPlot({ barplot(WorldPhones[input$year,], main=input$year, ylab="Number of Telephones", xlab="region") }) }
513f54438ae412c24c3a455eeee4d036f96a04db
df84e16f31db27af9cb69d95cd802ef7e4b4a065
/R/get_functions.R
76c61bc8de05eddd1b54e34d658578a3fc8f3f1e
[]
no_license
banskt/ebmr.alpha
375d1cace6dce2c59e5ddf0095c3eec36d30d80b
53c025f09e46f72e20f7240839408c79fbcfc807
refs/heads/main
2023-03-22T00:52:12.301317
2021-03-15T18:25:00
2021-03-15T18:25:00
null
0
0
null
null
null
null
UTF-8
R
false
false
110
r
get_functions.R
ebmr_get_elbodiff = function(fit){ niter = length(fit$elbo) return(fit$elbo[niter] - fit$elbo[niter-1]) }
96653fe856ed2cb6cc62744fb482e10721c3d87d
1c0975d66acdc096f06f7827618f69a6792a3e77
/man/match_font.Rd
7e741ab85d1be697e0262dc635f72bd0de9a7647
[ "MIT" ]
permissive
r-lib/systemfonts
2ad74f06f42e54e0bc48d5dd88c8e9cbc3442818
4ccb03c9e5d6f64b63fcd5e133830f906dab405f
refs/heads/main
2023-05-10T23:41:40.440662
2023-05-08T14:04:11
2023-05-08T14:04:11
190,163,549
58
16
NOASSERTION
2023-04-20T01:16:32
2019-06-04T08:45:46
C++
UTF-8
R
false
true
1,021
rd
match_font.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/match_font.R \name{match_font} \alias{match_font} \title{Find a system font by name and style} \usage{ match_font(family, italic = FALSE, bold = FALSE) } \arguments{ \item{family}{The name of the font family} \item{italic, bold}{logicals indicating the font style} } \value{ A list containing the path locating the font file and the 0-based index of the font in the file. } \description{ This function locates the font file (and index) best matching a name and optional style (italic/bold). A font file will be returned even if a match isn't found, but it is not necessarily similar to the requested family and it should not be relied on for font substitution. The aliases \code{"sans"}, \code{"serif"}, and \code{"mono"} match to the system default sans-serif, serif, and mono fonts respectively (\code{""} is equivalent to \code{"sans"}). } \examples{ # Get the system default sans-serif font in italic match_font('sans', italic = TRUE) }
673bd9d16c4b7be0b033c2b14cde51361da57869
d5e85cab536f569fb662d942ebe1d51315234ab5
/man/HiddenF.Rd
a99c6e640a0608783966de33897bef9f277beef7
[]
no_license
cran/hiddenf
60017a965a7200d172da4ded5b42197327c33f34
2e26480358c38caa1da8fc08da4c0c320d8ca6a7
refs/heads/master
2020-12-24T15:49:52.621097
2016-01-05T22:29:08
2016-01-05T22:29:08
20,746,855
0
0
null
null
null
null
UTF-8
R
false
false
1,452
rd
HiddenF.Rd
\name{HiddenF} \alias{HiddenF} \title{Hidden F function for matrix data } \description{ Fits linear model to ymtx, a matrix of responses of dimension r-by-c. Constructs all possible configurations of rows into two non-empty groups, then, for each configuration, fits full factorial effects models with three factors for group, group-by-column, row and row nested within column. The maximum F-ratio for group-by-column interaction is reported along with Bonferroni-adjusted p-value. } \usage{ HiddenF(ymtx) } \arguments{ \item{ymtx}{ A matrix of responses, with rows corresponding to levels of one factor, and columns the levels of a second factor } } \value{List-object of class `HiddenF' with components \item{adjpvalue}{(Bonferroni-adjusted) pvalue from configuration with maximal hidden additivity} \item{config.vector}{Vector of group indicators for configuration with maximal hidden additivity} \item{tall}{A list with components y, row, col} \item{cc}{Number of possible configurations} } \references{ Franck CT, Nielsen, DM and Osborne, JA. (2013) A Method for Detecting Hidden Additivity in two-factor Unreplicated Experiments, Computational Statistics and Data Analysis, 67:95-104.} \author{ Jason A. Osborne \email{jaosborn@ncsu.edu}, Christopher T. Franck and Bongseog Choi } \seealso{\code{\link{summary.HiddenF}}} \examples{ library(hiddenf) data(cjejuni.mtx) cjejuni.out <- HiddenF(cjejuni.mtx) summary(cjejuni.out) } \keyword{anova}
cd6f91e2d1d0f786da3fd70139221dea46f37362
46c1cdb91955b383ea6176d108f2d67fd0cd5a8d
/ISCAM2/R/iscamaddlnorm.R
58fe85faf9a55f4c56a68179bbe8ad15b9d87c91
[]
no_license
shannonpileggi/SP--Pablo--RProgramming
0f1a6621847d013e0c445059894e5bad5a940086
ad60dc509b077dd9657f7e97f587809251e19c18
refs/heads/master
2018-10-22T19:21:27.375766
2018-07-21T07:01:43
2018-07-21T07:01:43
114,397,446
0
0
null
null
null
null
UTF-8
R
false
false
452
r
iscamaddlnorm.R
#' iscamaddlnorm Function #' #' This function creates a histogram of the inputted variable and overlays a log normal density function. #' @param x a vector of numeric values. #' @keywords lognormal #' @export #' @examples #' iscamaddlnorm(x) iscamaddlnorm <- function(x){ hist(x, freq=FALSE, xlab = deparse(substitute(x)), ylim=c(0,1)) min = 0 max = max(x) myseq = seq(min, max, .001) lines(myseq, dlnorm(myseq, mean(log(x)), sd(log(x)))) }
a7be725e7d5b3e7e4dcea16a1da5a883ffba26cc
8951569f9b40c540e8606867db71c40a27539422
/2019_R_Files/Partials_Header_Treatment.R
2f62aa7627fdf5869151752418339c58a071300f
[ "CC-BY-4.0", "MIT" ]
permissive
HannesOberreiter/coloss_honey_bee_colony_losses_austria
3be5c198d8e253d3e6c810025b71bf63b7b933e4
f1bdb47e2c5e647788a080925a82c21e51e0199e
refs/heads/master
2021-06-15T13:09:58.171620
2021-04-02T12:33:22
2021-04-02T12:33:22
181,077,729
0
0
null
null
null
null
UTF-8
R
false
false
7,899
r
Partials_Header_Treatment.R
############################## ### Survey Bee Hive Losses ### # (c) 2019 Hannes Oberreiter # ############################## ############################## # List of Factors we want in our Plot treatmentList = list( c("T_drone_", "T_drone_total", "Drone brood removal"), c("T_hyperthermia_", "T_hyperthermia_total", "Hyperthermia"), c("T_biotechnical_", "T_biotechnical_total", "Other biotechnical method"), c("T_formic_short_", "T_formic_short_total", "Formic acid - short term"), c("T_formic_long_", "T_formic_long_total", "Formic acid - long term"), c("T_lactic_", "T_lactic_total", "Lactic acid"), #c("T_oxalic_trickle_pure_", "T_oxalic_trickle_pure_total", "Oxalic acid - trickling pure"), c("T_oxalic_vapo_", "T_oxalic_vapo_total", "Oxalic acid - sublimation"), #c("T_oxalic_trickle_mix_", "T_oxalic_trickle_mix_total", "Oxalic acid mixture"), c("T_oxalic_trickle_", "T_oxalic_trickle_total", "Oxalic acid - trickling"), c("T_thymol_", "T_thymol_total", "Thymol"), #c("T_synthetic_apistan_", "T_apistan_total", "Tau-fluvalinat"), #c("T_synthetic_flumethrin_", "T_flumethrin_total", "Flumethrin"), #c("T_synthetic_amitraz_strips_", "T_amitraz_strips_total", "Amitraz - Strips"), #c("T_synthetic_amitraz_vapo_", "T_amitraz_vapo_total", "Amitraz - Vaporize"), #c("T_synthetic_coumaphos_p_", "T_coumaphos_p_total", "Coumaphos - Perizin"), #c("T_synthetic_coumaphos_c_", "T_coumaphos_c_total", "Coumaphos - Checkmite+"), #c("T_synthetic_synother_", "T_chemical_total", "Other Synthetic"), c("T_synthetic_", "T_synthetic_total", "Synthetic methods"), c("T_other_", "T_other_total", "Another method") ) # Second List were Mix is not combined with trickle treatmentListwMix = list( c("T_drone_", "T_drone_total", "Drone brood removal"), c("T_hyperthermia_", "T_hyperthermia_total", "Hyperthermia"), c("T_biotechnical_", "T_biotechnical_total", "Other biotechnical method"), c("T_formic_short_", "T_formic_short_total", "Formic acid - short term"), c("T_formic_long_", "T_formic_long_total", "Formic acid - long term"), c("T_lactic_", "T_lactic_total", "Lactic acid"), #c("T_oxalic_trickle_pure_", "T_oxalic_trickle_pure_total", "Oxalic acid - trickling pure"), c("T_oxalic_vapo_", "T_oxalic_vapo_total", "Oxalic acid - sublimation"), c("T_oxalic_trickle_mix_", "T_oxalic_trickle_mix_total", "Oxalic acid mixture"), c("T_oxalic_trickle_", "T_oxalic_trickle_total", "Oxalic acid - trickling"), c("T_thymol_", "T_thymol_total", "Thymol"), #c("T_synthetic_apistan_", "T_apistan_total", "Tau-fluvalinat"), #c("T_synthetic_flumethrin_", "T_flumethrin_total", "Flumethrin"), #c("T_synthetic_amitraz_strips_", "T_amitraz_strips_total", "Amitraz - Strips"), #c("T_synthetic_amitraz_vapo_", "T_amitraz_vapo_total", "Amitraz - Vaporize"), #c("T_synthetic_coumaphos_p_", "T_coumaphos_p_total", "Coumaphos - Perizin"), #c("T_synthetic_coumaphos_c_", "T_coumaphos_c_total", "Coumaphos - Checkmite+"), #c("T_synthetic_synother_", "T_chemical_total", "Other Synthetic"), c("T_synthetic_", "T_synthetic_total", "Synthetic methods"), c("T_other_", "T_other_total", "Another method") ) fulltreatmentList = list( c("T_drone_", "T_drone_total", "Drone brood removal"), c("T_hyperthermia_", "T_hyperthermia_total", "Hyperthermia"), c("T_biotechnical_", "T_biotechnical_total", "Other biotechnical method"), c("T_formic_short_", "T_formic_short_total", "Formic acid - short term"), c("T_formic_long_", "T_formic_long_total", "Formic acid - long term"), c("T_lactic_", "T_lactic_total", "Lactic acid"), c("T_oxalic_trickle_pure_", "T_oxalic_trickle_pure_total", "Oxalic acid - trickling"), c("T_oxalic_vapo_", "T_oxalic_vapo_total", "Oxalic acid - sublimation"), c("T_oxalic_trickle_mix_", "T_oxalic_trickle_mix_total", "Oxalic acid mixture"), #c("T_oxalic_trickle_all_", "T_oxalic_trickle_all_total", "Oxalic acid - trickling all methods"), c("T_thymol_", "T_thymol_total", "Thymol"), c("T_synthetic_apistan_", "T_apistan_total", "Tau-fluvalinat"), c("T_synthetic_flumethrin_", "T_flumethrin_total", "Flumethrin"), c("T_synthetic_amitraz_strips_", "T_amitraz_strips_total", "Amitraz - Strips"), c("T_synthetic_amitraz_vapo_", "T_amitraz_vapo_total", "Amitraz - Vaporize"), c("T_synthetic_coumaphos_p_", "T_coumaphos_p_total", "Coumaphos - Perizin"), c("T_synthetic_coumaphos_c_", "T_coumaphos_c_total", "Coumaphos - Checkmite+"), c("T_synthetic_synother_", "T_chemical_total", "Other Synthetic"), #c("T_synthetic_", "T_synthetic_total", "Synthetic methods"), c("T_other_", "T_other_total", "Another method") ) #### SPRING Treatment Values #### # Dummy List D.CACHE <- list() # Loop through our Treatment Types for(i in treatmentList){ # Get Columns which are starting with List value treatmentexp <- paste("(", i[1], ")\\S*0[1-2]", sep = "") x <- grepl(treatmentexp, colnames(D.FULL), fixed = FALSE, perl = TRUE) # sum the row values (means 1 = for 1 month, 2 = 2 months etc.) D.CACHE[[paste(i[2], "_spring", sep = "")]] <- rowSums(D.FULL[, x], na.rm = TRUE) # create a yes no list too xn <- paste( i[2], "yn_spring", sep = "") D.CACHE[[xn]] <- ifelse((rowSums(D.FULL[, x], na.rm = TRUE)) > 0, 1, 0) } # Convert List to Dataframe D.CACHE <- data.frame(D.CACHE) D.FULL <- cbind(D.FULL, D.CACHE) #### SUMMER Treatment Values #### # Dummy List D.CACHE <- list() # Loop through our Treatment Types for(i in treatmentList){ # Get Columns which are starting with List value treatmentexp <- paste("(", i[1], ")\\S*0[3-7]", sep = "") x <- grepl(treatmentexp, colnames(D.FULL), fixed = FALSE, perl = TRUE) # sum the row values (means 1 = for 1 month, 2 = 2 months etc.) D.CACHE[[paste(i[2], "_summer", sep = "")]] <- rowSums(D.FULL[, x], na.rm = TRUE) # create a yes no list too xn <- paste( i[2], "yn_summer", sep = "") D.CACHE[[xn]] <- ifelse((rowSums(D.FULL[, x], na.rm = TRUE)) > 0, 1, 0) } # Convert List to Dataframe D.CACHE <- data.frame(D.CACHE) D.FULL <- cbind(D.FULL, D.CACHE) #### WINTER Treatment Values #### # Dummy List D.CACHE <- list() # Loop through our Treatment Types for(i in treatmentList){ # Get Columns which are starting with List value treatmentexp <- paste("(", i[1], ")\\S*0[8-9]|(", i[1], ")\\S*1[0]", sep = "") x <- grepl(treatmentexp, colnames(D.FULL), fixed = FALSE, perl = TRUE) # sum the row values (means 1 = for 1 month, 2 = 2 months etc.) D.CACHE[[paste(i[2], "_winter", sep = "")]] <- rowSums(D.FULL[, x], na.rm = TRUE) # create a yes no list too xn <- paste( i[2], "yn_winter", sep = "") D.CACHE[[xn]] <- ifelse((rowSums(D.FULL[, x], na.rm = TRUE)) > 0, 1, 0) } # Convert List to Dataframe D.CACHE <- data.frame(D.CACHE) D.FULL <- cbind(D.FULL, D.CACHE) #### TOTAL Treatment Values #### # Dummy List D.CACHE <- list() # Loop through our Treatment Types for(i in treatmentList){ # Get Columns which are starting with List value # double blackslash otherwise R wont escape the backslash treatmentexp <- paste("(", i[1], ")\\S*0[1-9]|(", i[1], ")\\S*1[0]", sep = "") x <- grepl(treatmentexp, colnames(D.FULL), fixed = FALSE) # sum the row values (means 1 = for 1 month, 2 = 2 months etc.) D.CACHE[[i[2]]] <- rowSums(D.FULL[, x], na.rm = TRUE) # create a yes (1) no (2) list too xn <- paste( i[2], "_yn", sep = "") D.CACHE[[xn]] <- ifelse((rowSums(D.FULL[, x], na.rm = TRUE)) > 0, 1, 0) } # sum rows for total different methods and seasons # sum rows by yn column, that way we get amount of different treatments used x <- grep("(yn_)", colnames(D.FULL), fixed = FALSE) D.FULL$T_amount_total <- rowSums(D.FULL[, x], na.rm = TRUE) # Convert List to Dataframe D.CACHE <- data.frame(D.CACHE) # sum rows by yn column, that way we get amount of different treatments used x <- grep("_yn", colnames(D.CACHE), fixed = TRUE) D.CACHE$T_amount <- rowSums(D.CACHE[, x], na.rm = TRUE) D.FULL <- cbind(D.FULL, D.CACHE)
57d0084c7e0f061119df7ec1ad13be305b0d0d51
c365e70f7489e674a1785db128f7aab931322333
/fig/plot2.R
4348ab15dba2bac293886e9d3f9d54877e90ab6a
[]
no_license
varghesearunct/ExData_Plotting1
042c47eaf407f3b782c225647e5a1d93ccbdc63c
ae975c13f3ffef3f1cedd7cd6a86b7434adf5ca5
refs/heads/master
2020-12-24T12:34:35.352239
2016-11-06T08:15:38
2016-11-06T08:15:38
72,976,288
0
0
null
2016-11-06T07:30:05
2016-11-06T07:30:04
null
UTF-8
R
false
false
786
r
plot2.R
#opening file "household_power_consumption.txt" f<-file("household_power_consumption.txt") #reading only the lines starting with 1/2/2007 or 2/2/2007 val<-read.csv(text = grep("^[1,2]/2/2007", readLines(f), value = T), sep = ";",stringsAsFactors=F,header=F) #naming the column variables names(val)<-c("Date", "Time", "Global_active_power", "Global_reactive_power", "Voltage", "Global_intensity", "Sub_metering_1", "Sub_metering_2", "Sub_metering_3") #converting the date and time class to POSIXct class val$tim<-paste(val$Date,val$Time,sep='_') val$tim<-as.POSIXct(strptime(val$tim,"%d/%m/%Y_%H:%M:%S")) #opening the file device png(file="plot2.png") #plotting the graph with(val,plot(Global_active_power~tim,ylab="Global Active Power (kilowatts)",type='l',xlab="")) dev.off()
297fc9abf1c3747e9a6fd2687aa08fb596d2754d
ecc6602d6be09b1e24160da680dc0068710660d7
/man/power.RatioF.Rd
43f6b6e3671c76d44fb5feff251f9de8a9a8736e
[]
no_license
ShuguangSun/PowerTOST
a60e97794d00301d048a7cba2b84454be3493b59
b94655713782cab9ba09ac9ecb2042731ce9d272
refs/heads/master
2020-08-03T07:46:11.927805
2019-09-25T08:41:58
2019-09-25T08:41:58
null
0
0
null
null
null
null
UTF-8
R
false
false
3,902
rd
power.RatioF.Rd
\encoding{utf-8} \name{power.RatioF} \alias{power.RatioF} \title{ Power for equivalence of the ratio of two means with normality on original scale } \description{ Calculates the power of the test of equivalence of the ratio of two means with normality on original scale.\cr This test is based on Fieller’s confidence (\sQuote{fiducial}) interval and Sasabuchi’s test (a TOST procedure as well). } \usage{ power.RatioF(alpha = 0.025, theta1 = 0.8, theta2, theta0 = 0.95, CV, CVb, n, design = "2x2", setseed=TRUE) } \arguments{ \item{alpha}{ Type I error probability, aka significance level.\cr Defaults here to 0.025 because this function is intended for studies with clinical endpoints. } \item{theta1}{ Lower bioequivalence limit. Typically 0.8 (default). } \item{theta2}{ Upper bioequivalence limit. Typically 1.25.\cr Is set to \code{1/theta1} if missing. } \item{theta0}{ \sQuote{True} or assumed T/R ratio. Typically set to 0.95 for planning. } \item{CV}{ Coefficient of variation as ratio. In case of \code{design="parallel"} this is the CV of the total variability, in case of \code{design="2x2"} the intra-subject CV (CVw in the reference). } \item{CVb}{ CV of the between-subject variability. Only necessary for \code{design="2x2"}. } \item{n}{ Number of subjects to be planned.\cr \code{n} is for both designs implemented the \bold{total} number of subjects.\cr } \item{design}{ A character string describing the study design.\cr \code{design="parallel"} or \code{design="2x2"} allowed for a two-parallel group design or a classical TR|RT crossover design. } \item{setseed}{ If set to \code{TRUE} the dependence of the power from the state of the random number generator is avoided. With \code{setseed = FALSE} you may see the dependence from the state of the random number generator. } } \details{ The power is calculated exact using the bivariate non-central \emph{t}-distribution via function \code{\link[mvtnorm]{pmvt}} of the package \code{mvtnorm}.\cr Due to the calculation method of the used package mvtnorm -- randomized Quasi-Monte-Carlo -- these probabilities are dependent from the state of the random number generator within the precision of the power. See argument \code{setseed}. } \value{ Value of power according to the input. } \references{ Hauschke D, Kieser M, Diletti E, Burke M. \emph{Sample size determination for proving equivalence based on the ratio of two means for normally distributed data.} Stat Med. 1999;18(1):93--105.\cr doi: \href{https://dx.doi.org/10.1002/(SICI)1097-0258(19990115)18\%3A1\%3C93\%3A\%3AAID-SIM992\%3E3.0.CO\%3B2-8}{10.1002/(SICI)1097-0258(19990115)18:1<93::AID-SIM992>3.0.CO;2-8}. Hauschke D, Steinijans V, Pigeot I. \emph{Bioequivalence Studies in Drug Development.} Chichester: Wiley; 2007. Chapter 10. European Agency for the Evaluation of Medicinal Products, CPMP. \emph{Points to Consider on Switching between Superiority and Non-Inferiority.} London, 27 July 2000. \href{https://www.ema.europa.eu/en/documents/scientific-guideline/points-consider-switching-between-superiority-non-inferiority_en.pdf}{CPMP/EWP/482/99} } \author{ D. Labes } \note{ This function is intended for studies with clinical endpoints where the 95\% confidence intervals are usually used for equivalence testing.\cr Therefore, alpha defaults here to 0.025 (see EMEA 2000).\cr\cr The formulas given in the references rely on the assumption of equal variances in the two treatment groups for the parallel group design or on assuming equal within-subject and between-subject variabilities for the 2×2 crossover design. } \seealso{ \code{\link{sampleN.RatioF}} } \examples{ # power for alpha=0.025, ratio0=0.95, theta1=0.8, theta2=1/theta1=1.25 # within-subject CV=0.2, between-subject CV=0.4 # 2x2 crossover study, n=24 # using all the defaults: power.RatioF(CV = 0.2, CVb = 0.4, n = 24) # gives [1] 0.7315357 }
698a3f125302960076debf9d66b0240d0284162e
639b8ca98fe73eb7732322ea2260031286f4aedc
/Dropbox_Conflicts/main (Ben Gibson's conflicted copy 2015-01-17).R
09cad27a44a49b6cc19ca87726cf9fa51da36d33
[]
no_license
cbengibson/QCArevision2
373d443b390597c10561b1ef1fdb700bc80db4bb
2b50bad8e79cc194af50490cf357bcbb6b54f785
refs/heads/master
2020-06-16T08:27:20.749639
2017-03-01T23:02:28
2017-03-01T23:02:28
75,122,791
0
0
null
null
null
null
UTF-8
R
false
false
323
r
main (Ben Gibson's conflicted copy 2015-01-17).R
laQCA<-function(mod, ncut="", sim=100){ source("sim.ltQCA.R") source("configuration.table.R") library("QCA") # #if (type=="crisp"){ s.data<-sim.ltQCA(mod, ncut=ncut, sim=sim) #} #if (type=="fuzzy"){ #s.data<-sim.fsQCA(qca.data, ncut=ncut, sim=sim)} results<-conf.table(s.data[[1]], ncut=s.data[[2]]) return(results) }
1029eec634aea3829d376cdd6870e17e33413ee3
26523018c9b3da0b3e2ff0f8d644920208ed7bc3
/man/interaction.fit.Rd
b04d7407e7bdf50ec74f56d2ef0c5c20d3831661
[ "MIT" ]
permissive
jlevy44/InteractionTransformer
5dfa7aa1bdbee8ffdb6c2f6b509fdfc30b92a887
e92473889cca25a292baa4a54e84490bf7699063
refs/heads/master
2023-02-17T06:01:43.658463
2021-01-18T15:12:56
2021-01-18T15:12:56
208,927,856
7
1
null
null
null
null
UTF-8
R
false
true
1,276
rd
interaction.fit.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/interaction_transformer.R \name{interaction.fit} \alias{interaction.fit} \title{Generate design matrix acquired from using SHAP on tree model.} \usage{ interaction.fit( X.train, y.train, untrained_model = "default", max_train_test_samples = 100, mode_interaction_extract = "knee", include_self_interactions = F, cv_splits = 5L ) } \arguments{ \item{X.train}{Predictors in the form of a dataframe.} \item{y.train}{One column dataframe containing outcomes.} \item{untrained_model}{Scikit-learn tree-based estimator that has not been fit to the data.} \item{max_train_test_samples}{Number of samples to train SHAP model off of.} \item{mode_interaction_extract}{: Options for choosing number of interactions are 'sqrt' for square root number features, 'knee' for experimental knee method based on interaction scores, and any integer number of interactions.} \item{include_self_interactions}{Whether to include self-interactions / quadratic terms.} \item{cv_splits}{Number of CV splits for finding top interactions.} } \value{ Interaction transformer object that can be applied to the design matrix. } \description{ Returns transformer object. Y must be a single column dataframe. }
e9abfa5a8e137a0ae210e8e115384ce2239ac2c5
a7cf32a5dcd89906f697cd10537ecbbe83794fd5
/exam-exx/GenAlgoForTSP/results/graphs/graphs42/time_plotter.r
8ab45b2e1635bd58372e8d95798ff198067f2330
[]
no_license
Cyofanni/MeMoCo-exercises
acc57bedad0dea4e920242afa574c973d6441e87
c41d0c4942b0231e15af8a49cac7303599646937
refs/heads/master
2021-09-09T15:24:55.379843
2018-03-17T12:48:55
2018-03-17T12:48:55
110,260,599
1
0
null
null
null
null
UTF-8
R
false
false
653
r
time_plotter.r
#run 'png(time.png)' from R shell generations <- c(100,200,300) time1 <- c(8.08,9.22,9.18) #no simulated annealing time2 <- c(5.01,5.18,5.56) #simulated annealing plot(generations, time1, main="Running time against number of generations for 800-500 indiv.", sub="", xlab="generations", ylab="time (in seconds)", xlim=c(100, 300), ylim=c(0, 10), lty=1) lines(generations,time1,col="red",lty=1) points(generations, time2, col="blue", pch="*") lines(generations, time2, col="blue",lty=2) legend(101, 3, legend=c("Without S.A.,800 indiv.", "With S.A.,500 indiv."), col=c("red", "blue"), lty=1:2, cex=0.8) #run 'dev.off()' from R shell
f7590eacdd9a8017729a13eaa5fe59aea5bb3b43
7aeaed0b07d51f91529c758ad4230df5faaf9fb6
/tests/testthat/test-doctest-onetime_mark_as_done.R
39911c1f315809a8264fe96ff40f621d2e75e149
[ "MIT" ]
permissive
hughjonesd/onetime
e7adaf5d0bfdcef36701f407e910989a0ddffb96
e463d43a4410c0aa9228d9d6191a9a5951d25b17
refs/heads/master
2023-06-08T08:17:28.297841
2023-05-29T11:24:52
2023-05-29T11:24:52
234,599,989
1
0
null
null
null
null
UTF-8
R
false
false
449
r
test-doctest-onetime_mark_as_done.R
# Generated by doctest: do not edit by hand # Please edit file in R/utils.R test_that("Doctest: onetime_mark_as_done", { # Created from @doctest for `onetime_mark_as_done` # Source file: R/utils.R # Source line: 60 oo <- options(onetime.dir = tempdir(check = TRUE)) id <- sample(10000L, 1) expect_true(onetime_mark_as_done(id = id)) expect_silent(onetime_message("Won't be shown", id = id)) onetime_reset(id = id) options(oo) })
a8ea96d03a7c2546c679d844ca080a2676d32599
5b7324f2e2b119bddf9e5519aae63bb42f881a09
/man/MCA.Rd
f7678b3e855c447f6b592b6f75031d30da18f9de
[]
no_license
guenardg/codep
58a3fcc743ebe89bdb6712f4789e5d65db631ed1
aa2ed70755a1c54645f444c531c8a82015f7e9d4
refs/heads/master
2023-04-06T06:08:19.620970
2023-04-01T16:43:41
2023-04-01T16:43:41
155,072,033
0
0
null
null
null
null
UTF-8
R
false
true
9,927
rd
MCA.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/MCA.R \name{MCA} \alias{MCA} \alias{test.cdp} \alias{permute.cdp} \alias{parPermute.cdp} \title{Multiple-descriptors, Multiscale Codependence Analysis} \usage{ MCA(Y, X, emobj) test.cdp(object, alpha = 0.05, max.step, response.tests = TRUE) permute.cdp(object, permute, alpha = 0.05, max.step, response.tests = TRUE) parPermute.cdp( object, permute, alpha = 0.05, max.step, response.tests = TRUE, nnode, seeds, verbose = TRUE, ... ) } \arguments{ \item{Y}{A numeric matrix or vector containing the response variable(s).} \item{X}{A numeric matrix or vector containing the explanatory variable(s).} \item{emobj}{A \link{eigenmap-class} object.} \item{object}{A \link{cdp-class} object.} \item{alpha}{The type I (alpha) error threshold used by the testing procedure.} \item{max.step}{The maximum number of steps to perform when testing for statistical significance.} \item{response.tests}{A boolean specifying whether to test individual response variables.} \item{permute}{The number of random permutations used for testing. When omitted, the number of permutations is calculated using function \code{\link{minpermute}}.} \item{nnode}{The number of parallel computation nodes.} \item{seeds}{Seeds for computation nodes' random number generators when using parallel computation during the permutation test.} \item{verbose}{Whether to return user notifications.} \item{...}{Parameters to be passed to function \code{parallel::makeCluster}} } \value{ A \link{cdp-class} object. } \description{ Class, Functions, and methods to perform Multiscale Codependence Analysis (MCA) } \details{ Multiscale Codependence Analysis (MCA) allows to calculate correlation-like (i.e.codependence) coefficients between two variables with respect to structuring variables (Moran's eigenvector maps). The purpose of this function is limited to parameter fitting. Test procedures are handled through \code{test.cdp} (parametric testing) or \code{permute.cdp} (permutation testing). Moreover, methods are provided for printing (\code{print.cdp}), displaying a summary of the tests (\code{summary.cdp}), plotting results (\code{plot.cdp}), calculating fitted (\code{fitted.cdp}) and residuals values (\code{redisuals.cdp}), and making predictions (\code{predict.cdp}). It is noteworthy that the test procedure used by \code{MCA} deviates from the standard R workflow since intermediate testing functions (\code{test.cdp} and \code{permute.cdp}) need first to be called before any testing be performed. Function \code{parPermute.cdp} allows the user to spread the number of permutation on many computation nodes. It relies on package parallel. Omitting argument \code{nnode} lets function \code{parallel::detectCores} specify the number of node. Similarly, omitting parameter \code{seeds} lets the function define the seeds as a set of values drawn from a uniform random distribution between with minimum value \code{-.Machine$integer.max} and maximum value \code{.Machine$integer.max}. } \section{Functions}{ \itemize{ \item \code{MCA()}: Main function to compute the multiscale codependence analysis \item \code{test.cdp()}: Parametric statistical testing for multiscale codependence analysis \item \code{permute.cdp()}: Permutation testing for multiscale codependence analysis. \item \code{parPermute.cdp()}: Permutation testing for multiscale codependence analysis using parallel processing. }} \examples{ ### Example 1: St. Marguerite River Salmon Transect data(salmon) ## Converting the data from data frames to to matrices: Abundance <- log1p(as.matrix(salmon[,"Abundance",drop = FALSE])) Environ <- as.matrix(salmon[,3L:5]) ## Creating a spatial eigenvector map: map1 <- eigenmap(x = salmon[,"Position"], weighting = wf.binary, boundaries = c(0,20)) ## Case of a single descriptor: mca1 <- MCA(Y = Abundance, X = Environ[,"Substrate",drop = FALSE], emobj = map1) mca1 mca1_partest <- test.cdp(mca1) mca1_partest summary(mca1_partest) par(mar = c(6,4,2,4)) plot(mca1_partest, las = 3, lwd=2) mca1_pertest <- permute.cdp(mca1) \dontrun{ ## or: mca1_pertest <- parPermute.cdp(mca1, permute = 999999) } mca1_pertest summary(mca1_pertest) plot(mca1_pertest, las = 3) mca1_pertest$UpYXcb$C # Array containing the codependence coefficients ## With all descriptors at once: mca2 <- MCA(Y = log1p(as.matrix(salmon[,"Abundance",drop = FALSE])), X = as.matrix(salmon[,3L:5]), emobj = map1) mca2 mca2_partest <- test.cdp(mca2) mca2_partest summary(mca2_partest) par(mar = c(6,4,2,4)) plot(mca2_partest, las = 3, lwd=2) mca2_pertest <- permute.cdp(mca2) \dontrun{ ## or: mca2_pertest <- parPermute.cdp(mca2, permute = 999999) } mca2_pertest summary(mca2_pertest) plot(mca2_pertest, las = 3, lwd=2) mca2_pertest$UpYXcb$C # Array containing the codependence coefficients mca2_pertest$UpYXcb$C[,1L,] # now turned into a matrix. ### Example 2: Doubs Fish Community Transect data(Doubs) ## Sites with no fish observed are excluded: excl <- which(rowSums(Doubs.fish) == 0) ## Creating a spatial eigenvector map: map2 <- eigenmap(x = Doubs.geo[-excl,"DFS"]) ## The eigenvalues are in map2$lambda, the MEM eigenvectors in matrix map2$U ## MCA with multivariate response data analyzed on the basis of the Hellinger ## distance: Y <- LGTransforms(Doubs.fish[-excl,],"Hellinger") mca3 <- MCA(Y = Y, X=Doubs.env[-excl,], emobj = map2) mca3_pertest <- permute.cdp(mca3) \dontrun{ ## or: mca3_pertest <- parPermute.cdp(mca3, permute = 999999) } mca3_pertest summary(mca3_pertest) par(mar = c(6,4,2,4)) plot(mca3_pertest, las = 2, lwd=2) ## Array containing all the codependence coefficients: mca3_pertest$UpYXcb$C ## Display the results along the transect spmeans <- colMeans(Y) pca1 <- svd(Y - rep(spmeans, each=nrow(Y))) par(mar = c(5,5,2,5) + 0.1) plot(y = pca1$u[,1L], x = Doubs.geo[-excl,"DFS"], pch = 21L, bg = "red", ylab = "PCA1 loadings", xlab = "Distance from river source (km)") ## A regular transect of sites from 0 to 450 (km) spaced by 1 km intervals ## (451 sites in total). It is used for plotting spatially-explicit ## predictions. x <- seq(0,450,1) newdists <- matrix(NA, length(x), nrow(Doubs.geo[-excl,])) for(i in 1L:nrow(newdists)) newdists[i,] <- abs(Doubs.geo[-excl,"DFS"] - x[i]) ## Calculating predictions for the regular transect under the same set of ## environmental conditions from which the codependence model was built. prd1 <- predict(mca3_pertest, newdata = list(target = eigenmap.score(map2, newdists))) ## Projection of the predicted species abundance on pca1: Uprd1 <- (prd1 - rep(spmeans, each = nrow(prd1))) \%*\% pca1$v \%*\% diag(pca1$d^-1) lines(y = Uprd1[,1L], x = x, col=2, lty = 1) ## Projection of the predicted species abundance on pca2: plot(y = pca1$u[,2L], x = Doubs.geo[-excl,"DFS"], pch = 21L, bg = "red", ylab = "PCA2 loadings", xlab = "Distance from river source (km)") lines(y = Uprd1[,2L], x = x, col = 2, lty = 1) ## Displaying only the observed and predicted abundance for Brown Trout. par(new = TRUE) plot(y = Y[,"TRU"], Doubs.geo[-excl,"DFS"], pch = 21L, bg = "green", ylab = "", xlab = "", new = FALSE, axes = FALSE) axis(4) lines(y = prd1[,"TRU"], x = x, col = 3) mtext(side = 4, "sqrt(Brown trout rel. abundance)", line = 2.5) ### Example 3: Borcard et al. Oribatid Mite ## Testing the (2-dimensional) spatial codependence between the Oribatid Mite ## community structure and environmental variables, while displaying the ## total effects of the significant variables on the community structure ## (i.e., its first principal component). data(mite) map3 <- eigenmap(x = mite.geo) Y <- LGTransforms(mite.species, "Hellinger") ## Organize the environmental variables mca4 <- MCA(Y = Y, X = mite.env, emobj = map3) mca4_partest <- test.cdp(mca4, response.tests = FALSE) summary(mca4_partest) plot(mca4_partest, las = 2, lwd = 2) plot(mca4_partest, col = rainbow(1200)[1L:1000], las = 3, lwd = 4, main = "Codependence diagram", col.signif = "white") ## Making a regular point grid for plotting the spatially-explicit ## predictions: rng <- list( x = seq(min(mite.geo[,"x"]) - 0.1, max(mite.geo[,"x"]) + 0.1, 0.05), y = seq(min(mite.geo[,"y"]) - 0.1, max(mite.geo[,"y"]) + 0.1, 0.05)) grid <- cbind(x = rep(rng[["x"]], length(rng[["y"]])), y = rep(rng[["y"]], each = length(rng[["x"]]))) newdists <- matrix(NA, nrow(grid), nrow(mite.geo)) for(i in 1L:nrow(grid)) { newdists[i,] <- ((mite.geo[,"x"] - grid[i,"x"])^2 + (mite.geo[,"y"] - grid[i,"y"])^2)^0.5 } spmeans <- colMeans(Y) pca2 <- svd(Y - rep(spmeans, each = nrow(Y))) prd2 <- predict(mca4_partest, newdata = list(target = eigenmap.score(map3, newdists))) Uprd2 <- (prd2 - rep(spmeans, each = nrow(prd2))) \%*\% pca2$v \%*\% diag(pca2$d^-1) ## Printing the response variable (first principal component of the mite ## community structure). prmat <- Uprd2[,1L] dim(prmat) <- c(length(rng$x), length(rng$y)) zlim <- c(min(min(prmat), min(pca2$u[,1L])), max(max(prmat), max(pca2$u[,1L]))) image(z = prmat, x = rng$x, y = rng$y, asp = 1, zlim = zlim, col = rainbow(1200L)[1L:1000], ylab = "y", xlab = "x") points( x=mite.geo[,"x"], y=mite.geo[,"y"], pch=21L, bg = rainbow(1200L)[round(1+(999*(pca2$u[,1L]-zlim[1L])/(zlim[2L]-zlim[1L])),0)]) } \references{ Guénard, G., Legendre, P., Boisclair, D., and Bilodeau, M. 2010. Multiscale codependence analysis: an integrated approach to analyse relationships across scales. Ecology 91: 2952-2964 Guénard, G. Legendre, P. 2018. Bringing multivariate support to multiscale codependence analysis: Assessing the drivers of community structure across spatial scales. Meth. Ecol. Evol. 9: 292-304 } \author{ \packageAuthor{codep} Maintainer: \packageMaintainer{codep} }
1678ab62695ff836149374ebbe816ce56e215a94
bb897377948a02b7ab68df22ab5aa2acbc73215a
/R/SummaryTableExcel.R
bbb4b1948e01df8679cc6257dc6f972d470f119a
[]
no_license
ShunHasegawa/WTC_Extractable
8ed0c9c1d27b883c9f76fe3b75cff80491ee7597
43922caa9acf819337a188838fbab2b9414998e6
refs/heads/master
2021-01-10T22:05:33.631756
2015-07-26T08:07:45
2015-07-26T08:07:45
20,788,814
0
0
null
null
null
null
UTF-8
R
false
false
1,136
r
SummaryTableExcel.R
# melt data frame extrMlt <- melt(extr, id = c("time", "date", "chamber", "location", "side", "id", "temp")) # chamber summary table & mean ChSmmryTbl <- dlply(extrMlt, .(variable), function(x) CreateTable(x, fac = "chamber")) ChMean <- ddply(extrMlt, .(time, date, temp, chamber, variable), summarise, value = mean(value, na.rm = TRUE)) # treat summary table $ mean TrtSmmryTbl <- dlply(ChMean, .(variable), function(x) CreateTable(x, fac = "temp")) ## create xcel workbook ## wb <- createWorkbook() # worksheet for rawdata sheet <- createSheet(wb,sheetName="raw_data") addDataFrame(extr, sheet, showNA=TRUE, row.names=FALSE, characterNA="NA") # worksheets for chamber summary shnames <- paste("Chamber_mean.",c("Nitrate", "Ammonium","Phosphate", sep="")) l_ply(1:3, function(x) crSheet(sheetname = shnames[x], dataset = ChSmmryTbl[[x]])) # worksheets for temp trt summary shnames <- paste("Temp_mean.", c("Nitrate", "Ammonium","Phosphate"), sep = "") l_ply(1:3, function(x) crSheet(sheetname = shnames[x], dataset = TrtSmmryTbl[[x]])) #save file saveWorkbook(wb,"Output/Table/WTC_Extractable.xlsx")
ef0e38c4e9402d66fda445a48f138fe81e9c275c
49645c4e57889635638399e88cb490a49b79607d
/R_scripts/EBSEQ_Multi.R
9de524679d702d956708abbe9c245816643b7360
[]
no_license
pbpayal/Bioinformatics-Documents
f9440c5efb735c5f9ac705f15832d4eb163248cc
3c79fc8c9afc87b962c7297edde8cbf5dffe12b0
refs/heads/master
2023-05-21T02:04:12.057441
2021-06-14T19:55:09
2021-06-14T19:55:09
170,368,307
0
0
null
null
null
null
UTF-8
R
false
false
2,678
r
EBSEQ_Multi.R
setwd("/Users/pbanerjee/Desktop/Bioinfo Unit_RNA seq/AB/") load("Forbrain.RData") save.image("Forbrain.RData") library(EBSeq) #write.csv(MultiPP_Forebrain_heatmap_datamat, "MultiPP_Forebrain_heatmap_datamat1.csv") ##incase to write the data out to a csv #Forebrain - EBSEQ Forbrain_data = read.table("all.genes.results.fb.txt", stringsAsFactors=F, row.names=1, header=T) Forbrain_datamat = data.matrix(Forbrain_data) str(Forbrain_datamat) MultiSize <- MedianNorm(Forbrain_datamat) Conditions=c("untreated","untreated","untreated","stress","stress","stress","stress_drug","stress_drug","stress_drug","drug","drug","drug") PosParti=GetPatterns(Conditions) EBOut_Forbrain <- EBMultiTest(Forbrain_datamat,NgVector = NULL,Conditions = Conditions, AllParti = PosParti, sizeFactors = MultiSize, maxround = 1) MultiFC_Forbrain <- GetMultiFC(EBOut_Forbrain, SmallNum = 0.01) dfMultiFC_Forebrain <- data.frame(MultiFC_Forbrain) MultiPP_Forbrain <- GetMultiPP(EBOut_Forbrain) dfMultiPP_Forebrain <- data.frame(MultiPP_Forbrain) #Fold change Heatmaps ##Stress_drug over Untreated Stress_drugoverUntreated <- dfMultiFC_Forebrain[,c(1,12)] Stress_drugoverUntreated <- Stress_drugoverUntreated[-c(1)] Stress_drugoverUntreated_heatmap_datamat <- data.matrix(Stress_drugoverUntreated) #All fold change Foldchange <- dfMultiFC_Forebrain[,c(7:12)] Foldchange_heatmap_datamat <- data.matrix(Foldchange) heatmap.2(Foldchange_heatmap_datamat, Rowv = FALSE, Colv = FALSE, hclustfun = hclust, scale = "column", trace = "none") #Forebrain - HEATMAP dfMultiPP_Forebrain_heatmap <- dfMultiPP_Forebrain[,c(0,2:15)] MultiPP_Forebrain_heatmap_datamat <- data.matrix(dfMultiPP_Forebrain_heatmap) na.omit(MultiPP_Forebrain_heatmap_datamat) #this is because while runing Heatmap, it gave errors. na.omit helps to find out if NA is there in data matrix MultiPP_Forebrain_heatmap_datamat_NArmovd <- MultiPP_Forebrain_heatmap_datamat[-c(21863),] heatmap(MultiPP_Forebrain_heatmap_datamat_NArmovd) #Hindbrain library(gplots) hbdata=read.table("all.genes.results.hb.txt", stringsAsFactors=F, row.names=1, header=T) hbdatamat = data.matrix(hbdata) str(hbdatamat) MultiSize=MedianNorm(hbdatamat) Conditions=c("C1","C1","C1","C2","C2","C2","C3","C3","C3","C4","C4","C4") PosParti=GetPatterns(Conditions) EBOut_HB <- EBMultiTest(hbdatamat,NgVector = NULL,Conditions = Conditions, AllParti = PosParti, sizeFactors = MultiSize, maxround = 5) HBMultiFC <- GetMultiFC(EBOut_HB, SmallNum = 0.01) dfHBMultiFC <- data.frame(HBMultiFC) HBMultiPP <- GetMultiPP(EBOut_HB) dfHBMultiPP <- data.frame(HBMultiPP) write.csv(dfFBMultiFC, "FBMultiFC.csv") save.image(file='myEnvironment.RData') load('myEnvironment.RData')
573b92c90095c84b969966e7ab84ea0cd6593e02
cd606a7cb762c786f92b7fe7ba974b49a899c732
/scripts/update-plots.R
9e73f90c7661c262e9ecd3e1ed07475959b95026
[ "CC0-1.0" ]
permissive
seabbs/CovidInterventionReview
31e8c92645f11c47c16f6977fc17cedcbd38a4f8
7397cc48559d10056c111e990648f50acd079cb2
refs/heads/master
2022-04-18T18:50:24.828751
2020-04-05T11:02:57
2020-04-05T11:02:57
245,412,109
3
0
CC0-1.0
2020-04-05T11:02:59
2020-03-06T12:18:45
R
UTF-8
R
false
false
2,178
r
update-plots.R
# Packages ---------------------------------------------------------------- ## Get required packages - managed using pacman if (!require(pacman)) install.packages("pacman"); library(pacman) p_load("dplyr") p_load("readr") p_load("lubridate") p_load("ggplot2") p_load("cowplot") # Functions --------------------------------------------------------------- source("functions/plot_interventions.R") # Load data --------------------------------------------------------------- cases <- readr::read_csv("output-data/counts.csv") interventions <- readr::read_csv("output-data/interventions.csv") first_cases <- readr::read_csv("output-data/first-cases.csv") cases <- cases %>% dplyr::mutate(country = country %>% factor(levels = first_cases$Country)) interventions <- interventions %>% dplyr::mutate(country = country %>% factor(levels = first_cases$Country)) # Make plots -------------------------------------------------------------- ## Social distancing interventions social_plot <- plot_interventions(cases, interventions, "yes", linetype = "Scale", scales = "free_y") ggsave("figures/social-plot.png", social_plot, width = 12, height = 12, dpi = 330) ## Social distancing interventions non_social_plot <- plot_interventions(cases, interventions, "no", linetype = "Scale", scales = "free_y") ggsave("figures/non-social-plot.png", non_social_plot, width = 12, height = 12, dpi = 330) # Make enforced plots ----------------------------------------------------- ## Social distancing interventions enforced_social_plot <- plot_interventions(cases, interventions, "yes", linetype = "Enforced", scales = "free_y") ggsave("figures/enforced-non-social-plot.png", enforced_social_plot, width = 12, height = 12, dpi = 330) ## Social distancing interventions enforced_non_social_plot <- plot_interventions(cases, interventions, "no", linetype = "Enforced", scales = "free_y") ggsave("figures/enforced-non-social-plot.png", enforced_non_social_plot, width = 12, height = 12, dpi = 330)
946aa3ef00982a247d2c765901eb8c35551fa9b7
0960dbdf02e232f2a8d6bd5f116a36876a57183a
/man/segmentPMDs.Rd
924a22c9abfadc8c799da8b84f76ac343d4e508d
[]
no_license
LukasBurger/MethylSeekR
fb9003cbeff6276be77f2e3fab4f0c3b045131f3
efb31e260fd2be0a2e1310c552e07d91a048c4a4
refs/heads/master
2023-06-06T09:22:17.932335
2021-06-21T06:13:09
2021-06-21T06:13:09
327,341,839
4
0
null
null
null
null
UTF-8
R
false
false
1,901
rd
segmentPMDs.Rd
\name{segmentPMDs} \alias{segmentPMDs} \title{ PMD segmenter } \description{ This function trains a Hidden Markov Model (HMM) to detect partially methylated domains (PMDs) in Bis-seq data. } \usage{ segmentPMDs(m, chr.sel, pdfFilename = NULL, seqLengths, num.cores = 1, nCGbin = 101) } \arguments{ \item{m}{ GRanges object containing the methylation data. } \item{chr.sel}{ Chromosome on which HMM should be trained. Must be one of the sequence levels of m. } \item{pdfFilename}{ Name of the pdf file in which the figure is saved. If no name is provided (default), the figure is printed to the screen. } \item{seqLengths}{ A named vector indicating the chromosome lengths of the genome used. } \item{num.cores}{ The number of cores used for the calculations (default 1). } \item{nCGbin}{ The number of CpGs in each sliding window used to calculate alpha (default 101). The default is highly recommended. } } \value{ A GRanges object containing segments that partition the genome into PMDs and regions outside of PMDs. The object contains two metadata columns indicating the type of region (PMD/notPMD) and the number of covered (by at least 5 reads) CpGs (nCG) in the region. The function also creates a figure showing the inferred emission distributions of the HMM that is either printed to the screen (default) or saved as a pdf if a filename is provided. } \author{ Lukas Burger lukas.burger@fmi.ch } \examples{ library(MethylSeekR) # get chromosome lengths library("BSgenome.Hsapiens.UCSC.hg18") sLengths=seqlengths(Hsapiens) # read methylation data methFname <- system.file("extdata", "Lister2009_imr90_hg18_chr22.tab", package="MethylSeekR") meth.gr <- readMethylome(FileName=methFname, seqLengths=sLengths) #segment PMDs PMDsegments.gr <- segmentPMDs(m=meth.gr, chr.sel="chr22", seqLengths=sLengths) }
0b74fe201bfeba8df4f6318c141f7b5a44392272
7a93571135c17e7ea4d3d3ed2e52b5ada1f8483f
/test-cassandra-part.r
6047f1424466630bdd34562827d7731a2b53349b
[]
no_license
kaneplusplus/cnidaria
cf5b7cd751f5dd67890884a764e03bd9847a0c98
d33f812641df51739ce31e6558ddcac4b6a9a137
refs/heads/master
2021-01-19T22:29:37.014301
2018-01-25T14:31:00
2018-01-25T14:31:00
16,467,882
8
0
null
2016-09-22T13:38:00
2014-02-03T01:54:14
R
UTF-8
R
false
false
215
r
test-cassandra-part.r
source("cassandra-part.r") # Initialize disk parting. init_cassandra_part() # Create a new part from a matrix. a <- as_part(matrix(1:10, ncol=2)) # Get rows 1, 3, 4. get_values(a, c(1, 3, 4)) get_attributes(a)
3fa94a7c7d5d326185640ee1fe1e479f34350025
2be9db22fd29bd6925944b19cbc880bbe465957b
/05-LogisticRegression/CaseStudy-02/Script.R
c48a1b4bc8a78de4c6cd7f1445f0862c702d4561
[]
no_license
wilberlinhares/Statistic_R
760df5dfd458cedd368b7330dd91fcce53533726
ddd6036fda9b9eb8e234585d2ea4d32d09ba9fd3
refs/heads/main
2023-07-08T23:10:53.944595
2021-08-11T13:27:39
2021-08-11T13:27:39
394,981,017
0
0
null
null
null
null
ISO-8859-1
R
false
false
16,103
r
Script.R
#********************************************************** # ESTUDO DE CASO - MODELO PREDITIVO DE CHURN #********************************************************** setwd("/Users/wilbe/OneDrive/Documentos/GoogleDrive/Estudos/FIA/Estatística Aplicada/Aula 17 e 18") getwd() # ********************************************************** # Leitura da base de telefonia telefonia <- read.table("Telefonia.txt", header = TRUE, sep = "\t", dec = ".") # ********************************************************** # Verificar estrutura e informações sobre a base de telefonia names(telefonia) nrow(telefonia) # ********************************************************** # (a) Faça a análise exploratória univariada dos dados, avalie a consistência das informações e missing values. # Medidas resumo das variável, menos a primeira coluna summary(telefonia[,-1]) # Tratamento da variável 'Idade' telefonia$Idade <- ifelse(is.na(telefonia$Idade), 999, telefonia$Idade) #Idades inconsistentes idade_17 <- ifelse(telefonia$Idade<18, 1, 0) sum(idade_17) idade_100 <- ifelse(telefonia$Idade>100, 1, 0) sum(idade_100) #Atribuindo idades incosistentes para missing telefonia$Idade <- ifelse(telefonia$Idade<18|telefonia$Idade>100, 999, telefonia$Idade) summary(telefonia$Idade) # Tratamento da variável 'Minutos realizados' telefonia$Minutos_realizados_T0 <- ifelse(is.na(telefonia$Minutos_realizados_T0), 0, telefonia$Minutos_realizados_T0) summary(telefonia$Minutos_realizados_T0) # Tabela de frequência para a variável 'resposta' (resposta_a <- table(telefonia$resposta)) (resposta_p <- prop.table(resposta_a) * 100) # 0,8% de cancelamento voluntário # Qtde de rentenção # Apesar de ser uma variável quantitativa, por se tratar de uma variável quantitativa discreta também é interessante também avaliar a frequência de cada valor (freq_Retencao <- table(telefonia$Qtd_retencao_6meses)) (pct_Retencao <- prop.table(table(telefonia$Qtd_retencao_6meses))) # utilizando a função prop.table, temos como output a tabela em percentual round(pct_Retencao * 100, 2) #Percentual de cada categoria # Qtde de produtos # Apesar de ser uma variável quantitativa, por se tratar de uma variável quantitativa discreta também é interessante também avaliar a frequência de cada valor (freq_Prod <- table(telefonia$Qtd_prod)) pct_Prod <- prop.table(table(telefonia$Qtd_prod)) # utilizando a função prop.table, temos como output a tabela em percentual round(pct_Prod * 100, 2) # percentual de cada categoria # ********************************************************** # (b) Faça a análise descritiva bivariada covariável x resposta e identifique as # covariáveis que tem mais relação com a resposta. # Pacote com a função 'quantcut' library(gtools) telefonia$Idade_q_aux <- quantcut(telefonia$Idade, 4) telefonia$Idade_q <- ifelse(telefonia$Idade == 999, "Missing", telefonia$Idade_q_aux) telefonia$Minutos_realizados_T0_q <- quantcut(telefonia$Minutos_realizados_T0, 4) telefonia$Tempo_safra_q <- quantcut(telefonia$Tempo_safra, 4) telefonia$Tempo_casa_q <- quantcut(telefonia$Tempo_casa, 4) telefonia$Qtd_retencao_6meses_q <- quantcut(telefonia$Qtd_retencao_6meses, 4) telefonia$Qtd_prod_q <- quantcut(telefonia$Qtd_prod, 4) # Tabela bidimensional: covariável x resposta Idade_table_q <- table(telefonia$Idade_q, telefonia$resposta) Minutos_table_q <- table(telefonia$Minutos_realizados_T0_q, telefonia$resposta) Tempo_safra_table_q <- table(telefonia$Tempo_safra_q, telefonia$resposta) Tempo_casa_table_q <- table(telefonia$Tempo_casa_q, telefonia$resposta) Qtd_retencao_table_q <- table(telefonia$Qtd_retencao_6meses_q, telefonia$resposta) Qtd_prod_table_q <- table(telefonia$Qtd_prod_q, telefonia$resposta) # Multiplicando por 100 para virar porcentagem e arredondamento para 2 casas decimais round(prop.table(Idade_table_q, 1) * 100, 2) # parâmetro 1 dentro de prop.table indica que é a proporção da linha table(telefonia$Idade_q,telefonia$Idade_q_aux)#Ver as categorias round(prop.table(Minutos_table_q, 1) * 100, 2) round(prop.table(Tempo_safra_table_q, 1) * 100, 2) round(prop.table(Tempo_casa_table_q, 1) * 100, 2) round(prop.table(Qtd_retencao_table_q, 1) * 100, 2) round(prop.table(Qtd_prod_table_q, 1) * 100, 2) # ********************************************************** # (c) Faça a análise de multicolinearidade entre as covariáveis. # Biblioteca para o cálculo da estatística de Cramers'V library(lsr) # Idade com as demais covariáveis cramersV(table(telefonia$Idade_q, telefonia$Minutos_realizados_T0_q)) cramersV(table(telefonia$Idade_q, telefonia$Tempo_safra_q)) cramersV(table(telefonia$Idade_q, telefonia$Tempo_casa_q)) cramersV(table(telefonia$Idade_q, telefonia$Qtd_retencao_6meses_q)) cramersV(table(telefonia$Idade_q, telefonia$Qtd_prod_q)) # Minutos realizados com as demais covariáveis cramersV(table(telefonia$Minutos_realizados_T0_q, telefonia$Tempo_safra_q)) cramersV(table(telefonia$Minutos_realizados_T0_q, telefonia$Tempo_casa_q)) cramersV(table(telefonia$Minutos_realizados_T0_q, telefonia$Qtd_retencao_6meses_q)) cramersV(table(telefonia$Minutos_realizados_T0_q, telefonia$Qtd_prod_q)) # Tempo_safra com as demais covariáveis cramersV(table(telefonia$Tempo_safra_q, telefonia$Tempo_casa_q)) cramersV(table(telefonia$Tempo_safra_q, telefonia$Qtd_retencao_6meses_q)) cramersV(table(telefonia$Tempo_safra_q, telefonia$Qtd_prod_q)) # Tempo_casa com as demais covariáveis cramersV(table(telefonia$Tempo_casa_q, telefonia$Qtd_retencao_6meses_q)) cramersV(table(telefonia$Tempo_casa_q, telefonia$Qtd_prod_q)) # Qtde de retenção com Qtd de produtos cramersV(table(telefonia$Qtd_retencao_6meses_q, telefonia$Qtd_prod_q)) # ********************************************************** # (d) Rode a regressão Logística considerando as covariáveis categorizadas. Identifique quais variáveis foram selecionadas pelo modelo, interprete-as, e avalie o desempenho do modelo pela Tabela de Classificação. # Modelo completo modelo_full <- glm(resposta ~ Idade_q + Minutos_realizados_T0_q + Tempo_safra_q + Tempo_casa_q + Qtd_retencao_6meses_q + Qtd_prod_q, family = binomial(link = "logit"), data = telefonia) summary(modelo_full) # Para o modelo logístico, com a função 'predict', tendo como parâmetro type = 'response' conseguimos obter as probabilidades do modelo para a classificação '1' telefonia$reg_log_p1 <- predict(modelo_full, newdata = telefonia, type = "response") summary(telefonia$reg_log_p1) # Cria variável resposta predita com base na probabilidade predita pelo modelo telefonia$resp_bin1 <- as.factor(ifelse(telefonia$reg_log_p1 >= 0.008685467, 1, 0)) # transforma a probabilidade em variável binária # Mostra a tabela de desempenho: Predito x Resposta observada (tabela_desempenho <- table(telefonia$resposta, telefonia$resp_bin1)) # Calcula as medidas de desempenho: Sensibilidade, Especificidade e Acurácia (sensibilidade <- tabela_desempenho[2, 2] / sum(tabela_desempenho[2, ])) (especificidade <- tabela_desempenho[1, 1] / sum(tabela_desempenho[1, ])) (n <- nrow(telefonia)) (acuracia <- sum(tabela_desempenho[1, 1] + tabela_desempenho[2, 2]) / n) (ks <- abs(sensibilidade - (1 - especificidade))) # Modelo reduzido: sem tempo safra modelo_red1 <- glm(resposta ~ Idade_q + Minutos_realizados_T0_q + Tempo_casa_q + Qtd_retencao_6meses_q + Qtd_prod_q, family = binomial(link = "logit"), data = telefonia) summary(modelo_red1) telefonia$reg_log_p1 <- predict(modelo_red1, newdata = telefonia, type = "response") summary(telefonia$reg_log_p1) # Transforma a probabilidade em variável binária telefonia$resp_bin1 <- as.factor(ifelse(telefonia$reg_log_p1 >= 0.008685467, 1, 0)) (tabela_desempenho <- table(telefonia$resposta, telefonia$resp_bin1)) (sensibilidade <- tabela_desempenho[2, 2] / sum(tabela_desempenho[2, ])) (especificidade <- tabela_desempenho[1, 1] / sum(tabela_desempenho[1, ])) (n <- nrow(telefonia)) (acuracia <- sum(tabela_desempenho[1, 1] + tabela_desempenho[2, 2]) / n) (ks <- abs(sensibilidade - (1 - especificidade))) # Modelo reduzido: sem tempo casa modelo_red2 <- glm(resposta ~ Idade_q + Minutos_realizados_T0_q + Tempo_safra_q + Qtd_retencao_6meses_q + Qtd_prod_q, family = binomial(link = "logit"), data = telefonia) summary(modelo_red2) telefonia$reg_log_p1 <- predict(modelo_red2, newdata = telefonia, type = "response") summary(telefonia$reg_log_p1) telefonia$resp_bin1 <- as.factor(ifelse(telefonia$reg_log_p1 >= 0.008685467, 1, 0)) # transforma a probabilidade em variável binária (tabela_desempenho <- table(telefonia$resposta, telefonia$resp_bin1)) (sensibilidade <- tabela_desempenho[2, 2] / sum(tabela_desempenho[2, ])) (especificidade <- tabela_desempenho[1, 1] / sum(tabela_desempenho[1, ])) (n <- nrow(telefonia)) (acuracia <- sum(tabela_desempenho[1, 1] + tabela_desempenho[2, 2]) / n) (ks <- abs(sensibilidade - (1 - especificidade))) # Modelo reduzido: sem tempo casa e Idade (tem categoria missing) modelo_red3 <- glm(resposta ~ Minutos_realizados_T0_q + Tempo_safra_q + Qtd_retencao_6meses_q + Qtd_prod_q, family = binomial(link = "logit"), data = telefonia) summary(modelo_red3) telefonia$reg_log_p1 <- predict(modelo_red3, newdata = telefonia, type = "response") summary(telefonia$reg_log_p1) telefonia$resp_bin1 <- as.factor(ifelse(telefonia$reg_log_p1 >= 0.008685467, 1, 0)) # transforma a probabilidade em variável binária (tabela_desempenho <- table(telefonia$resposta, telefonia$resp_bin1 )) (sensibilidade <- tabela_desempenho[2, 2] / sum(tabela_desempenho[2, ])) (especificidade <- tabela_desempenho[1, 1] / sum(tabela_desempenho[1, ])) (n <- nrow(telefonia)) (acuracia <- sum(tabela_desempenho[1, 1] + tabela_desempenho[2, 2]) / n) (ks <- abs(sensibilidade - (1 - especificidade))) # ********************************************************** # (e) Rode árvore de decisão usando o método CHAID com 3 níveis. Identifique quais variáveis foram selecionadas pelo modelo, interprete-as, e avalie o desempenho do modelo pela Tabela de Classificação. # Função 'chaid' nos permite criar uma árvore de decisão de acordo com o algoritmo CHAID library(partykit) # pacote precisa ser instalado previamente para usar o CHAID # install.packages("CHAID", repos="http://R-Forge.R-project.org") library(CHAID) # pacote com a função 'chaid' # Todas as variáveis como um fator (não como numérico para ser input da Árvore) telefonia$resposta <- as.factor(telefonia$resposta) telefonia$Idade_q <- as.factor(telefonia$Idade_q) # Para a árvore não ficar muito grande, a três níveis controle <- chaid_control(maxheight = 3) # Função 'chaid' nos permite criar uma árvore de decisão de acordo com o algoritmo CHAID (arvore_full <- chaid(resposta ~ Idade_q + Minutos_realizados_T0_q + Tempo_safra_q + Tempo_casa_q + Qtd_retencao_6meses_q + Qtd_prod_q, data = telefonia, control = controle)) # indicando em qual base o modelo deve ser estimado # Incluir na base de dados a probabilidade predita pela Árvore de Decisão probs<- as.data.frame(predict(arvore_full, newdata = telefonia, type = "p")) # "p" salva o valor predito da probabilidade names(probs) <- c("P_0", "P_1") telefonia <- cbind(telefonia, probs) # insere 2 colunas na base com as probabilidades preditas de 0 e 1 # Cria variável resposta predita com base na probabilidade predita pela Árvore de Decisão telefonia$predict_AD <- as.factor(ifelse(telefonia$P_1 >= 0.008685467, 1, 0)) # transforma a probabilidade em variável binária # Mostra a tabela de desempenho: Predito x Resposta observada (tabela_desempenho <- table(telefonia$resposta, telefonia$predict_AD)) # Calcula as medidas de desempenho: Sensibilidade, Especificidade e Acurácia (sensibilidade <- tabela_desempenho[2, 2] / sum(tabela_desempenho[2, ])) (especificidade <- tabela_desempenho[1, 1] / sum(tabela_desempenho[1, ])) (n <- nrow(telefonia)) (acuracia <- sum(tabela_desempenho[1, 1] + tabela_desempenho[2, 2])/n) (ks <- abs(sensibilidade - (1 - especificidade))) # Função 'chaid' sem Idade (arvore_red1 <- chaid(resposta ~ Minutos_realizados_T0_q + Tempo_safra_q + Tempo_casa_q + Qtd_retencao_6meses_q + Qtd_prod_q, data = telefonia, control = controle)) # indicando em qual base o modelo deve ser estimado probs <- as.data.frame(predict(arvore_red1, newdata = telefonia, type = "p")) # "p" salva o valor predito da probabilidade names(probs) <- c("P_0_AD", "P_1_AD") summary(telefonia) telefonia <- cbind(telefonia, probs) # insere 2 colunas na base com as probabilidades preditas de 0 e 1 telefonia$predict_AD <- as.factor(ifelse(telefonia$P_1 >= 0.008685467, 1, 0)) # transforma a probabilidade em variável binária (tabela_desempenho <- table(telefonia$resposta, telefonia$predict_AD)) (sensibilidade <- tabela_desempenho[2, 2] / sum(tabela_desempenho[2, ])) (especificidade <- tabela_desempenho[1, 1] / sum(tabela_desempenho[1, ])) (n <- nrow(telefonia)) (acuracia <- sum(tabela_desempenho[1, 1] + tabela_desempenho[2, 2]) / n) (ks <- abs(sensibilidade - (1 - especificidade))) # ********************************************************** # (g) Calcule a área abaixo da curva ROC, e avalie seu desempenho. library(pROC) # Área abaixo da curva ROC: Regressão Logística roc(telefonia$resposta, telefonia$reg_log_p1, plot = TRUE, legacy.axes = TRUE, print.auc = TRUE, main = "Regressão Logística") # Área abaixo da curva ROC: Árvore de Decisão roc(telefonia$resposta, telefonia$P_1_AD, plot = TRUE, legacy.axes = TRUE, print.auc = TRUE, main = "Árvore de Decisão") # ********************************************************** # (i) Construa a tabela de probabilidade preditas x resposta observada em VINTIS para Regressão Logística, # e obtenha de forma análoga a tabela de probabilidades por nó x resposta para Árvore de Decisão. # Use a planilha do Excel 'An_Desempenho_Exercicio'. # Tabela de Desempenho: Regressão Logística # (Use a planilha do Excel 'An_Desempenho_Exercicio') # Calcular as faixas de vintil telefonia$fx_reg_log <- quantcut(telefonia$reg_log_p1, 20) # Distribuição da resposta por faixa de probabilidade (table(telefonia$fx_reg_log, telefonia$resposta)) # Propensão dos nós finais: Árvore de Decisão telefonia$node <- predict(arvore_red1, type = "node") # Tabela de Desempenho: Árvore de Decisão (tabela_AD <- (table(telefonia$node, telefonia$resposta))) # Agrega a base para pegar propensão do associado ao nó attach(telefonia) aggdata <- aggregate(telefonia, by = list(node), FUN = mean) (DE_PARA <- cbind(aggdata$node, round(aggdata$P_1_AD, 4))) detach(telefonia) # Copiar as duas tabelas do excel, juntá-las e ordenar em ordem crescente de probabilidade
d5c666c2795aad1d49227f00f0838cfd9a1c1958
bffaec26f4f82430912725f9d83006aa63b8a4ab
/man/arima_multistep.Rd
52ad97de718a1b075ca84effe2dae7068fadd621
[]
no_license
vcerqueira/vest
37b0ce7d61796ad3474cd8a0a96ed519933c5509
a19aac8d7b9c2ada96f9afc4d8fcfe033ad75c4b
refs/heads/master
2022-12-17T17:49:21.603487
2021-02-08T21:31:26
2021-02-08T21:31:26
239,560,166
17
4
null
2022-12-08T11:51:49
2020-02-10T16:37:16
R
UTF-8
R
false
true
357
rd
arima_multistep.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/arima-expsmooth.r \name{arima_multistep} \alias{arima_multistep} \title{ARIMA MODEL} \usage{ arima_multistep(train, test, freq, h) } \arguments{ \item{train}{train series, ts} \item{test}{test series, ts} \item{freq}{frequency} \item{h}{horizon} } \description{ ARIMA MODEL }
c7035901ed3db4deb175726051f4b37280bafc11
abe567a26b3b20081ecf6a3952f16b90035f7ecf
/man/conways_game_of_life.Rd
34c80210eda1f5ad057d6d14d5f627fddee589a7
[]
no_license
KIT-IfGG/pets
4af61de028f29fa0495ecb149f3d774f4d3ef332
3cee6fe620354d682b5cef917b44a89f640d3748
refs/heads/master
2021-01-18T11:24:45.130165
2018-11-21T11:48:22
2018-11-21T11:48:22
100,360,310
2
2
null
null
null
null
UTF-8
R
false
false
1,999
rd
conways_game_of_life.Rd
\name{conways_game_of_life} \alias{conways_game_of_life} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Conways game of life } \description{ %% ~~ A concise (1-5 lines) description of what the function does. ~~ } \usage{ conways_game_of_life(x) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ %% ~~Describe \code{x} here~~ } } \details{ %% ~~ If necessary, more details than the description above ~~ } \value{ %% ~Describe the value returned %% If it is a LIST, use %% \item{comp1 }{Description of 'comp1'} %% \item{comp2 }{Description of 'comp2'} %% ... } \references{ %% ~put references to the literature/web site here ~ } \author{ %% ~~who you are~~ } \note{ %% ~~further notes~~ } %% ~Make other sections like Warning with \section{Warning }{....} ~ \seealso{ %% ~~objects to See Also as \code{\link{help}}, ~~~ } \examples{ ### Simulate mygrid <- Conway_game_of_life(size = 50, num_reps = 200, prob = c(0.01, 0.99), plot=TRUE) ### Plot the result x11() for(i in 1:length(mygrid)) { image(mygrid[[i]], main=i, col=c("white", "green")) Sys.sleep(0.1) } ### Plot population sizes over time. pop <- sapply(mygrid, sum)/length(mygrid[[1]]) x11() par(mar=c(5,5,1,1)) plot(pop ~ seq(1,length(pop), by=1), xlab="Time", ylab="Population size", cex.axis=1.5, cex.lab=1.5, type="l", col="darkred", lwd=1.5, ylim=c(0,0.5)) ### Compare several runs with the same parameters! reps <- replicate(10, Conway_game_of_life(size = 10, num_reps = 30, prob = c(0.5, 0.5), plot=FALSE), simplify = FALSE) pops <- sapply(reps, function(x) sapply(x, sum)/length(x[[1]])) x11() matplot(seq(1,nrow(pops), by=1), pops, xlab="Time", ylab="Population size", cex.axis=1.5, cex.lab=1.5, type="l", col=rainbow(ncol(pops)), lwd=1.5, ylim=c(0,0.6)) ### Create a gif saveGIF(Conway_game_of_life(size = 50, num_reps = 100, prob = c(0.01, 0.99), plot=TRUE), movie.name = "animation.gif", img.name = "Rplot", convert = "convert", interval = 0.6) }
f2bbb2292ebfeed4af9ef082f2dcebc7522b9aa1
54e6946ed588b5b2814b818249163e53ab14e9ce
/man/hdg_norm.Rd
f3eb7ebbab22246fdebdf2d9561be9e9be5cbbd6
[ "MIT" ]
permissive
paleolimbot/headings
1b640a96d6fa4420c1616fe80440d9fbcf4f5b3b
e7489d8f44c3d4ffd8c88044a3b6943196abba00
refs/heads/master
2023-04-01T20:03:06.835779
2021-04-07T15:19:35
2021-04-07T15:19:35
341,327,046
0
0
null
null
null
null
UTF-8
R
false
true
956
rd
hdg_norm.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/heading.R \name{hdg_norm} \alias{hdg_norm} \alias{uv} \alias{uv_norm} \alias{uv_from_hdg} \alias{hdg_from_uv} \alias{rad_from_hdg} \alias{hdg_from_rad} \title{Create and export headings} \usage{ hdg_norm(hdg) uv(u, v) uv_norm(uv) uv_from_hdg(hdg) hdg_from_uv(uv) rad_from_hdg(hdg) hdg_from_rad(rad) } \arguments{ \item{hdg}{A heading in degrees, where 0 is north, 90 is east, 180 is south, and 270 is west. Values outside the range [0-360) are coerced to this range using \code{\link[=hdg_norm]{hdg_norm()}}.} \item{uv, u, v}{A data.frame with columns \code{u} (magnitude east) and \code{v} (magnitude north).} \item{rad}{An angle in radians such that a \code{hdg} of 90 is zero radians and a \code{hdg} of 0 is \code{pi / 2} radians.} } \description{ Create and export headings } \examples{ hdg_norm(-10:10) hdg_from_uv(uv(1, 0)) uv_from_hdg(5:10) uv_norm(uv(2, 0)) }
8aafe079fe98dbc98fc4ad64ac3023c4ab1ac8d9
6d0999bafd5986933e13719034254d9bfab4d47c
/Code/R/megacategory_assign.R
2c1176bef86f8ebf9657c645f25c9517032198eb
[]
no_license
emilio-berti/rewiring-rewilding
63199f62d1b403c5f59b2e38d4942f448da3416d
864ac86669162238154da89a974b0ef66c95a9a7
refs/heads/master
2022-12-22T00:18:43.366985
2020-09-24T06:43:23
2020-09-24T06:43:23
290,488,904
0
0
null
null
null
null
UTF-8
R
false
false
575
r
megacategory_assign.R
megacategory <- function(species){ mass <- subset(phy, Binomial.1.2 == species)$Mass.g family <- subset(phy, Binomial.1.2 == species)$Family.1.2 if(family %in% c("Ursidae", "Felidae")){ candidates <- subset(phy, Family.1.2 == family)[c("Binomial.1.2", "Mass.g", "IUCN.Status.1.2")] candidates <- subset(candidates, Mass.g >= 100000) } else{ candidates <- NULL } if(!is.null(candidates)){ candidates <- subset(candidates, !IUCN.Status.1.2 %in% c("EX", "EW", "EP")) return(as.vector(candidates$Binomial.1.2)) } else{ return(NULL) } }
06331e8db041003e35bca1b8051af964cf26e353
dc7d3873fd7896fd4a81329a7aa24d4704a8bd90
/scripts/BcBOTnet/09_BOAforMEGA.R
6ae903cc97fd68d804c950937e1e52bbbf96a4aa
[]
no_license
nicolise/BcAt_RNAGWAS
4cd4cf169c06f46057e10ab1773779c8eaf77ab1
64f15ad85186718295c6a44146befa3ca57b7efc
refs/heads/master
2021-01-12T11:40:59.400854
2019-10-21T19:54:53
2019-10-21T19:54:53
72,249,016
0
0
null
null
null
null
UTF-8
R
false
false
2,763
r
09_BOAforMEGA.R
#Nicole E Soltis #-------------------------------------------------- #need FASTA file input for MEGA #want: beginning of C1 (5133) to 97414 #BcBoa17 goes up to 69449. 3 genes downstream is gene:Bcin01g00190. end position is 97414. #or, if looking within deletion ONLY: #last base of deletion = 82614 #first base of deletion = first base of C1 = 4029 #approach 2: read in BOA data, convert to fasta format in R #have been using binary PED -- lost SNP state info. #need to use: install.packages("seqRFLP") library("seqRFLP") #Your sequences need to be in a data frame with sequence headers in column 1 and sequences in column 2 [doesn't matter if it's nucleotide or amino acid] names <- c("seq1","seq2","seq3","seq4") sequences<-c("EPTFYQNPQFSVTLDKR","SLLEDPCYIGLR","YEVLESVQNYDTGVAK","VLGALDLGDNYR") df <- data.frame(names,sequences) #Then convert the data frame to .fasta format using the function: 'dataframe2fas' df.fasta = dataframe2fas(df, file="df.fasta") #--------------------------------------------------------------------- #failed approach 1: read in Chr 1 fasta, try to extract nucleotides of interest #BUT this does not include SNP state info for individual isolates. Dropping this approach. setwd("~/Projects/BcGenome/data/ensembl/B05.10/fasta/singleChr") library("Biostrings") library("seqinr") coi.fa <- read.fasta(file = textConnection("Botrytis_cinerea.ASM83294v1.dna.chromosome.1.fa/gpfs/nobackup/ensembl/amonida/rel91/eg38/fungi/fasta/botrytis_cinerea/dna/Botrytis_cinerea.ASM83294v1.dna.chromosome.1.fa"), as.string = T) myFA <- read.fasta(file = "Botrytis_cinerea.ASM83294v1.dna.chromosome.1.fa/gpfs/nobackup/ensembl/amonida/rel91/eg38/fungi/fasta/botrytis_cinerea/dna/Botrytis_cinerea.ASM83294v1.dna.chromosome.1.fa", as.string=FALSE, seqonly=FALSE) myFAdf <- as.data.frame(myFA) myFA2 = readDNAStringSet("Botrytis_cinerea.ASM83294v1.dna.chromosome.1.fa/gpfs/nobackup/ensembl/amonida/rel91/eg38/fungi/fasta/botrytis_cinerea/dna/Botrytis_cinerea.ASM83294v1.dna.chromosome.1.fa") seq_name = names(myFA2) sequence = paste(myFA2) myFAdf <- data.frame(seq_name, sequence) library("Biostrings") fasta2dataframe=function(fastaFile){ s = readDNAStringSet(fastaFile) RefSeqID = names(s) RefSeqID = sub(" .*", "", RefSeqID) #erase all characters after the first space: regular expression matches a space followed by any sequence of characters and sub replaces that with a string having zero characters for (i in 1:length(s)){ seq[i]=toString(s[i]) } RefSeqID_seq=data.frame(RefSeqID,seq) return(RefSeqID_seq) } mydf2 = fasta2dataframe("Botrytis_cinerea.ASM83294v1.dna.chromosome.1.fa/gpfs/nobackup/ensembl/amonida/rel91/eg38/fungi/fasta/botrytis_cinerea/dna/Botrytis_cinerea.ASM83294v1.dna.chromosome.1.fa")
6bffb21b87f5c60c695e46ab7976037bdac61903
31bb7850a8f76259887e142611bab3f3e45ff981
/NCAR/code/stl2/stl.tw617.td2.sw103.sd1.i10.o0/tmax.100stations.stl2.R
8ad266bc18bc8d6700cbfe1145c008dbfce2589b
[]
no_license
XiaosuTong/Spatial
4bb6951697f69477612fcef6c987a3a2a72b0143
068d1a00a2b5f08404da23049f7ddd3c76d03c96
refs/heads/master
2020-12-29T01:54:00.658233
2016-06-16T18:30:46
2016-06-16T18:30:46
20,975,405
0
0
null
null
null
null
UTF-8
R
false
false
22,809
r
tmax.100stations.stl2.R
############################################################################ ##Max temperature, 100 stations, seasonal+trend with raw data by stl2 ########################################################################## #load the data library(lattice) library(plyr) library(stl2) library(maps) outputdir <- "~/Projects/Spatial/NCAR/output/" datadir <- "~/Projects/Spatial/NCAR/RData/" load(paste(datadir,"USmonthlyMet.RData", sep="")) load(paste(datadir,"stations.RData", sep="")) #find the 100 stations with largest observation number for max temperature stations <- stations.tmax tmp <- UStemp[UStemp[,1] %in% stations,] tmp <- tmp[!(is.na(tmp$tmax)),] month <- tmp$month levels(month) <- c(1:12) month <- as.numeric(factor(month, levels=c(1:12))) date <- paste(tmp$year, month, "01", sep="-") tmp$date <- as.POSIXct(strptime(date, format = "%Y-%m-%d"), format='%Y%m%d', tz="") tmp <- tmp[order(tmp$date),] tmp <- tmp[order(tmp[,1]),-8] tmp$factor <- factor(rep(rep(paste("Period", 1:9), c(rep(144,8),84)), times=100), levels=paste("Period", c(9:1))) tmp$time <- c(rep(0:143,8), 0:83) lattice.theme <- trellis.par.get() col <- lattice.theme$superpose.symbol$col dr <- ddply(tmp, "station.id", function(r){stl2(r$tmax, r$date, n.p=12, s.window=103, s.degree=1, t.window=617, t.degree=2, inner = 10, outer = 0)$data}) tmp <- cbind(tmp, dr) tmp <- tmp[order(tmp$station.id,tmp$date),] ################################## ##trend+seasonal time series plot ################################## tmp1 <- tmp[,1:11] names(tmp1)[8] <- "response" tmp1$group <- rep("raw", 123600) tmp1 <- tmp1[,c(1:7,9,10,11,8,12)] tmp2 <- tmp[,c(1:7,9,10,11,14,15)] tmp2$response <- tmp2$seasonal + tmp2$trend tmp2 <- tmp2[,-c(11,12)] tmp2$group <- rep("seasonal+trend", 123600) rst <- rbind(tmp1, tmp2) #start <- as.POSIXct(strptime(paste(head(tmp$year,1), "01", "01", sep="-"), format = "%Y-%m-%d"), format='%Y%m%d', tz="") #end <- as.POSIXct(strptime(paste("2000", "01", "01", sep="-"), format = "%Y-%m-%d"), format='%Y%m%d', tz="") trellis.device(postscript, file = paste(outputdir, "scatterplot_of_tmax_with_stl2_trend+seasonal_for_100_stations",".ps", sep = ""), color=TRUE, paper="legal") for(i in stations){ b <- xyplot( response ~ time | factor, data = subset(rst, station.id==i), groups = group, xlab = list(label = "Month", cex = 1.2), ylab = list(label = "Maximum Temperature (degrees centigrade)", cex = 1.2), main = list(label = paste("Station ", i, sep=""), cex=1.5), type = c("p","l"), distribute.type= TRUE, layout = c(1,9), pch = 16, cex = 0.5, aspect= 0.06, strip = FALSE, # strip.left = TRUE, grib = TRUE, xlim = c(0, 143), # scales = list(y = list(relation = 'free', cex=1.5), x=list(relation= 'free',format = "%b %Y", tick.number=10), cex=1.2), scales = list(y = list(relation = 'same', alternating=TRUE), x=list(at=seq(0, 143, by=12), relation='same')), panel = function(...) { panel.abline(v=seq(0,145, by=12), color="lightgrey", lty=3, lwd=0.5) panel.xyplot(...) } ) print(b) } dev.off() ################################################################################## #QQ plot and time series plot of Pooled remainder of max temperature for 100 stations ################################################################################## #Create the QQ plot of temperature for one station trellis.device(postscript, file = paste(outputdir, "QQ_plot_of_stl2_remainder_tmax_of_100_stations", ".ps", sep = ""), color=TRUE, paper="legal") a <- qqmath(~ remainder | station.id, data = tmp, distribution = qnorm, aspect = 1, pch = 16, cex = 0.5, layout = c(6,3), # main = list(label= paste("Station ", i, sep=""), cex=2), xlab = list(label="Unit normal quantile", cex=1.2), ylab = list(label="Maximum Temperature(degrees centigrade)", cex=1.2), # scales = list(x = list(cex=1.5), y = list(cex=1.5)), prepanel = prepanel.qqmathline, panel = function(x, y,...) { panel.grid(lty=3, lwd=0.5, col="black",...) panel.qqmathline(x, y=x) panel.qqmath(x, y,...) } ) print(a) dev.off() tmp.remainder <- tmp tmp.remainder$time1 <- rep(0:1235,100) tmp.remainder$factor <- factor(tmp$factor, levels=paste("Period", c(3,2,1,6,5,4,9,8,7))) trellis.device(postscript, file = paste(outputdir, "scatterplot_of_tmax_with_stl2_remainder_for_100_stations",".ps", sep = ""), color=TRUE, paper="legal") for(i in stations){ b <- xyplot( remainder ~ time | factor, data = subset(tmp.remainder, station.id==i), xlab = list(label = "Month", cex = 1.2), ylab = list(label = paste("Station", i, "Maximum Temperature (degrees centigrade)"), cex = 1.2), # main = list(label = paste("Station ", i, sep=""), cex=1.5), type = "p", layout = c(1,3), pch = 16, cex = 0.5, # aspect= "xy", xlim = c(0, 143), strip = FALSE, # strip.left = TRUE, grib = TRUE, # xlim = c(start, end), # scales = list(y = list(relation = 'free', cex=1.5), x=list(relation= 'free',format = "%b %Y", tick.number=10), cex=1.2), scales = list(y = list(relation = 'same', alternating=TRUE), x=list(at=seq(0, 143, by=12), relation='same')), panel = function(x,y,...) { panel.abline(h=0, v=seq(0,143, by=12), color="lightgrey", lty=3, lwd=0.5) panel.xyplot(x,y,...) panel.loess(x,y,degree=2,span=1/4, col=col[2], ...) } ) print(b) } dev.off() trellis.device(postscript, file = paste(outputdir, "scatterplot_of_tmax_with_stl2_remainder2_for_100_stations",".ps", sep = ""), color=TRUE, paper="legal") for(i in stations){ b <- xyplot( remainder ~ time1, data = subset(tmp.remainder, station.id==i), xlab = list(label = "Month", cex = 1.2), ylab = list(label = paste("Station", i, "Maximum Temperature (degrees centigrade)"), cex = 1.2), # main = list(label = paste("Station ", i, sep=""), cex=1.5), type = "p", pch = 16, cex = 0.5, xlim = c(0, 1235), key=list(type="l", text=list(label=c("remainder","degree=2,span=0.15","degree=1,span=0.35")), lines=list(lwd=1.5, col=col[1:3]), columns=3), # scales = list(y = list(relation = 'free', cex=1.5), x=list(relation= 'free',format = "%b %Y", tick.number=10), cex=1.2), scales = list(y = list(relation = 'same', alternating=TRUE), x=list(at=seq(0, 1235, by=120), relation='same')), panel = function(x,y,...) { panel.abline(h=0) panel.xyplot(x,y,...) panel.loess(x,y,degree=2,span=0.15, col=col[2]) panel.loess(x,y,degree=1,span=0.35, col=col[3]) } ) print(b) } dev.off() ################################################# ##Auto correlation ACF for the remainder ################################################# ACF <- ddply(.data=tmp.remainder, .variables="station.id", .fun= summarise, correlation = c(acf(remainder, plot=FALSE)$acf), lag = c(acf(remainder, plot=FALSE)$lag) ) trellis.device(postscript, file = paste(outputdir, "acf_of_tmax_with_stl2_remainder_for_100_stations",".ps", sep = ""), color=TRUE, paper="legal") for(i in stations){ b <- xyplot( correlation ~ lag, data = subset(ACF, station.id==i & lag!=0), xlab = list(label = "Lag", cex = 1.2), ylab = list(label = paste("Station", i, "ACF"), cex = 1.2), # main = list(label = paste("Station ", i, sep=""), cex=1.5), type = "h", panel = function(x,y,...) { panel.abline(h=0) panel.xyplot(x,y,...) } ) print(b) } dev.off() ################################################## ##time series plot of seaosnal+remainder from stl2 ################################################## #tmp$sr <- tmp$seasonal + tmp$remainder # #trellis.device(postscript, file = paste("scatterplot_of_tmax_with_stl2_seasonal+remainder_for_100_stations",".ps", sep = ""), color=TRUE, paper="legal") # for(i in stations){ # b <- xyplot( sr ~ time | factor, # data = subset(tmp, station.id==i), # xlab = list(label = "Month", cex = 1.5), # ylab = list(label = "Maximum Temperature (degrees centigrade)", cex = 1.5), # main = list(label = paste("Station ", i, sep=""), cex=1.5), # type = "p", # layout = c(1,9), # pch = 16, # cex = 0.5, # aspect= 0.06, # strip = FALSE, # strip.left = TRUE, # grib = TRUE, ## xlim = c(start, end), ## scales = list(y = list(relation = 'free', cex=1.5), x=list(relation= 'free',format = "%b %Y", tick.number=10), cex=1.2), # scales = list(y = list(relation = 'same', cex=1, alternating=TRUE), x=list(tick.number=10, cex=1.2, relation='same')), # panel = function(...) { # panel.abline(h=seq(-10,10,by=5), v=seq(0,140, by=12), color="lightgrey", lty=3, lwd=0.5) # panel.xyplot(...) # # } # ) # print(b) # } #dev.off() ########################################################################## ##time series plot of trend component and yearly average of raw from stl2 ########################################################################## tmp.trend <- tmp[,c(1:9,15)] dr <- ddply(.data = tmp.trend, .variables = c("station.id","year"), .fun = summarise, mean = mean(tmax) ) mm <- dr[rep(row.names(dr), each=12),] tmp.trend <- cbind(tmp.trend, mean= mm$mean) order <- ddply(.data = tmp.trend, .variables = "station.id", .fun = summarise, mean = mean(tmax) ) order.st <- as.character(order[order(order$mean, decreasing=TRUE), ]$station.id) tmp.trend$station.id <- factor(tmp.trend$station.id, levels=order.st) tmp1 <- tmp.trend[,1:10] tmp1$time <- rep(0:1235,100) tmp2 <- tmp.trend[,c(1:9,11)] tmp2$time <- rep(0:1235,100) names(tmp1)[10] <- names(tmp2)[10] <- "response" tmp.trend <- rbind(tmp1, tmp2) tmp.trend$group <- rep(c("trend","yearly mean"), each = 123600) #Attend to add a small map in the corner of the trend loess plot #us.map <- map('state', plot = FALSE, fill = TRUE) trellis.device(postscript, file = paste(outputdir, "scatterplot_of_tmax_with_stl2_trend_for_100_stations",".ps", sep = ""), color=TRUE, paper="legal") for(i in levels(tmp.trend$station.id)){ b <- xyplot( response ~ time, data = subset(tmp.trend, station.id==i & group == "trend"), # main = list(label= paste("Station ", i, sep=""), cex=1.5), xlab = list(label = "Month", cex = 1.2), ylab = list(label = paste("Station", i, "Maximum Temperature (degrees centigrade)"), cex = 1.2), # groups = group, # distribute.type = TRUE, # type = c("l"), # strip = strip.custom(par.strip.text= list(cex = 1.5)), # par.settings = list(layout.heights = list(strip = 1.5)), xlim = c(0, 1235), ylim = c(min(subset(tmp.trend, station.id==i)$response),max(subset(tmp.trend, station.id==i)$response)), pch = 16, aspect="xy", key=list(type="l", text=list(label=c("trend component","yearly mean")), lines=list(lwd=1.5, col=col[1:2]), columns=2), cex = 0.3, # scales = list(y = list(relation = 'free', cex=1.5), x=list(relation= 'same',format = "%b %Y", tick.number=8), cex=1.2), scales = list(y = list(relation = 'free'), x=list(at=seq(0, 1236, by=120), relation = 'same')), panel = function(x,y,...) { panel.abline(h=seq(10,40,by=1), v=seq(0,1236, by=120), color="lightgrey", lty=3, lwd=0.5) panel.xyplot(x,y,type="l",...) v <- subset(tmp.trend, station.id==i&group=="yearly mean") panel.xyplot(v$time, type="p", v$response, col=col[2], ...) } ) print(b) # a <- xyplot(lat ~ lon, # data = subset(tmp.trend, station.id==i), # xlab = NULL, # ylab = NULL, # pch = 16, # cex = 0.4, # xlim = c(-127,-65), # ylim = c(23,50), # col = "red", ## scales = list(x = list(draw=FALSE), y = list(draw=FALSE)), ## strip = strip.custom(par.strip.text= list(cex = 1.5)), ## par.settings = list(layout.heights = list(strip = 1.5)), # panel = function(x,y,...) { # panel.polygon(us.map$x,us.map$y,lwd=0.2) # panel.xyplot(x,y,...) # } # ) # plot.new() # title(paste("Station ", i, sep=""), cex=1.5) # print(b, pos=c(0.4,0,1,0.95), newpage=FALSE, more=TRUE) # print(a, pos=c(0,0.55,0.4,1), more=FALSE) } dev.off() ##################################################### ##Time series plot of trend+remainder against time ##################################################### #tmp1 <- tmp[,c(1:9,15, 16)] #tmp1$tr <- tmp1$trend + tmp1$remainder #tmp2 <- tmp[, c(1:9, 15)] #names(tmp2)[10] <- names(tmp1)[12] <- "response" #tmp1$group <- rep("trend+remainder", 123600) #tmp2$group <- rep("trend", 123600) #tmp2$time <- rep(0:1235,100) #tmp1$time <- rep(0:1235,100) #tmp.tr <- do.call("rbind", list(tmp1[,-c(10:11)], tmp2)) # #trellis.device(postscript, file = paste(outputdir, "scatterplot_of_tmax_with_stl2_trend+remainder_for_100_stations",".ps", sep = ""), color=TRUE, paper="legal") # for(i in stations){ # b <- xyplot( response ~ time, # data = subset(tmp.tr, station.id==i), # main = list(label = paste("Station ", i, sep=""), cex=1.5), # xlab = list(label = "Month", cex = 1.2), # ylab = list(label = "Maximum Temperature (degrees centigrade)", cex = 1.2), # groups = group, # distribute.type = TRUE, # type = c("l","p"), ## strip = strip.custom(par.strip.text= list(cex = 1.5)), ## par.settings = list(layout.heights = list(strip = 1.5)), # xlim = c(0, 1235), # pch = 16, # aspect= "xy", # key=list(type="l", text=list(label=c("Trend","Trend+remainder", "loess")), lines=list(lwd=1.5, col=col[1:3]), columns=3), # cex = 0.3, ## scales = list(y = list(relation = 'free', cex=1.5), x=list(relation= 'same',format = "%b %Y", tick.number=8), cex=1.2), # scales = list(y = list(relation = 'free'), x=list(at=seq(0, 1236, by=120), relation = 'same')), # panel = function(x,y,...) { # panel.abline(h=seq(0,40,by=2), v=seq(0,1236, by=120), color="lightgrey", lty=3, lwd=0.5) # panel.xyplot(x,y,...) # panel.loess(x,y,span=1/3, degree=2, col = col[3], ...) # # } # ) # print(b) # } #dev.off() ##################################################### ##time series plot of trend component loess from stl2 ##################################################### tmp.trend <- tmp[,c(1:9,15)] tmp.trend$time <- rep(0:1235,100) order <- ddply(.data = tmp.trend, .variables = "station.id", .fun = summarise, mean = mean(tmax) ) order.st <- as.character(order[order(order$mean, decreasing=TRUE), ]$station.id) tmp.trend$station.id <- factor(tmp.trend$station.id, levels=order.st) #Attend to add a small map in the corner of the trend loess plot #us.map <- map('state', plot = FALSE, fill = TRUE) trellis.device(postscript, file = paste(outputdir, "scatterplot_of_tmax_with_stl2_trend_loess_for_100_stations",".ps", sep = ""), color=TRUE, paper="legal") for(i in levels(tmp.trend$station.id)){ b <- xyplot( trend ~ time, data = subset(tmp.trend[order(tmp.trend$time),], station.id==i), # main = list(label= paste("Station ", i, sep=""), cex=1.5), xlab = list(label = "Month", cex = 1.2), ylab = list(label = paste("Station", i, "Maximum Temperature (degrees centigrade)"), cex = 1.2), # strip = strip.custom(par.strip.text= list(cex = 1.5)), # par.settings = list(layout.heights = list(strip = 1.5)), pch = 16, cex = 0.3, aspect="xy", xlim = c(0, 1235), key=list(type="l", text=list(label=c("loess smoothing","trend component")), lines=list(lwd=1.5, col=col[1:2]), columns=2), # scales = list(y = list(relation = 'free', cex=1.5), x=list(relation= 'same',format = "%b %Y", tick.number=8), cex=1.2), scales = list(y = list(relation = 'free'), x=list(at=seq(0, 1236, by=120), relation = 'same')), prepanel = function(x,y,...) prepanel.loess(x,y,span=3/4, degree=1, ...), panel = function(x,y,...) { panel.abline(h=seq(10,40,by=0.5), v=seq(0,1236, by=120), color="lightgrey", lty=3, lwd=0.5) panel.loess(x,y,degree=1, span=3/4, col=col[1],...) panel.xyplot(x,y,col=col[2],...) } ) print(b) # a <- xyplot(lat ~ lon, # data = subset(tmp.trend, station.id==i), # xlab = NULL, # ylab = NULL, # pch = 16, # cex = 0.4, # xlim = c(-127,-65), # ylim = c(23,50), # col = "red", ## scales = list(x = list(draw=FALSE), y = list(draw=FALSE)), ## strip = strip.custom(par.strip.text= list(cex = 1.5)), ## par.settings = list(layout.heights = list(strip = 1.5)), # panel = function(x,y,...) { # panel.polygon(us.map$x,us.map$y,lwd=0.2) # panel.xyplot(x,y,...) # } # ) # plot.new() # title(paste("Station ", i, sep=""), cex=1.5) # print(b, pos=c(0.4,0,1,0.95), newpage=FALSE, more=TRUE) # print(a, pos=c(0,0.55,0.4,1), more=FALSE) } dev.off() ########################################################################################## ##QQ plot of the slopes of loess of trend component, ordered stations by average of slopes ########################################################################################## #Get the loess estimate of trend component #tmp.trend <- tmp[,c(1:9,15)] #tmp.trend$time <- rep(0:1235,100) #loess.trend <- ddply(.data = tmp.trend, # .variables = "station.id", # .fun = summarise, # elev = elev, # lon = lon, # lat = lat, # time = time, # loess = loess(trend ~ time, span=0.4, degree=2)$fitted #) # ##Since the x-axis are time with 1 unit, ##the difference between two loess estimate is the approximate of the slope. ##Each station will have 1235 slope approximations. #slope.trend <- ddply(.data = loess.trend, # .variables = "station.id", # .fun = summarise, # elev = elev[1:1235], # lon = lon[1:1235], # lat = lat[1:1235], # slope = diff(loess) #) # ##Calculate the mean of slopes for each station, and then order the stations by mean slope. #mean.slope <- ddply(.data = slope.trend, # .variables = "station.id", # .fun = summarise, # elev = unique(elev), # lon = unique(lon), # lat = unique(lat), # mean = mean(slope) #) #mean.slope <- mean.slope[order(mean.slope$mean),] #station.or <- as.character(mean.slope$station.id) # ##Attend to add a small map in the corner of the trend loess plot #us.map <- map('state', plot = FALSE, fill = TRUE) # #trellis.device(postscript, file = paste(outputdir, "QQ_plot_of_tmax_slope_of_trend_loess",".ps", sep = ""), color=TRUE, paper="legal") # for(i in station.or){ # a <- qqmath(~ slope, # data = subset(slope.trend, station.id == i), # distribution = qunif, # aspect = 1, # pch = 16, # cex = 0.5, ## main = list(label= paste("Station ", i, sep=""), cex=2), # xlab = list(label="f-value", cex=1.2), # ylab = list(label="Maximum temperature(degrees centigrade)", cex=1.2), ## scales = list(x = list(cex=1.5), y = list(cex=1.5)), # prepanel = prepanel.qqmathline, # panel = function(x, y,...) { # #panel.grid(lty=3, lwd=0.5, col="black",...) # panel.qqmath(x, y,...) # } ## ) # b <- xyplot(lat ~ lon, # data = subset(tmp.trend, station.id==i), # xlab = NULL, # ylab = NULL, # pch = 16, # cex = 0.4, # xlim = c(-127,-65), # ylim = c(23,50), # col = "red", ## scales = list(x = list(draw=FALSE), y = list(draw=FALSE)), ## strip = strip.custom(par.strip.text= list(cex = 1.5)), ## par.settings = list(layout.heights = list(strip = 1.5)), # panel = function(x,y,...) { # panel.polygon(us.map$x,us.map$y,lwd=0.2) # panel.xyplot(x,y,...) # } # ) # plot.new() # title(paste("Station ", i, sep=""), cex=1.5) # print(a, pos=c(0.4,0,1,1), newpage=FALSE, more=TRUE) # print(b, pos=c(0,0.5,0.4,1), more=FALSE) # } #dev.off() # ##scatter plot of average slops vs spatial factor #trellis.device(postscript, file = paste(outputdir, "scatter_plot_of_average_slopes_tmax",".ps", sep = ""), color=TRUE, paper="legal") # c <- xyplot(mean ~ log2(elev), # data = mean.slope, # xlab = list(label = "Elevation (meter)", cex=1.2), # ylab = list(label = "Average slope of trend", cex=1.2), # pch = 16, # cex = 0.7, ## scales = list(x = list(draw=FALSE), y = list(draw=FALSE)), ## strip = strip.custom(par.strip.text= list(cex = 1.5)), ## par.settings = list(layout.heights = list(strip = 1.5)), # panel = function(x,y,...) { # panel.xyplot(x,y,...) # } # ) # print(c) #dev.off()
1f62a6b7063441d7d4cf5397ccb7ef1607a29a42
b5ae747457d833c6543319332f47bd937a4d446e
/man/cvPSYmc.Rd
579541cc294d1ac5db30f46ed0febc71554d1dab
[]
no_license
cran/psymonitor
278f6d1e53a4c1b7a5f9441e6e39440dd6903968
84029dc78224d495a3e880d26300403998f01a15
refs/heads/master
2020-04-07T00:21:08.173656
2019-03-20T06:00:03
2019-03-20T06:00:03
157,900,046
0
2
null
null
null
null
UTF-8
R
false
true
1,988
rd
cvPSYmc.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/cvPSYmc.R \name{cvPSYmc} \alias{cvPSYmc} \title{Simulate the finite sample critical values for the PSY test.} \usage{ cvPSYmc(obs, swindow0, IC = 0, adflag = 0, nrep = 199, multiplicity = TRUE, Tb, useParallel = TRUE, nCores) } \arguments{ \item{obs}{A positive integer. The number of observations.} \item{swindow0}{A positive integer. Minimum window size (default = \eqn{T (0.01 + 1.8/\sqrt{T})}, where \eqn{T} denotes the sample size)} \item{IC}{An integer. 0 for fixed lag order (default), 1 for AIC and 2 for BIC (default = 0).} \item{adflag}{An integer, lag order when IC=0; maximum number of lags when IC>0 (default = 0).} \item{nrep}{A positive integer. Number of replications (default = 199).} \item{multiplicity}{Logical. If \code{multiplicity=TRUE}, use family-wise size control in the recursive testing algorithms.} \item{Tb}{A positive integer. The simulated sample size (swindow0+ controlling). Ignored if \code{multiplicity=FALSE}.} \item{useParallel}{Logical. If \code{useParallel=TRUE}, use multi core computation.} \item{nCores}{A positive integer. Optional. If \code{useParallel=TRUE}, the number of cores defaults to all but one.} } \value{ A matrix. BSADF bootstrap critical value sequence at the 90, 95 and 99 percent level. } \description{ \code{cvPSYmc} implements the real time bubble detection procedure of Phillips, Shi and Yu (2015a,b) } \examples{ cv <- cvPSYmc(80, IC = 0, adflag = 1, Tb = 30, nrep = 99, nCores = 1) } \references{ Phillips, P. C. B., Shi, S., & Yu, J. (2015a). Testing for multiple bubbles: Historical episodes of exuberance and collapse in the S&P 500. \emph{International Economic Review}, 56(4), 1034--1078. Phillips, P. C. B., Shi, S., & Yu, J. (2015b). Testing for multiple bubbles: Limit Theory for Real-Time Detectors. \emph{International Economic Review}, 56(4), 1079--1134. }
c9bf9952577317033b8fc2a2cf2870425de3bf2d
d3c24352a2959a31ec0d452ca94fde270594e0c8
/R/fars_read.R
0a06cf89444ec3c73126fd78116b0a16a83d9dcd
[ "MIT" ]
permissive
tikizu/famove
9f80d92aa63b3c1673357b0b86a3d08de802fa0b
7cc44171079c148c2eb21a93499a5bc41661d6b2
refs/heads/master
2023-02-25T11:16:23.524967
2021-02-05T16:34:33
2021-02-05T16:34:33
330,194,970
0
0
null
null
null
null
UTF-8
R
false
false
419
r
fars_read.R
#' Read in a CSV file #' #' Create a tibble from CSV file #' #' @param filename as a character #' #' @return tibble #' #' @importFrom readr read_csv #' @importFrom dplyr as_tibble #' #' #' @export fars_read <- function(filename) { if(!file.exists(filename)) stop("file '", filename, "' does not exist") data <- suppressMessages({ readr::read_csv(filename, progress = FALSE) }) dplyr::as_tibble(data) }
0d82055558396388b16f8da1c9fc8f9db2be510c
72261129cc58ac0368b012eebfad8b9cb9b9a94b
/Data Cleaning for sales data in R.R
f07b2643504f7e1f9902a6a9df5b9fbe9b0bfe0e
[]
no_license
AifenW/Project-for-R
4192849996085489c40c75292cbd38286c8005ec
13c3bc02c6ef1f567d64b7ab0d4c19419249e395
refs/heads/master
2020-08-09T05:56:54.020905
2020-01-02T18:37:25
2020-01-02T18:37:25
214,014,510
0
0
null
null
null
null
UTF-8
R
false
false
4,859
r
Data Cleaning for sales data in R.R
# Import data install.packages("readxl") library(readxl) salesdata<-read_excel("~/Data Cleaning/salesdata.xlsx") # glimpse salesdata library(tidyverse) glimpse(salesdata) # subset salesdata which contain only 5 attributes install.packages("sqldf") library(sqldf) subset_salesdata<-sqldf(" select Customer, `Sales Order #`, Amount, Date, Email from salesdata ") nrow(subset_salesdata) #248996 length(unique(subset_salesdata$Customer)) #12172 # create new_salesdata1 which Amount>0 and not from O nointer_sd<-subset_salesdata %>% filter(!grepl("@o",Email))%>% filter(Amount>0) head(nointer_sd) nrow(nointer_sd) #235877 (Amount>0) 248331 (!@o) 235877 (both) length(unique(nointer_sd$Email)) #9814 length(unique(nointer_sd$Customer)) #12006 # split Customer into Account_ID and Customer_ID install.packages("stringi") library(stringi) bftrans_sd<-nointer_sd %>% mutate(Account_ID=lapply(strsplit(Customer, " "),function(n)n[[1]][1]), Customer_ID=lapply(lapply(strsplit(Customer, " "), function(x)x[-1]),paste, collapse=" "), Customer_ID=stri_trim(tolower(Customer_ID)) ) %>% rename(SalesOrder='Sales Order #') %>% select(-Customer) bftrans_sd<-bftrans_sd[,c("Account_ID","Customer_ID","SalesOrder","Amount", "Date", "Email")] glimpse(bftrans_sd) head(bftrans_sd) nrow(bftrans_sd) #235877 length(unique(bftrans_sd$Customer_ID)) #11535 # check bftrans_sd check<-bftrans_sd %>% filter(str_detect(Customer_ID,"univ")) check<-bftrans_sd %>% filter(str_detect(Customer_ID,":")) check<-bftrans_sd %>% filter(str_detect(Customer_ID,"-")) head(check) tail(check) # first cleaning of bftrans_sd which convert "university" in Customer_ID to "univ" install.packages("stringr") library(stringr) fclean_bftrans_sd<- bftrans_sd %>% mutate( Customer_ID=lapply(str_split(Customer_ID, "[:]"),function(n)n[[1]][1]), Customer_ID=str_trim(sub("university","univ",x=Customer_ID))) nrow(fclean_bftrans_sd) #235877 length(unique(fclean_bftrans_sd$Customer_ID)) #10879 head(fclean_bftrans_sd) class(fclean_bftrans_sd$Email) # Second time to clean fclean_bftrans_sd # produce a list of near matches for Customer_ID # create empty dataframe library(stringdist) df<-data.frame(Account_ID=character(),Salesorder=character(),Amount=double(),Date=as.Date(character()),Email=character(),LikelyGroup=integer(),Group_Customer_ID=character()) for (i in 0:floor(n/10000)) { n<-nrow(fclean_bftrans_sd) #235877 start=i*10000+1 end= (i+1)*10000 if(n>end) { lclean_bftrans_sd<-fclean_bftrans_sd[start:end,] }else{ lclean_bftrans_sd<-fclean_bftrans_sd[start:n,] } dist_Customer_ID <- stringdistmatrix(lclean_bftrans_sd$Customer_ID,lclean_bftrans_sd$Customer_ID,useNames="strings",method="jw",p=0.1) row.names(dist_Customer_ID)<-lclean_bftrans_sd$Customer_ID names(dist2_Customer_ID)<-lclean_bftrans_sd$Customer_ID dist_Customer_ID<-as.dist(dist_Customer_ID) #Hierarchical clustering to find closest clusts<-hclust(dist_Customer_ID,method="ward.D2") #Cut into appropriate clusters based upon height in the dendrogram lclean_bftrans_sd$LikelyGroup<-cutree(clusts,h=0.1) #Define "mode" function which only selects one mode even in bimodal cases. Mode <- function(x) { ux <- unique(x) ux[which.max(tabulate(match(x, ux)))] } #Select modal name for each group lclean_bftrans_sd<-lclean_bftrans_sd%>% group_by(LikelyGroup)%>% mutate(Group_Customer_ID=Mode(Customer_ID)) df=rbind(df,as.data.frame(lclean_bftrans_sd)) } nrow(df) #235877 length(unique(df$Customer_ID)) #10879 length(unique(df$Group_Customer_ID)) #10716 head(df) check<-df %>% filter(Customer_ID != Group_Customer_ID) head(check) tail(check) nrow(check) # 1336 length(unique(check$Customer_ID)) #534 length(unique(check$Group_Customer_ID)) #500 # final cleaned data ...........will be used for RFM analysis final_tran_sd<-df nrow(df) nrow(final_tran_sd) class(df) class(final_tran_sd) # data subset for Customer_ID is different from Group_Customer_ID diff_CustomerID<-final_tran_sd %>% filter(Customer_ID != Group_Customer_ID) nrow(diff_CustomerID) #1336 # export fntrans_sd for RFM analysis library(openxlsx) final_tran_sd<-openxlsx::write.xlsx(final_tran_sd, file="C:/Users/awang/Documents/2018-1-22/SAS_R/R/RLearning/RProject/Project 6 Origene sales data analysis/Data Cleaning/final_tran_sd.xlsx") diff_CustomerID<-openxlsx::write.xlsx(diff_CustomerID, file="C:/Users/awang/Documents/2018-1-22/SAS_R/R/RLearning/RProject/Project 6 Origene sales data analysis/Data Cleaning/diff_CustomerID.xlsx") install.packages("xlsx") library(xlsx) write.xlsx(df, file="C:/Users/awang/Documents/2018-1-22/SAS_R/R/RLearning/RProject/Project 6 Origene sales data analysis/Data Cleaning/final_tran_sd.xlsx")
5f60c8fd8cfa710a67ca60a3b984768c95c6cb3f
45ace96c2914c90eadca3f5b9e0c381b414a480b
/data-code/_BuildFinalData.R
a50ffec05a09a0959b235e91ff491f9dc1785f19
[]
no_license
subeniwal/Physician-Shared-Patients
3b855e633b6f8a02fe8c01a261d0398ac673bfd1
71644ae7e9682b71610347379d1cd5ddb17a6b29
refs/heads/master
2023-07-17T14:20:04.617460
2021-08-26T21:22:56
2021-08-26T21:22:56
null
0
0
null
null
null
null
UTF-8
R
false
false
2,538
r
_BuildFinalData.R
# Meta -------------------------------------------------------------------- ## Title: Physician Shared Patients Data ## Author: Ian McCarthy ## Date Created: 10/10/2019 ## Date Edited: 9/15/2020 # Preliminaries ----------------------------------------------------------- if (!require("pacman")) install.packages("pacman") pacman::p_load(tidyverse, ggplot2, dplyr, lubridate, stringr, igraph, network, sna, ggraph, visNetwork, threejs, networkD3, ndtv) ## set paths source("data-code/paths.R") ## Run initial code files #source("data-code/SharedPatientData.R") #source("data-code/PhysicianCompare.R") source("data-code/SharedPatientData_2010.R") source("data-code/PhysicianCompare_2013.R") # Networks ---------------------------------------------------------------- node.data <- nodes.2010 %>% filter(str_to_lower(city_1)=="atlanta" | str_to_lower(city_2)=="atlanta" | str_to_lower(city_3)=="atlanta" | str_to_lower(city_4)=="atlanta" | str_to_lower(city_5)=="atlanta") %>% left_join(PSPD.final.2010 %>% distinct(npi1) %>% mutate(pcp=1, npi1=as.numeric(npi1)), by=c("npi"="npi1")) %>% mutate(pcp=replace_na(pcp,0)) edge.data <- PSPD.final.2010 %>% mutate(npi1=as.numeric(npi1), npi2=as.numeric(npi2)) %>% filter(str_detect(desc_tax2,"Ortho")) %>% inner_join(node.data %>% distinct(npi), by=c("npi1"="npi")) %>% inner_join(node.data %>% distinct(npi), by=c("npi2"="npi")) %>% select(from=npi1, to=npi2, weight=paircount) # Small Networks ---------------------------------------------------------- large.pcps <- edge.data %>% group_by(from) %>% mutate(pcp_count=sum(weight)) %>% ungroup() %>% distinct(from, pcp_count) %>% arrange(-pcp_count) large.pcps <- head(large.pcps, 20) edge.small <- edge.data %>% inner_join(large.pcps %>% distinct(from), by="from") small.from <- edge.small %>% distinct(from) %>% mutate(npi=from) small.to <- edge.small %>% distinct(to) %>% mutate(npi=to) npi.small <- bind_rows(small.from, small.to) node.small <- node.data %>% inner_join(npi.small %>% distinct(npi), by="npi") # Save Data --------------------------------------------------------------- saveRDS(node.data, file="data/node_data.RData") saveRDS(edge.data, file="data/edge_data.RData") saveRDS(node.small, file="data/node_small.RData") saveRDS(edge.small, file="data/edge_small.RData") saveRDS(PSPD.final.2010, file="data/pspd_data.RData")
6d5f5dea55d6e8104b040499d75e4dd99ccd9dc3
18893292dc638efa94c92bb826a7aaa772fa7a52
/man/bnets.Rd
5a91c9cb550cc2ef745f555defaa2b76d1d5ba40
[]
no_license
rithwik/bnets
1da4218d50c999cb4ad321abd99dee6b431537cb
e4a747493ac0e81a72f259fca2671ec2519ecaec
refs/heads/master
2021-01-10T05:09:57.730354
2016-02-25T07:43:20
2016-02-25T07:43:20
52,260,662
0
0
null
null
null
null
UTF-8
R
false
true
332
rd
bnets.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/bnets.R \docType{package} \name{bnets} \alias{bnets} \alias{bnets-package} \title{bnets: A package to play with Bayesian Networks} \description{ bnets combines functionalities from bnlearn, visNetwork, and shiny to make interactive bayesian networks. }
67d27d1d1a504b869c2b729f2630fb22af4ebcc9
d1d1d4d7cf34ffac0c5c421c0f6fb3846ae97939
/Plot1.R
b0f70eb72c35ac73d4b3a2676207a7aa9fef3d55
[]
no_license
vallvi/ExData_Plotting1
afed4f4d500d51c6bb5a92ead71068e9e02e8f72
2b887b11cc6b21e7a82349e71d41cd646d2bc8d7
refs/heads/master
2021-01-17T19:57:01.605608
2014-12-07T01:14:03
2014-12-07T01:14:03
null
0
0
null
null
null
null
UTF-8
R
false
false
613
r
Plot1.R
file <- read.table("household_power_consumption.txt",sep=";",header=T,colClasses=c("character","character","numeric","numeric","numeric","numeric","numeric","numeric","numeric"),na.strings="?") file1 <- file[file$Date=="1/2/2007",] file2 <- file[file$Date=="2/2/2007",] powdata <- rbind(file1,file2) powdata$DateTime <- strptime(paste(powdata$Date,powdata$Time),format="%d/%m/%Y %H:%M:%S") powdata$Date <- as.Date(powdata$Date,format="%d/%m/%Y") hist(powdata[,3],col="red",main="Global Active Power",xlab="Global Active Power (kilowatts)",ylab="Frequency",ylim=c(0,1200)) dev.copy(png,file="Plot1.png") dev.off()
6788d9ac3ea2eb14d153f6c051c967e29c90137a
677962a3141a34254a91e6c7ea7855695340e89e
/Bo-Chen-Code/3-1.R
c2f2944f8f43b7a5dbdd0192f1564aa3b99dbf8f
[]
no_license
YuCheng21/nkust-data-science
2f70f9eb007dac1b6ee9c5d556922afc4fbbbaba
c10812007fdec27e8cccf03b26f868964ebda1ea
refs/heads/master
2023-06-02T01:36:35.474870
2021-06-24T19:05:06
2021-06-24T19:05:06
346,954,244
0
0
null
null
null
null
UTF-8
R
false
false
124
r
3-1.R
a <- 1:9 b <- 1:9 for(i in a){ for(j in b){ x <- sprintf("%d * %d = %d",i,j,i*j) print(x) } }
58f9437c8babe12a97949dd1275726f8146bcab1
52b818cfc1d707cbc08e3d54b5db9bce828b83d2
/script.R
30c4dfc2025d1859d8475696c8ee4c067c2e1199
[]
no_license
julianpsd/SICSS2020
283a8ab1eff2d8ac157ad7e14c70062f4d3d501f
bea4d3b569779fe8bd3dc71b80a9c926dfcb763b
refs/heads/master
2023-07-18T22:24:27.284806
2021-09-18T19:35:37
2021-09-18T19:35:37
276,173,588
1
1
null
null
null
null
UTF-8
R
false
false
20,867
r
script.R
## COVID 19 Sentiment analysis #packages library(dplyr) library(ggplot2) library(tidyr) library(sjmisc) library(psych) library(MASS) library(reshape2) library(reshape) library(ggpubr) library(topicmodels) library(tm) library(tidytext) library(dplyr) library(SnowballC) library(lubridate) library(wordcloud2) library(wordcloud) library(syuzhet) library(scales) SICSS_Montreal <- read.csv("rehydrated_COVID_TweetIDs_MarchAprilMay_1Perc.csv",stringsAsFactors=FALSE) #Clean dataset: untoken the text SICSS_Mont <- SICSS_Montreal %>% filter(lang=="en", grepl('Canada', user_location))%>% unnest_tokens(word,text)%>% anti_join(stop_words)%>% filter(!(word=="https"| word=="rt"| word=="t.co"| word=="amp" | word== "3"| word== "19"| word=="2"| word=="1"| word== "coronavirus"| word=="covid"| word=="covid19"| word=="it’s"| word=="i'm")) SICSS_Mont %>% count(word, sort = TRUE) %>% filter(n > 100) %>% mutate(word = reorder(word, n)) %>% ggplot(aes(word, n)) + geom_col() + xlab(NULL) + coord_flip() ``` ## Topic Modelling ```{r warning=FALSE} #Version 1 # Load data Tweets_topic <- read.csv("rehydrated_COVID_TweetIDs_MarchAprilMay_1Perc.csv",stringsAsFactors=FALSE) # Pull the tweet text Tweets_sec <- Tweets_topic %>% filter(lang=="en", grepl('Canada', user_location)) %>% pull(text) # Create a corpus of tweets for a Document-Term Matrix corpus <- Corpus(VectorSource(Tweets_sec)) corpus <- tm_map(corpus, tolower) corpus <- tm_map(corpus, removePunctuation) corpus <- tm_map(corpus, removeWords, c("rt", "https", "t.co", stopwords("english"))) corpus <- tm_map(corpus, stemDocument) # Create the Document Term Matrix DTM <- DocumentTermMatrix(corpus) # OPTIONAL: we can delete the less frequent terms, for this, change "DTM" below for "sparse_DTM" #frequent_ge_20 <- findFreqTerms(DTM, lowfreq = 20) #sparse_DTM <- removeSparseTerms(DTM, 0.995) # Group the terms by topic # OPTIONAL: we can change the "k" variable velow to set the number of topics. For now it's set at 6 tweet_lda <- LDA(DTM, k = 4, control = list(seed = 1234)) # Extract the "per topic per word" probabilities of a topic ("beta") tweet_topics <- tidy(tweet_lda, matrix = "beta") # Select the top terms per topic tweet_top_terms <- tweet_topics %>% group_by(topic) %>% top_n(10, beta) %>% ungroup() %>% arrange(topic, -beta) # Plot the different topics and the top words tweet_top_terms %>% mutate(term = reorder_within(term, beta, topic)) %>% ggplot(aes(term, beta, fill = factor(topic))) + geom_col(show.legend = FALSE) + facet_wrap(~ topic, scales = "free") + coord_flip() + scale_x_reordered() #Version 2 tidy_dtm <- SICSS_Mont %>% filter(!(word=="https"| word=="rt"| word=="t.co"| word=="amp")) %>% count(word) %>% cast_dtm(word, word, n) tweet_topic_model<-LDA(tidy_dtm , k=4, control = list(seed = 321)) topics <- tidy(tweet_topic_model, matrix = "beta") top_terms1 <- topics %>% group_by(topic) %>% top_n(10, beta) %>% ungroup() %>% arrange(topic, -beta) top_terms1 %>% mutate(term = reorder_within(term, beta, topic)) %>% ggplot(aes(term, beta, fill = factor(topic))) + geom_col(show.legend = FALSE) + facet_wrap(~ topic, scales = "free") + coord_flip() + scale_x_reordered() #Sentiment analysis (Matt’s version) Tweets_topic <- read.csv("rehydrated_COVID_TweetIDs_MarchAprilMay_1Perc.csv",stringsAsFactors=FALSE) ################ ## Filter the tweets ################ library(plyr) ## Select only the English Canadian tweets Tweets_filtered<- Tweets_topic %>% filter(lang=="en", grepl("canada", ignore.case = TRUE, user_location)) ## Select only tweets that mention Canada Tweets_canada<- Tweets_filtered %>% filter(grepl("canad.*", ignore.case = TRUE, text)) ## Select only tweets that mention Trudeau Tweets_trudeau<- Tweets_filtered %>% filter(grepl("trudeau", ignore.case = TRUE, text)) ## Join the datasets Tweets_about_canada <- full_join(Tweets_canada, Tweets_trudeau) ## Rename dataset back to filtered (to work with legacy code below) Tweets_filtered <- Tweets_about_canada ## Select only tweets that mention America, US, Trump ################ ## Clean the filtered tweets ################ ## Create a new dataset based on the filtered tweets Tweets_tidy<-Tweets_filtered %>% dplyr::select(created_at,text)%>% unnest_tokens("word", text) #removing stop words data("stop_words") Tweets_tidy_rmstop <-Tweets_tidy %>% anti_join(stop_words) ## Remove numbers Tweets_tidy_rmstop<-Tweets_tidy_rmstop[-grep("\\b\\d+\\b", Tweets_tidy_rmstop$word),] ## Remove white spaces Tweets_tidy_rmstop$word <- gsub("\\s+","",Tweets_tidy_rmstop$word) #Stemming Tweets_tidy_rmstop %>% mutate_at("word", funs(wordStem((.), language = "en"))) #removal of twitter-specific language detach(package:plyr) top_words<- Tweets_tidy_rmstop %>% #anti_join(stop_words) %>% filter(!(word=="https"| word=="rt"| word=="t.co"| word=="amp")) %>% count(word) %>% arrange(desc(n)) # top_words %>% # ggplot(aes(x=reorder(word, -n), y=n, fill=word))+ # geom_bar(stat="identity")+ # theme_minimal()+ # theme(axis.text.x = # element_text(angle = 60, hjust = 1, size=13))+ # theme(plot.title = # element_text(hjust = 0.5, size=18))+ # ylab("Frequency")+ # xlab("")+ # ggtitle("Most Frequent Words in Tweets")+ # guides(fill=FALSE)+ # coord_flip() #sentiment analysis using dictionary Tweet_sentiment <- top_words %>% filter(!(word=="https"| word=="rt"| word=="t.co"| word=="amp")) %>% inner_join(get_sentiments("bing")) %>% count(sentiment) ## Plot by date ## Wrangle the date format # Tweets_tidy_rmstop$date<-as.Date(Tweets_tidy_rmstop$created_at, # format="%b %d %x %x %Y") Tweets_tidy_rmstop$createdClean<-paste(substr(Tweets_tidy_rmstop$created_at,5,10),"2020") ## Create new column with standard date format ## https://www.r-bloggers.com/date-formats-in-r/ Tweets_tidy_rmstop$date<-as.Date(Tweets_tidy_rmstop$createdClean, format="%b %d %Y") ## Plot negative sentiment by date # Tweet_sentiment_plot <- # Tweets_tidy_rmstop %>% # inner_join(get_sentiments("bing")) %>% # filter(sentiment=="negative") %>% # count(date, sentiment) ## Get a count of how many tweets per day words_perDay <- Tweets_tidy_rmstop %>% dplyr::count(date) words_perDay <- words_perDay %>% dplyr::rename("n_words" = n) ## Aggregate positive and negative sentiment by tweet # Aggregate by negative sentiment sentiment_negative <- Tweets_tidy_rmstop %>% inner_join(get_sentiments("bing")) %>% filter(sentiment=="negative") %>% count(date, sentiment) # Rename the new column sentiment_negative <- sentiment_negative %>% dplyr::rename(n_negative = n) ## Aggregate by positive sentiment ## Aggregate positive and negative sentiment by tweet sentiment_positive <- Tweets_tidy_rmstop %>% inner_join(get_sentiments("bing")) %>% filter(sentiment=="positive") %>% count(date, sentiment) sentiment_positive <- sentiment_positive %>% dplyr::rename(n_positive = n) ## Join the two datasets to get both positive and negative sentiment, and words per day sentiment_both <- full_join(sentiment_negative, sentiment_positive, by="date") sentiment_both <- full_join(sentiment_both, words_perDay, by="date") ## Replace missing values with 0 sentiment_both$n_negative <- ifelse(is.na(sentiment_both$n_negative),0,sentiment_both$n_negative) sentiment_both$n_positive <- ifelse(is.na(sentiment_both$n_positive),0,sentiment_both$n_positive) ## Create some derived variables sentiment_both$ratioPosNeg = sentiment_both$n_positive/sentiment_both$n_negative sentiment_both$ratioPosPerWord = sentiment_both$n_positive/sentiment_both$n_words sentiment_both$ratioNegPerWord = sentiment_both$n_negative/sentiment_both$n_words ## Create a new variable that keeps track of the week sentiment_both$week <- week(sentiment_both$date) ## Summarize the tweets by week sentiment_byWeek <- sentiment_both %>% group_by(week) %>% summarize(n_positive = sum(n_positive), n_negative = sum(n_negative), n_words = sum(n_words)) ## Create some derived variables sentiment_byWeek$ratioPosNeg = sentiment_byWeek$n_positive/sentiment_byWeek$n_negative sentiment_byWeek$ratioPosPerWord = sentiment_byWeek$n_positive/sentiment_byWeek$n_words sentiment_byWeek$ratioNegPerWord = sentiment_byWeek$n_negative/sentiment_byWeek$n_words ################## ## Save the datasets ################## # write.csv(sentiment_byWeek, # "~/Documents/GitHub/SICSS_2020/sentiment_aboutCanada_byWeek.csv") ``` ```{r warning=FALSE} ################## ## Plot the results ################## sentiment_byWeek <- readr::read_csv("sentiment_aboutCanada_byWeek.csv") ## Number of words ggplot(sentiment_both, aes(x=date)) + geom_line(aes(y = n_negative), color = "red") + geom_line(aes(y = n_positive), color="blue") + # geom_line(aes(y = n_words), color="black") + theme_minimal()+ theme(axis.text.x = element_text(angle = 60, hjust = 1, size=13))+ theme(plot.title = element_text(hjust = 0.5, size=18))+ ylab("Number of Words")+ xlab("")+ ggtitle("Sentiment in Tweets")+ theme(aspect.ratio=1/4) ## Plot the results ## Ratio of positive / negative sentiment per word ggplot(sentiment_both, aes(x=date)) + scale_x_date(date_breaks = "1 week", date_minor_breaks = "2 day") + #scale_x_date(date_minor_breaks = "2 day") + #geom_line(aes(y = ratioNegPerWord), color = "red") + #geom_line(aes(y = ratioPosPerWord), color="blue") + geom_line(aes(y = ratioPosNeg), color="black") + theme_minimal()+ theme(axis.text.x = element_text(angle = 60, hjust = 1, size=13))+ theme(plot.title = element_text(hjust = 0.5, size=18))+ ylab("Ratio of Positive/Negative Sentiment per total Words")+ xlab("")+ ggtitle("Sentiment in Tweets")+ theme(aspect.ratio=1/4) # ggplot(Tweet_sentiment_plot, aes(x=date, y=n))+ # geom_line(color="red", size=.5)+ # theme_minimal()+ # theme(axis.text.x = # element_text(angle = 60, hjust = 1, size=13))+ # theme(plot.title = # element_text(hjust = 0.5, size=18))+ # ylab("Number of Negative Words")+ # xlab("")+ # ggtitle("Negative Sentiment in Tweets")+ # theme(aspect.ratio=1/4) survey_weekly <- readr::read_csv("SURVEY_LABOR_WEEKLY.csv") ## Convert the start date column to a date survey_weekly$date <- as.Date(survey_weekly$Survey_Date_Start) ## Calculate the % satisfied with measures overall survey_weekly$satMeas_overall <- survey_weekly$SATMEAS_SS + survey_weekly$SATMEAS_VS ## Calculate the % fearful overall survey_weekly$fear_overall <- survey_weekly$FEAR_V + survey_weekly$FEAR_SW ## Note: $FEAR_AL = already contracted the virus ## Drop the first row survey_weekly <- survey_weekly[-c(1), ] # Add in the correct country data survey_weekly$Country <- "Canada" ## Wrangle the dates into weeks survey_weekly_tidy <- survey_weekly survey_weekly_tidy$week <- week(survey_weekly_tidy$date) ################## ## Correlations ################## ## Join the sentiment and survey data by week sentiment_with_survey <- full_join(sentiment_byWeek, survey_weekly_tidy, by="week") ## See if there is a correlation between sentiment and % satisfied cor.test(sentiment_with_survey$ratioPosNeg, sentiment_with_survey$satMeas_overall, method = "spearman" ) ## See if there is a correlation between positive sentiment and sat overall cor.test(sentiment_with_survey$ratioPosPerWord, sentiment_with_survey$satMeas_overall, method = "spearman" ) ## See if there is a correlation between negative sentiment and sat overall cor.test(sentiment_with_survey$ratioNegPerWord, sentiment_with_survey$satMeas_overall, method = "spearman" ) ## See if there is a correlation between positive sentiment and % fearful cor.test(sentiment_with_survey$ratioPosPerWord, sentiment_with_survey$fear_overall, method = "spearman" ) library(readxl) SURVEY_LABOR_CAN <- read_excel("SURVEY_LABOR_CAN.xlsx", sheet = "Feuil1") #View(SURVEY_LABOR_CAN) sentiment_with_survey <- full_join(sentiment_byWeek, SURVEY_LABOR_CAN, by="week") ## See if there is a correlation tweets sentiment and Proportion of respondents that already exposed to covid cor.test(sentiment_with_survey$ratioPosNeg, sentiment_with_survey$FEAR_AL, method = "spearman" ) ## See if there is a correlation tweets sentiment and Proportion that think we are in the worst of the pandemic now cor.test(sentiment_with_survey$ratioPosNeg, sentiment_with_survey$EVL_WN, method = "spearman" ) ## See if there is a correlation tweets sentiment and Proportion that approve provincial measures cor.test(sentiment_with_survey$ratioPosNeg, sentiment_with_survey$SATMEAS_PR, method = "spearman" ) ## See if there is a correlation tweets sentiment and Proportion that do not commit to measures cor.test(sentiment_with_survey$ratioPosNeg, sentiment_with_survey$NCOMM, method = "spearman" ) ## See if there is a correlation tweets sentiment and Proportion that think the threat is blown out of proportion cor.test(sentiment_with_survey$ratioPosNeg, sentiment_with_survey$THR_OP, method = "spearman" ) ## Plot the results ## By week ## Ratio of positive / negative sentiment per word ggplot(sentiment_with_survey, aes(x=week)) + #scale_x_date(date_breaks = "1 week", date_minor_breaks = "2 day") + geom_line(aes(y = ratioPosNeg), color="black") + geom_line(aes(y = SATMEAS_S), color="blue") + geom_line(aes(y = FEAR_NS), color="red") + #geom_line(aes(y = FEAR_AL), color="green") #geom_line(aes(y = EVL_WN), color="green") #geom_line(aes(y = SATMEAS_PR), color="green") #geom_line(aes(y = NCOMM), color="green") theme_minimal()+ theme(axis.text.x = element_text(angle = 60, hjust = 1, size=13))+ theme(plot.title = element_text(hjust = 0.5, size=18))+ ylab("Ratio of Positive/Negative Sentiment per total Words")+ xlab("")+ ggtitle("Sentiment in Tweets")+ theme(aspect.ratio=1/4) ######### ## Read the coronavirus data ######## library(readxl) covid_canada <- read_excel("Public_COVID-19_Canada.xlsx", skip = 3) ###### ## Optionally read the other datasets (if not already in memory) ###### #sentiment_both <- read_csv("~/Documents/GitHub/SICSS_2020/sentiment_aboutCanada_byDay.csv") #sentiment_byWeek <- read_csv("~/Documents/GitHub/SICSS_2020/sentiment_aboutCanada_byWeek.csv") #survey_weekly <- read_csv("~/Documents/GitHub/SICSS_2020/survey_weekly_tidy_canada") ########## ## Wrangle dates ######### covid_canada$date <- as.Date(covid_canada$date_report) covid_canada$week <- week(covid_canada$date) ## Create dataframe of cases per day casesPerDay <- covid_canada %>% count(date) casesPerDay <- casesPerDay %>% dplyr::rename(n_cases = n) ## Join the sentiment data per day with the casesPerDay dataframe sentiment_both <- full_join(sentiment_both, casesPerDay, by="date") ## scale the cases per day such that it is between 0 and 1 (/max) #sentiment_both$casesScaled <- sentiment_both$n_cases/max(sentiment_both$n_cases,na.rm = TRUE) ## Plot the result ## Number of words and cases #ggplot(sentiment_both, aes(x=date)) + # geom_line(aes(y = n_negative), color = "red") + #geom_line(aes(y = n_positive), color="blue") + # geom_line(aes(y = n_words), color="black") # theme_minimal()+ #theme(axis.text.x = # element_text(angle = 60, hjust = 1, size=13))+ #theme(plot.title = # element_text(hjust = 0.5, size=18))+ #ylab("Number of Words")+ #xlab("")+ #ggtitle("Sentiment in Tweets")+ #theme(aspect.ratio=1/4) ## Ratio of positivity and scaled cases ggplot(sentiment_both, aes(x=date)) + # geom_line(aes(y = n_negative), color = "red") + # geom_line(aes(y = n_positive), color="blue") + geom_line(aes(y = ratioPosNeg), color="black") + geom_line(aes(y = casesScaled), color = "green") + theme_minimal()+ theme(axis.text.x = element_text(angle = 60, hjust = 1, size=13))+ theme(plot.title = element_text(hjust = 0.5, size=18))+ ylab("Number of Words")+ xlab("")+ ggtitle("Sentiment in Tweets")+ theme(aspect.ratio=1/4) ## See if there is a correlation between sickness and positivity cor.test(sentiment_both$ratioPosNeg,sentiment_both$casesScaled, method = "spearman") ############ ## Create dataframe of cases per week ############ casesPerWeek <- covid_canada %>% count(week) casesPerWeek <- casesPerWeek %>% dplyr::rename(n_cases = n) ## Join the sentiment data per week with the casesPerWeek dataframe sentiment_with_cases <- full_join(sentiment_byWeek, casesPerWeek, by="week") ## Join the survey data #sentiment_with_cases_survey <- full_join(sentiment_with_cases, survey_weekly, by="week") ## Scale the cases between 0 and 1 (/max) sentiment_with_cases_survey$casesScaled <- sentiment_with_cases_survey$n_cases / max(sentiment_with_cases_survey$n_cases,na.rm = TRUE) ############## ### Save the dataset ############# #write.csv(sentiment_with_cases_survey, # "~/Documents/GitHub/SICSS_2020/sentiment_cases_survey_weekly_Canada.csv") ``` ```{r warning=FALSE} ############## ## Final analyses (after all wrangling is done) ############## ## Load the dataset library(readr) sentiment_with_cases_survey <- read_csv("sentiment_cases_survey_weekly_Canada.csv") ############### ## Plot the results ############### library(ggplot2) ## Ratio of positivity and scaled cases ggplot(sentiment_with_cases_survey, aes(x=week)) + geom_line(aes(y = fear_overall), color = "red") + geom_line(aes(y = satMeas_overall), color="blue") + geom_line(aes(y = ratioPosNeg), color="black") + geom_line(aes(y = casesScaled), color = "green") + theme_minimal()+ theme(axis.text.x = element_text(angle = 60, hjust = 1, size=13))+ theme(plot.title = element_text(hjust = 0.5, size=18))+ ylab("Number of Words")+ xlab("")+ ggtitle("Sentiment in Tweets")+ theme(aspect.ratio=1/4) ## See if there is a correlation between positivity and survey approval cor.test(sentiment_with_cases_survey$ratioPosNeg, sentiment_with_cases_survey$satMeas_overall, method = "spearman", na.action = "na.exclude") ## See if there is a correlation between cases and positive sentiment cor.test(sentiment_with_cases_survey$ratioPosNeg, sentiment_with_cases_survey$casesScaled, method = "spearman", na.action = "na.exclude") ## See if there is a correlation between cases and fear cor.test(sentiment_with_cases_survey$fear_overall, sentiment_with_cases_survey$casesScaled, method = "spearman", na.action = "na.exclude") ``` ```{r warning=FALSE} ############## ## Final analyses (after all wrangling is done) ############## ## Load the dataset library(readr) sentiment_with_cases_survey <- read_csv("sentiment_cases_survey_weekly_Canada.csv") ############### ## Plot the results ############### library(ggplot2) ## Ratio of positivity and scaled cases ggplot(sentiment_with_cases_survey, aes(x=week)) + geom_line(aes(y = fear_overall), color = "red") + geom_line(aes(y = satMeas_overall), color="blue") + geom_line(aes(y = ratioPosNeg), color="black") + geom_line(aes(y = casesScaled), color = "green") + theme_minimal()+ theme(axis.text.x = element_text(angle = 60, hjust = 1, size=13))+ theme(plot.title = element_text(hjust = 0.5, size=18))+ ylab("Number of Words")+ xlab("")+ ggtitle("Sentiment in Tweets")+ theme(aspect.ratio=1/4) ## See if there is a correlation between positivity and survey approval cor.test(sentiment_with_cases_survey$ratioPosNeg, sentiment_with_cases_survey$satMeas_overall, method = "spearman", na.action = "na.exclude") ## See if there is a correlation between cases and positive sentiment cor.test(sentiment_with_cases_survey$ratioPosNeg, sentiment_with_cases_survey$casesScaled, method = "spearman", na.action = "na.exclude") ## See if there is a correlation between cases and fear cor.test(sentiment_with_cases_survey$fear_overall, sentiment_with_cases_survey$casesScaled, method = "spearman", na.action = "na.exclude")
f49fb0f94b8faac9b3804c1d6872c2aad9835712
b57e31db43d7218962fd36d2f5281e0efd8aad24
/man/batch.Rd
42bd2644d62827a427fea8a4553bdea14b337db3
[]
no_license
cran/cyclestreets
69e6bd64bb5b9e4dd72f649252c5f0637acb8ff9
3215e5321a9fe79cb8d7449f1dd884a44e4edac3
refs/heads/master
2023-09-01T05:50:11.581440
2023-08-15T07:20:14
2023-08-15T08:31:03
131,992,217
0
0
null
null
null
null
UTF-8
R
false
true
4,550
rd
batch.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/batch.R \name{batch} \alias{batch} \title{Interface to CycleStreets Batch Routing API} \usage{ batch( desire_lines = NULL, id = NULL, directory = tempdir(), wait = FALSE, wait_time = NULL, name = "Batch job", serverId = 21, strategies = "quietest", bothDirections = 0, minDistance = 50, maxDistance = 5000, filename = "test", includeJsonOutput = 1, emailOnCompletion = "you@example.com", username = Sys.getenv("CYCLESTREETS_UN"), password = Sys.getenv("CYCLESTREETS_PW"), base_url = "https://api.cyclestreets.net/v2/batchroutes.createjob", pat = Sys.getenv("CYCLESTREETS_BATCH"), silent = TRUE, delete_job = TRUE, cols_to_keep = c("id", "name", "provisionName", "distances", "time", "quietness", "gradient_smooth"), segments = TRUE ) } \arguments{ \item{desire_lines}{Geographic desire lines representing origin-destination data} \item{id}{int Batch job ID, as returned from batchroutes.createjob. action string (start|pause|continue|terminate) Action to take. Available actions are: start: Start (open) job pause: Pause job continue: Continue (re-open) job terminate: Terminate job and delete data} \item{directory}{Where to save the data? \code{tempdir()} by default} \item{wait}{Should the process block your R session but return a route? FALSE by default.} \item{wait_time}{How long to wait before getting the data in seconds? NULL by default, meaning it will be calculated by the private function \code{wait_s()}.} \item{name}{The name of the batch routing job for CycleStreets} \item{serverId}{The server ID to use (21 by default)} \item{strategies}{Route plan types, e.g. \code{"fastest"}} \item{bothDirections}{int (1|0) Whether to plan in both directions, i.e. A-B as well as B-A. 0, meaning only one way routes, is the default in the R default.} \item{minDistance}{Min Euclidean distance of routes to be calculated} \item{maxDistance}{Maximum Euclidean distance of routes to be calculated} \item{filename}{Character string} \item{includeJsonOutput}{int (1|0) Whether to include a column in the resulting CSV data giving the full JSON output from the API, rather than just summary information like distance and time.} \item{emailOnCompletion}{Email on completion?} \item{username}{string Your CycleStreets account username. In due course this will be replaced with an OAuth token.} \item{password}{string Your CycleStreets account password. You can set it with Sys.setenv(CYCLESTREETS_PW="xxxxxx")} \item{base_url}{The base url from which to construct API requests (with default set to main server)} \item{pat}{The API key used. By default this uses \code{Sys.getenv("CYCLESTREETS")}.} \item{silent}{Logical (default is FALSE). TRUE hides request sent.} \item{delete_job}{Delete the job? TRUE by default to avoid clogged servers} \item{cols_to_keep}{Columns to return in output sf object} \item{segments}{logical, return segments TRUE/FALSE/"both"} } \description{ Note: set \code{CYCLESTREETS_BATCH}, \code{CYCLESTREETS_PW} and \code{CYCLESTREETS_PW} environment variables, e.g. with \code{usethis::edit_r_environ()} before trying this. } \details{ See https://www.cyclestreets.net/journey/batch/ for web UI. Recommneded max batch size: 300k routes } \examples{ if(FALSE) { library(sf) desire_lines = od::od_to_sf(od::od_data_df, od::od_data_zones)[4:5, 1:3] u = paste0("https://github.com/cyclestreets/cyclestreets-r/", "releases/download/v0.5.3/od-longford-10-test.Rds") desire_lines = readRDS(url(u)) routes_id = batch(desire_lines, username = "robinlovelace", wait = FALSE) # Wait for some time, around a minute or 2 routes_wait = batch(id = routes_id, username = "robinlovelace", wait = TRUE, delete_job = FALSE) names(routes_wait) plot(routes_wait) plot(desire_lines$geometry[4]) plot(routes_wait$geometry[routes_wait$route_number == "4"], add = TRUE) head(routes_wait$route_number) unique(routes_wait$route_number) # Job is deleted after this command: routes_attrib = batch(desire_lines, id = routes_id, username = "robinlovelace", wait = TRUE) names(routes_attrib) unique(routes_attrib$route_number) desire_lines_huge = desire_lines[sample(nrow(desire_lines), 250000, replace = TRUE), ] routes_id = batch(desire_lines_huge, username = "robinlovelace", wait = FALSE) names(routes) plot(routes$geometry) plot(desire_lines$geometry, add = TRUE, col = "red") routes = batch(desire_lines, username = "robinlovelace", wait_time = 5) # profvis::profvis(batch_read("test-data.csv.gz")) } }
e8ea6829110c92a66dc5d188c42ab240bcb00306
fd570307c637f9101ab25a223356ec32dacbff0a
/src-local/specpr/src.specpr/fcn43-47/zfeat.r
2a09420502fc810514f642a9fa36353683f4d3e8
[]
no_license
ns-bak/tetracorder-tutorial
3ab4dd14950eff0d63429291c648820fb14bb4cb
fd07c008100f6021c293ce3c1f69584cc35de98a
refs/heads/master
2022-07-30T06:04:07.138507
2021-01-03T22:19:09
2021-01-03T22:49:48
null
0
0
null
null
null
null
UTF-8
R
false
false
2,298
r
zfeat.r
subroutine zfeat(dataa,datab,datac,data,jdat,number,itnum,anadat,y) implicit integer*4 (i-q) #ccc name: zfeat #ccc version date: June 30, 1987 #ccc author(s): Noel Gorelick #ccc language: RATFOR #ccc #ccc short description: Finds continuum points for feature analysis #ccc and calls zstuf to do the dirty work #ccc #ccc algorithm description: #ccc system requirements: #ccc subroutines called: #ccc argument list description: #ccc parameter description: #ccc common description: #ccc message files referenced: #ccc internal variables: #ccc file description: #ccc user command lines: #ccc update information: #ccc NOTES: #ccc # RED Declared ilast to ensure integer*4 vs default of real*4 for undeclared integer*4 ilast integer*4 itnum,number,y,z,ilow real*4 center,width,depth,asym,contum,fract,anadat(4864),low,error real*4 dataa(number),datab(number),datac(number), data(number),jdat(number),ewidth #RED Initialize ilast to number ilast=number 1 do i=1,number { if (datac(i)==-1.23e34 | dataa(i)==-1.23e34) next if (datac(i)==1.0) { ilast=i go to 2 } } 2 if (ilast==number) return if (y+9 > 4855) return # will overflow 4864 limit do i=ilast+1,number { if (datac(i)==-1.23e34 | dataa(i)==-1.23e34) next if (datac(i)!=1.0) { go to 3 } else { ilast=i go to 2 } } 3 do j=i,number { if (datac(j)==1.0) { inext=j go to 4 } } return 4 if (inext-ilast==2) { error=(data(ilast)+data(inext))/2+data(ilast+1) if (1.0-datac(ilast+1)>2*error) { ilow=ilast+1 go to 10 } else { ilast=inext go to 2 } } low=1.0e25 do k=ilast,inext { if (datac(k)==-1.23e34 | dataa(k)==-1.23e34) next if (datac(k)<low) { low=datac(k) ilow=k } } error=(data(ilast)+data(inext))/2+data(ilow) if (1.0-datac(ilow)>error) { go to 10 } else { ilast=inext go to 2 } # -------- 10 call zstuf(dataa(ilast),datab(ilast),datac(ilast),jdat(ilast), inext-ilast+1,center,depth,width,asym,contum,fract, ilow-ilast+1,ewidth) # write (6,*) 'ewidth',ewidth # ----------- # put in data # ----------- anadat(y+1)=center anadat(y+2)=width anadat(y+3)=depth anadat(y+4)=error/2 anadat(y+5)=asym anadat(y+6)=contum anadat(y+7)=itnum anadat(y+8)=fract anadat(y+9)=ewidth y=y+9 ilast=inext go to 2 end
ec1eea736982042c66fa9669254cf77363a3b622
573f8339b51f5df74e09bfbed6ef0ccec15cb7b0
/analyses/DGE.R
a4da0e6759f2eb59c053ed060a2f0cbf809e1135
[]
no_license
eastmallingresearch/RNA-seq_pipeline
c40b0e62fbac468f823e0a86a7f83c7676fd5acf
edc4db511e17d7c7d364105138f071439cdbdfda
refs/heads/master
2022-08-09T22:34:49.319136
2022-08-03T14:03:24
2022-08-03T14:03:24
101,886,286
0
1
null
null
null
null
UTF-8
R
false
false
9,467
r
DGE.R
#=============================================================================== # Load libraries #=============================================================================== library(DESeq2) library("BiocParallel") register(MulticoreParam(12)) library(ggplot2) library(Biostrings) library(data.table) library(dplyr) library(naturalsort) library(tibble) library(devtools) install_github("eastmallingresearch/Metabarcoding_pipeline/scripts") # RUN ONCE library(metafuncs) # contains some useful plotting function e.g. plotOrd #=============================================================================== # Load data from fetureCounts #=============================================================================== # load tables into a list of data tables - "." should point to counts directory, e.g. "counts/." # depending on how your count files are named and stored (in subdirectories or not) the .*txt$ regex and recursive flag may need editing # the example below assumes all count files have file names ending in .txt and are all in a single folder (featureCounts standard) qq <- lapply(list.files(".",".*txt$",full.names=T,recursive=F),function(x) fread(x)) # rename the sample columns (7th column in a feature counts table, saved as the path to the BAM file) # in the below I'm saving the 8th ([[1]][8]) path depth (which was the informative folder name containg the BAM file) invisible(lapply(seq(1:length(qq)), function(i) colnames(qq[[i]])[7]<<-strsplit(colnames(qq[[i]])[7],"\\/")[[1]][8])) # merge the list of data tables into a single data table m <- Reduce(function(...) merge(..., all = T,by=c("Geneid","Chr","Start","End","Strand","Length")), qq) # output "countData" # write.table(m[,c(1,7:(ncol(m))),with=F],"countData",sep="\t",na="",quote=F,row.names=F) # output gene details write.table(m[,1:6,with=F],"genes.txt",sep="\t",quote=F,row.names=F) # Get counts from m countData <- data.frame(m[,c(7:length(m)),with=F],row.names=m$Geneid) #=============================================================================== # Load data from SALMON quasi mapping #=============================================================================== library(tximport) library(rjson) library(readr) # import transcript to gene mapping info tx2gene <- read.table("trans2gene.txt",header=T,sep="\t") # import quantification files # txi.reps <- tximport(list.files(".","quant.sf",full.names=T,recursive=T),type="salmon",tx2gene=tx2gene,txOut=T) # ...change of plan (it's easier to use list.dirs) though the below is very cool so I've left it here # mysamples <- rapply(strsplit(list.files(".","quant.sf",full.names=T,recursive=T),"\\/"), f=`[[`, ...=2, how="unlist") # import quantification files - will not work if any additional directories are in the specified path txi.reps <- tximport(paste(list.dirs(".",full.names=T,recursive=F),"/quant.sf",sep=""),type="salmon",tx2gene=tx2gene,txOut=T) # get the sample names from the folders mysamples <- list.dirs(".",full.names=F,recursive=F) # summarise to gene level (this can be done in the tximport step, but is easier to understand in two steps) txi.genes <- summarizeToGene(txi.reps,tx2gene) # set the sample names for txi.genes invisible(sapply(seq(1,3), function(i) colnames(txi.genes[[i]])<<-mysamples)) #========================================================================================== # Read pre-prepared sample metadata and annotations #========================================================================================= # Read sample metadata colData <- read.table("colData",header=T,sep="\t",row.names=1) # reorder colData for salmon colData <- colData[mysamples,] # reorder colData for featureCounts colData <- colData[colnames(countData),] # get annotations (if you have any) annotations <- read.table("annotations.txt", sep="\t",header=T) #=============================================================================== # DESeq2 analysis # Set alpha to the required significance level. This also effects how # DESeq calculated FDR - setting to 0.05 and then extracting results with a # significance below 0.01 will give slightly different results form setting # alpha to 0.01 #================================================================================ # create DESeq object from featureCounts counts and sample metadata dds <- DESeqDataSetFromMatrix(countData,colData,~1) # or create from Salmon counts and sample metadata dds <- DESeqDataSetFromTximport(txi.genes,colData,~1) #### Technical replicates only #### # add grouping factor to identify technical replicates dds$groupby <- paste(dds$condition,dds$sample,sep="_") # sum replicates (must use same library or library size correction will go wonky) dds <- collapseReplicates(dds,groupby=dds$groupby) #### end technical replicates #### # featureCounts only - normalise counts for different library size (do after collapsing replicates) # NOTE: need to work out what to do if there are technical replicates for salmon workflow # probably take average of avgTxLength for the summed samples sizeFactors(dds) <- sizeFactors(estimateSizeFactors(dds)) # define the DESeq 'GLM' model design=~condition # add design to DESeq object design(dds) <- design # Run the DESeq statistical model dds <- DESeq(dds,parallel=T) # set the significance level for BH adjustment alpha <- 0.05 # calculate the differences - uses the "levels" of the condition factor as the third term for the contrast # contrast=c("condition","S","H") etc - ?results for many more options res <- results(dds,alpha=alpha) # merge results with annotations res.merged <- left_join(rownames_to_column(as.data.frame(res)),annotations,by=c("rowname"="query_id")) # get significant results sig.res <- subset(res.merge,padj<=alpha) # sig.res <- res[which(res$padj<=alpha),] # use this is you don't have annotations # write tables of results write.table(res.merged,"results.txt",quote=F,na="",row.names=F,sep="\t") # get sequences of significant transcripts - transcripts.fa is the file of transcripts # this will only work if the fastas are over two lines, i.e. not split every 80 bases (and the names match) # the below shell script is a method for converting to 2 line fasta # awk '/^>/ {printf("\n%s\n",$0);next; } { printf("%s",$0);} END {printf("\n");}' split_transcripts.fa|sed '1d' > transcripts.fa # seqs <- DNAStringSet(sapply(rownames(sig.res),function(s) { # DNAString(system2("grep",c(paste0(s," "),"-A1", "transcripts.fa"),stdout=T)[[2]]) # })) # alternatively just load the whole of the transcript file (split every 80 bases or not) into a Biostrings object and subset by rowname: seqs <- readDNAStringSet("transcripts.fa")[rownames(sig.res)] # o.k this is probably a better method unless transcripts.fa is massive #=============================================================================== # FPKM #=============================================================================== # note this is pointless if using salmon or some other pseudo counting aligner # set GRanges for each gene # fast method - requires some editing rowRanges(dds) <- GRanges(geneData$Chr,IRanges(geneData$Start,as.numeric(geneData$End)),geneData$Strand) # slow method - doesn't require editing rowRanges(dds) <- GRangesList(apply(m,1,function(x) GRanges(x[[1]],IRanges(1,as.numeric(x[[6]])),"+"))) # calculate FPKM values myfpkm <- data.table(GeneID=m[,1],length=m[,6],fpkm(dds,robust=T)) # write FPKM values write.table(myfpkm,"fpkm.txt",quote=F,na="",sep="\t") #=============================================================================== # Heirachical clustering #=============================================================================== # this is out of date - ward.D2 is the prefered method for clustering - actaully the whole function is a bit naff clus <- function(X,clusters=10,m=1,name="hclust.pdf") { if (m==1) {d <- dist(X, method = "manhattan")} else if (m==2) {d <- dist(X, method = "euclidean")} else if (m==3) {d <- dist(X, method = "maximum")} else if (m==4) {d <- dist(X, method = "canberra")} else if (m==5) {d <- dist(X, method = "binary")} else d <- {dist(X, method = "minkowski")} hc <- hclust(d, method="ward") groups <- cutree(hc, k=clusters) # cut tree into n clusters pdf(name,height=8,width=8) plot(hc) rect.hclust(hc,k=clusters) dev.off() return(list(hc,groups,d)) } #=============================================================================== # Graphs #=============================================================================== # PCA 1 vs 2 plot vst <- varianceStabilizingTransformation(dds,blind=F,fitType="local") # calculate PCs mypca <- prcomp(t(assay(vst))) # calculate variance for each PC mypca$percentVar <- mypca$sdev^2/sum(mypca$sdev^2) # create data frame of PCs x variance (sets PCA plot axes to same scale) df <- t(data.frame(t(mypca$x)*mypca$percentVar)) # plotOrd is a PCA/ordination plotting function ggsave("pca.pdf",plotOrd(df,vst@colData,design="condition",xlabel="PC1",ylabel="PC2", pointSize=3,textsize=14)) # MA plots pdf("MA_plots.pdf") # plot_ma is an MA plotting function lapply(res.merged,function(obj) { plot_ma(obj[,c(1:5,7]),xlim=c(-8,8)) }) dev.off()
869d1df6ad4a324e2c496c41673d2f5ee6547bf1
e51f969dbc5a0af54fa3a8f577140f6ac7199464
/01.Algorithms/10.Regression/01.RobustLenearRegression.R
28424eaa64157af633f392dc2ca2a7a9a8b57b1d
[]
no_license
rmatam/DataScience
6dd02d81a24608a3f07df80f83c62d72732e5d36
ebd0f9f2b28404e66b481ec7179adb1fc8b090b7
refs/heads/master
2021-01-20T18:52:01.743018
2017-04-15T19:02:48
2017-04-15T19:02:48
64,743,868
0
0
null
2016-10-01T18:43:53
2016-08-02T09:34:02
R
UTF-8
R
false
false
1,020
r
01.RobustLenearRegression.R
library(MASS) rlm_mod <- rlm(stack.loss ~ ., stackloss, psi = psi.bisquare) # robust reg model summary(rlm_mod) #> Call: rlm(formula = stack.loss ~ ., data = stackloss) #> Residuals: #> Min 1Q Median 3Q Max #> -8.91753 -1.73127 0.06187 1.54306 6.50163 #> #> Coefficients: #> Value Std. Error t value #> (Intercept) -41.0265 9.8073 -4.1832 #> Air.Flow 0.8294 0.1112 7.4597 #> Water.Temp 0.9261 0.3034 3.0524 #> Acid.Conc. -0.1278 0.1289 -0.9922 #> #> Residual standard error: 2.441 on 17 degrees of freedom lm_mod <- lm(stack.loss ~ ., stackloss) # lm reg model # Errors from lm() model install.packages("DMwR") DMwR::regr.eval(stackloss$stack.loss, lm_mod$fitted.values) #> mae mse rmse mape #> 2.3666202 8.5157125 2.9181694 0.1458878 # Errors from rlm() model DMwR::regr.eval(stackloss$stack.loss, rlm_mod$fitted.values) #> mae mse rmse mape #> 2.1952232 9.0735283 3.0122298 0.1317191 # #
9ac3f032cce2b34f96b7cbb8c475e666c059b318
f18e1210ca120c9116e356a8549e89e04219dc75
/man/parse_mf.Rd
0f759d1bfec053573eec08e62955891a0560e864
[ "BSD-2-Clause" ]
permissive
EMSL-Computing/ftmsRanalysis
46c73a727d7c5d5a5320bf97a07e9dac72abd281
dd3bc3afbf6d1250d1f86e22b936dcc154f4101d
refs/heads/master
2023-07-21T18:13:26.355313
2023-02-09T17:03:09
2023-02-09T17:03:09
122,233,846
14
10
NOASSERTION
2023-07-11T16:34:15
2018-02-20T17:52:18
R
UTF-8
R
false
true
615
rd
parse_mf.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/parse_mf.R \name{parse_mf} \alias{parse_mf} \title{Parse Molecular Formulae to Obtain Elemental Counts} \usage{ parse_mf(ftmsObj) } \arguments{ \item{ftmsObj}{an object of class 'ftmsData', typically a result of \code{\link{as.peakData}}.} } \value{ an object of class 'ftmsData' with a column in \code{e\_meta} giving the molecular formula. } \description{ Construct elemental count columns based on provided molecular formulae } \details{ Parses molecular formulae for number of observed C, H, O, N, S, and P. } \author{ Lisa Bramer }
9d754c8ad8b9c33f4efb8afa9e6b57dd1b79bf95
5b2487622b24806d9d83db12be83b5c5fef68316
/India_GIS_Analysis.R
d000f292ba39895677161cc23914c21ff3b70ef8
[]
no_license
alexismenanieves/India_GIS
92ac8a8446d725b8a9d56c40ff5a30d3e24b5769
aafcc8352194611d713a9102c865bc4662719486
refs/heads/master
2020-08-10T02:56:07.982465
2019-10-11T18:46:42
2019-10-11T18:46:42
214,239,642
0
1
null
null
null
null
UTF-8
R
false
false
1,908
r
India_GIS_Analysis.R
# Load libraries library(tidyverse) library(sf) library(sp) library(GADMTools) library(lwgeom) # Load sf file my_sf <- st_read("india_states_2014/india_states.shp") india_wrapper <- gadm_sf.loadCountries("IND", level = 1, basefile = "./") # See info structure as sp and sf files my_spdf <- as(my_sf,"Spatial") class(my_spdf) str(my_spdf, max.level = 2) glimpse(my_spdf@data) ind_sf <- st_as_sf(my_spdf) head(ind_sf, 3) glimpse(ind_sf) # Using sf as dataframe for dplyr uts <- c("Delhi", "Andaman & Nicobar Islands", "Puducherry", "Lakshadweep", "Dadra & Nagar Haveli", "Daman & Diu", "Chandigarh") # sf can be used with dplyr, but sp can not ind_sf <- ind_sf %>% select(name,abbr) %>% mutate(type = ifelse(name %in% uts,"Union Territory", "State")) %>% rename(abb = abbr, state_ut = name) class(ind_sf) # Loading attributes attributes_df <- readRDS("attributes.rds") ind_sf <- ind_sf %>% left_join(attributes_df, by = "state_ut") %>% mutate( per_capita_GDP_inr = nominal_gdp_inr / pop_2011, per_capita_GDP_usd = nominal_gdp_usd / pop_2011) head(ind_sf,3) # Converting the units library(units) ind_sf <- ind_sf %>% mutate(my_area = st_area(.)) units(ind_sf$my_area) <- with(ud_units, km^2) ind_sf <- ind_sf %>% mutate(GDP_density_usd_km2 = nominal_gdp_usd / my_area) class(ind_sf$area_km2) class(ind_sf$my_area) ind_sf <- ind_sf %>% mutate(my_area = as.vector(my_area), GDP_density_usd_km2 = as.vector(GDP_density_usd_km2)) original_geometry <- st_geometry(ind_sf) library(rmapshaper) simp_sf <- ms_simplify(ind_sf, keep = 0.01, keep_shapes = TRUE) simple_geometry <- st_geometry(simp_sf) par(mfrow = c(1,2)) plot(original_geometry, main = "Original geometry") plot(simple_geometry, main = "Simplified geometry") # Lets see the size of units library(pryr) object_size(original_geometry) object_size(simple_geometry) saveRDS(simp_sf,"simp_sf.rds")