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
905a787f5c16471279a934b262fced7b8f9cdfa0
aaec73a1cc215e604b33dd2c57d8ea12ed07b64f
/MRSA_MLST_read.R
e599b20084ef87efac2e802eec3e44c1347e3f8d
[]
no_license
eugejoh/MRSA_MLST
8fb2bbbd654eb6d62f4bb6eb9301ab2b069b16a4
9fcd1d5687b2e6b9d4c15be504ce57a784bbeca9
refs/heads/master
2021-01-11T15:53:31.348380
2017-01-24T20:09:02
2017-01-24T20:09:02
79,949,566
0
0
null
null
null
null
UTF-8
R
false
false
8,927
r
MRSA_MLST_read.R
# MRSA MLST Database rm(list=ls()) # Taken from http://saureus.beta.mlst.net/ Jan 8, 2017 setwd("/Users/eugenejoh/Documents/Post-Grad/ID Data/MRSA/MLST") # portable_profile_edit #includes # filenames follow format... # portable_genename_edit # profile<-read.csv("portable_profile_edit.csv",header=T,na.strings=c("",NA)) dim(profile) #dimensions of the read-in dataset names(profile) # names of the columns in dataset str(profile) #structure of the data frame ################# # DATA CLEANING # ################# # Identify missing values levels(profile$country) #names of countries included in the dataset summary(profile$country) #summary of counts for each country # Change country to character from factor type profile$country <- as.character(profile$country) # Standardize resistiance factors ($methicillin, $vancomycin) summary(profile$methicillin) str(profile$methicillin) # nine levels for definitions for resistance? # we want to simplify this to binary output for resistant(R) and susceptible(S) factor(profile$methicillin) # factor(profile$methicillin) gives us I, MIC 4mgl/L, MIC 64mg/L, r, R, s, S, Unknown, Unspecified # now we merge r with R and s with S, while renaming the MICs levels(profile$methicillin) <- c("I","MIC4","MIC64","R","R","S","S","Unknown","Unspecified") # we also recognize MIC's of 4mg/L and 64mg/L are considered resistant. Important to note that breakpoints for methicillin MIC tests are now limited - see CDC website for info - https://www.cdc.gov/mrsa/lab/ # we are also going to combine the I, MIC4, MIC64 into the resistant category (R) levels(profile$methicillin) <- c("R","R","R","R","S","Unknown","Unspecified") # now we only have 4 levels : R, S, Unknown, Unspecified factor(profile$methicillin) ################ ################ #mis_profile<-sapply(profile,function(x) sum(is.na(x))) report.NA <- function(v){ nam <- deparse(substitute(v)) varNA <-paste0(nam,"NAs") #assign(newvar,sapply(v,function(x) sum(is.na(x))),envir = parent.frame()) #assign(newvar,apply(is.na(v),2,sum)) assign(varNA,as.data.frame(colSums(is.na(v))),envir=parent.frame()) message(paste("Sum of NAs in",nam,"dataset:",varNA),appendLF=T) } # Why you need to change the function environment, http://emilkirkegaard.dk/en/?p=5718 report.NA(profile);ls() summary(profile$st) #2594 different types of STs, 4 missing values summary(profile$methicillin) #review the MIC for each one (which ones are considered R or S) profileNAs # 20 strain names are missing # 4 STs are missing # 15 countries ################ ################ no.st<-which(is.na(profile$st)) #row index of those with missing STs in dataset profile[no.st,] # info on the missing values of STs # England, Eire (Ireland), 2 USA profile[which(is.na(profile$st)),] #################### # QUESTIONS TO ASK # #################### ### Which countries have reported ST 239? id.239 <- which(profile$st==239) #index of rows with ST-239 st.239 <-profile[id.239,] #new dataframe of only ST-239 sort(unique(st.239$country)) # alphabetical list of countries with ST-239 ### Which countries have report ST8 spa type t008? id.ST8.t008 <- which(profile$st==8 & profile$spa_type=="t008") ST8.t008 <- profile[id.ST8.t008,] dim(ST8.t008) sort(unique(ST8.t008$country)) length(sort(unique(ST8.t008$country))) # What is the proportion of S vs. R S. aureus reports are there in North America? table(profile$methicillin,useNA="always") #number of counts for R, S, Unknown, Unspecified and NA values for methicillin resistance sum(is.na(profile$methicillin)) #counts of NAs in dataset NA.MRSA <- profile[profile$country=="USA" | profile$country=="Canada",] #selection of North American countries table(NA.MRSA$methicillin,useNA="always") NA.MRSA <- NA.MRSA[complete.cases(NA.MRSA$country),] #removal of NAs # ggplot # http://stackoverflow.com/questions/16184188/ggplot-facet-piechart-placing-text-in-the-middle-of-pie-chart-slices library(ggplot2) install.packages("viridis") library(viridis) NA.MRSA$st <- as.numeric(NA.MRSA$st) #convert the STs to numeric type c.NorthA.MRSA <-as.data.frame(table(NA.MRSA$st));names(c.NorthA.MRSA) <- c("ST","count") #data frame containing count frequencies of the STs c.NorthA.MRSA<-c.NorthA.MRSA[order(-c.NorthA.MRSA$count),] #order the STs by count frequencies c.NorthA.MRSA[1:10,] # top ten blank_t <- theme_minimal()+ theme( axis.title.x = element_blank(), axis.title.y = element_blank(), panel.border = element_blank(), panel.grid=element_blank(), axis.ticks = element_blank(), plot.title=element_text(size=20, face="bold",hjust=0.6), plot.subtitle=element_text(size=15,face=c("bold","italic"),hjust=0.6), axis.text.x=element_blank(), legend.title=element_text(size=14,face="bold",vjust=0.5), panel.margin=unit(2,"cm") ) ggplot(c.NorthA.MRSA[1:10,], aes(x="",y=count,fill=ST,order=ST)) + geom_bar(width=1, stat="identity") + ggtitle(element_text(size=50))+ labs(title = "STs in North America", subtitle = "Canada and United States",y=NULL) + coord_polar(theta="y")+ geom_text(aes(label = scales::percent(count/sum(c.NorthA.MRSA[1:10,2]))),size=4, position = position_stack(vjust = 0.6)) + blank_t + scale_fill_manual(guide_legend(title="STs"), values=c("#e6b4c9", "#bce5c2", # colour palette resource for data scientists "#c7b5de", # http://tools.medialab.sciences-po.fr/iwanthue/ "#e3e4c5", "#a1bbdd", "#e5b6a5", "#99d5e5", "#bdbda0", "#dcd1e1", "#99c6b8")) # http://www.sthda.com/english/wiki/ggplot2-pie-chart-quick-start-guide-r-software-and-data-visualization # http://graphicdesign.stackexchange.com/questions/3682/where-can-i-find-a-large-palette-set-of-contrasting-colors-for-coloring-many-d # changing order of scale # https://learnr.wordpress.com/2010/03/23/ggplot2-changing-the-default-order-of-legend-labels-and-stacking-of-data/ install.packages("randomcoloR") library(randomcoloR) distinctColorPalette(k=15) #+facet_grid(Channel ~ ., scales = "free") bp <- ggplot(NA.MRSA,aes(x="",y=st,fill=country)) + geom_bar(width = 1,stat = "identity") bp pie <- bp + coord_polar("y",start=0) pie + geom_text(aes(label = country), position = position_stack(vjust = 0.5)) bp1 <- ggplot(NA.MRSA,aes(x=factor(1),fill=country)) + geom_bar(width = 1) bp1 pie1 <- bp1 + coord_polar("y",start=0) pie1 pie + scale_fill_brewer(palette="Blues") # How many STs are there in China, S Korea, Taiwan and Japan? F.east <- profile[profile$country=="China" | profile$country=="South Korea" | profile$country=="Japan" | profile$country=="Taiwan",] #subset the data by Far East countries. | logic operator is OR, & would be AND dim(F.east) #573 entries factor(F.east$st) # 289 different STs sum(is.na(F.east$st)) #15 missing values table(F.east$st) #counts of STs table(F.east$country) #counts of STs by country FE.final<-F.east[complete.cases(F.east$country),] #removal of all rows that are missing an entry for country dim(FE.final) #check the dimensions is 573-15 = ? # Country Specific Details # China length(which(FE.final$country=="China")) #counts for China FE.China <- FE.final[FE.final$country=="China",] FE.China$country dim(FE.China) # 229 entries sort(table(FE.China$st),decreasing=T) #most common STs are 97, 239 and 398 sort(table(FE.China$st),decreasing=T)[1:5] #top 10 most frequent factor(FE.China$st) #163 different type of STs China.tab <- table(FE.China$st) bp <- ggplot(FE.China,aes(x=st)) + geom_bar() bp + coord_polar("y",start=0) x <- c("Insurance", "Insurance", "Capital Goods", "Food markets", "Food markets") tt <- table(x) names(tt[tt==max(tt)]) # S Korea # Taiwan # Japan # Mapping out Countries using ggmap() package install.packages(c("ggmap","maptools","maps")) library(ggplot2,ggmap,maptools) library(maps) # HOW TO PLOT POINTS ON MAPS IN R # https://www.r-bloggers.com/r-beginners-plotting-locations-on-to-a-world-map/ # http://stackoverflow.com/questions/11201997/world-map-with-ggmap/13222504#13222504 # setup cities of interest visited <- c("SFO", "Chennai", "London", "Melbourne", "Johannesbury, SA") ll.visited <- geocode(visited) #get visit.x <- ll.visited$lon visit.y <- ll.visited$lat mp <- NULL mapWorld <- borders("world", colour="gray50", fill="gray50") # create a layer of borders mp <- ggplot() + mapWorld mp <- mp+ geom_point(aes(x=visit.x, y=visit.y) ,color="blue", size=3) # http://stackoverflow.com/questions/41018634/continuous-colour-gradient-that-applies-to-a-single-geom-polygon-element-with-gg library(ggplot2) map <- map_data("world") #map of the world from map$value <- setNames(sample(1:50, 252, T), unique(map$region))[map$region] world.p <- ggplot(map, aes(long, lat, group=group, fill=value)) + geom_polygon()+ coord_map(projection = "mercator",xlim=c(180,-180),ylim=c(75,-75)) p <- ggplot(map, aes(long, lat, group=group, fill=value)) + geom_polygon() + coord_quickmap(xlim = c(-50,50), ylim=c(25,75)) p + geom_polygon(data = subset(map, region=="Germany"), fill = "red")
f8e4fb8b9dc98f447ae79ada86b94e808958eb6c
904022448a1599c2e6dcb2a438beb4b64efb65bc
/adr_no_cells.R
e9b626725e472d7ff226c756f5de3fde1ea7f6f4
[]
no_license
GKild/neuroblastoma
1bb9ec3df959482d6d7e9a718fc98bb813033a8f
a17d359b8ad915ce3eb831739254c951df1719e4
refs/heads/master
2023-03-04T04:24:57.783627
2021-02-16T11:12:00
2021-02-16T11:12:00
217,528,698
0
0
null
null
null
null
UTF-8
R
false
false
5,167
r
adr_no_cells.R
#get all adrenal datasets ba1=readRDS("/lustre/scratch117/casm/team274/my4/oldScratch/preProcessSCP/output/babyAdrenal1_Seurat.RDS") ba2=readRDS("/lustre/scratch117/casm/team274/my4/oldScratch/preProcessSCP/output/babyAdrenal2_Seurat.RDS") bilateral=readRDS("/lustre/scratch117/casm/team274/my4/oldScratch/preProcessSCP/output/bilateralAdrenals_Seurat.RDS") bilat_tech=readRDS("/lustre/scratch117/casm/team274/my4/oldScratch/preProcessSCP/output/techComparison_Seurat.RDS") adr3=readRDS("/lustre/scratch117/casm/team274/my4/oldScratch/ProjectsExtras/SCP/Data/fAdrenal19wk/seurat.RDS") DimPlot(adr3, label=T) dim(ba1) dim(ba2) dim(bilateral) dim(bilat_tech) DimPlot(ba1, label=T) DimPlot(ba2, label=T) DimPlot(bilateral, label=T) DimPlot(bilat_tech,label=T) FeaturePlot(ba1, features=c('HBB','HBA1','PECAM1','PTPRC','EPCAM','PDGFRB','MYCN','SOX10','SOX2','PHOX2A','CHGB','PHOX2B')) FeaturePlot(ba2, features=c('HBB','HBA1','PECAM1','PTPRC','EPCAM','PDGFRB','MYCN','SOX10','SOX2','PHOX2A','CHGB','PHOX2B')) FeaturePlot(bilat_tech, features=c('HBB','HBA1','PECAM1','PTPRC','EPCAM','PDGFRB','MYCN','SOX10','SOX2','PHOX2A','CHGB','PHOX2B')) length(WhichCells(ba2, idents = c(19,7,11,17,10))) length(WhichCells(ba2, idents = c(0,1,2,4,6,8,12,13))) length(WhichCells(ba2, idents = c(18))) length(WhichCells(ba2, idents = c(14))) length(WhichCells(ba2, idents = c(3,9,15))) length(WhichCells(ba2, idents = c(5,16))) FeaturePlot(bilateral, features=c("EPCAM")) length(WhichCells(ba1, idents = c(14,19,20))) length(WhichCells(ba1, idents = c(0,1,2,4,6,7,8,10,11,13))) length(WhichCells(ba1, idents = c(5,17))) length(WhichCells(ba1, idents = c(16,18))) length(WhichCells(ba1, idents = c(3,9,15,12))) length(WhichCells(bilateral, idents = c(12,15,16,20,22))) length(WhichCells(bilateral, idents = c(0,2,4,5,9,10,23,24))) length(WhichCells(bilat_tech, idents = c(0,2,3,4,9,10,16,11))) length(WhichCells(bilat_tech, idents = c(6,7,14))) FeaturePlot(bilat_tech, c("SOX2")) length(WhichCells(adr3,idents=c(0,1,2,4,6,9,13,14))) length(WhichCells(adr3,idents=c(23))) length(WhichCells(bilateral, idents = c(22))) length(WhichCells(ba2, idents = c(17,10))) length(WhichCells(bilat_tech, idents = c(11))) WhichCells(bilateral, orig.ident="5388STDY7717452") left=rownames(bilateral@meta.data)[which(bilateral@meta.data$orig.ident%in%c("5388STDY7717452", "5388STDY7717453", "5388STDY7717454", "5388STDY7717455"))] right=rownames(bilateral@meta.data)[which(!bilateral@meta.data$orig.ident%in%c("5388STDY7717452", "5388STDY7717453", "5388STDY7717454", "5388STDY7717455"))] left_srat=subset(bilateral, cells=left) right_srat=subset(bilateral, cells=right) length(WhichCells(left_srat, idents = c(12,15,16,20,22))) length(WhichCells(left_srat, idents = c(0,2,4,5,9,10,23,24))) length(WhichCells(left_srat, idents = c(18,19))) length(WhichCells(left_srat, idents = c(1,21,13))) length(WhichCells(left_srat, idents = c(8,11))) length(WhichCells(left_srat, idents = c(3,6,7,14,17))) length(WhichCells(right_srat, idents = c(12,15,16,20,22))) length(WhichCells(right_srat, idents = c(0,2,4,5,9,10,23,24))) length(WhichCells(right_srat, idents = c(18,19))) length(WhichCells(right_srat, idents = c(1,21,13))) length(WhichCells(right_srat, idents = c(8,11))) length(WhichCells(right_srat, idents = c(3,6,7,14,17))) length(WhichCells(right_srat, idents = c(22))) sapply(strsplit(names(adr3@active.ident), "_"), "[", 6) old_left=rownames(adr3@meta.data)[which(sapply(strsplit(names(adr3@active.ident), "_"), "[", 6)%in%c("Adr8710632", "Adr8710633"))] old_right=rownames(adr3@meta.data)[which(!sapply(strsplit(names(adr3@active.ident), "_"), "[", 6)%in%c("Adr8710632", "Adr8710633"))] old_left_srat=subset(adr3, cells=old_left) old_right_srat=subset(adr3, cells=old_right) length(WhichCells(old_left_srat,idents=c(0,1,2,4,6,9,13,14))) length(WhichCells(old_left_srat,idents=c(23))) length(WhichCells(old_left_srat,idents=c(12,17,27,19,20))) length(WhichCells(old_left_srat,idents=c(3,5,7,24,21,25))) length(WhichCells(old_left_srat,idents=c(18,15))) length(WhichCells(old_left_srat,idents=c(22,8,11,10,16))) length(WhichCells(old_right_srat,idents=c(0,1,2,4,6,9,13,14))) length(WhichCells(old_right_srat,idents=c(23))) length(WhichCells(old_right_srat,idents=c(12,17,27,19,20))) length(WhichCells(old_right_srat,idents=c(3,5,7,24,21,25))) length(WhichCells(old_right_srat,idents=c(18,15))) length(WhichCells(old_right_srat,idents=c(22,8,11,10,16))) length(WhichCells(bilat_tech,idents=c(1,5,15))) length(WhichCells(bilat_tech,idents=c(17,13,18))) length(WhichCells(bilat_tech,idents=c(19,8,12))) length(WhichCells(bilat_tech,idents=c(20,21))) DimPlot(ba1, label=T) tab=read.csv("plts/Book3.csv", header = T) tab_melt=melt(tab,id.vars = "Sample") ggplot(tab_melt, aes(fill=variable, y=value, x=Sample)) + geom_bar(position="fill", stat="identity") + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black")) + scale_fill_manual(values=c("#332288", "#88CCEE", "#117733", "#DDCC77", "#CC6677","#AA4499"))
2304729c9de1e5dd83612f40613537ad1adbbb4e
4b5c970ac1dc877453c7a13f921c807b4177ae6c
/plot5.R
b9234270b55bb0f78d5d542f8521591f82309914
[]
no_license
ManuChalela/JHU_EDA_Project2
dec3e8fa7d02b6c2f57036b706154eba591e0070
18751cf6f6dee335cb9cd5a70dcfeee307c20501
refs/heads/main
2023-01-18T16:05:18.348466
2020-12-12T04:19:31
2020-12-12T04:19:31
320,467,620
0
0
null
null
null
null
UTF-8
R
false
false
1,208
r
plot5.R
library(data.table) library(reshape2) library(png) library(dplyr) library(fs) library(lubridate) library(ggplot2) path <- file.path(getwd(), "data/") fs::dir_create(path = path) url <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2FNEI_data.zip" download.file(url, file.path(path, "dataFiles.zip")) unzip(zipfile = file.path(path, "dataFiles.zip"), exdir = path) SCC <- data.table::as.data.table(x = readRDS(file = file.path(path, "Source_Classification_Code.rds"))) NEI <- data.table::as.data.table(x = readRDS(file = file.path(path, "summarySCC_PM25.rds"))) # Gather the subset of the NEI data which corresponds to vehicles vehiclesSCC <- SCC[grepl("vehicle", SCC.Level.Two, ignore.case=TRUE) , SCC] vehiclesNEI <- NEI[NEI[, SCC] %in% vehiclesSCC,] # Subset the vehicles NEI data to Baltimore's fip baltimoreVehiclesNEI <- vehiclesNEI[fips=="24510",] png("plot5.png") ggplot(baltimoreVehiclesNEI,aes(factor(year),Emissions)) + geom_bar(stat="identity", fill ="#FF9999" ,width=0.75) + labs(x="year", y=expression("Total PM"[2.5]*" Emission (10^5 Tons)")) + labs(title=expression("PM"[2.5]*" Motor Vehicle Source Emissions in Baltimore from 1999-2008")) dev.off()
5c2c21814c12d3e0b9cb528f024a53158d7c5a4a
43ac1b022fb160479e9baf022d522857323878d2
/analysis/dir-utility.r
4cd3d97e41967605094589f658a7727c16cef257
[]
no_license
franciscastro/research-plan-composition
6b532f4ea4ff339ef36948d886505f8b86e719a1
503108ea8393a6b03faed347ab91e65fcadc8008
refs/heads/master
2021-01-10T11:46:13.741052
2016-04-22T20:17:45
2016-04-22T20:17:45
45,146,889
0
0
null
null
null
null
UTF-8
R
false
false
2,078
r
dir-utility.r
#' --- #' title: "Directory creation utility script" #' author: "Francisco Castro (fgcastro@wpi.edu)" #' date: "15 March 2016" #' --- # NOTES #================================================== # # This script is used to create directories for each # sub-sample generated in data-setup.r and data-sample.r # # Run data-setup.r prior to running this script. # #================================================== # Set directory paths for each sample group #================================================== dir_1101_A <- "C:/Git Repositories/files/sampled/1101-a" dir_1101_B <- "C:/Git Repositories/files/sampled/1101-b" dir_1101_C <- "C:/Git Repositories/files/sampled/1101-c" dir_1102_A <- "C:/Git Repositories/files/sampled/1102-a" dir_1102_B <- "C:/Git Repositories/files/sampled/1102-b" #================================================== # Read files (csv files have been pre-generated) #================================================== data_1101a <- read.csv("sample-cs1101-A.csv") data_1101b <- read.csv("sample-cs1101-B.csv") data_1101c <- read.csv("sample-cs1101-C.csv") data_1102a <- read.csv("sample-cs1102-A.csv") data_1102b <- read.csv("sample-cs1102-B.csv") #================================================== # Fetch directory names (usernames) from data frames #================================================== data_1101a <- data_1101a$username data_1101b <- data_1101b$username data_1101c <- data_1101c$username data_1102a <- data_1102a$username data_1102b <- data_1102b$username #================================================== # Create directories for each sample group #================================================== create_dirs <- function(maindir, subdir) { dir.create(file.path(maindir, subdir)) } sapply(data_1101a, create_dirs, maindir = dir_1101_A) sapply(data_1101b, create_dirs, maindir = dir_1101_B) sapply(data_1101c, create_dirs, maindir = dir_1101_C) sapply(data_1102a, create_dirs, maindir = dir_1102_A) sapply(data_1102b, create_dirs, maindir = dir_1102_B) #==================================================
3ed23d80bb0869d75cede7a6279326b3b8186fc8
560f1adefa19f293eafbe63fc6bd18b0769bc154
/R programming/corr.R
c97c535675b1d7594333ee5646aab563792eeb0d
[]
no_license
kmj9000/datasciencecoursera
10e78b1889887536b1e8ecdab96aacf9e597b658
a1f7fd8515a8d13e68d1bee843627b035fbf895d
refs/heads/master
2020-05-30T16:03:48.949857
2015-11-22T17:13:27
2015-11-22T17:13:27
29,430,090
0
2
null
null
null
null
UTF-8
R
false
false
754
r
corr.R
corr <- function(directory, threshold = 0) { ## 'directory' is a character vector of length 1 indicating ## the location of the CSV files ## 'threshold' is a numeric vector of length 1 indicating the ## number of completely observed observations (on all ## variables) required to compute the correlation between ## nitrate and sulfate; the default is 0 ## Return a numeric vector of correlations files <- Sys.glob(paste0(directory, "/", "*.csv")) correlns <- c() for (i in files) { eachFile <- read.csv(i); completeCases <- eachFile[complete.cases(eachFile),] if (nrow(completeCases) > threshold) correlns <- c(correlns, cor(completeCases$sulfate, completeCases$nitrate)) } correlns }
7ee30b714afe9cb13a25be1ba3d880ff19a6dc57
2447be673b4bceaf193a5ced248dd0f62912d994
/man/extract-methods.Rd
643226eb2e1f5f81be34b12f452ed47ae8075a85
[]
no_license
benneic/gpuRcuda
024b6f1af5a08257a9c3e51ef68dc5014712d74d
23a4ad805c738da7227176f99ecdae1750fda00c
refs/heads/master
2020-07-22T03:38:06.289601
2018-01-10T17:50:15
2018-01-10T17:50:15
null
0
0
null
null
null
null
UTF-8
R
false
true
844
rd
extract-methods.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/methods-cudaVector.R, R/methods-nvVector.R, % R/methods.R \docType{methods} \name{[,cudaVector,missing,missing,missing-method} \alias{[,cudaVector,missing,missing,missing-method} \alias{[,nvVector,missing,missing,missing-method} \alias{[,cudaMatrix,missing,missing,missing-method} \alias{[,nvMatrix,missing,missing,missing-method} \title{Extract gpuRcuda elements} \usage{ \S4method{[}{cudaVector,missing,missing,missing}(x, i, j, drop) \S4method{[}{nvVector,missing,missing,missing}(x, i, j, drop) \S4method{[}{cudaMatrix,missing,missing,missing}(x, i, j, drop) \S4method{[}{nvMatrix,missing,missing,missing}(x, i, j, drop) } \arguments{ \item{x}{A gpuRcuda object} \item{i}{missing} \item{j}{missing} \item{drop}{missing} } \author{ Charles Determan Jr. }
592cf590c688fb9e504bdae57f5b5358f685c96a
9aafde089eb3d8bba05aec912e61fbd9fb84bd49
/codeml_files/newick_trees_processed/1842_12/rinput.R
63ad90d1e113c9f7dce696364438dbb816a130c9
[]
no_license
DaniBoo/cyanobacteria_project
6a816bb0ccf285842b61bfd3612c176f5877a1fb
be08ff723284b0c38f9c758d3e250c664bbfbf3b
refs/heads/master
2021-01-25T05:28:00.686474
2013-03-23T15:09:39
2013-03-23T15:09:39
null
0
0
null
null
null
null
UTF-8
R
false
false
137
r
rinput.R
library(ape) testtree <- read.tree("1842_12.txt") unrooted_tr <- unroot(testtree) write.tree(unrooted_tr, file="1842_12_unrooted.txt")
fe11c8160f62d13202ba1153617c73d04289f170
fdfe62a9b82d6537d633849a8f3ad5a24130bbeb
/irods-3.3.1-cyverse/iRODS/clients/icommands/test/rules3.0/rulemsiTarFileExtract.r
4d8af5cfbb0fdd6f808f4d96fd831199068db188
[]
no_license
bogaotory/irods-cyverse
659dbef3652c1713a419d588adf0b866474dea9a
2aceaf7c318c2fb581fcca2d62968f69460dcc9c
refs/heads/master
2021-01-10T14:15:27.267337
2016-02-25T00:44:06
2016-02-25T00:44:06
52,032,218
2
0
null
null
null
null
UTF-8
R
false
false
690
r
rulemsiTarFileExtract.r
myTestRule { # Input parameters are: # Tar file within iRODS that will have its files extracted # Collection where the extracted files will be placed # Resource where the extracted files will be written # Output parameter: # Status flag for the operation # Output from running the example is: # Extract files from a tar file into collection /tempZone/home/rods/ruletest/sub on resource demoResc msiTarFileExtract(*File,*Coll,*Resc,*Status); writeLine("stdout","Extract files from a tar file *File into collection *Coll on resource *Resc"); } INPUT *File="/tempZone/home/rods/test/testcoll.tar", *Coll="/tempZone/home/rods/ruletest/sub", *Resc="demoResc" OUTPUT ruleExecOut
700463f468d4da491b3ed47c51e528b0d2103ca6
72d9009d19e92b721d5cc0e8f8045e1145921130
/twosamples/man/ks_test.Rd
6b361c542c7d35e43351928ea11eb35a948a451e
[]
no_license
akhikolla/TestedPackages-NoIssues
be46c49c0836b3f0cf60e247087089868adf7a62
eb8d498cc132def615c090941bc172e17fdce267
refs/heads/master
2023-03-01T09:10:17.227119
2021-01-25T19:44:44
2021-01-25T19:44:44
332,027,727
1
0
null
null
null
null
UTF-8
R
false
true
1,719
rd
ks_test.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/RcppExports.R, R/documentation.R, % R/two_samples.R \name{ks_stat} \alias{ks_stat} \alias{ks_test} \title{Kolmogorov-Smirnov Test} \usage{ ks_stat(a, b, power = 1) ks_test(a, b, nboots = 2000, p = default.p) } \arguments{ \item{a}{a vector of numbers} \item{b}{a vector of numbers} \item{power}{power to raise test stat to} \item{nboots}{Number of bootstrap iterations} \item{p}{power to raise test stat to} } \value{ Output is a length 2 Vector with test stat and p-value in that order. That vector has 3 attributes -- the sample sizes of each sample, and the number of bootstraps performed for the pvalue. } \description{ A two-sample test using the Kolmogorov-Smirnov test statistic (\code{ks_stat}). } \details{ The KS test compares two ECDFs by looking at the maximum difference between them. Formally -- if E is the ECDF of sample 1 and F is the ECDF of sample 2, then \deqn{KS = max |E(x)-F(x)|^p} for values of x in the joint sample. The test p-value is calculated by randomly resampling two samples of the same size using the combined sample. In the example plot below, the KS statistic is the height of the vertical black line. \figure{ks.png}{Example KS stat plot} } \section{Functions}{ \itemize{ \item \code{ks_stat}: Kolmogorov-Smirnov test statistic \item \code{ks_test}: Permutation based two sample Kolmogorov-Smirnov test }} \examples{ vec1 = rnorm(20) vec2 = rnorm(20,4) ks_test(vec1,vec2) } \seealso{ \code{\link[=dts_test]{dts_test()}} for a more powerful test statistic. See \code{\link[=kuiper_test]{kuiper_test()}} or \code{\link[=cvm_test]{cvm_test()}} for the natural successors to this test statistic. }
dfa47530f78ff6a56276ad3ee7863bb633a40d03
669e0ccbaf738f5c0e0f6b8d790217c6ff5e15b4
/import_and_sample.R
a9e3528a6045540e85b44f97f29fb694294978d5
[]
no_license
hytsang/Capstone-Project
9550d161e8563a80de68ddefdb66018ffbf11682
dceb836ce63d46dc6d0be6015418fc4a1edb9a09
refs/heads/master
2021-01-11T14:00:43.052533
2015-04-19T11:35:07
2015-04-19T11:35:07
null
0
0
null
null
null
null
UTF-8
R
false
false
921
r
import_and_sample.R
# importing and sampling the data # load stringi library library(stringi) setwd("~/Capstone Project") list.files("final") list.files("final/en_US") # import the blogs and twitter datasets in text mode blogs <- readLines("final/en_US/en_US.blogs.txt", encoding="UTF-8") twitter <- readLines("final/en_US/en_US.twitter.txt", encoding="UTF-8") #importing news dataset con <- file("final/en_US/en_US.news.txt", open="rb") news <- readLines(con, encoding="UTF-8") close(con) rm(con) # dropping non UTF-8 character twitter <- iconv(twitter, from = "latin1", to = "UTF-8", sub="") twitter <- stri_replace_all_regex(twitter, "\u2019|`","'") twitter <- stri_replace_all_regex(twitter, "\u201c|\u201d|u201f|``",'"') # Sampling the data blogs <- sample(blogs,10000) news <- sample(news,10000) twitter <- sample(twitter,10000) data <- c(twitter,blogs,news) rm(blogs) rm(news) rm(twitter) save(data,file="sample_data.Rdata")
3f05634a5ead7cbf1bf90c9c161cb3dcff2e2454
72279a412260a94bdf5ae70db4cea2e153689331
/functional_response&Fig2_AP.R
704e5e10bca5680f52dc79e63434c7aa4997e6fc
[]
no_license
koehnl/Seabird_ForageFish_model
21b599eef6e5c4d143c2e21f2bf41148434eb691
54a105bf03eda27e4b6214208e7a3bd733de5207
refs/heads/main
2023-03-21T18:01:37.217260
2021-03-14T23:07:08
2021-03-14T23:07:08
344,362,258
0
0
null
null
null
null
UTF-8
R
false
false
10,696
r
functional_response&Fig2_AP.R
# CODE TO PLAY AROUND WITH FUNCTIONAL RESPONSES # and make Figure 2 from Koehn et al. 2021 # acknowledgments to Andre Punt (University of Washington) # for supplying lines of code and help alpha <- 0 # lowest possible impact on survival slope <-30 # how fast it drops from 1 to the lowest possible impact on suvival beta <- 0.2 # ratio (P/P0) where predator would switch? # P/P0 xx <- seq(from=0,to=1.5,by=0.01) yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) plot(xx,yy,type='l') abline(v = 0.15, lty = 3) ###################################### alpha <- 0 slope <- 40 beta <- 0.15 # P/P0 xx <- seq(from=0,to=1.5,by=0.01) yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) plot(xx,yy,type='l') alpha <- 0 slope <- 30 beta <- 0.2 # P/P0 yy2 <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) lines(xx, yy2, col = "red") functionalresponse <- function(alpha, slope, beta) { xx <- seq(from=0,to=1.1,by=0.01) yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) plot(xx,yy,type='l', ylim = c(0,1), ylab = "", xlab = "", yaxt = "n", xaxt = "n") #abline(v = 0.3, lty = 3) axis(side = 1, at = c(0,0.1,0.2,0.3,0.4,0.5,1), las = 0) axis(side = 2, at = c(0,0.2,0.4,0.6,0.8,1), las = 2) return(cbind(yy,xx)) } xx <- seq(from=0,to=1.1,by=0.01) functionalresponse(0.1, 40, 0.3) # test zz <- seq(from=0,to=1.1,by=0.01) lines(zz,xx) par(mfrow = c(3,2)) par(mar=c(3,4,3,2)) par(oma=c(3,3,2,2)) # BREEDER ATTENDANCE temp =functionalresponse(0.1,20,0.3) functionalresponse(0.1,30,0.3) #breeders specialist #functionalresponse(0.6,20,0.3) #generalist #functionalresponse(0.3,20,0.3) #middle alpha = 0.6; slope = 20; beta = 0.3 yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) lines(xx,yy, col = "red") mtext("% Breeder Attendance", side=3, line = 1) #mtext("Proportion Prey Available", side=1, line = 3) alpha = 0.3; slope = 20; beta = 0.3 yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) lines(xx,yy, col = "blue") legend("bottomright", legend = c("Specialist", "Generalist"), col = c("Black", "Red"), lty = c(1,1), y.intersp=1, bty = 'n') # fledgling functionalresponse(-0.3,30,0.2) # have a max(0, yy) so will give 0 if yy goes negative alpha = 0.51; slope = 15; beta = 0.1 yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) lines(xx,yy, col = "red") mtext("% Fledge 1 chick - if 3 chicks", side=3, line = 1) #mtext("Proportion Prey Available", side=1, line = 3) alpha = 0.27; slope = 20; beta = 0.15 yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) lines(xx,yy, col = "blue") legend("bottomright", legend = c("Specialist", "Generalist", "Middle"), col = c("Black", "Red", "Blue"), lty = c(1,1,1), y.intersp=1) # Second chick functionalresponse(-0.3,30,0.15) # vs. firrst chick alpha = -0.3; slope = 30; beta = 0.2 yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) lines(xx,yy, col = "red") functionalresponse(-0.3,30,0.15) alpha = 0.41; slope = 15; beta = 0.05 yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) lines(xx,yy, col = "red") mtext("% Fledge 1 chick - if 2 chicks", side=3, line = 1) #mtext("Proportion Prey Available", side=1, line = 3) alpha = 0.21; slope = 20; beta = 0.1 yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) lines(xx,yy, col = "blue") legend("bottomright", legend = c("Specialist", "Generalist", "Middle"), col = c("Black", "Red", "Blue"), lty = c(1,1,1), y.intersp=1) # 3rd chick functionalresponse(-0.3,30,0.1) alpha = 0.2; slope = 15; beta = 0 yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) lines(xx,yy, col = "red") mtext("% Fledge 1 chick", side=3, line = 1) #mtext("Proportion Prey Available", side=1, line = 3) alpha = 0.05; slope = 20; beta = 0.05 yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) lines(xx,yy, col = "blue") legend("bottomright", legend = c("Specialist", "Generalist", "Middle"), col = c("Black", "Red", "Blue"), lty = c(1,1,1), y.intersp=1) param_breeders_special = c(0.2,30,0.3) # colony/breeder attendance (not survival) param_breeders_general = c(0.6,30,0.3) param_breeders_mid = c(0.3,20,0.3) # OK? based on Piatt et al. 2007/Cairns should be shifted even further right. # also right shape? param_fledge_special = c(-0.3,30,0.2) # enough like 1/3 for the birds - i think so, and looks like Andre's param_fledge_general = c(0.3,15,0.1) # so at some lower survival, switch and survival goes back to 1? param_fledge_mid = c(0.1,20,0.15) param_fledge2_special = c(-0.3,30,0.10) paramfledge2_general = c(0.2,20,0.05) # *will 2nd and 3rd chick still apply for generalist who just switched anyway? paramfledge2_mid = c() paramfledge3_special = c(-0.3,30,0.05) # adult survival functionalresponse(0.1,20,0.15) alpha = 0.6; slope = 20; beta = 0.15 yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) lines(xx,yy, col = "red") mtext("% Adult Survival", side=3, line = 1) #mtext("Proportion Prey Available", side=1, line = 3) alpha = 0.3; slope = 20; beta = 0.15 yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) lines(xx,yy, col = "blue") legend("bottomright", legend = c("Specialist", "Generalist", "Middle"), col = c("Black", "Red", "Blue"), lty = c(1,1,1), y.intersp=1) param_adult_special = c(-0.1,20,0.15) # pretty good based on Piatt et al. 2007 param_adult_general = c(0.5,20,0.15) param_adult_mid = c(0.25,20,0.15) functionalresponse(0.1,10,0.3) alpha = 0.6; slope = 10; beta = 0.3 yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) lines(xx,yy, col = "red") mtext("% Juvenile Survival", side=3, line = 1) #mtext("Proportion Prey Available", side=1, line = 3) alpha = 0.3; slope = 10; beta = 0.3 yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) lines(xx,yy, col = "blue") legend("bottomright", legend = c("Specialist", "Generalist", "Middle"), col = c("Black", "Red", "Blue"), lty = c(1,1,1), y.intersp=1) par(xpd = NA) mtext(expression(paste('Relative Prey Availability (P'['y,s,l'],' / P'[0],')')), side = 1, outer = TRUE, line = 1) mtext(expression(paste('Demographic Rate Modifier (',delta['y,s,l'],')')), side = 2, outer = TRUE, line = 0, padj = 0) param_juv_special = c(0,10,0.3) # need lots of prey or else only the strong survive param_juv_general = c(0.5,10,0.3) param_juv_mid = c(0.25,10,0.3) # 1st vs. 2nd vs. 3rd chick functionalresponse(-0.3,30,0.2) # have a max(0, yy) so will give 0 if yy goes negative alpha = -0.3; slope = 30; beta = 0.15 yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) lines(xx,yy, col = "red") mtext("% Chick Fledge", side=2, line = 3) mtext("Proportion Prey Available", side=1, line = 3) alpha = -0.3; slope = 30; beta = 0.1 yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) lines(xx,yy, col = "blue") legend("bottomright", legend = c("1st chick", "2nd chick", "3rd chick"), col = c("Black", "Red", "Blue"), lty = c(1,1,1), y.intersp=1) functionalresponse(0.1,20,0.15) alpha = 0.1; slope = 20; beta = 0.1 yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) lines(xx,yy, col = "grey50") alpha = 0.1; slope = 20; beta = 0.3 yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) lines(xx,yy, col = "grey60") alpha = 0.3; slope = 20; beta = 0.3 yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) lines(xx,yy, col = "grey70") alpha = 0.5; slope = 20; beta = 0.15 yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) lines(xx,yy, col = "grey30") ######################### new plot 3/3/2020 functionalresponse <- function(alpha, slope, beta) { xx <- seq(from=0,to=0.5,by=0.01) yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) plot(xx,yy,type='l', ylim = c(0,1), ylab = "", xlab = "", yaxt = "n", xaxt = "n") #abline(v = 0.3, lty = 3) axis(side = 1, at = c(0,0.1,0.2,0.3,0.4,0.5,1), las = 0) axis(side = 2, at = c(0,0.2,0.4,0.6,0.8,1), las = 2) return(cbind(yy,xx)) } xx <- seq(from=0,to=0.5,by=0.01) par(xpd = FALSE) par(mfrow = c(2,1)) par(mar = c(2,2,1,1)) par(oma = c(3,4,1,1)) functionalresponse(0.2,30,0.3) #breeders specialist alpha = 0.6; slope = 30; beta = 0.3 yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) lines(xx,yy, col = "black", lty = 2) #mtext(expression(paste("Rate Modifier (", delta, ")" )), side=2, line = 2.5) #mtext("Proportion Prey Available", side=1, line = 3) #breeder = expression(paste("Breeder attendance", gamma)) legend("bottomright", legend = c("Specialist", "Generalist", expression(paste("Breeder attendance ",gamma)), "Adult survival", "Juvenile survival"), col = c("grey", "grey","black", "red", "blue"), lty = c(1,2,1,1,1), y.intersp=1, bty = 'n') alpha = 0.6; slope = 30; beta = 0.15 yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) lines(xx,yy, col = "red", lty = 2) alpha = 0.2; slope = 30; beta = 0.15 yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) lines(xx,yy, col = "red", lty = 1) alpha = 0.6; slope = 30; beta = 0.2 yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) lines(xx,yy, col = "blue", lty = 2) alpha = 0.2; slope = 30; beta = 0.2 yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) lines(xx,yy, col = "blue", lty = 1) text(0,0.95, label = "(A)", xpd = NA) functionalresponse(-0.3,30,0.2) # have a max(0, yy) so will give 0 if yy goes negative alpha = 0.51; slope = 15; beta = 0.1 yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) lines(xx,yy, col = "black", lty = 2) alpha = -0.3; slope = 30; beta = 0.15 yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) lines(xx,yy, col = "red") alpha = 0.41; slope = 15; beta = 0.05 yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) lines(xx,yy, col = "red", lty = 2) alpha = -0.3; slope = 30; beta = 0.1 yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) lines(xx,yy, col = "blue") alpha = 0.2; slope = 15; beta = 0 yy <- alpha + (1-alpha)/(1.0+exp(-slope*(xx-beta))) lines(xx,yy, col = "blue", lty = 2) legend("bottomright", legend = c("Fledge 1 of 3 chicks", "Fledge 1 of 2 chicks", "Fledge 1 of 1 chick"), col = c("Black", "Red", "Blue"), lty = c(1,1,1), y.intersp=1, bty = 'n') abline(v = 0.33, col = 'grey', lty = 4) par(xpd = NA) mtext(expression(paste('Relative Prey Availability (P'['y,s,l'],' / ',tilde(P)['l'],')')), side = 1, outer = TRUE, line = 1) mtext(expression(paste('Demographic Rate Modifier (',delta['y,s,l'],' or ',gamma['y,s,l'], ')')), side = 2, outer = TRUE, line = 1, padj = 0) text(0,0.95, label = "(B)", xpd = NA) # param_fledge_special = c(-0.3,30,0.2) # # enough like 1/3 for the birds - i think so, and looks like Andre's # param_fledge_general = c(0.51,15,0.1) # so at some lower survival, switch and survival goes back to 1? # # param_fledge2_special = c(-0.3,30,0.15) # param_fledge2_general = c(0.41,15,0.05) # *will 2nd and 3rd chick still apply for generalist who just switched anyway? # # param_fledge3_special = c(-0.3,30,0.1) # param_fledge3_general = c(0.2,15,0)
c56fe033019049ef5b80d3b8d65ceb552198014b
dde67e60fd78b0b30c68c3a877ee095aa931da55
/man/scNGP.data.Rd
09ed8c201948332f826898f32f2df60393633186
[]
no_license
CenterForStatistics-UGent/PIMseq
0ff61a203c806fa3ea65c15f097ef0500e8d800b
31e0463a09b1eb56a3be018cb26fcfe072f180a7
refs/heads/master
2021-07-09T16:33:17.211694
2020-09-05T10:20:31
2020-09-05T10:20:31
191,369,264
2
1
null
2019-07-10T10:25:58
2019-06-11T12:41:45
R
UTF-8
R
false
true
725
rd
scNGP.data.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/NGPscData.R \docType{data} \name{scNGP.data} \alias{scNGP.data} \title{Neuroblastoma cell line single cell RNA-seq.} \format{A SingleCellExperiment object} \source{ \url{http://dx.doi.org/10.1101/430090} } \usage{ scNGP.data } \description{ Contains 83 cell line neuroblastoma cells (31 nutlin-3 treated and 52 controls). The data is generated using SMARTer/C1 protocol. } \references{ Verboom, K., Everaert, C., Bolduc, N., Livak, K. J., Yigit, N., Rombaut, D., ... & Mestdagh, P. (2018). SMARTer single cell total RNA sequencing. BioRxiv, 430090. \describe{ \item{SingleCellExperiment}{counts + gene info+cell infro} } } \keyword{datasets}
13dfdf6070c787dc8ddeef5c77fe60876226f56a
d3f96c9ca845fc5b38ef9e7bd4c53b3f06beb49b
/man/system_check_requirements.Rd
93c656b96b4da081160d5340395c3a5492d08ed5
[ "BSD-3-Clause" ]
permissive
john-harrold/ubiquity
92f08e4bebf0c4a17f61e2a96ae35d01ba47e5a2
bb0532915b63f02f701148e5ae097222fef50a2d
refs/heads/master
2023-08-16T17:43:52.698487
2023-08-16T01:24:48
2023-08-16T01:24:48
121,585,550
9
3
null
null
null
null
UTF-8
R
false
true
684
rd
system_check_requirements.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/ubiquity.R \name{system_check_requirements} \alias{system_check_requirements} \title{Check For Perl and C Tools} \usage{ system_check_requirements( checklist = list(perl = list(check = TRUE, perlcmd = "perl"), C = list(check = TRUE)), verbose = TRUE ) } \arguments{ \item{checklist}{list with names corresponding to elements of the system to check.} \item{verbose}{enable verbose messaging} } \value{ List fn result of all packages } \description{ Check the local installation for perl and verify C compiler is installed and working. } \examples{ \donttest{ invisible(system_check_requirements()) } }
510fc5761191d4e059e6494071c4da75100d752a
580484276bd35b209fb3bf1a8ad134226c9363da
/Code/Download_Files.R
ba6688f28a067514b98d67c763c6d11dcab7b98c
[]
no_license
jbrittain72/MSDS_6306_Case_Study_1
8d4ba5ceb1e0f711319d7c0712fb36e8fe8cd5fb
240977dd29682b0af8c93f2c3e6cad7a484eeec4
refs/heads/master
2021-01-12T14:40:29.868900
2016-10-29T03:17:21
2016-10-29T03:17:21
72,046,599
0
0
null
null
null
null
UTF-8
R
false
false
846
r
Download_Files.R
############################################ ## Download Case Study 1 Data Files ## Jim Brittain ## 2016-10-27 ############################################ ### This make file will creat a folder (if it doesn't already exist) and ### download the required files for the Case Study 1 # Create a subfolder to download data files to if not present if (file.exists("Download_Files")){ setwd(file.path(MainDir, "Download_Files")) } else { dir.create(file.path(MainDir, "Download_Files")) setwd(file.path(MainDir, "Download_Files")) } # Download files to Download folder download.file(url="https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FGDP.csv", destfile="GDP.csv") download.file(url="https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FEDSTATS_Country.csv", destfile="EDSTATS_Country.csv")
8e0cef26e98b2eee337f7a55f1bc227b8d72a0bc
c2af459079b844373ffbb97c15afd93a785c107a
/textmining.R
a58c2b883b084d12133511736f4b24c44033753c
[]
no_license
TonyNdungu/Unsupervised_learning
4af19516ef509a18a20c48f76b8df45d5bd33f29
da030047114792860a6683df91c283cd7c9d2b67
refs/heads/master
2020-04-22T05:15:05.598461
2019-03-27T13:37:45
2019-03-27T13:37:45
170,153,302
0
0
null
null
null
null
UTF-8
R
false
false
6,516
r
textmining.R
# Load libraries library(twitteR) # Twitter API Oauth process. consumer_key <- 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' consumer_secret <- 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' access_token <- 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' access_secret <- 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' setup_twitter_oauth(consumer_key, consumer_secret, access_token, access_secret) # retrieve the first 200 tweets from the timeline of @Rdatamining rdmTweets <- userTimeline("rdatamining", n=200) (nDocs <- length(rdmTweets)) # Have a look at the five tweets numbered 11 to 15 rdmTweets[11:15] # Wrapping the tweets to fit the width of paper for (i in 11:15) { cat(paste("[[", i, "]] ", sep="")) writeLines(strwrap(rdmTweets[[i]]$getText(), width=73)) } #convert tweets to a data frame df <- do.call("rbind", lapply(rdmTweets, as.data.frame)) dim(df) # build a corpus, and specify the source to be character vectors library(tm) myCorpus <- Corpus(VectorSource(df$text)) # convert to lower case myCorpus <- tm_map(myCorpus, tolower) # remove punctuation myCorpus <- tm_map(myCorpus, removePunctuation) # remove numbers myCorpus <- tm_map(myCorpus, removeNumbers) # remove URLs removeURL <- function(x) gsub("http[[:alnum:]]*", "", x) myCorpus <- tm_map(myCorpus, removeURL) # add two extra stop words: "available" and "via" myStopwords <- c(stopwords('english'), "available", "via") # remove "r" and "big" from stopwords myStopwords <- setdiff(myStopwords, c("r", "big")) # remove stopwords from corpus myCorpus <- tm_map(myCorpus, removeWords, myStopwords) library(SnowballC) # keep a copy of corpus to use later as a dictionary for stem completion myCorpusCopy <- myCorpus # stem words myCorpus <- tm_map(myCorpus, stemDocument) # inspect documents (tweets) numbered 11 to 15 # inspect(myCorpus[11:15]) # The code below is used for to make text fit for paper width for (i in 11:15) { cat(paste("[[", i, "]] ", sep="")) writeLines(strwrap(myCorpus[[i]], width=73)) } # stem completion myCorpus <- tm_map(myCorpus, stemCompletion, dictionary=myCorpusCopy) #count frequency of "mining" miningCases <- tm_map(myCorpusCopy, grep, pattern="\\<mining") sum(unlist(miningCases)) # count frequency of "miners" minerCases <- tm_map(myCorpusCopy, grep, pattern="\\<miners") sum(unlist(minerCases)) # replace "miners" with "mining" myCorpus <- tm_map(myCorpus, gsub, pattern="miners", replacement="mining") # Build a term document matrix myTdm <- TermDocumentMatrix(myCorpus, control=list(wordLengths=c(1,Inf))) myTdm <- TermDocumentMatrix(myCorpus, control=list(minWordLength=1)) # inspect frequent words findFreqTerms(myTdm, lowfreq=10) termFrequency <- rowSums(as.matrix(myTdm)) termFrequency <- subset(termFrequency, termFrequency>=10) library(ggplot2) qplot(names(termFrequency), termFrequency, geom="bar", xlab="Terms") + coord_flip() barplot(termFrequency, las=2) # which words are associated with "r"? findAssocs(myTdm, 'r', 0.25) # which words are associated with "mining"? findAssocs(myTdm, 'mining', 0.25) library(wordcloud) m <- as.matrix(myTdm) # calculate the frequency of words and sort it descendingly by frequency wordFreq <- sort(rowSums(m), decreasing=TRUE) # word cloud set.seed(375) # to make it reproducible grayLevels <- gray( (wordFreq+10) / (max(wordFreq)+10) ) wordcloud(words=names(wordFreq), freq=wordFreq, min.freq=3, random.order=F, colors=grayLevels) # Clustering words # remove sparse terms myTdm2 <- removeSparseTerms(myTdm, sparse=0.95) m2 <- as.matrix(myTdm2) # cluster terms distMatrix <- dist(scale(m2)) fit <- hclust(distMatrix, method="ward") plot(fit) # cut tree into 10 clusters rect.hclust(fit, k=10) (groups <- cutree(fit, k=10)) # change it to a Boolean matrix termDocMatrix[termDocMatrix>=1] <- 1 # transform into a term-term adjacency matrix termMatrix <- termDocMatrix %*% t(termDocMatrix) # inspect terms numbered 5 to 10 termMatrix[5:10,5:10] #============================================================ # transpose the matrix to cluster documents (tweets) m3 <- t(m2) # set a fixed random seed set.seed(122) # k-means clustering of tweets k <- 8 kmeansResult <- kmeans(m3, k) # cluster centers round(kmeansResult$centers, digits=3) #Check the top 3 words in every cluster for (i in 1:k) { cat(paste("cluster ", i, ": ", sep="")) s <- sort(kmeansResult$centers[i,], decreasing=T) cat(names(s)[1:3], "\n") # print the tweets of every cluster # print(rdmTweets[which(kmeansResult$cluster==i)]) } # Clustering tweets with k-medoid algorithm library(fpc) # partitioning around medoids with estimation of number of clusters pamResult <- pamk(m3, metric="manhattan") # number of clusters identified (k <- pamResult$nc) pamResult <- pamResult$pamobject # print cluster medoids for (i in 1:k) { cat(paste("cluster", i, ": ")) cat(colnames(pamResult$medoids)[which(pamResult$medoids[i,]==1)], "\n") # print tweets in cluster i # print(rdmTweets[pamResult$clustering==i]) } # plot clustering result layout(matrix(c(1,2),2,1)) # set to two graphs per page plot(pamResult, color=F, labels=4, lines=0, cex=.8, col.clus=1, col.p=pamResult$clustering) layout(matrix(1)) # change back to one graph per page pamResult2 <- pamk(m3, krange=2:8, metric="manhattan") # LoadTerm document matrix # #Inspect part of the matrix m2[5:10,1:20] # change it to a Boolean matrix m2[m2>=1] <- 1 # transform into a term-term adjacency matrix m2 <- m2 %*% t(m2) # inspect terms numbered 5 to 10 m2[5:10,5:10] library(igraph) # build a graph from the above matrix g <- graph.adjacency(m2, weighted=T, mode="undirected") # remove loops g <- simplify(g) # set labels and degrees of vertices V(g)$label <- V(g)$name V(g)$degree <- degree(g) # Plot the network with layout # set seed to make the layout reproducible set.seed(3952) layout1 <- layout.fruchterman.reingold(g) plot(g, layout=layout1) #Details about other layout options plot(g, layout=layout.kamada.kawai) tkplot(g, layout=layout.kamada.kawai) V(g)$label.cex <- 2.2 * V(g)$degree / max(V(g)$degree)+ .2 V(g)$label.color <- rgb(0, 0, .2, .8) V(g)$frame.color <- NA egam <- (log(E(g)$weight)+.4) / max(log(E(g)$weight)+.4) E(g)$color <- rgb(.5, .5, 0, egam) E(g)$width <- egam # plot the graph in layout1 plot(g, layout=layout1)
ea5847a3845b6cf23dafc7092bdf66c869b83b51
517f85614328e6facc3134dcbda0efffca9c4370
/recode.R
2527c1fbe4ae975002cf32afb30b2d56e206f153
[]
no_license
fishforwish/fgc
2dce9636aebaee4a73396de8a9dd52b7603b190d
1cf825b1b35214fc7829816b64970d8c768738ac
refs/heads/master
2023-03-17T19:14:45.927645
2023-03-09T10:27:26
2023-03-09T10:27:26
47,423,818
0
0
null
null
null
null
UTF-8
R
false
false
2,388
r
recode.R
## Recode all problematic DHS entries print("####################### RTARGET ####################") library(gdata) library(dplyr) ## Reweight before subsetting. Answers <- (Answers ## Reweight before subsetting %>% mutate(sampleWeight = sampleWeight/sum(sampleWeight)) ## subset: Don't want people who never heard of FGC (heardFGC and heardGC) and visitors %>% filter((!is.na(heardFGC) & substr(heardFGC, 1, 3) == "Yes") | (!is.na(heardGC) & substr(heardGC, 1, 3) == "Yes") ) %>% filter(!is.na(visitorResident) & !grepl("Visitor", visitorResident)) ) # Ideally, I like to have a variable as daughterFGC (daughter's FGC status) which involves a few variables: numDaughterFgced (already cut; 95 and 0=none cut), and daughterToFgc. Those variables provides answers of yes (already cut), no (none cut), plan to cut, plan not to be cut, and don't know the plan yet. I like to make it a single outcome measurement with 6 levels: yes/to be cut, yes/not to be cut, no/to be cut, no/not to be cut, yes/don't know, no/don't know. Answers <- (Answers %>% mutate(daughterFgced = ifelse(numDaughterFgced == 95, "No", "Yes") , daughterFgced = ifelse(numDaughterFgced == 0, "Yes", daughterFgced) , daughterFgced = factor(daughterFgced) , continueFgc = ifelse(continueFgc == "Don't know", "Depends", as.character(continueFgc)) , continueFgc = factor(continueFgc) , daughterNotFgced = ifelse(daughterNotFgced == "Don't know", NA, as.character(daughterNotFgced)) , daughterNotFgced = factor(daughterNotFgced) , CC = substring(survey, 1, 2) , CC = as.factor(CC) , recode = substring(survey, 3, 3) , recode = as.numeric(recode) , region = as.factor(paste(CC, region, sep="_")) , clusterId = as.factor(paste(survey, clusterId, sep="_")) , ethni = as.factor(paste(CC, ethni, sep="_")) , religion = tableRecode(religion, "religion", maxCat=4) , maritalStat = tableRecode(maritalStat, "partnership", maxCat=4) , wealth = wealth/100000 , fgcstatus = fgc , fgc = rightfactor(fgc) , Education = edu , edu = rightfactor(edu) , edu = edu / mean(edu, na.rm = TRUE) , Persist = contfgc(continueFgc) , Persist01 = contfgc01(continueFgc) , daughterPlan = yesnodkFactor(daughterToFgc) , daughterPlan01 = yesnodk01(daughterToFgc) , Religion = religion , MaritalStatus = maritalStat , Residence = urRural , Job = job ) ) # rdsave(Answers)
645ebb9516e6391075d90abc2b0a171a6e94d4a5
06772dd41870da689df082609992e032970bac12
/R/plot.kora.samples.R
785fe00116f079df144370dfc97c3f1abe272c5a
[]
no_license
TheSeoman/Scripts
6c5ffa94d4c0e144a31f9f9e54ca324d90586ee0
3fb59b6ac7e24c6dba266d47ca7aeedbb2bb57c1
refs/heads/master
2021-05-15T15:00:56.679283
2018-04-11T18:03:39
2018-04-11T18:03:39
107,265,319
0
0
null
null
null
null
UTF-8
R
false
false
3,787
r
plot.kora.samples.R
source('Scripts/R/paths.R') require(gplots) library(VennDiagram) load(PATHS$METH.RESIDUALS.DATA) load(PATHS$EXPR.RESIDUALS.DATA) load(PATHS$SNP.SAMPLES.DATA) covariates.all <- read.table(PATHS$F.COVARIATES, sep = ";", header = TRUE) covariates.all$expr_s4f4ogtt <- as.character(covariates.all$expr_s4f4ogtt) covariates.all$axio_s4f4 <- as.character(covariates.all$axio_s4f4) covariates.all$meth_f4 <- as.character(covariates.all$meth_f4) id.map <- covariates.all[as.character(covariates.all$expr_s4f4ogtt) %in% rownames(expr.residuals) | as.character(covariates.all$axio_s4f4) %in% snp.samples | covariates.all$meth_f4 %in% rownames(meth.residuals), ] id.map <- id.map[order(id.map$expr_s4f4ogtt),] get.covariate.overview <- function(covariates.map) { overview <- data.frame(matrix(ncol = 4, nrow = 3)) rownames(overview) <- c('Age', 'BMI', 'WBC') colnames(overview) <- c('Covariate', 'Minimum', 'Maximum', 'Mean') overview[1, ] <- c('Age', min(covariates.map$utalteru), max(covariates.map$utalteru), format(mean(covariates.map$utalteru), digits = 4)) overview[2, ] <- c('BMI' ,min(na.omit(covariates.map$utbmi)), max(na.omit(covariates.map$utbmi)), format(mean(na.omit(covariates.map$utbmi)), digits = 4)) overview[3, ] <- c('WBC', min(na.omit(covariates.map$ul_wbc)), max(na.omit(covariates.map$ul_wbc)), format(mean(na.omit(covariates.map$ul_wbc)), digits = 3)) return(overview) } full.kora.overview <- get.covariate.overview(id.map) select.id.map <- id.map[id.map$expr_s4f4ogtt %in% rownames(expr.residuals) & id.map$axio_s4f4 %in% snp.samples & id.map$meth_f4 %in% rownames(meth.residuals),] select.kora.overview <- get.covariate.overview(select.id.map) write.table(full.kora.overview, file = paste0(PATHS$TABLE.DIR, 'full.covariate.overview.tsv'), quote = F, sep = '\t', row.names = F, col.names = T) write.table(select.kora.overview, file = paste0(PATHS$TABLE.DIR, 'select.covariate.overview.tsv'), quote = F, sep = '\t', row.names = F, col.names = T) expr.count <- sum(id.map$expr_s4f4ogtt %in% rownames(expr.residuals)) snp.count <- sum(id.map$axio_s4f4 %in% snp.samples) meth.count <- sum(id.map$meth_f4 %in% rownames(meth.residuals)) pdf(file = paste0(PATHS$PLOT.DIR, 'samples_venn.pdf'), width = 4.5, height = 2) grid.newpage() venn.plot <- draw.triple.venn(area1 = expr.count, area2 = snp.count, area3 = meth.count, n12 = sum(id.map$expr_s4f4ogtt %in% rownames(expr.residuals) & id.map$axio_s4f4 %in% snp.samples), n13 = sum(id.map$expr_s4f4ogtt %in% rownames(expr.residuals) & id.map$meth_f4 %in% rownames(meth.residuals)), n23 = sum(id.map$axio_s4f4 %in% snp.samples & id.map$meth_f4 %in% rownames(meth.residuals)), n123 = sum(id.map$expr_s4f4ogtt %in% rownames(expr.residuals) & id.map$axio_s4f4 %in% snp.samples & id.map$meth_f4 %in% rownames(meth.residuals)), category = c(paste0('Expression (', expr.count, ')'), paste0('Genotype (', snp.count, ')'), paste0('Methylation (', meth.count, ')')), fill = c('red', 'blue', 'yellow'), cex = c(1), cat.cex = c(1), euler.d = T, scaled = T, cat.dist = c(0.07, 0.07, 0.04), cat.pos = c(330, 30, 180)) dev.off() grid.draw(venn.plot)
67660fe00164e929cde897920127c0de5e6f2bc2
f89f43fe4f7fc6fec03716da4271679a605114a5
/scripts/ggprob.R
d846f2446f337924547517c717f57ac9180b1170
[]
no_license
DrSpecial/An-in-depth-analysis-about-how-the-NBA-has-changed-over-time
4f941ffd482c13b0645b69fc1333859b3612cc72
0ee32e2248959569f5f4618b0858c8f0662c4adc
refs/heads/main
2023-08-12T22:56:32.307323
2021-09-30T20:43:39
2021-09-30T20:43:39
412,182,960
1
0
null
null
null
null
UTF-8
R
false
false
7,396
r
ggprob.R
require(tidyverse) ### binomial gbinom_default_a = function(n, p, scale = FALSE) { a = ifelse(scale, floor(n*p - 4*sqrt(n*p*(1-p))),0) return (a) } gbinom_default_b = function(n, p, scale = FALSE) { b = ifelse(scale, floor(n*p + 4*sqrt(n*p*(1-p))),n) return (b) } geom_binom_density = function(n = 1, p = 0.5, scale = FALSE, a=NULL, b=NULL, color="blue", ...) { if ( is.null(a) ) { a = gbinom_default_a(n, p, scale) } if ( is.null(b) ) { b = gbinom_default_b(n, p, scale) } # make sure a and b are integers a = round(a) b = round(b) # make sure a < b if(a > b) { temp = a a = b b = temp } # make sure a and b are in range if(a < 0) a = 0 if(b > n) b = n dat = tibble( x = seq(a,b,1), xend = x, y = dbinom(x,n,p), yend = rep(0, length(y))) geom_segment(aes(x = x, xend = xend, y = y, yend = yend), data = dat, color = color, ...) } gbinom = function(n,p,scale = FALSE, a = gbinom_default_a(n,p,scale), b = gbinom_default_b(n,p,scale), color = "blue", title = TRUE, ...) { g = ggplot() g = g + geom_binom_density(n, p, scale, a, b, color, ...) + xlab('x') + ylab('Probability') + geom_hline(yintercept=0) if ( title ) { g = g + ggtitle( paste("Binomial(",n,",",p,")") ) } return( g ) } ### normal geom_norm_density = function(mu=0,sigma=1,a=NULL,b=NULL,color="blue",...) { if ( is.null(a) ) { a = qnorm(0.0001,mu,sigma) } if ( is.null(b) ) { b = qnorm(0.9999,mu,sigma) } x = seq(a,b,length.out=1001) df = data.frame( x=x, y=dnorm(x,mu,sigma) ) geom_line(aes(x=x,y=y), data = df, color=color,...) } geom_norm_fill = function(mu=0,sigma=1,a=NULL,b=NULL, fill="firebrick4",...) { if ( is.null(a) ) { a = qnorm(0.0001,mu,sigma) } if ( is.null(b) ) { b = qnorm(0.9999,mu,sigma) } x = seq(a,b,length.out=1001) df = data.frame( x=x, ymin=rep(0,length(x)), ymax = dnorm(x,mu,sigma) ) geom_ribbon(aes(x=x,ymin=ymin,ymax=ymax,y=NULL), data = df, fill = fill, ...) } gnorm = function(mu=0,sigma=1,a=NULL,b=NULL,color="blue", fill=NULL,title=TRUE,...) { g = ggplot() if ( !is.null(fill) ) g = g + geom_norm_fill(mu,sigma,a,b,fill) g = g + geom_norm_density(mu,sigma,a,b,color,...) + geom_hline(yintercept=0) + ylab('density') if ( title ) g = g + ggtitle(paste("N(",mu,",",sigma,")")) return ( g ) } ### chi-square geom_chisq_null_a = function(df) { if ( df < 2 ) a = qchisq(0.05,df) else a = qchisq(0.0001,df) return ( a ) } geom_chisq_null_b = function(df) { if ( df < 2 ) b = qchisq(0.95,df) else b = qchisq(0.9999,df) return ( b ) } geom_chisq_density = function(df=1,a=NULL,b=NULL,color="blue",...) { if ( is.null(a) ) a = geom_chisq_null_a(df) if ( is.null(b) ) b = geom_chisq_null_b(df) x = seq(a,b,length.out=1001) dat = data.frame( x=x, y=dchisq(x,df) ) geom_line(data=dat,aes(x=x,y=y),color=color,...) } geom_chisq_fill = function(df=1,a=NULL,b=NULL, fill="firebrick4",...) { if ( is.null(a) ) a = geom_chisq_null_a(df) if ( is.null(b) ) b = geom_chisq_null_b(df) x = seq(a,b,length.out=1001) dat = data.frame( x=x, ymin=rep(0,length(x)), ymax = dchisq(x,df) ) geom_ribbon(data=dat,aes(x=x,ymin=ymin,ymax=ymax,y=NULL),fill=fill,...) } gchisq = function(df=1,a=NULL,b=NULL,color="blue", fill=NULL,title=TRUE,...) { g = ggplot() if ( !is.null(fill) ) g = g + geom_chisq_fill(df,a,b,fill) g = g + geom_chisq_density(df,a,b,color,...) + geom_hline(yintercept=0) + ylab('density') if ( title ) g = g + ggtitle(paste("Chi-square(",df,")")) return ( g ) } ### t geom_t_density = function(df=1,a=NULL,b=NULL,color="blue",...) { if ( is.null(a) ) a = qt(0.0001,df) if ( is.null(b) ) b = qt(0.9999,df) x = seq(a,b,length.out=1001) dat = data.frame( x=x, y=dt(x,df) ) geom_line(data=dat,aes(x=x,y=y),color=color,...) } geom_t_fill = function(df=1,a=NULL,b=NULL, fill="firebrick4",...) { if ( is.null(a) ) a = qt(0.0001,df) if ( is.null(b) ) b = qt(0.9999,df) x = seq(a,b,length.out=1001) dat = data.frame( x=x, ymin=rep(0,length(x)), ymax = dt(x,df) ) geom_ribbon(data=dat,aes(x=x,ymin=ymin,ymax=ymax,y=NULL),fill=fill,...) } gt = function(df=1,a=NULL,b=NULL,color="blue", fill=NULL,title=TRUE,...) { g = ggplot() if ( !is.null(fill) ) g = g + geom_t_fill(df,a,b,fill) g = g + geom_t_density(df,a,b,color,...) + geom_hline(yintercept=0) + ylab('density') if ( title ) g = g + ggtitle(paste("t(",round(df,3),")")) return ( g ) } ### F geom_f_density = function(df1=1,df2=1,a=NULL,b=NULL,color="blue",...) { if ( is.null(a) ) a = qf(0.0001,df1,df2) if ( is.null(b) ) b = qf(0.9999,df1,df2) x = seq(a,b,length.out=1001) dat = data.frame( x=x, y=df(x,df1,df2) ) geom_line(data=dat,aes(x=x,y=y),color=color,...) } geom_f_fill = function(d1f=1,df2=1,a=NULL,b=NULL, fill="firebrick4",...) { if ( is.null(a) ) a = qf(0.0001,df1,df2) if ( is.null(b) ) b = qf(0.9999,df1,df2) x = seq(a,b,length.out=1001) dat = data.frame( x=x, ymin=rep(0,length(x)), ymax = df(x,df1,df2) ) geom_ribbon(data=dat,aes(x=x,ymin=ymin,ymax=ymax,y=NULL),fill=fill,...) } gf = function(df1=1,df2=1,a=NULL,b=NULL,color="blue", fill=NULL,title=TRUE,...) { g = ggplot() if ( !is.null(fill) ) g = g + geom_f_fill(df1,df2,a,b,fill) g = g + geom_f_density(df1,df2,a,b,color,...) + geom_hline(yintercept=0) + ylab('density') if ( title ) g = g + ggtitle(paste("F(",df1,",",df2,")")) return ( g ) } ### beta geom_beta_null_a = function(alpha,beta) { if ( alpha >= 1) a = 0 else a = 0.01 return ( a ) } geom_beta_null_b = function(alpha,beta) { if ( beta >= 1 ) b = 1 else b = 0.99 return ( b ) } geom_beta_density = function(alpha=1, beta=1, a=NULL, b=NULL, color="blue",...) { if ( is.null(a) ) a = geom_beta_null_a(alpha,beta) if ( is.null(b) ) b = geom_beta_null_b(alpha,beta) x = seq(a,b,length.out=1001) dat = data.frame( x=x, y=dbeta(x,alpha,beta) ) geom_line(data=dat,aes(x=x,y=y),color=color,...) } geom_beta_fill = function(alpha=1,beta=1,a=NULL,b=NULL, fill="firebrick4",...) { if ( is.null(a) ) a = geom_beta_null_a(alpha,beta) if ( is.null(b) ) b = geom_beta_null_b(alpha,beta) x = seq(a,b,length.out=1001) dat = data.frame( x=x, ymin=rep(0,length(x)), ymax = dbeta(x,alpha,beta) ) geom_ribbon(data=dat,aes(x=x,ymin=ymin,ymax=ymax,y=NULL),fill=fill,...) } gbeta = function(alpha=1,beta=1,a=NULL,b=NULL,color="blue", fill=NULL,title=TRUE,...) { g = ggplot() if ( !is.null(fill) ) g = g + geom_beta_fill(alpha,beta,a,b,fill) g = g + geom_beta_density(alpha,beta,a,b,color,...) + geom_hline(yintercept=0) + ylab('density') if ( title ) g = g + ggtitle(paste("Beta(",alpha,",",beta,")")) return ( g ) }
da24ea459e701f25d004b3b41f605cb22bbdad2d
499e407e5f3f16b7f5ed1905a9e150d41a8fe3ba
/workingfiles/ProjRShiny_my/global.R
a3e5af6ba4b5d85223d6b3cdbd152553789400ff
[]
no_license
cjy93/LTA_bus_analysis
93b360052680551d101f2b64781fb11a0262e73b
4293a2868500e7f566eef0b561aaf93075881f6b
refs/heads/master
2022-05-27T18:21:05.073801
2020-05-02T12:30:17
2020-05-02T12:30:17
242,526,627
0
0
null
null
null
null
UTF-8
R
false
false
7,187
r
global.R
## Library packages library(shiny) library(dplyr) library(tidyverse) library(shinydashboard) library(flows) library(maptools) library(st) library(leaflet) library(reshape2) library(igraph) library(ggraph) library(tidygraph) library(tmap) library(flows) library(sp) library(RColorBrewer) library(plotly) library(ggthemes) suppressWarnings(as.numeric(c("1", "2", "X"))) ##################################################### Import data here ######################################################### # busstop volume busstop_volume <- read.csv("data/passenger volume by busstop.csv") colnames(busstop_volume)[5] = "BusStopCode" busstop_volume$BusStopCode <- as.character(busstop_volume$BusStopCode) # busstop information busstops <- read.csv("data/busstop_lonlat_subzone_District.csv")%>% dplyr::filter(planning_area != "Invalid") busstops$subzone_name_my <- busstops$subzone_name busstops$BusStopCode <- as.integer(busstops$BusStopCode) busstops$BusStopCode <- as.character(busstops$BusStopCode) busstops$planning_area <- as.character(busstops$planning_area) busstops$planning_area[busstops$planning_area %in% c('Central Water Catchment', 'Mandai', 'Marina South', 'Museum', 'Newton', 'Orchard', 'Outram', 'Seletar', 'Rochor', 'Singapore River', 'Tanglin', 'Southern Islands', 'River Valley', 'Paya Lebar', 'Straits View', 'Tengah')] <- "Others" #bus route busroute <- read_csv('data/bus_route_overall.csv') busroute$BusStopCode <- as.integer(busroute$BusStopCode) busroute$BusStopCode <- as.character(busroute$BusStopCode) busroute <- busroute[c('BusStopCode', 'Direction', 'Distance', 'ServiceNo', 'StopSequence')] busroute <- busroute[busroute$BusStopCode %in% as.list(unique(busstops['BusStopCode']))[['BusStopCode']], ] ## Origin Destination data ##################################################### Mengyong Proportionate symbol map######################################################### busstop_volume_lat_long_my <- dplyr::inner_join(busstop_volume, busstops, by ='BusStopCode') location_my <- busstop_volume_lat_long_my %>% dplyr::group_by(BusStopCode)%>% dplyr::arrange(desc(BusStopCode)) location_my <- plyr::rename(location_my, c('Latitude'= 'lat' , 'Longitude'= 'lon' )) #location_my$tap_in_out_radius <- (location_my$TOTAL_TAP_IN_VOLUME + location_my$TOTAL_TAP_OUT_VOLUME)**(1/2)/6 location_my <- location_my[c('planning_area', 'subzone_name_my', 'DAY_TYPE', 'TIME_PER_HOUR', 'BusStopCode', 'Description', 'RoadName', 'TOTAL_TAP_IN_VOLUME', 'TOTAL_TAP_OUT_VOLUME', 'lon', 'lat')] location_my <- plyr::rename(location_my, c("DAY_TYPE" = "Day" , "TOTAL_TAP_IN_VOLUME"= "TapIns" , "TOTAL_TAP_OUT_VOLUME"= "TapOuts" ,"TIME_PER_HOUR"= "Time" , "planning_area"= "PlanningArea" )) location_my <- location_my %>% dplyr::filter(Time >=6 & Time <= 23) planning_area_list_my <-sort(unique(location_my$PlanningArea)) #pal <- colorNumeric(palette = "RdPu", domain = location_my$TapIns*2) ##################################################### Mengyong Centrality######################################################### busroute_2 <- busroute busroute_2['StopSequence'] = busroute_2['StopSequence']-1 busroute_2['BusStopCode_dest'] = busroute_2['BusStopCode'] busroute_2 <- busroute_2[c('BusStopCode_dest', 'Direction', 'ServiceNo', 'StopSequence')] busstops_from_to <- dplyr::inner_join(busroute, busroute_2, by =c('StopSequence', 'ServiceNo', 'Direction')) #join the two tables together busroute_busstop <- dplyr::inner_join(busstops_from_to, busstops, by ='BusStopCode') keeps <- c('BusStopCode', 'BusStopCode_dest') busroute_busstop <- busroute_busstop[, keeps, drop = FALSE] busroute_busstop <- plyr::rename(busroute_busstop, c("BusStopCode" = "from")) busroute_busstop <- plyr::rename(busroute_busstop,c("BusStopCode_dest" = "to")) #groupby busroute_busstop_aggregated <- busroute_busstop %>% #group_by(from, to, planning_area) %>% dplyr::group_by(from, to) %>% dplyr::summarise(Weight = n()) %>% dplyr::filter(from!=to) %>% dplyr::filter(Weight > 0) %>% dplyr::ungroup() busroute_busstop_aggregated$from <- as.character(busroute_busstop_aggregated$from) busroute_busstop_aggregated$to <- as.character(busroute_busstop_aggregated$to) #nodes nodes_my <- busstops nodes_my <- plyr::rename(nodes_my,c("BusStopCode" = "id" )) nodes_my$id <- as.character(nodes_my$id) #create graph structure bus_graph <- tbl_graph(nodes = nodes_my, edges = busroute_busstop_aggregated, directed = TRUE) #extract centrality bus_graph=bus_graph%>%mutate(betweenness_centrality = centrality_betweenness(normalized = TRUE)) %>%mutate(closeness_centrality = centrality_closeness(normalized = TRUE)) %>% dplyr::mutate(degree_centrality=centrality_degree(mode='out',normalized = TRUE)) bus_graph = bus_graph %>% dplyr::mutate(eigen_centrality=centrality_eigen(weight = bus_graph$betweenness_centrality, directed = TRUE, scale = FALSE)) #get edge table plot_vector2<- as.data.frame(cbind(V(bus_graph)$Longitude,V(bus_graph)$Latitude,V(bus_graph)$betweenness_centrality,V(bus_graph)$closeness_centrality, V(bus_graph)$eigen_centrality,V(bus_graph)$degree_centrality)) edgelist <- get.edgelist(bus_graph) edgelist[,1]<-as.numeric(match(edgelist[,1],V(bus_graph))) edgelist[,2]<-as.numeric(match(edgelist[,2],V(bus_graph))) node1=data.frame(plot_vector2[edgelist[,1],]) node2=data.frame(plot_vector2[edgelist[,2],]) node3=data.frame(cbind(node1,node2)) edge_table <- plyr::rename(node3,c("V1" = "long.f" , "V2" = "lat.f" , "V1.1" = "long.t" , "V2.1"= "lat.t" , "V3" = "between.f" , "V4"= "closeness.f","V5"= "eigen.f" , "V6" = "degree.f" )) edge_table<- edge_table %>% dplyr::left_join(busstops, by =c("long.f"= "Longitude", "lat.f" = "Latitude")) keeps <- c("long.f","lat.f","long.t","lat.t", "planning_area", 'subzone_name_my', "between.f", "closeness.f", "eigen.f","degree.f" ) edge_table <- edge_table[ , (names(edge_table) %in% keeps)] #range01 <- function(x){(x-min(x))/(max(x)-min(x))} range01 <- function(x) trunc(rank(x))/length(x) edge_table$between.f <-range01(edge_table$between.f) edge_table$closeness.f <-range01(edge_table$closeness.f) edge_table$eigen.f <-range01(edge_table$eigen.f) edge_table$degree.f <-range01(edge_table$degree.f) # get node table map_table <- plyr::rename(plot_vector2,c("V1"="long.f" , "V2"="lat.f" , "V3"="between.f" , "V4"="closeness.f" , "V5"="eigen.f" ,"V6"= "degree.f" )) map_table <- map_table %>% dplyr::left_join(busstops, by =c("long.f"= "Longitude", "lat.f" = "Latitude")) map_table$between.f <-round(range01(map_table$between.f),3) map_table$closeness.f <-round(range01(map_table$closeness.f),3) map_table$eigen.f <-round(range01(map_table$eigen.f),3) map_table$degree.f <-round(range01(map_table$degree.f),3) #write.csv(map_table,"Path where you'd like to export the DataFrame\\File Name.csv", row.names = FALSE) #get the radius of the bubbles map_table$combined.f = (map_table$between.f*3+1)**(3/4) + (map_table$closeness.f*3+1)**(3/4) + (map_table$eigen.f*3+1)**(3/4) + (map_table$degree.f*3+1)**(3/4)
7b3dd89a99c73e48fa30ca25d2a5d1764db51d2d
0d0104d63657026b3c987e65ba07e0c87e8cb549
/theApp/data_GSE148729_Calu3_totalRNA/deprecated_theApp.R
dd9b6d731f50f2eca63a5dc39dc8ec1107d554af
[]
no_license
EuancRNA/Pan-Coronavirus-Gene-Regulatory-Networks
765b1fa09968622f7acdf0a4cec7707179279f62
99c956abaec9eb8432790f3c9365c69bbc0b1476
refs/heads/master
2022-07-20T05:35:36.165289
2020-05-23T23:31:42
2020-05-23T23:31:42
250,493,330
5
2
null
2020-05-21T04:18:18
2020-03-27T09:32:34
R
UTF-8
R
false
false
3,362
r
deprecated_theApp.R
library(ggplot2) library(stringr) library(ggplot2) setwd("/home/zuhaib/Desktop/covid19Research/rnaSeqData/GSE148729/dataFiles/GSE148729_Calu3_totalRNA/dataLongFormat") data <- read.table("../GSE148729_Calu3_totalRNA_readcounts.txt", header = T, sep = "\t") fls <- list.files()[grep("GSE", list.files())] datasets <- lapply(fls, function(x) { read.table(x, header = T, sep = " ") }) names(datasets) <- fls names(datasets) <- str_replace_all(names(datasets), "\\.txt", "") # Takes in the DE between time points of some gene, and returns x,y coordinates for the line # as well as the color of the points based on whether it was significantly expressed. # Note: Time points must be sorted makeLine <- function(timePoints) { minTimePoint <- timePoints[1,2] retDF <- data.frame(x = c(minTimePoint, timePoints$T2), y = c(0, cumsum(timePoints$log2FoldChange)), sig = c("Significant", timePoints$Colour), gene = timePoints[1,1]) return(retDF) } makePlot <- function(goi, doi) { dataToPlot <- lapply(doi, function(y) { ds <- datasets[[y]] lst <- lapply(goi, function(x) { return(ds[grep(x, ds[,1]),]) }) lns <- lapply(lst, function(x) { return(makeLine(x)) }) xMax <- max(unlist(lapply(lns, function(x) return(x[,1])))) + 1 yMin <- min(unlist(lapply(lns, function(x) return(x[,2])))) - 1 yMax <- max(unlist(lapply(lns, function(x) return(x[,2])))) + length(lns) return(list(Plot = lns, xMax = xMax, yMin = yMin, yMax = yMax, Name = y)) }) maxX <- max(unlist(lapply(dataToPlot, function(x) return(x$xMax)))) minY <- min(unlist(lapply(dataToPlot, function(x) return(x$yMin)))) maxY <- max(unlist(lapply(dataToPlot, function(x) return(x$yMax)))) # pointShift <- (maxY - minY) / length(goi) # maxY <- maxY + 2 # print(maxY) for (d in dataToPlot) { vShift <- 0 plot(1, type="n", xlab="Time (h)", ylab="", xlim=c(-9, maxX), ylim=c(minY, maxY), main = d$Name) for (i in d$Plot) { lines(i$x, i$y + vShift, type = "b", col = sapply(i$sig, function(x) if (x == "Significant") return("black") else return("yellow")), cex = 2, pch = 16) text(-5, vShift, labels = i$gene) vShift <- vShift + 1 } } } # Old Code # makePlot <- function(goi, doi) { # lst <- lapply(goi, function(x) { # return(datasets$GSE148729_Calu3_sarsCov2[grep(x, datasets$GSE148729_Calu3_sarsCov2[,1]),]) # }) # lns <- lapply(lst, function(x) { # return(makeLine(x)) # }) # xMax <- max(unlist(lapply(lns, function(x) return(x[,1])))) + 1 # yMin <- min(unlist(lapply(lns, function(x) return(x[,2])))) - 1 # yMax <- max(unlist(lapply(lns, function(x) return(x[,2])))) + length(lns) # vShift <- 0 # plot(1, type="n", xlab="", ylab="", xlim=c(-5, xMax), ylim=c(yMin, yMax)) # # rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4], col = # # "antiquewhite") # for (i in lns) { # lines(i$x, # i$y + vShift, # type = "b", # col = sapply(i$sig, function(x) if (x == "Significant") return("black") else return("yellow")), # cex = 2, # pch = 16) # text(-1, vShift, labels = i$gene) # vShift <- vShift + 1 # } # }
d617ed5e434791be3b97667d1a600cd94d5f83b1
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/diagram/examples/coordinates.Rd.R
35dbc7a20f9e179ec0c19db2fa5c9b6c1d18faf6
[]
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
557
r
coordinates.Rd.R
library(diagram) ### Name: coordinates ### Title: coordinates of elements on a plot ### Aliases: coordinates ### Keywords: manip ### ** Examples openplotmat(main = "coordinates") text(coordinates(N = 6), lab = LETTERS[1:6], cex = 2) text(coordinates(N = 8, relsize = 0.5), lab = letters[1:8], cex = 2) openplotmat(main = "coordinates") text(coordinates(pos = c(2, 4, 2)), lab = letters[1:8], cex = 2) plot(0, type = "n", xlim = c(0, 5), ylim = c(2, 8), main = "coordinates") text(coordinates(pos = c(2, 4, 3), hor = FALSE), lab = 1:9, cex = 2)
08463022f9668a4c5d416768f42a4931f48317e9
e662def6f0876bdd2908d17601b0060e52d31577
/R/RcppExports.R
12816a383718ef71a10aea4e98a971fe0ebe094c
[]
no_license
XiangyuLuo/BLGGM
e2794e1c0016830b46e4d858780d74d8de3717d0
1b37a4e418f669207cd2e6a2171c243233c4c94d
refs/heads/main
2023-07-05T18:02:59.844543
2021-08-09T08:35:16
2021-08-09T08:35:16
330,578,042
0
0
null
2021-01-18T06:43:10
2021-01-18T06:43:09
null
UTF-8
R
false
false
1,000
r
RcppExports.R
# Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 MCMC_full <- function(num_iter, num_save, theta_t, ind_zero, mu_t, invcov_t, cov_t, edge_t, group_t, lambda0_t, lambda1_t, pi_t, gam, G, N, K, ssp_v0, ssp_v1, ssp_l, ssp_pi, epsilon_theta = 0.2, num_step_theta = 20L, eta_mu = 0, tau_sq_mu = 1, lam0_0 = 2, lam1_0 = -2, sigma2_lam0 = 0.25, sigma2_lam1 = 0.25, epsilon_lam = 0.01, num_step_lam = 10L, iter_save = FALSE, n_threads = 1L, iter_print = 1000L, class_print = FALSE) { .Call(`_BLGGM_MCMC_full`, num_iter, num_save, theta_t, ind_zero, mu_t, invcov_t, cov_t, edge_t, group_t, lambda0_t, lambda1_t, pi_t, gam, G, N, K, ssp_v0, ssp_v1, ssp_l, ssp_pi, epsilon_theta, num_step_theta, eta_mu, tau_sq_mu, lam0_0, lam1_0, sigma2_lam0, sigma2_lam1, epsilon_lam, num_step_lam, iter_save, n_threads, iter_print, class_print) } update_pi_R <- function(group_t, gam, K) { .Call(`_BLGGM_update_pi_R`, group_t, gam, K) }
a68bae85ce3cc017a47840d15f55880ea556e7b0
c87f61d1f1e048d52ca528093dff47823d92cad6
/R/wpmed-global.R
39f37e0ac4c789907c27516a5ec1b3962994dc03
[ "MIT" ]
permissive
nettrom/importance
96629fd2ff67ad6100172aa5aaca63d4a386c9d7
6e74623f87862d29ce423769f723adb7ff3d0a20
refs/heads/master
2021-01-17T15:17:59.831166
2017-08-14T23:02:53
2017-08-14T23:02:53
84,104,642
3
0
null
null
null
null
UTF-8
R
false
false
2,265
r
wpmed-global.R
## Comparing the global classifier on the WPMED dataset, and vice versa. ## This involves a little bit of fiddling because our measure of proportions ## of inlinks from WPMED is not in the global dataset. But we'll get to that later… ## Global classifier on the WPMED dataset. ## This is the classifier we used on that dataset. ## Based on an earlier run, I use gamma=1.40, cost=16, which produced err=0.5065 ## imp_svm = svm(rating ~ log_inlinks + log_views, data=training.set, ## cost=16, gamma=1.4, cross=10); summary(imp_svm); ## Our current test set is the WPMED test set, but I decided to name the ## log_inlinks column differently, let's fix that test.set[, log_inlinks := log_links]; wpmed[, log_inlinks := log_links]; svm_predictions = predict(object=imp_svm, newdata=test.set); test.set$global_pred = svm_predictions; conf_svm = table(test.set$global_pred, test.set$rating); confusionMatrix(conf_svm); test.set[rating == "Top" & global_pred == 'High']; test.set[rating == "High" & global_pred == 'Top']; svm_predictions = predict(object=imp_svm, newdata=wpmed); wpmed$global_pred = svm_predictions; conf_svm = table(wpmed$rating, wpmed$global_pred); cf = confusionMatrix(conf_svm); ## Switch the test set to the unanimous one we previously used. test.set = unanimous_dataset[is_training == 0]; ## Add the n_local_dampened to the test.set with a default value of 1 ## (which means no inlinks are from WPMED) test.set[, n_local_dampened := 1.0]; ## Let's see if any articles in this test set are in WPMED. test.set[talk_page_id %in% wpmed$talk_page_id]; ## We find 28 articles in WPMED, set their value to the one in the WPMED dataset. for(page in test.set[talk_page_id %in% wpmed$talk_page_id]$talk_page_id) { test.set[talk_page_id == page, n_local_dampened := wpmed[talk_page_id == page]$n_local_dampened]; } ## Also need to rename log_inlinks to log_links test.set[, log_links := log_inlinks]; ## Looks like that worked, let's make some predictions! svm_predictions = predict(object=imp_svm.kamps, newdata=test.set); test.set$kamps_pred = svm_predictions; cf_global_kamps = confusionMatrix(table(test.set$rating, test.set$kamps_pred))
f69329b06d132356530f89820b0a8cf54ba1b1b9
42dedcc81d5dc9a61a79dbcea9bdd7363cad97be
/age+gender/analysis/01_resolution/C-ROIs_01-extract.R
b46c17a16735607bd9b82854af8dc9367a12df50
[]
no_license
vishalmeeni/cwas-paper
31f4bf36919bba6caf287eca2abd7b57f03d2c99
7d8fe59e68bc7c242f9b3cfcd1ebe6fe6918225c
refs/heads/master
2020-04-05T18:32:46.641314
2015-09-02T18:45:10
2015-09-02T18:45:10
null
0
0
null
null
null
null
UTF-8
R
false
false
2,006
r
C-ROIs_01-extract.R
# This script will extract the time-series from each of the ROI sets ### # Setup ### library(Rsge) library(tools) tmpdf <- read.csv("z_details.csv") njobs <- nrow(tmpdf) # number of jobs = number of subjects nthreads <- 1 nforks <- 100 rbase <- "/home2/data/Projects/CWAS/share/age+gender/analysis/01_resolution/rois" mask_file <- file.path(rbase, "mask_4mm.nii.gz") ks <- c(25,50,100,200,400,800,1600,3200,6400) func_files <- as.character(read.table("z_funcpaths_4mm.txt")[,1]) #### ## ROI Extraction (Derived) #### # #roi_files <- file.path(rbase, sprintf("rois_k%04i.nii.gz", ks)) # #for (roi_file in roi_files) { # cat(sprintf("ROI: %s\n", roi_file)) # roi_base <- file_path_sans_ext(file_path_sans_ext(basename(roi_file))) # out_files <- sge.parLapply(func_files, function(func_file) { # set_parallel_procs(1, 1) # out_file <- file.path(dirname(func_file), paste(roi_base, ".nii.gz", sep="")) # roi_mean_wrapper(func_file, roi_file, mask_file, out_file) # return(out_file) # }, packages=c("connectir"), function.savelist=ls(), njobs=njobs) # out_files <- unlist(out_files) # ofile <- paste("z_", roi_base, ".txt", sep="") # write.table(out_files, file=ofile, row.names=F, col.names=F) #} ### # ROI Extraction (Random) ### roi_files <- file.path(rbase, sprintf("rois_random_k%04i.nii.gz", ks)) for (roi_file in roi_files) { cat(sprintf("ROI: %s\n", roi_file)) roi_base <- file_path_sans_ext(file_path_sans_ext(basename(roi_file))) out_files <- sge.parLapply(func_files, function(func_file) { set_parallel_procs(1, 1) out_file <- file.path(dirname(func_file), paste(roi_base, ".nii.gz", sep="")) roi_mean_wrapper(func_file, roi_file, mask_file, out_file) return(out_file) }, packages=c("connectir"), function.savelist=ls(), njobs=njobs) out_files <- unlist(out_files) ofile <- paste("z_", roi_base, ".txt", sep="") write.table(out_files, file=ofile, row.names=F, col.names=F) }
8ea68769e6b362a9c97804f253c1d914770a8112
11e7d531fcf7ea80b4c1a04fc6ab0e6efa8a7a7b
/man/abb2state.Rd
f0e5c1da8d2fdedd05eae9a194d9e5cee8187976
[]
no_license
nbarsch/tfwsp
81e5b82aa9b8f1ed0ed13b9e55457e4a565339f6
28e25f48c4d3180fa411f71dd7eef1382a33b153
refs/heads/master
2023-04-06T20:27:33.192381
2021-04-12T06:52:09
2021-04-12T06:52:09
287,382,128
0
0
null
null
null
null
UTF-8
R
false
true
312
rd
abb2state.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/abb2state.R \name{abb2state} \alias{abb2state} \title{abb2state()} \usage{ abb2state(stateabb) } \arguments{ \item{stateabb}{state abb as two character abb i.e. "CA", "TX", or "NY"} } \description{ Get state from state abbreviation }
43b571c21dd0bbb85e89cb550039ca967fd9c8be
ab26402079755c8eff8d4221267720dd44d89da0
/R/S3Method.R
0f3f5550b380148b0fa53ff6bd4b151698ce529e
[ "MIT" ]
permissive
haileibroad/SamplyzeR
787f0f87332e4680bb2452e7929d9542ac2a0112
fdd9fe66cfd50bdcfd87ed257e11c18f2eb46ca2
refs/heads/master
2021-05-15T12:35:45.215497
2017-10-26T18:02:26
2017-10-26T18:02:26
108,458,811
0
0
null
2017-10-26T19:53:21
2017-10-26T19:53:21
null
UTF-8
R
false
false
1,744
r
S3Method.R
#' Save an object to a specific format #' #' Save an object to tsv, RDS or excel format #' #' @param object #' #' @export save <-function(object, ...) UseMethod('save') #' Write sample dataset to tsv, RDS or excel files with S3 method save. #' #' @param object sample dataset #' @param tsv path and output name of tsv file #' @param RDS path and output name of RDS file #' @param xls path and output name of excel file #' #' @export save.sampleDataset <- function(object, RDS = NULL, tsv = NULL, xls = NULL) { if (is.null(RDS) & is.null(tsv) & is.null(xls)) { stop("Please specify at least one format (RDS, tsv or xls) for output") } if(!is.null(tsv)) { write.table(object$df, file = tsv, sep = '\t', row.names = F, quote = F) } if (!is.null(RDS)) { saveRDS(object, file = RDS) } if (!is.null(xls)) { WriteXLS::WriteXLS(object$df, ExcelFileName = xls) } } #' Update index of sample dataset by different annotation categories #' #' @param object sample dataset #' @param by sort by which category #' @return an sample dataset object with updated index #' #' @export sort.sampleDataset <- function(object, by) { byCol = which(names(object$df) == by) object$df = object$df[order(object$df[ ,byCol], na.last = T),] object$df$index = 1:dim(object$df)[1] return(object) } #' Show dimensions of sample dataset object #' #' @param object sample data set object #' @return a vector of rows and columns of the data frame of sample data set #' #' @export dim.sampleDataset <- function(object){ dim(object$df) } #' @export print.sampleDataset <- function(object) { cat("\nClass: SampleDataset\n", "Samples: ", dim(object)[1], "\n", "Attributes:", attributes(object)$names, "\n\n" ) }
2e73de4959f8d8fba9091ffd3fc1f52435d2bb06
ebf6c0331b9d77a3b1ee3190d34be377a322000c
/R/pcrsim-package.r
5d55ffd635b7060321f1bcfec6e28b8cceee6b0d
[]
no_license
cran/pcrsim
64296cbaa1262d142987f40ebb6710c6cb144618
dac5397ab9fa077915800be68c409459d180ee68
refs/heads/master
2021-01-17T11:20:07.490671
2017-03-17T23:30:37
2017-03-17T23:30:37
17,719,217
1
0
null
null
null
null
UTF-8
R
false
false
1,433
r
pcrsim-package.r
############################################################################### #' Forensic DNA process simulator. #' #' PCRsim is a package to simulate the forensic DNA process. The function \code{pcrsim} #' opens up a graphical user interface which allow the user to enter parameters #' required for the simulation. Once calibrated the program can potentially #' be used to: reduce the laboratory work needed to validate new STR kits, #' create samples for educational purposes, help develop methods for #' interpretation of DNA evidence, etc. #' #' This is a first version which is still experimental and under development. #' #' Areas in need of more research are better calibration and more correct #' scaling to peak heights over a range of input amounts. The current #' implementation is built to mimic the biological processes as closely as #' possible and are not suitable for simulation of large number of samples #' due to performance. #' #' @title Simulation of the Forensic DNA process #' @docType package #' @name pcrsim-package #' @author Oskar Hansson \email{oskar.hansson@@fhi.no} #' @keywords package #' @references Gill, Peter, James Curran, and Keith Elliot. #' \\u0022 A Graphical Simulation Model of the Entire DNA Process Associated with #' the Analysis of Short Tandem Repeat Loci\\u0022 #' Nucleic Acids Research 33, no. 2 (2005): 632-643. doi:10.1093/nar/gki205. #' NULL
070a7e957b1f852773afa4dd8ead3165cd97f420
70b973af1466108afbb476e62e5672b1fb495f94
/seir-model/plotlib.R
3afdc8d98104229bd9bf90897ab74aea5140b026
[]
no_license
openmodels/coronaclimate
dbac851a4a7b4d51891f69c7e9e43d691e34ecf1
2909520af378cc9b38db09c295f4c451a3be2c00
refs/heads/master
2022-11-07T07:19:59.006186
2022-11-03T01:58:19
2022-11-03T01:58:19
249,415,990
0
0
null
2020-03-30T19:39:06
2020-03-23T11:46:24
Python
UTF-8
R
false
false
2,159
r
plotlib.R
labelmap <- list('mobility_slope'="Mobility Adjustment", 'alpha'="Gradual Adjustment Rate", 'invsigma'="Incubation Period (days)", 'invgamma'="Infectious Period (days)", 'invkappa'="Pre-Testing Period (days)", 'invtheta'="Reporting Delay (days)", 'logbeta'="Log Transmission Rate", 'omega'="Realised Reporting Rate", 'deathrate'="Death Rate", 'deathomegaplus'="Extra Record of Deaths", 'deathlearning'="Death Learning Rate", 'portion_early'="Portion Reported Early", 'e.t2m'="Air Temperature Trans.", 'e.tp'="Total Precipitation Trans.", 'e.r'="Relative Humidity Trans.", 'e.absh'="Absolute Humidity Trans.", 'e.ssrd'="Solar Radiation Trans.", 'e.utci'="Thermal Discomfort Trans.", 'o.t2m'="Air Temperature Detect", 'o.tp'="Total Precipitation Detect", 'o.r'="Relative Humidity Detect", 'o.absh'="Absolute Humidity Detect", 'o.ssrd'="Solar Radiation Detect", 'o.utci'="Thermal Discomfort Detect", 'error'="Model Error", 'logomega'="Log Reporting Rate", 'eein'="Exposed Imports", 'rhat'="Bayesian convergence") paramorder <- c('alpha', 'invgamma', 'invsigma', 'invkappa', 'invtheta', 'mobility_slope', 'omega', 'portion_early', 'deathrate', 'deathomegaplus', 'deathlearning', 'logbeta', 'logomega', 'eein', 'e.absh', 'e.r', 'e.t2m', 'e.tp', 'e.ssrd', 'e.utci', 'o.absh', 'o.r', 'o.t2m', 'o.tp', 'o.ssrd', 'o.utci', 'error', 'rhat') ## Prefer to use this, since we've messed up with factor params before get.param.labels <- function(params) { param.labels <- sapply(params, function(param) labelmap[[as.character(param)]]) factor(param.labels, levels=rev(sapply(paramorder, function(param) labelmap[[param]]))) }
bd6bcf5e4a687a9f42d878f4e7efbfeb7a8f9694
1eb7487a6380572f6fbece1498acfa507f9a0662
/R/co_methylation_step1.R
083077fd5f4070312001c8cfa9f745cc735e03bc
[]
no_license
Gavin-Yinld/coMethy
41c82f2a8f41183e82a2f91727bc675b6d073986
66745fc4f20141517c889fd2b57e720240cf4053
refs/heads/master
2020-05-17T07:35:55.236667
2019-08-23T09:16:01
2019-08-23T09:16:01
183,583,856
0
0
null
null
null
null
UTF-8
R
false
false
1,557
r
co_methylation_step1.R
co_methylation_step1 <- function(csm_ml_matrix){ options(stringsAsFactors=F) set.seed(123) data <- as.matrix(csm_ml_matrix) km.res <- kmeans(data, 3, nstart = 25) pdf("parameter.pdf") par(mfrow = c(3,2),mar=c(3,5,2,2)); for(i in 1:3) { require(WGCNA) wgcna.data <- t(data[which(km.res$cluster==i),]) powers = c(c(1:10), seq(from = 12, to=30, by=2)) ###Call the network topology analysis function sft = pickSoftThreshold(wgcna.data, powerVector = powers, verbose = 5,networkType="signed") ####Plot the results: cex1 = 0.9; #######Scale-free topology fit index as a function of the soft-thresholding power plot(sft$fitIndices[,1], -sign(sft$fitIndices[,3])*sft$fitIndices[,2], xlab="Soft Threshold (power)",ylab="Scale Free Topology \n Model Fit,signed R^2",type="n", main = paste("Scale independence")); text(sft$fitIndices[,1], -sign(sft$fitIndices[,3])*sft$fitIndices[,2], labels=powers,cex=cex1,col="red"); ############this line corresponds to using an R^2 cut-off of h abline(h=0.80,col="red") #######Mean connectivity as a function of the soft-thresholding power plot(sft$fitIndices[,1], sft$fitIndices[,5], xlab="Soft Threshold (power)",ylab="Mean Connectivity", type="n", main = paste("Mean connectivity")) text(sft$fitIndices[,1], sft$fitIndices[,5], labels=powers, cex=cex1,col="red") #save(sft,file=paste0("kmeans_",i,"sft.Rdata")) } dev.off() return(km.res) } ###########################################################################
b33b3621e08d392ce59ec2092874d74ea9504116
30c5ed7d7cd44195dd4ce0d61a607579563f4133
/man/setcover.Rd
f9b5c42b7c2b873586ed7cdfb1af037708d31eb9
[]
no_license
cran/adagio
f08103c03dc491c09b2639e94a35339d90f5f36b
8b46ee3aac3d6e84eb153209c5e9399b09808126
refs/heads/master
2022-11-02T19:54:59.661507
2022-10-03T12:40:02
2022-10-03T12:40:02
17,694,245
4
1
null
null
null
null
UTF-8
R
false
false
1,438
rd
setcover.Rd
\name{setcover} \alias{setcover} \title{ Set cover problem } \description{ Solves the Set Cover problem as an integer linear program. } \usage{ setcover(Sets, weights) } \arguments{ \item{Sets}{matrix of 0s and 1s, each line defining a subset.} \item{weights}{numerical weights for each subset.} } \details{ The Set Cover problems attempts to find in subsets (of a 'universe') a minimal set of subsets that still covers the whole set. Each line of the matrix \code{Sets} defines a characteristic function of a subset. It is required that each element of the universe is contained in at least one of these subsets. The problem is treated as an Integer Linear Program (ILP) and solved with the \code{lp} solver in \code{lpSolve}. } \value{ Returns a list with components \code{sets}, giving the indices of subsets, and \code{objective}, the sum of weights of subsets present in the solution. } \references{ See the Wikipedia article on the "set cover problem". } \seealso{ \code{\link{knapsack}} } \examples{ # Define 12 subsets of universe {1, ..., 10}. set.seed(7*11*13) A <- matrix(sample(c(0,1), prob = c(0.8,0.2), size = 120, replace =TRUE), nrow = 12, ncol = 10) sol <- setcover(Sets = A, weights = rep(1, 12)) sol ## $sets ## [1] 1 2 9 12 ## $no.sets ##[1] 4 # all universe elements are covered: colSums(A[sol$sets, ]) ## [1] 1 1 2 1 1 1 2 1 1 2 } \keyword{ discrete-optimization }
7ca8a71d110d861361d5e289786c2fd7e9c73c5f
3b62ffa02efef29b8bbaa9041d74a1ee72b4807a
/R/rhrIsopleths.R
7b4dbe2216e872e5a1be144a96245f200f94d6d6
[]
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
false
582
r
rhrIsopleths.R
##' Isopleths of Home Range Estimate ##' ##' Function to retrieve isopleths of a home range estimate. ##' ##' Probabilistic estimators take (i.e. kernel density estimates) take ##' an additional argument, \code{levels}, that determines which isopleth are ##' returned. ##' ##' @template RhrEst ##' @param ... see details. ##' @return \code{SpatialPolygonsDataFrame} ##' @export rhrIsopleths <- function (x, ...) { UseMethod ("rhrIsopleths", x) } ##' @export rhrIsopleths.default <- function (x , ...) { paste0 ("rhrIsopleths is not defined for object of class", class(x)) }
f90cd9a6f7cab7fee34ea4c92c27cfb67cd38b5c
633be0e519a645e5828993070ec60192ec29ad46
/DMC-MBN18/dmc/models/LNR-SS/dists.R
035e4aaa656487a38e9ca656c7ff8f7bed5f53be
[]
no_license
StevenM1/summerschool_mbn_2018
5200f81a34d3025dee1ff8c9137a115585e39373
b8f0e0f37b606b6bb7a161b7692f3f58455bf4dc
refs/heads/master
2020-03-24T11:56:12.571909
2018-08-01T14:35:04
2018-08-01T14:35:04
142,698,961
1
2
null
null
null
null
UTF-8
R
false
false
19,315
r
dists.R
####################### LNR stop signal ####################### LNR n-choice ---- rlnr <- function (n, meanlog, sdlog, t0, st0 = 0) # Race among n_acc accumulators, mealnlog and sdlog can be n_acc length # vectors or n_acc x n matrices. t0 can be # a) a scalar, b) a vector of length number of accumulators or # c) a matrix with 1 row per accumulator, when start times differ on each trial # st0, range of non-decison time variability, must be a scalar, as the same # variability is assumed in a common encoding/production stage { n_acc <- ifelse(is.null(dim(meanlog)),length(meanlog),dim(meanlog)[1]) dt <- matrix(rlnorm(n = n*n_acc, meanlog = meanlog, sdlog = sdlog), nrow = n_acc) + t0 winner <- apply(dt,2,which.min) if (st0[1]==0) data.frame(RT=dt[cbind(winner,1:n)],R=winner) else data.frame(RT=dt[cbind(winner,1:n)]+runif(n,0,st0[1]),R=winner) } n1PDFfixedt0.lnr=function(dt,meanlog,sdlog) # Generates defective PDF for responses first among n_acc accumulator at # dt (decison time), a matrix with one row for each accumulator (allowing for # different start times per accumulator) { n_acc <- ifelse(is.null(dim(meanlog)),length(meanlog),dim(meanlog)[1]) if (!is.matrix(meanlog)) meanlog <- matrix(rep(meanlog,dim(dt)[2]),nrow=n_acc) if (!is.matrix(sdlog)) sdlog <- matrix(rep( sdlog,dim(dt)[2]),nrow=n_acc) # winner dt[1,] <- dlnorm(dt[1,],meanlog[1,],sdlog[1,]) # loosers if (dim(meanlog)[1]>1) for (i in 2:dim(meanlog)[1]) dt[1,] <- dt[1,]*plnorm(dt[i,],meanlog[i,],sdlog[i,],lower.tail=FALSE) dt[1,] } ####################### LNR stop signal ---- # NB1: no st0 # NB2: TRIALS effect on meanlog rlnrss <- function (n, meanlog, sdlog, t0, t0sg, tf=0, gf=0, ts = 0, SSD=Inf, TRIALS = NA, staircase=NA) # Race among length(meanlog) accumulators (if meanlog a vector), # or dim(meanlog)[1] (if a matrix), first of which is a stop accumulator. # Acts the same as rlnr except NA returned for RT when winner = 1. # Optional SSD argument can be used to adjust start time for first # accumulator. SSD can be a scalar or vector length n; output has an SSD column # For trials with winning first accumulator RT and R set to NA. # tf = trigger failure probability, gf = go failure probability # If any !is.na in staircase runs a staircase # t0 is a scalar with the standard interpritaiton for GO accumulators. # Definition of t0sg (a non-negative scalar) depends on whether response # production time is assumed to be ballistic or not. # If it is ballistic t0sg = stop encoding - go encoding time + t0 # If if it is NOT ballistic, t0sg = stop encoding # IN BOTH CASES t0sg < 0 IS NOT ALLOWED # ts = slope of slowing (speeding if negative) over TRIALS, meanlog - ts*TRIALS # This has a linear effect on mean and sd { if ( t0sg < 0 ) stop("t0sg cannot be less than zero") if ( length(SSD)==1 ) SSD <- rep(SSD,n) if ( any(is.na(SSD)) || length(SSD) != n ) stop("SSD cannot have NAs and must be a scalar or same length as n") n_acc <- ifelse(is.null(dim(meanlog)),length(meanlog),dim(meanlog)[1]) # t0sg -> sg for stop accumulator, relative to 0 for go accumulators t0S <- matrix(rep(c(t0sg-t0[1],rep(0,n_acc-1)),length.out=n*n_acc),nrow=n_acc) if (!is.matrix(meanlog)) meanlog <- matrix(rep(meanlog,n),nrow=n_acc) if (!is.matrix(sdlog)) sdlog <- matrix(rep(sdlog,n),nrow=n_acc) if ( !any(is.na(TRIALS)) ) { if (length(TRIALS)!=n) stop("TRIALS must have length n") meanlog[-1,] <- meanlog[-1,] + rep(ts*TRIALS,each=n_acc-1) } if ( gf > 0 ) # Setup for GO failure is.gf <- as.logical(rbinom(length(SSD),1,gf)) else is.gf <- logical(length(SSD)) if ( all(!is.finite(SSD)) ) { # ALL GO out <- rlnr(n,meanlog[-1,,drop=FALSE],sdlog[-1,,drop=FALSE],t0) out$R <- out$R+1 } else { # SOME STOP if ( any(is.na(staircase)) ) { # STOP fixed SSD # add SSD to stop accumulator t0S[1,] <- t0S[1,] + SSD out <- rlnr(n,meanlog,sdlog,t0S) if ( tf>0 ) { is.tf <- logical(length(SSD)) is.tf[is.finite(SSD)][as.logical(rbinom(sum(is.finite(SSD)),1,tf))] <- TRUE if ( any(is.tf) ) { out[is.tf,] <- rlnr(sum(is.tf),meanlog[-1,is.tf,drop=FALSE], sdlog[-1,is.tf,drop=FALSE],t0=0) out[is.tf,"R"] <- out[is.tf,"R"]+1 } } } else { # STOP, staircase if ( !is.numeric(staircase) | length(staircase)!=1 ) stop("Staircase must be a numeric vector of length 1 specifying the step.") SSDi <- SSD[is.finite(SSD)][1] # begining SSD dt <- matrix(rlnorm(n = n*n_acc, meanlog = meanlog, sdlog = sdlog), nrow = n_acc) + t0S # Setup winner <- numeric(n) for ( i in c(1:n) ) { if ( !is.finite(SSD[i]) ) # not staircase dt[1,i] <- dt[1,i] + SSD[i] else dt[1,i] <- dt[1,i] + SSDi # staircase if ( runif(1)<tf ) # Trigger failure winner[i] <- which.min(dt[2:n_acc,i])+1 else winner[i] <- which.min(dt[,i]) if (is.gf[i]) winner[i] <- 1 if ( is.finite(SSD[i]) ) { # update staircase SSD[i] <- SSDi if ( winner[i]==1 ) SSDi <- SSDi + staircase else SSDi <- SSDi - staircase if (SSDi<1e-10) SSDi <- 0 } } out <- data.frame(RT=dt[cbind(winner,1:n)],R=winner) } out$RT <- out$RT + t0 # Add t0 for go responses } out[out$R==1,"RT"] <- NA if (gf > 0) { out$RT[is.gf] <- NA out$R[is.gf] <- 1 } if ( any(is.na(TRIALS)) ) cbind.data.frame(out,SSD=SSD) else cbind.data.frame(out,SSD=SSD,TRIALS=TRIALS) } n1PDF.lnrss <- function(rt,meanlog,sdlog,t0,t0sg,tf=0,gf=0,ts=0, SSD=Inf,TRIALS=NA,Si) # Same as n1PDF.lnr except SSD is either a scalar or vector of length(rt) # stop accumulator must have name "NR". SSD is subtracted stop accumulator time # and dt=NA done by integration. # # tf= probabiliy of trigger failure, where # L = trigger fail & respond + trigger and respond + trigger and no-response # = tf*L(N-1)+(1-tf)[L(N)+p(S)], # L(N-1) = choice race likelihood (no stop accumulator), # L(N) = full N unit race likelihood given they did respond, # p(S) probability of stop winning # # gf = probabiliy of go failure. # On go trials: L = go fail (so no response) + go and L above # L = gf + (1-gf)*[tf*L(N-1)+(1-tf)[L(N)+p(S)]] or similarly # L = [ p(non-response) ] + [ p(response) ] # = [ gf + (1-gf)(1-tf)p(S) ] + [ (1-gf){(tf*Ln(n-1) + (1-tf)*L(N))} ] # # NB:rt is NOT decision time, but rather full RT as t0 has to be passed # in order to include properly in cases where RT is NA (i.e., sucessful stop) # # Definition of t0sg (a non-negative scalar) depends on whether response # production time is assumed to be ballistic or not. # If it is ballistic t0sg = stop encoding - go encoding time + t0 # If if it is NOT ballistic, t0sg = stop encoding # IN BOTH CASES t0sg < 0 IS NOT ALLOWED (zero likelihood returned) { stopfn <- function(t,meanlogj,sdlogj,t0,t0sg,SSD,Si) { # d = s-g = tD-t0(GO), then add SSDstart time to get # start time go - start time stop, i.e., finishing time advantage for GO t0S <- rep(0,length(meanlogj)) # Set relative to stop accumulator finish time t0S[-Si] <- t0S[-Si]+t0sg-t0+SSD # subtracting min(t0S) keeps all times positive dt <- matrix(rep(t,each=length(meanlogj)),nrow=length(meanlogj))+t0S-min(t0S) i <- c(Si,c(1:length(meanlogj))[-Si]) n1PDFfixedt0.lnr(dt[i,,drop=FALSE],meanlogj[i],sdlogj[i]) } # NOTE: t0 is not subtracted when making dt but passed to handle RT=NA case # Bad t0sg if (t0sg<0) return(rep(0,length(rt))) if ( length(SSD)==1 ) SSD <- rep(SSD,length(rt)) if (length(SSD) != length(rt)) stop("SSD must be a scalar or same length as rt") n_acc <- ifelse(is.null(dim(meanlog)),length(meanlog),dim(meanlog)[1]) rt <- matrix(rep(rt,each=n_acc),nrow=n_acc) is.stop <- is.na(rt[1,]) if (!is.matrix(meanlog)) meanlog <- matrix(rep(meanlog,dim(rt)[2]),nrow=n_acc) if (!is.matrix(sdlog)) sdlog <- matrix(rep(sdlog,dim(rt)[2]),nrow=n_acc) if ( any(is.na(TRIALS)) | ts == 0 ) { p <- SSD[is.stop] pj <- c(1:sum(is.stop))[!duplicated(p)] # index of unique SSD } else { meanlog[-Si,] <- meanlog[-Si,] + ts*TRIALS p <- apply( rbind(meanlog[,is.stop,drop=FALSE],SSD[is.stop]), 2,paste,collapse="") pj <- c(1:sum(is.stop))[!duplicated(p)] # index of unique p and SSD } if ( any(!is.stop) ) { rt[Si,!is.stop] <- rt[Si,!is.stop] - t0sg - SSD[!is.stop] rt[-Si,!is.stop] <- rt[-Si,!is.stop]-t0 if ( tf > 0 ) { rt[1,!is.stop] <- (1-gf)*( tf*n1PDFfixedt0.lnr(rt[-Si,!is.stop,drop=FALSE], meanlog[-Si,!is.stop,drop=FALSE],sdlog[-Si,!is.stop,drop=FALSE]) + (1-tf)*n1PDFfixedt0.lnr(rt[,!is.stop,drop=FALSE], meanlog[,!is.stop,drop=FALSE],sdlog[,!is.stop,drop=FALSE]) ) } else rt[1,!is.stop] <- (1-gf)*n1PDFfixedt0.lnr(rt[,!is.stop,drop=FALSE], meanlog[,!is.stop,drop=FALSE],sdlog[,!is.stop,drop=FALSE]) } if ( any(is.stop) ) for (j in pj) { # tmp <- ifelse(!is.finite(SSD[j]),0, # try(integrate(f=stopfn,lower=0,upper=Inf,meanlogj=meanlog[,j], # sdlogj=sdlog[,j],t0=t0,t0sg=t0sg,SSD=SSD[j],Si=Si, # NoBallistic = FALSE)$value,silent=TRUE)) # if (!is.numeric(tmp)) tmp <- 0 if ( !is.finite(SSD[j]) ) tmp <- 0 else tmp <- my.integrate(f=stopfn,lower=0,meanlogj=meanlog[,j], sdlogj=sdlog[,j],t0=t0,t0sg=t0sg,SSD=SSD[j],Si=Si) rt[1,is.stop][p %in% p[j]] <- gf +(1-gf)*(1-tf)*tmp } rt[1,] } # VERY EXTENSIVE TESTING WITH Two different SSDs { # # ########### TWO ACCUMULATOR CASE # # n=1e5 # meanlog=c(.75,.75); sdlog=c(.5,1) # SSD = rep(c(1,10)/10,each=n/2) # # # Run one of the follwing two lines # do.trials=FALSE # do.trials = TRUE # requires very differnet plotting check, can be SLOW! # # #### RUN ONE OF THE FOLLOWING THREE LINES, all assume .2s go Ter # t0=.2; t0sg= 0 # minimum possible value of t0sg, stop encoding .2 less than go # t0=.2; t0sg=.2 # equal stop and go enconding times # t0=.2; t0sg=.4 # stop .2 slower than go # # ### RUN ONE OF THE FOLLOWING FOUR LINES # # Without trigger failure or go failure # tf=0; gf=0 # # With trigger failure, no go failure # tf=.1;gf=0 # # Without trigger failure, with go failure # tf=0; gf=.1 # # With trigger failure and go failure # tf=.1;gf=.1 # # if (do.trials) { # ts=.5; TRIALS=log10(seq(1,10,length.out=n)) # 1..10 natural so 0-1 on log # TRIALS <- as.vector(t(matrix(TRIALS,nrow=2))) # interleave SSDs # # Plot slowing in GO (usually nice and linear, up to smooting overfitting) # sim.go <- rlnrss(n=n,meanlog,sdlog,t0,t0sg,tf=tf,gf=gf,TRIALS=TRIALS,ts=ts) # is.in <- !is.na(sim.go$RT) # in case go failure # plot(smooth.spline(TRIALS[is.in],sim.go$RT[is.in]),ylab="Smooth",xlab="TRIALS",type="l") # } else {TRIALS=NA;ts=0} # # # Simulate stop trials # sim <- rlnrss(n=n,meanlog,sdlog,t0,t0sg,SSD=SSD,tf=tf,gf=gf,TRIALS=TRIALS,ts=ts) # # # Plot densities # par(mfrow=c(1,2)) # dns1 <- plot.cell.density(sim[sim$SSD==.1,],xlim=c(0,7),save.density=TRUE,main="SSD=.1") # dns2 <- plot.cell.density(sim[sim$SSD!=.1,],xlim=c(0,7),save.density=TRUE,main="SSD=1") # x1c <- dns1$'2'$x; x2c <- dns2$'2'$x # # # Signal respond RT # dat <- sim; dat <- dat[!is.na(dat$RT),]; dat$R <- factor(as.character(dat$R)) # round(tapply(dat$RT,dat[,c("R","SSD")],mean),2) # # if (do.trials) { # tmp <- n1PDF.lnrss(sim$RT[!is.na(sim$RT)],meanlog[2:1],sdlog[2:1],t0,t0sg, # ts=ts,TRIALS=TRIALS[!is.na(sim$RT)],SSD=SSD[!is.na(sim$RT)],Si=2,tf=tf,gf=gf) # par(mfrow=c(1,2)) # # red=black? # plot(x1c,dns1$'2'$y,pch=".",main="SSD=.1",ylab="Density",xlab="RT") # lines(smooth.spline(sim$RT[!is.na(sim$RT) & SSD==.1], # tmp[c(SSD==.1)[!is.na(sim$RT)]]),col="red") # # red=black? # plot(x2c,dns2$'2'$y,pch=".",main="SSD=1",ylab="Density",xlab="RT") # lines(smooth.spline(sim$RT[!is.na(sim$RT) & SSD==1], # tmp[c(SSD==1)[!is.na(sim$RT)]]),col="red") # print(tapply(is.na(sim$RT),sim$SSD,mean)) # empirical # tmp <- n1PDF.lnrss(rep(NA,n),meanlog,sdlog,t0,t0sg,SSD=SSD,Si=1,tf=tf,gf=gf,ts=ts,TRIALS=TRIALS) # print(mean(tmp[SSD==.1])) # print(mean(tmp[SSD==1])) # plot(TRIALS,tmp,pch=".",xlab="TRIALS",ylab="p(NA)",ylim=c(0,1)) # lines(smooth.spline(TRIALS[SSD==.1],as.numeric(is.na(sim$RT)[SSD==.1])),col="red") # lines(smooth.spline(TRIALS[SSD==1],as.numeric(is.na(sim$RT)[SSD==1])),col="red") # } else { # # Save simulated densities # r1 <- c(2,1) # d.r1 <- n1PDF.lnrss(rt=c(x1c,x2c),meanlog[r1],sdlog[r1],t0,t0sg, # SSD=c(rep(.1,length(x1c)),rep(1,length(x2c))),Si=2,tf=tf,gf=gf) # # Plot simulated (black) and theoretical (red) densities # par(mfrow=c(1,2)) # # red=black? # plot(x1c,dns1$'2'$y,type="l",main="SSD=.1",ylab="Density",xlab="RT", # ylim=c(0,max(dns1$'2'$y))) # lines(x1c,d.r1[1:length(x1c)],col="red") # # red=black? # plot(x2c,dns2$'2'$y,type="l",main="SSD=1",ylab="Density",xlab="RT", # ylim=c(0,max(dns2$'2'$y))) # lines(x2c,d.r1[(length(x2c)+1):(2*length(x2c))],col="red") # # # p(Stop check) # print(tapply(is.na(sim$RT),sim$SSD,mean)) # empirical # print(n1PDF.lnrss(NA,meanlog,sdlog,t0,t0sg,SSD=.1,Si=1,tf=tf,gf=gf)) # print(n1PDF.lnrss(NA,meanlog,sdlog,t0,t0sg,SSD=1,Si=1,tf=tf,gf=gf)) # } # # # # ########### THREE ACCUMULATOR CASE # # n=1e5 # meanlog=c(.75,.75,1); sdlog=c(.5,1,1) # SSD = rep(c(1,10)/10,each=n/2) # # do.trials=FALSE # do.trials = TRUE # requires very differnet plotting check, can be SLOW! # # #### RUN ONE OF THE FOLLOWING THREE LINES, all assume .2s go Ter # t0=.2; t0sg= 0 # minimum possible value of t0sg, stop encoding .2 less than go # t0=.2; t0sg=.2 # equal stop and go enconding times # t0=.2; t0sg=.4 # stop .2 slower than go # # ### RUN ONE OF THE FOLLOWING FOUR LINES # # Without trigger failure or go failure # tf=0; gf=0 # # With trigger failure, no go failure # tf=.1;gf=0 # # Without trigger failure, with go failure # tf=0; gf=.1 # # With trigger failure and go failure # tf=.1;gf=.1 # # if (do.trials) { # ts=.5; TRIALS=log10(seq(1,10,length.out=n)) # 1..10 natural so 0-1 on log # TRIALS <- as.vector(t(matrix(TRIALS,nrow=2))) # interleave SSDs # # Plot slowing in GO (usually nice and linear, up to smooting overfitting) # sim.go <- rlnrss(n=n,meanlog,sdlog,t0,t0sg,tf=tf,gf=gf,TRIALS=TRIALS,ts=ts) # is.in <- !is.na(sim.go$RT) # in case go failure # plot(smooth.spline(TRIALS[is.in],sim.go$RT[is.in]),ylab="Smooth",xlab="TRIALS",type="l") # } else {TRIALS=NA;ts=0} # # # Simulate stop trials # sim <- rlnrss(n=n,meanlog,sdlog,t0,t0sg,SSD=SSD,tf=tf,gf=gf,TRIALS=TRIALS,ts=ts) # # par(mfrow=c(1,2)) # dns1 <- plot.cell.density(sim[sim$SSD==.1,],xlim=c(0,7),save.density=TRUE,main="SSD=.1") # dns2 <- plot.cell.density(sim[sim$SSD!=.1,],xlim=c(0,7),save.density=TRUE,main="SSD=1") # x1c <- dns1$'2'$x; x2c <- dns2$'2'$x # x1e <- dns1$'3'$x; x2e <- dns2$'3'$x # # # Signal respond RT # dat <- sim; dat <- dat[!is.na(dat$RT),]; dat$R <- factor(as.character(dat$R)) # round(tapply(dat$RT,dat[,c("R","SSD")],mean),2) # # if (do.trials) { # r1 <- c(2,1,3) # is.in1 <- !is.na(sim$RT) & sim$R==2 # d.r1 <- n1PDF.lnrss(sim$RT[is.in1],meanlog[r1],ts=ts,TRIALS=TRIALS[is.in1], # sdlog=sdlog[r1],t0=t0,t0sg=t0sg,SSD=SSD[is.in1],Si=2,tf=tf,gf=gf) # r2 <- c(3,1,2) # is.in2 <- !is.na(sim$RT) & sim$R==3 # d.r2 <- n1PDF.lnrss(sim$RT[is.in2],meanlog[r2],ts=ts,TRIALS=TRIALS[is.in2], # sdlog=sdlog[r2],t0=t0,t0sg=t0sg,SSD=SSD[is.in2],Si=2,tf=tf,gf=gf) # par(mfrow=c(1,3)) # # red=black? # plot(x1c,dns1$'2'$y,pch=".",main="SSD=.1",ylab="Density",xlab="RT",type="l") # lines(x1e,dns1$'3'$y,lty=2) # lines(smooth.spline(sim$RT[is.in1 & sim$SSD==.1], # d.r1[c(sim$SSD==.1)[is.in1]]),col="red") # lines(smooth.spline(sim$RT[is.in2 & sim$SSD==.1],d.r2[c(sim$SSD==.1)[is.in2]]), # lty=2,col="red") # # red=black? # plot(x2c,dns2$'2'$y,pch=".",main="SSD=1",ylab="Density",xlab="RT",type="l") # lines(x2e,dns2$'3'$y,lty=2) # lines(smooth.spline(sim$RT[is.in1 & sim$SSD==1], # d.r1[c(sim$SSD==1)[is.in1]]),col="red") # lines(smooth.spline(sim$RT[is.in2 & sim$SSD==1], # d.r2[c(sim$SSD==1)[is.in2]]),col="red",lty=2) # # print(tapply(is.na(sim$RT),sim$SSD,mean)) # empirical # tmp <- n1PDF.lnrss(rep(NA,n),meanlog,sdlog,t0,t0sg,SSD=SSD,Si=1,tf=tf,gf=gf,ts=ts,TRIALS=TRIALS) # print(mean(tmp[SSD==.1])) # print(mean(tmp[SSD==1])) # plot(TRIALS,tmp,pch=".",xlab="TRIALS",ylab="p(NA)",ylim=c(0,1)) # lines(smooth.spline(TRIALS[SSD==.1],as.numeric(is.na(sim$RT)[SSD==.1])),col="red") # lines(smooth.spline(TRIALS[SSD==1],as.numeric(is.na(sim$RT)[SSD==1])),col="red") # } else { # # Save simulated densities # r1 <- c(2,1,3) # d.r1 <- n1PDF.lnrss(rt=c(x1c,x2c),meanlog[r1],sdlog[r1],t0,t0sg, # SSD=c(rep(.1,length(x1c)),rep(1,length(x2c))),Si=2,tf=tf,gf=gf) # r2 <- c(3,1,2) # d.r2 <- n1PDF.lnrss(rt=c(x1e,x2e),meanlog[r2],sdlog[r2],t0,t0sg, # SSD=c(rep(.1,length(x1e)),rep(1,length(x2e))),Si=2,tf=tf,gf=gf) # # Plot simulated (black) and theoretical (red) densities # par(mfrow=c(1,2)) # # red=black? # plot(x1c,dns1$'2'$y,type="l",main="SSD=.1",ylab="Density",xlab="RT", # ylim=c(0,max(dns1$'2'$y))) # lines(x1c,d.r1[1:length(x1c)],col="red") # lines(x1e,dns1$'3'$y,lty=2) # lines(x1e,d.r2[1:length(x1e)],col="red",lty=2) # # red=black? # plot(x2c,dns2$'2'$y,type="l",main="SSD=1",ylab="Density",xlab="RT", # ylim=c(0,max(dns2$'2'$y))) # lines(x2c,d.r1[(length(x2c)+1):(2*length(x2c))],col="red") # lines(x2e,dns2$'3'$y,lty=2) # lines(x2e,d.r2[(length(x2e)+1):(2*length(x2e))],col="red",lty=2) # # # p(Stop check) # print(tapply(is.na(sim$RT),sim$SSD,mean)) # empirical # print(n1PDF.lnrss(NA,meanlog,sdlog,t0,t0sg,SSD=.1,Si=1,tf=tf,gf=gf)) # print(n1PDF.lnrss(NA,meanlog,sdlog,t0,t0sg,SSD=1,Si=1,tf=tf,gf=gf)) # } }
262d99ab098da8d9e75939d3ee22b5059ae648b6
f49cfda960b70907ee90ae9ba5fab016a5b70861
/server.R
cf058aaeb7effe3082c3736755e24fb6a5b58aff
[]
no_license
Semooooo/Web-Application
d412363b79379b768b3f0a05a978fbacebb9f80b
e4bf1304ff9141c2207a0b524ceff81887c0ddd6
refs/heads/main
2023-07-24T23:41:25.299964
2021-09-06T23:17:28
2021-09-06T23:17:28
null
0
0
null
null
null
null
UTF-8
R
false
false
6,591
r
server.R
library(shiny) library(readxl) library(dplyr) library(ggplot2) library(DT) library(shinydashboard) library(shinydashboardPlus) library(shinyWidgets) library(psych) library(corrplot) library(htmltools) library(GGally) library(stats) library(plotly) library(ggpubr) library(htmlwidgets) library(shinythemes) # Define server for application for Data Visualization server <- function(input, output, session) { # Get the upload file myData <- reactive({ inFile <- input$file1 if (is.null(inFile)) return(NULL) if (input$fileType_Input == "1") { myData<-read.csv(inFile$datapath, header = TRUE,stringsAsFactors = FALSE) } else { myData<-read_xlsx(inFile$datapath) } }) output$contents <- DT::renderDataTable({ DT::datatable(myData()) }) observe({ data <- myData() updateSelectInput(session, 'y', choices = names(data)) }) #gets the y variable name, will be used to change the plot legends yVarName <- reactive({ input$y }) observe({ data <- myData() updateSelectInput(session, 'x', choices = names(data)) }) #gets the x variable name, will be used to change the plot legends xVarName <- reactive({ input$x }) ################################# observe({ data <- myData() updateSelectInput(session, 'Y', choices = names(data)) }) #gets the Y variable name, will be used to change the plot legends YVarName <- reactive({ input$Y }) observe({ data <- myData() updateSelectInput(session, 'X', choices = names(data)) }) #gets the X variable name, will be used to change the plot legends XVarName <- reactive({ input$X }) # draw a checkbox input variables of uploaded file for xvariables.. output$xvariables <- renderUI({ df <- myData() x<-colnames(df) pickerInput(inputId = 'xvariable', label = 'Select x-axis variable', choices = c(x[1:length(x)]), selected=x[2], options = list(`style` = "btn-info"), multiple = TRUE) }) # draw a checkbox input variables of uploaded file for xvariables.. output$yvariables <- renderUI({ df <- myData() y<-colnames(df) pickerInput(inputId = 'yvariable', label = 'Select y-axis variable', choices = c(y[1:length(y)]), selected=y[1], options = list(`style` = "btn-info"), multiple = FALSE) }) output$Refresh1 <- renderText({ toString(format(Sys.Date(), format = "%d %b %Y")) }) output$summary <- renderPrint({ df <- myData() df <- df[,input$select_variable] describeBy(df) }) # This has not been placed anywhere; there is no uiOutput with id of checkbox in your ui code output$sumcheckbox <- renderUI({ df <- myData() checkboxGroupInput("select_variable", "Select Feature variables for Summary:", names(df), selected = names(df)) }) # This has not been placed anywhere; there is no uiOutput with id of select in your ui code output$select <- renderUI({ df <- myData() selectInput("variable", "Variable:",names(df)) }) output$checkbox <- renderUI({ df <- myData() checkboxGroupInput("select_var", "Select Feature variables:", names(df), selected = names(df)) }) #Draw a Intrective histogram for Given data variables. output$Plothist <- renderPlotly({ df <- myData() df <- df[,input$variable] # draw the histogram with the specified number of bins plot_ly(x = ~df, type = "histogram", nbinsx = 18, histnorm = "probability", marker = list(color = viridis::viridis_pal(option = "C", direction = -1)(18))) %>% layout(title = "Histogram of Data", yaxis = list(title = "Frequency", zeroline = FALSE) ) }) # for Barchart output$plot <- renderPlot({ df <- myData() ggplot(df, aes_string(x = input$x, y = input$y))+ geom_bar(stat = "identity", fill="blue", nbinsx=15) }) # For Scatter plot and Boxplot output$plot1 <- renderPlot({ df <- myData() p <- ggplot(df, mapping = aes_string(x = input$x, y = input$y)) if (input[["plot_type"]] == "scatter plot") { p + geom_point() + stat_smooth(method = "lm", col = "blue") } else { p + geom_boxplot() } }) # For Correlation matrix and Correlation plot.. output$Correlation <- renderPrint({ df <- myData() df <- df[,input$select_var] round(cor(df),4) }) output$Correlationplot <- renderPlot({ df <- myData() df <- df[,input$select_var] theme_lato <- theme_minimal(base_size=8, base_family="Lato Light") ggpairs(df, lower = list(continuous = function(...) ggally_smooth(..., colour="darkgreen", alpha = 0.3, size=0.4) + theme_lato), diag = list(continuous = function(...) ggally_barDiag(..., fill="purple") + theme_lato), ) + theme( strip.background = element_blank(), strip.text = element_text(size=8, family="Lato Light"), axis.line = element_line(colour = "grey"), panel.grid.minor = element_blank(), ) }) #For Simple and Multiple linear Regression model.. lmModel <- reactive({ df <- myData() x <- input$xvariable y <- input$yvariable x <- as.numeric(df[[as.name(input$xvariable)]]) y <- as.numeric(df[[as.name(input$yvariable)]]) current_formula <- paste0(input$yvariable, " ~ ", paste0(input$xvariable, collapse = " + ")) current_formula <- as.formula(current_formula) model <- lm(current_formula, data = df, na.action=na.exclude) return(model) }) output$lmSummary <- renderPrint({ req(lmModel()) summary(lmModel()) }) output$diagnosticPlot <- renderPlot({ req(lmModel()) par(mfrow = c(2,2)) plot(lmModel()) }) output$report <- downloadHandler( # For PDF output, change this to "report.pdf" filename = "report.pdf", content = function(file) { # Copy the report file to a temporary directory before processing it, in # case we don't have write permissions to the current working dir (which # can happen when deployed). tempReport <- file.path(myData(), "report.Rmd") file.copy("report.Rmd", tempReport, overwrite = TRUE) }) }
ccbdf63a38fc09dff1c5541f403329963213153a
bf8b1a069668712281a433a35d213cf1b20b29a3
/OrderDataFrame.R
99b0f0c5c9c23c76d6090e7fe96fe71e8b430214
[]
no_license
wmbeam02/Assignment3
65c25483aa498814f4dc2c4acd8ce52505b1f7d5
abff9955f0cf9fe6c88892cfae4af2c7eb42c74d
refs/heads/master
2021-01-10T02:19:03.417788
2015-05-31T02:53:18
2015-05-31T02:53:18
36,444,892
0
0
null
2015-05-28T15:04:40
2015-05-28T14:42:06
R
UTF-8
R
false
false
1,975
r
OrderDataFrame.R
## A function to sort a dataframe first by State then to order the data in lowest occurrence to highest with the names of the ## hospitals alphabetic relationship used to determine ties. rankhospital=function(state, outcome, num="best") { FileName="outcome-of-care-measures.csv" data=read.csv(FileName, colClasses="character", na.strings="Not Available") CorrectInput=c("heart attack", "heart failure", "pneumonia") state=toupper(state) outcome=tolower(outcome) if (!state %in% data$State) { stop("Invalid State") } if (!outcome %in% CorrectInput) { stop("Invalid Cause") } ## Was planning on using this <match> functionality to get the <ColumnNameSub> to enter into the <order> function below but it didn't work (<order>, not <match>) # ColumnName=c("Hospital.30.Day.Death..Mortality..Rates.from.Heart.Attack", "Hospital.30.Day.Death..Mortality..Rates.from.Heart.Failure", "Hospital.30.Day.Death..Mortality..Rates.from.Pneumonia") # ColumnNameSub=ColumnName[match(outcome, CorrectInput)] # View(ColumnNameSub) StateSub=data[data$State == state, ] # View(StateSub) if (outcome == "heart attack") { RankedData=StateSub[order((as.numeric(StateSub[, "Hospital.30.Day.Death..Mortality..Rates.from.Heart.Attack"])), StateSub[ "Hospital.Name"], decreasing=FALSE, na.last=NA), ] } else if (outcome == "heart failure"){ RankedData=StateSub[order((as.numeric(StateSub[, "Hospital.30.Day.Death..Mortality..Rates.from.Heart.Failure"])), StateSub[ "Hospital.Name"], decreasing=FALSE, na.last=NA), ] } else { RankedData=StateSub[order((as.numeric(StateSub[,"Hospital.30.Day.Death..Mortality..Rates.from.Pneumonia"])), StateSub[ "Hospital.Name"], decreasing=FALSE, na.last=NA), ] } View(RankedData) if(num == "best"){ num=1 } if (num == "worst"){ num=nrow(RankedData) } if (is.numeric(num) & num>nrow(RankedData)){ return(NULL) } Ranked=RankedData[num,"Hospital.Name"] return(Ranked) }
a30bad79eced9ae47e0ed6f69b0c9d1397f7a84b
0122ae5c5fe5bd1ffa25184f70d525aea956cdef
/score.r
035fbb4854318cf6bf765ac717e3abc5361d7a0a
[]
no_license
TBKelley/KAGGLE-WISE2014
ddfc141397bc9db69ba2fac3e4f103c8d6f07135
f4832c95cae57713468aaa8a2c2fca4f105a66c4
refs/heads/master
2021-01-10T19:31:07.250474
2014-07-04T12:34:17
2014-07-04T12:34:17
null
0
0
null
null
null
null
UTF-8
R
false
false
879
r
score.r
score <- function(score.table) { if ("FALSE" %in% rownames(score.table) && "FALSE" %in% colnames(score.table)) { TN <- score.table["FALSE","FALSE"] } else { TN <- 0 } if ("FALSE" %in% rownames(score.table) && "TRUE" %in% colnames(score.table)) { FN <- score.table["FALSE","TRUE"] } else { FN <- 0 } if ("TRUE" %in% rownames(score.table) && "FALSE" %in% colnames(score.table)) { FP <- score.table["TRUE","FALSE"] } else { FP <- 0 } if ("TRUE" %in% rownames(score.table) && "TRUE" %in% colnames(score.table)) { TP <- score.table["TRUE","TRUE"] } else { TP <- 0 } predicted <- ifelse((TP + FP) == 0, 1, TP /(TP + FP)) recall <- ifelse((TP + FN) == 0, 1, TP/(TP + FN)) F1 <- 2 * predicted * recall /(predicted + recall) F1 }
4030053b564e9c3a8fb2917da4b30eac2fd22b7c
41003e2f32d2d45720f4f5e6eb37b0a121923779
/simulation/method_functions.R
48558140aa5fbefb24c93fc5c9f653e9c3411327
[]
no_license
GreenwoodLab/ggmix
d4a3de1a4d6740520fbbacec81d0de277646d2fa
96fba3925a1f9a2a2d31918be9c30cbbb296f69b
refs/heads/master
2020-04-02T10:40:01.978342
2018-06-28T14:17:37
2018-06-28T14:17:37
null
0
0
null
null
null
null
UTF-8
R
false
false
5,882
r
method_functions.R
## @knitr methods source("/mnt/GREENWOOD_BACKUP/home/sahir.bhatnagar/ggmix/simulation/packages.R") source("/mnt/GREENWOOD_BACKUP/home/sahir.bhatnagar/ggmix/simulation/functions.R") # lasso <- new_method("lasso", "Lasso", # method = function(model, draw) { # fitglmnet <- cv.glmnet(x = model$x, y = draw, alpha = 1, standardize = F) # list(beta = coef(fitglmnet, s = "lambda.min")[-1,,drop=F], # yhat = predict(fitglmnet, newx = model$x, s = "lambda.min"), # nonzero = coef(fitglmnet)[nonzeroCoef(coef(fitglmnet)),,drop=F], # nonzero_names = setdiff(rownames(coef(fitglmnet)[nonzeroCoef(coef(fitglmnet)),,drop=F]),c("(Intercept)")), # y = draw) # }) lasso <- new_method("lasso", "lasso", method = function(model, draw) { fitglmnet <- cv.glmnet(x = model$x_lasso, y = draw, alpha = 1, standardize = T, penalty.factor = c(rep(1, ncol(model$x)), rep(0,10))) model_error <- l2norm(model$mu - model$x %*% coef(fitglmnet, s = "lambda.min")[2:(ncol(model$x)+1),,drop=F]) list(beta = coef(fitglmnet, s = "lambda.min")[-1,,drop=F], model_error = model_error, eta = NA, sigma2 = NA, yhat = predict(fitglmnet, newx = model$x_lasso, s = "lambda.min"), nonzero = coef(fitglmnet, s = "lambda.min")[nonzeroCoef(coef(fitglmnet, s = "lambda.min")),,drop=F], nonzero_names = setdiff(rownames(coef(fitglmnet, s = "lambda.min")[nonzeroCoef(coef(fitglmnet, s = "lambda.min")),,drop=F]),c("(Intercept)")), y = draw) }) ggmix <- new_method("ggmix", "ggmix", method = function(model, draw) { fit <- penfam(x = model$x, y = draw, phi = model$kin, thresh_glmnet = 1e-10, epsilon = 1e-5, fdev = 1e-7, alpha = 1, tol.kkt = 1e-3, nlambda = 100, # an = log(log(model$n)) * log(model$n), # an = log(log(1000)), an = log(length(draw)), # lambda_min_ratio = ifelse(model$n < model$p, 0.01, 0.001), lambda_min_ratio = 0.05, eta_init = 0.5, maxit = 100) model_error <- l2norm(model$mu - model$x %*% coef(fit, s = fit$lambda_min)[2:(ncol(model$x)+1),,drop=F]) list(beta = fit$beta[,fit$lambda_min,drop=F], #this doesnt have intercept and is a 1-col matrix model_error = model_error, nonzero = predict(fit, type = "nonzero", s = fit$lambda_min), nonzero_names = setdiff(rownames(predict(fit, type = "nonzero", s = fit$lambda_min)), c("(Intercept)","eta","sigma2")), yhat = fit$predicted[,fit$lambda_min], eta = fit$eta[,fit$lambda_min], sigma2 = fit$sigma2[,fit$lambda_min], y = draw ) }) twostep <- new_method("twostep", "two step", method = function(model, draw) { # pheno_dat <- data.frame(Y = draw, id = rownames(model$kin)) # fit_lme <- coxme::lmekin(Y ~ 1 + (1|id), data = pheno_dat, varlist = model$kin) # newy <- residuals(fit_lme) # fitglmnet <- glmnet::cv.glmnet(x = model$x, y = newy, standardize = F, alpha = 1) # pheno_dat <- data.frame(Y = draw, id = rownames(model$kin)) x1 <- cbind(rep(1, nrow(model$x))) fit_lme <- gaston::lmm.aireml(draw, x1, K = model$kin) gaston_resid <- draw - (fit_lme$BLUP_omega + fit_lme$BLUP_beta) fitglmnet <- glmnet::cv.glmnet(x = model$x, y = gaston_resid, standardize = T, alpha = 1, intercept = T) model_error <- l2norm(model$mu - model$x %*% coef(fitglmnet, s = "lambda.min")[2:(ncol(model$x)+1),,drop=F]) list(beta = coef(fitglmnet, s = "lambda.min")[-1,,drop=F], yhat = predict(fitglmnet, newx = model$x, s = "lambda.min"), nonzero = coef(fitglmnet, s = "lambda.min")[nonzeroCoef(coef(fitglmnet, s = "lambda.min")),,drop=F], nonzero_names = setdiff(rownames(coef(fitglmnet, s = "lambda.min")[nonzeroCoef(coef(fitglmnet, s = "lambda.min")),,drop=F]),c("(Intercept)")), model_error = model_error, eta = NA, sigma2 = NA, y = draw) })
491f6fcb02cb9282e6708752ade0b27e6c0a8766
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/PPRL/examples/DeterministicLinkage.Rd.R
8c9ca1cf14dd4c94fc7dfad61836d6efedd92722
[]
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
920
r
DeterministicLinkage.Rd.R
library(PPRL) ### Name: DeterministicLinkage ### Title: Deterministic Record Linkage ### Aliases: DeterministicLinkage 'Record Linkage' ### ** Examples # load test data testFile <- file.path(path.package("PPRL"), "extdata/testdata.csv") testData <- read.csv(testFile, head = FALSE, sep = "\t", colClasses = "character") # define year of birth (V3) as blocking variable bl <- SelectBlockingFunction("V3", "V3", method = "exact") # Select first name and last name as linking variables, # to be linked using the soundex phonetic (first name) # and exact matching (last name) l1 <- SelectSimilarityFunction("V7", "V7", method = "Soundex") l2 <- SelectSimilarityFunction("V8", "V8", method = "exact") # Link the data as specified in bl and l1/l2 # (in this small example data is linked to itself) res <- DeterministicLinkage(testData$V1, testData, testData$V1, testData, similarity = c(l1, l2), blocking = bl)
2e94bf8891e462098ba5fc68b473c32c2cfd2c59
a225f9e6f0a2f10e9222b717549c8324cb4f0dc4
/lib/makeIcon.R
88ed7e5548af8ee2b26eab7919454260de39bcd0
[]
no_license
Bingjiling/ShinyAPP-Rats-in-NYC
eeed1eb6990034d069554fdaff6684400bd5ad32
8edcdbc71a692d26599a100caa23a72d5fa62194
refs/heads/master
2021-01-18T12:18:44.791579
2016-02-27T03:25:10
2016-02-27T03:25:10
null
0
0
null
null
null
null
UTF-8
R
false
false
1,350
r
makeIcon.R
size = 10 icon1 <- makeIcon( iconUrl = "Hamburger.gif", iconWidth = size, iconHeight = size ) icon2 <- makeIcon( iconUrl = "https://www.emojibase.com/resources/img/emojis/apple/x1f1ee-1f1f9.png.pagespeed.ic.SxTX2CImcp.png", iconWidth = size, iconHeight = size ) icon3 <- makeIcon( iconUrl = "http://emojipedia-us.s3.amazonaws.com/cache/a1/5d/a15d18cf274f1701b4162c3876dd11e4.png", iconWidth = size, iconHeight = size ) icon4 <- makeIcon( iconUrl = "https://www.emojibase.com/resources/img/emojis/hangouts/1f1e8-1f1f3.png", iconWidth = size, iconHeight = size ) icon5 <- makeIcon( iconUrl = "http://pix.iemoji.com/images/emoji/apple/ios-9/256/hamburger.png", iconWidth = size, iconHeight = size ) icon6 <- makeIcon( iconUrl = "http://pix.iemoji.com/images/emoji/apple/ios-9/256/hot-beverage.png", iconWidth = size, iconHeight = size ) icon7 <- makeIcon( iconUrl = "http://3z489t2p9kbdv4il24as7q51.wpengine.netdna-cdn.com/wp-content/uploads/2015/10/pizza-emjoi.png", iconWidth = size, iconHeight = size ) icon8 <- makeIcon( iconUrl = "http://emojipedia-us.s3.amazonaws.com/cache/76/3f/763f6bb87378b2c3e26571561b235e81.png", iconWidth = size, iconHeight = size ) icons = c(icon1,icon2,icon3,icon4,icon5,icon6,icon7,icon8)
14cd1e28447c722249056f3d545a66c5de6e02ef
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/PepSAVIms/examples/msDat.Rd.R
0acc703c5c2825048333fe9b81f92ef50a7a7e79
[]
no_license
surayaaramli/typeRrh
d257ac8905c49123f4ccd4e377ee3dfc84d1636c
66e6996f31961bc8b9aafe1a6a6098327b66bf71
refs/heads/master
2023-05-05T04:05:31.617869
2019-04-25T22:10:06
2019-04-25T22:10:06
null
0
0
null
null
null
null
UTF-8
R
false
false
1,065
r
msDat.Rd.R
library(PepSAVIms) ### Name: msDat ### Title: Constructor for class 'msDat' ### Aliases: msDat ### ** Examples # Load mass spectrometry data data(mass_spec) # Convert mass_spec from a data.frame to an msDat object ms <- msDat(mass_spec = mass_spec, mtoz = "m/z", charge = "Charge", ms_inten = c(paste0("_", 11:43), "_47")) # Dimension of the data dim(ms) # Print the first few rows and columns ms[1:5, 1:2] # Let's change the fraction names to something more concise colnames(ms) <- c(paste0("frac", 11:43), "frac47") # Print the first few rows and columns with the new fraction names ms[1:5, 1:8] # Suppose there are some m/z levels that we wish to remove ms <- ms[-c(2, 4), ] # Print the first few rows and columns after removing rows 2 and 4 ms[1:5, 1:8] # Suppose that there was an instrumentation error and that we need to change # some values ms[1, paste0("frac", 12:17)] <- c(55, 57, 62, 66, 71, 79) # Print the first few rows and columns after changing some of the values in # the first row ms[1:5, 1:10]
980b40a1b7cbc39bfb8bd2eeb2eab5d600097da3
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/Ecfun/examples/logVarCor.Rd.R
0d498761ae5c0ba9626259ecf0a2949404607160
[]
no_license
surayaaramli/typeRrh
d257ac8905c49123f4ccd4e377ee3dfc84d1636c
66e6996f31961bc8b9aafe1a6a6098327b66bf71
refs/heads/master
2023-05-05T04:05:31.617869
2019-04-25T22:10:06
2019-04-25T22:10:06
null
0
0
null
null
null
null
UTF-8
R
false
false
1,725
r
logVarCor.Rd.R
library(Ecfun) ### Name: logVarCor ### Title: Log-diagonal reprentation of a variance matrix ### Aliases: logVarCor ### Keywords: multivariate ### ** Examples ## ## 1. Trivial 1 x 1 matrix ## # 1.1. convert vector to "matrix" mat1 <- logVarCor(1) # check ## Don't show: stopifnot( ## End(Don't show) all.equal(mat1, matrix(exp(1), 1)) ## Don't show: ) ## End(Don't show) # 1.2. Convert 1 x 1 matrix to vector lVCd1 <- logVarCor(diag(1)) # check lVCd1. <- 0 attr(lVCd1., 'corr') <- numeric(0) ## Don't show: stopifnot( ## End(Don't show) all.equal(lVCd1, lVCd1.) ## Don't show: ) ## End(Don't show) ## ## 2. simple 2 x 2 matrix ## # 2.1. convert 1:2 into a matrix lVC2 <- logVarCor(1:2) # check lVC2. <- diag(exp(1:2)) ## Don't show: stopifnot( ## End(Don't show) all.equal(lVC2, lVC2.) ## Don't show: ) ## End(Don't show) # 2.2. Convert a matrix into a vector lVC2d <- logVarCor(diag(1:2)) # check lVC2d. <- log(1:2) attr(lVC2d., 'corr') <- 0 ## Don't show: stopifnot( ## End(Don't show) all.equal(lVC2d, lVC2d.) ## Don't show: ) ## End(Don't show) ## ## 3. 3-d covariance matrix with nonzero correlations ## # 3.1. Create matrix (ex3 <- tcrossprod(matrix(c(rep(1,3), 0:2), 3))) dimnames(ex3) <- list(letters[1:3], letters[1:3]) # 3.2. Convert to vector (Ex3 <- logVarCor(ex3)) # check Ex3. <- log(c(1, 2, 5)) names(Ex3.) <- letters[1:3] attr(Ex3., 'corr') <- c(1/sqrt(2), 1/sqrt(5), 3/sqrt(10)) ## Don't show: stopifnot( ## End(Don't show) all.equal(Ex3, Ex3.) ## Don't show: ) ## End(Don't show) # 3.3. Convert back to a matrix Ex3.2 <- logVarCor(Ex3) # check ## Don't show: stopifnot( ## End(Don't show) all.equal(ex3, Ex3.2) ## Don't show: ) ## End(Don't show)
d459befca9d09de6d337cc94a0a776882928aa88
862bee845b055a3cfb7c0ab5ac1c277ed35f438f
/library/ggthemes/examples/ex-theme_pander.R
7c5229b72d07bbadecaa22c4babc7ec12f96708d
[ "MIT" ]
permissive
mayousif/Turbidity-Cleaner
a4862f54ca47305cfa47d6fcfa048e1573d6a2b7
e756d9359f1215a4c9e6ad993eaccbc3fb6fe924
refs/heads/master
2022-05-09T07:32:55.856365
2022-04-22T20:05:10
2022-04-22T20:05:10
205,734,717
2
2
null
2020-11-02T21:31:19
2019-09-01T21:31:43
HTML
UTF-8
R
false
false
428
r
ex-theme_pander.R
require("ggplot2") if (require("pander")) { p <- ggplot(mtcars, aes(x = mpg, y = wt)) + geom_point() p + theme_pander() panderOptions("graph.grid.color", "red") p + theme_pander() p <- ggplot(mtcars, aes(wt, mpg, colour = factor(cyl))) + geom_point() p + theme_pander() + scale_color_pander() ggplot(mpg, aes(x = class, fill = drv)) + geom_bar() + scale_fill_pander() + theme_pander() }
ac82022ed86025f45e7c0649a132f78b1c7d51a2
07bc1ed7d93eae1e2c43519d0afce17e33dfe8fb
/PAF_calculation_article_github.R
79edc2207913cb31daf086fa8b89d44795f364cd
[]
no_license
mulderac91/R-STECO157-spatialanalysis
48046a68a2bf06b6e3e25ce75f71622c754268dc
199e02172f548b69244a4c7e37a1e94c4a6e5d38
refs/heads/master
2022-04-26T19:28:34.550359
2020-04-30T11:43:23
2020-04-30T11:43:23
260,139,922
0
0
null
null
null
null
UTF-8
R
false
false
2,735
r
PAF_calculation_article_github.R
# # Init ---- # # Load packages library(tidyverse) library(INLA) # # Data ---- # # Run script STEC and animal numbers first # # Augment data ---- # tmp.data.summer <- tmp.data.summer %>% select(-geometry) ex.data.aug <- bind_rows( # Augmentation idicator: 0 = original data, 1 = augmented data bind_cols(tmp.data.summer, tibble(augmented = rep(0, nrow(tmp.data.summer)))), bind_cols(tmp.data.summer, tibble(augmented = rep(1, nrow(tmp.data.summer))))) %>% mutate( # Set exposed to reference value Kleine_Herkauwers_totaal = if_else(augmented == 1, 0, Kleine_Herkauwers_totaal), # Set exposed.cat to reference category #exposed.cat = if_else(augmented == 1, factor(levels(exposed.cat)[1], levels = levels(exposed.cat)), exposed.cat), # Set outcome to NA cases = if_else(augmented == 1, NA_real_, cases)) %>% ungroup ex.data.aug # # Fit models ---- # # Fit Poisson regression model with INLA fit.inla <- inla( formula = cases ~ sex + agecat + log2(Pluimvee_totaal + 1) + log2(Varkens_totaal + 1) + log2(Rundvee_totaal + 1) + log2(Kleine_Herkauwers_totaal + 1) + f(hex.car, model = "besag", hyper = list(prec = list(prior = "loggamma", param = c(1, 0.1))), graph = hex.nb) + f(hex.iid, model = "iid", hyper = list(prec = list(prior = "loggamma", param = c(1, 0.1)))), E = population, family = "poisson", data = ex.data.aug, control.inla = list(int.strategy = "eb"), control.predictor = list(compute = TRUE), # Enable posterior sampling control.compute = list(config = TRUE)) # # PAF # # Calculate predictions for both the original and augmented data # for both GLM and INLA models ex.data.aug <- ex.data.aug %>% mutate( # Predictions with INLA pred.inla = population*exp(fit.inla$summary.linear.predictor[, "mean"])) # PAF is then given by pred.data <- ex.data.aug %>% group_by(augmented) %>% summarize( pred.inla = sum(pred.inla)) PAF.inla <- pred.data %>% pull(pred.inla) PAF.inla <- (PAF.inla[1] - PAF.inla[2])/PAF.inla[1] PAF.inla post.inla <- inla.posterior.sample(n = 10000, result = fit.inla) linpred <- sapply(X = post.inla, FUN = function(x) { x.latent <- x$latent x.latent[x.latent %>% rownames %>% str_detect(pattern = "Predictor"), ] }) PAF <- rep(0, ncol(linpred)) for (i in 1:ncol(linpred)) { ex.data.aug <- ex.data.aug %>% mutate( # Predictions with INLA pred.inla = population*exp(linpred[, i])) # PAF is then given by pred.data <- ex.data.aug %>% group_by(augmented) %>% summarize( pred.inla = sum(pred.inla)) PAF.inla <- pred.data %>% pull(pred.inla) PAF.inla <- (PAF.inla[1] - PAF.inla[2])/PAF.inla[1] PAF[i] <- PAF.inla } quantile(PAF, c(0.5, 0.025, 0.975))
4f3d95fb7d71df2927ae9bb960c3a28a9a9b8e1d
30d561f20092f3549e0e2edb74fa2a4b8189d388
/man/edad_educ.Rd
3638651e6943ba9050271bcd89d1160e87c51064
[]
no_license
arcruz0/paqueteadp
11b134c25cb12303352848260d916491720d5e58
44a8c7733b71bee322cba4aa12e68068652e0338
refs/heads/master
2021-06-13T09:40:27.350756
2021-04-02T22:08:14
2021-04-02T22:08:14
175,672,056
3
3
null
null
null
null
UTF-8
R
false
true
646
rd
edad_educ.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/data_files.R \docType{data} \name{edad_educ} \alias{edad_educ} \title{Edad y educación como confounders} \description{ Datos simulados, en los que la edad y la educación son confounders para el tratamiento de usar redes de mosquitos. Creados por Andrew Heiss. Datos de los estados de Brasil, compilados por Freire (2018) } \references{ Freire, D. (2018). Evaluating the effect of homicide prevention strategies in são paulo, brazil: A synthetic control approach. Latin American Research Review, 53(2), 231. \url{https://doi.org/10.25222/larr.334} } \keyword{data}
5f8163933c748d20d768b0f86e5a20e0fdf5b473
fc5e180eef8ec24d8fe2396794bb317fbb8b1a42
/R/whatNWIS.R
1573b3f6930246d12c87ff7cfe187e06dafecefb
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-public-domain-disclaimer" ]
permissive
ldecicco-USGS/USGSwsDataRetrieval
cd6c3d7be7439e9a96b6aa3c88cd3c0ed210c88e
507d4088860915778af2db0c16c8b8a63f622b3a
refs/heads/master
2020-03-30T08:50:42.163419
2015-02-13T18:59:31
2015-02-13T18:59:31
30,770,882
0
0
null
2015-02-13T18:57:39
2015-02-13T18:57:39
null
UTF-8
R
false
false
5,003
r
whatNWIS.R
#' @title Data Inventory #' #' @description Gets a description of unit-value, daily-value, or instantaneous #'water-quality data are available for a USGS station and the #'beginning and ending dates of each parameter. #' #' @details The parameter group codes and corresponding NWIS descriptions #'\tabular{ll}{ #'Code \tab Description\cr #'INF \tab Information \cr #'PHY \tab Physical \cr #'INM \tab Inorganics, Major, Metals (major cations) \cr #'INN \tab Inorganics, Major, Non-metals (major anions) \cr #'NUT \tab Nutrient \cr #'MBI \tab Microbiological \cr #'BIO \tab Biological \cr #'IMN \tab Inorganics, Minor, Non-metals \cr #'IMM \tab Inorganics, Minor, Metals \cr #'TOX \tab Toxicity \cr #'OPE \tab Organics, pesticide \cr #'OPC \tab Organics, PCBs \cr #'OOT \tab Organics, other \cr #'RAD \tab Radiochemical \cr #'SED \tab Sediment \cr #'POP \tab Population/community \cr #'} #' @param site a single USGS station identifier as a character string. #' @param param.groups a character vector indicating the parameter group #'codes to retrun. If blank, then return all parameters. If "ALL," #'then return only the summary of all constituents. Otherwise any combination of #'"INF," "PHY," "INM," "INN," "NUT," "MBI," "BIO," "IMM," "IMN," "TOX," #'"OPE," "OPC," "OOT," "RAD," "SED", and "POP." See \bold{Details} for #'a decription of the parameter group codes. #' @return A data frame containing these columns: #'site_no, the USGS station identifier; #'parm_cd, the parameter code; description, a desciption of the parameter code; #'begin_date, the earliest date available for the parameter code data; #'end_date, the latest date available for the parameter code data; and #'count_nu, the number of values available for the parameter code. #',EndDate, pCode, and name. #' @keywords DataIO #' @examples #' \dontrun{ #'# These examples require an internet connection to run #'UVavailable <- whatNWISuv("04027000") #'} #' @name whatNWIS #' @rdname whatNWIS #' @export whatNWISuv whatNWISuv <- function(site) { ## Coding history: ## 2014Sep09 DLLorenz merge whatUV with getDataAvailability ## if(missing(site)) stop("site is required") myurl <- paste("http://waterservices.usgs.gov/nwis/site?format=rdb&seriesCatalogOutput=true&sites=",site,sep = "") retval <- importRDB(myurl) ## Filter for service requested (uv) and remove unnecessary columns retval <- retval[retval$data_type_cd %in% "uv", c("parm_cd", "site_no", "stat_cd", "dd_nu", "loc_web_ds", "medium_grp_cd", "parm_grp_cd", "srs_id", "access_cd", "begin_date", "end_date", "count_nu")] ## Merge with pcode info to get descriptions pCodes <- retval$parm_cd pcodeINFO <- parameterCdFile[parameterCdFile$parameter_cd %in% pCodes, c("parameter_cd", "srsname", "parameter_units")] retval <- merge(pcodeINFO,retval,by.x="parameter_cd", by.y="parm_cd", all.y=TRUE) return(retval) } #' @rdname whatNWIS #' @export whatNWISdv whatNWISdv <- function(site) { ## Coding history: ## 2014Sep09 DLLorenz merge whatUV with getDataAvailability ## if(missing(site)) stop("site is required") myurl <- paste("http://waterservices.usgs.gov/nwis/site?format=rdb&seriesCatalogOutput=true&sites=",site,sep = "") retval <- importRDB(myurl) ## Filter for service requested (uv) and remove unnecessary columns retval <- retval[retval$data_type_cd %in% "dv", c("parm_cd", "site_no", "stat_cd", "dd_nu", "loc_web_ds", "medium_grp_cd", "parm_grp_cd", "srs_id", "access_cd", "begin_date", "end_date", "count_nu")] ## Merge with pcode info to get descriptions pCodes <- retval$parm_cd pcodeINFO <- parameterCdFile[parameterCdFile$parameter_cd %in% pCodes, c("parameter_cd", "srsname", "parameter_units")] retval <- merge(pcodeINFO,retval,by.x="parameter_cd", by.y="parm_cd", all.y=TRUE) return(retval) } #' @rdname whatNWIS #' @export whatNWISqw whatNWISqw <- function(site, param.groups="") { ## Coding history: ## 2014Sep09 DLLorenz merge whatUV with getDataAvailability ## if(missing(site)) stop("site is required") myurl <- paste("http://waterservices.usgs.gov/nwis/site?format=rdb&seriesCatalogOutput=true&sites=",site,sep = "") retval <- importRDB(myurl) ## Filter for service requested (qw) and remove unnecessary columns retval <- retval[retval$data_type_cd %in% "qw", c("parm_cd", "site_no", "stat_cd", "dd_nu", "loc_web_ds", "medium_grp_cd", "parm_grp_cd", "srs_id", "access_cd", "begin_date", "end_date", "count_nu")] ## Merge with pcode info to get descriptions pCodes <- retval$parm_cd pcodeINFO <- parameterCdFile[parameterCdFile$parameter_cd %in% pCodes, c("parameter_cd", "srsname", "parameter_units")] retval <- merge(pcodeINFO,retval,by.x="parameter_cd", by.y="parm_cd", all.y=TRUE) ## Filter for parameter groups if(param.groups[1L] != "") retval <- retval[retval$parm_grp_cd %in% param.groups, ] return(retval) }
ef8e53ade373ab8ba221b077b3d2f81b33ba0b49
05965f92ec94ea32dcf6677f7345f6b0789265ae
/R/kobo_to_xlsform.R
43d4aab24a6d092d01c045ce2dad52f654faf3b2
[]
no_license
DamienSeite/koboloadeR
3187286e6351b24c9a43f3a0938e4bdfe20b2681
5da3c04531cf415fbca40950b52e86e547578635
refs/heads/gh-pages
2020-03-28T17:30:24.576746
2018-09-14T14:05:35
2018-09-14T14:05:35
131,474,775
0
0
null
2018-04-29T07:29:05
2018-04-29T07:29:05
null
UTF-8
R
false
false
3,561
r
kobo_to_xlsform.R
#' @name kobo_to_xlsform #' @rdname kobo_to_xlsform #' @title Generate xlsfrom skeleton from a dataframe #' #' @description Creates and save a xlsform skeleton from a data.frames in your data folder #' The form.xls will be saved in the data folder of your project. #' The generated xlsfrom will need to be manually edited to configure your analysis #' #' Note that this function only works with \code{data.frames}. The function #' will throw an error for any other object types. #' #' @param n number of levels for a factor to be considered as a text #' #' #' #' #' @author Edouard Legoupil #' #' @export #' @examples #' data(iris) #' str(iris) #' kobo_to_xlsform(iris) kobo_to_xlsform <- function(df, n=100) { stopifnot(is.data.frame(df)) # df <- data.df ## str(df) # n = 10 df[sapply(df, is.labelled)] <- lapply(df[sapply(df, is.labelled)], as.factor) ## build survey sheet survey <- data.frame( type = rep(as.character(NA), ncol(df)), name = names(df), label = names(df), chapter = rep(as.character(NA), ncol(df)), disaggregation = rep(as.character(NA), ncol(df)), correlate = rep(as.character(NA), ncol(df)), variable = rep(as.character(NA), ncol(df)), sensitive = rep(as.character(NA), ncol(df)), anonymise = rep(as.character(NA), ncol(df)), stringsAsFactors = FALSE) ## Fill survey type for(i in seq_along(df)) { #i <-12 #cat(i) if(is.factor(df[,i])) { survey[i,]$type <- paste0('select_one ', as.character(names(df[i])), '_choices') } else { survey[i,]$type <- class(df[,i])[1] } } ## build choices sheet choices <- data.frame(list_name = as.character(NA), name = as.character(NA), label = as.character(NA), order = as.integer(NA), stringsAsFactors = FALSE) ## Loop around variables to build choices based on factor levels for(i in seq_along(df)) { #i <-2 if(is.factor(df[,i])) { cat(paste0("Factor: ",i,"\n")) frame <- as.data.frame((levels(df[,i]))) if (nrow(frame)!=0 & nrow(frame)<100 ){ for(j in 1:nrow(frame)) { # j <- 1 choices1 <- data.frame(list_name = as.character(NA), name = as.character(NA), label = as.character(NA), order = as.integer(NA), stringsAsFactors = FALSE) cat(paste0("Inserting level: ",j,"\n")) choices1[j,]$list_name <- paste0( as.character(names(df[i])), '_choices') choices1[j,]$name <- as.character(frame[j, ]) choices1[j,]$label <- as.character(frame[j,]) choices1[j,]$order <- j choices <- rbind(choices, choices1) } rm(choices1) } else {cat("Too many choices to consider it as a factor\n")} ### } else {cat("This is not a factor \n")} } # install.packages("WriteXLS") library(WriteXLS) WriteXLS("survey", "data/form-from-data.xls", AdjWidth = TRUE, BoldHeaderRow = TRUE, AutoFilter = TRUE, FreezeRow = 1) #WriteXLS("choices", "data/form.xls", AdjWidth = TRUE, BoldHeaderRow = TRUE, AutoFilter = TRUE, FreezeRow = 1) library(XLConnect) writeWorksheetToFile(file = "data/form-from-data.xls", data = choices, sheet = "choices") }
f844f7df03c50588a60b817035ce3cca3941df0c
c0693698db7a132954d748ee3b4c7e156e12475f
/preprocess/8_nat_fig.R
70cf064610d6480d1e2f71cc52aeaa5233f9aeb2
[]
no_license
Flowminder/FDFA_01
cd527b2ed444da8d13eaf9aea58c8b8992f1e524
505792796b5cb4c88bc8f49518f87148976b1cf0
refs/heads/master
2023-04-10T04:51:56.346936
2021-04-15T10:58:10
2021-04-15T10:58:10
186,587,717
0
0
null
null
null
null
UTF-8
R
false
false
16,009
r
8_nat_fig.R
# national figure summaries #### EM_int=tbl(mig_db,"EM_int") EM_nat=tbl(mig_db,"EM_nat") IM_int=tbl(mig_db,"IM_int") IM_nat=tbl(mig_db,"IM_nat") admin_names=tbl(mig_db,"admin_names")%>% collect(n=Inf) COUNTRIES=EM_int%>% distinct(ISO)%>% collect(n=Inf) COUNTRIES=COUNTRIES$ISO df=data.frame() country_clicked="AFG" for(country_clicked in COUNTRIES){ # EM_int number & % ##### EM_int_mig_data=EM_int%>% filter(ISO==country_clicked)%>% group_by(sex)%>% summarise(move=sum(move))%>% collect() EM_int_mig_all=EM_int_mig_data%>% filter(sex=="all") EM_int_mig_female=EM_int_mig_data%>% filter(sex=="F") if(dim(EM_int_mig_female)[1]==0){ EM_int_mig_female=data.frame(sex="F", move=NA) } EM_int_mig_male=EM_int_mig_data%>% filter(sex=="M") EM_int_mig_female_perc=EM_int_mig_female$move/EM_int_mig_all$move EM_int_mig_male_perc=EM_int_mig_male$move/EM_int_mig_all$move # EM_nat number & % ##### EM_nat_mig_data=EM_nat%>% filter(ISO==country_clicked)%>% group_by(sex)%>% summarise(move=sum(move))%>% collect() EM_nat_mig_all=EM_nat_mig_data%>% filter(sex=="all") EM_nat_mig_female=EM_nat_mig_data%>% filter(sex=="F") EM_nat_mig_male=EM_nat_mig_data%>% filter(sex=="M") EM_nat_mig_female_perc=EM_nat_mig_female$move/EM_nat_mig_all$move EM_nat_mig_male_perc=EM_nat_mig_male$move/EM_nat_mig_all$move # IM_int number & % ##### IM_int_mig_data=IM_int%>% filter(ISO==country_clicked)%>% group_by(sex)%>% summarise(move=sum(move))%>% collect() IM_int_mig_all=IM_int_mig_data%>% filter(sex=="all") IM_int_mig_female=IM_int_mig_data%>% filter(sex=="F") IM_int_mig_male=IM_int_mig_data%>% filter(sex=="M") IM_int_mig_female_perc=IM_int_mig_female$move/IM_int_mig_all$move IM_int_mig_male_perc=IM_int_mig_male$move/IM_int_mig_all$move # IM_nat number & % ##### IM_nat_mig_data=IM_nat%>% filter(ISO==country_clicked)%>% group_by(sex)%>% summarise(move=sum(move))%>% collect() IM_nat_mig_all=IM_nat_mig_data%>% filter(sex=="all") IM_nat_mig_female=IM_nat_mig_data%>% filter(sex=="F") IM_nat_mig_male=IM_nat_mig_data%>% filter(sex=="M") IM_nat_mig_female_perc=IM_nat_mig_female$move/IM_nat_mig_all$move IM_nat_mig_male_perc=IM_nat_mig_male$move/IM_nat_mig_all$move # top destination countries of international emigration ##### data_dest_all=tbl(mig_db,"GLOBAL_mig_int_X_50_all_country") top_destination_all=data_dest_all%>% filter(ISOI==country_clicked)%>% collect()%>% group_by(ISOJ)%>% summarise(move=sum(pred_seed1))%>% arrange(desc(move))%>% top_n(3,move)%>% mutate(total=EM_int_mig_all$move, perc=move/total)%>% left_join(admin_names%>% distinct(ISO,COUNTRY_NAME), by=c("ISOJ"="ISO")) data_dest_female=tbl(mig_db,"GLOBAL_mig_int_X_50_F_country") top_destination_female=data_dest_female%>% filter(ISOI==country_clicked)%>% collect()%>% group_by(ISOJ)%>% summarise(move=sum(pred_seed1))%>% arrange(desc(move))%>% top_n(3,move)%>% mutate(total=EM_int_mig_female$move, perc=move/total)%>% left_join(admin_names%>% distinct(ISO,COUNTRY_NAME), by=c("ISOJ"="ISO")) data_dest_male=tbl(mig_db,"GLOBAL_mig_int_X_50_M_country") top_destination_male=data_dest_male%>% filter(ISOI==country_clicked)%>% collect()%>% group_by(ISOJ)%>% summarise(move=sum(pred_seed1))%>% arrange(desc(move))%>% top_n(3,move)%>% mutate(total=EM_int_mig_male$move, perc=move/total)%>% left_join(admin_names%>% distinct(ISO,COUNTRY_NAME), by=c("ISOJ"="ISO")) # top source countries of international immigration #### data_source_all=tbl(mig_db,"GLOBAL_mig_int_M_50_all_country") top_source_all=data_source_all%>% filter(ISOJ==country_clicked)%>% collect()%>% group_by(ISOI)%>% summarise(move=sum(pred_seed1))%>% arrange(desc(move))%>% top_n(3,move)%>% mutate(total=IM_int_mig_all$move, perc=move/total)%>% left_join(admin_names%>% distinct(ISO,COUNTRY_NAME), by=c("ISOI"="ISO")) data_source_female=tbl(mig_db,"GLOBAL_mig_int_M_50_F_country") top_source_female=data_source_female%>% filter(ISOJ==country_clicked)%>% collect()%>% group_by(ISOI)%>% summarise(move=sum(pred_seed1))%>% arrange(desc(move))%>% top_n(3,move)%>% mutate(total=IM_int_mig_female$move, perc=move/total)%>% left_join(admin_names%>% distinct(ISO,COUNTRY_NAME), by=c("ISOI"="ISO")) data_source_male=tbl(mig_db,"GLOBAL_mig_int_M_50_M_country") top_source_male=data_source_male%>% filter(ISOJ==country_clicked)%>% collect()%>% group_by(ISOI)%>% summarise(move=sum(pred_seed1))%>% arrange(desc(move))%>% top_n(3,move)%>% mutate(total=IM_int_mig_male$move, perc=move/total)%>% left_join(admin_names%>% distinct(ISO,COUNTRY_NAME), by=c("ISOI"="ISO")) # top destination admin of internal emigration ##### data_dest_all=tbl(mig_db,"GLOBAL_mig_nat_X_50_all_admin") top_destination_all_nat=data_dest_all%>% filter(ISOI==country_clicked)%>% collect()%>% group_by(JOIN_ID_J)%>% summarise(move=sum(sex_nat))%>% arrange(desc(move))%>% top_n(3,move)%>% mutate(total=EM_nat_mig_all$move, perc=move/total)%>% left_join(admin_names%>% filter(ISO==country_clicked)%>% distinct(JOIN_ID,COUNTRY_NAME,ADMIN_NAME), by=c("JOIN_ID_J"="JOIN_ID")) data_dest_female=tbl(mig_db,"GLOBAL_mig_nat_X_50_F_admin") top_destination_female_nat=data_dest_female%>% filter(ISOI==country_clicked)%>% collect()%>% group_by(JOIN_ID_J)%>% summarise(move=sum(sex_nat))%>% arrange(desc(move))%>% top_n(3,move)%>% mutate(total=EM_nat_mig_female$move, perc=move/total)%>% left_join(admin_names%>% filter(ISO==country_clicked)%>% distinct(JOIN_ID,COUNTRY_NAME,ADMIN_NAME), by=c("JOIN_ID_J"="JOIN_ID")) data_dest_male=tbl(mig_db,"GLOBAL_mig_nat_X_50_M_admin") top_destination_male_nat=data_dest_male%>% filter(ISOI==country_clicked)%>% collect()%>% group_by(JOIN_ID_J)%>% summarise(move=sum(sex_nat))%>% arrange(desc(move))%>% top_n(3,move)%>% mutate(total=EM_nat_mig_male$move, perc=move/total)%>% left_join(admin_names%>% filter(ISO==country_clicked)%>% distinct(JOIN_ID,COUNTRY_NAME,ADMIN_NAME), by=c("JOIN_ID_J"="JOIN_ID")) # top source admin of internal immigration ##### data_source_all=tbl(mig_db,"GLOBAL_mig_nat_M_50_all_admin") top_source_all_nat=data_source_all%>% filter(ISOI==country_clicked)%>% collect()%>% group_by(JOIN_ID_I)%>% summarise(move=sum(sex_nat))%>% arrange(desc(move))%>% top_n(3,move)%>% mutate(total=EM_nat_mig_all$move, perc=move/total)%>% left_join(admin_names%>% filter(ISO==country_clicked)%>% distinct(JOIN_ID,COUNTRY_NAME,ADMIN_NAME), by=c("JOIN_ID_I"="JOIN_ID")) data_source_female=tbl(mig_db,"GLOBAL_mig_nat_M_50_F_admin") top_source_female_nat=data_source_female%>% filter(ISOI==country_clicked)%>% collect()%>% group_by(JOIN_ID_I)%>% summarise(move=sum(sex_nat))%>% arrange(desc(move))%>% top_n(3,move)%>% mutate(total=EM_nat_mig_female$move, perc=move/total)%>% left_join(admin_names%>% filter(ISO==country_clicked)%>% distinct(JOIN_ID,COUNTRY_NAME,ADMIN_NAME), by=c("JOIN_ID_I"="JOIN_ID")) data_source_male=tbl(mig_db,"GLOBAL_mig_nat_M_50_M_admin") top_source_male_nat=data_source_male%>% filter(ISOI==country_clicked)%>% collect()%>% group_by(JOIN_ID_I)%>% summarise(move=sum(sex_nat))%>% arrange(desc(move))%>% top_n(3,move)%>% mutate(total=EM_nat_mig_male$move, perc=move/total)%>% left_join(admin_names%>% filter(ISO==country_clicked)%>% distinct(JOIN_ID,COUNTRY_NAME,ADMIN_NAME), by=c("JOIN_ID_I"="JOIN_ID")) # correct missing variables ##### variables=c("EM_int_mig_all", "EM_int_mig_female", "EM_int_mig_male", "EM_int_mig_female_perc", "EM_int_mig_male_perc", "IM_int_mig_all", "IM_int_mig_female", "IM_int_mig_male", "IM_int_mig_female_perc", "IM_int_mig_male_perc", "EM_nat_mig_all", "EM_nat_mig_female_perc", "EM_nat_mig_male_perc", "top_destination_all","top_destination_female","top_destination_male", "top_source_all","top_source_female","top_source_male", "top_destination_all_nat","top_destination_female_nat","top_destination_male_nat", "top_source_all_nat","top_source_female_nat","top_source_male_nat") for(VAR in variables){ var_test=get(VAR) var_test=as.data.frame(var_test) if(nrow(var_test)==0){ NAMES=names(var_test) var_test=data.frame(data.frame(t(array(NA,ncol(var_test))))) names(var_test)=NAMES assign(VAR, var_test) } } # data frame ##### nat_fig=data.frame(ISO=c(country_clicked,country_clicked,country_clicked), sex=c("all","F","M"), int_number_X=c(EM_int_mig_all$move,EM_int_mig_female$move,EM_int_mig_male$move), int_percent_X=c(1,EM_int_mig_female_perc,EM_int_mig_male_perc), int_number_M=c(IM_int_mig_all$move,IM_int_mig_female$move,IM_int_mig_male$move), int_percent_M=unlist(c(1,IM_int_mig_female_perc,IM_int_mig_male_perc)), nat_number=c(EM_nat_mig_all$move,EM_nat_mig_female$move,EM_nat_mig_male$move), nat_percent=c(1,EM_nat_mig_female_perc,EM_nat_mig_male_perc), int_top_dest_1_name=c(top_destination_all$COUNTRY_NAME[1],top_destination_female$COUNTRY_NAME[1],top_destination_male$COUNTRY_NAME[1]), int_top_dest_1_number=c(top_destination_all$move[1],top_destination_female$move[1],top_destination_male$move[1]), int_top_dest_1_percent=c(top_destination_all$perc[1],top_destination_female$perc[1],top_destination_male$perc[1]), int_top_dest_2_name=c(top_destination_all$COUNTRY_NAME[2],top_destination_female$COUNTRY_NAME[2],top_destination_male$COUNTRY_NAME[2]), int_top_dest_2_number=c(top_destination_all$move[2],top_destination_female$move[2],top_destination_male$move[2]), int_top_dest_2_percent=c(top_destination_all$perc[2],top_destination_female$perc[2],top_destination_male$perc[2]), int_top_dest_3_name=c(top_destination_all$COUNTRY_NAME[3],top_destination_female$COUNTRY_NAME[3],top_destination_male$COUNTRY_NAME[3]), int_top_dest_3_number=c(top_destination_all$move[3],top_destination_female$move[3],top_destination_male$move[3]), int_top_dest_3_percent=c(top_destination_all$perc[3],top_destination_female$perc[3],top_destination_male$perc[3]), int_top_source_1_name=c(top_source_all$COUNTRY_NAME[1],top_source_female$COUNTRY_NAME[1],top_source_male$COUNTRY_NAME[1]), int_top_source_1_number=c(top_source_all$move[1],top_source_female$move[1],top_source_male$move[1]), int_top_source_1_percent=c(top_source_all$perc[1],top_source_female$perc[1],top_source_male$perc[1]), int_top_source_2_name=c(top_source_all$COUNTRY_NAME[2],top_source_female$COUNTRY_NAME[2],top_source_male$COUNTRY_NAME[2]), int_top_source_2_number=c(top_source_all$move[2],top_source_female$move[2],top_source_male$move[2]), int_top_source_2_percent=c(top_source_all$perc[2],top_source_female$perc[2],top_source_male$perc[2]), int_top_source_3_name=c(top_source_all$COUNTRY_NAME[3],top_source_female$COUNTRY_NAME[3],top_source_male$COUNTRY_NAME[3]), int_top_source_3_number=c(top_source_all$move[3],top_source_female$move[3],top_source_male$move[3]), int_top_source_3_percent=c(top_source_all$perc[3],top_source_female$perc[3],top_source_male$perc[3]), nat_top_dest_1_name=c(top_destination_all_nat$ADMIN_NAME[1],top_destination_female_nat$ADMIN_NAME[1],top_destination_male_nat$ADMIN_NAME[1]), nat_top_dest_1_number=c(top_destination_all_nat$move[1],top_destination_female_nat$move[1],top_destination_male_nat$move[1]), nat_top_dest_1_percent=c(top_destination_all_nat$perc[1],top_destination_female_nat$perc[1],top_destination_male_nat$perc[1]), nat_top_dest_2_name=c(top_destination_all_nat$ADMIN_NAME[2],top_destination_female_nat$ADMIN_NAME[2],top_destination_male_nat$ADMIN_NAME[2]), nat_top_dest_2_number=c(top_destination_all_nat$move[2],top_destination_female_nat$move[2],top_destination_male_nat$move[2]), nat_top_dest_2_percent=c(top_destination_all_nat$perc[2],top_destination_female_nat$perc[2],top_destination_male_nat$perc[2]), nat_top_dest_3_name=c(top_destination_all_nat$ADMIN_NAME[3],top_destination_female_nat$ADMIN_NAME[3],top_destination_male_nat$ADMIN_NAME[3]), nat_top_dest_3_number=c(top_destination_all_nat$move[3],top_destination_female_nat$move[3],top_destination_male_nat$move[3]), nat_top_dest_3_percent=c(top_destination_all_nat$perc[3],top_destination_female_nat$perc[3],top_destination_male_nat$perc[3]), nat_top_source_1_name=c(top_source_all_nat$ADMIN_NAME[1],top_source_female_nat$ADMIN_NAME[1],top_source_male_nat$ADMIN_NAME[1]), nat_top_source_1_number=c(top_source_all_nat$move[1],top_source_female_nat$move[1],top_source_male_nat$move[1]), nat_top_source_1_percent=c(top_source_all_nat$perc[1],top_source_female_nat$perc[1],top_source_male_nat$perc[1]), nat_top_source_2_name=c(top_source_all_nat$ADMIN_NAME[2],top_source_female_nat$ADMIN_NAME[2],top_source_male_nat$ADMIN_NAME[2]), nat_top_source_2_number=c(top_source_all_nat$move[2],top_source_female_nat$move[2],top_source_male_nat$move[2]), nat_top_source_2_percent=c(top_source_all_nat$perc[2],top_source_female_nat$perc[2],top_source_male_nat$perc[2]), nat_top_source_3_name=c(top_source_all_nat$ADMIN_NAME[3],top_source_female_nat$ADMIN_NAME[3],top_source_male_nat$ADMIN_NAME[3]), nat_top_source_3_number=c(top_source_all_nat$move[3],top_source_female_nat$move[3],top_source_male_nat$move[3]), nat_top_source_3_percent=c(top_source_all_nat$perc[3],top_source_female_nat$perc[3],top_source_male_nat$perc[3]) ) if(country_clicked=="AFG"){ clean_names=names(nat_fig) } df=df%>% bind_rows(nat_fig%>% select(clean_names)) print(country_clicked) } # copy to DB ##### copy_to(mig_db, df, name="nat_fig", temporary = FALSE, indexes = list("ISO","sex"), overwrite = T)
19ae717c54dc3e11b4a4aa7e421b0492a2d44e29
19b01a47e88f43766314a6e83c4bae13c2595ef9
/R/target.R
1bdfcee0bcdfaceafc1034354723a59ba5171cb3
[ "MIT" ]
permissive
iandennismiller/i0
1db805eaa0802e4f34adb42c99f8539686a52ad2
36183c6a5d7e4be4fc2552baeb114bd692e194b3
refs/heads/master
2016-09-06T05:44:39.901985
2013-10-28T17:37:38
2013-10-28T17:37:38
null
0
0
null
null
null
null
UTF-8
R
false
false
7,891
r
target.R
#' Create a target object. #' #' @param x input model function specification #' @return target object #' @keywords character #' @export target <- function(x, ...) UseMethod("target") ###### # generic handlers #' Print a zero-targeted model #' #' @param x a zero-targeted model #' @export print.target <- function(x, ...) { print(x$estimates) } #' Get mean and stderr information about a zero-targeted model #' #' @param object a zero-targeted model #' @export summary.target <- function(object, ...) { res = list(summary = summarize(object)) class(res) <- "summary.target" res } #' Print a zero-targeted summary #' #' @param x a zero-targeted summary object #' @export print.summary.target <- function(x, ...) { print(x$summary) } #' Plot a zero-targeted model +/- 1 standard deviation. #' #' @param x a zero-targeted model object #' @param raw boolean indicating whether to plot raw values; defaults to FALSE #' (i.e. print scaled rather than raw values) #' @export plot.target <- function(x, raw=F, ...) { display = summarize(x) if (raw) { display = transform_raw(display, x$family) } else { display$ymins = display$means - display$ci display$ymaxs = display$means + display$ci } ggplot(display, aes(x=dim2, y=means, group=dim1)) + geom_line(aes(linetype=dim1), size=1) + geom_point(size=3, fill="white") + scale_x_discrete(labels=c(paste("low", x$terms$d2_name), paste("high", x$terms$d2_name))) + scale_linetype(labels=c(paste("high", x$terms$d1_name), paste("low", x$terms$d1_name))) + coord_cartesian(xlim=c(0.8, 2.2)) + xlab(NULL)+ ylab(x$terms$dv_name) + theme_bw() + geom_errorbar(aes(ymin=ymins, ymax=ymaxs), alpha=0.3, width=.05) + labs(title = paste(x$terms$dv_name, " ~ '", x$terms$d1_name, "' and '", x$terms$d2_name, "'", sep="")) + theme(legend.title=element_blank()) + theme(legend.position=c(.2, .9)) + theme(legend.text = element_text(size = 12)) + theme(axis.text.x = element_text(size = 14)) + theme(axis.text.y = element_text(size = 14)) } ################# # private methods # Unpack an S3 formula to figure out the name of the DV and IVs # # @param formula model specification # @return target object unpack_formula <- function(formula) { terms = names(attr(terms(formula), "factors")[,1]) list( dv_name = terms[1], d1_name = terms[2], d2_name = terms[3] ) } # undocumented # transform_raw <- function(display, family) { if (family == "poisson") { b0 = display$means - display$ci display$ymins = exp(b0) b0 = display$means + display$ci display$ymaxs = exp(b0) b0 = display$means display$means = exp(b0) } else if (family == "binomial") { b0 = display$means - display$ci display$ymins = exp(b0) / (1 + exp(b0)) b0 = display$means + display$ci display$ymaxs = exp(b0) / (1 + exp(b0)) b0 = display$means display$means = exp(b0) / (1 + exp(b0)) } else { display$ymins = display$means - display$ci display$ymaxs = display$means + display$ci } display } # undocumented # summarize <- function(x, ...) { display = data.frame( dim1 = c('low', 'low', 'high', 'high'), dim2 = c('low', 'high', 'low', 'high'), means = c( x$estimates$low$low$mean, x$estimates$low$high$mean, x$estimates$high$low$mean, x$estimates$high$high$mean ), ci = c( x$estimates$low$low$stderr, x$estimates$low$high$stderr, x$estimates$high$low$stderr, x$estimates$high$high$stderr ) ) display$dim2 = factor(display$dim2, levels=c('low', 'high')) display } # undocumented # calc_zero_target <- function(terms, data) { # zt means "zero targeted" zt = data.frame( #ids = seq(from=1, to=dim(data)[1]), dv = data[[terms$dv_name]], d1_high = data[[terms$d1_name]] - sd(data[[terms$d1_name]], na.rm=T), d1_low = data[[terms$d1_name]] + sd(data[[terms$d1_name]], na.rm=T), d2_high = data[[terms$d2_name]] - sd(data[[terms$d2_name]], na.rm=T), d2_low = data[[terms$d2_name]] + sd(data[[terms$d2_name]], na.rm=T) ) data.frame(data, zt) } # undocumented # gen_formulas <- function(formula_str, terms) { f_low_low = str_replace_all(formula_str, terms$d1_name, "d1_low") f_low_low = str_replace_all(f_low_low, terms$d2_name, "d2_low") f_low_high = str_replace_all(formula_str, terms$d1_name, "d1_low") f_low_high = str_replace_all(f_low_high, terms$d2_name, "d2_high") f_high_low = str_replace_all(formula_str, terms$d1_name, "d1_high") f_high_low = str_replace_all(f_high_low, terms$d2_name, "d2_low") f_high_high = str_replace_all(formula_str, terms$d1_name, "d1_high") f_high_high = str_replace_all(f_high_high, terms$d2_name, "d2_high") list( low_low = as.formula(f_low_low), low_high = as.formula(f_low_high), high_low = as.formula(f_high_low), high_high = as.formula(f_high_high) ) } # undocumented # calc_estimates <- function(f, zt, mlm, family) { if (mlm) { fn = calc_lmer } else { fn = calc_lm } list( low_low = fn(f$low_low, zt, family), low_high = fn(f$low_high, zt, family), high_low = fn(f$high_low, zt, family), high_high = fn(f$high_high, zt, family) ) } # undocumented # unpack_estimates <- function(estimate) { list( low = list( low = list( mean = estimate[["low_low"]][["mean"]], stderr = estimate[["low_low"]][["stderr"]] ), high = list( mean = estimate[["low_high"]][["mean"]], stderr = estimate[["low_high"]][["stderr"]] ) ), high = list( low = list( mean = estimate[["high_low"]][["mean"]], stderr = estimate[["high_low"]][["stderr"]] ), high = list( mean = estimate[["high_high"]][["mean"]], stderr = estimate[["high_high"]][["stderr"]] ) ) ) } # undocumented # calc_lm <- function(spec, data, family) { model = glm(spec, data, na.action="na.exclude", family=family) list( model = model, mean = summary(model)$coefficients[1,1], stderr = summary(model)$coefficients[1,2] ) } # undocumented # calc_lmer <- function(spec, data, family) { model = lmer(spec, data, na.action="na.exclude", family=family) list( model = model, mean = attr(model, 'fixef')[[1]], stderr = attr(summary(model), "coefs")[[1,2]] ) } ################ # public methods #' Create a target object. #' #' @param x input model function specification #' y data frame #' @return target object #' @keywords character #' @export #' @examples #' data = data.frame(y = c(0, 1, 2), x1 = c(2, 4, 6), x2 = c(3, 6, 9)) #' t = target(y ~ x1 * x2, data=data) #' t$point target.formula <- function( formula, data=list(), family="gaussian", mlm=FALSE, ...) { terms = unpack_formula(formula) f_str = as.character(formula) formula_str = paste(f_str[2], f_str[1], f_str[3]) std_formulas = gen_formulas(formula_str, terms) zt = calc_zero_target(terms, data) models = calc_estimates(std_formulas, zt, mlm, family) obj = list( formula = formula, call = match.call(), terms = terms, zero_targeted = zt, models = models, family = family, estimates = unpack_estimates(models) ) class(obj) = "target" obj }
68a92eaf40de4273d90ed95aff0a45f152aa19f9
6fa24cca5ba1dc15f9f206beb97c260786efe732
/研討會_202307/script/old/8.1-glmm.R
953a197585f553160cbc98d088f3d7c122ab7686
[]
no_license
wetinhsu/Macaca-population-trend
fe14e5dfa6290b4a982175feae290053c60446b9
a0e738ec817ae70b8ea042eeb7b64df4c9b5cb10
refs/heads/master
2023-07-19T12:38:45.198058
2023-07-11T01:13:59
2023-07-11T01:13:59
190,343,813
0
0
null
2019-06-05T07:07:49
2019-06-05T07:07:49
null
UTF-8
R
false
false
3,174
r
8.1-glmm.R
library(tidyverse) library(readxl) library(writexl) library(here) here::here() site_list <- read_xlsx("./研討會_202307/data/refer/分層隨機取樣的樣區清單 _20221031.xlsx", sheet = "樣區表") %>% .[,7] %>% setNames(., "site_list") BBS_Monkey_1521_GLMM <- read.csv("./研討會_202307/data/clean/BBS_Monkey_1521_0214.csv") %>% reshape2::melt(id = "site", variable.name ="year", value.name = "count") %>% mutate(year = str_remove_all(year, "X")) Ch5_matrix_line_site <- read_xlsx("./研討會_202307/data/refer/Dali/Ch5_matrix_line_site.xlsx") M.data <- read_excel(here("./研討會_202307/data/clean/for analysis_1521_v2.xlsx"), sheet=1) %>% mutate_at(c("Year", "Survey", "Point", "Macaca_sur", "Month", "Day", "Altitude", "julian.D"), as.numeric) %>% filter(Site_N %in% site_list$`site_list`) %>% filter(!(Year %in% 2020 & Survey %in% 3)) %>% filter(analysis=="Y") %>% mutate(transect = paste0(Site_N, "-", Point)) #--------------------------------- Df <- M.data %>% select(-(Macaca_dist:analysis))%>% left_join(Ch5_matrix_line_site, by = c("transect" = "site")) %>% filter(! is.na(Shannon))%>% group_split(Year) %>% map(., function(x){ sample(1:nrow(x), size = nrow(x[x$Macaca_sur %in% 1,]), replace = F) %>% slice(x, .) %>% mutate(Macaca_sur = 0) }) %>% bind_rows() %>% bind_rows( M.data %>% select(-(Macaca_dist:analysis))%>% left_join(Ch5_matrix_line_site, by = c("transect" = "site")) %>% filter(! is.na(Shannon))%>% filter( Macaca_sur != 0) ) %>% select(transect,Site_N,Year, Macaca_sur, elevation,edge,P_forest,P_farmland,Shannon,edge_length) %>% mutate(Year = Year %>% as.numeric(.) %>% as.integer(.))%>% mutate_at(c("elevation","edge","P_forest", "P_farmland", "Shannon", "edge_length"),scale) %>% data.frame(.) #---------------------------------- library(car) vif(lm( Macaca_sur ~ Year+ elevation+ edge + P_forest + P_farmland + Shannon , Df)) #------------------------- library(ggcorrplot) corr <- Df %>% filter(!is.na(edge)) %>% select(Year,elevation,edge,P_forest,P_farmland,Shannon) %>% cor(.) %>% round(1) ggcorrplot(corr, # method = "circle", hc.order = TRUE, type = "lower", lab = TRUE) #數字為correlation coefficient #---------------------------------------------- library(glmmTMB) model2 <- glmmTMB( Macaca_sur ~ elevation+ edge + P_forest + P_farmland + Shannon + (1|Year)+(1|transect) , Df, family = binomial(link = "logit") ) summary(model2) write.csv(Df,"./研討會_202307/data/clean/Df_0222.csv", row.names = F) Df <- read.csv("./研討會_202307/data/clean/Df_0222.csv" )%>% mutate_at(c("elevation","edge","P_forest", "P_farmland", "Shannon", "edge_length"),scale) #-------------------- ggplot(Df, aes(x = P_farmland, y = Macaca_sur))+ geom_point(pch = 1)+ geom_smooth(method = "glm", method.args = list(family = "binomial"), se = F)
4817684a4cd60b24e91410f6bbca1bf3447d4ec2
add0e24035b41dcb36aefd0156519221f85e8750
/Simul_fun.r
f3490e538d97d1e9710f27c91f06d76a94e0f2bc
[]
no_license
lsaravia/LogisticStochastic
831f4b4fdf3092a34b10e3a31c2c2263750e3078
2f2e1d5fa2089eff9571e5a4f7014403c6c0ead6
refs/heads/master
2020-04-15T04:37:31.117855
2016-11-14T19:36:48
2016-11-14T19:36:48
73,739,724
0
0
null
null
null
null
UTF-8
R
false
false
2,004
r
Simul_fun.r
# Simulacion estocastica para modelo logistico # # Simulacion estocastica para modelo logistico # con fluctuación ambiental en r (1+a cos(w t)) # STO_logistic_ef <- function(x,pars,times) { # Setup an array to store results: time, N # ltimes <- length(times) output <- array(dim=c(ltimes,2),dimnames=list(NULL,names(x))) t <- x[1] stopifnot(t<=times[1]) # loop until either k > maxstep or # output[1,] <-x k <- 2 while (k <= ltimes) { while (t < times[k]) { x <- logistic_ef_onestep(x,pars) t <- x[1] } while (t >= times[k] && k <= ltimes) { output[k,] <- x k <- k+1 } } as.data.frame(output) } # Logistica con fluctuación ambiental en r - Simulacion de Eventos # logistic_ef_onestep<- function(x,pars){ p<-as.list(pars) # 2nd element is the population # N<-x[2] B<- p$r*(1+p$a*cos(p$omega*x[1])) # Birth rate if(B<0) B<-0 R<- B+p$s*N event_rate<- B/R if(N>0){ if(runif(1) <=event_rate ){ N<-N+1 } else { N<-N-1 } } # Exponential random number tau<-rexp(n=1,rate=R) c(x[1]+tau,N) } # Ecuación logistica determinista con fluctuaciones ambientales # logistic_ef_det<-function(t,State,Pars){ with(as.list(c(State, Pars)), { dP <- N*(r*(1+a *cos(omega*t))-s*N) return(list(c(dP))) }) } # Estimacion de parametros usando Aproximate Bayesian computation # # estima_ABC <- function(dat,p,time,dlim,sim=1000) { da <- data.frame(matrix(, nrow = time, ncol = 2)) names(da) <- c("r","s") j <-1 lendat<-length(dat) for(i in 1:sim){ # calcula parametros # r<- runif(1,p$r[1],p$r[2]) s <- runif(1,p$s[1],p$s[2]) nini <- round(r/s) # Corre el modelo out <- STO_simul(c(0,nini),c(r=r,s=s),1:time) # selecciona la ultima parte out <- out[(time-lendat+1):time,2] dis <- sum((dat-out)^2) if(dis <= dlim){ da[j,]<-c(r,s) j <- j + 1 } } return(na.omit(da)) }
e93b298fde37584159b521ebdf57c649d0642c1d
fb9259f3098f3e02aadbb12dcfa36e1e8f022623
/R/wtd_mwu.R
03a3fb373a23a33cc31616184df4446190f66df3
[]
no_license
strengejacke/sjstats
4786c05635f33a19211c1adaf801b664f093ce38
6f78eb27c779b2a833452ec20baa017042d274a0
refs/heads/master
2023-03-15T19:25:15.651996
2022-11-19T20:13:55
2022-11-19T20:13:55
59,321,248
186
21
null
2023-03-08T16:25:18
2016-05-20T19:33:23
R
UTF-8
R
false
false
1,675
r
wtd_mwu.R
#' @rdname weighted_sd #' @export weighted_mannwhitney <- function(data, ...) { UseMethod("weighted_mannwhitney") } #' @importFrom dplyr select #' @rdname weighted_sd #' @export weighted_mannwhitney.default <- function(data, x, grp, weights, ...) { x.name <- deparse(substitute(x)) g.name <- deparse(substitute(grp)) w.name <- deparse(substitute(weights)) # create string with variable names vars <- c(x.name, g.name, w.name) # get data dat <- suppressMessages(dplyr::select(data, !! vars)) dat <- na.omit(dat) weighted_mannwhitney_helper(dat) } #' @importFrom dplyr select #' @rdname weighted_sd #' @export weighted_mannwhitney.formula <- function(formula, data, ...) { vars <- all.vars(formula) # get data dat <- suppressMessages(dplyr::select(data, !! vars)) dat <- na.omit(dat) weighted_mannwhitney_helper(dat) } weighted_mannwhitney_helper <- function(dat, vars) { # check if pkg survey is available if (!requireNamespace("survey", quietly = TRUE)) { stop("Package `survey` needed to for this function to work. Please install it.", call. = FALSE) } x.name <- colnames(dat)[1] group.name <- colnames(dat)[2] colnames(dat) <- c("x", "g", "w") if (dplyr::n_distinct(dat$g, na.rm = TRUE) > 2) { m <- "Weighted Kruskal-Wallis test" method <- "KruskalWallis" } else { m <- "Weighted Mann-Whitney-U test" method <- "wilcoxon" } design <- survey::svydesign(ids = ~0, data = dat, weights = ~w) mw <- survey::svyranktest(formula = x ~ g, design, test = method) attr(mw, "x.name") <- x.name attr(mw, "group.name") <- group.name class(mw) <- c("sj_wmwu", "list") mw$method <- m mw }
0bf7bccd59becbac484a54bd848e55f41a8bc58f
3038b772a273a2be8aca317104ceaa12ed7c76ec
/code/Data_CleanPrep.R
6e14058e2523b57a8222c5a9cd8b8bd7c4028465
[]
no_license
ArmanMadani/Stat-133-Project
54a7f6ecbb7b4ddf12e63646cf5e12361212e036
7bc245ed9996f4b7f9fe7453e12cdaff4785e3a1
refs/heads/master
2016-09-01T10:43:01.452617
2015-12-14T01:22:13
2015-12-14T01:22:13
47,475,530
0
0
null
null
null
null
UTF-8
R
false
false
6,192
r
Data_CleanPrep.R
# Data Cleaning and Preparation from .html files to .csv files library(XML) # Data Cleaning for Champions.html nba_champions <- readHTMLTable('rawdata/champions.html') nba_champions <- as.data.frame(nba_champions[[2]]) nba_champions[] <- lapply(nba_champions, as.character) colnames(nba_champions) <- c('Year', 'Champion', 'Score', 'Opponent') nba_champions <- nba_champions[-1, ] write.csv(nba_champions, 'data/champions.csv') # Getting the statistics for the champions champion_stats <- c() nba_champions$Champion[nba_champions$Year==1995] for (i in 1:21) { file.path <- paste0('data/leagues_NBA_', 1994 + i, '_team.csv') files <- read.csv(file.path) champion_stats[[i]] <- files[c("Team", "FGA", "FGP", "X3PA", "X3PP", "years")] } for (i in 1:21){ years <- 1994 + i champion <- nba_champions$Champion[nba_champions$Year==years] year_data <- champion_stats[[i]] year_data$Team <- gsub('\\*', '', as.character(year_data$Team)) champion_stats[[i]] <- year_data[year_data$Team == champion | year_data$Team == "Average", ] } all_champs <- do.call(rbind, champion_stats) all_champs <- all_champs[-seq(from = 2, to = nrow(all_champs), by = 2L), ] write.csv(all_champs, file = "data/champ_data.csv") # Drafted Players' Heights to_inches <- function(height) { h <- strsplit(as.character(height), "[^0-9]") h <- grep("[0-9]", h[[1]], value = TRUE) ft <- as.numeric(h[1]) inch <- as.numeric(h[2]) return(ft * 12 + inch) } players <- readHTMLTable('rawdata/player_heights1995.html') players <- as.data.frame(players[[9]]) players["Height"] <- unlist(lapply(players["Height"][[1]], to_inches)) players["Year"] = 1995 players["Average_Height"] = mean(players$Height, na.rm = TRUE) players["Average_Weight"] = mean(as.numeric(levels(players$Weight)), na.rm = TRUE) players <- players[c("Name", "Height", "Weight", "Average_Height", "Average_Weight", "Year")] for (i in 1996:2015) { p <- readHTMLTable(paste0('rawdata/player_heights', i, '.html')) p <- as.data.frame(p[[9]]) p["Height"] <- unlist(lapply(p["Height"][[1]], to_inches)) p["Year"] = i p["Average_Height"] = mean(p$Height, na.rm = TRUE) p["Average_Weight"] = mean(as.numeric(levels(p$Weight)), na.rm = TRUE) p <- p[c("Name", "Height", "Weight", "Average_Height", "Average_Weight", "Year")] players <- rbind(players, p) } write.csv(players, file = "data/players.csv") # Cleaning data for champion rosters champ <- readHTMLTable('rawdata/champion_stats1995.html') champ <- as.data.frame(champ[[1]]) champ["Ht"] <- unlist(lapply(champ["Ht"][[1]], to_inches)) champ["Year"] = 1995 champ["Average_Height"] = mean(champ$Ht, na.rm = TRUE) champ["Average_Weight"] = mean(as.numeric(levels(champ$Wt)), na.rm = TRUE) champ <- champ[c("Player", "Pos", "Ht", "Wt", "Average_Height", "Average_Weight", "Year")] for (i in 1996:2015) { ch <- readHTMLTable(paste0('rawdata/champion_stats', i, '.html')) ch <- as.data.frame(ch[[1]]) ch["Ht"] <- unlist(lapply(ch["Ht"][[1]], to_inches)) ch["Year"] = i ch["Average_Height"] = mean(ch$Ht, na.rm = TRUE) ch["Average_Weight"] = mean(as.numeric(levels(ch$Wt)), na.rm = TRUE) ch <- ch[c("Player", "Pos", "Ht", "Wt", "Average_Height", "Average_Weight", "Year")] champ <- rbind(champ, ch) } write.csv(champ, file = "data/roster.csv") # Case Study Player: Stephen Curry steph_curry <- readHTMLTable('rawdata/steph_curry.html') steph_curry <- as.data.frame(steph_curry[[11]]) steph_curry["Height w/o Shoes"] <- unlist(lapply(steph_curry["Height w/o Shoes"], to_inches)) steph_curry["Height w/shoes"] <- unlist(lapply(steph_curry["Height w/shoes"], to_inches)) steph_curry["Wingspan"] <- unlist(lapply(steph_curry["Wingspan"], to_inches)) steph_curry["Standing Reach"] <- unlist(lapply(steph_curry["Standing Reach"], to_inches)) write.csv(steph_curry, 'data/steph_curry.csv') steph_curry_stats <- readHTMLTable('rawdata/steph_curry_career.html') steph_curry_stats <- steph_curry_stats$per_game write.csv(steph_curry_stats, 'data/steph_curry_stats.csv') # Case Study Player: Draymond Green draymond_green <- readHTMLTable('rawdata/draymond_green.html') draymond_green <- as.data.frame(draymond_green[[11]]) draymond_green["Height w/o Shoes"] <- unlist(lapply(draymond_green["Height w/o Shoes"], to_inches)) draymond_green["Height w/shoes"] <- unlist(lapply(draymond_green["Height w/shoes"], to_inches)) draymond_green["Wingspan"] <- unlist(lapply(draymond_green["Wingspan"], to_inches)) draymond_green["Standing Reach"] <- unlist(lapply(draymond_green["Standing Reach"], to_inches)) write.csv(draymond_green, 'data/draymond_green.csv') draymond_green_stats <- readHTMLTable('rawdata/draymond_green.html') draymond_green_stats <- as.data.frame(draymond_green_stats[[12]]) write.csv(draymond_green_stats, 'data/draymond_green_stats.csv') # Case Study Player: Tim Duncan tim_duncan <- readHTMLTable('rawdata/tim_duncan.html') tim_duncan <- as.data.frame(tim_duncan[[11]]) tim_duncan["Height w/o Shoes"] <- unlist(lapply(tim_duncan["Height w/o Shoes"], to_inches)) tim_duncan["Height w/shoes"] <- unlist(lapply(tim_duncan["Height w/shoes"], to_inches)) tim_duncan["Wingspan"] <- unlist(lapply(tim_duncan["Wingspan"], to_inches)) tim_duncan["Standing Reach"] <- unlist(lapply(tim_duncan["Standing Reach"], to_inches)) write.csv(tim_duncan, 'data/tim_duncan.csv') tim_duncan_stats <- readHTMLTable('rawdata/tim_duncan.html') tim_duncan_stats <- as.data.frame(tim_duncan_stats[[12]]) write.csv(tim_duncan_stats, 'data/tim_duncan_stats.csv') # Case Study Player: Shaq shaq <- readHTMLTable('rawdata/shaq.html') shaq <- as.data.frame(shaq[[11]]) shaq["Height w/o Shoes"] <- unlist(lapply(shaq["Height w/o Shoes"], to_inches)) shaq["Height w/shoes"] <- unlist(lapply(shaq["Height w/shoes"], to_inches)) shaq["Wingspan"] <- unlist(lapply(shaq["Wingspan"], to_inches)) shaq["Standing Reach"] <- unlist(lapply(shaq["Standing Reach"], to_inches)) write.csv(shaq, 'data/shaq.csv') shaq_stats <- readHTMLTable('rawdata/shaq.html') shaq_stats <- as.data.frame(shaq_stats[[12]]) write.csv(shaq_stats, 'data/shaq_stats.csv')
7fb982e1c16c249433f83529ad9ea9d468fbb7f3
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/Rfssa/examples/ftsplot.Rd.R
c33ff1408bfd99086374aac459a5ddd52cecc26e
[]
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
679
r
ftsplot.Rd.R
library(Rfssa) ### Name: ftsplot ### Title: Functional Time Series Plots ### Aliases: ftsplot ### ** Examples data("Callcenter") library(fda) D <- matrix(sqrt(Callcenter$calls),nrow = 240) N <- ncol(D) time <- 1:30 K <- nrow(D) u <- seq(0,K,length.out =K) d <- 22 #Optimal Number of basises basis <- create.bspline.basis(c(min(u),max(u)),d) Ysmooth <- smooth.basis(u,D,basis) Y <- Ysmooth$fd par(mar=c(2,1,2,2),mfrow=c(1,3)) ftsplot(u,time,Y[1:30],space = 0.4,type=1,ylab = "",xlab = "Day",main = "Typ1=1") ftsplot(u,time,Y[1:30],space = 0.4,type=2,ylab = "",xlab = "Day",main = "Typ1=2") ftsplot(u,time,Y[1:30],space = 0.4,type=3,ylab = "",xlab = "Day",main = "Typ1=3")
5cc7ddbb67ed7455ee2fcac0ade66864132983fd
4420e96700b4f0f4d4b005d8afb46f07277393f4
/sread2.R
9716fe1edc8eacf03b7f59a568dab9cb7661aa80
[]
no_license
k2hrt/theo1
0df2a6dfcf4c3788d9eb9289f09514fbebfd17a1
dbf52c47d8dfb9e4f23eee1b4479390687433e64
refs/heads/master
2022-11-13T11:14:58.192956
2020-07-11T00:02:38
2020-07-11T00:02:38
276,737,195
2
0
null
null
null
null
UTF-8
R
false
false
780
r
sread2.R
sread2<-function(x,r,tau0=1) { # Get size of phase data array N=length(x) # Get # data frame rows n=nrow(r) # Allocate # analysis points array num<-1:n # Fill # analysis points array # ith row of tau column is r[i,1] for(i in 1:n){ af=(r[i,1]/0.75)/tau0 num[i]=((N-af)/2)*af } # Create output data frame # This is Stable32 Theo1 Read format # DF column not included # Add num column to data frame r<-cbind(r,num) # Re-arrange data frame columns # Now: tau,l,t,u,num # Want: tau,num,t,l,u r<-r[c(1,5,3,2,4)] # Write output to file # Note: Filename is hard-coded write.table(r, "C:\\Data\\sigma.tau", row.names=F, col.names=F) # Return output data frame invisible(r) }
6b7f86bd8c2e06411b19ae5c20b878746c86992d
ba1edf30bca6e023562e4aed21c0ca009d22f431
/db/man/dbfile.insert.Rd
943f28b9c98c6043d1a812e8cbb9e8653fe32101
[ "NCSA", "LicenseRef-scancode-unknown-license-reference" ]
permissive
rgknox/pecan
79f080e77637dfb974ebb29313b5c63d9a53228e
5b608849dccb4f9c3a3fb8804e8f95d7bf1e4d4e
refs/heads/master
2020-12-27T20:38:35.429777
2014-05-06T13:42:52
2014-05-06T13:42:52
19,548,870
1
0
null
null
null
null
UTF-8
R
false
false
784
rd
dbfile.insert.Rd
\name{dbfile.insert} \alias{dbfile.insert} \title{Insert file into tables} \usage{ dbfile.insert(filename, type, id, con, hostname = fqdn()) } \arguments{ \item{filename}{the name of the file to be inserted} \item{con}{database connection object} \item{hostname}{the name of the host where the file is stored, this will default to the name of the current machine} \item{params}{database connection information} } \value{ data.frame with the id, filename and pathname of the file that is written } \description{ Function to insert a file into the dbfiles table } \details{ This will write into the dbfiles and machines the required data to store the file } \examples{ \dontrun{ dbfile.insert('somefile.txt', 'Input', 7, dbcon) } } \author{ Rob Kooper }
17a0ee61723f79ed67a1159bc4785b60fdbc1e58
77f228315f25d2d5d3101a3f954fc6b1364fee59
/R/weight.R
4bab1eaad382c4584ca0629c0be0170f78d078bd
[]
no_license
TobieSurette/gulf.data
5fbe678b64d10d9f50fed501d958c65f70d79fcf
7e9796e47c90645e399775dadb1344e7f51a13b0
refs/heads/master
2023-09-03T23:53:10.733496
2023-08-29T18:45:20
2023-08-29T18:45:20
253,640,181
2
1
null
2022-06-01T12:33:15
2020-04-06T23:36:23
R
UTF-8
R
false
false
11,211
r
weight.R
#' Individual or Catch Weight #' #' @description Returns an estimate of the weight of individual organisms for a specified length. #' Estimated weights of sample subsets can also be calculated. #' #' This function makes use of a set of allometric length-weight coefficients to #' estimate the weight of an organism given its length. The species must be #' specified and the sex may be specified for dimorphic species. #' #' If \code{year} is specified, then survey data is loaded and the length-weight #' coefficients are calculated directly. #' #' @param x A numerical vector of organism lengths, or alternatively, a frequency table or a #' data frame of length-frequencies as produced by \code{\link{freq}}. The presence #' of \sQuote{species}, \sQuote{sex} or \sQuote{year} fields in the data frame will #' be passed onto the corresponding function arguments. #' #' @param species Species code. #' #' @param sex Numerical code specifying sex. #' #' @param coefficients A two-element numerical vector specifying the \code{a} and \code{b} #' coefficients, respectively. The the \sQuote{a} coefficient is assumed #' to be on the log-10 scale and the units in grams. #' #' @param units Units of the weight vector to be returned. It may be either in grams #' (\code{units = "g"}) or kilograms (\code{units = "kg"}). #' #' @param year Survey years to use as data when calculating the length-weight coefficients. #' If left unspecified, a table of default values are used. #' #' @param ... Futher arguments. #' #' @param category A character string specifying a snow crab or crustacean category for syntax. #' #' @param by Character string(s) specifying the fields by which to group the estimated weights. #' #' @param probability Logical value specifying whether maturity values are to be filled in with #' probabilities when morphometric values are unavailable. In this case, the #' numbers returned may be non-integer values. #' #' @return Returns a numerical vector the same size as \code{length} containing the expected weight #' of an organism for a given length measurement. #' #' @examples #' # Weights for Atlantic cod: #' weight(0:100, species = 10) #' #' # Weights for female white hake: #' weight(0:100, species = 12, sex = 2) #' #' # Weights for female white hake based on 2010 September survey data: #' weight(0:100, species = 12, sex = 2, year = 2010) #' #' # Weights for white hake based on pooled sexes and data from 2010-2013 September surveys: #' weight(0:100, species = 12, sex = 2, year = 2010:2013) #' #' # Transform length-frequencies to weight-length: #' x <- read.gulf(year = 2014, species = 40, card = "len") #' #' # Simple example: #' f <- freq(x, scale = TRUE) # Pooled length-frequencies. #' weight(f, species = 40) #' #' # Length-frequencies by stratum and sex: #' f <- freq(x, scale = TRUE, by = c("species", "stratum", "sex")) #' weight(f) #' #' # Length-frequencies by stratum and sex, use RV 2014 length-eight coefficients: #' f <- freq(x, scale = TRUE, by = c("species", "stratum", "sex", "year")) #' weight(f) #' #' # Load 2010 snow crab data: #' x <- read.scsbio(year = 2012) #' #' # Calculate weight for each crab: #' weight(x) #' #' # Calculate weights by tow: #' weight(x, by = "tow.number") #' #' # Calculate total weights by day: #' weight(x, by = c("year", "month", "day"), category = c("TM", "TMM", "TMSC12", "TMSC345")) #' @export weight <- function(x, ...) UseMethod("weight") #' @describeIn weight Default weight function. #' @export weight.default <- function(x, species, sex, coefficients, units = "kg", ...){ # Parse 'units' argument: units <- match.arg(tolower(units), c("grams", "kg", "kilograms")) if (units == "kg") units <- "kilograms" # Parse 'species' argument: if (!("species" %in% tolower(names(x)))){ if (missing(species) & missing(coefficients)) stop("'species' or 'coefficients' must be specified.") if (!missing(species) & !is.data.frame(x)){ if (length(species) == 1) species <- rep(species, length(x)) if (length(species) != length(x)) stop("'x' and 'species' have incompatible lengths.") } } # Parse 'sex' argument: if (!missing(sex) & !is.data.frame(x)){ if (length(sex) == 1) sex <- rep(sex, length(x)) if (length(sex) != length(x)) stop("'x' and 'sex' have incompatible lengths.") } # Input 'x' is a table or named vector of length-frequencies: if (is.numeric(x) & is.table(x) | (is.null(nrow(x)) & !is.null(names(x)))){ # 'x' is a frequency vector: if (length(grep("^[0-9]+$", names(x))) == length(x)){ f <- x x <- as.numeric(names(f)) v <- f * weight(x, species, sex, coefficients, units, ...) names(v) <- names(f) return(v) } } # Input 'x' are length-frequencies in a data frame: if (is.data.frame(x)){ # Extract frequency matrix: fvars <- names(x)[grep("^[ 0-9]+$", names(x))] vars <- setdiff(names(x), fvars) temp <- x[vars] names(x) <- tolower(names(x)) # Check that frequency variables are numeric: if (length(fvars) > 0){ flag <- TRUE for (i in 1:length(fvars)) flag <- flag & is.numeric(x[, fvars[i]]) if (flag){ f <- x[fvars] if ("sex" %in% names(x)) sex <- as.vector(repvec(x$sex, ncol = length(fvars))) if ("species" %in% names(x)) species <- as.vector(repvec(x$species, ncol = length(fvars))) x <- repvec(as.numeric(fvars), nrow = nrow(x)) d <- dim(x) x <- as.vector(x) if (!("year" %in% names(list(...))) & ("year" %in% names(temp))){ v <- weight(x, species, sex, coefficients, units, year = unique(temp$year), ...) }else{ v <- weight(x, species, sex, coefficients, units, ...) } dim(v) <- d v <- f * v v <- cbind(temp, v) return(v) } } } # Loop over species: if (length(unique(species)) > 1){ species.list <- unique(species) v <- rep(NA, length(x)) for (i in 1:length(species.list)){ index <- species == species.list[i] if (missing(sex)){ v[index] <- weight.default(x[index], species = species[index], units = "g", ...) }else{ v[index] <- weight.default(x[index], species = species[index], sex = sex[index], units = "g", ...) } } }else{ # Fetch length-weight coefficients: if (!missing(coefficients)){ if (is.data.frame(coefficients)){ if (!all(c("a", "b") %in% names(coefficients))) stop("'a' and 'b' must be column names if the length-weight coefficients are specified as a data frame.") if (nrow(coefficients) == 1){ coefficients <- c(coefficients$a, coefficients$b) }else{ stop("'coefficients' must be a two-element numeric vector.") } } if (is.numeric(coefficients) & length(coefficients)){ beta <- data.frame(a = coefficients[1], b = coefficients[2]) }else{ stop("'coefficients' must be a two-element numeric vector.") } }else{ if (missing(sex)){ beta <- length.weight(units = "g", log10 = TRUE, species = unique(species), ...) }else{ by <- "sex" if ("year" %in% names(list(...))) by <- c("year", by) beta <- length.weight(units = "g", log10 = TRUE, species = unique(species), sex = unique(sex), by = by, ...) } } # Calculate weights: if (is.null(beta)) stop("Corresponding length-weight coefficients were not found.") if (nrow(beta) == 1){ v <- (10^beta$a) * exp(beta$b * log(x)) }else{ # Match entries to corresponding length-weight coefficients: res <- data.frame(x = x, species = species) if (!missing(sex)) res$sex <- sex index <- match(res[setdiff(names(res), "x")], beta) v <- (10^beta$a[index]) * exp(beta$b[index] * log(x)) } } # Convert weight to proper units: if (units == "kilograms") v <- v / 1000 return(v) } #' @describeIn weight Weight function for \code{scsbio} objects. #' @export weight.scsbio <- function(x, category, by, as.hard.shelled, units = "g", ...){ # Parse input arguments: units <- match.arg(tolower(units), c("g", "kg", "grams", "kilograms", "tons", "tonnes", "mt", "t")) if (units %in% c("tons", "tonnes", "mt")) units <- "t" if (units == "kilograms") units <- "kg" if (units == "grams") units <- "g" # Parse 'as.hard.shelled' argument: if (!missing(as.hard.shelled)){ if (!is.logical(as.hard.shelled)) stop("'as.hard.shelled' must be a logical value.") if (as.hard.shelled) x$shell.condition <- 3 }else{ as.hard.shelled <- FALSE } if (missing(category) & missing(by)){ # Initialize weight vector: w <- rep(0, dim(x)[1]) # New adult: w <- w + is.category(x, "TMMSC12", ...) * exp(-9.399 + 3.315 * log(x$carapace.width)) # New adolescent: w <- w + is.category(x, "TMISC12", ...) * exp(-10.154 + 3.453 * log(x$carapace.width)) # Intermediate adult: w <- w + is.category(x, "TMMSC345", ...) * exp(-8.230136 + 3.098 * log(x$carapace.width)) # Intermediate adolescent: w <- w + is.category(x, "TMISC345", ...) * exp(-7.512 + 2.899 * log(x$carapace.width)) # Immature females: w <- w + is.category(x, "TFI", ...) * exp(-7.275 + 2.804 * log(x$carapace.width)) # Mature females: w <- w + is.category(x, "TFM", ...) * exp(-7.162 + 2.816 * log(x$carapace.width)) }else{ # Define indicator vector of category membership: if (!is.null(category)){ n <- is.category(x, category = category, ...) + 1 - 1 n <- as.data.frame(n) names(n) <- category }else{ n <- matrix(rep(1, dim(x)[1])) dimnames(n) <- list(NULL, "n") n <- as.data.frame(n) } w <- n * repvec(weight(x, ...), ncol = dim(n)[2]) # Return indicator vector if 'by' is NULL: if (is.null(by)) return(w) # Sum within 'by' groupings: w <- stats::aggregate(w, by = x[by], sum, na.rm = TRUE) } # Weight unit conversion: if (units == "kg") w <- w / 1000 if (units == "t") w <- w / 1000000 return(w) } #' @describeIn weight Weight function for \code{scobs} objects. #' @export weight.scobs <- function(x, ...){ # Buffer variables: if (!("chela.height" %in% names(x))) x$chela.height <- x$chela.height.right if (!("gonad.colour" %in% names(x))) x$gonad.colour <- NA if (!("egg.colour" %in% names(x))) x$egg.colour <- NA if (!("eggs.remaining" %in% names(x))) x$eggs.remaining <- NA x$chela.height <- chela.height(x) w <- weight.scsbio(x, ...) return(w) }
e136e65f8ef97f811196ac9f60c23d3bd1b331df
9036de5c22b81a4c27adb2f25dcc4dbf0faec193
/rhdf5_api.R
60a8e46b0447716ef799d475dc4859728f20e019
[]
no_license
vjcitn/rhdf5_api
afc7f0bf9045fce142488738f4222e0ebf83bb6c
d62020382635ddd7d17b4c8b240242f7210e6958
refs/heads/master
2020-03-21T16:28:41.020471
2018-06-26T17:44:59
2018-06-26T17:44:59
138,772,319
0
0
null
2018-06-26T17:40:43
2018-06-26T17:40:42
null
UTF-8
R
false
false
3,198
r
rhdf5_api.R
#' Function to create a file on hdf server #' @param url character string with http server url #' @note \url{"http://170.223.248.164:7248"} #' @param domain character string with domain name to be created #' @return r http response object #' @export putDomain = function(url, domain){ require(httr) password = Sys.getenv("password") username = Sys.getenv("username") auth <- authenticate(username, password, type="basic") r = PUT(url=url, config=auth, add_headers(host=domain)) r } #' Function to create a dataset in a file with extensible dimensions #' @param url character string with http server url #' @note \url{"http://170.223.248.164:7248/datasets"} #' @param domain character string with domain name to be created #' @param type character string with dataset type like H5T_IEEE_F32LE #' @param shape integer array with initial dimensions of dataset #' @param maxdims integer array with maximum extent of each dimension or 0 for unlimited dimension #' @return r http response object #' @export postDataset = function(url, domain, type, shape, maxdims){ require(httr) password = Sys.getenv("password") username = Sys.getenv("username") auth <- authenticate(username, password, type="basic") args <- list(type=type, shape=shape, maxdims=maxdims) r = POST(url=url, body=args, config=auth, add_headers(host=domain), encode="json") r } #To grab UUID of dataset created : #r = GET(url="http://170.223.248.164:7248/datasets",add_headers(host=domain)) #content(r)$datasets #' Function to modify dataset shape #' @param url character string with http server url #' @note \url{"http://170.223.248.164:7248/datasets/dsetuuid/shape"} #' @param domain character string with domain name to be created #' @param newshape integer array with new dataset new dataset shape (works for a resizeable dataset) #' @return r http response object modifyShape = function(url, domain, newshape){ require(httr) password = Sys.getenv("password") username = Sys.getenv("username") auth <- authenticate(username, password, type="basic") args <- list(shape=newshape) # PUT shape to resize the dataset r = PUT(url=url, body=args, config=auth, add_headers(host=domain), encode="json") r } #' Function to insert values into dataset #' @param url character string with http server url #' @note \url{"http://170.223.248.164:7248/datasets/dsetuuid/value"} #' @param domain character string with domain name to be created #' @param value list with values to be inserted into dataset #' @param start (optional)integer/integer array with starting coordinate of selection to be updated #' @param stop (optional)integer/integer array with ending coordinate of selection to be updated #' @return r http response object putValue = function(url, domain, value, start, stop){ require(httr) password = Sys.getenv("password") username = Sys.getenv("username") auth <- authenticate(username, password, type="basic") # to update or add data to dataset, value must be a list if(missing(start)){ args <- list(value=value) } else{ args <- list(value=value, start=start, stop=stop) } r = PUT(url=url, body=args, config=auth, add_headers(host=domain), encode="json") r }
886b918211f848a97d17d3fc4d5a2a7f33d8f509
69adc2fa8e3765b7323021ea99f83231eda5d79d
/covid19.R
f822fc2c8ae77d250c2639bcd40180c5fa768f0c
[]
no_license
mathstudent97/COVID-19
246cc9a6213f2e6dd3da80e93043b0604e682b24
7e9d162ef75dad012a9c9bfc387bbf316dcdb76e
refs/heads/master
2022-11-08T19:31:26.568861
2020-06-30T20:34:37
2020-06-30T20:34:37
275,473,577
1
0
null
null
null
null
UTF-8
R
false
false
4,820
r
covid19.R
rm(list=ls()) # removes all variables stored previously library(Hmisc) # need this for 'describe' function covid19_dataset <- read.csv("C:/Users/maullonv/Downloads/datasets_494724_994000_COVID19_line_list_data (2).csv") ##################################### ### Short summary of the data set ### ##################################### describe(covid19_dataset) # from Hmisc packg # Shows some informative things regarding the dataset # i.e. 27 vars and total of 1085 observations, missing and distinct values, # max and min etc. # Notice the data set is messy # Example: The 'death' variable shows that there are 14 distinct values # opposed to 2 # The reason for this is b/c the entries either shows a '1', '0', or # date of the death # '0' if one didn't die; '1' if one died # So now, will proceed with cleaning up data as this is inconsistent and difficult to # work with ##################### ## Clean the Data ### ##################### # Cleaning the data ('death' column) covid19_dataset$death_dummy <- as.integer(covid19_dataset$death != 0) # Will create a new column called 'death_dummy' # IOW if the data/ entry within the death column is '0', then the person died # if it's not i.e. '1' then they died # using 'unique(...)', it shows the values are only '0', '1' # now the death col is clean # Now, can CALCULATE the DEATH RATE sum(covid19_dataset$death_dummy) / nrow(covid19_dataset) # data shows a death rate of about 5.8% ########### ### AGE ### ########### # According to research, it is more likely that # the person that dies from covid-19 is older than # a person that surivives covid-19 # Can we prove that this claim is correct using our data? # CLAIM: people who tested positive for covid and died, are older # than those who tested positive and survived dead = subset(covid19_dataset, death_dummy == 1) alive = subset(covid19_dataset, death_dummy == 0) # So we have: 63 covid deaths and 1022 covid survivors # Now will calculate the mean age of both groups (those dead and alive) mean(dead$age, na.rm = TRUE) mean(alive$age, na.rm = TRUE) # The initial output is 'NA', indicating missing values # Looking at the data, there are some entries that appear as 'NA' # The reason behind Rs output as 'NA', indicates R does not # know how to interpret such missing values # So, will include 'na.rm = TRUE' into the code # This will just ignore all those values that appear as 'NA' # So now, the output shows: # The average age of one with covid and DIED is 68-69 years old # The average age of one with covid and SURVIVED is 48 years old # There is a 20 year gap between the mean ages # But is this statistically significant? # Will now use the t-test to check t.test(alive$age, dead$age, aleternative="two.sided", conf.level = 0.95) # Shows there is a 95% chance that the difference between a person # who is alive and dead in age is from 24 yrs to 16-17 (this is the conf int) # So an average, a person who is alive is much much younger # Try with 99% t.test(alive$age, dead$age, aleternative="two.sided", conf.level = 0.99) # Got around the same values # Now, look at the p-value: 2.2e-16 # This is the probability that from the sample we randomly # got such an extreme result, so this is basically 0 # So there is a 0% chance that the ages of the 2 populations # (dead and alive) are the same (reject null) # RECALL: normaly, if p-value is < 0.05, we reject null # hypothesis # CONCLUDE:our result IS STATISTICALLY SIGNIFICANT! # So, the people who die from Covid-19 are indeed # older than the people who survive covid-19 ############## ### Gender ### ############## # Question: Are women more likely to die due to Covid compared # to men? Or is it vice-versa? # Claim/ Hypothesis: Gender has no effect # Similar to testing the claim regarding age and Covid # Will make two subsets women = subset(covid19_dataset, gender == "female") men = subset(covid19_dataset, gender == "male") # Shows there are 520 males and 382 females mean(women$death_dummy, na.rm = TRUE) # Shows women have a covid death rate of 3.7% mean(men$death_dummy, na.rm = TRUE) # Shows men have a covid death rate of 8.5% # This is a pretty LARGE discrepancy # Is this STATISTICALLY SIGNIFICANT? t.test(women$death_dummy, men$death_dummy, aleternative="two.sided", conf.level = 0.99) # See that the means are the same # and that with 99% confidence, men have from .78% to 8.8% # higher fatality rates than woman # With p-value: 0.002105 < 0.05 so reject null # And thus IS SIGNIFICANT # Therefore mens higher death rate represents the population # and thus, gender does have an effect
f384e8b127a8ab422b7ce1a9bc19307e3da3ef70
3458aa7285e020e9e47fcf7b69600c807ead81bd
/setup_data.R
2b02980dd1775763e29ac2b50f622b5f21345712
[]
no_license
luoq/asap-sas
04037980cb570f8fd942943b05ef762bf3c82ef8
24035950792746fc9a29c8c2f9b472d0f552c6af
refs/heads/master
2021-01-10T19:59:42.197864
2012-11-18T02:27:30
2012-11-18T02:27:30
null
0
0
null
null
null
null
UTF-8
R
false
false
1,070
r
setup_data.R
require(tm) require(parallel) train_set <- read.delim("../data/train_rel_2.tsv",stringsAsFactors=FALSE) public_test_set <- read.delim("../data/public_leaderboard_rel_2.tsv",stringsAsFactors=FALSE) numberOfEssaySet <- 10 Set=vector(mode="list",length=numberOfEssaySet) Set <- mclapply(1:numberOfEssaySet,function(k){ within(list(),{ essay_set <- k id <- with(train_set,Id[EssaySet==k]) corpus <- Corpus(VectorSource(with(train_set,EssayText[EssaySet==k]))) corpus.public <- Corpus(VectorSource(with(public_test_set,EssayText[EssaySet==k]))) id.public <- with(public_test_set,Id[EssaySet==k]) y <- with(train_set,Score1[EssaySet==k]) # simple_feature <- extract.simpleFeatrure(corpus) # simple_feature.public <- extract.simpleFeatrure(corpus.public) dtm <- as.Matrix(get_dtm(corpus,ngram=3,minDoc=floor(0.005*length(y)),maxDoc=floor(0.80*length(y)))) terms <- colnames(dtm) ngram <- sapply(terms,wordNumber) dtm.public <- as.Matrix(get_dtm(corpus.public,dictionary=terms,ngram=3)) }) }) save(Set,file="data.RData")
3398fe185f21c01b1d7602eabcbe16890a236053
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/spatstat/examples/transect.im.Rd.R
ada361ee2861e8d9492d1d43da6daac5dc8b6e98
[]
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
317
r
transect.im.Rd.R
library(spatstat) ### Name: transect.im ### Title: Pixel Values Along a Transect ### Aliases: transect.im ### Keywords: spatial manip iplot ### ** Examples Z <- density(redwood) plot(transect.im(Z)) ## Not run: ##D if(FALSE) { ##D plot(transect.im(Z, click=TRUE)) ##D } ##D ## End(Not run)
1d2a9637a41917c21f3cd79a1b93f9c6bea2b169
f89c21bd47eaa88e29bef9bc3474d887486ecbc3
/plot1.R
1be6a032cba410ec9907713702f85aaadfd5ae31
[]
no_license
davidmede/ExData_Plotting1
ba2ffdf0f729355aa1e0608388a36ce18f3576e5
d4bd705015c309ca6159faf20c779162793f06be
refs/heads/master
2022-10-17T04:31:26.198173
2020-06-19T16:52:30
2020-06-19T16:52:30
273,086,053
0
0
null
2020-06-19T14:57:54
2020-06-17T21:56:46
R
UTF-8
R
false
false
681
r
plot1.R
dataset<-read.table("household_power_consumption.txt",header = TRUE,sep = ";",na.strings = "?") str(dataset) library(dplyr) library(tidyr) date_filter<-c("1/2/2007", "2/2/2007") dataset_filter<-filter(dataset, Date %in% date_filter) data_united<-unite(dataset_filter,col = "date_time", Date:Time,sep = "-") data_united$date_time<-gsub("(/|:)","-",data_united$date_time) library(lubridate) Sys.setlocale("LC_TIME", "English") data_united$date_time<-dmy_hms(data_united$date_time) png("plot1.png", height=480,width = 480) with(data_united,hist(Global_active_power,col="red", main = "Global Active Power", xlab = "Global Active Power (Killowatts)")) dev.off()
fb32681cf872aedafa95e6447969585209289c5e
f7b618d50b3f7777f7cdc8b55cdf4d9b08839262
/Lab2.R
937b88fec189e20cdb8925000712f4faf9fa33fa
[ "MIT" ]
permissive
5x/TweetsDataAnalytics
d717b9643aba54a3ca821cd7a66129c8d3ad2094
73b39be9c6af270bfe2b5782be827a892370e05c
refs/heads/master
2020-07-11T21:51:17.018529
2019-08-27T08:08:11
2019-08-27T08:08:11
204,651,081
0
0
null
null
null
null
UTF-8
R
false
false
9,310
r
Lab2.R
### --------------------------------------------------------------------------- ### Dependencies ### --------------------------------------------------------------------------- dependencies <- c( "twitteR", "ROAuth", "SnowballC", "data.table", "tm", "ggplot2", "graph", "topicmodels", "wordcloud", "Rgraphviz" ) dependency_loader <- function(dependencies) { for (index in 1:length(dependencies)) { dependency_package_name <- dependencies[index] if (!require(dependency_package_name, character.only = TRUE)) { install.packages(dependency_package_name, dependencies = TRUE) library(dependency_package_name) } } } dependency_loader(dependencies) ### --------------------------------------------------------------------------- ### Constants ### --------------------------------------------------------------------------- TWITTER_USER_NAME <- "nodejs" TWITTER_MAX_NUMBER_OF_TWEETS <- 3200 TWITTER_CONSUMER_KEY <- "__USE_U_TWITTER_CONSUMER_KEY__" TWITTER_CONSUMER_SECRET <- "__USE_U_TWITTER_CONSUMER_SECRET__" TWITTER_ACCESS_TOKEN <- "__USE_U_TWITTER_ACCESS_TOKEN__" TWITTER_ACCESS_SECRER <- "__USE_U_TWITTER_ACCESS_SECRER__" TWEETS_FILE_PATH <- paste("./", TWITTER_USER_NAME, ".rds", sep = "") WORKING_DIRECTORY <- getwd() # Codes: http://www.loc.gov/standards/iso639-2/php/code_list.php LANGUAGE_CODE <- "en" WORDS_TO_ANALISE <- c("app", "team") CUSTOM_STOP_WORDS <- c("can", "us") STOP_WORDS <- c(stopwords("english"), stopwords("russian"), CUSTOM_STOP_WORDS) HEAD_FIRST_TWEETS_COUNT <- 3 NUMBER_OF_TOP_WORDS <- 60 ASSIC_LOWER_CORRELATION_LIMITS = 0.2 FREQ_LOWER_BOUND <- 16 FREQ_MIN_VALUE <- 5 CLUSTERANALYSE_SPARSE_WEIGHT <- 0.95 CLUSTERANALYSE_CLUSTERS_NUMBER <- 5 TOPICMODEL_TOPIC_COUNT <- 10 POPICMODEL_TOPIC_TERMS_COUNT <- 5 ### --------------------------------------------------------------------------- ### Scraping ### ### @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline ### @see http://geoffjentry.hexdump.org/twitteR.pdf ### --------------------------------------------------------------------------- # Make an API Calls to the Twitter, only one time. After tweets saves on file, # and used from the local store. if (!file.exists(TWEETS_FILE_PATH)) { # Authorize a Twitter resource by OAuth protocol. setup_twitter_oauth( TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_SECRER) # Scraping tweets. tweets <- userTimeline(TWITTER_USER_NAME, n = TWITTER_MAX_NUMBER_OF_TWEETS) # Save tweets to *.rds file. saveRDS(tweets, file = TWEETS_FILE_PATH) } ### --------------------------------------------------------------------------- ### Loading from local store ### --------------------------------------------------------------------------- # Check for existing file with tweets. if (!file.exists(TWEETS_FILE_PATH)) { stop(paste("File doesn`t exist in work directory!\n", "File path[", TWEETS_FILE_PATH, "],\n", "Working directory path [", WORKING_DIRECTORY, "].")) } # Load tweets from local file store. tweets <- readRDS(TWEETS_FILE_PATH) # Getting real numbers of tweets loaded to memory. tweets.length <- length(tweets) print(paste("Number of downloaded tweets: ", tweets.length)) # Show example of tweets to standard out. print(paste("Fist ", HEAD_FIRST_TWEETS_COUNT, "tweets:")) for (index in 1:HEAD_FIRST_TWEETS_COUNT) { cat(paste("[Tweet#", index, "] ", tweets[[index]]$text, "\n", sep = "")) } # Convert TwitteR Lists To Data.Frames tweets.data_frame <- twListToDF(tweets) ### --------------------------------------------------------------------------- ### Text Cleaning ### --------------------------------------------------------------------------- # Build a corpus, and specify the source. # A vector source interprets each element of the vector as a document. # https://cran.r-project.org/web/packages/tm/tm.pdf#52 documents <- Corpus(VectorSource(tweets.data_frame$text)) # Remove unsupported encode chars(broken UTF-pairs, etc). documents <- tm_map(documents, function (x) { x <- gsub("\n", "", x) return(iconv(x, 'UTF-8', 'UTF-8', sub = "")) }) # Transform characters to lowercase. documents <- tm_map(documents, content_transformer(tolower)) # Remove punctuation symbols. documents <- tm_map(documents, removePunctuation) # Remove numeric values. documents <- tm_map(documents, removeNumbers) # Remove URLs links. # @see: http://www.rdatamining.com/books/rdm/faq/removeurlsfromtext removeURL <- function(x) gsub("http[^[:space:]]*", "", x) documents <- tm_map(documents, content_transformer(removeURL)) # Remove stopwords. documents <- tm_map(documents, removeWords, STOP_WORDS) # Stem words in a text document using Porter's stemming algorithm. documents <- tm_map(documents, function(x) { return(stemDocument(x, language = LANGUAGE_CODE)) }) # Show the first N documents (tweets) print(paste("Example of tweets after text cleaning: ", HEAD_FIRST_TWEETS_COUNT)) for (index in 1:HEAD_FIRST_TWEETS_COUNT) { cat(paste("[Tweet#", index, "] ", documents[[index]], "\n", sep = "")) } ### --------------------------------------------------------------------------- ### Freq&Assoc Analise. ### --------------------------------------------------------------------------- # Constructs coerces to a term-document matrix. termDocMatrix <- TermDocumentMatrix(documents, control = list(wordLengths = c(1, Inf), tolower = FALSE)) # Show term-document matrix. print(termDocMatrix) # Association with selected words(terms). associatedWeights <- findAssocs(termDocMatrix, terms = WORDS_TO_ANALISE, corlimit = ASSIC_LOWER_CORRELATION_LIMITS) # Show association weights. print(associatedWeights) # Creating Term/Freq data frame. freq.terms <- findFreqTerms(termDocMatrix, lowfreq = FREQ_LOWER_BOUND) term.freq <- rowSums(as.matrix(termDocMatrix)) term.freq <- subset(term.freq, term.freq >= FREQ_MIN_VALUE) termFreqDataFrame <- data.frame(term = names(term.freq), freq = term.freq) # Sort Term/Freq data frame by freq. termFreqDataFrame <- termFreqDataFrame[order(-termFreqDataFrame$freq),] topTerm <- head(termFreqDataFrame, NUMBER_OF_TOP_WORDS) # Build plot with top freq words. ggplot(topTerm, aes(x = reorder(term, -freq), y = freq)) + geom_bar(stat = "identity", fill = "orange") + xlab("Terms") + ylab("Count") + ggtitle("Histogram: Most freq words in tweets") + coord_flip() ### --------------------------------------------------------------------------- ### Word cloud. ### --------------------------------------------------------------------------- # Calculate the frequency of words and sort it by frequency. word.freq <- sort(rowSums(as.matrix(termDocMatrix)), decreasing = TRUE) # Build WordCloud plot. wordcloud( words = names(word.freq), freq = word.freq, min.freq = FREQ_MIN_VALUE, random.order = FALSE) ### --------------------------------------------------------------------------- ### Clustering. ### --------------------------------------------------------------------------- # Remove sparse terms. clearedTermDocMatrix <- removeSparseTerms( termDocMatrix, sparse = CLUSTERANALYSE_SPARSE_WEIGHT) # Transform to matrix. termMatrix <- as.matrix(clearedTermDocMatrix) # Cluster terms. distMatrix <- dist(scale(termMatrix)) # Hierarchical cluster analysis on a set of dissimilarities and methods # for analyzing it. # @see: http://stat.ethz.ch/R-manual/R-devel/library/stats/html/hclust.html hCluster <- hclust(distMatrix, method = "ward.D") # Build cluster dendrogram. plot(hCluster) rect.hclust( hCluster, k = CLUSTERANALYSE_CLUSTERS_NUMBER, border = 1:CLUSTERANALYSE_CLUSTERS_NUMBER) # Perform k-means clustering on a data matrix. kmeansResult <- kmeans(t(termMatrix), CLUSTERANALYSE_CLUSTERS_NUMBER) # Round cluster matrix centers, and show it to standart out. round(kmeansResult$centers, digits = 4) ### --------------------------------------------------------------------------- ### Topic model ### --------------------------------------------------------------------------- # Constructs document-term matrix. docTermMatrix <- as.DocumentTermMatrix(termDocMatrix) # Latent Dirichlet allocation by N-topics. lda <- LDA(docTermMatrix, k = TOPICMODEL_TOPIC_COUNT) # Buid terms by every topic. term <- terms(lda, POPICMODEL_TOPIC_TERMS_COUNT) term <- apply(term, 2, paste, collapse = ", ") # Show terms by evry topic. print(term) # Named topic list. topic <- topics(lda, 1) # Create data frame: Created date / Topic. topics <- data.frame(date = as.IDate(tweets.data_frame$created), topic) # Build topic model plot. Usage term on timeline. qplot( date, ..count.., data = topics, geom = "density", main = "Timeline usage a terms(words) on the tweets", fill = term[topic])
495c4c1e36388a188adf9e0dc7ba5c7e534f423e
00071d2723782db228a267a287a9cd314ca12dec
/code/supp_crossover_duration/crossdur_res.R
b0da3963d138f04b8f8372780b75d3d537feb790
[]
no_license
fintzij/ve_placebo_crossover
d12cbb8914256572a2ec8ed2f137074e42987266
deef82f6d9a3a1712ee132cf72b90b6f64aef368
refs/heads/main
2023-02-16T10:19:46.827837
2021-01-13T16:59:56
2021-01-13T16:59:56
325,616,572
0
0
null
null
null
null
UTF-8
R
false
false
7,158
r
crossdur_res.R
library(knitr) library(kableExtra) library(here) library(tidyverse) library(rsimsum) setwd(here("jon_stuff/cross_dur_2yr")) sim_settings <- expand.grid(ve = c("waning", "constant"), crossdur = c(2, 8)) pars <- expand.grid(ve = c("waning", "constant"), param = c("intcpt", "slope"), crossdur = c(2,8), model = c("linear", "pspline"), simulation = 1:1e4) ests <- expand.grid(ve = c("waning", "constant"), crossdur = c(2,8), time = c(0, 0.5, 1, 1.5, 2), model = c("const", "linear", "pspline"), simulation = 1:1e4) par_list <- vector("list", nrow(sim_settings)) ve_list <- vector("list", nrow(sim_settings)) decay_list <- vector("list", nrow(sim_settings)) t_cross_list <- vector("list", nrow(sim_settings)) n_cross_list <- vector("list", nrow(sim_settings)) for(s in seq_len(nrow(sim_settings))) { filename = paste0("cross_sim_", sim_settings$ve[s], "_", sim_settings$crossdur[s], ".Rds") sim_res = readRDS(filename) # get n_cross and t_cross n_cross_list[[s]] <- sapply(sim_res, "[[", "n_cross") t_cross_list[[s]] <- sapply(sim_res, "[[", "t_cross") # subset to only the times and models of interest ve_sub = do.call(rbind, lapply(sim_res, function(x) subset(x$VE_ests, time %in% c(0, 0.5, 1, 1.5, 2) & model %in% c("const", "linear", "pspline")))) decay_sub = do.call(rbind, lapply(sim_res, function(x) subset(x$VE_decays, time %in% c(0.5, 1, 1.5, 2) & model %in% c("const", "linear", "pspline")))) par_sub = do.call(rbind, lapply(sim_res, function(x) subset(x$par_ests, model %in% c("linear", "pspline")))) par_sub$param = c("intcpt", "slope") par_sub$simulation = as.numeric(par_sub$simulation) par_sub$truth = as.numeric(par_sub$truth) par_sub$est = as.numeric(par_sub$est) par_sub$var = as.numeric(par_sub$var) inds = which(ests$ve == sim_settings$ve[s] & ests$crossdur == sim_settings$crossdur[s]) par_inds = which(pars$ve == sim_settings$ve[s] & pars$crossdur == sim_settings$crossdur[s]) # merge ve_list[[s]] <- left_join(ests[inds,], ve_sub, by = c("time", "model", "simulation")) decay_list[[s]] <- left_join(ests[inds,], decay_sub, by = c("time", "model", "simulation")) par_list[[s]] <- left_join(pars[par_inds,], par_sub, by = c("param", "model", "simulation")) } # combine the results res_ve = do.call(rbind, ve_list) res_decay = do.call(rbind, decay_list) res_pars = do.call(rbind, par_list) # summarize crossover times and event counts cross_stats = data.frame( sim_settings, n_cross_mean = sapply(n_cross_list, mean, na.rm = T), n_cross_sd = sapply(n_cross_list, sd, na.rm = T), t_cross_mean = sapply(t_cross_list, mean, na.rm = T), t_cross_mean = sapply(t_cross_list, sd, na.rm = T) ) # summarize ve_sum = res_ve %>% group_by(ve, crossdur, time, model) %>% summarize(emp_var = var(est), covg = mean(truth > (est - 1.96 * sqrt(var)) & truth < (est + 1.96 * sqrt(var)))) decay_sum = res_decay %>% group_by(ve, crossdur, time, model) %>% summarize(emp_var = var(est), covg = mean(truth > (est - 1.96 * sqrt(var)) & truth < (est + 1.96 * sqrt(var)))) par_sum = res_pars %>% group_by(ve, crossdur, model, param) %>% summarize(emp_var = var(est), # sum((est - truth)^2) / (n()-1), covg = mean(truth > (est - 1.96 * sqrt(var)) & truth < (est + 1.96 * sqrt(var)))) # subset to get the true data generating mechanism and the pspline ve_sum = ve_sum %>% filter(model == "pspline" | model == "linear") %>% arrange(ve, crossdur, model, time) %>% ungroup() decay_sum = decay_sum %>% filter(model == "pspline" | model == "linear") %>% arrange(ve, crossdur, model, time) %>% ungroup() ve_sum = ve_sum[,c("ve", "crossdur", "model", "time", "emp_var", "covg")] decay_sum = decay_sum[,c("ve", "crossdur", "model", "time", "emp_var", "covg")] res_sum = full_join(ve_sum, decay_sum, c("ve", "crossdur", "model", "time")) # recode some of the variables res_sum = res_sum %>% mutate(model = case_when(model == "pspline" ~ "P-spline", TRUE ~ "log-linear"), crossdur = case_when(crossdur == 2 ~ "Two week crossover", crossdur == 8 ~ "Two month crossover")) par_sum = par_sum %>% mutate(model = case_when(model == "pspline" ~ "P-spline", TRUE ~ "log-linear"), crossdur = case_when(crossdur == 2 ~ "Two week crossover", crossdur == 8 ~ "Two month crossover"), param = case_when(param == "intcpt" ~ "Intercept", TRUE ~ "Linear trend")) res_sum[,5:8] = round(res_sum[,5:8], digits = 3) par_sum[,5:6] = round(par_sum[,5:6], digits = 3) # pivot par_sum wider par_sum = par_sum %>% pivot_wider(names_from = c("param"), values_from = c("emp_var", "covg")) par_sum = par_sum[,c(1:3,4,6,5,7)] # generate tables res_tab <- res_sum %>% arrange(desc(ve), desc(crossdur), model) %>% select(2:8) res_tab$crossdur[-seq(1,40,by=10)] = " " res_tab$model[-seq(1,40,by=5)] = " " res_tab %>% knitr::kable(format = "latex", booktabs = T) %>% kable_styling() %>% add_header_above(c(" " = 2, "$VE(t)$" = 2, "$\\Delta VE(t)$" = 2)) %>% pack_rows("Vaccine efficacy constant at 75%", 1, 20) %>% pack_rows("Vaccine efficacy wanes from 85% to 35% over 1.5 years", 21, 40) # par table partab <- par_sum %>% arrange(desc(ve), desc(crossdur)) %>% pivot_wider(names_from = c("param"), values_from = c("emp_var", "covg")) partab$crossdur[seq(2,8,by=2)] = " " partab[,c(3,4,6,5,7)] %>% knitr::kable(format = "latex", booktabs = T) %>% kable_styling() %>% add_header_above(c(" " = 1, "Intercept" = 2, "Linear Trend" = 2)) %>% pack_rows("Vaccine efficacy constant at 75%", 1, 4) %>% pack_rows("Vaccine efficacy wanes from 85% to 35% over 1.5 years", 5,8) %>% pack_rows("Two week crossover", 1, 2) %>% pack_rows("Two month crossover", 3, 4) %>% pack_rows("Two week crossover", 5, 6) %>% pack_rows("Two month crossover", 7, 8)
c6afd347aead3a326564816a7cfe256a6edd5b36
5e5235afb06284eec78be054f8c39ee1f9edbdac
/data-raw/friedman1.R
305d3cfc3b33d007dc3e5ee847c94e4e61195e9c
[]
no_license
enriquegit/ssr
c9a368263a4d5d7a7f5d1412c96e33676a3b97ff
bbf935ecac4486f303312e9cf56cea147d684c73
refs/heads/master
2020-07-04T04:22:45.855889
2019-09-05T12:14:10
2019-09-05T12:14:10
202,154,442
2
0
null
null
null
null
UTF-8
R
false
false
260
r
friedman1.R
# Script used to generate the friedman1 dataset using the tgp library. library(tgp) set.seed(1234) friedman1 <- friedman.1.data(n = 1000) friedman1 <- friedman1[,-11] friedman1 <- scale_zero_one(friedman1) usethis::use_data(friedman1, overwrite = TRUE)
5ade773042de856b862e90f309c48581b3eb90cd
992a8fd483f1b800f3ccac44692a3dd3cef1217c
/Rstudy/genomicsRange.R
1711c7913feb91348c46acf1966007c705f5b3ef
[]
no_license
xinshuaiqi/My_Scripts
c776444db3c1f083824edd7cc9a3fd732764b869
ff9d5e38d1c2a96d116e2026a88639df0f8298d2
refs/heads/master
2020-03-17T02:44:40.183425
2018-10-29T16:07:29
2018-10-29T16:07:29
133,203,411
3
1
null
null
null
null
UTF-8
R
false
false
5,130
r
genomicsRange.R
# Genomics Range data library(IRanges) rng <- IRanges(start=4, end=13) rng IRanges(start=4, width=3) IRanges(end=5, width=5) x <- IRanges(start=c(4, 7, 2, 20), end=c(13, 7, 5, 23)) names(x) <- letters[1:4] x class(x) # IRanges start(x) names(x) range(x) # the span of the ranges head(x) x[2:3]# subset x[start(x)<5] # # range operation # add or minus from both side x <- IRanges(start=c(40, 80), end=c(67, 114)) x + 4L x -10L # restrict on one side y <- IRanges(start=c(4, 6, 10, 12), width=13) restrict(y, 5, 10) # creates ranges width positions upstream of the ranges passed to it. flank(x, width=7) flank(x, width=7, start=FALSE) reduce(x) # all the covered region gap(x) # all the uncovered region intersect(a, b) setdff(a,b) setdff(b,a) union(b, a) # Pairwise version psetdiff(), pinter, sect(), punion(), and pgap(). findOverlaps(qry, sbj) distanceToNearest(qry, sbj) distance(qry, sbj) # Run length encoding x <- as.integer(c(4, 4, 4, 3, 3, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 4, 4, 4, 4, 4, 4, 4)) xrle <- Rle(x) xrle as.vector(xrle) # ==x summary(xrle) runLength(xrle) runValue(xrle) library(GenomicRanges) gr <- GRanges(seqname=c("chr1", "chr1", "chr2", "chr3"), ranges=IRanges(start=5:8, width=10), strand=c("+", "-", "-", "+")) gr ranges(gr) seqnames(gr) length(gr) names(gr)<-letters[1:length(gr)] gr # sequence data # fastQ # count seq number bioawk -cfastx 'END{print NR}' untreated1_chr4.fq Lowercase bases are often used to indicate soft masked repeats or low complexity sequences (by programs like RepeatMasker and Tandem Repeats Finder). Repeats and low-complexity sequences may also be hard masked, where nucleotides are replaced with N (or sometimes an X). Name ASCII character range Offset Quality score type Quality score range Sanger, Illumina (versions 1.8 onward) 33-126 33 PHRED 0-93 Solexa, early Illumina (before 1.3) 59-126 64 Solexa 5-62 Illumina (versions 1.3-1.7) 64-126 64 PHRED 0-62 # in python conver to 0 - 93 phred = [ord(b)-33 for b in qual] P = 10-Q/10 Q = -10 log10P [10**(-q/10) for q in phred] When working with sequencing data, you should always . Be aware of your sequencing technology's error distributions and limitations (e.g., whether it's affected by GC content) . Consider how this might impact your analyses seqtk is a general-purpose sequence toolkit written by Heng Li that contains a subcommand for trimming low-quality bases off the end of sequences # code sickle se -f untreated1_chr4.fq -t sanger -o untreated1_chr4_sickle.fq seqtk trimfq untreated1_chr4.fq > untreated1_chr4_trimfq.fq library(qrqc) readfq # by Heng Li # index samtools faidx Mus_musculus.GRCm38.75.dna.chromosome.8.fa # extract a specific region samtools faidx Mus_musculus.GRCm38.75.dna.chromosome.8.fa 8:123407082-123410744 ## SAM file head @SQ SN: seq names LN: seq length @RG read group SM: sample information PL: sequencing platform:PacBio, Illumina @PG mapping program VN: version CL: cmd used # view header samtools view -H celegans.bam # Alignment section Query seq names | Bitwise Flag | Ref seq name | Position | mapping quality | CIGAR | RNEXT/ PNEXT | Template length | SEQ | Quality # bitwise flag # true/false properties about an alignment samtools flags 147 0x93 147 PAIRED,PROPER_PAIR,REVERSE,READ2 # CIGAR flag # matches/mismatches, insertions, deletions, soft or hard clipped, and so on. # Soft clipping is when only part of the query sequence is aligned to the reference # hard-clipped regions are not present in the sequence stored in the SAM field SEQ. # mapping quality a mapping quality of 20 translates to a 10(20/-10) = 1% chance the alignment is incorrect. # sam to bam samtools view -b celegans.sam > celegans_copy.bam samtools view -h celegans.bam > celegans_copy.sam # Index ## sort samtools sort celegans_unsorted.bam celegans_sorted # more memory and more CPUs samtools sort -m 4G -@ 2 celegans_unsorted.bam celegans_sorted ## index samtools index celegans_sorted.bam # Extracting alignments from a region with samtools view samtools view NA12891_CEU_sample.bam 1:215906469-215906652 | head -n 3 samtools view -b NA12891_CEU_sample.bam 1:215906469-215906652 > USH2A_sample_alns.bam # from BEd extract regions samtools view -L USH2A_exons.bed NA12891_CEU_sample.bam | head -n 3 # samtools view also has options for filtering alignments based on bitwise flags, mapping quality, read group. samtools flags samtools flags unmap samtools flags 69 samtools flags READ1,PROPER_PAIR samtools view -f 4 NA12891_CEU_sample.bam | head -n 3 samtools view -f 66 NA12891_CEU_sample.bam | head -n 3 # -F # not match != samtools view -F 4 NA12891_CEU_sample.bam | head -n 3 # check counts samtools view -F 6 NA12891_CEU_sample.bam | wc - samtools view -F 7 NA12891_CEU_sample.bam | wc -l samtools view -F 6 -f 1 NA12891_CEU_sample.bam | wc -l # samtools mpileup call SNP samtools mpileup --no-BAQ --region 1:215906528-215906567 \ --fasta-ref human_g1k_v37.fasta NA12891_CEU_sample.bam
e6369207741459c71e71698c908db63c88526a42
89c089c0203592b1acc9691cb8bbeae1454cd9ac
/src/run_adaptive.R
f1031f9540588c2573ee1b9b5ef4eccb51aa9220
[]
no_license
kallus/sass
789e4ce47e8652a84724b6ed68d32dccdf0db394
b5138f3870d826948101840aad2d650a9a3d9f74
refs/heads/master
2022-11-09T11:14:36.298017
2020-06-23T08:21:32
2020-06-23T08:21:32
258,504,983
0
0
null
null
null
null
UTF-8
R
false
false
3,161
r
run_adaptive.R
source('src/sass/sass.R') source('src/sass/smoothing.R') source('src/experiment/generator.R') source('src/experiment/caching.R') source('src/experiment/contenders.R') source('src/experiment/real.R') source('src/experiment/scores.R') B <- 100 lambda_ratio <- 0.1 to_w <- function(theta, u=0.1, v=0.3) { omega = as.matrix(theta)*v diag(omega) = abs(min(eigen(omega)$values)) + 0.1 + u stats::cov2cor(solve(omega)) } pcor <- function(corr) { P <- solve(corr) Pii <- diag(P) %*% matrix(1, 1, ncol(P)) -P / sqrt(Pii * t(Pii)) } # run contending methods on data files cor_rmse_sassa <- c() cor_rmse_glasso <- c() pcor_rmse_sassa <- c() pcor_rmse_glasso <- c() for (datafile in list.files(path='cache/data/')) { if (!startsWith(datafile, 'cluster')) { next } print(datafile) net <- readRDS(paste('cache/data', datafile, sep='/')) n <- nrow(net$data) lambda_max <- cached(c('find_lambda_max', datafile), net$data) set.seed(1) subsamples <- subsample_observations(n, B) networks <- cached(c('subsample_neighsel', datafile), net$data, lambda_ratio*lambda_max, B, subsamples) stabsel_freq <- cached(c('selection_freq', datafile), networks) threshold <- cached(c('FDR_threshold', 'stabsel', datafile), stabsel_freq, FDR=0.1, length(networks)) stabsel_net <- cached(c('threshold_frequencies', 'stabsel', datafile), stabsel_freq, threshold) sassa_freq <- stabsel_freq sassa_net <- stabsel_net comm_counts <- cached(c('consensus_module_counts', 'sass', datafile), networks, B) comm_threshold <- cached(c('smooth_inner_minima', 'sass', datafile), uptri(comm_counts), 0, B) if (length(comm_threshold) != 1) { comm_threshold <- Inf } cmask <- comm_counts > comm_threshold if (any(cmask)) { inside_min <- cached(c('smooth_inner_minima', 'sass', 'inside', datafile), 2*B*uptri(stabsel_freq)[uptri(cmask)], 0, 2*B) if (length(inside_min) == 1) { between_min <- cached(c('best_smooth_min', 'sass', 'between', datafile), 2*B*uptri(stabsel_freq)[uptri(!cmask)], 0, 2*B) if (!is.na(between_min) && inside_min < between_min) { sassa_freq <- cached(c('adapt_frequencies_mask2', 'sass', datafile), stabsel_freq, inside_min, between_min, cmask, B) } } } sassa_wwi <- cached(c('sass_adaptive_strength', 'sassa', datafile), net$data, lambda_max, sassa_freq, stabsel_net) glasso_wwi <- cached(c('glasso_strength', datafile), net$data, lambda_max, stabsel_net) true_wwi <- list() true_wwi$w=to_w(net$theta) true_wwi$wi=solve(true_wwi$w) # compare partial correlations and/or correlations # RMSE cor_rmse_sassa <- c(cor_rmse_sassa, sqrt(mean(c(true_wwi$w - cov2cor(sassa_wwi$w))^2))) cor_rmse_glasso <- c(cor_rmse_glasso, sqrt(mean(c(true_wwi$w - cov2cor(glasso_wwi$w))^2))) pcor_rmse_sassa <- c(pcor_rmse_sassa, sqrt(mean(c(pcor(true_wwi$w) - pcor(cov2cor(sassa_wwi$w)))^2))) pcor_rmse_glasso <- c(pcor_rmse_glasso, sqrt(mean(c(pcor(true_wwi$w) - pcor(cov2cor(glasso_wwi$w)))^2))) } write.table(cbind(cor_rmse_sassa, cor_rmse_glasso, pcor_rmse_sassa, pcor_rmse_glasso), 'cache/glasso_sassa_cmp.tsv')
7600b1827198c89112739fbc6093a6a7cecabfbe
1d481ceeca7236ce5464c5fafd397fea7e193126
/man/survRM2-package.Rd
f8fa0f6b925136d2d15e0a0675d6c10917dc0e56
[]
no_license
cran/survRM2
d90db8bc397c9fa86db0d22231334a5abb748822
044089fcdd77b46e754cd18ac6d7f21498ce5e73
refs/heads/master
2022-07-27T15:04:02.632607
2022-06-14T02:50:02
2022-06-14T02:50:02
30,389,008
3
1
null
null
null
null
UTF-8
R
false
true
1,698
rd
survRM2-package.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/survRM2-package.R \docType{package} \name{survRM2-package} \alias{survRM2-package} \title{Comparing Restricted Mean Survival Time} \description{ Performs two-sample comparisons using the restricted mean survival time (RMST) as a summary measure of the survival time distribution. Three kinds of between-group contrast metrics (i.e., the difference in RMST, the ratio of RMST and the ratio of the restricted mean time lost (RMTL)) are computed. The package has a function to perform an ANCOVA-type covariate adjustment as well as unadjusted analyses for those measures. } \examples{ #--- sample data ---# D=rmst2.sample.data() time=D$time status=D$status arm=D$arm tau=NULL x=D[,c(4,6,7)] #--- without covariates ---- a=rmst2(time, status, arm, tau=10) print(a) plot(a, xlab="Years", ylab="Probability", density=60) #--- with covariates ---- a=rmst2(time, status, arm, tau=10, covariates=x) print(a) } \references{ Uno H, Claggett B, Tian L, Inoue E, Gallo P, Miyata T, Schrag D, Takeuchi M, Uyama Y, Zhao L, Skali H, Solomon S, Jacobus S, HughesM, Packer M, Wei LJ. Moving beyond the hazard ratio in quantifying the between-group difference in survival analysis. Journal of clinical Oncology 2014, 32, 2380-2385. doi:10.1200/JCO.2014.55.2208. Tian L, Zhao L, Wei LJ. Predicting the restricted mean event time with the subject's baseline covariates in survival analysis. Biostatistics 2014, 15, 222-233. doi:10.1093/biostatistics/kxt050. } \seealso{ survival } \author{ Hajime Uno, Lu Tian, Miki Horiguchi, Angel Cronin, Chakib Battioui, James Bell Maintainer: Hajime Uno <huno@jimmy.harvard.edu> } \keyword{survival}
ea250a79fec66bb6fca2ae7cb815c20da6b85655
c29a2534fb4e5224d49d3fed5e23f6c86987d055
/man/wgcna_get_module_genes_by_sign.Rd
367d0956316143040b60bd1aeeb1f64bf6959646
[]
no_license
ddeweerd/MODifieRDev
8c1ae2cd35c297a5394671e05d3198b6f3b6fcf8
5660de4df282b57cd2da20e8fe493e438019b759
refs/heads/Devel
2020-03-28T18:37:56.271549
2019-11-07T10:45:09
2019-11-07T10:45:09
148,896,901
4
0
null
2019-08-20T14:14:35
2018-09-15T11:42:06
R
UTF-8
R
false
true
839
rd
wgcna_get_module_genes_by_sign.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/wcgna.R \name{wgcna_get_module_genes_by_sign} \alias{wgcna_get_module_genes_by_sign} \title{Split WGCNA module in module containing only positive or negative correlation} \usage{ wgcna_get_module_genes_by_sign(wgcna_module, mode) } \arguments{ \item{wgcna_module}{Module object that has been produced by \code{wgcna} function} \item{mode}{Character. "p" or "positive" for positive correlation, "n" or "negative" for negative correlation.} } \value{ \code{wgcna_module} object } \description{ Split WGCNA module in module containing only positive or negative correlation } \details{ The functions returns a new \code{wgcna} module object that only contains positively or negatively correlated colors } \seealso{ \code{\link{wgcna}} } \author{ Dirk de Weerd }
95e8466c5adbf8da5e46aeaaf11a736e780e8dd6
97e4dfbf87eedd1ca0d32434215f17c50845e8c7
/R/Tsq_chart.R
26e387f863d362cc1c2041281d926ff802c53cd0
[ "MIT" ]
permissive
cil0834/LAGG4793
73486aec788e2420161071323d8c932ef5498f8c
5f60b208b81523d80f162527fb09783b6c579867
refs/heads/master
2023-04-10T17:47:41.482964
2021-04-22T22:36:58
2021-04-22T22:36:58
351,226,788
0
0
null
null
null
null
UTF-8
R
false
false
1,244
r
Tsq_chart.R
#' Tsq_chart #' #'@description This function takes in data and plots a T-squared plot #' #' @param data a dataframe #' #' @export #' #' @examples #' data = LAGG4793::project_data #' Tsq_chart(data) Tsq_chart = function(data){ # a dataframe n = dim(data)[1] p = dim(data)[2] m = colMeans(data) co_i = solve(stats::cov(data)) ucll = stats::qchisq(0.05, p, lower.tail = FALSE) uclu = stats::qchisq(0.01, p, lower.tail = FALSE) m_vec = as.matrix(data) tsqs = c() for(k in 1:n){ tsq = t(m_vec[k,]-m)%*%co_i%*%(m_vec[k,] - m) tsqs = round(c(tsqs, tsq),2) } observation = 1:n df = data.frame("observation" = observation, "tsqs" = tsqs) g = ggplot2::ggplot(data = df, ggplot2::aes(x=observation, y = tsqs)) + ggplot2::geom_point() + ggplot2::geom_hline(yintercept=ucll, linetype="dashed") + ggplot2::geom_hline(yintercept=uclu) + ggplot2::geom_text(x=max(observation)*.75, y=stats::qchisq(0.04, p, lower.tail = FALSE), label=paste("95% limit")) + ggplot2::geom_text(x=max(observation)*.75, y=stats::qchisq(0.0075, p, lower.tail = FALSE), label=paste("99% limit")) + ggplot2::ylim(0, stats::qchisq(0.007, p, lower.tail = FALSE)) + ggplot2::labs(title = "T-squared Plot") print(g) }
18b0e68ce959705821bcd69e4adfef800f880cb1
2879f5558c0a317ff1ca28f4fed69388304b69b6
/DB_mon/server.R
436e6e55ae2d87005d28c19d2514c086fdb0e81c
[]
no_license
liyuan97/R-SDSS
d2724b6d1ed136f3d981b1908bedd923fdd900f3
a91f3741f0a5140411bbf642dbb660f8cc78c620
refs/heads/master
2020-03-11T23:02:52.219447
2018-05-20T13:48:35
2018-05-20T13:48:35
130,310,727
0
0
null
null
null
null
UTF-8
R
false
false
1,109
r
server.R
library(shiny) library(DBI) library(ROracle) drv <- dbDriver("Oracle") con <- dbConnect(drv, user = "system", password="a", db="srcdb") qDF <- dbSendQuery(con, "select file_name,bytes from dba_data_files") dDF <- fetch(qDF) qDept <- dbSendQuery(con, "select * from scott.dept") dDept <- fetch(qDept) qSalGrd <- dbSendQuery(con, "select * from scott.SALGRADE") dSalGrd <- fetch(qSalGrd) # Define server logic required to summarize and view the selected dataset shinyServer(function(input, output) { # Return the requested dataset datasetInput <- reactive(function() { switch(input$dataset, "Datafiles" = dDF, "dept" = dDept, "salgrd" = dSalGrd) }) # Generate a summary of the dataset # output$summary <- reactivePrint(function() { # dataset <- datasetInput() # summary(dataset) # }) # Show the first "n" observations output$view <- reactiveTable(function() { #head(datasetInput()) datasetInput() }) output$main_plot <- reactivePlot(function() { barplot(dDF$BYTES, cex.names=c(dDF$FILE_NAME), horiz=TRUE) }) })
0ee8accf3fd1a17a01ccf63b497760318015af2f
e0e7425d5632f5b003a003c96fabc8663b3d1daf
/inst/doc/cvcrand.R
50b8c0dfc8190f0a2cb98d14da62b8c6e254944e
[]
no_license
cran/cvcrand
b58bf12903bb343f4e903a30d5872cae06cfa05a
81aba6e3091d51101aa00b3f03abc22ce2d25e89
refs/heads/master
2022-04-18T15:52:02.362306
2020-04-13T18:00:02
2020-04-13T18:00:02
112,377,460
0
0
null
null
null
null
UTF-8
R
false
false
8,065
r
cvcrand.R
## ----start,echo=FALSE,results="hide"------------------------------------------ library(cvcrand) ## ---- echo=FALSE, results='asis'---------------------------------------------- knitr::kable(Dickinson_design[ , 1:6]) ## ---- echo=FALSE, results='asis'---------------------------------------------- knitr::kable(Dickinson_design[ , 7:11]) ## ----cvrall, fig.keep="all", fig.width = 7, fig.height=4---------------------- Design_result <- cvrall(clustername = Dickinson_design$county, balancemetric = "l2", x = data.frame(Dickinson_design[ , c("location", "inciis", "uptodateonimmunizations", "hispanic", "incomecat")]), ntotal_cluster = 16, ntrt_cluster = 8, categorical = c("location", "incomecat"), ###### Option to save the constrained space ##### # savedata = "dickinson_constrained.csv", bhist = TRUE, cutoff = 0.1, seed = 12345) ## ----set-options1, echo=FALSE, fig.keep="all", fig.width = 7, fig.height=4------------------------ options(width = 100) ## ---- fig.keep="all", fig.width = 7, fig.height=4------------------------------------------------- # the balance metric used Design_result$balancemetric # the allocation scheme from constrained randomization Design_result$allocation # the histogram of the balance score with respect to the balance metric Design_result$bscores # the statement about how many clusters to be randomized to the intervention and the control arms respectively Design_result$assignment_message # the statement about how to get the whole randomization space to use in constrained randomization Design_result$scheme_message # the statement about the cutoff in the constrained space Design_result$cutoff_message # the statement about the selected scheme from constrained randomization Design_result$choice_message # the data frame containing the allocation scheme, the clustername as well as the original data frame of covariates Design_result$data_CR # the descriptive statistics for all the variables by the two arms from the selected scheme Design_result$baseline_table # the cluster pair descriptive, which is useful for valid randomization check Design_result$cluster_coin_des # the overall allocation summary Design_result$overall_allocations ## ----cvrallst1, fig.keep="all", fig.width = 7, fig.height=4--------------------------------------- # Stratification on location, with constrained randomization on other specified covariates Design_stratified_result1 <- cvrall(clustername = Dickinson_design$county, balancemetric = "l2", x = data.frame(Dickinson_design[ , c("location", "inciis", "uptodateonimmunizations", "hispanic", "incomecat")]), ntotal_cluster = 16, ntrt_cluster = 8, categorical = c("location", "incomecat"), weights = c(1000, 1, 1, 1, 1), cutoff = 0.1, seed = 12345) ## ---- fig.keep="all", fig.width = 7, fig.height=4------------------------------------------------- Design_stratified_result1$baseline_table ## ----cvrallst2, fig.keep="all", fig.width = 7, fig.height=4--------------------------------------- # An alternative and equivalent way to stratify on location Design_stratified_result2 <- cvrall(clustername = Dickinson_design$county, balancemetric = "l2", x = data.frame(Dickinson_design[ , c("location", "inciis", "uptodateonimmunizations", "hispanic", "incomecat")]), ntotal_cluster = 16, ntrt_cluster = 8, categorical = c("location", "incomecat"), stratify = "location", cutoff = 0.1, seed = 12345, check_validity = TRUE) ## ---- fig.keep="all", fig.width = 7, fig.height=4------------------------------------------------- Design_stratified_result2$baseline_table ## ----cvrcov, fig.keep="all", fig.width = 7, fig.height=4------------------------------------------ # change the categorical variable of interest to have numeric representation Dickinson_design_numeric <- Dickinson_design Dickinson_design_numeric$location = (Dickinson_design$location == "Rural") * 1 Design_cov_result <- cvrcov(clustername = Dickinson_design_numeric$county, x = data.frame(Dickinson_design_numeric[ , c("location", "inciis", "uptodateonimmunizations", "hispanic", "income")]), ntotal_cluster = 16, ntrt_cluster = 8, constraints = c("s5", "mf.5", "any", "any", "mf0.4"), categorical = c("location"), ###### Option to save the constrained space ##### # savedata = "dickinson_cov_constrained.csv", seed = 12345, check_validity = TRUE) ## ----set-options2, echo=FALSE, fig.keep="all", fig.width = 7, fig.height=4------------------------ options(width = 100) ## ---- fig.keep="all", fig.width = 7, fig.height=4------------------------------------------------- # the allocation scheme from constrained randomization Design_cov_result$allocation # the statement about how many clusters to be randomized to the intervention and the control arms respectively Design_cov_result$assignment_message # the statement about how to get the whole randomization space to use in constrained randomization Design_cov_result$scheme_message # the data frame containing the allocation scheme, the clustername as well as the original data frame of covariates Design_cov_result$data_CR # the descriptive statistics for all the variables by the two arms from the selected scheme Design_cov_result$baseline_table # the cluster pair descriptive, which is useful for valid randomization check Design_cov_result$cluster_coin_des # the overall allocation summary Design_cov_result$overall_allocations ## ---- echo=FALSE, results='asis'------------------------------------------------------------------ knitr::kable(head(Dickinson_outcome, 10)) ## ----cptest, fig.keep="all", fig.width = 7, fig.height=4------------------------------------------ Analysis_result <- cptest(outcome = Dickinson_outcome$outcome, clustername = Dickinson_outcome$county, z = data.frame(Dickinson_outcome[ , c("location", "inciis", "uptodateonimmunizations", "hispanic", "incomecat")]), cspacedatname = system.file("dickinson_constrained.csv", package = "cvcrand"), outcometype = "binary", categorical = c("location","incomecat")) ## ----cptestre, fig.keep="all", fig.width = 7, fig.height=4---------------------------------------- Analysis_result ## ----info, results='markup', echo=FALSE----------------------------------------------------------- sessionInfo()
e6451dc393ced820fb46a7518659b7c517a21aec
e3007f1c87c734f576bcbd7083dce72ec9f59e4b
/R/convert_motifs.R
5accf49f3e97266c8f633e70fceeb91fda1beb2a
[]
no_license
bjmt/universalmotif
99b0dfe9c9afea6f9a5a0db596c88c264aa194b3
ca0445479eda1043758a62aeb3b6239fbfa144ac
refs/heads/master
2023-07-20T05:51:55.219814
2023-07-11T14:17:23
2023-07-11T14:17:23
82,811,804
17
16
null
2022-05-30T09:27:26
2017-02-22T14:10:28
R
UTF-8
R
false
false
25,023
r
convert_motifs.R
#' Convert motif class. #' #' Allows for easy transfer of motif information between different classes as #' defined by other Bioconductor packages. This function is also used by #' nearly all other functions in this package, so any motifs of a compatible #' class can be used without needing to be converted beforehand. #' #' @param motifs Single motif object or list. See details. #' @param class `character(1)` Desired motif class. Input as #' 'package-class'. If left empty, defaults to #' 'universalmotif-universalmotif'. (See details.) #' #' @return Single motif object or list. #' #' @details #' ## Input #' The following packge-class combinations can be used as input: #' * MotifDb-MotifList #' * TFBSTools-PFMatrix #' * TFBSTools-PWMatrix #' * TFBSTools-ICMatrix #' * TFBSTools-PFMatrixList #' * TFBSTools-PWMatrixList #' * TFBSTools-ICMatrixList #' * TFBSTools-TFFMFirst #' * seqLogo-pwm #' * motifStack-pcm #' * motifStack-pfm #' * PWMEnrich-PWM #' * motifRG-Motif #' * universalmotif-universalmotif #' * matrix #' #' ## Output #' The following package-class combinations can be output: #' * MotifDb-MotifList #' * TFBSTools-PFMatrix #' * TFBSTools-PWMatrix #' * TFBSTools-ICMatrix #' * TFBSTools-TFFMFirst #' * seqLogo-pwm #' * motifStack-pcm #' * motifStack-pfm #' * PWMEnrich-PWM #' * Biostrings-PWM (\code{type = 'log2prob'}) #' * rGADEM-motif #' * universalmotif-universalmotif (the default, no need to specify this) #' #' Note: MotifDb-MotifList output was a later addition to [convert_motifs()]. #' As a result, to stay consistent with previous behaviour most functions #' will always convert MotifDb-MotifList objects to a list of `universalmotif` #' motifs, even if other formats would be simply returned as is (e.g. for #' other formats, [filter_motifs()] will return the input format; for #' MotifDb-MotifList, a list of `universalmotif` objects will be returned). #' #' @examples #' # Convert from universalmotif: #' jaspar <- read_jaspar(system.file("extdata", "jaspar.txt", #' package = "universalmotif")) #' if (requireNamespace("motifStack", quietly = TRUE)) { #' jaspar.motifstack.pfm <- convert_motifs(jaspar, "motifStack-pfm") #' } #' #' # Convert from another class to universalmotif: #' if (requireNamespace("TFBSTools", quietly = TRUE)) { #' library(TFBSTools) #' data(MA0003.2) #' motif <- convert_motifs(MA0003.2) #' #' # Convert from another class to another class #' if (requireNamespace("PWMEnrich", quietly = TRUE)) { #' motif <- convert_motifs(MA0003.2, "PWMEnrich-PWM") #' } #' #' # The 'convert_motifs' function is embedded in the rest of the universalmotif #' # functions: non-universalmotif class motifs can be used #' MA0003.2.trimmed <- trim_motifs(MA0003.2) #' # Note: if the motif object going in has information that the #' # 'universalmotif' class can't hold, it will be lost #' } #' #' @references #' #' Bembom O (2018). *seqLogo: Sequence logos for DNA sequence #' alignments*. R package version 1.46.0. #' #' Droit A, Gottardo R, Robertson G, Li L (2014). *rGADEM: de novo #' motif discovery*. R package version 2.28.0. #' #' Mercier E, Gottardo R (2014). *MotIV: Motif Identification and #' Validation*. R package version 1.36.0. #' #' Ou J, Wolfe SA, Brodsky MH, Zhu LJ (2018). “motifStack for the #' analysis of transcription factor binding site evolution.” *Nature #' Methods*, **15**, 8-9. doi: 10.1038/nmeth.4555. #' #' Shannon P, Richards M (2018). *MotifDb: An Annotated Collection of #' Protein-DNA Binding Sequence Motifs*. R package version 1.22.0. #' #' Stojnic R, Diez D (2015). *PWMEnrich: PWM enrichment analysis*. R #' package version 4.16.0. #' #' Tan G, Lenhard B (2016). “TFBSTools: an R/Bioconductor package for #' transcription factor binding site analysis.” *Bioinformatics*, #' **32**, 1555-1556. doi: 10.1093/bioinformatics/btw024. #' #' Yao Z (2012). *motifRG: A package for discriminative motif #' discovery, designed for high throughput sequencing dataset*. R #' package version 1.24.0. #' #' @author Benjamin Jean-Marie Tremblay, \email{benjamin.tremblay@@uwaterloo.ca} #' @include universalmotif-class.R #' @export setGeneric("convert_motifs", function(motifs, class = "universalmotif-universalmotif") standardGeneric("convert_motifs")) #' @describeIn convert_motifs Generate an error to remind users to run #' [to_list()] instead of using the column from [to_df()] directly. #' @export setMethod("convert_motifs", signature(motifs = "AsIs"), definition = function(motifs, class) { stop(wmsg( "If you are providing the `motif` column from the `data.frame` output of ", "to_df(), then please use to_list() instead. If this error ", "message does not apply to you, then remove the `AsIs` class attribute ", "and try again (`class(mylist) <- NULL`)." )) }) #' @describeIn convert_motifs Convert a list of motifs. #' @export setMethod("convert_motifs", signature(motifs = "list"), definition = function(motifs, class) { motifs <- unlist(motifs) if (!length(motifs)) stop("Input is an empty list") mot_classes <- unique(vapply(motifs, function(x) class(x), character(1))) if (length(mot_classes) == 1) { classin <- strsplit(class, "-", fixed = TRUE)[[1]][2] if (mot_classes == classin) return(motifs) } if (class == "MotifDb-MotifList") { motifs <- lapply(motifs, function(x) convert_motifs(x)) motifs <- convert_to_motifdb_motiflist(motifs) } else { motifs <- lapply(motifs, function(x) convert_motifs(x, class = class)) } motifs }) #' @describeIn convert_motifs Convert a \linkS4class{universalmotif} object. #' @export setMethod("convert_motifs", signature(motifs = "universalmotif"), definition = function(motifs, class) { out_class <- strsplit(class, "-", fixed = TRUE)[[1]][2] out_class_pkg <- strsplit(class, "-", fixed = TRUE)[[1]][1] switch(out_class_pkg, "universalmotif" = { validObject_universalmotif(motifs) motifs }, "TFBSTools" = { if (out_class %in% c("PFMatrix", "PWMatrix", "ICMatrix")) convert_to_tfbstools_matrix(motifs, out_class) else if (out_class == "TFFMFirst") convert_to_tfbstools_tffmfirst(motifs) else stop("unknown 'class'") }, "seqLogo" = { if (out_class == "pwm") convert_to_seqlogo_pwm(motifs) else stop("unknown 'class'") }, "motifStack" = { switch(out_class, "pcm" = convert_to_motifstack_pcm(motifs), "pfm" = convert_to_motifstack_pfm(motifs), stop("unknown 'class'")) }, "PWMEnrich" = { if (out_class == "PWM") convert_to_pwmenrich_pwm(motifs) else stop("unknown 'class'") }, "Biostrings" = { if (out_class == "PWM") convert_to_biostrings_pwm(motifs) else stop("unknown 'class'") }, "rGADEM" = { if (out_class == "motif") convert_to_rgadem_motif(motifs) else stop("unknown 'class'") }, "MotifDb" = { if (out_class == "MotifList") convert_to_motifdb_motiflist(motifs) else stop("unknown 'class'") }, stop("unknown 'class'") ) }) convert_to_tfbstools_matrix <- function(motifs, out_class) { motifs <- convert_type(motifs, "PCM") bkg <- motifs["bkg"][DNA_BASES] # names(bkg) <- DNA_BASES extrainfo <- motifs["extrainfo"] if (length(motifs["altname"]) == 0) { motifs["altname"] <- "" } strand <- motifs["strand"] if (strand %in% c("+-", "-+")) { strand <- "*" } if (requireNamespace("TFBSTools", quietly = TRUE)) { motifs <- TFBSTools::PFMatrix(name = motifs["name"], ID = motifs["altname"], strand = strand, bg = bkg, profileMatrix = motifs["motif"]) switch(out_class, "PFMatrix" = { motifs <- motifs }, "PWMatrix" = { motifs <- TFBSTools::toPWM(motifs, type = "log2probratio", pseudocounts = 1, bg = bkg) }, "ICMatrix" = { motifs <- TFBSTools::toICM(motifs, pseudocounts = 1, bg = bkg) } ) } else { stop("package 'TFBSTools' is not installed") } if (length(extrainfo) > 0) { motifs@tags <- as.list(extrainfo) } motifs } convert_to_tfbstools_tffmfirst <- function(motifs) { motifs <- convert_type(motifs, "PPM") if (!"2" %in% names(motifs@multifreq)) { stop("cannot convert without filled multifreq slot") } if (motifs["alphabet"] != "DNA") stop("alphabet must be DNA") bkg <- motifs["bkg"][DNA_BASES] emission <- list(length = ncol(motifs@multifreq[["2"]]) + 1) emission[[1]] <- bkg transition <- matrix(rep(0, (ncol(motifs@multifreq$"2") + 1) * ncol(motifs@multifreq$"2")), nrow = ncol(motifs@multifreq$"2") + 1, ncol = ncol(motifs@multifreq$"2")) for (i in seq_len(ncol(motifs@multifreq$"2"))) { emission[[i + 1]] <- motifs@multifreq$"2"[, i] transition[i, i] <- 1 } names(emission) <- rep("state", length(emission)) transition[nrow(transition), 1] <- 1 transition[2, 1:2] <- c(0.95, 0.05) colnames(transition) <- seq_len(ncol(transition)) rownames(transition) <- c(0, seq_len(ncol(transition))) if (length(motifs@altname) < 1) motifs@altname <- "Unknown" strand <- motifs@strand if (strand %in% c("+-", "-+")) strand <- "*" family <- motifs@family if (length(family) < 1) family <- "Unknown" if (requireNamespace("TFBSTools", quietly = TRUE)) { motifs <- TFBSTools::TFFMFirst(ID = motifs@altname, name = motifs@name, strand = strand, type = "First", bg = bkg, matrixClass = family, profileMatrix = motifs@motif, tags = as.list(motifs@extrainfo), emission = emission, transition = transition) } else { stop("package 'TFBSTools' is not installed") } motifs } convert_to_seqlogo_pwm <- function(motifs) { motifs <- convert_type(motifs, "PPM") if (requireNamespace("seqLogo", quietly = TRUE)) { motifs <- seqLogo::makePWM(motifs@motif) } else { stop("'seqLogo' package not installed") } motifs } convert_to_motifdb_motiflist <- function(motifs) { if (!is.list(motifs)) motifs <- list(motifs) if (requireNamespace("MotifDb", quietly = TRUE)) { motiflist_class <- getClass("MotifList", where = "MotifDb") motifs <- convert_type(motifs, "PPM") m <- lapply(motifs, function(x) x["motif"]) for (i in seq_along(m)) { colnames(m[[i]]) <- seq_len(ncol(m[[i]])) } m_names <- vapply(motifs, function(x) x["name"], character(1)) m_altnames <- vapply(motifs, function(x) { x <- x["altname"] if (!length(x)) "<ID:unknown>" else x }, character(1)) m_family <- vapply(motifs, function(x) { x <- x["family"] if (!length(x)) "<family:unknown>" else x }, character(1)) m_organisms <- vapply(motifs, function(x) { x <- x["organism"] if (!length(x)) "<organism:unknown>" else x }, character(1)) m_nsites <- as.numeric(sapply(motifs, function(x) { x <- x["nsites"] if (!length(x)) NA_real_ else x })) if (any(duplicated(m_names))) { stop("MotifDb-MotifList cannot be created from motifs with duplicated 'name' slots", call. = FALSE) } names(m) <- m_names extras <- c("dataSource", "geneSymbol", "geneId", "proteinId", "proteinType", "bindingSequence", "bindingDomain", "experimentType", "pubmedID") meta <- DataFrame( providerName = m_names, providerId = m_altnames, dataSource = "<dataSource:unknown>", geneSymbol = NA_character_, geneId = NA_character_, proteinId = NA_character_, proteinIdType = NA_character_, organism = m_organisms, sequenceCount = m_nsites, bindingSequence = NA_character_, bindingDomain = NA_character_, tfFamily = m_family, experimentType = NA_character_, pubmedID = NA_character_ ) for (i in seq_along(m)) { m_ex_i <- motifs[[i]]["extrainfo"] for (j in seq_along(extras)) { m_ex_i_j <- m_ex_i[extras[j]] if (!is.na(m_ex_i_j)) { meta[[extras[j]]][i] <- m_ex_i_j } } } assoctab <- data.frame( motif = m_names, tf.gene = NA_character_, tf.ensg = NA_character_ ) motifs <- new(motiflist_class, listData = m, elementMetadata = meta, manuallyCuratedGeneMotifAssociationTable = assoctab) } else { stop("'MotifDb' package not installed") } motifs } convert_to_motifstack_pcm <- function(motifs) { if (requireNamespace("motifStack", quietly = TRUE)) { pcm_class <- getClass("pcm", where = "motifStack") motifs <- convert_type(motifs, "PCM") motifs <- new(pcm_class, mat = motifs@motif, name = motifs@name, alphabet = motifs@alphabet, background = motifs@bkg[DNA_BASES]) } else { stop("'motifStack' package not installed") } colnames(motifs@mat) <- seq_len(ncol(motifs@mat)) names(motifs@background) <- rownames(motifs@mat) motifs } convert_to_motifstack_pfm <- function(motifs) { if (requireNamespace("motifStack", quietly = TRUE)) { pfm_class <- getClass("pfm", where = "motifStack") motifs <- convert_type(motifs, "PPM") motifs <- new(pfm_class, mat = motifs@motif, name = motifs@name, alphabet = motifs@alphabet, background = motifs@bkg[DNA_BASES]) } else { stop("'motifStack' package not installed") } colnames(motifs@mat) <- seq_len(ncol(motifs@mat)) names(motifs@background) <- rownames(motifs@mat) motifs } convert_to_pwmenrich_pwm <- function(motifs) { if (requireNamespace("PWMEnrich", quietly = TRUE)) { motifs <- convert_type(motifs, "PCM") PWM_class <- getClass("PWM", where = "PWMEnrich") bio_mat <- matrix(as.integer(motifs@motif), byrow = FALSE, nrow = 4) rownames(bio_mat) <- DNA_BASES bio_priors <- motifs@bkg[DNA_BASES] bio_mat <- PWMEnrich::PFMtoPWM(bio_mat, type = "log2probratio", prior.params = bio_priors, pseudo.count = motifs@pseudocount) motifs <- new(PWM_class, name = motifs["name"], pfm = motifs@motif, prior.params = bio_priors, pwm = bio_mat$pwm) } else { stop("package 'PWMEnrich' not installed") } motifs } convert_to_biostrings_pwm <- function(motifs) { motifs <- convert_type(motifs, "PCM") bio_mat <- matrix(as.integer(motifs["motif"]), byrow = FALSE, nrow = 4) rownames(bio_mat) <- DNA_BASES bio_priors <- motifs@bkg[DNA_BASES] motifs <- PWM(x = bio_mat, type = "log2probratio", prior.params = bio_priors) motifs } convert_to_rgadem_motif <- function(motifs) { if (requireNamespace("rGADEM", quietly = FALSE)) { motifs <- convert_type(motifs, "PPM") rGADEM_motif_class <- getClass("motif", where = "rGADEM") motifs <- new(rGADEM_motif_class, pwm = motifs@motif, name = motifs@name, consensus = motifs@consensus) } else { stop("'rGADEM' package not installed") } motifs } #' @describeIn convert_motifs Convert MotifList motifs. (\pkg{MotifDb}) #' @export setMethod("convert_motifs", signature(motifs = "MotifList"), definition = function(motifs, class) { x <- motifs altname <- x@elementMetadata@listData$providerName name <- x@elementMetadata@listData$geneSymbol family <- x@elementMetadata@listData$tfFamily organism <- x@elementMetadata@listData$organism motif <- x@listData nsites <- as.numeric(x@elementMetadata@listData$sequenceCount) dataSource <- x@elementMetadata@listData$dataSource motifdb_fun <- function(i) { mot <- universalmotif_cpp(altname = altname[i], name = name[i], family = family[i], organism = organism[i], motif = motif[[i]], alphabet = "DNA", type = "PPM", nsites = nsites[i], extrainfo = c(dataSource = dataSource[i])) validObject_universalmotif(mot) mot } motifs_out <- lapply(seq_len(length(x)), motifdb_fun) convert_motifs(motifs_out, class = class) }) #' @describeIn convert_motifs Convert TFFMFirst motifs. (\pkg{TFBSTools}) #' @export setMethod("convert_motifs", signature(motifs = "TFFMFirst"), definition = function(motifs, class) { if (requireNamespace("TFBSTools", quietly = TRUE)) { difreq <- motifs@emission[-1] difreq <- do.call(c, difreq) difreq <- matrix(difreq, nrow = 16) / 4 rownames(difreq) <- DNA_DI colnames(difreq) <- seq_len(ncol(difreq)) mot <- universalmotif_cpp(name = motifs@name, altname = motifs@ID, strand = motifs@strand, bkg = motifs@bg, motif = TFBSTools::getPosProb(motifs)) mot@multifreq <- list("2" = difreq) } else { stop("package 'TFBSTools' is not installed") } convert_motifs(mot, class = class) }) #' @describeIn convert_motifs Convert PFMatrix motifs. (\pkg{TFBSTools}) #' @export setMethod("convert_motifs", signature(motifs = "PFMatrix"), definition = function(motifs, class) { if (all(names(motifs@bg) %in% DNA_BASES)) { alphabet <- "DNA" } else alphabet <- "RNA" extrainfo <- motifs@tags if (length(extrainfo) > 0) { extrainfo <- unlist(extrainfo) } else { extrainfo <- character() } nsites <- sum(motifs@profileMatrix[, 1]) motifs <- universalmotif_cpp(name = motifs@name, altname = motifs@ID, family = paste0(motifs@tags$family, collapse = " / "), nsites = nsites, organism = paste0(motifs@tags$species, collapse = "/"), motif = motifs@profileMatrix, alphabet = alphabet, type = "PCM", bkg = motifs@bg, strand = collapse_cpp(motifs@strand), extrainfo = extrainfo) validObject_universalmotif(motifs) convert_motifs(motifs, class = class) }) #' @describeIn convert_motifs Convert PWMatrix motifs. (\pkg{TFBSTools}) setMethod("convert_motifs", signature(motifs = "PWMatrix"), definition = function(motifs, class) { if (all(names(motifs@bg) %in% DNA_BASES)) { alphabet <- "DNA" } else alphabet <- "RNA" extrainfo <- motifs@tags if (length(extrainfo) > 0) { extrainfo <- unlist(extrainfo) } else { extrainfo <- character() } motifs <- universalmotif_cpp(name = motifs@name, altname = motifs@ID, family = paste0(motifs@tags$family, collapse = " / "), organism = paste0(motifs@tags$species, collapse = "/"), motif = motifs@profileMatrix, alphabet = alphabet, type = "PWM", bkg = motifs@bg, strand = collapse_cpp(motifs@strand), extrainfo = extrainfo) validObject_universalmotif(motifs) convert_motifs(motifs, class = class) }) #' @describeIn convert_motifs Convert ICMatrix motifs. (\pkg{TFBSTools}) setMethod("convert_motifs", signature(motifs = "ICMatrix"), definition = function(motifs, class) { if (all(names(motifs@bg) %in% DNA_BASES)) { alphabet <- "DNA" } else alphabet <- "RNA" extrainfo <- motifs@tags if (length(extrainfo) > 0) { extrainfo <- unlist(extrainfo) } else { extrainfo <- character() } motifs <- universalmotif_cpp(name = motifs@name, altname = motifs@ID, family = paste0(motifs@tags$family, collapse = " / "), organism = paste0(motifs@tags$species, collapse = "/"), motif = motifs@profileMatrix, alphabet = alphabet, type = "ICM", bkg = motifs@bg, strand = collapse_cpp(motifs@strand), extrainfo = extrainfo) validObject_universalmotif(motifs) convert_motifs(motifs, class = class) }) #' @describeIn convert_motifs Convert XMatrixList motifs. (\pkg{TFBSTools}) #' @export setMethod("convert_motifs", signature(motifs = "XMatrixList"), definition = function(motifs, class) { motif_num <- length(motifs@listData) motifs_out <- lapply(seq_len(motif_num), function(i) motifs@listData[[i]]) motif_names <- unlist(lapply(seq_len(motif_num), function(i) motifs@listData[[i]]@name)) motifs <- lapply(motifs_out, convert_motifs) convert_motifs(motifs, class = class) }) #' @describeIn convert_motifs Convert pwm motifs. (\pkg{seqLogo}) #' @export setMethod("convert_motifs", signature(motifs = "pwm"), definition = function(motifs, class) { motifs <- universalmotif_cpp(motif = motifs@pwm, type = "PPM", alphabet = motifs@alphabet) validObject_universalmotif(motifs) convert_motifs(motifs, class = class) }) #' @describeIn convert_motifs Convert pcm motifs. (\pkg{motifStack}) #' @export setMethod("convert_motifs", signature(motifs = "pcm"), definition = function(motifs, class) { motifs <- universalmotif_cpp(name = motifs@name, motif = motifs@mat, nsites = unique(colSums(motifs@mat))[1], alphabet = motifs@alphabet, bkg = motifs@background, type = "PCM") validObject_universalmotif(motifs) convert_motifs(motifs, class = class) }) #' @describeIn convert_motifs Convert pfm motifs. (\pkg{motifStack}) #' @export setMethod("convert_motifs", signature(motifs = "pfm"), definition = function(motifs, class) { motifs <- universalmotif_cpp(name = motifs@name, motif = motifs@mat, alphabet = motifs@alphabet, bkg = motifs@background, type = "PPM") validObject_universalmotif(motifs) convert_motifs(motifs, class = class) }) #' @describeIn convert_motifs Convert PWM motifs. (\pkg{PWMEnrich}) #' @export setMethod("convert_motifs", signature(motifs = "PWM"), definition = function(motifs, class) { if (all(names(motifs@pwm) %in% DNA_BASES)) { alphabet <- "DNA" } else alphabet <- "RNA" motifs <- universalmotif_cpp(name = motifs@name, motif = motifs@pwm, type = "PWM", alphabet = alphabet, bkg = motifs@prior.params, altname = motifs@id) validObject_universalmotif(motifs) convert_motifs(motifs, class = class) }) #' @describeIn convert_motifs Convert Motif motifs. (\pkg{motifRG}) #' @export setMethod("convert_motifs", signature(motifs = "Motif"), definition = function(motifs, class) { motifs <- universalmotif_cpp(name = motifs@pattern, nsites = sum(motifs@count), alphabet = "DNA", type = "PCM", extrainfo = c(score = motifs@score), strand = paste(unique(motifs@match$match.strand), collapse = ""), motif <- create_motif(input = DNAStringSet(motifs@match$pattern))@motif) validObject_universalmotif(motifs) convert_motifs(motifs, class = class) }) #' @describeIn convert_motifs Create motif from matrices. #' @export setMethod("convert_motifs", signature(motifs = "matrix"), definition = function(motifs, class) { motifs <- create_motif(motifs) convert_motifs(motifs, class = class) }) # @describeIn convert_motifs Convert non-\linkS4class{universalmotif} class motifs. # @export # setMethod("convert_motifs", signature(motifs = "ANY"), # definition = function(motifs, class) { # success <- FALSE # ## convert to universalmotif # in_class <- class(motifs)[1] # in_class_pkg <- attributes(class(motifs))$package # if (paste(in_class_pkg, in_class, sep = "-") == class) { # return(motifs) # } # paste(in_class_pkg) # paste(in_class) # if (!success) stop("unrecognized class") # ## convert to desired class # motifs <- convert_motifs(motifs, class = class) # motifs # })
7468c4ec52b187f40673eeab1cf21f32cb933103
5b9559fbe07d61b8dc15bb5f701d9853e021f34f
/inst/scripts/outside.R
08c87e1daff699692aa0dda4161b22854e4a7393
[ "MIT" ]
permissive
adamkucharski/covidhm
ef1f3625a38000e919dc848222dcf94ec59afe02
0306b3a1e9940acdd4dc3ad8470a07fa67a1f702
refs/heads/master
2023-03-29T06:47:24.725622
2023-03-23T12:44:16
2023-03-23T12:44:16
563,936,939
0
0
NOASSERTION
2022-11-09T16:41:47
2022-11-09T16:41:46
null
UTF-8
R
false
false
859
r
outside.R
########################################### #SIMULATE OUTSIDE INFECTION ########################################### rm(list=ls()) library(covidhm) library(dplyr) library(purrr) library(tidyr) source("inst/scripts/default_params.R") future::plan("multiprocess") # Simulate scenarios ------------------------------------------------------ intervention = c("nothing","primary_quarantine","secondary_quarantine") outside = c(0.0001,0.001,0.005,0.01) scenarios <- expand_grid(intervention,outside) res <- scenarios %>% mutate(results = map2(intervention,outside, ~ scenario_sim2(scenario = .x, outside = .y, distancing = 0, testing = FALSE))) saveRDS(res,"data-raw/outside.rds")
d39ec2f55c45529432fe20c3667743e93934c2da
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/jstable/examples/coxExp.Rd.R
d4f8b029bb899f461bf6804a59005c7d2db9ded1
[]
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
297
r
coxExp.Rd.R
library(jstable) ### Name: coxExp ### Title: coxExp: transform the unit of coefficients in cox model(internal ### function) ### Aliases: coxExp ### ** Examples library(coxme) fit <- coxme(Surv(time, status) ~ ph.ecog + age + (1|inst), lung) jstable:::coxExp(jstable:::coxmeTable(fit))
29e14b1c489fb940d7ecbcca99d77d9d1ce2c537
62189fdb2b397f2b2050f885c4e9c7cac4045446
/scripts/prims_field_viz/www/scripts/load_packages.R
90167bd31c2ac2ab98a5c92c426bf9bb054bb71f
[]
no_license
ECO2ZTS/prims
9fde52dfdf6e6260dbbd8c60cd2bea3467b9928c
0740633804e230279e0b49981d71d67882199753
refs/heads/master
2022-04-04T01:17:36.281249
2020-01-28T08:06:13
2020-01-28T08:06:13
null
0
0
null
null
null
null
UTF-8
R
false
false
907
r
load_packages.R
######################################## # include all the needed packages here # packages <- function(x){ x <- as.character(match.call()[[2]]) if (!require(x,character.only=TRUE)){ install.packages(pkgs=x,repos="http://cran.r-project.org") require(x,character.only=TRUE) } } ## Packages for geospatial data handling # packages(raster) # packages(rgeos) # packages(rgdal) # packages(Formula) ## Packages for Shiny packages(shiny) packages(shinydashboard) packages(shinyFiles) packages(lubridate) # packages(snow) # packages(htmltools) # packages(devtools) # packages(RCurl) ## Packages for data table handling # packages(xtable) # packages(DT) # packages(dismo) packages(stringr) packages(dplyr) ## Packages for graphics and interactive maps packages(ggplot2) # packages(leaflet) # packages(RColorBrewer) ## Packages for BFAST #packages(bfastSpatial) #packages(parallel) #packages(ncdf4)
4990c7b26df014b84f6cafbe40ee6568ea4c7423
cb9e345318bd0f0502a459984fb00cb647b3ec2c
/MCD12Q2C6/MCD12Q2C6_sample.R
440e5860083008775fe070360585b8725c157b81
[]
no_license
jm-gray/pixel-forge
f3e70fdf8cd1ea2c834305a907893d8deb0e8dcc
be3f4b3e00f53f1df933e878a63a80e75c497c81
refs/heads/master
2021-07-15T06:05:46.746375
2021-06-29T13:36:14
2021-06-29T13:36:14
61,559,574
0
1
null
null
null
null
UTF-8
R
false
false
9,451
r
MCD12Q2C6_sample.R
library(raster) library(parallel) library(data.table) library(argparse) #--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ GetSDS <- function(file_path, sds=NULL){ # gets the SDS names for MCD12Q2 EOS HDFs # valid sds options: Greenup, MidGreenup, Peak, Senescence, MidGreendown, Dormancy, EVI_Minimum, EVI_Amplitude, NumCycles, QA_Detailed, QA_Overall # if sds is not provided, filenames for all SDS are returned all_sds <- c("NumCycles", "Greenup", "MidGreenup", "Maturity", "Peak", "Senescence", "MidGreendown", "Dormancy", "EVI_Minimum", "EVI_Amplitude", "EVI_Area", "QA_Overall", "QA_Detailed") if(is.null(sds)){ return(paste("HDF4_EOS:EOS_GRID:\"", file_path, "\":MCD12Q2:", all_sds, sep = "")) }else{ return(paste("HDF4_EOS:EOS_GRID:\"", file_path, "\":MCD12Q2:", sds, sep = "")) } } #--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ GetSDSQ1 <- function(file_path, sds="LC_Type1"){ # returns the proper EOS-HDF name for a particular MCD12Q1 C6 SDS return(paste("HDF4_EOS:EOS_GRID:\"", file_path, "\":MCD12Q1:", sds, sep = "")) } #--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ GetMetricSample <- function(metric, in_file, pt_sp, LC_DIR="/rsstu/users/j/jmgray2/SEAL/MCD12Q1"){ # extract the values from in_file, corresponding to the phenometric metric, at the locations in pt_sp # return as a long form data.table with: tile, cell#, x, y, lat, lon, metric, lc, year, and value columns file_year <- as.integer(gsub(".*A([0-9]{4})001.*$", "\\1", basename(in_file))) file_tile <- gsub(".*(h[0-9]{2}v[0-9]{2}).*$", "\\1", basename(in_file)) # extract values from MCD12Q2 data s <- stack(GetSDS(in_file, metric)) vals <- extract(s, pt_sp) # get the MCD12Q1 landcover lc_in_file <- dir(file.path(LC_DIR, 2016, "001"), pattern=file_tile, full=T) lc_r <- raster(GetSDSQ1(lc_in_file)) lc_v <- extract(lc_r, pt_sp) # get the cell numbers and lat/lon of sample locations cell_nums <- cellFromXY(s, pt_sp) proj4_latlon <- "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs" pt_sp_latlon <- spTransform(pt_sp, CRS(proj4_latlon)) if(ncol(vals) > 1){ DTcycle1 <- data.table(tile=file_tile, cell_num=cell_nums, x=coordinates(pt_sp)[, 1], y=coordinates(pt_sp)[, 2], lat=coordinates(pt_sp_latlon)[, 2], lon=coordinates(pt_sp_latlon)[, 1], igbp=lc_v, phenometric=paste(metric, "1", sep=""), year=file_year, value=vals[, 1]) DTcycle2 <- data.table(tile=file_tile, cell_num=cell_nums, x=coordinates(pt_sp)[, 1], y=coordinates(pt_sp)[, 2], lat=coordinates(pt_sp_latlon)[, 2], lon=coordinates(pt_sp_latlon)[, 1], igbp=lc_v, phenometric=paste(metric, "2", sep=""), year=file_year, value=vals[, 2]) DTreturn <- rbind(DTcycle1, DTcycle2) }else{ DTreturn <- data.table(tile=file_tile, cell_num=cell_nums, x=coordinates(pt_sp)[, 1], y=coordinates(pt_sp)[, 2], lat=coordinates(pt_sp_latlon)[, 2], lon=coordinates(pt_sp_latlon)[, 1], igbp=lc_v, phenometric=metric, year=file_year, value=vals[, 1]) } return(DTreturn) } #--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ GetSample <- function(in_file, pt_sp, metrics=NULL){ # apply GetMetricSample() over multiple phenometrics for a particular file and return as an aggregated data.table if(is.null(metrics)) metrics <- c("NumCycles", "Greenup", "MidGreenup", "Maturity", "Peak", "Senescence", "MidGreendown", "Dormancy", "EVI_Minimum", "EVI_Amplitude", "EVI_Area", "QA_Detailed", "QA_Overall") system.time(all_mets <- lapply(metrics, GetMetricSample, in_file=in_file, pt_sp=pt_sp)) DT_all_mets <- do.call(rbind, all_mets) return(DT_all_mets) } #--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # let's do it... arg_parser <- ArgumentParser() arg_parser$add_argument("-tile", type="character") # tile to process args <- arg_parser$parse_args() tile <- args$tile # define in/out directories and the sample size inca_dir <- "/rsstu/users/j/jmgray2/SEAL/INCA/INCAglobaloutput" output_dir <- "/rsstu/users/j/jmgray2/SEAL/INCA/GlobalPhenoSample" data_dir <- "/rsstu/users/j/jmgray2/SEAL/INCA/MCD12Q2C6/MCD12Q2" sample_frac <- 0.01 NUM_SAMPLES <- round(2400^2 * sample_frac) # Define a sample for this tile by getting the INCA file and choosing from non-NA values # this will undersample in deserts I guess? proj4_modis_sin <- "+proj=sinu +R=6371007.181 +nadgrids=@null +wktext +unit=m" proj4_latlon <- "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs " inca_file <- dir(inca_dir, pattern=paste(tile, ".*Peak", sep=""), full=T) inca_r <- raster(inca_file) inca_sample <- sampleRandom(inca_r, size=NUM_SAMPLES, cells=T, na.rm=T) xy <- xyFromCell(inca_r, inca_sample[, 1]) xy_sp <- SpatialPoints(xy, CRS(proj4_modis_sin)) xy_sp_latlon <- spTransform(xy_sp, CRS(proj4_latlon)) # Extract values across all years and all phenometrics at the sample locations # create a large long form data.table of the results # gather and sort input files in_files <- dir(data_dir, patt=paste("MCD12.*", tile, ".*hdf$", sep=""), full=T, rec=T) in_years <- as.integer(gsub(".*A([0-9]{4})001.*$", "\\1", basename(in_files))) # get data years from file name in_files <- in_files[order(in_years)] in_years <- sort(in_years) # create a cluster, use individual threads to fully process a single year (MCD12Q2 HDF file) cl <- makeCluster(8) clusterExport(cl, c("GetSample", "GetSDS", "GetMetricSample", "GetSDSQ1")) clusterEvalQ(cl, {library(raster); library(data.table)}) system.time(all_years <- parLapply(cl, in_files, GetSample, pt_sp=xy_sp)) # rbind all the output into one large data.table for this tile and write to disk DTfinal <- do.call(rbind, all_years) out_file <- file.path(output_dir, paste("GlobalPhenoSample_", tile, ".Rdata", sep="")) save(DTfinal, file=out_file) #------------------------------- # check if we need to resubmit # allRdata <- dir("/rsstu/users/j/jmgray2/SEAL/INCA/GlobalPhenoSample", pattern="*.Rdata") # all_tiles <- c("h08v04", "h09v04", "h10v04", "h11v04", "h12v04", "h13v04", "h08v05", "h09v05", "h10v05", "h11v05", "h12v05", "h08v06", "h09v06", "h10v06", "h00v08", "h00v09", "h00v10", "h01v08", "h01v09", "h01v10", "h01v11", "h02v06", "h02v08", "h02v09", "h02v10", "h02v11", "h03v06", "h03v07", "h03v09", "h03v10", "h03v11", "h04v09", "h04v10", "h04v11", "h05v10", "h05v11", "h05v13", "h06v03", "h06v11", "h07v03", "h07v05", "h07v06", "h07v07", "h08v03", "h08v07", "h08v08", "h08v09", "h09v02", "h09v03", "h09v07", "h09v08", "h09v09", "h10v02", "h10v03", "h10v07", "h10v08", "h10v09", "h10v10", "h10v11", "h11v02", "h11v03", "h11v06", "h11v07", "h11v08", "h11v09", "h11v10", "h11v11", "h11v12", "h12v01", "h12v02", "h12v03", "h12v07", "h12v08", "h12v09", "h12v10", "h12v11", "h12v12", "h12v13", "h13v01", "h13v02", "h13v03", "h13v08", "h13v09", "h13v10", "h13v11", "h13v12", "h13v13", "h13v14", "h14v01", "h14v02", "h14v03", "h14v04", "h14v09", "h14v10", "h14v11", "h14v14", "h14v16", "h14v17", "h15v01", "h15v02", "h15v03", "h15v05", "h15v07", "h15v11", "h15v14", "h15v15", "h15v16", "h15v17", "h16v00", "h16v01", "h16v02", "h16v05", "h16v06", "h16v07", "h16v08", "h16v09", "h16v12", "h16v14", "h16v16", "h16v17", "h17v00", "h17v01", "h17v02", "h17v03", "h17v04", "h17v05", "h17v06", "h17v07", "h17v08", "h17v10", "h17v12", "h17v13", "h17v15", "h17v16", "h17v17", "h18v00", "h18v01", "h18v02", "h18v03", "h18v04", "h18v05", "h18v06", "h18v07", "h18v08", "h18v09", "h18v14", "h18v15", "h18v16", "h18v17", "h19v00", "h19v01", "h19v02", "h19v03", "h19v04", "h19v05", "h19v06", "h19v07", "h19v08", "h19v09", "h19v10", "h19v11", "h19v12", "h19v15", "h19v16", "h19v17", "h20v01", "h20v02", "h20v03", "h20v04", "h20v05", "h20v06", "h20v07", "h20v08", "h20v09", "h20v10", "h20v11", "h20v12", "h20v13", "h20v15", "h20v16", "h20v17", "h21v01", "h21v02", "h21v03", "h21v04", "h21v05", "h21v06", "h21v07", "h21v08", "h21v09", "h21v10", "h21v11", "h21v13", "h21v15", "h21v16", "h21v17", "h22v01", "h22v02", "h22v03", "h22v04", "h22v05", "h22v06", "h22v07", "h22v08", "h22v09", "h22v10", "h22v11", "h22v13", "h22v14", "h22v15", "h22v16", "h23v01", "h23v02", "h23v03", "h23v04", "h23v05", "h23v06", "h23v07", "h23v08", "h23v09", "h23v10", "h23v11", "h23v15", "h23v16", "h24v02", "h24v03", "h24v04", "h24v05", "h24v06", "h24v07", "h24v12", "h24v15", "h25v02", "h25v03", "h25v04", "h25v05", "h25v06", "h25v07", "h25v08", "h25v09", "h26v02", "h26v03", "h26v04", "h26v05", "h26v06", "h26v07", "h26v08", "h27v03", "h27v04", "h27v05", "h27v06", "h27v07", "h27v08", "h27v09", "h27v10", "h27v11", "h27v12", "h27v14", "h28v03", "h28v04", "h28v05", "h28v06", "h28v07", "h28v08", "h28v09", "h28v10", "h28v11", "h28v12", "h28v13", "h28v14", "h29v03", "h29v05", "h29v06", "h29v07", "h29v08", "h29v09", "h29v10", "h29v11", "h29v12", "h29v13", "h30v05", "h30v06", "h30v07", "h30v08", "h30v09", "h30v10", "h30v11", "h30v12", "h30v13", "h31v06", "h31v07", "h31v08", "h31v09", "h31v10", "h31v11", "h31v12", "h31v13", "h32v07", "h32v08", "h32v09", "h32v10", "h32v11", "h32v12", "h33v07", "h33v08", "h33v09", "h33v10", "h33v11", "h34v07", "h34v08", "h34v09", "h34v10", "h35v08", "h35v09", "h35v10") # allRdata_tiles <- gsub(".*(h[0-9]{2}v[0-9]{2}).*","\\1", allRdata) # resub_tiles <- all_tiles[!c(all_tiles %in% allRdata_tiles)]
a54dc682934a895bbdb48991fcdf88a2d8eb2e4f
6292a37c62159e1ec96200c61fd5e5bd0ce03c2e
/dsia_demo_codes/ch0607.R
c4853a8d098c85252234203e88ee279f577bf270
[]
no_license
jtlai0921/AEL018600_codes
5270eb9bc11acc653f1ba24ff1f6eee340625eb5
1e4267ea82b75a2c9d57f92edfbc5e8f5a429dbf
refs/heads/master
2020-12-18T18:07:52.593639
2020-01-22T01:55:00
2020-01-22T01:55:00
235,479,335
0
0
null
null
null
null
UTF-8
R
false
false
67
r
ch0607.R
arr <- c(11, 12, 13, 14, 15) arr[3] <- 87 # 將 13 更換為 87 arr
426465e197a42645ebb3d260de0d2ba331e35fe1
4c43ba1d8985c586bf213fcb6258dca5cb1a6202
/code/elliptical_shiny.R
5e896d7d563cc0699e6b3fb933981749d0766fab
[]
no_license
kkemper/data_dashboard
d1996108b20ab1d67fcd2c54ba695c57c2ddafa7
deda7ff2296ff5320097c5653b4a7f5f1fb41bfa
refs/heads/master
2022-03-16T22:29:18.793162
2019-08-19T16:59:16
2019-08-19T16:59:16
184,115,561
0
0
null
null
null
null
UTF-8
R
false
false
291
r
elliptical_shiny.R
library(shiny) library(airtabler) library(dplyr) Sys.setenv("AIRTABLE_API_KEY"="<Your API key") #example key************** airtable <- airtabler::airtable("<base key>", "<Tab/sheet name>") ui <- fluidPage( ) server <- function(input, output) {} shinyApp(ui = ui, server = server)
44a0005ee10469e70bfad21ed27bbe94ba793d3f
2d7b0674a00f24f3e5b0744b2e5290798fa798cc
/IronBrain/OldVersion/FerricChloride+Cytotoxic_WST-1_logistic.R
ebe939f0270c44e938da02b1e5e33bc7e408b350
[]
no_license
KJKwon/Lab_project
48081fabe860781a00b9d70686b3ca4c334243a9
f60232df2977a5ec222ffa37f500304b360ffd31
refs/heads/master
2022-09-02T12:42:33.897989
2022-06-15T07:52:42
2022-06-15T07:52:42
69,477,714
0
0
null
null
null
null
UTF-8
R
false
false
3,677
r
FerricChloride+Cytotoxic_WST-1_logistic.R
library(ggplot2) library(reshape2) library(minpack.lm) library(drc) #Iron related gene error bar tbl = read.table('SH-SY5Y_IronToxicityTest_FeCl2_24h_WST-1_results.csv',sep='\t',row.names = 1, header = TRUE) tbl = apply(t(tbl),1,function(x){(x/tbl[,1])*100}) val.Mean = apply(tbl,2,mean) val.Mean = c(as.numeric(val.Mean)) #Calculate standard error val.se = apply(tbl,2,function(x){sd(x)/sqrt(length(rownames(tbl)))}) val.se = c(as.numeric(val.se)) tbl.dot = tbl #Melt table for ggplot2 plotting tbl.dotplot = melt(tbl.dot) tbl.dotplot$variable = rep(c(0,100,200,500,1000,2000,5000,10000), times = 1, each = length(rownames(tbl))) #Synchronize plot name to dotplot variable name tbl.new = t(data.frame(val.Mean)) tbl.plot = melt(tbl.new) tbl.plot$variable = c(0,100,200,500,1000,2000,5000,10000) tbl.plot$se = val.se tbl.plot = tbl.plot[,3:5] colnames(tbl.plot) = c('variable', 'value', 'se') p = ggplot(tbl.plot,aes(x = log10(value+1), y = variable)) + geom_line() + geom_point(aes(x = log10(variable+1) , y = value), tbl.dotplot)+ geom_errorbar(aes(ymin = variable - se, ymax = variable + se))+ theme(text = element_text(size = 15), legend.title = element_blank())+ xlab('log(FeCl2) uM') + ylab('Absorbance(450nm-690nm)') plot(p) ##Test_set p = ggplot() + geom_point(aes(x = log10(variable+1), y = value),tbl.dotplot)+ # geom_smooth(data= tbl.dotplot, aes(x = log10(variable+1), y = value), method = 'nls' , # formula = y ~ f(x,xmid,scal), method.args = list(start=c(xmid = 3.4910, scal = -0.6797)),se = FALSE) + geom_smooth(data = tbl.dotplot, aes(x = log10(variable+1), y = value), method = 'auto', se = F)+ geom_errorbar(aes(x = log10(value+1), ymin = variable - se, ymax = variable + se), tbl.plot)+ #panel design part theme(text = element_text(size = 15), legend.title = element_blank(), panel.background = element_blank(), panel.border = element_blank(), panel.grid.minor = element_blank(), axis.line = element_line(size = 1, colour = 'black'), axis.text.x = element_text(colour = 'black', size = 15), axis.text.y = element_text(colour = 'black', size = 15))+ xlab('log(FeCl2) uM') + ylab('% WST-1 Absorbance\n(compared to control)') + scale_y_continuous(breaks=c(0,25,50,75,100), limits = c(0,100))+ annotation_logticks(sides = 'b') plot(p) ##geom_point = scatter_plot, geom_errorbar = error_bar p = ggplot() + geom_point(aes(x = log10(variable+1), y = value),tbl.dotplot)+ geom_smooth(data= tbl.dotplot, aes(x = log10(variable+1), y = value), method = 'nls' , formula = y ~ SSlogis(x, Asym, xmid, scal), se = FALSE) + geom_errorbar(aes(x = log10(value+1), ymin = variable - se, ymax = variable + se), tbl.plot)+ #panel design part theme(text = element_text(size = 15), legend.title = element_blank(), panel.background = element_blank(), panel.border = element_blank(), panel.grid.minor = element_blank(), axis.line = element_line(size = 1, colour = 'black'), axis.text.x = element_text(colour = 'black', size = 15), axis.text.y = element_text(colour = 'black', size = 15))+ xlab('log(FeCl2) uM') + ylab('% WST-1 Absorbance\n(compared to control)') + scale_y_continuous(breaks=c(0,25,50,75,100,125), limits = c(0,125))+ annotation_logticks(sides = 'b') #scale_y_continuous(breaks = seq(0,125,25)) plot(p) ggsave(file = "200401_Iron_treat_suction_SH-SY5Y_WST-1_original.pdf", plot = last_plot(), width = 8, height = 6, units = c("in"), device = pdf()) dev.off()
e6cc865481a34ed126855badac8863330c34aeef
50dd2db2c197a76edfca7f5bb96439b36bfbc750
/R/mdev_distance_function(MDEV_DISTANCE).R
9dc09b78c8b67cb288e4b64fbececf16ca30d343
[]
no_license
absuag/dreaweRTools
1dbe6f00b8828bbbc84e21f687d794a3314e4506
583835604b3318d43ae75e36c73b0c71f2b926be
refs/heads/master
2022-04-09T23:52:11.174939
2020-03-12T12:16:53
2020-03-12T12:16:53
null
0
0
null
null
null
null
UTF-8
R
false
false
411
r
mdev_distance_function(MDEV_DISTANCE).R
#' Mean deviation distance #' #' Function to calculate mean deviation distances #' Output: A vector containing mean deviation distances from each point in given vector #' #' @param attr A vector of numeric values #' #' #' @return #' @export #' #' @examples #' MDEV_DISTANCE() MDEV_DISTANCE <- function(attr){ tmpMean <- mean(attr) tmpDev <- MDEV(attr) ret <- (attr - tmpMean)/tmpDev return(ret) }
be3c2b1438309453d625ced3551eafc00aaedaa3
ce55955fd4189ada9e35696d5cb7589e18eea266
/data-raw/prepare-data.R
423d16d3ca2eb5cc854941207939853ec67d41e1
[ "MIT" ]
permissive
laurafdeza/phon
1adec6d4b3a744b521048564c28bcca3b13ff10a
2e169a9f9ac3f0253f45d2e1b6be008715bdbb1d
refs/heads/master
2020-04-29T20:47:11.062654
2018-12-09T12:55:54
2018-12-09T12:55:54
null
0
0
null
null
null
null
UTF-8
R
false
false
2,456
r
prepare-data.R
suppressPackageStartupMessages({ library(dplyr) library(purrr) }) # This package uses the CMU Pronouncing Dictionary. # See: # http://www.speech.cs.cmu.edu/cgi-bin/cmudict # http://svn.code.sf.net/p/cmusphinx/code/trunk/cmudict/ #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Raw cmu dictionary #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ cmu_raw <- readLines(here::here("data-raw", "cmudict-0.7b.txt"), encoding = 'UTF-8') #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Remove the cruft at the top of the file #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ cmu_raw <- cmu_raw[-(1:56)] #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # parse into usable R structure - a matrix of characters # - column 1: the words # - column 2: string representing the ARPABET phonetic codes #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ cmu_mat <- stringr::str_split(cmu_raw, "\\s+", n=2L, simplify = TRUE) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Convert the first column into a list of lowercase words. # Some words are included multiple times to indicate alternate pronunciations. # e.g. if 'xxx' has 2 pronunciations, the first is 'xxx' and the second # is 'xxx(1)'. # Going to remove all the "(N)" suffixes from the words #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ cmu_words <- cmu_mat[,1] cmu_words[35418] <- 'DJ' cmu_words <- stringr::str_to_lower(gsub("\\(.*?\\)", "", cmu_words)) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # A single string oh phonemes per word #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ cmu_phons_orig <- cmu_mat[,2] #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Internal data representation #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ cmudict <- setNames(cmu_phons_orig, cmu_words) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Save all the internal data #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ usethis::use_data(cmudict, internal = FALSE, overwrite = TRUE, compress = 'xz') file.size(here::here("data/cmudict.rda"))
699264698a5a2756666b8bdb58e01371ef84e437
232c8b0213342e9e973ec8ffb695743759ee89b3
/man/make.refFn.Rd
2808846466a300003a7e81a60a92a34fb908fe0a
[]
no_license
uyedaj/bayou
304c98ba9516fb91688b345fb33c9a41765d06cd
b623758bf7b08900e2cd60c9247c2650b564d06b
refs/heads/master
2021-07-05T03:02:21.376172
2021-05-10T14:51:11
2021-05-10T14:51:11
21,963,529
19
10
null
2019-11-06T18:58:40
2014-07-18T01:29:03
HTML
UTF-8
R
false
true
1,698
rd
make.refFn.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/bayou-steppingstone.R \name{make.refFn} \alias{make.refFn} \title{Make a reference function in bayou} \usage{ make.refFn(chain, model, priorFn, burnin = 0.3, plot = TRUE) } \arguments{ \item{chain}{An mcmc chain produced by \code{bayou.mcmc()} and loaded with \code{load.bayou()}} \item{model}{A string specifying the model ("OU", "QG", "OUrepar") or a model parameter list} \item{priorFn}{The prior function used to generate the mcmc chain} \item{burnin}{The proportion of the mcmc chain to be discarded when generating the reference function} \item{plot}{Logical indicating whether or not a plot should be created} } \value{ Returns a reference function of class "refFn" that takes a parameter list and returns the log density given the reference distribution. If \code{plot=TRUE}, a plot is produced showing the density of variable parameters and the fitted distribution from the reference function (in red). } \description{ This function generates a reference function from a mcmc chain for use in marginal likelihood estimation. } \details{ Distributions are fit to each mcmc chain and the best-fitting distribution is chosen as the reference distribution for that parameter using the method of Fan et al. (2011). For positive continuous parameters \code{alpha, sigma^2, halflife, Vy, w2, Ne}, Log-normal, exponential, gamma and weibull distributions are fit. For continuous distributions \code{theta}, Normal, Cauchy and Logistic distributions are fit. For discrete distributions, \code{k}, negative binomial, poisson and geometric distributions are fit. Best-fitting distributions are determined by AIC. }
d60b8470cc7fea0b82ba311537c3cf6c4929f78f
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/madrat/examples/fingerprint.Rd.R
674b4826bc13cd1e24d39803d43d8e5da821a1ce
[]
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
171
r
fingerprint.Rd.R
library(madrat) ### Name: fingerprint ### Title: Tool: fingerprint ### Aliases: fingerprint ### ** Examples ## Not run: ##D fingerprint(".",ls,c) ## End(Not run)
ebf03b4b7ab21f9349143497caed705447291b62
089f28e1e03609dcd9fac4065e26d11d3359a0f3
/Work/Cleaning_Week2.R
b993025de0662c9d2b3d6b6f9c884da86ec79e16
[]
no_license
themp731/datasciencecoursera
8371f124617588205e7daa4089bab49af4d61907
c363749ef94eda0f6507ebc10f1cfb1ef4638fe0
refs/heads/master
2020-04-09T19:16:52.921598
2016-10-10T19:35:33
2016-10-10T19:35:33
62,075,087
0
0
null
null
null
null
UTF-8
R
false
false
1,425
r
Cleaning_Week2.R
"This is connecting to a mySql DB" library("RMySQL") ucscDb <- dbConnect(MySQL(),user="genome", host="genome-mysql.cse.ucsc.edu") result <- dbGetQuery(ucscDb,"show databases;"); dbDisconnect(ucscDb) result "The result is all the databases" #We're interested in hg19 hg19 <- dbConnect(MySQL(), user="genome", db = "hg19", host = "genome-mysql.cse.ucsc.edu") allTables <- dbListTables(hg19) length(allTables) #Getting dimensions of a table takes us to get fields form a table dbListFields(hg19, "affyU133Plus2") dbGetQuery(hg19, "select count(*) from affyU133Plus2") #Returning the data we want affyData <- dbReadTable(hg19, "affyU133Plus2") query <- dbSendQuery(hg19, "select * from affyU133Plus2 where misMatches between 1 and 3") affyMis <- fetch(query) quantile(affyMis$misMatches) #You need to clear your queries when you're done dbDisconnect(hg19) "HDF5 databases" #This is useful for downloading tons of large; #hierarchical data sets. "Reading Data from the Web" #This is good web scraping etc. # getting open a connection con <- url("http://scholar.google.com/citations?user=HI-I6C0AAAAJ&hl=en") #reading lines htmlCode = readLines(con) # but this is kind of annoying, so we can move it to read in XML library(XML) url <- "http://scholar.google.com/citations?user=HI-I6C0AAAAJ&hl=en" html <- htmlTreeParse(url, useInternalNodes = TRUE) close(con) #Or using the get Comand
e01c8eeac678fc73ea930593703bc0f07cdfe81e
1a058815dc84cf41ed87efc68feba6ddbf511b92
/diets.R
eaa30f92618b9067ba0d648ad30ab0c4419f3be4
[ "MIT" ]
permissive
JPGibert/Foodweb_thermal_asymmetries
f1e1ee241ead4eb473190284aa2da2134814ec43
76a7629b979b080a82a2c1155fc69bdbd4872528
refs/heads/master
2023-04-14T03:34:18.282452
2022-05-17T15:03:25
2022-05-17T15:03:25
246,418,052
1
0
null
null
null
null
UTF-8
R
false
false
13,855
r
diets.R
library(tidyverse) #mammal mortality data #mammal diet data mammal_diet0 <- read_tsv('/Users/jgradym/Google Drive/Gibert Paper/Data/Diet/Mammals/doi_10.5061_dryad.6cd0v__v1/MammalDIET_v1.0.txt') mammal_diet1 <- mammal_diet0 %>% mutate(Species = paste(Genus, Species, sep = "_")) %>% select(Species, TrophicLevel) unique(mammal_diet1$TrophicLevel) mammal_diet1$trophic_level <- NA mammal_diet1$trophic_level[mammal_diet1$TrophicLevel == "Herbivore"] <- 2 mammal_diet1$trophic_level[mammal_diet1$TrophicLevel == "Carnivore"] <- 3 mammal_diet1$trophic_level[mammal_diet1$TrophicLevel == "Omnivore"] <- 2.5 mammal_diet1$trophic_level[mammal_diet1$TrophicLevel == "NotAssigned"] <- NA mammal_diet1 #combine with mortality mortality0 <- read_csv(file.path(gdrive_path,'McCoy_mortality_updated.csv')) mammal_mort0 <- mortality0 %>% filter(Group == "Mammal") mammal_mort <- left_join(mammal_mort0, mammal_diet1, by = "Species") mammal_mort$Genus <- word(mammal_mort$Species, 1, sep = "_") missing_mamm <- mammal_mort[is.na(mammal_mort$trophic_level),] missing_mamm_gen <- word(missing_mamm$Species, 1, sep = "_") unique(missing_mamm_gen ) #manual fix mammal_mort$trophic_level[mammal_mort$Species == "Vulpes_lagopus"] <- 3 mammal_mort$trophic_level[mammal_mort$Genus == "Arctocephalus"] <- 4 mammal_mort$trophic_level[mammal_mort$Genus == "Balaena"] <- 3 mammal_mort$trophic_level[mammal_mort$Genus == "Balaenoptera"] <- 3 mammal_mort$trophic_level[mammal_mort$Genus == "Berardius"] <- 4.5 mammal_mort$trophic_level[mammal_mort$Genus == "Sapajus"] <- 2.5 mammal_mort$trophic_level[mammal_mort$Genus == "Callorhinus"] <- 4 mammal_mort$trophic_level[mammal_mort$Genus == "Cephalorhynchus"] <- 4 mammal_mort$trophic_level[mammal_mort$Genus == "Cystophora"] <- 4 mammal_mort$trophic_level[mammal_mort$Genus == "Delphinapterus"] <- 4 mammal_mort$trophic_level[mammal_mort$Genus == "Delphinus"] <- 4 mammal_mort$trophic_level[mammal_mort$Genus == "Dugong"] <- 2 mammal_mort$trophic_level[mammal_mort$Genus == "Erignathus"] <- 3.5 mammal_mort$trophic_level[mammal_mort$Genus == "Eschrichtius"] <- 3 mammal_mort$trophic_level[mammal_mort$Genus == "Eumetopias"] <- 4 mammal_mort$trophic_level[mammal_mort$Genus == "Halichoerus"] <- 3 mammal_mort$trophic_level[mammal_mort$Genus == "Hydrurga"] <- 4.5 mammal_mort$trophic_level[mammal_mort$Genus == "Hyperoodon"] <- 4.5 mammal_mort$trophic_level[mammal_mort$Genus == "Lagenorhynchus"] <- 4 mammal_mort$trophic_level[mammal_mort$Genus == "Lobodon"] <- 3 mammal_mort$trophic_level[mammal_mort$Genus == "Megaptera"] <- 3 mammal_mort$trophic_level[mammal_mort$Genus == "Mirounga"] <- 4.5 mammal_mort$trophic_level[mammal_mort$Genus == "Monodon"] <- 4 mammal_mort$trophic_level[mammal_mort$Genus == "Neophocaena"] <- 4 mammal_mort$trophic_level[mammal_mort$Genus == "Odobenus"] <- 3 mammal_mort$trophic_level[mammal_mort$Genus == "Orcinus"] <- 4.5 mammal_mort$trophic_level[mammal_mort$Genus == "Otaria"] <- 4 mammal_mort$trophic_level[mammal_mort$Genus == "Pusa"] <- 4 mammal_mort$trophic_level[mammal_mort$Genus == "Peponocephala"] <- 4 mammal_mort$trophic_level[mammal_mort$Genus == "Histriophoca"] <- 4 mammal_mort$trophic_level[mammal_mort$Genus == "Pagophilus"] <- 4 mammal_mort$trophic_level[mammal_mort$Genus == "Phoca"] <- 4 mammal_mort$trophic_level[mammal_mort$Genus == "Phocoena"] <- 4 mammal_mort$trophic_level[mammal_mort$Genus == "Phocoenoides"] <- 4 mammal_mort$trophic_level[mammal_mort$Genus == "Physeter"] <- 5 mammal_mort$trophic_level[mammal_mort$Genus == "Pontoporia"] <- 4 mammal_mort$trophic_level[mammal_mort$Genus == "Pseudorca"] <- 4.5 mammal_mort$trophic_level[mammal_mort$Genus == "Leontocebus"] <- 2.5 mammal_mort$trophic_level[mammal_mort$Genus == "Stenella"] <- 4 mammal_mort$trophic_level[mammal_mort$Genus == "Trichechus"] <- 2 mammal_mort$trophic_level[mammal_mort$Genus == "Tursiops"] <- 4 mammal_mort$trophic_level[mammal_mort$Genus == "Zalophus"] <- 4 mammal_mort[is.na(mammal_mort$trophic_level),] #---- birds bird_diet0 <- read_csv('/Users/jgradym/Google Drive/Gibert Paper/Data/Diet/Birds/41559_2019_1070_MOESM3_ESM.csv') unique(bird_diet0$TrophicLevel) bird_diet1 <- bird_diet0 %>% rename(Species = Binomial) %>% select(Species, TrophicLevel) bird_diet1$trophic_level <- NA bird_diet1$trophic_level[bird_diet1$TrophicLevel == "Herbivore"] <- 2 bird_diet1$trophic_level[bird_diet1$TrophicLevel == "Carnivore"] <- 3 bird_diet1$trophic_level[bird_diet1$TrophicLevel == "Omnivore"] <- 2.5 bird_diet1$trophic_level[bird_diet1$TrophicLevel == "Scavenger"] <- 2 #combine bird_mort0 <- mortality0 %>% filter(Group == "Bird") bird_mort <- left_join(bird_mort0 , bird_diet1, by = "Species") bird_mort bird_mort[is.na(bird_mort$trophic_level),] #-------- invertebrates invert_mort0 <- mortality0 %>% filter(Group == "Invertebrate") invert_genera <- as_tibble(unique(word(invert_mort0$Species), 1, sep = "_")) invert_genera <- invert_genera %>% rename(genera = value) write_csv(invert_genera, '~/Desktop/invert_genera.csv') invert_diet <- read_csv('/Users/jgradym/Google Drive/Gibert Paper/Data/Diet/invert_diet.csv') invert_mort0$genus <- word(invert_mort0$Species, 1, sep = " ") invert_mort <- left_join(invert_mort0, invert_diet, by= "genus") #fish fish_mort0 <- mortality0 %>% filter(Group == "Fish") #234 fish_genera <- unique(word(fish_mort0$Species, 1, sep = " ")) fish_spp <- fish_mort0$Species write.csv(fish_genera, "~/Desktop/fish_genera.csv") write.csv(fish_spp, "~/Desktop/fish_spp.csv") library(rfishbase) library(taxize) fish0 <- species_list(Class = "Actinopterygii") fish1 <- fish0[fish0 %in% fish_spp] missing_fish <- fish_mort0 %>% filter(Species %nin% fish0) #write_csv(missing_fish, "~/Desktop/missing_fish.csv") #manual fixes fish_mort1 <- fish_mort0 fish_mort1$Species[fish_mort1$Species == "Clupea pallassii"] <- "Clupea pallasii" fish_mort1$Species[fish_mort1$Species == "Restrelliger kanagurta"] <- "Rastrelliger kanagurta" fish_mort1$Species[fish_mort1$Species == "Restrelliger neglectus"] <- "Rastrelliger neglectus" fish_mort1$Species[fish_mort1$Species == "Lethrinops longispinis"] <- "Lethrinops longipinnis" fish_mort1$Species[fish_mort1$Species == "Pseudopeneus maculatus"] <- "Pseudupeneus maculatus" fish_mort1$Species[fish_mort1$Species == "Sebastes paucispinus"] <- "Sebastes paucispinis" fish_mort1$Species[fish_mort1$Species == "Bathylagus milleri"] <- "Pseudobathylagus milleri" fish_mort1$Species[fish_mort1$Species == "Blennius pholis"] <- "Lipophrys pholis" fish_mort1$Species[fish_mort1$Species == "Clupea pallasii"] <- "Clupea pallasii pallasii" fish_mort1$Species[fish_mort1$Species == "Cynoglossus macrolepidus"] <- "Cynoglossus arel" fish_mort1$Species[fish_mort1$Species == "Cynolebias adloffi"] <- "Austrolebias adloffi" fish_mort1$Species[fish_mort1$Species == "Engraulis encrasicholus"] <- "Engraulis encrasicolus" fish_mort1$Species[fish_mort1$Species == "Gadus minimus"] <- "Raniceps raninus" fish_mort1$Species[fish_mort1$Species == "Gadus minutus"] <- "Trisopterus minutus" fish_mort1$Species[fish_mort1$Species == "Gadus minitus"] <- "Trisopterus minutus" fish_mort1$Species[fish_mort1$Species == "Haemulon plumieri"] <- "Haemulon plumierii" fish_mort1$Species[fish_mort1$Species == "Haplochromis anaphyrmus"] <- "Mylochromis anaphyrmus" fish_mort1$Species[fish_mort1$Species == "Haplochromis mloto"] <- "Copadichromis mloto" fish_mort1$Species[fish_mort1$Species == "Lampanyctus regalis"] <- "Nannobrachium regale" fish_mort1$Species[fish_mort1$Species == "Leiognathus splendens"] <- "Eubleekeria splendens" fish_mort1$Species[fish_mort1$Species == "Leucichthys artedi"] <- "Coregonus artedi" fish_mort1$Species[fish_mort1$Species == "Leucichthys sardinella"] <- "Coregonus sardinella" fish_mort1$Species[fish_mort1$Species == "Lithrinus enigmaticus"] <- "Lethrinus enigmaticus" fish_mort1$Species[fish_mort1$Species == "Merluccius gayi"] <- "Merluccius gayi gayi" fish_mort1$Species[fish_mort1$Species == "Nemipterus bleekeri"] <- "Nemipterus bipunctatus" fish_mort1$Species[fish_mort1$Species == "Nemipterus delagoe"] <- "Nemipterus bipunctatus" fish_mort1$Species[fish_mort1$Species == "Nemipterus tolu"] <- "Nemipterus peronii" fish_mort1$Species[fish_mort1$Species == "Pneumatophorus japonicus"] <- "Scomber japonicus" fish_mort1$Species[fish_mort1$Species == "Pseudosciaena diacanthus"] <- "Protonibea diacanthus" fish_mort1$Species[fish_mort1$Species == "Rastrelliger neglectus"] <- "Rastrelliger brachysoma" fish_mort1$Species[fish_mort1$Species == "Sardinops caerrula"] <- "Sardinops sagax" fish_mort1$Species[fish_mort1$Species == "Sardinops melanosticta"] <- "Sardinops sagax " fish_mort1$Species[fish_mort1$Species == "Sebastes dalli"] <- "Sebastes dallii" fish_mort1$Species[fish_mort1$Species == "Sebastes jorani"] <- "Sebastes jordani" fish_mort1$Species[fish_mort1$Species == "Sebastes paucipinis"] <- "Sebastes paucispinis" fish_mort1$Species[fish_mort1$Species == "Sebastes ruberrinus"] <- "Sebastes ruberrimus" fish_mort1$Species[fish_mort1$Species == "Soela vulgaris"] <- "Solea solea" fish_mort1$Species[fish_mort1$Species == "Stizostedion canadensis"] <- "Sander canadensis" fish_mort1$Species[fish_mort1$Species == "Thunnus germo"] <- "Thunnus alalunga" fish_mort1$Species[fish_mort1$Species == "Thunnus alaunga"] <- "Thunnus alalunga" fish_mort1$Species[fish_mort1$Species == "Thunnus macoyi"] <- "Thunnus maccoyii" fish_mort1$Species[fish_mort1$Species == "Tracharus japonicus"] <- "Trachurus japonicus" fish_mort1$Species[fish_mort1$Species == "Tilapia esculenta"] <- "Oreochromis esculentus" fish_mort1$Species[fish_mort1$Species == "Cheilodactylus macropterus"] <- "Nemadactylus macropterus" fish_mort1$Species[fish_mort1$Species == "Cynolebias bellottii"] <- "Austrolebias bellottii" fish_mort1$Species[fish_mort1$Species == "Cynoscion macdonaldi"] <- "Totoaba macdonaldi" fish_mort1$Species[fish_mort1$Species == "Cynoscion nobilis"] <- "Atractoscion nobilis" fish_mort1$Species[fish_mort1$Species == "Cynolebias wolterstarfii"] <- "Austrolebias wolterstorffi" fish_mort1$Species[fish_mort1$Species == "Sardinops sagax "] <- "Sardinops sagax" fish_mort1$Species[fish_mort1$Species == "Acipsnser fulvescens"] <- "Acipenser fulvescens" fish_mort1$Species[fish_mort1$Species == "Aphinius fasciatus"] <- "Aphanius fasciatus" fish_mort1$Species[fish_mort1$Species == "Centengraulis mysticetus"] <- "Cetengraulis mysticetus" fish_mort1$Species[fish_mort1$Species == "Cololabis aira"] <- "Cololabis saira" fish_mort1$Species[fish_mort1$Species == "Coryphaennoides acrolepis"] <- "Coryphaenoides acrolepis" fish_mort1$Species[fish_mort1$Species == "Chelodactylus macropterus"] <- "Nemadactylus macropterus" fish_mort1$Species[fish_mort1$Species == "Pseudoupeneus macularus"] <- "Pseudupeneus maculatus" fish_mort2 <- fish_mort1 fish_mort2$TL <- estimate(fish_mort2$Species)$Troph fish_mort2$Species[is.na(fish_mort2$TL)] #combine mortality fish_mort_fin <- fish_mort2 %>% rename(trophic_level = TL) fish_mort_fin$type <- NA fish_mort_fin$TrophicLevel <- NA invert_mort$genus <- NULL invert_mort$TrophicLevel <- NA invert_mort$TrophicLevel <- as.character(invert_mort$TrophicLevel ) mammal_mort$Genus <- NULL mammal_mort <- mammal_mort %>% rename(TrophicLevel = trophic_level) endo_mort <- rbind(mammal_mort, bird_mort) endo_mort$type <- NA mort_TL <- rbind(endo_mort, invert_mort, fish_mort_fin) write_csv(mort_TL, "~/Desktop/mortality_TL.csv" ) #attack rates attack <- read_csv(file.path(gdrive_path, 'Lietal_oikos_2017_data.csv')) %>% select(predator.ana.group, predator.species, predator.mass.mg, temperature.degree.celcius, attack.rate, everything() ) %>% arrange(predator.ana.group, predator.species, attack.rate) %>% mutate(index = 1:451) attack_verts <- attack %>% filter(predator.ana.group == "vertebrate") %>% select(predator.species) %>% rename(Species = predator.species) attack_verts$TL <- estimate(attack_verts$Species)$Troph missing_attack_vert <- unique(attack_verts$Species[is.na( attack_verts$TL)]) missing_attack_vert attack_verts$Species[attack_verts$Species == "Brachydanio rerio"] <- "Danio rerio" attack_verts$Species[attack_verts$Species == "Perca fluviatilis"] <- "Perca fluviatilis" attack_verts$TL <- estimate(attack_verts$Species)$Troph attack_verts$pred_type <- NA attack_verts$pred_type <- as.character(attack_verts$pred_type) attack_verts_TL <- attack_verts %>% rename(predator.species = Species) #Attack invertebrates attack_inverts <- attack %>% filter(predator.ana.group == "invertebrate") %>% select(predator.species) attack_invert_spp <- unique(attack_inverts$Species) write.csv(unique(attack_inverts$Species), "~/Desktop/attack_invert_spp_new.csv") attack_invert_TL0 <- read_csv('~/Desktop/attack_invert_spp.csv') %>% rename(predator.species = Species) attack_invert_TL <- left_join(attack_inverts, attack_invert_TL0 , by = "predator.species") attack_TL0 <- as_tibble(rbind(attack_invert_TL, attack_verts_TL)) %>% mutate(index = 1:451) # Together attack_TL <- left_join(attack, attack_TL0, by = "index") %>% select(TL, predator.ana.group, pred_type, everything()) write_csv(attack_TL, "~/Desktop/attack_TL.csv" ) mort_Ea <- mortality %>% filter(temp_range_genus >= 5, n_genus >= 5) %>% nest(-Genus) %>% # the group variable mutate( fit = map(data, ~ lm(log(mass_corr_mortality) ~ one_kT , data = .x)), #this is a regression (y = attack.rate, x = one_kT), but you could adapt to whatever tidied = map(fit, tidy) ) %>% unnest(tidied) attack_Ea <- mortality %>% filter(temp_range_genus >= 5, n_genus >= 5) %>% nest(-Genus) %>% # the group variable mutate( fit = map(data, ~ lm(log(mass_corr_mortality) ~ one_kT , data = .x)), #this is a regression (y = attack.rate, x = one_kT), but you could adapt to whatever tidied = map(fit, tidy) ) %>% unnest(tidied)
7509fb0963ac018dcce01b346228aa218b8fdd49
3b337766cdaa82787e0e1a188c0bbb84dae96e41
/MechaCar_Challenge.RScript.R
e3a7926666e9b279b8688164c143a797a889fb58
[]
no_license
ConorMcGrew/MechaCar_Statistical_Analysis
80aa7d1474ed17fa2647a0814881919dbdf9103b
da874cbd452976b6ce3f4ad6d24ba2b8286cd5ca
refs/heads/main
2023-06-06T23:30:48.665143
2021-06-28T03:43:07
2021-06-28T03:43:07
380,807,570
0
0
null
null
null
null
UTF-8
R
false
false
1,069
r
MechaCar_Challenge.RScript.R
library(dplyr) MPGdataframe <- read.csv(file='MechaCar_mpg.csv', stringsAsFactors = FALSE) lm(mpg ~ vehicle_length + vehicle_weight + spoiler_angle + ground_clearance + AWD, data=MPGdataframe) summary(lm(mpg ~ vehicle_length + vehicle_weight + spoiler_angle + ground_clearance + AWD, data=MPGdataframe)) SuspensionTable <- read.csv(file='Suspension_Coil.csv', stringsAsFactors = TRUE) SuspensionTableSummary <- SuspensionTable %>% summarize(PSI_Mean = mean(PSI), PSI_Median = median(PSI), PSI_var = var(PSI), PSI_sd = sd(PSI)) lot_summary <- SuspensionTable %>% group_by(Manufacturing_Lot) %>% summarize(PSI_Mean = mean(PSI), PSI_Median = median(PSI), PSI_var = var(PSI), PSI_sd = sd(PSI)) t.test((SuspensionTable$PSI),mu=1500) Lot1_Data <- subset(SuspensionTable, SuspensionTable$Manufacturing_Lot == "Lot1") Lot2_Data <- subset(SuspensionTable, SuspensionTable$Manufacturing_Lot == "Lot2") Lot3_Data <- subset(SuspensionTable, SuspensionTable$Manufacturing_Lot == "Lot3") t.test(Lot1_Data$PSI, mu=1500) t.test(Lot2_Data$PSI, mu=1500) t.test(Lot3_Data$PSI, mu=1500)
438c5c501ba4a4cc7e41191ea2f8fb6396cd843c
8e865dd13098b885dd99ff8377ec1adb09f6b4a1
/AJB_scripts_github/filter_and_compare/subtree_functions.R
2590fe72ea310c4702be58e786cd96592766336e
[]
no_license
annethomas/veronica_phylo
157b7e9b699121d72fd718ed89f96e7ff386f202
db5faabf16d5997acb7eee93544522a675c8e6c8
refs/heads/main
2023-05-31T07:57:58.379739
2021-06-17T21:13:39
2021-06-17T21:13:39
308,403,666
0
0
null
null
null
null
UTF-8
R
false
false
3,350
r
subtree_functions.R
library(dplyr) getDescWrapper=function(tree,node,root){ tree$tip.label[phytools::getDescendants(tree,node)[which(phytools::getDescendants(tree,node)<root)]] } ## this is used in function, could add as argument genbank_species=unlist(read.table(file.path(compare_dir,"genbank_compare_species.txt"),stringsAsFactors = FALSE)) add_node_group=function(tree,stat_table,info_table,group_name,group=NULL,subgroup=FALSE){ ## checks and setup if(!is.null(group_name) & is.null(group)){ #retrieve group species from info_table if(group_name %in% info_table$hebe_group){ group=dplyr::filter(info_table, hebe_group==group_name & Species %in% genbank_species) %>% select("Species") %>% unlist() } else if(group_name %in% info_table$hebe_group_detail){ group=dplyr::filter(info_table, hebe_group_detail==group_name & Species %in% genbank_species) %>% select("Species") %>% unlist() } else{ print(unique(info_table$hebe_group)) print(unique(info_table$hebe_group_detail)) stop("please provide group_name present in info_table$hebe_group or info_table$hebe_group_detail") } } else if(is.null(group)){ stop("Please provide group (vector) or group name") } else{ if(any(!group %in% genbank_species)){ print(group[which(!group %in% genbank_species)]) stop("group includes species not in genbank_species") } print("using provided group species") } ## proceed print("species in target group:") print(group) mrca=getMRCA(tree,group) print(paste("mrca for",group_name,"is",mrca)) if(length(getDescWrapper(tree,mrca,80))==length(group)){ print("monophyletic") nodes=c(mrca,getDescendants(tree,mrca)) print(nodes) # if(!all(c("node","group") %in% names(stat_table))){ # stop("please provide stat table with 'node' and 'group' columns") # } if(!"group" %in% names(stat_table)){ #stop("please provide stat table with 'node' and 'group' columns") print("adding group column") stat_table$group=rep(NA,nrow(stat_table)) } if(!"mrca" %in% names(stat_table)){ #stop("please provide stat table with 'node' and 'group' columns") print("adding mrca column") stat_table$mrca=rep(FALSE,nrow(stat_table)) } if(subgroup){ if(!"subgroup" %in% names(stat_table)){ #stop("please provide stat table with 'node' and 'group' columns") print("adding subgroup column") stat_table$subgroup=rep(NA,nrow(stat_table)) } if(!"subgroup_mrca" %in% names(stat_table)){ #stop("please provide stat table with 'node' and 'group' columns") print("adding subgroup_mrca column") stat_table$subgroup_mrca=rep(FALSE,nrow(stat_table)) } stat_table[which(stat_table$node %in% nodes),"subgroup"]=group_name stat_table[which(stat_table$node == mrca),"subgroup_mrca"]=TRUE } else{ stat_table[which(stat_table$node %in% nodes),"group"]=group_name stat_table[which(stat_table$node == mrca),"mrca"]=TRUE } return(stat_table) } else{ print("paraphyletic species not in group:") print(setdiff(getDescWrapper(tree,mrca,80),group)) stop("paraphyletic, please examine and break up group") } }
aec4f8fa67dfb338b955ed0f862fa1c7aa032929
93cb634ab72a5456783b369e71b433678cfce7c7
/etl.R
abf33e504fb912a7cdda6d47b153dbde5765f71d
[]
no_license
thatcher/ExData_PeerAssessment2
f8ad8005746011c1bf958fd06e01aae83b23e500
437fc622406f3bb406005c411cbf7982ce9680f3
refs/heads/master
2021-01-19T00:46:44.696464
2015-03-22T17:07:55
2015-03-22T17:07:55
32,684,361
0
0
null
null
null
null
UTF-8
R
false
false
10,275
r
etl.R
# Homework assignment for Coursera exdata-011 # Week 3 # etl.R # # Basic routines for fetching the data from the web, read into R, # transform any fields we need to clean/manipulate, and load # the required subset for exploratory analysis. # # Extract will only download the data if it cant find the file locally or # is called with force=TRUE # # Tranform ensures the extract has been run will only load/manipulate/slice # the source data if the data slice does not exist on disk. # # Load ensures the transform has been performed and reads in and returns # just the serialized slice. # # All of the operations can be called with refresh=TRUE to force the step # to be re-performed, even if there data exists on disk. # # Chris Thatcher library(data.table) library(lubridate) NEI_DATA_URL = "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2FNEI_data.zip" NEI_SCC_FILE = "data/Source_Classification_Code.rds" NEI_PM25_FILE = "data/summarySCC_PM25.rds" NEI_PM25_BY_YEAR_FILE = "data/pm25_by_year.csv" NEI_PM25_BALTIMORE_FILE = "data/pm25_baltimore.csv" NEI_PM25_BALTIMORE_VEHICLE_FILE = "data/pm25_baltimore_vehicle.csv" NEI_PM25_BALTIMORE_VEHICLE_BY_YEAR_FILE = "data/pm25_baltimore_vehicle_by_year.csv" NEI_PM25_BALTIMORE_BY_YEAR_FILE = "data/pm25_baltimore_by_year.csv" NEI_PM25_LOS_ANGELES_FILE = "data/pm25_los_angeles.csv" NEI_PM25_LOS_ANGELES_VEHICLE_FILE = "data/pm25_los_angeles_vehicle.csv" NEI_PM25_LOS_ANGELES_VEHICLE_BY_YEAR_FILE = "data/pm25_los_angeles_vehicle_by_year.csv" NEI_PM25_LOS_ANGELES_BY_YEAR_FILE = "data/pm25_los_angeles_by_year.csv" NEI_PM25_COAL_FILE = "data/pm25_coal.csv" NEI_PM25_COAL_BY_YEAR_FILE = "data/pm25_coal_by_year.csv" # The following globals will be exported from etl.extract # NEI_SCC # NEI_PM25 etl.extract = function(refresh=FALSE){ # Make sure we have the data to work with locally, otherwise go get it. if( refresh || !file.exists(NEI_PM25_FILE) ){ message("Extracting data from url.") data_zip = "data/temp.zip" if("Windows" == Sys.info()["sysname"]) download.file(NEI_DATA_URL, destfile=data_zip) else download.file(NEI_DATA_URL, destfile=data_zip, method="curl") unzip(data_zip, exdir='data') file.remove(data_zip) } if(!exists('NEI_SCC')){ message('Reading NEI SCC codes.') NEI_SCC <<- readRDS(NEI_SCC_FILE) message('Complete.') } if(!exists('NEI_PM25')){ message('Reading NEI PM25 data.') NEI_PM25 <<- readRDS(NEI_PM25_FILE) NEI_PM25$type = as.factor(NEI_PM25$type) message('Complete.') } } # The following globals will be exported from etl.transform # NEI_PM25_BY_YEAR # NEI_PM25_BALTIMORE # NEI_PM25_BALTIMORE_VEHICLE # NEI_PM25_BALTIMORE_BY_YEAR # NEI_PM25_BALTIMORE_VEHICLE_BY_YEAR # NEI_PM25_LOS_ANGELES # NEI_PM25_LOS_ANGELES_VEHICLE # NEI_PM25_LOS_ANGELES_BY_YEAR # NEI_PM25_LOS_ANGELES_VEHICLE_BY_YEAR # NEI_PM25_COAL # NEI_PM25_COAL_BY_YEAR etl.transform = function(refresh=FALSE){ # loads the raw source data set if(refresh || !file.exists(NEI_PM25_FILE)){ etl.extract(refresh=refresh) } # ensure the raw data is in scope if(!exists('NEI_DATA') || !exists('SCC_CODES')){ etl.extract(refresh=refresh) } # Summarize the data for fine particulate matter by year, if(!exists('NEI_PM25_BY_YEAR') || !file.exists(NEI_EPMI25_BY_YEAR_FILE)){ message('Calculating PM25 by year.') NEI_PM25_BY_YEAR <<- aggregate( Emissions ~ year, data=NEI_PM25, FUN=sum ) write.csv( NEI_PM25_BY_YEAR, file=NEI_EPMI25_BY_YEAR_FILE, row.names=FALSE ) } # Subset the data for fine particulate matter for Baltimore, if(!exists('NEI_PM25_BALTIMORE') || !file.exists(NEI_PM25_BALTIMORE_FILE)){ message('Subsetting PM25 by fips 24510 (Baltimore).') NEI_PM25_BALTIMORE <<- subset(NEI_PM25, fips == "24510") write.csv( NEI_PM25_BALTIMORE, file=NEI_PM25_BALTIMORE_FILE, row.names=FALSE ) } # Summarize the data for fine particulate matter for Baltimore, if(!exists('NEI_PM25_BALTIMORE_BY_YEAR') || !file.exists(NEI_PM25_BALTIMORE_BY_YEAR_FILE)){ message('Calculating Baltimore PM25 by year.') NEI_PM25_BALTIMORE_BY_YEAR <<- aggregate( Emissions ~ year, data=NEI_PM25_BALTIMORE, FUN=sum ) write.csv( NEI_PM25_BALTIMORE_BY_YEAR, file=NEI_PM25_BALTIMORE_BY_YEAR_FILE, row.names=FALSE ) } # Subset the data for vehicle emissions from baltimore if(!exists('NEI_PM25_BALTIMORE_VEHICLE') || !file.exists(NEI_PM25_BALTIMORE_VEHICLE_FILE)){ message('Subsetting PM25 by "Mobile Sources" in SCC.Level.One.') vehicle_sources = subset(NEI_SCC, grepl("Mobile Sources", NEI_SCC$SCC.Level.One)) NEI_PM25_BALTIMORE_VEHICLE <<- subset(NEI_PM25_BALTIMORE, SCC %in% vehicle_sources$SCC) write.csv( NEI_PM25_BALTIMORE_VEHICLE, file=NEI_PM25_BALTIMORE_VEHICLE_FILE, row.names=FALSE ) } # Summarize the data for vehicle emissions for Baltimore, if(!exists('NEI_PM25_BALTIMORE_VEHICLE_BY_YEAR') || !file.exists(NEI_PM25_BALTIMORE_VEHICLE_BY_YEAR_FILE)){ message('Calculating Baltimore vehicle PM25 by year.') NEI_PM25_BALTIMORE_VEHICLE_BY_YEAR <<- aggregate( Emissions ~ year, data=NEI_PM25_BALTIMORE_VEHICLE, FUN=sum ) write.csv( NEI_PM25_BALTIMORE_VEHICLE_BY_YEAR, file=NEI_PM25_BALTIMORE_VEHICLE_BY_YEAR_FILE, row.names=FALSE ) } # Subset the data for fine particulate matter for Los Angeles, if(!exists('NEI_PM25_LOS_ANGELES') || !file.exists(NEI_PM25_LOS_ANGELES_FILE)){ message('Subsetting PM25 by fips 06037 (Los Angeles).') NEI_PM25_LOS_ANGELES <<- subset(NEI_PM25, fips == "06037") write.csv( NEI_PM25_LOS_ANGELES, file=NEI_PM25_LOS_ANGELES_FILE, row.names=FALSE ) } # Summarize the data for fine particulate matter for Los Angeles, if(!exists('NEI_PM25_LOS_ANGELES_BY_YEAR') || !file.exists(NEI_PM25_LOS_ANGELES_BY_YEAR_FILE)){ message('Calculating Los Angeles PM25 by year.') NEI_PM25_LOS_ANGELES_BY_YEAR <<- aggregate( Emissions ~ year, data=NEI_PM25_LOS_ANGELES, FUN=sum ) write.csv( NEI_PM25_LOS_ANGELES_BY_YEAR, file=NEI_PM25_LOS_ANGELES_BY_YEAR_FILE, row.names=FALSE ) } # Subset the data for vehicle emissions from Los Angeles if(!exists('NEI_PM25_LOS_ANGELES_VEHICLE') || !file.exists(NEI_PM25_LOS_ANGELES_VEHICLE_FILE)){ message('Subsetting PM25 by "Mobile Sources" in SCC.Level.One.') vehicle_sources = subset(NEI_SCC, grepl("Mobile Sources", NEI_SCC$SCC.Level.One)) NEI_PM25_LOS_ANGELES_VEHICLE <<- subset(NEI_PM25_LOS_ANGELES, SCC %in% vehicle_sources$SCC) write.csv( NEI_PM25_LOS_ANGELES_VEHICLE, file=NEI_PM25_LOS_ANGELES_VEHICLE_FILE, row.names=FALSE ) } # Summarize the data for vehicle emissions for Los Angeles, if(!exists('NEI_PM25_LOS_ANGELES_VEHICLE_BY_YEAR') || !file.exists(NEI_PM25_LOS_ANGELES_VEHICLE_BY_YEAR_FILE)){ message('Calculating Los Angeles vehicle PM25 by year.') NEI_PM25_LOS_ANGELES_VEHICLE_BY_YEAR <<- aggregate( Emissions ~ year, data=NEI_PM25_LOS_ANGELES_VEHICLE, FUN=sum ) write.csv( NEI_PM25_LOS_ANGELES_VEHICLE_BY_YEAR, file=NEI_PM25_LOS_ANGELES_VEHICLE_BY_YEAR_FILE, row.names=FALSE ) } # Subset the data for fine particulate matter from coal sources, if(!exists('NEI_PM25_COAL') || !file.exists(NEI_PM25_COAL_FILE)){ message('Subsetting PM25 by "Coal" in Energy Industry Sector.') coal_sectors = subset(NEI_SCC, grepl("Coal", NEI_SCC$EI.Sector)) NEI_PM25_COAL <<- subset(NEI_PM25, SCC %in% coal_sectors$SCC) write.csv( NEI_PM25_COAL, file=NEI_PM25_COAL_FILE, row.names=FALSE ) } # Summarize the data for fine particulate matter from coal sources. if(!exists('NEI_PM25_COAL_BY_YEAR') || !file.exists(NEI_PM25_COAL_BY_YEAR_FILE)){ message('Calculating PM25 from Coal by year.') NEI_PM25_COAL_BY_YEAR <<- aggregate( Emissions ~ year, data=NEI_PM25_COAL, FUN=sum ) write.csv( NEI_PM25_COAL_BY_YEAR, file=NEI_PM25_COAL_BY_YEAR_FILE, row.names=FALSE ) } } etl.load = function(data, refresh=FALSE){ # loads the data slice we need for our plot exploration etl.transform(refresh=refresh) if( 'pm25' == data ){ return(NEI_PM25) } if( 'pm25_by_year' == data ){ return(NEI_PM25_BY_YEAR) } if( 'pm25_baltimore' == data ){ return(NEI_PM25_BALTIMORE) } if( 'pm25_baltimore_vehicle' == data ){ return(NEI_PM25_BALTIMORE_VEHICLE) } if( 'pm25_baltimore_vehicle_by_year' == data ){ return(NEI_PM25_BALTIMORE_VEHICLE_BY_YEAR) } if( 'pm25_baltimore_by_year' == data ){ return(NEI_PM25_BALTIMORE_BY_YEAR) } if( 'pm25_los_angeles' == data ){ return(NEI_PM25_LOS_ANGELES) } if( 'pm25_los_angeles_vehicle' == data ){ return(NEI_PM25_LOS_ANGELES_VEHICLE) } if( 'pm25_los_angeles_vehicle_by_year' == data ){ return(NEI_PM25_LOS_ANGELES_VEHICLE_BY_YEAR) } if( 'pm25_los_angeles_by_year' == data ){ return(NEI_PM25_LOS_ANGELES_BY_YEAR) } if( 'pm25_coal' == data ){ return(NEI_PM25_COAL) } if( 'pm25_coal_by_year' == data ){ return(NEI_PM25_COAL_BY_YEAR) } }
afd31e00287fb1c5ea1f185c93af0972c4920b26
19449fbd87dad541e001ad7898ba30af0c839c27
/Kristina_Motue_Week8_Part2_Task3.R
e4d6ae39754f6a7cec7c827bf3e5b545ed92d433
[]
no_license
KristinaMotue/LearningWeek8
7d0a3837c9c1b51124d728feae38a574d00ef70f
7938d3921233d6c57951eaf97ce7f4484a40ccea
refs/heads/main
2023-03-30T04:39:39.244195
2021-03-29T21:03:59
2021-03-29T21:03:59
352,783,262
0
0
null
null
null
null
UTF-8
R
false
false
119
r
Kristina_Motue_Week8_Part2_Task3.R
library(ggplot2) x <- 1:20 y <- x^2 qplot(x,y, xlab = "x", ylab = "x^2", geom=c("point", "line"), color=I("Pink"))
f204deb707f8e25916b75c70a1e44c6cf4dfd171
951ac92c5e14a43947292208fa7a5ec7b113f752
/man/simVARmodel.Rd
806785ace9440adcfbf1ef2cf08b3b02c8d9a56d
[]
no_license
Allisterh/VARshrink-1
91c9054ae38111ce242553e73e8c03718b7725cf
2eb484246de70a9e4389357b2f7284b27caf56a3
refs/heads/master
2022-04-06T20:39:50.159056
2019-10-09T14:10:03
2019-10-09T14:10:03
null
0
0
null
null
null
null
UTF-8
R
false
true
1,160
rd
simVARmodel.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/simVARmodel.R \name{simVARmodel} \alias{simVARmodel} \title{Generate multivariate time series data using the given VAR model} \usage{ simVARmodel(numT, model, burnin = 0) } \arguments{ \item{numT}{Number of observed time points, T.} \item{model}{A list object with Coef, Sigma, dof; Coef is a list with A and c; A is a list object of K-by-K coefficient matrices and c is a length-K vector. Sigma is a K-by-K scale matrix and dof is a degree of freedom for multivariate t-distribution for noise.} \item{burnin}{Number of initial points which are not included in the final values.} } \value{ A numT-by-K matrix } \description{ Generate a multivariate time series data set using the given VAR model. } \details{ First, it creates (p+burnin+numT x K) data, then it remove the first (p+burnin) vectors. Finally, it returns (numT x K) data. } \examples{ myCoef <- list(A = list(matrix(c(0.5, 0, 0, 0.5), 2, 2)), c = c(0.2, 0.7)) myModel <- list(Coef = myCoef, Sigma = diag(0.1^2, 2), dof = Inf) simVARmodel(numT = 100, model = myModel, burnin = 10) }
f494eeaa9a9ab7e8cdbc5ea1d8b3cb53357e2bf2
6f4796e1757c4e4f7bccd7207d18c87e6f1e4e6b
/R/datprep.R
dd0d3abb5e0539d75aaa0c1490c1af319bc64355
[]
no_license
bjcochrane/TeachingPopGen
12dd96517bb0b005615235c5b567490eb0a41adc
033510f77f81fb1b2d668f34f682b857958c5cda
refs/heads/master
2021-11-30T21:05:55.295372
2021-11-08T18:02:53
2021-11-08T18:02:53
20,026,473
1
0
null
null
null
null
UTF-8
R
false
false
420
r
datprep.R
## Function to extract genotype numbers only from raw HapMap files ## min sets the limit for eliminating snps with fewer than n represenatatives in any genotype class. datprep <-function(dat,min=5){ genos <-cbind(dat$V13,dat$V16,dat$V19) genos <-data.frame(genos) rownames(genos) <-rownames(dat) colnames(genos) <-c("AA","Aa","aa") genos.sub <-genos[genos[,1]>min&genos[,2]>min&genos[,3]>min,] genos.sub }
9ee3e78d603d35a0257b67a306292c13d33e7680
188dbd6c2e199912b833fa14414b9668b3a97863
/scripts/05b_plot_ManhattanPlots.R
65707c428ed4f462b3cc0a47e4ae935ffd0f240e
[]
no_license
JasonMares63/Polygenic-Score-Portability
5ec9f611358246c9257c720cb3432bce30d93fc2
75ee51e2c5272d515902cbda20725be6ae4a6f50
refs/heads/main
2023-05-11T05:46:31.779941
2021-06-04T14:17:57
2021-06-04T14:17:57
358,634,609
0
1
null
null
null
null
UTF-8
R
false
false
1,490
r
05b_plot_ManhattanPlots.R
.libPaths("/rigel/mfplab/users/jm4454/rpackages/") suppressPackageStartupMessages(suppressWarnings(library(tcltk))) options(bitmapType='cairo') library("qqman",lib="/rigel/mfplab/users/jm4454/rpackages/") library("dplyr",lib="/rigel/mfplab/users/jm4454/rpackages/") phenotypes <- c("Basophil", "BMI", "DBP", "Eosinophil", "Hb", "Height", "Ht", "Lymphocyte", "MCH", "MCHC","MCV", "Monocyte", "Neutrophil", "Platelet", "RBC", "SBP","WBC") for (i in 1:length(phenotypes){ chr1 <- paste0("data/gwas_results/",phenotypes[i],".chr1.",phenotypes[i],".glm.linear") results_as <- read.csv(chr1,sep="\t") #Bind linear regression output together of all autosomes for (j in 2:22){ chr_bind <- paste0("data/gwas_results/",phenotypes[i],".chr",j,".",phenotypes[i],".glm.linear") results_bind <- read.csv(chr_bind,sep="\t") results_as <- bind_rows(results_as,results_bind) } results_as <- results_as[!is.na(results_as$P),] # Manhattan Plot png(paste0("img/",phenotypes[i],"_linear_manhattan.png")) manhattan(results_as,chr="X.CHROM",bp="POS",p="P",snp="ID", main = paste0("Manhattan plot: ",phenotypes[i]), col = c("blue4", "orange3"), suggestiveline=T, genomewideline=T, cex=0.4) dev.off() #QQ Plot of P-values png(paste0("img/",phenotypes[i],"_linear_qqplot.png")) qq(results_as$P, main = paste0("Q-Q plot of GWAS p-values for ",phenotypes[i]), xlim = c(0, 7), ylim = c(0, 12), pch = 18, col = "blue4", cex = 1.5, las = 1) dev.off() }
3c3ca5038e9d32c30d7083f1608ffd57dec9b876
99c837f0915c852a948947c3e69202de87525224
/analyses/rankings/processingDatasets/addAlignments.R
6e7521d29a671f51126e0e132f2df76bffa64100
[]
no_license
crisprVerse/crisprVersePaper
77ec43419f9f43c7edd9d28796e91e1ac2a9b1cd
b6e4356b6377c6c69a3d8e61c976372f496d1854
refs/heads/master
2023-04-10T10:55:32.970539
2022-10-20T17:01:41
2022-10-20T17:01:41
534,335,360
2
0
null
null
null
null
UTF-8
R
false
false
2,753
r
addAlignments.R
library(crisprDesign) library(crisprDesignGne) gs <- readRDS("../processingRankings/crisprverse/crisprverse.results.rds") cols <- c("ensembl_id", "spacer", "percentGC", "polyT", "n0", "n0_c", "n1", "n1_c", "n2", "n2_c", "n3", "n3_c", "hasSNP") newCols <- c("percentGC", "polyT", "hasSNP", "n0", "n0_c", "n1", "n1_c", "n2", "n2_c", "n3", "n3_c") gs <- gs[,cols] gs$name20 <- paste0(gs$ensembl_id, "_", gs$spacer) gs$name19 <- paste0(gs$ensembl_id, "_", substr(gs$spacer,2,20)) load("objects/rankings_achilles.rda") wh <- match(rankings_achilles$name, gs$name20) rankings_achilles <- cbind(rankings_achilles, gs[wh, newCols]) save(rankings_achilles, file="objectsFinal/rankings_achilles.rda") load("objects/rankings_achilles_neg.rda") wh <- match(rankings_achilles_neg$name, gs$name20) rankings_achilles_neg <- cbind(rankings_achilles_neg, gs[wh, newCols]) save(rankings_achilles_neg, file="objectsFinal/rankings_achilles_neg.rda") load("objects/rankings_sabatini.rda") wh <- match(rankings_sabatini$name, gs$name20) rankings_sabatini <- cbind(rankings_sabatini, gs[wh, newCols]) save(rankings_sabatini, file="objectsFinal/rankings_sabatini.rda") load("objects/rankings_sabatini_neg.rda") wh <- match(rankings_sabatini_neg$name, gs$name20) rankings_sabatini_neg <- cbind(rankings_sabatini_neg, gs[wh, newCols]) save(rankings_sabatini_neg, file="objectsFinal/rankings_sabatini_neg.rda") load("objects/rankings_toronto.rda") wh <- match(rankings_toronto$name, gs$name20) rankings_toronto <- cbind(rankings_toronto, gs[wh, newCols]) save(rankings_toronto, file="objectsFinal/rankings_toronto.rda") load("objects/rankings_toronto_neg.rda") wh <- match(rankings_toronto_neg$name, gs$name20) rankings_toronto_neg <- cbind(rankings_toronto_neg, gs[wh, newCols]) save(rankings_toronto_neg, file="objectsFinal/rankings_toronto_neg.rda") load("objects/rankings_toronto3.rda") wh <- match(rankings_toronto3$name, gs$name20) rankings_toronto3 <- cbind(rankings_toronto3, gs[wh, newCols]) save(rankings_toronto3, file="objectsFinal/rankings_toronto3.rda") load("objects/rankings_toronto3_neg.rda") wh <- match(rankings_toronto3_neg$name, gs$name20) rankings_toronto3_neg <- cbind(rankings_toronto3_neg, gs[wh, newCols]) save(rankings_toronto3_neg, file="objectsFinal/rankings_toronto3_neg.rda") load("objects/rankings_yusa.rda") wh <- match(rankings_yusa$name, gs$name19) rankings_yusa <- cbind(rankings_yusa, gs[wh, newCols]) save(rankings_yusa, file="objectsFinal/rankings_yusa.rda") load("objects/rankings_yusa_neg.rda") wh <- match(rankings_yusa_neg$name, gs$name19) rankings_yusa_neg <- cbind(rankings_yusa_neg, gs[wh, newCols]) save(rankings_yusa_neg, file="objectsFinal/rankings_yusa_neg.rda")
9a8cb3014fe3533c88b17992f2bcdf239fba416c
0a90eb1dcd39493a432098a6ff58f97231ef75d1
/verificarCiudad.R
a45eace86bbdb19a5d456d82e3ac8d9ce7298a40
[]
no_license
FerDoranNie/geodataLimpiezaSismo
b426162b08b30958cc3ce4cbe2a6589599f10442
3295b44ed620eded5e912f6cbca149dd08766678
refs/heads/master
2021-07-04T19:07:30.194507
2017-09-25T23:11:24
2017-09-25T23:11:24
104,497,405
3
0
null
null
null
null
UTF-8
R
false
false
2,451
r
verificarCiudad.R
#################################### #Creado por Fernando Dorantes Nieto # <(°) # ( >)" # /| #################################### library(magrittr) c("data.table", "ggmap", "dplyr", "tidyr", "lubridate", "geonames", "readxl") %>% sapply(require, character.only=T) setwd("~/ReposDesarollo/csvGeoData/") setwd("~/ReposDesarrollo/geodataLimpiezaSismo/") geocodeQueryCheck() # Agregar el nombre de usuario de geonames options(geonamesUsername="ferbase10") #options(geonamesUsername="tu User Name") #####TIENES QUE PONER TU NOMBRE DE USUARIO DE GEONAMES #####BASE DE DATOS DEL SERVICIO POSTAL MEXICANO PARA LA CIUDAD DE MÉXICO codigos <- read.csv("CodigosPostalesCiudadMexico.csv", header = T, stringsAsFactors = F) codigos2 <- codigos %>% select(Código.Postal, Municipio) %>% data.table %>% .[, Código.Postal := as.numeric(Código.Postal)] names(codigos2)<- c("cp", "ciudad_municipio" ) # Funciones --------------------------------------------------------------- ###Usarse en casos excepcionales codigoPostal <- function(postal){ postal <- as.numeric(postal) busqueda <- GNpostalCodeLookup(postalcode=postal) busqueda <- busqueda %>% filter(countryCode=="MX") print(busqueda) #print(busqueda$placeName) postal <- as.character(postal) postal <-ifelse(nchar(postal)<4, paste0("0", postal), postal) Y <-data.frame(Verificado = busqueda$adminName2, cp = postal) return(unique(Y)) } archivos <- list.files("verificadosTotal", all.files = T, full.names = T, pattern = "*.csv", recursive = T) #archivos <- archivos[-grep("Chiapas", archivos)] lapply(archivos, function(X){ file <- X file <- gsub(".*/","", file) file <- paste0("verificadosVuelta2Total/", file) X <- read.csv(X, header = T, stringsAsFactors = F) X1 <- X %>% filter(ciudad_municipio_Verificado!= "Ciudad de México") %>% data.frame X2 <- X %>% filter(ciudad_municipio_Verificado == "Ciudad de México") X2 <- merge(X2, codigos2, by.x="cp_Verificado", by.y="cp") %>% data.table %>% .[, ciudad_municipio_Verificado := ciudad_municipio ] %>% select(one_of(names(X2))) %>% data.frame X <- rbind(X1, X2) X <- data.frame(X) X %>% write.csv(file, row.names=F) })
a65844092dca75c037e7242fc9f882a2ed7aaf50
3799e008da31a5ca77b297ece995e5d2a4f74e20
/R/combineMolIon.R
555fba298ae0bbefac4f8f0afdba174c37eb2610
[]
no_license
rsilvabioinfo/ProbMetab
047f1ec7fff6d08aac2a97687af80c9b6d1cd39d
8311928cc5d18c6a215e8b48f8c2b4d82ea5df2a
refs/heads/master
2021-01-17T11:16:22.797086
2017-04-11T16:32:37
2017-04-11T16:32:37
16,100,752
2
2
null
2016-04-26T16:57:39
2014-01-21T11:32:18
R
UTF-8
R
false
false
7,213
r
combineMolIon.R
#' combineMolIon #' #' This function combines ion annotations in different acquisition modes. It operates #' in two main modes, combining individual annotations given by get.annot #' function, using the retention time and mass/charge windows provided by the user #' or extracting annotations from a peak table provided by CAMERA's combinexsAnnos #' function. #' @param antPOS positive annotation list given by get.annot. #' @param antNEG negative annotation list given by get.annot. #' @param peaklist given by CAMERA's combinexsAnnos function. If this option #' is chosen the user has to set the acquisition mode to the same as #' in CAMERA's function, and provide the respective object for downstream analysis. #' @param cameraobj xsAnnotate object for downstream analysis. #' @param polarity the same CAMERA's function acquisition mode. #' @param rtwin retention time window to annotate a peak as present #' in both acquisition modes. #' @param mzwin mass to charge ratio window to annotate a peak as present #' in both acquisition modes. #' @return a list with a matrix of possible molecular ions with a #' trace of their annotation and the respective xsAnnotate object. #' #' @export combineMolIon <- function(antPOS, antNEG, peaklist=NULL, cameraobj=NULL, polarity=NULL, rtwin=5, mzwin = 0.05) { if(!is.null(peaklist)) { peakidx <- which(peaklist[,"isotopes"]!="" | peaklist[,"adduct"]!="") antPOS3 <- peaklist[peakidx, c("mz", "rt", "isotopes", "adduct")] isoidx <- which(antPOS3$isotopes!="") iso <- antPOS3$isotopes[antPOS3$isotopes!=""] iso <- as.numeric(sapply(iso, function(x) sub("^\\[(\\d+)\\].+", "\\1", x))) charge <- (sapply(antPOS3$isotopes[antPOS3$isotopes!=""][order(iso)], function(x) sub(".+(\\d)\\+|\\-$", "\\1", x))) charge <- suppressWarnings(as.numeric(charge) ) charge[is.na(charge)] <- 1 niso <- (sapply(antPOS3$isotopes[antPOS3$isotopes!=""][order(iso)], function(x) sub(".+(\\[M.*\\]).+", "\\1", x))) niso <- sub(".+(\\d).+", "\\1", niso) niso <- suppressWarnings(as.numeric(niso)) niso[is.na(niso)] <- 0 preAnt <- cbind(iso[order(iso)], charge, niso, antPOS3[isoidx[order(iso)], c("mz", "rt", "isotopes")]) molIon <- data.frame(mass=numeric(nrow(preAnt)), retentionTime=numeric(nrow(preAnt)), isotope=numeric(nrow(preAnt)), adduct=numeric(nrow(preAnt)), trace=numeric(nrow(preAnt))) if(polarity=="pos") { molIon$mass <- preAnt$mz*preAnt$charge - (1.007276 * preAnt$charge) } if(polarity=="neg") { molIon$mass <- preAnt$mz*preAnt$charge + (1.007276 * preAnt$charge) } molIon$retentionTime <- preAnt$rt molIon$isotope <- preAnt$niso molIon$adduct <- 0 molIon$trace <- as.numeric(rownames(antPOS3[isoidx[order(iso)],])) molIon$comb <- polarity addidx <- which(antPOS3$adduct!="") v0 <- c(0,0) for(i in 1:length(addidx)) { v1 <- suppressWarnings(as.numeric(strsplit(antPOS3$adduct[addidx][i], " ")[[1]])) v0 <- rbind(v0, cbind(i, v1[-which(is.na(v1))])) } v0 <- v0[-1,] rnames <- as.numeric(rownames(antPOS3[addidx,])) rnames <-rnames[v0[,1]] molIon2 <- data.frame(mass=numeric(length(rnames)), retentionTime=numeric(length(rnames)), isotope=numeric(length(rnames)), adduct=numeric(length(rnames)), trace=numeric(length(rnames))) molIon2$mass <- v0[,2] molIon2$retentionTime <- peaklist[rnames, "rt"] molIon2$isotope <- 0 molIon2$adduct <- 1:length(rnames) molIon2$trace <- rnames molIon2$comb <- polarity molIon2$comb[which(peaklist[molIon2$trace, ncol(peaklist)]!="")] <- "both" molIon=rbind(molIon, molIon2) molIon$pcgroup <- peaklist[as.numeric(sapply(molIon[,"trace"], function(x) strsplit(as.character(x), ";")[[1]][1])), "pcgroup"] if(sum(duplicated(molIon[,1:2]))) molIon <- molIon[-which(duplicated(molIon[,1:2])),] antComb <- list(molIon=molIon, cameraobj=cameraobj) return(antComb) } vidx <- c("",""); nvidx <- c("",""); pvidx <- c("",""); for(i in 1:nrow(antNEG$molIon)) { idx <- which(antPOS$molIon[,1] > (antNEG$molIon[i,1]-mzwin) & antPOS$molIon[,1] < (antNEG$molIon[i,1]+mzwin) & antPOS$molIon[,2] > (antNEG$molIon[i,2]-rtwin) & antPOS$molIon[,2] < (antNEG$molIon[i,2]+rtwin) ) if(length(idx)){ for(k in 1:length(idx)) { # Possible cases # same isotopic distribution - discard one # adduct convergence - discard one # treated as isotope in one, and adduct in another # if the adduct is equal the 12C peak it is discarded # else keep the adduct and the 13C peak if(antNEG$molIon[i,3] != antPOS$molIon[idx[k],3]) { vidx <- rbind(vidx, c(i, idx[k])) next } if(antNEG$molIon[i,4] == 0 & antPOS$molIon[idx[k],4]!=0) { pvidx <- rbind(pvidx, c(i, idx[k])) next } if(antNEG$molIon[i,4] != 0 & antPOS$molIon[idx[k],4]==0) { nvidx <- rbind(nvidx, c(i, idx[k])) next } if(antNEG$molIon[i,4] != 0 & antPOS$molIon[idx[k],4]!=0) { nvidx <- rbind(nvidx, c(i, idx[k])) next } if(antNEG$molIon[i,4] == 0 & antPOS$molIon[idx[k],4]==0) { nvidx <- rbind(nvidx, c(i, idx[k])) next } vidx <- rbind(vidx, c(i, idx[k])) } } } # for debugging only if(!is.null(dim(vidx))) vidx <- vidx[-1,] if(!is.null(dim(nvidx))) nvidx <- nvidx[-1,] if(!is.null(dim(pvidx))) pvidx <- pvidx[-1,] antNEG$molIon$ind <- 0 id1 <- which(antNEG$molIon[,3]==1) antNEG$molIon$ind[id1] <- 1:length(id1) id1 <- which(antNEG$molIon[,3]==1)-1 antNEG$molIon$ind[id1] <- 1:length(id1) #antNEG2 <- antNEG$molIon[-as.numeric(vidx[,1]),] antNEG$molIon$comb <- "neg" if(!is.null(dim(pvidx))) antNEG$molIon$comb[as.numeric(pvidx[,1])] <- "both" if(!is.null(dim(nvidx))) { antNEG2 <- as.data.frame(antNEG$molIon[-as.numeric(nvidx[,1]),]) } else { antNEG2 <- as.data.frame(antNEG$molIon) } err1 <- setdiff(which(antNEG2[,3]==1), which(antNEG2[,3]==0 & antNEG2[,4]==0)+1 ) if(length(err1)) antNEG2 <- as.data.frame(antNEG2[-err1,]) err2 <- setdiff( which(antNEG2[,3]==0 & antNEG2[,4]==0), which(antNEG2[,3]==1) -1 ) if(length(err2)) antNEG2 <- as.data.frame(antNEG2[-err2,]) sn1 <- unique(antNEG2$ind) sn1 <- sn1[-which(unique(antNEG2$ind)==0)] snListNeg <- lapply(antNEG$snList, function(x) x[sn1]) antPOS$molIon$ind <- 0 id1 <- which(antPOS$molIon[,3]==1) antPOS$molIon$ind[id1] <- 1:length(id1) id1 <- which(antPOS$molIon[,3]==1)-1 antPOS$molIon$ind[id1] <- 1:length(id1) antPOS$molIon$comb <- "pos" if(!is.null(dim(nvidx))) antPOS$molIon$comb[as.numeric(nvidx[,2])] <- "both" if(!is.null(dim(pvidx))) { antPOS2 <- as.data.frame(antPOS$molIon[-as.numeric(pvidx[,2]),]) } else { antPOS2 <- as.data.frame(antPOS$molIon) } err <- setdiff(which(antPOS2[,3]==1), which(antPOS2[,3]==0 & antPOS2[,4]==0)+1 ) if(length(err)) antPOS2 <- as.data.frame(antPOS2[-err,]) sn1 <- unique(antPOS2$ind) sn1 <- sn1[-which(unique(antPOS2$ind)==0)] snListPos <- lapply(antPOS$snList, function(x) x[sn1]) #vpos <- unlist(sapply(vidx[,2], function(x) strsplit(x, ";")[[1]])) #antPOS2$comb[as.numeric(vpos)] <- "both" antComb <- list(molIon=rbind(antPOS2, antNEG2), antPOS=antPOS, antNEG=antNEG, neg=antNEG$cameraobj, pos=antPOS$cameraobj, snListPos=snListPos, snListNeg=snListNeg ) }
bdea4b22c938fb007037424b5d7192871b32f34b
5c82f476674236af1d1566c2e6d89ae7eb3a24a2
/Additional_models/C5_building_v1.R
b18397ad93e77f235f1904ca63d98bc6b11e21e6
[]
no_license
francescaprata/Indoor-Positioning_WiFi-Fingerprinting
ae0a7812a25b152892dcc7d460f8f8c7e9063bd7
487302044714e1d510263ea7253625a4084686df
refs/heads/master
2020-04-27T16:48:58.955044
2019-03-26T16:14:46
2019-03-26T16:14:46
174,494,320
0
0
null
null
null
null
UTF-8
R
false
false
3,496
r
C5_building_v1.R
########################################### # Name: Francesca Prata # # Project: WiFi Locationing # # Script: Predicting building ID with C.5 # # Date: 5 March 2019 # # Version: 1 # ########################################### #Retrieving the necessary scripts source(file = "2.PreProcess_v2.R") ########################################################## # TRAINING DATA # ########################################################## ############# # MODELLING # ############# #Checking that BUILDINGID and FLOOR are both factors Wifi_TrainSetNOZero$BUILDINGID <- as.factor(Wifi_TrainSetNOZero$BUILDINGID) Wifi_TrainSetNOZero$FLOOR <- as.factor(Wifi_TrainSetNOZero$FLOOR) #Data partition set.seed(123) indexTrain <- createDataPartition(y = Wifi_TrainSetNOZero$BUILDINGID, p = .4, list = FALSE) training <- Wifi_TrainSetNOZero[indexTrain,] testing <- Wifi_TrainSetNOZero[-indexTrain,] #Predicting BUILDINGID by only using the WAPs training <- select(training, -FLOOR, -SPACEID, -RELATIVEPOSITION, -USERID, -PHONEID, -TIMESTAMP, -LONGITUDE, - LATITUDE) #Setting cross validation parameters fitcontrolC5 <- trainControl(method = "repeatedcv", number = 10, repeats = 1, preProc = c("center", "scale", "range"), verboseIter = TRUE) #Training C5.0 model set.seed(123) C5FitBuilding <- train(BUILDINGID~., training, method = "C5.0", metric = "Accuracy", tuneLength = 1, trControl = fitcontrolC5) #Predicting the BUILDING ID from the training data predBUILD_C5 <- predict(C5FitBuilding, newdata = testing) #Creating a new column with the predictions testing$predBUILD_C5 <- predBUILD_C5 #Checking the metrics confusionMatrix(testing$predBUILD_C5, testing$BUILDINGID) ############################################################ # VALIDATION DATA # ############################################################ #Predicting BUILDINGID from the validation data predBUILD_C5 <- predict(C5FitBuilding, Wifi_ValidationSetNOZero) plot(predBUILD_C5) #Creating a new column with the predictions Wifi_ValidationSetNOZero$predBUILD_C5 <- predBUILD_C5 #Checking that BUILDINGID and predBUILD_C5 are both factors Wifi_ValidationSetNOZero$predBUILD_C5 <- as.factor(Wifi_ValidationSetNOZero$predBUILD_C5) Wifi_ValidationSetNOZero$BUILDINGID <- as.factor(Wifi_ValidationSetNOZero$BUILDINGID) #Checking the metrics confusionMatrix(Wifi_ValidationSetNOZero$predBUILD_C5, Wifi_ValidationSetNOZero$BUILDINGID) #Adding column with errors to the dataframe Wifi_ValidationSetNOZero <- mutate(Wifi_ValidationSetNOZero, errorsBUILD = predBUILD_C5 - BUILDINGID) #Storing the predicted values, actual values and errors in a tibble resultsBUILDINGID <- tibble(.rows = 1111) #Adding FLOOR and its prediction to the tibble resultsBUILDINGID$predBUILD_C5 <- predBUILD_C5 resultsBUILDINGID$BUILDINGID <-Wifi_ValidationSetNOZero$BUILDINGID #Storing the file saveRDS(resultsBUILDINGID, file = "resultsBUILDC5(V1).rds")
a47047391832c7d086421f6d744a513721f2e952
a4d3c14135bb1e3cf25fd0d0176fecc6accdb9eb
/R/intersectionint.R
8ac71fd6d5df97f71ebac21ed1265775e3c686d0
[]
no_license
sdestercke/Belief-R-Package
2d2ca9677547d302f3e46ac7c9beb59717063257
646fd2c73764e4af151bcfc26743c35000de8df0
refs/heads/master
2020-05-16T23:14:44.728977
2012-08-03T10:24:27
2012-08-03T10:24:27
3,516,891
1
0
null
null
null
null
UTF-8
R
false
false
237
r
intersectionint.R
'intersectionint'=function(interval,c){ #internal - used by SMCgen # inf=2*c-1 sup=2*c bound_inf=max(interval[inf]) bound_sup=min(interval[sup]) if(bound_inf>bound_sup){ bound_inf=0 bound_sup=0 } return(c(bound_inf,bound_sup)) }
d683c6b0541a5bbbcdeba30f88a342584f2e3116
8e233535ad72cc5068a87b7b3844463a3309d432
/2_Porcentaje_y_Enriquecimiento/Enriquecimiento_funcional.R
d8ebc2e358056988f5bd75234d0899b34e632c12
[]
no_license
rbarreror/Epigenetics_ChromHMM
9c7e030a2194b0aea0588b8bfa1d1cc1d1cbc8a0
97dcf36634f1ec592ae4981c434fedb1dd2aa6d5
refs/heads/master
2021-05-24T12:41:00.541480
2020-04-06T19:58:22
2020-04-06T19:58:22
253,566,385
0
0
null
null
null
null
UTF-8
R
false
false
5,498
r
Enriquecimiento_funcional.R
""" Name: Rafael Barrero Rodríguez Date: 2020-03-11 Description: En este script recogemos y realizamos el enriquecimiento funcional a partir de los distintos ficheros BED con los intervalos genómicos donde se encuentra nuestro estado. """ root_folder <- paste0("/home/rafael/Master_UAM/Transcriptomica_RegulacionGenomica_Epigenomica/", "3_Regulacion_Genomica_Epigenomica/Trabajo_Polycomb/anotation/", "enriquecimiento_funcional/") setwd(root_folder) library (clusterProfiler); packageDescription ("clusterProfiler", fields = "Version") library(topGO) library(org.Hs.eg.db) library("FGNet") library("AnnotationDbi") library("KEGGprofile") # If not installed, we’ll use pathview instead (hopefully it will install) library("pathview") # If not installed, then go to KEGG Mapper (web page https://www.genome.jp/kegg/tool/map_pathway2.html) library("gProfileR") # If not installed (web page instead https://biit.cs.ut.ee/gprofiler/) ######################################### # ALL SEGMENTS (segments_collapsed) ######################################### # Empezamos realizando el análisis con todos los segmentos. gene_table <- read.table("segments_collapsed/gene_table.tsv", header = TRUE, sep = "\t") gene_table <- dplyr::distinct(gene_table) """ Lo primero que haremos será ver los distintos tipos de genes en los que se encuentra (o en los que aparece asociado nuestro estado) """ gene_type <- as.data.frame(table(gene_table$Gene.type), stringsAsFactors = FALSE) # Pie Chart with Percentages slices <- gene_type$Freq[gene_type$Freq > 1000] lbls <- gene_type$Var1[gene_type$Freq > 1000] # Estamos desconsiderando elementos que tienen menos de 1000 ocurrencias slices <- c(slices, sum(gene_type$Freq)-sum(slices)) lbls <- c(lbls, "Others") pct <- round(slices/sum(gene_type$Freq)*100) lbls <- paste(lbls, pct) # add percents to labels lbls <- paste(lbls,"%",sep="") # ad % to labels pie(slices,labels = lbls, col=rainbow(length(lbls)), main="Gene Type Distribution") """ A continuación haremos el enriquecimiento funcional usando solo los genes del tipo protein_coding """ # Tomamos los gene_symbols gene_symbols <- as.character(gene_table$Gene.name[gene_table$Gene.type == "protein_coding"]) gene_symbols <- levels(factor(gene_symbols[!is.na(gene_symbols)])) # Tomamos ENTREZ ID gene_entrez_id <- as.character(gene_table$EntrezGene.ID[gene_table$Gene.type == "protein_coding"]) gene_entrez_id <- levels(factor(gene_entrez_id[!is.na(gene_entrez_id)])) # Tomamos ENSEMBL ID gene_ensembl_id <- as.character(gene_table$Gene.stable.ID[gene_table$Gene.type == "protein_coding"]) gene_ensembl_id <- levels(factor(gene_ensembl_id[!is.na(gene_ensembl_id)])) # Usamos enrichGO para enriquecer en GO ego1 <- enrichGO(gene = gene_symbols, OrgDb = org.Hs.eg.db, keyType = 'SYMBOL', ont = "BP", pAdjustMethod = "BH", pvalueCutoff = 0.01, qvalueCutoff = 0.05) results <- ego1@result dotplot(ego1, showCategory=15) # enrichMap(ego1, vertex.label.cex=1.2, layout=igraph::layout.kamada.kawai) # cnetplot(ego1) # par(cex = 0.65) # plotGOgraph(ego1, firstSigNodes = 5) """ Los términos GO que aparecen más enriquecidos son los asociados con la activación de la respuesta inmune mediada por neutrófilos. Recordemos que nuestro estado epigenético se asociaba a genes que estaban preparados para expresarse cuando fuera necesario. Por ello, estos resultados son coherentes, al menos parcialmente, teniendo en cuenta que nuestras células de partida eran células del sistema inmune, en concreto, monocitos. Puede ser que muchos de los genes implicados en la respuesta por neutrófilos también participen en la activación de monocitos. """ # A contniación haremos enriquecimiento de KEGG PATHWAYS geneLabels <- unlist(as.list(org.Hs.egSYMBOL)) geneList <- geneLabels[which(geneLabels %in% gene_symbols)] kegg_enrich <- enrichKEGG(gene = names(geneList), organism = "hsa", keyType = "kegg", pvalueCutoff = 0.05, pAdjustMethod = "BH", universe, minGSSize = 10, maxGSSize = 500, qvalueCutoff = 0.2, use_internal_data = FALSE) kegg_enrich_df <- kegg_enrich@result dotplot(kegg_enrich, showCategory=10) dir.create("./segments_collapsed/KEGG_Profile") setwd("./segments_collapsed/KEGG_Profile") list_variantspergene <- setNames(rep(NA, length(gene_ensembl_id)), gene_ensembl_id) #procesos_kegg <-levels(ENSGenes$pathway) # 6 pathways procesos_kegg <- kegg_enrich_df$ID[c(2,3,5,8,9)] for (keggNumber in procesos_kegg) { plotKegg(paste0("hsa",keggNumber), geneExpr=list_variantspergene, geneIDtype="ENSEMBL") } setwd(root_folder) write.table(results[1:15, -c(8,9)], file = "go_results.tsv", row.names = FALSE, col.names = TRUE, quote = FALSE, sep = "\t") write.table(kegg_enrich_df[1:15, -c(8,9)], file = "kegg_results.tsv", row.names = FALSE, col.names = TRUE, quote = FALSE, sep = "\t")
6dfddebaeb951c775cd99bb2f477eb8a2c640f0f
0c61299c0bfab751bfb5b5eac3f58ee2eae2e4b0
/Daphnia/Juveniles/set_up_fex.R
d93b8c3df4586fec1b11105952ce1b7e73248c6e
[]
no_license
jwerba14/Species-Traits
aa2b383ce0494bc6081dff0be879fc68ed24e9c2
242673c2ec6166d4537e8994d00a09477fea3f79
refs/heads/master
2022-10-13T10:57:54.711688
2020-06-12T01:57:21
2020-06-12T01:57:21
105,941,598
0
0
null
null
null
null
UTF-8
R
false
false
2,311
r
set_up_fex.R
## juvenile daphnia feeding and excretion source("../../transfer_functions.R") source("../../Graphing_Set_Up.R") library(tidyverse) ### hmm some problems with cc change-- need to double check rdatj <- read.csv("Small_Daph_Feeding.csv") ## missing data for treatments 6 and 7, if I can get back into lab can find missing data...for now drop names(rdatj)[names(rdatj)=="Rep.."] <- "Rep" rdatj <- rdatj %>% filter(!is.na(Chl_Time_Diff)) dim(rdatj) cont <- rdatj %>% mutate(chl_time_diff_h = Chl_Time_Diff/60, nh4_time_diff_h = Nh4_Time_Dif/60 ) %>% filter(Control.Y.N == "Y") %>% mutate(chl_diff =((Chl.1-Chl.2)/chl_time_diff_h), nh4_diff= ((Nh4.1-Nh4.2)/nh4_time_diff_h)) %>% ## change per hour group_by(Treatment) %>% summarize(mean_chl = mean(chl_diff, na.rm = T), mean_nh4 = mean(nh4_diff,na.rm = T)) ## onr row in treatment 3 is all NAs..?? dim(cont) ## add mean control avg back to main dataframe dat <- left_join(rdatj,cont) dim(dat) ## need to add in diff from control bc if positive algae grew so indiv actually ate more if neg indiv ate less??? dat <- dat %>% filter(Control.Y.N == "N") %>% mutate(chl_time_diff_h = (Chl_Time_Diff/60),nh4_time_diff_h = (Nh4_Time_Dif/60)) %>% mutate(chl_diff = (Chl.1-Chl.2)/chl_time_diff_h, nh4_diff = (Nh4.1-Nh4.2)/nh4_time_diff_h) %>% mutate(chl_diff_cc = (chl_diff-mean_chl)/Num_Daphnia, nh4_diff_cc = (nh4_diff-mean_nh4)/Num_Daphnia) dim(dat) dat1 <- dat %>% filter(nh4_diff_cc > -5) %>% ## remove one weird measurement dplyr::select(Rep, Treatment,Chl.1,Nh4.1, chl_diff_cc,nh4_diff_cc, Num_Daphnia) #ggplot(dat1, aes(Chl.1,chl_diff_cc)) + geom_point() mod_lm <- lm(data = dat1, chl_diff_cc ~ -1+Chl.1) #newpred <- sat_fun(k= seq(1,100,1), a=960892 ,b =1339121459) newdata = data.frame(Chl.1 = seq(1,25,0.1)) newpred1 <- as.data.frame(predict(mod_lm, newdata = newdata, interval = "confidence")) newdata$chl_diff_cc <- newpred1$fit newdata$lwr <- newpred1$lwr newdata$upr <- newpred1$upr j_feed_g <- ggplot(data = dat1, aes(Chl.1, chl_diff_cc)) + geom_point() + geom_line(data = newdata) + geom_ribbon(data = newdata, aes(ymin = lwr, ymax= upr),alpha = 0.3) + xlab("Chlorphyll a (ug/L)") + ylab(str_wrap("Change in Chlorophyll a/Juvenile Daphnia/Day", width = 25)) + ggtitle("LS: Linear Fit") print(j_feed_g)
91425afc3bfa761e491b1cb2fcbb6c265f9ddf80
a2d73f27df156aaf155ce81f474e38026ab350d0
/2_Logistic_regression_and_nonparametric_methods.R
d754a3a196161c889665f983929cdd084029cda0
[]
no_license
vonOrso/Stepic_524_Basics_of_statistics_Part_2
f2a0e40cacbb27f4d7de737018c6d85fd2584a09
9cb1c93d58732b77f67516b05a1b322bd410aa03
refs/heads/main
2023-02-11T17:22:51.923159
2021-01-04T21:34:27
2021-01-04T21:34:27
324,353,295
9
1
null
null
null
null
UTF-8
R
false
false
265
r
2_Logistic_regression_and_nonparametric_methods.R
# 2.1.3 # log(30/70) # 2.1.4 # exp(-1)/(1+exp(-1)) # 2.1.5 # log((24/41)/(17/41)) # 2.2.4 # 50*(exp(-0.8472979)/(1+exp(-0.8472979))) # 2.3.1 # exp(1.1243)+exp(-2.4778) # 2.3.3 # (197/64)/(93/360) # 2.5.2 # exp(-1.15+0.8+2.13-0.17)/(1+exp(-1.15+0.8+2.13-0.17))
79bf5b7b78bce981896f2990afd646aaf8c21159
b67d0705c87c4ac2fc6a0d0eb2b00b5cde91e770
/assignments/ch2_jakob.R
177e23b37d0efd70f64dad1c5cbd7a086cf77e8a
[]
no_license
ahulman/Assignment1
b607ac60c82b817bb42575ce814ff4a4c31a6f86
4d938e167d0aa9bf17899d6cb02641bf45b6347e
refs/heads/master
2020-04-06T05:48:39.808159
2017-07-05T10:17:34
2017-07-05T10:17:34
82,927,709
0
2
null
2017-03-03T13:04:46
2017-02-23T13:02:19
R
UTF-8
R
false
false
4,742
r
ch2_jakob.R
###Creates SimCohort simCohort <- function(N,S){ set.seed(S) ###Jakob id <- c(1:N) #creates a sex variable for first 600 and appends last 400 sex <- rep.int(0,N*6/10) sex <- append(sex, rep.int(1,N*4/10)) #creates dataframe from SEX and ID vectors dataContinuous = data.frame("sex" = sex, "id" = id) dataContinuous$age <- runif(N, min = 40, max = 70) dataContinuous$bmi <- ifelse(dataContinuous$sex==0, 21 + 0.1*dataContinuous$age + rnorm(N, 0 , 2), 20 + 0.15*dataContinuous$age + rnorm(N, 0 , 2.5)) ###OMAR dataContinuous$bmi <- ifelse(dataContinuous$sex==0, 21 + 0.1*dataContinuous$age + rnorm(N, 0 , 2), 20 + 0.15*dataContinuous$age + rnorm(N, 0 , 2.5)) ###OMAR #Output data frame dataCategorical = data.frame(sex, id) #Generate ethnicity dataCategorical$ethnic <-rbinom(N, 1, 0.05) #Generate smoking status smoke <- c(0, 1, 2) dataCategorical$smoke <- ifelse(dataCategorical$sex == 0, sample(smoke, N, replace = TRUE, prob = c(0.5, 0.3, 0.2)), sample(smoke, N, replace = TRUE, prob = c(0.6, 0.3, 0.1))) dataCategorical$smoke <- ifelse(dataCategorical$sex == 0, sample(smoke, N, replace = TRUE, prob = c(0.5, 0.3, 0.2)), sample(smoke, N, replace = TRUE, prob = c(0.6, 0.3, 0.1))) dataCategorical$smoke <- factor (dataCategorical$smoke, levels = c(0, 1, 2), labels = c("never", "ex", "current")) ###Analysis total <- merge(dataContinuous,dataCategorical, by=c("id","sex")) #change numeric storage type to factor total$ethnic <- factor (total$ethnic, levels = c(0, 1), labels = c("non-white", "white")) total$sex <- factor (total$sex, levels = c(0, 1), labels = c("male", "female")) return(total) } #creates sample cohorts simCohort(20000,1) cohort1 <- simCohort(100, 123) cohort2 <- simCohort(10000, 987) #plots associations to examine #plots associations plot(cohort1$age,cohort1$bmi) plot(cohort1$sex,cohort1$bmi) plot(cohort2$age,cohort2$bmi) plot(cohort2$sex,cohort2$bmi) # cohort1 ----------------------------------------------------------------- #creates linear models with single explanatory variable bmi.mod <- lm(bmi ~ age, cohort1) plot(cohort1$age,cohort1$bmi) mean.bmi <- mean(cohort1$bmi) abline(bmi.mod, col="red") abline(h=mean.bmi, col="blue") summary(bmi.mod) bmi.mod <- lm(bmi ~ sex, cohort1) bmi.mod <- lm(bmi ~ age, cohort2) plot(cohort2$age,cohort2$bmi) mean.bmi <- mean(cohort2$bmi) abline(bmi.mod, col="red") abline(h=mean.bmi, col="blue") summary(bmi.mod) #blue line indicate null-hypothesis, positiv slope indicates age affects BMI ##this plot indicates sex influences BMI plot(cohort2$sex,cohort2$bmi) ##linear models with multiple explanatory variables #plots the BMI by explanatory variables from cohort1 coplot(bmi~age|sex,cohort1) #This plot indicates that sex affects the intersection of BMI, let's examine the slope for men and women: summary(lm(bmi~age, sex == "male", data=cohort1)) summary(lm(bmi~age, sex == "female", data=cohort1)) #from the coeefficiens it appears that for men an increase of 1 year increases BMI with 0,09 abd for women it's 0,11 #The intersects are different indicating a difference in bmi at the same age # Cohort2---- #plots the BMI by explanatory variables from cohort2 coplot(bmi~age|sex,cohort2) #This plot indicates that sex affects atleast the deviation, let's examine the slope for men and women: summary(lm(bmi~age, sex == "male", data=cohort2)) summary(lm(bmi~age, sex == "female", data=cohort2)) ## the second cohort a closer to the true slope value, representing a a larger sample size. It is also #noted a larger standard error for women #multiple linear regression, notice the difference in slope and intersection. Cohort2 converges towards the true value #of bmi at year 40 (know from the equation) bmiMultiRegression <- lm(bmi~age*sex, cohort1) bmiMultiRegression plot(cohort1$age, fitted(bmiMultiRegression)) bmiMultiRegression <- lm(bmi~age*sex, cohort2) bmiMultiRegression plot(cohort2$age, fitted(bmiMultiRegression)) #notice that for females, the age effect is increased by 0,05 per year. Being female however reduces BMI with 0,9 #creates linear models bmi.mod <- lm(formula = bmi ~ age, cohort1) bmi.mod bmi.mod <- lm(formula = bmi ~ sex, cohort1) bmi.mod plot(bmi.mod)