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
a4d29cb75b296f97e62ab8cf4d39c31226d4a79e
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/multicolor/examples/multi_colour.Rd.R
15072e0e60c4b21f83e76a91834cf863effdc0ed
[]
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,011
r
multi_colour.Rd.R
library(multicolor) ### Name: multi_colour ### Title: Multi-colour text ### Aliases: multi_colour ### ** Examples ## Not run: ##D multi_colour() ##D ##D multi_colour("ahoy") ##D ##D multi_colour("taste the rainbow", ##D c("mediumpurple", ##D "rainbow", ##D "cyan3")) ##D ##D multi_colour(colours = c(rgb(0.1, 0.2, 0.5), ##D "yellow", ##D rgb(0.2, 0.9, 0.1))) ##D ##D multi_colour( ##D cowsay::animals[["buffalo"]], ##D c("mediumorchid4", "dodgerblue1", "lemonchiffon1")) ##D ##D multi_colour(cowsay:::rms, sample(colours(), 10)) ##D ##D # Mystery Bulgarian animal ##D multi_colour(things[[sample(length(things), 1)]], ##D c("white", "darkgreen", "darkred"), ##D direction = "horizontal") ##D ##D # Mystery Italian animal ##D multi_colour(things[[sample(length(things), 1)]], ##D c("darkgreen", "white", "darkred"), ##D direction = "vertical") ## End(Not run)
0893a9586814fa5fce035512906081e7321900f5
2a7e77565c33e6b5d92ce6702b4a5fd96f80d7d0
/fuzzedpackages/bpcs/man/create_index_with_existing_lookup_table.Rd
6422df0cd3b5a9ad282d6b58bd6b041f2048fe19
[ "MIT" ]
permissive
akhikolla/testpackages
62ccaeed866e2194652b65e7360987b3b20df7e7
01259c3543febc89955ea5b79f3a08d3afe57e95
refs/heads/master
2023-02-18T03:50:28.288006
2021-01-18T13:23:32
2021-01-18T13:23:32
329,981,898
7
1
null
null
null
null
UTF-8
R
false
true
970
rd
create_index_with_existing_lookup_table.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/bpc_helpers_indexes.R \name{create_index_with_existing_lookup_table} \alias{create_index_with_existing_lookup_table} \title{Create two columns with the indexes for the names Here we use an existing lookup table. Should be used in predicting} \usage{ create_index_with_existing_lookup_table(d, player0, player1, lookup_table) } \arguments{ \item{d}{A data frame containing the observations. The other parameters specify the name of the columns} \item{player0}{The name of the column of data data contains player0} \item{player1}{The name of the column of data data contains player0} \item{lookup_table}{lookup_table a lookup table data frame} } \value{ A dataframe with the additional columns 'player0_index' and 'player1_index' that contains the indexes } \description{ Create two columns with the indexes for the names Here we use an existing lookup table. Should be used in predicting }
80941cf567e7071022a56143e68cae23238ec563
767e36f775543750ced47685a5f1df035c12f1c2
/R/save_as_csv.R
af859e15679217faebee813d662a7a522c4dabca
[]
no_license
clemonster/nameplay
041c590eb69cc7bbf42b0fce9e06e7f2100a5e85
e1bd98e75fd8cea82449a1fbb4a4a0ff4706faed
refs/heads/master
2021-07-12T07:10:48.671766
2017-10-16T23:37:52
2017-10-16T23:37:52
106,831,358
0
0
null
null
null
null
UTF-8
R
false
false
889
r
save_as_csv.R
#' saves a dataframe as csv #' #' @param df the data frame we want to save #' @param path path to the csv file to be created #' @param row.names row names #' @param ... all other parameters for write.csv #' #' @return nothing #' @export #' @importFrom utils write.csv2 #' @importFrom assertthat is.dir #' @importFrom assertthat is.writeable #' @importFrom assertthat has_extension #' @importFrom assertthat not_empty #' #' #' @examples #' \dontrun{ #' my_df <- as.data.frame(c(1,24,3)) #' save_as_csv(my_df, "..\\..\\somefolder\\save_as_csv_test2.csv") #' } #' save_as_csv <- function(df,path, row.names = FALSE, ...){ is.data.frame(df) assertthat::is.dir(dirname(path)) assertthat::is.writeable(dirname(path)) assertthat::has_extension(path, "csv") assertthat::not_empty(df) write.csv2(x = df, file = path, row.names = row.names, ...) invisible(normalizePath(path)) }
663a94ad0ced6a76da5b375dfdd7dd4c4a80b147
aaaabb97ca1c7b08a147cd32c3886dae0e805d30
/Src/Apriori functions.R
dd2279f0b2da9ad2cae10e315fde8342cfdda035
[ "MIT" ]
permissive
ZyuAFD/DTW_Apriori
0c69aa4248f80056902cfa2dcee7fb0bb02663c4
80412d649eb882b23120bc58bf6d2c9ccbe52ff9
refs/heads/master
2021-01-21T22:14:44.460309
2018-02-23T18:01:55
2018-02-23T18:01:55
102,137,999
0
1
null
null
null
null
UTF-8
R
false
false
2,216
r
Apriori functions.R
MatchEvtPtn=function(Event_info,AddPC=TRUE) { library(arules) library(stringr) # min confidence and length need to be specified based on model minConf=0 minLength=7+AddPC Event_info %>% mutate(PC_diff=ifelse(rep(AddPC,nrow(.)),PC_diff,"")) %>% # These columns has to be ordered alphabetically mutate(Items=paste(AvgT_diff,DryPd_hr_diff,Dur_hr_diff,EvtP_diff,Jday_diff,PC_diff, RainPd_hr_diff, #SoilM_SD_diff,SoilM_Avg_diff, Dist,sep=','), Patn=paste(AvgT_diff,DryPd_hr_diff,Dur_hr_diff,EvtP_diff,Jday_diff,PC_diff, RainPd_hr_diff #SoilM_SD_diff,SoilM_Avg_diff, )) %>% select(Evt_n,Ref_Evt,Items,Patn,Dist) %>% mutate(Items=gsub(",,",",",Items), Patn=gsub(" "," ",Patn)) ->Soil_Seq_ts Event_info %>% # These columns has to be ordered alphabetically unite(Items,sort(noquote(colnames(Event_info[,-c('Evt_n','Ref_Evt')]))),sep=',',remove=F) %>% unite(Patn,sort(noquote(colnames(Event_info[,-c('Evt_n','Ref_Evt','Dist','Items')]))),sep=',') Soil_Pt=as(lapply(Soil_Seq_ts %>% select(Items) %>% unlist %>% as.list, function(x) strsplit(x,',') %>% unlist),'transactions') Pt_feq = apriori(Soil_Pt, parameter=list(support=1/nrow(Soil_Seq_ts), confidence=minConf,target='rules',minlen=minLength), appearance = list(rhs = c("Dist=TRUE","Dist=FALSE","Dist=Ambiguous"), default="lhs")) Pt_freq_df=data.frame( lhs=sapply(1:Pt_feq@lhs@data@Dim[2],function(x) paste(Pt_feq@lhs@itemInfo$labels[Pt_feq@lhs@data[,x]],collapse = ' ')), rhs=sapply(1:Pt_feq@rhs@data@Dim[2],function(x) paste(Pt_feq@rhs@itemInfo$labels[Pt_feq@rhs@data[,x]],collapse = ' '))) %>% cbind(Pt_feq@quality) %>% mutate(lhs=as.character(lhs),rhs=as.character(rhs)) list(Pt_freq_df,Soil_Seq_ts)%>% return }
70f71d836dae2c966d0f1082db3e42b92499302e
c255c8e7ed8057413fece1823ffe78ed2b88ba35
/GettingData.W4.Q4.R
61840bf63659110eefee6ae314300a4935ee2e14
[]
no_license
soroosj/Getting-Data
a93b569c834010d8fc687cff8bfb214598300f47
debfb4bbddf14fda169bb7d82b7cf3d5075e29f6
refs/heads/master
2021-05-09T18:52:03.764841
2018-03-04T20:23:28
2018-03-04T20:23:28
119,175,877
0
0
null
null
null
null
UTF-8
R
false
false
1,005
r
GettingData.W4.Q4.R
#1. load package(s) into R library(tidyverse) library(stringr) #2a. download file(s) to local directory gdp_url<-"https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FGDP.csv" download.file(gdp_url,"gdp.csv") education_url<-"https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FEDSTATS_Country.csv" download.file(education_url,"education.csv") #2b.load file(s) to R gdp<-read.csv("gdp.csv", skip = 5, header = FALSE, na.strings = c("","NA"), nrows=190, stringsAsFactors = F) education<-read.csv("education.csv", stringsAsFactors = F) #3. simplify to required rows, columns gdp_short <- select (gdp, V1, V2, V4, V5) education_short <- select (education, CountryCode, Special.Notes) #4. join tables combine <- inner_join(gdp_short, education_short, by = c("V1" = "CountryCode")) #5a. identify countries with June fiscal year end fiscal <- str_detect(combine$Special.Notes,"Fiscal year end: June 30") #5b. count countries with June fiscal year end sum(fiscal)
0c6bfa9805ab802dbaa407bb666bda512f6dfe95
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/rstan/examples/stanfit-method-plot.Rd.R
a7c37416bf9d79761e6df8c5c3fea24b06ce0ad8
[]
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
572
r
stanfit-method-plot.Rd.R
library(rstan) ### Name: plot-methods ### Title: Plots for stanfit objects ### Aliases: plot,stanfit-method plot,stanfit,missing-method ### Keywords: methods ### ** Examples ## Not run: ##D library(rstan) ##D fit <- stan_demo("eight_schools") ##D plot(fit) ##D plot(fit, show_density = TRUE, ci_level = 0.5, fill_color = "purple") ##D plot(fit, plotfun = "hist", pars = "theta", include = FALSE) ##D plot(fit, plotfun = "trace", pars = c("mu", "tau"), inc_warmup = TRUE) ##D plot(fit, plotfun = "rhat") + ggtitle("Example of adding title to plot") ## End(Not run)
b05a4ea803be156b535a4acd73d2fc741534279c
502d0505e01e1c1385571cf5fb935630614896de
/man/plotLegend.Rd
2198d89ab84d943200e54389e2fb1de586e94c04
[]
no_license
b2slab/FELLA
43308e802b02b8f566ac26c972dc51e72a340c0e
53276c4dfcb8cb4b5a688b167ba574d0f85228a6
refs/heads/master
2021-03-27T20:53:29.212810
2020-10-27T15:33:01
2020-10-27T15:33:01
24,852,722
14
4
null
null
null
null
UTF-8
R
false
true
751
rd
plotLegend.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/plotLegend.R \name{plotLegend} \alias{plotLegend} \title{Internal function to add a legend to a graph plot} \usage{ plotLegend(GO.annot = FALSE, cex = 0.75) } \arguments{ \item{GO.annot}{Logical, should GO annotations be included?} \item{cex}{Numeric value, \code{cex} parameter for the function \code{\link[graphics]{legend}}} } \value{ This function is only used for its effect, so it returns \code{invisible()} } \description{ This function adds a legend to a solution plot. It can include the CC similarity. } \examples{ ## This function is internal library(igraph) g <- barabasi.game(20) plot(g) FELLA:::plotLegend() plot(g) FELLA:::plotLegend(GO.annot = TRUE) }
5cffb4d345e96ecb081b01183df21343464e1159
00ea524f9956e17f045d83e5a78c810042f4c867
/CAP/man/drugTable1.Rd
b4eb625f76d6ea102b275e9da1fd7951683706b8
[]
no_license
ABMI/PneumoniaTxPath
2d81cd4ea6303d72c2f10da5bd3113c475d33bc6
468235e560d1e91a2b27f146ef17aa4a9a4dd464
refs/heads/master
2023-03-28T04:58:01.534131
2021-03-23T02:43:37
2021-03-23T02:43:37
278,856,134
0
0
null
null
null
null
UTF-8
R
false
true
917
rd
drugTable1.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/drugPathway.R \name{drugTable1} \alias{drugTable1} \title{get table1 about drug exposure} \usage{ drugTable1( drugExposureData = drugExposureData, cohortDatabaseSchema = cohortDatabaseSchema, cohortTable = cohortTable, cohortId = cohortId, conceptSets = conceptSets ) } \arguments{ \item{cohortDatabaseSchema}{Schema name where intermediate data can be stored. You will need to have write priviliges in this schema. Note that for SQL Server, this should include both the database and schema name, for example 'cdm_data.dbo'.} \item{cohortTable}{The name of the table that will be created in the work database schema. This table will hold the exposure and outcome cohorts used in this study.} \item{conceptSets}{} } \description{ get table1 about drug exposure } \details{ Extract concept_id from the json file of concept set }
3538df3940d3e106ac6063333931cd26870a38e5
b040e78795d547af081f046040d819f1f9f3d6b0
/script/fun2_transcriptoemIndex.R
3efa1927d49f0aea0675d52adc6fd89137b9e39e
[]
no_license
ljljolinq1010/developmental_constraints_genome_evolution
ee91616dfc1229104cfa30798399c41f45b200aa
8b51bb1fbbb75f52b34a47139d8a90bb0f999977
refs/heads/master
2021-09-15T02:54:19.033229
2018-05-24T13:45:52
2018-05-24T13:45:52
110,563,844
0
0
null
null
null
null
UTF-8
R
false
false
7,806
r
fun2_transcriptoemIndex.R
##### index function ##### index<-function(transcriptome,interestData,interestParameter,orgName,ylim1,ylim2,title) { ## merge two datasets ## paralogs number file only contain genes with at least one paralog, we need add genes without paralog if (interestParameter=="Paralogs.Number") { transData<- merge(transcriptome, interestData,all.x=TRUE, by="Ensembl.Gene.ID") transData$Paralogs.Number <- ifelse(is.na(transData$Paralogs.Number), 0, transData$Paralogs.Number) } if (interestParameter!="Paralogs.Number") { transData<- merge(transcriptome, interestData, by="Ensembl.Gene.ID") } cat("\nOverall ",nrow(transData)," genes were used for ", orgName," ", interestParameter," analysis.",sep="") ## choose organism if (orgName=="D.melanogaster") { timePoint<-c(2:92) ## totally 91 stages devTime<-c(paste0(seq(-15,1335,by=15)+150,"m")) devTime[seq(2,91,by=3)]<-"" devTime[seq(3,91,by=3)]<-"" devTimeColor<-c(rep(myPalette[9],20),rep(myPalette[10],20),rep(myPalette[12],51)) ## we separate 91 stages into 3 metastages: early,middle,late modules = list(early = 1:20, mid = 21:40, late =41:91) } if (orgName=="C.elegans") { timePoint<-c(2:87) ## totally 86 stages devTime<-c(paste0((c(-50,-30,seq(0,550,by=10),seq(570,840,by=10))+80),"m")) devTime[seq(2,86,by=3)]<-"" devTime[seq(3,86,by=3)]<-"" devTimeColor<-c(rep("grey",2),rep(myPalette[9],23),rep(myPalette[10],12),rep(myPalette[12],49)) ## we separate 86 stages into 4 metastages: maternal, early,middle,late (first two points are before MZT) modules = list(maternal = 1:2,early = 3:25, mid = 26:37, late =38:86) } if (orgName=="D.rerio") { timePoint<-c(2:107) ## totally 106 stages devTime<-c(paste0(seq(40,4240,by=40),"m")) devTime[seq(2,106,by=4)]<-"" devTime[seq(3,106,by=4)]<-"" devTime[seq(4,106,by=4)]<-"" devTimeColor<-c(rep("grey",3),rep(myPalette[9],13),rep(myPalette[10],55),rep(myPalette[12],35)) ## we separate 106 stages into 4 metastages: maternal, early,middle,late (first three points are before MZT) modules = list(maternal = 1:3,early = 4:16, mid = 17:71, late =72:106) } if (orgName=="M.musculus") { timePoint<-c(2:18) devTime<-c("0.5d","1.5d","2d","3.5","7.5d","8.5d","9d","9.5d","10.5d","11.5d","12.5d","13.5d","14.5d","15.5d","16.5d","17.5d","18.5d") devTimeColor<-c("grey",rep(myPalette[9],4),rep(myPalette[10],6),rep(myPalette[12],6)) modules = list(maternal = 1, early = 2:5, mid = 6:11, late =12:17 ) } ## plot parameters if (interestParameter=="omega0" || interestParameter=="omega" ) { yName<-"TDI" lineColor<-"blue" } else if (interestParameter=="Paralogs.Number") { yName<-"TPI" lineColor<-"deeppink" } else if (interestParameter=="Rank") { yName<-"TAI" lineColor<-"darkorchid" } transIndex<-c() transIndex<-apply(transData[timePoint], 2, function(x) sum(x*(transData[,interestParameter]))/sum(x)) plot(transIndex) ## bootstrap analysis cat("\nbootstrap analysis...") bootGeneID<-replicate(1000,sample(transData$Ensembl.Gene.ID,replace=T)) transIndexBoot<-c() transIndexBoot1<-c() for (i in 1:1000) { tempID<-data.frame(bootGeneID[,i]) names(tempID)<-"Ensembl.Gene.ID" tempTransData<-merge(tempID,transData,by="Ensembl.Gene.ID") transIndexBoot1<-apply(tempTransData[timePoint], 2, function(x) sum(x*(tempTransData[,interestParameter]))/sum(x)) transIndexBoot<-rbind(transIndexBoot,transIndexBoot1) } ## calculate mean index of each module, and compare the mean with wilcox test. meanIndex<-c() meanIndex1<-c() for (i in 1:1000) { meanIndex1 <- lapply( modules,function(x) mean(transIndexBoot[i,][x]) ) meanIndex <- rbind(meanIndex,meanIndex1) } if (length(modules)==3) { boxplotData<-data.frame(unlist(meanIndex[,1]),unlist(meanIndex[,2]),unlist(meanIndex[,3])) boxplotName<-c("Early", "Middle","Late") wt<-wilcox.test(boxplotData[[1]],boxplotData[[2]],alternative = "greater") } else { boxplotData<-data.frame(unlist(meanIndex[,1]),unlist(meanIndex[,2]),unlist(meanIndex[,3]),unlist(meanIndex[,4])) boxplotName<-c("Maternal","Early", "Middle","Late") wt<-wilcox.test(boxplotData[[2]],boxplotData[[3]],alternative = "greater") } pdf(paste0("result/transcriptomeIndex/logTrans/",title),w=7,h=6) par(mar=c(7,7,2,2),mgp = c(5, 1, 0)) boxplot(boxplotData,las=2,pch=16,outcex=0.5,boxwex=0.7,notch = T, xaxt = "n",main=orgName,cex.lab=1.5,cex.main=1.5,cex.axis=1.5, col=lineColor,ylab=bquote(.(yName) ~ (log[2]))) legend("topleft",paste0("p=", signif(wt$p.value,2)),col=1, bty="n",cex=1.5) mtext(side=1,text = boxplotName,at = c(1:length(modules)),cex=1.5,line = 1.1,col=unique(devTimeColor)) dev.off() ## permutation test cat("\npermutation test...") permuParameter<-replicate(1000,sample(transData[,interestParameter],replace=F)) transIndexPermu<-c() transIndexPermu1<-c() for (i in 1:1000) { transIndexPermu1<-apply(transData[timePoint], 2, function(x) sum(x*(permuParameter[,i]))/sum(x)) transIndexPermu<-rbind(transIndexPermu,transIndexPermu1) } ## calculate mean index meanIndex<-c() meanIndex1<-c() for (i in 1:1000) { meanIndex1 <- lapply( modules,function(x) mean(transIndexPermu[i,][x]) ) meanIndex <- rbind(meanIndex,meanIndex1) } ## calculate difference between mean index of early and mean index of middle if (length(modules)==3) { earlyMidDif<-(unlist(meanIndex[,1]))-(unlist(meanIndex[,2])) } else { earlyMidDif<-(unlist(meanIndex[,2]))-(unlist(meanIndex[,3])) } ## approximate normal distribution of differences meanEarlyMid<-mean(earlyMidDif) varEarlyMid<-var(earlyMidDif) sdEarlyMid<-sqrt(varEarlyMid) ## compute pValue under hypothesis of hourglass if (length(modules)==3) { observedDif<-mean(transIndex[c(unlist(modules[1]))])-mean(transIndex[c(unlist(modules[2]))]) } else { observedDif<-mean(transIndex[c(unlist(modules[2]))])-mean(transIndex[c(unlist(modules[3]))]) } pValue<-pnorm(observedDif,meanEarlyMid,sdEarlyMid,lower.tail = F) ## compute the probability of X>earlyMid ## plot cat("\nplot...") plotData <- data.frame(transIndex,timePoint) pdf(paste0("result/transcriptomeIndex/logTrans/",title),w=7,h=6) par(mfrow=c(1,1)) par(mar=c(7,5,2,2)) print( ggplot(plotData, aes(x = factor(timePoint, levels = unique(timePoint)),y = transIndex,group = 1))+ geom_ribbon(aes(ymin = apply(transIndexBoot, 2,function(x) quantile(x, probs =0.025)), ## 95% confidence interval ymax = apply(transIndexBoot, 2,function(x) quantile(x, probs =0.975))), fill = "grey") + geom_line(lwd = 3,col=lineColor) +ylim(ylim1,ylim2)+ annotate("text", label=paste0("p=",signif(pValue,2)),x=length(plotData$timePoint)/5,y=ylim2,size=7)+ annotate("text", label=paste0("n=",nrow(transData)),x=(length(plotData$timePoint)/5)*4,y=ylim2,size=7)+ ggtitle(orgName) +xlab("Time")+ ylab(bquote(.(yName) ~ (log[2])))+ scale_x_discrete(breaks=plotData$timePoint,labels=devTime)+ theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(),axis.line = element_line(colour = "black"), plot.title = element_text(color="black", size=20, face="bold",hjust = 0.5), axis.title.x = element_text(color="black", size=20, face="bold"), axis.title.y = element_text(color="black", size=20, face="bold"), axis.text.y = element_text(size=18,color="black"), axis.text.x = element_text(color=devTimeColor,size=18, angle=270)) ) dev.off() }
9c3ab86c47309cd070df662be59274d485214a59
4255a7c5a467c6ade48b0a5699089fe1b2082b5e
/man/check_identical_header.Rd
352b2fa0b0ee06e6187cfe80fbed453738e1589e
[ "MIT" ]
permissive
jianhong/HMMtBroadPeak
02978e06fcdf3c14dc4b2a4645018593b8c370b8
7a2932fb943e66d9154282b690f8e762967dc539
refs/heads/main
2023-06-07T15:15:24.245428
2021-06-23T20:35:10
2021-06-23T20:35:10
353,410,515
2
2
null
null
null
null
UTF-8
R
false
true
392
rd
check_identical_header.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/HMMtBroadPeak.R \name{check_identical_header} \alias{check_identical_header} \title{helper function to check the bam file header} \usage{ check_identical_header(bams) } \arguments{ \item{bams}{Bam file of treatments and controls} } \value{ seqlengths } \description{ helper function to check the bam file header }
2bdd1dcfbb7849392ae7c299179ad50fd370aea5
e325da8106789cffb6950b1492eb8d1ab6fb41f0
/R/try-patient-sharing-hhi.R
8a825b715ee004f1750d2c85398d983507756524
[ "MIT" ]
permissive
graveja0/health-care-markets
1aec79caad5155d6586f770cf06446c9d3efe256
da89d1375f287c2a393b2fbe93411ba6b4c079ae
refs/heads/master
2023-06-09T17:26:46.548666
2023-05-28T17:16:01
2023-05-28T17:16:01
166,048,364
37
11
null
null
null
null
UTF-8
R
false
false
6,646
r
try-patient-sharing-hhi.R
#' --- #' output: github_document #' --- # The objective of this file is to construct physician-level HHI measures. suppressWarnings(suppressMessages(source(here::here("/R/manifest.R")))) source(here("R/map-theme.R")) source(here("R/shared-objects.R")) source(here("R/get-market-from-x-y-coordinates.R")) source(here("R/estimate_hhi.R")) source(here("../../../box/Research-Provider_Networks/networks/R/construct-network-object.R")) pcsa_info <- foreign::read.dbf(here("public-data/shape-files/dartmouth-hrr-hsa-pcsa/ct_pcsav31.dbf")) %>% janitor::clean_names() %>% select(pcsa,pcsa_st, pcsa_l) %>% mutate_at(vars(pcsa,pcsa_st,pcsa_l),funs(paste0)) %>% unique() # ZCTA to PCSA Crosswalk (merges on PCSA state from above) zcta_to_pcsa <- foreign::read.dbf(here("public-data/shape-files/dartmouth-hrr-hsa-pcsa/zip5_pcsav31.dbf")) %>% janitor::clean_names() %>% mutate(pcsa = paste0(pcsa)) %>% left_join(pcsa_info,"pcsa") %>% rename(zip_code=zip5) df_hosp_npi <- read_rds(here("../../../box/Research-Provider_Networks/data/penn-xw-npi/general-acute-care-hospital-npi-crosswalk.rds")) df_aha <- read_rds(here("output/market-comparisons/01_aha-markets-2017.rds")) %>% # Constructed in R/construct-hosptial-hhi.R rename(aha_id=id) %>% select(aha_id,prvnumgrp,sysname,mname,everything()) %>% left_join(df_hosp_npi,c("aha_id","prvnumgrp")) %>% filter(!is.na(npi)) %>% mutate(genacute = 1) %>% rename(zip_code = hosp_zip_code) %>% select(npi,genacute,zip_code ) %>% mutate(npi = paste0(npi)) %>% tbl_df() #%>% #mutate(fips_code = paste0(fips_code,width=5,pad="0")) # Provider Denominator File from SK&A df_ska <- read_rds(here("output/ska/ska-2017.rds")) %>% #mutate(primcare = cardiology) %>% filter(primcare ==1 ) %>% mutate(npi = paste0(npi)) %>% select(npi,primcare,zip_code) df <- df_ska %>% bind_rows(df_aha) %>% mutate(primcare = ifelse(is.na(primcare),0,primcare)) %>% mutate(genacute = ifelse(is.na(genacute),0,genacute)) %>% filter(npi!="NA" & !is.na(npi)) %>% left_join(zcta_to_pcsa,"zip_code") ff <- quo(genacute) #enquo(source) tt <- quo(primcare) #enquo(target) kk <- sym("pcsa") #syms(keep) cc <- quo(referral_count) #enquo(referral_count) gg <- quo(pcsa) #enquo(geog) window = "60" tmp <- df %>% select(npi, !!ff, !!tt,!!!kk) %>% filter(!!ff == 1 | !!tt == 1) %>% group_by(npi) %>% filter(!is.na(npi) & npi != "NA") %>% ungroup() %>% group_by(npi) %>% filter(row_number()==1) %>% ungroup() %>% mutate(npi = paste0(npi)) # Docgraph Data VV <- readRDS(here("../../../box/Research-Provider_Networks/data/careset/node-list-2015.rds")) %>% mutate(npi = paste0(npi)) %>% rename(id = node_id) %>% inner_join(tmp,"npi") %>% data.frame() %>% mutate(id = as.numeric(paste0(id))) from_ids <- VV %>% filter(!!ff == 1) %>% pull(id) %>% unique() to_ids <- VV %>% filter(!!tt == 1) %>% pull(id) %>% unique() EE <- readRDS(here("../../../box/Research-Provider_Networks/data/careset/edge-list-2015.rds")) %>% filter(from %in% from_ids & to %in% to_ids) %>% data.frame() %>% mutate(from = as.numeric(paste0(from)), to = as.numeric(paste0(to))) referrals_by_pcsa <- EE %>% left_join(VV %>% select(from = id, npi = npi),"from") %>% left_join(VV %>% select(to = id, to_npi = npi, pcsa=pcsa),"to") %>% left_join(df_hosp_npi %>% mutate(npi = paste0(npi)),"npi") %>% group_by(aha_id,prvnumgrp,pcsa) %>% summarise(primary_care_referrals = sum(pair_count,na.rm=TRUE)) total_referrals <- referrals_by_pcsa %>% group_by(aha_id,prvnumgrp) %>% summarise(total_primary_care_referrals = sum(primary_care_referrals,na.rm=TRUE)) df_aha_market <- read_rds(here("output/market-comparisons/01_aha-markets-2017.rds")) %>% # Constructed in R/construct-hosptial-hhi.R rename(aha_id=id) %>% select(aha_id,prvnumgrp,sysname,mname,everything()) %>% inner_join(total_referrals,c("aha_id","prvnumgrp")) df_aha_market %>% ggplot(aes(x = rank(admtot),y=rank(total_primary_care_referrals))) + geom_point(alpha=0.1) + geom_smooth(se=FALSE, colour="black") + theme_tufte() + geom_abline(slope=1,intercept=0,lty=2) with(df_aha_market,lm(rank(admtot)~rank(total_primary_care_referrals))) hhi_genacute_pcsa_referral <- df_aha_market %>% inner_join(referrals_by_pcsa,c("aha_id","prvnumgrp")) %>% ungroup() %>% select(system_id,total_primary_care_referrals,pcsa) %>% estimate_hhi(id = system_id, weight = total_primary_care_referrals, market= pcsa) %>% rename(hhi_referral = hhi, total_weight = total_weight) pcsa_to_county <- read_csv(here("public-data/zcta-to-fips-county/zcta-to-fips-county.csv")) %>% janitor::clean_names() %>% filter(row_number() !=1) %>% mutate(fips_code = county) %>% select(zip_code = zcta5, fips_code,afact) %>% mutate(afact = as.numeric(paste0(afact))) %>% left_join(zcta_to_pcsa,"zip_code") %>% filter(afact==1) %>% group_by(pcsa,fips_code) %>% filter(row_number()==1) %>% select(pcsa,fips_code) %>% unique() pcsa_hhi_aggregated_to_county <- hhi_genacute_pcsa_referral %>% inner_join(pcsa_to_county,"pcsa") %>% mutate(weight = total_weight) %>% group_by(fips_code) %>% summarise(hhi_referral = weighted.mean(hhi_referral,weight,na.rm=TRUE)) hhi_foo <- read_rds(here("output/market-comparisons/01_market-comparisons-county.rds")) %>% bind_rows() %>% left_join(pcsa_hhi_aggregated_to_county, "fips_code") hhi_foo %>% select(fips_code,hhi_referral,hhi_zip) %>% ggplot(aes(x=hhi_referral,y=hhi_zip)) + geom_point(alpha=0.1) + geom_smooth(se=FALSE) with(hhi_foo,lm(hhi_referral~hhi_zip)) ms_by_zip <- read_rds(here("output/market-comparisons/01_2017_ZIP-market-shares.rds")) %>% filter(zip_code=="37203") %>% mutate(name = ifelse(sysname==""|is.na(sysname),mname,sysname)) %>% select(zip_code,name,total_cases,market_share,hhi_zip=hhi) %>% group_by(name) %>% summarise_at(vars(total_cases),function(x) sum(x,na.rm=TRUE)) %>% ungroup() %>% mutate_at(vars(total_cases),function(x) x /sum(x)) referrals_by_zip_code %>% filter(zip_code==37203) %>% arrange(desc(primary_care_referrals)) %>% left_join(df_aha_market %>% select(aha_id,prvnumgrp,sysname,mname),c("aha_id","prvnumgrp")) %>% mutate(name = ifelse(sysname=="",mname,sysname)) %>% group_by(name) %>% summarise_at(vars(primary_care_referrals),function(x) sum(x,na.rm=TRUE)) %>% ungroup() %>% mutate_at(vars(primary_care_referrals),function(x) x /sum(x)) %>% left_join(ms_by_zip,c("name")) %>% arrange(desc(primary_care_referrals))
f14f0baa747f30e80715cf32f998915aceeb3732
110965c3d64b535adfe23c0e409b304767f6941b
/run_analysis.R
d06b52cfada31fb41c49bbf705174a681943af08
[ "CC0-1.0" ]
permissive
etphonehome2/Getting_and_Cleaning_Data
4c7dfd50f1534aaa60cb7bfd4c927910e9b6664d
e64af1bff80e3a033a93fcfaff155f3f79df2cac
refs/heads/master
2016-09-11T13:46:17.703551
2015-06-21T03:32:17
2015-06-21T03:32:17
37,789,445
0
0
null
null
null
null
UTF-8
R
false
false
3,018
r
run_analysis.R
# ---------------------------------------------------------------------------------------------------- # # run_analysis.R # # ---------------------------------------------------------------------------------------------------- setwd("I:\\MyData\\Training\\Getting and Cleaning Data\\CourseProject") getwd() require("data.table") require("reshape2") fileUrl <- "http://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip" download.file(fileUrl, destfile = "projectfile.zip", method = "internal") unzip("projectfile.zip") list.files(path=".") # features.txt is the column names for the x-Files features <- read.table("./UCI HAR Dataset/features.txt",header=FALSE,colClasses="character") mn <- make.names(features$V2) # make syntactically valid names # read all files, and assign column names where possible testData <- read.table("./UCI HAR Dataset/test/X_test.txt",header=FALSE,col.names=mn) testData_activity <- read.table("./UCI HAR Dataset/test/y_test.txt",header=FALSE,col.names=c("Activity_Id")) testData_subject <- read.table("./UCI HAR Dataset/test/subject_test.txt",header=FALSE,col.names=c("Subject_Id")) trainData <- read.table("./UCI HAR Dataset/train/X_train.txt",header=FALSE,col.names=mn) trainData_activity <- read.table("./UCI HAR Dataset/train/y_train.txt",header=FALSE,col.names=c("Activity_Id")) trainData_subject <- read.table("./UCI HAR Dataset/train/subject_train.txt",header=FALSE,col.names=c("Subject_Id")) # yes descriptive activity names to name the activities in the data set activities <- read.table("./UCI HAR Dataset/activity_labels.txt",header=FALSE)[,2] testData_activity[,2] <- activities[testData_activity[,1]] colnames(testData_activity)[2] <- "Activity_Name" trainData_activity[,2] <- activities[trainData_activity[,1]] colnames(trainData_activity)[2] <- "Activity_Name" # merge the training and the test sets to create one data set testData <-cbind(testData_activity,testData) testData <-cbind(testData_subject,testData) trainData <-cbind(trainData_activity,trainData) trainData <-cbind(trainData_subject,trainData) oneDataset <-rbind(testData,trainData) # extracts only the measurements on the mean and standard deviation for each measurement # find all variable names containg the word "mean" and "std" data_mean_std <- oneDataset[, grepl("*.mean.*", colnames(oneDataset)) | grepl("*.std.*", colnames(oneDataset))] data_subj_act <-subset(oneDataset, select=c(Subject_Id, Activity_Id, Activity_Name)) data <- cbind(data_subj_act, data_mean_std) # reshape the data for processing id_variables <- c("Subject_Id", "Activity_Id", "Activity_Name") measure_variables <- setdiff(colnames(data), id_variables) melt_data <- melt(data, id = id_variables, measure.vars = data_labels) # aply mean function to dataset using dcast function tidy_data <- dcast(melt_data, Subject_Id + Activity_Name ~ variable, mean) write.table(tidy_data, file = "./tidy_data.txt", row.name=FALSE)
6afad496bec19dd9bb54e105cb3fdabdf146c9c2
c9df90ca1c6f04662ab56722d6e5fcfae9586e90
/R/GetCmat.R
3736317df61b479f11316ecadac7cb4743bb0bd1
[]
no_license
HerveAbdi/DistatisR
5b899bcf565c988cbadb636c0f4520b89f6e0c94
96c24d8a03d9f10067a5c5c26042c77d25aa1cc0
refs/heads/master
2023-08-29T05:28:14.289849
2022-12-05T00:13:45
2022-12-05T00:13:45
124,935,297
6
1
null
2022-09-01T14:24:29
2018-03-12T18:44:45
R
UTF-8
R
false
false
1,117
r
GetCmat.R
#' @title GetCmat #' @description Computes the RV coefficient matrix #' @param CubeCP A 3D array of cross-product matrices #' @param RV Boolean, if TRUE, GetCmat computes the matrix of the RV coefficients between all the slices of the 3D array, otherwise, GetCmat computes a scalar product. #' @return A matrix of either RV coefficients or scalar products. #' @examples #' \donttest{ #' D3 <- array(c(0, 1, 2, 1, 0, 1, 2, 1, 0, #' 0, 3, 3, 3, 0, 3, 3, 3, 0), #' dim = c(3, 3, 2)) #' GetCmat(D3) #' } #' @rdname GetCmat #' @export GetCmat <- function(CubeCP, RV = TRUE) { # Compute a C matrix (or RV) from a cube of CP # get the dimensions nI <- dim(CubeCP)[1] nJ <- dim(CubeCP)[3] # reshape the 3D array as an (nI^2)*(nJ) matrix CP2 <- array(CubeCP, dim = c(nI * nI, nJ)) C <- t(CP2) %*% CP2 # Scalar Product if (RV) { # RV is TRUE we want the RV coefficient instead of the Scalar Product laNorm <- sqrt(apply(CP2 ^ 2, 2, sum)) C <- C / (t(t(laNorm)) %*% laNorm) } # end if rownames(C) <- colnames(C) <- dimnames(CubeCP)[[3]] return(C) }
8d840be7d39ed3e2aa5c8437e65a0da64505955d
acc0b1c9d24d8784e5b7ec9009400c067b6ba353
/dataTransformation/R/combineSources.R
4bd25ef77aecdf1d560209ad81e600420ee8957c
[ "CC0-1.0" ]
permissive
ivozandhuis/dwarsliggers
611c22699e10605d6bdb43015bb37f365aad0dc5
33c051b280ba92cdd9753b34050bf813db52a502
refs/heads/master
2023-02-05T02:39:33.181522
2023-02-02T08:15:25
2023-02-02T08:15:25
228,387,452
0
0
null
null
null
null
UTF-8
R
false
false
4,395
r
combineSources.R
setwd("~/git/dwarsliggers/") source("dataTransformation/R/transformMedewerkerslijst.R") source("dataTransformation/R/transformBevolkingsregister.R") source("dataTransformation/R/transformPersoneelsregister.R") source("dataTransformation/R/transformBelastingkohier.R") source("dataTransformation/R/transformRoutes.R") # combine medewerkerslijst and bevolkingsregister first. # NB. in this action 19 RPs are removed, because they were not found in de bevolkingsregister. df <- merge(medewerkerslijst, bevolkingsregister, by = "my_medewerkersnummer") df <- merge(df, personeelsregister, by = "my_medewerkersnummer", all.x = TRUE) df <- merge(df, belastingkohier, by = "my_medewerkersnummer", all.x = TRUE) df <- merge(df, routes, by = "my_medewerkersnummer", all.x = TRUE) # create dummy "married" df$gehuwd_dummy[df$huw_st == "H"] <- 1 df$gehuwd_dummy[df$huw_st == "O"] <- 0 df$gehuwd_dummy[df$huw_st == "S"] <- 0 df$gehuwd_dummy[df$huw_st == "W"] <- 0 # replace wrong df$aantal_dienstjaren with average df$aantal_dienstjaren[(df$leeftijd - df$aantal_dienstjaren) < 12] <- NA df$aantal_dienstjaren[df$leeftijd == 16] <- 0 aantal_dienstjaren_avg <- aggregate(df$aantal_dienstjaren, list(df$leeftijd), mean, na.rm=TRUE, na.action=NULL) df <- merge(df, aantal_dienstjaren_avg, by.x = "leeftijd", by.y = "Group.1", all.x = TRUE) df <- within(df, aantal_dienstjaren <- ifelse(!is.na(aantal_dienstjaren), aantal_dienstjaren, round(x))) # remove temp-stuf rm(aantal_dienstjaren_avg) df$x <- NULL # add df$loon_intrapolatie for missing df$loon with averages # cleanup: list of variables to select loon_avg1 <- aggregate(loon~functie.x+werkplaats, df[df$loonsoort == "dagloon",], mean) loon_avg2 <- aggregate(loon~HISCO, df[df$loonsoort == "dagloon",], mean) names(loon_avg1) <- c("functie.x","werkplaats","loon_avg1") names(loon_avg2) <- c("HISCO","loon_avg2") df <- merge(df, loon_avg1, by = c("werkplaats","functie.x"), all.x = TRUE) df <- merge(df, loon_avg2, by = "HISCO", all.x = TRUE) # select the best value for loon_intrapolatie, # first loon, else loon_avg1, else loon_avg2 df$loon[df$loonsoort == "maandloon"] <- NA count <- df[!is.na(df$loon),] count <- df[(is.na(df$loon) & !is.na(df$loon_avg1)),] count <- df[(is.na(df$loon) & is.na(df$loon_avg1) & !is.na(df$loon_avg2)),] count <- df[(is.na(df$loon) & is.na(df$loon_avg1) & is.na(df$loon_avg2)),] df <- within(df, loon_intrapolatie <- ifelse(!is.na(loon), loon, loon_avg1) ) count <- df[(is.na(df$loon_intrapolatie) & !is.na(df$loon_avg2)),] df <- within(df, loon_intrapolatie <- ifelse(is.na(loon_intrapolatie), loon_avg2, loon_intrapolatie) ) count <- df[is.na(df$loon_intrapolatie),] df$loon_intrapolatie[is.na(df$loon_intrapolatie)] <- 1.84 rm(loon_avg1) rm(loon_avg2) rm(count) df$loon_avg1 <- NULL df$loon_avg2 <- NULL # create dummy for inkomen df$inkomen_dummy[is.na(df$inkomen)] <- 0 df$inkomen_dummy[!is.na(df$inkomen)] <- 1 # cleanup: list of variables to select selection = c( "my_medewerkersnummer", "aantal_uur", "achternaam.x", "functie.x", "gebdat", "gebpla", "amco", "kleur", "leeftijd", "provincie", "regio", "regio2", "geloof", "gemengd_huw", "type", "werkplaats", "afdeling", "loon", "loon_intrapolatie", "loonsoort", "inkomen", "inkomen_dummy", "aantal_dienstjaren", "HISCO", "HISCO_major", "HISCO_minor", "HISCO_unit", "HISCLASS", "SOCPO", "huw_st", "gehuwd_dummy", "aantal_gezinsleden", "aantal_kinderen", "kinderen_dummy", "gem_leeftijd_kinderen", "verantwoordelijkheid", "mijn_wijknaam", "adres.x", "afdeling_kohier", "kiesdistrict_GR1899", "woningbouwvereniging", "len", "t0", "t1", "t2", "t3", "t4", "t5", "aantal_wisselingen" ) df <- subset(df, select = selection) # create stakers, volhouders en ontslagen info, derived from df$kleur # TRUE/FALSE df$staker <- TRUE df$staker[df$kleur == 'b'] <- FALSE df$volhouder <- NA df$volhouder[df$staker] <- TRUE df$volhouder[df$kleur == 'w'] <- FALSE df$ontslagen <- NA df$ontslagen[df$volhouder] <- TRUE df$ontslagen[df$kleur == 'g'] <- FALSE # remove unused levels in all factors df <- droplevels(df) # write write.table(df, "data/constructs/csv/df.csv", sep = ",", row.names=FALSE) # remove temporary stuff rm(belastingkohier) rm(bevolkingsregister) rm(medewerkerslijst) rm(personeelsregister) rm(routes)
6fff010c98ffc3ec588f52061a5b15b42e5acf49
2d34708b03cdf802018f17d0ba150df6772b6897
/googlebloggerv3.auto/man/Page.author.Rd
8ca016e1b47abcf0af3b1eb70e1a026f5971e3b1
[ "MIT" ]
permissive
GVersteeg/autoGoogleAPI
8b3dda19fae2f012e11b3a18a330a4d0da474921
f4850822230ef2f5552c9a5f42e397d9ae027a18
refs/heads/master
2020-09-28T20:20:58.023495
2017-03-05T19:50:39
2017-03-05T19:50:39
null
0
0
null
null
null
null
UTF-8
R
false
true
914
rd
Page.author.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/blogger_objects.R \name{Page.author} \alias{Page.author} \title{Page.author Object} \usage{ Page.author(Page.author.image = NULL, displayName = NULL, id = NULL, image = NULL, url = NULL) } \arguments{ \item{Page.author.image}{The \link{Page.author.image} object or list of objects} \item{displayName}{The display name} \item{id}{The identifier of the Page creator} \item{image}{The page author's avatar} \item{url}{The URL of the Page creator's Profile page} } \value{ Page.author object } \description{ Page.author Object } \details{ Autogenerated via \code{\link[googleAuthR]{gar_create_api_objects}} The author of this Page. } \seealso{ Other Page functions: \code{\link{Page.author.image}}, \code{\link{Page.blog}}, \code{\link{Page}}, \code{\link{pages.insert}}, \code{\link{pages.patch}}, \code{\link{pages.update}} }
98964aa2a0f743d28fccbea70333c67d0e1ca87e
ffe99240aeea52977d8b08eb1c385d972b7818c8
/plot1.R
7cf283e9e2d9b7a7831718a49e07edbc35bee844
[]
no_license
fridanellros/ExData_Plotting1
0e68e6dc9b7bdd30e0d5b2b32baf51f6bdc3b585
a071dfeb12fbb9809ed572c17faabd0e7fe8e2e0
refs/heads/master
2021-01-14T09:45:43.257612
2015-04-11T18:43:04
2015-04-11T18:43:04
33,776,332
0
0
null
2015-04-11T13:17:25
2015-04-11T13:17:22
null
UTF-8
R
false
false
688
r
plot1.R
# LOAD data <- read.table( "household_power_consumption.txt", sep = ";", header = TRUE, colClasses = c(rep("character",2),rep("numeric",7)), na.strings = "?") # PROCESS require(lubridate) data$Date <- dmy( data$Date ) dates <- data$Date == ymd("20070201") | data$Date == ymd("20070202") # PLOT png( file = "plot1.png", width = 480, height = 480) hist( data$Global_active_power[ dates ], breaks = 11, main = "Global Active Power", xlab = "Global Active Power (kilowatts)", ylab = "Frequency", col = "red", ylim = c(0,1200)) dev.off()
664658e371ad3997d9455ff3e13744f44f941b7c
4f3acdccda11715665419446096b0eb0b35af8c3
/scripts/Paepalanthus/tree_and_matrix-paep.R
1c6a6d4f42d943bfc50641dce755ea42da8dec01
[]
no_license
souzayagob/no_one-size-fits-all
47e09fcbfafb77488b9b93c28278127b6182f9f9
e675e7dfa87ba865810ef65b909f7502a0806995
refs/heads/main
2023-04-15T17:35:18.408256
2022-11-07T15:09:32
2022-11-07T15:09:32
493,011,704
1
0
null
null
null
null
UTF-8
R
false
false
4,920
r
tree_and_matrix-paep.R
#This code is intended to prune and manipulate the phylogenetic tree and create a #presence/absence matrix #=====================================================================================================# library(ape) #=====================================================================================================# #=======# # INPUT # #=======# #Reading CR dataset paep_cr <- read.csv("datasets/Paepalanthus/paep_cr.csv", na.strings = c("", NA)) #Reading tree paep_tree <- read.nexus("trees/Paepalanthus/Paepalanthus_Bayes.nex") #=====================================================================================================# #====================# # STANDARDIZING TREE # #====================# #Extracting tip labels tip_labels <- data.frame("tip_labels" = paep_tree$tip.label, "std_labels" = NA, stringsAsFactors = FALSE) #Standardizing tip labels (maintaining varieties) vars <- tip_labels[grep("var_", tip_labels$tip_labels), 1] for(i in 1:nrow(tip_labels)){ if(!tip_labels$tip_labels[i] %in% vars){ tip_labels[i, 2] <- paste(strsplit(tip_labels[i, 1], split = "_")[[1]][c(1,2)], collapse = "_") } else{ tip_labels[i, 2] <- paste(strsplit(tip_labels[i, 1], split = "_")[[1]][c(1,2,3,4)], collapse = "_") } } tip_labels$std_labels <- gsub("_var_", "_", tip_labels$std_labels) #Replacing tip labels in the tree paep_tree$tip.label <- tip_labels$std_labels #=================# # COLLAPSING VARS # #=================# #Supressing infraspecific epithet tip_labels$vars_sup <- NA for(i in 1:nrow(tip_labels)){ tip_labels[i, "vars_sup"] <- paste(strsplit(tip_labels[i, "std_labels"], "_")[[1]][c(1, 2)], collapse = "_") } paep_tree$tip.label <- tip_labels$vars_sup #Removing duplicated labels duplicated_logical <- duplicated(paep_tree$tip.label) paep_tree$tip.label <- as.character(1:length(paep_tree$tip.label)) for(i in 1:length(paep_tree$tip.label)){ if(duplicated_logical[i] == TRUE) paep_tree <- drop.tip(paep_tree, paep_tree$tip.label[paep_tree$tip.label == as.character(i)]) } paep_tree$tip.label <- tip_labels$vars_sup[-which(duplicated_logical)] #=====================================================================================================# #===============# # SAMPLING BIAS # #===============# #Removing species not sampled in the tree paep_cr <- paep_cr[which(paep_cr$gen_sp %in% paep_tree$tip.label), ] #============# # Redundancy # #============# #Data frames with all samples (all_samples) and with one sample per species per grid (one_sample) all_samples <- paep_cr[ , which(colnames(paep_cr) %in% c("gen_sp", "id_grid"))] one_sample <- unique(all_samples, by = c("gen_sp", "id_grid")) #Redundancy values redundancy <- tibble("id_grid" = unique(all_samples$id_grid), "richness" = NA, "n" = NA, "redundancy" = NA) SR <- plyr::count(one_sample$id_grid) N <- plyr::count(all_samples$id_grid) for(i in 1:nrow(redundancy)){ redundancy$richness[i] <- SR$freq[SR$x == redundancy$id_grid[i]] redundancy$n[i] <- N$freq[N$x == redundancy$id_grid[i]] } redundancy$redundancy <- 1-(redundancy$richness/redundancy$n) #Removing grids with redundancy = 0 (meaning a species per sample) inv_grids <- redundancy$id_grid[redundancy$redundancy == 0] paep_cr <- paep_cr[!paep_cr$id_grid %in% inv_grids, ] #=====================================================================================================# #==============# # PRUNING TREE # #==============# paep_pruned.tree <- drop.tip(paep_tree, paep_tree$tip.label[!paep_tree$tip.label %in% paep_cr$gen_sp]) #==========================# # RESCALING BRANCH LENGTHS # #==========================# edge.l <- c() for(i in 1:length(paep_pruned.tree$edge.length)){ edge.l[i] <- paep_pruned.tree$edge.length[i]/sum(paep_pruned.tree$edge.length) } paep_pruned.tree$edge.length <- edge.l #=======# # NEXUS # #=======# write.nexus(paep_pruned.tree, file = "trees/Paepalanthus/pruned_tree-paep.nex") #=====================================================================================================# #========# # MATRIX # #========# #Composing a presence/absence matrix paep_matrix <- matrix(data = NA, nrow = length(unique(paep_cr$id_grid)), ncol = length(unique(paep_cr$gen_sp))) paep_matrix <- as.data.frame(paep_matrix) colnames(paep_matrix) <- unique(paep_cr$gen_sp) rownames(paep_matrix) <- unique(paep_cr$id_grid) for(i in 1:nrow(paep_matrix)){ for(j in 1:ncol(paep_matrix)){ if(colnames(paep_matrix)[j] %in% paep_cr$gen_sp[paep_cr$id_grid == rownames(paep_matrix)[i]]){ paep_matrix[i, j] <- 1 } else { paep_matrix[i, j] <- 0 } } } #Saving matrix write.csv(paep_matrix, "matrices/paep_matrix.csv", row.names = TRUE)
7c4abeb025bebd5556c119e1540974446d806ad7
12676471ec4e7015048e854817b3c253828df917
/econometrics-001/01__1/15_1.2.4._______R_11-16.R
8e61a12bcbd8da92b4e12b4be677ac958f91c2e3
[]
no_license
bdemeshev/coursera_metrics
9768a61e31e7d1b60edce9dde8e52f47bbd31060
a689b1a2eed26816b2c5e4fd795136d5f9d1bb4f
refs/heads/master
2021-11-01T14:15:56.877876
2021-10-24T13:16:59
2021-10-24T13:16:59
23,589,734
19
58
null
2021-07-25T10:51:56
2014-09-02T18:07:06
HTML
UTF-8
R
false
false
2,979
r
15_1.2.4._______R_11-16.R
# if you see KRAKOZYABRY then do # File-Reopen with encoding - UTF-8 - (Set as default) - OK library("psych") # описательные статистики library("dplyr") # манипуляции с данными library("ggplot2") # графики library("GGally") # еще графики d <- cars # встроенный набор данных по машинам glimpse(d) # что там? help(cars) # справка. действует для встроенных наборов данных head(d) # начало таблички d (первые 6 строк) tail(d) # хвостик таблички d describe(d) # среднее, мода, медиана и т.д. ncol(d) # число столбцов nrow(d) # число строк str(d) # структура (похоже на glimpse) # среднее арифметическое mean(d$speed) # создадим новую переменные и поместим их все в табличку d2 d2 <- mutate(d, speed=1.61*speed, dist=0.3*dist, ratio=dist/speed) glimpse(d2) # графики qplot(data=d2,dist) qplot(data=d2,dist,xlab="Длина тормозного пути (м)", ylab="Число машин",main="Данные по машинам 1920х") qplot(data=d2,speed,dist) # оценим модель парной регрессии y_i = \beta_1 + \beta_2 x_i + \varepsilon_i model <- lm(data=d2, dist~speed) model coef(model) # оценки бет residuals(model) # остатки (эпсилон с крышкой) y_hat <- fitted(model) # прогнозы (игрек с крышкой) y <- d2$dist # значения зависимой переменной RSS <- deviance(model) # так называют RSS TSS <- sum((y-mean(y))^2) # TSS TSS R2 <- 1-RSS/TSS R2 cor(y,y_hat)^2 # квадрат выборочной корреляции X <- model.matrix(model) # матрица регрессоров X # создаем новый набор данных nd <- data.frame(speed=c(40,60)) nd # прогнозируем predict(model,nd) # добавляем на график линию регрессии qplot(data=d2,speed,dist) + stat_smooth(method="lm") t <- swiss # встроенный набор данных по Швейцарии help(swiss) glimpse(t) describe(t) ggpairs(t) # все диаграммы рассеяния на одном графике # множественная регрессия model2 <- lm(data=t, Fertility~Agriculture+Education+Catholic) coef(model2) # оценки бет fitted(model2) # прогнозы residuals(model2) # остатки deviance(model2) # RSS report <- summary(model2) report report$r.squared # R^2 # второй способ расчета R^2 cor(t$Fertility,fitted(model2))^2 # создаем новый набор данных nd2 <- data.frame(Agriculture=0.5,Catholic=0.5, Education=20) # прогнозируем predict(model2,nd2)
a98ab60b57ccc32eb2e70b82e2dd4b839b313247
ae703e19ee171d6182a93946350ee41117c1c235
/run_analysis.R
8209ef5c4b639dc7c9ce7af0d15aac8604fd6f6c
[]
no_license
monsteragain/courseProject
f4a72efa0981baa59ca6368fa63c1e0fae102fb0
1170ff2faff4193d75a62222a19ad2c15cd8d097
refs/heads/master
2016-09-06T15:53:50.949094
2014-11-24T00:37:19
2014-11-24T00:37:19
null
0
0
null
null
null
null
UTF-8
R
false
false
4,518
r
run_analysis.R
##Read X_test and X-train data, use 'rbind' to merge the data and store it in 'data' variable data <- rbind(read.table("UCI HAR Dataset/test/X_test.txt"),read.table("UCI HAR Dataset/train/X_train.txt")) ##Read and rbind subject_test.txt and subject_train.txt subjects <- rbind(read.table("UCI HAR Dataset/test/subject_test.txt"),read.table("UCI HAR Dataset/train/subject_train.txt")) ##name the column so when we cbind it to data, there'd be no duplicate column names colnames(subjects) <- "Subjects" ##Read and rbind y_test.txt and y_train.txt activities <- rbind(read.table("UCI HAR Dataset/test/y_test.txt"),read.table("UCI HAR Dataset/train/y_train.txt")) ##name the column so when we cbind it to data, there'd be no duplicate column names colnames(activities) <- "Activities" ##make a vector 'features' with the names from 'features.txt' features <- as.vector(read.table("UCI HAR Dataset/features.txt")[ ,2]) ##use grep to find the positions of features that contain 'mean()' or 'std()' featurepos <- grep('mean\\(\\)|std\\(\\)',features) ##use 'featurepos' to extract only the columns with measurements on the mean and standard deviation from 'data' data <- data[ ,featurepos] ##apply 'featurepos' to 'features' to make a vector of measurement names, then make syntactically valid names with 'make.name' featurenames <- make.names(features[featurepos],unique = TRUE, allow_ = FALSE) ##clean the names with some substitutions to make readable descriptive names featurenames <- gsub('\\.','',featurenames) ##remove dots featurenames <- gsub('mean','Mean',featurenames) ##capitalize first letter of ##'mean' to make it more readable featurenames <- gsub('std','Std',featurenames) ##capitalize first letter of ##'std' to make it more readable featurenames <- gsub('BodyBody','Body',featurenames) ##correcting themismatch in the ##original authors features names as pointed by David Hood at ##https://class.coursera.org/getdata-009/forum/thread?thread_id=89#comment-656 ##name the columns in 'data' colnames(data) <- featurenames ##cbind subjects and activities to data - thus we merge the measurements with subjects and activities data <- cbind(data,c(subjects,activities)) ##read activity labels from file activityLabels <- as.vector(read.table("UCI HAR Dataset/activity_labels.txt")[ ,2]) ##turn the numbers in data$Activities column into factors then change the level ##names (this changes it in the same column)- as suggested by David Hood at ##https://class.coursera.org/getdata-009/forum/thread?thread_id=141#post-523 data$Activities <- factor(data$Activities, labels = activityLabels) ##Now getting to create the tidy data set ##Create a vector of strings to be used as colnames in the resulting data frame colnames <- colnames(data) ##adding 'Avg' to every var name to reflect the fact that we calculate ##the average of means and standard deviations colnames[1] <- paste0(colnames[1],"Avg") ##create an empty dataframe to store the tidy data ##the method to create empty df with column names by Floo0 at ##http://stackoverflow.com/a/26614741 df <- read.table(text='',col.names=colnames(data)) ##loop through subjects for (i in 1:30) { ##find indices of rows for the given subject ##NB! I'm not using if condition to loop through all the rows of data ##as 'which' is supposed to be a faster and less resourceful way rows_subjects <- which(data$Subjects==i) for (a in 1:6) { ##find a subset of row indices that contain the given activity label ##keep in mind, it finds indices inside data set subsetted by rows_subjects, ##not inside original 'data' rows_activities <- which(data[rows_subjects,"Activities"]==activityLabels[a]) ##finaly, get rows in the original 'data' with a given subject and activity rows <- rows_subjects[rows_activities] ##create a vector with averages for each of 66 columns with measurements ##plus the subject label - I do not include activityLabel here as it ##is a string and will coerce all the vector into a character class vec <- c(as.vector(colMeans(data[rows,1:66])),i) rownumber <- nrow(df) + 1 df[rownumber,1:67] <- vec df[rownumber,68] <- activityLabels[a] } } df
cb0b9d35dc8accdfe1e650568dba50d00a347046
4042c33db4606452e80bf20e763d388be2785372
/pkg/R/nw_setup.R
5378bca81149cfc9253c8f35d905807f919d6b46
[]
no_license
RodrigoAnderle/EvoNetHIV
992a5b735f8fac5255ea558ec2758251634ffaab
4bef435b0c5739d6baba9f80c93ac046e540647e
refs/heads/master
2023-08-25T14:01:38.754647
2021-09-24T16:48:29
2021-09-24T16:48:29
null
0
0
null
null
null
null
UTF-8
R
false
false
831
r
nw_setup.R
#' @export nw_setup <- function(params){ nw <- setup_initialize_network(params) #-------------------------------------------------------------- #estimate initial network (create argument list, then call fxn) netest_arg_list <- list( nw = nw, formation = as.formula(params$nw_form_terms), target.stats = params$target_stats, coef.form = params$nw_coef_form, constraints = as.formula(params$nw_constraints), verbose = FALSE, coef.diss = dissolution_coefs( dissolution = as.formula(params$dissolution), duration = params$relation_dur, d.rate = params$d_rate) ) sim <- do.call(EpiModel::netest, netest_arg_list) if(params$hyak_par==T){ save(sim,file="estimated_nw.RData") } return(sim) }
e9d810b63d2955520d9c9fb01446737545319358
7917fc0a7108a994bf39359385fb5728d189c182
/cran/paws.storage/man/efs_create_mount_target.Rd
f6b5669c0b63f314c5a0b71cf28d153550af6372
[ "Apache-2.0" ]
permissive
TWarczak/paws
b59300a5c41e374542a80aba223f84e1e2538bec
e70532e3e245286452e97e3286b5decce5c4eb90
refs/heads/main
2023-07-06T21:51:31.572720
2021-08-06T02:08:53
2021-08-06T02:08:53
396,131,582
1
0
NOASSERTION
2021-08-14T21:11:04
2021-08-14T21:11:04
null
UTF-8
R
false
true
6,582
rd
efs_create_mount_target.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/efs_operations.R \name{efs_create_mount_target} \alias{efs_create_mount_target} \title{Creates a mount target for a file system} \usage{ efs_create_mount_target(FileSystemId, SubnetId, IpAddress, SecurityGroups) } \arguments{ \item{FileSystemId}{[required] The ID of the file system for which to create the mount target.} \item{SubnetId}{[required] The ID of the subnet to add the mount target in.} \item{IpAddress}{Valid IPv4 address within the address range of the specified subnet.} \item{SecurityGroups}{Up to five VPC security group IDs, of the form \code{sg-xxxxxxxx}. These must be for the same VPC as subnet specified.} } \value{ A list with the following syntax:\preformatted{list( OwnerId = "string", MountTargetId = "string", FileSystemId = "string", SubnetId = "string", LifeCycleState = "creating"|"available"|"updating"|"deleting"|"deleted", IpAddress = "string", NetworkInterfaceId = "string", AvailabilityZoneId = "string", AvailabilityZoneName = "string", VpcId = "string" ) } } \description{ Creates a mount target for a file system. You can then mount the file system on EC2 instances by using the mount target. You can create one mount target in each Availability Zone in your VPC. All EC2 instances in a VPC within a given Availability Zone share a single mount target for a given file system. If you have multiple subnets in an Availability Zone, you create a mount target in one of the subnets. EC2 instances do not need to be in the same subnet as the mount target in order to access their file system. For more information, see \href{https://docs.aws.amazon.com/efs/latest/ug/how-it-works.html}{Amazon EFS: How it Works}. In the request, you also specify a file system ID for which you are creating the mount target and the file system's lifecycle state must be \code{available}. For more information, see \code{\link[=efs_describe_file_systems]{describe_file_systems}}. In the request, you also provide a subnet ID, which determines the following: \itemize{ \item VPC in which Amazon EFS creates the mount target \item Availability Zone in which Amazon EFS creates the mount target \item IP address range from which Amazon EFS selects the IP address of the mount target (if you don't specify an IP address in the request) } After creating the mount target, Amazon EFS returns a response that includes, a \code{MountTargetId} and an \code{IpAddress}. You use this IP address when mounting the file system in an EC2 instance. You can also use the mount target's DNS name when mounting the file system. The EC2 instance on which you mount the file system by using the mount target can resolve the mount target's DNS name to its IP address. For more information, see \href{https://docs.aws.amazon.com/efs/latest/ug/how-it-works.html#how-it-works-implementation}{How it Works: Implementation Overview}. Note that you can create mount targets for a file system in only one VPC, and there can be only one mount target per Availability Zone. That is, if the file system already has one or more mount targets created for it, the subnet specified in the request to add another mount target must meet the following requirements: \itemize{ \item Must belong to the same VPC as the subnets of the existing mount targets \item Must not be in the same Availability Zone as any of the subnets of the existing mount targets } If the request satisfies the requirements, Amazon EFS does the following: \itemize{ \item Creates a new mount target in the specified subnet. \item Also creates a new network interface in the subnet as follows: \itemize{ \item If the request provides an \code{IpAddress}, Amazon EFS assigns that IP address to the network interface. Otherwise, Amazon EFS assigns a free address in the subnet (in the same way that the Amazon EC2 \code{CreateNetworkInterface} call does when a request does not specify a primary private IP address). \item If the request provides \code{SecurityGroups}, this network interface is associated with those security groups. Otherwise, it belongs to the default security group for the subnet's VPC. \item Assigns the description \verb{Mount target fsmt-id for file system fs-id } where \code{fsmt-id} is the mount target ID, and \code{fs-id} is the \code{FileSystemId}. \item Sets the \code{requesterManaged} property of the network interface to \code{true}, and the \code{requesterId} value to \code{EFS}. } Each Amazon EFS mount target has one corresponding requester-managed EC2 network interface. After the network interface is created, Amazon EFS sets the \code{NetworkInterfaceId} field in the mount target's description to the network interface ID, and the \code{IpAddress} field to its address. If network interface creation fails, the entire \code{\link[=efs_create_mount_target]{create_mount_target}} operation fails. } The \code{\link[=efs_create_mount_target]{create_mount_target}} call returns only after creating the network interface, but while the mount target state is still \code{creating}, you can check the mount target creation status by calling the \code{\link[=efs_describe_mount_targets]{describe_mount_targets}} operation, which among other things returns the mount target state. We recommend that you create a mount target in each of the Availability Zones. There are cost considerations for using a file system in an Availability Zone through a mount target created in another Availability Zone. For more information, see \href{https://aws.amazon.com/efs/}{Amazon EFS}. In addition, by always using a mount target local to the instance's Availability Zone, you eliminate a partial failure scenario. If the Availability Zone in which your mount target is created goes down, then you can't access your file system through that mount target. This operation requires permissions for the following action on the file system: \itemize{ \item \code{elasticfilesystem:CreateMountTarget} } This operation also requires permissions for the following Amazon EC2 actions: \itemize{ \item \code{ec2:DescribeSubnets} \item \code{ec2:DescribeNetworkInterfaces} \item \code{ec2:CreateNetworkInterface} } } \section{Request syntax}{ \preformatted{svc$create_mount_target( FileSystemId = "string", SubnetId = "string", IpAddress = "string", SecurityGroups = list( "string" ) ) } } \examples{ \dontrun{ # This operation creates a new mount target for an EFS file system. svc$create_mount_target( FileSystemId = "fs-01234567", SubnetId = "subnet-1234abcd" ) } } \keyword{internal}
546bbb8ec1401c0c4cf5145d22b6769595981b48
84af362583c9562a8a5225986d877b6a5b26ef0a
/man/yf_collection_get.Rd
5558a04c24571b1267403191e1ea218d75b6239b
[ "MIT" ]
permissive
ropensci/yfR
945ef3f23a6f04560072d7436dd5c28e0f809462
b2f2c5c9f933e933821b5a92763c98f155b401bd
refs/heads/main
2023-05-23T19:12:44.048601
2023-02-16T10:48:15
2023-02-16T10:48:15
375,024,106
19
6
NOASSERTION
2023-01-30T17:18:11
2021-06-08T13:44:11
HTML
UTF-8
R
false
true
1,548
rd
yf_collection_get.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/yf_collections.R \name{yf_collection_get} \alias{yf_collection_get} \title{Downloads a collection of data from Yahoo Finance} \usage{ yf_collection_get( collection, first_date = Sys.Date() - 30, last_date = Sys.Date(), do_parallel = FALSE, do_cache = TRUE, cache_folder = yf_cachefolder_get(), ... ) } \arguments{ \item{collection}{A collection to fetch data (e.g. "SP500", "IBOV", "FTSE" ). See function \code{\link{yf_get_available_collections}} for finding all available collections} \item{first_date}{The first date of query (Date or character as YYYY-MM-DD)} \item{last_date}{The last date of query (Date or character as YYYY-MM-DD)} \item{do_parallel}{Flag for using parallel or not (default = FALSE). Before using parallel, make sure you call function future::plan() first. See <https://furrr.futureverse.org/> for more details.} \item{do_cache}{Use cache system? (default = TRUE)} \item{cache_folder}{Where to save cache files? (default = yfR::yf_cachefolder_get() )} \item{...}{Other arguments passed to \code{\link{yf_get}}} } \value{ A data frame with financial prices from collection } \description{ This function will use a set collection of YF data, such as index components and will download all data from Yahoo Finance using \code{\link{yf_get}}. } \examples{ \donttest{ df_yf <- yf_collection_get(collection = "IBOV", first_date = Sys.Date() - 30, last_date = Sys.Date() ) } }
178bfd8b213b596ac0015afb6e7f8cd850aea5a1
c0a0e4ee67152f89ea3bdb22a0752946c969ebf2
/scripts/happ_maier_merz.R
2245b9c6213a0b61eec26a00a2b34093b1341653
[]
no_license
PirateGrunt/cotor_correlation
eb1fac9fdc96523ea06c09d234b115fc09a2af3b
398158b82818e12153dba1858060e61a2de5bd2b
refs/heads/master
2020-03-26T11:48:17.772123
2018-09-24T00:36:08
2018-09-24T00:36:08
144,860,602
0
0
null
null
null
null
UTF-8
R
false
false
1,886
r
happ_maier_merz.R
library(tidyverse) library(magrittr) munge_triangle <- function(str_in, lags) { tbl_triangle <- str_in %>% str_replace_all('\\.', '') %>% str_split('\n', simplify = TRUE) %>% str_split('[:space:]+', simplify = TRUE) %>% extract(, -1) %>% as_tibble() %>% map_dfc(as.numeric) names(tbl_triangle) <- c('ay', lags) tbl_triangle %>% tidyr::gather(lag, incremental_paid, -ay, na.rm = TRUE) } lags <- 0:10 triangle_a <- ' 0 14.492 7.746 949 467 814 234 1.718 104 15 49 4 1 17.017 9.251 945 750 33 196 1.144 18 10 1 11 2 19.563 12.265 1.302 1.099 967 1.237 1.838 1.093 276 643 0 3 21.632 13.249 963 136 25 172 27 39 7 0 0 4 22.672 9.677 1.779 153 95 1.265 31 1 45 0 8 5 23.062 13.375 2.200 327 2.273 20 23 0 0 2 0 6 23.588 11.713 1.660 4.569 1.662 256 0 39 0 32 2 7 21.758 12.300 1.685 1.266 -28 -41 -49 -45 -26 0 8 20.233 9.197 932 644 754 2.452 161 34 0 9 24.984 12.632 1.931 415 1.730 163 113 33 10 24.260 13.555 1.585 1.679 123 147 32 11 20.616 11.430 2.932 516 558 37 12 18.814 11.499 3.363 1.711 97 13 18.563 13.492 16.370 2.704 14 18.457 11.089 2.064 15 19.533 9.833 16 17.620' triangle_b <- ' 0 16.651 8.206 -468 -152 5 4 6 0 1 0 0 1 16.292 8.129 1.713 195 426 35 68 50 55 0 11 2 16.658 10.566 1.736 618 1.272 442 572 15 38 749 2 3 19.715 10.690 968 2.098 154 197 100 63 3.519 24 149 4 21.220 8.815 2.969 896 151 1.146 26 20 0 0 2 5 21.302 10.582 2.237 952 7 1.183 14 0 26 70 -9 6 17.201 7.493 1.574 518 1.685 25 2 56 -8 71 7 7 15.835 11.668 1.728 122 493 -10 4 1 1 0 8 17.560 8.550 2.373 908 1.163 389 127 501 2 9 21.051 12.279 2.387 690 372 2.024 14 0 10 20.368 9.832 1.285 460 43 186 0 11 18.623 11.160 942 892 8 28 12 18.112 12.040 1.662 5.654 979 13 17.744 10.346 2.134 599 14 17.993 8.956 869 15 19.082 11.403 16 17.809' tbl_triangle <- triangle_a %>% munge_triangle(lags)
3ff8666170141d482e8424423dd49caeef861b22
1eee16736f5560821b78979095454dea33b40e98
/thirdParty/HiddenMarkov.mod/R/mmglm1.R
765bb029b2ad2d20d3e3e92d5abecc2db5a9282d
[]
no_license
karl616/gNOMePeaks
83b0801727522cbacefa70129c41f0b8be59b1ee
80f1f3107a0dbf95fa2e98bdd825ceabdaff3863
refs/heads/master
2021-01-21T13:52:44.797719
2019-03-08T14:27:36
2019-03-08T14:27:36
49,002,976
4
0
null
null
null
null
UTF-8
R
false
false
700
r
mmglm1.R
"mmglm1" <- function (y, Pi, delta, glmfamily, beta, Xdesign, sigma=NA, nonstat=TRUE, size=NA, msg=TRUE){ if (msg) message("NOTE: 'mmglm1' and its methods are still under development and may change.") if (glmfamily$family=="binomial" & all(is.na(size))) stop("Argument size must be specified when fitting a binomial model.") if (glmfamily$family=="binomial" | glmfamily$family=="poisson") discrete <- TRUE else discrete <- FALSE x <- c(list(y=y, Pi=Pi, delta=delta, glmfamily=glmfamily, beta=beta, Xdesign=Xdesign, sigma=sigma, size=size, nonstat=nonstat, discrete=discrete)) class(x) <- c("mmglm1") return(x) }
65546608f6e6e44b56dc5e0f3c3547835ea872f4
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/starma/examples/stcov.Rd.R
e4bc8a309a2040a086e3d66af6878920b0e7a5b9
[]
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
329
r
stcov.Rd.R
library(starma) ### Name: stcov ### Title: Space-time covariance function ### Aliases: stcov ### Keywords: starma stcov ### ** Examples data(nb_mat) # Get neighbourhood matrices data <- matrix(rnorm(9400), 100, 94) # Compute covariance between 2-nd and 1-st order neighbours, at time lag 5 stcov(data, blist, 2, 1, 5)
b78363943c6e47cc32431b9bf2a1d13f4582e7da
301bd6d09d7aa29572e944755e1966832db29066
/cachematrix.R
bfe0fee55dbd46179aefbe39b15f6478aa605514
[]
no_license
chewlwb/ProgrammingAssignment2
a001cd2d30c70bb4a865d26091f126b466fef1f4
53fcc6b651dbe7b65eee71d4fc12c6bfb2e03f88
refs/heads/master
2021-01-18T10:27:07.349087
2015-03-21T13:02:24
2015-03-21T13:02:24
32,588,762
0
0
null
2015-03-20T14:35:37
2015-03-20T14:35:35
null
UTF-8
R
false
false
2,376
r
cachematrix.R
## makeCacheMatrix creates a special "matrix, which is really a ## list containing a function to ## set the value of the matrix ## get the value of the matrix ## set the value of the inverse of matrix ## get the value of the inverse of matrix makeCacheMatrix <- function(x = matrix()) { inv <- NULL ## initialize inv so that makeCache will work for first time ## set function sets x to y and inv to null within its environment set <- function(y) { x <<- y inv <<- NULL } # the get function assigns a matrix to it. This function # is useful only when worked with the cacheSolve function. get <- function () x #this function sets the value ('inverse') to inv in the makeCacheMatrix # enironment. This function is useful only when CacheSolve is called second time # because the inverse is stored in setinv function and doesn't need to compute it again. setinv <- function(inverse) inv <<- inverse getinv <- function() inv #constructs a named list of functions within the environment in the makeCacheMatrix list(set = set, get = get, setinv = setinv, getinv = getinv) } ## cacheSolve calculates the inverse of the special "matrix" ## created with makeCacheMatrix. ## However, it first checks to see if the inverse has already been calculated in the getinv function. ## If so, it gets the inverse from the cache and skips the computation. ## Otherwise, it calculates the inverse of the data and sets the value of the inverse ## in the cache via the setinv function. ## Goes to the makeCachematrix environment and assigns the ## 'inv' value from that environment to this one. ## If the makeCacheMatrix environment has been evaluated ## before, the function prints the message and ## the value of inv (the cached inverse). cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' inv <- x$getinv() if (!is.null(inv)){ message("getting cached data") return(inv) } ## If the inverse has never been evaluated before, ## puts the x-matrix into a local variable called 'data' ## Calculate the inverse of the matrix x by calling ## solve function on the data local variable. ## Assign the calculated inverse to the MakeCacheMatrix ## environment using the 'setinv' function. ## Display the calculated inverse. data <- x$get() inv <- solve(data, ...) x$setinv(inv) inv }
d281a9dc0cf0341025687f1bc6786f26a24eb955
c95d61a58f83ea3beae1949c2e4cd8e5f1186c01
/BM-challenge/tabs/11. pyro.R
13eb4d2c7a35991e9440ba81842a57e4c2ea600c
[]
no_license
TMBish/TMBisc
d9da0e75320b47a5e539f6124430dc49cef61e4f
79378a7e18e02afaf9679ef8f914d9b21f39e453
refs/heads/master
2023-02-22T19:14:11.210224
2023-02-16T06:55:09
2023-02-16T06:55:09
172,413,835
0
0
null
null
null
null
UTF-8
R
false
false
1,844
r
11. pyro.R
pyroTab = fluidRow( column(width = 8, tabBox( title = "Pyro: wood chopping and fire construction", id = "tabset1", height = "600", width = 12, tabPanel("Challenge Description", HTML( "<strong> <big> Overview </big> </strong> <br/> <p> This is a time-trial. Each participant will recieve:<br/> 1. One log; <br/> 2. A fire lighter; <br/> 3. 3 sheets of newspaper; and <br/> 4. An axe. <br/> Your timer stops when your fire is going to the satisfaction of the chief justice: Tom B. </p> <br/> <br/> <strong> <big> What constitutes participation? </big> </strong> <br/> <p> A piece of the log must be alight. </p> <br/> <br/> <strong> <big> How do I win bonus points? </big> </strong> <br/> <p> NA </p>")), tabPanel("Results", hotable("hotable11"), br(), actionButton("calc11","calculate",styleclass="primary",size="mini"), actionButton("up11","upload",styleclass="danger")) ) ), column(width = 4, valueBox("Team/Individual", "Individual", icon = icon("user"), width = NULL, color = "olive"), valueBox("Min. Participants", 4, icon = icon("users"), width = NULL, color = "olive"), valueBox("Points Avaliable", 100, icon = icon("money"), width = NULL, color = "olive"), valueBox("Bonus Points?", NA, icon = icon("asterisk"), width = NULL, color = "olive") ) ) calc11 = function(hdf) { power = ifelse(hdf$Fire.Rank == 0,0,(10-hdf$Fire.Rank)^2) scaled = power / (sum(power)/100) pyroScore = round(scaled,0) hdf$Score = pyroScore return(hdf) }
e61f2bb4c0058ec2cb9f35359088b5ac231e0672
ac3738c440117527327ec58affb38f7d887adc91
/scripts/allelefreqs.R
b8f37af14084be239e1781cebb806035d21c0abe
[]
no_license
jpgerke/KrugQx
7e27bbf725563413b5694432bec5f84056cb91df
c83b874b7bf71d45ca07c0765fe8231b121f6ccf
refs/heads/master
2020-04-05T23:29:30.991478
2015-08-16T03:01:28
2015-08-16T03:01:28
38,621,692
0
0
null
null
null
null
UTF-8
R
false
false
860
r
allelefreqs.R
#!/usr/bin/Rscript rm(list=ls()) load_obj <- function (f) { env <- new.env() nm <- load(f, env)[1] return(env[[nm]]) } # allelefreqs <- function (filename) { # myobj <- load_obj(filename) # return(myobj) # } # # getfreq <- function (geno) { # return(sum(geno) / (length(geno) *2 )) # } # # calc_freqs <- function (filename) { # # alldata <- load_obj(filename) # mycols <- alldata[,-1] # freqs <- apply(mycols, 2, getfreq) # return(freqs) # } #running into memory problems running the whole thing so loop by chromosome allnames = list() for (x in 1:10) { filename <- paste("../data/Namfreqs/cut2uniqueAD_NAM_KIDS_chr", x, ".raw.RData", sep='') myobj <- load_obj(filename) mynames = names(myobj) allnames[[x]] = mynames } rm(myobj) rm(mynames) fullnames = do.call(c, allnames) write(fullnames, file = "../data/Namfreqs/GWAS_SNPs.txt")
bd951252aea0f2ea994e837fb369a4b705b47e40
83d93f6ff2117031ba77d8ad3aaa78e099657ef6
/R/gtimer.R
4621d839fad7c48d9bef3e252955b660a0f779a9
[]
no_license
cran/gWidgets2
64733a0c4aced80a9722c82fcf7b5e2115940a63
831a9e6ac72496da26bbfd7da701b0ead544dcc1
refs/heads/master
2022-02-15T20:12:02.313167
2022-01-10T20:12:41
2022-01-10T20:12:41
17,696,220
0
0
null
null
null
null
UTF-8
R
false
false
1,260
r
gtimer.R
##' @include methods.R NULL ##' Basic timer widget ##' ##' Calls FUN every ms/1000 seconds. A timer is stopped through its \code{stop_timer} method which is called using OO style: \code{obj$stop_timer()}. ##' @param ms interval in milliseconds ##' @param FUN FUnction to call. Has one argument, data passed in ##' @param data passed to function ##' @param one.shot logical. If TRUE, called just once, else repeats ##' @param start logical. If FALSE, started by \code{start_timer} OO method. (Call \code{obj$start_time()}). ##' @param toolkit gui toolkit to dispatch into ##' @export ##' @rdname gtimer ##' @examples ##' \dontrun{ ##' i <- 0 ##' FUN <- function(data) {i <<- i + 1; if(i > 10) a$stop_timer(); print(i)} ##' a <- gtimer(1000, FUN) ##' ## ##' ## a one shot timer is run only once ##' FUN <- function(data) message("Okay, I can breathe now") ##' hold_breath <- gtimer(1000*60, FUN, one.shot=TRUE) ##' } gtimer <- function(ms, FUN, data=NULL, one.shot=FALSE, start=TRUE, toolkit=guiToolkit()) { .gtimer(toolkit=toolkit, ms=ms, FUN=FUN, data=data, one.shot=one.shot, start=start) } ##' S3 generic for dispatch ##' ##' @export ##' @rdname gtimer .gtimer <- function(toolkit, ms, FUN, data=NULL, one.shot=FALSE, start=TRUE) UseMethod(".gtimer")
cddaac299a25a670be8829d4fbdcb55d8c6001ca
e1632c4e03c43bf56894760274e0a4c891395645
/ms_initialize_adjacency_matrix.R
2d5ccad5c0b4f0798daf0c4b0db9ced273fe06b9
[]
no_license
johnchower/ticket_to_ride
0c5596df43bb0a438600dc0b96b934ed3d1312e7
9d76fcb714b9e7da8c9501fef36e3e6e975211b8
refs/heads/master
2021-01-19T05:30:00.026202
2016-07-27T00:22:34
2016-07-27T00:22:34
64,262,098
0
0
null
null
null
null
UTF-8
R
false
false
422
r
ms_initialize_adjacency_matrix.R
library(dplyr) library(magrittr) city_df <- read.csv("city_graph.csv", stringsAsFactors = F) %>% select(city_1) city_df %<>% { matrix( 0 , nrow = nrow(.), ncol = length(.$city_1) , dimnames = list(1:length(.$city_1), .$city_1) ) %>% as.data.frame } %>% { cbind(data.frame(city_1 = city_df$city_1,.)) } city_df %<>% edit write.csv(city_df, "city_adjacency_matrix.csv")
cc9f5566a634ce8f05ac34c4a714bca9bcca1581
02203a5e1487c6bf95647b38038e2428c261aad7
/R/qm.R
65da8d5ce1e7f9f86ffb214e8942e7ce7f0802db
[]
no_license
cran/gdalUtils
8793292640f94d0f8960804f0ba9d4b5099baad7
9aa3955becca0970f98513ca20e4bff56be44d81
refs/heads/master
2021-06-07T07:27:23.972525
2020-02-13T19:10:02
2020-02-13T19:10:02
17,696,298
3
8
null
null
null
null
UTF-8
R
false
false
302
r
qm.R
#' qm #' #' Wraps an input in quotation marks. #' #' @param x Character or Numeric. #' #' @return A character string that begins and ends with quotation marks. #' @author Jonathan A. Greenberg #' #' @examples { #' qm("Hi!") #' qm(42) #' } #' @export qm <- function(x) { paste('"',x,'"',sep="") }
8a893dbaf0becf74dee174f62a96b15e31defc4f
589df3701d3012b0335d0f9e6090163ac160493c
/fn-train.r
3f7383e0c2417549a4673d8f528ca999ad9ffc08
[]
no_license
brentonk/ppp-replication
e8cdbef86723e6448d8efeecb36819c6ab9f6141
00e856ce3f054dfaeec9cf6fa1e6170c49df24f9
refs/heads/master
2020-04-28T14:04:50.412568
2019-04-22T21:15:31
2019-04-22T21:15:31
175,327,182
0
0
null
null
null
null
UTF-8
R
false
false
9,907
r
fn-train.r
################################################################################ ### ### Functions to train a Super Learner on the imputed CINC data ### ################################################################################ library("caret") library("dplyr") library("foreach") library("tidyr") ## Take a list of arguments and return either a list of trained models or a ## matrix of out-of-fold predicted probabilities ## ## Used in both the inner loop and the middle loop, which is why we need the ## flexibility in terms of the return value -- only need probabilities in the ## inner loop, but need the full model in the outer loop args_to_train <- function(arg_list, common_args, tr_control = trainControl(), data_train, data_test = NULL, id = NULL, for_probs = FALSE, allow_no_tune = TRUE, logfile = NULL) { ## Not allowing parallelization, since this function is always inside an ## imputation loop ans <- foreach (args = arg_list) %do% { ## Assemble arguments to pass to train() ## ## First element of each element of `args` must be `form`, containing ## the model formula train_args <- c(args, common_args, list(trControl = tr_control)) train_args$data <- data_train ## Don't resample if the model doesn't need to be tuned ## ## Can be switched off (e.g., if we want CV estimates of accuracy for ## non-tuned models) via the `allow_no_tune` argument if (allow_no_tune && isTRUE(train_args$doNotTune)) { train_args$trControl$method <- "none" } train_args$doNotTune <- NULL ## Train the model fit <- do.call(caret:::train.formula, train_args) ## Remove cross-validation indices, which aren't needed for further ## prediction and may take up a lot of space fit$control$index <- NULL fit$control$indexOut <- NULL ## Calculate out-of-fold probabilities, if requested ## ## In this case, the probabilities will be returned as output, not the ## trained model if (for_probs) { pred <- predict(fit, newdata = data_test, type = "prob") ## Hack to normalize predicted probabilities from avNNet models -- ## should be fixed in an upcoming version of caret ## ## See https://github.com/topepo/caret/issues/261 if (fit$method == "avNNet") { pred <- pred / rowSums(pred) } ## Include observation IDs for mapping back into original dataset pred$id <- id fit <- pred } if (!is.null(logfile)) { cat(args$method, as.character(Sys.time()), "\n", file = logfile, append = TRUE) } fit } ## Process output names(ans) <- names(arg_list) ans } ## Objective function for choosing weights on each model to minimize the ## log-loss of out-of-fold predicted probabilities ll_ensemble_weights <- function(w, pr_mat) { ## Compute the last weight -- not including in `w` because constrOptim() ## doesn't do equality constraints and must be initialized on the ## interior w <- c(w, 1 - sum(w)) ## Calculate predicted probability of the observed outcome for each ## observation pred <- drop(pr_mat %*% w) ## Log-likelihood of each observation is log(w * p_i) ## ## Multiplied by -1 since constrOptim() minimizes, and divided by number ## of observations for consistency with mnLogLoss() -1 * sum(log(pred)) / length(pred) } ## Derivative w.r.t. w_j is the sum of ## (p_j - p_J) / (w * p_i) ## across observations i grad_ensemble_weights <- function(w, pr_mat) { ## Calculate each w * p_i w <- c(w, 1 - sum(w)) pred <- drop(pr_mat %*% w) ## Subtract p_J from the preceding columns pr_mat <- sweep(pr_mat, 1, pr_mat[, ncol(pr_mat)], "-") pr_mat <- pr_mat[, -ncol(pr_mat)] ## Divide by each w * p_i pr_mat <- sweep(pr_mat, 1, pred, "/") ## Multiplied by -1 again since constrOptim() minimizes -1 * colSums(pr_mat) / length(pred) } ## Learn optimal ensemble weights for a matrix of out-of-fold predicted ## probabilities of observed outcomes learn_ensemble <- function(probs, outer.eps = 1e-8) { ## Constraints for weight selection: ## w_j >= 0 for all j ## -w_1 - ... - w_(J-1) + 1 >= 0 [ensures w_J is positive] n_models <- ncol(probs) ui <- rbind(diag(n_models - 1), -1) ci <- c(rep(0, n_models - 1), -1) ## Perform constrained out-of-fold log-likelihood maximization ## ## Starting value gives equal weight to all models theta_start <- rep(1/n_models, n_models - 1) names(theta_start) <- head(colnames(probs), n_models - 1) ensemble_optim <- constrOptim(theta = theta_start, f = ll_ensemble_weights, grad = grad_ensemble_weights, ui = ui, ci = ci, outer.eps = outer.eps, pr_mat = probs) ensemble_optim } train_weights <- function(dat, n_folds, arg_list, common_args, tr_control) { ## Generate cross-validation folds ## ## We're going to train each model *within* each fold as well, in order to ## get the out-of-sample probabilities we need to learn the ensemble weights cv_folds <- createFolds(y = dat$Outcome, k = n_folds, list = TRUE) ## Calculate out-of-fold predicted probabilities for each candidate model all_probs <- foreach (fold = seq_len(n_folds)) %do% { cat("FOLD", fold, as.character(Sys.time()), "\n") ## Retrieve the training and test sets corresponding to the given fold fold_train <- dat[-cv_folds[[fold]], , drop = FALSE] fold_test <- dat[cv_folds[[fold]], , drop = FALSE] ## Train each specified model and calculate the predicted probability of ## each out-of-fold outcome fold_probs <- args_to_train(arg_list = arg_list, common_args = common_args, tr_control = tr_control, data_train = fold_train, data_test = fold_test, id = cv_folds[[fold]], for_probs = TRUE, allow_no_tune = TRUE, logfile = "") fold_probs } ## Collapse the out-of-fold predictions from each model into a single data ## frame, each with observations in the same order as the original data ## ## The result is a list of said data frames, the same length as the number ## of models being trained all_probs_collapse <- foreach (model = seq_along(arg_list)) %do% { ## Retrieve relevant components of `all_probs` oof_preds <- foreach (fold = seq_len(n_folds), .combine = "rbind") %do% { all_probs[[fold]][[model]] } ## Place in order of original data using the id variable oof_preds <- oof_preds[order(oof_preds$id), ] oof_preds } names(all_probs_collapse) <- names(arg_list) ## Form a matrix of out-of-fold probabilities of *observed* outcomes obs_probs <- foreach (model = all_probs_collapse, .combine = "cbind") %do% { model$obs <- dat$Outcome ## Translate relevant element of `all_probs_collapse` into key-value ## format pred <- gather_(model, key_col = "Outcome", value_col = "prob", gather_cols = levels(dat$Outcome)) ## Extract the predicted values for the observed outcomes only pred <- filter(pred, as.character(obs) == as.character(Outcome)) ## Once again place in original order pred <- pred[order(pred$id), ] pred$prob } colnames(obs_probs) <- names(all_probs_collapse) ## Calculate optimal ensemble weights imputation_weights <- learn_ensemble(obs_probs) ## To estimate the bias of the minimum CV error via Tibshirani & ## Tibshirani's method, calculate the difference in CV error on each fold ## for the chosen weights versus the weights that would be optimal for that ## fold alone losses <- foreach (fold = seq_len(n_folds), .combine = "rbind") %do% { ## Subset the matrix of out-of-fold probabilities of observed outcomes ## to the relevant fold only obs_probs_fold <- obs_probs[cv_folds[[fold]], , drop = FALSE] ## Log loss using the weights chosen on the full dataset loss_global <- ll_ensemble_weights(w = imputation_weights$par, pr_mat = obs_probs_fold) ## Log loss using the weights that would be optimal for this fold alone loss_local <- learn_ensemble(obs_probs_fold)$value c(global = loss_global, local = loss_local) } bias_min_cv <- mean(losses[, "global"] - losses[, "local"]) list(out_probs = obs_probs, weights = imputation_weights, bias_min_cv = bias_min_cv, all_probs = all_probs_collapse) }
dbdefc902ffe5924d71c7c4a790ecead1d20aa8f
03e2a998e7764557d8333cd7063c1a06a5b2ec73
/R/session script.R
6d00adbb67e8001eedaf82422d8ed17b7fdda0f6
[]
no_license
jordache-ramjith/Project-1
0dee5e8da6d89a737a9fa26fea58b2f4a48472c6
f4f9f90970d379ec9a0e0463ff64f6142e0e88de
refs/heads/master
2021-09-09T12:57:34.224794
2018-03-16T10:22:48
2018-03-16T10:22:48
null
0
0
null
null
null
null
UTF-8
R
false
false
1,532
r
session script.R
library(usethis) #a function of the package usethis edit_r_profile() #this will allow us to use the package in future sessionswithout needing to call it from library if (interactive()){ suppressMessages(require(devtools)) suppressMessages(require(usethis)) } create_package("iemand") ###Go to package description and change etails ##type the following in the package script #use_mit_license(name="Jo Ramjith") creates an MIT license, obviously get the license for yourself use_r(name="create_age") #to link to a function called create_age use_git_config(user.name="Jordache1986", user.email="jordache.uct@gmail.com") use_git() creat_age() #inside gitbash send to server ?iemand #no documentation #create and R file for documentation use_package_doc() #link it to package document() ?document ######session 2###### #a unit test to not break the code use_testthat() context("test-create_age.R") test_that("create_age returns an integer",{ expect_is(create_age(),"integer")}) use_package(package="praise") use_package(package="magrittr") #a function to make UPPERCASE use_r("praise_nicely") praise_nicely("everyone") ?praise_nicely #####using data in your R package - including a function ###UCT github account - to share private repositories within your own institute ##create a data folder ##save data in package folder ##run prepare_name_data file #restart #run new package library(notiemand) head(sa_names) ##Now we WANT TO MAKE A FUNCTION THAT USES THE DATA #Function is called sa_names
953f51e30fb22910ed9dc6fd3d755bd4553cd2c2
46a1b4c7844e1287ce184ff4fb01fe74626460c1
/tests/runTests.R
37ef9b9fc5e2add033d4bd905607946c8134275d
[]
no_license
LihuaJulieZhu/NADfinder
7d3d810e5f35102efa69967a87e70d1dd64aad5c
2cf769212c7049274d84d9657eade65570a61384
refs/heads/master
2020-03-06T18:20:10.973542
2019-03-22T16:39:49
2019-03-22T16:39:49
127,005,268
0
0
null
null
null
null
UTF-8
R
false
false
238
r
runTests.R
require("NADfinder") || stop("unable to load Package:NADfinder") require("SummarizedExperiment") || stop("unable to load Package:SummarizedExperiment") require("testthat") || stop("unable to load testthat") #test_check("NADfinder")
9936e277ab13176eccf1971cd1c0a5e8eda3cdf3
fa3b78a6076dc9e4d46a087c6ee0f7d7e1d97f99
/GPX2CSV.R
0206b25d612040849ff029b0f173f0961cc8d8c9
[ "MIT" ]
permissive
quantixed/GPXanalysis
012202e1dfa0a92950c25a33f3ab9af93b6f0b78
2e8072aaf52f5c497af01bc2fe69908b97a58e60
refs/heads/master
2021-08-16T00:23:21.301564
2021-01-19T22:16:32
2021-01-19T22:16:32
77,203,820
1
0
null
null
null
null
UTF-8
R
false
false
1,389
r
GPX2CSV.R
library(XML) library(lubridate) library(raster) shift.vec <- function (vec, shift) { if(length(vec) <= abs(shift)) { rep(NA ,length(vec)) }else{ if (shift >= 0) { c(rep(NA, shift), vec[1:(length(vec)-shift)]) } else { c(vec[(abs(shift)+1):length(vec)], rep(NA, abs(shift))) } } } # Parse the GPX file gpxfile <- file.choose() pfile <- htmlTreeParse(gpxfile,error = function (...) {}, useInternalNodes = T) elevations <- as.numeric(xpathSApply(pfile, path = "//trkpt/ele", xmlValue)) times <- xpathSApply(pfile, path = "//trkpt/time", xmlValue) coords <- xpathSApply(pfile, path = "//trkpt", xmlAttrs) lats <- as.numeric(coords["lat",]) lons <- as.numeric(coords["lon",]) geodf <- data.frame(lat = lats, lon = lons,time = times) rm(list=c("elevations", "lats", "lons", "pfile", "times", "coords")) geodf$lat.p1 <- shift.vec(geodf$lat, -1) geodf$lon.p1 <- shift.vec(geodf$lon, -1) geodf$dist.to.prev <- apply(geodf, 1, FUN = function (row) { pointDistance(c(as.numeric(row["lon.p1"]), as.numeric(row["lat.p1"])), c(as.numeric(row["lon"]), as.numeric(row["lat"])), lonlat = T) }) geodf$time <- strptime(geodf$time, format = "%Y-%m-%dT%H:%M:%OS") geodf$time.p1 <- shift.vec(geodf$time, -1) geodf$time.diff.to.prev <- as.numeric(difftime(geodf$time.p1, geodf$time)) head(geodf) write.csv(geodf,'geodf.csv')
955267cd03aaadfcdff7ae7e5509d0dcb2578619
a2564d11f5b60532ad6c3ab2a850ffb996879819
/man/run_from_file.Rd
2ba1f934cc41fc1111d06edcfceaf59779e71b3e
[]
no_license
marcrr/BgeeCall
6aace1d3be82bfb6e291f1b04c6330a60924fb7e
c85802f1a90f76d701899c9e1962fb5a76bc74e0
refs/heads/master
2020-04-20T20:21:25.778673
2019-02-01T18:57:39
2019-02-01T18:57:39
169,074,371
0
0
null
2019-02-04T12:21:51
2019-02-04T12:21:51
null
UTF-8
R
false
true
795
rd
run_from_file.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/runCallsPipeline.R \name{run_from_file} \alias{run_from_file} \title{generate present/absent calls from a file} \usage{ run_from_file(myAbundanceMetadata = new("KallistoMetadata"), myBgeeMetadata = new("BgeeMetadata"), userMetadataFile) } \arguments{ \item{myAbundanceMetadata}{A Reference Class BgeeMetadata object (optional)} \item{myBgeeMetadata}{A Reference Class BgeeMetadata object (optional)} \item{userMetadataFile}{A tsv file describing all user libraries for which present/absent calls have to be generated} } \description{ Main function allowing to generate present/absent calls for some libraries described in a file. Each line of the file describes one RNA-Seq library. } \author{ Julien Wollbrett }
a8d1342ca89392709d8c8efe7deb43b409bdb35f
d220633376ccc1cb5cbe654a69d0459792c4d2ce
/01-Data_Functions.R
652f2285a4b09a48011c12d44ee68bc8da681f7e
[ "Apache-2.0" ]
permissive
jamiahuswalton/Analysis_Dissertation_Scripts
5b93ffbf25f31a517c42768d4927d88cece424c3
dbec4e82fb09f7f6c0ac2da4b5ca05db6c99c08b
refs/heads/master
2020-04-07T03:41:46.070652
2019-07-01T15:04:09
2019-07-01T15:04:09
158,026,449
0
0
Apache-2.0
2019-05-03T15:47:50
2018-11-17T21:28:30
HTML
UTF-8
R
false
false
52,693
r
01-Data_Functions.R
# Remove teams from raw data (Clean raw data) ---- remove_a_team_from_raw_data <- function(data, teams_to_be_removed, name_of_team_number_col){ clean_data <- data for(team in teams_to_be_removed){ team_to_remove_from_inventory <- which(clean_data[,name_of_team_number_col] == team) clean_data <- clean_data[-team_to_remove_from_inventory,] } return(clean_data) } # Remove measures with a give value ---- remove_measures_with_given_value <- function(data_set, col_name, value){ rows_to_move <- which(as.vector(data_set[,col_name]) == value) return(data_set[-rows_to_move,]) } # Clean inventory table---- clean_inventory_data_by_removing_game_enteries <- function(inventory_data, column_to_look_into, value_to_remove){ inventory_entries_to_remove <- which(inventory_data[,column_to_look_into] == value_to_remove) return(inventory_data[-inventory_entries_to_remove,]) } # Count the total number of errors commited by a team (regarless of if this rule was broken before) ---- total_number_of_errors_team <- function(data_errors, teamNum, condition){ team_errors_data <- data_errors %>% filter(teamnumber == teamNum & expcondition == condition) return(length(team_errors_data[,"ID"])) } # Function to calculate the total error rate (i.e., Duration / total errors) for a team Units: Sec / Error. # Duration is retruned if error count is 0. error_rate_team <- function(data_position, data_errors, teamNum, condition){ error_count_team <- total_number_of_errors_team(data_errors, teamNum, condition) data_team <- data_position %>% filter(teamnumber == teamNum & playernum == 1 & expcondition == condition) data_team_last_line <- tail(data_team,1) duration_team<- data_team_last_line[1,"duration"] if(error_count_team == 0){ return(duration_team) } else if(error_count_team > 0){ return(duration_team / error_count_team) } else if(error_count_team < 0){ message<- paste("error_rate_team: the error count generated for team", teamNum, "in condition", condition) stop(message) } } # Count the total number of errors commited by a player (regarless of if this rule was broken before) ---- total_number_of_errors_individual <- function(data_errors, teamNum, player, condition){ ind_errors_data <- data_errors %>% filter(teamnumber == teamNum & playernum == player & expcondition == condition) total_errors_individual <- length(ind_errors_data[,"ID"]) return(total_errors_individual) } # Function to calculate the total error rate (i.e., Duration / total errors) for an individual. Units: Sec / Error # Duration is retruned if error count is 0. error_rate_ind <- function(data_position, data_errors, teamNum, playerNum, condition){ error_count_ind <- total_number_of_errors_individual(data_errors, teamNum, playerNum, condition) data_ind <- data_position %>% filter(teamnumber == teamNum & playernum == playerNum & expcondition == condition) data_ind_last_line <- tail(data_ind,1) duration_ind<- data_ind_last_line[1,"duration_ind"] if(error_count_ind == 0){ return(duration_ind) } else if(error_count_ind > 0){ return(duration_ind / error_count_ind) } else if(error_count_ind < 0){ message<- paste("error_rate_ind: the error count generated for player", playerNum, "in team", teamNum, "in condition", condition) stop(message) } } # Factor the columns ---- re_factor_columns <- function(userData, columnNames){ factorData <- userData for(column in columnNames){ print(column) factorData[,column] <- factor(factorData[,column]) } return(factorData) } # Generate team number list in a given data set ---- list_of_team_numbers <- function(data, team_number_col_name){ return(as.numeric(levels(factor(as.vector(data[,team_number_col_name]))))) } # Count the number of times a game strategy was used ---- strategy_count_vector<- function(position_data, experimentalcondition, teamnumber_current, playernumber_one, playernumber_two, playernumber_three, strategy_barrier_distance){ #Need to get the position Data for all players (3 players) is_player_1 <- as.vector(position_data$expcondition == experimentalcondition & position_data$teamnumber == teamnumber_current & position_data$playernum == playernumber_one) is_player_2<- as.vector(position_data$expcondition == experimentalcondition & position_data$teamnumber == teamnumber_current & position_data$playernum == playernumber_two) is_player_3<- as.vector(position_data$expcondition == experimentalcondition & position_data$teamnumber == teamnumber_current & position_data$playernum == playernumber_three) is_team_current<- as.vector(position_data$expcondition == experimentalcondition & position_data$teamnumber == teamnumber_current) pos_player_1<- position_data[is_player_1,] pos_player_2<- position_data[is_player_2,] pos_player_3<- position_data[is_player_3,] #This is the length of the position data. They will not have the same number of enteries due to time issues. The number of strategies checked will be equal to the lowest number number_of_checkes <- min(c(length(pos_player_1[,1]), length(pos_player_2[,1]), length(pos_player_3[,1]))) #Make sure they are in the correct order (The ID value at the top should be the lowest) #Calculate calculate the centroiz value for X and Z (Y value does not change in unity) x_1 <- as.vector(pos_player_1$pos_x[1:number_of_checkes]) x_2 <- as.vector(pos_player_2$pos_x[1:number_of_checkes]) x_3 <- as.vector(pos_player_3$pos_x[1:number_of_checkes]) z_1 <- as.vector(pos_player_1$pos_z[1:number_of_checkes]) z_2 <- as.vector(pos_player_2$pos_z[1:number_of_checkes]) z_3 <- as.vector(pos_player_3$pos_z[1:number_of_checkes]) x_centroid<- (x_1 + x_2 + x_3)/3 z_centroid<- (z_1 + z_2 + z_3)/3 #Calculate the distance from each player to the centroid player_1_distance_from_centroid<- sqrt((x_1 - x_centroid)^2 + (z_1 - z_centroid)^2) player_2_distance_from_centroid<- sqrt((x_2 - x_centroid)^2 + (z_2 - z_centroid)^2) player_3_distance_from_centroid<- sqrt((x_3 - x_centroid)^2 + (z_3 - z_centroid)^2) #determine the strategy being used based on distance strategy_vectors<- seq(1:number_of_checkes) for(index in seq(1:number_of_checkes)){ #Performing math operations on logic vectors turns TRUEs in 1's and FALSE's into 0's check_distances<- c(player_1_distance_from_centroid[index] < strategy_barrier_distance, player_2_distance_from_centroid[index] < strategy_barrier_distance, player_3_distance_from_centroid[index] < strategy_barrier_distance) #1 = "Go Together", 2 = "Go Alone", 3 = "Mix" if(sum(check_distances) == 3){ #Go Together - this means that everyone is within the strategy border strategy_vectors[index]<- 1 } else if(sum(check_distances) == 0){ paste("Go Alone") #Go Alone - this means that everyone was outside the strategy border strategy_vectors[index] <- 2 } else { paste("Mix") #Mix - this means that some were inside the borader and others were outside the border strategy_vectors[index] <- 3 } } # 1 = "Go Together", 2 = "Go Alone", 3 = "Mix" count_go_together <- sum(strategy_vectors == 1) count_go_alone <- sum(strategy_vectors == 2) count_mix <- sum(strategy_vectors == 3) return(c(count_go_together, count_go_alone, count_mix)) } # Counts the number of utterences for a player in a given condition ---- utterance_count_for_a_player<- function(positionData, condition, team_number, player_num){ #Get players table data is_player_1 <- as.vector(positionData$expcondition == condition & positionData$teamnumber == team_number & positionData$playernum == player_num) current_player <- positionData[is_player_1,] #Determine the number of utterences current_player_transmission_set<- current_player$istransmitting #Need a variable that indicates if the player is currently talking isTalking <- FALSE #Utterance count utterance_count <- 0 # Count the number of utterances # An utterance is defined as a consecutive set of checks were the intervale value is great than 0, (i.e., ~.25) for(index in seq(from = 1, to = length(current_player_transmission_set))){ #get current check interval current_check_interval<- current_player_transmission_set[index] #If the index is 1, then this means it is the first check. The first check is different than the following checks if(index != 1){ # This means that the current index is not one. As a result, there should have been a previosu check value # Get the previous value previous_check_interval<- current_player_transmission_set[index-1] if(current_check_interval > 0){ #This means that the player was talking during this interval check #Is this the last vector index? if(index != length(current_player_transmission_set)){ # This is not the last vaule in the vector #If the previous value was 0, that means that the player just started talking. We set the isTalking value to true if(previous_check_interval == 0.00){ #This means that the player just started talking } else if(previous_check_interval > 0){ #This means that the paleyer is continuing to talk } } else { # This is the last value in the vector. #Since this is the last vector value and the value of it is greater than 0, this means the player was last talking before the game ended. #This will count as a utterence. The loop should end after this current pass utterance_count <- utterance_count + 1 } #The player is talking during this check isTalking <- TRUE } else if(current_check_interval == 0){ # Was the player talking previously? if(isTalking){ #This means that the player was talking previously but is not longer talking. This is the end of an utterance, so count it utterance_count <- utterance_count + 1 } else{ #This means that the player was not talkin previously and is still not talking } #The player is no longer talking isTalking <- FALSE } else { #isTalking <- FALSE } } else if(index == 1){ # This means that this is the first index value. #If the player is talking, set isTalking to true if(current_check_interval > 0){ isTalking <- TRUE } } } # Return utterance count for this player in a given condition return(utterance_count) } # Generate the IDs for a player on a given team (Assuming there are 3 members per team)---- generate_player_id <- function(playernum, teamnum){ # This function assumes that player IDs are assigned in sequential order. # For example, in team 1, player 1 is P1, 2 is p2, and P3. Team 2, player 1 is P4, 2 is P5, 3 is P6 max_player_ID_value <- 3 * teamnum # 3 is hardcoded because there should have only three elements palyer_ID <- "" if(playernum == 3){ player_ID_num <- max_player_ID_value if(player_ID_num < 10){ palyer_ID <- paste("P0", player_ID_num, sep = "") } else if(player_ID_num >= 10){ palyer_ID <- paste("P", player_ID_num, sep = "") } } else if(playernum == 2 ){ player_ID_num <- max_player_ID_value - 1 if(player_ID_num < 10){ palyer_ID <- paste("P0", player_ID_num, sep = "") } else if(player_ID_num >= 10){ palyer_ID <- paste("P", player_ID_num, sep = "") } } else if(playernum == 1) { player_ID_num <- max_player_ID_value - 2 if(player_ID_num < 10){ palyer_ID <- paste("P0", player_ID_num, sep = "") } else if(player_ID_num >= 10){ palyer_ID <- paste("P", player_ID_num, sep = "") } } return(palyer_ID) } #Function to retrive the NASA TLX value for a specific scale, for a specific player, in a specific team, in a specific condition scale_value_NASA_TLX <- function (TLX_table, teamNum, playerNum, condition, scale){ player_tlx <- TLX_table %>% filter(Team == teamNum, Player == playerNum, Condition == condition) if(length(player_tlx[,scale] == 1)){ return(player_tlx[,scale]) } else if(length(player_tlx[,scale]) == 0){ stop(paste("No TLX data found for player", playerNum, "in team", teamNum, "in condition", condition)) } else { stop(paste("There is not exactly 1 entery for player", playerNum, "in team", teamNum, "in condition", condition)) } } # Return familiary value for team familiarity_value<- function(data_familiar, team_num, team_column_name){ team_data <- data_familiar %>% filter(.data[[team_column_name]]== team_num) num_of_entries<- length(team_data[[team_column_name]]) if(num_of_entries == 1){ return(team_data[["Familiarity"]]) } } # Retrive demographic value demographic_value_get <- function(demographic_data, key_rand_playerID_data, player_Id_value, demographic_value){ rand_num <- key_rand_playerID_data %>% filter(ID == player_Id_value) if(length(rand_num[[1]]) == 1){ # There should only be one value. player_demo_data <- demographic_data %>% filter(Rand == rand_num$Random_num) if(length(rand_num[[1]]) == 1){ return(player_demo_data[[demographic_value]]) } else{ # This means there is more than one value. That is a problem. message <- paste("There are multiple deomgraphic entries for the player with the ID", player_Id_value, ".") stop(message) } } else{ # This means there is more than one value. That is a problem for demographic data. message <- paste("The player with the ID", player_Id_value, "does not have a rand number value.") stop(message) } } # Get post-session value post_session_survey_value<- function(data_post_session, team, player, condition, survey_value){ player_data<- data_post_session %>% filter(Condition == condition, Team == team, Player == player) if(length(player_data[[1]]) != 1){ message <- paste("Could not find post session survey data for player", player, "in team", team, "for condition", condition) stop(message) } return(player_data[[survey_value]]) } # Get overall post-session value overall_post_session_survey_value<- function(overall_post_data, key_rand_playerID_data, player_Id_value, value_name){ rand_num_player<- key_rand_playerID_data %>% filter(player_Id_value == ID) if(length(rand_num_player[["Random_num"]]) == 1){ player_rand_value<- rand_num_player[1,"Random_num"] } else{ message<- paste("Rand key data table has more than or less than one entery with the ID:", player_Id_value) stop(message) } player_data<- overall_post_data%>% filter(Rand == player_rand_value) if(length(player_data[["Rand"]])== 1){ return(player_data[[value_name]]) } else{ message<- paste("The overal post survey has more than or less than one entry that has a Random number value of", player_rand_value) stop(message) } } # Find session order ---- session_order_number <- function(teamNum, counter_balance_set_dataframe, condition){ set_index <- teamNum %% length(counter_balance_set_dataframe) #If this equal 0 then that means this team used the last set if(set_index == 0){ #This means that this team used the last set set_index = length(counter_balance_set_dataframe) } # Select the correct session order list session_set_in_order <- counter_balance_set_dataframe[,set_index] # Assumes the set is in a data frame #Find the index of the session order and that is the session order (e.g., an index of 3 means this session was the 3rd session) current_session_order <- which(condition == session_set_in_order) return(current_session_order) } # Find the counterbalance set order set_counter_balance_number <- function(teamNum, counter_balance_set_dataframe){ set_index <- teamNum %% length(counter_balance_set_dataframe) if(set_index == 0){ #This means that this team used the last set set_index = length(counter_balance_set_dataframe) } return(set_index) } # Total distance traveled by a player ---- total_distance_traveled_by_player<- function(position_data, experimentalcondition, teamnumber_current, playerNum, col_name_X, col_name_y){ # Player data player_data_index <- which(position_data$teamnumber == teamnumber_current & position_data$playernum == playerNum & position_data$expcondition == experimentalcondition) x <- position_data[player_data_index,col_name_X] y <- position_data[player_data_index,col_name_y] x.1 <- x[1:length(x) - 1] x.2 <- x[2:length(x)] y.1 <- y[1:length(y)-1] y.2 <- y[2:length(y)] total_distance <- sum(sqrt((x.2 - x.1)^2 + (y.2 - y.1)^2)) return(total_distance) } # Total distance traveled by team ---- total_distance_traveled_by_team <- function(position_data, experimentalcondition, teamnumber_current, col_name_X, col_name_y){ # Assuming there are three members in each team distance_traveled_by_each_player <- rep(x = 0, times = 3) for(player in seq(1,3)){ distance_traveled_by_each_player[player] <- total_distance_traveled_by_player(position_data, experimentalcondition, teamnumber_current, player, col_name_X, col_name_y) } return(sum(distance_traveled_by_each_player)) } # Total items (correct and incorrect)(team and individual) collected by a player in a given session total_items_collected_in_session_by_individual <- function(inventory_data, team_num, player_num, condition_name){ inventory_data_filtered <- inventory_data %>% filter(teamnumber == team_num & expcondition == condition_name & playernum == player_num & itemid != -1) return(length(inventory_data_filtered[,1])) } # Function to calculate the Collection Rate (i.e., duration / total items collected): Sec / Error. ---- # Duration is retruned if error count is 0. collection_rate_ind <- function(data_position, data_inventory, teamnum, playernumber, condition){ # This is the item collection rate for an individual # The units for this value is Sec / item. # This takes into account the total items (incorrect or correct) collected by the individual total_items_collected <- total_items_collected_in_session_by_individual(data_inventory, teamnum, playernumber, condition) player_data <- data_position %>% filter(teamnumber == teamnum & playernum == playernumber & expcondition == condition) player_data_last_line <- tail(player_data, 1) duration_ind <- player_data_last_line[1,"duration_ind"] if(total_items_collected == 0){ return(duration_ind) } else if(total_items_collected > 0){ return(duration_ind / total_items_collected ) } else if(total_items_collected < 0){ message<- paste("collection_rate_ind: the total item count for player", playerNum, "in team", teamNum, "in condition", condition) stop(message) } } # Total correct items (team and individual items) collected by a player in a given session ---- total_correct_items_collected_in_session_by_individual <- function(inventory_data, team_num, player_num, condition_name){ inventory_data_filtered <- inventory_data %>% filter(playernum == player_num & teamnumber == team_num & expcondition == condition_name & itemid != -1 & boughtcorrectly == 1) return(length(inventory_data_filtered[,"itemid"])) } # Function to calculate the Collection Rate for correct items (i.e., duration / total items collected): Sec / Item.---- # Duration is retruned if error count is 0. collection_rate_correct_items_ind <- function(data_position, data_inventory, teamnum, playernumber, condition){ # This is the item collection rate for an individual # The units for this value is Sec / item. # This takes into account the total correct items (team and individual) collected by the individual total_items_collected <- total_correct_items_collected_in_session_by_individual(data_inventory, teamnum, playernumber, condition) player_data <- data_position %>% filter(teamnumber == teamnum & playernum == playernumber & expcondition == condition) player_data_last_line <- tail(player_data, 1) duration_ind <- player_data_last_line[1,"duration_ind"] if(total_items_collected == 0){ return(duration_ind) } else if(total_items_collected > 0){ return(duration_ind / total_items_collected) } else if(total_items_collected < 0){ message<- paste("collection_rate_correct_items_ind: the total correct item count for player", playerNum, "in team", teamNum, "in condition", condition) stop(message) } } # Total items (correct and incorrect)(team and individual) collected by a team in a given session ---- total_items_collected_in_session_by_team <- function(data_inventory, team_num, condition_name){ inventory_data_filtered <- data_inventory %>% filter(teamnumber == team_num & expcondition == condition_name & itemid != -1) return(length(inventory_data_filtered[,"itemid"])) } # Function to calculate the Collection Rate (i.e., duration / total items collected): Sec / Error. ---- # Duration is retruned if error count is 0. collection_rate_team <- function(data_position, data_inventory, teamnum, condition){ # This is the item collection rate for a team # The units for this value is Sec / item. # This takes into account the total items (incorrect or correct) collected by the team total_items_collected <- total_items_collected_in_session_by_team(data_inventory, teamnum, condition) team_data <- data_position %>% filter(teamnumber == teamnum & playernum == 1, expcondition == condition) team_data_last_line <- tail(team_data, 1) duration_team <- team_data_last_line[1,"duration"] if(total_items_collected == 0){ return(duration_team) } else if(total_items_collected > 0){ return(duration_team / total_items_collected) } else if(total_items_collected < 0){ message<- paste("collection_rate_team: the total item count for team", teamNum, "in condition", condition) stop(message) } } # Total correct items (team and individual items) collected by a team in a given session ---- total_correct_items_collected_in_session_by_team <- function(data_inventory, team_num, condition_name){ inventory_data_filtered <- data_inventory %>% filter(teamnumber == team_num & expcondition == condition_name & itemid != -1 & boughtcorrectly == 1) return(length(inventory_data_filtered[,"itemid"])) } # Function to calculate the Collection Rate for correct items (i.e., duration / total items collected): Sec / Item. ---- # Duration is retruned if error count is 0. collection_rate_correct_items_team <- function(data_position, data_inventory, teamnum, condition){ # This is the item collection rate for a team # The units for this value is Sec / item. # This takes into account the total correct items (team and individual) collected by a team total_items_collected <- total_correct_items_collected_in_session_by_team(data_inventory, teamnum, condition) team_data <- data_position %>% filter(teamnumber == teamnum & playernum == 1, expcondition == condition) team_data_last_line <- tail(team_data, 1) duration_team <- team_data_last_line[1,"duration"] if(total_items_collected == 0){ return(duration_team) } else if(total_items_collected > 0){ return(duration_team / total_items_collected) } else if(total_items_collected < 0){ message<- paste("collection_rate_correct_items_team: the total correct item count for team", teamNum, "in condition", condition) stop(message) } } # Check to see if the random numbers in demographics surveys match the random numbers in the post surveys ---- is_demographic_rand_num_in_post_survey <- function(post_session_table, demo_survey, team_col_name, player_col_name, rand_num_col_name){ #team_col_name : for the post_session_table #rand_num_col_name: This name should be the same for the post_session_table survey and the demo_survey is the name in the is_in_post_survey <- T # Make sure post session data is good post_session_survey_is_good <- is_post_session_data_correct(post_session_table, team_col_name, player_col_name, rand_num_col_name) if(!post_session_survey_is_good){ message <- paste("Something wrong with post_session survey.") stop(message) } rand_num_list_demo <- as.vector(demo_survey[,rand_num_col_name]) if(sum(duplicated(rand_num_list_demo)) > 0){ # If there is more than one of the same rand number, then something is wrong message <- paste("There are duplicate rand num values.") is_in_post_survey <- F stop(message) } for(rand_num in rand_num_list_demo){ rand_in_post_survey <- rand_num == as.vector(post_session_table[,rand_num_col_name]) if(sum(rand_in_post_survey) == 0){ message <- paste("The rand number ", rand_num, " was not found in the post session", sep = "") stop(message) } } return(is_in_post_survey) } # Check to make sure TLX survey is correct (i.e., make sure every player in the key has the correct number of TLX values 4) ---- is_TLX_survey_correct <- function(data_tlx, rand_num_list){ is_valid <- T for (rand in rand_num_list) { data_tlxTemp <- data_tlx %>% filter(Rand.Num == rand) if(length(data_tlxTemp[[1]]) != 4){ message <- paste("There is not exactly 4 entries in the TLX for random number ", rand) is_valid <- F stop(message) break } } return(is_valid) } # Check to make sure each rand number in the post survey responses are the same for each player in each team ( for all of the conditions) ---- is_post_session_data_correct <- function(post_session_data, team_number_column_name, player_num_col_name, rand_num_col_name){ is_correct <- T team_list <- as.integer(levels(factor(post_session_data[,team_number_column_name]))) # The teams that are in the data set for(team in team_list){ for(player in c(1,2,3)){ team_col <- as.vector(post_session_data[,team_number_column_name]) player_num_col <- as.vector(post_session_data[,player_num_col_name]) player_index <- which(team_col == team & player_num_col == player) num.of.enteries <- length(player_index) if(num.of.enteries != 4){ # -- Check to see if there is exactly 4 entiers, if more/less than 4 then something is wrong message <- paste("There is either more than or less than 4 data points for team ", team, " and player ", player, sep = "") is_correct <- F stop(message) } # -- Pick first value and make sure it is the same throughout player_data <- post_session_data[player_index,] first.rand.num <- player_data[1, rand_num_col_name] all.rand.num <- player_data[,rand_num_col_name] if(sum(all.rand.num != first.rand.num) > 0){ # This means one or more rand numbers enteries are not the same as the others message <- paste("One or more of the rand number enteries are not the same as the other enteriesf. Team ", team, ", player ", player, ", rand ", first.rand.num, sep = "") is_correct <- F stop(message) } # Check to make sure the player numbers are correct team_index <- which(team_col == team) team_data <- post_session_data[team_index,] player_col <- as.vector(team_data[,"Player"]) # Get the player colum (i.e., 1,2, or 3) player_factors <- levels(factor(player_col)) # print(paste("Factors: ", player_factors)) for(player in player_factors){ # Check to make sure there are 4 enteries for each player num_of_enteries_for_player <- sum(player == player_col) if(num_of_enteries_for_player !=4){ message <- paste("There is more or less than 4 enteries for player ", player, " in team ", team, ".", sep = "") is_correct <-F stop(message) } } } } return(is_correct) } # Generate aggragate data (final team score, final individual score, ) ---- generate_aggragate_data <- function(team_numbers, condition_list, clean_position_data, clean_error_data, clean_invent_data, clean_demo_data, clean_familiarity_data, clean_overall_post_data, player_num_list, strategy_barrier_dis, counter_balance_set, col.names, names_TLX, names_PostSession, names_Overall_Postsession, key_rand_player_data, names_demographic ){ # Final data output number_of_columns<- length(col.names) data_output_final<- matrix(0, nrow = 0, ncol = number_of_columns) # Give column names colnames(data_output_final)<- col.names for(team in team_numbers){ # Counter balance set number for the team counter_balance_set_num <- set_counter_balance_number(team, counter_balance_set) # Familiarity value for team familiarity_of_team<- as.character(familiarity_value(clean_familiarity_data,team, "ï..Team")) # Note sure why the column name is "ï..Team" in stead of "Team". for(condition in condition_list){ #Count the number of times strategies were used current_strategy_vector<- strategy_count_vector(position_data = clean_position_data, experimentalcondition = condition, teamnumber_current = team, playernumber_one = player_num_list[1], playernumber_two = player_num_list[2], playernumber_three = player_num_list[3], strategy_barrier_distance = strategy_barrier_dis) current_go_together_count<- current_strategy_vector[1] current_go_alone_count <- current_strategy_vector[2] current_mix<- current_strategy_vector[3] #Get the total utterence count for a team player_utterance_count_list<- rep(x = 0, times = length(player_num_list)) #Get the total number of errors for team total_errors_team <- total_number_of_errors_team(clean_error_data, team, condition) #Find the count for each palyer (i.e., index 1 is player 1) for(player in player_num_list){ current_player_utterence_count <- utterance_count_for_a_player(positionData = clean_position_data, condition, team, player) #ErrorCheck if(length(current_player_utterence_count) > 1){ stop("utterance_count_for_a_player() function produceted a vector that had a length greater than 1. Should only be 1 element.") } player_utterance_count_list[player] <- current_player_utterence_count[1] #This is hard codded because there should only be one value } #Total Distance traveled - Team total_dis_team <- total_distance_traveled_by_team(position_data = clean_position_data, condition, team, "pos_x", "pos_z") # Get player 1 data is_player_1<- as.vector(clean_position_data$expcondition == condition & clean_position_data$teamnumber == team & clean_position_data$playernum == 1) #Use the team score recorded from player 1 player_data_1<- clean_position_data[is_player_1,] last_line_1 <- length(player_data_1[,1]) #Last line index #Team Score team_final_score<- as.vector(player_data_1[last_line_1,"teamscore"]) #Team time remaining time_remaining_team <- as.vector(player_data_1[last_line_1,"gametimer"]) # Collection rate for team in a condition (correct and incorrect items)(team and individual) team_collection_rate <- collection_rate_team(clean_position_data, clean_invent_data, team, condition) # Collection rate for team in a condition (correct items) (team and individual items) team_collection_rate_correct_items <- collection_rate_correct_items_team(clean_position_data, clean_invent_data, team, condition) # Error rate for the team team_error_rate <- error_rate_team(clean_position_data, clean_error_data, team, condition) for(player in player_num_list){ # The next step is to add all of the values for each cloumn is_player<- as.vector(clean_position_data$expcondition == condition & clean_position_data$teamnumber == team & clean_position_data$playernum == player) player_data<- clean_position_data[is_player,] #The order of the variables is determined by the cloumn name vector - col_names #Last Line in Data Table last_line<- length(player_data[,1]) #Last line index # Set the target feedback and if there was feedback present if(condition == "A"){ target_for_feedback<- c("None") } else if(condition == "B"){ target_for_feedback<- c("Ind") } else if (condition == "C"){ target_for_feedback<- c("Team") } else if (condition == "D"){ #The only other condition is condition D target_for_feedback<- c("Ind_Team") } else { stop("A condition value was not recognized.") } # Get the time remaining team and individual time_remaining_ind <- as.vector(player_data[last_line,"gametimer_ind"]) #Get the Individual Score individual_final_score<- as.vector(player_data[last_line,"individualscore"]) #Correct Individual Items Collected correct_individual_items_collected<- as.vector(player_data[last_line, "ci_ind"]) #Incorrect Individual Items Collected incorrect_individual_item_collected<- as.vector(player_data[last_line, "ii_ind"]) #errors Individual errors_individual_unique<- as.vector(player_data[last_line, "error_ind"]) #Get the total number of errors for player total_errors_ind <- total_number_of_errors_individual(data_errors = clean_error_data, team, player, condition) # Get total distance traveled by player total_dis_ind <- total_distance_traveled_by_player(position_data = clean_position_data, condition, team, player, "pos_x", "pos_z") #Correct Team Items Collected correct_team_items_collected<- as.vector(player_data[last_line, "ci_team"]) #Incorrect Team Items collected incorrect_team_item_collected<- as.vector(player_data[last_line, "ii_team"]) #Errors Team errors_team_unique<- as.vector(player_data[last_line, "error_team"]) #Transmission total_transmition_ind<- sum(as.vector(player_data$istransmitting)) #Utterance count current_utterance_count_player <- player_utterance_count_list[player] current_utterance_count_team <- sum(player_utterance_count_list) # total team transmission time current_team_index <- which(condition == clean_position_data[,"expcondition"] & team == clean_position_data[,"teamnumber"]) current_team_position_data <- clean_position_data[current_team_index,] total_transmition_team <- sum(current_team_position_data$istransmitting) #Dominate Strategy. The dominitate strategy was the strategy used the highest number of times if(max(current_strategy_vector) == current_go_together_count){ dominate_strategy_used<- go_together_name } else if (max(current_strategy_vector) == current_go_alone_count){ dominate_strategy_used<- go_alone_name } else if (max(current_strategy_vector) == current_mix){ dominate_strategy_used<- mix_name } else { stop("The max count in the strategy vector does not equal any of the selected strategy counts") } # Find player id current_player_id <- generate_player_id(player,team) # Demographic survey data demo_values<- vector() for(name in names_demographic){ # Need to make the the values a character because there are different types of values. value<- as.character(demographic_value_get(clean_demo_data, key_rand_player_data, current_player_id, name)) demo_values<- append(demo_values, value) } #--------------------------------------------------------------- #Find the session order current_session_order <- session_order_number(team, counter_balance_set, condition) #--------------------------------------------------------------- # Collection rate for individual (correct and incorrect)(team and individual items) individual_collection_rate <- collection_rate_ind(clean_position_data, clean_invent_data, team, player, condition) # Collection rate for individual (correct items)(team and individual items) individual_collection_rate_correct_items <- collection_rate_correct_items_ind(clean_position_data, clean_invent_data, team, player, condition) # TLX values for player TLX_values<- vector() for(name in names_TLX){ value<- scale_value_NASA_TLX(NASA_TLX_table, team, player, condition, name) TLX_values<- append(TLX_values,value) } # Post-Session Survey values Post_Session_Values<- vector() for (name in names_PostSession) { index<- which(names_PostSession == name) value<- as.character(post_session_survey_value(post_session_table, team, player,condition, name)) Post_Session_Values[index] <- value } # Overall post-session survey values Overall_Post_Session_Values<- vector() for (name in names_Overall_Postsession) { value <- as.character(overall_post_session_survey_value(clean_overall_post_data, key_rand_player_data, current_player_id, name)) Overall_Post_Session_Values<- append(Overall_Post_Session_Values, value) } # Error Rate for individual ind_error_rate <- error_rate_ind(clean_position_data, clean_error_data, team, player, condition) #This should be the same as the col_names variable above. data_output_final<- rbind(data_output_final, c(team, familiarity_of_team, condition, player, current_player_id, current_session_order, counter_balance_set_num, target_for_feedback, time_remaining_ind, time_remaining_team, individual_final_score, team_final_score, correct_individual_items_collected, incorrect_individual_item_collected, individual_collection_rate, individual_collection_rate_correct_items, errors_individual_unique, total_errors_ind, ind_error_rate, total_dis_ind, correct_team_items_collected, incorrect_team_item_collected, team_collection_rate, team_collection_rate_correct_items, errors_team_unique, total_errors_team, team_error_rate, total_dis_team, total_transmition_ind, total_transmition_team, current_utterance_count_player, current_utterance_count_team, current_go_together_count, current_go_alone_count, current_mix, dominate_strategy_used, TLX_values, Post_Session_Values, Overall_Post_Session_Values, demo_values)) } } # Progress Bar team_index <- which(team == team_numbers) progress(team_index / length(team_numbers) * 100) } return(data_output_final) } # Generate figures for dependent variables with specified x variables ---- generate_figures_team <- function(Data, num_of_teams, figure_titles, y_values_team, y_labels_team, x_values, x_labels_team, plot_types, filelocation){ # Need to change the variables previous_wd_location <- getwd() setwd(filelocation) # What is the N for Teams N_teams <- num_of_teams # The N text to add to title for teams N_teams_full_text <- paste("(N = ", N_teams, ")", sep = "") for(y_current in y_values_team){ for (x_current in x_values){ index_for_y <- which(y_current == y_values_team) index_for_x <- which(x_current == x_values) for(plot in plot_types){ x_label <- x_labels_team[index_for_x] y_label <- y_labels_team[index_for_y] figure_title <- figure_titles[index_for_y] # print(paste("x: ", x_current," ","y: ", y_current, " ", "Plot: ", plot, " ", "Label: ", x_label," ", "Label (y): ", y_label , sep = "")) filename_graph <- paste("team_",y_label,"_by_",x_label,"_",plot,".png", sep = "") if(plot == "Group_Bar"){ Data_ordered <- Data %>% mutate(position = rank(-Data[,y_current], ties.method="first")) ggplot(data = Data_ordered, aes_string(x = x_current, y = y_current, fill = "Team", group = "position")) + geom_bar(stat = "identity", position = "dodge") + labs(title = paste(figure_title, N_teams_full_text) , x = x_label, y = y_label) + guides(fill=guide_legend(title="Team")) ggsave(filename = filename_graph) } else if(plot == "Boxplot"){ ggplot(data = Data, aes_string(x = x_current, y = y_current)) + geom_boxplot() + labs(title = paste(figure_title, N_teams_full_text), x = x_label, y = y_label) ggsave(filename = filename_graph) } else if(plot == "Point_plot"){ ggplot(data = Data, aes_string(x = x_current, y = y_current)) + geom_point() + labs(title = paste(figure_title, N_teams_full_text), x = x_label, y = y_label) ggsave(filename = filename_graph) } } } # Progress Bar y_index <- which(y_current == y_values_team) progress(y_index / length(y_values_team) * 100) } setwd(previous_wd_location) } # Generate figures for dependent variables with specified x variables (Individual) ---- generate_figures_ind <- function(Data, num_of_players, figure_titles, y_values_ind, y_labels_ind, x_values_ind, x_labels_ind, plot_types_ind, filelocation){ previous_wd_location <- getwd() # What is the N for Inds N_ind <- num_of_players # The N text to add to title for Inds N_ind_full_text <- paste("(N = ", N_ind, ")", sep = "") for(y_current in y_values_ind){ for (x_current in x_values_ind){ index_for_y <- which(y_current == y_values_ind) index_for_x <- which(x_current == x_values_ind) for(plot in plot_types_ind){ x_label <- x_labels_ind[index_for_x] y_label <- y_labels_ind[index_for_y] figure_title <- figure_titles[index_for_y] filename_graph <- paste("ind_",y_label,"_by_",x_label,"_",plot,".png", sep = "") if(plot == "Group_Bar"){ Data_filtered<- Data %>% mutate(position = rank(-Data[,y_current], ties.method="first")) # print(paste("team_",y_label,"_by_",x_label,"_",plot, sep = "")) ggplot(data = Data_filtered, aes_string(x = x_current, y = y_current, fill = "Player_ID", group = "position")) + geom_bar(stat = "identity", position = "dodge") + labs(title = paste(figure_title, N_ind_full_text) , x = x_label, y = y_label) + guides(fill=FALSE) ggsave(filename = filename_graph) } else if(plot == "Boxplot"){ ggplot(data = Data, aes_string(x = x_current, y = y_current)) + geom_boxplot() + labs(title = paste(figure_title, N_ind_full_text), x = x_label, y = y_label) ggsave(filename = filename_graph) } else if(plot == "Point_plot"){ ggplot(data = Data, aes_string(x = x_current, y = y_current)) + geom_point() + labs(title = paste(figure_title, N_ind_full_text), x = x_label, y = y_label) ggsave(filename = filename_graph) } } } # Progress Bar y_index <- which(y_current == y_values_ind) progress(y_index / length(y_values_ind) * 100) } setwd(previous_wd_location) } # Model the data for the team level anlysis ---- model_data_Target_Session <- function(df, dependent, model.type, is.team, is.robust){ if(is.team){ if(model.type == "null" && !is.robust){ lmer(data = df, as.formula(paste(dependent,"~ 1 + (1|Team)"))) } else if(model.type == "All"){ lmer(data = df, as.formula(paste(dependent,"~ Target * SessionOrder + (1|Team)"))) } else if(model.type == "NoInteraction" && !is.robust){ lmer(data = df, as.formula(paste(dependent,"~ Target + SessionOrder + (1|Team)"))) } else if(model.type == "NoInteraction_NoTarget" && !is.robust){ lmer(data = df, as.formula(paste(dependent,"~ SessionOrder + (1|Team)"))) } else if(model.type == "NoInteraction_NoSession" && !is.robust){ lmer(data = df, as.formula(paste(dependent,"~ Target + (1|Team)"))) } else if(model.type == "null" && is.robust){ rlmer(data = df, as.formula(paste(dependent,"~ 1 + (1|Team)"))) } else if(model.type == "All" && is.robust){ rlmer(data = df, as.formula(paste(dependent,"~ Target * SessionOrder + (1|Team)"))) } else if(model.type == "NoInteraction" && is.robust){ rlmer(data = df, as.formula(paste(dependent,"~ Target + SessionOrder + (1|Team)"))) } else if(model.type == "NoInteraction_NoTarget" && is.robust){ rlmer(data = df, as.formula(paste(dependent,"~ SessionOrder + (1|Team)"))) } else if(model.type == "NoInteraction_NoSession" && is.robust){ rlmer(data = df, as.formula(paste(dependent,"~ Target + (1|Team)"))) } else{ stop("Model.type not supported") } } else { # Run this code if individual level model if(model.type == "null" && !is.robust){ lmer(data = df, as.formula(paste(dependent,"~ 1 + (1|Team) + (1| Player_ID)"))) } else if(model.type == "All" && !is.robust){ lmer(data = df, as.formula(paste(dependent,"~ Target * SessionOrder + (1|Team) + (1| Player_ID)"))) } else if(model.type == "NoInteraction" && !is.robust){ lmer(data = df, as.formula(paste(dependent,"~ Target + SessionOrder + (1|Team) + (1| Player_ID)"))) } else if(model.type == "NoInteraction_NoTarget" && !is.robust){ lmer(data = df, as.formula(paste(dependent,"~ SessionOrder + (1|Team) + (1| Player_ID)"))) } else if(model.type == "NoInteraction_NoSession"){ lmer(data = df, as.formula(paste(dependent,"~ Target + (1|Team) + (1| Player_ID)"))) } else if(model.type == "null" && is.robust){ rlmer(data = df, as.formula(paste(dependent,"~ 1 + (1|Team) + (1| Player_ID)"))) } else if(model.type == "All" && is.robust){ rlmer(data = df, as.formula(paste(dependent,"~ Target * SessionOrder + (1|Team) + (1| Player_ID)"))) } else if(model.type == "NoInteraction" && is.robust){ rlmer(data = df, as.formula(paste(dependent,"~ Target + SessionOrder + (1|Team) + (1| Player_ID)"))) } else if(model.type == "NoInteraction_NoTarget" && is.robust){ rlmer(data = df, as.formula(paste(dependent,"~ SessionOrder + (1|Team) + (1| Player_ID)"))) } else if(model.type == "NoInteraction_NoSession" && is.robust){ rlmer(data = df, as.formula(paste(dependent,"~ Target + (1|Team) + (1| Player_ID)"))) } else{ stop("Model.type not supported") } } } # Multiple plot function ---- # Function found: http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_(ggplot2)/ # # ggplot objects can be passed in ..., or to plotlist (as a list of ggplot objects) # - cols: Number of columns in layout # - layout: A matrix specifying the layout. If present, 'cols' is ignored. # # If the layout is something like matrix(c(1,2,3,3), nrow=2, byrow=TRUE), # then plot 1 will go in the upper left, 2 will go in the upper right, and # 3 will go all the way across the bottom. # multiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) { library(grid) # Make a list from the ... arguments and plotlist plots <- c(list(...), plotlist) numPlots = length(plots) # If layout is NULL, then use 'cols' to determine layout if (is.null(layout)) { # Make the panel # ncol: Number of columns of plots # nrow: Number of rows needed, calculated from # of cols layout <- matrix(seq(1, cols * ceiling(numPlots/cols)), ncol = cols, nrow = ceiling(numPlots/cols)) } if (numPlots==1) { print(plots[[1]]) } else { # Set up the page grid.newpage() pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout)))) # Make each plot, in the correct location for (i in 1:numPlots) { # Get the i,j matrix positions of the regions that contain this subplot matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE)) print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row, layout.pos.col = matchidx$col)) } } } # Test ---- # # The goal of this logic is to retrive values from the overall post survey # overall_post_data<- overall_post_session_table # key_rand_playerID_data<- Rand_num_key # player_Id_value<- "P20" # value_name<- "did_your_ind_perform_change_over_time_why_whyNot" # # rand_num_player<- key_rand_playerID_data %>% # filter(player_Id_value == ID) # # if(length(rand_num_player[["Random_num"]]) == 1){ # player_rand_value<- rand_num_player[1,"Random_num"] # } else{ # message<- paste("Rand key data table has multiple enteries with the same ID:", player_Id_value) # stop(message) # } # # player_data<- overall_post_data%>% # filter(Rand == player_rand_value) # # if(length(player_data[["Rand"]])== 1){ # player_data[[value_name]] # } else{ # message<- paste("The overal post survey has more than one entry that has a Random number value of", player_rand_value) # stop(message) # } # # # overall_post_session_survey_value<- function(overall_post_data, key_rand_playerID_data, player_Id_value, value_name){ # rand_num_player<- key_rand_playerID_data %>% # filter(player_Id_value == ID) # # if(length(rand_num_player[["Random_num"]]) == 1){ # player_rand_value<- rand_num_player[1,"Random_num"] # } else{ # message<- paste("Rand key data table has multiple enteries with the same ID:", player_Id_value) # stop(message) # } # # player_data<- overall_post_data%>% # filter(Rand == player_rand_value) # # if(length(player_data[["Rand"]])== 1){ # return(player_data[[value_name]]) # } else{ # message<- paste("The overal post survey has more than one entry that has a Random number value of", player_rand_value) # stop(message) # } # } # # overall_post_session_survey_value(overall_post_session_table, Rand_num_key, "P20", "did_your_ind_perform_change_over_time_why_whyNot")
739ed41832ae801c46cee3d42b6c0360ef4c1690
3ae034f636da3885d76ed09f03222520d557f8b9
/inst/tinytest/test_Utilities.R
5918a4b143d6f2cac66bd746bb443c80270d2e4c
[]
no_license
vlcvboyer/FITfileR
e32b03762ac55bfb6ac8e38aeb0f7ed6dadf549c
90f52e716022123a02ecd2c44bdb73967d3f467c
refs/heads/master
2023-07-09T05:02:09.914129
2021-08-11T08:11:07
2021-08-11T08:11:07
null
0
0
null
null
null
null
UTF-8
R
false
false
460
r
test_Utilities.R
############################################################ ## convert double representing a uint32 into a raw vector ## ############################################################ ## Should fail with negative or too large values expect_error(FITfileR:::.uintToBits(-1)) expect_error(FITfileR:::.uintToBits(2^32)) expect_true( is(FITfileR:::.uintToBits(10), "raw") ) expect_equal( FITfileR:::.binaryToInt(FITfileR:::.uintToBits(10)), 10 )
a5b54d67017b80a6d2d232c4d6e41bab390f2b7d
426a32c372432dd23462b558aa24c5e100cbbcab
/man/AlleleRetain-package.Rd
7112da0a79ca1045a22e618ff7c2226890f19fef
[]
no_license
cran/AlleleRetain
6e2922aa67a095effbc38e9c9822a8faa4d93e0b
5d47ba944a152f41220c92d4dd525ec95a07e990
refs/heads/master
2021-06-06T14:13:37.494126
2018-01-11T18:29:41
2018-01-11T18:29:41
17,677,695
0
0
null
null
null
null
UTF-8
R
false
false
602
rd
AlleleRetain-package.Rd
\name{AlleleRetain} \alias{AlleleRetain} \title{ Allele Retention, Inbreeding, and Demography } \description{ Simulates the effect of management or demography on allele retention and inbreeding accumulation in bottlenecked populations of animals with overlapping generations. } \details{ Typically, the user will run \code{aRetain}, then \code{aRetain.summary} to assess characteristics of the simulated population. \code{indiv.summary}, \code{pedigree.summary} (requires package \bold{pedigree}), \code{LRS.summary}, and \code{agerepro.summary} will provide further output. }
e51ab8fa20023bded079966ed61355bd9c994fc0
d69bc1641e7e83034660f0408b3e8fd65cfced80
/weighted_jaccard/GAGE_simulation/plot_sim_error_weighted_jaccard.R
de72929229d0000bfc09dc2ee929c6f3074324e7
[]
no_license
cchu70/perfect_mapper
1e9cf48d62bcd79c2b02d903ab48460e59c17d09
eca3850b499c3d62a73be35ca0075db90b870dcf
refs/heads/master
2020-06-17T09:16:32.039692
2019-08-16T15:35:16
2019-08-16T15:35:16
null
0
0
null
null
null
null
UTF-8
R
false
false
1,027
r
plot_sim_error_weighted_jaccard.R
# Rscript to plot the performance of weighted jaccard weighting schemes, table output from Simulated Reads Weighted Jaccard Performance Percentages library(ggplot2) args = commandArgs(trailingOnly=T) out=args[1] # Output name (no type ending) table=args[2] # Weighted Jaccard Performance Percentage output vary_weights=read.table(table, header=T) # Combine the weight schemes vary_weights$weight_scheme = paste(vary_weights$V5,vary_weights$V6) # Plot ggplot(data=vary_weights, aes(x=V1, y=V2, col=weight_scheme)) + geom_point() + ylim(0,1) + xlab("Error rate introduced") + ylab("Retention Rate") + theme_bw() # Subset or change the coloring schemes to view different combinations # Examples # Plot only the performances of weighting schemes where the non-uniqmer weight is 0 # ggplot(data=subset(vary_weights, (V6 == 0)), aes(x=V1, y=V2, col=paste(V3,V4))) + geom_point() + ylim(0,1) + theme_bw() + labs(fill = "Weight 0 for non-uniq-mers") ggsave(file=paste(out,'.plot_sim_error_weighted_jaccard.png', sep=""))
8eff69ad7578600ae7b70c482f59b97e85c615da
0500ba15e741ce1c84bfd397f0f3b43af8cb5ffb
/cran/paws.management/man/licensemanagerusersubscriptions_list_instances.Rd
83fd88300bc7a010acb659c9b15f441e503de5c7
[ "Apache-2.0" ]
permissive
paws-r/paws
196d42a2b9aca0e551a51ea5e6f34daca739591b
a689da2aee079391e100060524f6b973130f4e40
refs/heads/main
2023-08-18T00:33:48.538539
2023-08-09T09:31:24
2023-08-09T09:31:24
154,419,943
293
45
NOASSERTION
2023-09-14T15:31:32
2018-10-24T01:28:47
R
UTF-8
R
false
true
921
rd
licensemanagerusersubscriptions_list_instances.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/licensemanagerusersubscriptions_operations.R \name{licensemanagerusersubscriptions_list_instances} \alias{licensemanagerusersubscriptions_list_instances} \title{Lists the EC2 instances providing user-based subscriptions} \usage{ licensemanagerusersubscriptions_list_instances( Filters = NULL, MaxResults = NULL, NextToken = NULL ) } \arguments{ \item{Filters}{An array of structures that you can use to filter the results to those that match one or more sets of key-value pairs that you specify.} \item{MaxResults}{Maximum number of results to return in a single call.} \item{NextToken}{Token for the next set of results.} } \description{ Lists the EC2 instances providing user-based subscriptions. See \url{https://www.paws-r-sdk.com/docs/licensemanagerusersubscriptions_list_instances/} for full documentation. } \keyword{internal}
2d53c36519a1e9b370f285960183ab6757180328
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/spatstat/examples/closing.Rd.R
5a8fc11a11ac1b19a9ec3fb5482bd6b9b1b52d22
[]
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
304
r
closing.Rd.R
library(spatstat) ### Name: closing ### Title: Morphological Closing ### Aliases: closing closing.owin closing.ppp closing.psp ### Keywords: spatial math ### ** Examples v <- closing(letterR, 0.25) plot(v, main="closing") plot(letterR, add=TRUE) plot(closing(cells, 0.1)) points(cells)
8f1bdb02e7c21fd7a024fd55d91dc5248f8b3b3b
2d58f4d5eae4139a72ab36c255238536486b4ff7
/GameGP/R/Classification.R
d8ac8ff5f64e1b55957dd790b6a3c28c0eee5d33
[]
no_license
ahle-pro/datamining
39758cc665e7fc359d6d404ad1340f0300902e37
ba8e149dfd5b9d8eb65c0055ecae256d06250b69
refs/heads/master
2021-08-31T07:08:20.252750
2017-12-20T16:02:53
2017-12-20T16:02:53
114,905,772
0
0
null
null
null
null
UTF-8
R
false
false
1,504
r
Classification.R
library("readr", lib.loc="~/R/win-library/3.3") library("data.table") library(dplyr) setwd("D:/projects/Data Mining") dataSrc <- readRDS("data/dataStat.rds") pdf("report/program_classif.pdf") getPrograms_X<-function(df){ # create a table table = data.table(df)# table1: table with less columns from source data table <- table[,.(.N), by=Programid] # do on all row, produce the count, and group by the first columns #tUserFreq <- tUserFreq[order(N)]# table2: data groupeby users plot(tbPrograms, main="No. of exercises on each program dist.",sub="N = 5.8M obs., db = GamePro", xlab="Programid", ylab="No. of exercises") return(table) } tbPrograms = getPrograms_X(dataSrc) tabular1<-function(table){ # declare variables ret <- data.frame("Name"=character(), "Value" = character(), stringsAsFactors = FALSE) # count No. of the programs ret[nrow(ret)+1,] <- c("No. of programs", nrow(table)) #sort table = table[order(-N)] # output plot.new() grid.draw(grid.table(ret)) #output tb_head = head(table) colnames(tb_head)[2] <- "No. of exercises" plot.new() grid.draw(grid.table(tb_head)) } tabular1(tbPrograms) dev.off() build_save_data <- function(){ dataP4 = dataSrc[dataSrc$Programid == 4, ] saveRDS(dataP4, "data/dataP4.rds") dataP13 = dataSrc[dataSrc$Programid == 13, ] saveRDS(dataP13, "data/dataP13.rds") dataP14 = dataSrc[dataSrc$Programid == 14, ] saveRDS(dataP14, "data/dataP14.rds") } #build_save_data()
c807701c283d3e0565cda0d1e7e6928a10fc9861
6666615e41404182c1b0421c49c80e0fe223ab78
/1_master.R
a3805bb47d4784da96187b62f2e71ee480fb5b39
[]
no_license
PerinatalLab/PubMed_AbstractMinining_for_Genes
d8891a5dd56f3696baf48d801ee561b3640cb21d
c736a0084ba1f451baf0035e59e853e69cc17a64
refs/heads/master
2016-09-05T12:56:57.670311
2015-07-12T22:26:29
2015-07-12T22:26:29
37,733,156
0
0
null
null
null
null
UTF-8
R
false
false
843
r
1_master.R
#!/usr/bin/Rscript # passes arguments to the bash script that takes care of PubMed abstracts setwd("~/Biostuff/MOBA_GESTAGE_GWAS/PREGNANCY_GENES/PubMed_2015Jun_GYNECOLOGY") bash_script = "./1_extract_Abstracts_from_PubMed_output.sh" # abstracts that are downloaded from PubMed file_list1 = list.files("./PubMed_RAW/") file_list = file_list1[grep("SKIN|INTEST|MUSCL|HEART|LIVER|LUNG",file_list1)] # naming convention: PubMed_webSearch_RAW_CERVIX_GENES_2014Jun17_n1362.txt for (i in 1:length(file_list)) { file_name = file_list[i] print(file_name) name_chunks = unlist(strsplit(file_name,"_")) name_chunks[3] = "DIGESTED" name_chunks[7] = unlist(strsplit(name_chunks[7],"\\."))[1] # get rid of .txt new_name = paste(name_chunks,sep="_",collapse="_") cmnd = paste(bash_script,file_name,new_name,sep=" ") system(cmnd,ignore.stdout = F) }
20c7ce76c73bf1c2855450cbca1094249bd98597
c91350b98d6c2d6c067cd796742795847c6fd631
/vignettes/man/spectrum.id-set-PsmDetail-method.Rd
c55fe314cf9effe17c75925b17c767421c2c489c
[]
no_license
gccong/ddiR-sirius
127673f8fca158449e50dafc462ec78c234a5d55
6b1792d06e6ff094349e89b5cbee7144763b932d
refs/heads/master
2021-01-19T04:18:49.242352
2015-12-13T22:29:01
2015-12-13T22:29:01
62,987,187
0
0
null
null
null
null
UTF-8
R
false
false
429
rd
spectrum.id-set-PsmDetail-method.Rd
% Generated by roxygen2 (4.1.0): do not edit by hand % Please edit documentation in R/psm.R \docType{methods} \name{spectrum.id<-,PsmDetail-method} \alias{spectrum.id<-,PsmDetail-method} \title{Replaces a PSM spectrum.id} \usage{ \S4method{spectrum.id}{PsmDetail}(object) <- value } \arguments{ \item{object}{a ProteinDetail} \item{value}{the spectrum.id} } \description{ Replaces a PSM spectrum.id } \author{ Jose A. Dianes }
6a51a74fa77a7e568d038b42f6911cdc86dc3606
b6fd15efff8945a1f0b8501f422cbe6d9f4c23e9
/Anul III/Sem 2/Tehnici de Simulare/Proiect/cod.R
e2ce02209df7af216865608d06e7a3601cce5e09
[]
no_license
andreim9816/Facultate
729a14fb60755e36fca01355162253f088fabf3e
8eae7f73fd8ab5fd11de3f1fa744a1837abd49e0
refs/heads/master
2023-03-06T09:59:53.477012
2022-03-11T22:47:17
2022-03-11T22:47:17
175,485,457
0
0
null
null
null
null
UTF-8
R
false
false
20,051
r
cod.R
library(shiny) library(shinythemes) # Functie corespunzatoare intensitatii procesului Poisson LAMBDA <- function(t) { if (0 <= t & t < 3 * 60) { c <- -t ** 2 - 2 * t + 25 } else if (3 * 60 <= t & t <= 5 * 60) { c <- 14 } else if (5 * 60 < t & t < 9 * 60) { c <- -0.05 * (t ** 2) - 0.2 * t + 12 } else { c <- 11 } return (c) } # Functie ce simuleaza momentul primei sosiri a unui client dupa momentul de timp s # corespunzatoare unui proces Poisson neomogen cu functia de intensitate lambda si # maximul ei mLambda GET_TS <- function(s, lambda, mLambda) { ts <- t <- s while (TRUE) { # Simuleaza 2 valori uniforme in intervalul [0,1] U1 <- runif(1) U2 <- runif(1) # Noul moment de timp t t <- t - 1 / mLambda * log(U1) # Daca valoarea aleatoare uniforma este mai mica decat raportul dintre functia de intensitate # in momentul respectiv si valoarea maxima a functiei intensitate, atunci ne oprim if (U2 <= lambda(t) / mLambda) { ts <- t break } } ts } # Functie care simuleaza o variabila aleatoare exponentiala de parametru lambda folosind metoda inversa SIMULATE_EXP <- function(lambda) { # Genereaza o variabila aleatoare uniforma pe intervalul [0,1] u <- runif(1) # Construieste variabila exponentiala de parametru lambda x <- -1 / lambda * log(u) return (x) } # Functie care simuleaza o variabila aleatoare Poisson de parametru lambda = 6 # prin metoda inversa. GET_Y1 <- function(lambda = 6) { # Se foloseste de relatia de recurenta p_j+1 = p_j * lambda / (j + 1) # Contor i <- 0 # Probabilitatea curenta p <- exp(1) ^ (-lambda) # Valoarea functiei de repartitie in punctul curent F <- p u <- runif(1, 0, 1) while (u >= F) { # Updatam noile valori ale probabilitatilor si functiei de repartitie p <- p * lambda / (i + 1) F <- F + p i <- i + 1 } return (i) } # Functie care simuleaza o variabila aleatoare data prin densitatea de probabilitate # folosind metoda respingeri GET_Y2 <- function(x) { # Am ales g(y) = e^x, x > 0 # Am calculat maximul functiei h(x) = f(x)/g(x),iar acesta este c = 32 c <- 32 while (T) { # Simuleaza o variabila aleatoare exponentiala de parametru lambda = 1 y <- SIMULATE_EXP(1) # Simuleaza o variabila aleatoare uniforma cu valori in [0,1] u <- runif(1) if (u <= 2 / (61 * c) * y * exp(y - y ^ 2 / 61)) { return(y) } } } # Functia care simuleaza intregul sistem # t_max -> timpul (exprimat in minute) in care functioneaza centrul de vaccinare # lambda -> functia de intensitate a procesului poisson neomogen care simuleaza venirea clientilor # c_max -> lungimea maxima a cozii de asteptare pentru care un client pleaca RUN_SIMULATION <- function(t_max = 720, lambda = LAMBDA, c_max = 20) { # Vectorii de output # Momentul de timp in care un client ajunge in sistem A1 <- c() # Momentul de timp in care un client ajunge la serverul 2 A2 <- c() # momentul de timp in care un client paraseste sistemul D <- c() # timpul maxim de asteptare dupa care un pacient pleaca timp_asteptare_max <- 60 # valoarea maxima a functiei de intensitate max_value <- 26 # numarul de doze dintr-o zi nr_doze <- 100 # Generam primul moment la care ajunge un client ta <- GET_TS(0, lambda, max_value) # Variabile contor ce retin date despre starea sistemului t <- na <- nd <- n1 <- n2 <- 0 t1 <- t2 <- Inf # Variabile indecsi pt fiecare vector ce marcheaza primul pacient care e in asteptare pentru coada de la primul server, respectiv al 2-lea server indexA1 <- 1 indexA2 <- 0 # Numarul de pacienti care au ajuns la fiecare server, in total k1 <- 0 k2 <- 0 # Numarul de clienti pierduti la coada la fiecare server serv_1_pierdut <- 0 serv_2_pierdut <- 0 # Cat timp functioneaza centrul de vaccinare (si mai sunt doze destule) while (t < t_max && nr_doze > 0) { #Soseste un client nou if (ta == min(ta, t1, t2)) { t <- ta if (ta < t_max) { k1 <- k1 + 1 #A venit un client nou, adaugam in vectorii de output A1 <- append(A1, t) A2 <- append(A2, 0) D <- append(D, 0) #Punem in coada na <- na + 1 n1 <- n1 + 1 # Generam urmatorul timp la care vine un client ta <- GET_TS(t, lambda, max_value) #Daca e singurul client genereaza t1 (momentul de timp la care clientul de la serverul 1 termina cu acesta) if (n1 == 1) { t1 <- t + GET_Y1() } # Daca lungimea cozii e prea mare, clientul pleaca. Marcam in vectorii de output cu valori negative if(n1 > c_max) { n1 <- n1 - 1 A1[na] <- -t A2[na] <- -t D[na] <- -t serv_1_pierdut <- serv_1_pierdut + 1 } } } else if (t1 < ta && t1 <= t2) { # Daca clientul de la serverul 1 termina primul # Verificam daca primul pacient de la coada asteapta de prea mult timp t <- t1 if (indexA1 <= k1 && ((t - A1[indexA1]) > timp_asteptare_max)) { # Actualizam vectorii de output pentru pacientii care au asteptat prea mult si au plecat. # Marcam cu -t in vectorii A2 si D pentru a sti momentul in care un pacient a plecat A2[indexA1] <- -t D[indexA1] <- -t indexA1 <- indexA1 + 1 n1 <- n1 - 1 if (n1 == 0) { t1 <- Inf } } else { k2 <- k2 + 1 # Terminam de procesat un client pana ajunge altul in serverul 1 # Scade numarul de clienti ramasi in coada n1 <- n1 - 1 # Creste in serv2 n2 <- n2 + 1 # Adaugam timpul la care ajunge clientul la al II-lea server A2[indexA1] <- t indexA1 <- indexA1 + 1 if (n1 == 0) { # Daca serverul ramane gol reinitializeaza t1 <- Inf } else { # Altfel, pentru urmatorul client din coada, genereaza timpul pentru taskul lui t1 <- t + GET_Y1() } if (n2 == 1) { # Daca clientul terminat de serverul 1 e singurul in serverul 2 genereaza timpul pentru taskul lui t2 <- t + GET_Y2() } else if(n2 > c_max) { # Daca sunt prea multi clienti la coada, clientul pleaca A2[indexA1] <- -t D[indexA1] <- -t n2 <- n2 - 1 serv_2_pierdut <- serv_2_pierdut + 1 } } } else if (t2 < ta && t2 < t1) { # Serverul 2 termina de procesat client inainte sa primim persoane noi sau sa terminam pe cineva in s1 t <- t2 nd <- nd + 1 # Scadem numarul de doze ramase nr_doze <- nr_doze - 1 # Scade numarul de clienti din coada n2 <- n2 - 1 indexA2 <- indexA2 + 1 if (n2 == 0) { t2 <- Inf } #adaugam timpul la care pleaca persoana din centrul de vaccinare D[nd] <- t if (n2 >= 1 && n2 <= c_max) { #daca mai avem persoane de procesat, genereaza timpul pentru taskul lor t2 <- t + GET_Y2() } else if(n2 >= 1 && n2 > c_max) { # coada este prea mare, pleaca clientul D[indexA2] <- -t n2 <- n2 - 1 serv_2_pierdut <- serv_2_pierdut + 1 } } } res <- data.frame(A1, A2, D, nr_doze, n1, n2) return(res) } result <- RUN_SIMULATION() print("~~~~~~~~~~~~") print(result) print("________") print(result$A1) print("____________") print(result$A2) print("________________") print(result$D) # Functie corespunzatoare intensitatii procesului Poisson, in momentul in care # programul incepe cu o ora mai devreme LAMBDA_INCEPUT <- function(t) { if (0 <= t & t < 4 * 60) { c <- -t ** 2 - 2 * t + 25 } else if (4 * 60 <= t & t <= 6 * 60) { c <- 14 } else if (6 * 60 < t & t < 10 * 60) { c <- -0.05 * (t ** 2) - 0.2 * t + 12 } else { c <- 11 } return (c) } # Define UI ui <- fluidPage(theme = shinytheme("cerulean"), navbarPage( "Simulare vaccinare Covid-19", tabPanel("Pagina pricipala", # Cerinta 1 mainPanel( h2("Determinarea timpului minim, maxim si mediu petrecut de o persoana ce asteapta sa se vaccineze\n"), br(), column(10, tableOutput("table1")) ), br(), # Cerinta 2 mainPanel( h2("Determinarea numarului mediu de persoane vaccinate intr-un interval de timp"), br(), sidebarLayout( # Sidebar with a slider input sidebarPanel(sliderInput("oraSt", "Ora inceput:", min = 8, max = 20, value = 8), sliderInput("oraEnd", "Ora sfarsit:", min = 8, max = 20, value = 20), sliderInput("nrSim2", "Numar simulari:", min = 5, max = 20, value = 10) ), # Show a plot of the generated distribution mainPanel( plotOutput("plotClientiTotal") ) ), h3(textOutput("medie2")) ), # Suplimentar nr doze br(), mainPanel( h2("Numarul de doze de vaccin"), h3(textOutput("persNevaccinate")), plotOutput("plotNrDozePierdute"), h3(textOutput("medieDoze")) ), # Cerinta 3 mainPanel( h2("Determinarea primului moment de timp la care pleaca o persoana"), h4("Studiul a fost realizat pe 10 simulari"), column(8, tableOutput("tablePlecare")) ), # Cerinta 4 mainPanel( h2("Determinarea numarului mediu de persoane care au plecat datorita timpului de asteptare"), h4("Studiul a fost realizat pe 10 simulari"), column(10, tableOutput("tablePlecareMediu")) ), # Cerinta 5 mainPanel( h2("Determinarea numarului de doze suplimentare administrate"), br(), sidebarLayout( # Sidebar with a slider input sidebarPanel(sliderInput("nrSim5", "Numar simulari:", min = 10, max = 50, #todo: dim minima trebuie sa fie maximul curent value = 20), radioButtons(inputId="choice", label="Ce se modifica?", choices=c("Se incepe programul mai devreme cu o ora" = 1, "Se prelungeste programul cu o ora" = 2, "Se mareste dimensiunea maxima a cozii de asteptare" = 3)), sliderInput("dimCoada", "Dimensiune maxima a cozii de asteptare:", min = 20, max = 100, #todo: dim minima trebuie sa fie maximul curent value = 20)), # Show a plot of the generated distribution mainPanel( plotOutput("plotCastig") ) ), h3(textOutput("medie5")) ) ) ) # navbarPage ) # fluidPage TIMP_IN_SISTEM <- function(ta, td) { # Cerinta 1: determinarea timpilor maximi, minimi si medii de asteptare pentru fiecare server tmax <- 0 tmin <- Inf tmed <- 0 num <- 0 for(i in 1:length(ta)) { if(td[i] > 0 && ta[i] > 0) { # nu luam in calcul persoanele care au plecat inainte sa ajunga la servere tmed <- tmed + (td[i] - ta[i]) num <- num + 1 } if(td[i] > 0 && ta[i] > 0 && td[i] - ta[i] > tmax) tmax <- td[i] - ta[i] else if(td[i] > 0 && ta[i] > 0 && td[i] - ta[i] < tmin) tmin <- td[i] - ta[i] } tmed <- tmed / num # print("TIMPI ASTEPTARE") # print(tmax) # print(tmin) # print(tmed) res <- c(tmax, tmin, tmed) return(res) } # Define server function server <- function(input, output) { # Cerinta 1 res1 <- RUN_SIMULATION() server <- c("Completare fisa", "Vaccinare") # Pentru primul server, timpul de asteptare este momentul cand intra in asteptare la serverul 2 - cand intra in sistem s1 <- TIMP_IN_SISTEM(res1$A1, res1$A2) # Pentru al doilea server, timpul de asteptare este momentul cand iese din sistem(D) - cand intra in al doilea server s2 <- TIMP_IN_SISTEM(res1$A2, res1$D) timp_maxim <- c(paste0(toString(round(s1[1],2)), " min"), paste0(toString(round(s2[1],2)), " min")) timp_minim <- c(paste0(toString(round(s1[2],2)), " min"), paste0(toString(round(s2[2],2)), " min")) timp_mediu <- c(paste0(toString(round(s1[3],2)), " min"), paste0(toString(round(s2[3],2)), " min")) print("in cerinta 1") print(server) print(timp_maxim) print(timp_minim) print(timp_mediu) df1 <- data.frame("Server"=server, "Timp minim"=timp_minim, "Timp maxim"=timp_maxim, "Timp mediu"=timp_mediu) # Cerinta 1 output$table1 <- renderTable({df1}) # Cerinta 2 output$plotClientiTotal <- renderPlot({ oraSt <- input$oraSt oraEnd <- input$oraEnd nrSim <- input$nrSim2 x <- c() y <- c() med <- 0 if(oraSt <= oraEnd) { for(i in 1 : nrSim) { res <- RUN_SIMULATION() nrPers <- 0 for(j in 1 : length(res$D)) { if(((oraSt - 8) * 60) < res$D[j] && res$D[j] <= ((oraEnd - oraSt) * 60)) # nr persoane vaccinate intr-un interval de timp nrPers <- nrPers + 1 } x <- append(x, i) y <- append(y, nrPers) med <- med + nrPers } med <- med / nrSim plot(x, y, col = "green",main="Persoane care se vaccineaza", xlab="Indexul simularii", ylab="Numarul persoane", pch = 19) abline(h=med, col="magenta") legend("topright", legend=c("Numar persoane vaccinate", "Media nr de persoane vaccinate"), col=c("green", "magenta"), lty=c(NA, 1), pch=c(19, NA)) output$medie2 <- renderText({paste0("Numarul mediu de persoane vaccinate este de ", toString(round(med, 2)),".")}) } }) # Cerinta 3 idx <- c(1:10) # realizam pe 10 simulari timp_plecare <- c() for(i in 1:10) { res <- RUN_SIMULATION() t <- Inf for(j in 1 : length(res$A2)) if(res$A1[j] < 0 || res$A2[j] < 0 || res$D[j] < 0) { # a plecat de la una din cele 2 cozi sau nu avea loc la coada t <- abs(res$A1[j]) break } timp_plecare <- append(timp_plecare, paste0(toString(round(t, 2)), " min")) } df2 <- data.frame(idx, timp_plecare) # Cerinta 3 output$tablePlecare <- renderTable({df2}) # Suplimentar output$persNevaccinate <- renderText({ res <- RUN_SIMULATION() nevaccinati <- 0 if(res$nr_doze == 0) { nevaccinati <- res$n1[1] + res$n2[1] } paste0("Dintr-un total de 100 de doze, numarul persoanelor ramase nevaccinate din cauza numarului insuficient de doze este ", toString(nevaccinati), ".")}) output$plotNrDozePierdute <- renderPlot({ x <- c(1:10) y <- c() med <- 0 for(i in 1:10) { res <- RUN_SIMULATION() y <- append(y, res$nr_doze[1]) med <- med + res$nr_doze[1] } med <- med / 10 plot(x, y, main="Numar de doze pierdute", xlab="Indexul simularii", ylab="Nr doze pierdute", pch = 19, col="green") abline(h=med, col="magenta") legend("topright", legend=c("Nr doze pierdute", "Medie nr doze pierdute"), col=c("green", "magenta"), lty=c(NA, 1), pch=c(19, NA)) output$medieDoze <- renderText({paste0("Numarul mediu de doze pierdute este de ", toString(round(med, 2)),".")}) }) # Cerinta 4 server_1 <- 0 for(i in 1 : 10) { res <- RUN_SIMULATION() nr <- 0 for(j in 1 : length(res$A1)) { if(res$A1[j] > 0 && res$A2[j] < 0 && res$D[j] < 0) nr <- nr + 1 } server_1 <- server_1 + nr } server_1 <- server_1 / 10 server_2 <- 0 df3 <- data.frame(server_1, server_2) # Cerinta 4 output$tablePlecareMediu <- renderTable({df3}) # Cerinta 5 output$plotCastig <- renderPlot({ nrSim <- input$nrSim5 dimCoada <- input$dimCoada ch <- input$choice x <- c() y <- c() med <- 0 if(ch == 1) { for(i in 1 : nrSim) { res <- RUN_SIMULATION(13 * 60, LAMBDA_INCEPUT) x <- append(x, i) supl <- 0 for(j in 1:length(res$D)) { if(res$D[j] > 0 && res$D[j] < 60) #s-au vaccinat in prima ora supl <- supl + 1 } y <- append(y, supl) med <- med + supl } med <- med / nrSim } else if(ch == 2) { for(i in 1 : nrSim) { res <- RUN_SIMULATION(13 * 60) x <- append(x, i) supl <- 0 for(j in 1:length(res$D)) { if(res$D[j] > 0 && res$D[j] <= 780 && res$D[j] >= 720) #s-au vaccinat in ultima ora supl <- supl + 1 } y <- append(y, supl) med <- med + supl } med <- med / nrSim } else if(ch == 3) { for(i in 1 : nrSim) { res1 <- RUN_SIMULATION(c_max=dimCoada) res2 <- RUN_SIMULATION() nr_doze_res1 <- length(res1$D[res1$D > 0]) nr_doze_res2 <- length(res2$D[res2$D > 0]) x <- append(x, i) supl <- 0 if(nr_doze_res1 > nr_doze_res2) supl <- nr_doze_res1 - nr_doze_res2 y <- append(y, supl) med <- med + supl } med <- med / nrSim } plot(x, y, col = "green",main="Numarul suplimentar de doze administrate obtinute pentru fiecare simulare", xlab="Indexul simularii", ylab="Numarul suplimentar de doze", pch = 19) abline(h=med, col="magenta") legend("topright", legend=c("Numar suplimentar de doze", "Media nr suplimentar de doze"), col=c("green", "magenta"), lty=c(NA, 1), pch=c(19, NA)) output$medie5 <- renderText({paste0("Numarul de doze administrate suplimentar este de ", toString(round(med, 2)),".")}) }) } # Creeaza serverul Shiny App shinyApp(ui = ui, server = server)
813205c69f8b5c500632368fe99032f2dbe806a1
29585dff702209dd446c0ab52ceea046c58e384e
/OligoSpecificitySystem/R/security.r
f2640c2cc323920a4a04cdb8670524dae506d455
[]
no_license
ingted/R-Examples
825440ce468ce608c4d73e2af4c0a0213b81c0fe
d0917dbaf698cb8bc0789db0c3ab07453016eab9
refs/heads/master
2020-04-14T12:29:22.336088
2016-07-21T14:01:14
2016-07-21T14:01:14
null
0
0
null
null
null
null
UTF-8
R
false
false
632
r
security.r
"security"<-function(){ if (length(txt4)==1 & length(txt1)==1 & length(txt2)==1) tkmessageBox(message="Error. Please, load before at least 2 databases") if (length(txt4)==1 & length(txt1)==1 & length(txt2)==1) stop() if (length(txt4)==1 & length(txt1)==1 & length(txt3)==1) tkmessageBox(message="Error. Please, load before at least 2 databases") if (length(txt4)==1 & length(txt1)==1 & length(txt3)==1) stop() if (length(txt4)==1 & length(txt3)==1 & length(txt2)==1) tkmessageBox(message="Error. Please, load before at least 2 databases") if (length(txt4)==1 & length(txt3)==1 & length(txt2)==1) stop() }
dc31ebf5deb5a55ee42e0c536c3613982ed2fad5
5c90adf11c63ef8a8f05e310d72d61edcb8f31d3
/avg_duration.R
e6c8a048789d2944dade5a312789f2491de53051
[]
no_license
JohnnyFilip/Average_game_duration
fecb098d1583061194548c4fdaa35d372ac56225
7bb32ea2a116d700a74afed6761dd6b17932f8b0
refs/heads/master
2021-01-17T23:22:32.781817
2017-03-29T05:53:23
2017-03-29T05:53:23
84,218,892
0
0
null
2017-03-07T16:29:32
2017-03-07T16:02:28
null
UTF-8
R
false
false
7,576
r
avg_duration.R
library(jsonlite) library(plotly) library(magrittr) library(plyr) library(tidyr) # AVerage game duration by patch avg1 <- fromJSON("https://api.opendota.com/api/explorer?sql=SELECT%0Apatch%20%2C%0Around(sum(duration)%3A%3Anumeric%2Fcount(1)%2C%202)%20avg%2C%0Acount(distinct%20matches.match_id)%20count%2C%0Asum(case%20when%20(player_matches.player_slot%20%3C%20128)%20%3D%20radiant_win%20then%201%20else%200%20end)%3A%3Afloat%2Fcount(1)%20winrate%2C%0Asum(duration)%20sum%2C%0Amin(duration)%20min%2C%0Amax(duration)%20max%2C%0Around(stddev(duration)%2C%202)%20stddev%0AFROM%20matches%0AJOIN%20match_patch%0AUSING%20(match_id)%0AJOIN%20leagues%0AUSING(leagueid)%0AJOIN%20player_matches%0AUSING(match_id)%0ALEFT%20JOIN%20notable_players%0AUSING(account_id)%0ALEFT%20JOIN%20teams%0AUSING(team_id)%0AJOIN%20heroes%0AON%20player_matches.hero_id%20%3D%20heroes.id%0AWHERE%20TRUE%0AAND%20duration%20IS%20NOT%20NULL%0AGROUP%20BY%20patch%0AHAVING%20count(distinct%20matches.match_id)%20%3E%200%0AORDER%20BY%20avg%20DESC%2Ccount%20DESC%20NULLS%20LAST%0ALIMIT%20150") avg1a <- avg1$rows %>% arrange(desc(patch)) print(avg1a[avg1a$patch > 7.00,]) avg_patch <- mean(as.numeric(avg1a[avg1a$patch > 7.00,]$avg))/60 print(avg_patch) p_avg_patch <- plot_ly( avg1a, x = avg1a$patch, y = as.numeric(avg1a$avg)/60, name = 'Avg_game_duration', type = 'bar', marker = list( color = 'rgb(158,202,225)', line = list(color = 'rgb(8,48,107)', width = 1.5) ) ) %>% layout(yaxis = list(range = c(32,44), title = 'Average_game_duration'), xaxis = list(title = 'Patch')) # Average game duration by league avg2 <- fromJSON("https://api.opendota.com/api/explorer?sql=SELECT%0Aleagues.name%20leaguename%2C%0Around(sum(duration)%3A%3Anumeric%2Fcount(1)%2C%202)%20avg%2C%0Acount(distinct%20matches.match_id)%20count%0AFROM%20matches%0AJOIN%20match_patch%0AUSING%20(match_id)%0AJOIN%20leagues%0AUSING(leagueid)%0AJOIN%20player_matches%0AUSING(match_id)%0ALEFT%20JOIN%20notable_players%0AUSING(account_id)%0ALEFT%20JOIN%20teams%0AUSING(team_id)%0AJOIN%20heroes%0AON%20player_matches.hero_id%20%3D%20heroes.id%0AWHERE%20TRUE%0AAND%20duration%20IS%20NOT%20NULL%0AAND%20match_patch.patch%20%3D%20%277.00%27%20OR%20match_patch.patch%20%3D%20%277.01%27%20OR%20match_patch.patch%20%3D%20%277.02%27%0AGROUP%20BY%20leagues.name%0AHAVING%20count(distinct%20matches.match_id)%20%3E%200%0AORDER%20BY%20avg%20DESC%2Ccount%20DESC%20NULLS%20LAST%0ALIMIT%20150") avg2a <- avg2$rows %>% arrange(desc(avg)) avg2a$average <- as.numeric(avg2a$avg)/60 avg_league <- avg2a[avg2a$count >= 26,] %>% subset(select = -avg) print(avg_league) # AVerage game duration by team avg3 <- fromJSON("https://api.opendota.com/api/explorer?sql=SELECT%0Ateams.name%20%2C%0Around(sum(duration)%3A%3Anumeric%2Fcount(1)%2C%202)%20avg%2C%0Acount(distinct%20matches.match_id)%20count%2C%0Asum(case%20when%20(player_matches.player_slot%20%3C%20128)%20%3D%20radiant_win%20then%201%20else%200%20end)%3A%3Afloat%2Fcount(1)%20winrate%0AFROM%20matches%0AJOIN%20match_patch%0AUSING%20(match_id)%0AJOIN%20leagues%0AUSING(leagueid)%0AJOIN%20player_matches%0AUSING(match_id)%0ALEFT%20JOIN%20notable_players%0AUSING(account_id)%0ALEFT%20JOIN%20teams%0AUSING(team_id)%0AJOIN%20heroes%0AON%20player_matches.hero_id%20%3D%20heroes.id%0AWHERE%20TRUE%0AAND%20duration%20IS%20NOT%20NULL%0AAND%20match_patch.patch%20%3D%20%277.00%27%20OR%20match_patch.patch%20%3D%20%277.01%27%20OR%20match_patch.patch%20%3D%20%277.02%27%0AGROUP%20BY%20teams.name%0AHAVING%20count(distinct%20matches.match_id)%20%3E%200%0AORDER%20BY%20avg%20DESC%2Ccount%20DESC%20NULLS%20LAST%0ALIMIT%20150") avg3a <- avg3$rows %>% arrange(desc(avg)) %>% drop_na(name) avg3a$average <- as.numeric(avg3a$avg)/60 avg_team <- avg3a[avg3a$count >= 10,] %>% subset(select = -avg) print(avg_team) # Average game duration head to head team_list <- fromJSON('https://api.opendota.com/api/teams') avg_h2h <- function(team1_id, team2_id){ team1_id <- 111474 team2_id <- 1838315 teams <- 'https://api.opendota.com/api/explorer?sql=select%20match_id%2C%20start_time%2C%20duration%0Afrom%20matches%0AWHERE%20(radiant_team_id%3Dlight%20AND%20dire_team_id%3Ddark)%0AOR%20(radiant_team_id%3Ddark%20AND%20dire_team_id%3Dlight)%0A' teams_new <- gsub('light', team1_id, gsub('dark', team2_id, teams)) avg4 <- fromJSON(teams_new) avg4a <- avg4$rows[avg4$rows$start_time > 1481583600,] avg <- mean(avg4a$duration)/60 return(list(nrow(avg4a), avg)) } # AVerage game duration Kiev average_kiev <- function() { avg5 <- fromJSON( "https://api.opendota.com/api/explorer?sql=SELECT%0Ateams.name%20%2C%0Around(sum(duration)%3A%3Anumeric%2Fcount(1)%2C%202)%20avg%2C%0Acount(distinct%20matches.match_id)%20count%2C%0Asum(case%20when%20(player_matches.player_slot%20%3C%20128)%20%3D%20radiant_win%20then%201%20else%200%20end)%3A%3Afloat%2Fcount(1)%20winrate%2C%0Asum(duration)%20sum%2C%0Amin(duration)%20min%2C%0Amax(duration)%20max%2C%0Around(stddev(duration)%2C%202)%20stddev%0AFROM%20matches%0AJOIN%20match_patch%0AUSING%20(match_id)%0AJOIN%20leagues%0AUSING(leagueid)%0AJOIN%20player_matches%0AUSING(match_id)%0ALEFT%20JOIN%20notable_players%0AUSING(account_id)%0ALEFT%20JOIN%20teams%0AUSING(team_id)%0AJOIN%20heroes%0AON%20player_matches.hero_id%20%3D%20heroes.id%0AWHERE%20TRUE%0AAND%20duration%20IS%20NOT%20NULL%0AAND%20matches.leagueid%20%3D%205157%0AGROUP%20BY%20teams.name%0AHAVING%20count(distinct%20matches.match_id)%20%3E%200%0AORDER%20BY%20avg%20DESC%2Ccount%20DESC%20NULLS%20LAST%0ALIMIT%20150" ) avg5a <- avg5$rows %>% drop_na(name) avg5a$avg <- as.numeric(avg5a$avg) / 60 teams_kiev <- select(avg5a, c(name, count, avg)) avg_kiev <- mean(as.numeric(avg5a$avg)) list(teams_kiev, sum(teams_kiev$count), avg_kiev) } # AVerage game duration DAC - main tournament average_dac <- function() { avg6 <- fromJSON( "https://api.opendota.com/api/explorer?sql=SELECT%0Ateams.name%20%2C%0Around(sum(duration)%3A%3Anumeric%2Fcount(1)%2C%202)%20avg%2C%0Acount(distinct%20matches.match_id)%20count%2C%0Asum(case%20when%20(player_matches.player_slot%20%3C%20128)%20%3D%20radiant_win%20then%201%20else%200%20end)%3A%3Afloat%2Fcount(1)%20winrate%2C%0Asum(duration)%20sum%2C%0Amin(duration)%20min%2C%0Amax(duration)%20max%2C%0Around(stddev(duration)%2C%202)%20stddev%0AFROM%20matches%0AJOIN%20match_patch%0AUSING%20(match_id)%0AJOIN%20leagues%0AUSING(leagueid)%0AJOIN%20player_matches%0AUSING(match_id)%0ALEFT%20JOIN%20notable_players%0AUSING(account_id)%0ALEFT%20JOIN%20teams%0AUSING(team_id)%0AJOIN%20heroes%0AON%20player_matches.hero_id%20%3D%20heroes.id%0AWHERE%20TRUE%0AAND%20duration%20IS%20NOT%20NULL%0AAND%20matches.leagueid%20%3D%205197%0AAND%20matches.start_time%20%3E%3D%201490565600%0AGROUP%20BY%20teams.name%0AHAVING%20count(distinct%20matches.match_id)%20%3E%200%0AORDER%20BY%20avg%20DESC%2Ccount%20DESC%20NULLS%20LAST%0ALIMIT%20150" ) avg6a <- avg6$rows %>% drop_na(name) avg6a$avg <- as.numeric(avg6a$avg) / 60 teams_dac <- select(avg6a, c(name, count, avg)) avg_dac <- mean(as.numeric(avg6a$avg)) list(teams_dac, sum(teams_dac$count), avg_dac) } write.csv(avg1a, file = 'D:\\RTS\\Scripts\\avg_patch.csv') write.table(avg_league, file = 'D:\\RTS\\Scripts\\avg_league.csv', sep = ' ', row.names = FALSE) write.table(avg_match, file = 'D:\\RTS\\Scripts\\avg_match.csv', sep = ' ', row.names = FALSE) write.csv(team_list, file = 'D:\\RTS\\Scripts\\team_list.csv')
2b1fc92f180f128e588a237ea11f659b01a53a61
9096176d4a3a6305e08250fa1a7c9b5c2930f20f
/scripts/usa.R
6bc25e2b6059c6a573b49ef8292cb550aaa1c158
[]
no_license
cg0lden/subnational_distributions_BFA
6c9ad7ff1be1ce39a34a6e60724ae3a659c54364
4a8e3fb69691ee9b85be3ab9a064df5dc998bd30
refs/heads/master
2023-05-05T11:33:42.087553
2021-05-25T19:39:35
2021-05-25T19:39:35
300,038,711
0
0
null
null
null
null
UTF-8
R
false
false
3,900
r
usa.R
# NHANES data cleaning for SPADE # Created by Simone Passarelli on 11/23/2020 library(tidyverse) library(haven) library(here) library(janitor) # Clean day 1 data and sync names. Keep necessary vars only nhanes_day1 <- read_xpt(here("data", "raw", "United States", "DR1IFF_J.XPT")) %>% clean_names() %>% mutate(mday=1) %>% rename(id=seqn, code=dr1ifdcd, amount=dr1igrms, vita=dr1ivara, calc=dr1icalc, b12a=dr1ivb12, b12b=dr1ib12a, zinc=dr1izinc, epa=dr1ip205, dha=dr1ip226, iron=dr1iiron, weight1=wtdrd1, weight2=wtdr2d) %>% select(id, mday, code, amount, vita, b12a, b12b, zinc, iron, calc, epa, dha, weight1, weight2) #Clean day 2 data and sync names. Keep necessary vars only nhanes_day2 <- read_xpt(here("data", "raw", "United States", "DR2IFF_J.XPT")) %>% clean_names() %>% mutate(mday=2) %>% rename(id=seqn, code=dr2ifdcd, amount=dr2igrms, vita=dr2ivara, calc=dr2icalc, b12a=dr2ivb12, b12b=dr2ib12a, zinc=dr2izinc, epa=dr2ip205, dha=dr2ip226, iron=dr2iiron, weight1=wtdrd1, weight2=wtdr2d) %>% select(id, mday, code, amount, vita, b12a, b12b, zinc, iron, calc, epa, dha, weight1, weight2) #append day 1 and day 2 data nhanes <- rbind(nhanes_day1, nhanes_day2) # Merge in and combine food group codes from GDQS when they are available nhanes_gdqs_meat <- read_dta(here("data", "raw", "NHANES", "FPED_DR_1516.dta")) %>% select(DR1IFDCD, DESCRIPTION, DR1I_PF_MEAT, DR1I_PF_CUREDMEAT) %>% clean_names() %>% rename(code=dr1ifdcd) %>% filter(code >=20000000 & code < 30000000 , dr1i_pf_meat > 0 | dr1i_pf_curedmeat>0 ) %>% mutate(red = case_when(dr1i_pf_meat > 0 ~ 1, TRUE ~ 0)) %>% mutate(processed = case_when(dr1i_pf_curedmeat > 0 ~ 1 , TRUE ~ 0)) %>% select(code, red, processed) %>% distinct() #Load demographic data for age and sex variables usa_merge <- read_xpt(here("data", "raw", "NHANES", "DEMO_J.XPT")) %>% clean_names() %>% rename( age=ridageyr, sex=riagendr, id=seqn) %>% dplyr::select( age, sex, id) %>% distinct() nhanes1 <- merge(nhanes, nhanes_gdqs_meat, by.all="code", all.x=T) # see how many meat values weren't classified by the gdqs codes meat_test <- nhanes1 %>% filter(code >=20000000 & code < 30000000) %>% filter(processed==0 & red==0) # None, they were all classified usa_nut <- nhanes1 %>% mutate(red_meat = case_when(red >0 ~ amount, TRUE ~ 0), processed_meat = case_when(processed >0 ~ amount, TRUE ~ 0)) %>% group_by(id, mday) %>% summarize(b12 = sum(b12a, b12b), iron = sum(iron), zinc = sum(zinc), vita = sum(vita), calc = sum(calc), red_meat = sum(red_meat), processed_meat = sum(processed_meat), omega_3 = sum(epa, dha), weight1 = weight1, weight2=weight2) %>% distinct() # Rename and format variables for spade usa_spade <- usa_nut %>% left_join(usa_merge, by=c("id")) %>% group_by(id, mday) %>% distinct() %>% ungroup() %>% dplyr::select(id, weight1, weight2, age, sex, mday, b12, iron, zinc, vita, calc, omega_3, red_meat, processed_meat) %>% mutate(id=as.integer(id)) # Check for missing or differen ages usa_missings <- usa_spade[is.na(usa_spade$age), ] # shows you the missings usa_missings #No missing ages #Replace any cases where the ages are different for the same individual ids_data <- unique(usa_spade$id) for (idid in ids_data){ data.id <- usa_spade[usa_spade$id == idid, ] if(nrow(data.id) > 1){ usa_spade[usa_spade$id == idid,"age"] <- min(usa_spade[usa_spade$id == idid,"age"]) } } # Update sampling weights # We want to include both the day 1 and the day 2 data, so we should use the day 1 # Change id type to be numeric save(usa_spade, file=here("data", "processed", "usa"), replace)
475e509e545facda920869dcaeb7ef1ddc3a1b7e
df8e6ea4375e01082e05966c39aca2fa7c733aef
/R-Code/makePlot.R
80ae5a9388b16626f8739566cde528fd33016a68
[]
no_license
vrrani/IntegrativeRegressionNetwork
9b1669fbe9d3c7a63251f3b91d94e4b809825d10
2c41b39a592eae0dd4d8af6c534a88d3c73b07db
refs/heads/main
2023-01-08T01:01:37.346132
2020-11-01T10:32:05
2020-11-01T10:32:05
308,850,692
0
0
null
null
null
null
UTF-8
R
false
false
1,214
r
makePlot.R
maxIter <- 100 for( method in c("fused", "GFLasso", "Lasso", "SGL", "SIOL") ) { maxX <- 0 for( i in 1:length( Wset ) ) { X <- Wset[[i]][[method]] maxX <- max( maxX, max(X[upper.tri(X)]) ) } print( sprintf("%s %f", method, maxX) ) pdf( sprintf('figure_Breast_%s.pdf',method),width=9,height=13) par( mfrow=c(2,1) ) iv <- seq( 0, maxX, maxX / 40.0 ) ivAxis <- seq( 0, maxX, maxX / 20.0 ) plot( 0, type='n', xlim=c(0,maxX), ylim=c(0,log(2*10^5,10)), xaxt="n", ylab="log10(num. edges)", xlab="weight", title = method ) axis(1, at = sprintf("%.4f",iv) , las=2, cex.axis=0.8) for( i in 2:maxIter ) { lines( iv, log( getNumEdges( Wset[[i]][[method]], iv ), 10 ), col='gray' ) } lines( iv, log( getNumEdges(Wset[[1]][[method]], iv),10), lwd=1.5, col='red') plot( 0, type='n', xlim=c(maxX,0), ylim=c(600,0), xaxt="n", ylab="num. component", xlab="weight", title = method ) axis(1, at = sprintf("%.4f",iv) , las=2, cex.axis=0.8) for( i in 2:maxIter ) { lines( iv, getMaxComponent( Wset[[i]][[method]], iv ), col='gray' ) } lines( iv, getMaxComponent(Wset[[1]][[method]], iv), lwd=1.5, col='red') dev.off() }
b5ced5b9b8f86e36900cc66f1d9d3645e2f8d152
84f5ac25a17b16191b40d979b4d4fc0bc21b0b9e
/man/key_sentiment_jockers.Rd
560a7b5b57adc9ba379c185b57a57f5659cdaa7d
[]
no_license
cran/lexicon
1d23c81e51c828020110b9f7d2d01980bdf78bf3
03761ddba87f3ac1dd6af743508a7e8303be061b
refs/heads/master
2021-01-12T01:03:22.432056
2019-03-21T09:40:03
2019-03-21T09:40:03
78,337,774
0
1
null
null
null
null
UTF-8
R
false
true
725
rd
key_sentiment_jockers.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/hash_sentiment_jockers.R \docType{data} \name{key_sentiment_jockers} \alias{key_sentiment_jockers} \title{Jockers Sentiment Key} \format{An object of class \code{data.frame} with 10748 rows and 2 columns.} \usage{ key_sentiment_jockers } \description{ A dataset containing an imported version of Jocker's (2017) sentiment lookup table used in \pkg{syuzhet}. } \details{ \itemize{ \item word. Words \item value. Sentiment values ranging between -1 and 1. } } \references{ Jockers, M. L. (2017). Syuzhet: Extract sentiment and plot arcs from Text. Retrieved from https://github.com/mjockers/syuzhet } \keyword{datasets}
4213b6ecd475b99aabd53351ff49dd386ab5acd8
7ac8a44774d4e3f69fc5ffa55bdde5903c722e7f
/R/Visualizing_data.R
afc3de4930aa3dcfdbc0d4126cb6a7b1c031e485
[]
no_license
emmaSkarstein/Citizen_Science_Skarstein_master
e75910b931629a759f599f8660238bec0e3af3b3
73a8163d577456eefd7c685ea3d21adc52a4a44d
refs/heads/master
2021-07-09T19:32:45.701585
2020-10-20T13:23:19
2020-10-20T13:23:19
207,277,325
0
1
null
null
null
null
UTF-8
R
false
false
7,741
r
Visualizing_data.R
library(sf) library(sp) library(ggplot2) library(ggpubr) library(dplyr) library(fishualize) library(hexbin) library(tidyr) library(knitr) library(summarytools) library(pander) library(maps) library(maptools) library(PointedSDMs) library(patchwork) library(inlabru) library(colorspace) source("R/Model_visualization_functions.R") source("R/loading_map_obs_covs.R") # Setting fish species fish_sp <- "trout" #fish_sp <- "perch" #fish_sp <- "char" #fish_sp <- "pike" if(fish_sp == "trout"){ lat_name <- "Salmo trutta" }else if(fish_sp == "perch"){ lat_name <- "Perca fluviatilis" }else if(fish_sp == "char"){ lat_name <- "Salvelinus alpinus" }else{ lat_name <- "Esox lucius" } norway <- ggplot2::map_data("world", region = "Norway(?!:Svalbard)") norway <- dplyr::setdiff(norway, filter(norway, subregion == "Jan Mayen")) # Showing mesh ggplot() + geom_polygon(data = norway, aes(long, lat, group = group), color=NA, fill = NA) + coord_quickmap() + gg(Mesh$mesh, int.color = "darkorange2", edge.color = "gray20") + theme_bw() + theme(axis.title = element_blank()) ggsave("figs/meshplot.pdf") # Looking at the observations ## Observation map p2 <- ggplot(data.frame(trout_artsobs)) + geom_polygon(data = norway, aes(long, lat, group = group), color="black", fill = "grey93") + coord_quickmap() + geom_point(aes(x = decimalLongitude, y = decimalLatitude), color = "darkorange2", size = 0.5) + theme_bw() + theme(axis.title = element_blank(), axis.text.y = element_blank(), axis.ticks.y = element_blank(), axis.ticks.x = element_blank(), axis.text.x = element_blank()) + ggtitle("Artsobservasjoner") p1 <- ggplot(data.frame(trout_survey)) + geom_polygon(data = norway, aes(long, lat, group = group), color="black", fill = "grey93") + coord_quickmap() + geom_point(aes(x = decimalLongitude, y = decimalLatitude, color = occurrenceStatus), size = 0.5) + scale_color_manual(values=c("cyan4", "darkorange2"), labels = c("Absent", "Present")) + guides(colour = guide_legend(override.aes = list(size=2)))+ theme_bw() + theme(axis.title = element_blank(), legend.title = element_blank(), legend.position = "left", axis.ticks.x = element_blank(), axis.text.x = element_blank()) + ggtitle("Fish status survey") hex2 <- ggplot(data.frame(trout_artsobs), aes(x = decimalLongitude, y = decimalLatitude)) + geom_polygon(data = norway, aes(long, lat, group = group), color='gray93', fill = 'gray93') + coord_quickmap() + geom_hex() + scale_fill_continuous_sequential(palette = "Teal") + theme_bw() + theme(axis.title = element_blank(), axis.text.y = element_blank(), axis.ticks.y = element_blank()) hex1 <- ggplot(data.frame(trout_survey), aes(x = decimalLongitude, y = decimalLatitude)) + geom_polygon(data = norway, aes(long, lat, group = group), color='gray93', fill = 'gray93') + coord_quickmap() + geom_hex() + scale_fill_continuous_sequential(palette = "Teal") + theme_bw() + theme(axis.title = element_blank(), legend.position = "left") (p1 + p2)/ (hex1 + hex2) ggsave(paste0("figs/pointhex_", fish_sp, ".pdf"), height = 6, width = 8) # Hex map of all species all_sp <- bind_rows(Trout = data.frame(trout_artsobs), Perch = data.frame(perch_artsobs), Char = data.frame(char_artsobs), Pike = data.frame(pike_artsobs), .id = "species") all_hex <- ggplot(all_sp, aes(x = decimalLongitude, y = decimalLatitude)) + geom_polygon(data = norway, aes(long, lat, group = group), color='gray80', fill = 'gray80') + coord_quickmap() + geom_hex() + #geom_polygon(data = norway, aes(long, lat, group = group), color = "black", fill = NA) + scale_fill_continuous_sequential(palette = "Teal") + facet_wrap(vars(species), nrow = 1) + theme_bw() + theme(axis.title = element_blank(), strip.text.x = element_text(size = 14)) all_hex #ggsave("figs/hex_all_sp.pdf", width = 9, height = 3) ggsave("figs/hex_all_sp.png", height = 4, width = 10) # Point maps of survey all species all_sp_survey <- bind_rows(Trout = data.frame(trout_survey), Perch = data.frame(perch_survey), Char = data.frame(char_survey), Pike = data.frame(pike_survey), .id = "species") all_points <- ggplot(all_sp_survey, aes(x = decimalLongitude, y = decimalLatitude)) + geom_polygon(data = norway, aes(long, lat, group = group), color="black", fill = "grey93") + coord_quickmap() + geom_point(aes(x = decimalLongitude, y = decimalLatitude, color = occurrenceStatus), alpha = 0.8, size = 0.3) + scale_color_manual(values=c("cyan4", "darkorange2"), labels = c("Absent", "Present")) + facet_wrap(vars(species), nrow = 1) + guides(colour = guide_legend(override.aes = list(size=2))) + theme_bw() + theme(axis.title = element_blank(), strip.text.x = element_text(size = 14), legend.title = element_blank()) all_points ggsave("figs/points_all_sp.png", height = 4, width = 10) all_hex / all_points ggsave("figs/points_hex_all_sp.png", height = 8, width = 12) ## Number of observations per year top_four <- Data_artsobs_df %>% filter(species %in% c("Perca fluviatilis", "Salmo trutta", "Salvelinus alpinus", "Esox lucius")) time_counts <- dplyr::count(top_four, year, species) ggplot(time_counts, aes(x = year, y = n, fill = species)) + geom_bar(stat = "identity", position = position_stack(reverse = FALSE)) + theme_bw() + theme(axis.title = element_blank()) + scale_fill_viridis_d() + geom_vline(xintercept = 1996, linetype = "dashed", color = "black", size = 1) ggsave("figs/timeline.pdf", height = 2, width = 7) # Explanatory variables #Covariates <- readRDS("R/output/Covariates.RDS") Cov_long <- tidyr::gather(data.frame(Covariates), key = variable, value = value, area_km2:log_catchment) ## Explanatory variables on a map plot_exp_var <- function(var){ ggplot(Cov_long %>% dplyr::select(variable, value, decimalLatitude, decimalLongitude) %>% filter(variable==var)) + geom_polygon(data = norway, aes(long, lat, group = group), color = "grey", fill = "grey") + coord_quickmap() + geom_point(aes(x = decimalLongitude, y = decimalLatitude, color = value), alpha = 0.8, size = 0.2) + scale_color_continuous_sequential(palette = "OrRd") + facet_grid(cols = vars(variable), labeller = labeller(variable = cov.labs)) + theme_bw() + theme(axis.title = element_blank(), legend.title = element_blank(), strip.text.x = element_text(size = 14)) } Cov_names <- unique(Cov_long$variable) Use_p <- c("log_area", "log_catchment", "eurolst_bio10", "SCI", "log_perimeter", "distance_to_road", "HFP") Use_interesting <- c("eurolst_bio10", "distance_to_road", "HFP") cov.labs <- c("Log area", "Log catchment", "Temperature", "Shoreline complexity index", "Log perimeter", "Distance to road", "Human footprint index") names(cov.labs) <- Use_p var_plots <- lapply(Use_interesting, plot_exp_var) (var_plots[[1]] + var_plots[[2]] + var_plots[[3]]) #ggsave("figs/covariates_on_map_interesting.pdf", height = 4, width = 10) ggsave("figs/covariates_on_map_interesting.png", height = 4, width = 10) ## Explanatory variables histograms ggplot(Cov_long %>% filter(variable %in% Use_p), aes(x = value)) + geom_histogram(fill = "cyan4", color = "cyan4") + facet_wrap(~variable, scales = 'free_x', nrow = 2, labeller = labeller(variable = cov.labs)) + theme_bw() + theme(axis.title = element_blank()) ggsave("figs/covariate_histograms.pdf", width = 7, height = 4)
d05c4bed32dd7d7c665434a8202aa54e6d1fd4f3
9132996d08213cdf27c8f6d444e3f5b2cfdcfc85
/tests/testthat/test_all_positive.R
d8353640de47042f909073fc4ede00d7ea98b13b
[]
no_license
prioritizr/prioritizr
152013e81c1ae4af60d6e326e2e849fb066d80ba
e9212a5fdfc90895a3638a12960e9ef8fba58cab
refs/heads/main
2023-08-08T19:17:55.037205
2023-08-08T01:42:42
2023-08-08T01:42:42
80,953,648
119
30
null
2023-08-22T01:51:19
2017-02-04T22:45:17
R
UTF-8
R
false
false
3,382
r
test_all_positive.R
test_that("x = default", { expect_tidy_error(all_positive(new_waiver()), "recognized") }) test_that("x = numeric", { expect_true(all_positive(c(0, 1, 2, NA))) expect_true(all_positive(c(0L, 1L, 2L, NA))) expect_false(all_positive(c(-1, NA, 0))) expect_false(all_positive(c(-1L, NA, 0L))) expect_error( assert(all_positive(c(0, -1, 2, NA))), "negative" ) }) test_that("x = Matrix", { expect_true(all_positive(Matrix::Matrix(c(0, 1, 2, NA)))) expect_false(all_positive(Matrix::Matrix(c(-1, NA, 0)))) expect_error( assert(all_positive(Matrix::Matrix(c(-1, NA, 0)))), "negative" ) }) test_that("x = matrix", { expect_true(all_positive(matrix(c(0, 1, 2, NA)))) expect_false(all_positive(matrix(c(-1, NA, 0)))) expect_error( assert(all_positive(matrix(c(-1, NA, 0)))), "negative" ) }) test_that("x = data.frame", { expect_true(all_positive(data.frame(x = c(0, 1, NA), y = c(0L, 2L, NA)))) expect_false(all_positive(data.frame(x = c(0, 1, NA), y = c(-1, 1, 2)))) expect_error( assert(all_positive(data.frame(x = c(0, 1, NA), y = c(-1, 1, 2)))), "negative" ) }) test_that("x = sf", { # create data g <- sf::st_sfc(list(sf::st_point(c(1, 0)), sf::st_point(c(0, 1)))) x <- sf::st_as_sf(tibble::tibble(x = c(0, NA), y = c(0, NA), geom = g)) y <- sf::st_as_sf(tibble::tibble(x = c(0, NA), y = c(-1, 2), geom = g)) # tests expect_true(all_positive(x)) expect_false(all_positive(y)) expect_error(assert(all_positive(y)), "negative") }) test_that("x = Spatial", { # create data g <- sf::st_sfc(list(sf::st_point(c(1, 0)), sf::st_point(c(0, 1)))) x <- sf::st_as_sf(tibble::tibble(x = c(0, NA), y = c(2, NA), geom = g)) y <- sf::st_as_sf(tibble::tibble(x = c(0, NA), y = c(-1, 2), geom = g)) # tests expect_true(all_positive(sf::as_Spatial(x))) expect_false(all_positive(sf::as_Spatial(y))) expect_error( assert(all_positive(sf::as_Spatial(y))), "negative" ) }) test_that("x = SpatRaster", { expect_true(all_positive(terra::rast(matrix(c(0, 1, 2, NA))))) expect_false(all_positive(terra::rast(matrix(c(-1, NA, 0))))) expect_error( assert(all_positive(terra::rast(matrix(c(-1, NA, 0))))), "negative" ) }) test_that("x = Raster", { expect_true(all_positive(raster::raster(matrix(c(0, 1, 2, NA))))) expect_false(all_positive(raster::raster(matrix(c(-1, NA, 0))))) expect_error( assert(all_positive(raster::raster(matrix(c(-1, NA, 0))))), "negative" ) }) test_that("x = ZonesSpatRaster", { # create data z1 <- zones( terra::rast(matrix(c(0, 1, 2, NA))), terra::rast(matrix(c(0, 5, 2, NA))) ) z2 <- zones( terra::rast(matrix(c(0, 1, 2, NA))), terra::rast(matrix(c(0, 1, -2, NA))) ) # tests expect_true(all_positive(z1)) expect_false(all_positive(z2)) expect_error( assert(all_positive(z2)), "negative" ) }) test_that("x = ZonesRaster", { # create data expect_warning( z1 <- zones( raster::raster(matrix(c(0, 1, 2, NA))), raster::raster(matrix(c(0, 5, 2, NA))) ), "deprecated" ) expect_warning( z2 <- zones( raster::raster(matrix(c(0, 1, 2, NA))), raster::raster(matrix(c(0, 1, -2, NA))) ), "deprecated" ) # tests expect_true(all_positive(z1)) expect_false(all_positive(z2)) expect_error( assert(all_positive(z2)), "negative" ) })
628e7c1c1fbaa335ccbee2760e61a18abd5a4ac8
1983b21fb4d2dafa7f5d0e1196e5889253a60206
/Codes/data_frame.r
6be0716d993fca4c0d086ac73cddb2c147b8f942
[ "Apache-2.0" ]
permissive
hackwithabhishek/R-Programming-Knowledge
7348cc376a935732e6e3003502a6cf0a51181ec2
365664003655964b25bf84aee2e1c706efdff83f
refs/heads/main
2023-03-19T06:11:14.443380
2021-03-19T11:36:42
2021-03-19T11:36:42
346,687,501
0
0
null
null
null
null
UTF-8
R
false
false
1,400
r
data_frame.r
#basics of data frame S.No=1:5 df<-data.frame("S.no"=S.No, "Name"=c("John","Marry","Joseph","Mohan","Rihanna"), "Age"=c(32,26,20,43,26)) str(df) df1<-data.frame("S.no"=S.No, "Name"=c("John","Marry","Joseph","Mohan","Rihanna"), "Age"=c(32,26,20,43,26), "Start_date"=as.Date(c("2012-01-01","2013-09-23","2014-11-15","2014-05-11","2015-03-27"))) str(df1) df1 #total noof rows nrow(df1) #total no. of cols length(df1) dim(df1) names(df1) df2<-data.frame("S.no"=S.No, "Name"=c("John","Marry","Joseph","Mohan","Rihanna"), "Age"=c(32,26,20,43,26), "Start_date"=as.Date(c("2012-01-01","2013-09-23","2014-11-15","2014-05-11","2015-03-27")), stringsAsFactors = T) #How to Acces data #use either [,[[ or $ operator to acces col of df. df1["Nme"]#op will in the form df df1[["Nme"]] #op will be in the from vector df1$Name df[2] df1[[2]] df1[["Name"]][2] df1$Start_data[2] #error df1[2][2] df1["Nme"][2] df1$Start_date[2] df1[2,2] df1[,2] df1[c(1,3),] df1[3:5,c(1,4)] df1[.-3] #install .packages("tibble") #add col dept<-c("IT","HR","IT","Finance","Management") df1$Dept<-dept #remove col from df1<-df1[,-5] df1$Dept<-NULL df1 #add col is using cbind funtion emp_id=101:105 df1<-cbind(df1,emp_id) df1
85e495b6287a16b991238dfedbbf681c551ba1e4
cf1f32300d37750c4c74ea0b44c61888fd3a9a2e
/R/04_graphing.R
4ce4f1f92afd092e030728fcd19a633bcdaf8875
[]
no_license
UPGo-McGill/city_summaries
f47f1e654b0da4827f00fa1a180b9e2ecbcb97d3
ece792a27ba6e57b2bd13375d2fa07b7f161e7d1
refs/heads/master
2020-05-30T23:13:20.805172
2019-06-06T14:40:55
2019-06-06T14:40:55
190,011,487
0
0
null
null
null
null
UTF-8
R
false
false
1,429
r
04_graphing.R
############## GRAPHING ################################# source("R/01_helper_functions.R") # Set up timeframes year_prior <- as.POSIXlt(End_date) year_prior$year <- year_prior$year - 1 year_prior_prior <- as.POSIXlt(year_prior) year_prior_prior$year <- year_prior$year - 1 # Active airbnb listings over time figure2 <- ggplot(daily %>% group_by(Date) %>% summarize(Listings = n())) + geom_line(aes(Date, Listings)) + theme_minimal() #ggsave("output/figure2.jpg") # host revenue host_revenue<- daily %>% filter(Date >= year_prior, Date <= End_date, Status == "R") %>% group_by(Airbnb_HID) %>% summarize(rev = sum(Price)) %>% filter(rev > 0) %>% summarize( `Top 1%` = sum(rev[rev > quantile(rev, c(0.99))] / sum(rev)), `Top 5%` = sum(rev[rev > quantile(rev, c(0.95))] / sum(rev)), `Top 10%` = sum(rev[rev > quantile(rev, c(0.90))] / sum(rev))) %>% gather(`Top 1%`, `Top 5%`, `Top 10%`, key = "percentile", value = "value") %>% mutate(percentile = factor(percentile, levels = c('Top 1%', 'Top 5%', 'Top 10%'))) figure3 <- ggplot(host_revenue)+ geom_bar(mapping = aes(x = percentile, y = value, fill = percentile), stat = "identity")+ theme_minimal()+ scale_fill_manual("Percentile", values = alpha(c("lightblue", "blue", "darkblue"), .6))+ theme(axis.title.y = element_blank()) + theme(axis.title.x = element_blank()) #ggsave("output/figure3.jpg")
39d4a3f062d0ce4b52308bcb0ec439856b1b64a5
dcac5a647b01cce1d99ee5ab1bd1c14c2eb0467e
/R/sl_R/crawlers/R/twlottery.R
45f272ecc3580dfe7b5d10d2bf1efb46d93f5e9d
[]
no_license
slchangtw/R_Basics
de9dbef37660b18acb7471968891cd944cabc660
6a7b67558ed8cfee5f403fd1301b505680a82071
refs/heads/master
2021-06-16T23:31:11.051427
2017-05-28T14:37:04
2017-05-28T14:37:04
null
0
0
null
null
null
null
UTF-8
R
false
false
7,849
r
twlottery.R
#' --- #' title: "台灣彩券" #' author: "" #' date: "`r Sys.Date()`" #' output: #' html_document: #' toc: yes #' --- #+ include=FALSE knitr::opts_chunk$set(eval = FALSE) #' ## Load Packages library(httr) library(rvest) library(magrittr) #' ## 台灣彩券 (GET) {.tabset} #' ### Fill In url <- "http://www.taiwanlottery.com.tw/lotto/Lotto649/history.aspx" res <- GET(url = url) doc <- content(res, as = "text", encoding = "UTF-8") %>% read_html() %>% html_nodes(xpath = <Fill In>) %>% html_text() # get text from xml nodeset doc_cleaned <- doc %>% gsub(<Fill In>, "", .) dat <- matrix(doc_cleaned, ncol = <Fill In>, byrow = TRUE) %>% .[, -c(13:19)] %>% set_colnames(c('期別', '開獎日', '兌獎截止', '銷售金額', '獎金總額', '獎號_1', '獎號_2', '獎號_3', '獎號_4', '獎號_5', '獎號_6', '特別號' ,'頭獎_中獎注數', '貳獎_中獎注數', '參獎_中獎注數', '肆獎_中獎注數', '伍獎_中獎注數', '陸獎_中獎注數', '柒獎_中獎注數', '普獎_中獎注數', '頭獎_單注獎金', '貳獎_單注獎金', '參獎_單注獎金', '肆獎_單注獎金', '伍獎_單注獎金', '陸獎_單注獎金', '柒獎_單注獎金', '普獎_單注獎金', '頭獎_累積至次期獎', '貳獎_累積至次期獎金', '參獎_累積至次期獎金', '肆獎_累積至次期獎金', '伍獎_累積至次期獎金')) %>% as.data.frame(stringAsFactors = FALSE) #' ### Answer url <- "http://www.taiwanlottery.com.tw/lotto/Lotto649/history.aspx" res <- GET(url = url) doc <- content(res, as = "text", encoding = "UTF-8") %>% read_html() %>% html_nodes(xpath = "//td/span") %>% html_text() # get text from xml nodeset doc_cleaned <- doc %>% gsub(",|\r\n|\\s", "", .) dat <- matrix(doc_cleaned, ncol = 40, byrow = TRUE) %>% .[, -c(13:19)] %>% set_colnames(c('期別', '開獎日', '兌獎截止', '銷售金額', '獎金總額', '獎號_1', '獎號_2', '獎號_3', '獎號_4', '獎號_5', '獎號_6', '特別號' ,'頭獎_中獎注數', '貳獎_中獎注數', '參獎_中獎注數', '肆獎_中獎注數', '伍獎_中獎注數', '陸獎_中獎注數', '柒獎_中獎注數', '普獎_中獎注數', '頭獎_單注獎金', '貳獎_單注獎金', '參獎_單注獎金', '肆獎_單注獎金', '伍獎_單注獎金', '陸獎_單注獎金', '柒獎_單注獎金', '普獎_單注獎金', '頭獎_累積至次期獎', '貳獎_累積至次期獎金', '參獎_累積至次期獎金', '肆獎_累積至次期獎金', '伍獎_累積至次期獎金')) %>% as.data.frame(stringAsFactors = FALSE) #' ## 台灣彩券 (POST) {.tabset} #' ### Fill In get_lottery <- function(<Fill In>, <Fill In>) { url <- "http://www.taiwanlottery.com.tw/lotto/Lotto649/history.aspx" # get view state and event validation res_g <- GET(url = url) view_state <- content(res_g) %>% html_nodes("<Fill In>") %>% html_attr("<Fill In>") event_validation <- content(res_g) %>% html_nodes("<Fill In>") %>% html_attr("<Fill In>") form <- list( '__EVENTTARGET' = '', '__EVENTARGUMENT' = '', '__LASTFOCUS' = '', '__VIEWSTATE' = <Fill In>, '__VIEWSTATEGENERATOR' = 'C3E8EA98', '__EVENTVALIDATION' = <Fill In>, 'Lotto649Control_history$DropDownList1' = '2', 'Lotto649Control_history$chk' = 'radYM', 'Lotto649Control_history$dropYear' = <Fill In>, 'Lotto649Control_history$dropMonth' = <Fill In>, 'Lotto649Control_history$btnSubmit' = '查詢') res_p <- POST(url = url, body = form, encode = "form") doc <- content(res_p, as = "text", encoding = "UTF-8") %>% read_html() %>% html_nodes(xpath = "//td/span") %>% html_text() %>% gsub(",|\r\n|\\s", "", .) dat <- matrix(doc, ncol = 40, byrow = TRUE) %>% .[, -c(13:19)] %>% ## don't need the order of winning numbers as_tibble() %>% set_colnames(c('期別', '開獎日', '兌獎截止', '銷售金額', '獎金總額', '獎號_1', '獎號_2', '獎號_3', '獎號_4', '獎號_5', '獎號_6', '特別號' ,'頭獎_中獎注數', '貳獎_中獎注數', '參獎_中獎注數', '肆獎_中獎注數', '伍獎_中獎注數', '陸獎_中獎注數', '柒獎_中獎注數', '普獎_中獎注數', '頭獎_單注獎金', '貳獎_單注獎金', '參獎_單注獎金', '肆獎_單注獎金', '伍獎_單注獎金', '陸獎_單注獎金', '柒獎_單注獎金', '普獎_單注獎金', '頭獎_累積至次期獎', '貳獎_累積至次期獎金', '參獎_累積至次期獎金', '肆獎_累積至次期獎金', '伍獎_累積至次期獎金')) %>% as.data.frame(stringAsFactors = FALSE) return(dat) } #' ### Answer get_lottery <- function(year, month) { url <- "http://www.taiwanlottery.com.tw/lotto/Lotto649/history.aspx" # get view state and event validation res_g <- GET(url = url) view_state <- content(res_g) %>% html_nodes("#__VIEWSTATE") %>% html_attr("value") event_validation <- content(res_g) %>% html_nodes("#__EVENTVALIDATION") %>% html_attr("value") form <- list( '__EVENTTARGET' = '', '__EVENTARGUMENT' = '', '__LASTFOCUS' = '', '__VIEWSTATE' = view_state, '__VIEWSTATEGENERATOR' = 'C3E8EA98', '__EVENTVALIDATION' = event_validation, 'Lotto649Control_history$DropDownList1' = '2', 'Lotto649Control_history$chk' = 'radYM', 'Lotto649Control_history$dropYear' = year, 'Lotto649Control_history$dropMonth' = month, 'Lotto649Control_history$btnSubmit' = '查詢') res_p <- POST(url = url, body = form, encode = "form") doc <- content(res_p, as = "text", encoding = "UTF-8") %>% `Encoding<-`("UTF-8") %>% read_html() %>% html_nodes(xpath = "//td/span") %>% html_text() %>% gsub(",|\r\n|\\s", "", .) dat <- matrix(doc, ncol = 40, byrow = TRUE) %>% .[, -c(13:19)] %>% ## don't need the order of winning numbers set_colnames(c('期別', '開獎日', '兌獎截止', '銷售金額', '獎金總額', '獎號_1', '獎號_2', '獎號_3', '獎號_4', '獎號_5', '獎號_6', '特別號' ,'頭獎_中獎注數', '貳獎_中獎注數', '參獎_中獎注數', '肆獎_中獎注數', '伍獎_中獎注數', '陸獎_中獎注數', '柒獎_中獎注數', '普獎_中獎注數', '頭獎_單注獎金', '貳獎_單注獎金', '參獎_單注獎金', '肆獎_單注獎金', '伍獎_單注獎金', '陸獎_單注獎金', '柒獎_單注獎金', '普獎_單注獎金', '頭獎_累積至次期獎', '貳獎_累積至次期獎金', '參獎_累積至次期獎金', '肆獎_累積至次期獎金', '伍獎_累積至次期獎金')) %>% as.data.frame(stringAsFactors = FALSE) return(dat) } #' ## Notes #' 1. If the data is not table-like, extract it by DOM selector. #' 2. Use a GET request to get the value of viewstate. #' 3. Set the value in the body, and get data by a POST request
052d7c15ea95b46a9c4e8336c232eaf6ca14a659
d1d9c9a8197f8ae7060c1b2eea02c62e4529c6ad
/PDS/Slides/scratch.R
59e39c96a80c9d55aeb20b1ef8fcea2a7845c423
[]
no_license
jmontgomery/jmontgomery.github.io
bd0ec322b7416ef811ff5265b7b8edcb9337fe8b
a9a01ef49b6cff50b8a6fd3a4ca58ba5684fe426
refs/heads/master
2021-09-23T09:17:22.152539
2021-09-12T19:23:01
2021-09-12T19:23:01
99,852,460
0
2
null
null
null
null
UTF-8
R
false
false
674
r
scratch.R
library(shiny) runExample("01_hello") # a histogram ### setwd("~/GitHub/jmontgomery.github.io/PDS/Datasets/SenateForecast") senateData<-read.csv("PollingCandidateData92-16.csv") stateName<-"North Carolina" stateData<-senateData %>% filter(state==sateName & cycle==2016) %>% select(c("Poll", "daysLeft", "Candidateidentifier")) %>% group_by(Candidateidentifier)%>% glimpse() library(ggplot2) thisPlot<-ggplot(stateData, mapping=aes(x=daysLeft, y=Poll, color=Candidateidentifier)) + geom_point() + geom_smooth() + ggtitle(paste0("2016 Senate Election in", stateName)) + labs(y="Poll results", x="Days Till Election") print(thisPlot) ###
f9796f19840ddc1ba349357be3e30d60f26de638
9d941f38054390183c6215f47bb29db422d0c876
/man/acf2.Rd
f98fafd9311f3ed60c3e406f657ed7b8ea617249
[]
no_license
egedib/astsa
e9b54be69a517be48d8cd56daf0062adcec7df65
2a5e8d69e2f0ed62dca2fd37ed34a514fc8ed96f
refs/heads/master
2020-05-03T10:01:04.206943
2019-03-30T14:43:07
2019-03-30T14:43:07
178,569,127
0
0
null
2019-03-30T14:28:24
2019-03-30T14:28:24
null
UTF-8
R
false
false
3,358
rd
acf2.Rd
\name{acf2} \alias{acf2} %- Also NEED an '\alias' for EACH other topic documented here. \title{Plot and print ACF and PACF of a time series } \description{ Produces a simultaneous plot (and a printout) of the sample ACF and PACF on the same scale. The zero lag value of the ACF is removed. } \usage{ acf2(series, max.lag=NULL, plot=TRUE, main=paste("Series: ", deparse(substitute(series))), na.action = na.pass, ...) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{series}{The data. Does not have to be a time series object. } \item{max.lag}{ Maximum lag. Can be omitted. Defaults to \eqn{\sqrt{n} + 10} unless \eqn{n < 60}. If the series is seasonal, this will be at least 4 seasons by default. } \item{plot}{If FALSE, no graph is produced but the values are still printed. } \item{main}{Title of graphic; defaults to name of series. } \item{na.action}{How to handle missing data; default is \code{na.pass} } \item{...}{ Additional arguments passed to \code{acf} } } %\details{ %% ~~ If necessary, more details than the description above ~~ %} \value{\item{ACF}{The sample ACF} \item{PACF}{The sample PACF} %% ~Describe the value returned %% If it is a LIST, use %% \item{comp1 }{Description of 'comp1'} %% \item{comp2 }{Description of 'comp2'} %% ... } \details{This is basically a wrapper for \code{acf()} provided in \code{tseries}. The error bounds are approximate white noise bounds, \eqn{0 \pm 2/\sqrt{n}}; no other option is given. } \references{\url{http://www.stat.pitt.edu/stoffer/tsa4/} %% ~put references to the literature/web site here ~ } \author{ D.S. Stoffer } %\note{ %This is bacisally a front end for \code{acf()} and \code{pacf()} provided in \code{tseries}. %} %% ~Make other sections like Warning with \section{Warning }{....} ~ %%\seealso{\code{\link{acf1}} %% ~~objects to See Also as \code{\link{help}}, ~~~} \examples{ acf2(rnorm(100)) acf2(rnorm(100), 25, main='') # no title acf2(rnorm(100), plot=FALSE)[,'ACF'] # print only ACF } %% ##-- or do help(data=index) for the standard data sets. %% %% ## The function is currently defined as %% function(series,max.lag=NULL){ %% num=length(series) %% if (num > 49 & is.null(max.lag)) max.lag=ceiling(10+sqrt(num)) %% if (num < 50 & is.null(max.lag)) max.lag=floor(5*log10(num)) %% if (max.lag > (num-1)) stop("Number of lags exceeds number of observations") %% ACF=acf(series, max.lag, plot=FALSE)$acf[-1] %% PACF=pacf(series, max.lag, plot=FALSE)$acf %% LAG=1:max.lag/frequency(series) %% minA=min(ACF) %% minP=min(PACF) %% U=2/sqrt(num) %% L=-U %% minu=min(minA,minP,L)-.01 %% old.par <- par(no.readonly = TRUE) %% par(mfrow=c(2,1), mar = c(3,3,2,0.8), %% oma = c(1,1.2,1,1), mgp = c(1.5,0.6,0)) %% plot(LAG, ACF, type="h",ylim=c(minu,1), %% main=paste("Series: ",deparse(substitute(series)))) %% abline(h=c(0,L,U), lty=c(1,2,2), col=c(1,4,4)) %% plot(LAG, PACF, type="h",ylim=c(minu,1)) %% abline(h=c(0,L,U), lty=c(1,2,2), col=c(1,4,4)) %% on.exit(par(old.par)) %% ACF<-round(ACF,2); PACF<-round(PACF,2) %% return(cbind(ACF, PACF)) %% } %} %% % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ts}
37ff6460327ec26830206139837aacaa8f714928
e08c16082eec850673cce70157cb71f55531d0b0
/code/plot2.R
b8c7eff17e2575afec8d0bbc5c2dbf003d337c1b
[]
no_license
helenwan/ExData_Plotting1
723d3a100dc588d30fcfe4506955c463db7b377c
4fdd973e2321507ece7864f72eef72748409be8c
refs/heads/master
2021-01-22T07:03:46.363918
2014-05-11T23:21:10
2014-05-11T23:21:10
null
0
0
null
null
null
null
UTF-8
R
false
false
577
r
plot2.R
# only read in data from 2007-02-01 and 2007-02-02 data <- read.csv(pipe('egrep \'^Date|^[1-2]/2/2007\' household_power_consumption.txt'), header=T, sep=';') # open 480x480 pixel png file called plot2.png png(file="plot2.png", width=480, height=480, units = "px") # create new column of DateTime objects data$DateTime <- strptime(paste(data$Date, data$Time, sep=" "), format="%d/%m/%Y %H:%M:%S") # create line plot of Global Active Power with appropriate labels plot(data$DateTime, data$Global_active_power, type="l", ylab="Global Active Power (kilowatts)", xlab="") dev.off()
29106a3e114af9d825b81419f570cc8fa997382e
84a1906fcf51e71e12fc6c04dfae9bb4e5d314ce
/Rscripts/PCA.R
0703f4cbb329c4f199aa68e4656f8b1860f69fe6
[]
no_license
RyanSchu/gwasqc_pipeline
4224fcd4af2e000fbc8c5a71cb3e44d4ccaed048
bece21065427fd30f257a63fb58ee3fac2b22ba4
refs/heads/master
2020-03-24T18:44:52.514828
2019-03-18T19:23:29
2019-03-18T19:23:29
142,898,699
2
4
null
2018-09-21T14:57:39
2018-07-30T16:08:27
Shell
UTF-8
R
false
false
3,828
r
PCA.R
library(dplyr) library(tidyr) library(ggplot2) library(argparse) parser <- ArgumentParser() parser$add_argument("--hapmapdir", help="directory where all the hapmap files are written") parser$add_argument("--val",help="full path to eigenvalue file") parser$add_argument("--vec",help="full path to eigenvector file") parser$add_argument("--fam", help="full path to the fam file youd like to use") parser$add_argument("-o", "--outputdir", help="directory where you would like to output your plots") parser$add_argument("--pop", help="full path to the ") args <- parser$parse_args() "%&%" = function(a,b) paste (a,b,sep="") pcaplots <- args$outputdir %&% "/merged_pca_plots.pdf" if (!is.null(args$pop)){ hapmappopinfo <- read.table(args$pop) %>% select (V1,V3) } else if (grepl("19",args$hapmapdir, fixed=TRUE)) { hapmappopinfo <- read.table(args$hapmapdir %&% "/pop_HM3_hg19_forPCA.txt") %>% select (V1,V3) } else if (grepl( "18",args$hapmapdir, fixed=TRUE)) { hapmappopinfo <- read.table(args$hapmapdir %&% "/pop_HM3_hg18_forPCA.txt") %>% select (V1,V3) } colnames(hapmappopinfo) <- c("pop","IID") fam <- read.table(args$fam) %>% select (V1,V2) colnames(fam) <- c("FID","IID") popinfo <- left_join(fam,hapmappopinfo,by="IID") popinfo <- mutate(popinfo, pop=ifelse(is.na(pop),'GWAS', as.character(pop))) table(popinfo$pop) pcs <- read.table(args$vec,header=T) pcdf <- data.frame(popinfo, pcs[,3:ncol(pcs)]) gwas <- filter(pcdf,pop=='GWAS') hm3 <- filter(pcdf, grepl('NA',IID)) eval <- scan(args$val)[1:10] skree<-round(eval/sum(eval),3) skree<-cbind.data.frame(skree,c(1,2,3,4,5,6,7,8,9,10)) colnames(skree)<-c("percent_var", "PC") pdf(pcaplots) ggplot(data=skree, aes(x=PC, y=percent_var)) + geom_point() + geom_line() + scale_x_continuous(breaks = 1:10) + ggtitle("Proportion of variance explained") #PCA Plot 1 (PC1 vs PC2) ggplot() + geom_point(data=pcdf,aes(x=PC1,y=PC2,col=pop,shape=pop)) + theme_bw() + scale_colour_brewer(palette="Set1") + ggtitle("PC1 vs PC2") #PCA Plot 2 (PC1 vs PC3) ggplot() + geom_point(data=pcdf,aes(x=PC1,y=PC3,col=pop,shape=pop)) + theme_bw() + scale_colour_brewer(palette="Set1") + ggtitle("PC1 vs PC3") #PCA Plot 1 (PC2 vs PC3) ggplot() + geom_point(data=pcdf,aes(x=PC2,y=PC3,col=pop,shape=pop)) + theme_bw() + scale_colour_brewer(palette="Set1") + ggtitle("PC2 vs PC3") #PCA with HAPMAP populations yri <- filter(pcdf,pop=='YRI') uPC1 <- mean(yri$PC1) + 5*sd(yri$PC1) lPC1 <- mean(yri$PC1) - 5*sd(yri$PC1) uPC2 <- mean(yri$PC2) + 5*sd(yri$PC2) lPC2 <- mean(yri$PC2) - 5*sd(yri$PC2) ggplot() + geom_point(data=gwas,aes(x=PC1,y=PC2,col=pop,shape=pop))+geom_point(data=hm3,aes(x=PC1,y=PC2,col=pop,shape=pop))+ theme_bw() +geom_vline(xintercept=c(uPC1,lPC1)) +geom_hline(yintercept=c(uPC2,lPC2)) + ggtitle("Assuming homogeneous, non-admixed") inclusion <- gwas[gwas$PC1 >= lPC1,] inclusion <- inclusion[inclusion$PC1 <= uPC1,] inclusion <- inclusion[inclusion$PC2 >= lPC2,] inclusion <- inclusion[inclusion$PC2 <= uPC2,] samples <- inclusion[,1:2] table(inclusion$pop) dim(samples)[1] dim(gwas)[1]-dim(samples)[1] ggplot() + geom_point(data=gwas,aes(x=PC1,y=PC2,col=gwas$IID %in% samples$IID,shape=gwas$IID %in% samples$IID))+geom_point(data=hm3,aes(x=PC1,y=PC2,col=pop,shape=pop))+ theme_bw() + ggtitle("Assuming homogeneous, non-admixed") dev.off() #write.table(samples, args$QCdir %&% "/PCA/GWAS_PCA.txt",quote=F,row.names=F,col.names=F) #afrpcs <- read.table("/home/angela/px_yri_chol/QC/QCStep6/QCStep6e/QCStep6e.evec",skip=1) #afrcdf <- afrpcs %>% rename(PC1=V2,PC2=V3,PC3=V4,PC4=V5,PC5=V6,PC6=V7,PC7=V8,PC8=V9,PC9=V10,PC10=V11) %>% mutate(pop=ifelse(grepl("TC",V1),"GWAS","GWAS")) #eval <- scan("/home/angela/px_yri_chol/QC/QCStep6/QCStep6e/QCStep6e.eval")[1:10] #round(eval/sum(eval),3)
d3281b1c0f6adde22099337c2e3811e1ee6d94c8
42231220c4194fcef7c12819b72bb6c53c0b68d2
/man/UMRactiveSet_trust.Rd
8d60a68eebd83c43f6e4a534eb2cad04417141b1
[]
no_license
cran/UMR
d710c18c2f42ee71981925aee02f37dc724b17fc
2ce99462b3ef013db95fa703af901f280a5f9fd4
refs/heads/master
2023-07-11T06:36:57.461127
2021-08-14T08:00:09
2021-08-14T08:00:09
292,347,400
0
0
null
null
null
null
UTF-8
R
false
true
2,789
rd
UMRactiveSet_trust.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/UMRactiveSet_trust.R \name{UMRactiveSet_trust} \alias{UMRactiveSet_trust} \title{An active set approach to minimizing objective in Unlinked Monotone Regression} \usage{ UMRactiveSet_trust( yy, ww_y = NULL, grad, hess, UMR_curv, CDF, init, counts = rep(1, length(init)), stepsize, MM, tol_end = 1e-04, tol_collapse, printevery, filename ) } \arguments{ \item{yy}{Y (response) observation vector (numeric)} \item{ww_y}{Weights (nonnegative, sum to 1) corresponding to yy. Samelength as yy. Or NULL in which yy are taken as being evenly weighted.} \item{grad}{Is function(mm, ww_m). (Will be defined based on yy [and maybe ww_y] before being passed in.) Returns vector of length(mm). Gradient of objective function.} \item{hess}{Is function(mm, ww_m). (Will be defined based on yy [and maybe ww_y] before being passed in.) Returns matrix of dimensions length(mm) by length(mm). Hessian of objective function.} \item{UMR_curv}{A curvature function object (giving mathfrak(C) in the paper; and related to "C" in the paper). See UMR_curv_generic() and examples. This is generally a "curried" version of UMR_curv_generic with densfunc and BBp passed in.} \item{CDF}{This is the error (cumulative) distribution function, a function object. Function accepting vector or matrix arguments.} \item{init}{Initial value of estimate ('mm'). Vector, length may be different than length(yy). See 'counts' input.} \item{counts}{Together 'init' and 'counts' serve as the initialization; the implied initial vector is rep.int(init, counts).} \item{stepsize}{Stepsize for moving out of saddle points.} \item{MM}{A number of iterations. May not use them all. MM is not exactly the total number of iterations used in the sense that within each of MM iterations, we will possibly run another algorithm which may take up to MM iterations (but usually takes many fewer).} \item{tol_end}{Used as tolerance at various points . Generally algorithm (and some subalgorithms) end once sum(abs(mm-mmprev)) < tol, or you hit MM iterations.} \item{tol_collapse}{Collapsing roughly equal mm values into each other.} \item{printevery}{integer value (generally << MM). Every 'printevery' iterations, a count will be printed and the output saved.} \item{filename}{filename (path) to save output to.} } \description{ An active set approach to minimizing objective in Unlinked Monotone Regression } \details{ Uses first order (gradient) for optimization, and uses certain second derivative computations to leave saddle points. See Balabdaoui, Doss, and Durot (2021). Note that yy and mm (i.e., number covariates) may have different length. }
8a1a0ee75bf291c71e0801b33732200af362f3c7
89d8f5e676682c487f2143afa352251a7ee11a1a
/man/getPhyloNames.Rd
b0f17b1b48246dc3eff91f65d89df397b8b9d8b4
[ "MIT" ]
permissive
galacticpolymath/galacticEdTools
36d5cb580877c36f03f6f80f8d0e400c8a5d5a3d
32be95593eda122bfe359f724ddd17acad1d647d
refs/heads/main
2023-04-11T22:25:43.780344
2022-07-08T23:33:08
2022-07-08T23:33:08
379,769,787
0
0
NOASSERTION
2021-07-06T02:02:09
2021-06-24T01:22:04
R
UTF-8
R
false
true
1,456
rd
getPhyloNames.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/getPhyloNames.R \name{getPhyloNames} \alias{getPhyloNames} \title{getPhyloNames} \usage{ getPhyloNames(speciesNames, nameType, clearCache = F, quiet = T) } \arguments{ \item{speciesNames}{a name or vector of common or scientific names of organisms of interest (in quotes)} \item{nameType}{what type of name are you supplying? Either "sci" or "common"} \item{clearCache}{delete the cached phylonamescache.rds file saved in tempdir()? default=F} \item{quiet}{suppress verbose feedback from the taxize package? Default=T} } \description{ Find matching scientific or common names for the common or scientific names provided and cache the results for efficient retrieval. This is a convenience wrapper for the \code{\link[taxize]{sci2comm}} and \code{\link[taxize]{comm2sci}} functions. } \details{ Depending on what nameType you supply, getPhyloNames will use the sci2comm or comm2sci function to look for the matching taxonomic name. It first searches the NCBI database, and if that doesn't return a result, it will try the Encyclopedia of Life (EOL) database. This function relies on an internal helper function \code{\link{getPhyloNames_noCache}}, though you will generally not need to use it. The advantage of getPhyloNames is that it caches results, since the database APIs can be a little slow, so you will not need to keep looking up the same names over and over again. }
59f719c958a7bdf40eeb5212979f657ea2b4ad3a
5cd797823ac3e1b404b71b758cfceab9d41fd1b6
/MASA_Sentiment_Analysis.R
1933a25b6a5015a9edd5697f89510d13ac33ef4a
[]
no_license
matthewfarant/News-Tweets-Sentiment
ffec9707b73dd3fc724a2ac364be396899433531
313195c6b6f865a5204dbdbb9044cc1b8e532f03
refs/heads/master
2023-06-28T19:59:12.028962
2021-08-07T13:24:26
2021-08-07T13:24:26
null
0
0
null
null
null
null
UTF-8
R
false
false
12,974
r
MASA_Sentiment_Analysis.R
########### PACKAGES ############# if (!require('rtweet')) install.packages('rtweet'); library('rtweet') if (!require('tidyverse')) install.packages('tidyverse'); library('tidyverse') if (!require('tidytext')) install.packages('tidytext'); library('tidytext') if (!require('textclean')) install.packages('textclean'); library('textclean') if (!require('sentimentr')) install.packages('sentimentr'); library('sentimentr') if (!require('lubridate')) install.packages('lubridate'); library('lubridate') if (!require('stringr')) install.packages('stringr'); library('stringr') if (!require('tseries')) install.packages('tseries'); library('tseries') if (!require('lmtest')) install.packages('lmtest'); library('lmtest') if (!require('ggpubr')) install.packages('ggpubr'); library('ggpubr') if (!require('scales')) install.packages('scales'); library('scales') ########## SCRAPING TWEETS ###################### tweet_cnn<-get_timeline(user='@cnnbrk', n = 3200) tweet_nyt<-get_timeline(user='@nytimes', n= 3200) tweet_bbc<-get_timeline(user='@BBCBreaking',n=3200) tweet_bloom<-get_timeline(user='@business',n=3200) tweet_nbc<-get_timeline(user='@BreakingNews',n=3200) tweet_wsj<-get_timeline(user='@wsj',n=3200) ################################################# keywords<-c('Covid-19','coronavirus','corona','Covid','ncov','2019-ncov','SARS-CoV-2','lockdown') ############ KEYWORDS FILTER ########################### corona_cnn<-tweet_cnn %>% filter(grepl(paste(keywords, collapse="|"), text, ignore.case = TRUE)) corona_nyt<-tweet_nyt %>% filter(grepl(paste(keywords, collapse="|"), text, ignore.case = TRUE)) corona_bbc<-tweet_bbc %>% filter(grepl(paste(keywords, collapse="|"), text, ignore.case = TRUE)) corona_bloom<-tweet_bloom %>% filter(grepl(paste(keywords, collapse="|"), text, ignore.case = TRUE)) corona_nbc<-tweet_nbc %>% filter(grepl(paste(keywords, collapse="|"), text, ignore.case = TRUE)) corona_wsj<-tweet_wsj %>% filter(grepl(paste(keywords, collapse="|"), text, ignore.case = TRUE)) ############################################# corona_cnn %>% mutate(created_at=as.Date(created_at)) %>% dplyr::select(created_at,text)->corona_cnn corona_nyt %>% mutate(created_at=as.Date(created_at)) %>% dplyr::select(created_at,text)->corona_nyt corona_bbc %>% mutate(created_at=as.Date(created_at)) %>% dplyr::select(created_at,text)->corona_bbc corona_bloom %>% mutate(created_at=as.Date(created_at)) %>% dplyr::select(created_at,text)->corona_bloom corona_nbc %>% mutate(created_at=as.Date(created_at)) %>% dplyr::select(created_at,text)->corona_nbc corona_wsj %>% mutate(created_at=as.Date(created_at)) %>% dplyr::select(created_at,text)->corona_wsj ############ TOKEN NORMALIZATION ##################### corona_cnn$text %>% str_to_lower() %>% replace_contraction() %>% replace_symbol() %>% replace_url() %>% strip()->corona_cnn$text corona_nyt$text %>% str_to_lower() %>% replace_contraction() %>% replace_symbol() %>% replace_url() %>% strip()->corona_nyt$text corona_bbc$text %>% str_to_lower() %>% replace_contraction() %>% replace_symbol() %>% replace_url() %>% strip()->corona_bbc$text corona_bloom$text %>% str_to_lower() %>% replace_contraction() %>% replace_symbol() %>% replace_url() %>% strip()->corona_bloom$text corona_nbc$text %>% str_to_lower() %>% replace_contraction() %>% replace_symbol() %>% replace_url() %>% strip()->corona_nbc$text corona_wsj$text %>% str_to_lower() %>% replace_contraction() %>% replace_symbol() %>% replace_url() %>% strip()->corona_wsj$text ############################################### corona_bbc %>% filter(created_at>=as.Date('2020-01-01'))->corona_bbc corona_nbc %>% filter(created_at>=as.Date('2020-01-01'))->corona_nbc sentiment_cnn %>% filter(created_at>=as.Date('2020-01-01'))->sentiment_cnn ############################################### sentiment_cnn<-cbind(corona_cnn,sentiment_by(corona_cnn$text)) sentiment_nyt<-cbind(corona_nyt,sentiment_by(corona_nyt$text)) sentiment_bbc<-cbind(corona_bbc,sentiment_by(corona_bbc$text)) sentiment_bloom<-cbind(corona_bloom,sentiment_by(corona_bloom$text)) sentiment_nbc<-cbind(corona_nbc,sentiment_by(corona_nbc$text)) sentiment_wsj<-cbind(corona_wsj,sentiment_by(corona_wsj$text)) View(sentiment_wsj) #SUPER CLEANING keywords2<-c('crisis','positive','highest','top','death','new covid','new coronavirus') for(i in 1:nrow(sentiment_cnn)){ if(grepl(paste(keywords2, collapse="|"), sentiment_cnn$text[i], ignore.case = TRUE)& sentiment_cnn$ave_sentiment[i]>=0){ sentiment_cnn$ave_sentiment[i]<-sentiment_cnn$ave_sentiment[i]*(-1) } } for(i in 1:nrow(sentiment_bbc)){ if(grepl(paste(keywords2, collapse="|"),sentiment_bbc$text[i], ignore.case = TRUE)& sentiment_bbc$ave_sentiment[i]>=0){ sentiment_bbc$ave_sentiment[i]<-sentiment_bbc$ave_sentiment[i]*(-1) } } for(i in 1:nrow(sentiment_nbc)){ if(grepl(paste(keywords2, collapse="|"),sentiment_nbc$text[i], ignore.case = TRUE)& sentiment_nbc$ave_sentiment[i]>=0){ sentiment_nbc$ave_sentiment[i]<-sentiment_nbc$ave_sentiment[i]*(-1) } } keyword3<-c('vaccine','low','lowest') for(i in 1:nrow(sentiment_cnn)){ if(grepl(paste(keyword3,collapse="|"),sentiment_cnn$text[i],ignore.case = TRUE)& sentiment_cnn$ave_sentiment[i]<0){ sentiment_cnn$ave_sentiment[i]<-sentiment_cnn$ave_sentiment[i]*(-1) } } for(i in 1:nrow(sentiment_bbc)){ if(grepl(paste(keyword3,collapse="|"),sentiment_bbc$text[i],ignore.case = TRUE)& sentiment_bbc$ave_sentiment[i]<0){ sentiment_bbc$ave_sentiment[i]<-sentiment_bbc$ave_sentiment[i]*(-1) } } for(i in 1:nrow(sentiment_nbc)){ if(grepl(paste(keyword3,collapse="|"),sentiment_nbc$text[i],ignore.case = TRUE)& sentiment_nbc$ave_sentiment[i]<0){ sentiment_nbc$ave_sentiment[i]<-sentiment_nbc$ave_sentiment[i]*(-1) } } ############## SENTIMENT ANALYSIS #################### sentiment_cnn %>% group_by(created_at) %>% summarize(sentiment=mean(ave_sentiment)) %>% mutate(Status=ifelse(sentiment>0,'Positive','Negative')) %>% ggplot(aes(x=created_at,y=sentiment,fill=Status)) + geom_col()+ scale_x_date(breaks='1 month',labels=date_format('%B'))+ labs(x='Month',y='Sentiment',title='Sentiment Analysis of @CNNbrk Tweets',subtitle='Polarity analysis on tweets that contain coronavirus related words', caption='Source: Twitter') sentiment_nyt %>% group_by(created_at) %>% summarize(sentiment=mean(ave_sentiment)) %>% mutate(Status=ifelse(sentiment>0,'Positive','Negative')) %>% ggplot(aes(x=created_at,y=sentiment,fill=Status)) + geom_col() sentiment_bbc %>% group_by(created_at) %>% summarize(sentiment=mean(ave_sentiment)) %>% mutate(Status=ifelse(sentiment>0,'Positive','Negative')) %>% ggplot(aes(x=created_at,y=sentiment,fill=Status)) + geom_col()+ scale_x_date(breaks='1 month',labels=date_format('%B'))+ labs(x='Month',y='Sentiment',title='Sentiment Analysis of @BBCBreaking Tweets',subtitle='Polarity analysis on tweets that contain coronavirus related words', caption='Source: Twitter') sentiment_bloom %>% group_by(created_at) %>% summarize(sentiment=mean(ave_sentiment)) %>% mutate(Status=ifelse(sentiment>0,'Positive','Negative')) %>% ggplot(aes(x=created_at,y=sentiment,fill=Status)) + geom_col() sentiment_nbc %>% group_by(created_at) %>% summarize(sentiment=mean(ave_sentiment)) %>% mutate(Status=ifelse(sentiment>0,'Positive','Negative')) %>% ggplot(aes(x=created_at,y=sentiment,fill=Status)) + geom_col()+ scale_x_date(breaks='1 month',labels=date_format('%B'))+ labs(x='Month',y='Sentiment',title='Sentiment Analysis of @BreakingNews Tweets',subtitle='Polarity analysis on tweets that contain coronavirus related words', caption='Source: Twitter') ########################################################### sentiment_cnn %>% group_by(created_at) %>% summarize(sentiment=mean(ave_sentiment))->sentiment_cnn_sum sentiment_bbc %>% group_by(created_at) %>% summarize(sentiment=mean(ave_sentiment))->sentiment_bbc_sum sentiment_nbc %>% group_by(created_at) %>% summarize(sentiment=mean(ave_sentiment))->sentiment_nbc_sum ################### CNN BBC JOINED ####################### sentiment_cnn_sum %>% dplyr::select(created_at,sentiment) %>% left_join(sentiment_bbc_sum,by='created_at',suffix=c('_cnn','_bbc')) %>% left_join(sentiment_nbc_sum,by='created_at') %>% rename(sentiment_nbc=sentiment)->sentiment_cnn_bbc_joined sentiment_cnn_bbc_joined<-mutate(sentiment_cnn_bbc_joined,sentiment_mean=rowMeans( dplyr::select(sentiment_cnn_bbc_joined,starts_with("sentiment_")),na.rm = TRUE)) View(sentiment_cnn_bbc_joined) # includes nbc #############EMOTION ############################# emotion_cnn<-emotion_by(corona_cnn$text) emotion_cnn %>% filter(ave_emotion>0) %>% group_by(emotion_type) %>% summarize(emotion_count=sum(emotion_count)) %>% arrange(desc(emotion_count)) %>% head(8) %>% mutate(emotion_type=fct_reorder(emotion_type,emotion_count)) %>% ggplot(aes(emotion_type,emotion_count))+ geom_col(fill='#EC2029')+ coord_flip()+ labs(y='Word Count',x='Emotion Type',title='CNN Breaking News')->emotion_plot_cnn emotion_bbc<-emotion_by(corona_bbc$text) emotion_bbc %>% filter(ave_emotion>0) %>% group_by(emotion_type) %>% summarize(emotion_count=sum(emotion_count)) %>% arrange(desc(emotion_count)) %>% head(8) %>% mutate(emotion_type=fct_reorder(emotion_type,emotion_count)) %>% ggplot(aes(emotion_type,emotion_count))+ geom_col(fill='black')+ coord_flip()+ labs(x='Emotion Type', y= "Word Count", title='BBC Breaking News')->emotion_plot_bbc emotion_nyt<-emotion_by(corona_nyt$text) emotion_nyt %>% filter(ave_emotion>0) %>% group_by(emotion_type) %>% summarize(emotion_count=sum(emotion_count)) %>% arrange(desc(emotion_count)) %>% head(8)%>% mutate(emotion_type=fct_reorder(emotion_type,emotion_count)) %>% ggplot(aes(emotion_type,emotion_count))+ geom_col()+ coord_flip()+ labs(x="Emotion Type",y="Word Count",title='New York Times')->emotion_plot_nyt emotion_bloom<-emotion_by(corona_bloom$text) emotion_bloom %>% filter(ave_emotion>0) %>% group_by(emotion_type) %>% summarize(emotion_count=sum(emotion_count)) %>% arrange(desc(emotion_count)) %>% head(8) %>% mutate(emotion_type=fct_reorder(emotion_type,emotion_count)) %>% ggplot(aes(emotion_type,emotion_count))+ geom_col(fill='#0000FF')+ coord_flip()+ labs(x='Emotion Type',y="Word Count",title='Bloomberg')->emotion_plot_bloom emotion_nbc<-emotion_by(corona_nbc$text) emotion_nbc %>% filter(ave_emotion>0) %>% group_by(emotion_type) %>% summarize(emotion_count=sum(emotion_count)) %>% arrange(desc(emotion_count)) %>% head(8) %>% mutate(emotion_type=fct_reorder(emotion_type,emotion_count)) %>% ggplot(aes(emotion_type,emotion_count))+ geom_col(fill='#FF9900')+ coord_flip()+ labs(x='Emotion Type',y="Word Count",title='NBC Breaking News')->emotion_plot_nbc emotion_wsj<-emotion_by(corona_wsj$text) emotion_wsj %>% filter(ave_emotion>0) %>% group_by(emotion_type) %>% summarize(emotion_count=sum(emotion_count)) %>% arrange(desc(emotion_count)) %>% head(8) %>% mutate(emotion_type=fct_reorder(emotion_type,emotion_count)) %>% ggplot(aes(emotion_type,emotion_count))+ geom_col(fill='#edb879')+ coord_flip()+ labs(x='Emotion Type',y="Word Count",title='Wall Street Journal')->emotion_plot_wsj ggarrange(emotion_plot_bbc,emotion_plot_cnn,emotion_plot_nyt,emotion_plot_bloom,emotion_plot_nbc,emotion_plot_wsj, ncol=3,nrow=3) ################## VIX ######################## vix<-read.csv(file.choose()) vix$Date<-as.Date(vix$Date,format = '%m/%d/%Y') vix<-vix %>% filter(Date>=as.Date('2020-01-01')) changevix<-c() for(i in 1:nrow(vix)){ changevix[i]<-(vix$VIX.Close[i+1]-vix$VIX.Close[i])/vix$VIX.Close[i] } vix<-vix %>% mutate(changevix=changevix) #################################################################### sentiment_cnn_bbc_joined %>% inner_join(vix,by=c('created_at'='Date'))->vix_sent_joined #################################################################### vix_sent_joined$Status<-ifelse(vix_sent_joined$sentiment_mean>0 ,'Positive','Negative') ggplot(vix_sent_joined)+ geom_col(aes(created_at,sentiment_mean,fill=Status))+ geom_line(aes(created_at,changevix),size=1,alpha=0.6)+ labs(x='Month',y='Mean Polarity & VIX',title='Tweets\' Polarity vs. VIX*',caption='*VIX data downloaded from CBOE website') #adf test broom::tidy(adf.test(vix_sent_joined$sentiment_mean)) broom::tidy(adf.test(na.omit(vix_sent_joined$VIX.Close))) #kpss broom::tidy(kpss.test(vix_sent_joined$sentiment_mean)) broom::tidy(kpss.test(vix_sent_joined$changevix)) #ccf ccf(vix_sent_joined$sentiment_mean,na.omit(vix_sent_joined$changevix))
e457933921c8afbedaa3104fb210a44604051162
184180d341d2928ab7c5a626d94f2a9863726c65
/valgrind_test_dir/do_divisible2-test.R
87cc6554857277ccbade5708b614f8607bf48d2e
[]
no_license
akhikolla/RcppDeepStateTest
f102ddf03a22b0fc05e02239d53405c8977cbc2b
97e73fe4f8cb0f8e5415f52a2474c8bc322bbbe5
refs/heads/master
2023-03-03T12:19:31.725234
2021-02-12T21:50:12
2021-02-12T21:50:12
254,214,504
2
1
null
null
null
null
UTF-8
R
false
false
223
r
do_divisible2-test.R
function (x, nThread = 1L) { e <- get("data.env", .GlobalEnv) e[["do_divisible2"]][[length(e[["do_divisible2"]]) + 1]] <- list(x = x, nThread = nThread) .Call("_hutilscpp_do_divisible2", x, nThread) }
af5635179f3b974bc2bde2dc4be67b85826876c9
f5fdd56afdca7f8d9165ddfac54d6d005e3ffa0c
/RBioDeg.R
07584915e06da85e38b8f8386402fd2478f0b395
[]
no_license
pjkowalczyk/PhysicochemicalPropertyPredictions
866e04eb8cb869f7eeabffe7424840fec29b2a77
4a8020c4c0dd36abf8989ceb55591f36a117dd4e
refs/heads/main
2022-12-24T19:05:19.187489
2020-10-08T15:50:55
2020-10-08T15:50:55
302,376,811
0
0
null
null
null
null
UTF-8
R
false
false
7,052
r
RBioDeg.R
library(rcdk) library(tidyverse) library(magrittr) library(purrr) library(stringr) library(caret) library(corrplot) library(ggplot2) library(ggthemes) library(pROC) library(egg) # read data ## training data train <- read.csv('cache/TR_RBioDeg_1197_descrs.csv', header = TRUE, stringsAsFactors = FALSE) %>% select(-X,-CAS,-ROMol,-SMILES,-ID) %>% select(Ready_Biodeg, everything()) %>% na.omit() train$Ready_Biodeg <- ifelse(train$Ready_Biodeg > 0.5, 'RB', 'NRB') X_train <- train %>% select(-Ready_Biodeg) y_train <- train %>% select(Ready_Biodeg) %>% data.frame() ## test data test <- read.csv('cache/TST_RBioDeg_411_descrs.csv', header = TRUE, stringsAsFactors = FALSE) %>% select(-X,-CAS,-ROMol,-SMILES,-ID) %>% select(Ready_Biodeg, everything()) %>% na.omit() test$Ready_Biodeg <- ifelse(test$Ready_Biodeg > 0.5, 'RB', 'NRB') X_test <- test %>% select(-Ready_Biodeg) y_test <- test %>% select(Ready_Biodeg) %>% data.frame() # curate data ## near-zero variance descriptors nzv <- nearZeroVar(X_train, freqCut = 100/0) X_train <- X_train[ , -nzv] ### and X_test <- X_test[ , -nzv] ## highly correlated descriptors correlations <- cor(X_train) alles_plot <- corrplot::corrplot(correlations, order = 'hclust', tl.cex = 0.6) highCorr <- findCorrelation(correlations, cutoff = 0.85) X_train <- X_train[ , -highCorr] ### and X_test <- X_test[ , -highCorr] correlations <- cor(X_train) noCorr_plot <- corrplot::corrplot(correlations, order = 'hclust', tl.cex = 0.8) ## linear combinations comboInfo <- findLinearCombos(X_train) # returns NULL X_train <- X_train[ , -comboInfo$remove] ### and X_test <- X_test[ , -comboInfo$remove] ## center & scale descriptors preProcValues <- preProcess(X_train, method = c("center", "scale")) X_trainTransformed <- predict(preProcValues, X_train) ### and X_testTransformed <- predict(preProcValues, X_test) # models ## support vector machines set.seed(350) ctrl <- trainControl(## 10-fold CV method = "repeatedcv", number = 10, ## repeated ten times repeats = 10, classProbs = TRUE) library(kernlab) sigmaRangeReduced <- sigest(as.matrix(X_trainTransformed)) svmGridReduced <- expand.grid(.sigma = sigmaRangeReduced[1], .C = 2^(seq(-4, 4))) trainSet <- cbind(y_train, X_trainTransformed) svmModel <- train(Ready_Biodeg ~ ., data = trainSet, method = 'svmRadial', metric = 'ROC', tuneGrid = svmGridReduced, fit = FALSE, trControl = ctrl) y_predict <- predict(svmModel, newdata = X_testTransformed) %>% data.frame() colnames(y_predict) <- c('Predicted') confusionMatrix(data = as.factor(y_predict$Predicted), reference = as.factor(y_test$Ready_Biodeg), positive = 'NRB') library(pROC) y_test$endpt <- ifelse(y_test$Ready_Biodeg == 'NRB', 0, 1) y_predict$endpt <- ifelse(y_predict$Predicted == 'NRB', 0, 1) rocCurve <- roc(response = y_test$endpt, predictor = y_predict$endpt) auc(rocCurve) plot(rocCurve, legacy.axes = TRUE) #####...#####...#####...##### library(randomForest) library(caret) library(e1071) # read data ## training data train <- read.csv('cache/TR_RBioDeg_1197_descrs.csv', header = TRUE, stringsAsFactors = FALSE) %>% select(-X,-CAS,-ROMol,-SMILES,-ID) %>% select(Ready_Biodeg, everything()) %>% na.omit() train$Ready_Biodeg <- ifelse(train$Ready_Biodeg > 0.5, 'RB', 'NRB') ## test data test <- read.csv('cache/TST_RBioDeg_411_descrs.csv', header = TRUE, stringsAsFactors = FALSE) %>% select(-X,-CAS,-ROMol,-SMILES,-ID) %>% select(Ready_Biodeg, everything()) %>% na.omit() test$Ready_Biodeg <- ifelse(test$Ready_Biodeg > 0.5, 'RB', 'NRB') ## bind train and test, by row alles <- rbind(train, test) ## data splitting set.seed(350) trainIndex <- createDataPartition(alles$Ready_Biodeg, p = .8, list = FALSE, times = 1) train <- alles[trainIndex, ] test <- alles[-trainIndex, ] X_train <- train %>% select(-Ready_Biodeg) y_train <- train %>% select(Ready_Biodeg) %>% data.frame() %>% mutate(Ready_Biodeg = as.factor(Ready_Biodeg)) X_test <- test %>% select(-Ready_Biodeg) y_test <- test %>% select(Ready_Biodeg) %>% data.frame() %>% mutate(Ready_Biodeg = as.factor(Ready_Biodeg)) # curate data ## near-zero variance descriptors nzv <- nearZeroVar(X_train, freqCut = 100/0) X_train <- X_train[ , -nzv] ### and X_test <- X_test[ , -nzv] ## highly correlated descriptors correlations <- cor(X_train) corrplot::corrplot(correlations, order = 'hclust') highCorr <- findCorrelation(correlations, cutoff = 0.85) X_train <- X_train[ , -highCorr] ### and X_test <- X_test[ , -highCorr] correlations <- cor(X_train) corrplot::corrplot(correlations, order = 'hclust') ## linear combinations comboInfo <- findLinearCombos(X_train) # returns NULL X_train <- X_train[ , -comboInfo$remove] ### and X_test <- X_test[ , -comboInfo$remove] # 10 fold; repeat 3 times control <- trainControl(method='repeatedcv', number=10, repeats=3) # metric: Accuracy metric <- "Accuracy" mtry <- sqrt(ncol(X_train)) tunegrid <- expand.grid(.mtry=mtry) data2model <- cbind(y_train, X_train) rf_default <- train( Ready_Biodeg ~ ., data = data2model, method = 'rf', metric = 'Accuracy', tuneGrid = tunegrid, trControl = control ) print(rf_default) y_predict <- predict(rf_default, newdata = X_test) %>% data.frame() colnames(y_predict) <- c('Predicted') confusionMatrix(data = as.factor(y_predict$Predicted), reference = as.factor(y_test$Ready_Biodeg), positive = 'NRB') library(doParallel) cores <- 3 registerDoParallel(cores = cores) mtry <- sqrt(ncol(X_train)) #ntree: Number of trees to grow. ntree <- 3 control <- trainControl( method = 'repeatedcv', number = 10, repeats = 3, search = 'random' ) # rf_random <- train(Ready_Biodeg ~ ., data = data2model, method = 'rf', metric = 'Accuracy', tuneLength = 15, trControl = control) print(rf_random) plot(rf_random) # control <- trainControl(method='repeatedcv', number=10, repeats=3, search='grid') # tunegrid <- expand.grid(.mtry = (1:15)) rf_gridsearch <- train(Ready_Biodeg ~ ., data = data2model, method = 'rf', metric = 'Accuracy', tuneGrid = tunegrid)
2ca81b092ee85269c9f2a3c37b0ea69b172b247e
e61d4e17b5683e6c5c79588588aa302f24b03863
/R_Test_File.R
984c37602333bd3c13486fcfb62eb40caf1bde0b
[]
no_license
Joseph-C-Fritch/web_scrape_project
89466e585b3e10dab0be11e1d2d7c803945d1962
0d56f349421d8f564a4ade6ce15c4bda7be11407
refs/heads/master
2020-04-22T02:05:24.170732
2019-02-12T19:06:26
2019-02-12T19:06:26
170,035,903
0
0
null
null
null
null
UTF-8
R
false
false
86
r
R_Test_File.R
library(dplyr) xrp_price_df = read.csv('./xrp_price.csv', stringsAsFactors = 'False')
5b482b6e30a86e55e4de3286146a293f7373c612
342bd673b3cf5f3477eac4c23c7ba8b32d6e7062
/shiny/server_1_loadModels/server_1_loadModels.R
d6bd4514d53fdccb4942183a6c9218ab78827d19
[]
no_license
GRSEB9S/eSDM
4f3575b77fdffe4ebad35028e5dd67aef49da1af
a26b9ac92127346fe0d9e22c3eb6376b8ff88a77
refs/heads/master
2021-07-13T06:35:28.689723
2017-10-19T18:26:26
2017-10-19T18:26:26
null
0
0
null
null
null
null
UTF-8
R
false
false
3,993
r
server_1_loadModels.R
### Code for loading models and converting them to SPDFs ############################################################################### ### Flag for if any model predictions are loaded output$loadModels_display_flag <- reactive({ length(vals$models.ll) != 0 }) outputOptions(output, "loadModels_display_flag", suspendWhenHidden = FALSE) ### Flag for if any model predictions are selected in the table output$loaded_models_selected_flag <- reactive({ isTruthy(input$models_loaded_table_rows_selected) }) outputOptions(output, "loaded_models_selected_flag", suspendWhenHidden = FALSE) ############################################################################### ### Delete selected model observeEvent(input$model_remove_execute, { idx <- as.numeric(input$models_loaded_table_rows_selected) validate( need(length(idx) > 0, paste("Error: Please select one or more sets", "of model predictions to remove")) ) ######################################################### ### Remove the reactiveValue info for selected set(s) of model predicitons vals$models.ll <- vals$models.ll[-idx] vals$models.orig <- vals$models.orig[-idx] vals$models.pix <- vals$models.pix[-idx] vals$models.names <- vals$models.names[-idx] vals$models.data.names <- vals$models.data.names[-idx] vals$models.pred.type <- vals$models.pred.type[-idx] vals$models.specs <- vals$models.specs[-idx] if (length(vals$models.names) == 0) vals$models.names <- NULL if (length(vals$models.pred.type) == 0) vals$models.pred.type <- NULL ######################################################### # Handle other places this data was used ### If these predictions were previewed, hide preview ### Else, adjust vals idx if (!is.null(vals$models.plotted.idx)) { if (any(idx %in% vals$models.plotted.idx)) { shinyjs::hide("model_pix_preview_plot", time = 0) vals$models.plotted.idx <- NULL } else { idx.adjust <- sapply(vals$models.plotted.idx, function(i) { sum(idx < i) }) vals$models.plotted.idx <- vals$models.plotted.idx - idx.adjust validate( need(all(vals$models.plotted.idx > 0), "Error: While deleting original model(s), error 1") ) } } ### Remove evaluation metrics if they're calculated for original model preds # TODO: make this so it only removes the metrics of models being removed if (!is.null(vals$eval.models.idx)) { if (!is.null(vals$eval.models.idx[[1]])){ vals$eval.models.idx <- NULL vals$eval.metrics <- list() vals$eval.metrics.names <- NULL } } ### If these predictions were pretty-plotted, reset and hide pretty plot ### Else, adjust vals idx if (!is.null(vals$pretty.plotted.idx)) { if (any(idx %in% vals$pretty.plotted.idx[[1]])) { shinyjs::hide("pretty_plot_plot", time = 0) vals$pretty.params.list <- list() vals$pretty.plotted.idx <- NULL } else { idx.adjust <- sapply(vals$pretty.plotted.idx[[1]], function(i) { sum(idx < i) }) vals$pretty.plotted.idx[[1]] <- vals$pretty.plotted.idx[[1]] - idx.adjust validate( need(all(vals$pretty.plotted.idx[[1]] > 0), "Error: While deleting 1+ original model(s), error 2") ) } } }) ############################################################################### # Reset 'Prediction value type' to 'Relative' if new file is loaded observe({ input$model_csv_file updateSelectInput(session, "model_csv_pred_type", selected = 2) }) observe({ input$model_gis_raster_file updateSelectInput(session, "model_gis_raster_pred_type", selected = 2) }) observe({ input$model_gis_shp_files updateSelectInput(session, "model_gis_shp_pred_type", selected = 2) }) observe({ input$model_gis_gdb_load updateSelectInput(session, "model_gis_gdb_pred_type", selected = 2) }) ###############################################################################
c5fa95924f4d22ac1b4e3a33f51714206aae5e3e
7be74683083a548d47b31fa6cb826c061c1d2aea
/non-linear/non_linear_lab_6.R
65f4d2275c45672e68edb9a225d40331fa041742
[]
no_license
AnatoliiStepaniuk/ISLR
32b7ab6c9fed20c92dba36016c474b4d9b697ce9
f613a1c56a594f4594c813cbe8f35b55d4263f99
refs/heads/master
2021-01-09T06:35:46.439090
2017-02-12T13:22:29
2017-02-12T13:22:29
81,018,010
0
0
null
null
null
null
UTF-8
R
false
false
1,449
r
non_linear_lab_6.R
library(ISLR) set.seed(1) # (a) all.deltas <- rep(NA, 10) for(i in 1:10){ glm.fit <- glm(wage~poly(age,i), data=Wage) all.deltas[i] <- cv.glm(glm.fit, data=Wage, K=10)$delta[2] } min.delta <- min(all.deltas) d <- which.min(all.deltas) par(mfrow=c(1,1)) plot(x=1:10,y=all.deltas,col="red",type="l",ylab = "CV error",xlab="Polynomial degree") title("Choosing polynomial degree") fit1 <- lm(wage~poly(age,1), data=Wage) fit2 <- lm(wage~poly(age,2), data=Wage) fit3 <- lm(wage~poly(age,3), data=Wage) fit4 <- lm(wage~poly(age,4), data=Wage) fit5 <- lm(wage~poly(age,5), data=Wage) fit6 <- lm(wage~poly(age,6), data=Wage) fit7 <- lm(wage~poly(age,7), data=Wage) fit8 <- lm(wage~poly(age,8), data=Wage) fit9 <- lm(wage~poly(age,9), data=Wage) fit10 <- lm(wage~poly(age,10), data=Wage) anova(fit1,fit2,fit3,fit4,fit5,fit6,fit6,fit7,fit8,fit9,fit10) # Anova proved that CV determined polynom degree = 4 is a reasonable value # b all.step.deltas <- rep(NA, 9) for(i in 2:10){ Wage$age.cut <- cut(age,i) fit.step <- glm(wage~age.cut,data = Wage) all.step.deltas[i-1] <- cv.glm(Wage, fit.step,K=10)$delta[2] } Wage$age.cut<-NULL best.cut.n <- which.min(all.step.deltas) fit.step <- glm(wage~cut(age,best.cut.n),data = Wage) age.range <- range(Wage$age) age.grid <- (age.range[1]:age.range[2]) pred.step <- predict(fit.step, data.frame(age=age.grid)) plot(Wage$age, Wage$wage,col="darkgrey") lines(age.grid, pred.step, type = "l", col="red")
1f7dc4bf0127c9db91762ebeaff289f2c4ef1bb2
cb01200aef78010bbce2477944aec53357334de4
/script work/working scripts.R
16c347eaae4ba088b67a554da3e175453e2f617c
[]
no_license
S-AI-F/Open-Geo-KPI-App
4a5a14891ac94deb3671943673d35acbb8250815
a78da0578c519979efc9c418c44a7c2c70674491
refs/heads/master
2023-06-28T10:48:36.702859
2021-07-21T11:22:34
2021-07-21T11:22:34
263,057,928
0
0
null
null
null
null
UTF-8
R
false
false
6,096
r
working scripts.R
library(shinyjs) install.packages("shinyjs") # get map data geodata_world <- ne_countries() # rename country code and name variables names(geodata_world)[names(geodata_world) == "iso_a3"] <- "iso3c" names(geodata_world)[names(geodata_world) == "name"] <- "NAME" # get worldbank data attribute_data <- wb( indicator = c("EN.ATM.PM25.MC.M3", "SP.POP.TOTL"), return_wide = TRUE, POSIXct = TRUE ) attribute_data_world <- wb( indicator = c(# people indicators "SP.POP.TOTL","SE.PRM.ENRR","SL.TLF.CACT.ZS","SH.STA.MMRT", # porverty and inequality indicators "SI.POV.NAHC", "SI.POV.GINI", # Environment "AG.LND.AGRI.ZS","EN.ATM.CO2E.PC","EN.ATM.PM25.MC.M3", # Economy "NY.GDP.MKTP.CD","NE.GDI.TOTL.KD.ZG","SL.GDP.PCAP.EM.KD", # States and markets "GC.REV.XGRT.CN", "GC.XPN.TOTL.CN","MS.MIL.XPND.GD.ZS","GB.XPD.RSDV.GD.ZS", # Global links "DT.DOD.DECT.CD","SM.POP.NETM"), return_wide = TRUE, POSIXct = TRUE ) attribute_data_world = attribute_data_world %>% dplyr::rename(# people indicators Population_Total = SP.POP.TOTL, School_enrollment_primary = SE.PRM.ENRR, Labor_force_participation_rate = SL.TLF.CACT.ZS, Maternal_mortality_ratio = SH.STA.MMRT, # porverty and inequality indicators Poverty_headcount_ratio = SI.POV.NAHC, GINI_index = SI.POV.GINI, # Environment Agricultural_land = AG.LND.AGRI.ZS, CO2_emission = EN.ATM.CO2E.PC, PM2.5_air_pollution = EN.ATM.PM25.MC.M3, # Economy GDP = NY.GDP.MKTP.CD, Gross_capital_formation = NE.GDI.TOTL.KD.ZG, GDP_per_person_employed = SL.GDP.PCAP.EM.KD, # States and markets Government_revenue = GC.REV.XGRT.CN, Government_Expense = GC.XPN.TOTL.CN, Military_expenditure = MS.MIL.XPND.GD.ZS, Research_and_development_expenditure = GB.XPD.RSDV.GD.ZS, # Global Links External_debt_stocks = DT.DOD.DECT.CD, Net_migration = SM.POP.NETM) head(attribute_data) # get worldbank data exposure <- wb( indicator = "EN.ATM.PM25.MC.M3", return_wide = TRUE, POSIXct = TRUE ) head(exposure) EN.ATM.PM25.MC.M3 <- wb( indicator = "EN.ATM.PM25.MC.M3", return_wide = TRUE, POSIXct = TRUE ) population <- wb( indicator = "SP.POP.TOTL", return_wide = TRUE, POSIXct = TRUE ) head(population) attribute_data_world <- exposure %>% full_join(population[,c("iso3c","date","SP.POP.TOTL")], by = c("iso3c","date")) KPI_start_end_date_fill = function(KPIlist){ KPI_start_end_date = data.frame(indicator = KPIlist) } KPI_start_end_date = data.frame(indicator = c("EN.ATM.PM25.MC.M3", "SP.POP.TOTL")) KPI_start_end_date[KPI_start_end_date$indicator == "EN.ATM.PM25.MC.M3", "stratdate"] = min(EN.ATM.PM25.MC.M3$date) KPI_start_end_date[KPI_start_end_date$indicator == "EN.ATM.PM25.MC.M3", "enddate"] = max(EN.ATM.PM25.MC.M3$date) KPI_start_end_date = data.frame(KPI = as.character(), startdate = as.character(), enddate = as.character()) kpi_list = c("EN.ATM.PM25.MC.M3","SP.POP.TOTL") for(i in 1:length(kpi_list)){ KPI_name = kpi_list[1] KPI_start_end_date[,"KPI"] = KPI_name KPI_start_end_date[,"startdate"] = min() } # merge with attribute data with geodata map_data_world = sp::merge(geodata_world, attribute_data_world, by = "iso3c", duplicateGeoms = TRUE) map_data_world = map_data_world[!is.na(map_data_world@data$date_ct), ] date_vector_world = seq.Date(from = min(map_data_world@data$date_ct), to = max(map_data_world@data$date_ct), by = "years") # get selected date from animation selected_date_world = date_vector_world[10] # get selected kpi from kpi filters selected_kpi_world = "SP.POP.TOTL" # discretization param # discr_param = "KPIcolor_binpal" discr_param = "KPIcolor_qpal" binpal <- colorBin("YlOrRd", map_data_world@data[, selected_kpi_world], 5, pretty = FALSE) qpal = colorQuantile(palette = "YlOrRd", domain = map_data_world@data[, selected_kpi_world], n = 5) Specify_legend_colpal = function(discr_param){ if(discr_param == "KPIcolor_binpal"){ legend_pal = binpal } else if(discr_param == "KPIcolor_qpal"){ legend_pal = qpal } return(legend_pal) } legend_pal = Specify_legend_colpal(discr_param = discr_param) # filter map data based on selected filters map_data_selected_world = map_data_world[map_data_world@data$date_ct == selected_date_world, ] toto = map_data_world@data[ ,selected_kpi_world] # discretize indicator value and fill color map_data_selected_world@data$KPIcolor_qpal = qpal(map_data_selected_world@data[,selected_kpi_world]) map_data_selected_world@data$KPIcolor_binpal = binpal(map_data_selected_world@data[,selected_kpi_world]) # generte filteres map leaflet(map_data_selected_world) %>% clearControls() %>% addTiles() %>% addPolygons(stroke = TRUE, smoothFactor = 0.3, fillOpacity = 0.8, color = "gray", dashArray = "3", weight = 1, opacity = 0.8, fillColor = ~legend_pal(map_data_selected_world@data[,selected_kpi_world]), # fillColor = ~binpal(map_data_selected_world@data[,selected_kpi_world]), highlightOptions = highlightOptions(weight = 2, color = "grey", fillOpacity = 0.7, bringToFront = TRUE), label = ~paste0(NAME,": ",prettyNum(map_data_selected_world@data[ ,selected_kpi_world], format = "f", big.mark = ","))) %>% addLegend(pal = legend_pal, values = ~ map_data_selected_world@data[ ,selected_kpi_world], opacity = 0.5, title = selected_kpi_world) addLegend(pal = binpal, values = ~ map_data_selected_world@data[ ,selected_kpi_world], opacity = 0.5, title = selected_kpi_world)
1a17533e2828adf65f2accfc305d619d5a849303
0f56baca4f5779b5e389311a658f9e6c06617502
/man/preds.Rd
8fc0ff93c96f0a40fce47fa4ec8ce4600c38a102
[]
no_license
cfree14/datalimited2
4e01d6547b6735ee71403da228af6efee4df6621
152a352899585951ff09b52d26181f22d3e09dda
refs/heads/master
2023-08-17T12:23:13.694125
2023-08-04T14:09:57
2023-08-04T14:09:57
115,050,731
16
5
null
null
null
null
UTF-8
R
false
true
605
rd
preds.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/data.R \docType{data} \name{preds} \alias{preds} \title{RAM Legacy Database catch-only status predictions} \format{A data frame with 161 rows (stocks) and 57 variables including B/BMSY estimates and status estimates.} \usage{ preds } \description{ A dataset containing the catch and biomass time series for USA Southern New England/Mid-Atlantic (SNE/MA) Yellowtail flounder (\emph{Pleuronectes ferruginea}) from 1973-2014. This dataset is included for additional testing of the \pkg{datalimited2} package. } \keyword{datasets}
1a813667600961627fb0e8c4cc10e8515ed7f353
6ae2d6b27576cc8c75a7e02256db410e5007a8b2
/tests/testthat/test-dir2.R
ffcfa0332ccdfd9a4c15d85455fe8fcfb7da25bb
[]
no_license
HughParsonage/hutils
3c2cec1b1a01179219deb47df0dc9e6a3a127435
11e6f828876bbc87a42d43a0ee8084ee6d9a6765
refs/heads/master
2023-02-20T04:27:01.996815
2023-02-10T05:18:04
2023-02-10T05:18:04
88,268,552
11
2
null
2022-04-13T08:31:57
2017-04-14T13:09:05
R
UTF-8
R
false
false
2,181
r
test-dir2.R
context("test-dir2") test_that("Error handling", { skip_if_not(identical(.Platform$OS.type, "windows")) library(data.table) expect_error(dir2(.dont_use = TRUE), regexp = "Windows") expect_error(dir2(path = raw(1)), regexp = "`path` was a raw, but must be a string", fixed = TRUE) expect_error(dir2(path = data.table(x = 1)), regexp = "`path` was a data.table data.frame, but must be a string", fixed = TRUE) expect_error(dir2(path = character(0)), regexp = "`path` was length 0", fixed = TRUE) theDir <- "a" while (dir.exists(theDir)) { theDir <- paste0(theDir, "x") } skip_if(dir.exists(theDir)) expect_error(dir2(path = theDir), regexp = "does not exist") }) test_that("Error handling (non-Windows)", { skip_on_os("windows") expect_error(dir2(.dont_use = FALSE), regexp = "Windows") }) test_that("dir2 works", { skip_if_not(identical(.Platform$OS.type, "windows")) skip_only_on_cran() tempd <- tempfile() dir.create(tempd) file.create(file.path(tempd, "abc.csv")) file.create(file.path(tempd, "def.csv")) y <- dir(path = tempd, recursive = FALSE) z <- dir2(path = tempd, recursive = FALSE) expect_equal(length(z), length(y)) z <- dir2(path = tempd, file_ext = ".csv") expect_equal(length(z), 2L) z <- dir2(path = tempd, file_ext = "*.csv") expect_equal(length(z), 2L) z1 <- dir2(path = tempd, file_ext = "*.csv", pattern = "^a") expect_equal(length(z1), 1L) zp <- dir2(path = tempd, file_ext = "*.csv", pattern = "^a", perl = TRUE) expect_equal(length(zp), 1L) zp <- dir2(path = tempd, file_ext = "*.csv", pattern = "^a", perl = FALSE) expect_equal(length(zp), 1L) zfx <- dir2(path = tempd, file_ext = ".csv", pattern = "^a", fixed = TRUE) expect_equal(length(zfx), 0L) zic <- dir2(path = tempd, file_ext = ".csv", pattern = "^A", ignore.case = TRUE) expect_equal(length(zic), 1L) }) test_that("Nil files", { skip_if_not(identical(.Platform$OS.type, "windows")) z <- dir2(file_ext = "*.qqq") expect_equal(length(z), 0L) z <- dir2(file_ext = ".qqq") })
171d70d85fb338ce68ec30b7f1d27a95e39de2b9
bec2aef1fa0722ad373f0a51bcf119c3028855aa
/chap03/mpg.R
f189af1ac171d5dca057c1d3916401a904c8f07f
[]
no_license
floraOuO/R
751a275163758716806752e98f1a4cd3f06f6cc2
4cace0f4158513b08701c2c4f9987d2c1803d8f6
refs/heads/master
2020-04-28T04:02:56.088121
2019-03-22T09:07:50
2019-03-22T09:07:50
174,962,698
0
0
null
null
null
null
UTF-8
R
false
false
470
r
mpg.R
library(ggplot2) library(sqldf) x=c("a","a","b","c","d","d") qplot(x) mpg sqldf(" select distinct manufacturer from mpg ") sqldf(" select count(*) from mpg ") sqldf(" select manufacturer,round(avg(cty),2) as cty_avg,round(avg(hwy),2) as hwy_avg from mpg group by manufacturer order by avg(cty) desc ") ->mpg_ctyhwy_mean mpg_ctyhwy_mean qplot(mpg_ctyhwy_mean$manufacturer,mpg_ctyhwy_mean$cty_avg) qplot(mpg$hwy) table(mpg$drv)
7f6858b6b727fbafe58b028eab287c25809c5a28
2a4b11fd17377f5cf06ef1f89585c71266b8b1c9
/descr_stat_barpie.R
efc571e185d5d21c76d9061d971350c728a08757
[]
no_license
AhyonJeon/covid19-petitons-analysis
6ca1f3017dcfe127e936c5824d28e5df5dc4e8b5
ed69de78646352dd071fc53c5ed0f22bf3a1072f
refs/heads/master
2023-04-18T22:48:22.591345
2021-04-18T06:56:04
2021-04-18T06:56:04
null
0
0
null
null
null
null
UTF-8
R
false
false
4,147
r
descr_stat_barpie.R
# 라이브러리 library(dplyr) library(ggplot2) library(RColorBrewer) library(reshape2) library(data.table) # setdt() 사용하기 위해 library(plyr) #desc()를 사용하기 위해서 필요하다. # 코로나 전후 청원데이터 불러오기 before <- read_csv("before_covid_petition_enc.csv") after <- read_csv("after_covid_petition_enc.csv") total<- rbind(before, after) # category 확인 sort(unique(before$category)) sort(unique(after$category)) length(unique(before$category)) # 간단한 데이터 확인 summary(before) summary(after) # 카테고리별 청원건수 빈도와 비율 확인후 데이터프레임 생성 before_df<- cbind(freq= sort(table(before$category), decreasing =T), relative= prop.table(table(before$category))) after_df<- cbind(freq= sort(table(after$category), decreasing =T), relative= prop.table(table(after$category))) before_df<- data.frame(before_df) ## rownames가 카테고리로 되어있어 카테고리를 열 변수로 빼고 새로운 행이름을 설정 setDT(before_df, keep.rownames = TRUE)[] ## 변수명이 rn으로 빼진 카테고리 변수명을 category로 재설정 before_df<- rename(before_df, category=rn) ## df에 period 변수 생성 before_df<- before_df %>% mutate(period="before") after_df<- data.frame(after_df) setDT(after_df, keep.rownames = TRUE)[] after_df<- rename(after_df, category=rn) after_df<- after_df %>% mutate(period="after") # 카테고리별 청원동의 인원수 변수 생성 temp<- before %>% group_by(category) %>% summarise(AgreeSum= sum(numOfAgrees)) before_df<- merge(before_df, temp, by='category') temp2<- after %>% group_by(category) %>% summarise(AgreeSum= sum(numOfAgrees)) after_df<- merge(after_df, temp2, by='category') total_df= rbind(after_df,before_df) # 막대 그래프 # 빈도 건수 ggplot(total_df, aes(x= category, y= freq, fill=period))+ geom_bar(stat="identity",position= position_dodge2(reverse = TRUE))+ scale_fill_brewer(palette="Set2")+ labs(title="코로나 전후 카테고리 별 청원 건수")+ theme_bw()+ theme(plot.title = element_text(hjust = 0.5, face='bold', size = 15))+ theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5 ))+ theme(legend.text = element_text(size = 8))+ guides(fill=guide_legend(reverse=TRUE)) ggsave("category_freq_bar.jpg", dpi = 300) # ggplot를 저장합니다. # 비율 ggplot(total_df, aes(x= category, y= relative, fill=period))+ geom_bar(stat="identity",position= position_dodge2(reverse = TRUE))+ scale_fill_brewer(palette="Set2")+ labs(title="코로나 전후 카테고리 별 청원 비율")+ theme_bw()+ theme(plot.title = element_text(hjust = 0.5, face='bold', size = 15))+ theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5 ))+ theme(legend.text = element_text(size = 8))+ guides(fill=guide_legend(reverse=TRUE)) ggsave("category_rela_bar.jpg", dpi = 300) # ggplot를 저장합니다. # 파이 그래프 ggplot(before_df, aes(x="", y= -freq, fill= reorder(category,-freq)))+ geom_bar(stat="identity")+ coord_polar("y")+ theme_void()+ labs(title="코로나 전 카테고리 별 청원 건수")+ theme(plot.title = element_text(hjust = 0.6, face='bold', size = 15)) ggsave("category_freq_before_pie.jpg", dpi = 300) # ggplot를 저장합니다. ggplot(after_df, aes(x="", y= -freq, fill= reorder(category,-freq)))+ geom_bar(stat="identity")+ coord_polar("y")+ theme_void()+ labs(title="코로나 후 카테고리 별 청원 건수")+ theme(plot.title = element_text(hjust = 0.6, face='bold', size = 15)) ggsave("category_freq_after_pie.jpg", dpi = 300) # ggplot를 저장합니다. # 다른 파이차트 ## plot the outside pie and shades of subgroups lab <- with(before_df, sprintf('%s: %s',category, freq)) pie(before_df$freq, border = NA, labels = lab, cex = 0.5) # scatter plot ggplot(total_df, aes(x= freq, y= AgreeSum, color=category)) + geom_point()+ labs(title="청원건수에 따른 청원동의 인원수")+ theme(plot.title = element_text(hjust = 0.6, face='bold', size = 15))+ theme_bw() ggsave("agreesum_freq_scatter.jpg", dpi = 300)
986d8a1510c88a86a12321588e39dda5898f48c4
2d320d9af4bed14cc1bbfceb0e8014dcf6a82fe7
/Chapter5/auxFun/F_genNormal.R
d323383c7b32fb54da9e6d2e4122586902849cec
[]
no_license
sthawinke/DoctoralThesis
a5be71706a63d650f24c2a4bc43dd549c627e887
924b9c93ffa1b2939a93d8e88a372d1ce65efb09
refs/heads/master
2020-12-13T22:53:05.279324
2020-01-21T13:35:24
2020-01-21T13:35:24
234,554,358
0
0
null
null
null
null
UTF-8
R
false
false
1,061
r
F_genNormal.R
#' Generate normal data genNormal = function(estList, nPop, n, p, FC, TPR){ if((n %% nPop)!=0) stop("Choose even group sizes!") groupIndComp = rep(seq_len(nPop), times = n/nPop) p = min(p, length(estList["coef",])) ## Sample parameters coefSampled0 = sample(estList["coef",], p) nOTUs = round(p*TPR) #DA taxa meanSampled0 = lapply(integer(nPop), function(x){ OTUids = sample(names(coefSampled0), nOTUs, replace = FALSE) coefSampled0[OTUids] = coefSampled0[OTUids]+FC # Add fold change up indTP <- names(coefSampled0) %in% OTUids newTaxaNames <- paste0(names(coefSampled0)[indTP], "-TPup") names(coefSampled0)[indTP] <- newTaxaNames coefSampled0 }) meanSampled = simplify2array(meanSampled0)[,groupIndComp] dataMat = t(matrix(rnorm(n*p, mean = meanSampled, sd = estList["sd",]), ncol = n, nrow = p)) colnames(dataMat) = rownames(meanSampled) rownames(dataMat) = paste0("Group", groupIndComp, "_", seq_len(n)) list(dataMat = dataMat, meanSampled = meanSampled0) }
bed8feb65862e2eab2edae1f008ed24bb23720cb
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/SpatialNP/examples/spatial.location.Rd.R
282b7d28bd3e44393397d4bb31812b0e150524b0
[]
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
501
r
spatial.location.Rd.R
library(SpatialNP) ### Name: Spatial location ### Title: Multivariate location estimates based on spatial signs and ### signed ranks ### Aliases: ae.hl.estimate ae.spatial.median spatial.location ### Keywords: multivariate nonparametric ### ** Examples A<-matrix(c(1,2,-3,4,3,-2,-1,0,4),ncol=3) X<-matrix(rnorm(3000),ncol=3)%*%t(A) spatial.location(X,score="signrank") spatial.location(X,score="sign") #compare with: colMeans(X) ae.hl.estimate(X,shape=A%*%t(A)) ae.hl.estimate(X,shape=FALSE)
d827cc2793a3520ddd1ba3d7629ab58ed7ad3a7e
1e6970ee8f6b77a0881a2561c2b2836da0d66ac2
/R/celsius_to_kelvin.R
4ba68fa9c376366eeeacabc63286c27a6d69758e
[]
no_license
brilu815/tempConvert
9fd89c80fc434c171454b05dc9481b723bbf170e
675b4d859d964238ee06e78a7d0917af3adb2284
refs/heads/master
2021-01-18T22:29:32.843677
2016-11-02T00:58:48
2016-11-02T00:58:48
72,590,089
0
0
null
null
null
null
UTF-8
R
false
false
126
r
celsius_to_kelvin.R
celsius_to_kelvin = function(temp_c){ temp_f = celsius_to_fahr(temp_c) temp_k = fahr_to_kelvin(temp_f) return(temp_k) }
94014347ec8fef263030514bd26997e69eb25ddb
ea319f995c73653e2e43a1c0b0924757b7e19304
/rscripts/submit_createApsimSims.R
7bafaeb25a008d0f688834afaecfb9a73f9f6391
[]
no_license
cla473/AG_WHEATTEMP
0d25c943c08fcb752be8b49250ffb4a711c0c97e
383459818dae42883ae1f9134710bdb3b1999408
refs/heads/master
2020-03-23T04:16:40.890878
2019-03-27T22:02:21
2019-03-27T22:02:21
139,104,642
0
0
null
null
null
null
UTF-8
R
false
false
1,808
r
submit_createApsimSims.R
#Builds simulations using data from GridSoil.7z (needs to be extracted and converted first) and Ross' met files rm(list = ls()) library(tidyverse) library(xml2) apsimLoc <- "//OSM/CBR/AG_WHEATTEMP/work/ApsimNG-LC/apsimx/" baseApsimxFile <- "//OSM/CBR/AG_WHEATTEMP/work/ApsimNG-LC/prep/BaseWithCultivars.apsimx" metLoc <- "//OSM/CBR/AG_WHEATTEMP/work/ApsimNG-LC/met" soilLoc <- "//OSM/CBR/AG_WHEATTEMP/work/ApsimNG-test/APSIM_prep/SoilXML" gridData <- read.csv("//OSM/CBR/AG_WHEATTEMP/work/ApsimNG-LC/metGrid_Soil.csv", sep=',', header=TRUE) # gridData <- head(gridData, 5) simFiles <- paste(apsimLoc, gridData$simFile, sep = "") soilFiles <- paste(soilLoc, "/", gridData$soilLong * 100, gridData$soilLat * 100, ".soil", sep = "") #these don't need the path, as we are just updating the reference in the apsimx file metFiles <- as.character(gridData$metFile) df <- data.frame(sims=simFiles, mets=metFiles, soils=soilFiles, stringsAsFactors = FALSE) i <- 1 par_generate <- function(i, df, baseApsimxFile) { library(tidyverse) library(xml2) simName <- df$sims[i] #What is the name of apsimx file that will be created met <- df$mets[i] #get the name of the met file #Now read base the Apsim File sim <- read_xml(baseApsimxFile) #update the met file name xml_set_text(xml_find_first(sim, ".//Weather/FileName"), met) #replace the soil data soilData <- read_xml(df$soils[i]) xml_replace(xml_find_first(sim, ".//Soil"), soilData) write_xml(sim, simName) } library(parallel) library(snow) # Get cluster from pearcey cl <- getMPIcluster() if (is.null(cl)) { # Create a cluster for local cl <- makeCluster(parallel::detectCores() - 1, type = 'SOCK') } parLapply(cl, seq_len(nrow(df)), par_generate, df, baseApsimxFile)
3dea5db7934056ed2a22ef6cf34c89474c855336
1d8e6bb24a98389c46db0db658db539f7917c6ea
/problems/problem002.R
a8483611143f7dd0b395cd333d6764c9a817ceae
[]
no_license
parksw3/projectEuler
6609c5950344494476976ad4464f75264b8e5b48
133c4915d59d3ce43ab869fe6bf99e51158f135d
refs/heads/master
2020-04-06T06:54:48.299332
2016-08-31T12:29:59
2016-08-31T12:29:59
65,112,736
0
0
null
null
null
null
UTF-8
R
false
false
140
r
problem002.R
fib <- c(1,2) i <- 2 while(fib[i] < 4e6){ new.fib <- fib[i] + fib[i-1] fib <- c(fib, new.fib) i <- i + 1 } sum(fib[fib%%2 == 0])
f9e1827acbf230f7013ff46afbea3df7ab5f3e39
f753c3187e80b854c1600ef93ac3006851535bbc
/R/buoyData.R
51d73c64b9409e9d889c76e5dac5761497d09e5f
[]
no_license
NOAA-EDAB/buoydata
42055c8b5e55919927a9fce7ef069c6d7351bf04
ad6eceaf1c6c7f998db623f79fbcf8127d620529
refs/heads/master
2023-02-25T10:40:04.467643
2021-01-28T16:38:53
2021-01-28T16:38:53
238,990,643
0
1
null
null
null
null
UTF-8
R
false
false
337
r
buoyData.R
#' buoydata: Extract buoy data from ndbc #' #'Tools to aid in extraction of data from the nbdc website #' #'\itemize{ #'\item Get_ functions to get data. #'\item functions to manipulate the data, aggregate the data #'} #' #'To learn more about using \code{buoydata} click the index below #' #' #' @docType package #' @name buoydata NULL
65fee7d83bfaa1adb8c2eb64ff68e280189f1f86
8ac91b65f4b3674d5fa514b304940712bab78dc8
/plot4.R
dd5b3b685a1262684297fd39a258f5bcb75bd51a
[]
no_license
adanlp/ExData_Plotting1
1ad01af7129cb2bd4a4d624fb4201fc79e75ad9b
a9f3cafac5494d013263ac5b4995ab72664d9a93
refs/heads/master
2021-05-14T02:09:16.548604
2018-01-08T00:34:48
2018-01-08T00:34:48
116,588,050
0
0
null
2018-01-07T18:11:49
2018-01-07T18:11:49
null
UTF-8
R
false
false
1,869
r
plot4.R
# plot4.R # # Construct the corresponding plot for Plotting Assignment 1 # for Exploratory Data Analysis. In this case, plot4.png # # Define the source of data and a name for our file my_url <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip" my_file <- "household_power_consumption.zip" # If not exist, download and unzip the file (avoid downloading every time) if (!file.exists(my_file)){ download.file(my_url, my_file) unzip(my_file) } # Load the data only for the desired dates (2007-02-01 and 2007-02-02) my_data <- read.table("household_power_consumption.txt", sep=";", skip=66637, nrows=2879) # Set column names and convert Date column to date type my_cols <- c("Date","Time","Global_active_power","Global_reactive_power", "Voltage","Global_intensity","Sub_metering_1","Sub_metering_2", "Sub_metering_3") colnames(my_data) <- my_cols my_data <- transform(my_data, Date=as.Date(Date, "%d/%m/%Y")) my_data$Time <- paste(my_data$Date, my_data$Time) my_data <- transform(my_data, Time=strptime(Time, "%Y-%m-%d %H:%M:%S")) # Generates the plot with following options: # 4 plots (2x2) # output file=plot4.png par(mfrow=c(2,2)) with(my_data,{ plot(x=Time, y=Global_active_power, type="l", ylab="Global Active Power", xlab="") plot(x=Time, y=Voltage, type="l", ylab="Voltage", xlab="datetime") plot(x=Time, y=Sub_metering_1, type="l", ylab="Energy sub metering", xlab="") lines(x=Time, y=Sub_metering_2, col="red") lines(x=Time, y=Sub_metering_3, col="blue") legend("topright", pch=151, col=c("black","red","blue"), legend=c("Sub_metering_1","Sub_metering_2","Sub_metering_3"), bty="n") plot(x=Time, y=Global_reactive_power, type="l", ylab="Global_reactive_power", xlab="datetime") }) dev.copy(png, file="plot4.png") dev.off()
1bc4646fbf6b0fedb5dc3c5cec6f2963802069c1
2cb79ce691200221321447a586864810a138a562
/workflow/scripts/figures/disagreement_gender.R
1a45629f4458583abdcc3368725c0bda43c4ea71
[ "MIT" ]
permissive
murrayds/sci-text-disagreement
8cc76bf829577eadc9058a170b65af5b6249d63c
e70d5a16a9b770a4110980e9bacd90f361065d8a
refs/heads/master
2023-06-05T08:47:54.587986
2022-01-03T18:48:45
2022-01-03T18:48:45
288,233,573
2
1
MIT
2021-08-20T14:15:14
2020-08-17T16:42:15
TSQL
UTF-8
R
false
false
3,858
r
disagreement_gender.R
# # disagreement_gender.R # # author: Dakota Murray # # Plots a barchoart of the gender differences in disagreement # source("scripts/figures/themes.R") source("scripts/common.R") FIG.HEIGHT <- 6 FIG.WIDTH <- 5 library(dplyr) library(ggplot2) library(tidyr) library(readr) suppressPackageStartupMessages(require(optparse)) # Command line arguments option_list = list( make_option(c("--input"), action="store", default=NA, type="character", help="Path to file containing disagreement by gender data"), make_option(c("-o", "--output"), action="store", default=NA, type="character", help="Path to save output image") ) # end option_list opt = parse_args(OptionParser(option_list=option_list)) # Load the gender data (obtained from the SQL server) and # filter to the appropriate validity threshold, citation sentence # type, and measure. gender <- read_csv(opt$input, col_types = cols()) %>% filter(type == "citances") %>% filter(threshold == 80) # # The code here is a little messy, but basically we need two seaprate # dataframes, one for the 'count', and the other for the share of disagreement counts <- gender %>% filter(measure == "n_citances_valid") %>% gather(key, n_intext, F1, F2, M1, M2) # Now, the second (disagreement) data frame disagreement <- gender %>% filter(measure == "perc_citances_valid") %>% gather(key, perc_intext, F1, F2, M1, M2) %>% left_join(counts, by = c("LR_main_field", "key")) %>% mutate( key = recode(key, 'F1' = 'female first', 'F2' = 'female last', 'M1' = 'male first', 'M2' = 'male last' ), perc_intext = perc_intext * 100 ) %>% separate(key, into = c("gender", "authorship")) %>% mutate( authorship = recode(authorship, "first" = "First Author", "last" = "Last Author"), field = factor(LR_main_field, levels = field_long_levels()), field = factor(field, labels = field_long_labels()), gender = factor(gender, levels = c("male", "female"), labels = c("men", "women")) ) %>% filter(field != "All") %>% group_by(authorship, field) %>% mutate( # Calculate the ratio of the share of disagreement between # the genders ratio = lag(perc_intext) / (perc_intext) ) # Build the plot plot <- disagreement %>% ggplot(aes(x = gender, y = perc_intext, fill = field, group = interaction(authorship, field))) + geom_bar(stat = "identity", position = position_dodge(width = 0.9), color = "black", aes(alpha = gender)) + geom_text(aes(label = ifelse(is.na(ratio), NA, paste0(sprintf("%.2f", round(ratio, 2)), "x"))), position = position_dodge(width = 0.9), vjust = -1.5, hjust = -0.5 ) + # Add the number of disagreement citances geom_text(position = position_dodge(width = 0.9), aes(label = formatC(n_intext, format = "d", big.mark = ","), y = 0, group = interaction(authorship, field)), vjust = -0.5, alpha = 1, size = 3 ) + facet_grid(field~authorship, switch = "y", scales = "free") + scale_y_continuous(expand = expand_scale(mult = c(0, .5)), position = "right") + scale_alpha_manual(values = c(0.1, 1)) + scale_fill_manual(values = tail(field_long_colors(), 5)) + guides(fill = F, alpha = F) + theme_dakota() + theme( axis.title.x = element_blank(), panel.border = element_rect(size = 0.5, fill = NA), axis.title.y = element_text(face = "bold"), legend.position = "bottom", panel.grid.major.x = element_blank(), strip.text.y.left = element_text(angle = 0, hjust = 0), axis.text.x = element_text(face = "bold", angle = 45, hjust = 1), ) + ylab("% disagreement") # Save the plot ggsave(opt$output, plot, height = FIG.HEIGHT, width = FIG.WIDTH)
4d90a5018c3d85f57ec547241fda6f952ecc5fe8
57612442b949ad63fdf319006fa32b50270b8e89
/best.R
07c4812859f49d2358caff316ea97af63607026b
[]
no_license
zieka/r_programming
add79e86d272ea90982c6c6dbd612df5b0b38ce5
77a9368ecd6fd97d49d83f8a8eab8be26fb17a1d
refs/heads/master
2021-01-10T22:03:44.188911
2014-06-22T01:21:59
2014-06-22T01:21:59
null
0
0
null
null
null
null
UTF-8
R
false
false
1,362
r
best.R
# # best.R # # Copyright (C) 2014 Kyle Scully # # Author(s)/Maintainer(s): # Kyle Scully # # Function returns a character vector with the name of the hospital # that has the best (i.e. lowest) 30-day mortality for the specified # outcome in that state. The hospital name is the name provided in # the Hospital.Name variable. The outcomes can be one of # “heart attack”, “heart failure”, or “pneumonia”. # best <- function(state, outcome) { #Read outcome data data <- read.csv("./data/outcome-of-care-measures.csv", colClasses = "character") #Check that state and outcome are valid valid_states <- unique(data$State) valid_outcomes <- c("heart attack", "heart failure", "pneumonia") if (!(state %in% valid_states)){ stop("invalid state") } if (!(outcome %in% valid_outcomes)){ stop("invalid outcome") } data <- data[data$State == state, ] suppressWarnings(data[, c(11, 17, 23)] <- sapply(data[, c(11, 17, 23)], as.numeric)) #Order the data data <- data[order(data[, 2]), ] #Return hospital name in that state with lowest 30-day death rate if (outcome == "heart attack"){ data[which.min(data[, 11]), "Hospital.Name"] } else if (outcome == "heart failure"){ data[which.min(data[, 17]), "Hospital.Name"] } else if (outcome=="pneumonia"){ data[which.min(data[, 23]), "Hospital.Name"] } }
60e543b71368c432ec3f9875fb263f5177323d86
118960cf373053fe99ca322d17e47b07fe6eb4c9
/R_scripts/hdf5_lib.R
b47ea3f0bab20b3377d816c4dde96a658da4bad4
[ "CC-BY-4.0" ]
permissive
DeplanckeLab/ASAP
19b7926586db7beae943b1b232d399dc5376bd78
5795b7d7329b303973f4549cd78d0a7ae00bd91e
refs/heads/master
2023-08-25T06:24:26.055799
2023-08-22T15:38:39
2023-08-22T15:38:39
86,680,770
21
12
null
null
null
null
UTF-8
R
false
false
2,903
r
hdf5_lib.R
require(rhdf5) # For handling Loom files # loomR is deprecated error.json <- function(displayed) { stats <- list() stats$displayed_error = displayed write(toJSON(stats, method="C", auto_unbox=T), file = paste0(output_dir,"/output.json"), append=F) close_all() stop(displayed) } # Close All handles close_all <- function() { h5closeAll() } # Close File Handle close_file <- function(handle) { H5Fflush(handle) H5Fclose(handle) } # Open the Loom file while handling potential locking open_with_lock <- function(loom_filename, mode) { if(mode == "r") mode <- "H5F_ACC_RDONLY" if(mode == "r+") mode <- "H5F_ACC_RDWR" repeat{ # Handle the lock of the file tryCatch({ return(H5Fopen(name = loom_filename, flags = mode)) }, error = function(err) { if(!grepl("Unable to open file", err$message)) error.json(err$message) }) message("Sleeping 1sec for file lock....") time_idle <<- time_idle + 1 Sys.sleep(1) } } # Delete a dataset if exists delete_dataset <- function(handle, dataset_path) { tryCatch({ h5delete(file = handle, name = dataset_path) }, error = function(err) { if(!grepl("Specified link doesn't exist.", err$message)) error.json(err$message) }) } add_matrix_dataset <- function(handle, dataset_path, dataset_object, storage.mode_param="double", chunk_param=c(min(dim(dataset_object)[1], 64), min(dim(dataset_object)[2], 64)), level_param = 2) { if(is.null(dim(dataset_object))) error.json("Cannot write this dataset, it is not a matrix!") delete_dataset(handle, dataset_path) out <- h5createDataset(file = handle, dataset = dataset_path, dims = dim(dataset_object), storage.mode = storage.mode_param, chunk=chunk_param, level=level_param) h5write(file = handle, obj = dataset_object, name=dataset_path) } add_array_dataset <- function(handle, dataset_path, dataset_object, storage.mode_param="double", chunk_param=c(min(length(dataset_object), 64)), level_param = 2) { if(!is.null(dim(dataset_object))) error.json("Cannot write this dataset, it is not an array!") delete_dataset(handle, dataset_path) out <- h5createDataset(file = handle, dataset = dataset_path, dims = length(dataset_object), storage.mode = storage.mode_param, chunk=chunk_param, level=level_param) h5write(file = handle, obj = dataset_object, name=dataset_path) } # Fetch dataset if exists or return NULL fetch_dataset <- function(handle, dataset_path, transpose = F) { handle_dataset <- NULL tryCatch({ handle_dataset <- H5Dopen(h5loc = handle, name = dataset_path) out <- H5Dread(handle_dataset) H5Dclose(handle_dataset) if(transpose) out <- t(out) if(length(dim(out)) == 2) return(as.data.frame(out)) return(as.vector(out)) }, error = function(err) { if(!is.null(handle_dataset)) H5Dclose(handle_dataset) if(grepl("Can't open object", err$message)) return(NULL) else error.json(err$message) }) }
54146459cf21b4cc108ca9b4cd17e6e89e6894ed
31deaad1827ec16f80447a5e06c601d354e034a6
/inst/shiny-examples/testapp/app.R
772934593f14402e86ab64dd95c307c747ebe1d8
[]
no_license
schliebs/trollR
1976355e538d749b4ceb85763b4fd1fa864de462
365b65ea7f5b5af0fec2d45ead9867e40e1cec03
refs/heads/master
2020-03-11T14:04:17.049910
2018-04-19T17:03:20
2018-04-19T17:03:20
130,043,175
10
1
null
null
null
null
UTF-8
R
false
false
864
r
app.R
library(shiny) source("modules.R") ui <- fixedPage( h2("Module example"), actionButton("insertBtn", "Insert module") ) server <- function(input, output, session) { observeEvent(input$insertBtn, { btn <- input$insertBtn insertUI( selector = "h2", where = "beforeEnd", ui = tagList( h4(paste("Module no.", btn)), linkedScatterUI(paste0("scatters", btn)), textOutput(paste0("summary", btn)) ) ) df <- callModule(linkedScatter, paste0("scatters", btn), reactive(mpg), left = reactive(c("cty", "hwy")), right = reactive(c("drv", "hwy")) ) output$summary <- renderText({ sprintf("%d observation(s) selected", nrow(dplyr::filter(df(), selected_))) }) }) } shinyApp(ui, server)
c4dd937e7516e0e6f4073c37404dc1becc9df92d
eb61601e2a01b8ffe2b039cd3f4002ab4530fae0
/roller/tests/testthat/test-check-times.R
aca0fee89fa93d3df6ac16f65042dede68ca9bde
[]
no_license
ronishen86/hw-stat133
7fc597fca74ad4365a1d6db4526b794d3eee2449
769d836a2d17f65b8e997b8d7b6ada18e0d8cd97
refs/heads/master
2020-03-30T00:19:11.536294
2018-12-01T20:14:44
2018-12-01T20:14:44
150,516,127
0
0
null
null
null
null
UTF-8
R
false
false
279
r
test-check-times.R
context("Test check roll arguments") test_that("check_times works with ok vectors", { expect_true(check_times(1)) expect_true(check_times(33)) }) test_that("check_times fails with invalid numbers", { expect_error(check_times(.5)) expect_error(check_times("a")) })
583b89d241d7ec1f76d78a5e94e8b80cef4b5e11
11b20d7df0aecb79ba43e83ec271362da0cdc928
/R/reporting.R
d5ccee59aa3b5973ef86e9fa1df725f3f436ed06
[]
no_license
pinusm/Mmisc
63b5b8ce5e7262ae14dc102ebe06b5d990a14d3f
509a248d3564b557ef2c5eee6ca47a3a2a9b60ab
refs/heads/master
2021-06-06T06:44:00.360151
2021-06-03T06:42:31
2021-06-03T06:42:31
138,485,843
1
1
null
null
null
null
UTF-8
R
false
false
10,995
r
reporting.R
#' convert numeric p-values to strings for reporting, without leading zero #' @param p a p-value in numeric value #' @export pvalue.correct <- function(p){ p <- p %>% as.numeric pvalue = dplyr::case_when(p < 0.001 ~ "< .001", p < 0.01 ~ "< .01", p < 0.05 ~ "< .05", TRUE ~ p %>% round(2) %>% formatC(digits = 2, format = "f") %>% as.character() %>% str_replace("0.", ".") ) return(pvalue) } #' ggplot2 APA-style #' #' theme modified version of papaja's theme_apa() #' #' @param base_size base_size #' @param base_family base_family #' @param box box #' @importFrom grDevices windowsFonts #' @export # theme_apa <- function(base_size = 14, base_family = "", box = FALSE) { grDevices::windowsFonts(Times = grDevices::windowsFont("TT Times New Roman")) adapted_theme <- ggplot2::theme_bw(base_size, base_family) + ggplot2::theme(plot.title = ggplot2::element_text(size = ggplot2::rel(1.1), margin = ggplot2::margin(0, 0, ggplot2::rel(14), 0)), axis.title = ggplot2::element_text(size = ggplot2::rel(1.1)), axis.title.x = ggplot2::element_text(margin = ggplot2::margin(ggplot2::rel(18), 0, 0, 0)), axis.title.y = ggplot2::element_text(margin = ggplot2::margin(0, ggplot2::rel(18), 0, 0)), axis.ticks.length = ggplot2::unit(ggplot2::rel(6), "points"), axis.text = ggplot2::element_text(size = ggplot2::rel(0.9)), axis.text.x = ggplot2::element_text(margin = ggplot2::margin(ggplot2::rel(6), 0, 0, 0)), axis.text.y = ggplot2::element_text(margin = ggplot2::margin(0, ggplot2::rel(8), 0, 0)), axis.line.x = ggplot2::element_line(), axis.line.y = ggplot2::element_line(), legend.title = ggplot2::element_text(), legend.key = ggplot2::element_rect(fill = NA, color = NA), legend.key.width = ggplot2::unit(ggplot2::rel(20), "points"), legend.key.height = ggplot2::unit(ggplot2::rel(25), "points"), legend.spacing = ggplot2::unit(ggplot2::rel(18), "points"), panel.spacing = ggplot2::unit(ggplot2::rel(16), "points"), panel.grid.major.x = ggplot2::element_line(size = NA), panel.grid.minor.x = ggplot2::element_line(size = NA), panel.grid.major.y = ggplot2::element_line(size = NA), panel.grid.minor.y = ggplot2::element_line(size = NA), strip.background = ggplot2::element_rect(fill = NA, color = NA), strip.text.x = ggplot2::element_text(size = ggplot2::rel(1.1), margin = ggplot2::margin(0, 0, ggplot2::rel(16), 0)), strip.text.y = ggplot2::element_text(size = ggplot2::rel(1.1), margin = ggplot2::margin(0, 0, 0, ggplot2::rel(16)))) if (box) { adapted_theme <- adapted_theme + ggplot2::theme(panel.border = ggplot2::element_rect(color = "black")) } else { adapted_theme <- adapted_theme + ggplot2::theme(panel.border = ggplot2::element_blank()) } adapted_theme } #' convert string p-values to strings for reporting, without leading zero #' @param p a p-value in string value #' @export pvalue.report <- function(p){ pvalue <- p %>% formatC(digits = 2, format = "f") if (p < 0.001) { pvalue <- " < .001" } else { if (p < 0.01) { pvalue <- " < .001" } else { if (p < 0.05) { pvalue <- " < .05" } else { pvalue <- paste0(" = ", gsub(pattern = "0\\.", replacement = "\\.", as.character(p %>% formatC(digits = 2, format = "f")))) } } } paste0("*p*", pvalue) } #' report cocor's different of correlations #' @param cor_p a cocor object #' @export #' cor_diff_report <- function(cor_p){ pvalue <- pvalue.report(cor_p$fisher1925$p.value) cohensQ <- round(psych::fisherz(cor_p$fisher1925$estimate[1]) - psych::fisherz(cor_p$fisher1925$estimate[2]),2) return(paste0("*z* = ",round(cor_p$fisher1925$statistic,2),", ", pvalue, ", *Cohen's q* = ", cohensQ)) } #' report var.test's different of variances #' @param var_d a var.test's different of variances object #' @export var_diff_report <- function(var_d){ pvalue <- pvalue.report(var_d$p.value) DFnum <- var_d$parameter[["num df"]] DFdenom <- var_d$parameter[["denom df"]] return(paste0("*F*$\\textsubscript{(",DFnum,",",DFdenom,")}$ = ",round(var_d$statistic,2),", ", pvalue)) } #' report chi-square different of proportions #' @param var_d a chi-square different of proportions object #' @export chi_prop_diff_report <- function(var_d){ pvalue <- pvalue.report(var_d$p.value) DFnum <- var_d$parameter[["num df"]] DFdenom <- var_d$parameter[["denom df"]] return(paste0("*F*$\\textsubscript{(",DFnum,",",DFdenom,")}$ = ",round(var_d$statistic,2),", ", pvalue)) } #' give M and SD per group, with the 'apa' package, on the results of t_test() #' #' @param t_test an apa::t_test object #' @param x the name of a group in the apa::t_test object #' @export apa.desc <- function(t_test, x){ group <- as.character(x) group_data <- t_test$data[[group]] mean <- mean(group_data, na.rm = T) sd <- sd(group_data, na.rm = T) return(paste0("(*M* = ",round(mean,2),", *SD* = ", round(sd,2),")")) } #' report correlation with BF, created by cor.bf() #' #' @param corObject a cor.bf() object #' @param BF01 should the BF be 10, or 01 based #' @export report_cor.bf <- function(corObject , BF01 = F) { BFtype <- "10" BFvalue <- ifelse("jzs_med" %in% class(corObject$bf), corObject$bf$BayesFactor, ifelse("BFBayesFactor" %in% class(corObject$bf),BayesFactor::extractBF(corObject$bf)$bf, #corObject$bf@bayesFactor$bf, NA) ) if (BF01) { BFtype <- "01" BFvalue <- 1 / BFvalue } paste0(apa::apa(corObject$cor),", $\\textit{BF}_\\textit{",BFtype,"}$ = ",BFvalue %>% round(2)) } #' convert numbers to literal numbers #' #' based on https://github.com/ateucher/useful_code/blob/master/R/numbers2words.r #' #' @param x a number in numeric format #' @export numbers2words <- function(x){ ## Function by John Fox found here: ## http://tolstoy.newcastle.edu.au/R/help/05/04/2715.html ## Tweaks by AJH to add commas and "and" helper <- function(x){ digits <- rev(strsplit(as.character(x), "")[[1]]) nDigits <- length(digits) if (nDigits == 1) as.vector(ones[digits]) else if (nDigits == 2) if (x <= 19) as.vector(teens[digits[1]]) else trim(paste(tens[digits[2]], Recall(as.numeric(digits[1])))) else if (nDigits == 3) trim(paste(ones[digits[3]], "hundred and", Recall(makeNumber(digits[2:1])))) else { nSuffix <- ((nDigits + 2) %/% 3) - 1 if (nSuffix > length(suffixes)) stop(paste(x, "is too large!")) trim(paste(Recall(makeNumber(digits[ nDigits:(3*nSuffix + 1)])), suffixes[nSuffix],"," , Recall(makeNumber(digits[(3*nSuffix):1])))) } } trim <- function(text){ #Tidy leading/trailing whitespace, space before comma text = gsub("^\ ", "", gsub("\ *$", "", gsub("\ ,",",",text))) #Clear any trailing " and" text = gsub(" and$","",text) #Clear any trailing comma gsub("\ *,$","",text) } makeNumber <- function(...) as.numeric(paste(..., collapse = "")) #Disable scientific notation opts <- options(scipen = 100) on.exit(options(opts)) ones <- c("", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine") names(ones) <- 0:9 teens <- c("ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", " seventeen", "eighteen", "nineteen") names(teens) <- 0:9 tens <- c("twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety") names(tens) <- 2:9 x <- round(x) suffixes <- c("thousand", "million", "billion", "trillion") if (length(x) > 1) return(trim(sapply(x, helper))) helper(x) } #' a helper for GGally's ggpairs #' #' @param data data #' @param mapping mapping #' @param ... ... #' @export plot_trend_lines <- function(data, mapping, ...){ p <- ggplot2::ggplot(data = data, mapping = mapping) + ggplot2::geom_point() + ggplot2::geom_smooth(method=stats::loess, fill="#A4A4A4", color="#A4A4A4", ...) + ggplot2::geom_smooth(method=stats::lm, fill="#2E2E2E", color="#2E2E2E", ...) p } #' convert numeric p-values to asterik stars #' #' @param p a p-value in numeric format #' @export pvalue.stars <- function (p) { p <- p %>% as.numeric pstar = dplyr::case_when( p < 0.001 ~ "***", p < 0.01 ~ "**", p < 0.05 ~ "*", TRUE ~ "") return(pstar) }
6d52fe9cd5121068c0dc449b0c3c30ff090d76bb
3176c7f008fabb7a406241149808fc2f7cacec4d
/man/minExactMatch.Rd
fad2020bc4f28e0d448bc2f8cf3d7b8e5f94f19b
[ "MIT" ]
permissive
markmfredrickson/optmatch
712f451829c128c4f1fd433e2d527bb7160e8fcc
51e0b03a30420179149be254262d7d6414f3d708
refs/heads/master
2023-05-31T05:11:01.917928
2023-04-06T13:18:58
2023-04-06T13:18:58
1,839,323
37
18
NOASSERTION
2023-01-26T18:45:56
2011-06-02T20:49:32
R
UTF-8
R
false
true
1,527
rd
minExactMatch.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/feasible.R \name{minExactMatch} \alias{minExactMatch} \title{Find the minimal exact match factors that will be feasible for a given maximum problem size.} \usage{ minExactMatch(x, scores = NULL, width = NULL, maxarcs = 1e+07, ...) } \arguments{ \item{x}{The object for dispatching.} \item{scores}{Optional vector of scores that will be checked against a caliper width.} \item{width}{Optional width of a caliper to place on the scores.} \item{maxarcs}{The maximum problem size to attempt to fit.} \item{...}{Additional arguments for methods.} } \value{ A factor grouping units, suitable for \code{\link{exactMatch}}. } \description{ The \code{\link{exactMatch}} function creates a smaller matching problem by stratifying observations into smaller groups. For a problem that is larger than maximum allowed size, \code{minExactMatch} provides a way to find the smallest exact matching problem that will allow for matching. } \details{ \code{x} is a formula of the form \code{Z ~ X1 + X2}, where \code{Z} is indicates treatment or control status, and \code{X1} and \code{X2} are variables can be converted to factors. Any additional arguments are passed to \code{\link{model.frame}} (e.g., a \code{data} argument containing \code{Z}, \code{X1}, and \code{X2}). The the arguments \code{scores} and \code{width} must be passed together. The function will apply the caliper implied by the scores and the width while also adding in blocking factors. }
9858828a1deea58ea918c1e92826fad376d24c47
718de5af14276062cf57b96c2ed3f32a0fc74312
/man/clusterGenes.Rd
7a2e21e28411476b1b91e339ce24b873da43d196
[]
no_license
cole-trapnell-lab/monocle
34976ee5f1d7960245b30aa1ef07ff16cbb97092
5ad275623499b1830863d36b6a7db334460948bd
refs/heads/master
2021-01-10T22:53:24.172037
2016-05-15T20:14:22
2016-05-15T20:14:22
70,340,167
2
1
null
2016-10-08T15:25:47
2016-10-08T15:25:46
null
UTF-8
R
false
false
908
rd
clusterGenes.Rd
% Generated by roxygen2 (4.0.2): do not edit by hand \name{clusterGenes} \alias{clusterGenes} \title{Plots the minimum spanning tree on cells.} \usage{ clusterGenes(expr_matrix, k, method = function(x) { as.dist((1 - cor(t(x)))/2) }, ...) } \arguments{ \item{expr_matrix}{a matrix of expression values to cluster together} \item{k}{how many clusters to create} \item{method}{the distance function to use during clustering} \item{...}{extra parameters to pass to pam() during clustering} } \value{ a pam cluster object } \description{ Plots the minimum spanning tree on cells. } \examples{ \dontrun{ full_model_fits <- fitModel(HSMM[sample(nrow(fData(HSMM_filtered)), 100),], modelFormulaStr="expression~sm.ns(Pseudotime)") expression_curve_matrix <- responseMatrix(full_model_fits) clusters <- clusterGenes(expression_curve_matrix, k=4) plot_clusters(HSMM_filtered[ordering_genes,], clusters) } }
7233d52a6f0727e89f249ae4ae763114022eac24
9032d2c38dd8060bce037372e585de09e9a813d9
/man/Gcontrol.Rd
74e701ee6afc090328b320e7020d5b79e7c0bd2a
[]
no_license
huihualee/DLMtool
34e2dde7b978d71bf356c995d829601d12c6b809
2cbec6a21ddf04e44455c6bafde5910a568ffeb9
refs/heads/master
2021-01-16T22:27:15.259416
2014-09-11T00:00:00
2014-09-11T00:00:00
null
0
0
null
null
null
null
UTF-8
R
false
false
946
rd
Gcontrol.Rd
\name{Gcontrol} \alias{Gcontrol} %- Also NEED an '\alias' for EACH other topic documented here. \title{ G-control harvest control rule } \description{ A harvest control rule proposed by Carl Walters that uses trajectory in inferred surplus production to make upward/downward adjustments to quota recommendations } \usage{ Gcontrol(x, DLM, reps = 100, yrsmth = 10, gg = 2, glim = c(0.5, 2)) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ A position in data-limited methods data object } \item{DLM}{ A data-limited methods data object } \item{reps}{ The number of quota samples } \item{yrsmth}{ The number of years over which to smooth catch and biomass data } \item{gg}{ A gain parameter } \item{glim}{ A constraint limiting the maximum level of change in quota recommendations } } \references{ Made-up for this package. } \author{ C. Walters and T. Carruthers }
631fdd249d065a532a42c517c7b2980b22537e3d
0e19f4fc4f1908d238934e421a1de8480654ca42
/HorseRacingPrediction/LogisticRegression/Regression.r
6d08c7f63729c44e9ed3be117da7590a23fe1814
[ "CC-BY-2.0" ]
permissive
nitingautam/sa2014
a7aaf7499463933b57c815afacd4291722a02346
e8574ffb76c92860e1f13f2895c4423cd3aaa4ca
refs/heads/master
2021-01-15T18:08:30.516493
2015-01-07T13:56:06
2015-01-07T13:56:06
30,122,732
5
0
null
2015-01-31T19:05:04
2015-01-31T19:05:04
null
UTF-8
R
false
false
363
r
Regression.r
# Load the data and take a look at it. data <- read.csv("C:\\Users\\Gary\\Documents\\Presentations\\SoftwareArchitect\\HorseRacingPrediction\\LogisticRegression\\Data.csv"); head(data); # Predict win/lose based on mile time and weight logit <- glm(Win~MileTime+Weight, data=data, family="binomial"); summary(logit); # "Decode" the coefficients exp(coef(logit))
a3af06b64acc3dac9f3b88006f402f518b3d5861
cd8a77f7c6c09c32ffa6205cac6ba295bb97d838
/cachematrix.R
e81371461bd8c80711b3cb76f604d0b9f425b5b2
[]
no_license
tamasfrisch/ProgrammingAssignment2
16233dc529d4e4452abb0b4bdf14dedad4963f9f
e648e38c3d821ec9f621d0132facd83ade87a860
refs/heads/master
2020-12-25T20:54:10.811425
2014-09-16T23:51:21
2014-09-16T23:51:21
null
0
0
null
null
null
null
UTF-8
R
false
false
1,356
r
cachematrix.R
## Coursera Programming Assignment 2 ## Scoping exercise ## makeCacheMatrix generates a list, taking a matrix as an input ## The list contains 4 functions, basically methods that set and get the matrix and its cached inverse (invMatrix) ## Note that there is no checking of the values in the setinverse function. makeCacheMatrix <- function(x = matrix()) { invMatrix <-NULL set <- function (y){ x <<-y invMatrix <<- NULL } get <- function () x setinverse <- function (inverse) invMatrix <<- inverse getinverse <-function () invMatrix list (set=set, get=get, setinverse=setinverse, getinverse=getinverse) } ## cacheSolve expects an input generated by the makeCacheMatrix function; that is a list with 4 functions ## Then it checks whether the getinverse method has a value in the closure; if it does, it returns the cached value ## If the value does not exist (setinverse has not been called yet), it calls the setinverse function and sets it. cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' invMatrix <- x$getinverse() if (!is.null(invMatrix)) { message ("Getting cached data") return(invMatrix) } data <- x$get() invMatrix <- solve(data, ...) x$setinverse(invMatrix) invMatrix }
886d873acbe5f1c8f78bbbc52712de445d9db27e
2cf5744042a9802bc019c0557848db8fbfda0d39
/man/MRIaggr-plotLesion3D.Rd
a3a1fb412fd4d77293df90a72b61e459c5ce6b7c
[]
no_license
cran/MRIaggr
bcc874f1253ab7b168e4a6d68bc66e8556b7d330
099c3227ac60fdad71aa5c1b79bf53b91a92e177
refs/heads/master
2021-01-21T21:47:16.132229
2015-12-23T23:44:19
2015-12-23T23:44:19
31,946,742
1
1
null
null
null
null
UTF-8
R
false
false
2,992
rd
MRIaggr-plotLesion3D.Rd
\name{plotLesion3D} \title{3D plot of the lesion} \alias{plotLesion3D} \alias{plotLesion3D,MRIaggr-method} \description{ Make a 3D plot of the lesion. (experimental version) } \usage{ \S4method{plotLesion3D}{MRIaggr}(object, mask, edge = FALSE, Neighborhood = "3D_N6", numeric2logical = FALSE, spatial_res = c(1,1,1), xlim = NULL, ylim = NULL, zlim = NULL, type.plot = "shapelist3d", px_max = 10000, radius = 1, type = "s", col = "red", col.edge = "black") } \arguments{ \item{object}{an object of class \code{\linkS4class{MRIaggr}}. REQUIRED.} \item{mask}{the binary contrast parameter indicating the lesion. \emph{character}. REQUIRED.} \item{edge}{should the edges of the lesion be ploted instead of the core ? \emph{logical}.} \item{Neighborhood}{the type of neighbourhood used to defined the edges. \emph{character}.} \item{numeric2logical}{should \code{mask} be convert to logical ? \emph{logical}.} \item{spatial_res}{a dilatation factor for the coordinates. \emph{positive numeric vector of size 3}.} \item{xlim}{the x limits of the plot. \emph{numeric vector of size 2} or \code{NULL} leading to automatic setting of the x limits.} \item{ylim}{the y limits of the plot. \emph{numeric vector of size 2} or \code{NULL} leading to automatic setting of the y limits.} \item{zlim}{the z limits of the plot. \emph{numeric vector of size 2} or \code{NULL} leading to automatic setting of the z limits.} \item{type.plot}{the type of plot to be displayed. Can be \code{"plot3d"} or \code{"shapelist3d"}.} \item{px_max}{the maximum number of points that can be ploted. \emph{integer}.} \item{radius}{the radius of spheres. \emph{numeric}. See \code{plot3d} for more details.} \item{type}{the type of item to plot. \emph{character}. See \code{plot3d} for more details.} \item{col}{the color of the core of the lesion. \emph{character}.} \item{col.edge}{the color of the edge of the lesion. \emph{character}.} } \details{ ARGUMENTS: \cr the \code{Neighborhood} argument can be a \emph{matrix} or an \emph{array} defining directly the neighbourhood to use (i.e the weight of each neighbor) or a name indicating which type of neighbourhood should be used (see the details section of \code{\link{initNeighborhood}}). FUNCTION: \cr This functions uses the \code{plot3d} or \code{shapelist3d} and thus require the \emph{rgl} package to work. This package is not automatically loaded by the \code{MRIaggr} package. } \value{ None. } \examples{ ## load a MRIaggr object data("MRIaggr.Pat1_red", package = "MRIaggr") \dontrun{ if(require(rgl)){ # global view plotLesion3D(MRIaggr.Pat1_red, mask = "MASK_T2_FLAIR_t2", spatial_res = c(1.875,1.875,6), numeric2logical = TRUE) # by slice plotLesion3D(MRIaggr.Pat1_red, mask = "MASK_T2_FLAIR_t2", spatial_res = c(1.875,1.875,6), type.plot = "plot3d", numeric2logical = TRUE) } } } \concept{plot.} \keyword{methods}
9a172a862b18638a712cf2eb6e9f3ebe3fda6ff4
e42721b2bf31675a294e14b2d59111a1b83de58b
/R/GSE27034.R
bc41246f917d383784f554bfd402af374aa21345
[]
no_license
szymczak-lab/DataPathwayGuidedRF
d60fdd2a07cf69359f147b7956a27b03d1b9dd02
8af8869378e6aae27b727f1417e51c30564f4a34
refs/heads/master
2020-12-11T06:42:48.292639
2020-01-27T09:16:50
2020-01-27T09:16:50
233,790,509
0
0
null
null
null
null
UTF-8
R
false
false
746
r
GSE27034.R
#' GSE27034 #' #' This is a preprocessed hallmark data set with COAGULATION as target pathway. #' A Genome U133 Plus 2.0 Array is utilized to analyze peripheral artery disease in blood tissue. The study was performed in an unpaired design. #' #' #' @docType data #' @keywords datasets #' @name GSE27034 #' @usage data(GSE27034) #' @format A Summarized Experiment object with 19014 genes and 36 samples (19 cases and 17 controls). #' The column outcome in the colData corresponds to the outcome that was used in the paper. #' @references Masud, R., Shameer, K., Dhar, A., Ding, K., and Kullo, I. J. (2012). Gene expression profiling of peripheral blood mononuclear cells in the setting of peripheral arterial disease. J Clin Bioinf , 2, 6. NULL
1caf576d45ec5e28392471afa6a7b7946157b581
b3db9e15f1112a4ac9d58213396d6a6fff5e8e6f
/man/lasso.Rd
c8dd2ce62b932e46feebcdb47c40ff43ca902ee8
[]
no_license
Yannuo10/BIS557-HW4
700300059bef7ce37090430d0db0e5b51f01f66d
9d558ffab0dbb8308a91eb37157d25e51a70f60b
refs/heads/main
2023-01-16T05:06:56.773266
2020-11-23T08:17:25
2020-11-23T08:17:25
315,206,771
0
0
null
null
null
null
UTF-8
R
false
true
602
rd
lasso.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/lasso_py.R \name{lasso} \alias{lasso} \title{lasso() function} \usage{ lasso(form, df, contrasts = NULL, lambda) } \arguments{ \item{form}{a formula;} \item{df}{a data frame used for the function;} \item{contrasts}{a list of contrasts for factor variables} \item{lambda}{a constant for penalty} } \description{ to build a lasso regression model using python code } \examples{ data(iris) library(reticulate) library(casl) fit_model <- lasso(Sepal.Length ~ ., iris, contrasts = list(Species = "contr.sum"), lambda = 0.1) }
e4a7413b9a7b392f8d934deecd99a6c1dc7d1407
2a7e77565c33e6b5d92ce6702b4a5fd96f80d7d0
/fuzzedpackages/fDMA/R/fDMA.R
299acc8b78d2cac82ce128b3110d5f6ddd66ecf3
[]
no_license
akhikolla/testpackages
62ccaeed866e2194652b65e7360987b3b20df7e7
01259c3543febc89955ea5b79f3a08d3afe57e95
refs/heads/master
2023-02-18T03:50:28.288006
2021-01-18T13:23:32
2021-01-18T13:23:32
329,981,898
7
1
null
null
null
null
UTF-8
R
false
false
34,298
r
fDMA.R
fDMA <- function (y,x,alpha,lambda,initvar,W=NULL,initial.period=NULL,V.meth=NULL,kappa=NULL, gprob=NULL,omega=NULL,model=NULL,parallel=NULL,m.prior=NULL,mods.incl=NULL, DOW=NULL,DOW.nmods=NULL,DOW.type=NULL,DOW.limit.nmods=NULL,progress.info=NULL, forced.models=NULL,forbidden.models=NULL,forced.variables=NULL, bm=NULL,small.c=NULL,fcores=NULL,mods.check=NULL,red.size=NULL, av=NULL) { ### requires "forecast", "parallel", "stats" and "xts" packages ### y - a numeric or a column matrix of a dependent variable, ### if y is a xts object, then plots will have time index on the x axis ### x - a matrix of independent variables (drivers), different columns correspond to different variables ### alpha - a forgetting factor between 0 and 1 used in probabilities estimations ### lambda - a forgetting factor between 0 and 1 used in variance approximations, ### or numeric vector of forgetting factors between 0 and 1 ### initvar - initial variance in the state space equation ### W - a method for setting the initial values of variance for the models equations, ### W = "reg" corresponds to the method based on the linear regression as in the paper by Raftery et al. (2010), ### alternatively an arbitrary positive number can be specified, ### by default the method of Raftery et al. (2010) is used ### initial.period - a number of observation since which MSE and MAE are computed, ### by default the whole sample is used, i.e., initial.period = 1 ### V.meth - a method for the state space equation variance updating, ### V.meth = "rec" corresponds to the recursive moment estimator, as in the paper by Raftery et al. (2010), ### V.meth = "ewma" corresponds to the exponentially weighted moving average, ### by default V.meth = "rec" is used ### kappa - a parameter in the exponentially weighted moving average, between 0 and 1, ### used if V.meth = "ewma" ### gprob - a matrix of Google probabilities, columns should correspond to columns of x ### omega - a parameter between 0 and 1 used in probabilities estimations, ### used if gprob is specified ### model - model = "dma" for Dynamic Model Averaging, model = "dms" for Dynamic Model Selection, ### or model = "med" for Median Probability Model, ### by default model = "dma" is used ### parallel - indicate whether parallel computations should be used, ### by default parallel = FALSE ### m.prior - a parameter for general model prior (Mitchell and Beauchamp, 1988), ### by default m.prior = 0.5, which corresponds to the uniform distribution ### mods.incl - a matrix indicating which models should be used for estimation, ### the first column indicates inclusion of a constant, ### by default all possible models with a constant are used ### DOW - a threshold for Dynamic Occam's Window (Onorante and Raftery, 2016), ### should be a number between 0 and 1, ### if DOW = 0, then no Dynamic Occam's Window is applied, ### by default DOW = 0 ### DOW.nmods - initial number of models for Dynamic Occam's Window, ### should be less than the number of all possible models and larger than or equal to 2, ### they are randomly chosen, ### if DOW.nmods = 0, then initially models with exactly one variable are taken, ### by default DOW.nmods = 0 ### DOW.type - DOW.type = "r" for DMA-R (Onorante and Raftery, 2016), ### DOW.type = "e" for DMA-E, ### by default DOW.type = "r" ### bm - indicate whether benchmark forecast should be computed, ### by default bm = FALSE ### DOW.limit.nmods - the limit of number of models used in Dynamic Occam's Window ### progress.info - applicable only if Dynamic Occam's Window is used, ### if progress.info = TRUE number of round and number of models are printed, ### by default progress.info = FALSE ### small.c - a small constant added to posterior model probabilities, ### to prevent possible reduction them to 0 due to computational issues, ### by default small.c is taken as in small constant as in Eq. (17) ### in Raftery et al. (2010) ### forced.models - matrix of models which if Dynamic Occam's Window is used ### have to be always included, similar as mods.incl, ### by default forced.models = NULL ### forbidden.models - matrix of models which should not be used ### in Dynamic Occam's Window, similar as mods.incl, ### by default forbidden.models = NULL ### forced.variables - vector of variables which must be present in each model ### in Dynamic Occam's Window, first slot indicates constant, ### by default forced.variables = NULL ### fcores - used only if parallel = TRUE, otherwise ignored, ### indicates the number of cores that should not be used, ### by default fcores = 1 ### mods.check - indicates if models specified by the user should be checked, ### by default mods.check = FALSE ### red.size - indicates if outcomes should be reduced to save memory, ### by default red.size = FALSE ### av - av = "dma" corresponds to the original DMA averaging scheme, ### av = "mse" corresponds to averaging based on Mean Squared Error, ### av = "hr1" corresponds to averaging based on Hit Ratio, assuming time-series are in levels, ### av = "hr2" corresponds to averaging based on Hit Ratio, assuming time-series represent changes, ### by default av = "dma" ###################################### checking initial parameters if (missing(y)) { stop("please, specify y") } if (missing(x)) { stop("please, specify x") } if (is.xts(x)) { x <- as.matrix(x) } if (is.xts(y)) { y <- as.matrix(y) } if (! (is.numeric(y) || is.matrix(y))) { stop("y must be numeric or matrix") } if (is.matrix(y) && ! (ncol(y) == 1)) { stop("y must be a one column matrix") } if (! is.matrix(x)) { stop("x must be a matrix") } if (is.null(colnames(x))) { colnames(x) <- colnames(x, do.NULL = FALSE, prefix = "X") warning('column names of x were automatically created') } if (anyNA(colnames(x))) { stop("x must have column names") } if (is.matrix(y) && is.null(colnames(y))) { warning('column name of y was automatically created') colnames(y) <- colnames(y, do.NULL = FALSE, prefix = "Y") } if (is.matrix(y) && anyNA(colnames(y))) { warning('column name of y was automatically created') colnames(y) <- "Y1" } if (! length(y) == nrow(x)) { stop("y and x must have the same number of observations") } if (anyNA(y)) { stop("missing values in y") } if (anyNA(x)) { stop("missing values in x") } if (missing(alpha)) { stop("please, specify alpha") } if (! missing(alpha) && ! is.numeric(alpha)) { stop("alpha must be numeric") } if ((alpha <= 0) || (alpha > 1)) { stop("alpha must be greater than 0, and less than or equal to 1") } if (missing(lambda)) { stop("please, specify lambda") } if (! missing(lambda) && ! is.numeric(lambda)) { stop("lambda must be numeric or numeric vector") } if ((any(lambda <= 0)) || (any(lambda > 1))) { stop("lambda must be greater than 0, and less than or equal to 1") } if (missing(initvar)) { stop("please, specify initvar (i.e., initial variance)") } if (! missing(initvar) && ! is.numeric(initvar)) { stop("initvar must be numeric") } if (initvar <= 0) { stop("variance (initvar) must be positive") } if (is.null(W)) { W <- "reg" } if (! ((W == "reg") || is.numeric(W)) ) { stop("please, specify correct W (i.e., initial variance)") } if (is.numeric(W) && (W <= 0)) { stop("variance (W) must be positive") } if (W == "reg") { W <- NULL } if (is.null(initial.period)) { initial.period <- 1 } if (! is.numeric(initial.period)) { stop("initial.period must be numeric") } if ((initial.period <= 0) || (initial.period > length(y))) { stop("initial.period must be greater than or equal to 1, and less than the number of observations") } if (is.null(V.meth)) { V.meth <- "rec" } if (V.meth == "rec" && !is.null(kappa)) { stop("kappa is used only if V.meth is set to ''ewma''") } if (! V.meth %in% c("rec","ewma")) { stop("please, specify correct V.meth") } if (V.meth == "ewma" && is.null(kappa)) { stop("please, specify kappa") } if (V.meth == "ewma" && ! is.numeric(kappa)) { stop("kappa must be numeric") } if ( (V.meth == "ewma") && ( (kappa < 0) || (kappa > 1) ) ) { stop("kappa must be between 0 and 1") } if ( ! is.null(gprob) && ! is.matrix(gprob) ) { stop("gprob must be a matrix") } if ( ! is.null(gprob) && !(length(y) == nrow(gprob)) ) { warning("time-series of gprob and x differ in length") } if (! is.null(gprob)) { gprob.ind <- nrow(x) - nrow(gprob) + 1 } else { gprob.ind <- nrow(x) + 1 } if ( ! is.null(gprob) && !(ncol(x) == ncol(gprob)) ) { stop("gprob and x must have the same number of columns") } if ( ! is.null(gprob) && anyNA(gprob) ) { stop("missing values in gprob") } if ( (! is.null(gprob)) && ( (length(gprob[gprob<0]) > 0) || (length(gprob[gprob>1]) > 0) ) ) { stop("values of gprob must be greater than or equal to 0, and less than or equal to 1") } if ( (! is.null(gprob)) && (is.null(omega) ) ) { stop("please, specify omega") } if (! is.null(omega) && ! is.numeric(omega)) { stop("omega must be numeric") } if (! is.null(omega) && ( (omega < 0) || (omega > 1) ) ) { stop("omega must be greater than or equal to 0, and less than or equal to 1") } if (is.null(model)) { model <- "dma" } if (! model %in% c("dma","dms","med")) { stop("please, specify correct model: ''dma'', ''dms'', or ''med''") } if (is.null(parallel)) { parallel <- FALSE } if (! is.logical(parallel)) { stop("parallel must be logical, i.e., TRUE or FALSE") } if (is.null(m.prior)) { m.prior <- 0.5 } if (! is.null(m.prior) && ! is.numeric(m.prior)) { stop("m.prior must be numeric") } if ((m.prior <= 0) || (m.prior >= 1)) { stop("m.prior must be greater than 0, and less than 1") } if (is.null(mods.incl)) { all.mods <- TRUE mods.incl <- expand.grid(rep.int(list(0:1), ncol(x))) mods.incl <- as.matrix(cbind(rep.int(1,nrow(mods.incl)),mods.incl)) } else { all.mods <- FALSE } if (is.null(mods.check)) { mods.check <- FALSE } if (mods.check == TRUE) { if ((! is.null (mods.incl)) && (! is.matrix(mods.incl))) { stop("mods.incl must be a matrix") } if (is.matrix(mods.incl) && (! (ncol(mods.incl) == (ncol(x)+1)))) { stop("columns of mods.incl do not correspond to variables specified by columns of x") } if (is.matrix(mods.incl) && (length(mods.incl[!(mods.incl %in% c(0,1))]) > 0)) { stop("mods.incl should contain only 0 and 1") } if (is.matrix(mods.incl) && any(duplicated(mods.incl))) { stop("mods.incl contain duplicated models") } if (is.matrix(mods.incl)) { test <- FALSE test.row <- rep.int(0,ncol(mods.incl)) for (i in 1:nrow(mods.incl)) { if (identical(test.row,mods.incl[i,])) { test <- TRUE } } if (test == TRUE) { stop("mods.incl contain a model with no variables") } } } if ( (all.mods == TRUE ) && (ncol(x)>29) ) { stop("max number of variables, in case of using all possible models, is 29") } if ( (all.mods == FALSE ) && (nrow(mods.incl)>2^29) ) { stop("max number of models is 2^29") } if (all.mods == FALSE && nrow(mods.incl) == 2^ncol(x)) { all.mods <- TRUE } if (is.null(DOW)) { threshold <- 0 } if (all.mods == FALSE && model == "med") { stop("Median Probability Model can be applied only if all possible models with a constant are used, i.e, mods.incl is not specified") } if (!is.null(DOW) && !is.numeric(DOW)) { stop("DOW must be numeric") } if (!is.null(DOW) && ((DOW < 0) || (DOW > 1))) { stop("DOW must be between 0 and 1") } if (!is.null(DOW)) { threshold <- DOW } if (!is.null(DOW) && is.null(DOW.nmods)) { DOW.nmods <- 0 } if (!is.null(DOW.nmods) && !is.numeric(DOW.nmods)) { stop("DOW.nmods must be numeric") } if (!is.null(DOW.nmods) && ((DOW.nmods < 2 && !DOW.nmods == 0) || DOW.nmods > nrow(mods.incl))) { stop("DOW.nmods must be greater than or equal to 2, and less than or equal to the number of all possible models") } if (is.null(DOW.type)) { DOW.type <- "r" } if (! DOW.type %in% c("r","e")) { stop("please, specify correct DOW.type: ''r'', or ''e''") } if (!is.null(DOW) && DOW.type %in% c("r","e") && !model == "dma") { stop("Dynamic Occam's Window can be applied only to Dynamic Model Averaging, i.e., model must be ''dma''") } if (is.null(bm)) { bm <- FALSE } if (! is.logical(bm)) { stop("bm must be logical, i.e., TRUE or FALSE") } if (!is.null(DOW.limit.nmods) && !is.numeric(DOW.limit.nmods)) { stop("DOW.limit.nmods must be numeric") } if (!is.null(DOW.limit.nmods) && DOW.limit.nmods < 2) { stop("DOW.limit.nmods must be greater than or equal to 2") } rm(all.mods) if (length(lambda)>1 && model=="med") stop("multiple lambdas cannot be used for Median Probability Model") if (length(lambda)>1 && !threshold==0) stop("multiple lambdas cannot be used with Dynamic Occam's Window") if (is.null(progress.info)) { progress.info <- FALSE } if (! is.logical(progress.info)) { stop("progress.info must be logical, i.e., TRUE or FALSE") } if (! is.null(small.c) && ! is.numeric(small.c)) { stop("small.c must be a (small) number") } if (! is.null(small.c) && (small.c<0)) { stop("small.c must be positive") } if (! is.null(forced.models)) { forced.models <- forced.models[!duplicated(forced.models),,drop=FALSE] } if (! is.null(forbidden.models)) { forbidden.models <- forbidden.models[!duplicated(forbidden.models),,drop=FALSE] } if (is.null(fcores)) { fcores <- 1 } if (is.null(red.size)) { red.size <- FALSE } lambda <- unique(lambda) lambda <- sort(lambda,decreasing=TRUE) mods.incl <- matrix(as.logical(mods.incl), dim(mods.incl)) if (! is.null(forced.models)) { forced.models <- matrix(as.logical(forced.models), dim(forced.models)) } if (! is.null(forbidden.models)) { forbidden.models <- matrix(as.logical(forbidden.models), dim(forbidden.models)) } if (! is.null(forced.variables)) { forced.variables <- as.logical(forced.variables) } if (is.null(av)) { av <- "dma" } ################################################################### ################################################################### ################################################ basic DMA function f.basicDMA <- function (y,x,alpha,lambda,initvar,W=NULL,kappa=NULL, gprob=NULL,omega=NULL,model=NULL,parallel=NULL, m.prior=NULL,mods.incl=NULL,small.c=NULL) { ################################ setting initial values for DMA len <- length(lambda) exp.lambda <- vector() ### small constant as in Eq. (17) in Raftery et al. (2010) if (is.null(small.c)) { c <- 0.001 * (1/(len*(2^ncol(x)))) } else { c <- small.c } ### initialization of \pi_{0|0} as in Raftery et al. (2010) if (m.prior == 0.5) { pi1 <- as.vector(rep.int(1/(nrow(mods.incl)*len),len*nrow(mods.incl))) } else { pi1 <- vector() for (i in 1:nrow(mods.incl)) { pi1[i] <- m.prior^(sum(mods.incl[i,])) * (1-m.prior)^(ncol(mods.incl)-sum(mods.incl[i,])) } pi1 <- rep(pi1,len) pi1 <- pi1 / sum(pi1) } ### yhat.all - predictions from all regression models used in averaging ### post - posterior predictive model probabilities ### ### in DMA all models are averaged, in DMS the model with highest ### posterior predictive model probability is chosen, ### for MED see Barbieri and Berger (2004) if (model == "dma") { if (red.size==FALSE) { post <- as.vector(rep.int(0,len*nrow(mods.incl))) yhat.all <- matrix(0,ncol=len*nrow(mods.incl),nrow=1) } else { post <- as.vector(rep.int(0,len*ncol(mods.incl))) yhat.all <- NA vm <- as.matrix(apply(mods.incl,1,sum)) exp.var <- vector() } } if (model == "dms" || model == "med") { post <- vector() p.incl <- matrix(0,ncol=ncol(mods.incl),nrow=1) } ydma <- vector() thetas.exp <- as.vector(rep.int(0, ncol(mods.incl))) ############################################################### ############################ recursive estimation of sub-models f.param <- function(i) { i.old <- i i <- i.old %% nrow(mods.incl) if (i==0) { i <- nrow(mods.incl) } i.l <- 1 + ( (i.old - 1) %/% nrow(mods.incl) ) if (length(which(mods.incl[i,-1,drop=FALSE]==1))>0) { xx <- x[,which(mods.incl[i,-1,drop=FALSE]==1),drop=FALSE] if (mods.incl[i,1]==1) { c.incl <- TRUE } else { c.incl <- FALSE } } else { xx <- matrix(,ncol=0,nrow=length(y)) c.incl <- TRUE } out <- tvp(y=y,x=xx,V=initvar,lambda=lambda[i.l],W=W,kappa=kappa,c=c.incl) out[[4]] <- NULL return(out) } if (parallel == TRUE) { ncores <- detectCores() - fcores cl <- makeCluster(ncores) registerDoParallel(cl) est.models <- foreach(i=seq(len*nrow(mods.incl)),.packages=c("xts","fDMA")) %dopar% { f.param(i) } stopCluster(cl) rm(cl,ncores) } else { est.models <- lapply(seq(len*nrow(mods.incl)),f.param) } ############################################## models averaging ### modification as in Koop and Onorante (2014) f.pi2.g <- function(i) { if (length(which(mods.incl[i,-1,drop=FALSE]==1))>0) { p1 <- gprob[t-gprob.ind+1,which(mods.incl[i,-1,drop=FALSE]==1)] } else { p1 <- 1 } if (length(which(mods.incl[i,-1,drop=FALSE]==0))>0) { p2 <- 1-gprob[t-gprob.ind+1,which(mods.incl[i,-1,drop=FALSE]==0)] } else { p2 <- 1 } p1 <- prod(p1) p2 <- prod(p2) if (p1==0) { p1 <- 0.001 * (1/(2^ncol(mods.incl))) } if (p2==0) { p2 <- 0.001 * (1/(2^ncol(mods.incl))) } return( p1*p2 ) } f.pdens <- function(i) { return(.subset2(.subset2(est.models,i),3)[t]) } f.mse <- function(i) { out.mse <- mean((y[1:t] - .subset2(.subset2(est.models,i),1)[1:t])^2) if (out.mse==0) { out.mse <- 0.001 * (1/(2^ncol(mods.incl))) } return(1/out.mse) } f.hr1 <- function(i) { out.hr <- hit.ratio(y=y[1:t],y.hat=.subset2(.subset2(est.models,i),1)[1:t],d=FALSE) if (out.hr==0) { out.hr <- 0.001 * (1/(2^ncol(mods.incl))) } return(out.hr) } f.hr2 <- function(i) { out.hr <- hit.ratio(y=y[1:t],y.hat=.subset2(.subset2(est.models,i),1)[1:t],d=TRUE) if (out.hr==0) { out.hr <- 0.001 * (1/(2^ncol(mods.incl))) } return(out.hr) } f.yhat <- function(i) { return(.subset2(.subset2(est.models,i),1)[t]) } f.thetas <- function(i) { i.old <- i i <- i.old %% nrow(mods.incl) if (i==0) { i <- nrow(mods.incl) } theta.i.tmp <- as.vector(mods.incl[i,]) theta.i.tmp[theta.i.tmp==1] <- .subset2(.subset2(est.models,i.old),2)[t,] return(theta.i.tmp) } for (t in 1:nrow(x)) { if (t<gprob.ind) { pi2 <- (pi1^alpha + c) / (sum((pi1)^alpha + c)) } else { pi2.g <- unlist(lapply(seq(nrow(mods.incl)),f.pi2.g)) pi2.g <- pi2.g / sum(pi2.g) pi2.g <- pi2.g / len pi2.g <- rep(pi2.g,len) pi1sum <- sum((pi1)^alpha + c) pi2 <- omega * ( (pi1^alpha + c) / pi1sum ) + (1-omega) * pi2.g rm(pi1sum,pi2.g) } if (model == "dma") { if (red.size==FALSE) { post <- rbind(post,pi2) } else { f.split.pi2 <- function(i.col) { col.s <- ( ( i.col - 1 ) * nrow(mods.incl) ) + 1 col.e <- col.s + nrow(mods.incl) - 1 return(pi2[col.s:col.e]) } pi2.temp <- lapply(1:len,f.split.pi2) pi2.temp <- Reduce('+', pi2.temp) pi2.temp <- as.vector(pi2.temp) post <- rbind(post,pi2.temp %*% mods.incl) exp.var[t] <- pi2.temp %*% vm rm(pi2.temp) } } if (model == "dms") { j.m <- which.max(pi2) post[t] <- pi2[j.m] j.m.new <- j.m %% nrow(mods.incl) if (j.m.new==0) { j.m.new <- nrow(mods.incl) } p.incl <- rbind(p.incl,mods.incl[j.m.new,]) } if (model == "med") { j.m <- as.vector(pi2 %*% mods.incl) j.m1 <- which(j.m >= 0.5) j.m <- as.vector(rep.int(0, ncol(mods.incl))) j.m[j.m1] <- 1 j.m <- which(apply(mods.incl, 1, function(x) all(x == j.m))) rm(j.m1) post[t] <- pi2[j.m] p.incl <- rbind(p.incl,mods.incl[j.m,]) } yhat <- unlist(lapply(seq(len*nrow(mods.incl)),f.yhat)) if (model == "dma") { if (red.size==FALSE) { yhat.all <- rbind(yhat.all,yhat) } } if (model == "dma") { ydma[t] <- crossprod(pi2,yhat) thetas <- t(sapply(seq(len*nrow(mods.incl)),f.thetas)) thetas.exp <- rbind(thetas.exp,pi2 %*% thetas) exp.lambda[t] <- as.numeric(crossprod(pi2,rep(lambda,each=nrow(mods.incl)))) } if (model == "dms" || model == "med") { ydma[t] <- yhat[j.m] thetas <- f.thetas(j.m) thetas.exp <- rbind(thetas.exp,thetas) exp.lambda[t] <- lambda[1 + (j.m - 1) %/% nrow(mods.incl)] rm(j.m) } if (av=="dma") { pdens <- unlist(lapply(seq(len*nrow(mods.incl)),f.pdens)) } if (av=="mse") { pdens <- unlist(lapply(seq(len*nrow(mods.incl)),f.mse)) } if (av=="hr1") { if (t==1) { pdens <- rep(1,len*nrow(mods.incl)) } else { pdens <- unlist(lapply(seq(len*nrow(mods.incl)),f.hr1)) } } if (av=="hr2") { pdens <- unlist(lapply(seq(len*nrow(mods.incl)),f.hr2)) } pi1 <- (pi2 * pdens) / as.numeric(crossprod(pi2,pdens)) } rm(est.models) ######################################################## output thetas.exp <- thetas.exp[-1,,drop=FALSE] if (model == "dma") { post <- as.matrix(post[-1,,drop=FALSE]) if (red.size==FALSE) { yhat.all <- yhat.all[-1,,drop=FALSE] f.split <- function(i.col) { col.s <- ( ( i.col - 1 ) * nrow(mods.incl) ) + 1 col.e <- col.s + nrow(mods.incl) - 1 return(post[,col.s:col.e]) } post <- lapply(1:len,f.split) post <- Reduce('+', post) post <- as.matrix(post) } if (red.size==FALSE) { exp.var <- NA } return(list(post,yhat.all,thetas.exp,ydma,pdens,NA ,pi1,thetas,yhat,pi2,exp.lambda, NA, exp.var)) } if (model == "dms" || model == "med") { p.incl <- p.incl[-1,,drop=FALSE] return(list(post,NA ,thetas.exp,ydma,pdens,p.incl,pi1,thetas,yhat,pi2,exp.lambda)) } } ################################################## end of basic DMA ################################################################### ################################################################### if (threshold==0) { comput <- f.basicDMA(y=y,x=x,alpha=alpha,lambda=lambda,initvar=initvar,W=W,kappa=kappa, gprob=gprob,omega=omega,model=model,parallel=parallel, m.prior=m.prior,mods.incl=mods.incl,small.c=small.c) } else { ##### Dynamic Occam's Window as in Onorante and Raftery (2016) ############################################################## ydma.dow <- vector() post.dow <- as.vector(rep.int(0, ncol(mods.incl))) thetas.exp.dow <- as.vector(rep.int(0,ncol(mods.incl))) exp.var.dow <- vector() ### selection of initial models if (!(DOW.nmods == 0)) { mods.incl <- mods.incl[sample.int(nrow(mods.incl),size=DOW.nmods),] } else { mods.incl <- as.matrix(rbind(rep.int(0,ncol(x)),diag(1,nrow=ncol(x),ncol=ncol(x)))) mods.incl <- as.matrix(cbind(rep.int(1,ncol(x)+1),mods.incl)) mods.incl <- matrix(as.logical(mods.incl), dim(mods.incl)) } init.mods <- mods.incl nms <- vector() for (T in 1:nrow(x)) { nms[T] <- nrow(mods.incl) if (progress.info==TRUE) { print(paste('round:',T)) print(paste('models:',nms[T])) } if (parallel==TRUE && nms[T]>2^10) { dopar <- TRUE } else { dopar <- FALSE } T.dma <- f.basicDMA(y=y[1:T,,drop=FALSE],x=x[1:T,,drop=FALSE],alpha=alpha,lambda=lambda,initvar=initvar,W=W,kappa=kappa, gprob=gprob,omega=omega,model=model,parallel=dopar, m.prior=m.prior,mods.incl=mods.incl,small.c=small.c) yhat <- T.dma[[9]] thetas <- T.dma[[8]] T.dma[[8]] <- NA pi1 <- T.dma[[7]] if (DOW.type == "r") { pi2.temp <- T.dma[[10]] pi2.temp[which(pi1<(threshold*max(pi1)))] <- 0 pi2.temp <- pi2.temp / sum(pi2.temp) ydma.dow[T] <- crossprod(pi2.temp,yhat) post.dow <- rbind(post.dow,pi2.temp %*% mods.incl) exp.var.dow[T] <- pi2.temp %*% (as.matrix(apply(mods.incl,1,sum))) thetas <- pi2.temp %*% thetas thetas.exp.dow <- rbind(thetas.exp.dow,thetas) rm(pi2.temp) } if (DOW.type == "e") { ydma.dow[T] <- crossprod(T.dma[[10]],yhat) post.dow <- rbind(post.dow,T.dma[[10]] %*% mods.incl) exp.var.dow[T] <- T.dma[[10]] %*% (as.matrix(apply(mods.incl,1,sum))) thetas <- T.dma[[10]] %*% thetas thetas.exp.dow <- rbind(thetas.exp.dow,thetas) } ### models' space update mod.red <- mods.incl[which(pi1>=(threshold*max(pi1))),,drop=FALSE] if (!is.matrix(mod.red)) { mod.red <- t(as.matrix(mod.red)) } if (!is.null(DOW.limit.nmods)) { if (nrow(mod.red)>DOW.limit.nmods) { ind.red <- sort(pi1,decreasing=TRUE,index.return=TRUE)$ix ind.red <- ind.red[1:DOW.limit.nmods] mod.red <- mods.incl[ind.red,,drop=FALSE] rm(ind.red) } } if (!is.matrix(mod.red)) { mod.red <- t(as.matrix(mod.red)) } mod.exp <- mod.red unm <- matrix(TRUE,nrow(mod.red),1) for (i.col in 2:ncol(mod.red)) { mod.exp.temp <- mod.red mod.exp.temp[,i.col] <- xor(mod.red[,i.col],unm) mod.exp <- rbind(mod.exp,mod.exp.temp) } if (! is.null(forced.models)) { mod.exp <- rbind(mod.exp,forced.models) } if (! is.null(forced.variables)) { for (i.var in which(forced.variables==1)) { mod.exp[,i.var] <- TRUE } } mod.exp <- unique(mod.exp) if (! is.null(forbidden.models)) { mod.exp <- rbind(forbidden.models,mod.exp) mod.exp <- mod.exp[!duplicated(mod.exp),,drop=FALSE] mod.exp <- mod.exp[-(1:nrow(forbidden.models)),,drop=FALSE] } if (T<nrow(x)) { mods.incl <- mod.exp } rm(mod.red,mod.exp,mod.exp.temp) } comput <- list(post.dow[-1,,drop=FALSE],NA,thetas.exp.dow[-1,,drop=FALSE],ydma.dow,T.dma[[5]]) comput[[11]] <- T.dma[[11]] comput[[12]] <- exp.var.dow rm(post.dow,ydma.dow,thetas.exp.dow,T.dma) } ############################################################ output ################################################################### ydma <- comput[[4]] comput[[4]] <- NA pdens <- comput[[5]] comput[[5]] <- NA if (length(lambda)>1) { exp.lambda <- comput[[11]] } else { exp.lambda <- rep.int(lambda,nrow(x)) } if (model == "dma") { if (threshold==0) { post <- comput[[1]] } yhat.all <- comput[[2]] if (threshold==0) { if (red.size==FALSE) { colnames(yhat.all) <- seq(1,length(lambda)*nrow(mods.incl)) rownames(yhat.all) <- rownames(x) } } } thetas.exp <- as.matrix(comput[[3]]) colnames(thetas.exp) <- c("const",colnames(x)) if (model == "dma") { if (threshold==0) { if (red.size==FALSE) { post.inc <- post %*% mods.incl } else { post.inc <- post post <- NA } } else { post.inc <- comput[[1]] } } if (model == "dms" || model == "med") { post.inc <- comput[[6]] } colnames(post.inc) <- c("const",colnames(x)) if (model == "dma") { if (threshold==0) { if (red.size==FALSE) { exp.var <- post %*% (as.matrix(apply(mods.incl,1,sum))) } else { exp.var <- as.matrix(comput[[13]]) } } else { exp.var <- as.matrix(comput[[12]]) } } if (model == "dms" || model == "med") { exp.var <- as.matrix(rowSums(post.inc)) } if (model == "dms" || model == "med") { post <- as.matrix(comput[[1]]) yhat.all <- NA } mse <- (mean((y[initial.period:length(y)] - ydma[initial.period:length(y)])^2))^(1/2) mae <- mean(abs(y[initial.period:length(y)] - ydma[initial.period:length(y)])) naive.mse <- (mean((diff(as.numeric(y[initial.period:length(as.numeric(y))])))^2))^(1/2) naive.mae <- mean(abs(diff(as.numeric(y[initial.period:length(as.numeric(y))])))) if (bm == TRUE) { arima <- auto.arima(as.numeric(y))$residuals[initial.period:length(as.numeric(y))] arima.mse <- (mean((arima)^2))^(1/2) arima.mae <- mean(abs(arima)) } else { arima.mse <- NA arima.mae <- NA } benchmarks <- rbind(cbind(naive.mse,arima.mse),cbind(naive.mae,arima.mae)) rownames(benchmarks) <- c("RMSE", "MAE") colnames(benchmarks) <- c("naive", "auto ARIMA") if (model == "dma") { mod.type <- "DMA" } if (model == "dms") { mod.type <- "DMS" } if (model == "med") { mod.type <- "MED" } if (is.null(kappa)) { kappa <- NA } if (is.null(omega)) { omega <- NA } if (is.null(W)) { W <- "reg" } if (threshold==0) { DOW.nmods <- NA DOW.type <- NA } if (length(lambda)>1) { lambda <- paste(lambda,collapse=" ") } if (threshold==0) { temp <- list(ydma, post.inc, mse, mae, mods.incl+0, post, exp.var, thetas.exp, cbind(alpha,lambda,initvar,mod.type,W,initial.period,V.meth,kappa,omega,m.prior,threshold,DOW.nmods,DOW.type), yhat.all, y, benchmarks, NA, NA, pdens,exp.lambda) } else { colnames(init.mods) <- colnames(post.inc) rownames(init.mods) <- seq(1,nrow(init.mods)) temp <- list(ydma, post.inc, mse, mae, mods.incl+0, NA, exp.var, thetas.exp, cbind(alpha,lambda,initvar,mod.type,W,initial.period,V.meth,kappa,omega,m.prior,threshold,DOW.nmods,DOW.type), yhat.all, y, benchmarks, init.mods+0, nms, pdens,exp.lambda) } rownames(temp[[2]]) <- rownames(x) colnames(temp[[5]]) <- c("const", colnames(x)) if (threshold==0 & (!any(is.na(temp[[6]])))) { rownames(temp[[6]]) <- rownames(x) } if (model == "dma") { if (threshold==0 & (!any(is.na(temp[[6]])))) { colnames(temp[[6]]) <- seq(1,nrow(mods.incl)) } } if (model == "dms" || model == "med") { colnames(temp[[6]]) <- "mod. prob." } rownames(temp[[7]]) <- rownames(x) rownames(temp[[8]]) <- rownames(x) colnames(temp[[9]]) <- c("alpha","lambda","initvar","model type","W","initial period","V.meth","kappa","omega","m.prior","DOW threshold","DOW.nmods","DOW.type") rownames(temp[[9]]) <- "parameters" names(temp) <- c("y.hat","post.incl","RMSE","MAE","models","post.mod","exp.var","exp.coef.","parameters", "yhat.all.mods","y","benchmarks","DOW.init.mods","DOW.n.mods.t","p.dens.","exp.lambda") class(temp) <- "dma" return(temp) }
2ba52d2323b30132bf106e43b4483b2f648a217b
d06f4860f0815281085689b706a923740476b386
/landing/code/newsletter/src/Create_report.R
8db61e73c24f675c2dac3dc561a503c8bb24197a
[ "Apache-2.0" ]
permissive
jacobgreen4477/withmakers.github.io
b94d3a9e6247e161328224761047ad3478f4e436
28d3b68572b195f9bc84a44f32d31228dd31a16b
refs/heads/master
2022-01-08T21:31:08.236198
2019-05-15T11:55:35
2019-05-15T11:55:35
null
0
0
null
null
null
null
UTF-8
R
false
false
2,320
r
Create_report.R
# title : Write weekly report # author : Hyunseo Kim # path path_local <- "C:/Users/user/Documents/ds/2econsulting/newsletter/" path_git <- "C:/Users/user/Documents/2econsulting.github.io/data/newsletter/" # Set today and wordcloud's url, subject today <- gsub("-","",Sys.Date()) fileName <- paste0(path_local, "input/text.csv") text <- read.csv(fileName) kor <- paste(text$word[1], text$word[2], text$word[3]) wordcloud <- paste0("https://raw.githubusercontent.com/2econsulting/2econsulting.github.io/master/data/newsletter/output/report/wordcloud_",today,".png") subject <- paste0(gsub("-",".",Sys.Date()),". ",kor) # load data fileName <- paste0(path_git,"input/total_",today,".csv") total <- read.csv(fileName) total$X <- NULL # necessary function filename <- paste0(path_local,"src/text_mining_function.R") source(filename) # Get existing information kaggle_info <- exist_info(total, "kaggle") datacamp_info <- exist_info(total, "datacamp") vidhya_info <- exist_info(total, "vidhya") mastery_info <- exist_info(total, "mastery") # Make markdown code kaggle_report <- link_make(kaggle_info) datacamp_report <- link_make(datacamp_info) vidhya_report <- link_make(vidhya_info) mastery_report <- link_make(mastery_info) # Write the first paragragh report_head <- paste0('---\n', 'layout: post\n', 'title: ', subject,'\n', 'category: weekly report\n', 'tags: [Machine learning, Data Science article]\n', 'no-post-nav: true\n', '---\n\n',kor,' ([wordcloud](',wordcloud,'))\n') # Write kaggle's markdown kaggle_body <- paste0('\n<br>\n\n#### Kaggle Blog NEWS TITLE\n\n', kaggle_report) # Write datacamp's markdown datacamp_body <- paste0('\n<br>\n\n#### Data Camp NEWS TITLE\n\n', datacamp_report) # Write vidhya's markdown vidhya_body <- paste0('\n<br>\n\n#### Analytics Vidhya NEWS TITLE\n\n', vidhya_report) # Write mastery's markdown mastery_body <- paste0('\n<br>\n\n#### Machine Learning Mastery NEWS TITLE\n\n', mastery_report) # Conbine all markdown total_body <- paste0(report_head,kaggle_body,datacamp_body,vidhya_body,mastery_body,'\n<br>\n') # Save markdown fileName <- paste0("C:/Users/user/Documents/2econsulting.github.io/_posts/2018/",Sys.Date(),"-newsletter.md") write.table(total_body, fileName, row.names = FALSE, col.names = FALSE, quote = FALSE, fileEncoding = "UTF-8") gc()
5f47a415ea9fccacd149f5bc77d0f0114047bdd6
142283d08a3e4d48c76f3837a891f528bc1900c4
/man/get_providers_table.Rd
7e7224769db830b298ed4430129b8d49bc6294b3
[]
no_license
pachevalier/WidukindR
6f57731c86f2ada9214381642a51cdee5aa4dd84
f1c467956274bf9fec5e5d8ce6fe0643e5b8c629
refs/heads/master
2021-01-01T03:55:23.953998
2017-04-06T15:53:47
2017-04-06T15:53:47
56,228,009
0
0
null
null
null
null
UTF-8
R
false
true
357
rd
get_providers_table.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/get_providers.R \name{get_providers_table} \alias{get_providers_table} \title{Get Providers Table} \usage{ get_providers_table() } \value{ a tibble } \description{ This function returns a data frame with data on providers } \examples{ get_providers_table() } \keyword{providers}
7733b9ffe18da8cc11f890774363c4f3479f1a0c
e853edce6dc05ffa97588aba87cefad284acc8d4
/Rank 1/1_data_cleaner_basic.R
f543f649c2b0f025a2ba8965d34c52868c9b4137
[ "MIT" ]
permissive
BenJamesbabala/The_Ultimate_Student_Hunt
3cbf66d8f55985da0e9b51252263617cc312d404
edef8e81a07f7aacf67caf290ceaf5f3dba79b8d
refs/heads/master
2021-05-04T08:42:02.427769
2016-10-07T09:30:05
2016-10-07T09:30:05
null
0
0
null
null
null
null
UTF-8
R
false
false
9,184
r
1_data_cleaner_basic.R
library(caTools) library(lubridate) #--------------------------------- # Reading the train and test sets. #--------------------------------- train <- read.csv('Train.csv', stringsAsFactors = FALSE) test <- read.csv("Test.csv", stringsAsFactors = FALSE) #-------------------------------------------------------------- # Selecting the target and dropping it from the training frame. #-------------------------------------------------------------- target <- train$Footfall train <- train[, 1:17] proper_feature_names <- function(input_table){ #-------------------------------------------- # This function normalizes the column names. # INPUT -- Table with messed up column names. # OUTPUT -- Table with proper column names. #-------------------------------------------- colnames(input_table) <- tolower(colnames(input_table)) colnames(input_table) <- gsub('([[:punct:]])|\\s+','_',colnames(input_table)) while (any(grepl("__",colnames(input_table),fixed = TRUE)) == TRUE){ colnames(input_table) <- gsub("__","_",colnames(input_table),fixed = TRUE) } colnames(input_table) <- gsub("\\*$", "",colnames(input_table)) return(input_table) } dummygen <- function(new_table, original_table, dummified_column, column_values, new_name){ #--------------------------------------------------------------------------------------- # This function generates dummies from a categorical variable and adds them to a table. # INPUT 1. -- The new cleaned table -- I will attach the dummies. # INPUT 2. -- The original table that is being cleaned. # INPUT 3. -- The column that has the strings. # INPUT 4. -- The unique values in the column encoded. # INPUT 5. -- The new name of the columns. # OUTPUT -- The new table with the dummy variables. #--------------------------------------------------------------------------------------- i <- 0 for (val in column_values){ i <- i + 1 new_variable <- data.frame(matrix(0, nrow(new_table), 1)) new_variable[original_table[,dummified_column] == val, 1] <- 1 colnames(new_variable) <- paste0(new_name, i) new_table <- cbind(new_table,new_variable) } return(new_table) } #------------------------------------------------------------ # Normalizing the feature names in the train and test tables. #------------------------------------------------------------ train <- proper_feature_names(train) test <- proper_feature_names(test) data_munger <- function(input_table){ #------------------------------------ # This function cleans the data. # INPUT -- The table to be cleaned. # OUTPUT -- The cleaned numeric table. #------------------------------------ #---------------------------------------------- # Defining a target table for the cleaned data. #---------------------------------------------- new_table <- data.frame(matrix(0, nrow(input_table), 1)) new_table[, 1] <- input_table$id #----------------------------------------------------- # The first variable is an artifical ID. #----------------------------------------------------- colnames(new_table) <- c("id") #---------------------------- # Park ID dummy generation. #---------------------------- park_id <- c(12:39) new_table <- dummygen(new_table, input_table, "park_id", park_id, "park_id_") #------------------------------------------------------ # Generating a proper day variable in the input table. #------------------------------------------------------ input_table$monkey_day <- paste0(substr(input_table$date, 7, 10),"-",substr(input_table$date, 4, 5),"-",substr(input_table$date, 1, 2)) #------------------------------------- # Generating a day of week indicator. #------------------------------------- input_table$days <- lubridate::wday(input_table$monkey_day) #--------------------------------------- # Generating a day of year categorical. #--------------------------------------- new_table$super_monkey_day <- yday(input_table$monkey_day) #-------------------------------------- # Generating a day of month categorical. #-------------------------------------- new_table$hyper_monkey_day <- mday(input_table$monkey_day) #--------------------------------------------------- # Creating dummies from the day of week categorical. #--------------------------------------------------- days <- c(1:7) new_table <- dummygen(new_table, input_table, "days", days, "week_days_") #----------------------------------------------------------------------- # Days simple solution -- this is biased, but works as a biweekly proxy. #----------------------------------------------------------------------- new_table$date <- yday(input_table$date) #------------------------ # Month dummy variables. #------------------------ input_table$first_two <- substr(input_table$date, 6, 7) first_two <- c("01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12") new_table <- dummygen(new_table, input_table, "first_two", first_two, "first_two_") #---------------------------------------------------- # Extracting the numeric variables the way they are. #---------------------------------------------------- columns_to_extract_exactly <- c("direction_of_wind", "average_breeze_speed", "max_breeze_speed", "min_breeze_speed", "var1", "average_atmospheric_pressure", "max_atmospheric_pressure", "min_atmospheric_pressure", "min_ambient_pollution", "max_ambient_pollution", "average_moisture_in_park", "max_moisture_in_park", "min_moisture_in_park") sub_table <- input_table[, columns_to_extract_exactly] new_table <- cbind(new_table, sub_table) #--------------------------------------------------------------------- # Creating moving window standard deviation variables for the different parks. #------------------------------------------------------------------------------ names_to_use <- colnames(sub_table) keys <- unique(input_table$park_id) for (i in 1:ncol(sub_table)){ for (k in keys){ sub_table[input_table$park_id == k, i] <- runsd(sub_table[input_table$park_id == k, i], 4, endrule = "constant") } } colnames(sub_table) <- paste0("sd_", names_to_use) new_table <- cbind(new_table, sub_table) #---------------------------------------------------------------- # Creating moving window mean variables for the different parks. #---------------------------------------------------------------- keys <- unique(input_table$park_id) for (i in 1:ncol(sub_table)){ for (k in keys){ sub_table[input_table$park_id == k, i] <- runmean(sub_table[input_table$park_id == k, i], 4, endrule = "constant") } } colnames(sub_table) <- paste0("mean_", names_to_use) new_table <- cbind(new_table, sub_table) #----------------------------------------------------------------- # Creating moving window maxima variables for the different parks. #----------------------------------------------------------------- keys <- unique(input_table$park_id) for (i in 1:ncol(sub_table)){ for (k in keys){ sub_table[input_table$park_id == k, i] <- runmax(sub_table[input_table$park_id == k, i], 7, endrule = "constant") } } colnames(sub_table) <- paste0("max_", names_to_use) new_table <- cbind(new_table, sub_table) #----------------------------------------------------------------- # Creating moving window minima variables for the different parks. #----------------------------------------------------------------- keys <- unique(input_table$park_id) for (i in 1:ncol(sub_table)){ for (k in keys){ sub_table[input_table$park_id == k, i] <- runmin(sub_table[input_table$park_id == k, i], 7, endrule="constant") } } colnames(sub_table) <- paste0("min_", names_to_use) new_table <- cbind(new_table, sub_table) #---------------------------- # Creating location dummies. #---------------------------- location_type <- c(1:4) new_table <- dummygen(new_table, input_table, "location_type", location_type, "location_type_") return(new_table) } #-------------------------------------------- # Creating the cleaned test and train tables. #-------------------------------------------- new_train <- data_munger(train) new_test <- data_munger(test) #----------------------------------------- # Dumping the tables and arget variables. #----------------------------------------- write.csv(new_train, file = "train.csv", row.names = FALSE) write.csv(new_test, file = "test.csv", row.names = FALSE) write.csv(target, file = "target.csv", row.names = FALSE)
52f3a8e2c984db3d28bdc4cc78a3bf5f5c28c74f
5845a56588bef70f613a610d23f7833069f6dab2
/pkg/R/alignment_plot.R
49170cf5cf48d32b9371e0540851563f889f5ae0
[]
no_license
DrRoad/dataquality
fdc537b0d2e71785253bf8b3423dbd022a3177ff
96d930ef6469b73b8eb6a4db29273772f457bc2a
refs/heads/master
2022-01-27T07:03:35.073584
2013-11-25T10:05:39
2013-11-25T10:05:39
null
0
0
null
null
null
null
UTF-8
R
false
false
1,835
r
alignment_plot.R
alignment.plot <- function(src.nrow, ref.nrow, matched.nrow, src.name="source", ref.name="reference") { require(RColorBrewer) require(grid) grid.newpage() datnames <- c(src.name, ref.name) datwidths <- convertWidth(stringWidth(datnames),unitTo="npc", valueOnly=TRUE) parts <- c(src.nrow - matched.nrow, matched.nrow, ref.nrow - matched.nrow) total <- sum(parts) heights <- parts/total ys <- c(cumsum(c(0,heights))[1:3],1) numberwidth <- convertWidth(stringWidth("10000000"),unitTo="npc", valueOnly=TRUE) pushViewport(viewport(layout=grid.layout(3, 6, widths=unit(c(numberwidth,numberwidth,1,1,numberwidth,numberwidth), c("npc", "npc", "null", "null", "npc", "npc")), heights=unit(c(1.5,1, .5), c("lines", "null", "lines"))))) cellplot(1, 3, e={ grid.text(datnames[1]) }) cellplot(1, 4, e={ grid.text(datnames[2]) }) ys_numbers <- (ys[2:4]+ys[1:3])/2 brewer.set1 <- brewer.pal(9, name="Set1") cellplot(2, 1, e={ grid.text(parts[1:2], x=.9, y=ys_numbers[1:2], just="right") }) src_perc <- round(parts[1:2]/sum(parts[1:2])*100, 2) ref_perc <- round(parts[2:3]/sum(parts[2:3])*100, 2) cellplot(2, 2, e={ grid.text(paste0("(", src_perc, "%)"), x=.9, y=ys_numbers[1:2], just="right") }) cellplot(2, 5, e={ grid.text(parts[2:3], x=.9, y=ys_numbers[2:3], just="right") }) cellplot(2, 6, e={ grid.text(paste0("(", ref_perc, "%)"), x=.9, y=ys_numbers[2:3], just="right") }) cellplot(2, 3, e={ grid.rect(y=ys[1], height=sum(heights[1:2]), gp=gpar(fill=brewer.set1[2], col=NA), just=c("bottom")) }) cellplot(2, 4, e={ grid.rect(y=ys[2], height=sum(heights[2:3]), gp=gpar(fill=brewer.set1[3], col=NA), just=c("bottom")) }) cellplot(2, 3:4, e={ grid.polyline(y=rep(ys[2:3], each=2), x=rep(c(0,1), 2), id=rep(1:2, each=2)) }) }
06eb716b3cccd621f92896fec284adb9e4c4a556
0ad2a36dcd4191ac4da79933f66f08855489b934
/man/kmModel.Rd
835d1b9f0d0ed22c0eef16b0e72c4402085ab343
[]
no_license
schiffner/mobKriging
75f3f035b70d314361f3f117c492cbcb399007b4
3fac343fd86cac72f032b2a148c62d4dfde8f20d
refs/heads/master
2021-01-22T01:04:40.175978
2014-08-13T20:17:21
2014-08-13T20:17:21
22,139,892
1
0
null
null
null
null
UTF-8
R
false
false
2,571
rd
kmModel.Rd
% Generated by roxygen2 (4.0.1): do not edit by hand \docType{data} \name{kmModel} \alias{kmModel} \alias{kmModel-class} \title{\code{kmModel}} \format{\preformatted{Formal class 'StatModel' [package "modeltools"] with 5 slots ..@ name : chr "kriging model" ..@ dpp :function (formula, data = list(), subset = NULL, na.action = NULL, frame = NULL, enclos = sys.frame(sys.nframe()), other = list(), designMatrix = TRUE, responseMatrix = TRUE, setHook = NULL, ...) ..@ fit :function (object, weights = NULL, noise.var = NULL, km.args = NULL, ...) ..@ predict :function (object, newdata = NULL, ...) ..@ capabilities:Formal class 'StatModelCapabilities' [package "modeltools"] with 2 slots .. .. ..@ weights: logi FALSE .. .. ..@ subset : logi FALSE }} \usage{ kmModel } \value{ Slot \code{fit} returns an object of class \code{kmModel}. } \description{ An object of class \code{\linkS4class{StatModel}} that provides infra-structure for an unfitted Kriging model. } \examples{ ## We use the first example in the documentation of function km if (require(DiceKriging)) { d <- 2L x <- seq(0, 1, length = 4L) design <- expand.grid(x1 = x, x2 = x) y <- apply(design, 1, branin) df <- data.frame(y = y, design) ## Fitting the model using kmModel: # data pre-processing mf <- dpp(kmModel, y ~ ., data = df) # no trend (formula = ~ 1) m1 <- fit(kmModel, mf) # linear trend (formula = ~ x1 + x2) m1 <- fit(kmModel, mf, formula = ~ .) # predictions on the training data # recommended: improved version of predict for models fitted with objects # of class StatModel Predict(m1, type = "UK") # also possible predict(m1, type = "UK") ## This is equivalent to: # no trend (formula = ~ 1) m2 <- km(design = design, response = y) # linear trend (formula = ~ x1 + x2) m2 <- km(formula = ~ ., design = design, response = y) # predictions on the training data predict(m2, newdata = design, type = "UK") ## extract information coef(m1) residuals(m1) logLik(m1) ## diagnostic plots plot(m1) } } \references{ Roustant, O., Ginsbourger, D. and Deville, Y. (2012), DiceKriging, DiceOptim: Two R packages for the analysis of computer experiments by Kriging-based metamodeling and optimization. \emph{Journal of Statistical Software}, \bold{51(1)}, \url{http://www.jstatsoft.org/}. } \seealso{ \code{\linkS4class{StatModel}}, \code{\link[DiceKriging]{km}}, \code{\link[modeltools]{Predict}}. } \keyword{datasets}