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
191c2c300beab54091f522b1777e28e9ed6dabd4
0d54162fb6c64534561f1793b34d3446eb569723
/Step 1 - reads BBS data and runs detectability model.R
68156515055800e28cd80f22d11dfecb7b6e20ec
[]
no_license
samfranks/bbs
536817f3c14ba60350202e56f79bafb6b0400d60
0015dc2242a41b7daf9a9b74a94729d85c209df7
refs/heads/master
2021-01-24T06:40:32.947971
2014-11-04T10:55:18
2014-11-04T10:55:18
null
0
0
null
null
null
null
UTF-8
R
false
false
14,828
r
Step 1 - reads BBS data and runs detectability model.R
######################################################################## # DISTANCE SAMPLING OF BBS LINE TRANSECT DATA TO # # OBTAIN DENSITY AND ABUNDANCE ESTIMATES # ######################################################################## # The core program below was written by Ali Johnston 2009 with some original # code from Eric Rexstad and modified by Dario Massimino 2011 # The programs make use of the R library mrds # The data formatting code was written by Ali Johnston 2009 # IMPORTANT! Please type the name of the species and the visit here: species <- "SC" Visit <- "M" # It can be E (early), L (late), or M (maximum) min.year <- 1994 max.year <- 2011 # Final year (2 digits) setwd("D:/Whinchat") # These source functions to read and manipulate the bbs data: source("D:/R functions/get.data.per.yr.per.square function.txt") source("D:/R functions/format.data.all.yr.square function.txt") source("D:/R functions/get.data.per.yr function.txt") source("D:/R functions/format.data.all.yr function.txt") source("D:/R functions/get.zero.obs.weather function.txt") library(mrds) ####################### # MODEL DETECTABILITY # READING IN BIRD DATA # Need transect observations of all transects in which there WERE observations. miny <- substr(min.year,3,4) maxy <- substr(max.year,3,4) filename <- ifelse(substr(species,2,2)==".", paste(substr(species,1,1),"_ ",miny,maxy," tran zF.txt", sep=""), paste(species," ",miny,maxy," tran zF.txt", sep="")) if (length(list.files("Data",pattern=filename))==1) { bird.dat <- read.table(paste("Data/",filename,sep=""),sep=",") } else { print(Sys.time()) print(paste(filename,"has not been found")) print("Data are now being read from the BBS folder") print("This may take very long (several hours for the most abundant species!)") wd <- getwd() setwd("Z:/bbs") bird.dat.xx <- format.data.all.yr(spec.code=species, min.year=min.year, max.year=max.year, zero.obs.squares=F) # It often gives me this warnings, but the data frame seems ok: # In readLines(file.loc) : incomplete final line found on 'data05/ebird05' setwd(wd) write.table(bird.dat.xx,paste("Data/",filename,sep=""),sep=",") bird.dat <- bird.dat.xx print(Sys.time()) } # Use the top one for transects and the bottom one for squares bird.dat2 <- subset(bird.dat,select=c("site","observer","detected","year","distance","distbegin","distend","effort","eorl","habs1","tran.sec")) visit <- ifelse(bird.dat2$eorl=="E",1,0) # 1=Early; 0=Late bird.dat2 <- cbind(bird.dat2,visit) # Check for wrong effort. Anything over 0.4 is wrong. This is 2km*100m*2 = 2*0.1*2 km2 # Often the effort is wrong because the square is entered twice in the habitat file, so the real # effort is half of the recorded effort. Should check these, but for now is fudged: sub1 <- subset(bird.dat2,effort>0.4) sub2 <- subset(bird.dat2,effort<=0.4) sub1$effort <- sub1$effort/2 bird.dat2 <- rbind(sub1,sub2) # Values of the year as actual numbers (e.g. 1996) make convergence hard as they are # such big numbers. So scale to be 1=min.year: bird.dat2$year <- as.numeric(as.character(bird.dat2$year)) bird.dat2$year <- bird.dat2$year-min.year+1 # Create an 'object' column, with a unique index for each row. bird.dat2$object <- seq(1,nrow(bird.dat2)) # The procedure in mrds assumes that the 'observer' field is used for double observer # transects, so change the observer field to a vector of 1s, and put the observer code in # a different field 'observer.code'. bird.dat2$observer.code <- bird.dat2$observer bird.dat2$observer <- rep(1,length(bird.dat2$observer)) # Remove any habitat types which don't have a big enough sample size of observations. # Also remove any observations which don't have a habitat type recorded. # Use table(bird.dat2$habs1) to check the sample sizes. bird.dat2 <- bird.dat2[bird.dat2$habs1%in% c("A","B","C","D","E","F","G","H","I"),] bird.dat2$habs1 <- bird.dat2$habs1[drop=T] # Removing any with less than 20: table.hab <- table(bird.dat2$habs1) bird.dat2$habs1 <- as.character(bird.dat2$habs1) bird.dat2$habs2 <- bird.dat2$habs1 if ((table.hab["H"]<=20|is.na(table.hab["H"])) | (table.hab["I"]<=20|is.na(table.hab["I"])) | (table.hab["G"]<=20|is.na(table.hab["G"]))) { for(i in 1:nrow(bird.dat2)){ bird.dat2$habs2[i] <- ifelse(bird.dat2$habs1[i] %in% c("G","H","I"),"GHI",bird.dat2$habs1[i]) } } if ((table.hab["C"]<=20|is.na(table.hab["C"]<=20)) | (table.hab["D"]<=20|is.na(table.hab["D"]))) { for(i in 1:nrow(bird.dat2)){ bird.dat2$habs2[i] <- ifelse(bird.dat2$habs1[i] %in% c("C","D"),"CD",bird.dat2$habs2[i]) } } if ((table.hab["A"]<=20|is.na(table.hab["A"]<=20)) | (table.hab["B"]<=20|is.na(table.hab["B"]<=20))) { for(i in 1:nrow(bird.dat2)){ bird.dat2$habs2[i] <- ifelse(bird.dat2$habs1[i] %in% c("A","B"),"AB",bird.dat2$habs2[i]) } } if (any(table(bird.dat2$habs2)<=20)) print ("There are still habitats <=20") bird.dat2$habs1.old <- bird.dat2$habs1 bird.dat2$habs1 <- bird.dat2$habs2 bird.dat2$habs1 <- as.factor(bird.dat2$habs1) bird.dat3 <- bird.dat2 bird.dat3$habs1 <- bird.dat3$habs1[drop=T] bird.dat8 <- bird.dat3 # Jumped to bird.dat8 as we don't consider speed, etc. #n<-function(x){ as.numeric(as.character(x))} #bird.dat8$vis<-n(bird.dat8$vis) bird.dat8 <- subset(bird.dat8, !is.na(habs1)) # Makes one line for each individual observation: bird.dat9 <- bird.dat8 bird.dat8 <- bird.dat8[-c(1:nrow(bird.dat8)),] bird.dat.null <- bird.dat8 print(Sys.time()) batch <- 0 if (nrow(bird.dat9)>10000) { for (batch in 1:(floor(nrow(bird.dat9)/10000))){ print (paste("Processing batch number",batch,"of",floor(nrow(bird.dat9)/10000)+1)) linecounter <- 1 temp <- bird.dat.null for(i in 1:10000){ n <- bird.dat9$detected[(batch-1)*10000+i] temp[linecounter:(linecounter+n-1),] <- bird.dat9[(batch-1)*10000+i,] linecounter <- linecounter+n } # closes i bird.dat8 <- rbind(bird.dat8,temp) } # closes batch } # closes if batch <- batch+1 print (paste("Processing batch number",batch,"of",floor(nrow(bird.dat9)/10000)+1)) print (Sys.time()) linecounter <- 1 temp <- bird.dat.null for(i in 1:(ifelse(nrow(bird.dat9)>10000, nrow(bird.dat9)%%((batch-1)*10000), nrow(bird.dat9)))){ n <- bird.dat9$detected[(batch-1)*10000+i] temp[linecounter:(linecounter+n-1),] <- bird.dat9[(batch-1)*10000+i,] linecounter <- linecounter+n } bird.dat8 <- rbind(bird.dat8,temp) bird.dat8$detected <- rep(1,nrow(bird.dat8)) bird.dat8$size <- rep(1,nrow(bird.dat8)) bird.dat8$object <- seq(1,nrow(bird.dat8),by=1) bird.dat8$habs1 <- as.character(bird.dat8$habs1) # gets rid of 9s (code for missing values) bird.dat8 <- subset(bird.dat8, visit!=9) ######################## # RUNNING THE MODELS # # As the purpose is running these models for a wide range of species, we need to keep # computing time within reasonable limits. # For this reason we decided to fit only one models with visit and habitat # as predictors. Sys.time() ddf.visit.habs1 <- ddf(~mcds(key="hn",formula=~as.factor(habs1)+visit), data=bird.dat8, method="ds") Sys.time() final <- ddf.visit.habs1 save.image("Data/temporary rescue point.Rdata") load("Data/temporary rescue point.Rdata") ############################################################### # ESTIMATE DETECTABILITY AT THE SQUARE LEVEL ON ALL SQUARES # Need the program "final" (a distance sampling model output) and the counts from # each transect section of each square with the habitat for each transect section. # This is used to sum the counts from each habitat, on each square. # For the prediction step if the bird is a resident, only the first visit is used. # And if it is a migrant, only the second visit is used. # Therefore, if "visit" is a variable in the model "final", be careful to predict # detecability in squares based only on the visit type which is going to be used # for the abundance estimation. e.g for residents predict detectability in the # first visit of the season. filename <- ifelse(substr(species,2,2)==".", paste(substr(species,1,1),"_ ",miny,maxy," squr zT.txt", sep=""), paste(species," ",miny,maxy," squr zT.txt", sep="")) if (length(list.files("Data",pattern=filename))==1) { bird.dat.xx.sz<-read.table(paste("Data/",filename,sep=""), sep=",", header=T) } else { print(Sys.time()) print(paste(filename,"has not been found")) print("Data are now being read from the BBS folder") print("This may take very long(several hours for the most abundant species!)") wd <- getwd() setwd("Z:/bbs") bird.dat.xx.sz <- format.data.all.yr.square(spec.code=species, min.year=min.year, max.year=max.year, zero.obs.squares=T) # It often gives me this warnings, but the data frame seems ok: # In readLines(file.loc) : incomplete final line found on 'data05/ebird05' setwd(wd) write.table(bird.dat.xx.sz,paste("Data/",filename,sep=""),sep=",") print(Sys.time()) } # Run the following to get the square-visit-level information: # Include zero squares for the prediction step # Need to work out how many observation there were in each habitat per square: ag.t <- aggregate(bird.dat$detect, by=list(bird.dat$site, bird.dat$year, bird.dat$eorl), mean) sites <- as.character(ag.t$Group.1) years <- ag.t$Group.2 eorls <- as.character(ag.t$Group.3) habAdt<-habBdt<-habCdt<-habDdt<-habEdt<-habFdt<-habGdt<-habHdt<-habIdt<-vector(length=length(sites)) hab.det <- as.data.frame(cbind(habAdt,habBdt,habCdt,habDdt,habEdt,habFdt,habGdt,habHdt,habIdt,sites,eorls,years)) hab.det[,c(1:9)] <- matrix(nrow=length(sites),ncol=9,rep(0,9*length(sites))) habs <- c("A","B","C","D","E","F","G","H","I") for(i in 1:nrow(hab.det)){ sub<-subset(bird.dat,site==sites[i] & eorl==eorls[i] & year==years[i]) if(nrow(sub)>0){ for(j in 1:length(habs)){ g<-grep(habs[j],sub$habs1) if(length(g)>0){ hab.det[i,j]<-sum(sub$detected[g]) } # close if } # close j } # close if } # close i hab.det$siteeorl <- paste(hab.det$sites,hab.det$eorl,hab.det$year,sep="") # Match up the habitat counts with the square level information: # Don't have the no of transects info for some squares: bird.s2<-subset(bird.dat.xx.sz,!is.na(habA)) ## Chose whether "E"arly or "L"ate visits: ## "E" if resident; "L" if migratory. #if (Visit=="E"|Visit=="L") bird.s3 <- subset(bird.s2,eorl==Visit) #if (Visit=="M") { # bird.s2.1 <- aggregate(bird.s2$detected, by=list(bird.s2$site, bird.s2$year, bird.s2$dist.band), FUN=max) # names(bird.s2.1)<-c("site","year","dist.band","detected") # bird.s3<-bird.s2.1 #} #bird.s3<-subset(bird.s3,dist.band==1) bird.s3<-subset(bird.s2,dist.band==1) # Merge the two datasets and delete the variable "detected" to avoid confusion bird.s3$siteeorl <- paste(bird.s3$site, bird.s3$eorl, bird.s3$year, sep="") bird.s4 <- merge(bird.s3,hab.det,by="siteeorl",all.x=T) bird.s4 <- subset(bird.s4, select=-detected) # Fill in zeros where no observations were made: null.sites<-grep(TRUE,is.na(bird.s4$sites)) bird.s4[null.sites,c("habAdt","habBdt","habCdt","habDdt","habEdt","habFdt","habGdt","habHdt","habIdt")]<-0 # Amalgamate habitats which are from now on "the same": # This will be different for each species! # Also, be careful not to run more than once, otherwise the estimates are out. #bird.s4$habH<-bird.s4$habH+bird.s4$habI #bird.s4$habI <- 0 #bird.s4$habHdt<-bird.s4$habHdt+bird.s4$habIdt #bird.s4$habIdt <- 0 bird.s5<-bird.s4 # Specify the pooled habitats: # A B C D E F G H I habs<-c("A","B","C","D","E","F","G","H","I") if (any(names(table(bird.dat8$habs1))=="GHI")) { habs[c(7,8,9)]<-c("GHI","GHI","GHI") } if (any(names(table(bird.dat8$habs1))=="CD")) { habs[c(3,4)]<-c("CD","CD") } if (any(names(table(bird.dat8$habs1))=="AB")) { habs[c(1,2)]<-c("AB","AB") } # Work out the total detections and total transects for each square: st<-grep("habA",colnames(bird.s4)) st1<-st[1]-1 st2<-st[2]-1 tot.tran<-tot.det<-vector(length=nrow(bird.s5)) for(i in 1:nrow(bird.s5)){ tot.tran[i]<-sum(bird.s5[i,c(st1+1:9)]) tot.det[i]<-sum(bird.s5[i,c(st2+1:9)]) } bird.s5<-cbind(bird.s5,tot.tran,tot.det) bird.s5<-subset(bird.s5,tot.tran<11) bird.s5<-subset(bird.s5,tot.tran>0) # create visit and speed in the same way when we ran the model bird.s5$visit<-bird.s5$speed<-NA bird.s5$visit<-ifelse(bird.s5$eorl=="E", 1,0) # Temporary rescue point 2 save.image("Data/temporary rescue point 2.Rdata") #load("Data/temporary rescue point 2.Rdata") # The following loop takes about 20 mins habs1 <- as.vector(names(table(bird.dat8$habs1))) fit.vec<-vector() Sys.time() for(i in 1:nrow(bird.s5)){ sub <- bird.s5[i,] visit <- rep(sub$visit,length(habs1)) nd <- as.data.frame(cbind(habs1,visit)) nd$visit <- as.numeric(as.character(nd$visit)) fitted <- predict.ds(final, newdata=nd, compute=T)$fitted[,1] fit <- as.data.frame(cbind(habs1,fitted)) colnames(fit)[1]<-"habs" # Match up pooled habitats: ha <- as.data.frame(cbind(1:9,habs)) ha2 <- merge(ha,fit,by="habs",all.x=T) fit.hab <- as.numeric(as.character(ha2$fitted)) # Find which habitats are in the square and in what nos: g1 <- grep(TRUE,bird.s5[i,st1+1:9]>0) # Calculate the counts in each habitat and the weights: ct <- bird.s5[i,st2+g1] wt <- ct+bird.s5[i,st1+g1] # Calculate the square detectability: fit.vec[i] <- sum(fit.hab[g1]*wt)/sum(wt) if (i%%10000==0) print(paste(i,"of",nrow(bird.s5))) } bird.s6 <-cbind(bird.s5,fit.vec) save.image("temporary rescue point whinchat.Rdata") Sys.time() # THIS MUST BE CHECKED #if (Visit=="E"|Visit=="L") { # birds<-subset(bird.s6,eorl==Visit, select=c("site","year","eorl","tot.det","fit.vec","birds")) #} if (Visit=="M") { #bird.s6$est.birds <- bird.s6$tot.det/bird.s6$fit.vec bird.s6$eorl <- as.character(bird.s6$eorl) bird.s6.E <- subset(bird.s6, eorl=="E") bird.s6.L <- subset(bird.s6, eorl=="L") bird.s7 <- merge(bird.s6.E,bird.s6.L,by=c("site","year")) bird.s7 <- subset(bird.s7, select=c("site","year","eorl.x","tot.det.x","fit.vec.x","eorl.y","tot.det.y","fit.vec.y")) # compare birds detected during early and late visit and set best to: # 0 if same number; 1 if more birds for early visit; 2 for late visit best <- ifelse(bird.s7$tot.det.x==bird.s7$tot.det.y, 0, 2) best <- ifelse(bird.s7$tot.det.x>bird.s7$tot.det.y, 1, best) birds <- bird.s7[,1:2] birds$eorl <- ifelse(best==0, "B", "L") birds$eorl <- ifelse(best==1, "E", birds$eorl) birds$tot.det <- ifelse(best==1, bird.s7$tot.det.x, bird.s7$tot.det.y) birds$fit.vec <- ifelse(best==0, (bird.s7$fit.vec.x+bird.s7$fit.vec.y)/2, bird.s7$fit.vec.y) birds$fit.vec <- ifelse(best==1, bird.s7$fit.vec.x, birds$fit.vec) } imagename <- paste("Data/",species," Step 1.Rdata",sep="") save.image(imagename) #load(imagename) filename <- paste("Data/",species,"detect.csv",sep="") write.csv(birds, filename, row.names=F) print(paste("End of Step 1 for ",species,". Visit: ",Visit,sep=""))
6a1f581174bd779fc89210f6d9c7e4ea560a61d7
5eb745b3373899c8531e180b1404e545cf3ba150
/man/calc.ctmax.Rd
b665da89f9cd6c0be2d56ecee1eeec86d3e602d6
[]
no_license
qPharmetra/qpNCA
8a8e5a4bebf22ef9e3b005f7a3809102aacdb250
bde363e64dba0ce5ddbc01fc4211dab471a1f3ee
refs/heads/master
2022-01-16T18:05:24.976496
2022-01-11T16:38:36
2022-01-11T16:38:36
171,545,252
4
2
null
2021-10-17T18:16:50
2019-02-19T20:33:30
R
UTF-8
R
false
true
1,159
rd
calc.ctmax.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/calc.ctmax.r \name{calc.ctmax} \alias{calc.ctmax} \title{Calculate Cmax and Tmax} \usage{ calc.ctmax(x, by = NULL, timevar = "time", depvar = "dv") } \arguments{ \item{x}{data.frame} \item{by}{character: column names in x indicating grouping variables; default is as.character(dplyr::groups(x))} \item{timevar}{variable name containing the actual sampling time after dose} \item{depvar}{variable name containing the dependent variable (e.g., concentration)} } \value{ A dataset with estimates for the Cmax (maximum concentration) and Tmax (time of first occurence of cmax) parameters: one observation per subject } \description{ Calculates Cmax and Tmax from raw data for each PK curve defined using \code{by}. \cr } \details{ Input dataset can contain all uncorrected data, including LOQ; estimate first occurence of maximum concentration for each PK curve; if all concentrations are NA, sets Cmax and Tmax also to NA. } \examples{ \donttest{ library(magrittr) library(dplyr) data(ncx) x <- ncx x \%<>\% group_by(subject) x \%<>\% correct.loq x \%>\% calc.ctmax \%>\% head } }
28d65786e8f814049c011dce4c044c6790703646
a0aacfded5e9cc6b90ee9e4a5dcd41d80f6015e9
/tests/testthat/test_loading.R
9baeec71b0a5f7aec3b76fb0d4039add13cf9d4a
[ "MIT", "CC-BY-4.0" ]
permissive
lbusett/antanym
f86746bcb777e699c75cd6354188540d8b9a337d
2a6fee4e09dc039922832a04b6ec14ba3032e659
refs/heads/master
2020-03-11T05:15:28.618319
2018-04-22T21:13:56
2018-04-22T21:13:56
129,797,394
0
0
MIT
2018-04-16T19:50:51
2018-04-16T19:50:51
null
UTF-8
R
false
false
600
r
test_loading.R
context("fetching and caching data") test_that("caching works", { skip_on_cran() cdir <- tempdir() cfile <- file.path(cdir,"gaz_data.csv") if (file.exists(cfile)) file.remove(cfile) g <- an_read(cache_dir=cdir) expect_true(file.exists(cfile)) finfo <- file.info(cfile) ## re-read using cache g <- an_read(cache_dir=cdir) expect_identical(finfo$mtime,file.info(cfile)$mtime) ## refresh cache g <- an_read(cache_dir=cdir,refresh_cache=TRUE) ## mtime should have changed expect_gt(as.numeric(file.info(cfile)$mtime),as.numeric(finfo$mtime)) })
c81281f0483975d4a07edf712d68227e0f0f7ad1
f3ed3d52b590f89643c66eb95c649c9e69d54387
/MSDS6306_DoingDS/class_work/Unit10/livesession_code_EDA.r
97885d577a11b6e818c9ede5fef032a0733978ba
[]
no_license
khthomas/SMU_MSDS
39803cbac55d04bdae2fdc2c520fde2ac8b403cb
25b76caa80ff7e1c5a88951b993bf464247142cc
refs/heads/master
2021-09-06T15:27:09.069180
2018-02-08T02:23:12
2018-02-08T02:23:12
104,568,801
0
1
null
null
null
null
UTF-8
R
false
false
1,794
r
livesession_code_EDA.r
library(ggplot2) library(reshape2) files = "http://stat.columbia.edu/~rachel/datasets/nyt" listofsets = data.frame(col1="test") #This will grab all of the data and put it into a list of dataframes... it is really slow. for (x in 1:31) { listDF = list() link = paste(files, x, ".csv", sep="") holding = read.csv(url(link)) listDF[[x]] = holding } ### This will get you as far as needed for the live session. You may need to change which dataset is needed fileLocation <- "http://stat.columbia.edu/~rachel/datasets/nyt2.csv" data1 <- read.csv(url(fileLocation)) #Cut takes a variable and binds it. Above the first group is -Inf to 18, then 18 to 24 etc. data1$Age_Group <- cut(data1$Age, c(-Inf, 18, 24, 34, 44, 54, 64, Inf)) #change the levels to be more meaningful when read (changed the factors) levels(data1$Age_Group) <- c("<18", "18-24", "25-34", "35-44", "45-54", "55-64", "65+") #Problem: Click Through Rate (CTR) is notoriously small -- very few people click at all # Can I get click through rate for our website? That could be interesting. Where can you get that data? d1 = subset(data1, Impressions > 0) d1$CTR = d1$Clicks/d1$Impressions #change gender variable to a factor for GGplot d1$Gender = as.factor(d1$Gender) #Impressions by Gender ggplot(d1, aes(x=Impressions, fill=Age_Group)) + theme(plot.title =element_text(hjust = 0.5)) + geom_histogram(binwidth = 1) + ggtitle("Impressions by Age Group") #CTR by Gender ggplot(subset(d1, CTR>0), aes(x=CTR, fill=Gender)) + geom_histogram(binwidth = 0.05) + ggtitle("CTR by Gender") + theme(plot.title = element_text(hjust = 0.5)) + xlab("Probability of Click Through Rate: Clicks per Impression") + ylab("Count") + scale_fill_brewer(palette = "Dark2", labels=c("Female", "Male"))
ebef5c886a7f082ae4a1b921930847b1e278b3bd
0a0a04adad2a286a74017b572e51dc82dc3ef786
/inst/examplepkg/R/hypotenuse.R
44cfd202889469dd16e99252a0d6216e1b099362
[ "MIT" ]
permissive
armcn/covtracer
7e408e67a8ac1376e397a19cff7dc9dfa23f1ac2
9ccfacd171a2698bca7935f6bc88241d04b78d11
refs/heads/main
2023-08-18T20:40:23.765988
2021-09-30T15:56:29
2021-09-30T15:56:29
411,432,330
0
0
NOASSERTION
2021-09-28T20:40:59
2021-09-28T20:40:58
null
UTF-8
R
false
false
160
r
hypotenuse.R
#' Calculate the hypotenuse provided two edge lengths #' #' @param a,b edge lengths #' #' @export #' hypotenuse <- function(a, b) { return(sqrt(a^2 + b^2)) }
68634ca1d8319c0c39b4458b224f96b723399780
9fde3b252f2064d92ed109656802ff87b32d3084
/enhancer.R
d255e5d52ab4af485499516ac2ab0b8de1797828
[]
no_license
rachelGoldfeder/cfDNA
e87b6b8698e1b6b6925d566bbd1a3d220b4eef9c
a686bdcf8d27c3df9cabbd2818991918649e7d61
refs/heads/master
2021-07-24T18:37:05.908782
2019-01-08T21:04:34
2019-01-08T21:04:34
104,079,609
1
1
null
null
null
null
UTF-8
R
false
false
1,974
r
enhancer.R
#! /usr/bin/env Rscript args = commandArgs(trailingOnly=TRUE) samphmc=args[1] sampmc=args[2] sampname=args[3] library(data.table) methcalls=getwd() setwd(paste0(methcalls)) a=as.data.frame(fread(paste0(samphmc))) b=as.data.frame(fread(paste0(sampmc))) feat.mat=matrix(ncol=3,nrow=7) ct=1 sum=0 for(i in c("enhancer","super_enhancer")){ feat=nrow(unique((subset(a,V15==i))[c(1:3)])) feat.mat[ct,1] = paste0("hmc_",sampname) feat.mat[ct,2] = i feat.mat[ct,3] = feat ct=ct+1 sum=sum+feat } not=nrow(unique((subset(a,V15!="enhancer"&V15!="super_enhancer"))[c(1:3)])) feat.mat[3,]=c(paste0("hmc_",sampname),".",not) sum=sum+not feat.mat[4,]= c(paste0("hmc_",sampname),"sum",sum) ct=5 sum=0 for(i in c("enhancer",".")){ feat=nrow(unique((subset(a,V14==i))[c(1:3)])) feat.mat[ct,1] = paste0("hmc_",sampname) feat.mat[ct,2] = i feat.mat[ct,3] = feat ct=ct+1 sum=sum+feat } feat.mat[7,]= c(paste0("hmc_",sampname),"sum",sum) setwd(paste0(methcalls,"/plots")) write.table(feat.mat,paste0(sampname,"_feat_gene.txt"),col.names = F,row.names=FALSE, quote=FALSE, sep = "\t", append=T) feat.mat=matrix(ncol=3,nrow=7) ct=1 sum=0 for(i in c("enhancer","super_enhancer")){ feat=nrow(unique((subset(b,V12==i))[c(1:3)])) feat.mat[ct,1] = paste0("mc_",sampname) feat.mat[ct,2] = i feat.mat[ct,3] = feat ct=ct+1 sum=sum+feat } not=nrow(unique((subset(b,V12!="enhancer"&V12!="super_enhancer"))[c(1:3)])) feat.mat[3,]=c(paste0("mc_",sampname),".",not) sum=sum+not feat.mat[4,]= c(paste0("mc_",sampname),"sum",sum) ct=5 sum=0 for(i in c("enhancer",".")){ feat=nrow(unique((subset(b,V11==i))[c(1:3)])) feat.mat[ct,1] = paste0("mc_",sampname) feat.mat[ct,2] = i feat.mat[ct,3] = feat ct=ct+1 sum=sum+feat } feat.mat[7,]= c(paste0("mc_",sampname),"sum",sum) write.table(feat.mat,paste0(sampname,"_feat_gene.txt"),col.names = F,row.names=FALSE, quote=FALSE, sep = "\t", append=T)
e076561ef694415949afe4bcd79772aff55662bf
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/TreeBUGS/examples/getParam.Rd.R
6cd16a4eabad0ce6edfc1d7e943ec734ea258d85
[]
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
387
r
getParam.Rd.R
library(TreeBUGS) ### Name: getParam ### Title: Get Parameter Posterior Statistics ### Aliases: getParam ### ** Examples ## Not run: ##D # mean estimates per person: ##D getParam(fittedModel, parameter = "theta") ##D ##D # save summary of individual estimates: ##D getParam(fittedModel, parameter = "theta", ##D stat = "summary", file= "ind_summ.csv") ## End(Not run)
c2c483c710e28b67e5c0daf206f7c2d09fba76dc
9c781801315fb834cf4a39db4fb12db7a585002e
/Genetics/finalSubmission/SupportingInformation/plotLikelihoodComparisons.R
3d785d578d47ea1396f6bdf81718194bd57f11d3
[]
no_license
alexpopinga/CoalSIR
64a57ef6a79a73d61aafb3c548de522015e205ef
1f32e1ead268468c269f2f7ab730dbead6b04977
refs/heads/master
2021-04-26T23:27:15.868645
2018-03-06T00:43:56
2018-03-06T00:43:56
123,997,532
0
0
null
null
null
null
UTF-8
R
false
false
2,807
r
plotLikelihoodComparisons.R
source('likelihoodEstimator.R') regenerate <- FALSE ###### MAIN ###### if (regenerate) { gamma <- 0.3 beta <- 0.00075 S0 <- 999 origin <- 12.7808530307 tree <- read.tree('VolzSIRgamma_truth.tree') gammaVec <- seq(.1,.7,by=.05) # Estimate STOCHASTIC coalescent likelihoods for different gammas Ntraj <- 10000 Nensemb <- 10 llensemb <- list() for (e in 1:Nensemb) llensemb[[e]] <- rep(0,length(gammaVec)) Nensemb <- 10 llensemb <- list() for (e in 1:Nensemb) llensemb[[e]] <- rep(0,length(gammaVec)) for (i in 1:length(gammaVec)) { for (e in 1:Nensemb) { llensemb[[e]][i] <- getCoalescentTreeDensity(tree, beta, gammaVec[i], S0, origin, Ntraj) } } llmean <- rep(0,length(gammaVec)) llsd <- rep(0, length(gammaVec)) for (i in 1:length(gammaVec)) { thisEnsemble <- rep(0, Nensemb) for (e in 1:Nensemb) { thisEnsemble[e] <- llensemb[[e]][i] } llmean[i] <- mean(thisEnsemble) llsd[i] <- sd(thisEnsemble) } # Estimate DETERMINISTIC coalescent likelihoods for different gammas gammaVecDet <- seq(0.1,0.35,by=0.01) lldet <- rep(0, length(gammaVecDet)) for (i in 1:length(gammaVecDet)) { lldet[i] <- getDeterministicCoalescentTreeDensity(tree, beta, gammaVecDet[i], S0, origin) } } else { load(file='likelihoodResultsFromR10000_noCorrection.RData') } # Load in Java code results for same tree: df <- read.table('likelihoodResultsFromJava_noCorrection.txt', header=T) javaGamma <- df$gamma javaLogP <- df$logP javaSD <- apply(df[,3:12], 1, sd) # Create figure pdf('gammaLikelihoodComparison_noCorrection.pdf', width=7, height=5) plot(gammaVec, llmean, 'o', #ylim=c(-440,-400), xlab=expression(gamma), ylab='Log likelihood', main='Log likelihoods from simulated tree', col='blue') lines(gammaVec, llmean+2*llsd, lty=2, col='blue') lines(gammaVec, llmean-2*llsd, lty=2, col='blue') lines(javaGamma, javaLogP, 'o', col='red') lines(javaGamma, javaLogP+2*javaSD, lty=2, col='red') lines(javaGamma, javaLogP-2*javaSD, lty=2, col='red') #lines(gammaVecDet, lldet, 'o', col='purple') lines(c(0.3,0.3), c(-1e10,1e10), lty=2, col='grey', lwd=2) #legend('bottomright', inset=.05, c('R','Java (10000)','R (det.)', 'Truth'), lty=c(1,1,1,2), pch=c(1,1,1,NA), lwd=c(1,1,1,2), col=c('blue','red','purple','grey')) legend('bottomright', inset=.05, c('R 10*(10^4+)','Java 10*(10^4+)', '+/- 2*SD', 'Truth'), lty=c(1,1,2,2), pch=c(1,1,NA,NA), lwd=c(1,1,1,2), col=c('blue','red','black','grey')) #legend('bottomright', inset=.05, c('R','Java (10000)', '+/- 2*SD', 'Truth'), lty=c(1,1,2,2), pch=c(1,1,NA,NA), lwd=c(1,1,1,2), col=c('blue','red','black','grey')) dev.off()
51f590c56530d7a77a9bbec8b502626cdddf6a35
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/gtx/examples/make.moments2.Rd.R
2a91c952123841c6836998a7859f07e445bba9da
[]
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
247
r
make.moments2.Rd.R
library(gtx) ### Name: make.moments2 ### Title: Build matrix of second moments from subject-specific data. ### Aliases: make.moments2 ### ** Examples data(mthfrex) xtx <- make.moments2(mthfr.params, c("SBP", "DBP", "SexC", "Age"), mthfrex)
4e1fe3de4bfa4475a3ae9706a3b3d8e0e227daff
e79b09555dfc727b7e88a5942a155e1847630732
/plot_strat_ox_budget_eval.R
9120b1acb1b4dd0da62e8713924bf3b02e4b9397
[]
no_license
paultgriffiths/R_pyle
70b15e96c5dd7b2eef04aca69e5d11a8673c229c
0bc83cb1f3c2fa3c04c4cca36861c936163a9eb4
refs/heads/master
2021-09-10T21:22:11.776270
2018-04-02T12:09:10
2018-04-02T12:12:37
null
0
0
null
null
null
null
UTF-8
R
false
false
6,950
r
plot_strat_ox_budget_eval.R
# R script to plot and calculate the contribution of # different ozone loss reactions to the total loss # Alex Archibald, July 2012 # loop vars i <- NULL; j <- NULL nav <- 6.02214179E23 conv.factor <- 60*60*24*30*48*(1e-12) # extract/define variables lon <- get.var.ncdf(nc1, "longitude") lat <- get.var.ncdf(nc1, "latitude") hgt <- get.var.ncdf(nc1, "hybrid_ht")*1E-3 time <- get.var.ncdf(nc1, "t") # define empty arrays to hold data for (i in 1:12) { assign(paste("l",i,".std", sep=""), array(NA, dim=c(length(lon), length(lat), length(hgt), length(time)) ) ) } # Check to see if a trop. mask and mass exist? if ( exists("mask") == TRUE) print("Tropospheric Mask exists, carrying on") else (source(paste(script.dir, "calc_trop_mask.R", sep=""))) # copy the mask that is for the troposphere strat.mask <- 1-(mask) # extract the fluxes. These are based on the 12 Ox cycles # from Lee et al., JGR 2001 p1 <- get.var.ncdf(nc1, st.prod.code) l1 <- get.var.ncdf(nc1, st.loss1.code) l2 <- get.var.ncdf(nc1, st.loss2.code) l3 <- get.var.ncdf(nc1, st.loss3.code) l4 <- get.var.ncdf(nc1, st.loss4.code) l5 <- get.var.ncdf(nc1, st.loss5.code) l6 <- get.var.ncdf(nc1, st.loss6.code) l7 <- get.var.ncdf(nc1, st.loss7.code) l8 <- get.var.ncdf(nc1, st.loss8.code) l9 <- get.var.ncdf(nc1, st.loss9.code) l10 <- get.var.ncdf(nc1, st.loss10.code) l11 <- get.var.ncdf(nc1, st.loss11.code) l12 <- get.var.ncdf(nc1, st.loss12.code) # calculate the total fluxes in Tg/y # in the stratosphere production <- sum( (p1*strat.mask) )*conv.factor cyc1 <- sum( (l1*strat.mask) )*conv.factor cyc1 <- sum( (l1*strat.mask) )*conv.factor cyc2 <- sum( (l2*strat.mask) )*conv.factor cyc3 <- sum( (l3*strat.mask) )*conv.factor cyc4 <- sum( (l4*strat.mask) )*conv.factor cyc5 <- sum( (l5*strat.mask) )*conv.factor cyc6 <- sum( (l6*strat.mask) )*conv.factor cyc7 <- sum( (l7*strat.mask) )*conv.factor cyc8 <- sum( (l8*strat.mask) )*conv.factor cyc9 <- sum( (l9*strat.mask) )*conv.factor cyc10 <- sum( (l10*strat.mask) )*conv.factor cyc11 <- sum( (l11*strat.mask) )*conv.factor cyc12 <- sum( (l12*strat.mask) )*conv.factor # convert from moles/gridbox/s -> molecules/cm3/s for (i in 1:length(time) ) { l1.std[,,,i] <- ( l1[,,,i]/(vol*1E6))*nav l2.std[,,,i] <- ( l2[,,,i]/(vol*1E6))*nav l3.std[,,,i] <- ( l3[,,,i]/(vol*1E6))*nav l4.std[,,,i] <- ( l4[,,,i]/(vol*1E6))*nav l5.std[,,,i] <- ( l5[,,,i]/(vol*1E6))*nav l6.std[,,,i] <- ( l6[,,,i]/(vol*1E6))*nav l7.std[,,,i] <- ( l7[,,,i]/(vol*1E6))*nav l8.std[,,,i] <- ( l8[,,,i]/(vol*1E6))*nav l9.std[,,,i] <- ( l9[,,,i]/(vol*1E6))*nav l10.std[,,,i] <- ( l10[,,,i]/(vol*1E6))*nav l11.std[,,,i] <- ( l11[,,,i]/(vol*1E6))*nav l12.std[,,,i] <- ( l12[,,,i]/(vol*1E6))*nav } # find mid latitude grid box and do a zonal mean mid.lat <- which(lat >=37.50)[1] cyc.1 <- apply(l1.std[,mid.lat,,4], c(2), mean) cyc.2 <- apply(l2.std[,mid.lat,,4], c(2), mean) cyc.3 <- apply(l3.std[,mid.lat,,4], c(2), mean) cyc.4 <- apply(l4.std[,mid.lat,,4], c(2), mean) cyc.5 <- apply(l5.std[,mid.lat,,4], c(2), mean) cyc.6 <- apply(l6.std[,mid.lat,,4], c(2), mean) cyc.7 <- apply(l7.std[,mid.lat,,4], c(2), mean) cyc.8 <- apply(l8.std[,mid.lat,,4], c(2), mean) cyc.9 <- apply(l9.std[,mid.lat,,4], c(2), mean) cyc.10 <- apply(l10.std[,mid.lat,,4], c(2), mean) cyc.11 <- apply(l11.std[,mid.lat,,4], c(2), mean) cyc.12 <- apply(l12.std[,mid.lat,,4], c(2), mean) # ################################################################################################################################### # plot a mid latitude profile of the different cycles pdf(file=paste(out.dir,mod1.name,"_strat_o3_loss.pdf", sep=""),width=8,height=6,paper="special",onefile=TRUE,pointsize=12) par(mfrow=c(1,2)) ## Is this just repetition?? ## cyc.1 <- apply(l1.std[,mid.lat,,4], c(2), mean) cyc.2 <- apply(l2.std[,mid.lat,,4], c(2), mean) cyc.3 <- apply(l3.std[,mid.lat,,4], c(2), mean) cyc.4 <- apply(l4.std[,mid.lat,,4], c(2), mean) cyc.5 <- apply(l5.std[,mid.lat,,4], c(2), mean) cyc.6 <- apply(l6.std[,mid.lat,,4], c(2), mean) cyc.7 <- apply(l7.std[,mid.lat,,4], c(2), mean) cyc.8 <- apply(l8.std[,mid.lat,,4], c(2), mean) cyc.9 <- apply(l9.std[,mid.lat,,4], c(2), mean) cyc.10 <- apply(l10.std[,mid.lat,,4], c(2), mean) cyc.11 <- apply(l11.std[,mid.lat,,4], c(2), mean) cyc.12 <- apply(l12.std[,mid.lat,,4], c(2), mean) # plot the data plot(log10(cyc.1), hgt, type="l", col="red", ylim=c(10,52), xlim=c(0,8), xaxt="n", ylab="Altitude (km)", xlab="Rate of Ox loss", lwd=1.5) lines(log10(cyc.2), hgt, col="red", lty=2, lwd=1.5) lines(log10(cyc.3), hgt, col="blue", lty=1, lwd=1.5) lines(log10(cyc.4), hgt, col="red", lty=3, lwd=1.5) lines(log10(cyc.5), hgt, col="purple", lty=1, lwd=1.5) lines(log10(cyc.6), hgt, col="red", lty=4, lwd=1.5) lines(log10(cyc.7), hgt, col="green", lty=1, lwd=1.5) lines(log10(cyc.8), hgt, col="purple", lty=2, lwd=1.5) lines(log10(cyc.9), hgt, col="blue", lty=2, lwd=1.5) lines(log10(cyc.10), hgt, col="blue", lty=3, lwd=1.5) lines(log10(cyc.11), hgt, col="green", lty=3, lwd=1.5) lines(log10(cyc.12), hgt, col="black", lty=1, lwd=1.5) minor.ticks.axis(1,9,mn=0,mx=8) grid() legend("bottomright", c( expression(paste(h,nu,+Cl[2],O[2], sep="")), "ClO+BrO", expression(paste(HO[2],+O[3], sep="")), expression(paste(ClO+HO[2], sep="")), expression(paste(BrO+HO[2], sep="")), "ClO+O", expression(paste(NO[2],"+O", sep="")), "BrO+O", expression(paste(HO[2],"+O", sep="")), expression(paste(H+O[3], sep="")), expression(paste(h,nu,+NO[3], sep="")), expression(paste(O[3],"+O", sep="")) ), col=c("red","red","blue","red","purple","red","green","purple","blue","blue","green","black"), lty=c(1,2,1,3,1,4,1,2,2,3,3,1), bty="n", cex=0.8 ) par(xpd=NA) text(4,3, expression(paste("(molecules cm"^"-3"," s"^"-1",")", sep="") )) text(12,60, paste("37.5N, March, stratospheric Ox loss:",mod1.name, sep=" ")) par(xpd=FALSE) total <- rowSums(cbind(cyc.1, cyc.2, cyc.3, cyc.4, cyc.5, cyc.6, cyc.7, cyc.8, cyc.8, cyc.9, cyc.10, cyc.11, cyc.12) ) clox <- rowSums(cbind(cyc.1, cyc.2, cyc.4, cyc.6) ) / total hox <- rowSums(cbind(cyc.3, cyc.9, cyc.10) ) / total brox <- rowSums(cbind(cyc.5, cyc.8) ) / total nox <- rowSums(cbind(cyc.7, cyc.11) ) / total ox <- cyc.12 / total ox.loss <- data.frame(clox, hox, brox, nox, ox) plot(ox.loss$clox*100, hgt, ylim=c(10,52), xlim=c(0,100), lwd=2, col="red", type="l", yaxt="n", xlab="Percentage", ylab="") lines(ox.loss$hox*100, hgt, lwd=2, col="blue") lines(ox.loss$brox*100, hgt, lwd=2, col="purple") lines(ox.loss$nox*100, hgt, lwd=2, col="green") lines(ox.loss$ox*100, hgt, lwd=2, col="black") grid() legend(70,30, c( expression(paste(ClO[x], sep="")), expression(paste(HO[x], sep="")), expression(paste(BrO[x], sep="")), expression(paste(NO[x], sep="")), expression(paste(O[x], sep="")) ), col=c("red","blue","purple","green","black"), lty=c(1,1,1,1,1), bty="n", cex=0.8) dev.off()
bf3270b27582914aea9ce0f04c8bb992c1fe4b30
e039685fc9bdac3a7ffbeedb5aa22e4275f5c6a0
/classification/Naive Bayes Classifier.R
48e620e24da2d36010ef49ad069cd8e1fc70268f
[]
no_license
cajogos/r-machine-learning
fb227124d2a393a612b22c065421a96b16c0cbe8
261ebe2c5def39a6db4f31395a9d92fe26a81eda
refs/heads/master
2020-08-21T05:27:38.660252
2019-12-25T19:02:35
2019-12-25T19:02:35
216,102,102
0
0
null
null
null
null
UTF-8
R
false
false
898
r
Naive Bayes Classifier.R
# Classifying data with the Naïve Bayes classifier rm(list = ls(all = TRUE)) # Clean-up environment dev.off() # Clean-up any plots # --- The prepared churn dataset --- # library(C50) data(churn) churnTrain <- churnTrain[, ! names(churnTrain) %in% c("state", "area_code", "account_length")] set.seed(2) ind <- sample(2, nrow(churnTrain), replace = TRUE, prob = c(0.7, 0.3)) trainset <- churnTrain[ind == 1,] testset <- churnTrain[ind == 2, ] # ------ # library(e1071) # install.packages("e1071") classifier <- naiveBayes(trainset[, !names(trainset) %in% c("churn")], trainset$churn) classifier # Generate the classification table bayes.table <- table(predict(classifier, testset[, !names(testset) %in% c("churn")]), testset$churn) bayes.table # Generate a confusion matrix library(caret) confusionMatrix(bayes.table)
a00921785b8b863533ff68d7d62e0f4d63058579
118bc327b85a3ac1b40649dd4559d5f75b913a43
/man/removeCols.Rd
71625c667951126a0eb17bf7ccf3c2963c968135
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
bobverity/bobFunctions
2c613da2db8a3c2eaaffab0a8a5df170240891d4
3bce3fd92e4c30710413b02ea338ad1d987e5782
refs/heads/master
2021-01-17T12:36:57.566104
2018-10-05T10:57:10
2018-10-05T10:57:10
59,672,304
0
0
null
null
null
null
UTF-8
R
false
true
229
rd
removeCols.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/main.R \name{removeCols} \alias{removeCols} \title{removeCols} \usage{ removeCols(df, nameVec) } \description{ Remove named columns from data frame. }
9a5b0ba82171140ac0c39ff6f1cf2fa2d155c3bc
0dd3258d8c04a59d937529b49c8c64f054a23a60
/ruvseq/src/volplot.R
f43b4039471488158089763692c943687ab49de7
[]
no_license
knguyen4221/ruvseq-ag
5f63b1c18073884c8d3770434377eada3857d5ec
4c1b0e9fee27db6b357507169f89997fe7a2ae05
refs/heads/master
2021-09-04T06:53:01.085101
2018-01-11T20:36:17
2018-01-11T20:36:17
114,688,331
0
0
null
2018-01-11T20:36:18
2017-12-18T21:14:19
R
UTF-8
R
false
false
294
r
volplot.R
library(manhattanly) d <- read.table("S:\\Development\\fastq\\analyses\\graphs\\AST\\counts_differentialExpressionAnalysisWithDESeq2_spikeInNorm.csv", header=TRUE, sep = ",", na.rm) colnames(d) <- c( "X", "baseMean", "EFFECTSIZE", "lfcSE", "stat", "pvalue", "P") volcanoly(d)
0a002daa5738039ed36ec3887909e968a30bc90d
9c077831aaa80a56cff9e78303e3b923ff9c66d3
/R/fct_helpers.R
9e8f45c2c7ca666b80870d0b71d5d968715742fe
[ "MIT" ]
permissive
MaryleneH/Exo_activity
ae5df7c3ef80d4a211a8491c4cad3169d8e1707b
18a132862e3ed8fd57c9f3e3eb8154042eee8bb2
refs/heads/main
2023-03-08T10:53:56.720355
2021-02-24T14:36:15
2021-02-24T14:36:15
340,514,066
0
0
null
null
null
null
UTF-8
R
false
false
1,396
r
fct_helpers.R
# Fonction pour échantillonner une table my_sample <- function(dataset,number){ dataset %>% sample_n(number) } # Fonction pour filtrer selon le type d'activité filtrer_activites <- function(dataset,type_activity){ dataset %>% filter(`Activity Type` == type_activity) } # Fonction pour créer un nuage de points selon Distance / Time et Activity Type utils::globalVariables(c("Distance", "Time", "Activity Type","Elev Gain","Date")) graph_dist_time <- function(dataset){ dataset %>% ggplot() + geom_point(aes(x = Distance , y =Time, color = `Activity Type`))+ theme_minimal() } # Fonction pour créer un box_plot selon Time /Distance / Activity type graph_act_time <- function(dataset){ dataset %>% ggplot(aes(x = `Activity Type` , y =Time, color = `Activity Type`)) + geom_boxplot()+ theme_minimal() } # Fonction pour créer un box-plot selon Activity type / Elev Gain graph_act_elev <- function(dataset){ dataset %>% ggplot(aes(x = `Activity Type`, y =`Elev Gain`, color = `Activity Type`) ) + geom_boxplot()+ theme_minimal() } # Fonction pour créer un diagramme en barres selon Date / Distance et Activity Type graph_dist_month <- function(dataset){ dataset %>% ggplot() + aes(x = lubridate::month(Date), y = Distance, fill = `Activity Type`) + geom_col()+ theme_minimal()+ labs(x ="Month") }
6ca6add3ec3d06291c8c7a4c09b8f9df2ef0a416
a4f6b121c2f5a5fa124b464530b783852154ab61
/12. 회귀식(R).R
cb4af3874ec311a1c99c05ccbbfff06a1af0a2ae
[]
no_license
mjkim9001/R_basic
cc1b00a52175643e25be5163b187e33d6c254963
82e3d141de678cc72e72718d14ad5dca7f8d1e58
refs/heads/master
2022-11-20T19:52:52.206895
2020-07-15T07:02:01
2020-07-15T07:02:01
276,788,126
0
0
null
null
null
null
UHC
R
false
false
1,714
r
12. 회귀식(R).R
setwd('c:/Rdata') library(rvest) library(stringr) library(dplyr) View(attitude) cov(attitude) cor(attitude) with(attitude, cor.test(rating, complaints)) cor.test(attitude) plot(attitude) fasu = data.frame(fa, su) fasu lm(su~fa, data = fasu) data = read.csv("cars.csv") data out = lm(dist~speed, data = data) #설명변수를 종속변수에 회귀분석 summary(out) plot(dist~speed, data = data, col="blue") abline(out, col="red") lm(dist~speed+0, data = data) out1 = lm(dist~speed+0, data = data) plot(out1) par(mfrow = c(2, 2)) shapiro.test(data$dist) shapiro.test(log(data$dist)) shapiro.test(sqrt(data$dist)) out3 = lm(sqrt(dist)~speed+0, data = data) summary(out3) plot(out3) out3$fitted.values cbind(data$speed, out3$fitted.values) out2 = lm(sqrt(dist)~speed+0, data = cars) plot(out2) shapiro.test(resid(out2)) data_new = data.frame(speed = data$speed) predict(out2, data_new) predict(out2,data_new,interval="confidence") cbind(data_new$speed, fitted(out2)) # 다중회귀분석 data = read.csv("salary_data.csv") data out = lm(Salary~Experience+score, data=data) out = lm(rating~.-critical, data = attitude) summary(out) backward = step(out, direction = "backward", trace=FALSE) summary(backward) both = step(out, direction = "both", trace = FALSE) summary(both) install.packages("leaps") library(leaps) leaps = regsubsets(rating~., data = attitude, nbest=5) summary(leaps) plot(leaps) plot(leaps, scale= "bic") plot(leaps, scale="adjr2") plot(leaps, scale = "Cp") out_bic=glm(rating~complaints, data = attitude) summary(out_bic) summary.out = summary(leaps) which.max(summary.out$adjr2) summary.out$which[11,] out3 = lm(rating~complaints+learning+advance, data = attitude) summary(out3)
16a090fa493819e389065d8ebc0b144789d4633d
2f6860bf6c18c42b67b563e22a46ea3f6af8207f
/cachematrix.R
5a5d2b24c83a7e38b640bb99c5c0c2e61fabded3
[]
no_license
PooriaM/ProgrammingAssignment2
70aa8bc80f4d1008e4781991bd42f7805f62e1a1
1f20efd140c7641518b5f790ace9d464dd74b9fe
refs/heads/master
2020-07-14T15:47:21.679249
2016-08-03T23:01:35
2016-08-03T23:01:35
64,812,896
0
0
null
2016-08-03T03:43:33
2016-08-03T03:43:31
null
UTF-8
R
false
false
2,124
r
cachematrix.R
## Maxtrix inversion is usually costly, especially when running inside a loop. ## The following functions can compute and cache the inverse of a matrix so ## that they can be looked up later instead of recomputing the inverse. ## Written by:PooriaM ## "makeCacheMatrix"function creates a special "matrix" object that can cache ## its inverse. makeCacheMatrix <- function(x = matrix()) { ## @x: a square invertible matrix ## return: a list containing functions to ## 1. set the matrix ## 2. get the matrix ## 3. set the inverse ## 4. get the inverse ## this list is used as the input to cacheSolve() inv <- NULL set <- function(y) { # use `<<-` to assign a value to an object in an environment # different from the current environment. x <<- y inv <<- NULL } get <- function() x setInverse <- function(inverse) inv <<- inverse getInverse <- function() inv list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) } ## "cacheSolve" function computes the inverse of the "matrix" returned by ## makeCacheMatrix(). If the inverse has already been calculated and the matrix ## has not changed, it'll retrieves the inverse from the cache directly. cacheSolve <- function(x, ...) { ## @x: output of makeCacheMatrix() ## return: inverse of the original matrix input to makeCacheMatrix() inv <- x$getInverse() # if the inverse has already been calculated if(!is.null(inv)) { # get it from the cache and skips the computation. message("getting cached data") return(inv) } # otherwise, calculates the inverse mat <- x$get() inv <- solve(mat, ...) # sets the value of the inverse in the cache via the setInverse function. x$setInverse(inv) return(inv) }
d4b5984bffbdf3fcfd5c19a93bfab9682e3700e2
95cfd39bbc815ddaf2b790dade4c933a2f5cdc7a
/man/fars_read.Rd
85bb311cc70d9732fe626a318ee04345a331650d
[]
no_license
B0Ib0ivrb63B/farsRPackageProj-
81888d906384624d5d451869f12feffff71a1116
6019ab34bae149f00e619f8e2585c8933ccf13d4
refs/heads/master
2020-03-14T08:19:58.317395
2018-04-29T22:47:13
2018-04-29T22:47:13
131,522,740
0
0
null
null
null
null
UTF-8
R
false
true
713
rd
fars_read.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/fars_functions.R \name{fars_read} \alias{fars_read} \title{fars_read} \usage{ fars_read(filename) } \arguments{ \item{filename}{filename of data file} } \value{ A tibble: <number of rows> x 50 cols } \description{ Function to read a semicolon (;) delimited file (including csv, tsv, .gz, .bz2, or .zip) into a tibble from data from the US National Highway Traffic Safety Administration's Fatality Analysis Reporting System. SOURCE: http://www.nhtsa.gov/Data/Fatality-Analysis-Reporting-System-(FARS) } \note{ Using a non-existant filename will result in a trapped error. } \examples{ \dontrun{ fars_read("C://User//data.zip") } }
2a920cbefc0dc9d982fe05fb9a30f5b43b823e61
b7c166227a8ca6773e600bee3f82ed6e4ca61143
/man/BootPI.Rd
4deb183a5d50883d1fbf8af2e53e34c55d261dc5
[]
no_license
cran/BootPR
972b9db21662ec2f1555f8179dd1181d348e1d03
1c4d85c84317defd33826c4a4fe1d1e49e736cb5
refs/heads/master
2022-07-16T01:28:29.178653
2022-06-29T15:10:16
2022-06-29T15:10:16
17,717,260
0
0
null
null
null
null
UTF-8
R
false
false
1,174
rd
BootPI.Rd
\name{BootPI} \alias{BootPI} \title{ Bootstrap prediction intevals and point forecasts with no bias-correction} \description{This function returns bootstrap forecasts and prediction intervals with no bias-correction } \usage{ BootPI(x, p, h, nboot, prob, type) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ a time series data set} \item{p}{ AR order } \item{h}{ the number of forecast periods } \item{nboot}{number of bootstrap iterations } \item{prob}{a vector of probabilities } \item{type}{ "const" for the AR model with intercept only, "const+trend" for the AR model with intercept and trend } } \value{ \item{PI }{ prediction intervals} \item{forecast }{bias-corrected point forecasts} } \references{ Thombs, L. A., & Schucany, W. R. (1990). Bootstrap prediction intervals for autoregression. Journal of the American Statistical Association, 85, 486-492. } \author{ Jae H. Kim } \examples{ data(IPdata) BootPI(IPdata,p=1,h=10,nboot=100,prob=c(0.05,0.95),type="const+trend") } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ ts}
e9a7482904cc5c2bca991d6faf5a9e12451e8ae6
a026f85dbdd045ea2dc5b74df474afd02c3eb9af
/man/last_n_years.Rd
41c1b5c2c20108445a83e3f842843314376a61aa
[]
no_license
selesnow/timeperiodsR
93df215538e9091fd9a9f0f0cb8e95db7735dc9d
3612001767f0dce942cea54f17de22b1d97863af
refs/heads/master
2023-04-27T15:52:19.511667
2023-04-20T10:15:49
2023-04-20T10:15:49
208,013,525
7
0
null
null
null
null
UTF-8
R
false
false
1,769
rd
last_n_years.Rd
\name{last_n_years} \alias{last_n_years} \title{ Start and end of last n years } \description{ Defines first and last date in previous period } \usage{ last_n_years(x = Sys.Date(), n = 1, part = getOption("timeperiodsR.parts"), include_current = F) } \arguments{ \item{x}{Date object} \item{n}{Number of periods for offset} \item{part}{Part of period you need to receive, one of "all", "start", "end","sequence", "length". See details.} \item{include_current}{If TRUE incliding current period in sequence} } \details{ You can get object of tpr class with all components or specify which component you need, use \code{part} for manage this option: \itemize{ \item all - get all components \item start - get only first date of period \item end - get only last date of period \item start - get vector of all dates in period \item length - get number of dates in period } } \value{Object of tpr class} \author{ Alexey Seleznev } \seealso{ For get next other periods see \code{\link[timeperiodsR:last_n_months]{last_n_months()}}, \code{\link[timeperiodsR:last_n_days]{last_n_days()}}, \code{\link[timeperiodsR:last_n_weeks]{last_n_weeks()}}, \code{\link[timeperiodsR:last_n_quarters]{last_n_quarters()}} } \examples{ ## To get start, end and sequence of last 2 years, ## exclude current year last2years <- last_n_years(n = 2) ## include current year last2years_2 <- last_n_years(n = 2, include_current = TRUE) ## To get vector of date sequences last_n_years(n = 2, part = "sequence") last_n_years(n = 2)$sequence seq(last2years) ## Get number of days of last 2 years day_nums <- last_n_years(n = 2, part = "length") last_n_years()$length length(last2years) }
67380e1228dfe3286fb77ed8341e6d8191e5d166
ab76845b0cd8b17b74525042b0c83fbb93cc49d1
/R/redshift_add_column.R
c49a831efebdc8518f9f7879d5a18c1e3dbd5394
[ "MIT" ]
permissive
zapier/redshiftTools
88a9ca49a55b6665b76ae3facc5d01b1dbbcd74d
a2258ab6aa0b3f3250190da436ac020da3d972bb
refs/heads/develop
2021-07-24T19:38:02.674339
2021-04-21T17:03:46
2021-04-21T17:03:46
59,214,680
2
5
MIT
2021-07-14T10:18:40
2016-05-19T14:35:05
R
UTF-8
R
false
false
857
r
redshift_add_column.R
#' Add a column to a redshift table #' #' Add a typed column to a redshift database #' #' @param dbcon Database connection object of type RPostgreSQL #' @param table_name the name of the target table (character) #' @param column_name (character) #' @param redshift_type (character) for the redshift type to assign for this column #' #' @return NULL #' @export rs_add_column <- function(dbcon, table_name, column_name, redshift_type) { if (is_schema(table_name)) { table_name <- schema_to_character(table_name) } if (!column_name %in% DBI::dbListFields(dbcon, table_name)) { DBI::dbGetQuery( dbcon, whisker.render("alter table {{table_name}} add column {{column_name}} {{redshift_type}} default NULL", list(table_name = table_name, column_name = column_name, redshift_type = redshift_type)) ) } return(NULL) }
6aa3a1be75b6c329cff4190302dd7d3e0526bd41
4b23658a53d0f7502e2c9a6d67eff57a9f3791dd
/cachematrix.R
3c021c5e2ebaf4423512e99f18aa9842e7cac5c0
[]
no_license
LonePine/ProgrammingAssignment2
8d6ad0ee650aa3c22ee6bb7e12d849c8ab18fe24
f2a371b11ab946e4a070f66d0dd856272359080a
refs/heads/master
2020-05-02T09:52:56.772191
2015-07-22T23:47:37
2015-07-22T23:47:37
39,369,287
0
0
null
2015-07-20T07:23:14
2015-07-20T07:23:14
null
UTF-8
R
false
false
1,651
r
cachematrix.R
## Since calculating inverse of a matrix is time consuming in a repeated operation the two ## functions below help with that. makeCacheMatrix creates a special "matrix" that can cache its inverse. ## function cacheSolve computes the inverse of the matrix returned by makeCacheMatrix. ## function makeCacheMatrix caches the inverse of a matrix and returns a list of four functions: ## getmatrix, setmatrix, getinverse, setinverse. makeCacheMatrix <- function(x = matrix()) { IM <- NULL setmatrix <- function(y){ x <<- y IM <<- NULL } getmatrix <- function()x setinverse <- function(solve) IM <<- solve getinverse <- function()IM list(setmatrix = setmatrix,getmatrix = getmatrix,setinverse = setinverse,getinverse = getinverse) } ## function cacheSolve calculates the inverse of a matrix returned by the above function and checks ## for condition to see if inverse already exists. If not, then it calculates inverse and stores in IM. cacheSolve <- function(x, ...) { IM <- x$getinverse() if(!is.null(IM)){ message(" getting cached matrix") return(IM) } matrix <- x$getmatrix() IM <- solve(matrix,...) x$setinverse(IM) IM } ## created the matrix below and tested the functons makeCacheMatrix and cacheSolve above with ## print(mat), matrixx <-makeCacheMatrix(mat), matrixx$getmatrix(), matrixx$getinverse(), ## cacheSolve(matrixx), matrixx$getinverse(),class(matrixx$getmatrix()), ## class(matrixx$getinverse()) and results were found to be correct and valid. mat <- matrix(c(1,0,5,2,1,6,3,4,0), nrow = 3,ncol = 3)
4da3a053c29e295cfaaf4fb32d4314d2154aeaf2
cc11ab7cf4531b687e1ec0b0cdaef97183fd949d
/tests/testthat/test_minimal.R
54ed9d1806a116b107e57bbd922ed9a790f3e365
[]
no_license
mablab/rpostgisLT
7234b0d4f15bf10adea6a6fdb085055dc39e6cdb
af566be34182c8bd8bdac0a30b6ff39e5c4f9a04
refs/heads/master
2020-05-21T19:18:31.490234
2018-03-13T17:28:54
2018-03-13T17:28:54
61,544,009
9
3
null
null
null
null
UTF-8
R
false
false
2,451
r
test_minimal.R
context("rpostgisLT: minimal") # source_test_helpers(path = "tests/testthat", env = test_env()) test_that("minimal ltraj transfer is equal and identical", { testthat::skip_on_cran() ib_min <- dl(ld(ibexraw[1])[1:10,]) # note that step parameters are recomputed on purpose expect_true(ltraj2pgtraj(conn_empty, ltraj = ib_min, schema = "traj_min", pgtraj = "ib_min")) expect_message(ib_min_re <- pgtraj2ltraj(conn_empty, schema = "traj_min", pgtraj = "ib_min"), "Ltraj successfully created from ib_min.") expect_equal(ib_min, ib_min_re) expect_false(identical(ib_min, ib_min_re)) expect_true(pgtrajDrop(conn_empty, "ib_min", "traj_min")) }) test_that("overwrite with null proj4string", { testthat::skip_on_cran() ib_min <- dl(ld(ibexraw[1])[1:10, ]) expect_true(ltraj2pgtraj( conn_empty, ltraj = ib_min, schema = "traj_min", pgtraj = "ib_min" )) attr(ib_min, "proj4string") <- NULL expect_true( ltraj2pgtraj( conn_empty, ltraj = ib_min, schema = "traj_min", pgtraj = "ib_min", overwrite = TRUE ) ) expect_true(pgtrajDrop(conn_empty, "ib_min", "traj_min")) }) test_that("transfer with projection", { testthat::skip_on_cran() ib_min_srs <- dl(ld(ibexraw[2])[1:10, ], proj4string = srs) # note that step parameters are recomputed on purpose expect_true(ltraj2pgtraj( conn_empty, ltraj = ib_min_srs, schema = "traj_min", pgtraj = "ib_min_3395" )) expect_message( ib_min_srs_re <- pgtraj2ltraj(conn_empty, schema = "traj_min", pgtraj = "ib_min_3395"), "Ltraj successfully created from ib_min_3395." ) expect_equal(ib_min_srs, ib_min_srs_re) expect_true(pgtrajDrop(conn_empty, "ib_min_3395", "traj_min")) }) test_that("ibexraw is not regular", { testthat::skip_on_cran() expect_false(is.regular(ibexraw)) }) test_that("pgtraj and schema defaults", { testthat::skip_on_cran() expect_message(ltraj2pgtraj(conn_empty, ibex, overwrite = TRUE), "('ibex')|('traj')", fixed = FALSE) expect_message(ibexTest <- pgtraj2ltraj(conn_empty, pgtraj = "ibex"), "ibex") expect_equal(ibex, ibexTest) expect_true(pgtrajDrop(conn_empty, "ibex", "traj")) })
75717bc62faa1efc54277eddaf9973cfa5b4fa71
d859174ad3cb31ab87088437cd1f0411a9d7449b
/autonomics.import/man/replace_nas_with_zeros.Rd
00ceca7cdc6125f9729b5525c3af7a4bf599fa48
[]
no_license
bhagwataditya/autonomics0
97c73d0a809aea5b4c9ef2bf3f886614eceb7a3c
c7ca7b69161e5181409c6b1ebcbeede4afde9974
refs/heads/master
2023-02-24T21:33:02.717621
2021-01-29T16:30:54
2021-01-29T16:30:54
133,491,102
0
0
null
null
null
null
UTF-8
R
false
true
527
rd
replace_nas_with_zeros.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/mutators.R \name{replace_nas_with_zeros} \alias{replace_nas_with_zeros} \title{Replace NAs with zeros} \usage{ replace_nas_with_zeros(object, verbose = TRUE) } \arguments{ \item{object}{SummarizedExperiment} \item{verbose}{TRUE or FALSE} } \value{ eset } \description{ Replace NAs with zeros } \examples{ if (require(autonomics.data)){ require(magrittr) object <- autonomics.data::stemcomp.proteinratios replace_nas_with_zeros(object) } }
6e27716861977e8337bed86b9fd15bc13eea37ab
df0579b5738f674c9673780a4bd50cab37e94615
/ui.R
320552216a3b9976e14c24ee06d9515b1fc683f6
[]
no_license
poolupsoon/DataScienceCapstone
0968c7a7256b4faee54dcc14f52cdb59d5b374e9
c10f8e159312fa5972798d667702e7edee50f614
refs/heads/master
2021-01-25T01:21:17.360270
2017-06-19T07:28:52
2017-06-19T07:28:52
94,747,111
0
0
null
null
null
null
UTF-8
R
false
false
2,373
r
ui.R
library(shiny) library(tm) library(wordnet) set.seed(12345) shinyUI(fluidPage( splitLayout(cellWidths = c("20%", "60%", "20%"), div(), div(titlePanel("Data Science Capstone: Predictive Text Model")), div() ), splitLayout(cellWidths = c("20%", "60%", "20%"), div(), div(a(em("Click Here to View Documentation"), href = "documentation.html", target = "_blank")), div() ), hr(style = "border-color: black"), splitLayout(cellWidths = c("20%", "10%", "50%", "20%"), div(), div(strong("Phrase:")), div(textInput("textIn", label = NULL, width = "100%", placeholder = "Enter text in English")), div() ), splitLayout(cellWidths = c("20%", "10%", "50%", "20%"), div(), div(), div(submitButton("Predict")), div() ), br(), br(), splitLayout(cellWidths = c("20%", "10%", "50%", "20%"), div(), div(strong("Results:")), div(textOutput("textOut1")), div() ), splitLayout(cellWidths = c("20%", "10%", "50%", "20%"), div(), div(), div(textOutput("textOut2")), div() ), splitLayout(cellWidths = c("20%", "10%", "50%", "20%"), div(), div(), div(textOutput("textOut3")), div() ), splitLayout(cellWidths = c("20%", "10%", "50%", "20%"), div(), div(), div(textOutput("textOut4")), div() ), splitLayout(cellWidths = c("20%", "10%", "50%", "20%"), div(), div(), div(textOutput("textOut5")), div() ), splitLayout(cellWidths = c("20%", "10%", "50%", "20%"), div(), div(), div(textOutput("textOut6")), div() ), br(), br(), hr(style = "border-color: black"), div(em("DISCLAIMER: This Shiny Web App is for educational purposes only. The data and prediction accuracies are not guaranteed."), style = "text-align: center") ))
c177b4327e515dddf6e3d814669359b1520995b0
65cf48ec1a1c6cebdc2c9a1fedd0f40f0caf73a2
/R/ppsale.R
d34ee1406ccb6cecacf6165a5499c4598dc41f8f
[]
no_license
Menglinucas/extd.comavm
e3c59f06202acbe87f5ea394af22deefa15d2431
409d6394e68c9d3232d36f1a8cd7a5d1a2e9e036
refs/heads/master
2021-09-08T09:06:30.390886
2018-03-09T01:19:47
2018-03-09T01:19:47
114,219,130
0
0
null
null
null
null
UTF-8
R
false
false
12,105
r
ppsale.R
#' joining ha and price data #' #' This function can join price and ha info #' @param tabln.vec basic data provided by \code{\link{loadData}} #' @param proptype type code of properties.The defalut is 11 indiciting housing #' @return data including ha info and ha price ppsale<-function(tabln.vec=NULL,proptype='11',modelpath1=NULL,city_code=NULL) { if(is.null(tabln.vec)){ stop('must provide a tabln.vec!!!') } library(dplyr) # saleprice of property "11" (residence area) price_sale<-tabln.vec$ha_price%>%filter(proptype==proptype) # saleprice = 0 and Inf, not meaningful price_sale$saleprice[which(price_sale$saleprice<=0 | price_sale$saleprice>1000000)] <- NA # # mean saleprice of ha # price_sale <- price_sale[!duplicated(price_sale),] %>% group_by(ha_code) %>% summarise(saleprice=mean(saleprice,na.rm=T)) # add pricesale to ha_info, note: mybe exist duplicated ha_code, that's not a wrong ppi_sale<-merge(price_sale,tabln.vec$ha_info.sp,by="ha_code",all.y=T) # ppi_sale<-ppi_sale%>% # # mutate(year=floor(ymid/12), # # month=ifelse(!ymid%%12,12,ymid%%12))%>% # group_by(ha_code,x,y,name,ha_cl_code,ha_cl_name,dist_code, # dist_name,buildyear,bldg_code) %>% # summarise(saleprice=mean(saleprice,na.rm=T), # volume_rate=mean(volume_rate,na.rm=T),greening_rate=mean(greening_rate,na.rm=T), # edu.poi.sp_dens=mean(edu.poi.sp_dens,na.rm=T),hosi.poi.sp_dens=mean(hosi.poi.sp_dens,na.rm=T), # trans.poi.sp_dens=mean(trans.poi.sp_dens,na.rm=T),busi.poi.sp_dens=mean(busi.poi.sp_dens,na.rm=T), # poi.diversity.pts=mean(poi.diversity.pts,na.rm=T), # edu.poi.sp_mindist=mean(edu.poi.sp_mindist,na.rm=T),hosi.poi.sp_mindist=mean(hosi.poi.sp_mindist,na.rm=T), # trans.poi.sp_mindist=mean(trans.poi.sp_mindist,na.rm=T),busi.poi.sp_mindist=mean(busi.poi.sp_mindist,na.rm=T))%>% # as.data.frame() ppi_sale[ppi_sale=='NaN'] <- NA # substitute the price by Community avm values, should ensure that comavm model contains all bldg_code of a community ppi_sale <- subsp(ppi_sale,modelpath1,city_code) return(ppi_sale) } # substitue saleprice of tabln$vec$ha_price by community avm subsp <- function(sp,modelpath1,city_code){ # library(rjson) filenames <- list.files(paste0(modelpath1,"/",city_code)) filepos <- paste0(modelpath1,"/",city_code,"/",filenames) # number of files nha <- length(filenames) # create a dataframe to store all ha_code+saleprice of a city comsp <- data.frame("ha_code"=rep(NA,nha*4),"bldg_code"=rep(NA,nha*4), "K0"=rep(0,nha*4),"Kbyear"=rep(0,nha*4),"Kheight"=rep(0,nha*4),"Ktime"=rep(0,nha*4), "Kfloor"=rep(0,nha*4),"KbrArea"=rep(0,nha*4),"Kstru"=rep(0,nha*4),"Kface_through"=rep(0,nha*4), "Kface_sun"=rep(0,nha*4),"Kdeco_if"=rep(0,nha*4),"Kdeco_good"=rep(0,nha*4),"Kprop_rt"=rep(0,nha*4)) # extract the ha_code from filesnames, put in comsp@ha_code comsp$ha_code <- sapply(sapply(filenames,unlist(strsplit),split="[_]"),function(x) x[1]) # extract the bldg_code from json, put in comsp@bldg_code comsp$bldg_code[1:nha] <- rep("11",nha) comsp$bldg_code[(nha+1):(2*nha)] <- rep("12",nha) comsp$bldg_code[(2*nha+1):(3*nha)] <- rep("13",nha) comsp$bldg_code[(3*nha+1):(4*nha)] <- rep("21",nha) # extract the coefficients from json features <- sapply(filepos,jsp,bldg_code='11') comsp[1:nha,"K0"] <- features[1,1:nha] comsp[1:nha,"Kbyear"] <- features[2,1:nha] comsp[1:nha,"Kheight"] <- features[3,1:nha] comsp[1:nha,"Ktime"] <- features[4,1:nha] comsp[1:nha,"Kfloor"] <- features[5,1:nha] comsp[1:nha,"KbrArea"] <- features[6,1:nha] comsp[1:nha,"Kstru"] <- features[7,1:nha] comsp[1:nha,"Kface_through"] <- features[8,1:nha] comsp[1:nha,"Kface_sun"] <- features[9,1:nha] comsp[1:nha,"Kdeco_if"] <- features[10,1:nha] comsp[1:nha,"Kdeco_good"] <- features[11,1:nha] comsp[1:nha,"Kprop_rt"] <- features[12,1:nha] features <- sapply(filepos,jsp,bldg_code='12') comsp[(nha+1):(2*nha),"K0"] <- features[1,1:nha] comsp[(nha+1):(2*nha),"Kbyear"] <- features[2,1:nha] comsp[(nha+1):(2*nha),"Kheight"] <- features[3,1:nha] comsp[(nha+1):(2*nha),"Ktime"] <- features[4,1:nha] comsp[(nha+1):(2*nha),"Kfloor"] <- features[5,1:nha] comsp[(nha+1):(2*nha),"KbrArea"] <- features[6,1:nha] comsp[(nha+1):(2*nha),"Kstru"] <- features[7,1:nha] comsp[(nha+1):(2*nha),"Kface_through"] <- features[8,1:nha] comsp[(nha+1):(2*nha),"Kface_sun"] <- features[9,1:nha] comsp[(nha+1):(2*nha),"Kdeco_if"] <- features[10,1:nha] comsp[(nha+1):(2*nha),"Kdeco_good"] <- features[11,1:nha] comsp[(nha+1):(2*nha),"Kprop_rt"] <- features[12,1:nha] features <- sapply(filepos,jsp,bldg_code='13') comsp[(2*nha+1):(3*nha),"K0"] <- features[1,1:nha] comsp[(2*nha+1):(3*nha),"Kbyear"] <- features[2,1:nha] comsp[(2*nha+1):(3*nha),"Kheight"] <- features[3,1:nha] comsp[(2*nha+1):(3*nha),"Ktime"] <- features[4,1:nha] comsp[(2*nha+1):(3*nha),"Kfloor"] <- features[5,1:nha] comsp[(2*nha+1):(3*nha),"KbrArea"] <- features[6,1:nha] comsp[(2*nha+1):(3*nha),"Kstru"] <- features[7,1:nha] comsp[(2*nha+1):(3*nha),"Kface_through"] <- features[8,1:nha] comsp[(2*nha+1):(3*nha),"Kface_sun"] <- features[9,1:nha] comsp[(2*nha+1):(3*nha),"Kdeco_if"] <- features[10,1:nha] comsp[(2*nha+1):(3*nha),"Kdeco_good"] <- features[11,1:nha] comsp[(2*nha+1):(3*nha),"Kprop_rt"] <- features[12,1:nha] features <- sapply(filepos,jsp,bldg_code='21') comsp[(3*nha+1):(4*nha),"K0"] <- features[1,1:nha] comsp[(3*nha+1):(4*nha),"Kbyear"] <- features[2,1:nha] comsp[(3*nha+1):(4*nha),"Kheight"] <- features[3,1:nha] comsp[(3*nha+1):(4*nha),"Ktime"] <- features[4,1:nha] comsp[(3*nha+1):(4*nha),"Kfloor"] <- features[5,1:nha] comsp[(3*nha+1):(4*nha),"KbrArea"] <- features[6,1:nha] comsp[(3*nha+1):(4*nha),"Kstru"] <- features[7,1:nha] comsp[(3*nha+1):(4*nha),"Kface_through"] <- features[8,1:nha] comsp[(3*nha+1):(4*nha),"Kface_sun"] <- features[9,1:nha] comsp[(3*nha+1):(4*nha),"Kdeco_if"] <- features[10,1:nha] comsp[(3*nha+1):(4*nha),"Kdeco_good"] <- features[11,1:nha] comsp[(3*nha+1):(4*nha),"Kprop_rt"] <- features[12,1:nha] # saleprice = 0 and Inf, not meaningful comsp$K0[which(comsp$K0<=6 | comsp$K0>14)] <- NA # delete no price data comsp <- na.omit(comsp) # delete the duplicated row comsp <- comsp[!duplicated(subset(comsp,select=c(ha_code,bldg_code))),] # dataframe: ha_code, bldg_code, ..., bc11, bc12, bc13, bc21 comsp$bc11 <- 0 comsp$bc12 <- 0 comsp$bc13 <- 0 comsp$bc21 <- 0 idy <- sapply(1:nrow(comsp), function(i,df=comsp){ id <- which(substr(names(df),3,4)==df[i,'bldg_code'])} ) for (i in 1:nrow(comsp)){ comsp[i,idy[i]] <- 1 } # the coefficients sould not be too large comsp[(which(abs(comsp[4])>1)),4] <- sign(comsp[(which(abs(comsp[4])>1)),4]) comsp[(which(abs(comsp[5])>1)),5] <- sign(comsp[(which(abs(comsp[5])>1)),5]) comsp[(which(abs(comsp[6])>1)),6] <- sign(comsp[(which(abs(comsp[6])>1)),6]) comsp[(which(abs(comsp[7])>1)),7] <- sign(comsp[(which(abs(comsp[7])>1)),7]) comsp[(which(abs(comsp[8])>1)),8] <- sign(comsp[(which(abs(comsp[8])>1)),8]) comsp[(which(abs(comsp[9])>1)),9] <- sign(comsp[(which(abs(comsp[9])>1)),9]) comsp[(which(abs(comsp[10])>1)),10] <- sign(comsp[(which(abs(comsp[10])>1)),10]) comsp[(which(abs(comsp[11])>1)),11] <- sign(comsp[(which(abs(comsp[11])>1)),11]) comsp[(which(abs(comsp[12])>1)),12] <- sign(comsp[(which(abs(comsp[12])>1)),12]) comsp[(which(abs(comsp[13])>1)),13] <- sign(comsp[(which(abs(comsp[13])>1)),13]) comsp[(which(abs(comsp[14])>1)),14] <- sign(comsp[(which(abs(comsp[14])>1)),14]) # price_sale <- group_by(comsp,ha_code) %>% summarise(saleprice=mean(saleprice,na.rm=T)) %>% as.data.frame() # bldg <- table(comsp[1:2]) %>% unclass() %>% as.data.frame() # names(bldg) <- paste0("bc",names(bldg)) # bldg$ha_code <- row.names(bldg) # row.names(bldg) <- c(1:nrow(bldg)) # price_sale <- merge(bldg,price_sale,by="ha_code") # replace saleprice sp <- subset(sp,select=-c(saleprice,bldg_code)) result <- merge(comsp,sp,by='ha_code') # the last checking result <- result[!duplicated(result) & !is.na(result$K0),] return(result) } # read (building year, height) and all coefficients from json file based on bldg_code jsp <- function(filepos,bldg_code){ # all the variables # standard variables including time(1:5), floor, brArea, stru, face_through, face_sun, deco_if, deco_good and prop_rt coeffs <- c("price","buildyear","height", "time","floor","brArea","stru","face_through","face_sun","deco_if","deco_good","prop_rt") # the values of coefficients coeffsValue <- c(rep(0,length(coeffs))) # read Json temp <- fromJSON(file = filepos) # if the json file is null if (length(temp)!=0){ # if existing the bldg_code in the json file if (bldg_code %in% names(temp[[1]])){ bldgfeatures <- temp[[1]][[which(names(temp[[1]])==bldg_code)]] features <- bldgfeatures$listFeature # update time of the model t1 <- as.Date(bldgfeatures$modelUpdateDate) # the first day of this month t2 <- lubridate::floor_date(Sys.Date(),unit='month') # extract the coefficients of standard variables featurenames <- c() for (i in 1:length(features)) { featurenames[i] <- features[[i]]$featureName } # select the time segment (0-?) idt <- which(featurenames=='time') if (length(idt) > 0){ for (i in 1:length(idt)) { if (features[[idt[i]]]$min<2) { #the minimum time value is less than 2, maybe 0 or 1 in json file idt_select <- idt[i] coeffsValue[4] <- features[[idt_select]]$beta } } } if (coeffsValue[4]!=0){ stdtime <- as.numeric(t1-t2)/features[[idt_select]]$max coeffsValue[4] <- coeffsValue[4] * stdtime } # select the floor segment (1-?) idflr <- which(featurenames=='floor') if (length(idflr) > 0){ for (i in 1:length(idflr)) { if (features[[idflr[i]]]$min==1) { #the minimum floor value is 1 idflr_select <- idflr[i] coeffsValue[5] <- features[[idflr_select]]$beta } } } # stdflr == 0 # select the area segment (?<90<?) idarea <- which(featurenames=='brArea') if (length(idarea) > 0){ for (i in 1:length(idarea)) { if (features[[idarea[i]]]$min<90 & features[[idarea[i]]]$max>90) { # contain area = 90 m^2 idarea_select <- idarea[i] coeffsValue[6] <- features[[idarea_select]]$beta } } } # stdarea == log(90)/log(500) # # the maximum and minimum value of building year # idbuildyear <- which(featurenames=='buildyear') # must be a 1 dim # if (length(idbuildyear)==1){ # buildyear_max <- features[[idbuildyear]]$max # buildyear_min <- features[[idbuildyear]]$min # stdbuildyear <- (buildyear-buildyear_min)/(buildyear_max-buildyear_min) # }else{stdbuildyear <- 0} # # the maximum and minimum value of height # idheight <- which(featurenames=='height') # must be a 1 dim # if (length(idheight)==1){ # height_max <- features[[idheight]]$max # height_min <- features[[idheight]]$min # stdheight <- (height-height_min)/(height_max-height_min) # }else{stdheight <- 0} # else coefficients extraction idf <- which(featurenames!='time' & featurenames!='floor' & featurenames!='brArea') featurenames <- featurenames[idf] if (length(featurenames)>0){ id <- sapply(1:length(featurenames),function(i) which(coeffs==featurenames[i])) coeffsValue[id] <- sapply(1:length(featurenames),function(i) features[[idf[i]]]$beta) } return(coeffsValue) }else{return(coeffsValue)} }else{return(coeffsValue)} }
9e3e296439bab4d6c9983878e1b06de1bfaf81ce
64ecf2a801522d5c105d921ffeb413af201a78f4
/R/NorgastAnastomoselekkasje.R
f67226d49e6a9adc6ffb428235e455d3aa2d1a6d
[]
no_license
Rapporteket/norgast
c3a979915d4f6baca2d34130baf1684074037d89
a30ea9b2fa32ff9f224d7771f5f08a8802ecb721
refs/heads/rel
2023-06-10T11:47:55.564563
2023-06-09T14:05:19
2023-06-09T14:05:19
49,719,854
0
0
null
2023-02-22T09:55:01
2016-01-15T13:18:24
R
UTF-8
R
false
false
7,508
r
NorgastAnastomoselekkasje.R
#' Lag tabell over anastomoselekkasjerate #' #' Denne funksjonen lager tre tabeller for bruk i samlerapport #' #' @inheritParams FigAndeler #' #' @return Tabell En list med tre tabeller over anastomoselekkasjerater #' #' @export NorgastAnastomoselekkasje <- function(RegData=RegData, datoFra='2014-01-01', datoTil='2050-12-31', minald=0, maxald=130, erMann=99, reshID=601225, outfile='', elektiv=99, BMI='', valgtShus='') { RegData <- RegData[which(RegData$Op_gr2 != 9), ] RegData$Op_gr2 <- factor(RegData$Op_gr2) grtxt <- c('Kolonreseksjoner, ny anastomose', 'Kolonreseksjoner, øvrige', "Rektumreseksjoner, ny anastomose", "Rektumreseksjoner, øvrige", 'Øsofagusreseksjoner', 'Ventrikkelreseksjoner, ny anastomose', 'Ventrikkelreseksjoner, øvrige','Whipples operasjon') RegData$variabel <- 0 RegData$variabel[RegData$ViktigsteFunn==1] <- 1 NorgastUtvalg <- NorgastLibUtvalg(RegData=RegData, datoFra=datoFra, datoTil=datoTil, minald=minald, maxald=maxald, erMann=erMann, elektiv=elektiv, BMI=BMI, valgtShus=valgtShus) RegData <- NorgastUtvalg$RegData utvalgTxt <- NorgastUtvalg$utvalgTxt indSh <-which(RegData$AvdRESH == reshID) indRest <- which(RegData$AvdRESH != reshID) RegDataSh <- RegData[indSh,] RegDataRest <- RegData[indRest,] ### Lage tabeller ##################################################################### Tabell1 <- data.frame(Operasjonsgruppe=grtxt, N_lokal=numeric(8), RateAnastomoselekkasje_lokal=numeric(8), N_ovrig=numeric(8), RateAnastomoselekkasje_ovrig=numeric(8)) Tabell1$N_lokal <- tapply(RegDataSh$variabel, RegDataSh$Op_gr2, length)[1:8] Tabell1$RateAnastomoselekkasje_lokal <- round(tapply(RegDataSh$variabel, RegDataSh$Op_gr2, sum)/ tapply(RegDataSh$variabel, RegDataSh$Op_gr2, length)*100, 2)[1:8] Tabell1$N_ovrig <- tapply(RegDataRest$variabel, RegDataRest$Op_gr2, length)[1:8] Tabell1$RateAnastomoselekkasje_ovrig <- round(tapply(RegDataRest$variabel, RegDataRest$Op_gr2, sum)/ tapply(RegDataRest$variabel, RegDataRest$Op_gr2, length)*100, 2)[1:8] Tabell1$RateAnastomoselekkasje_lokal[2]<-NA Tabell1$RateAnastomoselekkasje_ovrig[2]<-NA Tabell1$RateAnastomoselekkasje_lokal[4]<-NA Tabell1$RateAnastomoselekkasje_ovrig[4]<-NA Tabell1$RateAnastomoselekkasje_lokal[7]<-NA Tabell1$RateAnastomoselekkasje_ovrig[7]<-NA ### Begrenset til rektum ################################## regdata <- RegData # Beholde det fulle datasettet RegData <- RegData[RegData$Op_gr2==3,] # Velg bare rektum indSh <-which(RegData$AvdRESH == reshID) indRest <- which(RegData$AvdRESH != reshID) RegDataSh <- RegData[indSh,] RegDataRest <- RegData[indRest,] Tabell2 <- data.frame(Operasjonsgruppe=c('Rektumreseksjoner, ny anastomose', '\\quad Uten avlastende stomi', '\\quad Med avlastende stomi'), N_lokal=numeric(3), RateAnastomoselekkasje_lokal=numeric(3), N_ovrig=numeric(3), RateAnastomoselekkasje_ovrig=numeric(3)) Tabell2$N_lokal[2:3] <- tapply(RegDataSh$variabel, RegDataSh$AvlastendeStomiRektum, length)[1:2] Tabell2$RateAnastomoselekkasje_lokal[2:3] <- round(tapply(RegDataSh$variabel, RegDataSh$AvlastendeStomiRektum, sum)/ tapply(RegDataSh$variabel, RegDataSh$AvlastendeStomiRektum, length)*100, 2)[1:2] Tabell2$N_ovrig[2:3] <- tapply(RegDataRest$variabel, RegDataRest$AvlastendeStomiRektum, length)[1:2] Tabell2$RateAnastomoselekkasje_ovrig[2:3] <- round(tapply(RegDataRest$variabel, RegDataRest$AvlastendeStomiRektum, sum)/ tapply(RegDataRest$variabel, RegDataRest$AvlastendeStomiRektum, length)*100, 2)[1:2] Tabell2[1,2:5] <- NA ### Onkologisk forbehandling ################################## regdata$ForbehandlingBinaer <- NA regdata$ForbehandlingBinaer[regdata$Forbehandling %in% c(1,2,3)] <- 1 regdata$ForbehandlingBinaer[regdata$Forbehandling == 4] <- 0 RegData <- regdata Tabell3 <- data.frame(Operasjonsgruppe=c('Rektumreseksjon, ny anastomose', '\\quad Ingen forbehandling', '\\quad Enhver forbehandling', 'Ventrikkelreseksjon, ny anastomose', '\\quad Ingen forbehandling', '\\quad Enhver forbehandling', 'Øsofagusreseksjon', '\\quad Ingen forbehandling', '\\quad Enhver forbehandling'), N_lokal=numeric(9), RateAnastomoselekkasje_lokal=numeric(9), N_ovrig=numeric(9), RateAnastomoselekkasje_ovrig=numeric(9)) RegData <- RegData[RegData$Op_gr2==3,] indSh <-which(RegData$AvdRESH == reshID) indRest <- which(RegData$AvdRESH != reshID) RegDataSh <- RegData[indSh,] RegDataRest <- RegData[indRest,] Tabell3$N_lokal[2:3] <- tapply(RegDataSh$variabel, RegDataSh$ForbehandlingBinaer, length)[1:2] Tabell3$RateAnastomoselekkasje_lokal[2:3] <- round(tapply(RegDataSh$variabel, RegDataSh$ForbehandlingBinaer, sum)/ tapply(RegDataSh$variabel, RegDataSh$ForbehandlingBinaer, length)*100, 2)[1:2] Tabell3$N_ovrig[2:3] <- tapply(RegDataRest$variabel, RegDataRest$ForbehandlingBinaer, length)[1:2] Tabell3$RateAnastomoselekkasje_ovrig[2:3] <- round(tapply(RegDataRest$variabel, RegDataRest$ForbehandlingBinaer, sum)/ tapply(RegDataRest$variabel, RegDataRest$ForbehandlingBinaer, length)*100, 2)[1:2] RegData <- regdata RegData <- RegData[RegData$Op_gr2==6,] indSh <-which(RegData$AvdRESH == reshID) indRest <- which(RegData$AvdRESH != reshID) RegDataSh <- RegData[indSh,] RegDataRest <- RegData[indRest,] Tabell3$N_lokal[5:6] <- tapply(RegDataSh$variabel, RegDataSh$ForbehandlingBinaer, length)[1:2] Tabell3$RateAnastomoselekkasje_lokal[5:6] <- round(tapply(RegDataSh$variabel, RegDataSh$ForbehandlingBinaer, sum)/ tapply(RegDataSh$variabel, RegDataSh$ForbehandlingBinaer, length)*100, 2)[1:2] Tabell3$N_ovrig[5:6] <- tapply(RegDataRest$variabel, RegDataRest$ForbehandlingBinaer, length)[1:2] Tabell3$RateAnastomoselekkasje_ovrig[5:6] <- round(tapply(RegDataRest$variabel, RegDataRest$ForbehandlingBinaer, sum)/ tapply(RegDataRest$variabel, RegDataRest$ForbehandlingBinaer, length)*100, 2)[1:2] RegData <- regdata RegData <- RegData[RegData$Op_gr2==5,] indSh <-which(RegData$AvdRESH == reshID) indRest <- which(RegData$AvdRESH != reshID) RegDataSh <- RegData[indSh,] RegDataRest <- RegData[indRest,] Tabell3$N_lokal[8:9] <- tapply(RegDataSh$variabel, RegDataSh$ForbehandlingBinaer, length)[1:2] Tabell3$RateAnastomoselekkasje_lokal[8:9] <- round(tapply(RegDataSh$variabel, RegDataSh$ForbehandlingBinaer, sum)/ tapply(RegDataSh$variabel, RegDataSh$ForbehandlingBinaer, length)*100, 2)[1:2] Tabell3$N_ovrig[8:9] <- tapply(RegDataRest$variabel, RegDataRest$ForbehandlingBinaer, length)[1:2] Tabell3$RateAnastomoselekkasje_ovrig[8:9] <- round(tapply(RegDataRest$variabel, RegDataRest$ForbehandlingBinaer, sum)/ tapply(RegDataRest$variabel, RegDataRest$ForbehandlingBinaer, length)*100, 2)[1:2] Tabell3[c(1,4,7),2:5] <- NA Tabell <- list(Tabell1=Tabell1, Tabell2=Tabell2, Tabell3=Tabell3) return(invisible(Tabell)) }
1dc7edfdc605756506068f153ff8281033aaf683
e869d56b65fdbaf8b2b5d273c8ca67dd4b3c25d2
/capstone.R
8a8128fb301a788f5c5aece3d849e7cdbae96796
[]
no_license
jodeck80/591-Capstone
ff35354b0eec4582c769d7835316e1b026058f7e
4c49627716f06ef0e7e8f5a6b0cfee8e6c05604e
refs/heads/master
2021-01-01T19:30:23.125263
2015-05-10T13:14:22
2015-05-10T13:14:22
34,755,991
0
0
null
null
null
null
UTF-8
R
false
false
18,227
r
capstone.R
library(streamR) library(plyr) library(ggplot2) library(grid) library(maps) library(RStorm) library(tm) library(stringr) library(ROAuth) load("my_oauth.Rdata") # Color blind friendly colors: cbbPalette <- c("#000000", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7") #1 minute tweet duration TWEET_DURATION <- 60 #number of times to iterate process ITERATIONS <- 3 MLBTerms <- c("MLB","yankees", "red sox", "orioles", "rays", "blue jays", "mets", "braves", "marlins", "phillies", "nationals", "tigers", "twins", "indians", "royals", "white sox", "cubs", "cardinals", "reds", "pirates", "brewers", "mariners", "a's", "astros", "angels", "rangers", "dodgers", "giants", "diamondbacks", "padres", "rockies") NBATerms <- c("NBA","hawks", "cavaliers", "bulls", "raptors", "wizards", "bucks", "celtics", "nets", "pacers", "heat", "hornets", "pistons", "magic", "76ers", "knicks", "warriors", "rockets", "clippers", "spurs", "trail blazers", "grizzlies", "mavericks", "pelicans", "thunder", "suns", "jazz", "nuggets", "kings", "lakers", "timberwolves") NFLTerms <- c("NFL","eagles", "giants", "cowboys", "redskins", "bills", "patriots", "dolphins", "jets", "bears", "lions", "packers", "vikings", "browns", "bengals", "steelers", "ravens", "panthers", "saints", "buccaneers", "falcons", "titans", "colts", "jaguars", "texans", "49ers", "cardinals", "seahawks", "rams", "broncos", "chargers", "raiders", "chiefs") NHLTerms <- c("NHL","rangers", "canadiens", "lightning", "capitals", "islanders", "red wings", "senators", "penguins", "bruins", "panthers", "blue jackets", "flyers", "devils", "hurricanes", "maple leafs", "sabres", "ducks", "blues", "predators", "blackhawks", "canucks", "wild", "jets", "flames", "kings", "stars", "avalanche", "sharks", "oilers", "coyotes") maxMLB<-function(a,b) { max1 = 0 max2 = 0 MLB=NULL for(i in 2:length(b)) { max1 = 0 for(j in 1:dim(a)[1]) { if(length(grep(b[i],a[j,]$word,ignore.case=TRUE))>0) { max1 = max1 + a[j,]$count } } if(max2<max1) { max2 = max1 MLB = b[i] } } return(MLB) } maxMLBcount<-function(a,b) { max1 = 0 for(i in 1:length(b)) { for(j in 1:dim(a)[1]) { if(length(grep(b[i],a[j,]$word,ignore.case=TRUE))>0) { max1 = max1 + a[j,]$count } } } return(max1) } # R word counting function: CountWord <- function(tuple,...){ # Get the hashmap "word count" counts <- GetHash("wordcount") if (tuple$word %in% counts$word) { # Increment the word count: counts[counts$word == tuple$word,]$count <-counts[counts$word == tuple$word,]$count + 1 } else { # If the word does not exist # Add the word with count 1 counts <- rbind(counts, data.frame(word = tuple$word, count = 1,stringsAsFactors=F)) } # Store the hashmap SetHash("wordcount", counts) } # and splits it into words: SplitSentence <- function(tuple,...) { if((tuple$text!="")||(tuple$text!=" ")) { # Split the sentence into words words <- unlist(strsplit(as.character(tuple$text), " ")) # For each word emit a tuple for (word in words) { if (word!="") { Emit(Tuple(data.frame(word = word,stringsAsFactors=F)),...) } } } } countMin<-function(tweets.running){ oneData<-as.data.frame(tweets.running$text) oneData[,1]<-as.data.frame(str_replace_all(oneData[,1],"[^[:graph:]]", " ")) oneData[,1] <- sapply(oneData[,1] ,function(row){ iconv(row, "ISO_8859-2", "ASCII", sub="") iconv(row, "latin1", "ASCII", sub="") iconv(row, "LATIN2", "ASCII", sub="") }) s <- Corpus(VectorSource(oneData[,1]),readerControl=list(language="en")) s <- tm_map(s, tolower) s <- tm_map(s, removeWords, c(stopwords("english"),"rt","http","retweet")) s <- tm_map(s, removePunctuation) s <- tm_map(s, PlainTextDocument) s <- tm_map(s, stripWhitespace) tweets<-data.frame(text=sapply(s, '[[', "content"), stringsAsFactors=FALSE) #function to pre-process tweet text topology = Topology(tweets) # Add the bolts: topology <- AddBolt( topology, Bolt(SplitSentence, listen = 0) ) topology <- AddBolt( topology, Bolt(CountWord, listen = 1) ) # R function that receives a tuple # (a sentence in this case) # Run the stream: resultLoc <- RStorm(topology) # Obtain results stored in "wordcount" return (resultLoc) } #function to remove tweets having both the words love and hate filterTweetsMLB<-function(a) { # check if text doesn't have both love and hate in it if((length(grep(MLBTerms[1],a,ignore.case=TRUE))>0) | (length(grep(MLBTerms[2],a,ignore.case=TRUE))>0) | (length(grep(MLBTerms[3],a,ignore.case=TRUE))>0) | (length(grep(MLBTerms[4],a,ignore.case=TRUE))>0) | (length(grep(MLBTerms[5],a,ignore.case=TRUE))>0) | (length(grep(MLBTerms[6],a,ignore.case=TRUE))>0) | (length(grep(MLBTerms[7],a,ignore.case=TRUE))>0) | (length(grep(MLBTerms[8],a,ignore.case=TRUE))>0) | (length(grep(MLBTerms[9],a,ignore.case=TRUE))>0) | (length(grep(MLBTerms[10],a,ignore.case=TRUE))>0) | (length(grep(MLBTerms[11],a,ignore.case=TRUE))>0) | (length(grep(MLBTerms[12],a,ignore.case=TRUE))>0) | (length(grep(MLBTerms[13],a,ignore.case=TRUE))>0) | (length(grep(MLBTerms[14],a,ignore.case=TRUE))>0) | (length(grep(MLBTerms[15],a,ignore.case=TRUE))>0) | (length(grep(MLBTerms[16],a,ignore.case=TRUE))>0) | (length(grep(MLBTerms[17],a,ignore.case=TRUE))>0) | (length(grep(MLBTerms[18],a,ignore.case=TRUE))>0) | (length(grep(MLBTerms[19],a,ignore.case=TRUE))>0) | (length(grep(MLBTerms[20],a,ignore.case=TRUE))>0) | (length(grep(MLBTerms[21],a,ignore.case=TRUE))>0) | (length(grep(MLBTerms[22],a,ignore.case=TRUE))>0) | (length(grep(MLBTerms[23],a,ignore.case=TRUE))>0) | (length(grep(MLBTerms[24],a,ignore.case=TRUE))>0) | (length(grep(MLBTerms[25],a,ignore.case=TRUE))>0) | (length(grep(MLBTerms[26],a,ignore.case=TRUE))>0) | (length(grep(MLBTerms[27],a,ignore.case=TRUE))>0) | (length(grep(MLBTerms[28],a,ignore.case=TRUE))>0) | (length(grep(MLBTerms[29],a,ignore.case=TRUE))>0) | (length(grep(MLBTerms[30],a,ignore.case=TRUE))>0) | (length(grep(MLBTerms[31],a,ignore.case=TRUE))>0)) { if(a$league != 0) { #another league was also mentioned, will remove tweet a$league = 5 } else { #set league to 1 if league wasnt previously set a$league = "MLB" } } data.frame(a) } #function to remove tweets having both the words love and hate filterTweetsNBA<-function(a) { # check if text doesn't have both love and hate in it if((length(grep(NBATerms[1],a,ignore.case=TRUE))>0) | (length(grep(NBATerms[2],a,ignore.case=TRUE))>0) | (length(grep(NBATerms[3],a,ignore.case=TRUE))>0) | (length(grep(NBATerms[4],a,ignore.case=TRUE))>0) | (length(grep(NBATerms[5],a,ignore.case=TRUE))>0) | (length(grep(NBATerms[6],a,ignore.case=TRUE))>0) | (length(grep(NBATerms[7],a,ignore.case=TRUE))>0) | (length(grep(NBATerms[8],a,ignore.case=TRUE))>0) | (length(grep(NBATerms[9],a,ignore.case=TRUE))>0) | (length(grep(NBATerms[10],a,ignore.case=TRUE))>0) | (length(grep(NBATerms[11],a,ignore.case=TRUE))>0) | (length(grep(NBATerms[12],a,ignore.case=TRUE))>0) | (length(grep(NBATerms[13],a,ignore.case=TRUE))>0) | (length(grep(NBATerms[14],a,ignore.case=TRUE))>0) | (length(grep(NBATerms[15],a,ignore.case=TRUE))>0) | (length(grep(NBATerms[16],a,ignore.case=TRUE))>0) | (length(grep(NBATerms[17],a,ignore.case=TRUE))>0) | (length(grep(NBATerms[18],a,ignore.case=TRUE))>0) | (length(grep(NBATerms[19],a,ignore.case=TRUE))>0) | (length(grep(NBATerms[20],a,ignore.case=TRUE))>0) | (length(grep(NBATerms[21],a,ignore.case=TRUE))>0) | (length(grep(NBATerms[22],a,ignore.case=TRUE))>0) | (length(grep(NBATerms[23],a,ignore.case=TRUE))>0) | (length(grep(NBATerms[24],a,ignore.case=TRUE))>0) | (length(grep(NBATerms[25],a,ignore.case=TRUE))>0) | (length(grep(NBATerms[26],a,ignore.case=TRUE))>0) | (length(grep(NBATerms[27],a,ignore.case=TRUE))>0) | (length(grep(NBATerms[28],a,ignore.case=TRUE))>0) | (length(grep(NBATerms[29],a,ignore.case=TRUE))>0) | (length(grep(NBATerms[30],a,ignore.case=TRUE))>0) ) { if(a$league != 0) { #another league was also mentioned, will remove tweet a$league = 5 } else { #set league to 2 if league wasnt previously set a$league = "NBA" } } data.frame(a) } #function to remove tweets having both the words love and hate filterTweetsNFL<-function(a) { # check if text doesn't have both love and hate in it if((length(grep(NFLTerms[1],a,ignore.case=TRUE))>0) | (length(grep(NFLTerms[2],a,ignore.case=TRUE))>0) | (length(grep(NFLTerms[3],a,ignore.case=TRUE))>0) | (length(grep(NFLTerms[4],a,ignore.case=TRUE))>0) | (length(grep(NFLTerms[5],a,ignore.case=TRUE))>0) | (length(grep(NFLTerms[6],a,ignore.case=TRUE))>0) | (length(grep(NFLTerms[7],a,ignore.case=TRUE))>0) | (length(grep(NFLTerms[8],a,ignore.case=TRUE))>0) | (length(grep(NFLTerms[9],a,ignore.case=TRUE))>0) | (length(grep(NFLTerms[10],a,ignore.case=TRUE))>0) | (length(grep(NFLTerms[11],a,ignore.case=TRUE))>0) | (length(grep(NFLTerms[12],a,ignore.case=TRUE))>0) | (length(grep(NFLTerms[13],a,ignore.case=TRUE))>0) | (length(grep(NFLTerms[14],a,ignore.case=TRUE))>0) | (length(grep(NFLTerms[15],a,ignore.case=TRUE))>0) | (length(grep(NFLTerms[16],a,ignore.case=TRUE))>0) | (length(grep(NFLTerms[17],a,ignore.case=TRUE))>0) | (length(grep(NFLTerms[18],a,ignore.case=TRUE))>0) | (length(grep(NFLTerms[19],a,ignore.case=TRUE))>0) | (length(grep(NFLTerms[20],a,ignore.case=TRUE))>0) | (length(grep(NFLTerms[21],a,ignore.case=TRUE))>0) | (length(grep(NFLTerms[22],a,ignore.case=TRUE))>0) | (length(grep(NFLTerms[23],a,ignore.case=TRUE))>0) | (length(grep(NFLTerms[24],a,ignore.case=TRUE))>0) | (length(grep(NFLTerms[25],a,ignore.case=TRUE))>0) | (length(grep(NFLTerms[26],a,ignore.case=TRUE))>0) | (length(grep(NFLTerms[27],a,ignore.case=TRUE))>0) | (length(grep(NFLTerms[28],a,ignore.case=TRUE))>0) | (length(grep(NFLTerms[29],a,ignore.case=TRUE))>0) | (length(grep(NFLTerms[30],a,ignore.case=TRUE))>0) | (length(grep(NFLTerms[31],a,ignore.case=TRUE))>0) | (length(grep(NFLTerms[32],a,ignore.case=TRUE))>0) | (length(grep(NFLTerms[33],a,ignore.case=TRUE))>0) ) { if(a$league != 0) { #another league was also mentioned, will remove tweet a$league = 5 } else { #set league to 3 if league wasnt previously set a$league = "NFL" } } data.frame(a) } #function to remove tweets having both the words love and hate filterTweetsNHL<-function(a) { # check if text doesn't have both love and hate in it if((length(grep(NHLTerms[1],a,ignore.case=TRUE))>0) | (length(grep(NHLTerms[2],a,ignore.case=TRUE))>0) | (length(grep(NHLTerms[3],a,ignore.case=TRUE))>0) | (length(grep(NHLTerms[4],a,ignore.case=TRUE))>0) | (length(grep(NHLTerms[5],a,ignore.case=TRUE))>0) | (length(grep(NHLTerms[6],a,ignore.case=TRUE))>0) | (length(grep(NHLTerms[7],a,ignore.case=TRUE))>0) | (length(grep(NHLTerms[8],a,ignore.case=TRUE))>0) | (length(grep(NHLTerms[9],a,ignore.case=TRUE))>0) | (length(grep(NHLTerms[10],a,ignore.case=TRUE))>0) | (length(grep(NHLTerms[11],a,ignore.case=TRUE))>0) | (length(grep(NHLTerms[12],a,ignore.case=TRUE))>0) | (length(grep(NHLTerms[13],a,ignore.case=TRUE))>0) | (length(grep(NHLTerms[14],a,ignore.case=TRUE))>0) | (length(grep(NHLTerms[15],a,ignore.case=TRUE))>0) | (length(grep(NHLTerms[16],a,ignore.case=TRUE))>0) | (length(grep(NHLTerms[17],a,ignore.case=TRUE))>0) | (length(grep(NHLTerms[18],a,ignore.case=TRUE))>0) | (length(grep(NHLTerms[19],a,ignore.case=TRUE))>0) | (length(grep(NHLTerms[20],a,ignore.case=TRUE))>0) | (length(grep(NHLTerms[21],a,ignore.case=TRUE))>0) | (length(grep(NHLTerms[22],a,ignore.case=TRUE))>0) | (length(grep(NHLTerms[23],a,ignore.case=TRUE))>0) | (length(grep(NHLTerms[24],a,ignore.case=TRUE))>0) | (length(grep(NHLTerms[25],a,ignore.case=TRUE))>0) | (length(grep(NHLTerms[26],a,ignore.case=TRUE))>0) | (length(grep(NHLTerms[27],a,ignore.case=TRUE))>0) | (length(grep(NHLTerms[28],a,ignore.case=TRUE))>0) | (length(grep(NHLTerms[29],a,ignore.case=TRUE))>0) | (length(grep(NHLTerms[30],a,ignore.case=TRUE))>0) | (length(grep(NHLTerms[31],a,ignore.case=TRUE))>0)) { if(a$league != 0) { #another league was also mentioned, will remove tweet a$league = 5 } else { #set league to 4 if league wasnt previously set a$league = "NHL" } } data.frame(a) } #Capture new tweets and updateTweets<-function(a, firstTime){ #stream tweets only in US locations filterStream("tweetsUS.json", locations = c(-125, 25, -66, 50), timeout = TWEET_DURATION, oauth = my_oauth) #parse tweets from .json file tweets.df <- parseTweets("tweetsUS.json", verbose = FALSE) #delete file once it is stored, to be written to again file.remove("tweetsUS.json") #copy parsed tweets, init league to 0 tweets.filter <- tweets.df tweets.filter$league = 0 # push tweets through all league filters tweets.filter<-ddply(tweets.filter,.(text),filterTweetsMLB) tweets.filter<-ddply(tweets.filter,.(text),filterTweetsNBA) tweets.filter<-ddply(tweets.filter,.(text),filterTweetsNFL) tweets.filter<-ddply(tweets.filter,.(text),filterTweetsNHL) #Only look at rows where one league was selected tweets.filter <- subset(tweets.filter, tweets.filter$league == "MLB" | tweets.filter$league == "NBA" | tweets.filter$league == "NFL" | tweets.filter$league == "NHL") #if first time, cant bind yet if(firstTime) { tweets.running <- tweets.filter } else { #append new filtered tweets to old tweets.running <- rbind(a, tweets.filter) } return (tweets.running) } mapData <- function(a){ #US map map.data <- map_data("state") p <- ggplot(map.data) + geom_map(aes(map_id = region), map = map.data, fill = "white", color = "grey20", size = 0.25) + expand_limits(x = map.data$long, y = map.data$lat) + theme(axis.line = element_blank(), axis.text = element_blank(), axis.ticks = element_blank(), axis.title = element_blank(), panel.background = element_blank(), panel.border = element_blank(), panel.grid.major = element_blank(), plot.background = element_blank(), legend.title=element_blank(), plot.margin = unit(0 * c(-1.5, -1.5, -1.5, -1.5), "lines")) + geom_point(data = points, aes(x = x, y = y, color = factor(points$league)), size = 2 , alpha = 1/2) + scale_colour_manual(values=cbbPalette) + coord_cartesian(xlim = c(-60, -130)) #trim off unused edges on x axis, not lways needed return (p) } #print total counts of each league printTotals <- function() { #print totals print(paste0("Total MLB Tweets: ", sum(tweets.running$league=="MLB", na.rm=TRUE))) print(paste0("Total NBA Tweets: ", sum(tweets.running$league=="NBA", na.rm=TRUE))) print(paste0("Total NFL Tweets: ", sum(tweets.running$league=="NFL", na.rm=TRUE))) print(paste0("Total NHL Tweets: ", sum(tweets.running$league=="NHL", na.rm=TRUE))) } #run these prior to starting loop #handshake for twitter credentials my_oauth$handshake(cainfo = system.file("CurlSSL", "cacert.pem", package = "RCurl")) #define globally, used in many functions tweets.running <- data.frame(0) points <- data.frame(0) result <- data.frame(0) #Set hash count counts <- GetHash("wordcount") #Gather new tweets and update filter for first time tweets.running <- updateTweets(tweets.running, TRUE) result <- countMin(tweets.running) #determine good length for (i in 1:ITERATIONS) { #Gather new tweets and update filter tweets.running <- updateTweets(tweets.running, FALSE) result <- countMin(tweets.running) #define points with only latitude, longitude, and league class #update global so it can be used in ggplot points <- data.frame(x = as.numeric(tweets.running$lon), y = as.numeric(tweets.running$lat), league = tweets.running$league) #Define map and print it map <- mapData(points) print(map) #Print total counts printTotals() } #Prints the most successful franchises in one league MLB=NULL pop = NULL MLBcount = 0 counts <- GetHash("wordcount", result) MLB = maxMLB(counts,MLBTerms) if(MLBcount<maxMLBcount(counts,MLBTerms)) { MLBcount = maxMLBcount(counts,MLBTerms) pop = "MLB" } print("Most Tweeted Baseball Team:") print(MLB) MLB = maxMLB(counts,NBATerms) if(MLBcount<maxMLBcount(counts,NBATerms)) { MLBcount = maxMLBcount(counts,NBATerms) pop = "NBA" } print("Most Tweeted Basketball Team:") print(MLB) MLB = maxMLB(counts,NHLTerms) if(MLBcount<maxMLBcount(counts,NHLTerms)) { MLBcount = maxMLBcount(counts,NHLTerms) pop = "NHL" } print("Most Tweeted Hockey Team:") print(MLB) MLB = maxMLB(counts,NFLTerms) if(MLBcount<maxMLBcount(counts,NFLTerms)) { MLBcount = maxMLBcount(counts,NFLTerms) pop = "NFL" } print("Most Tweeted Football Team:") print(MLB) print("Most Tweeted League:") print(pop)
ba14df1dcd84053ea2d7873f3a50ba03cfa4c27e
2f5db3fb3d5841cca614df7d5c881dc7004b0054
/tests/testthat/test-tree2mat.R
182fd99a15eacdce0d0eb04fca2808a89db6a2d8
[]
no_license
darcyj/specificity
d7e62e3cbe84ca20d3703aaf981ef2dc31f61db8
f826719f153656ddce6c7347ac6bbcd08be12e3d
refs/heads/master
2023-08-08T12:02:59.686467
2023-07-28T02:47:55
2023-07-28T02:47:55
205,035,039
7
1
null
null
null
null
UTF-8
R
false
false
934
r
test-tree2mat.R
library(specificity) library(testthat) test_that("tree2mat matches ape::cophenetic.phylo", { # use plant genera tree from specificity::endophyte set.seed(12345) a <- endophyte$supertree atips <- sample(a$tip.label, 20) cph_mat <- ape::cophenetic.phylo(ape::keep.tip(a, atips)) # re-order cph_mat to match atips cph_mat <- cph_mat[order(match(rownames(cph_mat),atips)), order(match(colnames(cph_mat),atips))] cph_dis <- as.dist(cph_mat) t2m_dis <- tree2mat(a, atips) # round to 4 decimal places gets around C vs R precision balogna expect_true(all(round(cph_dis, 4) == round(t2m_dis, 4))) }) test_that("tree2mat error if tip not in tree", { expect_error(tree2mat(endophyte$supertree, c("bob", "Cyanea", "Euphorbia"))) }) test_that("tree2mat error if tip in tree multiple times", { a <- endophyte$supertree a$tip.label[1:4] <- "bad_label" expect_error(tree2mat(a, c("Lycium", "Cyanea", "Euphorbia", "bad_label"))) })
b2689b7db0ee5accd63bea50db6745c28c4a9225
6e17a70abf17794d29f482336a805ae468096fb0
/man/scale_color_dubois1.Rd
ac32cd1b04fd91c3fc0d91851f614f93bafef83a
[ "MIT" ]
permissive
brevinf1/themedubois
544cd4e7a67c51d8a494304eb453fe89a76b5733
a80e44571aed55d3d06ed53706e31e8742296be4
refs/heads/master
2023-03-09T20:22:15.501152
2021-02-22T18:06:34
2021-02-22T18:06:34
null
0
0
null
null
null
null
UTF-8
R
false
true
305
rd
scale_color_dubois1.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/scale_color_dubois1.R \name{scale_color_dubois1} \alias{scale_color_dubois1} \title{Long color palette (color)} \usage{ scale_color_dubois1() } \value{ Color with long color palette } \description{ Long color palette (color) }
04479578c0c1cae83ddede789cba7ba976f475bf
fb66254c9f6579e7b5a3bac623c16e63c9c3f987
/updateWeight.ConvLayer.R
5db628943f0d54e922436e6a185d0ca3e6deff29
[]
no_license
LinHungShi/ConvolutionalNeuralNetwork
049573d1f9b400d84da55d47c1d0053c0f109da4
02d4e6b2e5c480951c0474cff5c732d1a1cc4a39
refs/heads/master
2020-04-14T13:16:53.313601
2015-09-07T15:59:23
2015-09-07T15:59:23
40,487,913
0
0
null
null
null
null
UTF-8
R
false
false
324
r
updateWeight.ConvLayer.R
updateWeight.ConvLayer <- function(layer, n_layer, alpha){ input <- layer$input output <- layer$output n_grad <- n_layer$grad layer$grad <- updateGradient(layer, n_layer) layer$w_grad <- updateWgradient(layer) layer$weight <- updateWeight_(layer$weight, layer$w_grad, alpha) return (layer) }
6a21051aa0f52b3cf0153fab0ed63c18b647bba8
e61f27d49a8a975b37b7b93ea79d605e430c4c57
/Module-2-Data-Warehousing/workspace/case 4/etl.r
a87e5fdba5cbea42fb81ddaa862f0cd966110db3
[]
no_license
Cbanzaime23/up-nec-business-intelligence
1c58fec21b5fbdf79f72c8fd9f7c0148aa7458b1
24c1d1d97b461e0e26a79cf6129f51b3cc545d2c
refs/heads/master
2020-08-28T15:24:33.874816
2017-09-03T09:07:04
2017-09-03T09:07:04
null
0
0
null
null
null
null
UTF-8
R
false
false
9,173
r
etl.r
# 3.1 Extraction of Data from Source and Insert to S library(RSQLite) #Connect to the Source System db <- dbConnect(SQLite(), dbname="source.db") #Extract Today's Shippers Data shippers_extract = dbGetQuery( db,'SELECT * FROM shippers' ) #Close Source Connection dbDisconnect(db) #Connect to the DW System dwcon <- dbConnect(SQLite(), dbname="datawarehousenew.db") #Insert into S deletesshippers = dbGetQuery(dwcon,"DELETE FROM s_shippers" ) dbWriteTable(conn = dwcon, name = "s_shippers", value =shippers_extract, row.names = FALSE, append = TRUE) #Validate dbGetQuery(dwcon, "SELECT * FROM s_shippers") # 3.2 Get New and Changed Data and Insert into X #Get New and Changed Data s_table_new_data <- dbGetQuery(dwcon, "SELECT * FROM s_shippers WHERE shipperid NOT IN (SELECT shipperid FROM m_shippers)") s_table_changed_company_name <-dbGetQuery(dwcon, "SELECT s.ShipperID, s.CompanyName,s.Phone FROM S_Shippers s INNER JOIN M_Shippers m ON s.ShipperID = m.ShipperID WHERE NOT s.CompanyName = m.CompanyName") s_table_changed_phone_number <-dbGetQuery(dwcon, "SELECT s.ShipperID, s.CompanyName,s.Phone FROM S_Shippers s INNER JOIN M_Shippers m ON s.ShipperID = m.ShipperID WHERE NOT s.Phone = m.Phone") s_table_changed_data <- rbind(s_table_changed_company_name,s_table_changed_phone_number) s_table_extract <- rbind(s_table_new_data,s_table_changed_data) #Insert into X deletequery=dbGetQuery(dwcon, "DELETE FROM X_Shippers") dbWriteTable(conn = dwcon, name = "X_Shippers", value =s_table_extract, row.names = FALSE, append = TRUE) #Validate dbGetQuery(dwcon, "SELECT * FROM X_shippers") # 3.3 Clean X and Insert Errors into E #Clean X #Select Companies with Null Names x_table_no_companyname = dbGetQuery(dwcon, "SELECT * FROM x_shippers WHERE companyname = ''") x_table_no_companyname$ErrorType = "No Company Name" #Select Duplicate Companies x_table_duplicate_companies= dbGetQuery(dwcon, "SELECT * FROM x_shippers WHERE companyname IN (SELECT companyname FROM s_shippers GROUP BY companyname HAVING COUNT(companyname) > 1)") x_table_duplicate_companies$ErrorType = "Duplicate Company Name" x_table_errors = rbind(x_table_duplicate_companies,x_table_no_companyname) #Set Unknown to Missing Phone Number updatequery =dbGetQuery(dwcon, "UPDATE X_shippers SET Phone='Unknown Phone Number' WHERE Phone = ''") #Insert into E deletequery=dbGetQuery(dwcon, "DELETE FROM e_shippers") dbWriteTable(conn = dwcon, name = "e_shippers", value =x_table_errors, row.names = FALSE, append = TRUE) #Validate dbGetQuery(dwcon, "SELECT * FROM e_shippers") # 3.4. Select Clean Data and Insert into C #Select Clean Data x_table_clean_data = dbGetQuery(dwcon, "SELECT * FROM X_Shippers WHERE ShipperID NOT IN (SELECT ShipperID FROM E_Shippers)") #Insert into C query=dbGetQuery(dwcon, "DELETE FROM C_Shippers") dbWriteTable(conn = dwcon, name = "C_Shippers", value =x_table_clean_data, row.names = FALSE, append = TRUE) #Validate dbGetQuery(dwcon, "SELECT * FROM C_Shippers") # 3.5. Update M Table #Update M Table #Select All New From C c_table_new_data = dbGetQuery(dwcon, "SELECT * from C_Shippers c WHERE c.ShipperID NOT IN (SELECT m.ShipperID FROM M_shippers m )") dbWriteTable(conn = dwcon, name = "M_Shippers_Test", value =c_table_new_data, row.names = FALSE, append = TRUE) #Select All Changed From C c_table_changed_data = dbGetQuery(dwcon, "SELECT c.* FROM C_Shippers c, M_Shippers m WHERE c.ShipperID = m.ShipperID and (c.CompanyName <> m.CompanyName or c.Phone <> m.Phone)") deletequery = dbGetQuery(dwcon, "DELETE FROM M_Shippers_Test WHERE ShipperID IN (SELECT m.ShipperID FROM C_Shippers c, M_Shippers m WHERE c.ShipperID = m.ShipperID and (c.CompanyName <> m.CompanyName or c.Phone <> m.Phone))") dbWriteTable(conn = dwcon, name = "M_Shippers_Test", value=c_table_changed_data, row.names = FALSE, append = TRUE) #Validate dbGetQuery(dwcon, "SELECT * FROM M_Shippers_Test") # 3.6. Select From C, Transform and Insert into T #Select From C and Transform to DW Format c_table_data = dbGetQuery(dwcon, "SELECT ShipperID as [Shipper_ID], CompanyName as [Shipper_Name], Phone as [Current_Shipper_Phone], DATE() as [Effective_Date] FROM C_Shippers" ) c_table_data$Previous_Shipper_Phone = "Previous_Shipper_Phone" c_table_data = c_table_data[,c("Shipper_ID", "Shipper_Name", "Current_Shipper_Phone","Previous_Shipper_Phone", "Effective_Date" ) ] #Insert into T query=dbGetQuery(dwcon, "DELETE FROM T_Shipper") dbWriteTable(conn = dwcon, name = "T_Shipper", value =c_table_data, row.names = FALSE, append = TRUE) #Validate dbGetQuery(dwcon, "SELECT * FROM T_Shipper") # 3.7. Select New From T Insert Into I #Select New from T t_table_new_data = dbGetQuery(dwcon, "SELECT t.* FROM t_shipper t LEFT JOIN d_shipper d ON t.Shipper_ID = d.Shipper_ID WHERE d.Shipper_ID IS NULL") t_table_new_data$Current_Row_Ind = 'Y' #Insert New into I query=dbGetQuery(dwcon, "DELETE FROM I_Shipper") dbWriteTable(conn = dwcon, name = "I_Shipper", value =t_table_new_data, row.names = FALSE, append = TRUE) #Validate dbGetQuery(dwcon, "SELECT * FROM I_Shipper") # 3.8. Select Updated From T Insert Into U #Select Changed from T t_table_changed_data=dbGetQuery(dwcon, "SELECT t.* FROM t_shipper t inner join d_shipper d ON t.Shipper_ID = d.Shipper_ID WHERE (NOT t.Shipper_Name = d.Shipper_Name or NOT t.Current_Shipper_Phone = d.Current_Shipper_Phone) AND d.Current_Row_Ind = 'Y'") t_table_changed_data$Current_Row_Ind = 'Y' #Insert into U deletequery=dbGetQuery(dwcon, "DELETE FROM U_Shipper") dbWriteTable(conn = dwcon, name = "U_Shipper", value =t_table_changed_data, row.names = FALSE, append = TRUE) #Validate dbGetQuery(dwcon, "SELECT * FROM U_Shipper") # 3.9. Select from I Insert into D maxkey <- dbGetQuery(dwcon, "SELECT MAX(Shipper_Key) as MAX FROM D_Shipper") i_table_data <- dbGetQuery(dwcon, "SELECT * FROM I_Shipper") i_table_data$Shipper_Key = (maxkey[1,1]+1):(maxkey[1,1]+nrow(i_table_data)) #Insert New into D i_table_data = i_table_data[,c("Shipper_Key","Shipper_ID","Shipper_Name", "Current_Shipper_Phone", "Previous_Shipper_Phone", "Effective_Date", "Current_Row_Ind" )] dbWriteTable(conn = dwcon, name = "D_Shipper", value =i_table_data, row.names = FALSE, append = TRUE) #Validate dbGetQuery(dwcon, "SELECT * FROM D_Shipper") # 3.10. Select Type 3 Updates from U, Update D #Select Type 3 from U and D u_table_type3_data <- dbGetQuery(dwcon, "SELECT u.* from u_shipper u inner join d_shipper d on u.Shipper_ID = d.Shipper_ID where NOT (u.Current_Shipper_Phone = d.Current_Shipper_Phone) and d.Current_Row_Ind = 'Y'") d_table_type3_data <- dbGetQuery(dwcon, "SELECT d.* from u_shipper u inner join d_shipper d on u.Shipper_ID = d.Shipper_ID where NOT (u.Current_Shipper_Phone = d.Current_Shipper_Phone) and d.Current_Row_Ind = 'Y'") u_table_type3_data$Previous_Shipper_Phone = d_table_type3_data$Current_Shipper_Phone u_table_type3_data$Shipper_Key = d_table_type3_data$Shipper_Key u_table_type3_data = u_table_type3_data[,c("Shipper_Key","Shipper_ID","Shipper_Name", "Current_Shipper_Phone", "Previous_Shipper_Phone", "Effective_Date", "Current_Row_Ind" )] deletequery = dbGetQuery(dwcon, "DELETE FROM d_shipper WHERE Shipper_ID IN (SELECT d.Shipper_ID from u_shipper u inner join d_shipper d on u.Shipper_ID = d.Shipper_ID where NOT (u.Current_Shipper_Phone = d.Current_Shipper_Phone) and d.Current_Row_Ind = 'Y')") dbWriteTable(conn = dwcon, name = "d_shipper", value =u_table_type3_data, row.names = FALSE, append = TRUE) #Validate dbGetQuery(dwcon, "SELECT * FROM D_Shipper") # 3.11. Select Type 2 Updates from U, Insert into D #Select Type 2 maxkey <- dbGetQuery(dwcon, "SELECT MAX(Shipper_Key) as MAX FROM D_Shipper") u_table_type2_data <- dbGetQuery(dwcon, "SELECT u.* FROM u_shipper u INNER JOIN d_shipper d ON u.Shipper_ID = d.Shipper_ID WHERE NOT (u.Shipper_Name = d.Shipper_Name) AND d.Current_Row_Ind = 'Y'") u_table_type2_data$Shipper_Key = (maxkey[1,1]+1):(maxkey[1,1]+nrow(u_table_type2_data)) #Insert New into D u_table_type2_data=u_table_type2_data[,c("Shipper_Key","Shipper_ID","Shipper_Name", "Current_Shipper_Phone", "Previous_Shipper_Phone", "Effective_Date", "Current_Row_Ind" )] dbWriteTable(conn = dwcon, name = "d_shipper", value =u_table_type2_data, row.names = FALSE, append = TRUE) #Validate dbGetQuery(dwcon, "SELECT * FROM D_Shipper") # 3.12. Update Current Indicators in D #Update Shipper Current Value forupdatedata <- dbGetQuery(dwcon, "SELECT d.* FROM u_shipper u INNER JOIN d_shipper d ON u.Shipper_Id = d.Shipper_Id WHERE d.Current_Row_Ind = 'Y' AND Not u.Shipper_Name = d.Shipper_Name ") forupdatedata$Current_Row_Ind = 'N' deletequery = dbGetQuery(dwcon, "DELETE FROM d_shipper WHERE Shipper_Key IN (SELECT d.Shipper_Key FROM u_shipper u INNER JOIN d_shipper d ON u.Shipper_Id = d.Shipper_Id WHERE d.Current_Row_Ind = 'Y' AND Not u.Shipper_Name = d.Shipper_Name)") dbWriteTable(conn = dwcon, name = "d_shipper", value =forupdatedata, row.names = FALSE, append = TRUE) dbGetQuery(dwcon, "SELECT * FROM D_Shipper") dbDisconnect(dwcon)
1b0ee8b57ee0954be2c858bb770fb821e46596f0
faec5b544d361a40e1955c776fd5483547d299b8
/MovieLens-project.R
3f0834fcd320fbd8daee6ecef716cf6e53b6e4ad
[]
no_license
kinube/edX-DataScience
62ce88b8cbf510025a32d72fa433b85512b357fe
24447dfc802269501cf7308dfd00d6bf24f65513
refs/heads/master
2020-04-05T16:45:50.507630
2020-01-06T01:50:06
2020-01-06T01:50:06
157,027,485
0
1
null
null
null
null
WINDOWS-1252
R
false
false
13,180
r
MovieLens-project.R
#### MovieLens project #### # Author: Kiko Núñez # Start Date: 09/08/2019 # End Date: 13/10/2019 ## Load libraries needed: library(stringr) library(dplyr) library(caret) library(ggplot2) library(grid) library(scales) ################################ # Create edx set, validation set ################################ # Note: this process could take a couple of minutes if(!require(tidyverse)) install.packages("tidyverse", repos = "http://cran.us.r-project.org") if(!require(caret)) install.packages("caret", repos = "http://cran.us.r-project.org") if(!require(data.table)) install.packages("data.table", repos = "http://cran.us.r-project.org") # MovieLens 10M dataset: # https://grouplens.org/datasets/movielens/10m/ # http://files.grouplens.org/datasets/movielens/ml-10m.zip dl <- tempfile() download.file("http://files.grouplens.org/datasets/movielens/ml-10m.zip", dl) ratings <- fread(text = gsub("::", "\t", readLines(unzip(dl, "ml-10M100K/ratings.dat"))), col.names = c("userId", "movieId", "rating", "timestamp")) movies <- str_split_fixed(readLines(unzip(dl, "ml-10M100K/movies.dat")), "\\::", 3) colnames(movies) <- c("movieId", "title", "genres") movies <- as.data.frame(movies) %>% mutate(movieId = as.numeric(levels(movieId))[movieId], title = as.character(title), genres = as.character(genres)) movielens <- left_join(ratings, movies, by = "movieId") # Validation set will be 10% of MovieLens data set.seed(1, sample.kind="Rounding") # if using R 3.5 or earlier, use `set.seed(1)` instead test_index <- createDataPartition(y = movielens$rating, times = 1, p = 0.1, list = FALSE) edx <- movielens[-test_index,] temp <- movielens[test_index,] # Make sure userId and movieId in validation set are also in edx set validation <- temp %>% semi_join(edx, by = "movieId") %>% semi_join(edx, by = "userId") # Add rows removed from validation set back into edx set removed <- anti_join(temp, validation) edx <- rbind(edx, removed) rm(dl, ratings, movies, test_index, temp, movielens, removed) #### 1. Initial analysis #### # Visual inspection: str(edx) #### 2. Preprocessing #### ## Extract year of rating from timestamp: edx <- transform(edx, timestamp = as.POSIXct(timestamp, origin = "1970-01-01")) edx$yearRating <- as.integer(format(edx$timestamp, '%Y')) # Add yearRating column to edx dataset ## Add year of movie column: edx$yearMovie <- as.integer(sub("\\).*", "", sub(".*\\(", "", edx$title))) ## Genre bagging: GenresBags <- unique(unlist(str_split(edx$genres, "\\|"))) # Split genre value by '|' print(GenresBags) print(paste("Movies in the dataset have", length(GenresBags), "different types of genres.")) GenresEdx <- matrix(, nrow(edx), length(GenresBags)) # set-up a matrix for bagging genres colnames(GenresEdx) <- GenresBags ## Populate the matrix of genres (this may take a while): pb <- txtProgressBar(min = 0, max = length(GenresBags), style = 3) for (i in 1:length(GenresBags)) { GenresEdx[grep(GenresBags[i],edx$genres), i] <- 1 setTxtProgressBar(pb, i) } GenresEdx[is.na(GenresEdx)] <- 0 edx <- cbind(edx, GenresEdx) ## Drop useless columns: timestamp and title: edx_clean <- edx %>% select(-c(timestamp, title)) #### 3. Understanding the dataset #### ## Overall ratings distribution: edx_clean %>% ggplot(aes(x=factor(rating))) + geom_bar(color="steelblue", fill="steelblue") + labs(x = "Ratings", y = "Counts") + scale_y_continuous(labels = comma) summary(edx_clean$rating) ## Ratings (counts and mean value) by users: edx_clean %>% group_by(userId) %>% summarise(Users = n()) %>% ggplot(aes(Users)) + geom_histogram(bins = 50, fill = "steelblue", color = "white") + scale_x_log10() + labs(title = "Number of ratings per user") + xlab("Number of ratings") + ylab("Number of users") edx_clean %>% group_by(userId) %>% summarise(meanRating = mean(rating)) %>% ggplot(aes(meanRating)) + geom_histogram(bins = 50, fill = "salmon4", color = "white") + labs(title = "Mean ratings per users") + xlab("Mean Rating") + ylab("Number of users") ## Ratings (counts and mean value) by movies: edx_clean %>% group_by(movieId) %>% summarise(Movies = n()) %>% ggplot(aes(Movies)) + geom_histogram(bins = 50, fill = "steelblue", color = "white") + scale_x_log10() + labs(title = "Number of ratings per movie") + xlab("Number of ratings") + ylab("Number of movies") edx_clean %>% group_by(movieId) %>% summarise(meanRatingMovie = mean(rating)) %>% ggplot(aes(meanRatingMovie)) + geom_histogram(bins = 50, fill = "salmon4", color = "white") + labs(title = "Mean ratings per movie") + xlab("Mean rating") + ylab("Number of movies") ## Ratings (counts and mean value) by movie antiquity: edx_clean %>% mutate(yearDiff = yearRating - yearMovie) %>% group_by(yearDiff) %>% summarise(Difference = n()) %>% ggplot(aes(yearDiff, Difference)) + geom_bar(stat = "identity", fill = "steelblue", color = "white") + scale_y_continuous(labels = comma) + labs(title = "Number of ratings per movie antiquity") + xlab("Movie antiquity") + ylab("Number of ratings") edx_clean %>% mutate(yearDiff = yearRating - yearMovie) %>% group_by(yearDiff) %>% summarise(meanRatingYearDiff = mean(rating)) %>% ggplot(aes(yearDiff, meanRatingYearDiff)) + geom_point(color = "salmon4") + geom_smooth(method = "loess", formula = y ~ x) + labs(title = "Mean rating per movie antiquity", x = "Movie antiquity (in years)", y = "Mean rating") ## Ratings (counts and mean values) by genres (aggregated): edx_clean %>% group_by(genres) %>% summarise(Genres = n()) %>% ggplot(aes(Genres)) + geom_histogram(bins = 50, fill = "steelblue", color = "white") + scale_x_log10(labels = comma) + labs(title = "Number of ratings per genre group") + xlab("Number of ratings") + ylab("Number of genre groups") edx_clean %>% group_by(genres) %>% summarise(meanRatingGenres = mean(rating)) %>% ggplot(aes(meanRatingGenres)) + geom_histogram(bins = 50, fill = "salmon4", color = "white") + labs(title = "Mean ratings per genres (aggregated)") + xlab("Mean rating") + ylab("Number of genres") ## Ratings (counts and mean values) by genres (atomic): p_countGenres <- NULL p_ratingGenres <- NULL for (i in 1:length(GenresBags)) { # Calculate counts and mean ratings per genre index <- which(edx_clean[GenresBags[i]] == 1) p_ratingGenres <- append(p_ratingGenres, mean(edx_clean[index, "rating"])) p_countGenres <- append(p_countGenres, length(index)) } names(p_ratingGenres) <- GenresBags names(p_countGenres) <- GenresBags # Plot the results par(mai = c(1.8, 1, 1, 1)) barplot(p_countGenres/1000000, ylim = c(-5, 5), axes = FALSE, border = NA, col = "steelblue", las = 2, main = "Number of ratings and mean ratings by genre") barplot(-p_ratingGenres, add = TRUE, axes = FALSE, col = "salmon4", border = NA, names.arg = NA) axis(2, at = seq(-5, 5, 1), labels = c(rev(seq(0, 5, 1)), seq(1, 5, 1)), las = 2) mtext("Mean", 2, line = 3, at = -2.5, col = "salmon4") mtext("Number (Mill.)", 2, line = 3, at = 2.5, col = "steelblue") ## Ratings (count and mean values) by year of movie: edx_clean %>% group_by(yearMovie) %>% summarise(Years = n()) %>% ggplot(aes(yearMovie, Years)) + geom_bar(stat = "identity", fill = "steelblue", color = "white") + labs(title = "Number of ratings per year of movie") + xlab("Year") + ylab("Number of ratings") + scale_y_continuous(labels = comma) edx_clean %>% group_by(yearMovie) %>% summarise(meanRatingYear = mean(rating)) %>% ggplot(aes(yearMovie, meanRatingYear)) + geom_point(color = "salmon4") + geom_smooth(method = "loess", formula = y ~ x) + labs(title = "Mean ratings per year of movie") + xlab("Year") + ylab("Mean rating") #### 4. Building the model to predict ratings #### ## Baseline (mean) model: # Baseline calculation: Baseline <- mean(edx_clean$rating) print(paste("Baseline model (average): ", Baseline)) ## Model includeing user effect: # Penalty term due to user effect (p_user): meanUsers <- edx_clean %>% group_by(userId) %>% summarise(p_user = mean(rating - Baseline)) meanUsers %>% ggplot(aes(p_user)) + geom_histogram(bins = 50, fill = "darkgreen", color = "white") + labs(title = "Effect of users") + xlab("Penalty due to user effect") + ylab("Frequency") ## Model including user and movie effect: # Penalty term due to movie effect: meanMovies <- edx_clean %>% left_join(meanUsers, by = "userId") %>% group_by(movieId) %>% summarise(p_movie = mean(rating - Baseline - p_user)) meanMovies %>% ggplot(aes(p_movie)) + geom_histogram(bins = 50, fill = "darkgreen", color = "white") + labs(title = "Effect of movies") + xlab("Penalty due to movie effect") + ylab("Frequency") ## Model including user, movie and antiquity: # Penalty term due to antiquity effect: meanDiffYear <- edx_clean %>% mutate(diffYear = yearRating - yearMovie) %>% left_join(meanUsers, by = "userId") %>% left_join(meanMovies, by = "movieId") %>% group_by(diffYear) %>% summarise(p_diffYear = mean(rating - Baseline - p_user - p_movie)) meanDiffYear %>% ggplot(aes(p_diffYear)) + geom_histogram(bins = 50, fill = "darkgreen", color = "white") + labs(title = "Effect of movie antiquity") + xlab("Penalty due to year of movie antiquity effect") + ylab("Frequency") ## Model including user, movie, antiquity and genre: # Penalty term due to genre effect: meanGenre <- edx_clean %>% mutate(diffYear = yearRating - yearMovie) %>% left_join(meanUsers, by = "userId") %>% left_join(meanMovies, by = "movieId") %>% left_join(meanDiffYear, by = "diffYear") %>% group_by(genres) %>% summarise(p_genres = mean(rating - Baseline - p_user - p_movie - p_diffYear)) meanGenre %>% ggplot(aes(p_genres)) + geom_histogram(bins = 50, fill = "darkgreen", color = "white") + labs(title = "Effect of movie genre") + xlab("Penalty due to movie genre") + ylab("Frequency") #### 5. Apply trained model to validation dataset #### ### First perform the same preprocessing: ## Extract year of rating from timestamp: validation <- transform(validation, timestamp = as.POSIXct(timestamp, origin = "1970-01-01")) validation$yearRating <- as.integer(format(validation$timestamp, '%Y')) # Add yearRating column to validation dataset ## Add year of movie column: validation$yearMovie <- as.integer(sub("\\).*", "", sub(".*\\(", "", validation$title))) ## Genre bagging: GenresVal <- matrix(, nrow(validation), length(GenresBags)) # set-up a matrix for bagging genres colnames(GenresVal) <- GenresBags pb <- txtProgressBar(min = 0, max = length(GenresBags), style = 3) for (i in 1:length(GenresBags)) { GenresVal[grep(GenresBags[i],validation$genres), i] <- 1 setTxtProgressBar(pb, i, title = "Populating genres") } GenresVal[is.na(GenresVal)] <- 0 validation <- cbind(validation, GenresVal) ## Drop useless columns (timestamp and title): validation_clean <- validation %>% select(-c(timestamp, title)) ## Now calculate RMSE of the model: # RMSE of baseline model: RMSE_Baseline <- RMSE(validation_clean$rating, Baseline) print(paste("RMSE in baseline model: ", RMSE_Baseline)) # RMSE including user effect: y_hat_users <- validation_clean %>% left_join(meanUsers, by = "userId") %>% mutate(pred_rating = Baseline + p_user) RMSE_Users <- RMSE(validation_clean$rating, y_hat_users$pred_rating) print(paste("RMSE adding user effect: ", RMSE_Users)) # RMSE including user and movie effect: y_hat_movies <- validation_clean %>% left_join(meanUsers, by = "userId") %>% left_join(meanMovies, by = "movieId") %>% mutate(pred_rating = Baseline + p_user + p_movie) RMSE_UsersMovies <- RMSE(validation_clean$rating, y_hat_movies$pred_rating) print(paste("RMSE adding movie and user effects: ", RMSE_UsersMovies)) # RMSE including user, movie and antiquity effects: y_hat_diffYear <- validation_clean %>% mutate(diffYear = yearRating - yearMovie) %>% left_join(meanUsers, by = "userId") %>% left_join(meanMovies, by = "movieId") %>% left_join(meanDiffYear, by = "diffYear") %>% mutate(pred_rating = Baseline + p_user + p_movie + p_diffYear) RMSE_UsersMoviesDiffYear <- RMSE(validation_clean$rating, y_hat_diffYear$pred_rating) print(paste("RMSE adding user, movie and antiquity effects: ", RMSE_UsersMoviesDiffYear)) # RMSE including user, movie, antiquity and genre effects: y_hat_genre <- validation_clean %>% mutate(diffYear = yearRating - yearMovie) %>% left_join(meanUsers, by = "userId") %>% left_join(meanMovies, by = "movieId") %>% left_join(meanDiffYear, by = "diffYear") %>% left_join(meanGenre, by = "genres") %>% mutate(pred_rating = Baseline + p_user + p_movie + p_diffYear + p_genres) RMSE_UsersMoviesDiffYearGenre <- RMSE(validation_clean$rating, y_hat_genre$pred_rating) print(paste("RMSE adding user, movie, antiquity and genre effects: ", RMSE_UsersMoviesDiffYearGenre))
c8e4a7c03ac2284f3f865fb3075b94896dc87a6d
31103bc586e6ea4959749543101d0d07679d53ec
/simulatePower.R
72c75875c882d1119f3cd5637c8aa5b99294cb4a
[]
no_license
luboRprojects/TDTmethodology
43e5b6d480ff78e1640f81475b7d92d86c60a30b
ad43770f1b064365b982935e7e8f872b1836ce21
refs/heads/master
2020-07-15T19:56:25.889499
2019-09-01T06:48:41
2019-09-01T06:48:41
205,638,413
0
0
null
null
null
null
UTF-8
R
false
false
760
r
simulatePower.R
# This file allows simulation of large number of # theoretical results if the DGP (data-generating process) is # know th the researcher. DGP is in the expressed in the: # - type of data distribution: rnorm # - parameters of such a distributions: mean, sd # Create a variable to which we store results pval <- c() # Run the simulation of n studies # Note that the research design is about number # of respondents: n nStudies <- 10000 for(i in 1:nstudies) { data1 <- rnorm(n=50, mean=15, sd=10) data2 <- rnorm(n=50, mean=11, sd=10) pval[i] <- t.test(data1, data2, alternative="greater")$p.val } # Table of p-values table(pval<0.05) # TRUE/nStudies is statistical power # What is the number of respondents (n) to reach power 0.8? # Check the G*power!
ff4a2262206e7e40ba882311a255717b75633f9a
121f6db541bfdaba545cd70742ef951b75c90e73
/R/analysis/statistics.R
93df4afcfc6f6c498b97cebcb16cb4e2089c1021
[ "MIT" ]
permissive
bwhsleepamu/sleep.tools
22444ae127f695b3ba4d5e35b67e07212e8c563d
b0d3e3801f60fd9c0daffe9d5c63e7eccfb3ef38
refs/heads/master
2021-09-25T02:04:53.439361
2018-10-16T18:52:45
2018-10-16T18:52:45
19,426,999
0
0
MIT
2018-10-16T18:52:46
2014-05-04T13:25:52
HTML
UTF-8
R
false
false
10,601
r
statistics.R
## For periods: ### NEED: #DONE #### Agreement stats by subject and or subject group FOR EACH METHOD #### Number of periods per sleep episode for each period type by each method #### Distribution of period lengths for each type by subject and or subject group for each method #### OTHER COMPARISONS?? ## For cycles: ### NEED: distribution of lengths and counts for 1st, 2nd...cycles by subject and/or subject group FOR EACH METHOD ### Possible others: start times by cycle, # young_s <- subjects[study=="NIAPPG" & age_group=='Y'] # old_s <- subjects[study=="NIAPPG" & age_group=='O'] # csr_s <- subjects[study=="T20CSR-CSR"] # control_s <- subjects[study=="T20CSR-Control"] ## Agreement function() { # Cleaning: ## No sleep periods clean.periods <- copy(periods) clean.periods <- clean.periods[sleep_wake_period>0] ## Strip wake at beginning and end of sleep periods clean.periods <- clean.periods[,strip_wake(.SD),by='subject_code,sleep_wake_period'] clean.periods[,pik:=.I] clean.periods[,agreement:=sum(sleep_data[start_position:end_position]$epoch_type == label)/length,by='pik'] ## Agreement graph p <- ggplot(clean.periods[label %in% c('NREM', 'REM')], aes(x=agreement, color=method)) p <- p + scale_fill_manual(values=cbbPalette) + scale_colour_manual(values=cbbPalette) p <- p + ggtitle("Agreement within Periods by Method") p <- p + xlab("Agreement") p <- p + facet_grid(label ~ ., scales='free_y') p <- p + geom_density(alpha=.3) p ggsave("/home/pwm4/Desktop/Visualizations/agreement_full.svg", scale=2, width=9, height=4) # Young p <- ggplot(clean.periods[label %in% c('NREM', 'REM') & subject_code %in% young_s$subject_code], aes(x=agreement, color=method)) p <- p + scale_fill_manual(values=cbbPalette) + scale_colour_manual(values=cbbPalette) p <- p + ggtitle("Agreement within Periods by Method\nYounger Subjects") p <- p + xlab("Agreement") p <- p + facet_grid(label ~ ., scales='free_y') p <- p + geom_density(alpha=.3) p ggsave("/home/pwm4/Desktop/Visualizations/agreement_young.svg", scale=2, width=9, height=4) # Old p <- ggplot(clean.periods[label %in% c('NREM', 'REM') & subject_code %in% old_s$subject_code], aes(x=agreement, color=method)) p <- p + scale_fill_manual(values=cbbPalette) + scale_colour_manual(values=cbbPalette) p <- p + ggtitle("Agreement within Periods by Method\nOlder Subjects") p <- p + xlab("Agreement") p <- p + facet_grid(label ~ ., scales='free_y') p <- p + geom_density(alpha=.3) p ggsave("/home/pwm4/Desktop/Visualizations/agreement_old.svg", scale=2, width=9, height=4) # CSR p <- ggplot(clean.periods[label %in% c('NREM', 'REM') & subject_code %in% csr_s$subject_code], aes(x=agreement, color=method)) p <- p + scale_fill_manual(values=cbbPalette) + scale_colour_manual(values=cbbPalette) p <- p + ggtitle("Agreement within Periods by Method\nChronic Sleep Restriction") p <- p + xlab("Agreement") p <- p + facet_grid(label ~ ., scales='free_y') p <- p + geom_density(alpha=.3) p ggsave("/home/pwm4/Desktop/Visualizations/agreement_csr.svg", scale=2, width=9, height=4) # NON-CSR p <- ggplot(clean.periods[label %in% c('NREM', 'REM') & subject_code %in% control_s$subject_code], aes(x=agreement, color=method)) p <- p + scale_fill_manual(values=cbbPalette) + scale_colour_manual(values=cbbPalette) p <- p + ggtitle("Agreement within Periods by Method\nControl") p <- p + xlab("Agreement") p <- p + facet_grid(label ~ ., scales='free_y') p <- p + geom_density(alpha=.3) p ggsave("/home/pwm4/Desktop/Visualizations/agreement_control.svg", scale=2, width=9, height=4) } function() { epoch_length <- EPOCH_LENGTH # period stats #period_counts <- clean.periods[,list(nrem_count=sum(label=='NREM'),rem_count=sum(label=='REM'),wake_count=sum(label=='WAKE')),by='subject_code,sleep_wake_period,method'] period_counts <- copy(clean.periods) period_counts <- period_counts[,list(count=.N),by='subject_code,sleep_wake_period,method,label'] plot.period_counts(period_counts, subjects, "period_counts_all", "All Subjects") plot.period_counts(period_counts, young_s, "period_counts_young", "Younger Subjects") plot.period_counts(period_counts, old_s, "period_counts_old", "Older Subjects") plot.period_counts(period_counts, control_s, "period_counts_control", "Control Subjects") plot.period_counts(period_counts, csr_s, "period_counts_csr", "Chronic Sleep Restriction Subjects") ## Length distribution of periods period_lengths <- copy(clean.periods) period_lengths[,length:=length*epoch_length*60] period_lengths[,period_number:=seq(.N),by='subject_code,sleep_wake_period,method,label'] plot.period_lengths(period_lengths, subjects, "period_lengths_all", "All Subjects") plot.period_lengths(period_lengths, young_s, "period_lengths_young", "Younger Subjects") plot.period_lengths(period_lengths, old_s, "period_lengths_old", "Older Subjects") plot.period_lengths(period_lengths, control_s, "period_lengths_control", "Control Subjects") plot.period_lengths(period_lengths, csr_s, "period_lengths_csr", "Chronic Sleep Restriction Subjects") } plot.period_counts <- function(period_counts, subject_group, file_name, label) { ## Number of periods of each type per sleep episode p <- ggplot(period_counts[label %in% c('NREM', 'REM') & subject_code %in% subject_group$subject_code], aes(x=count, fill=method, color=method)) p <- p + ggtitle(paste("Periods per Sleep Episode", label, sep="\n")) p <- p + scale_fill_manual(values=cbbPalette) + scale_colour_manual(values=cbbPalette) p <- p + facet_grid(label ~ ., scales='free') p <- p + geom_freqpoly(binwidth=1, origin=-0.5) #p + geom_histogram(binwidth=1) ggsave(paste("/home/pwm4/Desktop/Visualizations/", file_name, '.svg', sep=''), scale=2, width=9, height=4) } plot.period_lengths <- function(period_lengths, subject_group, file_name, label, by_period_count=FALSE, show_outliers=FALSE) { pl <- period_lengths[label %in% c('NREM', 'REM') & subject_code %in% subject_group$subject_code] ul <- unique(pl[method=='classic']$period_number) p <- ggplot(pl[period_number %in% ul], aes(factor(period_number), length, color=method)) #p <- ggplot(period_lengths[label %in% c('NREM', 'REM') & subject_code %in% subject_group$subject_code], aes(method, length, color=method)) p <- p + ggtitle(paste("Distribution of Period Lengths", label, sep="\n")) p <- p + scale_fill_manual(values=cbbPalette) + scale_colour_manual(values=cbbPalette) p <- p + facet_grid(label ~ .) p <- p + geom_boxplot(outlier.shape = NA) + scale_y_continuous(limits = quantile(period_lengths$length, c(0.1, 0.9))) ggsave(paste("/home/pwm4/Desktop/Visualizations/", file_name, '.svg', sep=''), scale=2, width=9, height=4) } ## Cycles function() { nrem_cycles.s <- copy(nrem_cycles) nrem_cycles.s[,length:=length*epoch_length*60] # p <- ggplot(nrem_cycles.s, aes(factor(cycle_number), length, color=method)) # p + geom_boxplot() cycle_counts <- nrem_cycles[,list(count=.N),by='subject_code,sleep_wake_period,method'] # p <- ggplot(cycle_counts, aes(x=count, fill=method, color=method)) #p <- p + facet_grid(label ~ ., scales='free') #p <- p + scale_x_discrete() #p + geom_freqpoly(binwidth=1) plot.cycles(nrem_cycles.s, cycle_counts, subjects, 'all') plot.cycles(nrem_cycles.s, cycle_counts, old_s, 'older') plot.cycles(nrem_cycles.s, cycle_counts, young_s, 'younger') plot.cycles(nrem_cycles.s, cycle_counts, csr_s, 'csr') plot.cycles(nrem_cycles.s, cycle_counts, control_s, 'control') } plot.cycles <- function(nrem_cycles, cycle_counts, subject_group, label, by_cycle_count = FALSE) { p <- ggplot(nrem_cycles[subject_code %in% subject_group$subject_code], aes(factor(cycle_number), length, color=method)) p <- p + scale_fill_manual(values=cbbPalette) + scale_colour_manual(values=cbbPalette) p <- p + ggtitle(paste("Distribution of Lengths of NREM Cycles by Method", label, sep="\n")) + ylab("Length (minutes)") + xlab("Cycle Number") p <- p + geom_boxplot(outlier.shape = NA) + scale_y_continuous(limits = quantile(nrem_cycles$length, c(0.1, 0.9))) ggsave(plot = p, filename=paste("/home/pwm4/Desktop/Visualizations/cycle_length_", label, '.svg', sep=''), scale=2, width=9, height=4) cycle_counts <- nrem_cycles[,list(count=.N),by='subject_code,sleep_wake_period,method'] p <- ggplot(cycle_counts[subject_code %in% subject_group$subject_code], aes(x=count, fill=method, color=method)) p <- p + scale_fill_manual(values=cbbPalette) + scale_colour_manual(values=cbbPalette) p <- p + geom_freqpoly(binwidth=1, origin=-.5) p <- p + ggtitle(paste("Number of NREM cycles per Sleep Episode", label, sep="\n")) + ylab("Number of Sleep Episodes") + xlab("Number of NREM Cycles") p <- p + scale_x_continuous(breaks=seq(from=0, to=14), limits=c(0,14)) ggsave(plot = p, filename=paste("/home/pwm4/Desktop/Visualizations/cycle_counts_", label, '.svg', sep=''), scale=2, width=9, height=4) } tmp <- function(lim) { seq(from=lim[1], to=lim[2], by=1) } #periods function(){ wd <- periods[subject_code=="3335GX" & sleep_wake_period==2] tst <- wd[method=='changepoint'] # Cleaning: ## No sleep periods clean.periods <- periods[sleep_wake_period>0] ## Strip wake at beginning and end of sleep periods clean.periods <- clean.periods[,strip_wake(.SD),by='subject_code,sleep_wake_period'] psts <- clean.periods[,list(count=length(length)),by='subject_code,sleep_wake_period,method,label'] psts[, mean(NREM_count), by='method'] plot <- ggplot(psts, aes(method, count)) plot <- plot + facet_wrap(~ label) plot + geom_boxplot() plot <- ggplot(psts, aes(x=count)) plot <- plot + facet_grid(method ~ label) plot <- plot + geom_histogram() plot #clean.periods[,table(label,method), by='subject_code,sleep_wake_period'] #summary(table(clean.periods$method,clean.periods$label,clean.periods$subject_code,clean.periods$sleep_wake_period)) } ## Stats for number of periods period_stats <- function(labels) { t <- table(labels) list(NREM_count=t[names(t)=='NREM'], REM_count=t[names(t)=='REM'],WAKE_count=t[names(t)=='WAKE'], total=length(labels)) } ## Strips start and end wake off strip_wake <- function(dt) { sleep_onset <- min(match(c("NREM", "REM"), dt$label, nomatch=1L)) sleep_end <- (length(dt$label) - min(match(c("NREM", "REM"), rev(dt$label), nomatch=1L))) + 1L dt[sleep_onset:sleep_end] }
f135f5c8274f155d46ea09996b5156dde1a529ea
5dcb6a2aa0b0ded3f265140c7c213c369289aa7f
/R/gradient_factory.R
42381502fe2e6696cc52eaf1dc89cefadaba669b
[ "MIT" ]
permissive
leeper/margins
f8086ca2abaf8e78d3d79244c6e7777ac1d1a2a1
bd374239f5da0a92e8e27d093785850933fdfa9e
refs/heads/main
2021-07-14T12:00:50.926131
2021-01-21T22:54:28
2021-01-21T22:54:28
25,176,098
269
56
NOASSERTION
2021-04-08T00:49:03
2014-10-13T20:21:42
R
UTF-8
R
false
false
2,100
r
gradient_factory.R
# a factory function that returns a function to give the gradient (as a vector) ## used as first argument to jacobian() gradient_factory <- function(data, model, variables = NULL, type = "response", weights = NULL, eps = 1e-7, varslist = NULL, ...) { UseMethod("gradient_factory", model) } gradient_factory.default <- function(data, model, variables = NULL, type = "response", weights = NULL, eps = 1e-7, varslist = NULL, ...) { # identify classes of terms in `model` if (is.null(varslist)) { varslist <- find_terms_in_model(model, variables = variables) } # factory function to return marginal effects holding data constant but varying coefficients FUN <- function(coefs, weights = NULL) { model <- reset_coefs(model, coefs) if (is.null(weights)) { # build matrix of unit-specific marginal effects if (is.null(type)) { me_tmp <- marginal_effects(model = model, data = data, variables = variables, eps = eps, as.data.frame = FALSE, varslist = varslist, ...) } else { me_tmp <- marginal_effects(model = model, data = data, variables = variables, type = type, eps = eps, as.data.frame = FALSE, varslist = varslist, ...) } # apply colMeans to get average marginal effects means <- stats::setNames(.colMeans(me_tmp, nrow(me_tmp), ncol(me_tmp), na.rm = TRUE), colnames(me_tmp)) } else { # build matrix of unit-specific marginal effects if (is.null(type)) { me_tmp <- marginal_effects(model = model, data = data, variables = variables, eps = eps, as.data.frame = FALSE, varslist = varslist, ...) } else { me_tmp <- marginal_effects(model = model, data = data, variables = variables, type = type, eps = eps, as.data.frame = FALSE, varslist = varslist, ...) } # apply colMeans to get average marginal effects means <- apply(me_tmp, 2L, stats::weighted.mean, w = weights, na.rm = TRUE) } means } return(FUN) }
9f661e226748424bc0cba22bf188af82d93ae12e
33e51cf37c476e94808b9a96dbbeb72f76a208a7
/downloadData.R
2d8b8722258f166e0382622d0e3e51afb8d6f5a3
[]
no_license
humberto-ortiz/PR2017replicaton
e81b9e3fabdb18d6cf10542e535680d694b6e099
ab0e35e2fc91c7b375a5c15151281006db3e69b8
refs/heads/master
2021-01-23T02:41:10.050982
2017-03-24T02:17:37
2017-03-24T02:17:37
86,019,834
1
0
null
2017-03-24T02:43:11
2017-03-24T02:43:11
null
UTF-8
R
false
false
3,026
r
downloadData.R
library(Biobase) library(PharmacoGx) GDSC <- downloadPSet("GDSC") CCLE <- downloadPSet("CCLE") common <- intersectPSet( list( 'CCLE'=CCLE, 'GDSC'=GDSC ), intersectOn=c("cell.lines", "drugs"), strictIntersect=TRUE) rawToDataFrame <- function( dataset ){ rawSensData <- common[[dataset]]@sensitivity$raw names( dimnames(rawSensData) ) <- c("drugCell", "doseID", "doseData") spNames <- strsplit( dimnames( rawSensData )[[1]], "_" ) allCells <- unique( sapply( spNames, "[[", 1 ) ) allDrugs <- unique( sapply( spNames, "[[", 2 ) ) allData <- expand.grid( dimnames(rawSensData)[["doseID"]], allCells, allDrugs, stringsAsFactors=FALSE ) colnames(allData) <- c("doseID", "cellLine", "drug") concatName <- with( allData, paste( cellLine, drug, sep="_" ) ) allData$concentration <- NA allData$viability <- NA for( i in seq_len( nrow( allData ) ) ){ x <- dimnames(rawSensData)[[1]] %in% concatName[i] y <- dimnames(rawSensData)[[2]] %in% allData$doseID[i] if( any( x ) & any(y) ){ allData$viability[i] <- rawSensData[x,y,"Viability"] allData$concentration[i] <- rawSensData[x,y,"Dose"] } } allData <- na.omit(allData) allData$doseID <- as.factor( allData$doseID ) allData$cellLine <- as.factor( allData$cellLine ) allData$drug <- as.factor( allData$drug ) allData$concentration <- as.numeric( allData$concentration ) allData$viability <- as.numeric( allData$viability ) allData$study <- dataset allData } rawSensitivityDf<- rbind( rawToDataFrame("CCLE"), rawToDataFrame("GDSC") ) rawSensitivityDf <- rawSensitivityDf[,c("cellLine", "drug", "doseID", "concentration", "viability", "study")] sdList <- lapply( c("CCLE", "GDSC"), function(dataset){ summarizedData <- common[[dataset]]@sensitivity$profiles keepCols <- c("ic50_published", "auc_published") summarizedData <- summarizedData[,keepCols] spNames <- as.data.frame( do.call(rbind, strsplit( rownames( summarizedData ), "_" )) ) colnames( spNames ) <- c("cellLine", "drug") summarizedData <- cbind( spNames, summarizedData ) colnames(summarizedData) <- gsub("_published", "", colnames( summarizedData )) rownames( summarizedData ) <- NULL summarizedData } ) names(sdList) <- c("CCLE", "GDSC") library(plyr) joinedSumData <- join( sdList[[1]], sdList[[2]], by=c("cellLine", "drug") ) colnames(joinedSumData) <- c("cellLine", "drug", "ic50_CCLE", "auc_CCLE", "ic50_GDSC", "auc_GDSC") write.table( joinedSumData, sep=",", quote=FALSE, col.names=TRUE, row.names=FALSE, file="summarizedPharmacoData.csv" ) write.table( rawSensitivityDf, sep=",", quote=FALSE, col.names=TRUE, row.names=FALSE, file="rawPharmacoData.csv" ) #library(dplyr) #library(ggplot2) #ggplot( dplyr:::filter( joinedSumData, drug == "Sorafenib" ), aes(-log10(ic50_GDSC), -log10(ic50_CCLE)) ) + # geom_point() #dev.off()
58a69558f014573b6e00df4a2c89e7f0b25b80b6
3542aa74a2aa1b8bb1f501f53dc05cf1ea7323ca
/plot3.R
522e77945e829f47fed1b5f0be5d2e38ed546a17
[]
no_license
rrnisha/ExData_Plotting1
723895e682c5739683565213fd3bd20d63cecf3c
df5b5f2f048db9e9ce820e11588069b505f1fcd3
refs/heads/master
2020-12-25T07:06:25.509570
2014-07-13T13:49:33
2014-07-13T13:49:33
null
0
0
null
null
null
null
UTF-8
R
false
false
527
r
plot3.R
# Plot Sub_metering_1,2,3 for Feb 01, 02 source("prepData.R") doPlot3 <- function() { data <- prepData() png(filename="plot3.png", width=480, height=480) plot(data$DateTime, data$Sub_metering_1, type="l", xlab="", ylab="Energy sub metering") lines(data$DateTime, data$Sub_metering_2, col="red") lines(data$DateTime, data$Sub_metering_3, col="blue") cols = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3") legend("topright", lty=1, lwd=1, col=c("black","blue","red"), legend=cols) dev.off() } doPlot3()
2a23d9089de76fb259174355810fff52c76445ed
c459dd32d88158cb064c3af2bc2ea8c7ab77c667
/clonality/calculate_ccf.20191031.v1.R
ef3e8e21e0d95338a20d82fce9ecf59fba213a50
[]
no_license
ding-lab/ccRCC_snRNA_analysis
d06b8af60717779671debe3632cad744467a9668
ac852b3209d2479a199aa96eed3096db0b5c66f4
refs/heads/master
2023-06-21T15:57:54.088257
2023-06-09T20:41:56
2023-06-09T20:41:56
203,657,413
6
3
null
null
null
null
UTF-8
R
false
false
7,126
r
calculate_ccf.20191031.v1.R
# Yige Wu @WashU Oct 2019 ## for calculating cancer cell fraction of CNAs and Mutations # source ------------------------------------------------------------------ setwd(dir = "~/Box/") source("./Ding_Lab/Projects_Current/RCC/ccRCC_snRNA/ccRCC_snRNA_analysis/ccRCC_snRNA_shared.R") # set run id ---------------------------------------------------------- version_tmp <- 1 run_id <- paste0(format(Sys.Date(), "%Y%m%d") , ".v", version_tmp) # set output directory ---------------------------------------------------- dir_out <- paste0(makeOutDir(), run_id, "/") dir.create(dir_out) # input VAF table --------------------------------------------------------- vaf_tab <- fread("./Ding_Lab/Projects_Current/RCC/ccRCC_snRNA/Resources/Analysis_Results/mutation/generate_bulk_mutation_table/20191024.v1/snRNA_ccRCC_Mutation_VAF_Table.20191024.v1.csv", data.table = F) # load meta data ---------------------------------------------------------- meta_tab <- fread(input = "./Ding_Lab/Projects_Current/RCC/ccRCC_snRNA/Resources/Analysis_Results/sample_info/make_meta_data/meta_data.20190924.v1.tsv", data.table = F) # add snRNA_aliquot_id to vaf table --------------------------------------- vaf_tab <- merge(vaf_tab, meta_tab, by.x = c("Aliquot"), by.y = c("Specimen.ID.bulk"), all.x = T) # input CNA frequency by gene --------------------------------------------- # gene_cna_state_tab <- # set samples to process ---------------------------------------------------------- snRNA_aliquot_ids <- c("CPT0019130004", "CPT0001260013", "CPT0086350004", "CPT0010110013", "CPT0001180011", "CPT0020120013", "CPT0001220012", "CPT0014450005") # using VHL mutation or BAP1 or SETD2 or PBRM1 mutation to estimate tumor purity by WES sample ------------------------------------- ccf_tab <- NULL for (snRNA_aliquot_id_tmp in snRNA_aliquot_ids) { # snRNA_aliquot_id_tmp <- "CPT0001260013" ## choose which mutated gene will be used for tumpor purity estiamte ## choose the highest VAF among VHL, PBRM1, SETD2 and BAP1 vaf_tmp <- vaf_tab %>% filter(Specimen.ID.snRNA == snRNA_aliquot_id_tmp) %>% select(VHL, PBRM1, BAP1, SETD2) gene0 <- colnames(vaf_tmp)[which.max(vaf_tmp)] gene0 vaf0 <- max(vaf_tmp, na.rm = T) vaf0 # get the cancer cell fraction of different copy number for the gene (for example VHL) -------- tumor_perc_0x <- as.numeric(gene_cna_state_tab$perc_cna_in_tumor_cell[gene_cna_state_tab$gene_symbol == gene0 & gene_cna_state_tab$cna_state == 0 & gene_cna_state_tab$snRNA_aliquot_id == snRNA_aliquot_id_tmp]) tumor_perc_1x <- as.numeric(gene_cna_state_tab$perc_cna_in_tumor_cell[gene_cna_state_tab$gene_symbol == gene0 & gene_cna_state_tab$cna_state == 0.5 & gene_cna_state_tab$snRNA_aliquot_id == snRNA_aliquot_id_tmp]) tumor_perc_3x <- as.numeric(gene_cna_state_tab$perc_cna_in_tumor_cell[gene_cna_state_tab$gene_symbol == gene0 & gene_cna_state_tab$cna_state == 1.5 & gene_cna_state_tab$snRNA_aliquot_id == snRNA_aliquot_id_tmp]) tumor_perc_4x <- as.numeric(gene_cna_state_tab$perc_cna_in_tumor_cell[gene_cna_state_tab$gene_symbol == gene0 & gene_cna_state_tab$cna_state == 2 & gene_cna_state_tab$snRNA_aliquot_id == snRNA_aliquot_id_tmp]) tumor_perc_over_4x <- as.numeric(gene_cna_state_tab$perc_cna_in_tumor_cell[gene_cna_state_tab$gene_symbol == gene0 & gene_cna_state_tab$cna_state == 3 & gene_cna_state_tab$snRNA_aliquot_id == snRNA_aliquot_id_tmp]) if (length(tumor_perc_over_4x) != 0) { tumor_perc_2x <- (1-tumor_perc_0x-tumor_perc_1x-tumor_perc_3x-tumor_perc_4x-tumor_perc_over_4x) } else { tumor_perc_2x <- (1-tumor_perc_0x-tumor_perc_1x-tumor_perc_3x-tumor_perc_4x) } a0 <- (1-tumor_perc_0x) b0 <- (1*tumor_perc_1x + 2*tumor_perc_2x + 3*tumor_perc_3x + 4*tumor_perc_4x) ccf0_to_test <- seq(from = 1, to = 0, by = -0.05) ## create a vector to hold the estimated tumor purity tumor_puritys <- NULL ## create a matrix to hold the CCF for the rest of the mutated gene ccf_mat <- matrix(data = 0, nrow = length(ccf0_to_test), ncol = length(SMGs[["CCRCC"]])) colnames(ccf_mat) <- SMGs[["CCRCC"]] for (i in 1:length(ccf0_to_test)) { ccf0 <- ccf0_to_test[i] # calculate purity according to the assumed ccf for the gene (for exapmle VHL-------------------------------------------------------- p <- 2/((a0*ccf0)/vaf0 + 2 - b0) tumor_puritys <- c(tumor_puritys, p) genes2test <- vaf_tab %>% filter(Specimen.ID.snRNA == snRNA_aliquot_id_tmp) genes2test <- colnames(genes2test[1, !is.na(genes2test)]) genes2test <- intersect(genes2test, SMGs[["CCRCC"]]) for (gene_tmp in genes2test) { tumor_perc_0x <- as.numeric(gene_cna_state_tab$perc_cna_in_tumor_cell[gene_cna_state_tab$gene_symbol == gene_tmp & gene_cna_state_tab$cna_state == 0 & gene_cna_state_tab$snRNA_aliquot_id == snRNA_aliquot_id_tmp]) tumor_perc_1x <- as.numeric(gene_cna_state_tab$perc_cna_in_tumor_cell[gene_cna_state_tab$gene_symbol == gene_tmp & gene_cna_state_tab$cna_state == 0.5 & gene_cna_state_tab$snRNA_aliquot_id == snRNA_aliquot_id_tmp]) tumor_perc_3x <- as.numeric(gene_cna_state_tab$perc_cna_in_tumor_cell[gene_cna_state_tab$gene_symbol == gene_tmp & gene_cna_state_tab$cna_state == 1.5 & gene_cna_state_tab$snRNA_aliquot_id == snRNA_aliquot_id_tmp]) tumor_perc_4x <- as.numeric(gene_cna_state_tab$perc_cna_in_tumor_cell[gene_cna_state_tab$gene_symbol == gene_tmp & gene_cna_state_tab$cna_state == 2 & gene_cna_state_tab$snRNA_aliquot_id == snRNA_aliquot_id_tmp]) tumor_perc_over_4x <- as.numeric(gene_cna_state_tab$perc_cna_in_tumor_cell[gene_cna_state_tab$gene_symbol == gene_tmp & gene_cna_state_tab$cna_state == 3 & gene_cna_state_tab$snRNA_aliquot_id == snRNA_aliquot_id_tmp]) if (length(tumor_perc_over_4x) != 0) { tumor_perc_2x <- (1-tumor_perc_0x-tumor_perc_1x-tumor_perc_3x-tumor_perc_4x-tumor_perc_over_4x) } else { tumor_perc_2x <- (1-tumor_perc_0x-tumor_perc_1x-tumor_perc_3x-tumor_perc_4x) } a <- (1-tumor_perc_0x) if (gene_tmp != "KDM5C") { b <- (1*tumor_perc_1x + 2*tumor_perc_2x + 3*tumor_perc_3x + 4*tumor_perc_4x) } else { b <- (1*tumor_perc_2x + 1.5*tumor_perc_3x + 2*tumor_perc_4x) } v <- as.numeric(vaf_tab %>% filter(Specimen.ID.snRNA == snRNA_aliquot_id_tmp) %>% select(gene_tmp)) ccf <- (v*(b*p+2-2*p))/(p*a) ccf_mat[i,gene_tmp] <- ccf } } ccf_tab_tmp <- data.frame(snRNA_aliquot_id = snRNA_aliquot_id_tmp, gene0 = gene2use, ccf0 = ccf0_to_test, tumor_purity = tumor_puritys, ccf_mat) ccf_tab <- rbind(ccf_tab_tmp, ccf_tab) } write.table(x = ccf_tab, file = paste0(dir_out, "CCF_CNmut1.", run_id, ".tsv"), quote = F, row.names = F, col.names = T, sep = "\t") # estimate CCF for somatic mutations using estimated tumor purity -------------------------------------- # input CNA CCF by chromosome arm results --------------------------- # merge Mutation CCF with CNA CCF ----------------------------------------- # write out results -------------------------------------------------------
a9cc8fbe50784db132049b88c711f84de7f75fd2
f53d33f6a26d33d6f15632841bf805e5074cef99
/R/check_empty_elements.R
362d7c120f0635e957108028c5cd5213b97b4b4b
[]
no_license
levisc8/Fun_Phylo_Package
6add7e6cd4e3cc0f1dfd21e669f0a55c143ee02a
224521f794d35297c1f3a0f835a6cb20f5e9c6fb
refs/heads/master
2021-06-10T04:56:43.768628
2020-06-01T12:07:58
2020-06-01T12:07:58
99,753,085
1
0
null
null
null
null
UTF-8
R
false
false
301
r
check_empty_elements.R
check_empty_elements <- function(...){ rmlist <- NULL iniList <- list(...) for(i in 1:length(iniList)){ if(is.null(iniList[[i]])){ rmlist <- c(rmlist, i) } } if(!is.null(rmlist)){ outList <- iniList[-c(rmlist)] } else { outList <- iniList } return(outList) }
ff64c2961cf7818d1aefbbd8c0ba1ea39879077d
fddcbf7ff2dad9d8d781da1dd9205a3dc22bf772
/server.R
1cb256bd3e621df760961264644b3bd425636a71
[]
no_license
Khominets/lab_6
1733530972dcb4faf066ca1bf8e32e536de59ae0
dc5129be28d4e668a66c9b273ef8d7f71b794aec
refs/heads/master
2021-01-11T10:47:23.895505
2016-12-11T20:04:24
2016-12-11T20:04:24
76,195,721
0
0
null
null
null
null
UTF-8
R
false
false
549
r
server.R
library(shiny) shinyServer( function(input, output) { output$func<-renderText({ input$start if (input$num1 >= 3) { paste0('Функція: ', '(' ,input$num1, '/' , '4' , ')' , '*', input$num2, '^', '2','*','tan','(' ,'pi', '/', input$num1, ')' ) } else if (input$num1 < 3 ) { paste0('Помилка') } }) output$dy<- renderText({ paste0('Площа правильного ',input$num1,'-кутника = ', ((input$num1/4)*input$num2^2*tan(pi/input$num1))) }) })
3ab1a59c25bbd903b59fa065bdfd3d59d973fa84
cea51b60f43efac0959bb6e52749f608e1eddd13
/nlsralt/R/nlxbs.R
c59edc8fa2417647c1bd33df20b58b1c0e4c8cb1
[]
no_license
ArkaB-DS/GSOC21-improveNLS
6bd711bca3ad1deac5aff3128cfc02e0237915a9
f33839f8ceef78591ee296c6e515cd52339bb2b0
refs/heads/master
2023-07-16T21:07:33.900548
2021-08-22T05:41:26
2021-08-22T05:41:26
398,542,725
3
0
null
null
null
null
UTF-8
R
false
false
5,498
r
nlxbs.R
nlxbs <- function(formula, start, trace = FALSE, data=NULL, subset=NULL, lower = -Inf, upper = Inf, masked = NULL, weights=NULL, control=list()) { # A simplified and hopefully robust alternative to finding # the nonlinear least squares minimizer that causes # 'formula' to give a minimal residual sum of squares. # # Modified 2021-6-26 to only used Identity matrix Marquardt stabilization # # nlxb is particularly intended to allow for the # resolution of very ill-conditioned or else near # zero-residual problems for which the regular nls() # function is ill-suited. # # J C Nash 2014-7-16 nashjc _at_ uottawa.ca # # formula looks like 'y~b1/(1+b2*exp(-b3*T))' start MUST be # a vector where all the elements are named: e.g., # start=c(b1=200, b2=50, b3=0.3) trace -- TRUE for console # output data is a data frame containing data for variables # used in the formula that are NOT the parameters. This # data may also be defined in the parent frame i.e., # 'global' to this function lower is a vector of lower # bounds upper is a vector of upper bounds masked is a # character vector of names of parameters that are fixed. # control is a list of control parameters. These are: ... # # This variant uses a qr solution without forming the sum # of squares and cross products t(J)%*%J # # ?? and put in the weights # ######### get data from data frame if exists # ######### print(str(data)) # if (!is.null(data)) { # for (dfn in names(data)) { # cmd <- paste(dfn, "<-data$", dfn, "") # eval(parse(text = cmd)) # } # } else stop("'data' must be a list or an environment") # ensure params in vector pnames <- names(start) start <- as.numeric(start) # ensure we convert (e.g., if matrix) names(start) <- pnames ## as.numeric strips names, so this is needed # bounds npar <- length(start) # number of parameters if (length(lower) == 1) lower <- rep(lower, npar) # expand to full dimension if (length(upper) == 1) upper <- rep(upper, npar) # more tests on bounds if (length(lower) != npar) stop("Wrong length: lower") if (length(upper) != npar) stop("Wrong length: upper") if (any(start < lower) || any(start > upper)) stop("Infeasible start") if (trace) { cat("formula: ") print(formula) cat("lower:") print(lower) cat("upper:") print(upper) } # controls ctrl <- list(watch = FALSE, phi = 1, lamda = 1e-04, offset = 100, laminc = 10, lamdec = 4, femax = 10000, jemax = 5000, rofftest = TRUE, smallsstest = TRUE) ## maxlamda <- 1e+60) ## dropped 130709 ??why? ## epstol <- (.Machine$double.eps) * ctrl$offset # ??161018 - not used elsewhere ncontrol <- names(control) nctrl <- names(ctrl) for (onename in ncontrol) { if (!(onename %in% nctrl)) { if (trace) cat("control ", onename, " is not in default set\n") stop(onename," is not a control for nlxb") } ctrl[onename] <- control[onename] } if (trace) print(ctrl) phiroot <- sqrt(ctrl$phi) # Note spelling of lamda -- a throwback to Ag Can 1974 and way to see if folk are copying code. # First get all the variable names: # vn <- all.vars(parse(text = formula)) # ??? need to fix -- why?, what is wrong vn <- all.vars(formula) # Then see which ones are parameters (get their positions # in the set xx pnum <- start # may simplify later?? pnames <- names(pnum) bdmsk <- rep(1, npar) # set all params free for now # ?? put in lower==upper mask defn maskidx <- union(which(lower==upper), which(pnames %in% masked)) # use both methods for masks # NOTE: %in% not == or order gives trouble if (length(maskidx) > 0 && trace) { cat("The following parameters are masked:") print(pnames[maskidx]) } bdmsk[maskidx] <- 0 # fixed parameters if (trace) { # diagnostic printout cat("Finished masks check\n") parpos <- match(pnames, vn) # ?? check this is right?? datvar <- vn[-parpos] # NOT the parameters cat("datvar:") print(datvar) for (i in 1:length(datvar)) { dvn <- datvar[[i]] cat("Data variable ", dvn, ":") if (is.null(data)) { print(eval(parse(text = dvn))) } else { print(with(data, eval(parse(text = dvn)))) } } } trjfn<-model2rjfun(formula, pnum, data=data) if (trace) { cat("trjfn:\n") print(trjfn) } ## Call the nlfb function here ## ?? problem is getting the data into the tresfn and tjacfn?? How? ## which gets data into the functions resfb <- nlfbs(start=pnum, resfn=trjfn, jacfn=trjfn, trace=trace, data=data, subset, lower=lower, upper=upper, maskidx=maskidx, weights=weights, control=ctrl) ## control=ctrl, ...) resfb$formula <- formula # 190805 to add formula # ?? should there be any ... arguments pnum <- as.vector(resfb$coefficients) names(pnum) <- pnames # Make sure names re-attached. ??Is this needed?? ## resfb$coefficients <- pnum ## commented 190821 result <- resfb ## attr(result, "pkgname") <- "nlsr" class(result) <- "nlsr" ## CAUSES ERRORS ?? Does it?? 190821 result }
47512cf818fc46625ec542d6e9d4ad4c5ffa0a1b
cbc4f1708ef51093fcf0bebe5c2a3ee8403d0f9a
/human_motif_analysis/parsing_GOrilla.R
488f2d65e5db56e6d9980249a7d0fa12e190725a
[]
no_license
AndyFeinberg/methyl_entropy
540cf6d97d0dcaf3f3cc3799e7bacac5f27ef1b3
0da2e12cf2226cd51a09365981352805b49fdee6
refs/heads/main
2023-04-18T23:45:18.571277
2023-01-05T04:59:10
2023-01-05T04:59:10
584,472,340
1
1
null
null
null
null
UTF-8
R
false
false
941
r
parsing_GOrilla.R
rm(list=ls()) library(xlsx) GO_in=as.data.table(read.xlsx('../downstream/output/graphs_tables/regulatory_non_regulatory_GOrilla.xlsx',1)) for(i in 1:nrow(GO_in)){ if(!is.na(GO_in$Description[i])){GO_term=GO_in$Description[i]} else{GO_in$Description[i]=GO_term} } GO_in=GO_in[,list(P.value=max(P.value,na.rm=T), FDR.q.value=max(FDR.q.value,na.rm=T), Enrichment..N..B..n..b.=max(as.numeric(gsub('\\(.*','',Enrichment..N..B..n..b.)),na.rm=T), Genes=gsub('\\[-] Hide genes,','',paste(unique(gsub(' - .*','',Genes)),collapse =','))),by=Description] top50_gene=read.xlsx2('../downstream/output/human_analysis/NME_motif/NME_regulaotry_Ken.xlsx',1,startRow = 2) GO_in$Genes=unlist(lapply(strsplit(GO_in$Genes,','),function(x) paste(x[x%in%top50_gene[1:50,]$Transcription.facotrs],collapse = ','))) write.csv(GO_in,'../downstream/output/graphs_tables/regulatory_non_regulatory_GOrilla_processed.csv')
415f6d537d82bde63ba2ab2d874b43eff3ec828b
0b5910a5e63a5d6e5fb49ea610014ef8688a0179
/man/dGAselID.Rd
960dfcf0c3ab6135b293b26a29daf7bca4ff201e
[]
no_license
cran/dGAselID
2b8d7c5cda432dc5e24f08998035cc979ae5e03f
3e7338b2c19a8f0a3af749a20716cd6bdc395d8b
refs/heads/master
2020-07-02T18:59:35.171136
2017-07-10T04:02:55
2017-07-10T04:02:55
74,287,862
1
0
null
null
null
null
UTF-8
R
false
true
3,827
rd
dGAselID.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dGAselID.R \name{dGAselID} \alias{dGAselID} \title{dGAselID} \usage{ dGAselID(x, response, method = knn.cvI(k = 3, l = 2), trainTest = "LOG", startGenes, populationSize, iterations, noChr = 22, elitism = NA, ID = "ID1", pMutationChance = 0, nSMutationChance = 0, fSMutationChance = 0, lSDeletionChance = 0, wChrDeletionChance = 0, transposonChance = 0, randomAssortment = TRUE, embryonicSelection = NA, EveryGeneInInitialPopulation = TRUE, nnetSize = NA, nnetDecay = NA, rdaAlpha = NA, rdaDelta = NA, ...) } \arguments{ \item{x}{Dataset in ExpressionSet format.} \item{response}{Response variable} \item{method}{Supervised classifier for fitness evaluation. Most of the supervised classifiers in MLInterfaces are acceptable. The default is knn.cvI(k=3, l=2).} \item{trainTest}{Cross-validation method. The default is "LOG".} \item{startGenes}{Genes in the genotypes at initialization.} \item{populationSize}{Number of genotypes in initial population.} \item{iterations}{Number of iterations.} \item{noChr}{Number of chromosomes. The default value is 22.} \item{elitism}{Elite population in percentages.} \item{ID}{Dominance. The default value is "ID1". Use "ID2" for Incomplete Dominance.} \item{pMutationChance}{Chance for a Point Mutation to occur. The default value is 0.} \item{nSMutationChance}{Chance for a Non-sense Mutation to occur. The default value is 0.} \item{fSMutationChance}{Chance for a Frameshift Mutation to occur. The default value is 0.} \item{lSDeletionChance}{Chance for a Large Segment Deletion to occur. The default value is 0.} \item{wChrDeletionChance}{Chance for a Whole Chromosome Deletion to occur. The default value is 0.} \item{transposonChance}{Chance for a Transposon Mutation to occur. The default value is 0.} \item{randomAssortment}{Random Assortment of Chromosomes for recombinations. The default value is TRUE.} \item{embryonicSelection}{Remove chromosomes with fitness < specified value. The default value is NA.} \item{EveryGeneInInitialPopulation}{Request for every gene to be present in the initial population. The default value is TRUE.} \item{nnetSize}{for nnetI. The default value is NA.} \item{nnetDecay}{for nnetI. The default value is NA.} \item{rdaAlpha}{for rdaI. The default value is NA.} \item{rdaDelta}{for rdaI. The default value is NA.} \item{...}{Additional arguments.} } \value{ The output is a list containing 5 named vectors, records of the evolution: \item{DGenes}{The occurrences in selected genotypes for every gene,} \item{dGenes}{The occurrences in discarded genotypes for every gene,} \item{MaximumAccuracy}{Maximum accuracy in every generation,} \item{MeanAccuracy}{Average accuracy in every generation,} \item{MinAccuracy}{Minimum accuracy in every generation,} \item{BestIndividuals}{Best individual in every generation.} } \description{ Initializes and starts the search with the genetic algorithm. } \examples{ \dontrun{ library(genefilter) library(ALL) data(ALL) bALL = ALL[, substr(ALL$BT,1,1) == "B"] smallALL = bALL[, bALL$mol.biol \%in\% c("BCR/ABL", "NEG")] smallALL$mol.biol = factor(smallALL$mol.biol) smallALL$BT = factor(smallALL$BT) f1 <- pOverA(0.25, log2(100)) f2 <- function(x) (IQR(x) > 0.5) f3 <- ttest(smallALL$mol.biol, p=0.1) ff <- filterfun(f1, f2, f3) selectedsmallALL <- genefilter(exprs(smallALL), ff) smallALL = smallALL[selectedsmallALL, ] rm(f1) rm(f2) rm(f3) rm(ff) rm(bALL) sum(selectedsmallALL) set.seed(149) res<-dGAselID(smallALL, "mol.biol", trainTest=1:79, startGenes=12, populationSize=200, iterations=150, noChr=5, pMutationChance=0.0075, elitism=4) } }
09f932618afac04328758c9dd235e3ab570ae1d6
695b88a36f548e410d8a4181ed7c6f433c7515a1
/R/lstrends.R
b6f19dea19cca06928ec6c0401b7c358d8c51946
[]
no_license
jonathon-love/lsmeans
16054e0a830df482fd6aa41b5a461535afb8d4bb
c6e91712705647bbd9aa2fa37e65929907fecca9
refs/heads/master
2021-01-12T00:31:38.801483
2017-08-02T11:31:32
2017-08-02T11:31:32
78,736,500
0
0
null
null
null
null
UTF-8
R
false
false
4,556
r
lstrends.R
############################################################################## # Copyright (c) 2012-2016 Russell V. Lenth # # # # This file is part of the lsmeans package for R (*lsmeans*) # # # # *lsmeans* is free software: you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation, either version 2 of the License, or # # (at your option) any later version. # # # # *lsmeans* is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with R and *lsmeans*. If not, see # # <https://www.r-project.org/Licenses/> and/or # # <http://www.gnu.org/licenses/>. # ############################################################################## ### Code for lstrends ### lstrends function lstrends = function(model, specs, var, delta.var=.01*rng, data, transform = c("none", "response"), ...) { estName = paste(var, "trend", sep=".") # Do now as I may replace var later if (missing(data)) { data = try(recover.data (model, data = NULL)) if (inherits(data, "try-error")) stop("Possible remedy: Supply the data used in the 'data' argument") } else # attach needed attributes to given data data = recover.data(model, data = data) x = data[[var]] fcn = NULL # differential if (is.null(x)) { fcn = var var = .all.vars(as.formula(paste("~",var))) if (length(var) > 1) stop("Can only support a function of one variable") else { x = data[[var]] if (is.null(x)) stop("Variable '", var, "' is not in the dataset") } } rng = diff(range(x)) if (delta.var == 0) stop("Provide a nonzero value of 'delta.var'") RG = orig.rg = ref.grid(model, data = data, ...) grid = RG@grid if (!is.null(mr <- RG@roles$multresp)) { # use the grid value only for the 1st mult resp (no dupes) if (length(mr) > 0) grid = grid[grid[[mr]] == RG@levels[[mr]][1], ] } grid[[var]] = grid[[var]] + delta.var basis = lsm.basis(model, attr(data, "terms"), RG@roles$xlev, grid, ...) if (is.null(fcn)) newlf = (basis$X - RG@linfct) / delta.var else { y0 = with(RG@grid, eval(parse(text = fcn))) yh = with(grid, eval(parse(text = fcn))) diffl = (yh - y0) if (any(diffl == 0)) warning("Some differentials are zero") newlf = (basis$X - RG@linfct) / diffl } transform = match.arg(transform) # Now replace linfct w/ difference quotient RG@linfct = newlf RG@roles$trend = var if(hasName(RG@misc, "tran")) { tran = RG@misc$tran if (is.list(tran)) tran = tran$name if (transform == "response") { prd = .est.se.df(orig.rg, do.se = FALSE) lnk = attr(prd, "link") deriv = lnk$mu.eta(prd[[1]]) RG@linfct = diag(deriv) %*% RG@linfct RG@misc$initMesg = paste("Trends are obtained after back-transforming from the", tran, "scale") } else RG@misc$initMesg = paste("Trends are based on the", tran, "(transformed) scale") } RG@misc$tran = RG@misc$tran.mult = NULL RG@misc$estName = estName RG@misc$methDesc = "lstrends" .save.ref.grid(RG) # save in .Last.ref.grid, if enabled # args for lsmeans calls args = list(object=RG, specs=specs, ...) args$at = args$cov.reduce = args$mult.levs = args$vcov. = args$data = args$trend = NULL do.call("lsmeans", args) }
881c0876f0635baadc452e8ddc6ab3d6721135ae
4344aa4529953e5261e834af33fdf17d229cc844
/input/gcamdata/man/module_energy_elec_bio_low_xml.Rd
dbc11e5364215292ade54df501d76114f5a015cd
[ "ECL-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
JGCRI/gcam-core
a20c01106fd40847ed0a803969633861795c00b7
912f1b00086be6c18224e2777f1b4bf1c8a1dc5d
refs/heads/master
2023-08-07T18:28:19.251044
2023-06-05T20:22:04
2023-06-05T20:22:04
50,672,978
238
145
NOASSERTION
2023-07-31T16:39:21
2016-01-29T15:57:28
R
UTF-8
R
false
true
749
rd
module_energy_elec_bio_low_xml.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/zenergy_xml_elec_bio_low.R \name{module_energy_elec_bio_low_xml} \alias{module_energy_elec_bio_low_xml} \title{module_energy_elec_bio_low_xml} \usage{ module_energy_elec_bio_low_xml(command, ...) } \arguments{ \item{command}{API command to execute} \item{...}{other optional parameters, depending on command} } \value{ Depends on \code{command}: either a vector of required inputs, a vector of output names, or (if \code{command} is "MAKE") all the generated outputs: \code{elec_bio_low.xml}. The corresponding file in the original data system was \code{batch_elec_bio_low_xml.R} (energy XML). } \description{ Construct XML data structure for \code{elec_bio_low.xml}. }
d90fc1db16cc666eb7abd019469c6a0abb3d6ef7
f99fa98d3f573726bcc18c9d87e257f79814e697
/basic_mapping_demo.R
9d9c5de354595336387919a90f7aff5a7a6b779a
[]
no_license
cjbattey/Rseminar_GIS
c938d21bd643c4b1672330abd73a3b5ce6da568e
f919feff759a255f31becf225df3de1c539b1b1e
refs/heads/master
2021-01-10T13:08:05.874891
2015-11-03T03:45:17
2015-11-03T03:45:17
45,404,659
0
2
null
null
null
null
UTF-8
R
false
false
4,863
r
basic_mapping_demo.R
########################### #### FUN WITH MAPS!!!! #### ########################### ### what you'll need getwd() install.packages('ggplot2') install.packages('ggmap') install.packages('mapdata') install.packages('maps') library(ggplot2) library(ggmap) library(mapdata) library(maps) ################################ #### making basic maps in R #### ################################ map("worldHires", "Mexico") #pick your basemap, define your country map("worldHires", "Mexico", col="grey90", fill=TRUE) #example visual tweak map("worldHires", xlim=c(-130, -53), ylim=c(15,35)) #define by lat / long instead localities <- read.csv("PABU.csv") #format is a column "lat" and a column "long" with data in decimal degrees colnames(localities) <-c("num","lat","long","species") map("worldHires", "Mexico", col="grey90", fill=TRUE) points(localities$long, localities$lat, pch=19, col="red", cex=0.5) #plot localities data, choose aesthetic parameters ################################################## #### more of the same but better with ggplot2 #### ################################################## map <- map_data("world", "Mexico") #pick basemap -- higher res options available ggplot() + theme_bw() + geom_path(data=map, aes(x=long, y=lat, group=group)) + coord_map() #look at the basemap ggplot() + geom_point(data=localities, aes(x=long, y=lat)) #look at the points in space #### and together now! ggplot() + geom_path(data=map, aes(x=long, y=lat, group=group)) + geom_point(data=localities, aes(x=long, y=lat)) ggplot() + coord_map()+ #hold ratios / project constant geom_path(data=map, aes(x=long, y=lat, group=group)) + geom_point(data=localities, aes(x=long, y=lat)) #### add more graphical parameters ggplot() + coord_map()+ geom_path(data=map, aes(x=long, y=lat, group=group)) + geom_point(data=localities, aes(x=long, y=lat, col=species, size=num)) #color code points by species, scale by size ggplot() + coord_map()+ geom_path(data=map, aes(x=long, y=lat, group=group)) + geom_point(data=localities, aes(x=long, y=lat, col=species, size=num)) + scale_size_continuous(range = c(3,13)) #tweak acceptable range of point sizes ggplot() + coord_map()+ geom_path(data=map, aes(x=long, y=lat, group=group)) + geom_point(data=localities, aes(x=long, y=lat, col=species, size=num)) + scale_size_continuous(range = c(3,13)) + theme_bw() # remove greyscale background ggplot() + coord_map()+ geom_path(data=map, aes(x=long, y=lat, group=group)) + geom_point(data=localities, aes(x=long, y=lat, col=species, size=num)) + scale_size_continuous(range = c(3,13)) + theme_bw() + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) #remove background grid ggplot() + coord_map()+ geom_path(data=map, aes(x=long, y=lat, group=group)) + geom_point(data=localities, aes(x=long, y=lat, col=species, size=num)) + scale_size_continuous(range = c(3,13)) + theme_bw() + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + theme(legend.title = element_blank(),legend.text = element_text(face = "italic"), axis.title.x = element_blank(), axis.title.y = element_blank()) #remove labels #### a few other tricks ggplot() + coord_map()+ geom_path(data=map, aes(x=long, y=lat, group=group)) + #geom_point(data=localities, aes(x=long, y=lat, col=species, size=num)) + #scale_size_continuous(range = c(3,13)) + theme_bw() + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + theme(legend.title = element_blank(),legend.text = element_text(face = "italic"), axis.title.x = element_blank(), axis.title.y = element_blank()) + geom_bin2d(data=localities,aes(x=long,y=lat)) #"rasterize" your data (record density) ggplot() + coord_map()+ geom_path(data=map, aes(x=long, y=lat, group=group)) + #geom_point(data=localities, aes(x=long, y=lat, col=species, size=num)) + #scale_size_continuous(range = c(3,13)) + theme_bw() + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + theme(legend.title = element_blank(),legend.text = element_text(face = "italic"), axis.title.x = element_blank(), axis.title.y = element_blank()) + stat_summary2d(data=localities,aes(x=long,y=lat,z=num,fun="mean")) # visualize a summary statistic of it ggplot() + coord_map()+ geom_path(data=map, aes(x=long, y=lat, group=group)) + #geom_point(data=localities, aes(x=long, y=lat, col=species, size=num)) + #scale_size_continuous(range = c(3,13)) + theme_bw() + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + theme(legend.title = element_blank(),legend.text = element_text(face = "italic"), axis.title.x = element_blank(), axis.title.y = element_blank()) + stat_density2d(data=localities,aes(x=long,y=lat)) ### cool topographic overlay of density
1ee371af06457ee6ec3b2c79d8ee9351c9ea95a8
2da2406aff1f6318cba7453db555c7ed4d2ea0d3
/inst/snippet/balldrop-nls07-fig.R
2942ed5774ce72fd91830a3bc03ae63bce2a1069
[]
no_license
rpruim/fastR2
4efe9742f56fe7fcee0ede1c1ec1203abb312f34
d0fe0464ea6a6258b2414e4fcd59166eaf3103f8
refs/heads/main
2022-05-05T23:24:55.024994
2022-03-15T23:06:08
2022-03-15T23:06:08
3,821,177
11
8
null
null
null
null
UTF-8
R
false
false
206
r
balldrop-nls07-fig.R
plot(balldrop.nls) plot(balldrop.lm, w = 1) gf_qq( ~ resid(balldrop.nls)) gf_qq( ~ resid(balldrop.lm)) gf_point(resid(balldrop.nls) ~ f(BallDrop$height)) gf_point(resid(balldrop.lm) ~ g(BallDrop$height))
6a90027b2e6bbe46f28044a424cab0b5e3003c6e
da725622bc962b639e1eb6df535b433e4366bcc5
/shinyCredentialsAndEducation/ui.r
2d0484e38312cfb48b03e8520cfe13c199a48423
[]
no_license
bekahdevore/rKW
5649a24e803b88aa51a3e64020b232a23bd459fa
970dcf8dc93d4ec0e5e6a79552e27ddc0f850b91
refs/heads/master
2020-04-15T12:41:49.567456
2017-07-25T16:29:31
2017-07-25T16:29:31
63,880,311
0
1
null
null
null
null
UTF-8
R
false
false
1,122
r
ui.r
# This is the user-interface definition of a Shiny web application. # You can find out more about building applications with Shiny here: # # http://shiny.rstudio.com # library(shiny) library(dplyr) library(googleVis) credentialsData <- as.data.frame(read.csv("credentialsAndEducation.csv")) occupationsList <- as.character(unique(credentialsData$source)) shinyUI(fluidPage( # Application title titlePanel("Louisville MSA Credentials"), # Sidebar with a slider input for number of bins fluidRow( column(12, selectInput("credential", "Select a credential", choices = occupationsList)), fluidRow( column(4, (htmlOutput("credentials"))), column(4, offset = 4, h4("Occupations"), DT::dataTableOutput("credentialTable")) ) )))
5f2a1875c84ef11de8d9d20c6a614cfbf329c586
c2b9eb709f1e5bf19b83d0977b5f3ff2c89d255c
/R/utils-httr.R
d6a6fd95b0175dcd41071b950fbed8a5dd293c7f
[]
no_license
StevenMMortimer/rdynamicscrm
0a2d0b60ebb26bea741d94351f844d6b7b4babef
0077326f8f770eef582adaf12a4becb590ab426d
refs/heads/main
2021-06-02T10:16:23.849693
2019-07-08T15:09:08
2019-07-08T15:09:08
144,392,345
0
0
null
null
null
null
UTF-8
R
false
false
3,656
r
utils-httr.R
#' Function to catch and print HTTP errors #' #' @importFrom httr content http_error status_code POST add_headers #' @importFrom xml2 xml_ns_strip xml_find_all xml_text #' @note This function is meant to be used internally. Only use when debugging. #' @keywords internal #' @export catch_errors <- function(x, retry=TRUE, verbose=FALSE){ if(http_error(x)){ response_parsed <- content(x, as="parsed", type="text/xml", encoding="UTF-8") if(status_code(x) == 500){ error_code <- response_parsed %>% xml_ns_strip() %>% xml_find_all("s:Body//s:Fault//s:Code//s:Value") %>% xml_text() error_text <- response_parsed %>% xml_ns_strip() %>% xml_find_all("s:Body//s:Fault//s:Reason//s:Text") %>% xml_text() if(retry & error_text == "An error occurred when verifying security for the message."){ dyn_auth_refresh(verbose = verbose) if(x$request$options$post){ this_body <- update_header(rawToChar(x$request$options$postfields)) x <- POST(x$request$url, add_headers(x$request$headers), body = this_body) } else { message(sprintf("%s: %s", error_code, error_text)) stop() } catch_errors(x, retry=FALSE, verbose = verbose) # retry=FALSE prevents infinite looping if we can't re-authenticate } else { message(sprintf("%s: %s", error_code, error_text)) stop() } } else { message(response_parsed) stop() } } invisible(x) } #' Another function to catch and print HTTP errors #' #' @importFrom httr content http_error status_code #' @importFrom xml2 xml_ns_strip xml_find_all xml_text #' @note This function is meant to be used internally. Only use when debugging. #' @keywords internal #' @export catch_errors2 <- function(x, verbose=FALSE){ retry <- FALSE if(http_error(x)){ response_parsed <- content(x, as="parsed", type="text/xml", encoding="UTF-8") if(status_code(x) == 500){ error_code <- response_parsed %>% xml_ns_strip() %>% xml_find_all("s:Body//s:Fault//s:Code//s:Value") %>% xml_text() error_text <- response_parsed %>% xml_ns_strip() %>% xml_find_all("s:Body//s:Fault//s:Reason//s:Text") %>% xml_text() if(error_text == "An error occurred when verifying security for the message."){ if(verbose) message('Refreshing Authentication') dyn_auth_refresh(verbose = verbose) retry <- TRUE } else { message(sprintf("%s: %s", error_code, error_text)) stop() } } else { message(response_parsed) stop() } } return(retry) } #' Another function to catch and print HTTP errors #' #' @importFrom httr content http_error status_code #' @importFrom xml2 xml_ns_strip xml_find_all xml_text #' @note This function is meant to be used internally. Only use when debugging. #' @keywords internal #' @export catch_errors_wo_retry <- function(x, verbose=FALSE){ retry <- FALSE if(http_error(x)){ response_parsed <- content(x, as="parsed", type="text/xml", encoding="UTF-8") if(status_code(x) == 500){ error_code <- response_parsed %>% xml_ns_strip() %>% xml_find_all("s:Body//s:Fault//s:Code//s:Value") %>% xml_text() error_text <- response_parsed %>% xml_ns_strip() %>% xml_find_all("s:Body//s:Fault//s:Reason//s:Text") %>% xml_text() message(sprintf("%s: %s", error_code, error_text)) stop() } else { message(response_parsed) stop() } } return(invisible(retry)) }
72dd6caef8397e6c4e636e2b38561066a5e3294c
b287e9f0550018796dccf868de06aef5fadf0558
/R/events_guildrolecreate.r
f7d0345826e1a118d3f9262540573e9df1401375
[]
no_license
TheOnlyArtz/Pirate
ffedc098db2f847c2b1fb3329fd94b6393d5af99
f68e1a0f16f872387b6a1d46d7a62ae6eb0c3ed1
refs/heads/master
2020-05-17T15:40:19.106630
2019-08-13T11:58:46
2019-08-13T11:58:46
183,796,627
1
0
null
2019-08-13T11:58:47
2019-04-27T16:29:31
R
UTF-8
R
false
false
714
r
events_guildrolecreate.r
#' Event, emitted whenever a role is being created #' @param data The event fields #' @param client The client object #'\dontrun{ #' client$emitter$on("GUILD_ROLE_CREATE", function(guild, role) { #' cat("A new role:", role$name, "has been created in:", guild$name, "!") #' }) #'} #' @section Disclaimer: #' This event will return guild id instead of guild object if not cached. #' this can be used in order to fetch the guild from the API (DISABLED FOR NOW) events.guild_role_create <- function(data, client) { guild <- client$guilds$get(data$guild_id) if (is.null(guild)) return() role <- Role(data$role, guild) guild$roles$set(role$id, role) client$emitter$emit("GUILD_ROLE_CREATE", guild, role) }
8ca99b520c5d0f98e57a60b14964f2cf3d5e51a4
777ac67d5ce4447560305313871ab8c4b0fc9c8d
/module01_data_and_files/materials/process_course_data.R
ffb2278313367989cba589518bef054e1ec8685f
[]
no_license
tavareshugo/slcu_r_course
c31ac0b4350e2597e72ad174f672ea91232364d4
4bb4b37e794d706d6bd69a6ede8eef2faa18608e
refs/heads/master
2021-09-11T08:22:42.931505
2018-04-06T08:25:52
2018-04-06T08:25:52
103,411,299
2
0
null
null
null
null
UTF-8
R
false
false
1,080
r
process_course_data.R
# Script can be run from the command line as # Rscript process_course_data.R library(tidyverse) # Read data directly from repository x <- read.table("https://datadryad.org/bitstream/handle/10255/dryad.104508/Experiment1.txt?sequence=2", header = TRUE, stringsAsFactors = FALSE) # Rename all variables to be lowercase x <- x %>% rename_all(funs(tolower(.))) # Retain only the genotypes shown in Fig. 1b-c x <- x %>% filter(genotype %in% c("Ler-1", "Col Ama", "fca-6", "flc-3 FRI", "FRI", "Col FRI", "ld-1", "flk-1", "fve-3", "prmt5 FRI", "vin3-4 FRI")) # Keep only a few of the variables (remove some redundant ones) x <- x %>% select(genotype, background, temperature, fluctuation, daylength, vernalization, survival.bolt, bolt, days.to.bolt, days.to.flower, rosette.leaf.num, cauline.leaf.num, blade.length.mm, total.leaf.length.mm, blade.ratio) # Rename "daylength" to "day.length" for good example of consistency x <- rename(x, day.length = daylength) # Save as CSV write_csv(x, "burghardt_et_al_2015_expt1.csv")
9ef3296689b1638bc09b7a0f70b401e8d9be3652
ba7e5cd3bd2d27da96a784954cb4478676decbce
/r/mfa.R
a8cce7be245fe6177341dec62f1dc066757d79b0
[]
no_license
nfagan/hwwa
2179b7817b478208f150d6fab90a6ad85e3cc2fc
be173e4c0947589e380436a8f5bae5a3ebc339ae
refs/heads/master
2021-06-12T07:32:28.064086
2021-02-22T20:45:54
2021-02-22T20:45:54
128,787,231
0
0
null
null
null
null
UTF-8
R
false
false
1,423
r
mfa.R
library(R.matlab) library(FactoMineR) combine_data_labels <- function(data, labels) { all_data <- data for (name in names(labels)) { all_data$name = labels$name } return(all_data) } raw_data_to_frame <- function(raw_data) { mat_data <- data.frame(raw_data$data) names(mat_data) <- unlist(raw_data$data.header) return(mat_data) } extract_labels <- function(raw_data) { categories <- unlist(raw_data$label.categories) entries <- unlist(raw_data$label.entries) indices <- raw_data$label.indices label_entries <- matrix(0, nrow(indices), ncol(indices)) for (i in 1:ncol(label_entries)) { label_entries[, i] = entries[indices[, i]] } labels <- data.frame(label_entries) names(labels) <- categories return(labels) } raw_data <- readMat("/Users/Nick/Desktop/hwwa/pca_data.mat") labels <- extract_labels(raw_data) data <- raw_data_to_frame(raw_data) all_data <- cbind(data, labels) keep_categories <- c("drug", "trial_type") keep_columns <- c(names(data), keep_categories) mfa_data <- all_data[keep_columns] any_nan = apply(apply(mfa_data[names(data)], 2, is.nan), 1, any) res.mfa <- MFA(mfa_data[!any_nan,], group = c(ncol(data), length(keep_categories)), type = c("s", "n"), name.group = c("saccade_info", "behavior"), num.group.sup = 1, graph = FALSE) quanti_var <- get_mfa_var(res.mfa)
403c34948e19042ccb11a7d3327df8a30019a844
b1c6daedae2a5cc1692a813249d91945765c1de5
/server.R
b0ee9690239f64ba55d26f4d9172f9ca44b43e76
[]
no_license
jyhsieh/boardgame-match
23fe0b9894f47dfd3d8a3c7442cd4ab7704fc558
06443aa3bc4613c7e33a6457230df8effd42d94b
refs/heads/master
2020-03-20T08:03:03.050398
2018-09-18T14:26:05
2018-09-18T14:26:05
137,297,549
0
0
null
null
null
null
UTF-8
R
false
false
3,628
r
server.R
library(shiny) library(tidyverse) library(wordcloud2) library(ggplot2) #========================================================================= # Expand Mechanic and Category Variable #========================================================================= All_mechanic = unlist(strsplit(boardgame$mechanic, ", ")) Uniq_mechanic = unique(All_mechanic) All_cat = unlist(strsplit(boardgame$category, ", ")) Uniq_cat = unique(All_cat) boardgame_cluster <- matrix(0,nrow = dim(boardgame)[1],ncol = length(Uniq_mechanic)+length(Uniq_cat)) for(i in 1:length(Uniq_mechanic)){ boardgame_cluster[,i] <- grepl(Uniq_mechanic[i],boardgame$mechanic)*1 } for(i in 1:length(Uniq_cat)){ boardgame_cluster[,length(Uniq_mechanic)+i] <- grepl(Uniq_cat[i],boardgame$category)*1 } dim(boardgame_cluster) # 4999 136 boardgame_cluster <- as.data.frame(boardgame_cluster) colnames(boardgame_cluster)[1:length(Uniq_mechanic)] <- Uniq_mechanic colnames(boardgame_cluster)[(1+length(Uniq_mechanic)):136] <- Uniq_cat colnames(boardgame_cluster)[which(duplicated(colnames(boardgame_cluster)))] #"none" "Memory" which(colnames(boardgame_cluster)=="none") #50 114 colnames(boardgame_cluster)[50] <- "none_mechanic" colnames(boardgame_cluster)[114] <- "none_cat" which(colnames(boardgame_cluster)=="Memory") # 26 117 colnames(boardgame_cluster)[26] <- "Memory_mechanic" colnames(boardgame_cluster)[117] <- "Memory_cat" #======================================================== # cluster determined by max mode #======================================================== getmode <- function(v) { uniqv <- unique(v) uniqv[which.max(tabulate(match(v, uniqv)))] } cluster_max <- function(dat,n_cluster,num_iter){ result <- matrix(0,nrow = dim(dat)[1],ncol = num_iter) for(i in 1:num_iter){ result[,i] <- kmeans(dat,centers = n_cluster)$cluster } return(apply(result,MARGIN = 1,getmode)) } #======================================================== server <- function(input,output){ n_cluster <- reactive({input$num_cluster}) i <- reactive({input$which_cluster}) cluster_result <- reactive({ cluster_max(boardgame_cluster,n_cluster = n_cluster(),num_iter = 20) }) boardgame_cluster_all <- reactive({ cbind(names = boardgame$names,boardgame_cluster,cluster = cluster_result()) }) d <- reactive({ word_freq <- c() for(i in 1:n_cluster()){ word_freq <- cbind(word_freq,apply(boardgame_cluster_all()[boardgame_cluster_all()$cluster==i,-c(1,138)],2,sum)) } #========================================================================= # Word Cloud and Frequency Plot #========================================================================= data.frame(word=names(sort(word_freq[,i()],decreasing = T)),freq = sort(word_freq[,i()],decreasing = T)) }) output$freqplot <- renderPlot({ ggplot(data = d()[1:10,],aes(x = reorder(word,-freq),y = freq)) + geom_bar(stat = "identity", fill = "steelblue") + xlab("Game Type")+ ylab("Frequency") + ggtitle(paste("Top 10 Game Types of Cluster ",i()))+ theme_classic() + theme( axis.text.x = element_text(angle = 45, hjust = 1), plot.title = element_text(size=24, face="bold.italic",hjust = 0.5), axis.title.x = element_text(size=14, face="bold"), axis.title.y = element_text(size=14, face="bold") ) }) output$wordcloud <- renderWordcloud2({ set.seed(1234) if(d()$freq[1]>3*d()$freq[2]){ size <- 0.1 } else{size <- 0.3} wordcloud2(d(), size = size, fontWeight = "bold", color = "random-light",backgroundColor = "grey") }) }
fc61ffa5b5c459273880ecfdf8436008e2b69cba
dbf4d16af283045abb830df0ec5445b0dbd4af6c
/covid/acces OurWorldinData cases/read_in_our_worldindata.R
bb1930a8145440ad6beb6e7289613ad9eaafb197
[]
no_license
ammapanin/striking-statistics-tap
1d7845e4b78fde053332141a64c8a5a82a5abb02
135ed9c902271ccfbf4803b466a3181995735817
refs/heads/master
2020-08-01T20:07:59.450793
2020-04-10T13:22:55
2020-04-10T13:22:55
211,101,091
1
2
null
null
null
null
UTF-8
R
false
false
8,507
r
read_in_our_worldindata.R
library(tidyverse) library(countrycode) library(readxl) library(magick) ### Setup paths covid.path <- file.path(normalizePath("~"), "Dropbox", "Work Documents", "World Bank", "amma_striking_stats_local", "covid") setwd(covid.path) final.figures.path <- "final figures" #trend.plot.path <- file.path(final.figures.path) full.data.link <- "https://covid.ourworldindata.org/data/ecdc/full_data.csv" full.dt.in <- read.csv(full.data.link) ### Get a list of SSA countries wb.path <- file.path(shared.data.path, "wb_country_codes.csv") wb.in <- read.csv(wb.path) ssa.codes <- wb.in %>% filter(region == "Sub-Saharan Africa") %>% pull(code) %>% as.character() ### Prepare dataset for plotting comparison.countries <- c("United States", "China") dt <- full.dt.in %>% mutate(ccode = countrycode( sourcevar = .$location, origin = "country.name", destination ="iso3c"), is.ssa = ifelse(ccode %in% ssa.codes, TRUE, FALSE), date = as.Date(date)) dt.ssa <- dt %>% filter((is.ssa == TRUE | location %in% comparison.countries)) latest.date <- max(dt$date) latest.date.text <- format(latest.date, "%d %B %Y") dt.today <- dt %>% filter(date== latest.date) ### Define some general parameters general.theme <- theme_minimal() + theme(axis.text.x = element_text(size = 6)) ### Plot cases latest.cases <- dt.ssa %>% filter(date == latest.date) %>% ggplot(aes(x = ccode, y = total_cases)) + geom_point() + scale_y_continuous(trans = "log10") + general.theme ### Make the trend plots translate.date <- function(date.col){ seq_along(date.col) - 1 } get.earliest.date <- function(country.dt, n.cases = Ncases){ earliest.date <- country.dt %>% mutate(more.than.n = total_cases >= n.cases) %>% filter(more.than.n == TRUE) %>% pull(date) %>% min() names(earliest.date) <- country.dt$location %>% unique() %>% as.character() return(earliest.date) } get.days.since.n <- function(country.dt, n.cases = Ncases){ earliest.date <- get.earliest.date(country.dt, n.cases) more.cases.df <- country.dt %>% filter(date >= earliest.date) %>% mutate(date.zeroed = translate.date(date)) return(more.cases.df) } double.day.function <- function(doubling.days, time.vec, n.cases = Ncases){ n.cases * (2 ^ (time.vec/doubling.days)) } get.doubling.plot.coords <- function(ddf, max.cases.in = max.cases.plot, max.days.in = max.days.plot){ coords.df.out <- ddf %>% filter(number_cases < max.cases.in) %>% filter(date.zeroed == max.days.in) return(coords.df.out) } pretty.doubling.names <- function(xstr){ paste(gsub("days", "doubling every ", xstr), "days") } make.doubling.df <- function(doubling.days.list, time.vec.in, ncases.in = Ncases){ doubling.times.list <- lapply( doubling.days.list, double.day.function, time.vec = time.vec.in, n.cases = ncases.in) names(doubling.times.list) <- paste0("days", doubling.days.list) doubling.df <- data.frame(doubling.times.list) %>% mutate(date.zeroed = time.vec.in) %>% pivot_longer(cols = starts_with("days"), names_to = "doubling_time", values_to = "number_cases") plot.names.df <- doubling.df %>% group_by(doubling_time) %>% group_modify(~get.doubling.plot.coords(.x)) %>% ungroup() %>% mutate(line_name = pretty.doubling.names(.$doubling_time)) return(list(doubling.df, plot.names.df)) } get.levels.of.factor <- function(df.in, factor.name, value.name){ ordered.out <- df.in %>% arrange_(value.name) %>% select_(factor.name) %>% pluck(1) %>% unique() %>% as.character() return(rev(ordered.out)) } add.e4t.branding <- function(plot, plot.name, width.in, height.in){ plot.png <- paste0(plot.name, ".png") ggsave(plot.png, width = width.in, height = height.in, units = "cm", plot = plot) stats.png <- image_read(plot.png) logo <- image_read("e4t_logo.png")%>% image_resize("x150") twitter <- image_read("e4t_twitter.png") %>% image_resize("x90") logo.offset <- paste0("+", round((width.in - 1)*100, 0), "+", "0") print(logo.offset) plot.img <- image_composite(stats.png, logo, offset = logo.offset) #%>% # image_composite(twitter, offset = "+1250+1950") image_write(plot.img, path = file.path(final.figures.path, plot.png)) return(plot.img) } ### Check when different countries crossed the N threshold Ncases <- 150 country.cross.n.list <- dt %>% group_by(location) %>% group_map(~get.earliest.date(.x, n.cases = Ncases), keep = TRUE) country.cross.n <- do.call("c", country.cross.n.list) N.more.than.n <- dt.today %>% filter(total_cases > Ncases) %>% pull(location) %>% as.character() %>% length() %>% `-`(1) ssa.N <- dt.ssa %>% group_by(location) %>% group_modify(~get.days.since.n(.x, n.cases = Ncases)) %>% ungroup() %>% mutate(location = as.character(location), location = factor( location, levels = get.levels.of.factor( df.in = filter(., date == latest.date), "location", "total_cases")), ordered = TRUE) ssa.only.df <- ssa.N %>% filter(is.ssa) max.cases.plot <- ssa.only.df %>% pull(total_cases) %>% max() %>% `+`(20) min.cases.plot <- ssa.only.df %>% pull(total_cases) %>% min() %>% `-`(1) max.days.plot <- ssa.only.df %>% pull(date.zeroed) %>% max() %>% `+`(1) N.countries <- length(ssa.N$location %>% unique()) days.since.n <- ssa.N$date.zeroed %>% unique() doubling.days.plot <- c(1, 5, 10) doubling.df.list <- make.doubling.df(doubling.days.plot, days.since.n) doubling.df <- doubling.df.list[[1]] doubling.df.names <- doubling.df.list[[2]] plot.title.base <- paste("%s African countries have more", "than %s confirmed COVID-19 cases") caption.text <- paste( "Source: Our World in Data. Plot inspired by FT.", sprintf("Last accessed on %s", latest.date.text)) xlab.text <- paste( sprintf("Days since case %s was reported", Ncases)) plot.title <- sprintf(plot.title.base, N.countries, Ncases) trend.plot <- ssa.N %>% ggplot(aes(x = date.zeroed, y = total_cases, colour = location)) + geom_point() + geom_line() + geom_line(data = doubling.df, inherit.aes = FALSE, aes(x = date.zeroed, y = number_cases, linetype = doubling_time), colour = "gray") + geom_text(data = doubling.df.names, inherit.aes = FALSE, aes(x = date.zeroed, y = number_cases, label = line_name), colour = "grey67", hjust = "right", nudge_x = -0.5) + scale_y_continuous(trans = "log10", limits = c(min.cases.plot, max.cases.plot)) + scale_x_continuous(limits = c(0, max.days.plot)) + labs(caption = caption.text) + xlab(xlab.text) + ylab("Total number of cases") + guides(linetype = "none") + general.theme + theme(legend.title = element_blank(), plot.title.position = "plot", plot.caption.position = "plot", plot.caption = element_text( hjust = 0, size = 7, margin = margin(t = 0.5, unit = "cm"))) plot.final <- add.e4t.branding(trend.plot, "SSA_more_than_100a", width.in = 26.9, height.in = 15.5)
d9aca7633db92bb9df6c0d0fd6e3d5f743685ca0
87f85a565768dbf5418516b1c742f45f2342f524
/scripts/misc/RMSDcov.R
a9aebba18cef3bbaf2e714251151bb63750986d1
[ "Apache-2.0" ]
permissive
genomicsengland/gel-coverage
1ad6716efaa3059146c30812f1f7e21a0f4a9236
61a671a53ac52a0b62c8aea983ced65fd0bed6cc
refs/heads/master
2022-07-07T00:04:27.718426
2021-05-06T16:55:58
2021-05-06T16:55:58
70,790,696
2
0
Apache-2.0
2022-07-05T21:29:25
2016-10-13T09:27:20
Python
UTF-8
R
false
false
215
r
RMSDcov.R
args = commandArgs(trailingOnly = TRUE) bwtool.file = args[1] data <- read.delim(bwtool.file, as.is=T, sep = "\t", header = TRUE) median <- median(sqrt(data$sum_of_squares/100000)) writeLines(paste(median,sep=" "))
09d718b4a74c51a5732be610e5f46ce64e55ede7
223756424b32600a66b505e886fbad9c9fe47e7b
/Plot1.R
8c5190d683b7b628d25d77a58fa25784a78d370e
[]
no_license
ghostdatalearner/ExData_project2
12070e2091b54d0a6a1da7012e1fa849b4ab010b
867d83df40d8fabe459c0a41838086520ccf04c0
refs/heads/master
2021-01-22T23:11:14.325383
2014-06-21T16:32:27
2014-06-21T16:32:27
null
0
0
null
null
null
null
UTF-8
R
false
false
849
r
Plot1.R
# Coursera JHU Spec Data Science # # Exploratory Data Analysis # # Project 2 # # Plot1.R # NEI <- readRDS("summarySCC_PM25.rds") # Total emissions by year. acc_emiss_year <- tapply(NEI$Emissions,NEI$year,sum) # We open the graphic png(file = "Plot1.png", width = 480, height = 480, bg = "transparent") # As the accumulated emissions are in the order of millions of tons, we divide by 1000.000 # and add the proper indication in the y label df_scaled <- acc_emiss_year/1000000 b<-barplot(df_scaled,ylab="PM_2.5 (Million tons)",main="Total PM_2.5 yearly emissions in USA",xlab="",axis.lty=1,ylim=c(0, 1.3*round(df_scaled[1],2))) percent_labels <- paste0(100*(round((df_scaled-df_scaled[1])/df_scaled[1],3)),"%") percent_labels[1] <- "1999 Reference: 100%" text(x=b,y=as.vector(df_scaled),labels=percent_labels, pos=3,col="black",cex=0.75) dev.off()
0b7bed3adeedcd7ae881fcb17e285d75ee191f37
22dc322d68a8bfaecf3c57be5ec99a433f0a95a8
/man/data_heckman.Rd
98353ea9902ab2b578c673b7672ca40bdef01bff
[]
no_license
cran/micemd
19a1acfeb69da9e62d1639265a518ecebeb1f3a5
e5adbe076babd9f6c9aa3926eaabdd73d76dd69f
refs/heads/master
2023-06-09T21:04:43.211056
2023-06-01T11:00:04
2023-06-01T11:00:04
91,136,501
0
2
null
null
null
null
UTF-8
R
false
false
2,325
rd
data_heckman.Rd
\name{data_heckman} \docType{data} \alias{data_heckman} \title{ A two-level incomplete dataset based on an online obesity survey} \description{ The dataset used here was based on data collected from 2111 individuals in an online obesity survey in different locations. The data were simplified and grouped into five clusters. The values and observability of the weight variable were defined according to Heckman's model in a herarchical model, and a systematic loss of this variable was assumed in one cluster. Additionally, the predictor variables Age, Height and FAVC follow a MAR missing mechanism. Response time (Time) was used as an exclusion restriction variable. } \format{ A dataframe with 2111 observations with the following variables: \tabular{rll}{ \tab Gender \tab a factor value with two levels: 1 ("Female"), 0 ("Male").\cr \tab Age \tab a numeric value indicating age of subject in years.\cr \tab Height\tab a numeric value with Height in meters.\cr \tab FAVC\tab a factor value describing the frequent consumption of high caloric food (FAVC) with two levels:1("Yes"), 0("Male").\cr \tab Weight\tab a numeric value with Weight in Kilograms.\cr \tab Time\tab a numeric value indicating time in responding the questions in minutes.\cr \tab Cluster\tab a numeric indexing the cluster.\cr } } \source{Dataset obtained from "https://www.kaggle.com/datasets/fabinmndez/obesitydata?select=ObesityDataSet_raw_and_data_sinthetic.csv"} \references{ Palechor, F. M., & de la Hoz Manotas, A. (2019). Dataset for estimation of obesity levels based on eating habits and physical condition in individuals from Colombia, Peru and Mexico. Data in brief, 25, 104344. } \details{ Simulation data code on gen_dataObs.R github repository } \examples{ require(mice) require(ggplot2) data(data_heckman) summary(data_heckman) # missing data pattern md.pattern(data_heckman) # Count missingness per group by(data_heckman, INDICES = data_heckman$Cluster, FUN=md.pattern) # Plot weight ggplot(data_heckman, aes(x = Weight, group=as.factor(Cluster))) + geom_histogram(aes(color = as.factor(Cluster),fill= as.factor(Cluster)), position = "identity", bins = 30)+facet_grid(Cluster~.) } \keyword{datasets}
b7bbd4945c8b51d422702c63e28d63d286f23104
aedc3ee164734a8c42d5c535a02ee1acdf3443fb
/R/scRNA-seq/1.3_integrate_SCT-RPCA_fromMatrix.R
d50dea83cff643421f1a1b357a3b998cf13ecb63
[]
no_license
zglu/Scripts_Bioinfo
60fdd5fe70b4900d981cc06560595ecb4fb9690e
8589ed613868f88ae12b8a629156c0a12b420bbc
refs/heads/master
2023-01-27T11:13:18.140272
2023-01-23T13:19:09
2023-01-23T13:19:09
96,612,675
3
1
null
null
null
null
UTF-8
R
false
false
2,118
r
1.3_integrate_SCT-RPCA_fromMatrix.R
# Rscript 1.3_integrate_SCT-RPCA_fromMatrix.R library(Seurat) library(dplyr) # each data Data1<-Read10X("~/zl3/Inqueries/Cheng_Sj_scRNA/_newCellRangerMapping2021-12/CellRanger_mito-4genes/F16/filtered_feature_bc_matrix/", gene.column=1) # default is col2: gene names. col1 is gene ids Data2<-Read10X("~/zl3/Inqueries/Cheng_Sj_scRNA/_newCellRangerMapping2021-12/CellRanger_mito-4genes/F26/filtered_feature_bc_matrix/", gene.column=1) # default is col2: gene names. col1 is gene ids Data1<-CreateSeuratObject(Data1, project = "F16", min.cells = 3, min.features = 200) Data2<-CreateSeuratObject(Data2, project = "F26", min.cells = 3, min.features = 200) Data1[["percent.mt"]] <- PercentageFeatureSet(object = Data1, pattern = "^Sj-") Data2[["percent.mt"]] <- PercentageFeatureSet(object = Data2, pattern = "^Sj-") Fil1 <- subset(x = Data1, subset = nFeature_RNA > 500 & nFeature_RNA < 4000 & nCount_RNA > 2000 & nCount_RNA < 30000 & percent.mt < 2.5) Fil2 <- subset(x = Data2, subset = nFeature_RNA > 500 & nFeature_RNA < 4000 & nCount_RNA > 2000 & nCount_RNA < 30000 & percent.mt < 2.5) int_list<-list(Fil1, Fil2) int_list <- lapply(X = int_list, FUN = SCTransform, method = "glmGamPoi", vars.to.regress = "percent.mt") features <- SelectIntegrationFeatures(object.list = int_list, nfeatures = 3000) int_list <- PrepSCTIntegration(object.list = int_list, anchor.features = features) ## integration using RPCA int_list <- lapply(X = int_list, FUN = RunPCA, features = features) int.anchors <- FindIntegrationAnchors(object.list = int_list, normalization.method = "SCT", anchor.features = features, reduction = "rpca")# , dims = 1:30, k.anchor = 20) int.combined.sct <- IntegrateData(anchorset = int.anchors, normalization.method = "SCT")#, dims = 1:30) int.combined.sct <- RunPCA(int.combined.sct, verbose = FALSE) int.combined.sct <- RunUMAP(int.combined.sct, reduction = "pca", dims = 1:30) int.combined.sct <- FindNeighbors(int.combined.sct, reduction = "pca", dims = 1:30) int.combined.sct <- FindClusters(int.combined.sct, resolution = 0.5) saveRDS(int.combined.sct, file="integrated_SCT-RPCA.rds")
16eec0354085a15393087ebc20bb338c4803d488
72d9009d19e92b721d5cc0e8f8045e1145921130
/SpaDES.tools/man/heading.Rd
04bcfa72fdfe5cc90494b061fcb6005335d501f2
[]
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,742
rd
heading.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/heading.R \name{heading} \alias{heading} \alias{heading,SpatialPoints,SpatialPoints-method} \alias{heading,matrix,matrix-method} \alias{heading,matrix,SpatialPoints-method} \alias{heading,SpatialPoints,matrix-method} \title{Heading between spatial points.} \usage{ heading(from, to) \S4method{heading}{SpatialPoints,SpatialPoints}(from, to) \S4method{heading}{matrix,matrix}(from, to) \S4method{heading}{matrix,SpatialPoints}(from, to) \S4method{heading}{SpatialPoints,matrix}(from, to) } \arguments{ \item{from}{The starting position; an object of class SpatialPoints.} \item{to}{The ending position; an object of class SpatialPoints.} } \value{ The heading between the points, in degrees. } \description{ Determines the heading between spatial points. } \examples{ library(sp) N <- 10L # number of agents x1 <- stats::runif(N, -50, 50) # previous X location y1 <- stats::runif(N, -50, 50) # previous Y location x0 <- stats::rnorm(N, x1, 5) # current X location y0 <- stats::rnorm(N, y1, 5) # current Y location # using SpatialPoints prev <- SpatialPoints(cbind(x = x1, y = y1)) curr <- SpatialPoints(cbind(x = x0, y = y0)) heading(prev, curr) # using matrix prev <- matrix(c(x1, y1), ncol = 2, dimnames = list(NULL, c("x","y"))) curr <- matrix(c(x0, y0), ncol = 2, dimnames = list(NULL, c("x","y"))) heading(prev, curr) #using both prev <- SpatialPoints(cbind(x = x1, y = y1)) curr <- matrix(c(x0, y0), ncol = 2, dimnames = list(NULL, c("x","y"))) heading(prev, curr) prev <- matrix(c(x1, y1), ncol = 2, dimnames = list(NULL, c("x","y"))) curr <- SpatialPoints(cbind(x = x0, y = y0)) heading(prev, curr) } \author{ Eliot McIntire }
6214b3b0a411afb2e64cdce7714de86546cad967
d7d2382f23fe3296d1528d17220ba2d29dc915b0
/SimpleInterpolationApp/TokenizeData_tm.R
6cb49174430c234614ee3e66e579ef584e80eafc
[]
no_license
fredcaram/JohnHopkinsDataScienceCapstone
7f86988ec567d83d075408115ff795d8e4a0bbea
f53c23e7d884e9a9e445ccf3696486a90a4bbb35
refs/heads/master
2021-01-15T16:53:06.677732
2017-08-11T12:57:55
2017-08-11T12:57:55
99,732,754
0
0
null
null
null
null
UTF-8
R
false
false
1,837
r
TokenizeData_tm.R
library("RColorBrewer") library("tm") #library("ngramrr") library("SnowballC") library("wordcloud") library(rJava) .jinit(parameters="-Xmx128g") library("RWeka") #badWords <- VectorSource(readLines("./dirty/english.txt")) tm.GetCorpus <- function(path){ corp <- VCorpus(DirSource(path)) corp <- tm.CleanCorpus(corp) corp } tm.GetTextCorpus <- function(text){ corp <- VCorpus(VectorSource(text)) corp } tm.RemoveNaFilter <- function(x) any(grep("^na$", x, ignore.case = TRUE, invert = TRUE)) tm.CleanCorpus <- function(corp, removeStopWords = FALSE){ corp <- tm_map(corp, removePunctuation) corp <- tm_map(corp, removeNumbers) corp <- tm_map(corp, content_transformer(tolower)) if(removeStopWords){ corp <- tm_map(corp, removeWords, stopwords("english")) } corp <- tm_map(corp, removeWords, badWords$content) corp <- tm_map(corp, stripWhitespace) corp <- tm_map(corp, PlainTextDocument) corp <- tm_filter(corp, tm.RemoveNaFilter) corp } tm.GetDTM <- function(corp, ng, sparsity, removeStopWords){ options(mc.cores=1) ptm <- proc.time() ngramTokenizer <- function(x) RWeka::NGramTokenizer(x, RWeka::Weka_control(min = ng, max = ng)) if(removeStopWords){ corp <- tm_map(corp, removeWords, stopwords("english")) } my_dtm <- DocumentTermMatrix(corp, control = list(tokenize = ngramTokenizer)) if(!is.null(sparsity)) { my_dtm <- removeSparseTerms(my_dtm, sparse= sparsity) } # Stop the clock print(proc.time() - ptm) my_dtm } tm.GetTermsFrequency <- function(mydtm){ freq <- colSums(as.matrix(mydtm)) freq <- freq[order(freq * -1)] freq } tm.PlotFrequency <- function(freq){ qplot(freq, xlim=c(0, 50), bins=100) } tm.PlotWordCloud <- function(freq, n){ wordcloud(names(head(freq, n=n)), head(freq, n=n), c(4,.01), colors = brewer.pal(6, "Dark2")) }
eea5d85c4c6393fab6070eb393d4a08e88f4a537
547660ed83f72f861078c2e9ab32255e112b8ac8
/inst/ignore/phylomedb.R
2f9019217c7a07baccd26be0b1caacde9fb01c8c
[ "MIT" ]
permissive
ropensci/brranching
6d84f64ae7b97d873191be03ed2c7580efa07a32
efd089fd8218de75b1148d14db3e9926552fa705
refs/heads/master
2023-05-23T05:26:09.112878
2022-12-05T08:37:57
2022-12-05T08:37:57
30,196,325
18
10
NOASSERTION
2022-11-17T21:54:34
2015-02-02T16:31:55
R
UTF-8
R
false
false
817
r
phylomedb.R
#' @title PhylomeDB #' #' @description Fetch phylome trees from PhylomeDB #' #' @export #' @param seqid An id #' @param ... Curl options passed on to \code{\link[httr]{GET}} #' @return Newick formatted tree or nexml text. #' @examples \dontrun{ #' # Fetch by seqid #' id <- "Phy004LGJW_CROPO" #' tree <- phylomedb(seqid = id) #' plot(tree, no.margin=TRUE) #' } phylomedb <- function(seqid, ...) { args <- list(q = "search_tree", seqid = seqid) gzpath <- tempfile(fileext = ".tar.gz") tt <- GET(phydb_base, query = args, config(followlocation=1)) stop_for_status(tt) out <- content(tt, as = "text") } phydb_base <- "http://phylomedb.org" tar_url <- function(x) { txt <- content(x, 'text') grep("download data\\.tar\\.gz", txt) } do_tar <- function(x) { tt <- GET(url, query = args, write_disk()) }
4abe7a5b8b60c0bfe4ea6ff9fa0a4aa9521e539b
16e3ea1b885ea80b6b6e1c8a76d085c0bed97462
/maineQTL.R
b1dad8914bc1ede819bd5a1b403bbb663e567b9f
[]
no_license
CreRecombinase/MatrixeQTLGLM
5ba48a6877c38b57585ac56ce5627a424376acd1
c78e7d848f9b668b5ed840d6d5ac7880ccf1b62f
refs/heads/master
2020-12-24T14:53:48.802827
2013-04-23T18:29:11
2013-04-23T18:29:11
null
0
0
null
null
null
null
UTF-8
R
false
false
2,823
r
maineQTL.R
#First revision of Andy's pseudocode for unimputed BRCA SNP and Expression Data #2/6/13 #NWK library(sqldf) library(plyr) library(BatchExperiments) library(MatrixEQTL) ###USAGE maineQTL.R <out.files> <root.dir> <out-dir> <annofile> <snp.expfile> <samples> <fold-validation> <time> <queue> <memory> <CISTRA|CIS> makeClusterFunctionsLSF("~/lsf-standard.tmpl") oargs <- commandArgs(trailingOnly=TRUE) args <- list() args$OUT.FILES <- oargs[1] args$ROOT.DIR <- oargs[2] args$OUT.DIR <- oargs[3] args$ANNOFILE <- oargs[4] args$SNP.EXPFILE <- oargs[5] args$SAMPLES <- as.integer(oargs[6]) args$FOLD.VALIDATION <- as.integer(oargs[7]) args$TIME <- oargs[8] args$QUEUE <- oargs[9] args$MEMORY <- oargs[10] args$CISTRA <- oargs[11] root.dir <- args$ROOT.DIR out.dir <- args$OUT.DIR setwd(root.dir) annofile <- args$ANNOFILE snp.expdata <- args$SNP.EXPFILE ###Function for cross validation mat.train <- function(i,snp.exploc,anno.loc,train.indices,MEQTL.params){ load(snp.exploc) load(anno.loc) total.ids <- snp.exp$snps$nCols() snp.exp$snps$ColumnSubsample(train.indices) snp.exp$gene$ColumnSubsample(match(colnames(snp.exp$snps),colnames(snp.exp$gene))) with(MEQTL.params, Matrix_eQTL_main( snps=snp.exp$snps, gene=snp.exp$gene, output_file_name=paste(output.file.name.tra,i,".txt",sep=""), output_file_name.cis=paste(output.file.name.cis,i,".txt",sep=""), useModel=useModel, verbose=verbose, pvOutputThreshold=pvOutputThreshold.tra, pvOutputThreshold.cis=pvOutputThreshold.cis, snpspos=annolist$snp.anno, genepos=annolist$exp.anno, cisDist=cisDist, pvalue.hist=pvalue.hist ) ) } samples <- args$SAMPLES train.indices <- chunk(rep(1:samples,args$FOLD.VALIDATION),n.chunks=args$FOLD.VALIDATION) test.indices <- chunk(1:samples,chunk.size=ceiling(samples/args$FOLD.VALIDATION)) train.indices <- mapply(FUN=function(x,y)x[-y],train.indices,test.indices,SIMPLIFY=F) MEQTL.params <- list( output.file.name.tra=paste(out.dir,args$OUT.FILES,"_trans",sep=""), output.file.name.cis=paste(out.dir,args$OUT.FILES,"_cis",sep=""), useModel=modelANOVA, verbose=T, pvOutputThreshold.tra=ifelse(args$CISTRA=="CISTRA",1e-8,0), pvOutputThreshold.cis=1e-8, cisDist=1e6, pvalue.hist=F ) m.dir <- tempfile(paste("meqtl.res",args$OUT.FILES,sep=""),tmpdir=out.dir) registry.name <- paste("meqtl_reg_",args$OUT.FILES,sep="") MEQTL.reg <- makeRegistry(registry.name,file.dir=m.dir,packages="MatrixEQTL") batchMap(MEQTL.reg,mat.train,train.indices=train.indices,i=1:length(train.indices),more.args=list( MEQTL.params=MEQTL.params, snp.exploc=snp.expdata, anno.loc=annofile)) submitJobs(MEQTL.reg,resources=list(queue=args$QUEUE,memory=args$MEMORY,time=args$TIME,threads=1)) Sys.sleep(35)
213f47b39253b8a1df2885d2ad303b38d2c39cca
39940b7cc4ce9470f5e8201e1f82b02b98984601
/utils/Nonpareil/man/summary.Nonpareil.Curve.Rd
8c4a4edefa927c09d59106b8c8f1fbf03d8ea876
[ "Artistic-2.0" ]
permissive
lmrodriguezr/nonpareil
dcd7ac99330b9dc1737f0a46f0985095e58d6e65
162f1697ab1a21128e1857dd87fa93011e30c1ba
refs/heads/master
2022-02-23T11:52:11.279418
2022-02-22T19:51:05
2022-02-22T19:51:05
5,099,209
36
15
null
2017-11-14T15:13:17
2012-07-18T17:02:52
C++
UTF-8
R
false
true
1,240
rd
summary.Nonpareil.Curve.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/Nonpareil.R \name{summary.Nonpareil.Curve} \alias{summary.Nonpareil.Curve} \title{Returns a summary of the \code{Nonpareil.Curve} results.} \usage{ \method{summary}{Nonpareil.Curve}(object, ...) } \arguments{ \item{object}{\code{Nonpareil.Curve} object.} \item{...}{Additional parameters ignored.} } \value{ Returns a matrix with the following values for the dataset: \itemize{ \item kappa: "Redundancy" value of the entire dataset. \item C: Average coverage of the entire dataset. \item LRstar: Estimated sequencing effort required to reach the objective average coverage (star, 95% by default). \item LR: Actual sequencing effort of the dataset. \item modelR: Pearson's R coefficient betweeen the rarefied data and the projected model. \item diversity: Nonpareil sequence-diversity index (Nd). This value's units are the natural logarithm of the units of sequencing effort (log-bp), and indicates the inflection point of the fitted model for the Nonpareil curve. If the fit doesn't converge, or the model is not estimated, the value is zero (0). } } \description{ Returns a summary of the \code{Nonpareil.Curve} results. }
40fc0d38d99ac760d92574bf365a85c1fd44fe7c
bc2a485ffe10d8e42b0a5e100fbaeed83a6d57d4
/3.r
391e0957bbbb4bcb812a2bbb3a30d547bed2f462
[]
no_license
Phanideep007/datascience
4989a11fc11aa8eb3a32ffd0644a087ffba0c837
eb1dfd08b57b397f97eb69605f156a531829c377
refs/heads/master
2020-03-16T03:28:10.537415
2018-05-18T16:11:28
2018-05-18T16:11:28
132,488,245
0
0
null
null
null
null
UTF-8
R
false
false
365
r
3.r
usedcar=read.csv(file.choose()) scale(usedcar$Price) usedcar=usedcar[-1] head(usedcar) boxprice=BoxCoxTrans(usedcar$Price) priceboxcox=predict(boxprice,usedcar$Price) head(priceboxcox) hist(priceboxcox) plot(density(priceboxcox)) plot(density(usedcar$Price)) skewness(priceboxcox) skewness(usedcar$Price) par(mfrow=c(1,2)) dev.off() princomp()
b36f893db7a6c1e1a570a48579e0fdaf0fd22bdb
9d0c396fc511e651a1a58d6f6c62b3667695d60f
/R/KMCox_RacoonOlyLarvaeSurvival.R
9fb298adca52a203752eb28782bc5631bf4a7224
[]
no_license
lalma/RacoonOlyLarvalSurvival
fc902e502ca77c33317d057d1875ce4c9294943f
521f8626d79476e9f891fca4a0397588ba0fd5cc
refs/heads/main
2023-08-16T06:05:24.001055
2021-10-22T02:48:42
2021-10-22T02:48:42
393,133,714
0
0
null
null
null
null
UTF-8
R
false
false
7,719
r
KMCox_RacoonOlyLarvaeSurvival.R
#kaplan meier survival #load libraries library(survival) library(survminer) library(ggplot2) library(rms) library(readxl) library(survELtest) #upload datasheet 38,400 lines. once for each larvae OlyLarvaeKMforR <- read_excel("C:/Users/Lindsay/Dropbox/Raccoon/larvae/oyster/larvae survival stats/GitHub/RacoonOlyLarvalSurvival/OlyLarvaeKMforR.xlsx") View(OlyLarvaeKMforR) #make surv object KMsurv = Surv(time = OlyLarvaeKMforR$day, OlyLarvaeKMforR$dead, type = "right") # fit KM model and plot without random effect of tank sf <- survfit(KMsurv ~ Treatment+Location, data = OlyLarvaeKMforR) summary(coxph(KMsurv ~ Treatment*Location, data = OlyLarvaeKMforR)) # Graph the KMsurvival distribution #you can add pval = TRUE, but we know our p>0.0001 ggsurvplot(sf, conf.int = 0.05) # another type of graph plot(sf, xlab="Larval Age", ylab="% Surviving", yscale=100, col=c("springgreen4", "royalblue3", "red","orange2","springgreen2","dodgerblue","indianred","gold1"), main="% Larval Survival") #Plot with breaktime by = # of days, palette=number of treatments listed colors fontsize<-20 pCox <- ggsurvplot(sf, data=OlyLarvaeKMforR, risk.table = FALSE, pval = FALSE, conf.int = TRUE, font.main = fontSize, font.x = fontSize, font.y = fontSize, font.tickslab = fontSize, font.legend = fontSize, palette = c("springgreen4", "royalblue3", "red","orange2","springgreen2","dodgerblue","indianred","gold1"), legend = "none" ) + xlab("Time (d)") pCox$plot #add a legend, dont need. probably make one not on R legend("topright" , c("CI20-14C","CI5-14C","DB-14C","PW-14C", "CI20-20C", "CI5-20C", "DB-20C", "PW-20C"), fill=c("springgreen4", "royalblue3", "red","orange2","springgreen2","dodgerblue","indianred","gold1")) #another type of graph- will prob use this one ggsurvplot(sf, data=OlyLarvaeKMforR, conf.int=T, risk.table=F, pval=F,legend=c("right"), legend.labs=c("CI20-14C","CI5-14C","DB-14C","PW-14C", "CI20-20C", "CI5-20C", "DB-20C", "PW-20C"),legend.title="Treatment", palette = c('darkgreen', 'blue4', 'darkred', 'darkgoldenrod', '#33CC66','steelblue','red','darkgoldenrod1'), risk.table.height=.25,xlab="Time (days)", size=0.7, break.time.by = 3, break.y.by=.2, ggtheme = theme_bw() + theme( panel.grid.major.y = element_blank(), panel.grid.minor.y = element_blank(), panel.grid.major.x = element_blank(), panel.grid.minor.x = element_blank() )) #Test non parametric (logrank test) p<0.0001 chisq=4053 #report this value in paper to compare data from multuple pairwise groups #log-rank test does not make assumptions about survival distribution. Analyzes each cohort separetely. " When survival curves cross, the log-rank test should not be used because the probability of a type II error will be increased, and the test has low power." survdiff(formula=Surv(day,dead)~Treatment +Location, data=OlyLarvaeKMforR) #emperica likelyhood-optimize power #p-value <0.0001 surv_pvalue(sf) #cox model sample code without interaction cox1<-coxph(KMsurv~Treatment+Location, data=OlyLarvaeKMforR) summary(cox1) #cox model sample code with interaction, this is the model for the main analysis cox<-coxph(KMsurv~Treatment*Location, data=OlyLarvaeKMforR) cox##<here results!!! summary(cox) #38400 larvae, 25506 death, 12894 censored #Looking at exp(coef)-- for example the Hazard Ratio of 20C is 0.586, this means that each additional #day is associated with a 0.586 fold increse in the hazard death when compared to 14C, and its 95% confidence #interval is (0.56,0.61). I think..Since this confidence interval is <1 #it indicates a decrease in the hazard survival compared to 14C, and there is a significant association #between days and temperature (p<0.0001) anova(cox) cox.zph(cox) plot(cox.zph(cox)) #A hazard ratio of 1 indicates no effect #A hazard ratio > 1 indicates an increase in the hazard as the covariate rises- It gets to death faster than the control #A hazard ratio < 1 indicates a decrease in the hazard as the covariate rises- it is slower go get to the event (death) than the cotnrol ggforest(cox, data=OlyLarvaeKMforR) #time-dependent covariate to fix proportional hazard assumption #A Cox model with time-dependent covariate would compare the risk of an event between transplant and nontransplant at each event time, but would re-evaluate #which risk group each person belonged in based on whether #they'd had a transplant by that time #model with temp only coxTemp<-coxph(KMsurv~Treatment, data=OlyLarvaeKMforR) ggforest(coxTemp, data=OlyLarvaeKMforR) #model with locaiton only coxLocation<-coxph(KMsurv~Location, data=OlyLarvaeKMforR) ggforest(coxLocation, data=OlyLarvaeKMforR) #model with non categorial veraibles cox.number<-coxph(KMsurv~Temp+LocationNumber+Temp*LocationNumber, data=OlyLarvaeKMforR) cox.number summary(cox.number) ggforest(cox.number) ############time varying coefficients #show time points in time at which an individual died cut.points <- unique(OlyLarvaeKMforR$day[OlyLarvaeKMforR$dead == 1]) #duplicate 4 line per individual, times 0-1, 1-7, 7-10, 10-13 =time0 and time SURV2 <- survSplit(data = OlyLarvaeKMforR, cut = cut.points, end = "day", start = "day0", event = "dead") View(SURV2) cut.points #run the cox model on orginal data- estimates one treatment male-21yrs model.1 <- coxph(Surv(day, dead) ~ Treatment+Location+Treatment:Location, data = OlyLarvaeKMforR) model.1 summary(model.1) #Schoenfeld's global test for the violation of proportional assumption-- Grambsch PM, Therneau TM. Proportional hazards tests # diagnostics based on weighted residuals. Biometrika 1994;81:515-26 zph<-cox.zph(model.1) zph #results of cox.zph show there is significant deviation from the proportional hazards assumption for the variable covs <- data.frame(Location = "CI20", Treatment = "14C") covs summary(survfit(model.1, newdata = covs, type = "aalen")) #output gives us probability of survival for CI20 14C for each day, i.e. a larvae has a .708 chance of survivind to day 4, but 0.163 chance of surviving to day 15 cox.zph(model.1) #The result of zph shows that there is significant deviation from the proportional hazards assumption for all veriables ggforest(model.1, SURV2) plot(cox.zph(model.1)) ####Percent mortality CI2020C<-subset(OlyLarvaeKMforR, TreatmentLocation=="20CCI20") CI2020Cend<-sum(CI2020C$Status) CI2020Cend CI2020Ctot<-length(CI2020C$Status) CI2020Ctot CI2020Cend/CI2020Ctot CI2014C<-subset(OlyLarvaeKMforR, TreatmentLocation=="14CCI20") CI2014Cend<-sum(CI2014C$Status) CI2014Cend CI2014Ctot<-length(CI2014C$Status) CI2014Ctot CI2014Cend/CI2014Ctot CI520C<-subset(OlyLarvaeKMforR, TreatmentLocation=="20CCI5") CI520Cend<-sum(CI520C$Status) CI520Cend CI520Ctot<-length(CI520C$Status) CI520Ctot CI520Cend/CI520C CI514C<-subset(OlyLarvaeKMforR, TreatmentLocation=="14CCI5") CI514Cend<-sum(CI514C$Status) CI514Cend CI514Ctot<-length(CI514C$Status) CI514Ctot CI514Cend/CI514Ctot DB520C<-subset(OlyLarvaeKMforR, TreatmentLocation=="20CDB") DB520Cend<-sum(DB520C$Status) DB520Cend DB520Ctot<-length(DB520C$Status) DB520Ctot DB520Cend/DB520Ctot DB514C<-subset(OlyLarvaeKMforR, TreatmentLocation=="14CDB") DB514Cend<-sum(DB514C$Status) DB514Cend DB514Ctot<-length(DB514C$Status) DB514Ctot DB514Cend/DB514Ctot PW520C<-subset(OlyLarvaeKMforR, TreatmentLocation=="20CPW") PW520Cend<-sum(PW520C$Status) PW520Cend PW520Ctot<-length(PW520C$Status) PW520Ctot PW520Cend/PW520Ctot PW514C<-subset(OlyLarvaeKMforR, TreatmentLocation=="14CPW") PW514Cend<-sum(PW514C$Status) PW514Cend PW514Ctot<-length(PW514C$Status) PW514Ctot PW514Cend/PW514Ctot
7fb74ab947e7d703e607a228207fb4b3711a49fc
68654fffeaba279324df9493948c0b63c0b23cc6
/odds_and_ends/former/08_paleo_monthly_gen_percentile_pred.R
f8532ca3383c4781c42d5a6a1c7bc1c58d426abd
[ "MIT" ]
permissive
jstagge/weber_paleo_clim
dcb0fee723c920f90fc3ca343a8386aba427de7a
45d3f824265f37d8f9b916102240d8d145dcc2c2
refs/heads/master
2022-02-26T09:48:24.994255
2019-08-22T20:05:01
2019-08-22T20:05:01
133,690,915
1
0
null
null
null
null
UTF-8
R
false
false
19,011
r
08_paleo_monthly_gen_percentile_pred.R
# *------------------------------------------------------------------ # | PROGRAM NAME: Data Music # | FILE NAME: paleo_monthly_gen_null.R # | DATE: # | CREATED BY: Jim Stagge # *---------------------------------------------------------------- # | PURPOSE: This is a code wrapper to generate a midicsv file from data. # | The resulting file can be processed into a midi file using the program csvmidi. # | This midi file can then be played using timidity. # | Check the ToRun.txt file for detailed code # | # *------------------------------------------------------------------ # | COMMENTS: # | # | 1: # | 2: # | 3: # |*------------------------------------------------------------------ # | DATA USED: # | This is a test instance using reconstructed climate indices ENSO and PDO # | # |*------------------------------------------------------------------ # | CONTENTS: # | # | PART 1: # | PART 2: # | PART 3: # *----------------------------------------------------------------- # | UPDATES: # | # | # *------------------------------------------------------------------ ### Clear any existing data or functions. rm(list=ls()) ########################################################################### ## Set the Paths ########################################################################### ### Path for Data and Output data_path <- "../../data" output_path <- "../../output" global_path <- "../global_func" function_path <- "./functions" ### Set output location output_name <- "apr_model" weber_output_path <- file.path(output_path,"paleo_weber") write_output_path <- file.path(weber_output_path,output_name) write_figures_path <- file.path(weber_output_path, "figures") write_figures_path <- file.path(write_figures_path, output_name) dir.create(write_output_path) dir.create(write_figures_path) ########################################################################### ### Load functions ########################################################################### ### Load these functions for all code require(colorout) require(assertthat) ### Load these functions for this unique project require(ggplot2) require(monthlypaleo) require(staggefuncs) ### Load project specific functions file.sources = list.files(function_path, pattern="*.R", recursive=TRUE) sapply(file.path(function_path, file.sources),source) ### Load global functions file.sources = list.files(global_path, pattern="*.R", recursive=TRUE) sapply(file.path(global_path, file.sources),source) ########################################################################### ## Set Initial Values ########################################################################### ### Set site data site_id_list <- c("10128500") site_name_list <- c("Weber River") recons_file_name_list <- c("weber2014flow.txt") first_month_wy <- 10 ### Water Year starts on Oct 1 param_cd <- "00060" monthly_distr <- "gamma" annual_distr <- "logis" ref_period <- c(1900,2005) ### Number of PCs to consider as predictors pc_pred <- 8 ### Lags to consider lags_pred <- seq(-2,2) ########################################################################### ## Read in reconstructed flows, tree rings and climate indices ########################################################################### ### Read in PC scores pc_score_impute_res <- read.csv(file.path(file.path(weber_output_path,"pca_chronol"), "PC_Score_impute_res.csv")) pc_score_impute_std <- read.csv(file.path(file.path(weber_output_path,"pca_chronol"), "PC_Score_impute_std.csv")) ### Read in climate indices clim_ind <- read.csv(file.path(file.path(data_path,"paleo_clim_ind"), "clim_ind.csv")) ### Remove ENSO_var, this is simply a running variance calculation - not useful as a predictor clim_ind <- subset(clim_ind, select=-c(ENSO_var)) ################################################ ### Create matrix of potential predictor values ################################################# ## Cut PCs to only number in initial settings pc_cut <- seq(1,pc_pred+1) pc_score_impute_std <- pc_score_impute_std[,pc_cut] pc_score_impute_res <- pc_score_impute_res[,pc_cut] ### Create only climate index predictors pred_clim_only <- clim_ind pred_clim_only_lag <- shift_indices_df(pred_clim_only, lags=lags_pred) pred_enso_ind <- clim_ind[,seq(1,3)] pred_enso_ind_lag <- shift_indices_df(enso_ind, lags=lags_pred) ### Create concurrent predictors (same calendar year), with climate indices and first 8 PCs pred_clim_pca_impute_std_concur <- merge(clim_ind, pc_score_impute_std, by.x="Year", by.y="X", all=TRUE) pred_clim_pca_impute_res_concur <- merge(clim_ind, pc_score_impute_res, by.x="Year", by.y="X", all=TRUE) pred_enso_pca_impute_std_concur <- merge(enso_ind, pc_score_impute_std, by.x="Year", by.y="X", all=TRUE) pred_enso_pca_impute_res_concur <- merge(enso_ind, pc_score_impute_res, by.x="Year", by.y="X", all=TRUE) ### Lag the predictors pred_clim_pca_impute_std_lag <- shift_indices_df(pred_clim_pca_impute_std_concur, lags=lags_pred) pred_clim_pca_impute_res_lag <- shift_indices_df(pred_clim_pca_impute_res_concur, lags=lags_pred) pred_enso_pca_impute_std_lag <- shift_indices_df(pred_enso_pca_impute_std_concur, lags=lags_pred) pred_enso_pca_impute_res_lag <- shift_indices_df(pred_enso_pca_impute_res_concur, lags=lags_pred) ########################################################################### ### Set up a loop to run through all site_ides and Transform based on the Percentile Model ########################################################################### for (n in seq(1,length(site_id_list))) { site_id <- site_id_list[n] site_name <- site_name_list[n] recons_file_name <- recons_file_name_list[n] ########################################################################### ### Read in Flow Data ########################################################################### ### Read in observed flow and fix data type obs_file_name <- paste0(site_id,"_",param_cd,"_mon_wy.csv") flow_obs <- read.csv(file.path(weber_output_path,paste0("observed_flow/",obs_file_name))) flow_obs$date <- as.Date(flow_obs$date) #head(flow_obs) # Review data frame ### Read in reconst flows (use fread because of large header) flow_recon <- read_table_wheaders(file.path(data_path,paste0("paleo_flow_annual/",recons_file_name)), sep="\t", na.string="-9999") flow_recon <- merge(flow_recon, data.frame(age_AD=flow_obs$water_year, flow.obs.m3s=flow_obs$annual_mean), by="age_AD", all.x=TRUE) ################################################ ### Read in monthly and annual parameters to Transform Percentiles ################################################# percentile_path <- file.path(file.path(weber_output_path, "paleo_reconst"), "ap_model") monthly_param <- list(param=read.csv(file.path(percentile_path, paste0(site_id,"/",site_id,"_param_month_",monthly_distr,".csv"))), distr=monthly_distr) monthly_param$param <- monthly_param$param[,c(2,3)] annual_param <- list(param=read.csv(file.path(percentile_path, paste0(site_id,"/",site_id,"_param_annual_",annual_distr,".csv"))), distr=annual_distr) annual_param$param <- annual_param$param[,seq(1,3)] ################################################# ### Apply the Percentile Model with Lagged years (1 year previous, 1 year following) ################################################# ### Set up list of data combinations to fit ### Only use the imputed values #pred_list <- c("enso_ind", "clim_only", "enso_ind_lag", "clim_only_lag", "enso_pca_impute_std_concur", "enso_pca_impute_res_concur", "clim_pca_impute_std_concur", "clim_pca_impute_lag") pred_list <- c("enso_ind", "clim_only", "enso_pca_impute_std_concur", "enso_pca_impute_res_concur", "clim_pca_impute_std_concur", "clim_pca_impute_res_concur") data_list <- c("observ_annual", "rec_local_m3s") run_combinations <- expand.grid(predictors=pred_list, data=data_list) ### Loop through all combations, fitting, and saving for (c in seq(1,dim(run_combinations)[1])){ pred_c <- run_combinations$predictors[c] data_c <- run_combinations$data[c] if(data_c != "observ_annual"){ data_name <- as.character(paste0("annual_flow_",data_c)) } else { data_name <- as.character(data_c) } ### Fit model lag_fit <- perc_fit_pred(data=flow_obs, predictors=get(paste0("pred_",pred_c )), monthly_param, annual_param, data_name= data_name) ### Write to csv file write_location <- file.path(write_output_path, paste0(site_id,"_",output_name, "_coef_",data_c,"_",pred_c,".csv")) write.csv(lag_fit$coef, file = write_location,row.names=TRUE) write_location <- file.path(write_output_path, paste0(site_id,"_",output_name, "_alpha_lambda_",data_c,"_",pred_c,".csv")) write.csv(lag_fit$alpha_lambda, file = write_location,row.names=TRUE) } } ########################################################################### ### Set up a loop to run through all site_ides and Plot results ########################################################################### dir.create(file.path(write_figures_path,"png/"), showWarnings=FALSE) dir.create(file.path(write_figures_path,"svg/"), showWarnings=FALSE) dir.create(file.path(write_figures_path,"pdf/"), showWarnings=FALSE) for (n in seq(1,length(site_id_list))) { site_id <- site_id_list[n] site_name <- site_name_list[n] recons_file_name <- recons_file_name_list[n] ### Create table of all combinations ### Chose not to plot all the lags (too much) #pred_list <- c("clim_only","clim_only_lag","clim_pca_impute_concur", "clim_pca_impute_lag") pred_list <- c("enso_ind", "clim_only", "enso_pca_impute_std_concur", "enso_pca_impute_res_concur", "clim_pca_impute_std_concur", "clim_pca_impute_res_concur") data_list <- c("observ_annual", "rec_local_m3s") run_combinations <- expand.grid(predictors=pred_list, data=data_list) ### Loop through all combations, reading in data and saving for (c in seq(1,dim(run_combinations)[1])){ pred_c <- as.character(run_combinations$predictors[c]) data_c <- run_combinations$data[c] if(data_c != "observ_annual"){ data_name <- as.character(paste0("annual_flow_",data_c)) } else { data_name <- as.character(data_c) } ### Read in CSV file file_location <- file.path(write_output_path, paste0(site_id,"_",output_name, "_coef_",data_c,"_",pred_c,".csv")) coef_df <- read.csv(file_location) rownames(coef_df) <- as.character(coef_df$X) ### Reorganize dataframe, remove the first column, set class coef_df <- subset(coef_df, select=-c(X)) colnames(coef_df) <- seq(1,12) coef_df <- data.frame(coef_df) ### Create plot of annual drivers predictor_levels <- c("annual_norm", "annual_norm_neg_1year", "annual_norm_pos_1year") predictor_labels <- c("Concurrent Water Year\nStd Normal", "Previous (-1) Water Year\nStd Normal", "Next (+1) Water Year\nStd Normal") p <- norm_coef_plot(coef_df, predictor_levels=predictor_levels, predictor_labels=predictor_labels) ### Save annual drivers ggsave(paste0(file.path(write_figures_path,"png/"), site_id, "_percent_pred_coef_", data_name,"_",pred_c,"_annual.png"), p, width=6, height=4, dpi=600) ggsave(paste0(file.path(write_figures_path,"svg/"), site_id, "_percent_pred_coef_", data_name,"_",pred_c,"_annual.svg"), p, width=6, height=4) ggsave(paste0(file.path(write_figures_path,"pdf/"), site_id, "_percent_pred_coef_", data_name,"_",pred_c,"_annual.pdf"), p, width=6, height=4) #### Add a combination of 2 ENSO methods, not needed #coef_df_enso_comb <- coef_df[rownames(coef_df) == "ENSO",] + coef_df[rownames(coef_df) == "ENSO_short",] #rownames(coef_df_enso_comb) <- "ENSO_comb" #coef_df <- rbind(coef_df, coef_df_enso_comb) ### Create plot of climate drivers predictor_levels <- c("ENSO", "ENSO_short", "PDO") predictor_labels <- c("ENSO (NADA)", "ENSO (Pacific Proxy)", "PDO") p <- norm_coef_plot(coef_df, predictor_levels=predictor_levels, predictor_labels=predictor_labels) ### Reset the color scheme p <- p + scale_colour_brewer(name="Predictor", type="qual", palette = "Accent") ### Save annual drivers ggsave(paste0(file.path(write_figures_path,"png/"), site_id, "_percent_pred_coef_", data_name,"_",pred_c,"_clim_ind.png"), p, width=6, height=4, dpi=600) ggsave(paste0(file.path(write_figures_path,"svg/"), site_id, "_percent_pred_coef_", data_name,"_",pred_c,"_clim_ind.svg"), p, width=6, height=4) ggsave(paste0(file.path(write_figures_path,"pdf/"), site_id, "_percent_pred_coef_", data_name,"_",pred_c,"_clim_ind.pdf"), p, width=6, height=4) ### If it includes pca, create plots if (grepl("pca",pred_c)) { ### Create a plot of PC coefficients predictor_levels <- paste0("PC",seq(1,8)) predictor_labels <- predictor_levels p <- norm_coef_plot(coef_df, predictor_levels=predictor_levels, predictor_labels=predictor_labels) ### Reset color scale p <- p + scale_colour_brewer(name="Predictor", type="qual", palette = "Set2") ### Save annual drivers ggsave(paste0(file.path(write_figures_path,"png/"), site_id, "_percent_pred_coef_", data_name,"_",pred_c,"_pcs.png"), p, width=6, height=4, dpi=600) ggsave(paste0(file.path(write_figures_path,"svg/"), site_id, "_percent_pred_coef_", data_name,"_",pred_c,"_pcs.svg"), p, width=6, height=4) ggsave(paste0(file.path(write_figures_path,"pdf/"), site_id, "_percent_pred_coef_", data_name,"_",pred_c,"_pcs.pdf"), p, width=6, height=4) } } } ########################################################################### ### Set up a loop to run through all site_ides and Plot results ########################################################################### for (n in seq(1,length(site_id_list))) { site_id <- site_id_list[n] site_name <- site_name_list[n] recons_file_name <- recons_file_name_list[n] ### Create table of all combinations ### Chose not to plot all the lags (too much) pred_list <- c("clim_only_lag","clim_pca_impute_lag") if (site_id == "10109001") { data_list <- c("observ_annual", "rec_local_m3s", "rec_region_m3s") } else { data_list <- c("observ_annual", "rec_m3s") } run_combinations <- expand.grid(predictors=pred_list, data=data_list) ### Loop through all combations, reading in data and saving for (c in seq(1,dim(run_combinations)[1])){ pred_c <- as.character(run_combinations$predictors[c]) data_c <- run_combinations$data[c] if(data_c != "observ_annual"){ data_name <- as.character(paste0("annual_flow_",data_c)) } else { data_name <- as.character(data_c) } ### Read in CSV file file_location <- file.path(write_output_path, paste0(site_id,"_",output_name, "_coef_",data_c,"_",pred_c,".csv")) coef_df <- read.csv(file_location) rownames(coef_df) <- as.character(coef_df$X) ### Reorganize dataframe, remove the first column, set class coef_df <- subset(coef_df, select=-c(X)) colnames(coef_df) <- seq(1,12) coef_df <- data.frame(coef_df) ### Create plot of annual drivers predictor_levels <- c("annual_norm", "annual_norm_neg_1year", "annual_norm_pos_1year") predictor_labels <- c("Concurrent Water Year\nStd Normal", "Previous (-1) Water Year\nStd Normal", "Next (+1) Water Year\nStd Normal") p <- norm_coef_plot(coef_df, predictor_levels=predictor_levels, predictor_labels=predictor_labels) ### Save annual drivers ggsave(paste0(file.path(write_figures_path,"png/"), site_id, "_percent_pred_coef_", data_name,"_",pred_c,"_annual.png"), p, width=6, height=4, dpi=600) ggsave(paste0(file.path(write_figures_path,"svg/"), site_id, "_percent_pred_coef_", data_name,"_",pred_c,"_annual.svg"), p, width=6, height=4) ggsave(paste0(file.path(write_figures_path,"pdf/"), site_id, "_percent_pred_coef_", data_name,"_",pred_c,"_annual.pdf"), p, width=6, height=4) #### Add a combination of 2 ENSO methods, not needed #coef_df_enso_comb <- coef_df[rownames(coef_df) == "ENSO",] + coef_df[rownames(coef_df) == "ENSO_short",] #rownames(coef_df_enso_comb) <- "ENSO_comb" #coef_df <- rbind(coef_df, coef_df_enso_comb) ### Create plot of climate drivers predictor_levels <- c("ENSO_0", "ENSO_short_0", "PDO_0") predictor_labels <- c("ENSO (NADA)", "ENSO (Pacific Proxy)", "PDO") p <- norm_coef_plot(coef_df, predictor_levels=predictor_levels, predictor_labels=predictor_labels) ### Reset the color scheme p <- p + scale_colour_brewer(name="Predictor", type="qual", palette = "Accent") ### Save annual drivers ggsave(paste0(file.path(write_figures_path,"png/"), site_id, "_percent_pred_coef_", data_name,"_",pred_c,"_clim_ind.png"), p, width=6, height=4, dpi=600) ggsave(paste0(file.path(write_figures_path,"svg/"), site_id, "_percent_pred_coef_", data_name,"_",pred_c,"_clim_ind.svg"), p, width=6, height=4) ggsave(paste0(file.path(write_figures_path,"pdf/"), site_id, "_percent_pred_coef_", data_name,"_",pred_c,"_clim_ind.pdf"), p, width=6, height=4) ### Create plots of PCs at different lags lag_names <- c("-2", "-1", "0", "1", "2") lag_numbers <- c(".2", ".1", "0", "1", "2") ### If it includes pca, create plots if (grepl("pca",pred_c)) { for (k in seq(1,length(lag_numbers))) { ### Create a plot of PC coefficients predictor_labels <- paste0("PC",seq(1,8)) predictor_levels <- paste0(predictor_labels, "_",lag_numbers[k]) predictor_labels <- paste0(predictor_labels, " Lag ", lag_names[k]) p <- norm_coef_plot(coef_df, predictor_levels=predictor_levels, predictor_labels=predictor_labels) ### Reset color scale p <- p + scale_colour_brewer(name="Predictor", type="qual", palette = "Set2") p <- p + coord_cartesian(ylim=c(-0.2,0.2)) # ### Save annual drivers ggsave(paste0(file.path(write_figures_path,"png/"), site_id, "_percent_pred_coef_", data_name,"_",pred_c,"_pcs_lag_",lag_names[k],".png"), p, width=6, height=4, dpi=600) ggsave(paste0(file.path(write_figures_path,"svg/"), site_id, "_percent_pred_coef_", data_name,"_",pred_c,"_pcs_lag_",lag_names[k],".svg"), p, width=6, height=4) ggsave(paste0(file.path(write_figures_path,"pdf/"), site_id, "_percent_pred_coef_", data_name,"_",pred_c,"_pcs_lag_",lag_names[k],".pdf"), p, width=6, height=4) } ### Extract PC names coef_df_names <- rownames(coef_df) coef_df_pc <- substr(coef_df_names,1,2) == "PC" coef_df_pc[[1]] <- TRUE coef_df_pc <- coef_df[coef_df_pc,] coef_df_names <- rownames(coef_df_pc) for (k in seq(1,8)) { ### Subset to each PC pc_test <- substr(coef_df_names,1,3) == paste0("PC", k) pc_test[[1]] <- TRUE pc_subset <- coef_df_pc[pc_test,] ### Create plot of climate drivers predictor_levels <- rownames(pc_subset) predictor_levels <- predictor_levels[seq(2,length(predictor_levels))] predictor_labels <- c("Lag -2", "Lag -1", "Concur", "Lag +1", "Lag +2") p <- norm_coef_plot(pc_subset, predictor_levels=predictor_levels, predictor_labels=predictor_labels) ### Save plot ggsave(paste0(file.path(write_figures_path,"png/"), site_id, "_percent_pred_coef_", data_name,"_",pred_c,"_pc",k,"_lag",".png"), p, width=6, height=4, dpi=600) ggsave(paste0(file.path(write_figures_path,"svg/"), site_id, "_percent_pred_coef_", data_name,"_",pred_c,"_pc",k,"_lag",".svg"), p, width=6, height=4) ggsave(paste0(file.path(write_figures_path,"pdf/"), site_id, "_percent_pred_coef_", data_name,"_",pred_c,"_pc",k,"_lag",".pdf"), p, width=6, height=4) } } } }
d8657ef4c06d2bb9f7a3cea86b2692a1dd8a4f55
bad164cec8333f690f187f53643aaa9e9e70061c
/counts_forloop.R
6d9b81fc55f28f3fd09329628ff388dd917f5b8c
[]
no_license
cocomushroom/meta_commu
7151c5d48164d55832644a4323757f5e1cf6abe0
568c2edc5049fdc694fa77e0dc9137ca2fd00ac9
refs/heads/master
2021-01-10T13:05:06.661282
2017-03-02T19:42:48
2017-03-02T19:42:48
55,309,772
0
0
null
null
null
null
UTF-8
R
false
false
1,988
r
counts_forloop.R
setwd("/Users/kc178/Downloads/all_GB+customized_silva_wLRORLR3_1208/cutfirst") list_tab <- dir(pattern = "*IdxStats.tabular") #make sure the files are read in the correct order list_tab <- list_tab[c(3,2,1,6,5,4,9,8,7)] ldf <- list() present <- list() for (k in 1:length(list_tab)) { ldf[[k]] <- read.delim(list_tab[k], header=FALSE) names(ldf[[k]]) <- c("seqID", "length", "mapped", "unmapped") } for (a in 1:length(ldf)) { data0 <- ldf[[a]] present[[a]] <- data0[data0$mapped>0, c(1,3)] present[[a]]$seqID <- as.character(present[[a]]$seqID) } #ll<-vector(length=9, mode="list") #combine count from all condition/replicate allcount <- present[[1]][,c(1,2)] #allcount <- present1[,c(1,2)] # this conmmand can make sure exactly how many "0" are assigned; otherwise in some case only 1 "0" is assigned #note that "$new column name" is enough to add a new column for (i in 3:10) { allcount[,i] <- rep(0, NROW(allcount)) } names(allcount) <- c("seqID", "t1", "m1", "b1", "t2", "m2", "b2", "t3", "m3", "b3") numCol <- ncol(allcount) numColZero <- rep(0, numCol) for (q in 2:length(present)) { for (i in 1:NROW(present[[q]])) { index<- present[[q]]$seqID[i]==allcount$seqID if( any(index)){ allcount[index, 1+q] <- present[[q]]$mapped[i] }else { allcount <- rbind(allcount, numColZero) rownumber <- NROW(allcount) allcount[rownumber, 1] <- present[[q]]$seqID[i] allcount[rownumber, q+1] <- present[[q]]$mapped[i] # temp <- c(present2$seqID[i], 0, present2$mapped[i]) } #this syntax will only return "TRUE" } } write.csv(allcount, row.names = FALSE, "allcount.csv") #remove contaminated sequences checked by BLAST & MEGAN not_fungi <- read.delim("/Users/kc178/Documents/HiSeq1269/community_RDP_NC_J_CF/velvet91/vel91_c95_meganNonfungi", header=FALSE) not_fungi <- as.character(not_fungi$V1) remove <- allcount$seqID %in% not_fungi write.csv(allcount[!remove,], row.names = FALSE, "allcount_removenonfungi.csv")
d037a95f33fc722ff803f420ab01e161ac2ac604
63d97198709f3368d1c6d36739442efa699fe61d
/advanced algorithm/round3/k-server-analysis-master/data/tests/case184.rd
2d7b27ce86c03d418cbf45a45be8f3b2de6a842e
[]
no_license
tawlas/master_2_school_projects
f6138d5ade91e924454b93dd8f4902ca5db6fd3c
03ce4847155432053d7883f3b5c2debe9fbe1f5f
refs/heads/master
2023-04-16T15:25:09.640859
2021-04-21T03:11:04
2021-04-21T03:11:04
360,009,035
0
0
null
null
null
null
UTF-8
R
false
false
6,265
rd
case184.rd
36 1 [1, 22, 8] 14 14 14 18 18 2 [1, 23, 8] 1 2 16 2 20 3 [1, 22, 8] 1 2 18 2 22 4 [1, 23, 8] 1 2 20 2 24 5 [1, 22, 8] 1 2 22 2 26 6 [1, 23, 8] 1 2 24 2 28 7 [1, 22, 8] 1 2 26 2 30 8 [1, 23, 8] 1 2 28 2 32 9 [1, 22, 8] 1 2 30 2 34 10 [1, 23, 8] 1 2 32 2 36 11 [1, 22, 8] 1 2 34 2 38 12 [1, 23, 8] 1 2 36 2 40 13 [1, 22, 8] 1 2 38 2 42 14 [23, 22, 8] 14 2 40 2 44 15 [23, 22, 33] 11 11 51 18 62 16 [23, 22, 34] 1 2 53 2 64 17 [23, 22, 33] 1 2 55 2 66 18 [23, 22, 34] 1 2 57 2 68 19 [23, 22, 33] 1 2 59 2 70 20 [23, 22, 34] 1 2 61 2 72 21 [23, 22, 33] 1 2 63 2 74 22 [23, 22, 34] 1 2 65 2 76 23 [23, 22, 33] 1 2 67 2 78 24 [23, 22, 34] 1 2 69 2 80 25 [23, 22, 33] 1 2 71 2 82 26 [23, 22, 34] 1 2 73 2 84 27 [23, 22, 33] 1 2 75 2 86 28 [23, 22, 34] 1 2 77 2 88 29 [23, 22, 33] 1 2 79 2 90 30 [23, 22, 34] 1 2 81 2 92 31 [23, 22, 33] 1 2 83 2 94 32 [23, 22, 34] 1 2 85 2 96 33 [23, 22, 33] 1 2 87 2 98 34 [23, 22, 34] 1 2 89 2 100 35 [33, 22, 34] 10 1 90 1 101 36 [33, 10, 34] 12 24 114 24 125 37 [33, 11, 34] 1 2 116 2 127 38 [33, 10, 34] 1 2 118 2 129 39 [33, 11, 34] 1 2 120 2 131 40 [33, 10, 34] 1 2 122 2 133 41 [33, 11, 34] 1 2 124 2 135 42 [33, 10, 34] 1 2 126 2 137 43 [33, 11, 34] 1 2 128 2 139 44 [33, 10, 34] 1 2 130 2 141 45 [33, 11, 34] 1 2 132 2 143 46 [33, 10, 34] 1 2 134 2 145 47 [33, 11, 34] 1 2 136 2 147 48 [33, 10, 34] 1 2 138 2 149 49 [33, 11, 34] 1 2 140 2 151 50 [33, 10, 34] 1 2 142 2 153 51 [33, 11, 34] 1 2 144 2 155 52 [33, 10, 34] 1 2 146 2 157 53 [33, 11, 34] 1 2 148 2 159 54 [33, 10, 34] 1 2 150 2 161 55 [33, 11, 34] 1 2 152 2 163 56 [33, 10, 34] 1 2 154 2 165 57 [33, 11, 34] 1 2 156 2 167 58 [33, 10, 34] 1 2 158 2 169 59 [33, 11, 34] 1 2 160 2 171 60 [33, 11, 10] 12 0 160 0 171 61 [22, 11, 10] 11 14 174 14 185 62 [23, 11, 10] 1 2 176 2 187 63 [22, 11, 10] 1 2 178 2 189 64 [23, 11, 10] 1 2 180 2 191 65 [22, 11, 10] 1 2 182 2 193 66 [23, 11, 10] 1 2 184 2 195 67 [22, 11, 10] 1 2 186 2 197 68 [23, 11, 10] 1 2 188 2 199 69 [22, 11, 10] 1 2 190 2 201 70 [23, 11, 10] 1 2 192 2 203 71 [22, 11, 10] 1 2 194 2 205 72 [23, 11, 10] 1 2 196 2 207 73 [22, 11, 10] 1 2 198 2 209 74 [23, 11, 10] 1 2 200 2 211 75 [22, 11, 10] 1 2 202 2 213 76 [23, 11, 10] 1 2 204 2 215 77 [22, 11, 10] 1 2 206 2 217 78 [23, 11, 10] 1 2 208 2 219 79 [22, 11, 10] 1 2 210 2 221 80 [23, 11, 10] 1 2 212 2 223 81 [22, 11, 10] 1 2 214 2 225 82 [23, 11, 10] 1 2 216 2 227 83 [22, 11, 10] 1 2 218 2 229 84 [23, 11, 10] 1 2 220 2 231 85 [23, 22, 10] 11 0 220 0 231 86 [34, 22, 10] 11 22 242 22 253 87 [35, 22, 10] 1 2 244 2 255 88 [34, 22, 10] 1 2 246 2 257 89 [35, 22, 10] 1 2 248 2 259 90 [34, 22, 10] 1 2 250 2 261 91 [35, 22, 10] 1 2 252 2 263 92 [34, 22, 10] 1 2 254 2 265 93 [35, 22, 10] 1 2 256 2 267 94 [34, 22, 10] 1 2 258 2 269 95 [35, 22, 10] 1 2 260 2 271 96 [34, 22, 10] 1 2 262 2 273 97 [35, 22, 10] 1 2 264 2 275 98 [34, 22, 10] 1 2 266 2 277 99 [35, 22, 10] 1 2 268 2 279 100 [34, 22, 10] 1 2 270 2 281 101 [35, 22, 10] 1 2 272 2 283 102 [34, 22, 10] 1 2 274 2 285 103 [35, 22, 10] 1 2 276 2 287 104 [34, 22, 10] 1 2 278 2 289 105 [35, 22, 10] 1 2 280 2 291 106 [34, 22, 10] 1 2 282 2 293 107 [35, 22, 10] 1 2 284 2 295 108 [34, 22, 10] 1 2 286 2 297 109 [34, 22, 35] 11 0 286 2 299 110 [34, 10, 35] 12 14 300 14 313 111 [34, 11, 35] 1 2 302 2 315 112 [34, 10, 35] 1 2 304 2 317 113 [34, 11, 35] 1 2 306 2 319 114 [34, 10, 35] 1 2 308 2 321 115 [34, 11, 35] 1 2 310 2 323 116 [34, 10, 35] 1 2 312 2 325 117 [34, 11, 35] 1 2 314 2 327 118 [34, 10, 35] 1 2 316 2 329 119 [34, 11, 35] 1 2 318 2 331 120 [34, 10, 35] 1 2 320 2 333 121 [34, 11, 35] 1 2 322 2 335 122 [34, 10, 35] 1 2 324 2 337 123 [34, 11, 35] 1 2 326 2 339 124 [34, 10, 35] 1 2 328 2 341 125 [34, 11, 35] 1 2 330 2 343 126 [34, 10, 35] 1 2 332 2 345 127 [34, 11, 35] 1 2 334 2 347 128 [34, 10, 35] 1 2 336 2 349 129 [34, 11, 35] 1 2 338 2 351 130 [34, 10, 35] 1 2 340 2 353 131 [34, 11, 35] 1 2 342 2 355 132 [34, 10, 35] 1 2 344 2 357 133 [34, 11, 35] 1 2 346 2 359 134 [34, 11, 10] 11 0 346 0 359 135 [22, 11, 10] 12 22 368 22 381 136 [23, 11, 10] 1 2 370 2 383 137 [22, 11, 10] 1 2 372 2 385 138 [23, 11, 10] 1 2 374 2 387 139 [22, 11, 10] 1 2 376 2 389 140 [23, 11, 10] 1 2 378 2 391 141 [22, 11, 10] 1 2 380 2 393 142 [23, 11, 10] 1 2 382 2 395 143 [22, 11, 10] 1 2 384 2 397 144 [23, 11, 10] 1 2 386 2 399 145 [22, 11, 10] 1 2 388 2 401 146 [23, 11, 10] 1 2 390 2 403 147 [22, 11, 10] 1 2 392 2 405 148 [23, 11, 10] 1 2 394 2 407 149 [22, 11, 10] 1 2 396 2 409 150 [23, 11, 10] 1 2 398 2 411 151 [22, 11, 10] 1 2 400 2 413 152 [23, 11, 10] 1 2 402 2 415 153 [22, 11, 10] 1 2 404 2 417 154 [23, 11, 10] 1 2 406 2 419 155 [22, 11, 10] 1 2 408 2 421 156 [23, 11, 10] 1 2 410 2 423 157 [22, 11, 10] 1 2 412 2 425 158 [23, 11, 10] 1 2 414 2 427 159 [23, 22, 10] 11 0 414 0 427 160 [23, 22, 34] 12 14 428 14 441 161 [23, 22, 35] 1 2 430 2 443 162 [23, 22, 34] 1 2 432 2 445 163 [23, 22, 35] 1 2 434 2 447 164 [23, 22, 34] 1 2 436 2 449 165 [23, 22, 35] 1 2 438 2 451 166 [23, 22, 34] 1 2 440 2 453 167 [23, 22, 35] 1 2 442 2 455 168 [23, 22, 34] 1 2 444 2 457 169 [23, 22, 35] 1 2 446 2 459 170 [23, 22, 34] 1 2 448 2 461 171 [23, 22, 35] 1 2 450 2 463 172 [23, 22, 34] 1 2 452 2 465 173 [23, 22, 35] 1 2 454 2 467 174 [23, 22, 34] 1 2 456 2 469 175 [23, 22, 35] 1 2 458 2 471 176 [23, 22, 34] 1 2 460 2 473 177 [23, 22, 35] 1 2 462 2 475 178 [23, 22, 34] 1 2 464 2 477 179 [23, 22, 35] 1 2 466 2 479 180 [23, 22, 34] 1 2 468 2 481 181 [23, 22, 35] 1 2 470 2 483 182 [34, 22, 35] 11 2 472 2 485 183 [34, 10, 35] 12 22 494 22 507 184 [34, 11, 35] 1 2 496 2 509 185 [34, 10, 35] 1 2 498 2 511 186 [34, 11, 35] 1 2 500 2 513 187 [34, 10, 35] 1 2 502 2 515 188 [34, 11, 35] 1 2 504 2 517 189 [34, 10, 35] 1 2 506 2 519 190 [34, 11, 35] 1 2 508 2 521 191 [34, 10, 35] 1 2 510 2 523 192 [34, 11, 35] 1 2 512 2 525 193 [34, 10, 35] 1 2 514 2 527 194 [34, 11, 35] 1 2 516 2 529 195 [34, 10, 35] 1 2 518 2 531 196 [34, 11, 35] 1 2 520 2 533 197 [34, 10, 35] 1 2 522 2 535 198 [34, 11, 35] 1 2 524 2 537 199 [34, 10, 35] 1 2 526 2 539 200 [34, 11, 35] 1 2 528 2 541 201 [34, 10, 35] 1 2 530 2 543 202 [34, 11, 35] 1 2 532 2 545 203 [34, 10, 35] 1 2 534 2 547 204 [34, 11, 35] 1 2 536 2 549 205 [34, 10, 35] 1 2 538 2 551 206 [34, 11, 35] 1 2 540 2 553 207 [34, 11, 10] 11 0 540 0 553 540 553 415
2f26db8310aa3ef7627ac37330322f5d02813db0
1e8dd86a73b6a8d678f94933cf1cfc9e453cb2ae
/SurveyQs/ui.R
d61d52e71954657e1224c9be999dc7612627cbec
[]
no_license
aclheexn/myrepo
4b3870ebd22481b7f0450b4b9a1acdf0c2afea34
5193994a56d9cbdffb0009472b6fcf46171f1060
refs/heads/master
2021-01-22T08:48:51.442258
2017-06-05T21:34:59
2017-06-05T21:34:59
92,636,372
0
0
null
null
null
null
UTF-8
R
false
false
2,968
r
ui.R
# # This is the user-interface definition of a Shiny web application. You can # run the application by clicking 'Run App' above. # # Find out more about building applications with Shiny here: # # http://shiny.rstudio.com/ # # input a class code # Get classes or everybody's data # Collecting, saving, Download # Number of responses per quesiton # Question bank of 10 then giving options to add another question # Age Gender Major <-- Important Qs(Need 20. Get info Qs from other groups) library(shinydashboard) library(shiny) # Define UI for application that draws a histogram shinyUI(fluidPage( # Application title titlePanel("Survey Data"), numericInput("code", "Class Code", value = 000), # Sidebar with a slider input for number of bins sidebarLayout( sidebarPanel( numericInput("score", "Input your SAT Math Score(To the nearest 25)", min = 0, max = 800, step = 25, value = 0), sliderInput("hours", "Input how many hours you spend on the internet", min = 0, max = 12, value = 0, step = 0.25), textInput(inputId = "text", label = "Name", value = "None"), selectInput(inputId = "height", label = "Input Your Height(Inches)", choices = seq(48, 78)), sliderInput("age", "What is your age", min = 0, max = 100, value = 0), selectInput("major", "What college are you in", choices = c("Engineering", "Science", "Agricultural Sciences", "Arts & Architecture", "Communications", "Earth & Mineral Sciences", "Education", "Health & Human Development", "IST", "Liberal Arts", "DUS", "Business")), radioButtons("gender", "Gender", choices = c("Female", "Male")), # actionButton("folder", label = "Create Folder"), actionButton("save", label = "Save"), actionButton("update", label = "Update Table"), actionButton("clear", label = "Clear Table"), actionButton("show", label = "Show All Data"), actionButton("show2", label = "Show Class Data"), helpText(textOutput("Updated"), style = "color:red"), br(), downloadButton("downloadData", "Download All Existing Data") ), # Show a plot of the generated distribution mainPanel( verbatimTextOutput("table"), tableOutput("tote") ) ) ))
d960ef09ffafd033eb404510a8fabde05afb6d7b
002929791137054e4f3557cd1411a65ef7cad74b
/tests/testthat/test_getProbandPedigree.R
9a273523d3e93d8fcf0f78091789c5daad94ae85
[ "MIT" ]
permissive
jhagberg/nprcgenekeepr
42b453e3d7b25607b5f39fe70cd2f47bda1e4b82
41a57f65f7084eccd8f73be75da431f094688c7b
refs/heads/master
2023-03-04T07:57:40.896714
2023-02-27T09:43:07
2023-02-27T09:43:07
301,739,629
0
0
NOASSERTION
2023-02-27T09:43:08
2020-10-06T13:40:28
null
UTF-8
R
false
false
926
r
test_getProbandPedigree.R
#' Copyright(c) 2017-2020 R. Mark Sharp #' This file is part of nprcgenekeepr context("getProbandPedigree") library(testthat) library(stringi) data("lacy1989Ped") ped <- lacy1989Ped test_that("getProbandPedigree returns the correct pedigree", { expect_true(all(getProbandPedigree(probands = c("A", "B"), ped)$id %in% c("A", "B"))) expect_true(all(getProbandPedigree(probands = c("A", "B", "E"), ped)$id %in% c("A", "B", "E"))) expect_true(all(getProbandPedigree(probands = c("F"), ped)$id %in% c("A", "B", "D", "E", "F"))) expect_true(all(c("A", "B", "D", "E", "F") %in% getProbandPedigree(probands = c("F"), ped)$id)) expect_true(all(getProbandPedigree(probands = c("D"), ped)$id %in% c("A", "B", "D"))) expect_true(all(c("A", "B", "D") %in% getProbandPedigree(probands = c("D"), ped)$id)) })
9f677b520e6b99620ebf278a9ae3b657585f9919
6f52523561fee8f1244d1cc2be3abf4124352e8a
/plot2.R
ff4234de200d9d1fa941391855a2267424cc3a4b
[]
no_license
ishaanagw/ExData_Plotting1
6584148e1e98088d14ef641c3ca216c1c3ef62af
5eeea11ff0bdaf626192b555a96883caebcd49c9
refs/heads/master
2022-09-01T22:24:02.404093
2020-05-24T08:30:29
2020-05-24T08:30:29
266,476,688
0
0
null
2020-05-24T05:33:01
2020-05-24T05:33:00
null
UTF-8
R
false
false
1,700
r
plot2.R
## This part of code is common to all the plots #======================================================================== ## Reading the data ## calculating memory required for the data ## memory for a data set = number of rows* number of columns* 8 bytes memory_bytes <- 2075259*9*8 memory_mb <- memory_bytes/10^6 cat("The memory required to store the data set is: ",memory_mb,"mb") ##loading the full data data <- read.table("household_power_consumption.txt",sep = ";",na.strings = "?",header = TRUE) ##Saving the Date in the data set as Date data$Date <- as.Date(data$Date,format = "%d/%m/%Y") ## subsetting the data based on the dates mentioned in the project data_req <- subset(data,Date == "2007-02-01"| Date == "2007-02-02") ##Merging the Date and time column of the new data set to a new column called date_time data_req$date_time <- paste(data_req$Date,data_req$Time) data_req$date_time <- as.character(data_req$date_time) ## Changing the Time in the data set as POSXlt format data_req$date_time <- as.POSIXlt(data_req$date_time) #================================================================= ##Plot 2 ## The plot is a line plot with the x axis as the time of the day for each day ## and the y axis is the Global Active Power par(mfrow = c(1,1)) with(data_req,plot(date_time,Global_active_power,type = "l",ylab = "Global Active Power (killowatts)",xlab = "")) ## copying the plot to a png file with height and width 480 using the dev.copy function dev.copy(png,"plot2.png",width = 480,height = 480) ## switching off the currently active file device dev.off()
9e8af75290ae33090656b62b448b9979ad1db5cb
523090931e3508b00eb5d7b32986ae99a219c4a3
/server.R
3c7610c544c259057ae3eff687d8a43651bafbc2
[]
no_license
PeiWeiChi/Shiny-Application-and-Reproducible-Pitch
a5f69da61bde2e47a10fc319448f2805ecbb98f3
45045a1f3d217711c8e8992734c351a2f13be718
refs/heads/master
2021-05-08T14:44:00.428075
2018-02-04T03:25:29
2018-02-04T03:25:29
120,096,809
0
0
null
null
null
null
UTF-8
R
false
false
746
r
server.R
library(shiny) # Define server logic required to draw a histogram shinyServer(function(input, output) { output$dtext <- renderText({ n <- input$myMonth y<-as.vector(window(AirPassengers,n,end = c(n,12))) word <- paste0("Yearly total passengers:", sum(y)) print( word) }) output$distPlot <- renderPlot({ n <- input$myMonth y<-as.vector(window(AirPassengers,n,end = c(n,12))) x <- c(1:12) mydata<- cbind(x,y) # draw the histogram with the specified number of bins plot(mydata,type="b",xlab="Month",ylab="number of passengers",col="blue") points(mydata,pch=1,col="red") }) })
89fa15b20686d76e3f7e87f23b220338fa0cf14f
0bb0975ad2c2fd6c3afa41908a59ac7615082aa8
/Rjunk.R
ec065663fa777f427a8ada714c2efc21b42cd669
[]
no_license
CoppellMustang/6306_BLT9.5
c852aa9aedfdef178050a7ee98d1ec2f3455a229
d246c9e5da8db398c471fb72ca60667eb6ce70ab
refs/heads/master
2021-01-20T19:59:45.456670
2016-07-20T17:19:50
2016-07-20T17:19:50
63,285,082
0
0
null
null
null
null
UTF-8
R
false
false
718
r
Rjunk.R
install.packages("tseries") library("tseries") SNPdata <- get.hist.quote('^gspc',quote="Close") length(SNPdata) SNPret <- log(lag(SNPdata)) - log(SNPdata) length(SNPret) SNPvol <- sd(SNPret) * sqrt(250) *100 Vol <- function(d, logrets){ var = 0 lam = 0 varlist <- c() for (r in logrets){ lam = lam * (1 - 1/d) +1 var = (1 - 1/lam)*var+ (1/lam)*r^2 varlist <- c(varlist, var) } sqrt(varlist) } volest <- Vol(10, SNPret) volest2 <- Vol(30, SNPret) volest3 <- Vol(100, SNPret) plot(volest,type='l') lines(volest2,type='l', col = 'red') lines(volest3,type='l', col = 'blue') # smooth with higher weight
0001876efb1b9e9f9ca30971ad7938e138b9c125
ab8d2c2ecd193cfdf7e4bed46e7585d51e71ed6c
/man/trait.dictionary.Rd
9a16ec1c48b969e3f91d78dfdd8a6d8ebb2daf78
[ "NCSA", "LicenseRef-scancode-unknown-license-reference" ]
permissive
dlebauer/pecan-priors
17cc74617485ce6c59e4e8e48e52773baabaf42a
919eed91e77d7d445e052f3f50e235a23f16f966
refs/heads/master
2021-06-02T09:49:36.286969
2019-09-25T04:40:17
2019-09-25T04:40:17
7,034,392
2
0
null
null
null
null
UTF-8
R
false
false
598
rd
trait.dictionary.Rd
\name{trait.dictionary} \alias{trait.dictionary} \title{Dictionary of terms used to identify traits in ed, filenames, and figures} \usage{ trait.dictionary(traits = NULL) } \arguments{ \item{traits}{a vector of trait names, if traits = NULL, all of the traits will be returned.} } \value{ a dataframe with id, the name used by ED and BETY for a parameter; fileid, an abbreviated name used for files; figid, the parameter name written out as best known in english for figures and tables. } \description{ Dictionary of terms used to identify traits in ed, filenames, and figures }
ae4271dcf6c35db203e93249b7e71d0c7f5c167a
ddcfacca3170c9de0185ae08bc8ad3df3a4213c3
/man/T2O.Rd
9ea70a22f574d4af217191a38e58002572c4a619
[]
no_license
cran/TVMM
042db76fcbb90ee557149879b5ba9ae4d85aae4f
a1564c4589ae9500d679a1df0ffef5477561ae09
refs/heads/master
2021-04-05T11:33:27.126549
2020-12-14T18:50:02
2020-12-14T18:50:02
248,552,850
0
0
null
null
null
null
UTF-8
R
false
true
937
rd
T2O.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/T2O.R \name{T2O} \alias{T2O} \title{The traditional T2 test (T2).} \usage{ T2O(X, mu0) } \arguments{ \item{X}{a matrix n x p containing n observations and p variables. It should not contain missing values (NA).} \item{mu0}{a vector containing the mean population to be tested.} } \value{ the numerical value and the p-value of the test statistic. } \description{ The traditional T2 test (T2). } \examples{ set.seed(0) library(MASS) n <- 30 p <- 2 rho <- 0.9 delta <- 0.9 mu <- rep(0, times = p) Sigma <- (1 - rho) * diag(p) + rho * matrix(1, p, p) mu0 <- rep(0.3271,times = p) X <- mvrnorm(n, mu, Sigma) T2O(X=X, mu0=mu0) } \references{ Henrique J. P. Alves & Daniel F. Ferreira (2019): Proposition of new alternative tests adapted to the traditional T2 test, Communications in Statistics - Simulation and Computation, DOI: 10.1080/03610918.2019.1693596 }
08e1e72539e8b8446ab424b44649a4008dade1a1
57744ab6fedc2d4b8719fc51dce84e10189a0a7f
/rrdfqbcrnd0/R/GetDescrStatProcedure.R
68cabd4f5e1abd820f6716a8347fd5c0b3c4ce23
[]
no_license
rjsheperd/rrdfqbcrnd0
3e808ccd56ccf0b26c3c5f80bec9e4d1c83e4f84
f7131281d5e4a415451dbd08859fac50d9b8a46d
refs/heads/master
2023-04-03T01:00:46.279742
2020-05-04T19:10:43
2020-05-04T19:10:43
null
0
0
null
null
null
null
UTF-8
R
false
false
1,616
r
GetDescrStatProcedure.R
##' Get list of Descriptive statistics ##' ##' For q1 and q3 type=2 is used, as it gives same results as SAS. However, ##' the R help on quantile states type=3 gives same result as SAS. ##' TODO(MJA): investigate which definition is the preferable. ##' @return List providing function for each descriptive statistics ##' @export GetDescrStatProcedure<- function( ) { list( "code:procedure-mean"=list(fun=function(x){mean(x, na.rm=TRUE)}, univfunc="univfunc1" ), "code:procedure-stddev"=list(fun=function(x){sd(x, na.rm=TRUE)}, univfunc="univfunc1" ), "code:procedure-stdev"=list(fun=function(x){sd(x, na.rm=TRUE)}, univfunc="univfunc1" ), "code:procedure-std"=list(fun=function(x){sd(x, na.rm=TRUE)}, univfunc="univfunc1" ), "code:procedure-median"=list(fun=function(x){median(x, na.rm=TRUE)}, univfunc="univfunc1" ), "code:procedure-min"=list(fun=function(x){min(x, na.rm=TRUE)}, univfunc="univfunc1" ), "code:procedure-max"=list(fun=function(x){max(x, na.rm=TRUE)}, univfunc="univfunc1" ), "code:procedure-n"=list(fun=function(x){length(x[!is.na(x)])}, univfunc="univfunc1" ), "code:procedure-q1"=list(fun=function(x){quantile(x, probs=c(0.25),type=2, na.rm=TRUE)}, univfunc="univfunc1" ), "code:procedure-q3"=list(fun=function(x){quantile(x, probs=c(0.75),type=2, na.rm=TRUE)}, univfunc="univfunc1" ), "code:procedure-count"=list(fun=function(x){length(x)}, univfunc="univfunc2" ), "code:procedure-countdistinct"=list(fun=function(x){length(unique(x))}, univfunc="univfunc2" ), "code:procedure-percent"=list(fun=function(x){-1}, univfunc="univfunc3" ) ) }
f1434fcf3815bc4e61861fc8b9d9d1d72492c50e
b110ef8ad122bfbdcf65eac900680b0cb62ac851
/R/classContainer.R
493824651b429787dc093c388ca694e7a703ae8a
[]
no_license
adelabriere/proFIA
fcebc86845c908e0c5978b3d603e2f48af9e64e5
8eaf9aa3105ca7bd9b71bf3754007a867afa522f
refs/heads/master
2020-03-13T09:11:17.646649
2019-07-10T13:31:11
2019-07-10T13:31:11
131,059,383
0
1
null
2019-04-07T11:17:12
2018-04-25T20:23:38
R
UTF-8
R
false
false
3,925
r
classContainer.R
#####Annotate FIA #An object to contain all the information from an FIA acquisition. #' An S4 class to represent an FIA experiments. #' #' The S4 class also includes all the informations about processing, and the detected signals #' are stored. #' #' @include noiseEstimator.R #' @param object A proFIAset object. #' @export #' @slot peaks A matrix containg all the peaks which have been detected in each #' individual files. #' \itemize{ #' \item mzmin the minimum value of the mass traces in the m/z dimension. #' \item mzmax the maximum value of the mass traces in the m/z dimension. #' \item scanMin the first scan on which the signal is detected. #' \item scanMax the last scan on which the signal is detected. #' \item areaIntensity the integrated area of the signal. #' \item maxIntensity the maximum intensity of the signal. #' \item solventIntensity the intensity of the solvent, 0 means that no significant #' solvent was detected. #' \item corSampPeak An idicator of matrix effect, if it's close to 1, the compound #' does not suffer from heavy matrix effect, if it is inferior to 0.5, the compound #' suffer from heavy matrix effect. #' \item signalOverSolventRatio The ratio of the signal max intensity on the oslvent max intensity. #' } #' @include noiseEstimator.R #' @slot group A matrix containing the information on the groups done between all the #' acquisitions. #' \itemize{ #' \item mzMed the median value of group in the m/z dimension. #' \item mzMin the minimum value of the group in the m/z dimension. #' \item mzMax the maximum value of the group in the m/z dimension. #' \item scanMin the first scan on which the signal is detected. #' \item scanMax the last scan on which the signal is detected. #' \item nPeaks The number of peaks grouped in a group. #' \item meanSolvent The mean of solvent in the acquisition. #' \item pvalueMedian The median p-value of the group. #' \item corMean The mean of the matrix effect indicator. #' \item signalOverSolventMean The mean of ratio of the signal max #' intensity on the oslvent max intensity. #' \item corSd The standard deviation of the matrix effect indicator. #' \item timeShifted Is the peak shifted compared to the injection peak. #' } #' @slot groupidx The row of the peaks corresponding to each group #' in \code{peaks}. #' @slot step The step of processing of the experiment. #' @slot path The path of the experiment. #' @slot classes A table with two columns, "rname" the absolute path #' of a file, and "group" the class to which the file belong. #' @slot dataMatrix A matrix variables x experiments suitable for #' statistical analysis. #' @slot noiseEstimation A model of noise as estimated by #' \link{estimateNoiseMS} #' @slot injectionPeaks A list of the injection peak which have been #' detected for each experiment. #' @slot injectionScan A numeric vector giving the scan of injection of #' sample. #' @aliases proFIAset-class dataMatrix peaks groupMatrix phenoClasses injectionPeaks setClass( "proFIAset", slot = list( peaks = "matrix", group = "matrix", groupidx = "list", step = "character", path = "character", classes = "data.frame", dataMatrix = "matrix", noiseEstimation = "noiseEstimation", injectionPeaks = "list", injectionScan = "numeric" ), prototype = list( peaks = matrix(nrow = 0, ncol = 0), group = matrix(nrow = 0, ncol = 0), groupidx = list(), step = "empty", path = character(), classes = data.frame(), dataMatrix = matrix(nrow = 0, ncol = 0), noiseEstimation = new("noiseEstimation"), injectionPeaks = list(), injectionScan = numeric(0) ) )
d398b576c9ae97b1322f64ec982a43ee939627cf
73b297f2e53e18fc7a3d52de4658fede00a0319c
/man/arrayToDf.Rd
bbb020e66db60eeae1d5643e0a4f29bb4deb3e7a
[ "MIT" ]
permissive
bentyeh/r_bentyeh
4f5d0f403dceffb450bd77d8ff87adcaa6c222da
971c63f4ec1486366e0fe07fc705c0589ac7ea39
refs/heads/master
2023-02-06T19:10:18.055017
2020-07-21T18:18:48
2020-07-21T18:18:48
281,471,203
0
0
null
null
null
null
UTF-8
R
false
true
1,190
rd
arrayToDf.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/utils.R \name{arrayToDf} \alias{arrayToDf} \title{Convert an array to a data frame.} \usage{ arrayToDf(ar) } \arguments{ \item{ar}{An array.} } \value{ \code{data.frame. dim = c(prod(dim(ar)), length(dim(ar)) + 1)}. \itemize{ \item Rows: One row per element of the array. Rows are "entered" into the data frame in \href{https://en.wikipedia.org/wiki/Row-_and_column-major_order}{column major order}. \item Columns: One column per dimension of the array, plus one column for the values in the array. \itemize{ \item Column names are retained from names of array dimensions (\code{names(dimnames(ar)}). Where non-existant, column names are given as "d#", where # is the index of the dimension. \item For each column, if the corresponding array dimension was named, then the column is of class \code{character}. Otherwise, the column is of class \code{numeric}. \item The last column (the values from the array) is named "value". } } } \description{ Convert an array to a data frame. } \seealso{ \code{\link[tidyr]{pivot_longer}}, \url{https://stackoverflow.com/a/42810479}. }
0da5041389b93b17b08f7180217a4794edcfc26c
9a79d2eb242a5aa1ea537b395726bbb1b615582c
/data/readdata_POS_CASH_balance.R
4e38ed3d63d30c9ef57321e129b5752d1459c7d1
[]
no_license
HeHuangDortmund/HomeCredit
80d49e1d6c417e4434cab98649893bfee0d1f7cc
f7d809539d1e48bbf00db38489d5f7a695d1e86d
refs/heads/master
2020-03-20T01:28:41.060990
2018-08-31T22:41:06
2018-08-31T22:41:06
137,077,343
0
0
null
null
null
null
UTF-8
R
false
false
4,235
r
readdata_POS_CASH_balance.R
readData = function(version = 1){ library(rprojroot) library(data.table) root = find_root(is_git_root) setwd(root) POS_CASH_balance = fread("../data/POS_CASH_balance.csv", na.strings = "") if (version == 2){ # 在汇总前先填一部分NA POS_CASH_balance$CNT_INSTALMENT[is.na(POS_CASH_balance$CNT_INSTALMENT)] = mean(POS_CASH_balance$CNT_INSTALMENT, na.rm = TRUE) POS_CASH_balance$CNT_INSTALMENT_FUTURE[is.na(POS_CASH_balance$CNT_INSTALMENT_FUTURE)] = mean(POS_CASH_balance$CNT_INSTALMENT_FUTURE, na.rm = TRUE) } POS_CASH_balance[, Add_RATIO_INSTALMENT_LEFT := CNT_INSTALMENT_FUTURE / CNT_INSTALMENT] ############################## calculate the trend and intercept variables ################################################################### # POS_CASH_balance = POS_CASH_balance[order(SK_ID_CURR, SK_ID_PREV, MONTHS_BALANCE)] # temp_data = POS_CASH_balance[!is.na(Add_RATIO_INSTALMENT_LEFT)] # temp_trend1 = temp_data[, lapply(.SD, function(x) {lm(x~(seq(1,length(MONTHS_BALANCE),by=1)))$coefficients[1]}), # .SDcols = c("Add_RATIO_INSTALMENT_LEFT"), # by = SK_ID_PREV] # 14min # temp_trend2 = temp_data[, lapply(.SD, function(x) {lm(x~(seq(1,length(MONTHS_BALANCE),by=1)))$coefficients[2]}), # .SDcols = c("Add_RATIO_INSTALMENT_LEFT"), # by = SK_ID_PREV] # temp_trend = merge(temp_trend1, temp_trend2, all = TRUE, by = c("SK_ID_PREV")) ############################################################################################################################################## temp_trend = fread("trend_pos_cash.txt", drop = "V1") # 对每个变量通过求MEAN和MAX进行汇总 temp_name = setdiff(names(POS_CASH_balance),c("SK_ID_PREV","SK_ID_CURR","NAME_CONTRACT_STATUS")) temp = POS_CASH_balance[, c(lapply(.SD, mean, na.rm = TRUE), lapply(.SD, max, na.rm = TRUE)), .SDcols = temp_name, by = SK_ID_CURR] setnames(temp, 2:ncol(temp),paste(temp_name, rep(c('MEAN','MAX'),each = length(temp_name)), sep = "_")) temp = temp[,c("CNT_INSTALMENT_MAX","CNT_INSTALMENT_FUTURE_MAX") := NULL] # drop 2 variables temp[temp == Inf | temp == -Inf] = NA # 对于Inf/-Inf用NA替换 # 对于每一个SK_ID_PREV求MONTH_BALANCE的数量, 然后求MEAN进行汇总 temp2 = POS_CASH_balance[,.(Nr_POSCASH_MONTH = .N),by = list(SK_ID_CURR,SK_ID_PREV)] ## merge temp_trend temp2 = merge(temp2, temp_trend, all = TRUE, by = "SK_ID_PREV") temp2 = temp2[, lapply(.SD, mean, na.rm = TRUE), .SDcols = names(temp2)[-c(1,2)],by = SK_ID_CURR] names(temp2)[-1] = paste(names(temp2)[-1],"MEAN",sep = "_") # 对于每一个SK_ID_CURR求相对应的SK_ID_PREV的数量 temp3 = POS_CASH_balance[,.(Nr_POS_CASH = length(unique(SK_ID_PREV))), by = "SK_ID_CURR"] # merge temp = merge(temp2, temp, all = TRUE, by = "SK_ID_CURR") temp = merge(temp3, temp, all = TRUE, by = "SK_ID_CURR") rm(temp2,temp3) # 处理唯一的一个categorical变量 # XNA = NA POS_CASH_balance$NAME_CONTRACT_STATUS[POS_CASH_balance$NAME_CONTRACT_STATUS == "XNA"] = NA # 此处或先不把Canceled和NA两个类别合并, 之后尝试使用mergeSmallFactorLevels合并? POS_CASH_balance$NAME_CONTRACT_STATUS[POS_CASH_balance$NAME_CONTRACT_STATUS == "Canceled" | is.na(POS_CASH_balance$NAME_CONTRACT_STATUS)] = "Other" temp_cat = POS_CASH_balance[,.N,by = list(SK_ID_CURR, NAME_CONTRACT_STATUS)] temp_cat_wide = dcast(temp_cat, SK_ID_CURR~NAME_CONTRACT_STATUS, fill = 0, value.var = "N") names(temp_cat_wide)[-1] = paste("NAME_CONTRACT_STATUS_POSCASH", names(temp_cat_wide)[-1],sep = "_") # merge POS_CASH_balance = merge(temp,temp_cat_wide,all = TRUE, by = "SK_ID_CURR") rm(temp,temp_cat,temp_cat_wide) POS_CASH_balance[,c("Add_RATIO_INSTALMENT_LEFT_MAX")] = NULL names(POS_CASH_balance)[grep("SK_DPD",names(POS_CASH_balance))] = paste(names(POS_CASH_balance)[grep("SK_DPD",names(POS_CASH_balance))],"POS",sep="_") names(POS_CASH_balance)[grep("MONTHS_BALANCE",names(POS_CASH_balance))] = paste(names(POS_CASH_balance)[grep("MONTHS_BALANCE",names(POS_CASH_balance))],"POS",sep="_") return(POS_CASH_balance) }
8e1c1cbfb76a8f64c81ca99bdf004202fd9feaa3
3f85f047f5d22d44f50e420ea64b6592f5fa349d
/plot4.R
f404c052eaac3bb9dd4d514201abbebf1c74ed0b
[]
no_license
byronrdz/ExData_Plotting1
fb657b39a00fa66979373d8b1d0c3f59b8e6180b
63d5d52fca24f61947a5100becf427cc4b6502ac
refs/heads/master
2020-12-01T03:08:22.325941
2015-03-08T23:29:47
2015-03-08T23:29:47
31,691,325
0
0
null
2015-03-05T02:23:01
2015-03-05T02:22:59
null
UTF-8
R
false
false
1,172
r
plot4.R
#PLOT4 #Settting working directory where the data file is located setwd("C:/Users/Byron/Documents/Coursera Data Science Sp/Exploratory Data Analysis/ExData_Plotting1") #Loading filtered data from the file. Just rows corresponding to 1/2/2007 and 2/2/2007 library(sqldf) data <- read.csv.sql("household_power_consumption.txt",header=TRUE,sep=";",sql="select * from file where Date in('1/2/2007','2/2/2007')") #Creating the time vector for the graphic. days <- paste(as.Date(data$Date,"%d/%m/%Y"),data$Time) days <- strptime(days,"%Y-%m-%d %H:%M:%S") #Creating the graphic 4 png("plot4.png",width=480,height=480) par(mfrow=c(2,2)) plot(days,data$Global_active_power,type="l",ylab="Global Active Power (kilowats)",xlab="") plot(days,data$Voltage,type="l",ylab="Voltage",xlab="datetime") plot(days,data$Sub_metering_1,type="l",ylab="Energy sub metering",xlab="") lines(days,data$Sub_metering_2,col="red") lines(days,data$Sub_metering_3,col="blue") legend("topright",lty=c(1,1,1),col=c("black","red","blue"),legend=c("Sub_metering_1","Sub_metering_2","Sub_metering_3")) plot(days,data$Global_reactive_power,type="l",ylab="Global_reactive_power",xlab="datetime") dev.off()
14fb10fd8f8ba403a4e47c304870a1bf29d1297d
3396a0f6202149a80a6170ab088bf407f5e30169
/analysis/networks-statistics.R
84db725eb504a1dddf1527c12d8577aea52db172
[]
no_license
akastrin/medline-evolution
c997e51f155b2ffea73374fa0b9a48edeb2436cc
294f7414d8d2d6b50e0ffa4806057519fc91a1b7
refs/heads/master
2021-08-24T06:50:04.338605
2017-12-08T13:42:56
2017-12-08T13:42:56
112,579,727
0
1
null
null
null
null
UTF-8
R
false
false
3,455
r
networks-statistics.R
library(igraph) library(data.table) library(Rcpp) library(R.matlab) library(tidyverse) library(Matrix) # source("clustercoef_kaiser.R") sourceCpp("./scripts/kaiser.cpp") # Create network-statistics.csv file files <- paste0("../data/matlab/adj-mats/adj-mat-", 1:49, ".mm") n_nodes <- vector(mode = "integer", length = length(files)) n_edges <- vector(mode = "integer", length = length(files)) ave_deg <- vector(mode = "double", length = length(files)) cen <- vector(mode = "integer", length = length(files)) apl <- vector(mode = "double", length = length(files)) cc <- vector(mode = "double", length = length(files)) for (i in 1:length(files)) { file <- files[i] data <- readMM(file) g <- graph_from_adjacency_matrix(adjmatrix = data, mode = "undirected", weighted = TRUE) adj <- get.adjacency(g, sparse = FALSE) n_nodes[i] <- vcount(g) n_edges[i] <- ecount(g) ave_deg[i] <- mean(degree(g)) cen[i] <- mean(eigen_centrality(g, directed = FALSE)$vector) apl[i] <- mean_distance(g = g, directed = FALSE) cc[i] <- kaiser(adj) cat(i, "\n") } modularity <- read_tsv("../data/matlab/other/modularity.txt") comm_size <- readMat("../data/matlab/other/comm-sizes.mat") comm_size <- apply(comm_size$commSizes != 0, 1, sum) year <- 1966:2014 tab <- data.frame(year, n_nodes, n_edges, ave_deg, cen, apl, cc, modul, comm_size) write_tsv(tab, path = "../data/networks_statistics.txt") #################################### # Heatmap comm_evol_size <- readMat("../data/matlab/other/comm-evol-size.mat")$commEvolSize # library(heatmap3) library(RColorBrewer) data <- t(comm_evol_size) data2 <- data data2 <- log(data2 + 1) library(reshape2) data_melt <- melt(data) data_melt2 <- melt(data2) library(ggplot2) library(scales) plt <- ggplot(data_melt2, aes(Var2, Var1)) + geom_tile(aes(fill = value)) + scale_fill_gradient(low = "white", high = "black") + scale_x_continuous(labels = seq(1965, 2015, 5), breaks = seq(1, 51, 5)) + scale_y_reverse() + labs(x = "Year", y = "Community") + theme(panel.background = element_blank(), panel.border=element_rect(fill=NA), legend.position = "none") plt ggsave("../figures/community-heatmap.pdf", plt, height = 9, width = 5) #################################### # How many ... each particular community active life_span <- apply(X = comm_evol_size, MARGIN = 2, FUN = function(x) sum(x != 0)) med_comm_size <- apply(X = comm_evol_size, MARGIN = 2, FUN = function(x) median(x[x != 0])) # Read community structure from MATLAB comm1 <- readMat("/home/andrej/Documents/dev/community-evolution-analysis/data/mats/medline/strComms1.mat")$strComms mesh2cluster <- function(str_comms) { res <- list() n <- length(str_comms) for (i in 1:n) { mesh_terms <- unlist(str_comms[[i]]) setNames(object = mesh_terms, nm = rep(n, length(mesh_terms))) res[[i]] <- mesh_terms } return(res) } #################################### data <- readMM("../data/matlab/adj-mats/adj-mat-1.mm") g <- graph_from_adjacency_matrix(adjmatrix = data, mode = "undirected", weighted = TRUE) g <- simplify(as.undirected(g)) l <- layout.auto(g) png("../figures/net.png") plot(g, vertex.size = 0, vertex.shape = "none", vertex.label = NA, edge.color = adjustcolor("black", alpha = .1), edge.curved = TRUE, edge.width=0.2, layout = l) dev.off() library(HiveR) gAdj <- get.adjacency(g, type = "upper", edges = FALSE, names = TRUE, sparse = FALSE) hive1 <- adj2HPD(gAdj, type = "2D")
d19a55a2377991e72edc0e8135637e57010cadd2
b82c3a70ecc18227493239f0a2037592a0e767d2
/collection/mysql_config.R
1f062927d9f7d9e0e81e3c415a0552718ff5637b
[]
no_license
hzontine/polarbear
8fed9f3befe7c4e40547df5c0463bb14d15c454f
893a322a566d05f00b47fbbd70d8987ffd5a11ce
refs/heads/master
2020-05-21T15:04:26.039931
2017-09-30T21:43:25
2017-09-30T21:43:25
58,944,871
0
1
null
null
null
null
UTF-8
R
false
false
191
r
mysql_config.R
# MySQL configuration. #mysql.db.name <- "polarbear" mysql.db.name <- "polarbear" mysql.user <- "stephen" mysql.password <- "iloverae" # git update-index --assume-unchanged mysql_config.R
4c41b1bc45f0ec7a40e460f7ddf820832f6132b1
a0a9934e32e7c68e57af0eddf83b00d3189cca1d
/Animal_Matching.R
0e3ed9f4da5b11a371029de4235489ff7f81a63c
[]
no_license
mathemagicalgames/mathe-magical-games
708cc51c43a8cff94068e82b540508a88ad4ef9a
164b497910575382ccf9fc4c5cb31c57ea280eff
refs/heads/master
2020-08-01T08:09:51.128294
2019-09-25T19:54:45
2019-09-25T19:54:45
210,926,486
2
0
null
null
null
null
UTF-8
R
false
false
2,534
r
Animal_Matching.R
# Copyright (c) 2017 - 2018 # Nicolai Meinshausen [meinshausen@stat.math.ethz.ch] # Jonas Peters [jonas.peters@math.ku.dk] # All rights reserved. See the file COPYING for license terms. ## dimension (will result in p^2+p+1 players and unique animals) p <- 3 ## check whether p is a small prime number if(! p %in% c(2,3,5,7,11, 13)) stop(" Dimension p has to be a small prime: 2,3,5,7 or (if you are not impatient) also 11 or 13") ## names for animals -- is padded with characters in the end for a potentially larger number of players -- can be easily changed here names <- c("Lion", "Giraffe", "Dog", "Cat", "Mouse", "Elephant", "Snake","Eagle","Frog","Spider","Dolphin","Jellyfish","Earthworm", as.character(1:150)) ## start from {0,1,...,p-1} set <- 0:(p-1) ## embed into three dimensions three.dim <- expand.grid(set,set,set) ## select points that lead to unique lines through origin (this is not just one possible choice -- keeping those vectors whose first nonzero entry is a 1) keep <- which( apply(three.dim,1, function(x) if(identical(as.numeric(x),c(0,0,0))) FALSE else x[which(x!=0)[1]]==1)) ## for the p^2+p+1 unique lines through the origin, keep a representative point lines <- as.matrix(three.dim[keep,]) ## m is now the number of players and unique animals m <- p^2+p+1 ## q is the number of possible pairs between players (or animals) q <- (m*(m-1))/2 ## s is the number of animals each player will have (or players that will have a specific animal) s <- p+1 ## the matrix M will store the indices of s animals of player i in row i M <- matrix(nrow=q,ncol=s) cc <- 0 for (j1 in 1:(m-1)){ for (j2 in (j1+1):m){ o1 <- lines[j1,] o2 <- lines[j2,] tmp <- c(j1,j2) for (c1 in 0:p){ for (c2 in 0:p){ vec <- as.numeric((c1*o1 + c2*o2) %% p) new <- which( apply( sweep( lines,2,vec,FUN="-")==0, 1, all)) tmp <- sort(unique(c(tmp, new))) } } cc <- cc+1 M[ cc,] <- tmp } } M <- unique(M) ## A is the incidence matrix for the choice of animals in M A <- matrix(0,nrow=m,ncol=m) for (j in 1:m) A[j, M[j,]] <- 1 ## can check that A satisfies A A^{\transp} =pI + J print( A%*%t(A) ) ## write out table of animals (latex version TRUE or FALSE ) latex <- FALSE for (j in 1:m){ if (latex){ cat("\n Player ",j," & ", paste(names[M[j,]],collapse=" & " )," \\\\ ") }else{ cat("\n Player ",j," takes ", paste(names[M[j,]],collapse=", " )," ") } }
55765445891239364a14c077a3b14fce07004e33
d34170b0244866131fd5d959688f908f02ea5404
/R/corrXY.r
8e96b9006a494b57b7ea51acb7d32bd173c3ffad
[]
no_license
ClementCalenge/adehabitatLT
7ac4182ce35abc6b8d85f8929017102e5a430bf3
1da9d94626de2ed4c069ba4fedef16cf9ddf5c8f
refs/heads/master
2023-04-14T12:32:51.368684
2023-04-07T07:25:26
2023-04-07T07:25:26
81,651,833
5
1
null
null
null
null
UTF-8
R
false
false
2,783
r
corrXY.r
.convtime <- function(step, units) { if (units=="min") step <- step*60 if (units=="hour") step <- step*60*60 if (units=="day") step <- step*60*60*24 return(step) } .corrXY <- function(x, y, dab, daa) { x1 <- x[1] y1 <- y[1] if (daa[1]!=dab[1]) { dt <- daa[2]-daa[1] dif <- abs(daa[1]-dab[1]) alpha <- atan2( (y[2]-y[1]), (x[2]-x[1]) ) r <- sqrt( (x[2]-x[1])^2 + (y[2]-y[1])^2 )*dif/dt if (daa[1] > dab[1]) { x1 <- x[1]+cos(alpha)*r y1 <- y[1]+sin(alpha)*r } if (daa[1] < dab[1]) { alpha <- pi + alpha x1 <- x[1]+cos(alpha)*r y1 <- y[1]+sin(alpha)*r } } xn <- x[length(y)] yn <- y[length(y)] if (daa[length(daa)]!=dab[length(dab)]) { dt <- daa[length(daa)]-daa[length(daa)-1] dif <- abs(daa[length(daa)]-dab[length(daa)]) alpha <- atan2((y[length(daa)]-y[length(daa)-1]), (x[length(daa)]-x[length(daa)-1])) r <- sqrt((x[length(daa)]-x[length(daa)-1])^2 + (y[length(daa)]-y[length(daa)-1])^2)*dif/dt if (daa[length(dab)]<dab[length(dab)]) { alpha <- pi + alpha xn <- x[length(daa)]+cos(alpha)*r yn <- y[length(daa)]+sin(alpha)*r } else { xn <- x[length(daa)]+cos(alpha)*r yn <- y[length(daa)]+sin(alpha)*r } } x[1] <- x1 y[1] <- y1 x[length(x)] <- xn y[length(x)] <- yn xb <- x[1:(length(x)-2)] xc <- x[2:(length(x)-1)] xa <- x[3:length(x)] yb <- y[1:(length(x)-2)] yc <- y[2:(length(x)-1)] ya <- y[3:length(x)] daat <- daa dabt <- dab if (any(daa[-c(1,length(daa))]<dab[-c(1,length(daa))])) { dt <- diff(daa[1:(length(daa)-1)]) daa <- daa[2:(length(x)-1)] dab <- dab[2:(length(x)-1)] dif <- abs(daa-dab) alpha <- atan2( (yc-yb),(xc-xb) ) r <- sqrt( (xc-xb)^2 + (yc-yb)^2 )*dif/dt xc[daa<dab] <- xc[daa<dab] + cos(alpha[daa<dab] + pi)*r[daa<dab] yc[daa<dab] <- yc[daa<dab] + sin(alpha[daa<dab] + pi)*r[daa<dab] } daa <- daat dab <- dabt if (any(daa[-c(1,length(daa))] > dab[-c(1,length(daa))])) { dt <- diff(daat[2:(length(daat))]) daa <- daa[2:(length(x)-1)] dab <- dab[2:(length(x)-1)] dif <- abs(daa-dab) alpha <- atan2( (ya-yc),(xa-xc) ) r <- sqrt( (xa-xc)^2 + (ya-yc)^2 )*dif/dt xc[daa>dab] <- xc[daa>dab] + cos(alpha[daa>dab])*r[daa>dab] yc[daa>dab] <- yc[daa>dab] + sin(alpha[daa>dab])*r[daa>dab] } xn <- c(x1, xc, xn) yn <- c(y1, yc, yn) return(list(x=xn,y=yn)) }
a751159ff1fad33e8cffa5a118274f07c4d19792
0fb33ca8eef07fcb5d3687f4cf2793ef187f79f4
/R/ca-scoreFACT_EN.R
b64db6bda8b8ac8bdb482b7107c789c31d990e69
[ "MIT" ]
permissive
raybaser/FACTscorer
e3c10b9a065cb5b6290b211519b72ed9171a1fc2
070a1cf479ee8c1f19bf6a295c2ed0d544ff6406
refs/heads/master
2022-03-16T20:20:29.198088
2022-03-12T09:42:36
2022-03-12T09:42:36
61,918,573
2
0
null
null
null
null
UTF-8
R
false
false
3,334
r
ca-scoreFACT_EN.R
#' @title Score the FACT-En #' #' @description #' Generates all of the scores of the Functional Assessment of Cancer Therapy - #' Endometrial Cancer (FACT-En, v4) from item responses. #' #' @templateVar MEASURE FACT-En #' @templateVar SCOREFUN scoreFACT_En #' @template templateDetailsAC #' #' #' @template templateParamsAC #' #' #' @return A data frame with the following scale scores is returned: #' #' \itemize{ #' \item \strong{PWB} - Physical Well-Being subscale #' \item \strong{SWB} - Social/Family Well-Being subscale #' \item \strong{EWB} - Emotional Well-Being subscale #' \item \strong{FWB} - Physical Well-Being subscale #' \item \strong{FACTG} - FACT-G Total Score (PWB+SWB+EWB+FWB) #' \item \strong{ENCS} - Endometrial Cancer subscale #' \item \strong{FACT_En_TOTAL} - FACT-En Total Score (PWB+SWB+EWB+FWB+ENCS) #' \item \strong{FACT_En_TOI} - FACT-En Trial Outcome Index (PWB+FWB+ENCS) #' } #' #' If \code{AConly = TRUE}, the only scale score returned is \strong{ENCS}. #' #' If a variable was given to the \code{id} argument, then that variable will #' also be in the returned data frame. Additional, relatively unimportant, #' variables will be returned if \code{updateItems = TRUE} or \code{keepNvalid = #' TRUE}. #' #' @references FACT-En Scoring Guidelines, available at #' \url{http://www.facit.org} #' #' #' @export #' #' @examples #' \dontshow{ #' ## FIRST creating a df with fake item data to score #' itemNames <- c('O1', 'O3', 'Hep8', 'ES6', 'ES4', 'Hep1', 'ES1', #' 'ES2', 'ES3', 'HI7', 'ES8', 'En1', 'B1', 'Cx6', 'Bl2', 'En2') #' exampleDat <- make_FACTdata(namesAC = itemNames) #' #' ## NOW scoring the items in exampleDat #' #' ## Returns data frame with ONLY scale scores #' (scoredDat <- scoreFACT_En(exampleDat)) #' #' ## Using the id argument (makes merging with original data more fool-proof): #' (scoredDat <- scoreFACT_En(exampleDat, id = "ID")) #' #' ## Merge back with original data, exampleDat: #' mergeDat <- merge(exampleDat, scoredDat, by = "ID") #' names(mergeDat) #' #' ## If ONLY the "Additional Concerns" items are in df, use AConly = TRUE #' (scoredDat <- scoreFACT_En(exampleDat, AConly = TRUE)) #' #' ## AConly = TRUE with an id variable #' (scoredDat <- scoreFACT_En(exampleDat, id = "ID", AConly = TRUE)) #' #' ## Returns scale scores, plus recoded items (updateItems = TRUE) #' ## Also illustrates effect of setting keepNvalid = TRUE. #' scoredDat <- scoreFACT_En(exampleDat, updateItems = TRUE, keepNvalid = TRUE) #' names(scoredDat) #' ## Descriptives of scored scales #' summary(scoredDat[, c('PWB', 'SWB', 'EWB', 'FWB', 'FACTG', #' 'ENCS', 'FACT_En_TOTAL', 'FACT_En_TOI')]) #' } scoreFACT_En <- function(df, id = NULL, AConly = FALSE, updateItems = FALSE, keepNvalid = FALSE) { df_scores <- scoreFACT_any( df = df, id = id, namesAC = c("O1", "O3", "Hep8", "ES6", "ES4", "Hep1", "ES1", "ES2", "ES3", "HI7", "ES8", "En1", "B1", "Cx6", "Bl2", "En2"), namesRev = c("O1", "O3", "Hep8", "ES6", "ES4", "Hep1", "ES1", "ES2", "ES3", "HI7", "ES8", "En1", "B1", "Cx6", "Bl2", "En2"), nameSub = "ENCS", nameTot = "FACT_En", AConly = AConly, updateItems = updateItems, keepNvalid = keepNvalid ) return(df_scores) }
f29143b43266c6f0b522c9f106c3dc96e452a151
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/TPD/examples/Rao.Rd.R
efd378be1148c0012196665be1e97c77ac8514f7
[]
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,054
r
Rao.Rd.R
library(TPD) ### Name: Rao ### Title: Rao's Quadratic Entropy and its Partition ### Aliases: Rao ### ** Examples # 1. Compute the TPDs of three different species. traits_iris <- iris[, c("Sepal.Length", "Sepal.Width")] sp_iris <- iris$Species TPDs_iris <- TPDs(species = sp_iris, traits_iris) #2. Compute the dissimilarity between the three species: dissim_iris_sp <- dissim(TPDs_iris) #3. Compute the TPDc of five different communities: abundances_comm_iris <- matrix(c(c(0.9, 0.1, 0), # setosa dominates c(0.4, 0.5, 0.1 ), c(0.15, 0.7, 0.15), #versicolor dominates c(0.1, 0.5, 0.4), c(0, 0.1, 0.9)), #virginica dominates ncol = 3, byrow = TRUE, dimnames = list(paste0("Comm.",1:5), unique(iris$Species))) TPDc_iris <- TPDc( TPDs = TPDs_iris, sampUnit = abundances_comm_iris) #4. Compute Rao: Rao_iris <- Rao(diss = dissim_iris_sp, TPDc = TPDc_iris)
527f30ebbdde326a045271de5e635fb20782cdca
089626fd5094bbf9478bd11c1b16331675082113
/week1/plot_trips.R
0b8cf4e57dab957faf50e6f6094733f3948a610e
[]
no_license
BasiraS/coursework
6ed0aa3f35bcb1b0a73b4251bf3c13526911868e
6bd93c96374fb5ec442d0992069be3084c488536
refs/heads/master
2022-11-05T18:44:37.686794
2020-06-19T19:53:01
2020-06-19T19:53:01
268,619,251
0
0
null
2020-06-01T19:58:03
2020-06-01T19:58:02
null
UTF-8
R
false
false
12,211
r
plot_trips.R
######################################## # load libraries ######################################## # load some packages that we'll need library(tidyverse) library(scales) # be picky about white backgrounds on our plots theme_set(theme_bw()) # load RData file output by load_trips.R load('trips.RData') ######################################## # plot trip data ######################################## # plot the distribution of trip times across all rides (compare a histogram vs. a density plot) # Histogram trips %>% filter(tripduration < 3600) %>% ggplot(aes(x = tripduration)) + geom_histogram() # Density trips %>% filter(tripduration < 3600) %>% ggplot(aes(x = tripduration)) + geom_density(fill = "grey") # plot the distribution of trip times by rider type indicated using color and fill (compare a histogram vs. a density plot) # Histogram trips %>% filter(tripduration < 3600) %>% ggplot(aes(x = tripduration, colour = usertype)) + geom_histogram(position = "identity", alpha = 0.25) + facet_wrap(~ usertype, scales = "free") # Density trips %>% filter(tripduration < 3600) %>% ggplot(aes(x = tripduration, colour = usertype, )) + geom_density(fill = "grey") + facet_wrap(~ usertype, scales = "free") # plot the total number of trips on each day in the dataset trips %>% mutate(day = as.Date(starttime)) %>% group_by(day) %>% summarize(num_trips = n()) %>% ggplot(aes(x = day, y = num_trips)) + geom_line() + scale_y_continuous(label = comma) + xlab('Day') + ylab('Number of Trips') trips %>% mutate(day = as.Date(starttime)) %>% ggplot(aes(x = day)) + geom_histogram()+ scale_y_continuous(label = comma) + xlab('Day') + ylab('Number of Trips') trips %>% mutate(day = factor((weekdays(as.POSIXct(starttime), abbreviate = F)), levels=c("Monday","Tuesday","Wednesday","Thursday","Friday"))) %>% ggplot(aes(x = day)) + geom_histogram(stat = "count") + scale_y_continuous(label = comma) + xlab('Day') + ylab('Number of Trips') # plot the total number of trips (on the y axis) by age (on the x axis) and gender (indicated with color) trips %>% mutate(age = 2014 - birth_year) %>% group_by(age, gender) %>% summarize(num_trips = n()) %>% filter(num_trips <= 600000) %>% ggplot(aes(x = age, y = num_trips, colour = gender)) + geom_point() + scale_y_continuous(label = comma) trips %>% mutate(age = 2014 - birth_year) %>% group_by(age) %>% ggplot(aes(x = age, colour = gender)) + geom_histogram(position = "identity", alpha = 0.25) + scale_y_continuous(label = comma) + facet_wrap(~ gender, scales = "free") # plot the ratio of male to female trips (on the y axis) by age (on the x axis) # hint: use the spread() function to reshape things to make it easier to compute this ratio # (you can skip this and come back to it tomorrow if we haven't covered spread() yet) trips %>% mutate(age = 2014 - birth_year) %>% group_by(age, gender) %>% summarize(count = n()) %>% pivot_wider(names_from = gender, values_from = count) %>% mutate(ratio = Male / Female) %>% ggplot(aes(x = age, y = ratio)) + geom_point() ######################################## # plot weather data ######################################## # plot the minimum temperature (on the y axis) over each day (on the x axis) weather %>% ggplot(aes(x = ymd, y = tmin)) + geom_point() + geom_smooth(se = FALSE) # plot the minimum temperature and maximum temperature (on the y axis, with different colors) over each day (on the x axis) # hint: try using the gather() function for this to reshape things before plotting # (you can skip this and come back to it tomorrow if we haven't covered gather() yet) weather %>% select(tmin, tmax, ymd) %>% pivot_longer(names_to = "temp_type", values_to = "temp", cols = c('tmin', 'tmax')) %>% ggplot(aes(x = ymd, y = temp, group = temp_type)) + geom_point(aes(colour = temp_type)) + geom_smooth(se = FALSE) ######################################## # plot trip and weather data ######################################## # join trips and weather trips_with_weather <- inner_join(trips, weather, by="ymd") # plot the number of trips as a function of the minimum temperature, where each point represents a day # you'll need to summarize the trips and join to the weather data to do this trips_with_weather %>% group_by(tmin, ymd) %>% summarize(num_trips = n()) %>% ggplot(aes(x = tmin, y = num_trips)) + geom_point(aes(colour = ymd)) + scale_y_continuous(label = comma) # repeat this, splitting results by whether there was substantial precipitation or not # you'll need to decide what constitutes "substantial precipitation" and create a new T/F column to indicate this trips_with_weather %>% mutate(prcp_chance = (prcp > 0)) %>% group_by(tmin, ymd, prcp_chance) %>% summarize(num_trips = n()) %>% ggplot(aes(x = tmin, y = num_trips)) + geom_point(aes(colour = prcp_chance)) + scale_y_continuous(label = comma) # add a smoothed fit on top of the previous plot, using geom_smooth trips_with_weather %>% mutate(prcp_chance = (prcp > 0.5)) %>% group_by(tmin, ymd, prcp_chance) %>% summarize(num_trips = n()) %>% ggplot(aes(x = tmin, y = num_trips)) + geom_point(aes(colour = prcp_chance)) + geom_smooth(aes(colour = prcp_chance), se = FALSE) + scale_y_continuous(label = comma) # compute the average number of trips and standard deviation in number of trips by hour of the day # hint: use the hour() function from the lubridate package # plot the above trips_with_weather %>% mutate(hourTime = hour(starttime)) %>% group_by(hourTime, ymd) %>% summarize(count = n()) %>% group_by(hourTime) %>% summarize(average_trips = mean(count), sd_trips = sd(count)) %>% pivot_longer(names_to = "computation", values_to = "result", cols = c('average_trips', 'sd_trips')) %>% ggplot(aes(x = hourTime, y = result)) + geom_point() + scale_y_continuous(label = comma) + facet_wrap(~ computation, scales = "free") # repeat this, but now split the results by day of the week (Monday, Tuesday, ...) or weekday vs. weekend days # hint: use the wday() function from the lubridate package trips_with_weather %>% mutate(hourTime = hour(starttime)) %>% group_by(hourTime, wday(ymd)) %>% summarize(count = n()) %>% group_by(hourTime) %>% summarize(average_trips = mean(count), sd_trips = sd(count)) %>% pivot_longer(names_to = "computation", values_to = "result", cols = c('average_trips', 'sd_trips')) %>% ggplot(aes(x = hourTime, y = result)) + geom_point() + scale_y_continuous(label = comma) + facet_wrap(~ computation, scales = "free") ######################################## # Chapter 3 ######################################## library(tidyverse) ggplot2::mpg ######################################## # SOLUTIONS ######################################## # 3.3.1 # Exercise 1: What's gone wrong with this code? Why are the points not blue? #Original Code: ggplot(data = mpg) + geom_point(mapping = aes(x = displ, y = hwy, color = "blue")) #Modified Code: ggplot(data = mpg) + geom_point(mapping = aes(x = displ, y = hwy), color = "blue") # Exercise 2: Which variables in mpg are categorical? Which variables are continuous? (Hint: type ?mpg to read the documentation for the dataset). How can you see this information when you run mpg? #Categorical variables: manufacturer, model, year, cyl, trans, drv, fl, class #Continuous variables: displ, cty, hwy # Exercise 3: Map a continuous variable to color, size, and shape. How do these aesthetics behave differently for categorical vs. continuous variables? # It works well for categorical since there is a finite set, however, it does not work so well for # continuous variables because of the various values types. Color and Size still can work, however, it cannot be mapped to shape # 3.5.1 # Exercise 1: What happens if you facet on a continuous variable? # The continuous variable is converted to a categorical variable, and the plot contains a facet for each distinct value. # Exercise 4: What are the advantages to using faceting instead of the color aesthetic? What are the disadvantages? How might the balance change if you had a larger data set? ggplot(data = mpg) + geom_point(mapping = aes(x = displ, y = hwy)) + facet_wrap(~ class, nrow = 2) # The advantage is that you get to see a more detail view of the data, easier to distinguish # The disadvantage is that it becomes difficult to compare the values of observations between categories since the observations for each category are on different plots. # 3.6.1 # Exercise 5: Will these two graphs look different? Why/why not? ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) + geom_point() + geom_smooth() ggplot() + geom_point(data = mpg, mapping = aes(x = displ, y = hwy)) + geom_smooth(data = mpg, mapping = aes(x = displ, y = hwy)) # The two graphs will not be different because both geom_point() and geom_smooth() will use the same data and mappings. # They will inherit those options from the ggplot() object, so the mappings don't need to specified again. # Exercise 6: Recreate the R code necessary to generate the following graphs. ggplot(mpg, aes(x = displ, y = hwy)) + geom_point() + geom_smooth(se = FALSE) ggplot(mpg, aes(x = displ, y = hwy, group = drv)) + geom_point() + geom_smooth(se = FALSE) ggplot(mpg, aes(x = displ, y = hwy, colour = drv)) + geom_point() + geom_smooth(se = FALSE) ggplot(mpg, aes(x = displ, y = hwy)) + geom_point(aes(colour = drv)) + geom_smooth(se = FALSE) ggplot(mpg, aes(x = displ, y = hwy)) + geom_point(aes(colour = drv)) + geom_smooth(aes(linetype = drv), se = FALSE) ggplot(mpg, aes(x = displ, y = hwy)) + geom_point(size = 4, color = "white") + geom_point(aes(colour = drv)) # 3.8.1 # Question 1: What is the problem with this plot? How could you improve it? # Original Code: ggplot(data = mpg, mapping = aes(x = cty, y = hwy)) + geom_point() # Modified Code: ggplot(data = mpg, mapping = aes(x = cty, y = hwy)) + geom_point(position = "jitter") # Question 2: What parameters to geom_jitter() control the amount of jittering? # There are two parameters that control the amount of jittering: width and height ######################################## # Chapter 12 ######################################## library(tidyverse) ggplot2::mpg ######################################## # SOLUTIONS ######################################## # 12.2.1 # Exercise 2: Using prose, describe how the variables and observations are organized in each of the sample tables. # Table 1: Observations: country and year; Variables: cases and population # Table 2: Observations: country, year, and type of count; Variable: the count (value) # Table 3: Observations: country and year; Variable: rate # Table 4a: Observations: country; Variable: year 1999 and 2000 (value for cases) # Table 4b: Observations: country; Variable: year 1999 and 2000 (value for population) # 12.3.3 # Exercise 1: Why are pivot_longer() and pivot_wider() not perfectly symmetrical? # The two are not symmetrical because of the variation on column. # Exercise 3: What would happen if you widen this table? Why? How could you add a new column to uniquely identify each value? people <- tribble( ~name, ~names, ~values, #-----------------|--------|------ "Phillip Woods", "age", 45, "Phillip Woods", "height", 186, "Phillip Woods", "age", 50, "Jessica Cordero", "age", 37, "Jessica Cordero", "height", 156 ) pivot_wider(people, names_from = "names", values_from = "values") # It will fail because columns do not uniquely identity rows # Modification: people %>% group_by(name, names) %>% mutate(identify = row_number()) %>% pivot_wider(names_from = "names", values_from = "values")
35d9ae20034f29785a18298bf63af0b6d92d334a
6a5a13aa76f394b99c3ba24580c63e492c72314f
/exploratory_data_analysis/week1/week1_course.R
6c4e038704ea4d5d2c0b3fcd735c3da00c1ee899
[]
no_license
sriharshams/datasciencecoursera
6de4616997c687e14c62d816d19859bffc1f7f98
e34263d3080e5b272d2d61fa323439c353effa61
refs/heads/master
2020-04-15T08:46:39.289593
2017-06-24T22:09:29
2017-06-24T22:09:29
52,250,701
0
0
null
null
null
null
UTF-8
R
false
false
5,349
r
week1_course.R
#Get data getwd() #Note: This directory needs to be changed based on the required directory for data location setwd("C:/learning/coursera/coursera-data_science-data/exploratory_data_analysis/week1/data") filename <- "avgpm25.csv" ## Download the dataset: if (!file.exists(filename)){ fileURL <- "https://raw.githubusercontent.com/jtleek/modules/master/04_ExploratoryAnalysis/exploratoryGraphs/data/avgpm25.csv" download.file(fileURL, filename, mode='wb', cacheOK=FALSE) } pollution <- read.csv(filename, colClasses = c("numeric", "character", "factor", "numeric", "numeric")) head(pollution) #Simple summaries of data, one dimension #Five-number summary (6-number) summary(pollution$pm25) # Box plot boxplot(pollution$pm25, col = "blue") abline(h = 12) # Histograms & density plot hist(pollution$pm25, col = "green", breaks = 100) abline(v = 12, lwd = 2) abline(v = median(pollution$pm25), col = "magenta", lwd = 4) rug(pollution$pm25) #barplot barplot(table(pollution$region), col = "wheat", main = "Number of Counties in Each Region") # Simple smmaries of Data 2 dimensoins # Multiple / overlayed 1-D plots(Lattice / ggplot2) # Multople Boxplots boxplot(pm25 ~ region, data = pollution, col = "red") par(mfrow = c(2, 1), mar = c(4, 4, 2, 1)) hist(subset(pollution, region == "east")$pm25, col = "green") hist(subset(pollution, region == "west")$pm25, col = "green") # Scatterplots with(pollution, plot(latitude, pm25, col = region)) abline(h = 12, lwd = 2, lty = 2) par(mfrow = c(2, 1), mar = c(5, 4, 2, 1)) with(subset(pollution, region == "west"), plot(latitude, pm25, main = "West")) with(subset(pollution, region == "east"), plot(latitude, pm25, main = "East")) # Smooth scatterplots # > 2 dimensions # Overlayed/ multiple 2-D plots : coplots # Use color, size, shape to add dimensions # Spinning plots # Actual 3-D plots (not that useful) #baseplot library(datasets) data(cars) with(cars, plot(speed, dist)) #latticeplot xyplot, bwplot library(lattice) state <- data.frame(state.x77, region = state.region) xyplot(Life.Exp ~ Income | region, data = state, layout = c(4,1)) # ggplot2 mixes baseplot & lattice plot library(ggplot2) data(mpg) qplot(displ, hwy, data = mpg) #baseplot system (graphics : plot, hist, boxplot, grDevices : X11, PDF, PostScript, PNG etc) #Latticeplot system (lattice : xyplot, bwplot, levelplot, grid : lattice uses grid) hist(airquality$Ozone) with(airquality, plot(Wind, Ozone)) boxplot(Ozone ~ Month, airquality, xlab = "Month", ylab = "Ozone (ppb)") par("lty") par("mar") par("mfrow") with(airquality, plot(Wind, Ozone)) title(main = "Ozone and Wind in New York City") #baseplot with annotation with(airquality, plot(Wind, Ozone, main = "Ozone and Wind in New York City")) with(subset(airquality, Month == 5), points(Wind, Ozone, col = "blue")) with(subset(airquality, Month != 5), points(Wind, Ozone, col = "red")) legend("topright", pch = 1, col = c("blue", "red"), legend = c("May", "Other Months")) #baseplot with regression line with(airquality, plot(Wind, Ozone, main = "Ozone and Wind in New York City", pch = 20)) model <- lm(Ozone ~ Wind, airquality) abline(model, lwd = 2) #multiple baseplots par(mfrow = c(1,2)) with(airquality, { plot(Wind, Ozone, main = "Ozone and Wind") plot(Solar.R, Ozone, main = "Ozone and Solr Radiation") }) par(mfrow = c(1, 3), mar = c(4, 4, 2, 1), oma = c(0, 0, 2, 0)) with(airquality, { plot(Wind, Ozone, main = "Ozone and Wind" ) plot(Solar.R, Ozone, main = "Ozone and Solar Radiation") plot(Temp, Ozone, main = "Ozone and Temperature") mtext("Ozone and Weather in New York City", outer = TRUE) }) x <- rnorm(100) hist(x) y <- rnorm(100) plot(x, y) z <- rnorm(100) plot(x, z) par(mar = c(4, 4, 2, 2)) plot(x, y, pch = 20) plot(x, y, pch = 19) plot(x, y, pch = 2) plot(x, y, pch = 3) plot(x, y, pch = 4) example(points) plot(x, y, pch = 20) title("Scatterplot") text(-2, -2, "Label") legend("topright", legend = "Data", pch = 20) fit <- lm(y ~ x) abline(fit) abline(fit, lwd = 3, col = "red") plot(x, y, xlab ="Weight", ylab = "height", main = "Scatterplot", pch = 20) z <- rpois(100, 2) par(mfrow = c(2,1)) plot(x, y, pch = 20 ) plot(x, z, pch = 20) par("mar") par(mar = c(2, 2, 1, 1)) par(mfrow = c(1,2)) plot(x, y, pch = 20 ) plot(x, z, pch = 20) par(mar = c(4, 4, 2, 2)) par(mfrow = c(2, 2)) plot(x, y) plot(x, z) plot(z, x) plot(y, x) par(mfcol = c(2, 2)) plot(x, y) plot(x, z) plot(z, x) plot(y, x) par(mfrow = c(1, 1)) x <- rnorm(100) y <- x + rnorm(100) g <- gl(2, 50) g <- gl(2, 50, labels = c("Male", "Female")) str(g) plot(x, y) plot(x, y, type = "n") points(x[g=="Male"], y[g=="Male"], col ="blue") points(x[g=="Female"], y[g=="Female"], col ="red", pch = 19) ?Devices with(faithful, plot(eruptions, waiting)) title(main = "Old Faithful gyser data") getwd() setwd("C:/learning/coursera/coursera-data_science-data/exploratory_data_analysis/week1") pdf(file = "myplot.pdf") with(faithful, plot(eruptions, waiting)) title(main = "Old Faithful gyser data") dev.off() with(faithful, plot(eruptions, waiting)) title(main = "Old Faithful gyser data") dev.copy(png, file = "geyserplot.png") dev.off()
c7e201eb87579bd3ffb8fbbb57d49853fc939285
33b7262af06cab5cd28c4821ead49b3a0c24bb9d
/pkg/caret/tests/testthat/test_sampling_options.R
b5ae0ef8f56243b3997b70272e0c1b30b10110f2
[]
no_license
topepo/caret
d54ea1125ad41396fd86808c609aee58cbcf287d
5f4bd2069bf486ae92240979f9d65b5c138ca8d4
refs/heads/master
2023-06-01T09:12:56.022839
2023-03-21T18:00:51
2023-03-21T18:00:51
19,862,061
1,642
858
null
2023-03-30T20:55:19
2014-05-16T15:50:16
R
UTF-8
R
false
false
2,493
r
test_sampling_options.R
library(caret) library(testthat) context("sampling options") load(system.file("models", "sampling.RData", package = "caret")) test_that('check appropriate sampling calls by name', { skip_on_cran() arg_names <- c("up", "down", "rose", "smote") arg_funcs <- sampling_methods arg_first <- c(TRUE, FALSE) ## test that calling by string gives the right result for(i in arg_names) { out <- caret:::parse_sampling(i, check_install = FALSE) expected <- list(name = i, func = sampling_methods[[i]], first = TRUE) expect_equivalent(out, expected) } }) test_that('check appropriate sampling calls by function', { skip_on_cran() arg_names <- c("up", "down", "rose", "smote") arg_funcs <- sampling_methods arg_first <- c(TRUE, FALSE) ## test that calling by function gives the right result for(i in arg_names) { out <- caret:::parse_sampling(sampling_methods[[i]], check_install = FALSE) expected <- list(name = "custom", func = sampling_methods[[i]], first = TRUE) expect_equivalent(out, expected) } }) test_that('check bad sampling name', { skip_on_cran() expect_error(caret:::parse_sampling("what?")) }) test_that('check bad first arg', { skip_on_cran() expect_error( caret:::parse_sampling( list(name = "yep", func = sampling_methods[["up"]], first = 2), check_install = FALSE) ) }) test_that('check bad func arg', { skip_on_cran() expect_error( caret:::parse_sampling( list(name = "yep", func = I, first = 2), check_install = FALSE) ) }) test_that('check incomplete list', { skip_on_cran() expect_error(caret:::parse_sampling(list(name = "yep"), check_install = FALSE)) }) test_that('check call', { skip_on_cran() expect_error(caret:::parse_sampling(14, check_install = FALSE)) }) ################################################################### ## test_that('check getting all methods', { skip_on_cran() expect_equivalent(getSamplingInfo(), sampling_methods) }) test_that('check getting one method', { skip_on_cran() arg_names <- c("up", "down", "rose", "smote") for(i in arg_names) { out <- getSamplingInfo(i, regex = FALSE) expected <- list(sampling_methods[[i]]) names(expected) <- i expect_equivalent(out, expected) } }) test_that('check missing method', { skip_on_cran() expect_error(getSamplingInfo("plum")) })
b99835ac2fde0eae55f8b0d0cc3d6f20f57bedc1
accc9bcaf489cbd6d9394a6b7971cb0f80b1d350
/Lung_asthma/Celda_code.R
b2ffcbe66ae3636931f8cba283a41d4706b31731
[]
no_license
zx1an95/JH
f7a6e1d6ca827e3ad81857c4b42d0970aacd731a
5c6de3003f95eacd7b1208164a7d24e2635fdf51
refs/heads/master
2020-12-29T08:40:03.438489
2020-05-05T18:54:28
2020-05-05T18:54:28
238,539,667
0
0
null
null
null
null
UTF-8
R
false
false
10,873
r
Celda_code.R
load("GSE130148_raw_counts.RData") lung_resection <- CreateSeuratObject(counts = raw_counts, project = "lung_resection", min.cells = 3, min.features = 250) lung_resection[["percent.mt"]] <- PercentageFeatureSet(lung_resection, pattern = "^MT-") lung_resection <- subset(lung_resection, subset = nFeature_RNA > 200 & nFeature_RNA < 4000 & percent.mt < 20) lung_resection <- NormalizeData(lung_resection, normalization.method = "LogNormalize", scale.factor = 10000) lung_resection <- FindVariableFeatures(lung_resection, selection.method = "vst", nfeatures = 4500) topgenes <- lung_resection@assays$RNA@var.features library(celda) new_lung_resection <- as.matrix(lung_resection@assays$RNA@counts) new_lung_resection <- new_lung_resection[topgenes,] moduleSplit <- recursiveSplitModule(counts = new_lung_resection, initialL = 3, maxL = 150) #L = 85 plotGridSearchPerplexity(celdaList = moduleSplit) moduleSplitSelect <- subsetCeldaList(moduleSplit, params = list(L = 85)) cellSplit <- recursiveSplitCell(counts = new_lung_resection, initialK = 3, maxK = 45, yInit = clusters(moduleSplitSelect)$y) #K = 30 plotGridSearchPerplexity(celdaList = cellSplit) goodceldaModel <- subsetCeldaList(celdaList = cellSplit, params = list(K = 30, L = 85)) factorized <- factorizeMatrix(new_lung_resection, celdaMod = goodceldaModel) names(factorized) cellPop <- factorized$proportions$cellPopulation topGenes <- topRank(matrix = factorized$proportions$module, n = 5, threshold = NULL) celdaHeatmap(counts = new_lung_resection, celdaMod = goodceldaModel, nfeatures = 5) tsne <- celdaTsne(counts = new_lung_resection, celdaMod = goodceldaModel) plotDimReduceCluster(dim1 = tsne[, 1], dim2 = tsne[, 2], cluster = clusters(goodceldaModel)$z) plotDimReduceFeature(dim1 = tsne[, 1], dim2 = tsne[, 2], counts = new_lung_resection, features = "DCN") celdaProbabilityMap(counts = new_lung_resection, celdaMod = goodceldaModel) moduleHeatmap(counts = new_lung_resection, celdaMod = goodceldaModel, featureModule = 55, topCells = 100) genes <- c(topGenes$names$L76, topGenes$names$L78) geneIx <- which(rownames(new_lung_resection) %in% genes) normCounts <- normalizeCounts(counts = new_lung_resection, scaleFun = scale) plotHeatmap(counts = normCounts, z = clusters(goodceldaModel)$z, y = clusters(goodceldaModel)$y, featureIx = geneIx, showNamesFeature = TRUE) plotDimReduceCluster(dim1 = tsne[, 1], dim2 = tsne[, 2], cluster = clusters(goodceldaModel)$z, specificClusters = c(2,3)) plotDimReduceCluster(dim1 = tsne[, 1], dim2 = tsne[, 2], cluster = clusters(goodceldaModel)$z) plotDimReduceFeature(dim1 = tsne[, 1],dim2 = tsne[, 2],counts = new_lung_resection,features = c("APOC1", "MARCO", "C1QB", "C19orf59", "FABP4")) plotDimReduceFeature(dim1 = tsne[, 1],dim2 = tsne[, 2],counts = new_lung_resection,features = c("SFTPB", "SFTPC", "SFTPA2", "SLPI", "NAPSA")) plotDimReduceFeature(dim1 = tsne[, 1],dim2 = tsne[, 2],counts = new_lung_resection,features = c("IGHA1", "IGHM", "IGHG3", "IGHG1", "IGKC")) plotDimReduceFeature(dim1 = tsne[, 1],dim2 = tsne[, 2],counts = new_lung_resection,features = c("CCL5", "TRBC2", "CD2", "IL32", "TRAC")) plotDimReduceFeature(dim1 = tsne[, 1],dim2 = tsne[, 2],counts = new_lung_resection,features = c("S100A9", "VCAN", "APOBEC3A", "CD300E", "THBS1")) plotDimReduceFeature(dim1 = tsne[, 1],dim2 = tsne[, 2],counts = new_lung_resection,features = c("SCGB1A1", "SCGB3A1", "SCGB3A2", "BPIFB1", "WFDC2")) plotDimReduceFeature(dim1 = tsne[, 1],dim2 = tsne[, 2],counts = new_lung_resection,features = c("TPSAB1", "CPA3", "HPGDS", "KIT", "TPSD1")) plotDimReduceFeature(dim1 = tsne[, 1],dim2 = tsne[, 2],counts = new_lung_resection,features = c("PRG4", "MT2A", "MT1E", "KRT19", "SLC6A14")) plotDimReduceFeature(dim1 = tsne[, 1],dim2 = tsne[, 2],counts = new_lung_resection,features = c("C9orf24", "TPPP3", "C20orf85", "RSPH1", "C11orf88")) plotDimReduceFeature(dim1 = tsne[, 1],dim2 = tsne[, 2],counts = new_lung_resection,features = c("EMP2", "AGER", "CAV1", "RTKN2", "CEACAM6")) plotDimReduceFeature(dim1 = tsne[, 1],dim2 = tsne[, 2],counts = new_lung_resection,features = c("SPARCL1", "EPAS1", "EMP1", "VWF", "SERPINE1")) plotDimReduceFeature(dim1 = tsne[, 1],dim2 = tsne[, 2],counts = new_lung_resection,features = c("GNLY", "NKG7", "GZMA", "FGFBP2")) plotDimReduceFeature(dim1 = tsne[, 1],dim2 = tsne[, 2],counts = new_lung_resection,features = c("HLA-DPA1", "HLA-DQA1", "HLA-DQB1", "GPR183", "FCER1A")) plotDimReduceFeature(dim1 = tsne[, 1],dim2 = tsne[, 2],counts = new_lung_resection,features = c("DCN", "COL1A2", "LUM", "COL3A1", "A2M")) plotDimReduceFeature(dim1 = tsne[, 1],dim2 = tsne[, 2],counts = new_lung_resection,features = c("CCL21", "TFF3", "GNG11", "MMRN1", "LYVE1")) plotDimReduceFeature(dim1 = tsne[, 1],dim2 = tsne[, 2],counts = new_lung_resection,features = c("FCGR3B","S100A9","CSF3R","S100A8","IFITM2")) plotDimReduceFeature(dim1 = tsne[, 1],dim2 = tsne[, 2],counts = new_lung_resection,features = c("CMTM2","MNDA","VNN2","CXCR2","S100P")) plotDimReduceFeature(dim1 = tsne[, 1],dim2 = tsne[, 2],counts = new_lung_resection,features = c("S100A12","RGS2","FPR1","NAMPT","G0S2","IFITM3")) DE <- array() cluster1 <- which(rownames(new_lung_resection) %in% head(diffexpClust1$Gene,20)) Indlist <- c() for (ct in cell_type){ y <- differentialExpression(counts = new_lung_resection, celdaMod = goodceldaModel, c1 = ct, c2 = NULL) y <- y[y$FDR < 0.05 & abs(y$Log2_FC) > 2, ] Indlist <- append(Indlist,which(rownames(new_lung_resection) %in% head(y$Gene,5))) } Indexlist <- which(rownames(new_lung_resection) %in% head(cluster1$Gene,5)) Indexlist <- append(Indexlist,which(rownames(new_lung_resection) %in% head(cluster35$Gene,5))) Indexlist2 <- which((rownames(new_lung_resection) %in% c("APOC1", "MARCO", "C1QB", "C19orf59", "FABP4", "SFTPB", "SFTPC", "SFTPA2", "SLPI", "NAPSA", "IGHA1", "IGHM", "IGHG3", "IGHG1", "IGKC", "CCL5", "TRBC2", "CD2", "IL32", "TRAC", "S100A9", "VCAN", "APOBEC3A", "CD300E", "THBS1", "SCGB1A1", "SCGB3A1", "SCGB3A2", "BPIFB1", "WFDC2", "TPSAB1", "CPA3", "HPGDS", "KIT", "TPSD1", "PRG4", "MT2A", "MT1E", "KRT19", "SLC6A14", "C9orf24", "TPPP3", "C20orf85", "RSPH1", "C11orf88", "EMP2", "AGER", "CAV1", "RTKN2", "CEACAM6", "SPARCL1", "EPAS1", "EMP1", "VWF", "SERPINE1", "GNLY", "NKG7", "GZMA", "FGFBP2", "HLA-DPA1", "HLA-DQA1", "HLA-DQB1", "GPR183", "FCER1A", "DCN", "COL1A2", "LUM", "COL3A1", "A2M", "CCL21", "TFF3", "GNG11", "MMRN1", "LYVE1"))) normCounts <- normalizeCounts(counts = new_lung_resection, scaleFun = scale) cell_type <- c("Macrophages", "Type 2", "Neutrophils", "B cell", "T cell", "Type 1", "Ciliated", "Club", "Endothelium","NK cell", "Mast cell", "Transformed epithelium", "Dendritic cell", "Fibroblast", "Lymphatic") plotHeatmap(counts = normCounts[, clusters(goodceldaModel)$z %in% cell_type], z = clusters(goodceldaModel)$z[clusters(goodceldaModel)$z %in% cell_type], featureIx = Indlist, clusterFeature = FALSE, clusterCell = TRUE, showNamesFeature = TRUE) plotHeatmap(counts = normCounts[, clusters(goodceldaModel)$z %in% cell_type], clusterCell = TRUE, clusterFeature = FALSE, z = clusters(goodceldaModel)$z[clusters(goodceldaModel)$z %in% cell_type], y = clusters(goodceldaModel)$y, featureIx = Indexlist2, showNamesFeature = TRUE) goodceldaModel@clusters$z[goodceldaModel@clusters$z=='27'] <- "26" goodceldaModel@clusters$z[goodceldaModel@clusters$z=='28'] <- "26" goodceldaModel@clusters$z[goodceldaModel@clusters$z=='9'] <- "8" goodceldaModel@clusters$z[goodceldaModel@clusters$z=='10'] <- "8" goodceldaModel@clusters$z[goodceldaModel@clusters$z=='29'] <- "7" goodceldaModel@clusters$z[goodceldaModel@clusters$z=='5'] <- "4" goodceldaModel@clusters$z[goodceldaModel@clusters$z=='6'] <- "4" goodceldaModel@clusters$z[goodceldaModel@clusters$z=='23'] <- "22" goodceldaModel@clusters$z[goodceldaModel@clusters$z=='21'] <- "20" goodceldaModel@clusters$z[goodceldaModel@clusters$z=='26'] <- "Macrophages" goodceldaModel@clusters$z[goodceldaModel@clusters$z=='8'] <- "Type 2" goodceldaModel@clusters$z[goodceldaModel@clusters$z=='7'] <- "B cell" goodceldaModel@clusters$z[goodceldaModel@clusters$z=='18'] <- "T cell" goodceldaModel@clusters$z[goodceldaModel@clusters$z=='24'] <- "Neutrophils" goodceldaModel@clusters$z[goodceldaModel@clusters$z=='4'] <- "Club" goodceldaModel@clusters$z[goodceldaModel@clusters$z=='22'] <- "Mast cell" goodceldaModel@clusters$z[goodceldaModel@clusters$z=='11'] <- "Transformed epithelium" goodceldaModel@clusters$z[goodceldaModel@clusters$z=='11'] <- "Ciliated" goodceldaModel@clusters$z[goodceldaModel@clusters$z=='20'] <- "Type 1" goodceldaModel@clusters$z[goodceldaModel@clusters$z=='15'] <- "Endothelium" goodceldaModel@clusters$z[goodceldaModel@clusters$z=='19'] <- "NK cell" goodceldaModel@clusters$z[goodceldaModel@clusters$z=='30'] <- "Dendritic cell" goodceldaModel@clusters$z[goodceldaModel@clusters$z=='13'] <- "Lymphatic" goodceldaModel@clusters$z[goodceldaModel@clusters$z=='1'] <- "B cell" goodceldaModel@clusters$z[goodceldaModel@clusters$z=='12'] <- "Club" goodceldaModel@clusters$z[goodceldaModel@clusters$z=='14'] <- "B cell" goodceldaModel@clusters$z[goodceldaModel@clusters$z=='2'] <- "B cell" goodceldaModel@clusters$z[goodceldaModel@clusters$z=='3'] <- "B cell" goodceldaModel@clusters$z[goodceldaModel@clusters$z=='25'] <- "Neutrophils" length(unique(goodceldaModel@clusters$z))
d08c3a08948203fc8d97b1a89cbdf6676248d67d
7090f45f05d288c426d91515ea0a80371c402fcc
/tests/testthat/test-search.R
bdc29b349b76c4f2f460ec9507731b57705c6c97
[ "MIT" ]
permissive
KTH-Library/dblp
5969671b9d6a11c19646aac3a309ad6aaa1966ef
8a5488b2a9c13c9506c497fdfaa75b4ec7384e50
refs/heads/master
2021-08-26T01:01:14.531024
2021-08-18T15:15:44
2021-08-18T15:15:44
246,881,922
0
0
null
null
null
null
UTF-8
R
false
false
400
r
test-search.R
test_that("search works", { t1 <- dblp_search("European", entity = "venues")$content expect_gt(nrow(t1), 5) }) test_that("search venues w zero hits works", { t1 <- dblp_search("venues", entity = "venues")$content expect_equal(nrow(t1), 0) }) test_that("search authors w zero hits works", { t1 <- dblp_search("nooneinparticular", entity = "authors")$content expect_equal(nrow(t1), 0) })
6307f3c80c9aea88ca07aba9504bbfb424262a6f
1277466828a8aa3bfd8e3d3280b9f21a8b575cf4
/app/global.R
159186d51bcccc901e321d9ed697839cad0deb8b
[]
no_license
gabrielteotonio/pca-image-compression
c8e52acd855cc2aff842967c11b7aeeacf8e0f3d
734282c32ab76da9a55b6a912c1ababfade6cb23
refs/heads/master
2020-05-15T10:38:52.418552
2019-04-20T23:45:23
2019-04-20T23:45:23
182,195,726
4
0
null
null
null
null
UTF-8
R
false
false
2,124
r
global.R
# Packages ---- library(shiny) library(EMD) # Lena's image library(blockmatrix) # For creating block matrices library(ggplot2) # Graphics library(redR) # For MSE and PSNR measures library(SPUTNIK) # For SSIM measure # Loading data ---- data(lena) # Storage the image # Functions ---- blockToObs <- function(block_matrix) { obs_matrix <- c() for (i in 1:64) { for (j in 1:64) { obs <- as.vector(t(block_matrix[i,j])) obs_matrix <- rbind(obs_matrix, obs) } } return(obs_matrix) } obsToBlock <- function(Obs_matrix) { matrix <- matrix(0, nrow = 512, ncol = 512) cont <- 1 for (i in seq(1,512,8)) { for (j in seq(1,512,8)) { block_matrix <- matrix(Obs_matrix[cont,], nrow = 8, ncol = 8, byrow = T) matrix[i:(i+8-1), j:(j+8-1)] <- block_matrix cont <- cont + 1 } } return(matrix) } Tmatrix <- function(m) { t_m <- diag(0, ncol = 64, nrow = 64) for (i in 1:m) { t_m[i,i] <- 1 } return(t_m) } pca <- function(data) { lena_block <- as.blockmatrix(data, nrowe = 8, ncole = 8) # Create a block matrix for image data x <- blockToObs(lena_block) # Transform a block matrix into a "dataframe" (blocks by row) x_cent <- scale(x, center = T, scale = F) # Centering the matrix cov_matrix <- t(x_cent) %*% x_cent # Calculating the Covariance matrix eigen_pairs <- eigen(cov_matrix) # Calculating eigenvalues and eigenvectors eigenvalues <- eigen_pairs$values # Accessing eigenvalues eigenvectors <- eigen_pairs$vectors # Accessing eigenvectors results <- list("x" = x, "eigenvalues" = eigenvalues, "eigenvectors" = eigenvectors) return(results) } compression <- function(x, eigenvectors, m) { y <- x %*% eigenvectors # Creating the new "dataframe" with new p principal components t_m <- Tmatrix(m) # T matrix for define the number of p taking into account y_m <- y %*% t_m # Creating the new "dataframe" with new p = dim(t_m) principal components b <- y_m %*% t(eigenvectors) # Inverse of the transformation B <- obsToBlock(b) # The image generating matrix return(B) # Returning the image matrix } PCA <- pca(lena)
ad2106406837b11d40646fb906428e47a756a8f9
034af5f06904647579ab75acca51ca597611eca8
/func-room.R
eb1ba58e2e1af5c674741df519ac14a10cfe7556
[ "MIT" ]
permissive
rintukutum/DREAM-PretermBirth-SC2
bc1218a0d70755655ce59ff8d2dfdcc6df803adf
f49a0ed96d36941a7ff14764594eb0fe73d4e024
refs/heads/master
2020-12-02T03:34:11.741355
2019-12-31T14:24:37
2019-12-31T14:24:37
230,874,237
0
0
null
null
null
null
UTF-8
R
false
false
3,804
r
func-room.R
ctrl.sptd <- function(x){ x.ctrl <- x[idx.ctrl] x.sptd <- x[idx.sptd] df_ <- data.frame( class = rep( c('ctrl','sptd'), c(length(x.ctrl), length(x.sptd))), value = c( x.ctrl, x.sptd ) ) normal <- shapiro.test(df_$value)$p.value > 0.05 if(normal){ pval <- t.test(value~class,data=df_)$p.value }else{ pval <- wilcox.test(value~class,data=df_)$p.value } return(pval) } ctrl.pprom <- function(x){ x.ctrl <- x[idx.ctrl] x.pprom <- x[idx.pprom] df_ <- data.frame( class = rep( c('ctrl','pprom'), c(length(x.ctrl), length(x.pprom))), value = c( x.ctrl, x.pprom ) ) normal <- shapiro.test(df_$value)$p.value > 0.05 if(normal){ pval <- t.test(value~class,data=df_)$p.value }else{ pval <- wilcox.test(value~class,data=df_)$p.value } return(pval) } performSVM <- function(tr.x,tr.y,tt.x,SEED=7860){ # tr.x <- ctrl.PPROM.sig.2H.probes.data$tr.x[,1:100] # tr.y <- ctrl.PPROM.sig.2H.probes.data$tr.y # tt.x <- ctrl.PPROM.sig.2H.probes.data$tt.x[,1:100] library(e1071) library(caret) library(foreach) set.seed(SEED) cv.5 <- createFolds(tr.y,k = 5) out <- list() for(i in 1:length(cv.5)){ idx.tr <- unlist(cv.5[-i]) idx.tt <- unlist(cv.5[i]) mini.tr.x <- tr.x[idx.tr,] mini.tr.y <- tr.y[idx.tr] mini.tt.x <- tr.x[idx.tt,] mini.tt.y <- tr.y[idx.tt] #-------------------- # MODELS mod.linear <- svm( x = mini.tr.x, y= mini.tr.y, kernel = 'linear', probability = TRUE ) pred.linear <- predict( mod.linear, mini.tt.x ) mod.radial <- svm( x = mini.tr.x, y= mini.tr.y, kernel = 'radial', probability = TRUE ) pred.radial <- predict( mod.radial, mini.tt.x ) mod.sigmoid <- svm( x = mini.tr.x, y= mini.tr.y, kernel = 'sigmoid', probability = TRUE ) pred.sigmoid <- predict( mod.sigmoid, mini.tt.x ) tmpOUT.r <- getCVperf( pred = pred.radial, orig = mini.tt.y, mod.method = 'SVM.radial' ) tmpOUT.s <- getCVperf( pred = pred.sigmoid, orig = mini.tt.y, mod.method = 'SVM.sigmoid' ) tmpOUT.l <- getCVperf( pred = pred.linear, orig = mini.tt.y, mod.method = 'SVM.linear' ) perf.svm <- list( tmpOUT.r, tmpOUT.s, tmpOUT.l ) perf.svm.df <- plyr::ldply(perf.svm) #--------- # PREDICT TT tt.linear <- predict(mod.linear,tt.x,probability = TRUE) tt.linear <- data.frame(round(attr(tt.linear,'probabilities'),4)) tt.linear$SampleID <- rownames(tt.linear) tt.sigmoid <- predict(mod.sigmoid,tt.x,probability = TRUE) tt.sigmoid <- data.frame(round(attr(tt.sigmoid,'probabilities'),4)) tt.sigmoid$SampleID <- rownames(tt.sigmoid) tt.radial <- predict(mod.radial,tt.x,probability = TRUE) tt.radial <- data.frame(round(attr(tt.radial,'probabilities'),4)) tt.radial$SampleID <- rownames(tt.radial) tt.out <- list( 'linear' = tt.linear, 'sigmoid' = tt.sigmoid, 'radial' = tt.radial ) OUT <- list( perf = perf.svm.df, tt.prediction = plyr::ldply(tt.out) ) out[[i]] <- OUT } names(out) <- paste0('CV',1:length(cv.5)) return(out) } getCVperf <- function(pred, orig, mod.method){ xout <- caret::confusionMatrix( data = pred, reference=orig ) df_ <- data.frame(xout$byClass[c('Sensitivity','Specificity')]) colnames(df_)[1] <- 'val' df_$property <- rownames(df_) df_$method <- mod.method return(df_) } extractMODpred <- function(x,method){ x <- x$tt.prediction idx <- x$.id %in% method return(x[idx,]) }
34eb6636e8a3f8a1d17c6f1f6e76b73a35377358
df5cfd2a2c753abae911f275b8842ae2905b0e98
/tests/testthat/test-correlation.R
13d8f0144c42cf0de5c91ecd6b11ad1ec9766887
[]
no_license
cran/roahd
badc33125a145e40ad62ca4cb46dbb3686d1a004
678f7c77246bcbd290673ce405519eddb3a323f7
refs/heads/master
2021-11-23T08:04:45.984396
2021-11-03T23:10:02
2021-11-03T23:10:02
56,397,799
0
0
null
null
null
null
UTF-8
R
false
false
16,268
r
test-correlation.R
# maxima() & minima() ----------------------------------------------------- test_that("maxima() works for functional data when `which = TRUE`", { # Arrange P <- 1e4 time_grid <- seq(0, 1, length.out = P) h <- time_grid[2] - time_grid[1] Data <- matrix(c(1 * time_grid, 2 * time_grid, 3 * ( 0.5 - abs( time_grid - 0.5))), nrow = 3, ncol = P, byrow = TRUE) fD <- fData(time_grid, Data) # Act actual <- maxima(fD, which = TRUE) # Assert expected_grid <- c(1, 1, 0 + 4999 * h) expected_value <- c(1, 2, 3 * ( 0.5 - abs( 0.5 - 4999 * h))) expect_equal(actual$grid, expected_grid) expect_equal(actual$value, expected_value) }) test_that("minima() works for functional data when `which = TRUE`", { # Arrange P <- 1e4 time_grid <- seq(0, 1, length.out = P) Data <- matrix(c(1 * time_grid, 2 * time_grid, 3 * ( 0.5 - abs( time_grid - 0.5))), nrow = 3, ncol = P, byrow = TRUE) fD <- fData(time_grid, Data) # Act actual <- minima(fD, which = TRUE) # Assert expected_grid <- rep(0, 3) expected_value <- rep(0, 3) expect_equal(actual$grid, expected_grid) expect_equal(actual$value, expected_value) }) test_that("maxima() works for functional data when `which = FALSE`", { # Arrange P <- 1e4 time_grid <- seq(0, 1, length.out = P) h <- time_grid[2] - time_grid[1] Data <- matrix(c(1 * time_grid, 2 * time_grid, 3 * ( 0.5 - abs( time_grid - 0.5))), nrow = 3, ncol = P, byrow = TRUE) fD <- fData(time_grid, Data) # Act actual <- maxima(fD, which = FALSE) # Assert expected <- c(1, 2, 3 * (0.5 - abs( 0.5 - 4999 * h))) expect_equal(actual, expected) }) test_that("minima() works for functional data when `which = FALSE`", { # Arrange P <- 1e4 time_grid <- seq(0, 1, length.out = P) Data <- matrix(c(1 * time_grid, 2 * time_grid, 3 * ( 0.5 - abs( time_grid - 0.5))), nrow = 3, ncol = P, byrow = TRUE) fD <- fData(time_grid, Data) # Act actual <- minima(fD, which = FALSE) # Assert expected <- rep(0, 3) expect_equal(actual, expected) }) # area_under_curve() ------------------------------------------------------ test_that("area_under_curve() works for functional data", { # Arrange P <- 1e4 time_grid <- seq(0, 1, length.out = P) fD_1 <- fData(time_grid, matrix(c(1 * time_grid, 2 * time_grid, 3 * ( 0.5 - abs( time_grid - 0.5))), nrow = 3, ncol = P, byrow = TRUE)) fD_2 <- fData(time_grid, matrix(c(sin(2 * pi * time_grid), cos(2 * pi * time_grid), 4 * time_grid * (1 - time_grid)), nrow = 3, ncol = P, byrow = TRUE)) # Act actual <- area_under_curve(fD_1) # Assert expected <- c(0.5, 1, 0.75) expect_equal(actual, expected) expect_true(all(c( area_under_curve(fD_2)[1:2], abs(area_under_curve(fD_2[3, ]) - 2/3) ) <= .Machine$double.eps^0.5)) }) # Ordering functions ------------------------------------------------------ test_that("max_ordered() works as expected", { # Arrange P <- 1e3 time_grid <- seq(0, 1, length.out = P) h <- time_grid[2] - time_grid[1] Data_1 <- matrix( c(1 * time_grid, 2 * time_grid), nrow = 2, ncol = P, byrow = TRUE ) Data_2 <- matrix( 3 * (0.5 - abs(time_grid - 0.5)), nrow = 1, byrow = TRUE ) Data_3 <- rbind(Data_1, Data_1) fD_1 <- fData(time_grid, Data_1) fD_2 <- fData(time_grid, Data_2) fD_3 <- fData(time_grid, Data_3) # Act actual_max_1 <- max_ordered(fD_1, fD_2) actual_max_2 <- max_ordered(fD_2, fD_1) actual_max_3 <- max_ordered(fD_2, fD_3) actual_max_4 <- max_ordered(fD_3, fD_2) # Assert expected_max_1 <- c(TRUE, FALSE) expect_equal(actual_max_1, expected_max_1) expected_max_2 <- c(FALSE, TRUE) expect_equal(actual_max_2, expected_max_2) expect_error(max_ordered(fD_1, fD_3)) expect_error(max_ordered(fD_3, fD_1)) expected_max_3 <- c(FALSE, TRUE, FALSE, TRUE) expect_equal(actual_max_3, expected_max_3) expected_max_4 <- c(TRUE, FALSE, TRUE, FALSE) expect_equal(actual_max_4, expected_max_4) }) test_that("area_ordered() works as expected", { # Arrange P <- 1e3 time_grid <- seq(0, 1, length.out = P) h <- time_grid[2] - time_grid[1] Data_1 <- matrix( c(1 * time_grid, 2 * time_grid), nrow = 2, ncol = P, byrow = TRUE ) Data_2 <- matrix( 3 * (0.5 - abs(time_grid - 0.5)), nrow = 1, byrow = TRUE ) Data_3 <- rbind(Data_1, Data_1) fD_1 <- fData(time_grid, Data_1) fD_2 <- fData(time_grid, Data_2) fD_3 <- fData(time_grid, Data_3) # Act actual_area_1 <- area_ordered(fD_1, fD_2) actual_area_2 <- area_ordered(fD_2, fD_1) actual_area_3 <- area_ordered(fD_2, fD_3) actual_area_4 <- area_ordered(fD_3, fD_2) # Assert expected_area_1 <- c(TRUE, FALSE) expect_equal(actual_area_1, expected_area_1) expected_area_2 <- c(FALSE, TRUE) expect_equal(actual_area_2, expected_area_2) expect_error(area_ordered(fD_1, fD_3)) expect_error(area_ordered(fD_3, fD_1)) expected_area_3 <- c(FALSE, TRUE, FALSE, TRUE) expect_equal(actual_area_3, expected_area_3) expected_area_4 <- c(TRUE, FALSE, TRUE, FALSE) expect_equal(actual_area_4, expected_area_4) }) # cor_kendall() & cor_spearman() ------------------------------------------ test_that("cor_kendall() and cor_spearman() work as expected", { # Arrange withr::local_seed(1234) N <- 2e2 P <- 1e3 time_grid <- seq(0, 1, length.out = P) Cov <- exp_cov_function(time_grid, alpha = 0.3, beta = 0.4) Data_1 <- generate_gauss_fdata( N, centerline = sin(2 * pi * time_grid), Cov = Cov ) Data_2 <- generate_gauss_fdata( N, centerline = sin(2 * pi * time_grid), Cov = Cov ) mfD <- mfData(time_grid, list(Data_1, Data_2)) # Act actual_kendall_max <- cor_kendall(mfD, ordering = 'max') actual_kendall_area <- cor_kendall(mfD, ordering = 'area') actual_spearman_mei <- cor_spearman(mfD, ordering = 'MEI') actual_spearman_mhi <- cor_spearman(mfD, ordering = 'MHI') # Assert expect_snapshot_value(actual_kendall_max, style = "serialize") expect_snapshot_value(actual_kendall_area, style = "serialize") expect_snapshot_value(actual_spearman_mei, style = "serialize") expect_snapshot_value(actual_spearman_mhi, style = "serialize") }) # Case studies from Dalia Valencia, Rosa Lillo, Juan Romo ----------------- test_that("cor_kendall() & cor_spearman() work on Case Study 1 from Dalia Valencia, Rosa Lillo, Juan Romo.", { withr::local_seed(1234) N <- 50 P <- 50 time_grid<- seq(0, 1, length.out = P) sigma_12 <- 0.8 R <- matrix(c(1, sigma_12, sigma_12, 1), ncol = 2, nrow = 2) Z <- matrix(rnorm(N * 2, 0, 1), ncol = 2, nrow = N) %*% chol(R) X <- (matrix(time_grid, nrow = N, ncol = P, byrow = TRUE) + Z[, 1])^3 + (matrix(time_grid, nrow = N, ncol = P, byrow = TRUE) + Z[, 1])^2 + (matrix(time_grid, nrow = N, ncol = P, byrow = TRUE) + Z[, 1]) * 3 Y <- (matrix(time_grid, nrow = N, ncol = P, byrow = TRUE) + Z[, 2])^2 + (matrix(time_grid, nrow = N, ncol = P, byrow = TRUE) + Z[, 2]) * 7 / 8 + - 10 mfD <- mfData(time_grid, list(X, Y)) expect_snapshot_value(cor_kendall(mfD, ordering = 'max'), style = "serialize") expect_snapshot_value(cor_kendall(mfD, ordering = 'area'), style = "serialize") expect_snapshot_value(cor_spearman(mfD, ordering = 'MEI'), style = "serialize") expect_snapshot_value(cor_spearman(mfD, ordering = 'MHI'), style = "serialize") }) test_that("cor_kendall() & cor_spearman() work on Case Study 2 from Dalia Valencia, Rosa Lillo, Juan Romo.", { withr::local_seed(1234) N <- 50 P <- 50 time_grid<- seq(0, 1, length.out = P) sigma_12 <- - 0.7 R <- matrix(c(1, sigma_12, sigma_12, 1), ncol = 2, nrow = 2) Z <- matrix(rnorm(N * 2, 0, 1), ncol = 2, nrow = N) %*% chol(R) X <- sin(matrix(time_grid, nrow = N, ncol = P, byrow = TRUE) + Z[, 1]) Y <- cos(matrix(time_grid, nrow = N, ncol = P, byrow = TRUE) + Z[, 2]) mfD <- mfData(time_grid, list(X, Y)) expect_snapshot_value(cor_kendall(mfD, ordering = 'max'), style = "serialize") expect_snapshot_value(cor_kendall(mfD, ordering = 'area'), style = "serialize") expect_snapshot_value(cor_spearman(mfD, ordering = 'MEI'), style = "serialize") expect_snapshot_value(cor_spearman(mfD, ordering = 'MHI'), style = "serialize") }) test_that("cor_kendall() & cor_spearman() work on Case Study 3 from Dalia Valencia, Rosa Lillo, Juan Romo.", { withr::local_seed(1234) N <- 50 P <- 50 time_grid<- seq(0, 1, length.out = P) sigma_12 <- 1 Z <- rnorm(N, 0, 1) X <- (matrix(time_grid, nrow = N, ncol = P, byrow = TRUE) + Z)^2 Y <- (matrix(time_grid, nrow = N, ncol = P, byrow = TRUE) + Z)^4 mfD <- mfData(time_grid, list(X, Y)) expect_equal(cor_kendall(mfD, ordering = 'max' ), 1) expect_equal(cor_kendall(mfD, ordering = 'area'), 1) expect_equal(cor_spearman(mfD, ordering = 'MEI'), 1) expect_equal(cor_spearman(mfD, ordering = 'MHI'), 1) }) test_that("cor_kendall() & cor_spearman() work on Case Study 4 from Dalia Valencia, Rosa Lillo, Juan Romo.", { withr::local_seed(1234) N <- 50 P <- 50 time_grid<- seq(0, 1, length.out = P) sigma_12 <- 1 Z <- rnorm(N, 0, 1) X <- (matrix(time_grid, nrow = N, ncol = P, byrow = TRUE) + Z)^2 + (matrix(time_grid, nrow = N, ncol = P, byrow = TRUE) + Z) * 7 + 2 Y <- ((matrix(time_grid, nrow = N, ncol = P, byrow = TRUE) + Z)^2 + (matrix(time_grid, nrow = N, ncol = P, byrow = TRUE) + Z) * 7 + 2)^3 mfD <- mfData(time_grid, list(X, Y)) expect_equal(cor_kendall(mfD, ordering = 'max' ), 1) expect_equal(cor_kendall(mfD, ordering = 'area'), 1) expect_equal(cor_spearman(mfD, ordering = 'MEI'), 1) expect_equal(cor_spearman(mfD, ordering = 'MHI'), 1) }) test_that("cor_kendall() & cor_spearman() work on Case Study 5 from Dalia Valencia, Rosa Lillo, Juan Romo.", { withr::local_seed(1234) N <- 50 P <- 50 time_grid<- seq(0, 1, length.out = P) sigma_12 <- 1 Z <- rnorm(N, 0, 1) X <- (matrix(time_grid, nrow = N, ncol = P, byrow = TRUE) + Z)^2 + (matrix(time_grid, nrow = N, ncol = P, byrow = TRUE) + Z) * 7 + 2 Y <- 1 - ((matrix(time_grid, nrow = N, ncol = P, byrow = TRUE) + Z)^2 + (matrix(time_grid, nrow = N, ncol = P, byrow = TRUE) + Z) * 7 + 2)^3 mfD <- mfData(time_grid, list(X, Y)) expect_equal(cor_kendall(mfD, ordering = 'max' ), -1) expect_equal(cor_kendall(mfD, ordering = 'area'), -1) expect_equal(cor_spearman(mfD, ordering = 'MEI'), -1) expect_equal(cor_spearman(mfD, ordering = 'MHI'), -1) }) test_that("cor_kendall() & cor_spearman() work on Case Study 6 from Dalia Valencia, Rosa Lillo, Juan Romo.", { withr::local_seed(1234) N <- 50 P <- 50 time_grid<- seq(0, 1, length.out = P) sigma_12 <- 0.6 R <- matrix(c(1, sigma_12, sigma_12, 1), ncol = 2, nrow = 2) Z <- matrix(rnorm(N * 2, 0, 1), ncol = 2, nrow = N) %*% chol(R) X <- exp(matrix(time_grid, nrow = N, ncol = P, byrow = TRUE) + Z[, 1]) Y <- (matrix(time_grid, nrow = N, ncol = P, byrow = TRUE) + Z[, 2])^3 + (matrix(time_grid, nrow = N, ncol = P, byrow = TRUE) + Z[, 2])^2 + (matrix(time_grid, nrow = N, ncol = P, byrow = TRUE) + Z[, 2]) * 3 mfD <- mfData(time_grid, list(X, Y)) expect_snapshot_value(cor_kendall(mfD, ordering = 'max'), style = "serialize") expect_snapshot_value(cor_kendall(mfD, ordering = 'area'), style = "serialize") expect_snapshot_value(cor_spearman(mfD, ordering = 'MEI'), style = "serialize") expect_snapshot_value(cor_spearman(mfD, ordering = 'MHI'), style = "serialize") }) test_that("cor_kendall() & cor_spearman() work on Case Study 7 from Dalia Valencia, Rosa Lillo, Juan Romo.", { withr::local_seed(1234) N <- 50 P <- 50 time_grid<- seq(0, 1, length.out = P) sigma_12 <- -0.8 R <- matrix(c(1, sigma_12, sigma_12, 1), ncol = 2, nrow = 2) Z <- matrix(rnorm(N * 2, 0, 1), ncol = 2, nrow = N) %*% chol(R) X <- exp(matrix(time_grid, nrow = N, ncol = P, byrow = TRUE) + Z[, 1])^2 Y <- cos((matrix(time_grid, nrow = N, ncol = P, byrow = TRUE) + Z[, 2])) mfD <- mfData(time_grid, list(X, Y)) expect_snapshot_value(cor_kendall(mfD, ordering = 'max'), style = "serialize") expect_snapshot_value(cor_kendall(mfD, ordering = 'area'), style = "serialize") expect_snapshot_value(cor_spearman(mfD, ordering = 'MEI'), style = "serialize") expect_snapshot_value(cor_spearman(mfD, ordering = 'MHI'), style = "serialize") }) test_that("cor_kendall() & cor_spearman() work on Case Study 8 from Dalia Valencia, Rosa Lillo, Juan Romo.", { withr::local_seed(1234) N <- 50 P <- 50 time_grid<- seq(0, 1, length.out = P) sigma_12 <- 0.4 R <- matrix(c(1, sigma_12, sigma_12, 1), ncol = 2, nrow = 2) Z <- matrix(rnorm(N * 2, 0, 1), ncol = 2, nrow = N) %*% chol(R) X <- sin(matrix(time_grid, nrow = N, ncol = P, byrow = TRUE) + Z[, 1]) Y <- (matrix(time_grid, nrow = N, ncol = P, byrow = TRUE) + Z[, 2])^2 mfD <- mfData(time_grid, list(X, Y)) expect_snapshot_value(cor_kendall(mfD, ordering = 'max'), style = "serialize") expect_snapshot_value(cor_kendall(mfD, ordering = 'area'), style = "serialize") expect_snapshot_value(cor_spearman(mfD, ordering = 'MEI'), style = "serialize") expect_snapshot_value(cor_spearman(mfD, ordering = 'MHI'), style = "serialize") }) test_that("cor_kendall() & cor_spearman() work on Case Study 9 from Dalia Valencia, Rosa Lillo, Juan Romo.", { withr::local_seed(1234) N <- 50 P <- 50 time_grid<- seq(0, 1, length.out = P) sigma_12 <- 1 Z <- rnorm(N, 0, 1) X <- (matrix(time_grid, nrow = N, ncol = P, byrow = TRUE) + Z)^2 + (matrix(time_grid, nrow = N, ncol = P, byrow = TRUE) + Z) * 9 + - 5 Y <- cos(matrix(3 * time_grid, nrow = N, ncol = P, byrow = TRUE) + Z) mfD <- mfData(time_grid, list(X, Y)) expect_snapshot_value(cor_kendall(mfD, ordering = 'max'), style = "serialize") expect_snapshot_value(cor_kendall(mfD, ordering = 'area'), style = "serialize") expect_snapshot_value(cor_spearman(mfD, ordering = 'MEI'), style = "serialize") expect_snapshot_value(cor_spearman(mfD, ordering = 'MHI'), style = "serialize") }) test_that("cor_kendall() & cor_spearman() work on Case Study 10 from Dalia Valencia, Rosa Lillo, Juan Romo.", { withr::local_seed(1234) N <- 50 P <- 50 time_grid<- seq(0, 1, length.out = P) sigma_12 <- 0.9 R <- matrix(c(1, sigma_12, sigma_12, 1), ncol = 2, nrow = 2) Z <- matrix(rnorm(N * 2, 0, 1), ncol = 2, nrow = N) %*% chol(R) X <- exp(matrix(time_grid, nrow = N, ncol = P, byrow = TRUE)^2 + Z[, 1]) Y <- (matrix(time_grid, nrow = N, ncol = P, byrow = TRUE) + Z[, 2])^2 + matrix(time_grid, nrow = N, ncol = P, byrow = TRUE) * (-8) + (matrix(0, nrow = N, ncol = P, byrow = TRUE) + Z[, 2]) mfD <- mfData(time_grid, list(X, Y)) expect_snapshot_value(cor_kendall(mfD, ordering = 'max'), style = "serialize") expect_snapshot_value(cor_kendall(mfD, ordering = 'area'), style = "serialize") expect_snapshot_value(cor_spearman(mfD, ordering = 'MEI'), style = "serialize") expect_snapshot_value(cor_spearman(mfD, ordering = 'MHI'), style = "serialize") }) test_that("cor_kendall() & cor_spearman() work on Case Study 11 from Dalia Valencia, Rosa Lillo, Juan Romo.", { withr::local_seed(1234) N <- 50 P <- 50 time_grid <- seq(0, 1, length.out = P) sigma_12 <- 0. R <- matrix(c(1, sigma_12, sigma_12, 1), ncol = 2, nrow = 2) Z <- matrix(rnorm(N * 2, 0, 1), ncol = 2, nrow = N) %*% chol(R) X <- exp(matrix(time_grid, nrow = N, ncol = P, byrow = TRUE) + Z[, 1]) Y <- sin(matrix(time_grid, nrow = N, ncol = P, byrow = TRUE) + Z[, 2]) mfD <- mfData(time_grid, list(X, Y)) expect_snapshot_value(cor_kendall(mfD, ordering = 'max'), style = "serialize") expect_snapshot_value(cor_kendall(mfD, ordering = 'area'), style = "serialize") expect_snapshot_value(cor_spearman(mfD, ordering = 'MEI'), style = "serialize") expect_snapshot_value(cor_spearman(mfD, ordering = 'MHI'), style = "serialize") })
c3c0c5281b141ecd384fe2a9fa73d679bdcdb6ab
7eb63399fa00e3c547e5933ffa4f47de515fe2c6
/man/serr.lgcpPredict.Rd
71f11a4aa35097a21ca750e1c25fbd13e4b8d2b6
[]
no_license
bentaylor1/lgcp
a5cda731f413fb30e1c40de1b3360be3a6a53f19
2343d88e5d25ecacd6dbe5d6fcc8ace9cae7b136
refs/heads/master
2021-01-10T14:11:38.067639
2015-11-19T13:22:19
2015-11-19T13:22:19
45,768,716
2
0
null
null
null
null
UTF-8
R
false
false
514
rd
serr.lgcpPredict.Rd
% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/lgcpMethods.R \name{serr.lgcpPredict} \alias{serr.lgcpPredict} \title{serr.lgcpPredict function} \usage{ \method{serr}{lgcpPredict}(obj, ...) } \arguments{ \item{obj}{an lgcpPredict object} \item{...}{additional arguments} } \value{ Standard error of the relative risk as computed by MCMC. } \description{ Accessor function returning the standard error of relative risk as an lgcpgrid object. } \seealso{ \link{lgcpPredict} }
501faccfb23e26f090d46c5a4b5bc247d20813ca
89f7311158c333e2e35f12fda6af01e00d9ca55d
/man/preprocess_experiment.Rd
b7cf0ff711c0b9e22a565280e120912ef1175def
[]
no_license
BrainVR/brainvr-gonogo
282b3165f606203cc4c20c6baaeeea04b923996f
b7c133822d2c54311c229a89f106f9c2229e644e
refs/heads/main
2023-09-01T14:59:20.664380
2021-10-30T20:44:14
2021-10-30T20:44:14
384,252,148
0
0
null
null
null
null
UTF-8
R
false
true
385
rd
preprocess_experiment.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/gonogo-preprocessing.R \name{preprocess_experiment} \alias{preprocess_experiment} \title{Prepares experimental data to cleaner stats} \usage{ preprocess_experiment(df_experiment) } \arguments{ \item{df_experiment}{} } \value{ } \description{ Renames columns, recodes some values, adds new deduced values }
89d2353b8781f73823b73d2141d4d1b3582c03d9
5bae3c3cd5e47b3088e0fb6478a60ae74e8f7767
/rawdata/rawcleandata.R
d2e0b157772f1cb3dabe98a640275598fa5d2eea
[]
no_license
gravatarsmiley/capstoneR
04d4093e63815b3ec91102c1a0ec8f6b869e5838
28154a9e672b1a23d5a76233ef380eb193b08b85
refs/heads/master
2020-03-20T19:15:23.746641
2018-06-24T22:27:07
2018-06-24T22:27:07
137,628,993
0
0
null
null
null
null
UTF-8
R
false
false
365
r
rawcleandata.R
# Load and clean up the NOAA data, and put .rdata into the data directory # need devtools, dplyr, readr library(devtools) library(dplyr) library(lubridate) library(readr) library(stringr) # read in the raw data raw_NOAA <- readr::read_delim('./rawdata/signif.txt',delim = '\t') # now use data clean_NOAA <- eq_clean_data(raw_NOAA) devtools::use_data(clean_NOAA)
693251f3d29d788d5547590e0ef8d8195e886491
7f1fbfc87e553e2304f80c16b523ffd3dd57dedf
/plot4.R
b457820a5312cf684fda17136786fedaf8f3352b
[]
no_license
rupesh2017/ExData_Plotting1
b8cb1821b1b9397b0b93274a32daa0589c1b1f52
652bea9363743d7aa972a05859fd7f0e7ad1136d
refs/heads/master
2020-03-22T00:12:27.840224
2018-06-30T08:01:48
2018-06-30T08:01:48
138,697,007
0
0
null
2018-06-26T06:55:02
2018-06-26T06:55:00
null
UTF-8
R
false
false
1,661
r
plot4.R
#set working directory #reading data #find column class to read file faster a <- read.table(file="household_power_consumption.txt",header=TRUE,sep=";",nrows = 5) classes <- sapply(a,class) #read the file file <- read.table(file="household_power_consumption.txt",header=TRUE,sep=";",nrow=2075259,colClasses = classes,na.strings = "?") #change the date which was factor to date class file$Date <- as.Date(file$Date,"%d/%m/%Y") #subset required date data <- file[file$Date >="2007-02-01" & file$Date<="2007-02-02",] #format both date and time in combination,also paste convert the time of factor class to #character class and strptime change it to time class x <- strptime(paste(data$Date,data$Time),"%Y-%m-%d %H:%M:%S") #----------------------------------------------------------------------------------------- #initialise png graphics # no need for width and height argument by default it is 480p both png("plot4.png") #set 2 column and 2 row using mfrow for 4 graphs and choose margin using mar par(mfrow=c(2,2),mar=c(4,4,4,4)) #1 plot(x,data$Global_active_power,type="l",xlab="",ylab="Global Active Power") #2 plot(x,data$Voltage,type="l",xlab="datatime",ylab="Voltage") #3 plot(x,data$Sub_metering_1,type="l",xlab="",ylab="Energy sub metering") lines(x,data$Sub_metering_2,type="l",col="red") lines(x,data$Sub_metering_3,type="l",col="blue") legend("topright",legend=c("sub_metering_1","sub_metering_2","sub_metering_3"),col=c("black","red","blue"),lty=(rep(1,3)),bty="n",cex=0.70) #4 plot(x,data$Global_reactive_power,type="l",xlab="datatime",ylab="Global_reactive_power") #turn off graphics dev.off()
782ef9e894eb5c17c5994ebc040cc187d8770ca2
cbb287e2060194451f8f4dc4b68dc9de5b20a8d9
/cachematrix.R
b682eb00d48ce24653af49c05ffdb5405cadb710
[]
no_license
DonResnik/ProgrammingAssignment2
7410c028818a2d8f6483c392e0de20cfa370e57a
fdff4bdba81e3ba9f533194eee1221838b9898f8
refs/heads/master
2021-01-15T13:52:35.622413
2016-03-25T01:08:05
2016-03-25T01:08:05
54,630,293
0
0
null
2016-03-24T09:27:26
2016-03-24T09:27:25
null
UTF-8
R
false
false
1,200
r
cachematrix.R
## makeCacheMatrix - takes in a matrix, and sets up ## a cache to store a value related to the matrix ## that can be retrieved using internal getmatrix() method makeCacheMatrix <- function(x = matrix()) { m <- NULL set <- function(y) { x <<- y m <<- NULL } get <- function() setmatrix <- function(solve) m <<- solve getmatrix <- function() m list(set = set, get = get, setmatrix = setmatrix, getmatrix = getmatrix) } ## cacheSolve - checks the cacheMatrix to see if the ## matrix already has a stored result. If it ## does it returns it from the cache and notifies the ## user that the result came from cached data. If not, it runs ## solve() on the matrix and stores the result in the cache. ## sample code to test the methods: ## d <- matrix(c(10,0,9,6), nrow=2, ncol=2) ## myMatrix <- makeCacheMatrix(d) ## cacheSolve(myMatrix) cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' m <- x$getmatrix() if(!is.null(m)) { message("getting cached data") return(m) } data <- x$get() m <- solve(data, ...) x$setmatrix(m) m }
928ca4f8d6b749e6604c4cfbcebfe9a3d3a43a52
77ef73c072c75fc92d313d404fa1b6df50a53e40
/man/cyto_details_save.Rd
c8824cc4e1ac40d215c710e6f12ed42eeb79d30d
[]
no_license
DillonHammill/CytoExploreR
8eccabf1d761c29790c1d5c1921e1bd7089d9e09
0efb1cc19fc701ae03905cf1b8484c1dfeb387df
refs/heads/master
2023-08-17T06:31:48.958379
2023-02-28T09:31:08
2023-02-28T09:31:08
214,059,913
60
17
null
2020-08-12T11:41:37
2019-10-10T01:35:16
R
UTF-8
R
false
true
893
rd
cyto_details_save.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/cyto-helpers.R \name{cyto_details_save} \alias{cyto_details_save} \title{Save experiment details to csv file} \usage{ cyto_details_save(x, save_as = NULL) } \arguments{ \item{x}{object of class \code{flowSet} or \code{GatingSet} annotated with experiment details.} \item{save_as}{name of csv file to which the experiment details shuld be saved.} } \value{ write experiment details to named csv file. } \description{ Save experiment details to csv file } \examples{ \dontrun{ library(CytoExploreRData) # Activation GatingSet gs <- GatingSet(Activation) # Modify experiment details manually cyto_details(gs)$Treatment <- c( rep("A", 8), rep("B", 8), rep("C", 8), rep("D", 8), NA ) # Save experiment details to file cyto_details_save(gs) } } \author{ Dillon Hammill, \email{Dillon.Hammill@anu.edu.au} }